diff --git a/.github/workflows/sc.yml b/.github/workflows/sc.yml
index aee83c94..4faf9257 100644
--- a/.github/workflows/sc.yml
+++ b/.github/workflows/sc.yml
@@ -28,7 +28,9 @@ jobs:
- run: rustup show active-toolchain || rustup toolchain install
- uses: Swatinem/rust-cache@v2
with:
- workspaces: sc
+ workspaces: |
+ sc
+ sc/swarm
# The sandbox tests build the WASM through `cargo near` (cargo-near 0.22.0, see sc/CLAUDE.md). Pinned by checksum.
- name: Install cargo-near 0.22.0
working-directory: ${{ runner.temp }}
@@ -43,3 +45,13 @@ jobs:
- run: cargo test --locked --test test_registry
- run: cargo test --locked --test test_migration
- run: cargo clippy --locked --all-targets
+ # The swarm auction (sc/swarm, AI Swarms track): its own crate with its own target. The 20-buyer simulation takes
+ # ~2 min on a laptop, so it runs here too: it is the swarm's main proof.
+ - run: cargo test --locked --lib
+ working-directory: sc/swarm
+ - run: cargo test --locked --test test_round
+ working-directory: sc/swarm
+ - run: cargo test --locked --test simulation
+ working-directory: sc/swarm
+ - run: cargo clippy --locked --all-targets
+ working-directory: sc/swarm
diff --git a/CLAUDE.md b/CLAUDE.md
index d7ede579..ea5a3d28 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -83,6 +83,7 @@ The team uses macOS with **OrbStack** as the Docker runtime. Keep local services
| What | Account | Env |
|---|---|---|
| Mind registry contract (`sc/`), v0.3.0 | `hellonear-registry.testnet` | `REGISTRY_CONTRACT_ID`, `NEAR_NETWORK=testnet` |
+| Swarm auction contract (`sc/swarm`), v0.1.0, source verified | `auction.hellonear-swarm.testnet`; agents are sub-accounts of `hellonear-swarm.testnet` (`coordinator`, `buyer-1..3`, `seller-1..2`), keys in Axel's keychain | none (no app reads it yet) |
| Demo Mind wallet (OutLayer, policy v2), owner `lin1er.testnet` | `83e05486fc84f7150a70fe44bdfc0692c19182cdd72af7721c9a8a2a511e98bd`; sub-wallet `skill-payments` `bcd8cdbd8b4038c12ab9076188d01f9e5238ff397c3c6097cec1488c6b16588b`. Replaced `0fdc9294…` on 8 Nov (its key was exposed; #70) | `OUTLAYER_API_KEY`, `OUTLAYER_SUB_SKILL_PAYMENTS` (James's `apps/be/.env`, never committed); hosted demo: `DEMO_OUTLAYER_API_KEY` |
| Try-out email inbox (AgentMail, Free plan, lexirieru's organization; not on chain) (#96) | `hellonear-demo@agentmail.to` (AgentMail `client_id` `hellonear-demo`), created 9 Nov | `AGENTMAIL_API_KEY` (Axel's local `apps/be/.env`, never committed), `DEMO_AGENTMAIL_INBOX`; not on the hosted demo yet |
diff --git a/README.md b/README.md
index 87c2702c..76813f20 100644
--- a/README.md
+++ b/README.md
@@ -28,10 +28,11 @@ HelloNear gives a person a **Mind**: an AI agent with a persona, memory, skills
| **Landing page** | **[hellonear.xyz](https://hellonear.xyz)** |
| **API** (NEAR testnet) | **[api.hellonear.xyz/v1/health](https://api.hellonear.xyz/v1/health)** |
| **Mind registry contract** | **[`hellonear-registry.testnet`](https://testnet.nearblocks.io/address/hellonear-registry.testnet)** (v0.3.0, NEP-330, [source verified](https://testnet.nearblocks.io/address/hellonear-registry.testnet?tab=contract)) |
+| **Swarm auction contract** | **[`auction.hellonear-swarm.testnet`](https://testnet.nearblocks.io/address/auction.hellonear-swarm.testnet?tab=contract)** (NEP-330, [source verified](https://testnet.nearblocks.io/address/auction.hellonear-swarm.testnet?tab=contract), [a real round](#the-swarm-auction-one-real-round-on-testnet)) |
| **API reference** | **[OpenAPI spec](docs/openapi.json)** · [README section](#api-reference) |
| **Repository** | **[github.com/Hellonear-AI/hellonear](https://github.com/Hellonear-AI/hellonear)** |
-**[The agent and its 50 tools](#the-agent-mastra-on-near-ai-cloud)** ·
+**[The agent and its 53 tools](#the-agent-mastra-on-near-ai-cloud)** ·
**[Receipts](#receipts-check-them-yourself)** ·
**[Security model](#security-model)** ·
**[Try it](#try-it)** ·
@@ -68,7 +69,7 @@ HelloNear's answer is to **take the limits out of the model** and **make the mod
| Feature | What it means |
|---|---|
| **A Mind per job** | Pick a template (General Assistant, Payments Mind, Email Manager), give it a name and a voice. It remembers what matters, and you can read, edit or clear that memory. |
-| **Skills grant tools** | 33 skills, each a playbook plus a fixed list of tools. A Mind has exactly the tools its skills grant, so a Mind without a payment skill cannot pay, whatever it is told. |
+| **Skills grant tools** | 34 skills, each a playbook plus a fixed list of tools. A Mind has exactly the tools its skills grant, so a Mind without a payment skill cannot pay, whatever it is told. |
| **Approval cards** | Payments, emails, calendar changes, Sheets cells, Notion rows, Docs, Slack posts and Zoom meetings wait for the owner, with the old value shown next to the new one. |
| **A wallet with its own rules** | Per-payment limit, daily limit and allowed addresses, enforced by OutLayer in a TEE before signing; freeze with one signature. |
| **Cross-chain quotes** | A Payments Mind quotes a USDC or USDT payment from NEAR to Base, Solana, Arbitrum and more through **NEAR Intents**, with 1Click's signature checked. |
@@ -98,7 +99,7 @@ HelloNear is submitted to six tracks. For each one: what the organizers ask for
| | |
|---|---|
| **The track asks for** | "Build spending limits, policy engines, sandboxed wallets, reputation and scam detection. Give AI money without giving it the keys to everything." Hints: agent security, function call keys, TEE attestation |
-| **What HelloNear built** | Seven layers that each stop an attack alone: the model, skills that grant tools, the owner's approval, the OutLayer wallet policy checked **in a TEE before signing**, a daily limit, freeze, and unattended jobs with no payment tools. Writes re-check their target before writing. A Recipient guard against lookalike accounts, a Phishing check, and an Attack playground that names the layer that stopped each attack. Why not function-call keys: they cannot transfer NEAR and their allowance is gas, not a spending cap |
+| **What HelloNear built** | Seven layers that each stop an attack alone: the model, skills that grant tools, the owner's approval, the OutLayer wallet policy checked **in a TEE before signing**, a daily limit, freeze, and unattended jobs with no payment tools. Writes re-check their target before writing. A Recipient guard that answers allow, warn or block with the reason before every payment (where the recipient came from, that it exists, lookalikes of people already paid, first payments, contracts), a Phishing check, and an Attack playground that names the layer that stopped each attack. Why not function-call keys: they cannot transfer NEAR and their allowance is gas, not a spending cap |
| **Skills** | Recipient guard, Phishing check, Freeze advisor, Spending audit, Payments |
| **Check it** | Attack playground, any scenario: `attack.verdict` names the layer. Approve 1 NEAR: `policy_denied`, no transaction |
@@ -109,15 +110,15 @@ HelloNear is submitted to six tracks. For each one: what the organizers ask for
| **The track asks for** | "Explore confidential computation, private finance and AI that protects sensitive data. Build intelligence without exposure." Hints: private AI, TEE, NEAR AI Cloud |
| **What HelloNear built** | Every model call runs on **NEAR AI Cloud** inside a TEE. Each reply's signature is checked against the hardware attestation before the Verified badge shows; the proof is kept, shown under View proof, and opens on Phala's TEE Explorer as VERIFIED. Secrets and wallet tokens never reach the model, traces or stored snapshots. Skills that read sensitive email without sending it anywhere |
| **Skills** | Confidential reader, Redact before send, Health journal |
-| **Check it** | Verified badge → View proof → Check it in TEE Explorer: a VERIFIED report whose nonce matches the dialog |
+| **Check it** | Verified badge → View proof → Check it in TEE Explorer: a VERIFIED report whose nonce matches the dialog. What is kept and what is not: [What is private, and what HelloNear keeps](#what-is-private-and-what-hellonear-keeps) |
### `agents`: Agent Economy
| | |
|---|---|
| **The track asks for** | "Build agents that earn, spend, negotiate, hire other agents and pay for APIs, compute or data — with crypto directly or through NEAR Intents." Hints: agent commerce, NEAR Intents, chain signatures |
-| **What HelloNear built** | Minds pay for data with a 402 pattern on testnet NEAR (price, approved payment, report with the tx hash as receipt), sell what they made to other Minds into their own wallet, compare sellers before buying, invoice and check payment on chain, and quote cross-chain payments through **NEAR Intents**. All inside the owner's limits |
-| **Skills** | Paid data, Best price buyer, Price watch, Mind as seller, Invoice & get paid, Payments |
+| **What HelloNear built** | Minds pay for data with a 402 pattern on testnet NEAR (price, approved payment, report with the tx hash as receipt), sell what they made to other Minds into their own wallet, compare sellers before buying, invoice and check payment on chain, quote cross-chain payments through **NEAR Intents**, haggle once with a seller (offer within the owner's budget, then buy at the agreed price or walk away), and find agents on the **NEAR AI Agent Market** (market.near.ai) with each job's exact price from the agent's own x402 answer, picking the cheapest one within the owner's budget (hiring is paid in USDC on mainnet, so it only quotes for now). All inside the owner's limits |
+| **Skills** | Paid data, Best price buyer, Hire on Agent Market, Price watch, Mind as seller, Invoice & get paid, Payments |
| **Check it** | *"What's the gas price on NEAR testnet? Buy the report."*: a `402` price, a card for 0.001 NEAR, then the report and its tx hash |
### `swarms`: AI Swarms
@@ -125,16 +126,16 @@ HelloNear is submitted to six tracks. For each one: what the organizers ask for
| | |
|---|---|
| **The track asks for** | "Build coordination markets, bidding, collective purchasing, intent-based settlement and emergent economies between agents." Hints: multi-agent systems, NEAR Intents, sub-accounts |
-| **What HelloNear built** | Best price buyer runs each order as a small auction between sellers and buys only from one the wallet may pay; Minds buy from and sell to other Minds (each with its own wallet); Split bill and Revenue split pay several people from one request, each payment approved on its own |
-| **Skills** | Best price buyer, Mind as seller, Split bill, Revenue split |
-| **Check it** | *"Split 0.02 NEAR between alice.testnet and bob.testnet"*: shares worked out in yoctoNEAR, one card per person |
+| **What HelloNear built** | A **sealed-bid group-buying auction contract** ([`sc/swarm`](sc/swarm), rules in [`RULES.md`](sc/swarm/RULES.md)): buyer agents pool demand with escrow, seller agents commit hidden asks with a bond and reveal them, the cheapest asks fill demand at one clearing price, and every agent is its own NEAR sub-account. A simulation of **20 buyers and 5 sellers with scripted strategies and no LLM** runs three rounds on a local NEAR sandbox and checks money is conserved each round ([report](sc/swarm/simulation-report.md)); an independent audit's 9 findings are fixed. In the app, Best price buyer runs each order as a small auction between sellers and buys only from one the wallet may pay; Minds buy from and sell to other Minds (each with its own wallet); Split bill and Revenue split pay several people from one request, each payment approved on its own |
+| **Skills** | Best price buyer, Mind as seller, Split bill, Revenue split; contract `sc/swarm` |
+| **Check it** | [One real round on testnet](#the-swarm-auction-one-real-round-on-testnet): every step's transaction, 6 units filled at one clearing price. Locally, `cd sc/swarm && cargo test --test simulation -- --nocapture`: 20 buyers and 5 sellers, three rounds, a clearing price per round and who got what. In the app: *"Split 0.02 NEAR between alice.testnet and bob.testnet"*: shares worked out in yoctoNEAR, one card per person |
### `business`: Autonomous Business
| | |
|---|---|
| **The track asks for** | "Build AI-native businesses with treasury, sales, procurement, cross-chain payments via NEAR Intents and revenue sharing. Humans only set the constraints." Hints: AI agents, NEAR Intents, chain signatures |
-| **What HelloNear built** | The owner sets the constraints (limits, recipients, rules); the Mind runs the treasury: daily treasury reports, a weekly spending audit, revenue sharing between partners, invoices and follow-ups, procurement through Best price buyer, cross-chain quotes through NEAR Intents, and Autopilot jobs that run on a schedule |
+| **What HelloNear built** | The owner sets the constraints (per-payment and daily limits, allowed recipients, approval rules) and holds a kill switch (Freeze, one signature); the Mind runs the treasury: daily treasury reports, a weekly spending audit, revenue sharing between partners, invoices and follow-ups, procurement through Best price buyer, cross-chain quotes through NEAR Intents, and Autopilot jobs that run on a schedule |
| **Skills** | Treasury report, Spending audit, Revenue split, Invoice & get paid, Follow-ups, Subscriptions & bills |
| **Check it** | *"Give me today's treasury report"*: balance, what went out, what is pending, read only |
@@ -143,7 +144,7 @@ HelloNear is submitted to six tracks. For each one: what the organizers ask for
| | |
|---|---|
| **The track asks for** | "Build payroll, invoicing, remittances, merchant payments and stablecoin rails for real businesses. Something a normal company could use tomorrow." Hints: stablecoins, NEAR Intents, meta transactions |
-| **What HelloNear built** | Invoices sent from the Mind's own email address with payment checked by its transaction on chain; bills and subscriptions found in the owner's Gmail; USDC/USDT payments to other chains quoted through **NEAR Intents**, signed by 1Click and checked with the official SDK (sending needs mainnet); every payment approved by the owner and limited by the wallet |
+| **What HelloNear built** | Invoices sent from the Mind's own email address with payment checked by its transaction on chain; bills and subscriptions found in the owner's Gmail; a payments CSV an accountant can open without asking (`GET /v1/minds/{id}/payments.csv`: date, status in words, amount, counterparty, purpose, who approved, tx hash and NearBlocks link); a meta-transaction relayer (NEP-366) that pays gas only for owner calls to our own registry contract and never pays a deposit; USDC/USDT payments to other chains quoted through **NEAR Intents**, signed by 1Click and checked with the official SDK (sending needs mainnet); every payment approved by the owner and limited by the wallet |
| **Skills** | Invoice & get paid, Subscriptions & bills, Spending tracker, Payments |
| **Check it** | *"Send 10 USDC to 0x8ba1f109551bD432803012645Ac136ddd64DBA72 on Base."*: what would arrive, the cost, the time, `proof.signedBy1Click: true`, nothing sent |
@@ -179,6 +180,8 @@ What a Mind can work with. Logos are the ones the web app shows on the Connectio
| | **NEAR Protocol** (testnet) | `sc/`, `apps/be/src/auth.ts`, `apps/be/src/wallets.ts` | The Mind registry contract (Minds, published skills, `equip_skill` pays the publisher); NEP-413 sign-in; every payment, policy change and freeze is a NEAR transaction |
| | **NEAR AI Cloud** | `engine/src/models.ts`, `engine/src/verify.ts`, `engine/src/titles.ts` | Runs every model call inside a TEE; HelloNear checks each reply's signature against the attestation before the Verified badge, and keeps the proof |
| | **NEAR Intents** (1Click API + official SDK) | `engine/src/crosschain.ts` | Cross-chain USDC/USDT quotes from NEAR to other chains; each quote's 1Click signature is verified with `verifyQuoteSignature` |
+| | **NEAR AI Agent Market** ([market.near.ai](https://market.near.ai)) | `engine/src/market.ts`, skill `agent-market` | Searches the public catalog of agents and gets a job's exact price from the agent's own x402 answer (A2A, unpaid), then picks the cheapest within the owner's budget; hiring is paid in USDC on mainnet, so it only quotes for now |
+| | **Swarm auction contract** (`near-sdk`, testnet) | `sc/swarm` | Sealed-bid group buying between agents, each its own sub-account; deployed at `auction.hellonear-swarm.testnet`, source verified |
| | **OutLayer** (testnet) | `apps/be/src/wallets.ts`, `apps/be/src/payments.ts` | One wallet per Mind; its policy (per-payment limit, daily limit, allowed recipients) is stored on chain and checked in a TEE before anything is signed; freeze |
| | **Meteor Wallet** via **NEAR Connect** | `apps/fe` | The owner's wallet: signs in, signs the Mind wallet's policy, adds funds, freezes. Other NEAR Connect wallets work too |
| | **FastNear** testnet RPC | `engine/src/tools.ts`, `apps/be/src/config.ts` | Account lookups before a payment (`view_account`) and transfer checks after one (`tx`) |
@@ -244,6 +247,21 @@ curl -s $RPC -H 'content-type: application/json' -d '{"jsonrpc":"2.0","id":1,"me
To rebuild it yourself (needs Docker): `git checkout 95c2b3d && cd sc && cargo near build reproducible-wasm`, then compare the SHA-256 (base58) of `target/near/hellonear_mind_registry.wasm` with the code hash above.
+### The swarm auction: one real round on testnet
+
+The group-buying auction contract (`sc/swarm`, rules in [`RULES.md`](sc/swarm/RULES.md)) is deployed at **[`auction.hellonear-swarm.testnet`](https://testnet.nearblocks.io/address/auction.hellonear-swarm.testnet?tab=contract)**. It was built reproducibly from commit `64c9278`, and its **source is verified** through SourceScan (code hash `6Wn9K6b3DtoH4TnoXs2jx6zFzihdzFDQGw4ae2dzcCv1`, deploy [`FkvHpxf9…`](https://testnet.nearblocks.io/txns/FkvHpxf9ff8LBeMcLEqSbhmFUbhcx5PebyG3qzJdQAwo)). Every agent is its own sub-account of `hellonear-swarm.testnet`. Round 0 (13 Nov 2026) had 3 buyers wanting 6 "gpu-hours", a ceiling of 0.01 NEAR per unit, and 2 sellers bidding sealed asks:
+
+| Step | Who | Transaction | What it shows |
+|---|---|---|---|
+| Open the round | `coordinator` | [`B4CFzH9o…`](https://testnet.nearblocks.io/txns/B4CFzH9oCH8smUfCbTeKD7hNLPAmCwgzegzmnodavQaj) | Ceiling 0.01 NEAR per unit, seller bond 0.01 NEAR, a fixed 3 min commit window and 2 min reveal window |
+| Join with escrow | `buyer-1`, `buyer-2`, `buyer-3` | [`GdBiXyn4…`](https://testnet.nearblocks.io/txns/GdBiXyn44oTHPEtcdxiZNdE9xdCPjPqiJUbUniGuVLG6) [`Eo4m23zh…`](https://testnet.nearblocks.io/txns/Eo4m23zhYhpxGTMZB7FxAK7oZAp6rCLFJvkJnrDMRQJJ) [`cgt2zw9v…`](https://testnet.nearblocks.io/txns/cgt2zw9vewKo9HQQC9g8FJFcu5GXM3n9FBWWCzcheaY) | 2, 3 and 1 units, each paying units × ceiling into escrow |
+| Sealed asks | `seller-1`, `seller-2` | [`CQUFGq7K…`](https://testnet.nearblocks.io/txns/CQUFGq7KoJ9VH5pi78GyvA84TLxrDTw1D8wgnuECmSH9) [`4FsTkdpw…`](https://testnet.nearblocks.io/txns/4FsTkdpwJDxX4xXxWp1jfxXo8pLtN1cQizdbMnjP67iN) | Only a SHA-256 commitment (round, seller, ask, capacity, salt) plus the bond. Nobody can see the price |
+| Reveal | `seller-1`, `seller-2` | [`Gu7qQBFn…`](https://testnet.nearblocks.io/txns/Gu7qQBFnV8uUCgp3VgjxntrNzwSnczWLxsq6TLi3U6pw) [`4EPJqmC6…`](https://testnet.nearblocks.io/txns/4EPJqmC6dtzSGADFLnNqffo3DMkvxEmxVuTmbcFFuyyC) | 0.006 NEAR × 4 units and 0.008 NEAR × 5 units; each must hash to its commitment, and the bond comes back |
+| Close (a buyer, not the organizer) | `buyer-2` | [`44guvtrj…`](https://testnet.nearblocks.io/txns/44guvtrj8riB75rgQiC1kfMsBQzYHQcmruR3cdA4eL5C) | All 6 units filled at **one clearing price, 0.008 NEAR**: seller-1 sold 4, seller-2 sold 2. Buyers paid 0.048 NEAR in total and sellers earned 0.048 NEAR |
+| Withdraw | each agent | [`CNsVsstu…`](https://testnet.nearblocks.io/txns/CNsVsstuuumXzjLbjGTFWXEYVXtw1bDfcTsiej7PEy7s) [`E2Amtv9p…`](https://testnet.nearblocks.io/txns/E2Amtv9pnSWdLhQoFaXeZxuxrm8Jjhc8NBgLbcDMcnJC) [`APe2tSRJ…`](https://testnet.nearblocks.io/txns/APe2tSRJqZrcrKUMNhsKnMjvCFcMLfWD4ayHqSvpMgD2) [`3WYa3qLP…`](https://testnet.nearblocks.io/txns/3WYa3qLPAP57WCg5fM7ptgQ6QyKv31M6f7r66NWDGBw6) [`5qV7kPVS…`](https://testnet.nearblocks.io/txns/5qV7kPVSVV17KzvCZBLVbtHbM52ZDnrRtmtaM36V6f9w) | Buyers pull their change (0.004, 0.006 and 0.002 NEAR); sellers pull sales plus bond (0.042 and 0.026 NEAR) |
+
+Read the round yourself: `get_round` with `{"round_id":0}` on `auction.hellonear-swarm.testnet` (public RPC, no key). The full 20-buyer, 5-seller simulation runs on a local sandbox: `cd sc/swarm && cargo test --test simulation -- --nocapture`.
+
### The proof behind a verified reply (NEAR AI Cloud TEE)
| | |
@@ -279,7 +297,7 @@ flowchart LR
subgraph EN[Engine · Mastra 1.81]
direction TB
AG[One generic Mind agent persona, memory, skills from RequestContext]
- TL[[50 tools granted only by equipped skills]]
+ TL[[53 tools granted only by equipped skills]]
WF[Visual Builder workflows + Autopilot schedules]
AG --> TL
WF --> TL
@@ -358,7 +376,7 @@ This is the core of HelloNear, and the part a judge can read end to end in `engi
| **Events** | Mastra's stream is normalised into HelloNear events (`tool.called`, `tool.approval_required`, `run.verified`, …) that drive the chat, the live view and the Mind Graph. | `engine/src/server.ts`, `docs/api-contract.md` |
| **Stop** | Closing the request aborts the model call, so a stopped reply stops spending tokens. Payments already sent to OutLayer are never cut halfway. | `engine/src/server.ts` |
-### All 50 tools
+### All 53 tools
**A** (approval) = needs the owner's approval (or an owner rule). Reads never ask.
@@ -370,11 +388,14 @@ This is the core of HelloNear, and the part a judge can read end to end in `engi
| `get_balance` | | The Mind's wallet address and balance | Backend wallet route |
| `list_payments` | | Recent payments, including refused ones and why | Backend wallet route |
| `split_amount` | | Each person's share of an amount, exactly, in yoctoNEAR | Local (BigInt) |
-| `near_view_account` | | Look up a testnet account: exists, balance, storage | NEAR RPC `view_account` |
+| `near_view_account` | | Look up a testnet account: exists, balance, storage, and whether it is a contract (`isContract`, `codeHash`) | NEAR RPC `view_account` |
| `near_check_transfer` | | Check one transaction: success, receiver, amount, whether it paid this Mind | NEAR RPC `tx` |
| `crosschain_quote` | | Quote a USDC/USDT payment to another chain, signature checked | NEAR Intents 1Click `/v0/quote` (`dry: true`) |
| `buy_data` | | Buy a live NEAR data report (402 pattern) | Backend shop route |
| `get_quotes` | | Every seller's price for a report, cheapest first, and which ones the wallet may pay | Backend shop route |
+| `make_offer` | | Offer one seller less than it quoted, once, within the owner's budget; answers accepted or its last price, and whether to buy or walk away | Backend shop route (`offer`) |
+| `market_search` | | Search the NEAR AI Agent Market's public catalog: agents, default price, track record, verification | market.near.ai `GET /v1/agents` |
+| `market_quote` | | Get a listed agent's exact price for the owner's task, unpaid (its x402 answer), and whether it is within the owner's budget; nothing starts, nothing is paid | market.near.ai A2A `SendMessage` without payment |
| `sell_offer` | yes | Put something this Mind made on sale to other Minds | Backend offers route |
| `buy_from_mind` | | Buy what another Mind sells (402 pattern) | Backend offers route |
@@ -437,18 +458,19 @@ This is the core of HelloNear, and the part a judge can read end to end in `engi
| `add_numbers` | | Exact addition, so the model never sums in its head | Local |
| `http_request` | | Call a public HTTPS API with a key from Connections, only to the hosts the owner allowed; no redirects, private addresses refused, the key redacted from the result | The owner's service |
-### All 33 skills
+### All 34 skills
Icons are the ones the web app shows on each skill card.
| | Skill | What it does | Tools it grants |
|---|---|---|---|
| | **Payments** (`payments`) | Sends testnet NEAR and pays bills after the owner approves; quotes USDC or USDT payments to other chains (Base, Solana…) through NEAR Intents | `send_payment`, `get_balance`, `list_payments`, `get_time`, `near_view_account`, `crosschain_quote` |
-| | **Recipient guard** (`recipient-guard`) | Checks a recipient for scams and lookalikes before paying, and asks when in doubt | `near_view_account`, `list_payments`, `send_payment`, `get_balance`, `get_time` |
+| | **Recipient guard** (`recipient-guard`) | Checks a recipient before paying and answers allow, warn or block with the reason: where the account came from, that it exists, lookalikes of people you already pay, first payments, and contracts | `near_view_account`, `list_payments`, `send_payment`, `get_balance`, `get_time` |
| | **Split bill** (`split-bill`) | Works out each person's share of a bill and pays each one after you approve | `add_numbers`, `split_amount`, `send_payment`, `near_view_account`, `list_payments`, `get_balance`, `get_time` |
| | **Revenue split** (`revenue-split`) | Remembers your partners' shares and pays each one their part of new income after you approve | `get_balance`, `send_payment`, `near_view_account`, `add_numbers`, `split_amount`, `list_payments`, `get_time` |
| | **Paid data** (`paid-data`) | Buys small live NEAR reports, paying only after you approve | `buy_data`, `send_payment`, `list_payments`, `get_time` |
-| | **Best price buyer** (`best-price`) | Compares every seller of a data report and buys the cheapest one your wallet may pay, after you approve | `get_quotes`, `buy_data`, `send_payment`, `list_payments`, `get_time` |
+| | **Best price buyer** (`best-price`) | Compares every seller of a data report, haggles once when the price is over your budget (then buys or walks away), and buys from one your wallet may pay, after you approve | `get_quotes`, `make_offer`, `buy_data`, `send_payment`, `list_payments`, `get_time` |
+| | **Hire on Agent Market** (`agent-market`) | Finds agents on the NEAR AI Agent Market (market.near.ai), gets a job's exact price and picks the cheapest within your budget; hiring is paid in USDC on NEAR mainnet, so during the testnet phase it only quotes | `market_search`, `market_quote` |
| | **Price watch** (`price-watch`) | Checks a data report's price and buys only at or under your limit, after you approve | `get_quotes`, `buy_data`, `send_payment`, `add_numbers`, `get_time` |
| | **Mind as seller** (`mind-seller`) | Sells what this Mind made to other Minds for testnet NEAR into its own wallet, and buys from other Minds, after you approve | `sell_offer`, `buy_from_mind`, `send_payment`, `get_balance`, `get_time` |
| | **Invoice & get paid** (`invoice`) | Emails an invoice from this Mind's address after you approve, and checks a payment only by its transaction | `mail_send`, `mail_list`, `mail_read`, `get_balance`, `near_check_transfer`, `get_time` |
@@ -501,11 +523,28 @@ Each layer stops an attack on its own; the ones further down do not trust the on
| **The wallet policy (OutLayer, in a TEE)** | A payment the owner approved by mistake: over the per-payment limit or to an address not on the list is refused before signing, with no transaction | Approve a payment above the limit. See: `policy_denied`, no tx hash. The card already says "blocked even if you approve" |
| **Daily limit (OutLayer, in a TEE)** | Many small payments that add up: once today's payments reach the daily limit, the next one is refused before signing; the day starts at 00:00 UTC | Wallet → Edit → *Per day*. See: "Spent today: X of Y NEAR" |
| **The owner's rules (opt-in)** | Nothing by themselves: they only skip the card the owner chose to skip, only up to the owner's amount and only to a listed address. Guests and the Attack playground always ask, and the TEE policy still checks every payment | Mind settings → Approvals → payments up to 0.01. See: no card, and the receipt says "Approved by your rule" |
-| **Freeze** | Everything, at once: one transaction the owner signs | Wallet → Freeze wallet (on your own Mind). See: every later payment ends `wallet_frozen` |
+| **Freeze (the kill switch)** | Everything, at once: one transaction the owner signs | Wallet → Freeze wallet (on your own Mind). See: every later payment ends `wallet_frozen` |
| **Unattended jobs** | Autopilot jobs get no payment or approval tools; they may only email the owner or add to the owner's calendar, as steps the owner placed | Builder → Use a tool → *Email me*. See: it can only send the Mind's notes, to your own Gmail |
**Why not a capped function-call key?** NEAR function-call access keys cannot transfer NEAR, and their `allowance` is a gas budget for the key's whole life, not a spending cap ([docs](https://docs.near.org/protocol/accounts-contracts/access-keys)). The spending rules therefore live in the wallet's policy, which OutLayer checks in its TEE before every signature.
+
+### What is private, and what HelloNear keeps
+
+The TEE protects the model calls. It does not make HelloNear's own backend blind: a Mind that remembers its owner needs that memory stored somewhere. This table says exactly where the line is.
+
+| Data | Who can see it | Kept? |
+|---|---|---|
+| **Prompts and replies while the model runs** | Nobody outside the TEE: not the cloud provider, not the model host, not NEAR AI. Each reply's signature is checked against the hardware attestation | HelloNear keeps the chat itself (next row); inside the TEE the operator cannot read it |
+| **Chat history** | The owner, and HelloNear's backend (Postgres, **not** in a TEE) | Yes, so the Mind can continue a chat. Deleting a chat also deletes its semantic-recall vectors (`engine/src/threads.ts`) |
+| **The Mind's memory of its owner** (working memory) | The owner (Mind settings → Memory), and HelloNear's backend | Yes, until the owner edits or clears it in Settings (`engine/src/memory.ts`) |
+| **API keys and connection secrets** | Nobody in plain text: AES-256-GCM, bound to the owner and the secret's name (`apps/be/src/crypto.ts`). The model only ever writes `{{secrets.NAME}}` | Encrypted, until the owner deletes it |
+| **Secrets and wallet tokens during a run** | Only the tool that uses them | **Never** in prompts, traces or stored run snapshots: they live in an in-memory map, and a test scans every table for them |
+| **Proofs behind the Verified badge** | Anyone with the run | Signatures, hashes and Intel's TDX quote only, never the conversation text |
+| **Guest sessions** | The guest | Deleted with all their Minds after the retention period (7 days) |
+
+So: HelloNear can keep your chats and memory to be useful, and you can delete them. It never stores your secrets in a form it can read back to the model, and the AI provider never sees your prompts outside the TEE.
+
---
## How NEAR is used
@@ -606,7 +645,7 @@ Every route and event is in [`docs/api-contract.md`](docs/api-contract.md).
## API reference
-The web app is a client of a public HTTP API, and everything it does can be done with `curl`. The full spec is **[`docs/openapi.json`](docs/openapi.json)** (OpenAPI 3.1, 60 operations): open it in [Swagger Editor](https://editor.swagger.io/?url=https://raw.githubusercontent.com/Hellonear-AI/hellonear/main/docs/openapi.json) or any OpenAPI viewer to read every route and try it against the hosted API. Every server-sent event type is described in [`docs/api-contract.md`](docs/api-contract.md) §3.
+The web app is a client of a public HTTP API, and everything it does can be done with `curl`. The full spec is **[`docs/openapi.json`](docs/openapi.json)** (OpenAPI 3.1, 62 operations): open it in [Swagger Editor](https://editor.swagger.io/?url=https://raw.githubusercontent.com/Hellonear-AI/hellonear/main/docs/openapi.json) or any OpenAPI viewer to read every route and try it against the hosted API. Every server-sent event type is described in [`docs/api-contract.md`](docs/api-contract.md) §3.
- **Base URL:** `https://api.hellonear.xyz` (NEAR testnet), or `http://localhost:4000`.
- **Auth:** a session cookie, `hn_session`. Get one with `POST /v1/auth/demo` (guest, no wallet) or with a NEAR wallet: `POST /v1/auth/challenge`, sign the message (NEP-413), then `POST /v1/auth/login`. `curl` works as is (no `Origin` header); a browser page on another site gets `403` for any call that changes something (CSRF protection).
@@ -778,6 +817,9 @@ Stated plainly, so nothing here surprises a judge:
- **Mainnet.** Deploy the registry and the Mind wallets on NEAR mainnet; cross-chain stablecoin payments through NEAR Intents can then be sent, not only quoted, under the same limits and approvals.
- **Pay-as-you-go AI credits.** Owners top up credits and pay for what their Minds use. Each run already records its tokens and cost.
- **More Mind templates** beyond the three today, each starting with the skills for its job.
+- **Hiring on the Agent Market.** On mainnet a Mind can pay a market.near.ai agent itself: the payment is one signed delegate action (NEP-366) for the agent's quoted USDC price, behind the owner's approval card and wallet limits, and the agent's result comes back into the chat.
+- **Haggling through the Agent Market's job board.** The Mind posts the owner's job with their budget, compares the bids that come in, answers one counter, and funds the escrow only through the owner's approval card. Today it compares the fixed prices of several agents and picks the cheapest within the budget.
+- **The swarm auction on chain for Minds.** Minds join group-buying rounds of the swarm auction contract (`sc/swarm`) with their own wallets, so several owners' Minds pool demand and pay one clearing price.
- **Images and voice.** Owners send their Mind a photo (a receipt, an invoice, a screenshot) or a voice message, and the Mind reads it and acts on it, with the same approvals and limits.
---
diff --git a/apps/be/.env.example b/apps/be/.env.example
index e74449e6..fb2de79c 100644
--- a/apps/be/.env.example
+++ b/apps/be/.env.example
@@ -42,10 +42,17 @@ DEMO_AGENTMAIL_INBOX=
# Optional: the testnet account a Mind pays for a Paid data report (#150). It must be on the paying wallet's address list
# (the demo wallet's, for try-outs). Empty: the shop answers 503 shop_not_configured
SHOP_PAY_TO=
-# Optional, Best Price Buyer (#176): several sellers for the same items, account:multiplier separated by commas
-# (e.g. a.testnet:1,b.testnet:0.8; price = base price x multiplier, up to 3 decimals). Each account must be on the paying
-# wallet's address list. Empty: SHOP_PAY_TO is the only seller
+# Optional, Best Price Buyer (#176): several sellers for the same items, account:multiplier[:floor] separated by commas
+# (e.g. a.testnet:1,b.testnet:0.8:0.5; price = base price x multiplier, up to 3 decimals; floor = the share of its price a
+# seller accepts in a negotiation, default 0.8). Each account must be on the paying wallet's address list. Empty:
+# SHOP_PAY_TO is the only seller
SHOP_SELLERS=
+# Optional, meta-transaction relayer (POST /v1/relay): a funded testnet account and one of its full-access keys
+# (ed25519:...), created and funded by a person, never committed. It pays gas only for unequip_skill / set_wallet on
+# REGISTRY_CONTRACT_ID (default hellonear-registry.testnet). Either one empty: the route answers 503 relay_not_configured
+RELAYER_ACCOUNT_ID=
+RELAYER_PRIVATE_KEY=
+REGISTRY_CONTRACT_ID=
# Telegram (#168). The public API URL Telegram calls for webhooks (e.g. https://api.hellonear.xyz); leave it empty locally
# and set TELEGRAM_POLLING=true to poll getUpdates instead. TELEGRAM_API_URL is for tests (default https://api.telegram.org).
TELEGRAM_WEBHOOK_BASE=
diff --git a/apps/be/CLAUDE.md b/apps/be/CLAUDE.md
index 5ba4bf79..08149376 100644
--- a/apps/be/CLAUDE.md
+++ b/apps/be/CLAUDE.md
@@ -43,6 +43,9 @@ Backend API: Postgres + pgvector, NEP-413 login, run/event storage + SSE, encryp
- App connections (#13): the Composio user id is our `users.id`, which the engine already receives as `userId`. Toolkits: `gmail`, `googlecalendar` (#57), `googlemeet` (#97, Meet links for the engine's `googlecalendar_create_meeting`; auth config `ac_ISu09_uuoKCK`, scopes `meetings.space.created` + `meetings.space.settings`), and for #194: `googlesheets`, `googledrive`, `googledocs`, `slack`, `discord`, `notion`, `outlook`, `hubspot` (#195–#201, Composio-managed OAuth2, a Connect Link made for each on 11 Nov; the backend only connects, lists and disconnects them, the engine decides which actions a Mind runs), and `zoom` (#246, Composio-managed OAuth2, toolkit read live 11 Nov; no Connect Link made for it yet; the Telegram card for `zoom_create_meeting` is in `src/approvals.ts`) (`TOOLKITS` in `src/connections.ts`, slugs checked live against Composio). `POST /v1/connections/{toolkit}` creates a Tool Router session for that user and a Connect Link (callback `{FE_ORIGIN}/connections?toolkit={toolkit}`), removing unfinished attempts first; never trust the callback's query string, re-read `GET /v1/connections`. Composio-managed OAuth (no Google app of our own). Tests use `test/fake-composio.ts`.
- **Paid data (#150, `src/shop.ts`):** `GET /internal/v1/shop/{item}` answers 402 with a price and `SHOP_PAY_TO`; with `?tx=` it serves a live NEAR RPC report only for this Mind's own `sent` payment row (to `SHOP_PAY_TO`, at least the price, last hour), confirmed by RPC `tx` (success, signer = the Mind's wallet), and records the hash in `shop_purchases` (009) so it is used once. Plain `rpc.testnet.near.org` forgets transactions after a few days, hence the one-hour window. `SHOP_PAY_TO` must be on the paying wallet's address list. Tests use the fake OutLayer's `/rpc` (`tx`, `status`, `gas_price`).
- **Several sellers (#176, Best Price Buyer):** `SHOP_SELLERS` (`account:multiplier,…`) lists sellers `s1`, `s2`, … by their place in the list; empty means `SHOP_PAY_TO` alone as `s1`. A bad list stops the backend at start. `?quotes=1` lists them cheapest first with `onYourList`, read from the paying wallet's own OutLayer policy (`addressRuleOf` in `wallets.ts`), so the Mind only picks sellers OutLayer would let it pay. A 402 without `seller` offers the cheapest. A payment counts for the seller its `wallet_payments.to_account` names, at that seller's price; with `?seller=` it must be that seller. Every seller must also be on the demo wallet's list for try-outs, which is a policy the demo wallet's owner signs in Meteor. Intended (11 Nov, not set yet): `SHOP_SELLERS="lin1er.testnet:1.0,testing7.testnet:0.8"`.
+- **Negotiation (agents track, `src/shop.ts`):** `?seller=sN&offer=` asks one seller to sell for less. Each seller has a floor, a share of its price (third `SHOP_SELLERS` field `account:multiplier:floor`, default 0.8): at or above it the offer is `accepted` (never above the list price), below it the seller `countered`s once, halfway to its price but not under the floor. Stateless; the paid step carries the same `offer` and checks the payment against the agreed price (an offer under the floor never lowers it). The engine's `make_offer` and `buy_data.offerNear` call exactly this; keep the shape (`docs/api-contract.md`).
+- **Payments CSV (realworld track):** `GET /v1/minds/{id}/payments.csv` (`paymentsCsv` in `src/payments.ts`), owner only. "Approved by" is read from the run events of the call that made the payment (`tool.result.result.paymentId` → same `toolCallId`'s `tool.called.approvedBy` / `tool.approval_required`), in one query with CTEs: per-row subqueries made it 3× slower under load. Cells that start like a formula get a leading `'`.
+- **Meta-transaction relayer (realworld track, `src/relay.ts`):** `POST /v1/relay { signedDelegate }` (NEP-366, base64 Borsh). The relayer account (`RELAYER_ACCOUNT_ID`, `RELAYER_PRIVATE_KEY`) pays gas **and any inner deposit** (docs.near.org "Meta Transactions", read 13 Nov), and the registry refunds storage to the caller, so only `unequip_skill` / `set_wallet` with exactly 1 yoctoNEAR are relayed; `register_mind` and `equip_skill` need storage (and a price) and are not. Everything that can be refused is refused before sending (sender = signed-in account, receiver = `REGISTRY_CONTRACT_ID`, gas, ed25519 signature over sha256(NEP-461 prefix + delegate), expiry ≤ 1000 blocks, full-access key, nonce) so a bad request costs no gas. 10 per owner per hour, in memory. RPC: `NEAR_RPC_URL`, default `https://test.rpc.fastnear.com`. `borsh` 2.0.0 is a direct dependency for decoding (same version near-api-js uses). Not run on testnet yet: no relayer account is funded; a wallet that signs delegate actions without sending them (Meteor?) is not proven either.
- **Mind as Seller (#181, `src/offers.ts`, migration 011):** a Mind publishes an offer with its own wallet token (`PUT /internal/v1/offers/{item}`, stored in `mind_offers`); another Mind buys it with `GET /internal/v1/minds/{sellerMindId}/offers/{item}[?tx=]`, the same 402 and receipt check as the shop but `payTo` is the seller Mind's own wallet address and the RPC `tx` must show receiver = that address; hashes are used once (`offer_purchases`). Try-out and playground Minds can neither sell nor be bought from (the shared demo wallet is nobody's own): `403 demo_not_allowed` / `404 no_offer`. The buyer's wallet must list the seller's 64-hex address, or OutLayer refuses the payment (`policy_denied`).
- **Telegram (#168, `src/telegram.ts`, migration 010):** one bot per Mind, made by the owner with @BotFather. `PUT /v1/minds/{id}/telegram { token }` checks it with `getMe`, refuses a bot another Mind uses (`409 telegram_bot_in_use`), stores it AES-GCM with AAD `telegram:{mindId}`, and either sets a webhook (`TELEGRAM_WEBHOOK_BASE` + `/v1/telegram/{mindId}/webhook`, with a random `secret_token`) or, locally, deletes it so `TELEGRAM_POLLING=true` can poll `getUpdates`. The answer has a one-time `t.me/?start=`: the private chat that sends that code becomes the owner; every other chat is ignored without a reply. `POST /v1/telegram/{mindId}/webhook` has no session: the `X-Telegram-Bot-Api-Secret-Token` header must match (`401` otherwise), it answers `200` at once and handles the update after; `last_update_id` drops redelivered updates. An owner message runs as a chat through `runTelegramChat` (`src/server.ts`: `relayRun` into an in-memory sink, so events, threads, the live view and try-out limits are the same as the app), in one thread per bot (`thread_id`), in UTC (no time zone from Telegram). **Streaming (#222, `LiveReply` in `src/telegram.ts`):** the sink passes each relayed event to Telegram as it is written (`memorySink(onEvent)`; `relayRun` and the app path are unchanged). "typing…" is sent every 4 s until the first text shows and again while a tool runs (Telegram clears it after 5 s). The first text is sent at once, then the same message is edited as it grows, at most once per 1.5 s (`telegramTiming`), each time the whole text so far through the converter (a half-written mark stays literal until its pair arrives, so it is always valid HTML); past 4096 characters it continues in a new message. `run.finished` triggers the last edit with the complete formatted reply, so the owner does not wait for `run.verified`. An edit answered "message is not modified" is ignored. Approvals still come as their own messages after the reply. The reply after an approval button press is not streamed yet (sent whole when the resumed run ends). **Rich text (#221, `src/telegramFormat.ts`):** every bot message is sent with `parse_mode: "HTML"`. The Mind's Markdown is converted by our own small converter (no library): bold, italic, strikethrough, inline and fenced code (`
`), links `[text](url)` and bare URLs (http/https only; any other scheme stays visible as text), headings as bold lines, lists as "•"/"1." lines, blockquotes, tables as one line per row; all other text is escaped (`< > & "` only). `telegramChunks` splits at 4096 between blocks or lines, never inside a tag, so each message is valid on its own. A `400` "can't parse entities" resends that message as plain text (`plainOf`). Approval cards (#208) use the same path, but only the title is bold and every other word is escaped, never read as Markdown: their words come from tool arguments (an email subject, an event title someone else wrote), so a stranger cannot inject a link into a message that asks the owner to approve. **Approvals happen in Telegram too (#208, Axel's call 11 Nov; replaces "never in Telegram"):** each approval a Telegram run asks for is its own message (`askOwner`) with the app card's checks or details (`src/approvals.ts`, ported from apps/fe `wallet/data/checks.ts` and `runs/data/approvalDetails.ts`; keep the words in step, and give every new approval tool a case in both, or Telegram shows only its name; long values are cut by `clip` to stay under Telegram's 4096 characters) and buttons Approve / Decline / Open in app (`/minds/{id}/chat/{threadId}`); no Approve when the policy would refuse or the wallet holds less than the payment (`next: 'fund'`, #228; an unfunded wallet's account isn't on chain yet and OutLayer reads its balance as `"0"`, spike 01, so it counts as 0), a button to `/minds/{id}/wallet` instead. Order of reasons: frozen, limit, today's limit, list, balance. Today's limit (#149) is OutLayer's rule `spentTodayNear + amount > dailyNear` (a payment exactly on the cap goes through; the day starts 00:00 UTC), and a `policy_denied` message names it too, since a refused payment doesn't count toward the day. A wallet read that fails still shows no checks and keeps Approve (OutLayer decides). `callback_data` is an opaque one-time code in `telegram_approvals` (013); only `callback_query.from.id` = the owner chat id counts, everyone else gets "Only the owner can approve"; `answerCallbackQuery` is always called; the first press uses up both codes. A press resumes through `resumeRun` (`src/server.ts`), the same function as the app's approve/decline route, then edits the message to the result (never "rejected on-chain", no tx link for a refusal) and sends the Mind's reply and any next approval. `resumeRun` accepts only a call of the run's current pause (`isAwaiting` in `src/runs.ts`: at most one `run.finished` after its `tool.approval_required`) and claims the run (`awaiting_approval` → `running` in one update, undone if the engine refuses), so the app and Telegram cannot resume one run twice. `allowed_updates` is `["message", "callback_query"]`, and every start re-runs `setWebhook` for all bots (`registerTelegramWebhooks`) so bots linked before #208 get presses; a URL button Telegram refuses (`400`) is resent as a link in the text. `DELETE` deletes the webhook (best effort) and the row. Polling skips a bot that errors, so one bad row cannot stop the others. Tests use `test/fake-telegram.ts` (also `answerCallbackQuery`, `editMessageText`, `editMessageReplyMarkup`, `refuseLocalUrls`, `refuseHtmlOnce`, `telegramHtmlError`, which refuses HTML Telegram would refuse, `deleteMessage`, and "message is not modified"; every call has its time `at`) and the fake engine's `fake.scripts` (scripted replies with slow tools, text pacing and verification delay; `fake.timings`) with fresh bot ids per run; the fake engine's `pay NEAR to [ and …]` asks for `send_payment` one pause at a time and pays through the backend's internal route (`fake.backendUrl`). A labelled link shows its host after it (`[Your bank](http://evil.example/login)` reads "Your bank (evil.example)"), unless the label names it; the plain-text fallback drops that note since it shows the whole URL (Lin1er, #223).
- **Mind email addresses (#96, `src/mail.ts`):** AgentMail REST v0 with `fetch` (no SDK, like Composio): `POST /inboxes` with `client_id` = Mind id (retries return the same inbox; checked live 9 Nov), `POST /inboxes/{id}/messages/send` with an `Idempotency-Key` header, `GET /inboxes/{id}/messages[/{message_id}]`. An inbox is created only when the owner equips the `email-address` skill (`POST`/`PATCH /v1/minds` or `POST …/inbox`); one row per Mind in `mind_inboxes`, address `{name}-{6 id chars}@agentmail.to`. `key_slot` names the AgentMail key (organization) holding it: slot 0 `AGENTMAIL_API_KEY`, slot 1 `AGENTMAIL_API_KEY_2`; a `403 limit_exceeded` on create moves to the next slot (Free plan: 3 inboxes per organization). The engine's mail tools call `/internal/v1/mail/{send,messages,messages/{id}}` with `X-Engine-Key` and a **mail token** (`mt_…`, `src/walletToken.ts`, own HMAC key, 15 min, one Mind), added to runs only while the skill is on and the inbox exists; same three checks as the wallet routes. Every send is stored in `mail_sends` (refusals too); a retry with the same idempotency key (the engine's tool call id) maps to the same row id, so it is stored, listed and counted once. Caps: owners 20 sends per Mind per day; try-out users share `DEMO_AGENTMAIL_INBOX`, may only send to it, and get 2 sends each (per-user advisory lock, like `sendPayment`'s cap). AgentMail refusals keep their code: `429 rate_limit_exceeded` → `rate_limited`, `403 message_rejected`/`limit_exceeded`/suspended → `rejected` (send results), or `429 mail_rate_limited` / `403 mail_rejected` (other routes); a wrong key or anything else → `503 agentmail_error`. A message read is checked against the Mind's own `inbox_id`. **The shared try-out inbox is public** (anyone can mail it), so a try-out Mind only lists and reads messages whose `message_id` its own user's Minds sent (`mail_sends`); mail from anyone else is never shown. Deleting a Mind deletes its own AgentMail inbox first (`DELETE /inboxes/{id}`, asynchronous `202`), best effort: AgentMail down or `404` does not block the delete; the shared inbox is never deleted. **Email me (#146):** `POST /internal/v1/mail/owner` (engine key only, since Autopilot runs carry no mail token; body names `userId` and `mindId`, and the Mind must be theirs) sends to the address of the owner's connected Gmail, read with Composio `GMAIL_GET_PROFILE` (`gmailAddress` in `src/connections.ts`); the recipient is never in the request, try-out users are refused, the daily cap applies. Tests use `test/fake-agentmail.ts`; `test/agentmail-live.test.ts` is opt-in (`AGENTMAIL_LIVE=1`, creates/reuses only `hellonear-demo@agentmail.to`, sends to itself; `AGENTMAIL_LIVE_TO` adds one send to the account owner).
@@ -53,7 +56,7 @@ Backend API: Postgres + pgvector, NEP-413 login, run/event storage + SSE, encryp
## Commands
-- `bun run dev` (port 4000, applies migrations at start), `bun run migrate`, `bun run test:unit` (offline), `bun run test` (unit + integration: local Postgres + fake engine), `bun run load` (fake engine and fake Telegram; fails if a run loses events, if a paused run answered twice at once is resumed other than once, or if a Telegram reply streamed alongside the app traffic does not end with the full text), `bun run typecheck`.
+- `bun run dev` (port 4000, applies migrations at start), `bun run migrate`, `bun run test:unit` (offline), `bun run test` (unit + integration: local Postgres + fake engine), `bun run load:shop` (the shop's quotes and offers and the payments CSV under load, fake engine and fake OutLayer; fails on any wrong answer), `bun run load` (fake engine and fake Telegram; fails if a run loses events, if a paused run answered twice at once is resumed other than once, or if a Telegram reply streamed alongside the app traffic does not end with the full text), `bun run typecheck`.
- Postgres: `docker compose up -d postgres` from the repo root; `docker compose stop` when done. If port 55432 is taken by another project, run it on another host port with a compose override (`ports: !override ["55433:5432"]`) and pass `DATABASE_URL=…:55433/hellonear` to `bun run test` / `bun run load`.
- Schema changes: add a new `migrations/NNN_name.sql` (never edit an applied one) and update `docs/api-contract.md` §5.
- Tests never call NEAR AI or the NEAR RPC: `test/fake-engine.ts` stands in for the engine and `setProvider()` fakes the access-key lookup; signatures are real. Run `bun run test` and `bun run load` before every push/merge that touches `apps/be`, and report results in the PR. CI: `.github/workflows/be.yml`.
@@ -61,4 +64,4 @@ Backend API: Postgres + pgvector, NEP-413 login, run/event storage + SSE, encryp
## Env
-See `.env.example`: `DATABASE_URL`, `ENGINE_URL`, `ENGINE_API_KEY`, `SECRETS_MASTER_KEY` (32 bytes base64; losing it loses every stored secret), optional `PORT`, `FE_ORIGIN`, `AUTH_RECIPIENT`, `NEAR_RPC_URL`, `COOKIE_SECURE`, `OUTLAYER_URL`, `OUTLAYER_CONTRACT_ID`, `DEMO_MODE`, `DEMO_OUTLAYER_API_KEY`, `COMPOSIO_API_KEY`, `COMPOSIO_URL`, `AGENTMAIL_API_KEY`, `AGENTMAIL_API_KEY_2`, `AGENTMAIL_URL`, `DEMO_AGENTMAIL_INBOX`, `TEE_EXPLORER_URL`. `.env` is gitignored; never commit it.
+See `.env.example`: `DATABASE_URL`, `ENGINE_URL`, `ENGINE_API_KEY`, `SECRETS_MASTER_KEY` (32 bytes base64; losing it loses every stored secret), optional `PORT`, `FE_ORIGIN`, `AUTH_RECIPIENT`, `NEAR_RPC_URL`, `COOKIE_SECURE`, `OUTLAYER_URL`, `OUTLAYER_CONTRACT_ID`, `DEMO_MODE`, `DEMO_OUTLAYER_API_KEY`, `COMPOSIO_API_KEY`, `COMPOSIO_URL`, `AGENTMAIL_API_KEY`, `AGENTMAIL_API_KEY_2`, `AGENTMAIL_URL`, `DEMO_AGENTMAIL_INBOX`, `TEE_EXPLORER_URL`, `SHOP_PAY_TO`, `SHOP_SELLERS`, `RELAYER_ACCOUNT_ID`, `RELAYER_PRIVATE_KEY`, `REGISTRY_CONTRACT_ID`. `.env` is gitignored; never commit it.
diff --git a/apps/be/bun.lock b/apps/be/bun.lock
index 599bebc4..7d924eb8 100644
--- a/apps/be/bun.lock
+++ b/apps/be/bun.lock
@@ -5,6 +5,7 @@
"": {
"name": "@hellonear/be",
"dependencies": {
+ "borsh": "2.0.0",
"near-api-js": "7.4.0",
"pg": "8.23.1",
"zod": "4.6.7",
diff --git a/apps/be/load/shop.ts b/apps/be/load/shop.ts
new file mode 100644
index 00000000..fb90dae6
--- /dev/null
+++ b/apps/be/load/shop.ts
@@ -0,0 +1,110 @@
+// Short local load test of the paths the track work changed: the paid-data shop's price list and negotiation
+// (`/internal/v1/shop/{item}?quotes=1` and `?seller=&offer=`, with the run's wallet token, as the engine calls them) and
+// the payments CSV (`GET /v1/minds/{id}/payments.csv`, each Mind holding 200 payments with their runs' events). Every
+// answer must be 200 with the right shape: an offer is accepted or countered at the expected price, and the CSV has one
+// line per payment. Fake engine and fake OutLayer, local Postgres. Never point this at a public endpoint.
+// Run: bun run load:shop (env: VUS=10, DURATION_S=10)
+import type { AddressInfo } from 'node:net'
+import { randomBytes } from 'node:crypto'
+import { ENGINE_KEY, engine } from '../test/fake-engine.ts'
+import { outlayerServer } from '../test/fake-outlayer.ts'
+
+const VUS = Number(process.env.VUS ?? 10)
+const DURATION_S = Number(process.env.DURATION_S ?? 10)
+const PAYMENTS_PER_MIND = 200
+
+await new Promise((r) => engine.listen(0, r))
+process.env.ENGINE_URL = `http://127.0.0.1:${(engine.address() as AddressInfo).port}`
+process.env.ENGINE_API_KEY = ENGINE_KEY
+await new Promise((r) => outlayerServer.listen(0, r))
+process.env.OUTLAYER_URL = `http://127.0.0.1:${(outlayerServer.address() as AddressInfo).port}`
+process.env.NEAR_RPC_URL = `${process.env.OUTLAYER_URL}/rpc`
+process.env.SHOP_PAY_TO = 'shop.testnet'
+process.env.SHOP_SELLERS = 'shop.testnet:1,cheap.testnet:0.8:0.5,dear.testnet:1.3'
+process.env.DATABASE_URL ??= 'postgresql://hellonear:hellonear-dev-only@localhost:55432/hellonear'
+process.env.SECRETS_MASTER_KEY ??= randomBytes(32).toString('base64')
+
+const { server } = await import('../src/server.ts')
+const { migrate, pool, query } = await import('../src/db.ts')
+const { newId, randomToken, sha256 } = await import('../src/crypto.ts')
+const { issueWalletToken } = await import('../src/walletToken.ts')
+await migrate()
+await new Promise((r) => server.listen(0, r))
+const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
+
+async function user() {
+ const id = newId('usr')
+ const token = randomToken()
+ await query('insert into users (id, near_account_id) values ($1, $2)', [id, `loadshop-${id}.testnet`])
+ await query(`insert into sessions (token_hash, user_id, expires_at) values ($1, $2, now() + interval '1 hour')`, [sha256(token), id])
+ const cookie = `hn_session=${token}`
+ const headers = { cookie, 'content-type': 'application/json', origin: 'http://localhost:3000' }
+ const mindId = (await (await fetch(`${base}/v1/minds`, { method: 'POST', headers, body: JSON.stringify({ templateId: 'payments-mind', name: 'Load shop' }) })).json()).mind.id as string
+ const w = await fetch(`${base}/v1/minds/${mindId}/wallet`, { method: 'POST', headers, body: '{}' })
+ if (w.status !== 201) throw new Error(`wallet: ${w.status} ${await w.text()}`)
+ // Payments, each made by a run whose events say who approved it (half by the owner's card, half by a rule).
+ const runId = `run_loadshop_${randomBytes(4).toString('hex')}`
+ await query(`insert into runs (id, mind_id, status) values ($1, $2, 'finished')`, [runId, mindId])
+ for (let i = 0; i < PAYMENTS_PER_MIND; i++) {
+ const pay = newId('pay')
+ await query(`insert into wallet_payments (id, mind_id, to_account, amount_yocto, status, tx_hash, message) values ($1, $2, 'shop.testnet', $3, $4, $5, $6)`,
+ [pay, mindId, (10n ** 21n * BigInt(i + 1)).toString(), i % 5 ? 'sent' : 'policy_denied', i % 5 ? randomBytes(22).toString('hex') : null, i % 5 ? null : 'Payment, "over" the limit, refused'])
+ const call = `c${i}`
+ const seq = i * 2
+ await query('insert into run_events (run_id, seq, type, payload, ts) values ($1, $2, $3, $4, now()), ($1, $5, $6, $7, now())', [runId, seq + 1,
+ i % 2 ? 'tool.approval_required' : 'tool.called', i % 2 ? { toolCallId: call } : { toolCallId: call, approvedBy: 'rule' }, seq + 2, 'tool.result', { toolCallId: call, result: { paymentId: pay } }])
+ }
+ return { cookie, mindId, walletToken: issueWalletToken(id, mindId) }
+}
+
+const users = await Promise.all(Array.from({ length: VUS }, user))
+const latencies: Record = { quotes: [], offer: [], csv: [] }
+let errors = 0
+const fail = (what: string) => { if (errors++ < 5) console.error(what) }
+async function timed(name: string, f: () => Promise) {
+ const t = performance.now()
+ try { if (!(await f())) fail(`${name}: wrong answer`) } catch (e) { fail(`${name}: ${e instanceof Error ? e.message : e}`) }
+ latencies[name].push(performance.now() - t)
+}
+// cheap.testnet (s2): price 0.0008, floor 0.0004. Offers and the answers they must get.
+const OFFERS: [string, string, string][] = [['0.0004', 'accepted', '0.0004'], ['0.0006', 'accepted', '0.0006'], ['0.0002', 'countered', '0.0005'], ['0.0001', 'countered', '0.00045'], ['0.01', 'accepted', '0.0008']]
+
+const until = Date.now() + DURATION_S * 1000
+const started = Date.now()
+await Promise.all(users.map(async (u, n) => {
+ const engineHeaders = { 'x-engine-key': ENGINE_KEY, 'x-wallet-token': u.walletToken }
+ let i = n
+ while (Date.now() < until) {
+ i++
+ await timed('quotes', async () => {
+ const r = await fetch(`${base}/internal/v1/shop/gas-price?quotes=1`, { headers: engineHeaders })
+ const b = await r.json()
+ return r.status === 200 && b.quotes.length === 3 && b.quotes[0].seller === 's2'
+ })
+ const [offer, status, price] = OFFERS[i % OFFERS.length]
+ await timed('offer', async () => {
+ const r = await fetch(`${base}/internal/v1/shop/network-status?seller=s2&offer=${offer}`, { headers: engineHeaders })
+ const b = await r.json()
+ return r.status === 200 && b.status === status && b.priceNear === price && b.payTo === 'cheap.testnet'
+ })
+ if (i % 3 === 0) await timed('csv', async () => {
+ const r = await fetch(`${base}/v1/minds/${u.mindId}/payments.csv`, { headers: { cookie: u.cookie } })
+ const text = await r.text()
+ const lines = text.trimEnd().split('\r\n')
+ return r.status === 200 && lines.length === PAYMENTS_PER_MIND + 1 && lines.filter((l) => l.includes(',your rule,')).length === PAYMENTS_PER_MIND / 2
+ })
+ }
+}))
+const seconds = (Date.now() - started) / 1000
+const pct = (xs: number[], p: number) => xs.slice().sort((a, b) => a - b)[Math.min(xs.length - 1, Math.floor((p / 100) * xs.length))]?.toFixed(1)
+for (const [name, xs] of Object.entries(latencies)) {
+ console.log(`${name}: ${xs.length} requests, ${(xs.length / seconds).toFixed(1)}/s, p50 ${pct(xs, 50)} ms, p95 ${pct(xs, 95)} ms, max ${pct(xs, 100)} ms`)
+}
+console.log(`VUs: ${VUS}, ${seconds.toFixed(1)} s; errors: ${errors}`)
+
+await query(`delete from users where near_account_id like 'loadshop-%'`)
+server.close()
+engine.close()
+outlayerServer.close()
+await pool.end()
+process.exit(errors || Object.values(latencies).some((xs) => !xs.length) ? 1 : 0)
diff --git a/apps/be/package.json b/apps/be/package.json
index 6220dee6..ca4c2bdf 100644
--- a/apps/be/package.json
+++ b/apps/be/package.json
@@ -9,11 +9,13 @@
"dev": "node --env-file=.env --import tsx src/server.ts",
"migrate": "node --env-file=.env --import tsx src/migrate.ts",
"test": "node --env-file-if-exists=.env --import tsx --test --test-concurrency=1 test/*.test.ts",
- "test:unit": "node --import tsx --test test/crypto.test.ts test/sse.test.ts test/telegram-format.test.ts test/approvals.test.ts",
+ "test:unit": "node --import tsx --test test/crypto.test.ts test/sse.test.ts test/telegram-format.test.ts test/approvals.test.ts test/relay.test.ts",
"load": "node --env-file-if-exists=.env --import tsx load/api.ts",
+ "load:shop": "node --env-file-if-exists=.env --import tsx load/shop.ts",
"typecheck": "tsc --noEmit"
},
"dependencies": {
+ "borsh": "2.0.0",
"near-api-js": "7.4.0",
"pg": "8.23.1",
"zod": "4.6.7"
diff --git a/apps/be/src/config.ts b/apps/be/src/config.ts
index c0db85d8..f1fb809c 100644
--- a/apps/be/src/config.ts
+++ b/apps/be/src/config.ts
@@ -34,6 +34,13 @@ export const config = {
authRecipient: process.env.AUTH_RECIPIENT ?? 'hellonear.app',
authMessage: 'Sign in to HelloNear',
nearRpcUrl: process.env.NEAR_RPC_URL ?? 'https://rpc.testnet.near.org',
+ // Meta-transaction relayer (realworld track, src/relay.ts): it pays gas only for allowed calls to the registry contract.
+ // Off (503 relay_not_configured) until both relayer values are set. rpc.testnet.near.org is deprecated, so the relay
+ // defaults to FastNear's testnet RPC unless NEAR_RPC_URL names another.
+ registryContractId: process.env.REGISTRY_CONTRACT_ID ?? 'hellonear-registry.testnet',
+ relayerAccountId: process.env.RELAYER_ACCOUNT_ID ?? '',
+ relayerPrivateKey: process.env.RELAYER_PRIVATE_KEY ?? '',
+ relayRpcUrl: process.env.NEAR_RPC_URL ?? 'https://test.rpc.fastnear.com',
cookieSecure: process.env.COOKIE_SECURE === 'true',
// Judge try-out mode (#43). Off unless DEMO_MODE=true; the shared demo wallet's agent key is optional.
demoMode: process.env.DEMO_MODE === 'true',
diff --git a/apps/be/src/payments.ts b/apps/be/src/payments.ts
index d52a058b..b52cc0e9 100644
--- a/apps/be/src/payments.ts
+++ b/apps/be/src/payments.ts
@@ -111,3 +111,53 @@ export async function listPayments(mindId: string, limit = 20) {
...(p.tx_hash ? { txHash: p.tx_hash } : {}), ...(p.message ? { message: p.message } : {}), at: p.created_at.toISOString(),
}))
}
+
+// CSV of a Mind's payments for an accountant (realworld track): one row per attempt, newest first, in words that need
+// no explaining. "Approved by" comes from the run that made the payment: a `tool.called` with `approvedBy: "rule"` is the
+// owner's auto-approve rule (#167), a `tool.approval_required` for the same call is the owner's own approval.
+const CSV_STATUS: Record = {
+ sent: 'sent', pending: 'pending', policy_denied: 'refused by the wallet policy (no money moved)',
+ wallet_frozen: 'refused, wallet frozen (no money moved)', failed: 'failed (no money moved)',
+}
+export const CSV_HEADER = ['Date (UTC)', 'Status', 'Direction', 'Amount (NEAR)', 'Counterparty', 'Purpose', 'Approved by', 'Transaction hash', 'Explorer link', 'Note']
+// RFC 4180 quoting, and a leading ' on a cell that a spreadsheet would read as a formula.
+export function csvCell(v: string): string {
+ const safe = /^[=+\-@\t\r]/.test(v) ? `'${v}` : v
+ return /[",\r\n]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe
+}
+export async function paymentsCsv(mindId: string, limit = 10_000): Promise {
+ // One pass: the payment calls in this Mind's runs, then who approved each, then the rows (no per-row subqueries).
+ const rows = await query<{ id: string; created_at: Date; status: PaymentStatus; amount_yocto: string; to_account: string; tx_hash: string | null; message: string | null; shop_item: string | null; offer_item: string | null; approved_by: string | null }>(
+ `with calls as (
+ select e.payload->'result'->>'paymentId' as payment_id, e.run_id, e.payload->>'toolCallId' as call
+ from run_events e join runs r on r.id = e.run_id
+ where r.mind_id = $1 and e.type in ('tool.result', 'tool.error') and e.payload->'result' ? 'paymentId'
+ ), approvals as (
+ select c.payment_id,
+ bool_or(a.type = 'tool.called' and a.payload->>'approvedBy' = 'rule') as by_rule,
+ bool_or(a.type = 'tool.approval_required') as by_owner
+ from calls c join run_events a on a.run_id = c.run_id and a.type in ('tool.called', 'tool.approval_required') and a.payload->>'toolCallId' = c.call
+ group by c.payment_id
+ )
+ select p.id, p.created_at, p.status, p.amount_yocto, p.to_account, p.tx_hash, p.message, s.item as shop_item, o.item as offer_item,
+ case when ap.by_rule then 'your rule' when ap.by_owner then 'owner' end as approved_by
+ from wallet_payments p
+ left join approvals ap on ap.payment_id = p.id
+ left join (select distinct on (payment_id) payment_id, item from shop_purchases where mind_id = $1) s on s.payment_id = p.id
+ left join (select distinct on (payment_id) payment_id, item from offer_purchases where buyer_mind_id = $1) o on o.payment_id = p.id
+ where p.mind_id = $1 order by p.created_at desc limit $2`, [mindId, limit])
+ const lines = [CSV_HEADER, ...rows.map((p) => [
+ p.created_at.toISOString().replace('T', ' ').slice(0, 19),
+ CSV_STATUS[p.status] ?? p.status,
+ 'out',
+ toNear(BigInt(p.amount_yocto)),
+ p.to_account,
+ p.shop_item ? `data report: ${p.shop_item}` : p.offer_item ? `bought from another Mind: ${p.offer_item}` : '',
+ p.approved_by ?? '',
+ p.tx_hash ?? '',
+ p.tx_hash ? `https://testnet.nearblocks.io/txns/${encodeURIComponent(p.tx_hash)}` : '',
+ p.message ?? '',
+ ])]
+ // A BOM so Excel opens it as UTF-8; CRLF line ends per RFC 4180.
+ return '' + lines.map((l) => l.map(csvCell).join(',')).join('\r\n') + '\r\n'
+}
diff --git a/apps/be/src/relay.ts b/apps/be/src/relay.ts
new file mode 100644
index 00000000..f115ef67
--- /dev/null
+++ b/apps/be/src/relay.ts
@@ -0,0 +1,112 @@
+// Meta-transaction relayer (realworld track, NEP-366): the owner signs a delegate action in their own wallet, and the
+// backend's relayer account wraps it in a transaction and pays the gas, so the owner needs no NEAR for gas. It only pays
+// for calls to our own registry contract (REGISTRY_CONTRACT_ID), only for the methods below, and never for a deposit
+// beyond the 1 yoctoNEAR those methods require: docs.near.org "Meta Transactions" (read 13 Nov) says an inner action's
+// attached deposit "is also paid for by the relayer", and the registry refunds storage to the caller, so allowing more
+// would let anyone drain the relayer. register_mind and equip_skill need a storage deposit (and equip a skill's price),
+// so they are not relayed. Every check that can fail runs before anything is sent: a refused request costs nothing.
+import { createHash } from 'node:crypto'
+import { deserialize } from 'borsh'
+import { Account, JsonRpcProvider, KeyPairSigner, PublicKey, SCHEMA, actions, baseEncode, encodeDelegateAction, encodeSignedDelegate, type KeyPairString, type SignedDelegate } from 'near-api-js'
+import { config } from './config.ts'
+import { HttpError, UPSTREAM_ERROR, fetchFailure } from './http.ts'
+
+// Owner methods the relayer pays gas for, each with the exact deposit the contract asks for (unequip_skill: exactly
+// 1 yoctoNEAR; set_wallet: at least 1, and storage only when the new address is longer, which the relayer won't pay).
+export const RELAY_METHODS: Record = { unequip_skill: 1n, set_wallet: 1n }
+const MAX_ACTIONS = 4
+const MAX_GAS_PER_CALL = 30_000_000_000_000n
+const MAX_ARGS_BYTES = 2048
+const MAX_DELEGATE_BYTES = 8192
+// How far ahead a delegate may expire: ~1 block a second, so about 16 minutes.
+export const MAX_TTL_BLOCKS = 1000n
+// Per owner, in memory (one backend process).
+export const RELAY_LIMIT = { perHour: 10 }
+const relayed = new Map()
+export const resetRelayLimits = () => relayed.clear()
+
+type Decoded = { delegateAction: { senderId: string; receiverId: string; actions: Record[]; nonce: bigint; maxBlockHeight: bigint; publicKey: { ed25519Key?: { data: number[] } } }; signature: { ed25519Signature?: { data: number[] } } }
+
+const refuse = (error: string, details: Record = {}) => new HttpError(400, error, details)
+
+// Decodes and checks the parts that need no chain: shape, receiver, methods, deposits, gas, sender and signature.
+export function checkDelegate(signedDelegateBase64: string, owner: string): Decoded {
+ const bytes = Buffer.from(signedDelegateBase64, 'base64')
+ if (!bytes.length || bytes.length > MAX_DELEGATE_BYTES || bytes.toString('base64') !== signedDelegateBase64.replace(/\s/g, '')) throw refuse('invalid_signed_delegate')
+ let sd: Decoded
+ try {
+ sd = deserialize((SCHEMA as any).SignedDelegate, bytes) as unknown as Decoded
+ // Trailing bytes or a non-canonical encoding would mean we check one thing and relay another.
+ if (Buffer.compare(Buffer.from(encodeSignedDelegate(sd as unknown as SignedDelegate)), bytes) !== 0) throw new Error('not canonical')
+ } catch {
+ throw refuse('invalid_signed_delegate')
+ }
+ const da = sd.delegateAction
+ if (da.senderId !== owner) throw new HttpError(403, 'delegate_sender_mismatch', { senderId: da.senderId })
+ if (da.receiverId !== config.registryContractId) throw refuse('receiver_not_allowed', { receiverId: da.receiverId, allowed: config.registryContractId })
+ if (!da.actions.length || da.actions.length > MAX_ACTIONS) throw refuse('too_many_actions', { max: MAX_ACTIONS })
+ for (const a of da.actions) {
+ const call = a.functionCall
+ if (!call || Object.keys(a).length !== 1) throw refuse('action_not_allowed', { action: Object.keys(a)[0] })
+ const deposit = RELAY_METHODS[call.methodName]
+ if (deposit === undefined) throw refuse('method_not_allowed', { method: call.methodName, allowed: Object.keys(RELAY_METHODS) })
+ if (BigInt(call.deposit) !== deposit) throw refuse('deposit_not_allowed', { method: call.methodName, depositYocto: String(call.deposit), allowedYocto: deposit.toString() })
+ if (BigInt(call.gas) > MAX_GAS_PER_CALL) throw refuse('gas_too_high', { maxGas: MAX_GAS_PER_CALL.toString() })
+ const args = Buffer.from(call.args)
+ if (args.length > MAX_ARGS_BYTES) throw refuse('args_too_large')
+ try { JSON.parse(args.toString('utf8')) } catch { throw refuse('args_not_json') }
+ }
+ // Only ed25519 (what NEAR wallets sign with); the signature covers sha256(NEP-461 prefix + delegate action).
+ const key = da.publicKey.ed25519Key?.data
+ const sig = sd.signature.ed25519Signature?.data
+ if (!key || !sig) throw refuse('unsupported_key_type')
+ const hash = createHash('sha256').update(encodeDelegateAction(da as never)).digest()
+ if (!PublicKey.fromString(`ed25519:${baseEncode(Uint8Array.from(key))}`).verify(hash, Uint8Array.from(sig))) throw refuse('bad_signature')
+ return sd
+}
+
+const publicKeyOf = (sd: Decoded) => `ed25519:${baseEncode(Uint8Array.from(sd.delegateAction.publicKey.ed25519Key!.data))}`
+
+export async function relay(signedDelegateBase64: string, owner: string): Promise<{ txHash: string; status: 'success' | 'failure'; senderId: string; receiverId: string; methods: string[]; failure?: unknown }> {
+ if (!config.relayerAccountId || !config.relayerPrivateKey) throw new HttpError(503, 'relay_not_configured')
+ const sd = checkDelegate(signedDelegateBase64, owner)
+ const da = sd.delegateAction
+
+ const now = Date.now()
+ const recent = (relayed.get(owner) ?? []).filter((t) => now - t < 3_600_000)
+ if (recent.length >= RELAY_LIMIT.perHour) throw new HttpError(429, 'relay_rate_limited', { perHour: RELAY_LIMIT.perHour })
+
+ const provider = new JsonRpcProvider({ url: config.relayRpcUrl })
+ const chain = async (f: () => Promise, notFound?: string): Promise => {
+ try { return await f() } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e)
+ if (notFound && /does not exist|UNKNOWN_ACCESS_KEY|doesn't exist/i.test(msg)) throw refuse(notFound)
+ throw new HttpError(UPSTREAM_ERROR, 'rpc_unreachable', { reason: fetchFailure(e) })
+ }
+ }
+ // The chain checks a relayed delegate too, but then the relayer has already paid gas for the failure.
+ const block = await chain(() => provider.viewBlock({ finality: 'final' }))
+ const height = BigInt(block.header.height)
+ if (da.maxBlockHeight <= height) throw refuse('delegate_expired', { maxBlockHeight: da.maxBlockHeight.toString(), height: height.toString() })
+ if (da.maxBlockHeight > height + MAX_TTL_BLOCKS) throw refuse('delegate_ttl_too_long', { maxBlocks: MAX_TTL_BLOCKS.toString() })
+ const key = await chain(() => provider.viewAccessKey({ accountId: da.senderId, publicKey: publicKeyOf(sd) as never }), 'unknown_access_key')
+ // The registry's 1 yoctoNEAR deposits exist so that a function-call key can't call these methods.
+ if (key.permission !== 'FullAccess') throw refuse('key_not_full_access')
+ if (da.nonce <= key.nonce) throw refuse('stale_nonce', { keyNonce: key.nonce.toString() })
+
+ recent.push(now)
+ relayed.set(owner, recent)
+ const relayer = new Account(config.relayerAccountId, provider, KeyPairSigner.fromSecretKey(config.relayerPrivateKey as KeyPairString))
+ let outcome: any
+ try {
+ outcome = await relayer.signAndSendTransaction({ receiverId: da.senderId, actions: [actions.signedDelegate(sd as never)], throwOnFailure: false })
+ } catch (e) {
+ throw new HttpError(UPSTREAM_ERROR, 'relay_failed', { reason: e instanceof Error ? e.message.slice(0, 200) : 'unknown' })
+ }
+ const failure = outcome?.status?.Failure ?? outcome?.receipts_outcome?.map((r: any) => r?.outcome?.status?.Failure).find(Boolean)
+ return {
+ txHash: String(outcome?.transaction?.hash ?? outcome?.transaction_outcome?.id ?? ''),
+ status: failure ? 'failure' : 'success', senderId: da.senderId, receiverId: da.receiverId,
+ methods: da.actions.map((a) => a.functionCall.methodName), ...(failure ? { failure } : {}),
+ }
+}
diff --git a/apps/be/src/server.ts b/apps/be/src/server.ts
index 1f60a67e..d008631e 100644
--- a/apps/be/src/server.ts
+++ b/apps/be/src/server.ts
@@ -11,10 +11,11 @@ import { TOOLKITS, connect, disconnect, listConnections, toolkitSchema } from '.
import { createMind, createMindSchema, deleteMind, listMinds, mindConfig, playgroundAttackOf, playgroundMind, requireMind, updateMind, updateMindSchema, type Mind } from './minds.ts'
import { cancelRun, getRun, isAwaiting, listRuns, mindEvents, pendingApprovals, relayRun, runEvents, runProofs, sweepStuckRuns } from './runs.ts'
import { explorerReport, quotesOf } from './teeExplorer.ts'
+import { relay } from './relay.ts'
import { deleteSecret, listSecrets, putSecret, putSecretSchema, secretNameSchema, secretsForRun } from './secrets.ts'
import { addressRuleOf, assertWalletEmpty, createWallet, freezeTransaction, getWallet, hasWallet, isDemoMind, policySchema, policyTransaction } from './wallets.ts'
-import { listPayments, sendPayment, sendPaymentSchema, walletBalance } from './payments.ts'
-import { itemSchema, sellerSchema, shop, txHashSchema } from './shop.ts'
+import { listPayments, paymentsCsv, sendPayment, sendPaymentSchema, walletBalance } from './payments.ts'
+import { itemSchema, offerNearSchema, sellerSchema, shop, txHashSchema } from './shop.ts'
import { buyOffer, offerItemSchema, putOffer, putOfferSchema } from './offers.ts'
import { issueMailToken, issueWalletToken, verifyMailToken, verifyWalletToken } from './walletToken.ts'
import { EMAIL_SKILL, ensureInbox, inboxOf, listMail, listSends, mailEnabled, messageIdSchema, ownerMailSchema, readMail, releaseInbox, sendMail, sendMailSchema, sendMailToOwner } from './mail.ts'
@@ -272,7 +273,11 @@ export const server = createServer(async (req, res) => {
// Best Price Buyer (#176): the price list, without paying; it takes no seller or tx.
const quotes = url.searchParams.get('quotes')
if (quotes !== null && (quotes !== '1' || tx !== null || seller !== null)) throw new HttpError(400, 'invalid_query')
- const out = await shop(mindId, item.data, { txHash: tx ?? undefined, seller: seller ?? undefined, quotes: quotes === '1' })
+ // Negotiation: an offer to one seller (`?seller=&offer=`), and the same offer again on the paid step.
+ const offer = url.searchParams.get('offer')
+ if (offer !== null && (quotes !== null || seller === null)) throw new HttpError(400, 'invalid_query')
+ if (offer !== null && !offerNearSchema.safeParse(offer).success) throw new HttpError(400, 'invalid_offer')
+ const out = await shop(mindId, item.data, { txHash: tx ?? undefined, seller: seller ?? undefined, quotes: quotes === '1', offerNear: offer ?? undefined })
return sendJson(res, out.httpStatus, out.body)
}
// Mind as Seller (#181): a Mind publishes what it sells (`PUT /internal/v1/offers/{item}`) and another Mind buys it
@@ -341,6 +346,14 @@ export const server = createServer(async (req, res) => {
// Skill ids are [a-z0-9-] in the engine; anything else is unknown and never reaches it.
if (skillRoute) return /^[a-z0-9-]{1,64}$/.test(skillRoute[1]) ? sendJson(res, 200, { skill: await skill(skillRoute[1]) }) : sendJson(res, 404, { error: 'unknown_skill' })
+ // Meta-transaction relayer (realworld track, src/relay.ts): the owner's signed delegate action for an allowed registry
+ // call; the relayer pays the gas. Try-out users have no NEAR account to sign with.
+ if (route('POST', /^\/v1\/relay$/)) {
+ denyDemo(user, 'relay')
+ const { signedDelegate } = await readBody(req, z.object({ signedDelegate: z.string().min(1).max(12_000) }))
+ return sendJson(res, 200, await relay(signedDelegate, user.nearAccountId))
+ }
+
// Secrets (#18): names and hosts only ever leave the backend, never values.
if (route('GET', /^\/v1\/secrets$/)) return sendJson(res, 200, { secrets: await listSecrets(user.id) })
const secret = path.match(/^\/v1\/secrets\/([^/]+)$/)
@@ -440,6 +453,12 @@ export const server = createServer(async (req, res) => {
if (sub === '/wallet' && req.method === 'POST') return sendJson(res, 201, { wallet: await createWallet(mind.id) })
if (sub === '/wallet' && req.method === 'GET') return sendJson(res, 200, { wallet: await getWallet(mind.id) })
if (sub === '/wallet/payments' && req.method === 'GET') return sendJson(res, 200, { payments: await listPayments(mind.id, limitOf(url, 20, 100)) })
+ // Every payment as a CSV an accountant can open (realworld track).
+ if (sub === '/payments.csv' && req.method === 'GET') {
+ const csv = await paymentsCsv(mind.id)
+ res.writeHead(200, { 'content-type': 'text/csv; charset=utf-8', 'content-disposition': `attachment; filename="hellonear-${mind.id}-payments.csv"`, 'cache-control': 'no-store', 'access-control-expose-headers': 'content-disposition' }).end(csv)
+ return
+ }
if (sub === '/wallet/policy' && req.method === 'POST') denyDemo(user, 'set_policy')
if (sub === '/wallet/policy' && req.method === 'POST') return sendJson(res, 200, { transaction: await policyTransaction(mind.id, user.nearAccountId, await readBody(req, policySchema)) })
if ((sub === '/wallet/freeze' || sub === '/wallet/unfreeze') && req.method === 'POST') denyDemo(user, 'freeze')
diff --git a/apps/be/src/shop.ts b/apps/be/src/shop.ts
index 15083f3f..ec02b333 100644
--- a/apps/be/src/shop.ts
+++ b/apps/be/src/shop.ts
@@ -6,6 +6,10 @@
// The reports are read live from NEAR testnet RPC. This is a 402 pattern on testnet NEAR, not the x402 standard.
// Best Price Buyer (#176): the same items can have several sellers (SHOP_SELLERS) at different prices. `?quotes=1` lists
// them cheapest first without paying, `?seller=` picks one, and a payment counts for the seller it was sent to.
+// Negotiation (agents track): `?seller=&offer=` asks one seller to sell for less. Each seller has a floor (a share of its
+// price, 0.8 unless SHOP_SELLERS names one); an offer at or above it is accepted, one below it gets a single counter
+// halfway between the offer and the price, never under the floor. Stateless: offering the counter is accepted, and the
+// paid step with the same `offer` checks the payment against the agreed price.
import { z } from 'zod'
import { config } from './config.ts'
import { query } from './db.ts'
@@ -51,15 +55,19 @@ export const txHashSchema = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{43,44}$/, 'a
export const sellerSchema = z.string().regex(/^s\d{1,2}$/, 'a seller id such as "s1"')
// A seller's id is its place in SHOP_SELLERS (`s1`, `s2`, …), so it stays the same while the list does.
-export type Seller = { id: string; account: string; multiplierMilli: bigint }
+export type Seller = { id: string; account: string; multiplierMilli: bigint; floorMilli: bigint }
+const DEFAULT_FLOOR_MILLI = 800n
+const milliOf = (whole: string, frac: string | undefined) => BigInt(whole) * 1000n + BigInt((frac ?? '').padEnd(3, '0'))
const ACCOUNT_ID = /^(?=.{2,64}$)(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/
export function parseSellers(spec: string, fallback: string): Seller[] {
- if (!spec) return fallback ? [{ id: 's1', account: fallback, multiplierMilli: 1000n }] : []
+ if (!spec) return fallback ? [{ id: 's1', account: fallback, multiplierMilli: 1000n, floorMilli: DEFAULT_FLOOR_MILLI }] : []
const sellers = spec.split(',').map((part, i) => {
- const m = part.trim().match(/^([^:\s]+):(\d{1,2})(?:\.(\d{1,3}))?$/)
- const milli = m ? BigInt(m[2]) * 1000n + BigInt((m[3] ?? '').padEnd(3, '0')) : 0n
- if (!m || !ACCOUNT_ID.test(m[1]) || milli === 0n) throw new Error(`SHOP_SELLERS: "${part.trim()}" is not account:multiplier (e.g. a.testnet:0.8)`)
- return { id: `s${i + 1}`, account: m[1], multiplierMilli: milli }
+ // account:multiplier[:floor], the floor a share of the seller's own price (0 < floor <= 1).
+ const m = part.trim().match(/^([^:\s]+):(\d{1,2})(?:\.(\d{1,3}))?(?::(\d)(?:\.(\d{1,3}))?)?$/)
+ const milli = m ? milliOf(m[2], m[3]) : 0n
+ const floor = m?.[4] === undefined ? DEFAULT_FLOOR_MILLI : milliOf(m[4], m[5])
+ if (!m || !ACCOUNT_ID.test(m[1]) || milli === 0n || floor === 0n || floor > 1000n) throw new Error(`SHOP_SELLERS: "${part.trim()}" is not account:multiplier[:floor] (e.g. a.testnet:0.8 or a.testnet:0.8:0.7)`)
+ return { id: `s${i + 1}`, account: m[1], multiplierMilli: milli, floorMilli: floor }
})
if (new Set(sellers.map((x) => x.account)).size !== sellers.length) throw new Error('SHOP_SELLERS: an account is listed twice')
return sellers
@@ -68,15 +76,20 @@ export function parseSellers(spec: string, fallback: string): Seller[] {
parseSellers(config.shopSellers, config.shopPayTo)
const priceOf = (it: Item, s: Seller) => toYocto(it.priceNear) * s.multiplierMilli / 1000n
+const floorOf = (it: Item, s: Seller) => priceOf(it, s) * s.floorMilli / 1000n
+// What this seller takes for an offer: the offer itself (never more than the price) when it reaches the floor, else null.
+const agreedOf = (it: Item, s: Seller, offer: bigint) => offer >= floorOf(it, s) ? (offer < priceOf(it, s) ? offer : priceOf(it, s)) : null
+export const offerNearSchema = z.string().regex(/^\d{1,3}(\.\d{1,24})?$/, 'a decimal NEAR amount such as "0.0008"').refine((a) => /[1-9]/.test(a), 'must be more than 0')
const offerOf = (item: string, it: Item, s: Seller) => ({ item, title: it.title, seller: s.id, priceNear: toNear(priceOf(it, s)), payTo: s.account })
type Offer = ReturnType
export type ShopAnswer =
| ({ status: 'payment_required' } & Offer)
| { status: 'quotes'; item: string; title: string; quotes: { seller: string; payTo: string; priceNear: string; onYourList: boolean }[] }
+ | { status: 'accepted' | 'countered'; item: string; title: string; seller: string; priceNear: string; payTo: string; reason: string }
| { status: 'paid'; item: string; title: string; seller: string; data: Record; receipt: { txHash: string; paymentId: string; amountNear: string; payTo: string } }
-export async function shop(mindId: string, item: string, opts: { txHash?: string; seller?: string; quotes?: boolean } = {}): Promise<{ httpStatus: 200 | 402; body: ShopAnswer }> {
+export async function shop(mindId: string, item: string, opts: { txHash?: string; seller?: string; quotes?: boolean; offerNear?: string } = {}): Promise<{ httpStatus: 200 | 402; body: ShopAnswer }> {
const it = ITEMS[item]
// Cheapest first; a tie keeps the SHOP_SELLERS order.
const sellers = parseSellers(config.shopSellers, config.shopPayTo).sort((a, b) => { const d = priceOf(it, a) - priceOf(it, b); return d < 0n ? -1 : d > 0n ? 1 : 0 })
@@ -89,7 +102,19 @@ export async function shop(mindId: string, item: string, opts: { txHash?: string
}
const asked = opts.seller === undefined ? undefined : sellers.find((s) => s.id === opts.seller)
if (opts.seller !== undefined && !asked) throw new HttpError(404, 'unknown_seller')
- const offer = offerOf(item, it, asked ?? sellers[0])
+ if (opts.offerNear !== undefined && !asked) throw new HttpError(400, 'offer_needs_seller')
+ const offered = opts.offerNear === undefined ? undefined : toYocto(opts.offerNear)
+ const agreed = asked && offered !== undefined ? agreedOf(it, asked, offered) : null
+ if (asked && offered !== undefined && !opts.txHash) {
+ const base = { item, title: it.title, seller: asked.id, payTo: asked.account }
+ if (agreed !== null) return { httpStatus: 200, body: { ...base, status: 'accepted', priceNear: toNear(agreed), reason: agreed < priceOf(it, asked) ? `Seller ${asked.id} accepts ${toNear(agreed)} NEAR instead of ${toNear(priceOf(it, asked))}.` : `${toNear(priceOf(it, asked))} NEAR is already the full price; no discount needed.` } }
+ const mid = (offered + priceOf(it, asked)) / 2n
+ const counter = mid > floorOf(it, asked) ? mid : floorOf(it, asked)
+ return { httpStatus: 200, body: { ...base, status: 'countered', priceNear: toNear(counter), reason: `${toNear(offered)} NEAR is under what seller ${asked.id} takes; it counters at ${toNear(counter)} NEAR, halfway to its price of ${toNear(priceOf(it, asked))}. Offer that to accept, or walk away.` } }
+ }
+ // The price a payment must reach: the agreed one after an accepted offer, else the seller's list price.
+ const owed = (s: Seller) => s === asked && agreed !== null ? agreed : priceOf(it, s)
+ const offer = { ...offerOf(item, it, asked ?? sellers[0]), ...(asked && agreed !== null ? { priceNear: toNear(agreed) } : {}) }
if (!opts.txHash) return { httpStatus: 402, body: { status: 'payment_required', ...offer } }
const txHash = opts.txHash
@@ -100,12 +125,12 @@ export async function shop(mindId: string, item: string, opts: { txHash?: string
`select id, to_account, amount_yocto from wallet_payments where mind_id = $1 and tx_hash = $2 and status = 'sent' and created_at > now() - interval '1 hour'`, [mindId, txHash])
if (!pay) throw new HttpError(402, 'payment_not_found', offer)
const seller = sellers.find((s) => s.account === pay.to_account)
- if (!seller || (asked && seller !== asked) || BigInt(pay.amount_yocto) < priceOf(it, seller)) throw new HttpError(402, 'payment_does_not_match', offer)
+ if (!seller || (asked && seller !== asked) || BigInt(pay.amount_yocto) < owed(seller)) throw new HttpError(402, 'payment_does_not_match', offer)
// Then the chain: the transfer succeeded, from this wallet, to that seller, for at least its price.
const { address } = await keyOf(mindId)
const tx = (await rpc('tx', { tx_hash: txHash, sender_account_id: address, wait_until: 'FINAL' })).result
const deposit = (tx?.transaction?.actions ?? []).reduce((sum: bigint, a: any) => sum + BigInt(a?.Transfer?.deposit ?? 0), 0n)
- const ok = tx?.status && 'SuccessValue' in tx.status && tx.transaction?.signer_id === address && tx.transaction?.receiver_id === seller.account && deposit >= priceOf(it, seller)
+ const ok = tx?.status && 'SuccessValue' in tx.status && tx.transaction?.signer_id === address && tx.transaction?.receiver_id === seller.account && deposit >= owed(seller)
if (!ok) throw new HttpError(402, 'payment_not_on_chain', offer)
// Read before redeeming: if RPC fails here, the hash is still unused and the Mind can ask again (Lin1er, #156).
diff --git a/apps/be/test/api.test.ts b/apps/be/test/api.test.ts
index 3d30280d..97b7cecc 100644
--- a/apps/be/test/api.test.ts
+++ b/apps/be/test/api.test.ts
@@ -5,7 +5,7 @@ import { after, before, describe, test } from 'node:test'
import assert from 'node:assert/strict'
import type { AddressInfo } from 'node:net'
import { createHash, randomBytes } from 'node:crypto'
-import { KeyPair, KeyPairSigner } from 'near-api-js'
+import { KeyPair, KeyPairSigner, actions as nearActions, buildDelegateAction, decodeSignedTransaction, encodeSignedDelegate } from 'near-api-js'
import { ENGINE_KEY, engine, fake, fakeProof } from './fake-engine.ts'
import { fakeOutlayer, outlayerServer } from './fake-outlayer.ts'
import { COMPOSIO_KEY, composioServer, fakeComposio } from './fake-composio.ts'
@@ -1084,13 +1084,143 @@ describe('payment tools through the backend (#42, option B)', () => {
// A bad list stops the backend at start rather than at the first purchase.
for (const bad of ['a.testnet', 'a.testnet:0', 'a.testnet:1,a.testnet:2', 'NOT AN ACCOUNT:1', 'a.testnet:1.2345']) assert.throws(() => parseSellers(bad, ''), /SHOP_SELLERS/, bad)
- assert.deepEqual(parseSellers('', 'shop.testnet'), [{ id: 's1', account: 'shop.testnet', multiplierMilli: 1000n }])
+ assert.deepEqual(parseSellers('', 'shop.testnet'), [{ id: 's1', account: 'shop.testnet', multiplierMilli: 1000n, floorMilli: 800n }])
assert.deepEqual(parseSellers('', ''), [])
} finally {
;[config.shopPayTo, config.shopSellers] = saved
}
})
+ test('Negotiation: an offer at the floor is accepted, one under it gets one counter, and the paid step checks the agreed price', async () => {
+ const { config } = await import('../src/config.ts')
+ const { parseSellers } = await import('../src/shop.ts')
+ const saved = [config.shopPayTo, config.shopSellers] as const
+ try {
+ config.shopPayTo = 'shop.testnet'
+ // s1 keeps the default floor (0.8 of its price), s2 names its own (0.5).
+ config.shopSellers = 'shop.testnet:1,cheap.testnet:0.8:0.5'
+ const a = await signIn()
+ const { mindId } = await walletMind(a, { policy: false })
+ const token = await tokenFromChat(a, mindId)
+ const get = async (q: string) => { const r = await engineCall('GET', `/internal/v1/shop/network-status${q}`, token); return [r.status, await r.json()] as const }
+ const sold = { item: 'network-status', title: 'NEAR testnet status: latest block, protocol version, validator count' }
+
+ // s1: price 0.001, floor 0.0008.
+ let [status, out] = await get('?seller=s1&offer=0.0008')
+ assert.equal(status, 200, JSON.stringify(out))
+ assert.deepEqual({ ...out, reason: undefined }, { ...sold, status: 'accepted', seller: 's1', priceNear: '0.0008', payTo: 'shop.testnet', reason: undefined })
+ assert.match(out.reason, /accepts 0\.0008 NEAR instead of 0\.001/)
+ // Under the floor: one counter, halfway to the price (0.0007 → 0.00085), never under the floor.
+ ;[status, out] = await get('?seller=s1&offer=0.0007')
+ assert.deepEqual([status, out.status, out.priceNear], [200, 'countered', '0.00085'])
+ assert.match(out.reason, /counters at 0\.00085 NEAR/)
+ // Halfway would be 0.00055, under the floor: the counter is the floor.
+ ;[, out] = await get('?seller=s1&offer=0.0001')
+ assert.deepEqual([out.status, out.priceNear], ['countered', '0.0008'])
+ // Offering the counter is accepted (stateless).
+ ;[, out] = await get('?seller=s1&offer=0.00085')
+ assert.deepEqual([out.status, out.priceNear], ['accepted', '0.00085'])
+ // Over the price: the price, not more.
+ ;[, out] = await get('?seller=s1&offer=0.5')
+ assert.deepEqual([out.status, out.priceNear], ['accepted', '0.001'])
+ // s2: price 0.0008, its own floor 0.5 → 0.0004.
+ ;[, out] = await get('?seller=s2&offer=0.0004')
+ assert.deepEqual([out.status, out.priceNear, out.payTo], ['accepted', '0.0004', 'cheap.testnet'])
+ ;[, out] = await get('?seller=s2&offer=0.0002')
+ assert.deepEqual([out.status, out.priceNear], ['countered', '0.0005'])
+
+ // An offer needs a seller and a valid amount, and is not part of the price list.
+ for (const q of ['?offer=0.0008', '?seller=s1&offer=0', '?seller=s1&offer=abc', '?seller=s1&offer=-1', '?quotes=1&offer=0.0008']) assert.equal((await get(q))[0], 400, q)
+ assert.equal((await get('?seller=s9&offer=0.0008'))[0], 404)
+
+ const pay = async (to: string, amountNear: string) => (await (await engineCall('POST', '/internal/v1/wallet/send_payment', token, { to, amountNear })).json()).txHash as string
+ // Paid at the agreed price: redeemed with the same offer.
+ const agreed = await pay('shop.testnet', '0.0008')
+ // Without the offer, 0.0008 is short of s1's list price.
+ assert.equal((await get(`?seller=s1&tx=${agreed}`))[1].error, 'payment_does_not_match')
+ // An offer under the floor was never agreed, so the list price still applies.
+ ;[status, out] = await get(`?seller=s1&offer=0.0007&tx=${agreed}`)
+ assert.deepEqual([status, out.error, out.priceNear], [402, 'payment_does_not_match', '0.001'])
+ // A 402 for an accepted offer names the agreed price.
+ ;[status, out] = await get('?seller=s1&offer=0.0008&tx=' + '1'.repeat(44))
+ assert.deepEqual([status, out.error, out.seller, out.priceNear, out.payTo], [402, 'payment_not_found', 's1', '0.0008', 'shop.testnet'])
+ ;[status, out] = await get(`?seller=s1&offer=0.0008&tx=${agreed}`)
+ assert.equal(status, 200, JSON.stringify(out))
+ assert.deepEqual([out.status, out.seller, out.receipt.amountNear], ['paid', 's1', '0.0008'])
+ // Paying under the agreed price does not count.
+ const short = await pay('shop.testnet', '0.00079')
+ assert.equal((await get(`?seller=s1&offer=0.0008&tx=${short}`))[1].error, 'payment_does_not_match')
+
+ for (const bad of ['a.testnet:1:0', 'a.testnet:1:1.5', 'a.testnet:1:0.8:1']) assert.throws(() => parseSellers(bad, ''), /SHOP_SELLERS/, bad)
+ assert.deepEqual(parseSellers('a.testnet:1.2:0.65', '')[0], { id: 's1', account: 'a.testnet', multiplierMilli: 1200n, floorMilli: 650n })
+ assert.deepEqual(parseSellers('a.testnet:1:1', '')[0].floorMilli, 1000n)
+ } finally {
+ ;[config.shopPayTo, config.shopSellers] = saved
+ }
+ })
+
+ test('payments CSV: every attempt in plain words, with purpose, who approved it, the tx and its explorer link; owner only', async () => {
+ const { csvCell } = await import('../src/payments.ts')
+ const saved = [config.shopPayTo, config.shopSellers] as const
+ try {
+ config.shopPayTo = 'shop.testnet'
+ config.shopSellers = ''
+ const a = await signIn()
+ const { mindId } = await walletMind(a)
+ const token = await tokenFromChat(a, mindId)
+ const pay = async (to: string, amountNear: string) => (await (await engineCall('POST', '/internal/v1/wallet/send_payment', token, { to, amountNear })).json())
+ const bought = await pay('shop.testnet', '0.001')
+ const r = await engineCall('GET', `/internal/v1/shop/gas-price?tx=${bought.txHash}`, token)
+ assert.equal(r.status, 200, await r.clone().text())
+ const ruled = await pay('shop.testnet', '0.002')
+ const refused = await pay('stranger.testnet', '0.003')
+ assert.equal(refused.status, 'policy_denied')
+ // The runs that made them: one approved by the owner's card, one by an auto-approve rule.
+ const runId = `run_csv_${randomBytes(4).toString('hex')}`
+ await query(`insert into runs (id, mind_id, status) values ($1, $2, 'finished')`, [runId, mindId])
+ const ev = [
+ ['tool.approval_required', { toolCallId: 'c1', tool: 'send_payment' }],
+ ['tool.result', { toolCallId: 'c1', tool: 'send_payment', result: { paymentId: bought.paymentId } }],
+ ['tool.called', { toolCallId: 'c2', tool: 'send_payment', approvedBy: 'rule', rule: 'payment' }],
+ ['tool.result', { toolCallId: 'c2', tool: 'send_payment', result: { paymentId: ruled.paymentId } }],
+ ] as const
+ for (const [i, [type, payload]] of ev.entries()) await query('insert into run_events (run_id, seq, type, payload, ts) values ($1, $2, $3, $4, now())', [runId, i + 1, type, payload])
+
+ const res = await a.call('GET', `/v1/minds/${mindId}/payments.csv`)
+ assert.equal(res.status, 200)
+ assert.equal(res.headers.get('content-type'), 'text/csv; charset=utf-8')
+ assert.equal(res.headers.get('content-disposition'), `attachment; filename="hellonear-${mindId}-payments.csv"`)
+ // The web app fetches it from another origin on the hosted site and names the file from this header (#297 review).
+ assert.equal(res.headers.get('access-control-expose-headers'), 'content-disposition')
+ const text = await res.text()
+ // fetch's text() strips the BOM; check the raw bytes start with it.
+ assert.equal(text.includes('\r\n'), true)
+ const lines = text.trimEnd().split('\r\n')
+ assert.equal(lines[0], 'Date (UTC),Status,Direction,Amount (NEAR),Counterparty,Purpose,Approved by,Transaction hash,Explorer link,Note')
+ assert.equal(lines.length, 4)
+ const byAmount = Object.fromEntries(lines.slice(1).map((l) => [l.split(',')[3], l.split(',')]))
+ const b = byAmount['0.001']
+ assert.match(b[0], /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/)
+ assert.deepEqual(b.slice(1, 9), ['sent', 'out', '0.001', 'shop.testnet', 'data report: gas-price', 'owner', bought.txHash, `https://testnet.nearblocks.io/txns/${bought.txHash}`])
+ assert.deepEqual(byAmount['0.002'].slice(1, 7), ['sent', 'out', '0.002', 'shop.testnet', '', 'your rule'])
+ assert.deepEqual(byAmount['0.003'].slice(1, 8), ['refused by the wallet policy (no money moved)', 'out', '0.003', 'stranger.testnet', '', '', ''])
+ const raw = new Uint8Array(await (await a.call('GET', `/v1/minds/${mindId}/payments.csv`)).arrayBuffer())
+ assert.deepEqual([...raw.slice(0, 3)], [0xef, 0xbb, 0xbf])
+
+ // Another owner's Mind is not found; no session is 401.
+ assert.equal((await (await signIn()).call('GET', `/v1/minds/${mindId}/payments.csv`)).status, 404)
+ assert.equal((await client()('GET', `/v1/minds/${mindId}/payments.csv`)).status, 401)
+
+ assert.equal(csvCell('plain'), 'plain')
+ assert.equal(csvCell('a,b'), '"a,b"')
+ assert.equal(csvCell('say "hi"\nok'), '"say ""hi""\nok"')
+ assert.equal(csvCell('=HYPERLINK("x")'), `"'=HYPERLINK(""x"")"`)
+ assert.equal(csvCell('-1'), "'-1")
+ } finally {
+ ;[config.shopPayTo, config.shopSellers] = saved
+ }
+ })
+
test('Mind as Seller (#181): a Mind publishes an offer; another Mind pays the seller\'s own wallet and gets it, once', async () => {
const a = await signIn()
const seller = await walletMind(a)
@@ -2798,3 +2928,115 @@ describe('auto-approve rules (#167)', () => {
assert.deepEqual((await (await call('GET', `/v1/minds/${mind.id}`, undefined, h)).json()).mind.autoApprove, { tools: [], payment: null })
})
})
+
+describe('meta-transaction relayer (realworld track)', () => {
+ const origin = { origin: 'http://localhost:3000' }
+ async function owner() {
+ const { keyPair, accountId, publicKey } = await newAccount()
+ const call = client()
+ const { nonce } = await (await call('POST', '/v1/auth/challenge', {})).json()
+ const res = await call('POST', '/v1/auth/login', { accountId, publicKey, nonce, signature: await sign(keyPair, accountId, nonce) })
+ const cookie = res.headers.get('set-cookie')!.split(';')[0]
+ fakeOutlayer.accessKeys.set(`${accountId}:${publicKey}`, { nonce: 100, permission: 'FullAccess' })
+ return { keyPair, accountId, publicKey, call: client(cookie) }
+ }
+ async function delegate(o: { keyPair: KeyPair; accountId: string }, over: { nonce?: bigint; maxBlockHeight?: bigint; method?: string } = {}) {
+ const da = buildDelegateAction({
+ senderId: o.accountId, receiverId: config.registryContractId,
+ actions: [nearActions.functionCall(over.method ?? 'unequip_skill', { mind_id: 'mnd_1', skill_id: 'pay' }, 30_000_000_000_000n, 1n)],
+ nonce: over.nonce ?? 101n, maxBlockHeight: over.maxBlockHeight ?? BigInt(fakeOutlayer.height + 100), publicKey: o.keyPair.getPublicKey(),
+ })
+ const { signedDelegate } = await new KeyPairSigner(o.keyPair).signDelegateAction(da)
+ return Buffer.from(encodeSignedDelegate(signedDelegate)).toString('base64')
+ }
+ const relayer = KeyPair.fromRandom('ed25519')
+ const saved = [config.relayerAccountId, config.relayerPrivateKey] as const
+ before(async () => {
+ const { resetRelayLimits } = await import('../src/relay.ts')
+ resetRelayLimits()
+ config.relayerAccountId = 'relayer.testnet'
+ config.relayerPrivateKey = relayer.toString()
+ fakeOutlayer.accessKeys.set(`relayer.testnet:${relayer.getPublicKey().toString()}`, { nonce: 5, permission: 'FullAccess' })
+ })
+ after(() => { [config.relayerAccountId, config.relayerPrivateKey] = saved })
+
+ test('relays an allowed registry call: the relayer signs a transaction to the owner carrying the owner\'s signed delegate', async () => {
+ const o = await owner()
+ const before = fakeOutlayer.sent.length
+ const res = await o.call('POST', '/v1/relay', { signedDelegate: await delegate(o) }, origin)
+ assert.equal(res.status, 200, await res.clone().text())
+ const out = await res.json()
+ assert.deepEqual({ ...out, txHash: typeof out.txHash }, { txHash: 'string', status: 'success', senderId: o.accountId, receiverId: config.registryContractId, methods: ['unequip_skill'] })
+ assert.equal(fakeOutlayer.sent.length, before + 1)
+ const tx: any = decodeSignedTransaction(Buffer.from(fakeOutlayer.sent.at(-1)!.signedTxBase64, 'base64'))
+ assert.equal(tx.transaction.signerId, 'relayer.testnet')
+ assert.equal(tx.transaction.receiverId, o.accountId)
+ assert.equal(tx.transaction.nonce, 6n)
+ assert.equal(tx.transaction.actions.length, 1)
+ assert.equal(tx.transaction.actions[0].signedDelegate.delegateAction.senderId, o.accountId)
+ assert.equal(tx.transaction.actions[0].signedDelegate.delegateAction.actions[0].functionCall.methodName, 'unequip_skill')
+ // The relayer's signature is valid for its own key over the transaction.
+ const { createHash } = await import('node:crypto')
+ const { encodeTransaction } = await import('near-api-js')
+ const hash = createHash('sha256').update(encodeTransaction(tx.transaction)).digest()
+ assert.ok(relayer.getPublicKey().verify(hash, Uint8Array.from(tx.signature.ed25519Signature.data)))
+
+ // An inner failure is reported, not hidden.
+ fakeOutlayer.relayOutcome = { Failure: { ActionError: { kind: { FunctionCallError: { ExecutionError: 'skill is not equipped' } } } } }
+ try {
+ const failed = await (await o.call('POST', '/v1/relay', { signedDelegate: await delegate(o, { nonce: 102n }) }, origin)).json()
+ assert.equal(failed.status, 'failure')
+ assert.ok(failed.failure.ActionError)
+ } finally {
+ fakeOutlayer.relayOutcome = { SuccessValue: '' }
+ }
+ })
+
+ test('refuses before sending: expired, too far ahead, a stale nonce, an unknown or function-call key, another method, another sender', async () => {
+ const o = await owner()
+ const before = fakeOutlayer.sent.length
+ const post = async (signedDelegate: string, c = o.call) => { const r = await c('POST', '/v1/relay', { signedDelegate }, origin); return [r.status, (await r.json()).error] }
+ assert.deepEqual(await post(await delegate(o, { maxBlockHeight: BigInt(fakeOutlayer.height) })), [400, 'delegate_expired'])
+ assert.deepEqual(await post(await delegate(o, { maxBlockHeight: BigInt(fakeOutlayer.height + 5000) })), [400, 'delegate_ttl_too_long'])
+ assert.deepEqual(await post(await delegate(o, { nonce: 100n })), [400, 'stale_nonce'])
+ assert.deepEqual(await post(await delegate(o, { method: 'equip_skill' })), [400, 'method_not_allowed'])
+ fakeOutlayer.accessKeys.set(`${o.accountId}:${o.publicKey}`, { nonce: 100, permission: { FunctionCall: { allowance: null, receiver_id: config.registryContractId, method_names: [] } } })
+ assert.deepEqual(await post(await delegate(o)), [400, 'key_not_full_access'])
+ fakeOutlayer.accessKeys.delete(`${o.accountId}:${o.publicKey}`)
+ assert.deepEqual(await post(await delegate(o)), [400, 'unknown_access_key'])
+ // Signed by one owner, sent by another.
+ const other = await owner()
+ assert.deepEqual(await post(await delegate(other), o.call), [403, 'delegate_sender_mismatch'])
+ assert.equal(fakeOutlayer.sent.length, before)
+ // Bad body, CSRF, no session.
+ assert.equal((await o.call('POST', '/v1/relay', {}, origin)).status, 400)
+ assert.equal((await o.call('POST', '/v1/relay', { signedDelegate: await delegate(other) }, { origin: 'https://evil.example' })).status, 403)
+ assert.equal((await client()('POST', '/v1/relay', { signedDelegate: 'x' }, origin)).status, 401)
+ })
+
+ test('per-owner hourly limit, try-out users refused, and 503 when no relayer is configured', async () => {
+ const { RELAY_LIMIT, resetRelayLimits } = await import('../src/relay.ts')
+ const o = await owner()
+ const limit = RELAY_LIMIT.perHour
+ RELAY_LIMIT.perHour = 2
+ try {
+ for (const n of [201n, 202n]) assert.equal((await o.call('POST', '/v1/relay', { signedDelegate: await delegate(o, { nonce: n }) }, origin)).status, 200)
+ const r = await o.call('POST', '/v1/relay', { signedDelegate: await delegate(o, { nonce: 203n }) }, origin)
+ assert.deepEqual([r.status, (await r.json()).error], [429, 'relay_rate_limited'])
+ } finally {
+ RELAY_LIMIT.perHour = limit
+ resetRelayLimits()
+ }
+ const demo = await client()('POST', '/v1/auth/demo', {}, { ...origin, 'cf-connecting-ip': '198.51.100.251' })
+ const demoCall = client(demo.headers.get('set-cookie')!.split(';')[0])
+ const d = await demoCall('POST', '/v1/relay', { signedDelegate: await delegate(o, { nonce: 300n }) }, origin)
+ assert.deepEqual([d.status, (await d.json()).error], [403, 'demo_not_allowed'])
+ config.relayerPrivateKey = ''
+ try {
+ const r = await o.call('POST', '/v1/relay', { signedDelegate: await delegate(o, { nonce: 301n }) }, origin)
+ assert.deepEqual([r.status, (await r.json()).error], [503, 'relay_not_configured'])
+ } finally {
+ config.relayerPrivateKey = relayer.toString()
+ }
+ })
+})
diff --git a/apps/be/test/fake-outlayer.ts b/apps/be/test/fake-outlayer.ts
index a23ab84a..63a238a0 100644
--- a/apps/be/test/fake-outlayer.ts
+++ b/apps/be/test/fake-outlayer.ts
@@ -13,6 +13,11 @@ export const fakeOutlayer = {
// The next gas_price answer is an RPC error (#156 review: a failed read must not use up the payment).
failGasPrice: false,
failNext: 0,
+ // The relayer's chain (src/relay.ts): block height, access keys (`account:publicKey`), and the transactions it sent.
+ height: 277390000,
+ accessKeys: new Map(),
+ sent: [] as { signedTxBase64: string }[],
+ relayOutcome: { SuccessValue: '' } as unknown,
// A wallet created outside the backend (the shared demo wallet), funded with 1 NEAR, no policy.
addWallet(): Wallet {
const w: Wallet = { walletId: randomUUID(), key: `wk_${randomBytes(32).toString('hex')}`, account: randomBytes(32).toString('hex'), frozen: false, policy: null, balance: (10n ** 24n).toString(), policyVersion: 0 }
@@ -55,6 +60,19 @@ export const outlayerServer = createServer(async (req, res) => {
}
if (req.method === 'POST' && url.pathname === '/rpc' && body.method === 'gas_price' && fakeOutlayer.failGasPrice) { fakeOutlayer.failGasPrice = false; return send(res, 200, { jsonrpc: '2.0', id: 1, error: { name: 'INTERNAL_ERROR' } }) }
if (req.method === 'POST' && url.pathname === '/rpc' && body.method === 'gas_price') return send(res, 200, { jsonrpc: '2.0', id: 1, result: { gas_price: '100000000' } })
+ if (req.method === 'POST' && url.pathname === '/rpc' && body.method === 'block') {
+ return send(res, 200, { jsonrpc: '2.0', id: body.id, result: { header: { height: fakeOutlayer.height, hash: 'GJ2rdQDMGFVsZPn9RYfWo5BibVx8iBFDWvnbvMzaWUfR', timestamp: 0 } } })
+ }
+ if (req.method === 'POST' && url.pathname === '/rpc' && body.method === 'query' && body.params?.request_type === 'view_access_key') {
+ const k = fakeOutlayer.accessKeys.get(`${body.params.account_id}:${body.params.public_key}`)
+ if (!k) return send(res, 200, { jsonrpc: '2.0', id: body.id, error: { name: 'HANDLER_ERROR', cause: { name: 'UNKNOWN_ACCESS_KEY', info: { public_key: body.params.public_key } }, code: -32000, message: 'Server error', data: `Access key for public key ${body.params.public_key} does not exist while viewing` } })
+ return send(res, 200, { jsonrpc: '2.0', id: body.id, result: { nonce: k.nonce, permission: k.permission, block_height: fakeOutlayer.height, block_hash: 'GJ2rdQDMGFVsZPn9RYfWo5BibVx8iBFDWvnbvMzaWUfR' } })
+ }
+ if (req.method === 'POST' && url.pathname === '/rpc' && body.method === 'send_tx') {
+ fakeOutlayer.sent.push({ signedTxBase64: body.params.signed_tx_base64 })
+ const hash = createHash('sha256').update(body.params.signed_tx_base64).digest('hex').slice(0, 44)
+ return send(res, 200, { jsonrpc: '2.0', id: body.id, result: { final_execution_status: 'EXECUTED_OPTIMISTIC', status: fakeOutlayer.relayOutcome, transaction: { hash }, transaction_outcome: { id: hash, outcome: { status: { SuccessValue: '' } } }, receipts_outcome: [] } })
+ }
if (req.method === 'POST' && url.pathname === '/rpc') {
const p = body.params
if (p.account_id !== 'outlayer.testnet' || p.method_name !== 'estimate_wallet_policy_cost') return send(res, 200, { jsonrpc: '2.0', id: 1, error: { message: 'unknown view' } })
diff --git a/apps/be/test/relay.test.ts b/apps/be/test/relay.test.ts
new file mode 100644
index 00000000..89489d86
--- /dev/null
+++ b/apps/be/test/relay.test.ts
@@ -0,0 +1,65 @@
+// Relayer checks (src/relay.ts) that need no chain: each refusal with a delegate action built and signed here with a
+// throwaway key, exactly as a wallet would sign it (near-api-js signDelegateAction). Offline.
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { randomBytes } from 'node:crypto'
+import { KeyPair, KeyPairSigner, actions, buildDelegateAction, encodeSignedDelegate } from 'near-api-js'
+
+// The config module wants these at import; nothing here connects to them.
+process.env.DATABASE_URL ??= 'postgresql://unused@127.0.0.1:1/unused'
+process.env.ENGINE_API_KEY ??= 'unused'
+process.env.SECRETS_MASTER_KEY ??= randomBytes(32).toString('base64')
+const { config } = await import('../src/config.ts')
+const { checkDelegate } = await import('../src/relay.ts')
+const { HttpError } = await import('../src/http.ts')
+
+const owner = 'alice.testnet'
+const registry = config.registryContractId
+const kp = KeyPair.fromRandom('ed25519')
+const unequip = (deposit = 1n, gas = 30_000_000_000_000n) => actions.functionCall('unequip_skill', { mind_id: 'mnd_1', skill_id: 'pay' }, gas, deposit)
+
+async function signed(opts: { senderId?: string; receiverId?: string; acts?: ReturnType[]; key?: KeyPair; signWith?: KeyPair } = {}) {
+ const key = opts.key ?? kp
+ const da = buildDelegateAction({ senderId: opts.senderId ?? owner, receiverId: opts.receiverId ?? registry, actions: opts.acts ?? [unequip()], nonce: 7n, maxBlockHeight: 1000n, publicKey: key.getPublicKey() })
+ const signer = new KeyPairSigner(opts.signWith ?? key)
+ // signDelegateAction refuses a key that isn't the signer's own, so a forged signature is spliced in by hand below.
+ const { signedDelegate } = await new KeyPairSigner(key).signDelegateAction(da)
+ if (opts.signWith) {
+ const other = await signer.signDelegateAction(buildDelegateAction({ ...da, publicKey: opts.signWith.getPublicKey() } as never))
+ signedDelegate.signature = other.signedDelegate.signature
+ }
+ return Buffer.from(encodeSignedDelegate(signedDelegate)).toString('base64')
+}
+const refusal = (f: () => unknown) => { try { f() } catch (e) { assert.ok(e instanceof HttpError); return [e.status, e.message] } assert.fail('expected a refusal') }
+
+test('a well-formed unequip_skill with 1 yoctoNEAR, signed by the owner, passes', async () => {
+ const sd = checkDelegate(await signed(), owner)
+ assert.equal(sd.delegateAction.actions[0].functionCall.methodName, 'unequip_skill')
+ assert.equal(sd.delegateAction.nonce, 7n)
+ // set_wallet too, and several allowed calls in one delegate.
+ checkDelegate(await signed({ acts: [actions.functionCall('set_wallet', { mind_id: 'mnd_1', wallet: 'w.testnet' }, 10_000_000_000_000n, 1n), unequip()] }), owner)
+})
+
+test('refuses another receiver, a method off the list, a deposit, too much gas, and non-JSON args', async () => {
+ assert.deepEqual(refusal(checkDelegate.bind(null, await signed({ receiverId: 'wrap.testnet' }), owner)), [400, 'receiver_not_allowed'])
+ assert.deepEqual(refusal(checkDelegate.bind(null, await signed({ acts: [actions.functionCall('equip_skill', { mind_id: 'm', skill_id: 's' }, 30_000_000_000_000n, 0n)] }), owner)), [400, 'method_not_allowed'])
+ assert.deepEqual(refusal(checkDelegate.bind(null, await signed({ acts: [actions.functionCall('register_mind', {}, 30_000_000_000_000n, 10n ** 22n)] }), owner)), [400, 'method_not_allowed'])
+ // The relayer would pay any deposit: only the exact 1 yoctoNEAR the method needs.
+ assert.deepEqual(refusal(checkDelegate.bind(null, await signed({ acts: [unequip(10n ** 24n)] }), owner)), [400, 'deposit_not_allowed'])
+ assert.deepEqual(refusal(checkDelegate.bind(null, await signed({ acts: [unequip(0n)] }), owner)), [400, 'deposit_not_allowed'])
+ assert.deepEqual(refusal(checkDelegate.bind(null, await signed({ acts: [unequip(1n, 300_000_000_000_000n)] }), owner)), [400, 'gas_too_high'])
+ assert.deepEqual(refusal(checkDelegate.bind(null, await signed({ acts: [actions.transfer(1n) as never] }), owner)), [400, 'action_not_allowed'])
+ assert.deepEqual(refusal(checkDelegate.bind(null, await signed({ acts: [unequip(), unequip(), unequip(), unequip(), unequip()] }), owner)), [400, 'too_many_actions'])
+ const raw = actions.functionCall('unequip_skill', new Uint8Array(Buffer.from('not json')) as never, 30_000_000_000_000n, 1n)
+ assert.deepEqual(refusal(checkDelegate.bind(null, await signed({ acts: [raw] }), owner)), [400, 'args_not_json'])
+})
+
+test('refuses another sender, a bad signature, garbage and trailing bytes', async () => {
+ assert.deepEqual(refusal(checkDelegate.bind(null, await signed({ senderId: 'mallory.testnet' }), owner)), [403, 'delegate_sender_mismatch'])
+ assert.deepEqual(refusal(checkDelegate.bind(null, await signed({ signWith: KeyPair.fromRandom('ed25519') }), owner)), [400, 'bad_signature'])
+ assert.deepEqual(refusal(checkDelegate.bind(null, Buffer.from('hello').toString('base64'), owner)), [400, 'invalid_signed_delegate'])
+ assert.deepEqual(refusal(checkDelegate.bind(null, 'not base64!!', owner)), [400, 'invalid_signed_delegate'])
+ const trailing = Buffer.concat([Buffer.from(await signed(), 'base64'), Buffer.from([0])]).toString('base64')
+ assert.deepEqual(refusal(checkDelegate.bind(null, trailing, owner)), [400, 'invalid_signed_delegate'])
+ assert.deepEqual(refusal(checkDelegate.bind(null, await signed({ key: KeyPair.fromRandom('secp256k1') }), owner)), [400, 'unsupported_key_type'])
+})
diff --git a/apps/fe/CLAUDE.md b/apps/fe/CLAUDE.md
index 1219713a..9a479bd2 100644
--- a/apps/fe/CLAUDE.md
+++ b/apps/fe/CLAUDE.md
@@ -127,7 +127,7 @@ Approvals (#14): **no page since 11 Nov** (Axel and Ancung: it repeated the chat
- The live view's "Waiting for you" rows open the chat that asked. Emergency stop and recent payments live in Wallet. Telegram approvals happen in Telegram (#208); its "Open in app" should go to the chat, not the old page.
Wallet (`/minds/[mindId]/wallet`, `src/modules/wallet`, design "5 · Money" W1, W2, W4):
-- `WalletScreen`: balance with the address (copy on click), "Spent today" (OutLayer's own counter `spentTodayNear` when the backend sends it, else the sent payments since 00:00 UTC; the daily cap resets at 00:00 UTC, measured by James on #149, so local midnight read wrong; with a daily cap it reads "of X NEAR"), Recent activity from `GET …/wallet/payments` with All / Sent / Blocked, and "Your limits" beside it. States: normal, empty (Add funds becomes the main button), frozen (banner, Unfreeze), loading, no wallet yet (W1.6, "Set up a wallet"), and a wallet with no limits ("Set limits"). Try-out users and the shared demo wallet only read.
+- `WalletScreen`: balance with the address (copy on click), "Spent today" (OutLayer's own counter `spentTodayNear` when the backend sends it, else the sent payments since 00:00 UTC; the daily cap resets at 00:00 UTC, measured by James on #149, so local midnight read wrong; with a daily cap it reads "of X NEAR"), Recent activity from `GET …/wallet/payments` with All / Sent / Blocked, a **Download CSV** button beside its title once there are payments (a plain link to `GET …/payments.csv`, so the browser downloads it with the session cookie; `FileDownIcon` from lucide), and "Your limits" beside it. States: normal, empty (Add funds becomes the main button), frozen (banner, Unfreeze), loading, no wallet yet (W1.6, "Set up a wallet"), and a wallet with no limits ("Set limits"). Try-out users and the shared demo wallet only read.
- Money coming in isn't in the payments list (it records what the Mind tried to send), so the design's "Added by you" rows don't show; W5 (all activity, payment detail) isn't built yet.
- `LimitsDialog` (W2): per-payment limit, an optional "Per day" cap (#149, `dailyError` in `minds/data/limits.ts`: above 0, at most 100, not below the per-payment limit; empty = none; it starts from the stored cap, because a save without it would remove it) and addresses with the rules from `minds/data/limits.ts`, "Was 2" on a changed limit, "New" on added addresses, a summary of what the Mind may do after saving, then `useSaveLimits`: create the wallet if there is none (409 is fine), `POST …/wallet/policy`, the owner signs `store_wallet_policy` in Meteor (it costs a small deposit), and the wallet is read back until the new limits show.
- `AddFundsDialog` (W4): the owner's Meteor wallet sends a plain `Transfer` to the Mind's address (no backend call), then the balance is read back until it grew. The owner's sendable balance comes from the testnet RPC (`view_account`, `NEAR_RPC_URL` in `src/lib/config.ts`): the balance minus storage at 10^19 yoctoNEAR per byte over the free 770 bytes (docs.near.org, checked 9 Nov). Quick picks are 1, 2, 5 NEAR, not the design's 5, 10, 20, because the faucet gives 5.
diff --git a/apps/fe/src/lib/format.ts b/apps/fe/src/lib/format.ts
index 87e91571..ab49b66b 100644
--- a/apps/fe/src/lib/format.ts
+++ b/apps/fe/src/lib/format.ts
@@ -29,6 +29,19 @@ export function formatNear(amount: string): string {
return `${Number(whole).toLocaleString("en-US")}.${cents}`
}
+/**
+ * A payment amount: two decimals like `formatNear`, but up to four when the cents would hide it, so a
+ * 0.001 NEAR payment reads "0.001", not "0.00" (Axel, 13 Nov: "-0.00 NEAR" on the Wallet screen).
+ * Still rounded down, never up. Balances keep `formatNear`.
+ */
+export function formatNearAmount(amount: string): string {
+ const match = /^(\d+)(?:\.(\d*))?$/.exec(amount.trim())
+ if (!match) return amount
+ const digits = (match[2] ?? "").padEnd(4, "0").slice(0, 4)
+ const shown = digits.slice(2) === "00" ? digits.slice(0, 2) : digits.replace(/0+$/, "")
+ return `${Number(match[1].replace(/^0+(?=\d)/, "")).toLocaleString("en-US")}.${shown}`
+}
+
/** A clock time for chat messages, in the viewer's own format ("10:42"). */
export function clockTime(iso: string): string {
const date = new Date(iso)
diff --git a/apps/fe/src/modules/runs/data/steps.ts b/apps/fe/src/modules/runs/data/steps.ts
index f11ceedd..3459677f 100644
--- a/apps/fe/src/modules/runs/data/steps.ts
+++ b/apps/fe/src/modules/runs/data/steps.ts
@@ -77,6 +77,17 @@ function summary(step: ToolStep): string | null {
const n = `${quotes.length} ${quotes.length === 1 ? "seller" : "sellers"}`
return best?.priceNear ? `${n}, best ${best.priceNear} NEAR` : n
}
+ // Haggling: the seller's answer, and what the Mind does next.
+ case "make_offer":
+ if (!text(r.priceNear)) return null
+ return r.status === "accepted" ? `Accepted at ${r.priceNear} NEAR` : r.next === "walk_away" ? `Countered at ${r.priceNear} NEAR, over budget` : `Countered at ${r.priceNear} NEAR`
+ // Agent Market: how many agents, and one agent's price for the task (USDC, never paid here).
+ case "market_search":
+ return count(r.agents, "agent", "agents")
+ case "market_quote": {
+ const usdc = text((r.price as { usdc?: unknown } | undefined)?.usdc)
+ return usdc ? `${usdc} USDC, not paid` : r.status === "quoted" ? null : "No price right now"
+ }
case "split_amount":
return count(r.shares, "share", "shares")
// A cross-chain preview (#273): what would arrive, where. Kept short to fit a phone's line; the
@@ -89,8 +100,10 @@ function summary(step: ToolStep): string | null {
}
case "near_check_transfer":
return r.coversAmount === true ? "Paid in full" : r.status === "succeeded" ? "Paid, but not the full amount" : r.status === "failed" ? "Not paid" : null
- case "near_view_account":
- return text(r.accountId) ?? text(a.accountId)
+ case "near_view_account": {
+ const id = text(r.accountId) ?? text(a.accountId)
+ return id && r.isContract === true ? `${id}, a contract` : id
+ }
// Google Sheets (#195, #249): which cells, so "Changed cells" says where (Ancung, 11 Nov).
case "googlesheets_find_spreadsheets":
return count(r.spreadsheets, "spreadsheet", "spreadsheets")
diff --git a/apps/fe/src/modules/runs/data/tools.ts b/apps/fe/src/modules/runs/data/tools.ts
index 6b3f0c9c..19a65a94 100644
--- a/apps/fe/src/modules/runs/data/tools.ts
+++ b/apps/fe/src/modules/runs/data/tools.ts
@@ -74,6 +74,11 @@ export const TOOLS: Record = {
add_numbers: { doing: "Adding numbers", done: "Added numbers", orb: "solving", node: "Calculator", about: "Adds numbers exactly instead of guessing." },
// The skills for the five tracks (#194, #211). Reading or looking up: searching.
get_quotes: { doing: "Asking sellers for prices", done: "Compared prices", orb: "searching", node: "Price quotes" },
+ // Haggling (Best price buyer): one offer under the seller's price; it pays nothing.
+ make_offer: { doing: "Making an offer", done: "Made an offer", orb: "working", node: "Offer", about: "Offers a seller less than it asked, once, within your budget. It pays nothing." },
+ // NEAR AI Agent Market: the public catalog, and an agent's price for a task (an unpaid call; nothing is hired).
+ market_search: { doing: "Searching the Agent Market", done: "Searched the Agent Market", orb: "searching", node: "Agent Market", about: "Searches the NEAR AI Agent Market's public catalog. It can only read." },
+ market_quote: { doing: "Asking an agent for a price", done: "Got an agent's price", orb: "searching", node: "Agent price", about: "Asks one Agent Market agent what your task would cost. Nothing is hired or paid." },
near_check_transfer: { doing: "Checking for a payment", done: "Checked for a payment", orb: "searching", node: "Transfer check" },
// A stablecoin payment to another chain, previewed through NEAR Intents (#273): a dry quote, nothing is sent.
crosschain_quote: { doing: "Getting a cross-chain quote", done: "Got a cross-chain quote", orb: "searching", node: "Cross-chain quote", about: "Asks NEAR Intents what a stablecoin payment to another chain would deliver. A preview only: nothing is sent." },
diff --git a/apps/fe/src/modules/skills/data/categories.ts b/apps/fe/src/modules/skills/data/categories.ts
index 57f5ca67..31374d6f 100644
--- a/apps/fe/src/modules/skills/data/categories.ts
+++ b/apps/fe/src/modules/skills/data/categories.ts
@@ -8,7 +8,7 @@ export const CATEGORIES: { id: CategoryId; label: string; skills: string[] }[] =
{
id: "money",
label: "Money",
- skills: ["payments", "best-price", "price-watch", "split-bill", "revenue-split", "invoice", "mind-seller", "paid-data", "subscriptions"],
+ skills: ["payments", "best-price", "agent-market", "price-watch", "split-bill", "revenue-split", "invoice", "mind-seller", "paid-data", "subscriptions"],
},
{
id: "safety",
diff --git a/apps/fe/src/modules/skills/data/icons.tsx b/apps/fe/src/modules/skills/data/icons.tsx
index 8cbf4c72..2bf5d881 100644
--- a/apps/fe/src/modules/skills/data/icons.tsx
+++ b/apps/fe/src/modules/skills/data/icons.tsx
@@ -1,4 +1,4 @@
-import { AtSignIcon, BadgePercentIcon, CalendarX2Icon, ChartPieIcon, ClipboardCheckIcon, EyeOffIcon, FileLockIcon, HeartPulseIcon, LandmarkIcon, MailWarningIcon, ReceiptIcon, ReceiptTextIcon, ReplyIcon, ShieldCheckIcon, SnowflakeIcon, SplitIcon, StoreIcon, TagIcon, CalendarDaysIcon, ChartNoAxesColumnIcon, ClipboardListIcon, PlugIcon, RepeatIcon, SearchIcon, SunriseIcon, WalletIcon, type LucideIcon } from "lucide-react"
+import { AtSignIcon, BadgePercentIcon, CalendarX2Icon, ChartPieIcon, ClipboardCheckIcon, EyeOffIcon, FileLockIcon, HandshakeIcon, HeartPulseIcon, LandmarkIcon, MailWarningIcon, ReceiptIcon, ReceiptTextIcon, ReplyIcon, ShieldCheckIcon, SnowflakeIcon, SplitIcon, StoreIcon, TagIcon, CalendarDaysIcon, ChartNoAxesColumnIcon, ClipboardListIcon, PlugIcon, RepeatIcon, SearchIcon, SunriseIcon, WalletIcon, type LucideIcon } from "lucide-react"
import type { ComponentType } from "react"
import { GmailLogo, GoogleDocsLogo, GoogleSheetsLogo, NotionLogo, OutlookLogo, SlackLogo, ZoomLogo } from "@/components/elements/AppLogos"
@@ -17,6 +17,8 @@ export const SKILL_ICON: Record = {
// Business and agents: paying and getting paid.
"best-price": {
title: "Best price buyer",
- blurb: "Asks every seller of a data report for a price and buys the cheapest one your wallet may pay.",
+ blurb: "Asks every seller of a data report for a price, haggles once if it's over your budget, and buys from one your wallet may pay.",
canUse: (c) => ["Prices from every seller in the data shop", `${c.name}'s wallet, ${limitText(c.limit)}`],
cannot: ["Can't pay a seller off your address list"],
needsWallet: true,
ask: {
why: (c) => `${c.name} will compare sellers before buying a report and show you the prices, then pay the cheapest one you allow after you approve.`,
- does: () => ["Ask every seller for a price", "Show you the comparison", "Pay the cheapest seller on your list, after you approve"],
+ does: () => ["Ask every seller for a price", "Show you the comparison", "Offer less once if the price is over your budget, then buy or walk away", "Pay the seller on your list, after you approve"],
never: () => ["Pay without asking you", "Pay a seller you haven't listed"],
note: approvalNote,
},
added: (c) => `${c.name} can find the cheapest seller now. Ask it in the chat, for example "Buy the gas price report at the best price."`,
removed: (c) => `${c.name} won't compare sellers any more.`,
},
+ // NEAR AI Agent Market (market.near.ai): find an agent for a job and get its exact price. Hiring is
+ // paid in USDC on NEAR mainnet, so during the testnet phase it only quotes (engine/skills/agent-market).
+ "agent-market": {
+ title: "Hire on Agent Market",
+ blurb: "Finds AI agents for a job on the NEAR AI Agent Market and gets the job's exact price. Hiring is paid in mainnet USDC, so it only quotes for now.",
+ canUse: () => ["The Agent Market's public catalog", "A price for the task you write, from the agent itself"],
+ cannot: ["Can't hire or pay during the testnet phase", "Never sends secrets in a task"],
+ ask: {
+ why: (c) => `${c.name} will look for agents that can do a job you describe, show their price and track record, and ask one for the exact price of your task.`,
+ does: () => ["Search the Agent Market", "Show agents with price, jobs done and success rate", "Ask one agent for the price of your task"],
+ never: () => ["Hire or pay anyone", "Put secrets or private data in a task"],
+ note: "No signature needed. Asking for a price starts no work and moves no money.",
+ },
+ added: (c) => `${c.name} can look for agents on the Agent Market now. Ask it in the chat, for example "Find an agent to research coffee shop competitors. What would it cost?"`,
+ removed: (c) => `${c.name} won't look for agents on the Agent Market any more.`,
+ },
"price-watch": {
title: "Price watch",
blurb: "Checks a data report's price and buys it only at or under the limit you set.",
diff --git a/apps/fe/src/modules/wallet/components/WalletScreen.tsx b/apps/fe/src/modules/wallet/components/WalletScreen.tsx
index 14b85697..5686d308 100644
--- a/apps/fe/src/modules/wallet/components/WalletScreen.tsx
+++ b/apps/fe/src/modules/wallet/components/WalletScreen.tsx
@@ -1,7 +1,8 @@
"use client"
-import { CheckIcon, CircleSlashIcon, CopyIcon, HourglassIcon, LockIcon, PlusIcon, SnowflakeIcon, WalletIcon, XIcon } from "lucide-react"
+import { CheckIcon, CircleSlashIcon, CopyIcon, FileDownIcon, HourglassIcon, LockIcon, PlusIcon, SnowflakeIcon, WalletIcon, XIcon } from "lucide-react"
import { useState, type ReactNode } from "react"
+import { toast } from "sonner"
import { cn } from "cn"
import { ErrorRetry } from "@/components/elements/ErrorRetry"
import { EmptyState } from "@/components/elements/EmptyState"
@@ -10,7 +11,8 @@ import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Skeleton } from "@/components/ui/skeleton"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
-import { formatNear } from "@/lib/format"
+import { apiUrl } from "@/lib/api"
+import { formatNear, formatNearAmount } from "@/lib/format"
import { TryOutLockedDialog, useTryOutLock, type LockedAction } from "@/modules/auth/components/TryOutLockedDialog"
import { useIsTryOut } from "@/modules/auth/hooks/useSession"
import type { ApiWallet } from "@/modules/wallet/api"
@@ -178,7 +180,7 @@ function Balance({ mindId, name, wallet }: { mindId: string; name: string; walle
{/* OutLayer's own counter when the backend sends it (#149), else the sent payments since 00:00 UTC. */}
@@ -198,6 +200,21 @@ const TONE = {
waiting: { icon: HourglassIcon, dot: "bg-warning-soft text-warning", badge: "warning" as const, amount: "text-foreground" },
}
+async function downloadCsv(mindId: string) {
+ try {
+ const res = await fetch(apiUrl(`/minds/${encodeURIComponent(mindId)}/payments.csv`), { credentials: "include" })
+ if (!res.ok) throw new Error(res.status === 401 ? "Your session ended. Sign in again to download." : "Could not download the CSV. Try again.")
+ const name = /filename="([^"]+)"/.exec(res.headers.get("content-disposition") ?? "")?.[1] ?? "hellonear-payments.csv"
+ const url = URL.createObjectURL(await res.blob())
+ const a = Object.assign(document.createElement("a"), { href: url, download: name })
+ a.click()
+ URL.revokeObjectURL(url)
+ } catch (e) {
+ // A network failure is a TypeError ("Failed to fetch"); only our own messages are shown as they are.
+ toast.error(e instanceof Error && e.name !== "TypeError" ? e.message : "Could not download the CSV. Try again.")
+ }
+}
+
function Activity({ mindId, name }: { mindId: string; name: string }) {
const { data: payments, isPending, isError } = usePayments(mindId, 50)
const [filter, setFilter] = useState("all")
@@ -205,7 +222,18 @@ function Activity({ mindId, name }: { mindId: string; name: string }) {
return (
-
Recent activity
+
+
Recent activity
+ {/* Every payment as a CSV an accountant can open (GET …/payments.csv). Fetched and saved as a blob,
+ not a plain link: on the hosted site the API is another origin, where browsers ignore `download`,
+ and an expired session would open the JSON error in the tab (Ancung, #297 review). */}
+ {payments?.length ? (
+
+ ) : null}
+
{isPending ? (
) : isError ? (
diff --git a/apps/fe/src/modules/wallet/data/activity.ts b/apps/fe/src/modules/wallet/data/activity.ts
index 903fc22d..3eab9eba 100644
--- a/apps/fe/src/modules/wallet/data/activity.ts
+++ b/apps/fe/src/modules/wallet/data/activity.ts
@@ -2,7 +2,7 @@
// Money coming in isn't in that list (it only records what the Mind tried to send), so
// "Added by you" rows from the design can't show yet. No "·" separators (Ancung, 9 Nov).
-import { clockTime, formatNear, shortWhen } from "@/lib/format"
+import { clockTime, formatNearAmount, shortWhen } from "@/lib/format"
import { compareNear } from "@/lib/near"
import type { ApiPayment } from "@/modules/wallet/api"
@@ -17,7 +17,7 @@ export type ActivityLine = {
}
export function activityLine(p: ApiPayment, now: Date = new Date()): ActivityLine {
- const amount = `${formatNear(p.amountNear)} NEAR`
+ const amount = `${formatNearAmount(p.amountNear)} NEAR`
const when = `${shortWhen(p.at, now)}, ${clockTime(p.at)}`
switch (p.status) {
case "sent":
diff --git a/apps/fe/tests/chat-steps.test.ts b/apps/fe/tests/chat-steps.test.ts
index 5e483473..a7401093 100644
--- a/apps/fe/tests/chat-steps.test.ts
+++ b/apps/fe/tests/chat-steps.test.ts
@@ -129,6 +129,19 @@ describe("step words for the track skills (#211)", () => {
expect(shortAmount("0.004512")).toBe("0.0045")
expect(shortAmount("0.000000")).toBe("0")
})
+
+ it("says what a haggle, an Agent Market search or quote, and a contract lookup came to", async () => {
+ const { stepText } = await import("@/modules/runs/data/steps")
+ const done = (tool: string, result: unknown) => stepText({ toolCallId: "t", tool, status: "ok", args: {}, result })
+ expect(done("make_offer", { status: "accepted", priceNear: "0.0008", next: "buy_at_price" })).toMatchObject({ label: "Made an offer", detail: "Accepted at 0.0008 NEAR" })
+ expect(done("make_offer", { status: "countered", priceNear: "0.0009", next: "buy_at_price" }).detail).toBe("Countered at 0.0009 NEAR")
+ expect(done("make_offer", { status: "countered", priceNear: "0.0012", next: "walk_away" }).detail).toBe("Countered at 0.0012 NEAR, over budget")
+ expect(done("market_search", { query: "research", agents: [{}, {}, {}] })).toMatchObject({ label: "Searched the Agent Market", detail: "3 agents" })
+ expect(done("market_quote", { status: "quoted", price: { usdc: "15", network: "near:mainnet", payTo: "x" } })).toMatchObject({ label: "Got an agent's price", detail: "15 USDC, not paid" })
+ expect(done("market_quote", { status: "unavailable" }).detail).toBe("No price right now")
+ expect(done("near_view_account", { accountId: "hellonear-registry.testnet", isContract: true }).detail).toBe("hellonear-registry.testnet, a contract")
+ expect(done("near_view_account", { accountId: "lin1er.testnet", isContract: false }).detail).toBe("lin1er.testnet")
+ })
})
describe("streamed replies show whole words (11 Nov)", () => {
diff --git a/apps/fe/tests/format.test.ts b/apps/fe/tests/format.test.ts
index 3a128add..1fade12d 100644
--- a/apps/fe/tests/format.test.ts
+++ b/apps/fe/tests/format.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"
-import { formatNear, shortWhen } from "@/lib/format"
+import { formatNear, formatNearAmount, shortWhen } from "@/lib/format"
describe("shortWhen", () => {
const now = new Date(2026, 10, 8, 15, 0) // Sun 8 Nov 2026, 15:00 local
@@ -20,6 +20,20 @@ describe("shortWhen", () => {
})
})
+describe("formatNearAmount", () => {
+ it("shows a small payment instead of 0.00, still rounded down", () => {
+ expect(formatNearAmount("0.001")).toBe("0.001")
+ expect(formatNearAmount("0.0006")).toBe("0.0006")
+ expect(formatNearAmount("0.00012345")).toBe("0.0001")
+ expect(formatNearAmount("0.012")).toBe("0.012")
+ expect(formatNearAmount("1.5")).toBe("1.50")
+ expect(formatNearAmount("0.01")).toBe("0.01")
+ expect(formatNearAmount("1234.56789")).toBe("1,234.5678")
+ expect(formatNearAmount("0")).toBe("0.00")
+ expect(formatNearAmount("0.00001")).toBe("0.00")
+ })
+})
+
describe("formatNear", () => {
it("shows two decimals, rounded down", () => {
expect(formatNear("0.979910726975")).toBe("0.97")
diff --git a/design/brands/agent-market.svg b/design/brands/agent-market.svg
new file mode 100644
index 00000000..688798b4
--- /dev/null
+++ b/design/brands/agent-market.svg
@@ -0,0 +1,16 @@
+
diff --git a/docs/api-contract.md b/docs/api-contract.md
index 3ccdd888..82de4eb3 100644
--- a/docs/api-contract.md
+++ b/docs/api-contract.md
@@ -98,6 +98,13 @@ Several sellers (#176, Best Price Buyer) **[tested, fake OutLayer and RPC; not l
- Intended config once the demo wallet lists both accounts (decided 11 Nov): `SHOP_SELLERS="lin1er.testnet:1.0,testing7.testnet:0.8"`. Not set anywhere yet.
- Engine: `get_quotes` `{ item }` → `{ item, title, quotes, cheapestOnYourList }` (`?quotes=1`); `buy_data` takes an optional `seller` (`?seller=`).
+Negotiation (agents track) **[tested, fake OutLayer and RPC; not live yet]**:
+- Each seller has a floor, a share of its price: `SHOP_SELLERS` entries take an optional third field, `account:multiplier:floor` (0 < floor ≤ 1, up to 3 decimals; e.g. `b.testnet:0.8:0.5`); without it the floor is `0.8`. Stateless: nothing is stored.
+- `?seller=sN&offer=` (no `tx`) → `200` `{ status: "accepted" | "countered", item, title, seller, priceNear, payTo, reason }`. An offer at or above the floor is `accepted` at the offer (never above the list price). One below it is `countered` once, halfway between the offer and the list price but never below the floor; offering that counter is accepted. `reason` is one plain sentence.
+- Paid step `?seller=sN&offer=&tx=`: the payment must reach the agreed price when the offer was accepted, else the list price (an offer under the floor was never agreed). A 402 then names the agreed `priceNear`.
+- `400 invalid_query` for `offer` without `seller` or with `quotes`; `400 invalid_offer` for an amount that is not a positive decimal (`\d{1,3}(\.\d{1,24})?`); `404 unknown_seller`.
+- Engine: `make_offer` → `?seller=&offer=`; `buy_data` with `offerNear` → the same `offer` on the 402 and paid steps.
+
**Cross-chain quote (#273), engine tool `crosschain_quote`, payments skill:** `{ token: "USDC" | "USDT", amount, toChain, recipient, toToken? }` → `{ status: "quote_only", from: { chain: "near", token, amount }, to: { chain, token, recipient, amount, minAmount }, cost, seconds, quoteId, quotedAt, proof: { signedBy1Click, signature, quoteHash, publicKey }, note }`. `proof.signedBy1Click` is 1Click's ed25519 signature over the quote, checked with the official SDK (`verifyQuoteSignature`, 0.1.26); the FE can show it as "Signed by NEAR Intents" with the hash, key and signature behind it. A NEAR Intents 1Click `POST /v0/quote` with `dry: true` (no deposit address, no transaction, no key); the engine reads the Mind's wallet address from `GET /internal/v1/wallet/balance` for `refundTo` only, so no backend change. No approval: nothing moves. NEAR Intents is mainnet only and the wallets are testnet, so this is a preview and the Mind says so **[tested: unit with a fake 1Click and a recorded signed quote; live prompt tests 9/9 on 12 Nov; Chrome e2e on a local stack against the real 1Click, signature verified]**.
**Mind as Seller (#181)** **[tested, fake OutLayer and RPC; not live yet]**. Same 402 pattern, paid to the selling Mind's own wallet. Both routes take `X-Engine-Key` and the calling Mind's run `X-Wallet-Token`.
@@ -426,6 +433,8 @@ One OutLayer wallet per Mind, on testnet. The backend keeps the agent key and ne
| `POST /v1/minds/{mindId}/wallet/policy` | `{ perTransactionNear: "0.05", dailyNear?: "0.3" \| null, whitelist: ["shop.testnet", …] }` | `{ transaction }` for `store_wallet_policy` (100 Tgas, deposit from the contract's `estimate_wallet_policy_cost`; args `wallet_pubkey`, `encrypted_data`, `wallet_signature`, `version`, `locked`, `valid_until`, the last three exactly as `sign-policy` returned them: `version` = stored version + 1, `valid_until` ≈ 7 days, after which the owner must ask for a new transaction). Builds policy v2: per-transaction limit (≤ 10 NEAR), optional daily cap (`rules.limits.daily.native`, ≤ 100 NEAR and not below the per-transaction limit; left out or `null` = none; over it OutLayer answers `403 policy_denied` "Daily limit exceeded…", no tx), whitelist (1–20 accounts), `transfer` only, OutLayer approval off (the app approves), bound to this wallet's key, approver = the owner **[tested; built live on testnet; owner signing not run yet]** |
| `POST /v1/minds/{mindId}/wallet/freeze`, `…/unfreeze` | `{}` | `{ transaction }` for `freeze_wallet` / `unfreeze_wallet` (30 Tgas, no deposit). A frozen wallet's transfers get `403 wallet_frozen` before signing **[tested]** |
| `GET /v1/minds/{mindId}/wallet/payments?limit=20` | | `{ payments }`, the same receipts the engine's `list_payments` reads (Receipts screen) **[tested]** |
+| `GET /v1/minds/{mindId}/payments.csv` | | Every payment of the Mind as a CSV for an accountant (realworld track): `text/csv; charset=utf-8`, UTF-8 with a BOM, CRLF, `Content-Disposition: attachment; filename="hellonear-{mindId}-payments.csv"`. Columns `Date (UTC)` (`YYYY-MM-DD HH:MM:SS`), `Status` in words (`sent`, `pending`, `refused by the wallet policy (no money moved)`, `refused, wallet frozen (no money moved)`, `failed (no money moved)`), `Direction` (`out`), `Amount (NEAR)`, `Counterparty`, `Purpose` (`data report: ` / `bought from another Mind: `, else empty), `Approved by` (`owner` when the run paused on `tool.approval_required` for that call, `your rule` when `tool.called` carries `approvedBy: "rule"`, else empty), `Transaction hash`, `Explorer link` (NearBlocks testnet), `Note` (the stored message). Newest first, up to 10,000 rows. RFC 4180 quoting; a cell starting with `=`, `+`, `-`, `@` gets a leading `'` so spreadsheets don't run it **[tested; load-tested locally with 200 payments per Mind]** |
+| `POST /v1/relay` | `{ signedDelegate }`: base64 of a Borsh `SignedDelegate` (NEP-366, near-api-js `encodeSignedDelegate`) the owner signed | Meta-transaction relayer (realworld track, `src/relay.ts`): the backend's relayer account (`RELAYER_ACCOUNT_ID` / `RELAYER_PRIVATE_KEY`) wraps the delegate in a transaction to the owner and pays the gas. `200` `{ txHash, status: "success" \| "failure", senderId, receiverId, methods, failure? }`. Refused before anything is sent: `403 delegate_sender_mismatch` (sender ≠ the signed-in account), `400` `receiver_not_allowed` (only `REGISTRY_CONTRACT_ID`), `method_not_allowed` (only `unequip_skill`, `set_wallet`), `deposit_not_allowed` (exactly 1 yoctoNEAR: the relayer pays inner deposits, docs.near.org "Meta Transactions"), `action_not_allowed`, `too_many_actions` (> 4), `gas_too_high` (> 30 Tgas a call), `args_too_large`, `args_not_json`, `unsupported_key_type` (ed25519 only), `bad_signature`, `invalid_signed_delegate`, `delegate_expired`, `delegate_ttl_too_long` (> 1000 blocks), `unknown_access_key`, `key_not_full_access`, `stale_nonce`; `429 relay_rate_limited` (10 per owner per hour), `403 demo_not_allowed`, `503 relay_not_configured \| rpc_unreachable \| relay_failed` **[tested: unit + fake RPC; never run on testnet: no relayer account is funded or configured]** |
`transaction` = `{ receiverId: "outlayer.testnet", actions: [{ type: "FunctionCall", params: { methodName, args, gas, deposit } }] }`. OutLayer down → `503 outlayer_unreachable` (`reason`); refusing → `503 outlayer_error` (`outlayerStatus`). Deleting a Mind deletes its wallet row: move the balance out first (a later route will do it).
diff --git a/docs/openapi.json b/docs/openapi.json
index 058faf6a..ddadd226 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -1042,6 +1042,42 @@
]
}
},
+ "/v1/minds/{mindId}/payments.csv": {
+ "get": {
+ "tags": [
+ "Wallet"
+ ],
+ "summary": "Every payment as a CSV an accountant can open",
+ "responses": {
+ "200": {
+ "description": "`text/csv; charset=utf-8` (UTF-8 with a BOM, CRLF), downloaded as `hellonear-{mindId}-payments.csv`. Columns: Date (UTC), Status (in words; refused rows say no money moved), Direction, Amount (NEAR), Counterparty, Purpose (the data report or Mind offer it bought), Approved by (`owner` or `your rule`), Transaction hash, Explorer link (NearBlocks testnet), Note. Newest first, up to 10,000 rows",
+ "content": {
+ "text/csv": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Not signed in"
+ },
+ "404": {
+ "description": "`mind_not_found` (not yours)"
+ }
+ },
+ "parameters": [
+ {
+ "name": "mindId",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ]
+ }
+ },
"/v1/minds/{mindId}/wallet/policy": {
"post": {
"tags": [
@@ -2037,6 +2073,54 @@
}
}
}
+ },
+ "/v1/relay": {
+ "post": {
+ "tags": [
+ "Wallet"
+ ],
+ "summary": "Meta-transaction relayer: HelloNear pays the gas for an owner's signed registry call (NEP-366)",
+ "description": "The owner signs a delegate action in their own NEAR wallet; the relayer wraps it in a transaction and pays the gas. Only for `REGISTRY_CONTRACT_ID`, only `unequip_skill` and `set_wallet` with exactly 1 yoctoNEAR (the relayer would pay any deposit), at most 4 calls of at most 30 Tgas, a full-access key, a nonce above the key's, and an expiry at most 1000 blocks ahead. 10 per owner per hour.",
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "required": [
+ "signedDelegate"
+ ],
+ "properties": {
+ "signedDelegate": {
+ "type": "string",
+ "description": "Base64 of the Borsh-encoded SignedDelegate (near-api-js `encodeSignedDelegate`)"
+ }
+ }
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "`{ txHash, status: \"success\" | \"failure\", senderId, receiverId, methods, failure? }`"
+ },
+ "400": {
+ "description": "`invalid_signed_delegate | receiver_not_allowed | method_not_allowed | deposit_not_allowed | action_not_allowed | too_many_actions | gas_too_high | args_too_large | args_not_json | unsupported_key_type | bad_signature | delegate_expired | delegate_ttl_too_long | unknown_access_key | key_not_full_access | stale_nonce`"
+ },
+ "401": {
+ "description": "Not signed in"
+ },
+ "403": {
+ "description": "`delegate_sender_mismatch` (signed by another account) | `demo_not_allowed`"
+ },
+ "429": {
+ "description": "`relay_rate_limited`"
+ },
+ "503": {
+ "description": "`relay_not_configured | rpc_unreachable | relay_failed`"
+ }
+ }
+ }
}
}
}
\ No newline at end of file
diff --git a/docs/readme/icons/skills/agent-market.svg b/docs/readme/icons/skills/agent-market.svg
new file mode 100644
index 00000000..44b407f6
--- /dev/null
+++ b/docs/readme/icons/skills/agent-market.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/engine/.env.example b/engine/.env.example
index 9be2ba5c..a94ca7ea 100644
--- a/engine/.env.example
+++ b/engine/.env.example
@@ -22,5 +22,8 @@ COMPOSIO_API_KEY=
COMPOSIO_URL=
# Optional, default https://1click.chaindefuser.com: NEAR Intents 1Click API for crosschain_quote (#273, dry quotes only, no key; tests point it at a fake)
ONECLICK_URL=
+# Optional: NEAR AI Agent Market (market_search, market_quote). Defaults: https://market.near.ai and https://{handle}.market.near.ai
+MARKET_URL=
+MARKET_AGENT_URL=
# Optional, default 12000: token budget for the messages of each model call; the oldest are trimmed first (#123)
CONTEXT_TOKEN_LIMIT=
diff --git a/engine/CLAUDE.md b/engine/CLAUDE.md
index 89159724..7bc0cb9c 100644
--- a/engine/CLAUDE.md
+++ b/engine/CLAUDE.md
@@ -36,6 +36,9 @@ AI engine: a Mastra server that runs each Mind (soul, skills, tools, memory, sch
- **Best price buyer (#176, `get_quotes`, skill `best-price`):** `get_quotes` reads the shop's `?quotes=1` (every seller, cheapest first, `onYourList` from the wallet's own policy) and adds `cheapestOnYourList`; `buy_data` takes an optional `seller` id. The skill shows the comparison and buys only the cheapest seller with `onYourList: true`. Sellers come from the backend's `SHOP_SELLERS` (intended `lin1er.testnet:1.0,testing7.testnet:0.8`, not set yet). Never call it NEAR Intents.
- **Price watch (#179, skill `price-watch`):** `get_quotes`, then `add_numbers` (limit minus price) decides; buys through the same `buy_data` + `send_payment` approval only at or under the owner's limit. Autopilot runs drop `send_payment`, so there it only checks and reports. No Builder canvas template exists in the repo yet, so none was added.
- **Cross-chain quote (#273, `crosschain_quote` in `src/crosschain.ts`, skill `payments`):** a stablecoin payment from NEAR to another chain through NEAR Intents, as a **preview only**. NEAR Intents has no testnet and none is planned (docs.near-intents.org FAQ; HACKATHON.md Q-007 suggests `dry: true` quotes), and every wallet here is testnet. So the tool only calls 1Click `POST /v0/quote` with `dry: true` (`ONECLICK_URL`, default `https://1click.chaindefuser.com`, no key: without one 1Click adds its unauthenticated fee to the quote, Q-006). It never gets a deposit address, and nothing can be sent with it. `EXACT_INPUT`, 1% slippage, `ORIGIN_CHAIN` deposit and refund, `DESTINATION_CHAIN` recipient, deadline 10 min. `refundTo` is the Mind's own wallet address (from the backend's balance route; 1Click requires it even dry), so no wallet means "no wallet yet". Asset ids come from `GET /v0/tokens` (cached 10 min; read live 12 Nov: 230 tokens, USDC on 16 chains incl. BNB Chain with 18 decimals, USDT on 13), never typed by hand; chain names map to 1Click's `blockchain` ids (`chainId`). Amounts are converted with BigInt (`toUnits`/`fromUnits`), and `cost` is sent minus received in the token, scaled to the larger decimals. 1Click's refusal text ("recipient is not valid") is passed on. No approval: nothing moves. The playbook line says to use the owner's typed address, show amount, cost and time, say nothing was sent, and never call `send_payment` for it. **Proof (12 Nov):** 1Click signs every quote, dry ones too (docs "Verify Quote Signatures"): ed25519 by its manager key over a base58 SHA-256 of the request and quote fields. The result carries `proof: { signedBy1Click, signature, quoteHash, publicKey }`, checked with the official `verifyQuoteSignature` / `quoteHash` from `@defuse-protocol/one-click-sdk-typescript` **0.1.26, pinned** (it ships the key `ed25519:reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc`). A live quote verified and the same quote with `amountOut` changed did not; `test/fixtures/oneclick-dry-quote.json` is a real signed dry quote for the tests. A quote that does not verify is still returned with `signedBy1Click: false`, and the playbook says the signature could not be checked. Dry quotes are not on chain, so the signature is the only proof (no explorer link). The Mind states the proof unasked, in plain words, and is told never to retype the hash, key or signature: retyping them it dropped characters (the 88-character signature lost three, the hash was missing or wrong in 3 of 6 runs, 12 Nov), so the exact values belong on an FE card from the tool result (#273). The live test fails on any proof-like string in the reply that is not exactly the tool's. It still named `signedBy1Click` once in Chrome, and a Mind that had shown the values in an earlier chat copied that format (correctly, once). Graph node `tool:crosschain_quote`. Live dry quote, 12 Nov: 10 USDC on NEAR → 9.99558 on Base, ~22 s estimate, answered in ~1 s. Tests: `test/crosschain.test.ts` (unit, fake 1Click plus the recorded signed quote), `test/skills-crosschain.test.ts` (live prompts, a 14-skill Payments Mind, fake 1Click: Base answered with the signed fixture, so the reply must say it is signed; Solana USDT unsigned, never called verified; a NEAR payment still gets `send_payment`; 9/9 in 3 runs). With only `payments` equipped the model always called the tool, but a try-out Mind with ~20 skills answered from the blurb alone while it read "(cannot send them yet)"; the blurb now names the quote. Chrome e2e on a local stack with the real 1Click (12 Nov): Base USDC and Solana USDT quotes, and a proof question in English and Indonesian answered with the hash, key and signature. Real sending needs a mainnet wallet and a policy that allows 1Click deposit addresses; not built (mainnet needs Axel's approval).
+- **Haggling (agents track, 13 Nov, `make_offer`, skill `best-price`):** one offer to one seller, within the owner's budget. `make_offer` (item, seller, `offerNear`, `maxNear`; no approval, pays nothing) calls the shop's `GET /internal/v1/shop/{item}?seller=&offer=`, which answers `accepted` or `countered` (its last price). The tool, not the model, compares the answer with `maxNear` in yoctoNEAR and returns `next: buy_at_price | walk_away`; an offer above `maxNear` never reaches the shop. On `walk_away` it marks the request's wallet `Map` (`walked:`) and `buy_data` refuses that item for the rest of the request: in a live test (13 Nov) the model got a counter over the budget and then bought at the original quote anyway. `buy_data` takes `offerNear` and passes it as `offer` on both calls; before paying, the shop answers the same accepted/countered JSON, which `buy_data` turns into `payment_required` at that price (or a refusal). The playbook allows one round, only when the owner gave a budget or asked to haggle. Unit tests in `test/wallet-tools.test.ts`; live prompts in `test/skills-market-negotiation.test.ts` (fake shop).
+- **Agent Market (agents track, 13 Nov, `src/market.ts`, skill `agent-market`, in the General Assistant template):** the NEAR AI Agent Market (market.near.ai) as a **quote only**. `market_search` reads the public catalog (`GET /v1/agents?q=&category=&sort=delivered&limit=`, no auth) and each agent's default plan (`GET /v1/agents/{id}/pricing-plans`, `is_default`, `price_amount` USD per job, paid 1:1 in USDC); rows with a handle that is not a plain DNS label are dropped. `market_quote` sends the owner's task to `https://{handle}.market.near.ai/a2a/v1` as an A2A `SendMessage` **without** `X-PAYMENT`: the market answers HTTP 402 with `accepts[]` (`network` `near:mainnet`, atomic USDC with 6 decimals, `payTo`, `maxTimeoutSeconds` = window + 10 min), starts no task and moves nothing (market.near.ai/skill/x402-caller/SKILL.md, read 12 Nov). JSON-RPC `-32603` → `unavailable`, `-32004` → `not_taking_calls`, 404 → `not_found`, empty `accepts` → `no_payments`. Paying is one NEP-366 signed delegate action moving USDC on NEAR mainnet; every wallet here is testnet, so the result always carries `canPayHere: false` and `NOT_HIRED`. The handle must match `HANDLE` (one DNS label) so it can't point the call elsewhere; a task with `{{secrets.` is refused before any call, and the playbook keeps private data out (the agent's builder reads the task). `MARKET_URL` / `MARKET_AGENT_URL` (a `{handle}` template) are read per call for tests. Recorded live 12 Nov into `test/fixtures/market-*.json`: catalog search for "market research", `infinito-absoluto` quoted 15 USDC with an 86,400 s window, `qadri-research` answered `-32603`. Unit tests `test/market.test.ts`; live prompts `test/skills-market-negotiation.test.ts`.
+- **Contract check in Recipient guard (security track, 13 Nov):** `near_view_account` returns `isContract` and `codeHash` (an account with no code reports `11111111111111111111111111111111`, checked live 13 Nov: `lin1er.testnet` has it, `hellonear-registry.testnet` has `GUxsMNJd…`). The guard warns before paying a contract and states each outcome as allow, warn or block with the reason. It now reads `NEAR_RPC_URL` per call. Live test: `test/skills-wallet.test.ts` (pays `hellonear-registry.testnet`, expects no card).
- **Invoice & get paid (#180, `near_check_transfer`, skill `invoice`):** `list_payments` only lists what the Mind sent and `get_balance` does not say who paid, so "paid" needs `near_check_transfer` (RPC `tx` by hash + sender: success, receiver, NEAR moved). The tool itself sets `toThisMindsWallet` (receiver vs the wallet's own address from `/internal/v1/wallet/balance`) and `coversAmount` (vs the required `amountNear`, in yocto; it was optional and the model once left it out): in a live test (11 Nov) the model read two equal 64-character addresses as different and called a real payment unpaid. It reads `NEAR_RPC_URL` per call. The invoice goes out with `mail_send` (approval), so the `email-address` skill must be on too. The skill has no `send_payment`.
- **Mind as seller (#181, `sell_offer`, `buy_from_mind`, skill `mind-seller`):** `sell_offer` (approval) publishes through `PUT /internal/v1/offers/{item}`, paid into the Mind's own wallet; `buy_from_mind` is the 402 pattern against `GET /internal/v1/minds/{sellerMindId}/offers/{item}`. The buyer's wallet must list the seller's address or the policy refuses the payment before signing. Try-out Minds can neither sell nor be bought from.
- **Email tools (#13, #43, `src/email.ts`):** `gmail_list_emails`, `gmail_read_email`, `gmail_create_draft` (no send tool; drafts only), and `gmail_organize` (#106 step 2: archive or label up to 20 emails in one approval; archive removes `INBOX`, nothing is ever deleted; `GMAIL_CREATE_LABEL` finds or makes the label, then `GMAIL_ADD_LABEL_TO_EMAIL` per email, failures listed; with `demo` it changes nothing and its `note` makes the Mind say so). A run with `demo: true` (judge try-out user) reads `SAMPLE_INBOX`, fictional and fixed, with times relative to now; results carry `source: "sample_inbox"`. Without `demo` they read the run user's own Gmail through Composio (`src/composio.ts`, REST v3.1): one tool-router session per user id (cached 30 min, reopened once on 404), then `execute` of `GMAIL_FETCH_EMAILS` / `GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID` / `GMAIL_CREATE_EMAIL_DRAFT`. The Composio user id is the backend user id (`USER_KEY` in `RequestContext`), so a session only reaches that user's Gmail. No connection (`400 ToolRouterV2_NoActiveConnection`), no user or no `COMPOSIO_API_KEY` → "Gmail is not connected". Never log the session response (it carries MCP connection headers). Owners must never get the sample. The sample keeps one email that tries to instruct the Mind: the `email-triage` playbook must flag it. App tools are named `_` so the Mind Graph maps them to `app:`. `email-triage` is `available`; no catalog skill is `blocked` right now, so tests add a temporary one.
@@ -60,14 +63,14 @@ AI engine: a Mastra server that runs each Mind (soul, skills, tools, memory, sch
- **Memory per persona version (#116, `resourceId` in `src/mind.ts`):** memory is `userId:mindId`, or `userId:mindId:v{n}` once the backend sends `mind.personaVersion` (bumped when the owner changes the name or soul). A renamed Mind once signed with its old name, recalled from resource-scoped memory. Old memory stays in the database but is no longer read; skills or model changes keep the memory.
- **Deleting a chat (#207, `src/threads.ts`, `DELETE /v1/minds/{mindId}/threads/{threadId}` with `{ userId }`):** `forgetThread` checks the thread's resource is the caller's (`ownsResource`: `userId:mindId` or `:v{n}`, else `404`), then `Memory.deleteThread` (from `mindAgent.getMemory()`: a bare `Memory` has no storage until the agent hands it Mastra's) and `await memory.settled()`. `PostgresStore.deleteThread` removes the messages, the `memory_messages*` vector rows (today `mastra.memory_messages_1024`) and the thread in one transaction, so a deleted chat no longer comes back through resource-scoped semantic recall. A missing thread is `204` (the backend retries until `204`). Working memory is per resource and stays. `test/threads.test.ts` writes rows and fake vectors directly (no NEAR AI); its last test embeds through NEAR AI and checks real recall.
- **HelloNear guide and the Mind's own skills (#114):** `skills/hellonear-guide` has `builtin: true`: every Mind loads it (`mindSkills` in `src/skills.ts`), it is left out of `GET /v1/skills`, and it can't be equipped. It holds only what the app really has (screens, buttons, skills, try-out rules, "HelloNear support" messages are phishing); keep it in step with the FE when screens change. Each SKILL.md also has `title` (the Skills screen name) and `blurb` (one line on what it can and cannot do): `skillsLine` in `src/mind.ts` puts the Mind's skills and the ones it could add into its prompt. Without blurbs it once told an owner to add Email helper to send email, which Email helper cannot do.
-- **Memory in Settings (#209, `src/memory.ts`, `GET`/`PUT`/`DELETE /v1/minds/{mindId}/memory`):** the owner reads, replaces and clears the working memory of one resource, `resourceId(userId, mindId, personaVersion)`, the key chat runs use (GET takes `userId` and `personaVersion` as query parameters; PUT `{ userId, personaVersion?, markdown }` (at most 20,000 characters) answers `{ memory: { markdown, updatedAt } }`; DELETE `{ userId, personaVersion? }` answers `204`). Working memory is **free Markdown**: `mastra.ts` sets no `template` or `schema`, so the Mind is only shown Mastra's default template ("# User Information" with bullet fields) and each `updateWorkingMemory` replaces the whole document (docs-memory-working-memory.md in `@mastra/memory`). `updatedAt` is the row's (`mastra.mastra_resources`), one time for the whole document; nothing stamps sections. Clearing writes `''`, which `Memory.getWorkingMemory` reads as none; recall embeddings of past chats stay (deleting a chat drops those, #207). **Switches per run:** `mind.memory: { enabled?, recall? }` (absent = on); `memoryOptions` turns `false` into Mastra per-call `memory.options` (`workingMemory: { enabled: false }`: no document in the prompt, no `updateWorkingMemory` tool; `semanticRecall: false`: no vector search and the run's messages are not embedded, so chats held with recall off are not found later either). Workflow and Autopilot agent steps take no per-call options and keep the defaults. **When the embedder does not answer (13 Nov, `src/embedderHealth.ts`):** NEAR AI's embeddings endpoint hung for over 60 s while chat answered, and every chat run failed in Mastra's prepare-memory-step ("Failed to determine the embedder's output dimension"), the hosted demo too. A probe (one embedding, 8 s timeout, every 30 s, started at boot with `startEmbedderProbe(embedder)`) keeps `embedderReady()`; while it is false, `memoryOptions(mind, false)` adds `semanticRecall: false`, so chat runs still answer, without search of past chats (working memory and the thread's last messages stay). Workflow and Autopilot agent steps still use the defaults and fail while the embedder is down (not fixed). Tests: `test/embedder-health.test.ts`, `test/mind.test.ts`. Tests: `test/mind.test.ts` (unit) and `test/memory.test.ts` (Postgres; the switch tests run the real Memory on Mastra's mock model and check its prompt and tools; one test embeds through NEAR AI).
+- **Memory in Settings (#209, `src/memory.ts`, `GET`/`PUT`/`DELETE /v1/minds/{mindId}/memory`):** the owner reads, replaces and clears the working memory of one resource, `resourceId(userId, mindId, personaVersion)`, the key chat runs use (GET takes `userId` and `personaVersion` as query parameters; PUT `{ userId, personaVersion?, markdown }` (at most 20,000 characters) answers `{ memory: { markdown, updatedAt } }`; DELETE `{ userId, personaVersion? }` answers `204`). Working memory is **free Markdown**: `mastra.ts` sets no `template` or `schema`, so the Mind is only shown Mastra's default template ("# User Information" with bullet fields) and each `updateWorkingMemory` replaces the whole document (docs-memory-working-memory.md in `@mastra/memory`). `updatedAt` is the row's (`mastra.mastra_resources`), one time for the whole document; nothing stamps sections. Clearing writes `''`, which `Memory.getWorkingMemory` reads as none; recall embeddings of past chats stay (deleting a chat drops those, #207). **Switches per run:** `mind.memory: { enabled?, recall? }` (absent = on); `memoryOptions` turns `false` into Mastra per-call `memory.options` (`workingMemory: { enabled: false }`: no document in the prompt, no `updateWorkingMemory` tool; `semanticRecall: false`: no vector search and the run's messages are not embedded, so chats held with recall off are not found later either). Workflow and Autopilot agent steps take no per-call options and keep the defaults. **When the embedder does not answer (13 Nov, `src/embedderHealth.ts`):** NEAR AI's embeddings endpoint hung for over 60 s while chat answered, and every chat run failed in Mastra's prepare-memory-step ("Failed to determine the embedder's output dimension"), the hosted demo too. A probe (one embedding, 8 s timeout, every 30 s, started at boot with `startEmbedderProbe(embedder)`) keeps `embedderReady()`; while it is false, `memoryOptions(mind, false)` adds `semanticRecall: false`, so chat runs still answer, without search of past chats (working memory and the thread's last messages stay). Workflow and Autopilot agent steps still use the defaults and fail while the embedder is down (not fixed). Tests: `test/embedder-health.test.ts`, `test/mind.test.ts` (unit) and `test/memory.test.ts` (Postgres; the switch tests run the real Memory on Mastra's mock model and check its prompt and tools; one test embeds through NEAR AI).
- **Stop (#121, `abortOnClose` in `src/server.ts`):** chat and approve/decline runs pass an `abortSignal` to Mastra that fires when the backend drops the request (its cancel route aborts the fetch). Measured 9 Nov: without it the engine kept writing ~25 s (301 text deltas) after the cut, so the model kept spending tokens; with it, 0. The wallet and mail tools call the backend without that signal, so a payment already sent to OutLayer is never cut halfway. Builder workflow runs are not covered yet.
- **#124 (live Meet test):** `meetLinkOf` takes the first `https://meet.google.com/` URL anywhere in Composio's answer (live, it was not at `response_data.meetingUri`); without one the error lists the field names it saw, never values. With a run `timeZone`, the prompt states the owner's zone and offset (`timeZoneLine`), and the calendar create tools refuse a time whose offset is not the owner's at that moment (`checkOwnerOffset`): "tomorrow 2pm" once became 14:00+00:00. Reply text goes through `plainDashes` (em and en dash → hyphen), because the prompt rule alone still let them through from real calendars; display only, verification covers the model's bytes.
- **Composio tool versions (#124):** the tool router runs each tool's **latest** version, not the default schema `GET /api/v3/tools/{slug}` shows. Always read `?version=latest` before changing tool arguments. On 9 Nov `GOOGLECALENDAR_CREATE_EVENT` latest (`20261103_00`) takes `start_datetime` / `end_datetime` with an offset (end wins over the duration fields) and `send_updates: 'all' | 'externalOnly' | 'none'`; a boolean failed live. `create_meeting_room` now defaults to true there, so it is always sent `false`.
- Emit stream events in the shape agreed in `docs/api-contract.md` (#7); the Mind Graph depends on them.
- In stream chunks, `payload.toolName` is the **key** in the agent's `tools` object, not the tool's `id`. Use the same string for both to avoid mismatches.
- **Skills** live in `skills//SKILL.md` (YAML frontmatter: `name` = folder, `description`, `metadata.hellonear.{tools, connections, status, note?}`). `tools` must be keys of `toolRegistry` in `src/tools.ts`; `status` is `available`, `simulated` (works but fakes a side effect, say how in `note`) or `blocked` (never loaded). The loader fails fast on any mistake. **Shared references:** a skill can list files under `metadata.hellonear.references` (e.g. `[near-recipients.md]`); the loader reads them from `references/` (engine root) and passes them to `createSkill({ references })`. The Mind opens one with `skill_read` (path `references/`) only when its playbook says so, so the text stays out of every prompt (#123) and several skills share it (Payments and NEAR account lookup both use `near-recipients.md`). Write references from live docs and say which page and date; keep them short. Proven 9 Nov in Chrome against a local stack (fake OutLayer with a 0.1 NEAR limit and whitelist): Payments looked up the recipient before the approval card; `lumenhost.testnet` (does not exist) was refused with no card; a 64-character implicit id that was never used made it call `skill_read` for `near-recipients.md`, warn, and ask before paying; an approved 0.01 NEAR to `alice.testnet` came back sent; 0.5 NEAR showed "blocked even if you approve" with no Approve button.
-- **Templates** live in `templates/.json` and may only use skills from the catalog. Keep guardrails (`soul.invariants`) in every template. Each template has a `quote` (≤ 80 characters, the card line in the Mind's own voice) and a character voice in `soul.identity`; money facts (amount, recipient, owner's approval) stay plain, never jokes about refusals or limits (#55). Since 11 Nov each starts with the skills its tracks show (#194): Payments Mind adds recipient-guard, split-bill, treasury-report, spending-audit, best-price, freeze-advisor; Email Manager adds phishing-detector, follow-ups, subscriptions, confidential-reader, calendar-conflicts; General Assistant adds calendar-conflicts, health-journal, redact-before-send (`test/templates.test.ts`). Only Minds made after that get them; existing Minds keep their list.
+- **Templates** live in `templates/.json` and may only use skills from the catalog. Keep guardrails (`soul.invariants`) in every template. Each template has a `quote` (≤ 80 characters, the card line in the Mind's own voice) and a character voice in `soul.identity`; money facts (amount, recipient, owner's approval) stay plain, never jokes about refusals or limits (#55). Since 11 Nov each starts with the skills its tracks show (#194): Payments Mind adds recipient-guard, split-bill, treasury-report, spending-audit, best-price, freeze-advisor; Email Manager adds phishing-detector, follow-ups, subscriptions, confidential-reader, calendar-conflicts; General Assistant adds calendar-conflicts, health-journal, redact-before-send, and agent-market since 13 Nov (`test/templates.test.ts`). Only Minds made after that get them; existing Minds keep their list.
- Never let the backend choose tools: it sends skill ids, the catalog maps them to tools. `GET /v1/skills` publishes the catalog (every skill, its status and tools); keep it the one list the backend validates against. Its items also carry `title` and `blurb`; `GET /v1/skills/{skillId}` returns one equippable skill with `markdown`, the SKILL.md body without frontmatter (`skillDetail` in `src/skills.ts`, 404 for unknown and built-in skills, no references) (#220).
- **Visual Builder (#20, `src/builder.ts`, `src/workflows.ts`):** canvases compile to Mastra dynamic workflows (Beta). Rules from spike 02, keep them: never allow a `requireApproval` tool as a workflow step (Mastra runs it without asking); workflow runs set `UNATTENDED_KEY` so agent steps never see approval tools; never let user text reach a Mastra `${...}` template (templates can read `requestContext`, which holds the secrets), so the compiler only emits templates it built from `{{steps.…}}` / `{{input.…}}`; mappings are top-level only, so condition branches share one mapping. **If ways of several steps (#153):** a way with two or more steps compiles to its own dynamic workflow (`wayWorkflowId`: `--then|else`) referenced from the `conditional` as `{ type: 'workflow' }`; values from before the If reach it through the shared mapping as `_pN` inputs. Children are registered before the parent, kept out of `listWorkflows` (no `metadata.hellonear`), removed when a way shrinks back to one step and deleted with the job; Mastra reloads them on boot (checked after a restart). Its steps stream as `way-.` (the `steps` map has those keys; the way's own entry has `way: true`, is skipped by the normalizer and gives run history the way's final output, the only part Mastra snapshots). `requestContext` reaches the steps inside (spike on #153). One-step ways compile as before. **Ifs anywhere and End (#164, `compileTree` in `src/builder.ts`):** canvases with an `end` node, more than one If, or an If with a plain (no `sourceHandle`) edge compile as a tree; the old shapes keep the old compiler, so saved jobs don't change. Every way and every "after the If" is a nested dynamic workflow (`--.then|else|next`), because a mapping must never read a step that didn't run (spike on #164: `Invalid path … in step b`). Values from earlier on the path reach a nested workflow through its parent's mapping as `pN` inputs, recursively. A nested block that carries on ends with an `out` mapping `{ continues: true, s_: