### Install and Start Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/resume-generator/README.md Install dependencies and start the resume generator with a person's name. ```bash npm install npm start "Person Name" ``` -------------------------------- ### Install Dependencies Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/excel-demo/agent/README.md Commands to activate the virtual environment and install dependencies from requirements.txt. ```bash source .venv/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Setup Python Environment Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/excel-demo/README.md Sets up a Python virtual environment and installs requirements. ```bash cd agent python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate pip install -r requirements.txt ``` -------------------------------- ### Quick Start Installation and Execution Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/research-agent/README.md Commands to install dependencies, set the API key, and run the research agent. ```bash # Install dependencies uv sync # Set your API key export ANTHROPIC_API_KEY="your-api-key" # Run the agent uv run python research_agent/agent.py ``` -------------------------------- ### Formula Recalculation Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/excel-demo/agent/README.md Example usage of the formula recalculation script. ```bash python .claude/skills/xlsx/recalc.py Budget_Tracker.csv 30 ``` -------------------------------- ### Install dependencies Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/README.md Instructions to install project dependencies using Bun or npm. ```bash bun install # or npm install ``` -------------------------------- ### Install dependencies Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/excel-demo/README.md Installs project dependencies using npm or bun. ```bash npm install # or bun install ``` -------------------------------- ### Install Dependencies Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/simple-chatapp/README.md Installs the necessary project dependencies. ```bash npm install ``` -------------------------------- ### Running the Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/hello-world/README.md Command to run the hello-world example using tsx. ```bash npx tsx hello-world.ts ``` -------------------------------- ### Install Dependencies Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/README_LISTENER.md Instructions for installing the necessary dependencies for the email listener script, including both a setup script and manual steps. ```bash # Make setup script executable chmod +x setup_listener.sh # Run setup ./setup_listener.sh ``` ```bash # Create virtual environment python3 -m venv venv # Activate it source venv/bin/activate # Install dependencies pip install -r requirements.txt ``` -------------------------------- ### Example Output Format Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/agent/CLAUDE.MD Demonstrates the recommended markdown formatting for presenting email search results, including email references and metadata. ```markdown Found 3 matching emails: - **Quarterly Report Q4** from finance@company.com [email:] *Sent: 2024-01-15 10:30 AM* | 📎 Has attachments - **Invoice #2024-001** from billing@vendor.com [email:] *Sent: 2024-01-14 3:45 PM* | 📎 Has attachments ``` -------------------------------- ### Installation Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/hello-world/README.md Install the necessary packages for the Claude Agent SDK. ```bash npm install @anthropic-ai/claude-agent-sdk typescript @types/node tsx zod ``` -------------------------------- ### Run Example Scripts Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/excel-demo/README.md Runs example Python scripts to create workout and budget trackers. ```bash # Create a workout tracker python create_workout_tracker.py # Create a budget tracker python create_budget_tracker.py ``` -------------------------------- ### Run the Application Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/simple-chatapp/README.md Starts both the backend and frontend development servers. ```bash npm run dev ``` -------------------------------- ### Run the Electron application Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/excel-demo/README.md Starts the Electron application. ```bash npm start # or bun start ``` -------------------------------- ### Create environment file Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/README.md Command to copy the example environment file. ```bash cp .env.example .env ``` -------------------------------- ### UI State Operations (Backend) Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/UI_STATE_SYSTEM.md TypeScript examples for getting and setting UI state within actions/listeners. ```typescript // Get UI state const state = await context.uiState.get(stateId); // Set/update UI state await context.uiState.set(stateId, newState); ``` -------------------------------- ### Agent System Prompt Addition Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/LISTENERS_SPEC.md An example of how to structure a listener file within the agent's system prompt, including available events and context methods. ```typescript import type { ListenerConfig, Email, ListenerContext } from "../types"; export const config: ListenerConfig = { id: "unique_id", name: "Listener Name", enabled: true, event: "email_received" }; export async function handler(email: Email, context: ListenerContext): Promise { // Filter in handler if (!email.from.includes("example@email.com")) return; // Call context methods to make things happen await context.notify("Notification message", { priority: "high" }); await context.starEmail(email.messageId); await context.markAsRead(email.messageId); } ``` -------------------------------- ### Running the App Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/simple-chatapp/CLAUDE.md Commands to install dependencies and run the application. ```bash cd simple-chatapp npm install npm run dev ``` -------------------------------- ### Example Listener Configuration and Handler Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/LISTENERS_SPEC.md A basic TypeScript example demonstrating the structure of a listener file, including configuration and handler function. ```typescript // agent/custom_scripts/listeners/example-listener.ts import type { ListenerConfig, Email, ListenerContext } from "../types"; export const config: ListenerConfig = { id: "unique_listener_id", name: "Human Readable Name", description: "What this listener does", enabled: true, event: "email_received" }; export async function handler(email: Email, context: ListenerContext): Promise { // Filter and custom logic here if (!email.from.includes("example@email.com")) return; // Call context methods to make things happen await context.notify("Notification message", { priority: "high" }); } ``` -------------------------------- ### Parallel Spawning Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/research-agent/research_agent/prompts/lead_agent.txt Demonstrates the correct way to spawn multiple researcher agents simultaneously. ```text GOOD (parallel): - Spawn researcher for subtopic A - Spawn researcher for subtopic B - Spawn researcher for subtopic C - (All run simultaneously) BAD (sequential): - Spawn researcher for subtopic A, wait for completion - Then spawn researcher for subtopic B, wait for completion - Then spawn researcher for subtopic C, wait for completion ``` -------------------------------- ### Example Listener File Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/LISTENERS_SPEC.md An example TypeScript file demonstrating how to create a listener that notifies the user about urgent emails from their boss and stars them. ```typescript // Agent uses Write tool to create: // agent/custom_scripts/listeners/boss-urgent.ts import type { ListenerConfig, Email, ListenerContext } from "../types"; export const config: ListenerConfig = { id: "boss_urgent", name: "Boss Urgent Watcher", enabled: true, event: "email_received" }; export async function handler(email: Email, context: ListenerContext): Promise { // Filter for boss emails with urgent keywords if (!email.from.includes("boss@company.com")) return; const subject = email.subject.toLowerCase(); if (!subject.includes("urgent") && !subject.includes("asap")) return; // Notify await context.notify(`Urgent from boss: ${email.subject}`, { priority: "high" }); // Star for later await context.starEmail(email.messageId); } ``` -------------------------------- ### Example Listener File Structure Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/LISTENERS_SPEC.md Illustrates the directory structure for custom listener scripts within the agent. ```bash agent/custom_scripts/ ├── listeners/ │ ├── boss-urgent-watcher.ts │ ├── daily-summary.ts │ ├── package-tracking.ts │ └── auto-archive-newsletters.ts └── types.ts ``` -------------------------------- ### Task Board Usage - Create Task Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/UI_STATE_SYSTEM.md Example of how to ask the agent to create a task. ```shell Ask the agent: "Create a task to review the quarterly report, high priority, due next Friday" ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/excel-demo/agent/README.md Command to activate the Python virtual environment. ```bash # From the agent folder source .venv/bin/activate ``` -------------------------------- ### System Prompt Addition for Actions Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/ACTIONS_SPEC.md Example of how to add action capabilities to an agent's system prompt, including instructions on how to create actions and a JSON example. ```markdown ## Action Capabilities You can create interactive action buttons that users can click to execute specific operations. ### Available Action Templates: {INSERT LIST OF TEMPLATES HERE - dynamically loaded} ### How to Create Actions: When responding to the user, you can include action instances in your response. The system will automatically render them as clickable buttons. Include actions in a special format: ```json { "actions": [ { "templateId": "send_payment_reminder_acme", "label": "Send payment reminder to ACME Corp for Invoice #2024-001", "params": { "invoiceNumber": "INV-2024-001", "amount": "$5,000", "dueDate": "December 15, 2024", "daysPastDue": 15 }, "style": "primary" } ] } ``` ``` -------------------------------- ### Error Handling: Matplotlib Installation Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/research-agent/research_agent/prompts/data_analyst.txt Instructions to install the matplotlib library if it is not available, which is necessary for generating charts. ```bash pip install matplotlib ``` -------------------------------- ### Structured Tool Calls Log Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/research-agent/README.md Example of structured JSON log output for tool calls. ```json {"event":"tool_call_start","agent_id":"RESEARCHER-1","tool_name":"WebSearch",...} {"event":"tool_call_complete","success":true,"output_size":15234} ``` -------------------------------- ### Gmail IMAP Configuration Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/README.md Example environment file configuration for Gmail IMAP access. ```env ANTHROPIC_API_KEY=your-anthropic-api-key EMAIL_USER=your-email@gmail.com EMAIL_PASSWORD=your-16-char-app-password # NOT your regular password! IMAP_HOST=imap.gmail.com IMAP_PORT=993 ``` -------------------------------- ### PreToolUse Hook Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/hello-world/README.md An example of a `PreToolUse` hook that intercepts tool usage, specifically for file writing operations, to enforce that `.js` and `.ts` files can only be written to the `custom_scripts` directory. ```typescript hooks: { PreToolUse: [ { matcher: "Write|Edit|MultiEdit", hooks: [ async (input: any): Promise => { // Validation logic // Return { continue: true } to allow // Return { decision: 'block', stopReason: '...', continue: false } to deny } ] } ] } ``` -------------------------------- ### Simple Notification Listener Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/LISTENERS_SPEC.md An example of a listener that watches for urgent emails from the boss and notifies immediately, then stars the email. ```typescript // agent/custom_scripts/listeners/boss-urgent-watcher.ts import type { ListenerConfig, Email, ListenerContext } from "../types"; export const config: ListenerConfig = { id: "boss_urgent_watcher", name: "Boss Urgent Email Watcher", description: "Notifies immediately when boss sends urgent emails", enabled: true, event: "email_received" }; export async function handler(email: Email, context: ListenerContext): Promise { // Filter in handler if (!email.from.includes("boss@company.com")) return; const subject = email.subject.toLowerCase(); const isUrgent = subject.includes("urgent") || subject.includes("asap") || subject.includes("important") || subject.includes("critical"); if (!isUrgent) return; // Notify await context.notify(`🚨 Urgent email from boss: "${email.subject}"`, { priority: "high" }); // Also star it for later await context.starEmail(email.messageId); } ``` -------------------------------- ### Agent Creates Actions Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/ACTIONS_SPEC.md An example of how an agent can create action instances during a conversation, including metadata like template ID, label, description, and parameters. ```typescript // Agent's response includes actions metadata // This is handled by the backend Session class { content: "I found that ACME Corp's invoice is 15 days overdue. Here's what you can do:", actions: [ { instanceId: "act_" + generateId(), templateId: "send_payment_reminder_acme", label: "Send payment reminder to ACME Corp for Invoice #2024-001", description: "Invoice #2024-001 ($5,000) is 15 days past due", params: { invoiceNumber: "INV-2024-001", amount: "$5,000", dueDate: "December 15, 2024", daysPastDue: 15 }, style: "primary", sessionId: currentSessionId, createdAt: new Date().toISOString() } ] } ``` -------------------------------- ### Formula Recalculation Script Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/excel-demo/agent/README.md Command to run the formula recalculation script using LibreOffice. ```bash source .venv/bin/activate python .claude/skills/xlsx/recalc.py [timeout_seconds] ``` -------------------------------- ### Finance Email Labeler Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/recursive-code-generation.md An example TypeScript listener that labels finance-related emails, demonstrating both heuristic and AI-powered approaches. ```typescript // agent/custom_scripts/listeners/finance-email-labeler.ts export async function handler(email: Email, context: ListenerContext) { // Option 1: Simple heuristics (current implementation) const hasFinanceKeywords = checkKeywords(email); if (hasFinanceKeywords) { await context.addLabel(email.messageId, "Finance"); } // Option 2: AI-powered (when callAgent is implemented) const analysis = await context.callAgent({ prompt: `Analyze this email and determine if it's finance-related: From: ${email.from} Subject: ${email.subject} Body: ${email.body}`, schema: { type: "object", properties: { isFinance: { type: "boolean" }, category: { type: "string", enum: ["invoice", "payment", "statement"] }, confidence: { type: "number" } } } }); if (analysis.isFinance && analysis.confidence > 0.8) { await context.addLabel(email.messageId, "Finance"); await context.addLabel(email.messageId, analysis.category); } } ``` -------------------------------- ### Running as a Background Service - Using screen Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/README_LISTENER.md Commands to start a screen session, run the listener, and detach from the session. ```bash screen -S email-listener python accounting_email_listener.py # Press Ctrl+A, then D to detach ``` -------------------------------- ### Running as a Background Service - Using cron Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/README_LISTENER.md Example of adding a cron job to run the listener script hourly. ```bash crontab -e # Add this line: 0 * * * * cd /Users/thariq/code/sdk-demos/email-agent && /usr/bin/python3 accounting_email_listener.py ``` -------------------------------- ### Example Subtopics Breakdown Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/research-agent/research_agent/prompts/lead_agent.txt Illustrates how to break down a broad research request into specific subtopics for individual researcher agents. ```text User asks: "Research quantum computing" * Researcher 1: "Current state of quantum hardware and qubit technology" * Researcher 2: "Quantum algorithms and real-world applications" * Researcher 3: "Major companies and investments in quantum computing" * Researcher 4: "Challenges and timeline to practical quantum advantage" ``` -------------------------------- ### UI State Operations Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/UI_STATE_COMPONENTS_SPEC.md TypeScript examples demonstrating how to get and set UI state using the `uiState` context. ```typescript // Get state by ID (returns null if doesn't exist) uiState.get(stateId: string): Promise // Set/update entire state uiState.set(stateId: string, data: T): Promise ``` -------------------------------- ### scheduled_time Listener Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/LISTENERS_SPEC.md Example handler for the 'scheduled_time' event, sending a daily summary. ```typescript export const config: ListenerConfig = { id: "daily_summary", name: "Daily Morning Summary", enabled: true, event: "scheduled_time" }; // Schedule this with cron: "0 9 * * *" in scheduler configuration export async function handler(data: { timestamp: Date }, context: ListenerContext): Promise { await context.notify(`Good morning! Daily summary for ${data.timestamp.toDateString()}`); } ``` -------------------------------- ### email_labeled Listener Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/LISTENERS_SPEC.md Example handler for the 'email_labeled' event, routing workflows based on labels. ```typescript export const config: ListenerConfig = { id: "workflow_router", name: "Workflow Automation Router", enabled: true, event: "email_labeled" }; export async function handler( data: { email: Email, label: string }, context: ListenerContext ): Promise { // Trigger different workflows based on labels if (data.label === "action-required") { await context.starEmail(data.email.messageId); await context.notify(`Action needed: ${data.email.subject}`, { priority: "high" }); } } ``` -------------------------------- ### email_archived Listener Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/LISTENERS_SPEC.md Example handler for the 'email_archived' event, logging important archived emails. ```typescript export const config: ListenerConfig = { id: "track_archived", name: "Track Archived Emails", enabled: true, event: "email_archived" }; export async function handler(email: Email, context: ListenerContext): Promise { // Log important emails that get archived if (!email.from.includes("important-sender.com")) return; await context.notify(`Archived important email: ${email.subject}`, { priority: "low" }); } ``` -------------------------------- ### email_starred Listener Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/LISTENERS_SPEC.md Example handler for the 'email_starred' event, notifying about starred important emails. ```typescript export const config: ListenerConfig = { id: "starred_follow_up", name: "Follow Up on Starred Emails", enabled: true, event: "email_starred" }; export async function handler(email: Email, context: ListenerContext): Promise { const from = email.from.toLowerCase(); if (!from.includes("boss") && !from.includes("client")) return; await context.notify(`Starred important email from ${email.from}`, { priority: "high" }); } ``` -------------------------------- ### email_sent Listener Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/LISTENERS_SPEC.md Example handler for the 'email_sent' event, tracking emails sent to clients. ```typescript export const config: ListenerConfig = { id: "track_client_emails", name: "Track Client Communications", enabled: true, event: "email_sent" }; export async function handler(email: Email, context: ListenerContext): Promise { // Track all emails sent to clients if (!email.to.includes("client")) return; await context.notify(`Sent to client: ${email.subject}`); await context.addLabel(email.messageId, "client-sent"); } ``` -------------------------------- ### Solution for 'ENOENT' errors on spawn Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/hello-world/README.md Ensure the `cwd` directory exists to resolve 'ENOENT' errors on spawn. ```bash mkdir -p agent ``` -------------------------------- ### Transcript Log Example Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/research-agent/README.md Example of human-readable log output for subagent tool calls. ```text [RESEARCHER-1] → WebSearch Input: query='quantum computing 2025' [DATA-ANALYST-1] → Bash Input: python matplotlib chart generation ``` -------------------------------- ### Run the application Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/README.md Commands to run the email agent application using Bun or npm. ```bash bun run dev # or npm run dev ``` -------------------------------- ### Clone the repository Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/excel-demo/README.md Clones the repository and navigates into the excel-demo directory. ```bash git clone https://github.com/anthropics/sdk-demos.git cd sdk-demos/excel-demo ``` -------------------------------- ### Clone the repository Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/README.md Clones the repository to your local machine. ```bash git clone https://github.com/anthropics/claude-agent-sdk-demos.git cd claude-agent-sdk-demos ``` -------------------------------- ### Create Directory Structure Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/hello-world/README.md Create the required directory structure for the agent's working directory and custom scripts. ```bash mkdir -p agent/custom_scripts ``` -------------------------------- ### SDK Configuration Options Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/ask-user-question-previews/README.md Configuration options for the SDK, including system prompt, permission mode, available tools, and tool-specific configuration for AskUserQuestion. ```typescript permissionMode: "plan", // nudges Claude to ask before acting tools: ["AskUserQuestion"], // only this tool is available toolConfig: { askUserQuestion: { previewFormat: "html" } } // adds opt.preview to each option ``` -------------------------------- ### Clone the repository Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/README.md Instructions to clone the repository for the email agent demo. ```bash git clone https://github.com/anthropics/sdk-demos.git cd sdk-demos/email-agent ``` -------------------------------- ### Migration using Bun Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/database/migrations/README.md Execute a SQL migration file programmatically using Bun, reading the SQL content from a file. ```bash bun run -e " import { Database } from 'bun:sqlite'; import { readFileSync } from 'fs'; const db = new Database('database/emails.db'); const migration = readFileSync('database/migrations/add-imap-uid.sql', 'utf-8'); db.exec(migration); console.log('Migration complete!'); " ``` -------------------------------- ### File Structure for UI States Source: https://github.com/anthropics/claude-agent-sdk-demos/blob/main/email-agent/UI_STATE_COMPONENTS_SPEC.md Example file structure for organizing UI state definitions within the agent's custom scripts. ```text agent/custom_scripts/ ├── ui-states/ │ ├── financial-dashboard.ts │ ├── package-tracker.ts │ ├── task-board.ts │ └── [custom-state].ts └── .logs/ └── ui-states/ └── {date}.jsonl ```