diff --git a/agent/core/loop.ts b/agent/core/loop.ts index 0135d8c..c5f88d8 100644 --- a/agent/core/loop.ts +++ b/agent/core/loop.ts @@ -84,6 +84,8 @@ export interface CycleOptions { /** A set of tools the cycle can offer instead of the simulated ones. */ export interface Toolset { specs: readonly ToolSpec[]; + /** The instructions for these tools; without them, the prompt for real money. */ + prompt?: string; /** Runs one call and returns JSON for the model; throws ToolInputError on bad input. */ run(name: string, input: unknown, events: AgentEvent[]): Promise; } @@ -119,7 +121,7 @@ export async function runCycle(options: CycleOptions): Promise { for (let step = 0; step < maxSteps; step++) { if (options.deadline !== undefined && ctx.now() >= options.deadline) return { history, events, report: "", stopReason: "time_limit" }; - const turn = await brain.step(options.tools ? REAL_SYSTEM_PROMPT : SYSTEM_PROMPT, history, options.tools?.specs ?? toolSpecs); + const turn = await brain.step(options.tools ? (options.tools.prompt ?? REAL_SYSTEM_PROMPT) : SYSTEM_PROMPT, history, options.tools?.specs ?? toolSpecs); history.push(turn); if (turn.stop === "end" || turn.toolCalls.length === 0) { return { history, events, report: turn.text, stopReason: "done" }; diff --git a/agent/server/app.ts b/agent/server/app.ts index 4301bdf..7efe2d7 100644 --- a/agent/server/app.ts +++ b/agent/server/app.ts @@ -21,6 +21,7 @@ import type { Dashboard } from "./dashboard.js"; import { LIMITS } from "./config.js"; import { GRANT_DAY_CHOICES, GRANT_DAYS, newGrantRequest, usableGrant, type GrantRecord, type GrantStore } from "./grants.js"; import type { ChainPort } from "./orders.js"; +import { dryRunTools, practiceDashboard, type DryRunDeps, type DryRunRecord } from "./dryRun.js"; import { DailyQuota } from "./quota.js"; import { realTools } from "./realTools.js"; import type { Trading } from "./trading.js"; @@ -50,6 +51,9 @@ export interface AppDeps { agentQuota?: DailyQuota; verifyQuota?: DailyQuota; heldSaleQuota?: DailyQuota; + /** Where dry-run quotes come from; without it, the dry run prices with the live token list. */ + dryRun?: Omit; + dryRunQuota?: DailyQuota; logger?: boolean; } @@ -668,6 +672,63 @@ export async function buildApp(deps: AppDeps): Promise { } }); + // Dry run: open to anyone, no sign-in, no wallet. The tools can only read prices and quotes, so + // nothing here can move money; the caps per IP and per day bound what it costs in model calls. + const dryRunQuota = deps.dryRunQuota ?? new DailyQuota(LIMITS.dryRunsPerIpPerDay, LIMITS.dryRunsPerDayTotal); + const dryRunBusy = new Set(); + const dryRunSource = deps.dryRun ?? { quoteAgent: async () => null, agent: { quote: async () => null } }; + // The practice wallet's dashboard: live prices and the rules every agent signs. No model call. + app.get("/api/dry-run/dashboard", async (req, reply) => { + try { + return practiceDashboard(await deps.tokens(), now()); + } catch (error) { + req.log.error({ err: error instanceof Error ? error.message : "unknown" }, "dry_run_dashboard_failed"); + return reply.code(502).send({ error: "agent_unavailable" }); + } + }); + + app.post("/api/dry-run/chat", { config: { rateLimit: { max: LIMITS.dryRunsPerIpPerMinute, timeWindow: "1 minute" } } }, async (req, reply) => { + const body = chatBody.safeParse(req.body); + if (!body.success) return reply.code(400).send({ error: "bad_request" }); + if (!deps.agentEnabled) return reply.code(503).send({ error: "agent_paused" }); + const client = req.ip; + if (dryRunBusy.has(client)) return reply.code(409).send({ error: "busy" }); + dryRunBusy.add(client); + try { + const allowed = dryRunQuota.take(client); + if (allowed !== "ok") { + req.log.warn({ cap: allowed }, "dry_run_quota_refused"); + return reply.code(429).send({ error: allowed }); + } + const tokens = await deps.tokens(); + const record: DryRunRecord = { log: [], steps: [] }; + const result = await runCycle({ + brain: deps.brain, + goal: body.data.message, + policy: deps.policy(), + portfolio: deps.newPortfolio(tokens), + mode: "execute", + tools: dryRunTools({ ...dryRunSource, tokens: deps.tokens }, record), + maxSteps: LIMITS.dryRunSteps, + deadline: now() + LIMITS.dryRunTimeLimitMs, + }); + req.log.info({ stopReason: result.stopReason, tools: record.log.length }, "dry_run"); + return { + dryRun: true, + report: result.report, + stopReason: result.stopReason, + events: result.events.map(publicEvent), + log: record.log, + steps: record.steps, + }; + } catch (error) { + req.log.error({ err: error instanceof Error ? error.message : "unknown" }, "dry_run_failed"); + return reply.code(502).send({ error: "agent_unavailable" }); + } finally { + dryRunBusy.delete(client); + } + }); + // What the signed-in user's message is doing: its steps while it runs, then the reply POST // /api/chat used to wait for. Only the user's own job is found; it has its own rate limit, since // the app asks every few seconds. diff --git a/agent/server/config.ts b/agent/server/config.ts index 737ef70..0d6c7b3 100644 --- a/agent/server/config.ts +++ b/agent/server/config.ts @@ -69,6 +69,14 @@ export const LIMITS = { chatJobKeepMs: 15 * 60_000, /** Progress reads per IP per minute: the app asks every few seconds while a message runs. */ chatPollsPerIpPerMinute: 120, + /** Dry-run messages, open to anyone without signing in: per IP per minute and per day, and in total per day. */ + dryRunsPerIpPerMinute: 5, + dryRunsPerIpPerDay: 20, + dryRunsPerDayTotal: 300, + /** Model steps one dry-run message may take: the portfolio, a quote or two, and the reply. */ + dryRunSteps: 6, + /** After this long no new step of a dry-run message starts. */ + dryRunTimeLimitMs: 90_000, } as const; const envSchema = z.object({ diff --git a/agent/server/dryRun.test.ts b/agent/server/dryRun.test.ts new file mode 100644 index 0000000..f9599ba --- /dev/null +++ b/agent/server/dryRun.test.ts @@ -0,0 +1,178 @@ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; +import { ScriptedBrain } from "../brains/scripted.js"; +import { demoPolicy, demoPortfolio } from "../core/demo.js"; +import type { PricedToken } from "../core/portfolio.js"; +import type { AgentEvent } from "../core/tools.js"; +import { ASSETS } from "../policy/assets.js"; +import { HELD_ASSETS } from "../policy/heldAssets.js"; +import type { AgentAccounts } from "./agents.js"; +import { buildApp } from "./app.js"; +import { dryRunTools, LOG_LINES, partnerQuoteAgent, QUOTES_PER_MESSAGE, type DryRunRecord } from "./dryRun.js"; +import type { GrantStore } from "./grants.js"; +import { FUNDING_ASSET } from "./orders.js"; +import { DailyQuota } from "./quota.js"; + +const AGENT_ID = "e".repeat(64); +const TOKENS: PricedToken[] = [ + { asset_id: ASSETS.bitcoin.assetId, symbol: "BTC", decimals: 8, blockchain: "btc", price: 100_000 }, + { asset_id: HELD_ASSETS.gold.assetId, symbol: "XAUT", decimals: 6, blockchain: "eth", price: 4000 }, + { asset_id: FUNDING_ASSET, symbol: "wNEAR", decimals: 24, blockchain: "near", price: 2.5 }, +]; + +function setup(agentId: string | null = AGENT_ID) { + const quotes: { agentId: string; from: string; to: string; amount: bigint }[] = []; + const record: DryRunRecord = { log: [], steps: [] }; + const tools = dryRunTools( + { + tokens: () => Promise.resolve(TOKENS), + quoteAgent: () => Promise.resolve(agentId), + agent: { + quote: (id, from, to, amount) => { + quotes.push({ agentId: id, from, to, amount }); + return Promise.resolve({ amountOut: 4945n, minAmountOut: 4895n, costUsd: "0.0065", costPercent: "0.19", seconds: 12 }); + }, + }, + }, + record, + ); + return { tools, record, quotes }; +} + +describe("dry-run tools", () => { + it("offers no tool that moves money", () => { + const { tools } = setup(); + expect(tools.specs.map((s) => s.name)).toEqual(["get_portfolio", "get_quote", "buy_now", "ask_user"]); + }); + + it("refuses the real money tools by name", async () => { + const { tools, quotes } = setup(); + for (const name of ["sell_now", "buy_at_price", "send_near_to_wallet", "transfer"]) { + await expect(tools.run(name, {}, [])).rejects.toThrow("unknown tool"); + } + expect(quotes).toEqual([]); + }); + + it("a buy asks NEAR Intents for a dry quote and shows where the money would go, buying nothing", async () => { + const { tools, record, quotes } = setup(); + const events: AgentEvent[] = []; + const out = JSON.parse(await tools.run("buy_now", { asset: "bitcoin", usd: "5", reason: "asked" }, events)) as Record; + expect(out).toMatchObject({ status: "dry_run", nothing_bought: true, receive: "0.00004945", ends_in: "wallet" }); + // 5 USD at 2.5 USD per NEAR is 2 NEAR. + expect(quotes).toEqual([{ agentId: AGENT_ID, from: FUNDING_ASSET, to: ASSETS.bitcoin.assetId, amount: 2n * 10n ** 24n }]); + expect(record.log[0]?.request?.body).toMatchObject({ dry: "true", amount: (2n * 10n ** 24n).toString() }); + expect(record.steps.map((s) => s.place)).toEqual(["wallet", "agent", "intents", "wallet"]); + expect(events.map((e) => e.type)).toEqual(["swap_proposed"]); + }); + + it("gold ends with the agent, as in the real app", async () => { + const { tools, record } = setup(); + await tools.run("buy_now", { asset: "gold", usd: "5", reason: "asked" }, []); + expect(record.steps.at(-1)?.place).toBe("agent"); + }); + + it("a buy above the practice limit per order is refused before any quote", async () => { + const { tools, quotes } = setup(); + const out = JSON.parse(await tools.run("buy_now", { asset: "bitcoin", usd: "26", reason: "asked" }, [])) as { status: string }; + expect(out.status).toBe("refused"); + expect(quotes).toEqual([]); + }); + + it("asks the trading service for at most a few quotes per message", async () => { + const { tools, quotes } = setup(); + for (let i = 0; i < QUOTES_PER_MESSAGE; i++) await tools.run("get_quote", { asset: "bitcoin", usd: "5" }, []); + await expect(tools.run("get_quote", { asset: "bitcoin", usd: "5" }, [])).rejects.toThrow("at most"); + expect(quotes).toHaveLength(QUOTES_PER_MESSAGE); + }); + + it("stops running tools once the log of one message is full", async () => { + const { tools, record } = setup(); + for (let i = 0; i < LOG_LINES; i++) await tools.run("get_portfolio", {}, []); + await expect(tools.run("get_portfolio", {}, [])).rejects.toThrow("too many steps"); + expect(record.log).toHaveLength(LOG_LINES); + }); + + it("without an agent to ask, it prices with the live token list and says so in the log", async () => { + const { tools, record, quotes } = setup(null); + const out = JSON.parse(await tools.run("get_quote", { asset: "bitcoin", usd: "5" }, [])) as { receive: string }; + expect(out.receive).toBe("0.00005"); + expect(quotes).toEqual([]); + expect(record.log[0]).toMatchObject({ request: null, answer: { source: "live_prices" } }); + }); +}); + +describe("partner quote agent", () => { + it("picks an active agent and never sends the key anywhere but the header", async () => { + const seen: { url: string; key: string | null }[] = []; + const fetcher = ((url: URL, init: RequestInit) => { + seen.push({ url: url.toString(), key: new Headers(init.headers).get("X-API-Key") }); + return Promise.resolve(new Response(JSON.stringify({ data: [{ id: "a".repeat(64), status: "PENDING" }, { id: AGENT_ID, status: "ACTIVE" }] }))); + }) as unknown as typeof fetch; + const find = partnerQuoteAgent("partner-key", "https://agents.example", fetcher); + expect(await find()).toBe(AGENT_ID); + expect(await find()).toBe(AGENT_ID); + expect(seen).toEqual([{ url: "https://agents.example/v1/agents", key: "partner-key" }]); + }); +}); + +describe("POST /api/dry-run/chat", () => { + const fixture = JSON.parse(readFileSync(new URL("../core/fixtures/priced-tokens.json", import.meta.url), "utf8")) as { tokens: PricedToken[] }; + const buyThenReport = () => + new ScriptedBrain([ + () => ({ text: "", stop: "tool_use", toolCalls: [{ id: "1", name: "buy_now", input: { asset: "bitcoin", usd: "5", reason: "asked" } }] }), + () => ({ text: "Dry run: nothing was bought.", stop: "end", toolCalls: [] }), + ]); + const server = (quota?: DailyQuota) => + buildApp({ + verify: () => Promise.reject(new Error("no sign-in here")), + brain: buyThenReport(), + tokens: () => Promise.resolve([...fixture.tokens, ...TOKENS]), + agents: {} as AgentAccounts, + grants: {} as GrantStore, + policy: demoPolicy, + newPortfolio: demoPortfolio, + allowedOrigins: ["https://example.com"], + agentEnabled: true, + trustedProxy: null, + logger: false, + dryRun: { quoteAgent: () => Promise.resolve(AGENT_ID), agent: { quote: () => Promise.resolve({ amountOut: 4945n, minAmountOut: 4895n, costUsd: null, costPercent: null, seconds: null }) } }, + ...(quota ? { dryRunQuota: quota } : {}), + }); + const send = (app: Awaited>, payload: unknown) => + app.inject({ method: "POST", url: "/api/dry-run/chat", headers: { "content-type": "application/json" }, payload: JSON.stringify(payload) }); + + it("answers without signing in, with the log and the steps of the money", async () => { + const res = await send(await server(), { message: "buy 5 dollars of bitcoin" }); + expect(res.statusCode).toBe(200); + const body = res.json<{ dryRun: boolean; report: string; log: unknown[]; steps: unknown[] }>(); + expect(body.dryRun).toBe(true); + expect(body.report).toBe("Dry run: nothing was bought."); + expect(body.log).toHaveLength(1); + expect(body.steps).toHaveLength(4); + expect(res.headers["cache-control"]).toBe("no-store"); + }); + + it("refuses a message past the per-client daily cap", async () => { + const app = await server(new DailyQuota(1, 100)); + expect((await send(app, { message: "hi" })).statusCode).toBe(200); + const second = await send(app, { message: "hi" }); + expect(second.statusCode).toBe(429); + expect(second.json()).toEqual({ error: "user_limit" }); + }); + + it("shows the practice dashboard without signing in: live prices and the rules every agent signs", async () => { + const res = await (await server()).inject({ method: "GET", url: "/api/dry-run/dashboard" }); + expect(res.statusCode).toBe(200); + const body = res.json<{ prices: Record; agent: { account: string; policy: { sendsOnlyToOwner: boolean; canBuyNow: boolean; destinations: string[] }; held: unknown[] } }>(); + expect(body.prices.bitcoin).toBe(100_000); + expect(body.agent.account).toBe("practice-agent"); + expect(body.agent.policy).toMatchObject({ sendsOnlyToOwner: true, canBuyNow: true, destinations: ["0".repeat(64)] }); + expect(body.agent.held).toEqual([]); + }); + + it("refuses unknown fields and messages that are too long", async () => { + const app = await server(); + expect((await send(app, { message: "hi", tools: ["sell_now"] })).statusCode).toBe(400); + expect((await send(app, { message: "x".repeat(1001) })).statusCode).toBe(400); + }); +}); diff --git a/agent/server/dryRun.ts b/agent/server/dryRun.ts new file mode 100644 index 0000000..9ef534d --- /dev/null +++ b/agent/server/dryRun.ts @@ -0,0 +1,269 @@ +import { z } from "zod"; +import type { Toolset } from "../core/loop.js"; +import { priceToMicro, usdStringToMicro } from "../core/money.js"; +import type { PricedToken } from "../core/portfolio.js"; +import { ToolInputError, type AgentEvent } from "../core/tools.js"; +import { fromAtomic } from "../policy/units.js"; +import { ASSET_KEYS, ASSETS } from "../policy/assets.js"; +import { HELD_ASSETS, HELD_KEYS, tradable, TRADABLE_KEYS, type TradableKey } from "../policy/heldAssets.js"; +import { FUNDING_ASSET, staysOnAgent, type AgentPort, type SwapQuote } from "./orders.js"; +import { quoteView, usdToWnear } from "./realTools.js"; +import { agentPolicy } from "../policy/agentPolicy.js"; +import { summarizePolicy, type DashboardView } from "./dashboard.js"; +import { GRANT_DAYS } from "./grants.js"; + +/** + * Dry run: anyone can try Inti without an account or funds. The agent works on a practice wallet + * and asks NEAR Intents for real quotes, but it has no tool that moves money: buying shows what a + * real purchase would do, step by step, and buys nothing. + */ + +/** The practice wallet: NEAR worth this many dollars, set aside for orders. */ +export const PRACTICE_USD = "100"; +/** The practice limits, the same kind the owner signs in Spending Limits. */ +export const PRACTICE_PER_ORDER_USD = "25"; +export const PRACTICE_PER_DAY_USD = "50"; +const MIN_ORDER_USD = "0.10"; +/** Quotes one dry-run message may ask the trading service for. */ +export const QUOTES_PER_MESSAGE = 4; +/** Lines of the log one reply carries. */ +export const LOG_LINES = 12; + +/** One line of the dry run's log: what the agent asked for and what came back. Built by code only. */ +export interface DryRunLogEntry { + tool: string; + asked: Record; + /** The request sent to the NEAR Intents Agent API, or null when none was sent. */ + request: { route: string; body: Record } | null; + answer: Record; +} + +/** Where the money would sit at one step of a real purchase. */ +export interface FundStep { + place: "wallet" | "agent" | "intents"; + text: string; +} + +export interface DryRunRecord { + log: DryRunLogEntry[]; + steps: FundStep[]; +} + +export interface DryRunDeps { + tokens: () => Promise; + /** A live agent of this server, used only to ask for quotes; null when there is none. */ + quoteAgent: () => Promise; + agent: Pick; +} + +const usd = z + .string() + .regex(/^\d{1,4}(\.\d{1,2})?$/) + .describe('Amount in US dollars, e.g. "5" or "2.50"'); +const asset = z.enum(TRADABLE_KEYS).describe("Which asset, by its key from get_portfolio"); + +const inputs = { + get_portfolio: z.strictObject({}), + get_quote: z.strictObject({ asset, usd }), + buy_now: z.strictObject({ asset, usd, reason: z.string().min(1).max(300).describe("One sentence: why this order serves the request") }), + ask_user: z.strictObject({ question: z.string().min(1).max(500) }), +}; +type ToolName = keyof typeof inputs; + +const descriptions: Record = { + get_portfolio: + "The practice wallet: the NEAR set aside for orders and its value, the practice limits, and each asset Inti trades with its live price.", + get_quote: + "What buying an asset now for an amount in US dollars would cost, without buying: the NEAR it takes, what the owner would receive and its value, and the cost of the trade.", + buy_now: + "Show what buying an asset now for an amount in US dollars would do, step by step, with a live quote. This is a dry run: nothing is bought and no money moves.", + ask_user: "Ask the owner a question when the request is unclear. Ends the cycle.", +}; + +export const dryRunToolSpecs = (Object.keys(inputs) as ToolName[]).map((name) => { + const schema = { ...(z.toJSONSchema(inputs[name]) as Record) }; + delete schema.$schema; + return { name, description: descriptions[name], inputSchema: schema }; +}); + +export const DRY_RUN_PROMPT = `You are Inti, a portfolio assistant on NEAR that buys assets through NEAR Intents. Right now the person is trying Inti in a dry run: they have a practice wallet with NEAR worth ${PRACTICE_USD} US dollars set aside for orders, the prices and quotes are live, and nothing is ever bought or moved. + +Never give investment advice or predictions, never promise returns, and stay on the portfolio: if asked about something else, say briefly that you help with their portfolio. + +Language: every text you write is in the language of the person's message. Decide it from their words only, never from these instructions or the tool results. + +How you work: +- Call get_portfolio before any decision. +- For a question about price, cost or fees, call get_quote and answer with its numbers. +- For a request to buy, call buy_now. It returns a live quote and the steps a real purchase would take. Say plainly that this was a dry run and nothing was bought, then what they would receive and the cost of the trade. +- Selling, price orders and sending money are not part of the dry run: say they work in the real app once the wallet is activated. +- The code checks every order against the practice limits and refuses what does not fit. If an order is refused, say why in plain words. +- Ask only when the request is unclear (which asset, how much). +- Every number you give comes from a tool result. Call the cost "the cost of the trade", never a fee or commission. + +Your reply: 1 to 3 short plain sentences, no headings, tables, lists or bold.`; + +const route = "POST /v1/agents/{agent_id}/swap"; +const swapBody = (to: string, wnear: bigint): Record => ({ origin_asset: FUNDING_ASSET, destination_asset: to, amount: wnear.toString(), dry: "true" }); + +/** A quote's numbers for the log, never anything else the service sent. */ +const answerOf = (q: SwapQuote): Record => ({ + amount_out: q.amountOut.toString(), + min_amount_out: q.minAmountOut.toString(), + ...(q.costUsd === null ? {} : { cost_usd: q.costUsd }), + ...(q.costPercent === null ? {} : { cost_percent: q.costPercent }), + ...(q.seconds === null ? {} : { seconds: String(q.seconds) }), +}); + +/** The tools of one dry-run message; every call is written to `record` for the app to show. */ +export function dryRunTools(deps: DryRunDeps, record: DryRunRecord): Toolset & { prompt: string } { + const prices = async () => { + const list = await deps.tokens(); + const byId = new Map(list.map((t) => [t.asset_id, t])); + const near = byId.get(FUNDING_ASSET); + if (!near?.price) throw new ToolInputError("no fresh NEAR price, try later"); + return { byId, nearMicro: priceToMicro(near.price) }; + }; + + let quotesLeft = QUOTES_PER_MESSAGE; + + /** A live quote for `wnear` of NEAR into `to`: from NEAR Intents, or from live prices when no agent can quote. */ + const quote = async (tool: string, asked: Record, to: string, wnear: bigint, token: PricedToken, nearMicro: bigint) => { + // A few quotes answer any one message; more would only spend the trading service's calls. + if (quotesLeft <= 0) throw new ToolInputError(`at most ${QUOTES_PER_MESSAGE} quotes per message in the dry run; answer with the ones you have`); + quotesLeft -= 1; + const agentId = await deps.quoteAgent(); + if (agentId !== null) { + const q = await deps.agent.quote(agentId, FUNDING_ASSET, to, wnear); + record.log.push({ tool, asked, request: { route, body: swapBody(to, wnear) }, answer: q ? answerOf(q) : { status: "no_route" } }); + return q; + } + // No agent to ask: the same math on the live token prices, with no cost known. + const out = (wnear * nearMicro * 10n ** BigInt(token.decimals)) / (priceToMicro(token.price ?? 0) * 10n ** 24n); + const q: SwapQuote = { amountOut: out, minAmountOut: out, costUsd: null, costPercent: null, seconds: null }; + record.log.push({ tool, asked, request: null, answer: { source: "live_prices", amount_out: out.toString() } }); + return q; + }; + + const order = async (key: TradableKey, amountUsd: string) => { + const micro = usdStringToMicro(amountUsd); + if (micro < usdStringToMicro(MIN_ORDER_USD)) throw new ToolInputError(`amount must be at least ${MIN_ORDER_USD} USD`); + const a = tradable(key); + const { byId, nearMicro } = await prices(); + const token = byId.get(a.assetId); + return { a, token: token?.price ? token : null, nearMicro, wnear: usdToWnear(amountUsd, nearMicro) }; + }; + + return { + specs: dryRunToolSpecs, + prompt: DRY_RUN_PROMPT, + async run(name, rawInput, events: AgentEvent[]) { + // Bounds the tool calls of one message, however many the model asks for in a turn. + if (record.log.length >= LOG_LINES) throw new ToolInputError("too many steps for one message; answer with what you have"); + if (!(name in inputs)) throw new ToolInputError(`unknown tool: ${name}`); + const parsed = inputs[name as ToolName].safeParse(rawInput); + if (!parsed.success) throw new ToolInputError(`invalid input: ${parsed.error.message}`); + + switch (name as ToolName) { + case "get_portfolio": { + const { byId, nearMicro } = await prices(); + const wnear = usdToWnear(PRACTICE_USD, nearMicro); + // Six decimals, as the app shows NEAR. + const nearShown = fromAtomic((wnear / 10n ** 18n).toString(), 6); + const priced = (assetId: string) => byId.get(assetId)?.price ?? null; + record.log.push({ tool: name, asked: {}, request: null, answer: { practice_usd: PRACTICE_USD, near_for_orders: nearShown } }); + return JSON.stringify({ + dry_run: true, + paid_with: "NEAR", + near_for_orders: nearShown, + money_for_orders_usd: PRACTICE_USD, + limits: { per_order_usd: PRACTICE_PER_ORDER_USD, per_day_usd: PRACTICE_PER_DAY_USD }, + assets: ASSET_KEYS.map((key) => ({ key, name: ASSETS[key].name, symbol: ASSETS[key].symbol, price_usd: priced(ASSETS[key].assetId), goes_to: "wallet" })), + held_by_agent: HELD_KEYS.map((key) => ({ key, name: HELD_ASSETS[key].name, symbol: HELD_ASSETS[key].symbol, price_usd: priced(HELD_ASSETS[key].assetId), goes_to: "agent" })), + }); + } + case "get_quote": + case "buy_now": { + const input = parsed.data as z.infer; + const asked = { asset: input.asset, usd: input.usd }; + const { a, token, nearMicro, wnear } = await order(input.asset as TradableKey, input.usd); + if (!token) return JSON.stringify({ status: "refused", reason: "there is no fresh price for this asset right now" }); + if (name === "buy_now" && usdStringToMicro(input.usd) > usdStringToMicro(PRACTICE_PER_ORDER_USD)) { + record.log.push({ tool: name, asked, request: null, answer: { status: "refused", code: "over_order_limit" } }); + events.push({ type: "swap_denied", from: "NEAR", amountIn: input.usd, code: "over_order_limit", reason: "above the practice limit per order" }); + return JSON.stringify({ status: "refused", reason: `the amount is above the practice limit of ${PRACTICE_PER_ORDER_USD} USD per order` }); + } + const q = await quote(name, asked, a.assetId, wnear, token, nearMicro); + if (!q) return JSON.stringify({ status: "refused", reason: "there is no way to trade this right now, often because the amount is too small for this asset's market" }); + const view = quoteView(input.usd, wnear, q, token.decimals, priceToMicro(token.price ?? 0)); + if (name === "get_quote") return JSON.stringify({ status: "quoted", asset: a.name, ...view }); + const kept = staysOnAgent(a.assetId); + record.steps = [ + { place: "wallet", text: `${view.pay_near} NEAR (${input.usd} USD) waits in your wallet, set aside for orders. Your Spending Limits contract caps each order and each day.` }, + { place: "agent", text: `Inti's limited key sends those ${view.pay_near} NEAR to your own agent on NEAR Intents, into its private balance.` }, + { place: "intents", text: `Your agent swaps them on NEAR Intents for about ${view.receive} ${a.symbol}, and never accepts less than ${view.receive_at_least}.` }, + kept + ? { place: "agent", text: `${a.symbol} stays with your agent, in its private balance, ready to sell back anytime.` } + : { place: "wallet", text: `The ${a.symbol} goes straight back to your wallet. The agent keeps nothing.` }, + ]; + events.push({ type: "swap_proposed", from: "NEAR", to: a.symbol, amountIn: input.usd, amountOut: view.receive, usd: input.usd, reason: input.reason }); + return JSON.stringify({ status: "dry_run", nothing_bought: true, asset: a.name, ...view, ends_in: kept ? "agent" : "wallet" }); + } + case "ask_user": { + const input = parsed.data as z.infer; + record.log.push({ tool: name, asked: {}, request: null, answer: { status: "asked" } }); + events.push({ type: "question", text: input.question }); + return JSON.stringify({ status: "sent", note: "End your turn now." }); + } + } + }, + }; +} + +const agentListSchema = z.object({ data: z.array(z.object({ id: z.string().regex(/^[0-9a-f]{64}$/), status: z.string().max(32) })).max(1000) }); + +/** + * Finds one active agent of this server's partner account to ask for dry quotes, and remembers it + * for a while. A dry quote moves nothing, whatever the agent holds. + */ +export function partnerQuoteAgent(apiKey: string, baseUrl: string, fetcher: typeof fetch = fetch, now: () => number = Date.now, keepMs = 10 * 60_000) { + let cached: { at: number; id: string | null } | null = null; + return async (): Promise => { + if (cached && now() - cached.at < keepMs) return cached.id; + try { + const res = await fetcher(new URL("/v1/agents", baseUrl), { headers: { "X-API-Key": apiKey }, signal: AbortSignal.timeout(15_000) }); + if (!res.ok) return null; + const list = agentListSchema.parse(await res.json()); + cached = { at: now(), id: list.data.find((a) => a.status === "ACTIVE")?.id ?? null }; + return cached.id; + } catch { + return null; + } + }; +} + +/** The practice wallet's account, shown on the page; it is not a real account and holds nothing. */ +export const PRACTICE_OWNER = "0".repeat(64); +/** The practice agent's account, shown on the page. */ +export const PRACTICE_AGENT = "practice-agent"; + +/** + * The dashboard of the practice wallet: live prices, and the rules every real agent signs, summarized + * by the same code as a real user's. Nothing here is read from any real account. + */ +export function practiceDashboard(tokens: readonly PricedToken[], now: number): DashboardView { + const priceOf = (assetId: string) => tokens.find((t) => t.asset_id === assetId)?.price ?? null; + const prices = { near: priceOf(FUNDING_ASSET), ...Object.fromEntries(TRADABLE_KEYS.map((k) => [k, priceOf(tradable(k).assetId)])) } as DashboardView["prices"]; + const policy = summarizePolicy({ policy: agentPolicy(PRACTICE_OWNER), cooldowns: null }, PRACTICE_OWNER, now); + return { + prices, + agent: { + account: PRACTICE_AGENT, + grantUntil: new Date(now + GRANT_DAYS * 86_400_000).toISOString(), + policy, + orders: [], + held: [], + cash: "0", + }, + }; +} diff --git a/agent/server/index.ts b/agent/server/index.ts index 973b919..25898a2 100644 --- a/agent/server/index.ts +++ b/agent/server/index.ts @@ -11,6 +11,7 @@ import { demoPolicy, demoPortfolio, fetchTokens } from "../core/demo.js"; import type { PricedToken } from "../core/portfolio.js"; import { agentApiAccounts } from "./agents.js"; import { buildApp } from "./app.js"; +import { partnerQuoteAgent } from "./dryRun.js"; import { agentApiView, dashboard } from "./dashboard.js"; import { privyVerifier } from "./auth.js"; import { LIMITS, loadConfig } from "./config.js"; @@ -34,7 +35,8 @@ async function main(): Promise { const chain = nearChain(config.nearRpcUrl, await loadIntiKey(config.intiKeyFile, config.intiPublicKey)); // Next to the grants, so it lives wherever the server already keeps its state. const spendLog = await fileSpendLog(join(dirname(config.grantFile), "agent-spend.json")); - const orders = trading({ agents, grants, chain, agent: agentApiPort(config.agentApiKey, config.agentApiUrl), tokens, spendLog }); + const agentPort = agentApiPort(config.agentApiKey, config.agentApiUrl); + const orders = trading({ agents, grants, chain, agent: agentPort, tokens, spendLog }); // What an agent holds goes back to its owner's wallet: at start, then every few minutes. let sweeping = false; @@ -68,6 +70,7 @@ async function main(): Promise { proveReply(model, calls, { fetch, apiKey: config.nearAiApiKey, attestedKey, wait: (ms) => new Promise((r) => setTimeout(r, ms)), now: Date.now }), policy: demoPolicy, newPortfolio: demoPortfolio, + dryRun: { quoteAgent: partnerQuoteAgent(config.agentApiKey, config.agentApiUrl), agent: agentPort }, allowedOrigins: config.allowedOrigins, agentEnabled: config.agentEnabled, trustedProxy: config.trustedProxy, diff --git a/web/src/dashboard/Dashboard.tsx b/web/src/dashboard/Dashboard.tsx index 7c47975..9d29187 100644 --- a/web/src/dashboard/Dashboard.tsx +++ b/web/src/dashboard/Dashboard.tsx @@ -110,6 +110,7 @@ function useDashboard( getAccessToken: () => Promise, grantSigned: boolean, refreshKey: number, + readDashboard?: () => Promise, ): DashboardState { const [data, setData] = useState(null); const [assets, setAssets] = useState(null); @@ -127,8 +128,11 @@ function useDashboard( async (quiet = false) => { if (!quiet) setLoading(true); try { - const token = await getAccessToken(); - const [server, rows] = await Promise.all([token ? fetchDashboard(token) : Promise.resolve(null), client.assets(address).catch(() => null)]); + const readServer = readDashboard ?? (async () => { + const token = await getAccessToken(); + return token ? fetchDashboard(token) : null; + }); + const [server, rows] = await Promise.all([readServer(), client.assets(address).catch(() => null)]); // A failed read keeps what is already on screen instead of blanking it. if (server) setData(server); if (rows) setAssets(rows); @@ -136,7 +140,7 @@ function useDashboard( if (!quiet) setLoading(false); } }, - [address, client, getAccessToken], + [address, client, getAccessToken, readDashboard], ); // Read again only when the account's balances, limits or Inti's permission really changed, not on @@ -168,11 +172,13 @@ interface MoneyProps { * holds together; on a phone each has its own tab: "walletAssets" and "agent". */ part: "wallet" | "assets" | "both" | "walletAssets" | "agent"; + /** The dry run's practice wallet: its address takes no deposits, so Receive shows no QR code. */ + practice?: boolean; className?: string; } /** The user's money: the wallet and the assets Inti can buy, each enabled from its own tile. */ -export function MoneyPanel({ address, config, client, status, state, onManage, onChanged, getAccessToken, part, className }: MoneyProps) { +export function MoneyPanel({ address, config, client, status, state, onManage, onChanged, getAccessToken, part, practice = false, className }: MoneyProps) { const { signer, confirmDialog } = useOwnerSigner(address, config); const { data, assets, loading, load } = state; const { hidden, toggleHidden } = useHideAmounts("money"); @@ -293,7 +299,7 @@ export function MoneyPanel({ address, config, client, status, state, onManage, o
- + ))} +
+ + + {note && ( +

+ {note} +

+ )} + +
+ +
+
+ + {empty && ( + <> +

Try Inti with no funds

+

+ A practice wallet with $100 in NEAR. Prices and quotes are live from NEAR Intents. Nothing is bought and no money moves. +

+
    + {SUGGESTIONS.map((s) => ( +
  • + +
  • + ))} +
+ + )} +
+ + {!empty && ( +
    + {messages.map((m, i) => ( + 0 || (m.log?.length ?? 0) > 0) ? ( + <> + Dry run, no real funds moved + {m.steps && m.steps.length > 0 && } + {m.log && m.log.length > 0 && } + + ) : undefined + } + /> + ))} + {thinking && } +
+ )} + +
+ void send(text)} placeholder="e.g. buy $5 of bitcoin" disabled={thinking} /> +
+
+
+
+ + ); +} + +const appId = import.meta.env.PRIVY_APP_ID as string | undefined; + +/** + * The dry run page. The portfolio panels are the app's own, which expect the sign-in provider, so + * it is loaded; nobody signs in here, so there is no wallet and nothing that could sign. + */ +export function DryRunRoot() { + return ( + + {(theme) => + appId ? ( + + + + ) : ( + + ) + } + + ); +} diff --git a/web/src/dryrun/client.ts b/web/src/dryrun/client.ts new file mode 100644 index 0000000..2f795b9 --- /dev/null +++ b/web/src/dryrun/client.ts @@ -0,0 +1,84 @@ +import type { DashboardData } from "../dashboard/dashboardClient"; +/** Public URL of Inti's agent API (INTI_API_URL in the root .env). Not a secret. */ +const API_URL = (import.meta.env as Record).INTI_API_URL; + +export interface DryRunLogEntry { + tool: string; + asked: Record; + request: { route: string; body: Record } | null; + answer: Record; +} + +export interface FundStep { + place: "wallet" | "agent" | "intents"; + text: string; +} + +export interface DryRunReply { + report: string; + log: DryRunLogEntry[]; + steps: FundStep[]; +} + +const MESSAGES: Record = { + user_limit: "You reached today's limit of dry-run messages. Open the app to keep going.", + server_limit: "The dry run is very busy today. Try again tomorrow, or open the app.", + rate_limited: "Too many messages in a minute. Wait a moment and retry.", + busy: "I'm still working on your last message.", + agent_paused: "Inti is paused for maintenance. Try again later.", + agent_unavailable: "I couldn't reach my tools right now. Try again in a minute.", +}; +const GENERIC = "Something went wrong. Try again in a minute."; + +export class DryRunError extends Error {} + +const record = (value: unknown): value is Record => + typeof value === "object" && value !== null && Object.values(value).every((v) => typeof v === "string"); + +/** Sends one message to the dry run. No sign-in: nothing here can move money. */ +export async function askDryRun(message: string): Promise { + if (!API_URL) throw new DryRunError("Inti's server is not configured yet."); + let res: Response; + try { + res = await fetch(new URL("/api/dry-run/chat", API_URL), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ message }), + signal: AbortSignal.timeout(120_000), + }); + } catch { + throw new DryRunError("I couldn't reach Inti's server. Check your connection and retry."); + } + const body = (await res.json().catch(() => ({}))) as Record; + if (!res.ok) throw new DryRunError(MESSAGES[typeof body.error === "string" ? body.error : ""] ?? GENERIC); + // Only the fields the page shows, each checked: text that is not a string is dropped. + const log = Array.isArray(body.log) + ? body.log.flatMap((e: unknown): DryRunLogEntry[] => { + const entry = e as Record; + if (typeof entry.tool !== "string" || !record(entry.asked) || !record(entry.answer)) return []; + const req = entry.request as { route?: unknown; body?: unknown } | null; + const request = req && typeof req.route === "string" && record(req.body) ? { route: req.route, body: req.body } : null; + return [{ tool: entry.tool, asked: entry.asked, request, answer: entry.answer }]; + }) + : []; + const steps = Array.isArray(body.steps) + ? body.steps.flatMap((s: unknown): FundStep[] => { + const step = s as Record; + return (step.place === "wallet" || step.place === "agent" || step.place === "intents") && typeof step.text === "string" ? [{ place: step.place, text: step.text }] : []; + }) + : []; + return { report: typeof body.report === "string" ? body.report : "", log, steps }; +} + +/** The practice wallet's dashboard: live prices and the rules every agent signs. Null when it cannot be read. */ +export async function fetchPracticeDashboard(): Promise { + if (!API_URL) return null; + try { + const res = await fetch(new URL("/api/dry-run/dashboard", API_URL), { signal: AbortSignal.timeout(15_000) }); + if (!res.ok) return null; + const body = (await res.json()) as DashboardData; + return typeof body === "object" && body !== null && typeof body.prices === "object" && body.prices !== null ? body : null; + } catch { + return null; + } +} diff --git a/web/src/dryrun/practice.ts b/web/src/dryrun/practice.ts new file mode 100644 index 0000000..6d7d4b0 --- /dev/null +++ b/web/src/dryrun/practice.ts @@ -0,0 +1,86 @@ +import { ASSET_KEYS, type AssetKey } from "../../../agent/policy/assets"; +import { LimitsClient, type LimitsStatus, type SpendLimit } from "../limits/client"; +import { loadLimitsConfig, type LimitsConfig } from "../limits/config"; + +/** What a dry-run button that would sign says instead. */ +export const NOTHING_SIGNED = "In the dry run nothing is signed. Open the app to do this with your own wallet."; + +/** The practice wallet: a well-formed address nobody holds a key for, so nothing can ever be signed for it. */ +export const PRACTICE_WALLET = "0".repeat(64); +/** The practice agent's name on the page. */ +export const PRACTICE_AGENT = "practice-agent"; + +/** The practice money and limits, the same kind the owner signs in Spending Limits. */ +export const PRACTICE_USD = 100; +const PER_ORDER_USD = 25; +const PER_DAY_USD = 50; +/** Plain NEAR the practice wallet keeps for network fees. */ +const PLAIN_NEAR = 10n ** 24n / 2n; +/** Size of the Spending Limits build the app installs; the network keeps NEAR aside for it. */ +const SPENDING_LIMITS_WASM_BYTES = 165_756; + +const NEAR = 10n ** 24n; + +/** Dollars to atomic NEAR at a price, without floats past the cents. */ +function nearFor(usd: number, nearPrice: number): bigint { + return (BigInt(Math.round(usd * 100)) * NEAR * 1_000_000n) / (100n * BigInt(Math.round(nearPrice * 1_000_000))); +} + +/** The app's own settings, with the practice agent in place of the user's. */ +export function practiceConfig(): LimitsConfig { + return loadLimitsConfig(PRACTICE_AGENT); +} + +/** An installed Spending Limits account holding $100 in NEAR for orders, at the given NEAR price. */ +export function practiceStatus(nearPrice: number): Extract { + const limit: SpendLimit = { perOrder: nearFor(PER_ORDER_USD, nearPrice), perDay: nearFor(PER_DAY_USD, nearPrice) }; + return { + kind: "installed", + available: PLAIN_NEAR, + intiConnected: true, + intiFeesLeft: NEAR / 4n, + agent: PRACTICE_AGENT, + limit, + sellsAllowed: true, + spentToday: 0n, + spendable: nearFor(PRACTICE_USD, nearPrice), + setAside: LimitsClient.storageCost(SPENDING_LIMITS_WASM_BYTES), + }; +} + +/** + * The real client with every action that would sign replaced by a refusal: the dry run reads its + * practice numbers and never reaches the network to change anything. + */ +export class PracticeLimitsClient extends LimitsClient { + override status(): Promise { + return Promise.reject(new Error(NOTHING_SIGNED)); + } + override assets(): Promise<{ key: AssetKey; enabled: boolean; balance: bigint }[]> { + return Promise.resolve(ASSET_KEYS.map((key) => ({ key, enabled: true, balance: 0n }))); + } + override enableAsset(): Promise { + return Promise.reject(new Error(NOTHING_SIGNED)); + } + override activate(): Promise { + return Promise.reject(new Error(NOTHING_SIGNED)); + } + override addForOrders(): Promise { + return Promise.reject(new Error(NOTHING_SIGNED)); + } + override moveToWallet(): Promise { + return Promise.reject(new Error(NOTHING_SIGNED)); + } + override send(): Promise { + return Promise.reject(new Error(NOTHING_SIGNED)); + } + override setLimit(): Promise { + return Promise.reject(new Error(NOTHING_SIGNED)); + } + override disconnectInti(): Promise { + return Promise.reject(new Error(NOTHING_SIGNED)); + } + override reconnectInti(): Promise { + return Promise.reject(new Error(NOTHING_SIGNED)); + } +} diff --git a/web/src/landing/Landing.tsx b/web/src/landing/Landing.tsx index 05a6d55..4c080bd 100644 --- a/web/src/landing/Landing.tsx +++ b/web/src/landing/Landing.tsx @@ -36,6 +36,8 @@ const BARRIERS: readonly Barrier[] = [ /** Where the app lives; the landing only links to it. */ const APP_PATH = "/app"; +/** The dry run: try Inti with a practice wallet, no sign-in. */ +const TRY_PATH = "/try"; function Header() { return ( @@ -73,6 +75,12 @@ function Hero() { > Open app + + Dry run, no funds + root.render({page}); +/** The dry run lives under /try: no sign-in, no wallet. */ +const onTry = /^\/try(\/|$)/.test(window.location.pathname); + // Each page loads only its own code: the landing never loads the wallet or sign-in. if (onApp) void import("./AppRoot").then(({ AppRoot }) => show()); +else if (onTry) void import("./dryrun/DryRun").then(({ DryRunRoot }) => show()); else void import("./landing/Landing").then(({ Landing }) => show());