### Client Setup - Sign In / Sign Up / Sign Out Source: https://github.com/agentuity/docs/blob/main/content/Frontend/authentication.mdx Examples for performing sign-in, sign-up, and sign-out operations. ```APIDOC ### Sign In / Sign Up / Sign Out ```tsx import { signIn, signUp, signOut } from './auth-client'; // Email/password sign in await signIn.email({ email, password }); // Email/password sign up await signUp.email({ email, password, name }); // Sign out await signOut(); ``` ``` -------------------------------- ### Example: Run a Web Server in a Sandbox Source: https://github.com/agentuity/docs/blob/main/content/Reference/CLI/sandbox.mdx Demonstrates creating a sandbox with port mapping, uploading a server file, starting the server, and accessing it via its public URL. ```bash # Create sandbox with port 3000 agentuity cloud sandbox create --port 3000 --network --name my-api # sbx_abc123 # Upload server code agentuity cloud sandbox cp ./server.js sbx_abc123:/home/agentuity/ # Start the server agentuity cloud sandbox exec sbx_abc123 -- bun run /home/agentuity/server.js # Get the public URL agentuity cloud sandbox get sbx_abc123 # URL: https://my-api-abc123.agentuity.cloud # Test from anywhere curl https://my-api-abc123.agentuity.cloud/api/health ``` -------------------------------- ### Fast Sandbox Creation with Snapshots (TypeScript) Source: https://github.com/agentuity/docs/blob/main/content/Services/Sandbox/snapshots.mdx Demonstrates the efficiency of creating sandboxes with pre-installed dependencies using snapshots, significantly reducing cold start times compared to manual installation. ```typescript // Fast: Dependencies already installed const sandbox = await ctx.sandbox.create({ snapshot: 'project-deps' }); await sandbox.execute({ command: ['npm', 'run', 'build'] }); // Immediate ``` -------------------------------- ### Manual Installation with Bun Source: https://github.com/agentuity/docs/blob/main/content/Frontend/authentication.mdx Install necessary packages for Agentuity Auth in a non-Agentuity project or for custom setups using Bun. ```bash bun add @agentuity/auth better-auth drizzle-orm ``` -------------------------------- ### Initialize Resources and Manage App State with Lifecycle Hooks Source: https://github.com/agentuity/docs/blob/main/content/Agents/events-lifecycle.mdx Use `setup` and `shutdown` hooks to initialize resources like database connections or external clients when the app starts, and to clean them up when the app shuts down. The `setup` hook can return typed app state that is accessible in all agent handlers via `ctx.app`. ```typescript import { createApp } from '@agentuity/runtime'; const { server, logger } = await createApp({ setup: async () => { // Initialize resources when the app starts const dbClient = await connectToDatabase(); // Return typed app state - available in all agents via ctx.app return { db: dbClient, startedAt: new Date(), }; }, shutdown: async (state) => { // Cleanup when the app shuts down // state is typed from setup's return value await state.db.close(); logger.info('App ran for:', Date.now() - state.startedAt.getTime(), 'ms'); }, }); ``` ```typescript const agent = createAgent('DataFetcher', { handler: async (ctx, input) => { // ctx.app is fully typed from setup's return value const results = await ctx.app.db.query('SELECT * FROM users'); return { users: results }; }, }); ``` -------------------------------- ### Start Key-Value REPL Source: https://github.com/agentuity/docs/blob/main/content/Reference/CLI/storage.mdx Initiates an interactive session for Key-Value storage operations. Use commands like `set`, `get`, `delete`, `keys`, and `stats` within the REPL. ```bash agentuity cloud kv repl ``` -------------------------------- ### Start Development Server Source: https://github.com/agentuity/docs/blob/main/content/Get-Started/quickstart.mdx Starts the Agentuity development server for local testing. ```bash agentuity dev # or: bun run dev ``` -------------------------------- ### Install AI SDK and OpenAI Provider Source: https://github.com/agentuity/docs/blob/main/content/Agents/ai-sdk-integration.mdx Install the AI SDK and the OpenAI provider using bun. ```bash bun add ai @ai-sdk/openai ``` -------------------------------- ### Install @agentuity/postgres Source: https://github.com/agentuity/docs/blob/main/content/Services/Database/postgres.mdx Install the package using bun. ```bash bun add @agentuity/postgres ``` -------------------------------- ### Start Local Development Server Source: https://github.com/agentuity/docs/blob/main/content/Reference/CLI/index.mdx Starts the local development server for agent development. ```bash agentuity dev ``` -------------------------------- ### Start Development Server Source: https://github.com/agentuity/docs/blob/main/doc-agents/README.md Use this command to start the development server with hot reloading for rapid development. ```bash bun dev ``` -------------------------------- ### Create HTTP Routes with createRouter() Source: https://context7.com/agentuity/docs/llms.txt Sets up an HTTP router using `createRouter` from `@agentuity/runtime`. This example demonstrates creating basic GET and POST endpoints, integrating agents with validation, and handling route parameters with KV storage access. It also shows standalone schema validation for a POST request. ```typescript import { createRouter, validator } from '@agentuity/runtime'; import { s } from '@agentuity/schema'; import assistant from '@agent/assistant'; const router = createRouter(); // Basic GET endpoint router.get('/health', async (c) => { return c.json({ status: 'healthy', timestamp: Date.now() }); }); // POST with agent validation router.post('/chat', assistant.validator(), async (c) => { const data = c.req.valid('json'); const result = await assistant.run(data); return c.json(result); }); // Route parameters router.get('/users/:id', async (c) => { const userId = c.req.param('id'); const user = await c.var.kv.get('users', userId); if (!user.exists) { return c.json({ error: 'User not found' }, 404); } return c.json({ user: user.data }); }); // Standalone validation without agent const searchSchema = s.object({ query: s.string(), limit: s.number().optional(), }); router.post('/search', validator({ input: searchSchema }), async (c) => { const { query, limit } = c.req.valid('json'); c.var.logger.info('Search request', { query, limit }); return c.json({ results: [], query }); }); export default router; ``` -------------------------------- ### Install AI SDK with Multiple Providers Source: https://github.com/agentuity/docs/blob/main/content/Agents/ai-sdk-integration.mdx Install the AI SDK with multiple providers like OpenAI, Anthropic, and Google. ```bash bun add ai @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google ``` -------------------------------- ### Create Sandbox and Install Dependencies Source: https://github.com/agentuity/docs/blob/main/content/Services/Sandbox/snapshots.mdx Manually creates a sandbox with specified resources and installs dependencies using package managers. This is a step towards creating a manual snapshot. ```bash agentuity cloud sandbox create --runtime bun:1 --memory 1Gi --network agentuity cloud sandbox exec sbx_abc123 -- npm init -y agentuity cloud sandbox exec sbx_abc123 -- npm install typescript zod ``` -------------------------------- ### Client Setup - Creating the Auth Client Source: https://github.com/agentuity/docs/blob/main/content/Frontend/authentication.mdx How to create an authentication client for use in React applications. ```APIDOC ## Client Setup - Creating the Auth Client ### Description This section details how to set up the Agentuity authentication client for frontend applications, including creating the client instance and integrating it with React components. ### Creating the Auth Client ```typescript title="src/web/auth-client.ts" import { createAuthClient } from '@agentuity/auth/react'; export const authClient = createAuthClient(); // Export methods for use in components export const { signIn, signUp, signOut, useSession, getSession } = authClient; ``` ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/agentuity/docs/blob/main/README.md Run this command in your terminal to install all necessary project dependencies. ```bash npm install ``` -------------------------------- ### Define Agent Setup and Shutdown Hooks Source: https://github.com/agentuity/docs/blob/main/content/Agents/events-lifecycle.mdx Use `setup` for agent initialization and `shutdown` for cleanup. `setup` receives app state and returns agent config, while `shutdown` receives app state and config. Config is accessed via `ctx.config`. ```typescript import { createAgent } from '@agentuity/runtime'; import { z } from 'zod'; const agent = createAgent('CachedLookup', { schema: { input: z.object({ key: z.string() }), output: z.object({ value: z.string() }), }, // Called once when app starts - receives app state, returns agent config setup: async (app) => { const cache = new Map(); return { cache }; }, // Called when app shuts down - receives app state and agent config shutdown: async (app, config) => { config.cache.clear(); }, handler: async (ctx, input) => { // ctx.config is typed from setup's return value const cached = ctx.config.cache.get(input.key); if (cached) { return { value: cached }; } // Fetch and cache const value = await fetchValue(input.key); ctx.config.cache.set(input.key, value); return { value }; }, }); export default agent; ``` -------------------------------- ### Install @agentuity/react Source: https://github.com/agentuity/docs/blob/main/content/Frontend/react-hooks.mdx Install the Agentuity React library using Bun. ```bash bun add @agentuity/react ``` -------------------------------- ### Copy Environment File Source: https://github.com/agentuity/docs/blob/main/README.md Copy the example environment file to create your local environment configuration. ```bash cp .env.example .env.local ``` -------------------------------- ### Start Doc-Agents Backend Source: https://github.com/agentuity/docs/blob/main/README.md Navigate to the doc-agents directory and run this command to start the backend service, which is required for AI search and chat features. ```bash cd doc-agents agentuity dev ``` -------------------------------- ### Client Setup - AuthProvider Source: https://github.com/agentuity/docs/blob/main/content/Frontend/authentication.mdx Instructions for wrapping your application with `AgentuityProvider` and `AuthProvider`. ```APIDOC ### AuthProvider Wrap your app with `AgentuityProvider` and `AuthProvider`: ```tsx title="src/web/frontend.tsx" import { AgentuityProvider } from '@agentuity/react'; import { AuthProvider, createAuthClient } from '@agentuity/auth/react'; import { App } from './App'; const authClient = createAuthClient(); export function Root() { return ( ); } ``` ``` -------------------------------- ### Start Agentuity Development Server Source: https://github.com/agentuity/docs/blob/main/content/Learn/Cookbook/Patterns/tailwind-setup.mdx Run this command to start the development server and see your Tailwind CSS styles applied in the browser. ```bash bun run dev ``` -------------------------------- ### Basic SSE Streaming Example Source: https://github.com/agentuity/docs/blob/main/content/Routes/sse.mdx Demonstrates a basic SSE stream that sends a connection message and then streams numbered updates every second. Ensure the @agentuity/runtime library is installed. ```typescript import { createRouter, sse } from '@agentuity/runtime'; const router = createRouter(); router.get('/updates', sse(async (c, stream) => { await stream.write('Connected!'); // Stream data to client for (let i = 0; i < 5; i++) { await stream.write(`Update ${i + 1}`); await new Promise((r) => setTimeout(r, 1000)); } stream.close(); })); export default router; ``` -------------------------------- ### Install Valibot Source: https://github.com/agentuity/docs/blob/main/content/Agents/schema-libraries.mdx Installs the Valibot schema validation library using Bun. Valibot is chosen for its small bundle size. ```bash bun add valibot ``` -------------------------------- ### Install Drizzle Kit for Migrations Source: https://github.com/agentuity/docs/blob/main/content/Services/Database/drizzle.mdx Install Drizzle Kit as a development dependency for managing database schema migrations. ```bash bun add -D drizzle-kit ``` -------------------------------- ### Complete Stateful Agent Example Source: https://github.com/agentuity/docs/blob/main/content/Reference/sdk-reference.mdx A comprehensive example demonstrating the usage of request, thread, and session state management within a single agent handler. ```typescript const statefulAgent = createAgent('StatefulAgent', { schema: { input: z.object({ action: z.string(), data: z.any() }), output: z.object({ success: z.boolean(), stats: z.object({ requestDuration: z.number(), threadStep: z.number(), sessionTotal: z.number(), }), }), }, handler: async (ctx, input) => { // Request-scoped state (sync) ctx.state.set('startTime', Date.now()); // Thread-scoped state (async, conversation flow) const threadStep = (await ctx.thread.state.get('step')) || 0; await ctx.thread.state.set('step', threadStep + 1); await ctx.thread.state.set('lastAction', input.action); // Session-scoped state (user-level) const sessionTotal = (ctx.session.state.get('total') as number) || 0; ctx.session.state.set('total', sessionTotal + 1); ctx.session.state.set('lastSeen', Date.now()); // Process action await processAction(input.action, input.data); return { success: true, stats: { requestDuration: Date.now() - (ctx.state.get('startTime') as number), threadStep: threadStep + 1, sessionTotal: sessionTotal + 1, }, }; }, }); ``` -------------------------------- ### Complete Example with Event Listener Cleanup Source: https://github.com/agentuity/docs/blob/main/content/Reference/sdk-reference.mdx A comprehensive example illustrating the creation of an agent, adding multiple event listeners for different lifecycle events, and showing how to remove them later. This pattern is useful for managing resources and preventing memory leaks. ```typescript const agent = createAgent('ActionHandler', { schema: { input: z.object({ action: z.string() }), output: z.object({ success: z.boolean() }), }, handler: async (ctx, input) => { return { success: true }; }, }); // Create handlers with references for cleanup const startedHandler = (eventName, agent, ctx) => { ctx.logger.info('Started processing'); }; const completedHandler = (eventName, agent, ctx) => { ctx.logger.info('Completed processing'); }; const erroredHandler = (eventName, agent, ctx, error) => { ctx.logger.error('Error occurred', { error }); }; // Add listeners agent.addEventListener('started', startedHandler); agent.addEventListener('completed', completedHandler); agent.addEventListener('errored', erroredHandler); // Later, if needed, remove listeners // agent.removeEventListener('started', startedHandler); // agent.removeEventListener('completed', completedHandler); // agent.removeEventListener('errored', erroredHandler); ``` -------------------------------- ### ArkType Installation Source: https://github.com/agentuity/docs/blob/main/content/Agents/schema-libraries.mdx Command to install the ArkType library using Bun. This is a prerequisite for using ArkType schemas. ```bash bun add arktype ``` -------------------------------- ### App Configuration with Lifecycle Hooks Source: https://github.com/agentuity/docs/blob/main/content/Get-Started/app-configuration.mdx Configure app setup and shutdown hooks for resource initialization and cleanup. Resources initialized in setup are available in agents via ctx.app. ```typescript import { createApp } from '@agentuity/runtime'; const { server, logger } = await createApp({ setup: async () => { // Initialize resources, return app state // Available in agents via ctx.app const db = await connectDatabase(); return { db }; }, shutdown: async (state) => { // Clean up resources await state.db.close(); }, }); logger.debug('Running %s', server.url); ``` -------------------------------- ### Create Agent with Setup and Shutdown Source: https://github.com/agentuity/docs/blob/main/content/Reference/sdk-reference.mdx Defines an agent with input/output schemas, setup for initializing external services and cache, and shutdown for cleaning up resources. ```typescript import { createAgent, } from '@agentuity/runtime'; import { z, } from 'zod'; const agent = createAgent('CachedProcessor', { schema: { input: z.object({ key: z.string(), }), output: z.object({ value: z.string(), }), }, // Called once when app starts - return value available via ctx.config setup: async (app) => { const cache = new Map(); const client = await initializeExternalService(); return { cache, client, }; }, // Called when app shuts down shutdown: async (app, config) => { await config.client.disconnect(); config.cache.clear(); }, handler: async (ctx, input) => { // ctx.config is fully typed from setup's return value const cached = ctx.config.cache.get(input.key); if (cached) { return { value: cached, }; } const value = await ctx.config.client.fetch(input.key); ctx.config.cache.set(input.key, value); return { value, }; }, }); export default agent; ``` -------------------------------- ### Create Agent with Lifecycle Methods Source: https://github.com/agentuity/docs/blob/main/doc-agents/src/agent/AGENTS.md An agent that includes setup and shutdown functions for resource initialization and cleanup. The setup function runs once on startup and its return value is available in ctx.config. ```typescript import { createAgent } from '@agentuity/runtime'; import { s } from '@agentuity/schema'; const agent = createAgent('lifecycle-agent', { description: 'Agent with setup and shutdown', schema: { input: s.object({ message: s.string() }), output: s.object({ result: s.string() }), }, setup: async (app) => { // Initialize resources (runs once on startup) // app contains: appName, version, startedAt, config return { agentId: `agent-${Math.random().toString(36).substr(2, 9)}`, connectionPool: ['conn-1', 'conn-2'], }; }, handler: async (ctx, input) => { // Access setup config via ctx.config (fully typed) ctx.logger.info('Agent ID:', ctx.config.agentId); ctx.logger.info('Connections:', ctx.config.connectionPool); return { result: `Processed: ${input.message}` }; }, shutdown: async (app, config) => { // Cleanup resources (runs on shutdown) console.log('Shutting down agent:', config.agentId); }, }); export default agent; ``` -------------------------------- ### Install OpenCode Plugin Source: https://github.com/agentuity/docs/blob/main/content/Get-Started/quickstart.mdx Install the OpenCode plugin for AI-assisted agent development. This plugin helps with writing agents, debugging, and deploying directly from your editor. ```bash agentuity ai opencode install ``` -------------------------------- ### Application-Wide Analytics Example Source: https://github.com/agentuity/docs/blob/main/content/Reference/sdk-reference.mdx An example demonstrating how to use app event listeners for tracking agent executions, monitoring errors, session analytics, and thread cleanup. Requires importing createApp. ```typescript import { createApp } from '@agentuity/runtime'; const { app, server, logger } = createApp(); // Track agent executions let agentExecutions = 0; app.addEventListener('agent.started', (eventName, agent, ctx) => { agentExecutions++; logger.info(`Total agent executions: ${agentExecutions}`); }); // Track errors for monitoring app.addEventListener('agent.errored', (eventName, agent, ctx, error) => { logger.error('Agent error detected', { agentName: agent.metadata.name, error: error.message, sessionId: ctx.sessionId }); // Could send to error tracking service // await sendToErrorTracker(error, agent, ctx); }); // Session analytics app.addEventListener('session.completed', (eventName, session) => { const messageCount = session.state.get('messageCount') || 0; logger.info('Session completed', { sessionId: session.id, totalMessages: messageCount }); }); // Thread cleanup app.addEventListener('thread.destroyed', (eventName, thread) => { logger.info('Thread destroyed', { threadId: thread.id }); }); ``` -------------------------------- ### Declarative Snapshot YAML Example Source: https://github.com/agentuity/docs/blob/main/content/Services/Sandbox/snapshots.mdx An example of a YAML file defining a declarative snapshot. It specifies the base runtime, apt dependencies, files to include, and environment variables. ```yaml version: 1 runtime: bun:1 # Base runtime - snapshot layers on top of this description: Node.js environment with common dependencies dependencies: # Apt packages to install - curl - jq files: # Files to include from your project - src/** - package.json - "!**/*.test.ts" # Exclude test files - "!node_modules/**" # Exclude node_modules env: NODE_ENV: production ``` -------------------------------- ### Simple RAG Example with Vector Search and LLM Source: https://github.com/agentuity/docs/blob/main/content/Services/Storage/vector.mdx This example demonstrates a Retrieval-Augmented Generation (RAG) pattern. It searches for relevant documents using `ctx.vector.search`, builds context from the results, and then uses an LLM to generate an answer based on the provided context and the user's question. ```typescript import { createAgent } from '@agentuity/runtime'; import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; import { s } from '@agentuity/schema'; const ragAgent = createAgent('RAG', { schema: { input: s.object({ question: s.string() }), output: s.object({ answer: s.string(), sources: s.array(s.string()), }), }, handler: async (ctx, input) => { // Search for relevant documents const results = await ctx.vector.search('knowledge-base', { query: input.question, limit: 3, similarity: 0.7, }); if (results.length === 0) { return { answer: "I couldn't find relevant information.", sources: [], }; } // Build context from results const context = results .map(r => r.metadata?.content || '') .join('\n\n'); // Generate response using context const { text } = await generateText({ model: openai('gpt-5-mini'), prompt: `Answer based on this context:\n\n${context}\n\nQuestion: ${input.question}`, }); return { answer: text, sources: results.map(r => r.key), }; }, }); ``` -------------------------------- ### Start Agentuity Development Server Source: https://github.com/agentuity/docs/blob/main/content/Get-Started/installation.mdx Starts the Agentuity development server. This command uses Vite for frontend updates and Bun for server rebuilds, enabling instant reflection of changes. ```bash agentuity dev ``` ```bash bun run dev ``` -------------------------------- ### Router GET Request Example Source: https://github.com/agentuity/docs/blob/main/content/Reference/sdk-reference.mdx Handles GET requests for retrieving user data. Supports parameters for specific user IDs. ```typescript router.get('/users', (c) => { return c.json({ users: [] }); }); router.get('/users/:id', (c) => { const id = c.req.param('id'); return c.json({ userId: id }); }); ``` -------------------------------- ### Get Vector by ID Source: https://github.com/agentuity/docs/blob/main/content/Reference/CLI/storage.mdx Retrieves a specific vector embedding using its unique ID. Example: `agentuity cloud vec get `. ```bash agentuity cloud vec get ``` -------------------------------- ### Get Key-Value Pair Source: https://github.com/agentuity/docs/blob/main/content/Reference/CLI/storage.mdx Retrieves a value associated with a specific key from a given namespace. Example: `agentuity cloud kv get production user:123`. ```bash agentuity cloud kv get production user:123 ``` ```bash agentuity cloud kv get cache session:abc ``` -------------------------------- ### Create Agentuity Application with Setup and Shutdown Hooks Source: https://github.com/agentuity/docs/blob/main/content/Reference/sdk-reference.mdx Initializes an Agentuity application with setup and shutdown hooks for managing application state and resources. The setup function runs before the server starts, and the shutdown function handles cleanup. ```typescript import { createApp } from '@agentuity/runtime'; const { server, logger } = await createApp({ // Initialize shared resources setup: async () => { const db = await connectDatabase(); const redis = await connectRedis(); return { db, redis }; }, // Clean up on shutdown shutdown: async (state) => { await state.db.close(); await state.redis.quit(); }, }); // In agents, access via ctx.app: // ctx.app.db.query('SELECT * FROM users') ``` -------------------------------- ### Get S3 Storage Details Source: https://github.com/agentuity/docs/blob/main/content/Reference/CLI/storage.mdx Retrieves detailed information about a specific S3 storage resource using its ID. Example: `agentuity cloud s3 get `. ```bash agentuity cloud s3 get ``` -------------------------------- ### Initialize Auth Source: https://github.com/agentuity/docs/blob/main/content/Frontend/authentication.mdx Use this command to set up the authentication system. Options include skipping database migrations or dependency installations. If Drizzle or Prisma is detected, migrations will be skipped. ```bash agentuity project auth init [options] ``` -------------------------------- ### Standalone Input Validation for GET Requests Source: https://github.com/agentuity/docs/blob/main/content/Routes/http.mdx This example demonstrates how to validate query parameters for GET requests using the standalone validator. The validator automatically detects the HTTP method and applies validation to the appropriate request part (query for GET, JSON body for others). ```typescript import { createRouter, validator } from '@agentuity/runtime'; import * as v from 'valibot'; const router = createRouter(); // GET route: validates query parameters const searchSchema = v.object({ q: v.string(), limit: v.optional(v.number()), }); router.get('/search', validator({ input: searchSchema }), async (c) => { const { q, limit } = c.req.valid('query'); // GET uses query params return c.json({ results: [], query: q, limit }); } ); export default router; ``` -------------------------------- ### Agent-to-Agent Communication v0 Source: https://github.com/agentuity/docs/blob/main/content/Reference/migration-guide.mdx Example of how agent-to-agent communication was handled in v0 using context to get and run agents. ```typescript const handler: AgentHandler = async (request, response, context) => { // Get agent by ID const agent = await context.getAgent({ id: 'agent_123' }); // Or by name const agent = await context.getAgent({ name: 'other-agent', projectId: 'proj_123' }); // Run the agent const result = await agent.run({ data: JSON.stringify({ message: 'Hello' }), contentType: 'application/json' }); const output = await result.data.json(); }; ``` -------------------------------- ### Build Application Source: https://github.com/agentuity/docs/blob/main/doc-agents/README.md Compiles the application into the .agentuity/ directory for deployment. ```bash bun build ``` -------------------------------- ### Create a Simple Health Check Route Source: https://github.com/agentuity/docs/blob/main/content/APIs/when-to-use.mdx Use a simple route for basic endpoints like health checks. This example demonstrates creating a GET endpoint that checks database health. ```typescript // src/api/index.ts import { createRouter } from '@agentuity/runtime'; const router = createRouter(); router.get('/health', async (c) => { const dbHealthy = await checkDatabase(); return c.json({ status: dbHealthy ? 'healthy' : 'degraded' }); }); export default router; ``` -------------------------------- ### KV-Backed API Example Source: https://github.com/agentuity/docs/blob/main/content/Routes/http.mdx Demonstrates a Key-Value (KV) backed API using Agentuity's `createRouter` and `validator`. It includes routes for getting, creating, and deleting items, with input validation for POST requests. ```typescript import { createRouter, validator } from '@agentuity/runtime'; import * as v from 'valibot'; const router = createRouter(); const itemSchema = v.object({ name: v.string(), value: v.number(), }); router.get('/items/:key', async (c) => { const key = c.req.param('key'); const result = await c.var.kv.get('items', key); if (!result.exists) { return c.json({ error: 'Not found' }, 404); } return c.json({ data: result.data }); }); router.post('/items/:key', validator({ input: itemSchema }), async (c) => { const key = c.req.param('key'); const data = c.req.valid('json'); await c.var.kv.set('items', key, data); c.var.logger.info('Item created', { key }); return c.json({ success: true, key }, 201); } ); router.delete('/items/:key', async (c) => { const key = c.req.param('key'); await c.var.kv.delete('items', key); return c.json({ success: true }); }); export default router; ``` -------------------------------- ### Log Agent Lifecycle Events Source: https://github.com/agentuity/docs/blob/main/content/Reference/sdk-reference.mdx Sets up event listeners for an agent's 'started', 'completed', and 'errored' lifecycle events. This example logs key information such as the agent's name and session ID to the console using ctx.logger. ```typescript import { createAgent } from '@agentuity/runtime'; import { z } from 'zod'; const agent = createAgent('TaskRunner', { schema: { input: z.object({ task: z.string() }), output: z.object({ result: z.string() }), }, handler: async (ctx, input) => { return { result: `Completed: ${input.task}` }; }, }); // Log when agent starts agent.addEventListener('started', (eventName, agent, ctx) => { ctx.logger.info('Agent started', { agentName: agent.metadata.name, sessionId: ctx.sessionId, }); }); // Log when agent completes agent.addEventListener('completed', (eventName, agent, ctx) => { ctx.logger.info('Agent completed', { agentName: agent.metadata.name, sessionId: ctx.sessionId, }); }); // Log when agent errors agent.addEventListener('errored', (eventName, agent, ctx, error) => { ctx.logger.error('Agent errored', { agentName: agent.metadata.name, sessionId: ctx.sessionId, error: error.message, }); }); ``` -------------------------------- ### Create Pre-configured Python Environment Source: https://github.com/agentuity/docs/blob/main/content/Services/Sandbox/snapshots.mdx Set up a Python environment with common data science packages. This involves creating a base sandbox, installing packages, and then creating a snapshot. ```bash # Python with common packages agentuity cloud sandbox create --runtime base:latest --network agentuity cloud sandbox exec sbx_... -- apt-get update agentuity cloud sandbox exec sbx_... -- apt-get install -y python3 python3-pip agentuity cloud sandbox exec sbx_... -- pip install numpy pandas requests agentuity cloud sandbox snapshot create sbx_... --tag python-data ``` -------------------------------- ### Verify Agentuity CLI Installation Source: https://github.com/agentuity/docs/blob/main/content/Reference/CLI/getting-started.mdx Check the installed version of the Agentuity CLI after installation. ```bash agentuity --version ``` -------------------------------- ### Install Agentuity CLI Source: https://github.com/agentuity/docs/blob/main/content/Get-Started/installation.mdx Installs the Agentuity CLI globally using curl. Ensure you have curl installed. ```bash curl -sSL https://agentuity.sh | sh ``` -------------------------------- ### Build Application with Bun Source: https://github.com/agentuity/docs/blob/main/doc-agents/AGENTS.md Use this command to compile your application for production. It leverages the Bun runtime for efficient building. ```bash bun run build ``` -------------------------------- ### Install Agentuity CLI via Bun Source: https://github.com/agentuity/docs/blob/main/content/Get-Started/installation.mdx Alternative installation method for the Agentuity CLI using the Bun package manager. Requires Bun to be installed. ```bash bun add -g @agentuity/cli ``` -------------------------------- ### Install @agentuity/drizzle Source: https://github.com/agentuity/docs/blob/main/content/Services/Database/drizzle.mdx Install the necessary packages for Drizzle ORM integration. ```bash bun add @agentuity/drizzle drizzle-orm ``` -------------------------------- ### Agent Creation and Handler Example Source: https://github.com/agentuity/docs/blob/main/content/Reference/sdk-reference.mdx Demonstrates how to create an agent using `createAgent` and implement its handler function. Shows accessing context properties like `sessionId`, `logger`, `kv`, `state`, and `session` for various operations. ```typescript import { createAgent } from '@agentuity/runtime'; import { z } from 'zod'; const agent = createAgent('QueryProcessor', { schema: { input: z.object({ query: z.string() }), output: z.object({ result: z.string() }), }, handler: async (ctx, input) => { // Access session ID ctx.logger.info(`Session ID: ${ctx.sessionId}`); // Use storage services await ctx.kv.set('cache', 'last-query', input.query); // Store request-scoped data ctx.state.set('startTime', Date.now()); // Call another agent (import at top of file) // import enrichmentAgent from '@agent/enrichment'; const enrichedData = await enrichmentAgent.run({ text: input.query }); // Use session state ctx.session.state.set('queryCount', (ctx.session.state.get('queryCount') as number || 0) + 1 ); return { result: enrichedData.output }; }, }); ``` -------------------------------- ### Create a Database Source: https://github.com/agentuity/docs/blob/main/content/Reference/CLI/storage.mdx Creates a new database. You can specify a custom name and an optional description. This command also automatically adds the DATABASE_URL to your local .env file. ```bash agentuity cloud db create --name my-database ``` ```bash agentuity cloud db create --name analytics-db --description "Analytics data warehouse" ``` -------------------------------- ### Application Entry Point - createApp Source: https://github.com/agentuity/docs/blob/main/content/Reference/sdk-reference.mdx Initializes an Agentuity application instance. This function sets up the application with configuration, router, server, and event system. ```APIDOC ## createApp `createApp(config?: AppConfig): App` Creates and initializes an Agentuity application instance. ### Parameters - `config` (optional): Application configuration object - `cors`: Override default CORS settings - `services`: Override default services (KV, Vector, Stream) - `useLocal`: Use local services for development (default: false) - `keyvalue`: Custom KeyValueStorage implementation - `vector`: Custom VectorStorage implementation - `stream`: Custom StreamStorage implementation - `setup`: Async function called before server starts, returns app state available via `ctx.app` - `shutdown`: Async cleanup function called when server stops, receives app state ### Return Value Returns an `App` instance with the following properties: ```typescript interface App { router: Hono; server: Server; logger: Logger; } ``` **Note:** The App instance also provides `addEventListener()` and `removeEventListener()` methods for lifecycle events. ### Request Example **Basic Example** ```typescript // app.ts import { createApp } from '@agentuity/runtime'; // Create the application instance (async) const { server, logger } = await createApp(); // Access application properties logger.info(`Server running at ${server.url}`); ``` **With Configuration** ```typescript import { createApp } from '@agentuity/runtime'; const { server, logger } = await createApp({ // Custom CORS settings cors: { origin: ['https://example.com'], credentials: true }, // Use local services for development services: { useLocal: true } }); ``` **With Setup and Shutdown** ```typescript import { createApp } from '@agentuity/runtime'; const { server, logger } = await createApp({ // Initialize shared resources setup: async () => { const db = await connectDatabase(); const redis = await connectRedis(); return { db, redis }; }, // Clean up on shutdown shutdown: async (state) => { await state.db.close(); await state.redis.quit(); }, }); // In agents, access via ctx.app: // ctx.app.db.query('SELECT * FROM users') ``` ### Environment Variables Agentuity applications access configuration and secrets through standard Node.js environment variables (`process.env`). **Standard Environment Variables:** - `AGENTUITY_SDK_KEY` - SDK-level API key (used in development to access Agentuity Cloud) - `AGENTUITY_PROJECT_KEY` - Project-level API key (used when deployed) **Example** ```typescript // app.ts import { createApp } from '@agentuity/runtime'; if (!process.env.AGENTUITY_SDK_KEY) { console.error('Missing AGENTUITY_SDK_KEY environment variable'); process.exit(1); } const { server, logger } = await createApp(); // Access other environment variables const apiEndpoint = process.env.API_ENDPOINT || 'https://api.example.com'; const openaiKey = process.env.OPENAI_API_KEY; ``` **Note**: Environment variables are typically loaded from a `.env` file in development and configured in your deployment environment. ``` -------------------------------- ### Create Sandbox from Snapshot in Code Source: https://github.com/agentuity/docs/blob/main/content/Services/Sandbox/snapshots.mdx Demonstrates how to create a new sandbox from a pre-existing snapshot using the SDK. This bypasses the need for dependency installation in the new sandbox. ```typescript import { createAgent } from '@agentuity/runtime'; const agent = createAgent('TypeScriptRunner', { handler: async (ctx, input) => { // Create sandbox from snapshot - dependencies already installed const sandbox = await ctx.sandbox.create({ snapshot: 'node-typescript', // Use tag or snapshot ID resources: { memory: '512Mi' }, }); try { // Write the user's code await sandbox.writeFiles([ { path: 'index.ts', content: Buffer.from(input.code) }, ]); // Run immediately - no npm install needed const result = await sandbox.execute({ command: ['npx', 'tsx', 'index.ts'], }); return { success: true, exitCode: result.exitCode }; } catch (error) { ctx.logger.error('Sandbox execution failed', { error }); return { success: false, exitCode: -1, error: String(error) }; } finally { await sandbox.destroy(); } }, }); ``` -------------------------------- ### Create Sandbox from Snapshot Source: https://github.com/agentuity/docs/blob/main/content/Reference/CLI/sandbox.mdx Creates a new sandbox initialized from a previously saved snapshot, allowing for faster setup as dependencies are pre-installed. ```bash # Create sandbox from snapshot (fast - deps already installed) agentuity cloud sandbox create --snapshot python-ml # sbx_def456 ``` -------------------------------- ### Create Manual Snapshot Source: https://github.com/agentuity/docs/blob/main/content/Services/Sandbox/snapshots.mdx Creates a snapshot from an existing sandbox, capturing its current filesystem state. A tag can be provided for easier reference. ```bash agentuity cloud sandbox snapshot create sbx_abc123 --tag node-typescript ``` -------------------------------- ### Using Bun SQL in a Router Source: https://github.com/agentuity/docs/blob/main/content/Services/Database/overview.mdx Shows how to use Bun's SQL API within an Agentuity router for handling HTTP requests. Includes examples for fetching users with a limit and inserting a new user, returning the inserted data. ```typescript import { createRouter } from '@agentuity/runtime'; import { sql } from "bun"; const router = createRouter(); router.get('/users', async (c) => { const limit = parseInt(c.req.query('limit') || '10'); const users = await sql` SELECT id, name, email FROM users ORDER BY created_at DESC LIMIT ${limit} `; return c.json({ users }); }); router.post('/users', async (c) => { const body = await c.req.json(); const result = await sql` INSERT INTO users (name, email) VALUES (${body.name}, ${body.email}) RETURNING id, name, email `; return c.json({ user: result[0] }, 201); }); export default router; ``` -------------------------------- ### Install Dependencies in Sandbox Source: https://github.com/agentuity/docs/blob/main/content/Reference/CLI/sandbox.mdx Installs system and Python package dependencies within a sandbox environment. Ensure the sandbox is running and accessible. ```bash # Install dependencies agentuity cloud sandbox exec sbx_abc123 -- apt-get update agentuity cloud sandbox exec sbx_abc123 -- apt-get install -y python3 python3-pip agentuity cloud sandbox exec sbx_abc123 -- pip install numpy pandas scikit-learn ``` -------------------------------- ### Quick Start: Bun S3 File Operations Source: https://github.com/agentuity/docs/blob/main/content/Services/Storage/object.mdx Demonstrates basic file operations like writing, reading, checking existence, and deleting files using Bun's S3 API. Ensure S3 credentials are automatically injected or configured. ```typescript import { s3 } from "bun"; // Create a file reference const file = s3.file("documents/report.pdf"); // Write content await file.write("Hello, World!"); await file.write(jsonData, { type: "application/json" }); // Read content const text = await file.text(); const json = await file.json(); const bytes = await file.bytes(); // Check existence and delete if (await file.exists()) { await file.delete(); } ``` -------------------------------- ### Binary Pass/Fail Eval Example Source: https://github.com/agentuity/docs/blob/main/content/Reference/sdk-reference.mdx Example of an evaluation that returns a simple boolean indicating success or failure, along with a reason and metadata. ```typescript import agent from './agent'; export const lengthEval = agent.createEval('output-length-check', { description: 'Ensures output meets minimum length', handler: async (ctx, input, output) => { const passed = output.answer.length >= 10; return { passed, reason: passed ? 'Output meets minimum length' : 'Output too short', metadata: { actualLength: output.answer.length, minimumLength: 10 }, }; }, }); ``` -------------------------------- ### Install Agentuity Coder Plugin Source: https://github.com/agentuity/docs/blob/main/content/Reference/CLI/claude-code-plugin.mdx Install the plugin using the Agentuity CLI or directly through the Claude Code marketplace. Ensure you have the necessary prerequisites. ```bash agentuity ai claude-code install ``` ```bash /plugin marketplace add agentuity/sdk /plugin install agentuity-coder@agentuity ``` -------------------------------- ### Start Agentuity Dev Server Source: https://github.com/agentuity/docs/blob/main/content/Reference/CLI/development.mdx Use this command to start the Agentuity development server. It supports hot reload and type checking by default. ```bash agentuity dev # or bun run dev ``` -------------------------------- ### Get JWT Token Source: https://github.com/agentuity/docs/blob/main/content/Frontend/authentication.mdx Retrieve the JWT token within a route handler. The JWKS endpoint is available at GET /api/auth/.well-known/jwks.json for token verification. ```typescript // Get token in route handler const token = await c.var.auth.getToken(); // JWKS endpoint: GET /api/auth/.well-known/jwks.json ``` -------------------------------- ### Create an Agent using Groq SDK Source: https://github.com/agentuity/docs/blob/main/content/Agents/creating-agents.mdx Integrate Groq SDK for fast LLM inference with open-source models. Define input and output schemas. Requires Groq SDK import and client initialization. ```typescript import { createAgent } from '@agentuity/runtime'; import { s } from '@agentuity/schema'; import Groq from 'groq-sdk'; const client = new Groq(); const agent = createAgent('Assistant', { description: 'An agent using Groq SDK with open-source models', schema: { input: s.object({ prompt: s.string() }), output: s.string(), }, handler: async (ctx, { prompt }) => { const completion = await client.chat.completions.create({ model: 'llama-3.3-70b-versatile', messages: [{ role: 'user', content: prompt }], }); return completion.choices[0]?.message?.content ?? ''; }, }); export default agent; ``` -------------------------------- ### Create Pre-configured Node.js TypeScript Environment Source: https://github.com/agentuity/docs/blob/main/content/Services/Sandbox/snapshots.mdx Set up a Node.js environment with TypeScript and related tools. This involves creating a base sandbox, installing global packages, and then creating a snapshot. ```bash # Node.js with TypeScript agentuity cloud sandbox create --runtime bun:1 --network agentuity cloud sandbox exec sbx_... -- npm install -g typescript tsx agentuity cloud sandbox snapshot create sbx_... --tag node-typescript ``` -------------------------------- ### HTTP Routes for Session Management (GET) Source: https://github.com/agentuity/docs/blob/main/content/Learn/Cookbook/Patterns/server-utilities.mdx Defines a GET route to retrieve a chat session by ID from a key-value store. Handles cases where the session does not exist. ```typescript import { createRouter } from '@agentuity/runtime'; const router = createRouter(); interface ChatSession { messages: Array<{ role: string; content: string }>; createdAt: string; updatedAt: string; } // Get a session by ID router.get('/:id', async (c) => { const sessionId = c.req.param('id'); const result = await c.var.kv.get('sessions', sessionId); // [!code highlight] if (!result.exists) { return c.json({ error: 'Session not found' }, 404); } return c.json(result.data); }); ``` -------------------------------- ### Create Multi-Endpoint API with Authentication Source: https://github.com/agentuity/docs/blob/main/content/APIs/calling-agents.mdx This example shows how to create a router with multiple endpoints, including authentication middleware and agent integration for chat, summarization, and analysis. It demonstrates applying middleware to all routes and handling different agent schemas. ```typescript import { createRouter } from '@agentuity/runtime'; import { createMiddleware } from 'hono/factory'; import { s } from '@agentuity/schema'; import chat from '@agent/chat'; import summarizer from '@agent/summarizer'; import sentimentAnalyzer from '@agent/sentiment-analyzer'; import entityExtractor from '@agent/entity-extractor'; const router = createRouter(); // Auth middleware const authMiddleware = createMiddleware(async (c, next) => { const apiKey = c.req.header('X-API-Key'); if (!apiKey) { return c.json({ error: 'API key required' }, 401); } const keyData = await c.var.kv.get('api-keys', apiKey); if (!keyData.exists) { return c.json({ error: 'Invalid API key' }, 401); } c.set('userId', keyData.data.userId); await next(); }); // Apply auth to all routes router.use('/*', authMiddleware); // Chat endpoint - uses chat agent's schema router.post('/chat', chat.validator(), async (c) => { const userId = c.var.userId; const data = c.req.valid('json'); const result = await chat.run({ ...data, userId, }); // Track usage in background c.waitUntil(async () => { await c.var.kv.set('usage', `${userId}:${Date.now()}`, { endpoint: 'chat', tokens: result.tokensUsed, }); }); return c.json(result); }); // Summarization endpoint - uses summarizer's schema router.post('/summarize', summarizer.validator(), async (c) => { const data = c.req.valid('json'); const result = await summarizer.run(data); return c.json(result); }); // Multi-agent analysis - uses custom schema router.post('/analyze', sentimentAnalyzer.validator({ input: s.object({ content: s.string() }), }), async (c) => { const { content } = c.req.valid('json'); // Run multiple agents in parallel const [sentiment, entities, summary] = await Promise.all([ sentimentAnalyzer.run({ text: content }), entityExtractor.run({ text: content }), summarizer.run({ content, maxLength: 100 }), ]); return c.json({ sentiment: sentiment.score, entities: entities.items, summary: summary.text, }); } ); export default router; ``` -------------------------------- ### Create API Route for Product Search Source: https://github.com/agentuity/docs/blob/main/content/Learn/Cookbook/Patterns/product-search.mdx Sets up a GET endpoint '/search' that accepts query parameters for search. It parses 'q', 'category', 'maxPrice', and 'limit' from the request and calls the product search agent. ```typescript import { createRouter } from '@agentuity/runtime'; import productSearch from '@agent/product-search'; const router = createRouter(); router.get('/search', async (c) => { const query = c.req.query('q') || ''; const category = c.req.query('category'); const maxPrice = c.req.query('maxPrice'); const limit = parseInt(c.req.query('limit') || '10'); const result = await productSearch.run({ query, category, maxPrice: maxPrice ? parseFloat(maxPrice) : undefined, limit, }); return c.json(result); }); export default router; ``` -------------------------------- ### Quick Test with Snapshot Dependencies Source: https://github.com/agentuity/docs/blob/main/content/Reference/CLI/sandbox.mdx Runs a Python command using dependencies installed from a specified snapshot. This allows for quick testing of code that relies on specific libraries. ```bash # Test with dependencies from snapshot agentuity cloud sandbox run --snapshot python-ml -- python3 -c "import numpy; print(numpy.array([1,2,3]).mean())" ```