### GET /tools/list - List All Registered Tools Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Returns all dynamically created tools with their purposes and callable methods. ```APIDOC ## GET /tools/list - List All Registered Tools ### Description Returns all dynamically created tools with their purposes and callable methods. ### Method GET ### Endpoint /tools/list ### Response #### Success Response (200) - **tools** (array) - A list of registered tools. - **name** (string) - The name of the tool. - **class_name** (string) - The class name of the tool. - **code_version_id** (string) - The version ID of the tool's code. - **purpose** (string) - The purpose of the tool. - **methods** (array) - A list of methods available for the tool. - **name** (string) - The name of the method. - **description** (string) - A description of the method. - **params** (array of strings) - The parameters the method accepts. - **created_at** (integer) - Timestamp when the tool was created. #### Response Example ```json { "tools": [ { "name": "WaterTracker", "class_name": "FacetTool", "code_version_id": "WaterTracker-1719835200000", "purpose": "Track daily water intake in milliliters", "methods": [ {"name": "logIntake", "description": "Record/log new data", "params": ["amount"]}, {"name": "getTodayTotal", "description": "Get summary/totals", "params": []}, {"name": "getHistory", "description": "Get historical entries", "params": []} ], "created_at": 1719835200000 } ] } ``` ``` -------------------------------- ### Get Tool Source Code Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Retrieves the raw AI-generated source code for a specific tool by name. ```bash curl -X GET "https://your-worker.workers.dev/tools/code?name=WaterTracker" ``` -------------------------------- ### GET /tools/code - Get Tool Source Code Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Retrieves the AI-generated source code for a specific tool. ```APIDOC ## GET /tools/code - Get Tool Source Code ### Description Retrieves the AI-generated source code for a specific tool. ### Method GET ### Endpoint /tools/code ### Parameters #### Query Parameters - **name** (string) - Required - The name of the tool whose source code is to be retrieved. ### Request Example ```bash curl -X GET "https://your-worker.workers.dev/tools/code?name=WaterTracker" ``` ### Response #### Success Response (200) - The response body contains the source code of the requested tool as a string. #### Response Example ```javascript // Example response for WaterTracker tool code export class WaterTracker { constructor(state, env) { this.state = state; this.env = env; } async logIntake(amount) { const currentData = await this.state.storage.get('intakeData') || []; const newData = [...currentData, { amount, timestamp: Date.now() }]; await this.state.storage.put('intakeData', newData); return { ok: true }; } async getTodayTotal() { const intakeData = await this.state.storage.get('intakeData') || []; const today = new Date().setHours(0, 0, 0, 0); const total = intakeData .filter(entry => entry.timestamp >= today) .reduce((sum, entry) => sum + entry.amount, 0); return { total }; } async getHistory() { return await this.state.storage.get('intakeData') || []; } } ``` ``` -------------------------------- ### GET /api - API Information Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Returns API metadata including available routes and the AI model being used. ```APIDOC ## GET /api - API Information ### Description Returns API metadata including available routes and the AI model being used. ### Method GET ### Endpoint /api ### Response #### Success Response (200) - **name** (string) - The name of the project. - **routes** (array of strings) - A list of available API routes. - **model** (string) - The AI model currently in use. #### Response Example ```json { "name": "Project Hephaestus", "routes": ["/chat", "/tools/list", "/tools/create", "/tools/call", "/tools/destroy", "/tools/code"], "model": "@cf/zai-org/glm-4.7-flash" } ``` ``` -------------------------------- ### Wrangler Configuration for Hephaestus Deployment Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Configuration for deploying Hephaestus with required bindings for Durable Objects, Worker Loaders, and Workers AI. Includes static asset configuration and migration setup for SQLite. ```jsonc { "$schema": "node_modules/wrangler/config-schema.json", "name": "agents-week-demo", "main": "src/index.ts", "compatibility_date": "2026-04-01", "compatibility_flags": ["nodejs_compat"], // Static assets for the chat UI "assets": { "directory": "./public" }, // Durable Object binding for the supervisor "durable_objects": { "bindings": [ { "class_name": "SupervisorDO", "name": "SUPERVISOR" } ] }, // Worker Loader for dynamic tool deployment "worker_loaders": [ { "binding": "LOADER" } ], // Workers AI binding "ai": { "binding": "AI" }, // SQLite migrations for the supervisor "migrations": [ { "new_sqlite_classes": ["MyDurableObject"], "tag": "v1" }, { "renamed_classes": [{"from": "MyDurableObject", "to": "SupervisorDO"}], "tag": "v2" } ] } ``` -------------------------------- ### POST /tools/create - Create a New Tool Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Generates and deploys a new tool using AI code generation based on the provided name and purpose. ```APIDOC ## POST /tools/create - Create a New Tool ### Description Generates and deploys a new tool using AI code generation. The AI writes a Durable Object class based on the provided name and purpose. ### Method POST ### Endpoint /tools/create ### Parameters #### Request Body - **name** (string) - Required - The desired name for the new tool. - **purpose** (string) - Required - A description of the tool's functionality. ### Request Example ```json { "name": "TodoList", "purpose": "Manage a simple todo list with add, complete, and list operations" } ``` ### Response #### Success Response (200) - **name** (string) - The name of the created tool. - **purpose** (string) - The purpose of the tool. - **codeVersionId** (string) - The version ID of the tool's code. - **methods** (array) - A list of methods available for the tool. - **name** (string) - The name of the method. - **description** (string) - A description of the method. - **params** (array of strings) - The parameters the method accepts. - **alreadyExisted** (boolean) - Indicates if a tool with the same name already existed. #### Response Example ```json { "name": "TodoList", "purpose": "Manage a simple todo list with add, complete, and list operations", "codeVersionId": "TodoList-1719835300000", "methods": [ {"name": "addTodo", "description": "Record/log new data", "params": ["text"]}, {"name": "completeTodo", "description": "Update data", "params": ["id"]}, {"name": "listTodos", "description": "Get historical entries", "params": []} ], "alreadyExisted": false } ``` ``` -------------------------------- ### Retrieve API Metadata Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Fetches general information about the project, including available endpoints and the AI model in use. ```bash curl -X GET https://your-worker.workers.dev/api ``` -------------------------------- ### Create a New Tool Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Triggers AI code generation to create and deploy a new Durable Object tool based on the provided name and purpose. ```bash curl -X POST https://your-worker.workers.dev/tools/create \ -H "Content-Type: application/json" \ -d '{"name": "TodoList", "purpose": "Manage a simple todo list with add, complete, and list operations"}' ``` -------------------------------- ### List Registered Tools Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Retrieves a list of all dynamically created tools, including their purposes and available methods. ```bash curl -X GET https://your-worker.workers.dev/tools/list ``` -------------------------------- ### Call Tool Method Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Invokes a specific method on a registered tool. Requires the tool name, method name, and arguments. ```bash # Add a todo item curl -X POST https://your-worker.workers.dev/tools/call \ -H "Content-Type: application/json" \ -d '{"name": "TodoList", "method": "addTodo", "args": ["Buy groceries"]}' # List all todos curl -X POST https://your-worker.workers.dev/tools/call \ -H "Content-Type: application/json" \ -d '{"name": "TodoList", "method": "listTodos", "args": []}' ``` -------------------------------- ### Create Workers AI Supervisor Model Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Creates an AI SDK compatible model for streaming text using the `workers-ai-provider`. It initializes the provider with the `env.AI` binding and specifies the AI model to use. ```typescript // Create AI SDK compatible model for streamText import { createWorkersAI } from "workers-ai-provider"; export function createSupervisorModel(env: Env) { const workersai = createWorkersAI({ binding: env.AI }); return workersai(AI_MODEL); // "@cf/zai-org/glm-4.7-flash" } ``` -------------------------------- ### POST /tools/call - Call a Tool Method Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Invokes a specific method on a registered tool with the provided arguments. ```APIDOC ## POST /tools/call - Call a Tool Method ### Description Invokes a specific method on a registered tool with the provided arguments. ### Method POST ### Endpoint /tools/call ### Parameters #### Request Body - **name** (string) - Required - The name of the tool to call. - **method** (string) - Required - The name of the method to invoke on the tool. - **args** (array) - Required - An array of arguments to pass to the method. ### Request Example ```json # Add a todo item { "name": "TodoList", "method": "addTodo", "args": ["Buy groceries"] } # List all todos { "name": "TodoList", "method": "listTodos", "args": [] } ``` ### Response #### Success Response (200) - **tool** (string) - The name of the tool that was called. - **method** (string) - The name of the method that was invoked. - **result** (any) - The result returned by the tool method. The structure of this field depends on the specific tool and method called. #### Response Example ```json # Example for addTodo method { "tool": "TodoList", "method": "addTodo", "result": {"ok": true, "id": 1, "text": "Buy groceries", "createdAt": 1719835400000} } # Example for listTodos method { "tool": "TodoList", "method": "listTodos", "result": [ {"id": 1, "text": "Buy groceries", "completed": 0, "created_at": 1719835400000} ] } ``` ``` -------------------------------- ### SupervisorDO Class - Core Durable Object Methods Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Documentation for the core methods of the SupervisorDO class, which orchestrates tool management and interactions. ```APIDOC ## SupervisorDO Class ### Core Durable Object Methods The SupervisorDO class is the central orchestrator that handles all requests and manages the tool lifecycle. ### createTool #### Description Creates a new tool using AI code generation. It normalizes the name, generates code via AI, stores it in SQLite, and creates a facet. #### Parameters - **name** (string) - Required - The name of the tool to create. - **purpose** (string) - Required - The purpose of the tool. #### Returns - **name** (string) - The name of the created tool. - **purpose** (string) - The purpose of the created tool. - **codeVersionId** (string) - The version ID of the generated code. - **methods** (array) - An array of method descriptors for the tool. - **alreadyExisted** (boolean) - Indicates if a tool with the same name already existed. ### callTool #### Description Calls a method on any registered tool. It retrieves the tool, gets the facet stub, and invokes the specified method with the provided arguments. #### Parameters - **name** (string) - Required - The name of the tool. - **method** (string) - Required - The name of the method to call on the tool. - **args** (array) - Required - An array of arguments to pass to the method. #### Returns - (any) - The result of the method call on the tool. ### destroyTool #### Description Deletes a tool and cleans up associated resources, including its Durable Object facet and stored code. #### Parameters - **name** (string) - Required - The name of the tool to delete. #### Returns - void ### handleChatStream #### Description Handles streaming chat interactions with an AI model using the Vercel AI SDK. It sets up the model, system prompt, user prompt, and available tools, and returns a streaming response. #### Parameters - **message** (string) - Required - The user's chat message. #### Returns - Response - A streaming response object. ``` -------------------------------- ### Implement SupervisorDO Orchestrator Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Central class for managing tool lifecycles, routing requests, and handling AI streaming interactions. ```typescript import { DurableObject } from "cloudflare:workers"; import { Hono } from "hono"; import { streamText, tool } from "ai"; import { z } from "zod"; export class SupervisorDO extends DurableObject { private readonly router: Hono; constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); // Initialize SQLite schema for tool registry this.ctx.blockConcurrencyWhile(async () => this.initializeSchema()); this.router = createSupervisorRouter(this); } // All HTTP requests are handled by the Hono router async fetch(request: Request): Promise { return this.router.fetch(request, this.env); } // Create a new tool using AI code generation async createTool(name: string, purpose: string): Promise<{ name: string; purpose: string; codeVersionId: string; methods: MethodDescriptor[]; alreadyExisted: boolean; }> { // Normalizes name, generates code via AI, stores in SQLite, creates facet } // Call a method on any registered tool async callTool(name: string, method: string, args: unknown[]): Promise { const tool = this.getTool(name); const facet = this.getFacetStub(tool.name, tool.code_version_id, tool.class_name); const rpc = facet as Record Promise>; return rpc[method](...args); } // Delete a tool and clean up resources async destroyTool(name: string): Promise { this.ctx.facets.delete(normalizedName); this.ctx.storage.sql.exec("DELETE FROM tool_registry WHERE name = ?", normalizedName); } // Handle streaming chat with AI using Vercel AI SDK handleChatStream(message: string): Response { const result = streamText({ model: createSupervisorModel(this.env), system: buildAgentSystemPrompt(), prompt: message, tools: { list_tools: tool({ /* ... */ }), create_tool: tool({ /* ... */ }), call_tool: tool({ /* ... */ }), // Plus dynamically registered tool methods }, stopWhen: stepCountIs(20), }); return result.toUIMessageStreamResponse(); } } ``` -------------------------------- ### Destroy a Tool via API Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Sends a POST request to remove a tool from the registry and clean up associated resources. ```bash curl -X POST https://your-worker.workers.dev/tools/destroy \ -H "Content-Type: application/json" \ -d '{"name": "TodoList"}' ``` -------------------------------- ### Send AI Chat Request Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Sends a message to the supervisor. The response is a Server-Sent Events (SSE) stream containing tool inputs, outputs, and text deltas. ```bash curl -X POST https://your-worker.workers.dev/chat \ -H "Content-Type: application/json" \ -d '{"message": "Track my water intake. I just drank 500ml."}' ``` -------------------------------- ### WaterTracker API Endpoints Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt This section details the available methods for interacting with the WaterTracker Durable Object. ```APIDOC ## POST /logIntake ### Description Records a new water intake entry. ### Method POST ### Endpoint /logIntake ### Parameters #### Request Body - **amount** (number) - Required - The amount of water intake in milliliters. ### Request Example ```json { "amount": 500 } ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the operation was successful. - **amount** (number) - The logged amount of water intake. - **loggedAt** (number) - The timestamp when the intake was logged. #### Response Example ```json { "ok": true, "amount": 500, "loggedAt": 1719835200000 } ``` ## GET /getTodayTotal ### Description Retrieves the total water intake for the current day. ### Method GET ### Endpoint /getTodayTotal ### Response #### Success Response (200) - **total** (number) - The total amount of water intake for the current day in milliliters. #### Response Example ```json { "total": 1500 } ``` ## GET /getHistory ### Description Retrieves a list of historical water intake entries, limited to the 50 most recent entries. ### Method GET ### Endpoint /getHistory ### Response #### Success Response (200) - **id** (number) - The unique identifier for the intake entry. - **amount** (number) - The amount of water intake in milliliters. - **logged_at** (number) - The timestamp when the intake was logged. #### Response Example ```json [ { "id": 1, "amount": 500, "logged_at": 1719835200000 }, { "id": 2, "amount": 750, "logged_at": 1719748800000 } ] ``` ``` -------------------------------- ### POST /chat - AI Chat with Streaming Response Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Sends a message to the AI supervisor and receives a streaming response. The AI can use built-in tools and dynamically registered tools. ```APIDOC ## POST /chat - AI Chat with Streaming Response ### Description Sends a message to the AI supervisor and receives a streaming response. The AI can use built-in tools (list_tools, create_tool, call_tool) and any dynamically registered tools to fulfill requests. ### Method POST ### Endpoint /chat ### Parameters #### Request Body - **message** (string) - Required - The user's message to the AI. ### Request Example ```json { "message": "Track my water intake. I just drank 500ml." } ``` ### Response #### Success Response (200) - The response is a Server-Sent Events (SSE) stream containing various event types such as `tool-input-available`, `tool-output-available`, `text-delta`, and `[DONE]`. #### Response Example ``` data: {"type":"tool-input-available","toolName":"create_tool","toolCallId":"abc123","input":{"name":"WaterTracker","purpose":"Track daily water intake in milliliters"}} data: {"type":"tool-output-available","toolCallId":"abc123"} data: {"type":"tool-input-available","toolName":"call_tool","toolCallId":"def456","input":{"name":"WaterTracker","method":"logIntake","args":[500]}} data: {"type":"tool-output-available","toolCallId":"def456"} data: {"type":"text-delta","delta":"I've created a water tracker and logged your 500ml intake!"} data: [DONE] ``` ``` -------------------------------- ### POST /tools/destroy - Delete a Tool Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Removes a tool from the registry and cleans up its Durable Object facet and stored code. ```APIDOC ## POST /tools/destroy ### Description Removes a tool from the registry and cleans up its Durable Object facet and stored code. ### Method POST ### Endpoint /tools/destroy ### Parameters #### Request Body - **name** (string) - Required - The name of the tool to delete. ### Request Example ```bash curl -X POST https://your-worker.workers.dev/tools/destroy \ -H "Content-Type: application/json" \ -d '{"name": "TodoList"}' ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the operation was successful. - **deleted** (string) - The name of the deleted tool. #### Response Example ```json { "ok": true, "deleted": "TodoList" } ``` ``` -------------------------------- ### Define WaterTracker Durable Object Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Implements a Durable Object for tracking water intake with SQLite persistence. Requires Cloudflare Workers environment. ```typescript import { DurableObject } from "cloudflare:workers"; export class FacetTool extends DurableObject { constructor(ctx, env) { super(ctx, env); this.sql = ctx.storage.sql; this.sql.exec("CREATE TABLE IF NOT EXISTS intake (id INTEGER PRIMARY KEY AUTOINCREMENT, amount INTEGER NOT NULL, logged_at INTEGER NOT NULL)"); } async logIntake(amount) { const now = Date.now(); this.sql.exec("INSERT INTO intake (amount, logged_at) VALUES (?, ?)", amount, now); return { ok: true, amount, loggedAt: now }; } async getTodayTotal() { const startOfDay = new Date().setHours(0,0,0,0); const rows = this.sql.exec("SELECT SUM(amount) as total FROM intake WHERE logged_at >= ?", startOfDay).toArray(); return { total: rows[0]?.total || 0 }; } async getHistory() { return this.sql.exec("SELECT id, amount, logged_at FROM intake ORDER BY logged_at DESC LIMIT 50").toArray(); } } ``` -------------------------------- ### Extract Method Signatures from Generated Code Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Extracts method signatures from generated JavaScript code. It parses `async methodName(params)` patterns, skipping common methods like `constructor`, `fetch`, and `alarm`. The `MethodDescriptor` type is used to store extracted information. ```typescript // Extract method signatures from generated code export function extractMethods(code: string): MethodDescriptor[] { const methods: MethodDescriptor[] = []; const pattern = /async\s+(\w+)\s*\(([^)]*)\)/g; const skip = new Set(["constructor", "fetch", "alarm"]); let match; while ((match = pattern.exec(code)) !== null) { const methodName = match[1]; if (!skip.has(methodName)) { const params = match[2].split(",").map((p) => p.trim()).filter(Boolean); methods.push({ name: methodName, description: inferMethodDescription(methodName), params }); } } return methods; } ``` -------------------------------- ### Core TypeScript Type Definitions Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Defines essential TypeScript types used throughout the application, including descriptors for tool methods, records for tool registry and code versions, request bodies for chat and tool APIs, AI call options, and chat message formats. ```typescript // Method descriptor for tool RPC methods export type MethodDescriptor = { name: string; description: string; params: string[]; }; // Tool registry record stored in SQLite export type ToolRecord = { name: string; class_name: string; code_version_id: string; purpose: string; methods: string; // JSON stringified MethodDescriptor[] created_at: number; }; // Tool code version stored in SQLite export type ToolCodeRecord = { code_version_id: string; module_code: string; created_at: number; }; // Chat API request body export type ChatBody = { message: string; }; // Tool API request body export type ToolBody = { name: string; purpose?: string; method?: string; args?: unknown[]; }; // AI call options export type RunAiOptions = { maxCompletionTokens?: number; timeoutMs?: number; }; // Chat message format export type ChatMessage = { role: "system" | "user" | "assistant"; content: string; }; ``` -------------------------------- ### Call Workers AI with Timeout Handling Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Low-level function to call Workers AI with timeout handling and response extraction. It uses `withTimeout` to enforce a specified timeout and `extractTextFromAiResponse` to process the AI's reply. Ensure `env.AI` is bound. ```typescript import { AI_MODEL } from "../constants"; import type { ChatMessage, RunAiOptions } from "../types"; const DEFAULT_TIMEOUT_MS = 20_000; export async function runAi( env: Env, messages: ChatMessage[], options: RunAiOptions = {} ): Promise { const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; const payload = { messages, max_completion_tokens: options.maxCompletionTokens ?? 500, chat_template_kwargs: { enable_thinking: false }, }; const raw = await withTimeout(env.AI.run(AI_MODEL, payload), timeoutMs); return extractTextFromAiResponse(raw); } ``` -------------------------------- ### Generate JavaScript Durable Object Code Source: https://context7.com/apeacock1991/agents-week-demo-2026/llms.txt Generates JavaScript Durable Object code using Workers AI based on the tool name and purpose. Requires a `runAiFn` that handles AI calls and returns raw completion. Ensure the generated code includes `export class ${FACET_CLASS_NAME}` and `async `. ```typescript import { FACET_CLASS_NAME } from "../constants"; import { buildCodePrompt } from "../prompts"; import type { ChatMessage, RunAiOptions } from "../types"; export async function generateToolCode( name: string, purpose: string, runAiFn: (messages: ChatMessage[], options?: RunAiOptions) => Promise, ): Promise { const codePrompt = buildCodePrompt(name, purpose); const raw = await runAiFn( [ { role: "system", content: "You write compact, valid JavaScript Durable Object classes..." }, { role: "user", content: codePrompt } ], { maxCompletionTokens: 900, timeoutMs: 25_000 } ); let code = stripCodeFences(raw); code = fixCommonSqlMistakes(code); if (code.includes(`export class ${FACET_CLASS_NAME}`) && code.includes("async ")) { return code; } throw new Error(`AI returned invalid tool code for "${name}" (${purpose})`); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.