From b0205640f51caffb5147df7676ea44968c2881cd Mon Sep 17 00:00:00 2001 From: EfeDurmaz16 Date: Sun, 22 Nov 2026 14:54:50 +0300 Subject: [PATCH] test(docs): run managed agent guides against packed SDKs --- .github/workflows/managed-agent-guides.yml | 34 ++++++++ docs/CONTRIBUTING.md | 18 ++++ guides/single-chain-agent.mdx | 14 +-- guides/spectre-stellar-cookbook.mdx | 99 ++++++++++++++-------- scripts/managed-agent/check.mjs | 29 +++++++ scripts/managed-agent/check.sh | 30 +++++++ scripts/managed-agent/client-fixture.ts | 63 ++++++++++++++ scripts/managed-agent/client.mjs | 24 ++++++ scripts/managed-agent/cookbook.mjs | 55 ++++++++++++ sdk/agent-client.mdx | 14 +-- 10 files changed, 332 insertions(+), 48 deletions(-) create mode 100644 .github/workflows/managed-agent-guides.yml create mode 100644 scripts/managed-agent/check.mjs create mode 100644 scripts/managed-agent/check.sh create mode 100644 scripts/managed-agent/client-fixture.ts create mode 100644 scripts/managed-agent/client.mjs create mode 100644 scripts/managed-agent/cookbook.mjs diff --git a/.github/workflows/managed-agent-guides.yml b/.github/workflows/managed-agent-guides.yml new file mode 100644 index 0000000..52b340f --- /dev/null +++ b/.github/workflows/managed-agent-guides.yml @@ -0,0 +1,34 @@ +name: Managed agent guides + +on: + pull_request: + push: + branches: [develop, main] + +permissions: + contents: read + +jobs: + packed-examples: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/checkout@v4 + with: + repository: wraith-protocol/sdk + ref: af34393a7676a11876703a9e5e4ce5381bd08700 + path: sdk-source + persist-credentials: false + - uses: pnpm/action-setup@v4 + with: + version: 10.34.4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - name: Build SDK packages + working-directory: sdk-source + run: | + pnpm install --frozen-lockfile + pnpm run build + - name: Test the guides as an external package consumer + run: bash scripts/managed-agent/check.sh sdk-source diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 5c61ef3..bba35b7 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -163,3 +163,21 @@ GitHub also requires a `workflow_dispatch` workflow to exist on the default branch before it can be manually dispatched, so this PR uses the documented command against the preview URL instead of adding a workflow that cannot yet be run for this PR. + +### Managed agent examples + +The managed-agent workflow builds core 1.4.5 and sdk-agent 0.1.0 from a pinned +SDK commit. To reproduce it with Node 22 and pnpm 10.34.4, run these commands +from the docs root with a fresh SDK checkout: + +```sh +git clone https://github.com/wraith-protocol/sdk.git /tmp/wraith-guide-sdk +git -C /tmp/wraith-guide-sdk checkout af34393a7676a11876703a9e5e4ce5381bd08700 +pnpm --dir /tmp/wraith-guide-sdk install --frozen-lockfile +pnpm --dir /tmp/wraith-guide-sdk run build +bash scripts/managed-agent/check.sh /tmp/wraith-guide-sdk +``` + +The check installs both tarballs in a temporary consumer, compiles the +TypeScript fences in the client, single-chain and Stellar cookbook pages, +and runs their request/response fixtures. It needs no platform credentials. diff --git a/guides/single-chain-agent.mdx b/guides/single-chain-agent.mdx index dda9c16..a47bef7 100644 --- a/guides/single-chain-agent.mdx +++ b/guides/single-chain-agent.mdx @@ -5,12 +5,14 @@ description: "Create an agent on one blockchain" Create an agent on one chain and interact with it. This guide walks through the full lifecycle: creation, funding, payments, scanning, withdrawals, invoicing, and privacy. +Use `@wraith-protocol/sdk-agent@0.1.0` with core SDK `1.4.5`. Run these examples on a server with a dedicated testnet wallet. Set `WRAITH_API_KEY` for this agent and obtain ownership signatures from the connected wallet. Balance and status checks do not need a private key export. + ## Create the Agent ```typescript -import { Wraith, Chain } from "@wraith-protocol/sdk"; +import { Wraith, Chain } from "@wraith-protocol/sdk-agent"; -const wraith = new Wraith({ apiKey: "wraith_live_abc123" }); +const wraith = new Wraith({ apiKey: process.env.WRAITH_API_KEY! }); // Sign a message to prove wallet ownership const message = "Sign to create Wraith agent"; @@ -183,7 +185,7 @@ const { secret } = await agent.exportKey( exportSig, "Export private key for agent " + agent.info.id ); -console.log(secret); // "0x..." — the agent's private key +// Store the secret securely. Never log it. ``` Requires a fresh wallet signature from the owner. @@ -192,11 +194,11 @@ Requires a fresh wallet signature from the owner. ```typescript // By agent ID -const agent = wraith.agent("agent-uuid"); +const byId = wraith.agent("agent-uuid"); // By owner wallet -const agent = await wraith.getAgentByWallet("0xMyWallet"); +const byWallet = await wraith.getAgentByWallet("0xMyWallet"); // By .wraith name -const agent = await wraith.getAgentByName("alice"); +const byName = await wraith.getAgentByName("alice"); ``` diff --git a/guides/spectre-stellar-cookbook.mdx b/guides/spectre-stellar-cookbook.mdx index b3a9051..6045bc6 100644 --- a/guides/spectre-stellar-cookbook.mdx +++ b/guides/spectre-stellar-cookbook.mdx @@ -6,6 +6,8 @@ keywords: "Stellar, soroban, freighter, xlm, lumen, friendbot, stellar.expert, p Three complete recipes for building Stellar agents in production. Each is copy-pasteable and covers the full lifecycle: agent creation, funding, payments, webhooks, and privacy automation. +The examples target core SDK 1.4.5 and managed-agent SDK 0.1.0. Run them on a server. Use a dedicated testnet agent and provide only its credentials to that job. Keep the owner signer in the provisioning step. Monitoring jobs should never hold it or call payment or key-export methods. + > These recipes use `Chain.Stellar` throughout. For multichain variants, see the [Multichain Agent guide](/guides/multichain-agent). --- @@ -24,7 +26,8 @@ A SaaS product that receives USDC payments on Stellar, webhooks on every incomin ### Step 1 — Create the agent ```typescript -import { Wraith, Chain } from "@wraith-protocol/sdk"; +// create-payments.ts +import { Wraith, Chain } from "@wraith-protocol/sdk-agent"; import { Keypair } from "@stellar/stellar-sdk"; const wraith = new Wraith({ apiKey: process.env.WRAITH_API_KEY! }); @@ -34,7 +37,7 @@ const ownerKeypair = Keypair.fromSecret(process.env.OWNER_SECRET!); const message = "Sign to create Wraith agent"; const signature = ownerKeypair.sign(Buffer.from(message)); -const agent = await wraith.createAgent({ +export const agent = await wraith.createAgent({ name: "payments", // → payments.wraith chain: Chain.Stellar, wallet: ownerKeypair.publicKey(), @@ -69,9 +72,9 @@ curl -X POST https://api.usewraith.xyz/agent/create \ { "id": "a1b2c3d4-...", "name": "payments", - "chain": "stellar", - "address": "GABC...agent-address", - "metaAddress": "st:xlm:abc123...def456..." + "chains": ["stellar"], + "addresses": { "stellar": "GABC...agent-address" }, + "metaAddresses": { "stellar": "st:xlm:abc123...def456..." } } ``` @@ -80,7 +83,8 @@ curl -X POST https://api.usewraith.xyz/agent/create \ Stellar testnet funding uses Friendbot. The agent handles this automatically: ```typescript -const res = await agent.chat("fund my wallet"); +// create-payments.ts (continued) +export const funding = await agent.chat("fund my wallet"); // "Wallet funded via Friendbot. Balance: 10,000 XLM" ``` @@ -127,27 +131,23 @@ curl https://api.usewraith.xyz/agent/info/payments \ Poll notifications on a schedule, or wire up a background worker: ```typescript -// poll-payments.ts — run every 60 seconds -async function pollIncoming(agentId: string) { - const res = await fetch( - `https://api.usewraith.xyz/agent/${agentId}/notifications`, - { headers: { Authorization: `Bearer ${process.env.WRAITH_API_KEY}` } } - ); - const { notifications, unreadCount } = await res.json(); +// poll-payments.ts (run every 60 seconds) +import { Wraith, type Notification } from "@wraith-protocol/sdk-agent"; + +export async function pollIncoming(agentId: string) { + const client = new Wraith({ apiKey: process.env.WRAITH_API_KEY! }); + const agent = client.agent(agentId); + const { notifications, unreadCount } = await agent.getNotifications(); if (unreadCount === 0) return; - for (const n of notifications.filter((n: any) => !n.read)) { + for (const n of notifications.filter((n) => !n.read)) { if (n.type === "payment_received") { await handleIncomingPayment(n); } } - // Mark all read - await fetch( - `https://api.usewraith.xyz/agent/${agentId}/notifications/read`, - { method: "POST", headers: { Authorization: `Bearer ${process.env.WRAITH_API_KEY}` } } - ); + await agent.markNotificationsRead(); } ``` @@ -167,7 +167,8 @@ async function pollIncoming(agentId: string) { Your handler extracts amount, token, and stealth address from the `body` field: ```typescript -async function handleIncomingPayment(notification: any) { +// poll-payments.ts (continued) +async function handleIncomingPayment(notification: Notification) { // Parse: "50 USDC received at stealth address GABC...xyz via payments.wraith" const match = notification.body.match( /^(\S+)\s+(\S+)\s+received at stealth address\s+(\S+)/ @@ -194,7 +195,7 @@ Schedule this with your platform's cron (AWS EventBridge, GitHub Actions, Vercel ```typescript // weekly-withdraw.ts -import { Wraith, Chain } from "@wraith-protocol/sdk"; +import { Wraith } from "@wraith-protocol/sdk-agent"; export async function weeklyWithdraw() { const wraith = new Wraith({ apiKey: process.env.WRAITH_API_KEY! }); @@ -244,6 +245,8 @@ Enable privacy autopilot to get weekly analysis and preemptive warnings built in ```typescript // privacy-autopilot.ts — run weekly, or after large payment batches +import { Wraith } from "@wraith-protocol/sdk-agent"; + export async function privacyAutopilot(agentId: string) { const wraith = new Wraith({ apiKey: process.env.WRAITH_API_KEY! }); const agent = wraith.agent(agentId); @@ -268,12 +271,11 @@ export async function privacyAutopilot(agentId: string) { ```typescript // agent-setup.ts -import { Wraith, Chain } from "@wraith-protocol/sdk"; +import { pollIncoming } from "./poll-payments.js"; +import { weeklyWithdraw } from "./weekly-withdraw.js"; +import { privacyAutopilot } from "./privacy-autopilot.js"; import cron from "node-cron"; -const wraith = new Wraith({ apiKey: process.env.WRAITH_API_KEY! }); -const agent = wraith.agent(process.env.AGENT_ID!); - // Poll for payments every 60s setInterval(() => pollIncoming(process.env.AGENT_ID!), 60_000); @@ -300,7 +302,8 @@ A DAO pays contributors weekly in USDC via `.wraith` stealth addresses on Stella ### Step 1 — Create the payroll agent ```typescript -import { Wraith, Chain } from "@wraith-protocol/sdk"; +// create-payroll.ts +import { Wraith, Chain } from "@wraith-protocol/sdk-agent"; import { Keypair } from "@stellar/stellar-sdk"; const wraith = new Wraith({ apiKey: process.env.WRAITH_API_KEY! }); @@ -362,10 +365,10 @@ export const contributors: Contributor[] = [ ```typescript // payroll-run.ts -import { Wraith } from "@wraith-protocol/sdk"; -import { contributors } from "./payroll-registry"; +import { Wraith } from "@wraith-protocol/sdk-agent"; +import { contributors } from "./payroll-registry.js"; -interface PayrollResult { +export interface PayrollResult { contributorId: string; wraithName: string; amount: number; @@ -447,6 +450,9 @@ curl -X POST https://api.usewraith.xyz/agent/$AGENT_ID/chat \ ```typescript // payroll-monitor.ts +import { Wraith } from "@wraith-protocol/sdk-agent"; +import type { PayrollResult } from "./payroll-run.js"; + export async function monitorAndRetry( results: PayrollResult[], agentId: string @@ -485,7 +491,7 @@ export async function monitorAndRetry( } // Alert function — wire to Slack, PagerDuty, email, etc. -async function alertOps(info: { +export async function alertOps(info: { contributor: string; amount: number; error: string; @@ -506,6 +512,8 @@ Contributors update their `.wraith` destination monthly to prevent pattern analy ```typescript // rotation.ts +import { contributors } from "./payroll-registry.js"; + export async function rotateDestinations( updates: Array<{ contributorId: string; newWraithName: string }> ) { @@ -533,6 +541,10 @@ To rotate, contributors call `wraith.getAgentByName("alice")` on a new agent and ```typescript // scheduler.ts +import { Wraith } from "@wraith-protocol/sdk-agent"; +import { alertOps, monitorAndRetry } from "./payroll-monitor.js"; +import { runWeeklyPayroll } from "./payroll-run.js"; +import { contributors } from "./payroll-registry.js"; import cron from "node-cron"; // Every Friday at 16:00 UTC @@ -599,7 +611,8 @@ A weekly background agent that analyzes stealth payment patterns, sends Slack/em ### Step 1 — Create the monitoring agent ```typescript -import { Wraith, Chain } from "@wraith-protocol/sdk"; +// create-monitor.ts +import { Wraith, Chain } from "@wraith-protocol/sdk-agent"; import { Keypair } from "@stellar/stellar-sdk"; const wraith = new Wraith({ apiKey: process.env.WRAITH_API_KEY! }); @@ -638,7 +651,7 @@ curl -X POST https://api.usewraith.xyz/agent/create \ ```tsx // privacy-analysis.ts -import { Wraith } from "@wraith-protocol/sdk"; +import { Wraith } from "@wraith-protocol/sdk-agent"; export interface PrivacyReport { agentId: string; @@ -725,6 +738,7 @@ Best Practices: ```tsx // reporters.ts +import type { PrivacyReport } from "./privacy-analysis.js"; // Slack report export async function sendSlackReport(report: PrivacyReport) { @@ -822,6 +836,8 @@ When the privacy score drops below a threshold, the agent suggests new `.wraith` ```typescript // auto-rotate.ts +import { Wraith } from "@wraith-protocol/sdk-agent"; +import type { PrivacyReport } from "./privacy-analysis.js"; export async function generateRotationPlan( agentId: string, report: PrivacyReport @@ -865,6 +881,9 @@ export async function applyRotation( ```typescript // weekly-privacy-job.ts +import { analyzePrivacy } from "./privacy-analysis.js"; +import { generateRotationPlan } from "./auto-rotate.js"; +import { sendEmailReport, sendSlackReport } from "./reporters.js"; import cron from "node-cron"; // Every Monday at 08:00 UTC @@ -1024,11 +1043,15 @@ Or a name-transfer endpoint that moves ownership to a new agent without requirin All three recipes reconnect to a pre-created agent by ID. Store the agent ID in your environment after the first `createAgent` call: ```typescript -// Reconnect — no new agent is created +// reconnect.ts +import { Wraith } from "@wraith-protocol/sdk-agent"; +const wraith = new Wraith({ apiKey: process.env.WRAITH_API_KEY! }); + +// Reconnect by ID const agent = wraith.agent(process.env.AGENT_ID!); // Or by name -const agent = await wraith.getAgentByName("payments"); +const byName = await wraith.getAgentByName("payments"); ``` ```bash @@ -1058,6 +1081,7 @@ curl https://api.usewraith.xyz/agent/$AGENT_ID/status \ ### Error handling ```typescript +// reconnect.ts (continued) try { const res = await agent.chat("send 500 USDC to alice.wraith on stellar"); } catch (err: any) { @@ -1086,10 +1110,13 @@ All API errors follow: New stealth addresses on Stellar require a `createAccount` operation (not `payment`) to activate the account with the 1 XLM minimum balance. The Wraith agent handles this automatically. If you're using the low-level SDK: ```typescript +// activate-account.ts import { generateStealthAddress } from "@wraith-protocol/sdk/chains/stellar"; -const stealth = generateStealthAddress(spendingPubKey, viewingPubKey); -// stealth.stealthAddress is a G... address with no on-chain existence yet +export function receivingAddress(spendingPubKey: Uint8Array, viewingPubKey: Uint8Array) { + return generateStealthAddress(spendingPubKey, viewingPubKey).stealthAddress; +} +// The returned G... address is an account with no on-chain existence yet // Use Operation.createAccount to fund it for the first time // Use stealth-sender contract for subsequent USDC transfers ``` diff --git a/scripts/managed-agent/check.mjs b/scripts/managed-agent/check.mjs new file mode 100644 index 0000000..399f41f --- /dev/null +++ b/scripts/managed-agent/check.mjs @@ -0,0 +1,29 @@ +import { execFileSync } from 'node:child_process'; +import { readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { client } from './client.mjs'; +import { cookbook } from './cookbook.mjs'; + +const consumer = process.argv[2]; +const pages = [ + ['sdk/agent-client.mdx', 'client', fences => client(fences, false)], + ['guides/single-chain-agent.mdx', 'single-chain', fences => client(fences, true)], + ['guides/spectre-stellar-cookbook.mdx', 'cookbook', cookbook], +]; + +for (const [page, entry, generate] of pages) { + const mdx = readFileSync(page, 'utf8'); + const fences = Array.from(mdx.matchAll(/^```(?:typescript|tsx|ts|javascript|js)\b[^\n]*\n([\s\S]*?)^```\s*$/gm), + match => ({ code: match[1].trimEnd(), line: mdx.slice(0, match.index).split('\n').length })); + if (!fences.length) throw new Error(`No examples found in ${page}`); + const files = generate(fences); + for (const [name, contents] of files) { + writeFileSync(path.join(consumer, name), contents); + } + const tsc = path.join(consumer, 'node_modules/typescript/bin/tsc'); + execFileSync(process.execPath, [tsc, '--strict', '--skipLibCheck', '--target', 'ES2022', + '--module', 'ESNext', '--moduleResolution', 'Bundler', '--types', 'node', + '--outDir', 'dist', ...files.keys()], { cwd: consumer, stdio: 'inherit' }); + execFileSync(process.execPath, [`dist/${entry}.js`], { cwd: consumer, stdio: 'inherit' }); + console.log(`Verified ${page} (${fences.length} examples)`); +} diff --git a/scripts/managed-agent/check.sh b/scripts/managed-agent/check.sh new file mode 100644 index 0000000..91b7b98 --- /dev/null +++ b/scripts/managed-agent/check.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Accept a built SDK checkout. Keep the consumer outside both workspaces so +# workspace links, source aliases and ambient types cannot satisfy an import. +sdk=$(cd "${1:?usage: check.sh }" && pwd) +consumer=$(mktemp -d) +trap 'rm -rf "$consumer"' EXIT +pnpm --dir "$sdk" pack --pack-destination "$consumer" +pnpm --dir "$sdk/packages/sdk-agent" pack --pack-destination "$consumer" +cat > "$consumer/package.json" <<'JSON' +{ + "private": true, + "type": "module", + "dependencies": { + "@wraith-protocol/sdk": "file:wraith-protocol-sdk-1.4.5.tgz", + "@wraith-protocol/sdk-agent": "file:wraith-protocol-sdk-agent-0.1.0.tgz", + "@stellar/stellar-sdk": "13.3.0", + "@types/node": "22.20.1", + "typescript": "5.9.3" + }, + "pnpm": { + "overrides": { + "@wraith-protocol/sdk": "file:wraith-protocol-sdk-1.4.5.tgz" + } + } +} +JSON +pnpm --dir "$consumer" install --ignore-scripts --no-frozen-lockfile +node scripts/managed-agent/check.mjs "$consumer" diff --git a/scripts/managed-agent/client-fixture.ts b/scripts/managed-agent/client-fixture.ts new file mode 100644 index 0000000..6c9a2c5 --- /dev/null +++ b/scripts/managed-agent/client-fixture.ts @@ -0,0 +1,63 @@ +import assert from "node:assert/strict"; + +export const walletAddress = "0xYourWallet"; +export const wallet = { signMessage: async (message: string) => "fixture:" + message }; + +export function installClientFixture() { + // Each page runs in a fresh Node process. Intercept every request before + // constructing the real SDK client so no example can reach the network. + process.env.WRAITH_API_KEY = "fixture-key"; + const info = { + id: "fixture-agent", name: "alice", chains: ["horizen"], + addresses: { horizen: "0x01" }, metaAddresses: { horizen: "st:eth:fixture" }, + }; + const routes = new Map([ + ["GET /agents", [info]], + ["GET /agent/wallet/0xYourWallet", info], + ["GET /agent/wallet/0xMyWallet", info], + ["GET /agent/info/alice", info], + ["GET /agent/fixture-agent/status", { balance: "1.5", tokens: { USDC: "50" } }], + ["GET /agent/fixture-agent/conversations", []], + ["GET /agent/fixture-agent/conversations/conv-uuid/messages", []], + ["DELETE /agent/fixture-agent/conversations/conv-uuid", {}], + ["GET /agent/fixture-agent/notifications", { notifications: [], unreadCount: 0 }], + ["POST /agent/fixture-agent/notifications/read", {}], + ["DELETE /agent/fixture-agent/notifications", {}], + ]); + const seen = new Set(); + globalThis.fetch = async (input, init) => { + const url = new URL(String(input)); + assert.equal(url.origin, "https://api.wraith.dev"); + assert.equal(new Headers(init?.headers).get("authorization"), "Bearer fixture-key"); + const route = init?.method + " " + url.pathname; + seen.add(route); + const body = init?.body ? JSON.parse(String(init.body)) : undefined; + if (route === "POST /agent/create") { + assert.equal(body.chain, "horizen"); + assert.equal(body.name, info.name); + assert.equal(body.wallet, walletAddress); + assert.equal(body.signature, body.message ? await wallet.signMessage(body.message) : "0xSignatureFromWallet"); + return Response.json(info); + } + if (route === "POST /agent/fixture-agent/chat") { + assert.equal(typeof body.message, "string"); + if (body.message === "what was the tx hash?") assert.equal(body.conversationId, "conv-uuid"); + if (body.message === "send 100 ETH to bob.wraith") return new Response(null, { status: 400 }); + return Response.json({ response: "Fixture reply", conversationId: "conv-uuid" }); + } + if (route === "POST /agent/fixture-agent/export") { + assert.equal(body.message, "Export private key for agent " + info.id); + assert.equal(body.signature, await wallet.signMessage(body.message)); + return Response.json({ secret: "fixture-only" }); + } + assert.ok(routes.has(route), "Unexpected request: " + route); + return Response.json(routes.get(route)); + }; + return { + verify() { + for (const route of ["POST /agent/create", "GET /agent/fixture-agent/status", "POST /agent/fixture-agent/chat"]) { + assert.ok(seen.has(route), "Missing request: " + route); + } + }, + }; +} diff --git a/scripts/managed-agent/client.mjs b/scripts/managed-agent/client.mjs new file mode 100644 index 0000000..362b963 --- /dev/null +++ b/scripts/managed-agent/client.mjs @@ -0,0 +1,24 @@ +import { readFileSync } from "node:fs"; + +// The setup fences introduce the client and agent used throughout each page. +// Later fences are independent examples and may reuse local variable names. +export function client(fences, singleChain) { + const setupCount = singleChain ? 1 : 2; + const setup = fences.slice(0, setupCount).map(({ code }) => code).join("\n"); + const examples = fences.slice(setupCount).map(({ code, line }) => + `// MDX line ${line}\n{\n${code}\n}`, + ); + const source = [ + 'import assert from "node:assert/strict";', + 'import { installClientFixture, wallet, walletAddress } from "./client-fixture.js";', + 'const fixture = installClientFixture();', + setup, + 'assert.equal(agent.info.id, "fixture-agent");', + ...examples, + 'fixture.verify();', + ].join("\n"); + return new Map([ + [singleChain ? "single-chain.ts" : "client.ts", source], + ["client-fixture.ts", readFileSync(new URL("./client-fixture.ts", import.meta.url), "utf8")], + ]); +} diff --git a/scripts/managed-agent/cookbook.mjs b/scripts/managed-agent/cookbook.mjs new file mode 100644 index 0000000..9a71def --- /dev/null +++ b/scripts/managed-agent/cookbook.mjs @@ -0,0 +1,55 @@ +// File labels in the cookbook identify modules and their continuation blocks. +export function cookbook(fences) { + const files = new Map(); + for (const { code, line } of fences) { + const name = /^\s*\/\/ ([a-z0-9-]+\.ts)\b/.exec(code)?.[1]; + if (!name) throw new Error(`Cookbook line ${line}: expected a filename comment`); + files.set(name, (files.get(name) ?? "") + "\n" + code + "\n"); + } + // Only the host application's database, alerts and scheduler are supplied here. + files.set("cookbook-app.d.ts", ` + declare const db: { + payments: { create(input: { amount: string, token: string, stealthAddress: string, receivedAt: string }): Promise }; + contributors: { update(input: { where: { id: string }, data: { wraithName: string } }): Promise }; + privacyReports: { create(input: { data: import("./privacy-analysis.js").PrivacyReport }): Promise }; + }; + declare function alertOpsTeam(message: string): Promise; + declare module "node-cron" { + const cron: { schedule(expression: string, task: () => Promise): unknown }; + export default cron; + } + `); + files.set("cookbook.ts", ` + import assert from "node:assert/strict"; + import { Keypair } from "@stellar/stellar-sdk"; + + const owner = Keypair.fromRawEd25519Seed(Buffer.alloc(32, 1)); + process.env.OWNER_SECRET = owner.secret(); + process.env.WRAITH_API_KEY = "fixture-api-key"; + const calls: string[] = []; + globalThis.fetch = async (input, init) => { + const url = new URL(String(input)); + const path = url.pathname; + calls.push(path); + assert.equal(init?.method, "POST"); + assert.equal(new Headers(init.headers).get("Authorization"), "Bearer fixture-api-key"); + const body = JSON.parse(String(init.body)); + if (path === "/agent/create") { + assert.equal(body.chain, "stellar"); + assert.equal(body.name, "payments"); + assert.equal(body.wallet, owner.publicKey()); + assert.ok(owner.verify(Buffer.from(body.message), Buffer.from(body.signature, "hex"))); + return Response.json({ id: "payments-id", name: body.name, chains: [body.chain], + addresses: { stellar: owner.publicKey() }, metaAddresses: { stellar: "fixture-meta" } }); + } + assert.equal(path, "/agent/payments-id/chat"); + assert.deepEqual(body, { message: "fund my wallet" }); + return Response.json({ response: "Funded on testnet", conversationId: "fixture-chat" }); + }; + const { agent, funding } = await import("./create-payments.js"); + assert.deepEqual(calls, ["/agent/create", "/agent/payments-id/chat"]); + assert.equal(agent.info.addresses.stellar, owner.publicKey()); + assert.equal(funding.response, "Funded on testnet"); + `); + return files; +} diff --git a/sdk/agent-client.mdx b/sdk/agent-client.mdx index dc771ea..4d09601 100644 --- a/sdk/agent-client.mdx +++ b/sdk/agent-client.mdx @@ -5,15 +5,17 @@ description: "Wraith and WraithAgent classes for the managed platform" The `Wraith` and `WraithAgent` classes are the primary interface for building with Wraith. They handle all communication with the managed TEE infrastructure. +Use `@wraith-protocol/sdk-agent@0.1.0` with core SDK `1.4.5`. The agent package is built from the [SDK repository](https://github.com/wraith-protocol/sdk/tree/af34393a7676a11876703a9e5e4ce5381bd08700/packages/sdk-agent). Install the core and agent tarballs from the same SDK build. Keep the platform API key on the server. Use a dedicated test agent and wallet when trying write operations. Leave AI provider credentials unset unless you bring your own model. + ## `Wraith` Class ### Constructor ```typescript -import { Wraith } from "@wraith-protocol/sdk"; +import { Wraith } from "@wraith-protocol/sdk-agent"; const wraith = new Wraith({ - apiKey: "wraith_live_abc123", + apiKey: process.env.WRAITH_API_KEY!, }); ``` @@ -32,7 +34,7 @@ const wraith = new Wraith({ Create a new agent with a `.wraith` name and stealth keys. ```typescript -import { Chain } from "@wraith-protocol/sdk"; +import { Chain } from "@wraith-protocol/sdk-agent"; const agent = await wraith.createAgent({ name: "alice", @@ -164,7 +166,7 @@ Export the agent's private key. Requires a fresh wallet signature for verificati ```typescript const sig = await wallet.signMessage("Export private key for agent " + agent.info.id); const { secret } = await agent.exportKey(sig, "Export private key for agent " + agent.info.id); -console.log(secret); // "0x..." +// Store the secret securely. Never log it. ``` ### `agent.getConversations()` @@ -276,12 +278,12 @@ Every request includes: ## Error Handling -All methods throw on failure. The error message comes from the server: +Request failures throw errors. Handle an unknown error before reading its message: ```typescript try { await agent.chat("send 100 ETH to bob.wraith"); } catch (err) { - console.error(err.message); // "Insufficient balance" + if (err instanceof Error) console.error(err.message); } ```