Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/api-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ 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=`).

**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`.
- `PUT /internal/v1/offers/{item}`: the selling Mind publishes or replaces one offer. `item` = `[a-z0-9][a-z0-9-]{0,39}`. Body (strict) `{ title (≤ 200), priceNear (> 0, ≤ 1), content (≤ 20,000) }` → `200 { sellerMindId, item, title, priceNear, payTo }`, `payTo` = this Mind's own wallet address. `403 demo_not_allowed` for a try-out or playground Mind (the shared demo wallet is nobody's own).
- `GET /internal/v1/minds/{sellerMindId}/offers/{item}[?tx=<hash>]`: the buying Mind. Without `tx`: **`402`** `{ status: "payment_required", sellerMindId, item, title, priceNear, payTo }`. With `tx`: `200 { status: "paid", sellerMindId, item, title, content, receipt: { txHash, paymentId, amountNear, payTo } }` only if the buyer's own `wallet_payments` row has that hash as `sent` to `payTo` for at least the price within the last hour, NEAR RPC `tx` shows success with signer = the buyer's wallet and receiver = the seller's, and the hash was never redeemed (`offer_purchases`). Otherwise `402` with the offer and `error` = `payment_not_found` \| `payment_does_not_match` \| `payment_not_on_chain`, or `409 payment_already_used`. `404 no_offer` (unknown Mind, no such item, or a try-out seller), `400 own_offer`, `400 invalid_tx_hash`.
Expand Down Expand Up @@ -213,7 +215,7 @@ Canvas (React Flow shape; `position` and extra fields are kept for the editor):
```

Rules (the engine answers `400` with `issues` otherwise) **[tested]**:
- Node types: `trigger` (exactly one; optional `inputs` and `schedule`), `agent` (the Mind itself, `{ prompt }`), `tool` (`{ tool, args }`, `tool` = a tool key such as `near_view_account`, `add_numbers`, `get_time`), `http` (the `http_request` tool), `condition` (`left` is one reference, `op` is `eq | ne | lt | lte | gt | gte`, `right` a literal).. An If compares one value, never a list: every tool that returns a list of results also returns `count` (#264: `googlecalendar_list_events` `events`, `googlecalendar_find_free_time` `slots`, `gmail_list_emails` / `outlook_list_emails` `emails`, `mail_list` `messages`, `list_payments` `payments`, `get_quotes` `quotes`, `googlesheets_find_spreadsheets` `spreadsheets`, `googlesheets_read_range` `values`, `googledrive_find_files` `files`, `slack_list_channels` `channels`, `notion_search` `results`, `notion_query_database` `rows`, `zoom_list_meetings` `meetings`), so "Number of events > 0" is `{{steps.<node>.count}}` `gt` `0`; `{{steps.<node>.events.length}}` is refused with `400 invalid_workflow`. An agent step's reply is `{{steps.<node>.text}}`, compared as exact text (`"Yes"` is not `eq` `"yes"`) **[tested: `engine/test/workflows.test.ts` (count on the sample calendar takes the then way, `events.length` refused), 11 Nov; agent `text` saved and run once by hand]**. At most 20 nodes.
- Node types: `trigger` (exactly one; optional `inputs` and `schedule`), `agent` (the Mind itself, `{ prompt }`), `tool` (`{ tool, args }`, `tool` = a tool key such as `near_view_account`, `add_numbers`, `get_time`), `http` (the `http_request` tool), `condition` (`left` is one reference, `op` is `eq | ne | lt | lte | gt | gte`, `right` a literal). An If compares one value, never a list: every tool that returns a list of results also returns `count` (#264: `googlecalendar_list_events` `events`, `googlecalendar_find_free_time` `slots`, `gmail_list_emails` / `outlook_list_emails` `emails`, `mail_list` `messages`, `list_payments` `payments`, `get_quotes` `quotes`, `googlesheets_find_spreadsheets` `spreadsheets`, `googlesheets_read_range` `values`, `googledrive_find_files` `files`, `slack_list_channels` `channels`, `notion_search` `results`, `notion_query_database` `rows`, `zoom_list_meetings` `meetings`), so "Number of events > 0" is `{{steps.<node>.count}}` `gt` `0`; `{{steps.<node>.events.length}}` is refused with `400 invalid_workflow`. An agent step's reply is `{{steps.<node>.text}}`, compared as exact text (`"Yes"` is not `eq` `"yes"`) **[tested: `engine/test/workflows.test.ts` (count on the sample calendar takes the then way, `events.length` refused), 11 Nov; agent `text` saved and run once by hand]**. At most 20 nodes.
- Shape (#164): a tree from the trigger. Nodes are agent/tool/http steps, conditions (If) and `{ type: "end" }`. An If's `then` / `else` edges start its yes / no ways, and its edge **without** `sourceHandle` starts what comes after both ways. A way whose last step has no next step (or an empty way) carries on after its If; a way that reaches an End stops that path. Ifs may sit anywhere: in the main line, inside a way, inside a way of a way. No joins or loops (every node has one way in), End has no next step, and steps after an If whose ways both end are refused. Inside any way, `{{steps.…}}` may name steps earlier on the same path back to the trigger, never another way's. Runs stream `node.*` for every step at any depth, and the run history lists every step that ran, in order **[tested: unit, local engine runs of three paths, an engine restart, a scheduled fire in `test/autopilot.test.ts`, 10 Nov]**.
- Older shape, still accepted as is: trigger → a chain of agent/tool/http nodes → optionally one condition whose `then` edge (required) and `else` edge each lead to a chain of agent/tool/http nodes (#153; no condition inside a way, one next step per node). No cycles, no unreachable nodes. Two **one-step** ways may not need the same input with different values (e.g. two single agent ways); a way of two or more steps has its own mappings, so that limit does not apply to it. Inside a way, `{{steps.…}}` may name earlier steps of the main chain or of the same way, never the other way.
- Runs: steps inside a way stream `node.started` / `node.finished` with their own canvas node ids, like any step. The run history (`GET …/runs`) keeps a multi-step way's **final output only**, under its last node (Mastra does not keep the steps inside a nested workflow in the run snapshot) **[tested: unit, local engine run, a scheduled fire in `test/autopilot.test.ts`, 10 Nov]**.
Expand Down
4 changes: 3 additions & 1 deletion engine/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ PORT=4100
# NEAR network and the Mind registry contract (sc/)
NEAR_NETWORK=testnet
REGISTRY_CONTRACT_ID=hellonear-registry.testnet
# Optional NEAR RPC for read-only lookups, default https://rpc.testnet.near.org
# Optional NEAR RPC for read-only lookups, default https://test.rpc.fastnear.com (rpc.testnet.near.org is deprecated)
NEAR_RPC_URL=
# Optional, default 14: workflow run snapshots and Autopilot fire history older than this many days are pruned hourly
RUN_RETENTION_DAYS=
Expand All @@ -20,5 +20,7 @@ BACKEND_URL=
COMPOSIO_API_KEY=
# Optional, default https://backend.composio.dev/api/v3.1 (tests point it at a fake)
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, default 12000: token budget for the messages of each model call; the oldest are trimmed first (#123)
CONTEXT_TOKEN_LIMIT=
3 changes: 2 additions & 1 deletion engine/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ AI engine: a Mastra server that runs each Mind (soul, skills, tools, memory, sch
- **Wallet skills (skills only, no new tools; prompt tests in `test/skills-wallet.test.ts` with a fake wallet backend):** `recipient-guard` (#182: `near_view_account`, `list_payments`, grants `send_payment` itself; a lookalike of an account paid before, e.g. `b0b.testnet` vs `bob.testnet`, gets a question and no card; the TEE policy stays the real wall), `freeze-advisor` (#185: reads only, points to "Freeze wallet"; no freeze tool exists, by design), `split-bill` (#177) and `revenue-split` (#190: split kept in working memory) send one `send_payment` per person, each with its own approval, `treasury-report` (#189) and `spending-audit` (#184) only read `get_balance` / `list_payments`. Refused payments are visible: the backend stores every attempt and `list_payments` returns `policy_denied` / `wallet_frozen` rows with their `message`. Incoming transfers are not listed by any tool (only the balance shows them), and Autopilot runs get no wallet token, so a scheduled daily or weekly report cannot read the wallet yet; no Builder template was added.
- **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).
- **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 `<app>_<action>` so the Mind Graph maps them to `app:<app>`. `email-triage` is `available`; no catalog skill is `blocked` right now, so tests add a temporary one.
Expand Down Expand Up @@ -93,4 +94,4 @@ The `mastra` skill can report bugs and doc defects to the Mastra team. Never let

## Env

See `.env.example` (`NEARAI_API_KEY`, `DATABASE_URL`, `ENGINE_API_KEY`, optional `PORT`, optional `NEAR_RPC_URL` for `near_view_account`, default `https://rpc.testnet.near.org`, optional `RUN_RETENTION_DAYS`, default 14, `BACKEND_URL` for the payment and mail tools, `COMPOSIO_API_KEY` and optional `COMPOSIO_URL` for Gmail, Google Calendar and Google Meet). `.env` is gitignored; never commit it.
See `.env.example` (`NEARAI_API_KEY`, `DATABASE_URL`, `ENGINE_API_KEY`, optional `PORT`, optional `NEAR_RPC_URL` for `near_view_account` and `near_check_transfer`, default `https://test.rpc.fastnear.com` (since 12 Nov: `rpc.testnet.near.org` is deprecated and answered "THIS ENDPOINT IS DEPRECATED!" on and off, failing 11 tests in one full run), optional `RUN_RETENTION_DAYS`, default 14, `BACKEND_URL` for the payment and mail tools, `COMPOSIO_API_KEY` and optional `COMPOSIO_URL` for Gmail, Google Calendar and Google Meet). `.env` is gitignored; never commit it.
Loading
Loading