### Post-Scaffolding Project Setup Source: https://github.com/agentuity/sdk/blob/main/packages/claude-code/skills/agentuity-project/SKILL.md After creating a new project, navigate into the project directory, install dependencies using `bun install`, and then instruct the user on how to start the development server or deploy the project. ```bash cd my-app bun install # Then tell the user: # "Run `agentuity dev` to start the dev server at http://localhost:3500" # "When ready to ship, run `agentuity deploy`" ``` -------------------------------- ### Run a Web Server in a Sandbox Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/cli/sandbox.mdx This example demonstrates creating a sandbox with a Bun runtime, exposing port 3000, uploading a server file, starting the server, and testing it via its public URL. Ensure you have a compatible runtime like Bun installed. ```bash # Create sandbox with port 3000. The URL is returned immediately. agentuity cloud sandbox create --runtime bun:1 --port 3000 --name my-api # ✓ created sandbox sbx_abc123 in 1200ms # ℹ url: https://my-api-abc123.agentuity.cloud # Upload server code agentuity cloud sandbox fs cp ./server.js sbx_abc123:/home/agentuity/server.js # Start the server agentuity cloud sandbox exec sbx_abc123 -- bun run /home/agentuity/server.js # Test from anywhere using the URL from create curl https://my-api-abc123.agentuity.cloud/api/health ``` -------------------------------- ### Install Dependencies and Run App Source: https://github.com/agentuity/sdk/blob/main/tests/services/db/README.md Install project dependencies using Bun and then run the application. This prepares the environment and starts the test app. ```bash # Install dependencies bun install # Run the test bun run start ``` -------------------------------- ### Quick Start: Create, List, and Get Schedules Source: https://github.com/agentuity/sdk/blob/main/packages/schedule/README.md Demonstrates creating an hourly schedule, listing all schedules, and retrieving details of a specific schedule. ```typescript import { ScheduleClient } from '@agentuity/schedule'; const client = new ScheduleClient(); // Create a schedule that runs every hour const result = await client.create({ name: 'Hourly Sync', expression: '0 * * * *', destinations: [ { type: 'url', config: { url: 'https://example.com/sync' } } ] }); console.log('Created schedule:', result.schedule.id); console.log('Next run:', result.schedule.due_date); // List all schedules const { schedules, total } = await client.list(); console.log(`Found ${total} schedules`); // Get schedule details const { schedule, destinations } = await client.get(result.schedule.id); ``` -------------------------------- ### TanStack Start Server Route Example Source: https://github.com/agentuity/sdk/blob/main/docs/src/agent/chat/agentuity-context.txt Example of a TanStack Start server route handler using KeyValueClient. This pattern is used for file-based routing in TanStack Start applications. ```typescript import { KeyValueClient } from '@agentuity/keyvalue'; import { createFileRoute } from '@tanstack/react-router'; const kv = new KeyValueClient(); export const Route = createFileRoute('/api/visits')({ server: { handlers: { GET: async () => { const current = await kv.get<{ count: number }>('metrics', 'visits'); const count = current.exists ? current.data.count + 1 : 1; await kv.set('metrics', 'visits', { count }, { ttl: null }); return Response.json({ count }); }, }, }, }); ``` -------------------------------- ### Example .env file for deployment Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/cli/deployment.mdx Shows how environment variables are structured in a .env file. Keys starting with AGENTUITY_ are filtered out. ```bash # .env DATABASE_URL=postgres://... WEBHOOK_SECRET=secret123 MY_CUSTOM_API_KEY=xxx ``` -------------------------------- ### Install @agentuity/core Source: https://github.com/agentuity/sdk/blob/main/packages/core/README.md Install the core package using bun. ```bash bun add @agentuity/core ``` -------------------------------- ### Start Development Server Source: https://github.com/agentuity/sdk/blob/main/docs/AGENTS.md Starts the development server for local development and testing. ```bash bun run dev ``` -------------------------------- ### Start Key-Value REPL Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/cli/storage.mdx Initiates an interactive command-line session for exploring and managing Key-Value storage. Use this for faster exploration of commands like set, get, delete, keys, and stats within the REPL. ```bash agentuity cloud kv repl ``` -------------------------------- ### Install Dependencies Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/cookbook/patterns/cron-with-storage.mdx Install the necessary Hono, schedule, keyvalue, and valibot packages. ```bash npm install hono @agentuity/schedule @agentuity/keyvalue valibot ``` -------------------------------- ### Start Local Docs Development Source: https://github.com/agentuity/sdk/blob/main/docs/README.md Run this command from the 'docs' directory to start the local development server for the docs app. This starts both the web app and the docs API server. ```bash cd docs bun run dev ``` -------------------------------- ### Install and Configure Gluon Source: https://github.com/agentuity/sdk/blob/main/packages/cli/docs/localstack-testing-playbook.md Build and install the Gluon CLI. Ensure it is added to your system's PATH for persistent access. Verify the installation by checking the help and version information. ```bash # Build and install gluon cd /home/ubuntu/repos/gluon go install . # Add to PATH (add to ~/.bashrc for persistence) export PATH=$PATH:$HOME/go/bin # Verify installation gluon --help gluon version ``` -------------------------------- ### Install Sandbox Client Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/standalone-packages.mdx Install the standalone sandbox client using npm. ```bash npm install @agentuity/sandbox ``` -------------------------------- ### Install Dependencies Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/sdk-reference/communication.mdx Install the necessary packages for key-value storage and validation. ```bash npm install @agentuity/keyvalue zod ``` -------------------------------- ### Install @agentuity/postgres Source: https://github.com/agentuity/sdk/blob/main/packages/postgres/README.md Install the package using Bun. ```bash bun add @agentuity/postgres ``` -------------------------------- ### Install Vector Client Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/standalone-packages.mdx Install the Vector client package using npm. ```bash npm install @agentuity/vector ``` -------------------------------- ### Install Dependencies Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/cookbook/tutorials/rag-agent.mdx Installs the necessary Hono, Agentuity, and validation libraries for the project. ```bash npm install hono @agentuity/aigateway @agentuity/vector valibot zod ``` -------------------------------- ### Install Dependencies Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/cookbook/patterns/webhook-handler.mdx Install the necessary packages for Hono, Stripe, and Agentuity Queue/KeyValue. ```bash npm install hono stripe @agentuity/queue @agentuity/keyvalue ``` -------------------------------- ### Test Installation Script Source: https://github.com/agentuity/sdk/blob/main/scripts/README.md Used within the CI pipeline to test package installation. ```bash bash scripts/test-install.sh ``` -------------------------------- ### Install Bun Source: https://github.com/agentuity/sdk/blob/main/packages/claude-code/skills/agentuity-project/SKILL.md Installs Bun if it is not already present on the system. Run this command directly. ```bash which bun # If missing: curl -fsSL https://bun.sh/install | bash ``` -------------------------------- ### Install Agentuity CLI Source: https://github.com/agentuity/sdk/blob/main/README.md Install the Agentuity CLI using curl. This is the fastest way to get started. ```bash curl -fsSL https://agentuity.sh | sh ``` -------------------------------- ### Quick Start: Create, Execute, and Manage Sandbox Source: https://github.com/agentuity/sdk/blob/main/packages/sandbox/README.md Demonstrates the basic workflow of creating a sandbox, executing a command, writing and reading files, and finally destroying the sandbox. ```typescript import { SandboxClient } from '@agentuity/sandbox'; const client = new SandboxClient(); // Create a sandbox const sandbox = await client.create(); console.log(`Created sandbox: ${sandbox.id}`); // Execute a command const execution = await sandbox.execute({ command: ['node', '-e', 'console.log("Hello from sandbox!")'] }); console.log(`Execution status: ${execution.status}`); // Write files to the sandbox await sandbox.writeFiles([ { path: '/app/index.js', content: 'console.log("Hello!")' } ]); // Read a file const stream = await sandbox.readFile('/app/index.js'); // Clean up await sandbox.destroy(); ``` -------------------------------- ### Get Tasks API Example Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/api/tasks.mdx Example of how to retrieve a list of tasks using the GET /task endpoint. This is useful for fetching tasks that match specific filters and can be paginated. ```javascript fetch('/task', { method: 'GET', headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` -------------------------------- ### Quick Start: List Models and Complete Text Source: https://github.com/agentuity/sdk/blob/main/packages/aigateway/README.md Initialize the client, list available models, and perform a text completion. Ensure the client is imported correctly. ```typescript import { AIGatewayClient } from '@agentuity/aigateway'; const client = new AIGatewayClient(); const models = await client.listModels(); console.log(Object.keys(models)); const completion = await client.complete({ model: 'openai/gpt-4.1-mini', messages: [{ role: 'user', content: 'Say hello' }], }); console.log(completion.choices?.[0]); ``` -------------------------------- ### Create a Workspace with Setup Inputs Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/cli/coder.mdx Creates a new workspace and configures it with specified dependencies and a setup script. ```bash # Create a workspace with setup inputs agentuity coder workspace create "Node Workspace" --dependency git --setup-script-file ./setup.sh ``` -------------------------------- ### GET Request Example Source: https://github.com/agentuity/sdk/blob/main/packages/core/src/services/api-example.md Demonstrates how to make a GET request with response schema validation. ```APIDOC ## GET /users/{id} ### Description Retrieves a user by their ID and validates the response against a provided schema. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user to retrieve. #### Query Parameters None #### Request Body None ### Request Example ```typescript // Assuming client is an instance of APIClient and UserSchema is defined const user = await client.get('/users/123', UserSchema); ``` ### Response #### Success Response (200) - **user** (UserSchema) - The retrieved user object, validated against UserSchema. #### Response Example ```json { "id": "string", "name": "string", "email": "string" } ``` ``` -------------------------------- ### GET /hub/sessions API Example Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/api/coder.mdx Example of listing sessions with query parameters. Use this to retrieve sessions with specific filters and pagination. ```json GET /hub/sessions?search=my-session&includeArchived=true&limit=10&offset=0&orgId=org_abc ``` -------------------------------- ### Start Deployment Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/api/projects.mdx Initiates a new deployment for a specified project. Requires project ID and can include resource requirements and provisioning mode. Returns deployment details and upload information. ```bash curl POST https://api.agentuity.com/cli/deploy/2/start/proj_abc123 \ -H "Content-Type: application/json" \ -d '{ "resources": { "memory": 512, "cpu": 1 } }' ``` -------------------------------- ### Log in to Agentuity CLI Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/get-started/installation.mdx Authenticates the Agentuity CLI by logging in. This is a one-time setup after installation. ```bash agentuity auth login ``` -------------------------------- ### Example Build Output Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/cli/build-configuration.mdx This is an example of the output you might see during the build process, indicating detected framework and build steps. ```text Detecting framework... Detected nextjs (node) Building with nextjs adapter to .agentuity ✓ Dependencies installed in 510ms ✓ Next.js build completed in 3400ms ✓ Standalone output packaged Build complete (nextjs, 4012ms) ``` -------------------------------- ### Listing Objects with a Prefix Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/services/storage/object.mdx Enumerate stored objects under a specific prefix. This example lists up to 100 objects starting with 'users/'. ```typescript const result = await storage.list({ prefix: 'users/', maxKeys: 100 }); for (const object of result.contents) { console.log(object.key, object.size); } ``` -------------------------------- ### Build CLI Source: https://github.com/agentuity/sdk/blob/main/packages/cli/docs/localstack-testing-playbook.md Navigate to the SDK directory, install dependencies, and build the CLI. This prepares the command-line interface for local testing. ```bash cd /home/ubuntu/repos/sdk bun install bun run build ``` -------------------------------- ### Quick Start: Task Management with TaskClient Source: https://github.com/agentuity/sdk/blob/main/packages/task/README.md Demonstrates basic usage of the TaskClient to create a task, add a comment, manage tags, and list tasks. Ensure TaskClient is imported. ```typescript import { TaskClient } from '@agentuity/task'; const client = new TaskClient(); // Create a task const task = await client.create({ title: 'Implement new feature', description: 'Add support for batch operations', priority: 'high', type: 'feature' }); console.log('Created task:', task.id); // Add a comment await client.createComment(task.id, 'Started working on this task'); // Create and assign tags const tag = await client.createTag('backend', '#3366cc'); await client.addTagToTask(task.id, tag.id); // List tasks const { tasks, total } = await client.list({ status: 'open' }); console.log(`Found ${total} open tasks`); ``` -------------------------------- ### Get Product Recommendation using cURL Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/cookbook/patterns/product-search.mdx Example of requesting a product recommendation using a POST request with cURL and a JSON payload. ```bash curl -X POST http://localhost:3000/api/products/recommend \ -H 'content-type: application/json' \ -d '{ "query": "supportive chair for a long workday" }' ``` -------------------------------- ### Quick Start: Email Client Usage Source: https://github.com/agentuity/sdk/blob/main/packages/email/README.md Demonstrates creating an EmailClient, creating an email address, sending an email, and listing inbound messages. Ensure the EmailClient is imported. ```typescript import { EmailClient } from '@agentuity/email'; const client = new EmailClient(); // Create an email address const addr = await client.createAddress('support'); console.log('Created:', addr.email); // support@agentuity.email // Send an email const result = await client.send({ from: addr.email, to: ['user@example.com'], subject: 'Welcome!', text: 'Welcome to our platform.', html: '

Welcome!

Welcome to our platform.

' }); // List inbound emails const inbound = await client.listInbound(addr.id); for (const msg of inbound) { console.log(`From: ${msg.from}, Subject: ${msg.subject}`); } ``` -------------------------------- ### Get Organizational Webhook Analytics Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/services/webhooks.mdx Retrieve aggregated analytics for all webhooks in an organization, broken down by day. Optional start and end timestamps can be provided. ```typescript const analytics = await webhooks.getOrgAnalytics({ granularity: 'day' }); const series = await webhooks.getOrgTimeSeries({ granularity: 'day' }); ``` -------------------------------- ### Install AI SDK and Google Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/services/ai-gateway.mdx Install the AI SDK and the Google integration package using npm. ```bash npm install ai@latest @ai-sdk/google@latest ``` -------------------------------- ### Create a Workspace with Lead Prompt Guidance Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/cli/coder.mdx Creates a new workspace and configures it with a system prompt, specifying how it should be applied. ```bash # Create a workspace with Lead prompt guidance agentuity coder workspace create "Focused Review" --system-prompt-file ./WORKSPACE_PROMPT.md --system-prompt-mode append ``` -------------------------------- ### Generate Sandbox Snapshot Template Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/cli/sandbox.mdx Generates a template snapshot build file in YAML or JSON format to help you get started with sandbox snapshots. ```bash agentuity cloud sandbox snapshot generate [options] ``` ```bash # Generate YAML template (default) agentuity cloud sandbox snapshot generate > agentuity-snapshot.yaml ``` ```bash # Generate JSON template agentuity cloud sandbox snapshot generate --format json > agentuity-snapshot.json ``` -------------------------------- ### Use Key-Value Service Client Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/services/index.mdx Demonstrates how to use the KeyValueClient to set and get data. Ensure the '@agentuity/keyvalue' package is installed and necessary environment variables are configured. ```typescript import { KeyValueClient } from '@agentuity/keyvalue'; const kv = new KeyValueClient(); await kv.set('cache', 'homepage', { generatedAt: new Date().toISOString() }); const cached = await kv.get<{ readonly generatedAt: string }>('cache', 'homepage'); ``` -------------------------------- ### Agent Handler for Object Storage Operations Source: https://github.com/agentuity/sdk/blob/main/packages/core/docs/objectstore_service_implementation.md Provides an example of an agent handler function that uses `c.objectstore` to perform 'put' and 'get' operations based on incoming commands. ```typescript handler: async (c: AgentContext, { operation, bucket, key, data }) => { switch (operation) { case 'put': { const bytes = new TextEncoder().encode(data); await c.objectstore.put(bucket, key, bytes, { contentType: 'text/plain', }); return { operation, success: true }; } case 'get': { const result = await c.objectstore.get(bucket, key); if (result.exists) { const text = new TextDecoder().decode(result.data); return { operation, success: true, result: { data: text } }; } return { operation, success: false }; } } } ``` -------------------------------- ### Start Deployment Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/api/projects.mdx Initiates a new deployment for a specified project, configuring resources, mode, and dependencies. ```APIDOC ## POST /cli/deploy/2/start/{projectId} ### Description Start a new deployment for a project. ### Method POST ### Endpoint /cli/deploy/2/start/{projectId} ### Parameters #### Path Parameters - **projectId** (string) - Required - Project ID #### Request Body Deployment configuration payload. - **resources** (object) - Optional - the resource requirements for your deployed project - **memory** (string) - Required - The memory requirements - **cpu** (string) - Required - The CPU requirements - **disk** (string) - Required - The disk requirements - **mode** (object) - Optional - the provisioning mode for the project - **type** (string) - Required - on-demand or provisioned - **idle** (string) - Optional - Idle timeout duration when on-demand (e.g., "10m", "1h") - **dependencies** (string[]) - Optional - - **domains** (string[]) - Optional - ### Request Example { "resources": { "memory": 512, "cpu": 1 } } ### Response #### Success Response (201) Deployment started #### Response Fields - **id** (string) - the unique id for the deployment - **orgId** (string) - the organization id - **publicKey** (string) - the public key to use for encrypting the deployment - **buildLogsStreamURL** (string) - the URL for streaming build logs (PUT to write, GET to read) #### Error Response - **401** - Unauthorized — invalid or missing API key - **404** - Project not found ``` -------------------------------- ### Get Log Paths with Agentuity CLI Source: https://github.com/agentuity/sdk/blob/main/packages/cli/LOGGING.md Retrieve the file path for the most recent log session or the general logs directory. Includes an example of copying the log directory. ```bash # Get the path to the most recent session directory agentuity support logs path ``` ```bash # Get the path to the logs directory agentuity support logs path --logs ``` ```bash # Copy logs for sharing cp -r $(agentuity support logs path) ./my-logs ``` -------------------------------- ### Update a Workspace Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/sdk-reference/coder.mdx Use `updateWorkspace` to modify an existing workspace. Provide only the fields you wish to change. This example updates the setup script and system prompt mode for a workspace. ```typescript await client.updateWorkspace('ws_abc123', { setupScript: 'corepack enable && bun install', systemPromptMode: 'overwrite', }); ``` -------------------------------- ### Create a Sandbox with Defaults Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/cli/sandbox.mdx Use this command to create a new sandbox with default settings. This is the simplest way to get a sandbox running. ```bash agentuity cloud sandbox create ``` -------------------------------- ### Search Products by Query String using cURL Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/cookbook/patterns/product-search.mdx Example of searching products using a GET request with cURL, specifying query parameters like 'q' and 'maxPrice'. ```bash curl 'http://localhost:3000/api/products/search?q=comfortable%20office%20chair&maxPrice=300' ``` -------------------------------- ### Build and Pack SDK for Testing Source: https://github.com/agentuity/sdk/blob/main/packages/migrate/test/chain/README.md Prepare the SDK by building and packing it into tarballs for testing purposes. This script is idempotent. ```bash bash scripts/prepare-sdk-for-testing.sh ``` -------------------------------- ### Start Development Server Source: https://github.com/agentuity/sdk/blob/main/skills/agentuity-cli/SKILL.md Run `bun run dev` to start the development server. Pay attention to the terminal output for the correct URL, as it may not always be `localhost:3000`. ```bash bun run dev # Start dev server with hot reload ``` -------------------------------- ### Show Agent Introduction Primer Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/cli/ai-commands.mdx Prints a short primer for coding agents before they modify an Agentuity project. Use this at the start of an agent-driven setup or when an agent joins an existing app. ```bash agentuity ai intro ``` -------------------------------- ### Initialize Node.js SDK with OTLP Exporter Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/cookbook/patterns/opentelemetry-route-spans.mdx Configure and start the Node.js SDK with an OTLP trace exporter. Ensure the OTEL_EXPORTER_OTLP_TRACES_ENDPOINT environment variable is set. This setup should be loaded before your route modules. ```typescript import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'; import { NodeSDK } from '@opentelemetry/sdk-node'; const otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT; if (!otlpEndpoint) { throw new Error('OTEL_EXPORTER_OTLP_TRACES_ENDPOINT is required'); } const sdk = new NodeSDK({ traceExporter: new OTLPTraceExporter({ url: otlpEndpoint, }), instrumentations: [getNodeAutoInstrumentations()], }); sdk.start(); ``` -------------------------------- ### Install Dependencies and Run Test with Bun Source: https://github.com/agentuity/sdk/blob/main/tests/services/storage/README.md Install project dependencies using Bun and then run the storage test application using Bun's runtime. This automatically selects the Bun.S3Client backend. ```bash bun install bun run start:bun ``` -------------------------------- ### Key-Value Storage Operations in Agentuity Source: https://github.com/agentuity/sdk/blob/main/skills/agentuity-agents/SKILL.md Provides examples for setting, getting, and deleting data using the key-value (KV) storage in Agentuity. Values can be set with an optional Time-To-Live (TTL) in seconds. ```typescript // Set a value (with optional TTL in seconds) await ctx.kv.set('namespace', 'key', { data: 'value' }); await ctx.kv.set('cache', 'user:123', userData, { ttl: 3600 }); // Get a value const result = await ctx.kv.get('namespace', 'key'); if (result.exists) { console.log(result.data); } // Delete await ctx.kv.delete('namespace', 'key'); ``` -------------------------------- ### Get and Connect to Existing Sandbox Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/services/sandbox/sdk-usage.mdx Use `client.get()` to retrieve metadata for a specific sandbox and `client.connect()` to establish an interactive session. This example retrieves info, lists files, and then destroys the sandbox. ```typescript import { logger } from '@agentuity/telemetry'; const info = await client.get('sbx_abc123'); logger.info('sandbox info', { status: info.status, createdAt: info.createdAt }); const existing = await client.connect('sbx_abc123'); const files = await existing.listFiles(); logger.info('sandbox files', { files: files.map((file) => file.path) }); await existing.destroy(); ``` -------------------------------- ### Install KeyValue Service Client Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/frameworks/index.mdx Install the direct client for the KeyValue service. This client can be used in various parts of your application, including route handlers and server functions. ```bash npm install @agentuity/keyvalue ``` -------------------------------- ### Install OpenAI SDK and Dependencies Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/build/agents/tool-calling.mdx Install the necessary packages for using the OpenAI SDK and KeyValue client. ```bash npm install openai @agentuity/keyvalue zod ``` -------------------------------- ### Validate and Create Workspace with Dependencies and Setup Script Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/cookbook/patterns/using-workspaces-to-reuse-repos-skills-and-agent-selection.mdx This TypeScript code validates workspace dependencies like 'git', then creates a workspace with specified dependencies and a setup script. It also demonstrates refreshing the workspace snapshot to ensure future sessions start from the prepared state. Use 'systemPromptMode: "append"' for most reusable workspaces. ```typescript import { CoderClient } from '@agentuity/coder'; import { logger } from '@agentuity/telemetry'; const client = new CoderClient(); const dependencyCheck = await client.validateWorkspaceDependencies(['git']); if (dependencyCheck.invalid.length > 0) { logger.warn('workspace dependencies need review', { invalid: dependencyCheck.invalid.map((item) => item.package), }); } const workspace = await client.createWorkspace({ name: 'node-review-workspace', dependencies: ['git'], setupScript: 'corepack enable && bun install', systemPrompt: 'Start by reading package scripts and test setup.', systemPromptMode: 'append', enabledAgents: ['builder', 'reviewer'], }); await client.refreshWorkspaceSnapshot(workspace.id); ``` -------------------------------- ### Fetch API in React Component Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/frameworks/react-router.mdx Use the fetch API from client-side code to interact with API routes. This example shows how to POST data, GET history, and DELETE data from an API endpoint. ```typescript async function translate(text: string, toLanguage: string, model: string) { const response = await fetch('/api/translate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text, toLanguage, model }), }); if (!response.ok) { const err = await response.json().catch(() => ({ error: `HTTP ${response.status}` })); throw new Error(err.error ?? `HTTP ${response.status}`); } return response.json(); } // GET history on mount const history = await fetch('/api/translate').then((r) => r.json()); // DELETE to clear await fetch('/api/translate', { method: 'DELETE' }); ``` -------------------------------- ### Quick Start: Webhook Client Usage Source: https://github.com/agentuity/sdk/blob/main/packages/webhook/README.md Demonstrates creating a webhook, adding a destination, listing receipts, and checking delivery status using the WebhookClient. ```typescript import { WebhookClient } from '@agentuity/webhook'; const client = new WebhookClient(); // Create a webhook const { webhook } = await client.create({ name: 'GitHub Events', description: 'Receives GitHub webhook events' }); console.log('Ingest URL:', webhook.url); // Add a destination await client.createDestination(webhook.id, { type: 'url', config: { url: 'https://example.com/webhook' } }); // List receipts const { receipts } = await client.listReceipts(webhook.id); for (const receipt of receipts) { console.log(`Received: ${receipt.id} at ${receipt.date}`); } // Check delivery status const { deliveries } = await client.listDeliveries(webhook.id); for (const d of deliveries) { console.log(`${d.status} → ${d.webhook_destination_id}`); } ``` -------------------------------- ### Create Custom Routes with Agent Validation Source: https://github.com/agentuity/sdk/blob/main/packages/runtime/README.md Define custom routes using createRouter. This example includes a simple GET route and a POST route that uses an agent's validator and runner for input validation and processing. ```typescript import { createRouter } from '@agentuity/runtime'; import greetingAgent from './agent/greeting'; const router = createRouter(); router.get('/hello', (c) => { return c.json({ message: 'Hello, world!' }); }); // Route with agent validation router.post('/greeting', greetingAgent.validator(), async (c) => { const data = c.req.valid('json'); // Fully typed from agent schema! const result = await greetingAgent.run(data); return c.json(result); }); export default router; ``` -------------------------------- ### Implement Custom Session Store with KeyValueClient Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/services/storage/custom.mdx This example demonstrates how to create a custom session store by implementing a `SessionStore` interface using `KeyValueClient`. It defines `get` and `set` methods for managing session data with a specified TTL. ```typescript import { KeyValueClient } from '@agentuity/keyvalue'; interface Session { readonly userId: string; readonly email: string; } interface SessionStore { get(id: string): Promise; set(id: string, session: Session): Promise; } class AgentuitySessionStore implements SessionStore { readonly #kv = new KeyValueClient(); async get(id: string): Promise { const result = await this.#kv.get('sessions', id); return result.exists ? result.data : undefined; } async set(id: string, session: Session): Promise { await this.#kv.set('sessions', id, session, { ttl: 60 * 60 * 24 * 30, }); } } ``` -------------------------------- ### Get User Preferences with Agentuity OIDC Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/services/authentication.mdx This example demonstrates how to retrieve user preferences using the KeyValueClient after obtaining the user's session. It handles cases where the user is not signed in and provides default preferences if none are found. ```typescript import { KeyValueClient } from '@agentuity/keyvalue'; interface AppUser { readonly id: string; readonly email: string; } interface AppSession { readonly user: AppUser; } interface Preferences { readonly theme: 'light' | 'dark'; } declare function getSession(request: Request): Promise; const kv = new KeyValueClient(); export async function getPreferences(request: Request): Promise { const session = await getSession(request); if (!session) { return Response.json({ error: 'Sign in required' }, { status: 401 }); } const result = await kv.get('user-preferences', session.user.id); return Response.json({ user: session.user, preferences: result.exists ? result.data : { theme: 'light' } satisfies Preferences, }); } ``` -------------------------------- ### Create and Query PostgreSQL Client Source: https://github.com/agentuity/sdk/blob/main/packages/postgres/AGENTS.md Demonstrates how to create a PostgreSQL client instance, either using the default DATABASE_URL or explicit configuration. Shows basic query execution and transaction management. ```typescript import { postgres } from '@agentuity/postgres'; // Create client (uses DATABASE_URL by default) const sql = postgres(); // Or with explicit config const sql = postgres({ hostname: 'localhost', port: 5432, database: 'mydb', reconnect: { maxAttempts: 5, initialDelayMs: 100, }, }); // Query using tagged template literals const users = await sql`SELECT * FROM users WHERE active = ${true}`; // Transactions const tx = await sql.begin(); try { await tx`INSERT INTO users (name) VALUES (${name})`; await tx.commit(); } catch (error) { await tx.rollback(); throw error; } ``` -------------------------------- ### Install Dependencies Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/cookbook/patterns/product-search.mdx Install the necessary Hono, Agentuity, and Zod packages for the product search functionality. ```bash npm install hono @agentuity/aigateway @agentuity/vector zod ``` -------------------------------- ### Define Typed Hono Routes Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/cookbook/patterns/hono-rpc-tanstack-query.mdx Define Hono routes with Zod validation for request bodies. Export the router type to enable type-safe client-side calls. This example includes GET, POST, and DELETE methods for user management. ```typescript import { Hono } from 'hono'; import { zValidator } from '@hono/zod-validator'; import { z } from 'zod'; const createUserSchema = z.object({ name: z.string().min(1), email: z.string().email(), }); const router = new Hono() .get('/users', async (c) => { const users = [ { id: '1', name: 'Alice', email: 'alice@example.com' }, { id: '2', name: 'Bob', email: 'bob@example.com' }, ]; return c.json({ users }); }) .get('/users/:id', async (c) => { const id = c.req.param('id'); return c.json({ id, name: 'Alice', email: 'alice@example.com' }); }) .post('/users', zValidator('json', createUserSchema), async (c) => { const body = c.req.valid('json'); const user = { id: crypto.randomUUID(), ...body }; return c.json({ user }, 201); }) .delete('/users/:id', async (c) => { const id = c.req.param('id'); return c.json({ deleted: id }); }); export type UsersRoute = typeof router; export default router; ``` -------------------------------- ### Initialize App Setup and Shared State Source: https://github.com/agentuity/sdk/blob/main/skills/agentuity-agents/SKILL.md Use `createApp` in `app.ts` to set up shared resources like databases. These resources are then accessible via `ctx.app` in all agents. ```typescript import { createApp } from '@agentuity/runtime'; const { server, logger } = await createApp({ setup: async () => { const db = await connectDatabase(); return { db }; // Available as ctx.app.db in all agents }, shutdown: async (state) => { await state.db.close(); }, }); ``` -------------------------------- ### Install Bun Runtime Source: https://github.com/agentuity/sdk/blob/main/packages/claude-code/AGENTS.md Command to install the Bun runtime environment if it is not already installed. Bun is required for running Agentuity projects. ```bash curl -fsSL https://bun.sh/install | bash ``` -------------------------------- ### Marketplace Plugin Installation Commands Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/cli/claude-code-plugin.mdx These commands are used to add and install the Agentuity plugin from the Claude Code marketplace for a permanent installation. ```text /plugin marketplace add agentuity/sdk /plugin install agentuity-coder@agentuity ``` -------------------------------- ### Test Package Installation Source: https://github.com/agentuity/sdk/blob/main/scripts/README.md Installs all published SDK packages into a temporary project and verifies that imports function correctly. ```bash bash scripts/test-package-install.sh ``` -------------------------------- ### Remove GitHub App Installation Source: https://github.com/agentuity/sdk/blob/main/docs/src/web/content/reference/cli/git-integration.mdx Remove a specific GitHub App installation. You can remove a specific installation by its ID or remove the default one. ```bash agentuity git account remove ``` ```bash # Remove a specific installation without prompts agentuity git account remove --account inst_xyz --confirm ``` -------------------------------- ### Quick Start: CoderClient Usage Source: https://github.com/agentuity/sdk/blob/main/packages/coder/README.md Demonstrates common operations like listing, creating, and managing sessions and workspaces using the CoderClient. Ensure you have imported CoderClient. ```typescript import { CoderClient } from '@agentuity/coder'; const client = new CoderClient(); // List sessions const { sessions } = await client.listSessions({ limit: 10 }); for (const session of sessions) { console.log(`${session.sessionId}: ${session.label} (${session.status})`); } // Create a new session const session = await client.createSession({ task: 'Implement feature X', workflowMode: 'standard', }); console.log(`Created session: ${session.sessionId}`); // Create a session from a saved workspace const workspaceSession = await client.createSession({ task: 'Test workspace startup', workspaceId: 'ws_...', }); console.log(`Created workspace session: ${workspaceSession.sessionId}`); // Manage workspace snapshot inputs const validation = await client.validateWorkspaceDependencies(['git', 'nodejs']); if (validation.invalid.length > 0) { throw new Error(validation.invalid.map((pkg) => pkg.error).join(', ')); } const workspace = await client.createWorkspace({ name: 'Node workspace', scope: 'org', dependencies: ['git', 'nodejs'], setupScript: 'corepack enable', }); await client.updateWorkspace(workspace.id, { setupScript: 'corepack enable && bun install', }); await client.refreshWorkspaceSnapshot(workspace.id); // Get session details const details = await client.getSession(session.sessionId); console.log(`Task: ${details.task}`); // Archive a session await client.archiveSession(session.sessionId); ```