// Optional language model for explanations and the agent's reasoning. The owner pastes an Anthropic API key in /studio; // it is sealed at rest with the server secret (same as the relayer key) and never sent back to any browser. // Nothing security-relevant depends on the model: the auditor's verdict comes from the simulation and fixed rules, // the model only puts that result into plain words. With no key saved, every caller gets { configured: false }. import fs from "node:fs"; import path from "node:path"; import Anthropic from "@anthropic-ai/sdk"; import { seal, unseal, dataDir } from "./burn.mjs"; export const MODEL = "claude-opus-5-5"; const FILE = () => path.join(dataDir(), "ai.json"); const read = () => { try { return JSON.parse(fs.readFileSync(FILE(), "utf8")); } catch { return { key: null, dailyCap: 200, used: {} }; } }; const write = (v) => { const p = FILE(), tmp = p + ".tmp"; fs.writeFileSync(tmp, JSON.stringify(v, null, 1), { mode: 0o600 }); fs.renameSync(tmp, p); }; let client = null, clientFor = null; export function saveKey(key) { key = String(key || "").trim(); if (!/^sk-ant-[A-Za-z0-9_-]{20,}$/.test(key)) throw new Error("That does not look like an Anthropic API key (sk-ant-…)."); const c = read(); c.key = { sealed: seal(key), hint: key.slice(0, 10) + "…" + key.slice(-4), saved: new Date().toISOString() }; write(c); client = null; return status(); } export function removeKey() { const c = read(); c.key = null; write(c); client = null; return status(); } export function setCap(n) { const c = read(); c.dailyCap = Math.max(0, Math.min(5000, Math.floor(+n || 0))); write(c); return status(); } export function status() { const c = read(), day = new Date().toISOString().slice(0, 10); return { configured: !!c.key, model: MODEL, hint: c.key?.hint || null, saved: c.key?.saved || null, dailyCap: c.dailyCap, usedToday: c.used?.[day] || 0 }; } export const configured = () => !!read().key; function api() { const c = read(); if (!c.key) return null; if (!client || clientFor !== c.key.sealed.data) { client = new Anthropic({ apiKey: unseal(c.key.sealed), maxRetries: 2, timeout: 120_000 }); clientFor = c.key.sealed.data; } return client; } function count() { // a daily ceiling on model calls, so a public endpoint cannot run up the owner's bill const c = read(), day = new Date().toISOString().slice(0, 10); c.used = { [day]: (c.used?.[day] || 0) + 1 }; if (c.used[day] > c.dailyCap) throw Object.assign(new Error("The AI's daily budget is used up. The checks above still apply."), { status: 429 }); write(c); } /** One Messages API call. Refusal fallback is on (server-side, routed by category). */ export async function create(params) { const a = api(); if (!a) throw Object.assign(new Error("AI not configured."), { status: 503, code: "AI_OFF" }); count(); const r = await a.beta.messages.create({ model: MODEL, max_tokens: 16000, betas: ["server-side-fallback-2026-07-01"], fallbacks: "default", ...params }); if (r.stop_reason === "refusal") throw Object.assign(new Error("The model declined this request."), { status: 422 }); return r; } export const textOf = (r) => r.content.filter((b) => b.type === "text").map((b) => b.text).join("\n").trim(); const EXPLAIN = `You explain a simulated vault transaction to its owner before they sign it with their quantum-safe vault key. You receive a JSON report produced by deterministic code: the decoded calls, the result of simulating each one against the live chain, and rule-based warnings. Write at most 120 words, plain English, no markdown headings. Say what will happen to the funds and settings, then repeat any warning in plain words. Never contradict the report: if it says a call reverts or a warning fired, say so. Do not add risks the report does not contain, and do not reassure beyond it.`; export async function explainAudit(report) { const r = await create({ max_tokens: 2000, output_config: { effort: "low" }, system: EXPLAIN, messages: [{ role: "user", content: JSON.stringify(report) }] }); return textOf(r); }