@standardagents/agentbuilder-template 0.15.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,59 +1,49 @@
1
- declare const ROOT_CLAUDE_MD = "# Standard Agents\n\nThis project uses Standard Agents - a framework for building AI agents on Cloudflare Workers.\n\n## Architecture Overview\n\nStandard Agents uses a **composition model** where four core components work together:\n\n```\nModel \u2192 Prompt \u2192 Agent \u2192 Thread\n \u2502 \u2502 \u2502 \u2502\n \u2502 \u2502 \u2502 \u2514\u2500 Conversation instance (Durable Object)\n \u2502 \u2502 \u2514\u2500 Orchestrates conversation flow\n \u2502 \u2514\u2500 System instructions + tools\n \u2514\u2500 LLM provider configuration\n```\n\n**Models** define which LLM to use (provider, model ID, pricing, fallbacks).\n**Prompts** define what the LLM should do (system instructions, available tools).\n**Agents** orchestrate conversations (which prompt, stop conditions, turn limits).\n**Threads** are individual conversation instances with persistent storage.\n\n## How Components Compose\n\n### Basic Flow\n1. User creates a thread with an agent\n2. Agent uses its configured prompt\n3. Prompt specifies the model and tools\n4. LLM responds, potentially calling tools\n5. Tools execute and return results\n6. Loop continues until stop condition\n\n### Sub-Prompts (Prompts as Tools)\nPrompts can call other prompts as tools. This enables:\n- **Specialized reasoning**: A main prompt delegates to expert sub-prompts\n- **Structured outputs**: Sub-prompt validates and formats data\n- **Context isolation**: Sub-prompt gets fresh context without full history\n\n```typescript\n// Main prompt can call 'data_extractor' as a tool\ndefinePrompt({\n name: 'main_assistant',\n tools: ['data_extractor'], // Another prompt exposed as tool\n // ...\n});\n```\n\n### Agent Handoffs (Agents as Tools)\nAgents can delegate to other agents entirely:\n- **Specialization**: Route to domain-specific agents\n- **Escalation**: Hand off to more capable agents\n- **Workflows**: Chain agents for multi-step processes\n\n```typescript\ndefineAgent({\n name: 'triage_agent',\n exposeAsTool: true,\n toolDescription: 'Hand off to triage for initial assessment',\n // ...\n});\n```\n\n## File Structure\n\n```\nagents/\n\u251C\u2500\u2500 CLAUDE.md # This file\n\u251C\u2500\u2500 Thread.ts # Durable Object for conversation threads\n\u251C\u2500\u2500 AgentBuilder.ts # Durable Object for metadata\n\u251C\u2500\u2500 agents/ # Agent definitions (defineAgent)\n\u2502 \u2514\u2500\u2500 CLAUDE.md\n\u251C\u2500\u2500 prompts/ # Prompt definitions (definePrompt)\n\u2502 \u2514\u2500\u2500 CLAUDE.md\n\u251C\u2500\u2500 models/ # Model configurations (defineModel)\n\u2502 \u2514\u2500\u2500 CLAUDE.md\n\u251C\u2500\u2500 tools/ # Custom tools (defineTool)\n\u2502 \u2514\u2500\u2500 CLAUDE.md\n\u251C\u2500\u2500 hooks/ # Lifecycle hooks (defineHook)\n\u2502 \u2514\u2500\u2500 CLAUDE.md\n\u2514\u2500\u2500 api/ # Thread API endpoints (defineThreadEndpoint)\n \u2514\u2500\u2500 CLAUDE.md\n```\n\nFiles are **auto-discovered** at runtime. No manual registration needed.\n\n## ThreadState\n\n`ThreadState` is the state object available in tools and hooks:\n\n```typescript\ninterface ThreadState {\n // Identity (readonly)\n threadId: string; // Thread identifier\n agentId: string; // Agent identifier\n userId: string | null; // User identifier (if set)\n createdAt: number; // Creation timestamp\n children: SubagentRegistryEntry[]; // Resumable child registry\n terminated: number | null; // Soft-termination timestamp\n\n // Methods\n getMessages(options?): Promise<MessagesResult>; // Get conversation history\n injectMessage(input): Promise<Message>; // Add message to thread\n queueMessage(input): Promise<void>; // Queue message for next step\n loadModel(name): Promise<ModelConfig>; // Load model definition\n loadPrompt(name): Promise<PromptConfig>; // Load prompt definition\n loadAgent(name): Promise<AgentConfig>; // Load agent definition\n env(propertyName): Promise<string>; // Resolve env value for this thread\n setEnv(propertyName, value): Promise<void>; // Set thread env + propagate to active descendants\n getValue<T = unknown>(key: string): Promise<T | null>; // Read durable per-thread JSON value\n setValue(key: string, value: unknown): Promise<void>; // Write durable value; null/undefined deletes\n notifyParent(content): Promise<void>; // Explicitly queue a silent message to the parent\n setStatus(status): Promise<void>; // Update this child in the parent registry\n getChildThread(referenceId): Promise<ThreadState | null>; // Resolve child thread\n getParentThread(): Promise<ThreadState | null>; // Resolve parent thread\n terminate(): Promise<void>; // Soft-terminate thread\n runCode(source, options?): CodeExecution; // Run JS/TS in a fresh Dynamic Worker sandbox\n}\n```\n\n`runCode` has no implicit access to thread state, filesystem, network, timers, or host globals. Bridge only the exact capabilities needed through `imports` or `globals`; use `modules` for local relative ES modules; use `execute` to select the export and args to run. `modules` keys are graph-root relative paths; entry-source imports resolve from `filename` when supplied, including `../` parent paths that stay inside the supplied graph. TypeScript input is accepted by default and erased before evaluation. In thread endpoints, `runCode` is forwarded into the thread Durable Object; pass plain transferable options there and keep function-backed bridges in tools or in-thread execution contexts.\n\n## Subagents\n\n`dual_ai` agents can be used as subagents from prompt tool configs:\n\n- Each subagent runs in its own thread (`DurableThread`)\n- Parent/child linkage is tracked in thread metadata\n- Resumable children are visible in `state.children`\n- Parent threads create/message resumable children via built-ins (`subagent_create`, `subagent_message`)\n- Child completion results are queued back to the parent when `parentCommunication` is `implicit`\n- Explicit relationships can stay idle until code calls `state.notifyParent()` or `state.setStatus()`\n\nAccess in tools:\n```typescript\nexport default defineTool('...', schema, async (state, args) => {\n const threadId = state.threadId;\n const { messages } = await state.getMessages();\n const count = (await state.getValue<number>('invocation_count')) ?? 0;\n await state.setValue('invocation_count', count + 1);\n // ...\n});\n```\n\nAccess in hooks:\n```typescript\nexport default defineHook({\n hook: 'before_create_message',\n id: 'my_hook',\n execute: async (state, message) => {\n console.log(`Thread: ${state.threadId}, Agent: ${state.agentId}`);\n return message;\n }\n});\n```\n\n## Quick Reference\n\n| Function | Purpose | Directory |\n|----------|---------|-----------|\n| `defineModel()` | Configure LLM provider | `agents/models/` |\n| `definePrompt()` | System instructions + tools | `agents/prompts/` |\n| `defineAgent()` | Conversation orchestration | `agents/agents/` |\n| `defineTool()` | Custom tool functions | `agents/tools/` |\n| `defineHook()` | Lifecycle interception | `agents/hooks/` |\n| `defineThreadEndpoint()` | Custom API routes | `agents/api/` |\n\n## Runtime Utilities\n\nImport from `@standardagents/builder`:\n\n```typescript\nimport {\n queueTool, // Queue another tool for execution\n injectMessage, // Add message without triggering execution\n getMessages, // Retrieve message history\n emitThreadEvent, // Send custom WebSocket events\n} from '@standardagents/builder';\n```\n\n## Documentation\n\nFull documentation: https://docs.standardagentbuilder.com\n\n- [Architecture Overview](https://docs.standardagentbuilder.com/introduction/architecture)\n- [Models](https://docs.standardagentbuilder.com/core-concepts/models)\n- [Prompts](https://docs.standardagentbuilder.com/core-concepts/prompts)\n- [Agents](https://docs.standardagentbuilder.com/core-concepts/agents)\n- [Tools](https://docs.standardagentbuilder.com/core-concepts/tools)\n- [Hooks](https://docs.standardagentbuilder.com/core-concepts/hooks)\n- [ThreadState](https://docs.standardagentbuilder.com/core-concepts/threadstate)\n- [Thread API](https://docs.standardagentbuilder.com/core-concepts/api)\n";
1
+ declare const ROOT_AGENTS_MD = "# Standard Agents\n\nThis project uses Standard Agents - a framework for building AI agents on Cloudflare Workers.\n\n## Architecture Overview\n\nStandard Agents uses a **composition model** where four core components work together:\n\n```\nModel \u2192 Prompt \u2192 Agent \u2192 Thread\n \u2502 \u2502 \u2502 \u2502\n \u2502 \u2502 \u2502 \u2514\u2500 Conversation instance (Durable Object)\n \u2502 \u2502 \u2514\u2500 Orchestrates conversation flow\n \u2502 \u2514\u2500 System instructions + tools\n \u2514\u2500 LLM provider configuration\n```\n\n**Models** define which LLM to use (provider, model ID, pricing, fallbacks).\n**Prompts** define what the LLM should do (system instructions, available tools).\n**Agents** orchestrate conversations (which prompt, stop conditions, turn limits).\n**Threads** are individual conversation instances with persistent storage.\n\n## How Components Compose\n\n### Basic Flow\n1. User creates a thread with an agent\n2. Agent uses its configured prompt\n3. Prompt specifies the model and tools\n4. LLM responds, potentially calling tools\n5. Tools execute and return results\n6. Loop continues until stop condition\n\n### Sub-Prompts (Prompts as Tools)\nPrompts can call other prompts as tools. This enables:\n- **Specialized reasoning**: A main prompt delegates to expert sub-prompts\n- **Structured outputs**: Sub-prompt validates and formats data\n- **Context isolation**: Sub-prompt gets fresh context without full history\n\n```typescript\n// Main prompt can call 'data_extractor' as a tool\ndefinePrompt({\n name: 'main_assistant',\n tools: ['data_extractor'], // Another prompt exposed as tool\n // ...\n});\n```\n\n### Agent Handoffs (Agents as Tools)\nAgents can delegate to other agents entirely:\n- **Specialization**: Route to domain-specific agents\n- **Escalation**: Hand off to more capable agents\n- **Workflows**: Chain agents for multi-step processes\n\n```typescript\ndefineAgent({\n name: 'triage_agent',\n exposeAsTool: true,\n toolDescription: 'Hand off to triage for initial assessment',\n // ...\n});\n```\n\n## File Structure\n\n```\nAGENTS.md # Project guidance for AI coding tools\nCLAUDE.md -> AGENTS.md # Compatibility symlink\nvite.config.ts # Uses builder(); Cloudflare config is generated\ntsconfig.json # Includes agents and generated .agents types\nagents/\n\u251C\u2500\u2500 agents/ # Agent definitions (defineAgent)\n\u2502 \u251C\u2500\u2500 AGENTS.md\n\u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n\u251C\u2500\u2500 prompts/ # Prompt definitions (definePrompt)\n\u2502 \u251C\u2500\u2500 AGENTS.md\n\u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n\u251C\u2500\u2500 models/ # Model configurations (defineModel)\n\u2502 \u251C\u2500\u2500 AGENTS.md\n\u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n\u251C\u2500\u2500 tools/ # Custom tools (defineTool)\n\u2502 \u251C\u2500\u2500 AGENTS.md\n\u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n\u251C\u2500\u2500 hooks/ # Lifecycle hooks (defineHook)\n\u2502 \u251C\u2500\u2500 AGENTS.md\n\u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n\u2514\u2500\u2500 api/ # Thread API endpoints (defineThreadEndpoint)\n \u251C\u2500\u2500 AGENTS.md\n \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n```\n\nThe `builder()` Vite plugin generates the Worker entry, Durable Object bindings, Cloudflare Vite plugin configuration, and local `.agents/` support files at build time. Agent files are **auto-discovered** at runtime. No manual registration needed.\n\n## ThreadState\n\n`ThreadState` is the state object available in tools and hooks:\n\n```typescript\ninterface ThreadState {\n // Identity (readonly)\n threadId: string; // Thread identifier\n agentId: string; // Agent identifier\n userId: string | null; // User identifier (if set)\n createdAt: number; // Creation timestamp\n children: SubagentRegistryEntry[]; // Resumable child registry\n terminated: number | null; // Soft-termination timestamp\n\n // Methods\n getMessages(options?): Promise<MessagesResult>; // Get conversation history\n injectMessage(input): Promise<Message>; // Add message to thread\n queueMessage(input): Promise<void>; // Queue message for next step\n loadModel(name): Promise<ModelConfig>; // Load model definition\n loadPrompt(name): Promise<PromptConfig>; // Load prompt definition\n loadAgent(name): Promise<AgentConfig>; // Load agent definition\n env(propertyName): Promise<string>; // Resolve env value for this thread\n setEnv(propertyName, value): Promise<void>; // Set thread env + propagate to active descendants\n getValue<T = unknown>(key: string): Promise<T | null>; // Read durable per-thread JSON value\n setValue(key: string, value: unknown): Promise<void>; // Write durable value; null/undefined deletes\n notifyParent(content): Promise<void>; // Explicitly queue a silent message to the parent\n setStatus(status): Promise<void>; // Update this child in the parent registry\n getChildThread(referenceId): Promise<ThreadState | null>; // Resolve child thread\n getParentThread(): Promise<ThreadState | null>; // Resolve parent thread\n terminate(): Promise<void>; // Soft-terminate thread\n runCode(source, options?): CodeExecution; // Run JS/TS in a fresh Dynamic Worker sandbox\n}\n```\n\n`runCode` has no implicit access to thread state, filesystem, network, timers, or host globals. Bridge only the exact capabilities needed through `imports` or `globals`; use `modules` for local relative ES modules; use `execute` to select the export and args to run. `modules` keys are graph-root relative paths; entry-source imports resolve from `filename` when supplied, including `../` parent paths that stay inside the supplied graph. TypeScript input is accepted by default and erased before evaluation. In thread endpoints, `runCode` is forwarded into the thread Durable Object; pass plain transferable options there and keep function-backed bridges in tools or in-thread execution contexts.\n\n## Subagents\n\n`dual_ai` agents can be used as subagents from prompt tool configs:\n\n- Each subagent runs in its own thread (`DurableThread`)\n- Parent/child linkage is tracked in thread metadata\n- Resumable children are visible in `state.children`\n- Parent threads create/message resumable children via built-ins (`subagent_create`, `subagent_message`)\n- Child completion results are queued back to the parent when `parentCommunication` is `implicit`\n- Explicit relationships can stay idle until code calls `state.notifyParent()` or `state.setStatus()`\n\nAccess in tools:\n```typescript\nexport default defineTool('...', schema, async (state, args) => {\n const threadId = state.threadId;\n const { messages } = await state.getMessages();\n const count = (await state.getValue<number>('invocation_count')) ?? 0;\n await state.setValue('invocation_count', count + 1);\n // ...\n});\n```\n\nAccess in hooks:\n```typescript\nexport default defineHook({\n hook: 'before_create_message',\n id: 'my_hook',\n execute: async (state, message) => {\n console.log(`Thread: ${state.threadId}, Agent: ${state.agentId}`);\n return message;\n }\n});\n```\n\n## Quick Reference\n\n| Function | Purpose | Directory |\n|----------|---------|-----------|\n| `defineModel()` | Configure LLM provider | `agents/models/` |\n| `definePrompt()` | System instructions + tools | `agents/prompts/` |\n| `defineAgent()` | Conversation orchestration | `agents/agents/` |\n| `defineTool()` | Custom tool functions | `agents/tools/` |\n| `defineHook()` | Lifecycle interception | `agents/hooks/` |\n| `defineThreadEndpoint()` | Custom API routes | `agents/api/` |\n\n## Runtime Utilities\n\nImport from `@standardagents/builder`:\n\n```typescript\nimport {\n queueTool, // Queue another tool for execution\n injectMessage, // Add message without triggering execution\n getMessages, // Retrieve message history\n emitThreadEvent, // Send custom WebSocket events\n} from '@standardagents/builder';\n```\n\n## Documentation\n\nFull documentation: https://docs.standardagentbuilder.com\n\n- [Architecture Overview](https://docs.standardagentbuilder.com/introduction/architecture)\n- [Models](https://docs.standardagentbuilder.com/core-concepts/models)\n- [Prompts](https://docs.standardagentbuilder.com/core-concepts/prompts)\n- [Agents](https://docs.standardagentbuilder.com/core-concepts/agents)\n- [Tools](https://docs.standardagentbuilder.com/core-concepts/tools)\n- [Hooks](https://docs.standardagentbuilder.com/core-concepts/hooks)\n- [ThreadState](https://docs.standardagentbuilder.com/core-concepts/threadstate)\n- [Thread API](https://docs.standardagentbuilder.com/core-concepts/api)\n";
2
2
 
3
- declare const MODELS_CLAUDE_MD = "# Model Definitions\n\nModels define which LLM provider and model to use for prompts.\n\n## Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `name` | `string` | Yes | Unique identifier for this model configuration |\n| `provider` | `'openai' \\| 'anthropic' \\| 'openrouter' \\| 'google' \\| 'cerebras' \\| 'groq' \\| 'xai'` | Yes | LLM provider |\n| `model` | `string` | Yes | Model ID sent to provider API |\n| `fallbacks` | `string[]` | No | Fallback model names to try if primary fails |\n| `inputPrice` | `number` | No | Cost per 1M input tokens (USD) |\n| `outputPrice` | `number` | No | Cost per 1M output tokens (USD) |\n| `cachedPrice` | `number` | No | Cost per 1M cached input tokens |\n| `includedProviders` | `string[]` | No | Provider prefixes for OpenRouter routing |\n| `providerTools` | `string[]` | No | Provider-built-in tool names to make available for prompts using this model |\n\n## Example\n\n```typescript\nimport { defineModel } from '@standardagents/builder';\n\nexport default defineModel({\n name: 'default',\n provider: 'openrouter',\n model: 'google/gemini-3-flash-preview',\n fallbacks: ['fast', 'cheap-heavy'],\n});\n```\n\n## Provider Tools\n\nProviders can expose built-in tools such as search, file search, code execution,\nor provider-specific tools through their `getTools()` implementation. Enable the\nprovider tool names on the model with `providerTools`; prompts can then include\nthose tools like normal tool names. Provider tools execute on the upstream\nprovider, not in AgentBuilder, and successful calls are logged as provider tool\nentries.\n\nOpenRouter exposes `web_search`, `web_fetch`, `datetime`, and `image_generation`\nas provider-executed server tools. Configure optional OpenRouter parameters with\n`providerOptions.serverTools` on the model.\n\n## Recommended Models (OpenRouter)\n\n| Use Case | Model ID | Description |\n|----------|----------|-------------|\n| Fast/Cheap | `z-ai/glm-4.5-air` | Quick responses, low cost |\n| Mid-tier | `google/gemini-3-flash-preview` | Good balance of speed and quality |\n| Cheap Heavy | `z-ai/glm-4.7` | More capable, still affordable |\n| Heavy | `google/gemini-3-pro-preview` | Most capable, for complex tasks |\n\n**\u26A0\uFE0F Google Models**: When using Google models (`google/gemini-*`), you must enable `reasoning` in your prompt configuration or tool calls will fail. See the prompts CLAUDE.md for details.\n\n## Provider API Keys\n\nSet these environment variables in `.dev.vars` (local) or Cloudflare secrets (production):\n\n| Provider | Environment Variable |\n|----------|---------------------|\n| Cerebras | `CEREBRAS_API_KEY` |\n| Groq | `GROQ_API_KEY` |\n| OpenAI | `OPENAI_API_KEY` |\n| Anthropic | `ANTHROPIC_API_KEY` |\n| OpenRouter | `OPENROUTER_API_KEY` |\n| Google | `GOOGLE_API_KEY` |\n| xAI | `XAI_API_KEY` |\n\nIf `STANDARD_AGENTS_API_KEY` is present and a provider-specific key is not set,\nfirst-party Standard Agents providers route through the hosted Standard Agents\nrouter. Setting a provider-specific key always uses that provider directly.\n\n## Fallback Strategy\n\nWhen a model fails, fallbacks are tried in order:\n1. Primary model (2 attempts)\n2. First fallback (2 attempts)\n3. Second fallback (2 attempts)\n4. ...and so on\n\nRetries occur on: network errors, rate limits (429), server errors (5xx), auth errors (401).\n\n## OpenRouter Configuration\n\nFor OpenRouter, use the full model path:\n\n```typescript\nexport default defineModel({\n name: 'heavy',\n provider: 'openrouter',\n model: 'google/gemini-3-pro-preview',\n includedProviders: ['google'], // Prefer Google's servers\n});\n```\n\n## Best Practices\n\n- **Name by use case**, not model ID (e.g., `fast`, `default`, `heavy`)\n- **Configure fallbacks** for production reliability\n- **Set pricing** for cost tracking in logs when your provider or runtime does not supply it automatically\n- **Cerebras note:** documented Cerebras models have built-in fallback pricing for request logs, but custom/private Cerebras models should still set `inputPrice` and `outputPrice`\n- **Use environment variables** for API keys, never hardcode\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/model\n";
3
+ declare const MODELS_AGENTS_MD = "# Model Definitions\n\nModels define which LLM provider and model to use for prompts.\n\n## Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `name` | `string` | Yes | Unique identifier for this model configuration |\n| `provider` | `'openai' \\| 'anthropic' \\| 'openrouter' \\| 'google' \\| 'cerebras' \\| 'groq' \\| 'xai'` | Yes | LLM provider |\n| `model` | `string` | Yes | Model ID sent to provider API |\n| `fallbacks` | `string[]` | No | Fallback model names to try if primary fails |\n| `inputPrice` | `number` | No | Cost per 1M input tokens (USD) |\n| `outputPrice` | `number` | No | Cost per 1M output tokens (USD) |\n| `cachedPrice` | `number` | No | Cost per 1M cached input tokens |\n| `includedProviders` | `string[]` | No | Provider prefixes for OpenRouter routing |\n| `providerTools` | `string[]` | No | Provider-built-in tool names to make available for prompts using this model |\n\n## Example\n\n```typescript\nimport { defineModel } from '@standardagents/builder';\n\nexport default defineModel({\n name: 'default',\n provider: 'openrouter',\n model: 'google/gemini-3-flash-preview',\n fallbacks: ['fast', 'cheap-heavy'],\n});\n```\n\n## Provider Tools\n\nProviders can expose built-in tools such as search, file search, code execution,\nor provider-specific tools through their `getTools()` implementation. Enable the\nprovider tool names on the model with `providerTools`; prompts can then include\nthose tools like normal tool names. Provider tools execute on the upstream\nprovider, not in AgentBuilder, and successful calls are logged as provider tool\nentries.\n\nOpenRouter exposes `web_search`, `web_fetch`, `datetime`, and `image_generation`\nas provider-executed server tools. Configure optional OpenRouter parameters with\n`providerOptions.serverTools` on the model.\n\n## Recommended Models (OpenRouter)\n\n| Use Case | Model ID | Description |\n|----------|----------|-------------|\n| Fast/Cheap | `z-ai/glm-4.5-air` | Quick responses, low cost |\n| Mid-tier | `google/gemini-3-flash-preview` | Good balance of speed and quality |\n| Cheap Heavy | `z-ai/glm-4.7` | More capable, still affordable |\n| Heavy | `google/gemini-3-pro-preview` | Most capable, for complex tasks |\n\n**\u26A0\uFE0F Google Models**: When using Google models (`google/gemini-*`), you must enable `reasoning` in your prompt configuration or tool calls will fail. See the prompts AGENTS.md for details.\n\n## Provider API Keys\n\nSet these environment variables in `.dev.vars` (local) or Cloudflare secrets (production):\n\n| Provider | Environment Variable |\n|----------|---------------------|\n| Cerebras | `CEREBRAS_API_KEY` |\n| Groq | `GROQ_API_KEY` |\n| OpenAI | `OPENAI_API_KEY` |\n| Anthropic | `ANTHROPIC_API_KEY` |\n| OpenRouter | `OPENROUTER_API_KEY` |\n| Google | `GOOGLE_API_KEY` |\n| xAI | `XAI_API_KEY` |\n\nIf `STANDARD_AGENTS_API_KEY` is present and a provider-specific key is not set,\nfirst-party Standard Agents providers route through the hosted Standard Agents\nrouter. Setting a provider-specific key always uses that provider directly.\n\n## Fallback Strategy\n\nWhen a model fails, fallbacks are tried in order:\n1. Primary model (2 attempts)\n2. First fallback (2 attempts)\n3. Second fallback (2 attempts)\n4. ...and so on\n\nRetries occur on: network errors, rate limits (429), server errors (5xx), auth errors (401).\n\n## OpenRouter Configuration\n\nFor OpenRouter, use the full model path:\n\n```typescript\nexport default defineModel({\n name: 'heavy',\n provider: 'openrouter',\n model: 'google/gemini-3-pro-preview',\n includedProviders: ['google'], // Prefer Google's servers\n});\n```\n\n## Best Practices\n\n- **Name by use case**, not model ID (e.g., `fast`, `default`, `heavy`)\n- **Configure fallbacks** for production reliability\n- **Set pricing** for cost tracking in logs when your provider or runtime does not supply it automatically\n- **Cerebras note:** documented Cerebras models have built-in fallback pricing for request logs, but custom/private Cerebras models should still set `inputPrice` and `outputPrice`\n- **Use environment variables** for API keys, never hardcode\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/model\n";
4
4
 
5
- declare const PROMPTS_CLAUDE_MD = "# Prompt Definitions\n\nPrompts define system instructions, model selection, and available tools for LLM interactions.\n\n## Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `name` | `string` | Yes | Unique identifier for this prompt |\n| `toolDescription` | `string` | Yes | Description shown when used as a tool |\n| `prompt` | `string \\| StructuredPrompt` | Yes | System instructions |\n| `model` | `string` | Yes | Model name to use (references `agents/models/`) |\n| `tools` | `(string \\| ToolConfig \\| SubagentToolConfig)[]` | No | Available tools (include ai_human agent names for handoffs and dual_ai subagent configs) |\n| `includeChat` | `boolean` | No | Include full conversation history |\n| `includePastTools` | `boolean` | No | Include previous tool results |\n| `parallelToolCalls` | `boolean` | No | Allow multiple concurrent tool calls |\n| `toolChoice` | `'auto' \\| 'none' \\| 'required'` | No | Tool calling strategy |\n| `requiredSchema` | `z.ZodObject` | No | Input validation when called as tool |\n| `variables` | `VariableDefinition[]` | No | Variable declarations (`name`, `type`, `required`, `scoped`, `description`) |\n| `env` | `Record<string, string>` | No | Prompt-level default values for variables |\n| `hooks` | `string[]` | No | Hook IDs to run for this prompt (overrides agent hooks) |\n| `reasoning` | `ReasoningConfig` | No | Extended thinking configuration |\n\n## Basic Example\n\n```typescript\nimport { definePrompt } from '@standardagents/builder';\n\nexport default definePrompt({\n name: 'customer_support',\n toolDescription: 'Handle customer support inquiries',\n model: 'default',\n prompt: `You are a helpful customer support agent.\nAlways be polite and professional.\nIf you cannot help, escalate to a human.`,\n tools: ['search_knowledge_base', 'create_ticket'],\n includeChat: true,\n});\n```\n\n## Structured Prompts\n\nInclude other prompts for reusable instruction blocks:\n\n```typescript\nexport default definePrompt({\n name: 'main_assistant',\n toolDescription: 'Primary assistant',\n model: 'default',\n prompt: [\n { type: 'text', content: 'You are a helpful assistant.\\n\\n' },\n { type: 'include', prompt: 'common_rules' }, // Includes another prompt\n { type: 'env', property: 'ASSISTANT_TONE' }, // Inject variable value\n { type: 'text', content: '\\n\\nBe concise.' },\n ],\n});\n```\n\n`type: 'env'` inserts a resolved thread variable value. Use this only for non-secret values that are safe to expose to the LLM.\n\nThe sandboxed coding prompt declares `HTTP_HOST` as a text variable. Its URL helper uses that value as the origin for files exposed from the thread `public/` directory and endpoints exposed from the thread `api/` directory. Public URLs should usually omit extensions; extensionless public paths resolve `.html`, then `.js`, then `.ts`, then matching `index` files in the same order. Browser pages should reference only public files, `api/` endpoints, or absolute external URLs, using relative asset URLs like `./app` and `./api/todos`; private `src/` files are not served directly. Public `.ts` files are transformed to browser JavaScript and are not server endpoints. Server-side endpoints live under the thread filesystem `api/` directory, and the `api/` directory name stays in the public URL: `api/todo.ts` is `/api/threads/{threadId}/api/todo`, while `api/todo.ts` is not `/api/threads/{threadId}/todo` or `/api/threads/{threadId}/todos`. Endpoint files default-export a function that accepts `Request` and returns `Response` or `Promise<Response>`. Endpoint code can import `fetch`, `fs`, and `storage`, and can import private helpers with relative paths such as `../src/todo.ts`. When the coding agent creates a site, page, or endpoint, it should call `get_public_url` with the created file path and use the returned URL.\n\nSandboxed code and `api/` endpoints can persist small JSON-serializable runtime data through `import { storage } from \"storage\"`. Use `storage.get`, `storage.set`, `storage.delete`, and `storage.has` with stable logical keys. Do not expose, mention, or depend on internal storage key prefixes.\n\nThe sandboxed coding prompt includes `delete_file` for removing files or empty directories from the thread filesystem. Use it to clean up obsolete implementation files, stale public assets, and abandoned endpoint routes after the replacement is working.\n\n## Tool Configuration\n\nTools can be simple names or detailed configs:\n\n```typescript\ntools: [\n 'simple_tool', // Just the tool name\n {\n name: 'complex_tool',\n includeTextResponse: true, // Include sub-prompt text in result\n includeToolCalls: false, // Exclude sub-prompt tool calls\n includeErrors: true, // Include error details\n initUserMessageProperty: 'query', // Use this arg as initial message\n },\n],\n```\n\nProvider-built-in tools use the same `tools` list once the selected model enables\nthem with `providerTools`. AgentBuilder passes them to the provider and records\nprovider-reported calls in request logs; it does not execute those tools locally.\nGenerated prompt files may store these selections as `provider:<toolName>` to\ndistinguish provider tools from local tools with the same name.\n\n### Subagent Tool Configuration\n\nUse `SubagentToolConfig` when the tool is a `dual_ai` agent:\n\n```typescript\ntools: [\n // Blocking, non-resumable (default)\n { name: 'data_processor_agent' },\n\n // Non-blocking, resumable with a single instance\n {\n name: 'browser_agent',\n blocking: false,\n immediate: {\n nameEnv: 'BROWSER_AGENT_NAME',\n descriptionEnv: 'BROWSER_AGENT_DESCRIPTION',\n scopedEnv: ['BROWSER_AGENT_API_KEY'],\n },\n optional: 'ENABLE_BROWSER_AGENT',\n initAgentNameProperty: 'name',\n resumable: {\n receives_messages: 'side_a',\n maxInstances: 1,\n parentCommunication: 'explicit',\n },\n },\n]\n```\n\nWhen prompt-configured resumable dual_ai subagents exist, the runtime auto-injects:\n- `subagent_create` for spawning new child instances\n- `subagent_message` for messaging active resumable instances\n\n`subagent_create` requires a non-empty `name` for human-friendly child thread labels.\nAgentBuilder stores that argument as a `name:<value>` thread tag.\n\nSet `immediate: true` to run a tool automatically when the prompt activates.\nUse `immediate: { nameEnv, descriptionEnv, scopedEnv }` when you want safe per-instance bootstrap hints while keeping copied scoped env runtime-only.\nSet `optional: 'ENV_NAME'` to enable a subagent branch only when env resolves to `true`, `1`, or `yes`.\nSet `resumable.parentCommunication: 'explicit'` when the child should stay quiet until its own tools or hooks call `state.notifyParent()` or `state.setStatus()`.\nIf required scoped vars are missing, the runtime returns `error_code: \"subagent_env_required\"` with a temporary `GET/POST /api/threads/:threadId/variables/:requestId` endpoint in `error_data.endpoint`.\n\n## Input Validation\n\nValidate inputs when prompt is called as a tool:\n\n```typescript\nimport { z } from 'zod';\n\nexport default definePrompt({\n name: 'data_extractor',\n toolDescription: 'Extract structured data from text',\n model: 'default',\n prompt: 'Extract the requested data from the input.',\n requiredSchema: z.object({\n text: z.string().describe('Text to extract from'),\n fields: z.array(z.string()).describe('Fields to extract'),\n }),\n});\n```\n\n## Extended Thinking (Reasoning)\n\nEnable for complex reasoning tasks:\n\n```typescript\nexport default definePrompt({\n name: 'code_reviewer',\n toolDescription: 'Review code for issues',\n model: 'heavy',\n prompt: 'Review the code thoroughly...',\n reasoning: {\n effort: 'high', // 'low' | 'medium' | 'high'\n maxTokens: 16000, // Max thinking tokens\n exclude: true, // Don't include thinking in response\n },\n});\n```\n\n**\u26A0\uFE0F Google Models Require Reasoning**: When using Google models (`google/gemini-*`) via OpenRouter, you **must** include `reasoning` configuration or tool calls will fail. At minimum:\n\n```typescript\nreasoning: {\n effort: 'low', // Can be 'low', 'medium', or 'high'\n},\n```\n\n## Hooks\n\nAttach lifecycle hooks to a prompt:\n\n```typescript\nexport default definePrompt({\n name: 'customer_support',\n toolDescription: 'Handle customer support',\n model: 'default',\n prompt: 'You are a support agent...',\n hooks: ['limit_to_20', 'redact_pii'], // Hook IDs from agents/hooks/\n});\n```\n\nPrompt hooks take precedence over agent hooks. See `agents/hooks/CLAUDE.md` for details.\n\n## Best Practices\n\n- **Write clear instructions** - Structure with headers and bullet points\n- **Describe tools thoroughly** - LLMs decide based on descriptions\n- **Validate inputs with Zod** - Catch errors early\n- **Use `includeChat`** for conversational context\n- **Name by purpose**, not model (e.g., `support_agent` not `gpt4_prompt`)\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/prompt\n";
5
+ declare const PROMPTS_AGENTS_MD = "# Prompt Definitions\n\nPrompts define system instructions, model selection, and available tools for LLM interactions.\n\n## Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `name` | `string` | Yes | Unique identifier for this prompt |\n| `toolDescription` | `string` | Yes | Description shown when used as a tool |\n| `prompt` | `string \\| StructuredPrompt` | Yes | System instructions |\n| `model` | `string` | Yes | Model name to use (references `agents/models/`) |\n| `tools` | `(string \\| ToolConfig \\| SubagentToolConfig)[]` | No | Available tools (include ai_human agent names for handoffs and dual_ai subagent configs) |\n| `includeChat` | `boolean` | No | Include full conversation history |\n| `includePastTools` | `boolean` | No | Include previous tool results |\n| `parallelToolCalls` | `boolean` | No | Allow multiple concurrent tool calls |\n| `toolChoice` | `'auto' \\| 'none' \\| 'required'` | No | Tool calling strategy |\n| `requiredSchema` | `z.ZodObject` | No | Input validation when called as tool |\n| `variables` | `VariableDefinition[]` | No | Variable declarations (`name`, `type`, `required`, `scoped`, `description`) |\n| `env` | `Record<string, string>` | No | Prompt-level default values for variables |\n| `hooks` | `string[]` | No | Hook IDs to run for this prompt (overrides agent hooks) |\n| `reasoning` | `ReasoningConfig` | No | Extended thinking configuration |\n\n## Basic Example\n\n```typescript\nimport { definePrompt } from '@standardagents/builder';\n\nexport default definePrompt({\n name: 'customer_support',\n toolDescription: 'Handle customer support inquiries',\n model: 'default',\n prompt: `You are a helpful customer support agent.\nAlways be polite and professional.\nIf you cannot help, escalate to a human.`,\n tools: ['search_knowledge_base', 'create_ticket'],\n includeChat: true,\n});\n```\n\n## Structured Prompts\n\nInclude other prompts for reusable instruction blocks:\n\n```typescript\nexport default definePrompt({\n name: 'main_assistant',\n toolDescription: 'Primary assistant',\n model: 'default',\n prompt: [\n { type: 'text', content: 'You are a helpful assistant.\\n\\n' },\n { type: 'include', prompt: 'common_rules' }, // Includes another prompt\n { type: 'env', property: 'ASSISTANT_TONE' }, // Inject variable value\n { type: 'text', content: '\\n\\nBe concise.' },\n ],\n});\n```\n\n`type: 'env'` inserts a resolved thread variable value. Use this only for non-secret values that are safe to expose to the LLM.\n\nThe sandboxed coding prompt declares `HTTP_HOST` as a text variable. Its URL helper uses that value as the origin for files exposed from the thread `public/` directory and endpoints exposed from the thread `api/` directory. Public URLs should usually omit extensions; extensionless public paths resolve `.html`, then `.js`, then `.ts`, then matching `index` files in the same order. Browser pages should reference only public files, `api/` endpoints, or absolute external URLs, using relative asset URLs like `./app` and `./api/todos`; private `src/` files are not served directly. Public `.ts` files are transformed to browser JavaScript and are not server endpoints. Server-side endpoints live under the thread filesystem `api/` directory, and the `api/` directory name stays in the public URL: `api/todo.ts` is `/api/threads/{threadId}/api/todo`, while `api/todo.ts` is not `/api/threads/{threadId}/todo` or `/api/threads/{threadId}/todos`. Endpoint files default-export a function that accepts `Request` and returns `Response` or `Promise<Response>`. Endpoint code can import `fetch`, `fs`, and `storage`, and can import private helpers with relative paths such as `../src/todo.ts`. When the coding agent creates a site, page, or endpoint, it should call `get_public_url` with the created file path and use the returned URL.\n\nSandboxed code and `api/` endpoints can persist small JSON-serializable runtime data through `import { storage } from \"storage\"`. Use `storage.get`, `storage.set`, `storage.delete`, and `storage.has` with stable logical keys. Do not expose, mention, or depend on internal storage key prefixes.\n\nThe sandboxed coding prompt includes `delete_file` for removing files or empty directories from the thread filesystem. Use it to clean up obsolete implementation files, stale public assets, and abandoned endpoint routes after the replacement is working.\n\n## Tool Configuration\n\nTools can be simple names or detailed configs:\n\n```typescript\ntools: [\n 'simple_tool', // Just the tool name\n {\n name: 'complex_tool',\n includeTextResponse: true, // Include sub-prompt text in result\n includeToolCalls: false, // Exclude sub-prompt tool calls\n includeErrors: true, // Include error details\n initUserMessageProperty: 'query', // Use this arg as initial message\n },\n],\n```\n\nProvider-built-in tools use the same `tools` list once the selected model enables\nthem with `providerTools`. AgentBuilder passes them to the provider and records\nprovider-reported calls in request logs; it does not execute those tools locally.\nGenerated prompt files may store these selections as `provider:<toolName>` to\ndistinguish provider tools from local tools with the same name.\n\n### Subagent Tool Configuration\n\nUse `SubagentToolConfig` when the tool is a `dual_ai` agent:\n\n```typescript\ntools: [\n // Blocking, non-resumable (default)\n { name: 'data_processor_agent' },\n\n // Non-blocking, resumable with a single instance\n {\n name: 'browser_agent',\n blocking: false,\n immediate: {\n nameEnv: 'BROWSER_AGENT_NAME',\n descriptionEnv: 'BROWSER_AGENT_DESCRIPTION',\n scopedEnv: ['BROWSER_AGENT_API_KEY'],\n },\n optional: 'ENABLE_BROWSER_AGENT',\n initAgentNameProperty: 'name',\n resumable: {\n receives_messages: 'side_a',\n maxInstances: 1,\n parentCommunication: 'explicit',\n },\n },\n]\n```\n\nWhen prompt-configured resumable dual_ai subagents exist, the runtime auto-injects:\n- `subagent_create` for spawning new child instances\n- `subagent_message` for messaging active resumable instances\n\n`subagent_create` requires a non-empty `name` for human-friendly child thread labels.\nAgentBuilder stores that argument as a `name:<value>` thread tag.\n\nSet `immediate: true` to run a tool automatically when the prompt activates.\nUse `immediate: { nameEnv, descriptionEnv, scopedEnv }` when you want safe per-instance bootstrap hints while keeping copied scoped env runtime-only.\nSet `optional: 'ENV_NAME'` to enable a subagent branch only when env resolves to `true`, `1`, or `yes`.\nSet `resumable.parentCommunication: 'explicit'` when the child should stay quiet until its own tools or hooks call `state.notifyParent()` or `state.setStatus()`.\nIf required scoped vars are missing, the runtime returns `error_code: \"subagent_env_required\"` with a temporary `GET/POST /api/threads/:threadId/variables/:requestId` endpoint in `error_data.endpoint`.\n\n## Input Validation\n\nValidate inputs when prompt is called as a tool:\n\n```typescript\nimport { z } from 'zod';\n\nexport default definePrompt({\n name: 'data_extractor',\n toolDescription: 'Extract structured data from text',\n model: 'default',\n prompt: 'Extract the requested data from the input.',\n requiredSchema: z.object({\n text: z.string().describe('Text to extract from'),\n fields: z.array(z.string()).describe('Fields to extract'),\n }),\n});\n```\n\n## Extended Thinking (Reasoning)\n\nEnable for complex reasoning tasks:\n\n```typescript\nexport default definePrompt({\n name: 'code_reviewer',\n toolDescription: 'Review code for issues',\n model: 'heavy',\n prompt: 'Review the code thoroughly...',\n reasoning: {\n effort: 'high', // 'low' | 'medium' | 'high'\n maxTokens: 16000, // Max thinking tokens\n exclude: true, // Don't include thinking in response\n },\n});\n```\n\n**\u26A0\uFE0F Google Models Require Reasoning**: When using Google models (`google/gemini-*`) via OpenRouter, you **must** include `reasoning` configuration or tool calls will fail. At minimum:\n\n```typescript\nreasoning: {\n effort: 'low', // Can be 'low', 'medium', or 'high'\n},\n```\n\n## Hooks\n\nAttach lifecycle hooks to a prompt:\n\n```typescript\nexport default definePrompt({\n name: 'customer_support',\n toolDescription: 'Handle customer support',\n model: 'default',\n prompt: 'You are a support agent...',\n hooks: ['limit_to_20', 'redact_pii'], // Hook IDs from agents/hooks/\n});\n```\n\nPrompt hooks take precedence over agent hooks. See `agents/hooks/AGENTS.md` for details.\n\n## Best Practices\n\n- **Write clear instructions** - Structure with headers and bullet points\n- **Describe tools thoroughly** - LLMs decide based on descriptions\n- **Validate inputs with Zod** - Catch errors early\n- **Use `includeChat`** for conversational context\n- **Name by purpose**, not model (e.g., `support_agent` not `gpt4_prompt`)\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/prompt\n";
6
6
 
7
- declare const AGENTS_CLAUDE_MD = "# Agent Definitions\n\nAgents orchestrate conversations by defining prompts, stop conditions, and turn limits.\n\n## Agent Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `name` | `string` | Yes | Unique identifier for this agent |\n| `type` | `'ai_human' \\| 'dual_ai'` | No | Conversation type (default: `ai_human`) |\n| `sideA` | `SideConfig` | Yes | Configuration for side A (AI in ai_human) |\n| `sideB` | `SideConfig` | No | Configuration for side B (required for dual_ai) |\n| `maxSessionTurns` | `number` | No | Max total turns across both sides |\n| `exposeAsTool` | `boolean` | No | Allow other prompts to hand off to this agent |\n| `toolDescription` | `string` | No | Description when used as tool (required if exposeAsTool) |\n| `env` | `Record<string, string>` | No | Agent-level default variable values |\n| `hooks` | `string[]` | No | Hook IDs to run for this agent (fallback if prompt has no hooks) |\n| `tags` | `string[]` | No | Tags for categorization and filtering |\n\n## Side Configuration\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `label` | `string` | No | Display name for this side |\n| `prompt` | `string` | Yes | Prompt name to use (references `agents/prompts/`) |\n| `stopOnResponse` | `boolean` | No | Stop turn when LLM returns text (default: true) |\n| `stopTool` | `string` | No | Tool that stops this side's turn |\n| `stopToolResponseProperty` | `string` | No | Property to extract from stop tool result |\n| `maxSteps` | `number` | No | Maximum step budget for this side |\n| `sessionStop` | `string \\| SessionToolBinding` | No | Terminal success lifecycle binding |\n| `sessionFail` | `string \\| SessionToolBinding` | No | Terminal failure lifecycle binding |\n| `sessionStatus` | `string \\| SessionToolBinding` | No | Non-terminal status lifecycle binding |\n| `manualStopCondition` | `boolean` | No | Enable custom stop handling via hooks |\n\n## Basic Example (AI-Human)\n\n```typescript\nimport { defineAgent } from '@standardagents/builder';\n\nexport default defineAgent({\n name: 'support_agent',\n type: 'ai_human',\n sideA: {\n label: 'Support',\n prompt: 'customer_support',\n stopOnResponse: true,\n sessionStop: 'close_ticket',\n maxSteps: 50,\n },\n tags: ['support', 'tier-1'],\n});\n```\n\n## Dual-AI Example\n\nTwo AI agents conversing (e.g., debate, iterative refinement):\n\n```typescript\nexport default defineAgent({\n name: 'code_review_debate',\n type: 'dual_ai',\n maxSessionTurns: 20,\n sideA: {\n label: 'Reviewer',\n prompt: 'code_reviewer',\n stopOnResponse: true,\n },\n sideB: {\n label: 'Developer',\n prompt: 'code_defender',\n stopOnResponse: true,\n },\n});\n```\n\n## Dual-AI Subagent Pattern\n\nWhen a `dual_ai` agent is used as a subagent tool, a common split is:\n- **sideA**: performs work (tools, data gathering, execution)\n- **sideB**: reflection, verification, and quality checks\n\n```typescript\nexport default defineAgent({\n name: 'research_subagent',\n type: 'dual_ai',\n exposeAsTool: true,\n toolDescription: 'Researches and validates findings autonomously',\n maxSessionTurns: 16,\n sideA: {\n label: 'Worker',\n prompt: 'research_worker',\n sessionStatus: 'set_subagent_status',\n sessionFail: 'fail_research_subagent',\n sessionStop: 'finish_subagent',\n },\n sideB: {\n label: 'Reviewer',\n prompt: 'research_reviewer',\n stopOnResponse: true,\n },\n});\n```\n\n## Agent Handoffs\n\nExpose an agent for handoffs from other prompts:\n\n```typescript\nexport default defineAgent({\n name: 'escalation_agent',\n type: 'ai_human',\n exposeAsTool: true,\n toolDescription: 'Escalate to senior support for complex issues',\n sideA: {\n prompt: 'senior_support',\n },\n});\n```\n\nOther prompts can then include the agent name in their `tools` array to enable handoffs.\n\n## Stop Conditions (Priority Order)\n\n1. **sessionFail** - Ends entire conversation with a terminal failure\n2. **sessionStop** - Ends entire conversation successfully\n3. **stopTool** - Ends current side's turn\n4. **maxSteps** - Ends side execution when the safety budget is reached\n5. **stopOnResponse** - Ends turn when LLM returns text\n6. **maxSessionTurns** - Ends conversation (hard limit: 250)\n\n## Hooks\n\nAttach lifecycle hooks at the agent level:\n\n```typescript\nexport default defineAgent({\n name: 'support_agent',\n type: 'ai_human',\n hooks: ['log_all_messages', 'sanitize_results'],\n sideA: {\n prompt: 'customer_support',\n },\n});\n```\n\nAgent hooks run as a fallback when the active prompt has no hooks defined. Prompt hooks always take precedence. See `agents/hooks/CLAUDE.md` for details.\n\n## Naming Convention\n\nAgent names **must** end with the `_agent` suffix (e.g., `support_agent`, `research_agent`).\nThis convention is enforced by the builder UI and makes agents easily identifiable in logs and code.\n\n## Best Practices\n\n- **Use descriptive names** (`customer_support_agent` not `agent1`)\n- **Always use the _agent suffix** - names like `support_agent`, `research_agent`\n- **Always set maxSteps or maxSessionTurns** as safety limits\n- **Match stop conditions to use case** - chat apps use stopOnResponse, workflows use stopTool\n- **Use labels** for clarity in logs and UI\n- **Organize with tags** for filtering\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/agent\n";
7
+ declare const AGENT_DEFINITIONS_AGENTS_MD = "# Agent Definitions\n\nAgents orchestrate conversations by defining prompts, stop conditions, and turn limits.\n\n## Agent Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `name` | `string` | Yes | Unique identifier for this agent |\n| `type` | `'ai_human' \\| 'dual_ai'` | No | Conversation type (default: `ai_human`) |\n| `sideA` | `SideConfig` | Yes | Configuration for side A (AI in ai_human) |\n| `sideB` | `SideConfig` | No | Configuration for side B (required for dual_ai) |\n| `maxSessionTurns` | `number` | No | Max total turns across both sides |\n| `exposeAsTool` | `boolean` | No | Allow other prompts to hand off to this agent |\n| `toolDescription` | `string` | No | Description when used as tool (required if exposeAsTool) |\n| `env` | `Record<string, string>` | No | Agent-level default variable values |\n| `hooks` | `string[]` | No | Hook IDs to run for this agent (fallback if prompt has no hooks) |\n| `tags` | `string[]` | No | Tags for categorization and filtering |\n\n## Side Configuration\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `label` | `string` | No | Display name for this side |\n| `prompt` | `string` | Yes | Prompt name to use (references `agents/prompts/`) |\n| `stopOnResponse` | `boolean` | No | Stop turn when LLM returns text (default: true) |\n| `stopTool` | `string` | No | Tool that stops this side's turn |\n| `stopToolResponseProperty` | `string` | No | Property to extract from stop tool result |\n| `maxSteps` | `number` | No | Maximum step budget for this side |\n| `sessionStop` | `string \\| SessionToolBinding` | No | Terminal success lifecycle binding |\n| `sessionFail` | `string \\| SessionToolBinding` | No | Terminal failure lifecycle binding |\n| `sessionStatus` | `string \\| SessionToolBinding` | No | Non-terminal status lifecycle binding |\n| `manualStopCondition` | `boolean` | No | Enable custom stop handling via hooks |\n\n## Basic Example (AI-Human)\n\n```typescript\nimport { defineAgent } from '@standardagents/builder';\n\nexport default defineAgent({\n name: 'support_agent',\n type: 'ai_human',\n sideA: {\n label: 'Support',\n prompt: 'customer_support',\n stopOnResponse: true,\n sessionStop: 'close_ticket',\n maxSteps: 50,\n },\n tags: ['support', 'tier-1'],\n});\n```\n\n## Dual-AI Example\n\nTwo AI agents conversing (e.g., debate, iterative refinement):\n\n```typescript\nexport default defineAgent({\n name: 'code_review_debate',\n type: 'dual_ai',\n maxSessionTurns: 20,\n sideA: {\n label: 'Reviewer',\n prompt: 'code_reviewer',\n stopOnResponse: true,\n },\n sideB: {\n label: 'Developer',\n prompt: 'code_defender',\n stopOnResponse: true,\n },\n});\n```\n\n## Dual-AI Subagent Pattern\n\nWhen a `dual_ai` agent is used as a subagent tool, a common split is:\n- **sideA**: performs work (tools, data gathering, execution)\n- **sideB**: reflection, verification, and quality checks\n\n```typescript\nexport default defineAgent({\n name: 'research_subagent',\n type: 'dual_ai',\n exposeAsTool: true,\n toolDescription: 'Researches and validates findings autonomously',\n maxSessionTurns: 16,\n sideA: {\n label: 'Worker',\n prompt: 'research_worker',\n sessionStatus: 'set_subagent_status',\n sessionFail: 'fail_research_subagent',\n sessionStop: 'finish_subagent',\n },\n sideB: {\n label: 'Reviewer',\n prompt: 'research_reviewer',\n stopOnResponse: true,\n },\n});\n```\n\n## Agent Handoffs\n\nExpose an agent for handoffs from other prompts:\n\n```typescript\nexport default defineAgent({\n name: 'escalation_agent',\n type: 'ai_human',\n exposeAsTool: true,\n toolDescription: 'Escalate to senior support for complex issues',\n sideA: {\n prompt: 'senior_support',\n },\n});\n```\n\nOther prompts can then include the agent name in their `tools` array to enable handoffs.\n\n## Stop Conditions (Priority Order)\n\n1. **sessionFail** - Ends entire conversation with a terminal failure\n2. **sessionStop** - Ends entire conversation successfully\n3. **stopTool** - Ends current side's turn\n4. **maxSteps** - Ends side execution when the safety budget is reached\n5. **stopOnResponse** - Ends turn when LLM returns text\n6. **maxSessionTurns** - Ends conversation (hard limit: 250)\n\n## Hooks\n\nAttach lifecycle hooks at the agent level:\n\n```typescript\nexport default defineAgent({\n name: 'support_agent',\n type: 'ai_human',\n hooks: ['log_all_messages', 'sanitize_results'],\n sideA: {\n prompt: 'customer_support',\n },\n});\n```\n\nAgent hooks run as a fallback when the active prompt has no hooks defined. Prompt hooks always take precedence. See `agents/hooks/AGENTS.md` for details.\n\n## Naming Convention\n\nAgent names **must** end with the `_agent` suffix (e.g., `support_agent`, `research_agent`).\nThis convention is enforced by the builder UI and makes agents easily identifiable in logs and code.\n\n## Best Practices\n\n- **Use descriptive names** (`customer_support_agent` not `agent1`)\n- **Always use the _agent suffix** - names like `support_agent`, `research_agent`\n- **Always set maxSteps or maxSessionTurns** as safety limits\n- **Match stop conditions to use case** - chat apps use stopOnResponse, workflows use stopTool\n- **Use labels** for clarity in logs and UI\n- **Organize with tags** for filtering\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/agent\n";
8
8
 
9
- declare const TOOLS_CLAUDE_MD = "# Custom Tools\n\nTools extend agent capabilities beyond text generation. They allow LLMs to fetch data, perform calculations, execute side effects, and chain to other prompts or agents.\n\n## Function Signature\n\n```typescript\ndefineTool({\n description: string, // What the tool does (shown to LLM)\n args?: z.ZodObject, // Input validation schema (optional)\n execute: (state, args) => ToolResult, // Implementation\n variables?: VariableDefinition[], // Declared variables (optional)\n})\n```\n\n## Basic Example\n\n```typescript\nimport { defineTool } from '@standardagents/builder';\nimport { z } from 'zod';\n\nexport default defineTool({\n description: 'Search the knowledge base for articles matching a query',\n args: z.object({\n query: z.string().describe('Search query'),\n limit: z.number().optional().default(10).describe('Max results'),\n }),\n execute: async (state, args) => {\n const results = await searchKB(args.query, args.limit);\n return {\n status: 'success',\n result: JSON.stringify(results),\n };\n },\n});\n```\n\n## Argument Schemas\n\nTool args must be a top-level `z.object(...)`. Prefer explicit, bounded schemas made from strings, numbers, booleans, nulls, literals, enums, arrays, objects, optionals, nullables, and defaults. Avoid provider-visible recursive or open-ended schemas such as `z.unknown()`, `z.any()`, and `z.object({}).catchall(...)`; strict tool providers can reject the generated JSON Schema. If a tool needs arbitrary JSON input, accept it as a JSON string and parse it inside `execute`.\n\n## ToolResult Interface\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `status` | `'success' \\| 'error'` | Whether the tool succeeded |\n| `result` | `string` | Tool output (required for success) |\n| `error` | `string` | Error message (for error status) |\n| `error_code` | `string` | Machine-readable error code |\n| `error_data` | `Record<string, unknown>` | Structured error payload |\n| `attachments` | `ToolAttachment[]` | Files to attach (images, etc.) |\n\n## ThreadState Access\n\nThe `state` parameter provides access to:\n\n```typescript\nexecute: async (state, args) => {\n // Thread information\n const threadId = state.thread.id;\n const thread = state.thread.instance;\n\n // Configuration\n const agentName = state.agent.name;\n const modelName = state.model.name;\n\n // Message history\n const messages = state.messages;\n\n // Thread variable resolution\n const apiKey = await state.env('GOOGLE_API_KEY');\n await state.setEnv('LAST_TOOL_RUN_AT', new Date().toISOString());\n\n // Durable per-thread JSON values\n const runCount = (await state.getValue<number>('run_count')) ?? 0;\n await state.setValue('run_count', runCount + 1);\n\n // Sandboxed JS/TS execution with explicit bridge capabilities\n const run = state.runCode('export async function main(path) { return await read(path) }', {\n execute: { fn: 'main', args: ['/notes.txt'] },\n globals: {\n read: async (path: string) => {\n const data = await state.readFile(path);\n return data ? new TextDecoder().decode(data) : null;\n },\n },\n });\n const codeResult = await run;\n\n // Parent state (for sub-prompts)\n const root = state.rootState;\n}\n```\n\nUse `state.runCode()` instead of `eval` or `new Function` for model- or user-authored JavaScript/TypeScript. The sandbox starts with no ambient host capabilities; provide imports/globals explicitly, use `modules` for local relative ES modules, use `execute` to select an export and pass args, use `report` for streamed observations, and call `run.terminate(reason)` from your own timeout budget when needed. `modules` keys are graph-root relative paths; entry-source imports resolve from `options.filename` when supplied. Relative module imports may use `./` and `../` as long as they resolve within the supplied module graph. In thread endpoints, `runCode` is forwarded into the thread Durable Object; pass plain transferable option values there, and do function-backed bridges from tools or in-thread execution contexts.\n\n## Tool Without Arguments\n\n```typescript\nexport default defineTool({\n description: 'Get current server time',\n execute: async (state) => {\n return {\n status: 'success',\n result: new Date().toISOString(),\n };\n },\n});\n```\n\n## Error Handling\n\nReturn errors gracefully instead of throwing:\n\n```typescript\nexport default defineTool({\n description: 'Fetch user data',\n args: z.object({ userId: z.string() }),\n execute: async (state, args) => {\n try {\n const user = await fetchUser(args.userId);\n return { status: 'success', result: JSON.stringify(user) };\n } catch (error) {\n return {\n status: 'error',\n error: `Failed to fetch user: ${error.message}`,\n };\n }\n },\n});\n```\n\n## Queueing Additional Tools\n\nQueue another tool to run after the current one:\n\n```typescript\nimport { queueTool } from '@standardagents/builder';\n\nexport default defineTool({\n description: 'Create order and send confirmation',\n args: z.object({ items: z.array(z.string()) }),\n execute: async (state, args) => {\n const order = await createOrder(args.items);\n\n // Queue email tool to run next\n queueTool(state, 'send_confirmation_email', {\n orderId: order.id,\n email: state.thread.metadata.userEmail,\n });\n\n return { status: 'success', result: JSON.stringify(order) };\n },\n});\n```\n\n## Injecting Messages\n\nAdd messages without triggering re-execution:\n\n```typescript\nimport { injectMessage } from '@standardagents/builder';\n\nexport default defineTool({\n description: 'Log audit event',\n args: z.object({ event: z.string() }),\n execute: async (state, args) => {\n await injectMessage(state, {\n role: 'system',\n content: `[AUDIT] ${args.event}`,\n });\n return { status: 'success', result: 'Logged' };\n },\n});\n```\n\n## Variables and Env\n\nTools can declare variable requirements with `variables`, including `required` and `description` metadata:\n\n```typescript\nexport default defineTool({\n description: 'Search uploaded documents',\n args: z.object({ query: z.string() }),\n execute: async (state, args) => {\n const vectorStoreId = await state.env('VECTOR_STORE_ID');\n const results = await searchVectorStore(vectorStoreId, args.query);\n return { status: 'success', result: JSON.stringify(results) };\n },\n variables: [\n {\n name: 'VECTOR_STORE_ID',\n type: 'text',\n required: true,\n scoped: false,\n description: 'OpenAI Vector Store ID',\n },\n ],\n});\n```\n\nUse `scoped: true` for per-instance values that should not inherit from parent thread env (for example per-account OAuth tokens on subagents).\n\n## Returning Attachments\n\nTools can return file attachments (e.g., generated images):\n\n```typescript\nexport default defineTool({\n description: 'Generate a chart from data',\n args: z.object({ data: z.array(z.number()) }),\n execute: async (state, args) => {\n const chartImage = await generateChart(args.data);\n return {\n status: 'success',\n result: 'Chart generated successfully',\n attachments: [{\n name: 'chart.png',\n mimeType: 'image/png',\n data: chartImage.base64,\n width: 800,\n height: 600,\n }],\n };\n },\n});\n```\n\n## Best Practices\n\n- **Write clear descriptions** - LLMs decide tool usage based on descriptions\n- **Describe all parameters** with `.describe()` in Zod schemas\n- **Handle errors gracefully** - return error status, don't throw\n- **Use snake_case** for file names (`search_knowledge_base.ts`)\n- **Keep tools focused** - one task per tool\n- **Use `state.rootState`** when queueing from sub-prompts\n\n## Supported Zod Types\n\n- Primitives: `string`, `number`, `boolean`, `null`\n- Enums: `z.enum(['a', 'b', 'c'])`\n- Arrays: `z.array(z.string())`\n- Objects: `z.object({ ... })`\n- Optional: `z.string().optional()`\n- Default: `z.number().default(10)`\n- Nullable: `z.string().nullable()`\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/tool\n";
9
+ declare const TOOLS_AGENTS_MD = "# Custom Tools\n\nTools extend agent capabilities beyond text generation. They allow LLMs to fetch data, perform calculations, execute side effects, and chain to other prompts or agents.\n\n## Function Signature\n\n```typescript\ndefineTool({\n description: string, // What the tool does (shown to LLM)\n args?: z.ZodObject, // Input validation schema (optional)\n execute: (state, args) => ToolResult, // Implementation\n variables?: VariableDefinition[], // Declared variables (optional)\n})\n```\n\n## Basic Example\n\n```typescript\nimport { defineTool } from '@standardagents/builder';\nimport { z } from 'zod';\n\nexport default defineTool({\n description: 'Search the knowledge base for articles matching a query',\n args: z.object({\n query: z.string().describe('Search query'),\n limit: z.number().optional().default(10).describe('Max results'),\n }),\n execute: async (state, args) => {\n const results = await searchKB(args.query, args.limit);\n return {\n status: 'success',\n result: JSON.stringify(results),\n };\n },\n});\n```\n\n## Argument Schemas\n\nTool args must be a top-level `z.object(...)`. Prefer explicit, bounded schemas made from strings, numbers, booleans, nulls, literals, enums, arrays, objects, optionals, nullables, and defaults. Avoid provider-visible recursive or open-ended schemas such as `z.unknown()`, `z.any()`, and `z.object({}).catchall(...)`; strict tool providers can reject the generated JSON Schema. If a tool needs arbitrary JSON input, accept it as a JSON string and parse it inside `execute`.\n\n## ToolResult Interface\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `status` | `'success' \\| 'error'` | Whether the tool succeeded |\n| `result` | `string` | Tool output (required for success) |\n| `error` | `string` | Error message (for error status) |\n| `error_code` | `string` | Machine-readable error code |\n| `error_data` | `Record<string, unknown>` | Structured error payload |\n| `attachments` | `ToolAttachment[]` | Files to attach (images, etc.) |\n\n## ThreadState Access\n\nThe `state` parameter provides access to:\n\n```typescript\nexecute: async (state, args) => {\n // Thread information\n const threadId = state.thread.id;\n const thread = state.thread.instance;\n\n // Configuration\n const agentName = state.agent.name;\n const modelName = state.model.name;\n\n // Message history\n const messages = state.messages;\n\n // Thread variable resolution\n const apiKey = await state.env('GOOGLE_API_KEY');\n await state.setEnv('LAST_TOOL_RUN_AT', new Date().toISOString());\n\n // Durable per-thread JSON values\n const runCount = (await state.getValue<number>('run_count')) ?? 0;\n await state.setValue('run_count', runCount + 1);\n\n // Sandboxed JS/TS execution with explicit bridge capabilities\n const run = state.runCode('export async function main(path) { return await read(path) }', {\n execute: { fn: 'main', args: ['/notes.txt'] },\n globals: {\n read: async (path: string) => {\n const data = await state.readFile(path);\n return data ? new TextDecoder().decode(data) : null;\n },\n },\n });\n const codeResult = await run;\n\n // Parent state (for sub-prompts)\n const root = state.rootState;\n}\n```\n\nUse `state.runCode()` instead of `eval` or `new Function` for model- or user-authored JavaScript/TypeScript. The sandbox starts with no ambient host capabilities; provide imports/globals explicitly, use `modules` for local relative ES modules, use `execute` to select an export and pass args, use `report` for streamed observations, and call `run.terminate(reason)` from your own timeout budget when needed. `modules` keys are graph-root relative paths; entry-source imports resolve from `options.filename` when supplied. Relative module imports may use `./` and `../` as long as they resolve within the supplied module graph. In thread endpoints, `runCode` is forwarded into the thread Durable Object; pass plain transferable option values there, and do function-backed bridges from tools or in-thread execution contexts.\n\n## Tool Without Arguments\n\n```typescript\nexport default defineTool({\n description: 'Get current server time',\n execute: async (state) => {\n return {\n status: 'success',\n result: new Date().toISOString(),\n };\n },\n});\n```\n\n## Error Handling\n\nReturn errors gracefully instead of throwing:\n\n```typescript\nexport default defineTool({\n description: 'Fetch user data',\n args: z.object({ userId: z.string() }),\n execute: async (state, args) => {\n try {\n const user = await fetchUser(args.userId);\n return { status: 'success', result: JSON.stringify(user) };\n } catch (error) {\n return {\n status: 'error',\n error: `Failed to fetch user: ${error.message}`,\n };\n }\n },\n});\n```\n\n## Queueing Additional Tools\n\nQueue another tool to run after the current one:\n\n```typescript\nimport { queueTool } from '@standardagents/builder';\n\nexport default defineTool({\n description: 'Create order and send confirmation',\n args: z.object({ items: z.array(z.string()) }),\n execute: async (state, args) => {\n const order = await createOrder(args.items);\n\n // Queue email tool to run next\n queueTool(state, 'send_confirmation_email', {\n orderId: order.id,\n email: state.thread.metadata.userEmail,\n });\n\n return { status: 'success', result: JSON.stringify(order) };\n },\n});\n```\n\n## Injecting Messages\n\nAdd messages without triggering re-execution:\n\n```typescript\nimport { injectMessage } from '@standardagents/builder';\n\nexport default defineTool({\n description: 'Log audit event',\n args: z.object({ event: z.string() }),\n execute: async (state, args) => {\n await injectMessage(state, {\n role: 'system',\n content: `[AUDIT] ${args.event}`,\n });\n return { status: 'success', result: 'Logged' };\n },\n});\n```\n\n## Variables and Env\n\nTools can declare variable requirements with `variables`, including `required` and `description` metadata:\n\n```typescript\nexport default defineTool({\n description: 'Search uploaded documents',\n args: z.object({ query: z.string() }),\n execute: async (state, args) => {\n const vectorStoreId = await state.env('VECTOR_STORE_ID');\n const results = await searchVectorStore(vectorStoreId, args.query);\n return { status: 'success', result: JSON.stringify(results) };\n },\n variables: [\n {\n name: 'VECTOR_STORE_ID',\n type: 'text',\n required: true,\n scoped: false,\n description: 'OpenAI Vector Store ID',\n },\n ],\n});\n```\n\nUse `scoped: true` for per-instance values that should not inherit from parent thread env (for example per-account OAuth tokens on subagents).\n\n## Returning Attachments\n\nTools can return file attachments (e.g., generated images):\n\n```typescript\nexport default defineTool({\n description: 'Generate a chart from data',\n args: z.object({ data: z.array(z.number()) }),\n execute: async (state, args) => {\n const chartImage = await generateChart(args.data);\n return {\n status: 'success',\n result: 'Chart generated successfully',\n attachments: [{\n name: 'chart.png',\n mimeType: 'image/png',\n data: chartImage.base64,\n width: 800,\n height: 600,\n }],\n };\n },\n});\n```\n\n## Best Practices\n\n- **Write clear descriptions** - LLMs decide tool usage based on descriptions\n- **Describe all parameters** with `.describe()` in Zod schemas\n- **Handle errors gracefully** - return error status, don't throw\n- **Use snake_case** for file names (`search_knowledge_base.ts`)\n- **Keep tools focused** - one task per tool\n- **Use `state.rootState`** when queueing from sub-prompts\n\n## Supported Zod Types\n\n- Primitives: `string`, `number`, `boolean`, `null`\n- Enums: `z.enum(['a', 'b', 'c'])`\n- Arrays: `z.array(z.string())`\n- Objects: `z.object({ ... })`\n- Optional: `z.string().optional()`\n- Default: `z.number().default(10)`\n- Nullable: `z.string().nullable()`\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/tool\n";
10
10
 
11
- declare const HOOKS_CLAUDE_MD = "# Lifecycle Hooks\n\nHooks intercept and modify agent execution at specific lifecycle points.\n\n## Available Hooks\n\n| Hook | Signature | Purpose |\n|------|-----------|---------|\n| `after_thread_created` | `(state: ThreadState) => void` | Initialize a newly created thread before execution |\n| `after_subagent_created` | `(state: ThreadState, childState: ThreadState) => void` | Run parent-side logic after a child thread is created |\n| `after_system_message` | `(state: ThreadState, systemMessage: string) => string \\| null \\| undefined` | Modify the rendered system message for a request |\n| `filter_messages` | `(state: ThreadState, messages: Message[]) => Message[]` | Filter raw messages before LLM context |\n| `prefilter_llm_history` | `(state: ThreadState, messages: LLMMessage[]) => LLMMessage[]` | Modify chat completion messages before LLM |\n| `before_create_message` | `(state: ThreadState, message: Message) => Message` | Modify message before database insert |\n| `after_create_message` | `(state: ThreadState, message: Message) => void` | Run logic after message created |\n| `before_update_message` | `(state: ThreadState, id: string, updates: Record) => Record` | Modify updates before message update |\n| `after_update_message` | `(state: ThreadState, message: Message) => void` | Run logic after message updated |\n| `before_store_tool_result` | `(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => HookToolResult` | Modify tool result before storage |\n| `after_tool_call_success` | `(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => HookToolResult \\| null` | Process successful tool execution |\n| `after_tool_call_failure` | `(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => HookToolResult \\| null` | Process failed tool execution |\n\nAll hooks receive `ThreadState` as their first parameter, providing access to thread identity, message history, resource loading, durable per-thread values via `getValue` / `setValue`, and sandboxed JS/TS execution via `runCode`.\n\n## Creating a Hook\n\nEach hook file exports a default `defineHook` call with three properties:\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'filter_messages', // Hook type\n id: 'limit_recent_messages', // Unique ID (snake_case)\n execute: async (state, messages) => {\n return messages.slice(-20);\n }\n});\n```\n\n## Hook Scoping\n\nHooks are scoped to **prompts** or **agents** via their ID:\n\n```typescript\n// In a prompt definition\ndefinePrompt({\n name: 'customer_support',\n hooks: ['limit_recent_messages', 'redact_pii'],\n // ...\n});\n\n// In an agent definition\ndefineAgent({\n name: 'support_agent',\n hooks: ['log_all_messages'],\n // ...\n});\n```\n\n- **Prompt hooks** take precedence over agent hooks\n- If a prompt defines hooks, only those run (agent hooks are skipped)\n- If no prompt hooks are defined, agent hooks run as fallback\n- Hooks are filtered by type at runtime\n\n## File Naming\n\nHook files can use **any name** \u2014 the hook type and ID are defined inside the file:\n\n```\nagents/hooks/\n\u251C\u2500\u2500 my_filter.ts # Could contain any hook type\n\u251C\u2500\u2500 redact_sensitive_data.ts\n\u251C\u2500\u2500 log_tool_usage.ts\n\u2514\u2500\u2500 add_metadata.ts\n```\n\n## Examples\n\n### Filter Messages (Limit Context)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'filter_messages',\n id: 'limit_to_20',\n execute: async (state, messages) => {\n return messages.slice(-20);\n }\n});\n```\n\n### Prefilter LLM History (Redact Content)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'prefilter_llm_history',\n id: 'redact_pii',\n execute: async (state, messages) => {\n return messages.map(msg => ({\n ...msg,\n content: typeof msg.content === 'string'\n ? msg.content.replace(/\\b\\d{4}-\\d{4}-\\d{4}-\\d{4}\\b/g, '[REDACTED]')\n : msg.content,\n }));\n }\n});\n```\n\n### Before Create Message (Add Metadata)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'before_create_message',\n id: 'add_version_metadata',\n execute: async (state, message) => {\n if (message.role === 'user' && message.content) {\n return { ...message, content: `[v1.0] ${message.content}` };\n }\n return message;\n }\n});\n```\n\n### Before Store Tool Result (Sanitize)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'before_store_tool_result',\n id: 'sanitize_results',\n execute: async (state, toolCall, toolResult) => {\n // toolCall: { id, type: 'function', function: { name, arguments } }\n // toolResult: { status, result?, error?, stack?, attachments? }\n if (toolResult.result) {\n return { ...toolResult, result: toolResult.result.replace(/secret/gi, '[REDACTED]') };\n }\n return toolResult;\n }\n});\n```\n\n### After Tool Call Success (Logging)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'after_tool_call_success',\n id: 'log_tool_success',\n execute: async (state, toolCall, result) => {\n console.log(`Tool ${toolCall.function.name} succeeded`);\n return null; // Return null to use original result\n }\n});\n```\n\n### After Tool Call Failure (Recovery)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'after_tool_call_failure',\n id: 'weather_fallback',\n execute: async (state, toolCall, result) => {\n if (toolCall.function.name === 'fetch_weather') {\n return {\n status: 'success',\n result: JSON.stringify({ temp: 'unavailable', fallback: true }),\n };\n }\n return null; // Use original error for other tools\n }\n});\n```\n\n## Hook Categories\n\n**Transformation hooks** (return modified data):\n- `after_system_message` (return replacement string, or null/undefined for no change)\n- `filter_messages`\n- `prefilter_llm_history`\n- `before_create_message`\n- `before_update_message`\n- `before_store_tool_result`\n- `after_tool_call_success` (return modified result or null)\n- `after_tool_call_failure` (return modified result or null)\n\n**Event hooks** (side effects only):\n- `after_thread_created`\n- `after_subagent_created`\n- `after_create_message`\n- `after_update_message`\n\n## Best Practices\n\n- **Keep hooks fast** - target <100ms execution\n- **Wrap in try-catch** - hooks continue on error (original data preserved)\n- **Use unique IDs** - hook IDs must be snake_case and unique across the project\n- **Scope appropriately** - assign hooks to prompts or agents that need them\n- **Document purpose** with clear comments\n- **Use for cross-cutting concerns** - logging, redaction, enrichment\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/hook\n";
11
+ declare const HOOKS_AGENTS_MD = "# Lifecycle Hooks\n\nHooks intercept and modify agent execution at specific lifecycle points.\n\n## Available Hooks\n\n| Hook | Signature | Purpose |\n|------|-----------|---------|\n| `after_thread_created` | `(state: ThreadState) => void` | Initialize a newly created thread before execution |\n| `after_subagent_created` | `(state: ThreadState, childState: ThreadState) => void` | Run parent-side logic after a child thread is created |\n| `after_system_message` | `(state: ThreadState, systemMessage: string) => string \\| null \\| undefined` | Modify the rendered system message for a request |\n| `filter_messages` | `(state: ThreadState, messages: Message[]) => Message[]` | Filter raw messages before LLM context |\n| `prefilter_llm_history` | `(state: ThreadState, messages: LLMMessage[]) => LLMMessage[]` | Modify chat completion messages before LLM |\n| `before_create_message` | `(state: ThreadState, message: Message) => Message` | Modify message before database insert |\n| `after_create_message` | `(state: ThreadState, message: Message) => void` | Run logic after message created |\n| `before_update_message` | `(state: ThreadState, id: string, updates: Record) => Record` | Modify updates before message update |\n| `after_update_message` | `(state: ThreadState, message: Message) => void` | Run logic after message updated |\n| `before_store_tool_result` | `(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => HookToolResult` | Modify tool result before storage |\n| `after_tool_call_success` | `(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => HookToolResult \\| null` | Process successful tool execution |\n| `after_tool_call_failure` | `(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => HookToolResult \\| null` | Process failed tool execution |\n\nAll hooks receive `ThreadState` as their first parameter, providing access to thread identity, message history, resource loading, durable per-thread values via `getValue` / `setValue`, and sandboxed JS/TS execution via `runCode`.\n\n## Creating a Hook\n\nEach hook file exports a default `defineHook` call with three properties:\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'filter_messages', // Hook type\n id: 'limit_recent_messages', // Unique ID (snake_case)\n execute: async (state, messages) => {\n return messages.slice(-20);\n }\n});\n```\n\n## Hook Scoping\n\nHooks are scoped to **prompts** or **agents** via their ID:\n\n```typescript\n// In a prompt definition\ndefinePrompt({\n name: 'customer_support',\n hooks: ['limit_recent_messages', 'redact_pii'],\n // ...\n});\n\n// In an agent definition\ndefineAgent({\n name: 'support_agent',\n hooks: ['log_all_messages'],\n // ...\n});\n```\n\n- **Prompt hooks** take precedence over agent hooks\n- If a prompt defines hooks, only those run (agent hooks are skipped)\n- If no prompt hooks are defined, agent hooks run as fallback\n- Hooks are filtered by type at runtime\n\n## File Naming\n\nHook files can use **any name** \u2014 the hook type and ID are defined inside the file:\n\n```\nagents/hooks/\n\u251C\u2500\u2500 my_filter.ts # Could contain any hook type\n\u251C\u2500\u2500 redact_sensitive_data.ts\n\u251C\u2500\u2500 log_tool_usage.ts\n\u2514\u2500\u2500 add_metadata.ts\n```\n\n## Examples\n\n### Filter Messages (Limit Context)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'filter_messages',\n id: 'limit_to_20',\n execute: async (state, messages) => {\n return messages.slice(-20);\n }\n});\n```\n\n### Prefilter LLM History (Redact Content)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'prefilter_llm_history',\n id: 'redact_pii',\n execute: async (state, messages) => {\n return messages.map(msg => ({\n ...msg,\n content: typeof msg.content === 'string'\n ? msg.content.replace(/\\b\\d{4}-\\d{4}-\\d{4}-\\d{4}\\b/g, '[REDACTED]')\n : msg.content,\n }));\n }\n});\n```\n\n### Before Create Message (Add Metadata)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'before_create_message',\n id: 'add_version_metadata',\n execute: async (state, message) => {\n if (message.role === 'user' && message.content) {\n return { ...message, content: `[v1.0] ${message.content}` };\n }\n return message;\n }\n});\n```\n\n### Before Store Tool Result (Sanitize)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'before_store_tool_result',\n id: 'sanitize_results',\n execute: async (state, toolCall, toolResult) => {\n // toolCall: { id, type: 'function', function: { name, arguments } }\n // toolResult: { status, result?, error?, stack?, attachments? }\n if (toolResult.result) {\n return { ...toolResult, result: toolResult.result.replace(/secret/gi, '[REDACTED]') };\n }\n return toolResult;\n }\n});\n```\n\n### After Tool Call Success (Logging)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'after_tool_call_success',\n id: 'log_tool_success',\n execute: async (state, toolCall, result) => {\n console.log(`Tool ${toolCall.function.name} succeeded`);\n return null; // Return null to use original result\n }\n});\n```\n\n### After Tool Call Failure (Recovery)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'after_tool_call_failure',\n id: 'weather_fallback',\n execute: async (state, toolCall, result) => {\n if (toolCall.function.name === 'fetch_weather') {\n return {\n status: 'success',\n result: JSON.stringify({ temp: 'unavailable', fallback: true }),\n };\n }\n return null; // Use original error for other tools\n }\n});\n```\n\n## Hook Categories\n\n**Transformation hooks** (return modified data):\n- `after_system_message` (return replacement string, or null/undefined for no change)\n- `filter_messages`\n- `prefilter_llm_history`\n- `before_create_message`\n- `before_update_message`\n- `before_store_tool_result`\n- `after_tool_call_success` (return modified result or null)\n- `after_tool_call_failure` (return modified result or null)\n\n**Event hooks** (side effects only):\n- `after_thread_created`\n- `after_subagent_created`\n- `after_create_message`\n- `after_update_message`\n\n## Best Practices\n\n- **Keep hooks fast** - target <100ms execution\n- **Wrap in try-catch** - hooks continue on error (original data preserved)\n- **Use unique IDs** - hook IDs must be snake_case and unique across the project\n- **Scope appropriately** - assign hooks to prompts or agents that need them\n- **Document purpose** with clear comments\n- **Use for cross-cutting concerns** - logging, redaction, enrichment\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/hook\n";
12
12
 
13
- declare const API_CLAUDE_MD = "# Thread-Specific API Endpoints\n\nDefine custom API endpoints that operate on specific threads with access to the thread's ThreadState.\n\n## File-Based Routing\n\n| File Pattern | HTTP Method | Route |\n|--------------|-------------|-------|\n| `name.ts` | GET | `/api/threads/:threadId/name` |\n| `name.get.ts` | GET | `/api/threads/:threadId/name` |\n| `name.post.ts` | POST | `/api/threads/:threadId/name` |\n| `name.put.ts` | PUT | `/api/threads/:threadId/name` |\n| `name.delete.ts` | DELETE | `/api/threads/:threadId/name` |\n| `index.ts` | GET | `/api/threads/:threadId` |\n| `nested/route.ts` | GET | `/api/threads/:threadId/nested/route` |\n| `items/[id].ts` | GET | `/api/threads/:threadId/items/:id` |\n| `files/[*].ts` | GET | `/api/threads/:threadId/files/*` |\n\nFiles without a method suffix default to GET. Method suffixes are case-insensitive and support `.get.ts`, `.post.ts`, `.put.ts`, `.patch.ts`, and `.delete.ts`.\n\nDynamic segments use `[name]` and are passed to the handler as `params.name`. Catch-all segments use `[*]` and are passed as `params['*']`; the catch-all value may contain `/` for nested paths. Static routes match before dynamic routes, and dynamic routes match before catch-all routes.\n\n## Basic Example\n\n```typescript\n// agents/api/status.get.ts -> GET /api/threads/:threadId/status\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state, params) => {\n const { messages, total } = await state.getMessages();\n return Response.json({\n threadId: state.threadId,\n messageCount: total,\n status: 'active',\n params,\n });\n});\n```\n\n## Handler Parameters\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `req` | `Request` | The incoming HTTP request |\n| `state` | `ThreadState` | Thread state with messages, identity, file system, `runCode`, etc. |\n| `params` | `Record<string, string>` | Route parameters captured from `[name]` and `[*]` path segments |\n\nNote: `state.execution` is always `null` in endpoints since the thread is at rest. `state.runCode()` is available from endpoints and is forwarded into the thread runtime; pass plain transferable option values there, and do function-backed sandbox bridges from tools or in-thread execution contexts.\n\n## ThreadState Methods\n\nAccess thread data through the state object:\n\n```typescript\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n // Thread identity\n console.log('Thread ID:', state.threadId);\n console.log('Agent ID:', state.agentId);\n console.log('User ID:', state.userId);\n\n // Message operations\n const { messages, total, hasMore } = await state.getMessages({\n limit: 100,\n offset: 0,\n order: 'desc',\n });\n\n // Thread env (thread scope + active descendants)\n const approvalGate = await state.env('TOPDOWN_APPROVAL_GATE');\n await state.setEnv('TOPDOWN_APPROVAL_GATE', approvalGate || 'open');\n\n // Durable per-thread JSON values\n const exports = (await state.getValue<number>('export_count')) ?? 0;\n await state.setValue('export_count', exports + 1);\n\n // File system operations\n const files = await state.findFiles('**/*.json');\n const data = await state.readFile('/data/config.json');\n\n // Resource loading\n const agent = await state.loadAgent('my-agent');\n const prompt = await state.loadPrompt('my-prompt');\n\n return Response.json({ messages, total });\n});\n```\n\n## POST with Request Body\n\n```typescript\n// agents/api/export.post.ts -> POST /api/threads/:threadId/export\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n const body = await req.json();\n const { format = 'json' } = body;\n\n const { messages } = await state.getMessages();\n\n if (format === 'csv') {\n const csv = messages.map(m => `${m.role},${m.content}`).join('\\n');\n return new Response(csv, {\n headers: { 'Content-Type': 'text/csv' },\n });\n }\n\n return Response.json(messages);\n});\n```\n\n## Nested Routes\n\nCreate directories for nested routes:\n\n```\nagents/api/\n\u251C\u2500\u2500 status.get.ts -> GET /api/threads/:threadId/status\n\u251C\u2500\u2500 export.post.ts -> POST /api/threads/:threadId/export\n\u2514\u2500\u2500 messages/\n \u251C\u2500\u2500 count.ts -> GET /api/threads/:threadId/messages/count\n \u251C\u2500\u2500 [id].ts -> GET /api/threads/:threadId/messages/:id\n \u2514\u2500\u2500 [*].ts -> GET /api/threads/:threadId/messages/*\n```\n\n## Error Handling\n\n```typescript\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n try {\n const data = await riskyOperation();\n return Response.json(data);\n } catch (error) {\n return Response.json({ error: error.message }, { status: 500 });\n }\n});\n```\n\n## File System Operations\n\n```typescript\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n // Read files\n const content = await state.readFile('/data/file.txt');\n\n // Write files\n await state.writeFile('/output/result.json', JSON.stringify(data), 'application/json');\n\n // List directory\n const { entries } = await state.readdirFile('/data');\n\n // Search files\n const matches = await state.grepFiles('pattern');\n const paths = await state.findFiles('**/*.ts');\n\n return Response.json({ success: true });\n});\n```\n\n## Best Practices\n\n- **Keep handlers fast** - endpoints are in the request path\n- **Paginate large queries** - use limit/offset for messages\n- **Validate input data** - check request body before processing\n- **Use descriptive file names** - `export.post.ts` not `ep1.ts`\n- **Return proper status codes** - 200, 400, 404, 500\n- **Import from spec** - use `@standardagents/spec` for `defineThreadEndpoint`\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/core-concepts/api\n";
13
+ declare const API_AGENTS_MD = "# Thread-Specific API Endpoints\n\nDefine custom API endpoints that operate on specific threads with access to the thread's ThreadState.\n\n## File-Based Routing\n\n| File Pattern | HTTP Method | Route |\n|--------------|-------------|-------|\n| `name.ts` | GET | `/api/threads/:threadId/name` |\n| `name.get.ts` | GET | `/api/threads/:threadId/name` |\n| `name.post.ts` | POST | `/api/threads/:threadId/name` |\n| `name.put.ts` | PUT | `/api/threads/:threadId/name` |\n| `name.delete.ts` | DELETE | `/api/threads/:threadId/name` |\n| `index.ts` | GET | `/api/threads/:threadId` |\n| `nested/route.ts` | GET | `/api/threads/:threadId/nested/route` |\n| `items/[id].ts` | GET | `/api/threads/:threadId/items/:id` |\n| `files/[*].ts` | GET | `/api/threads/:threadId/files/*` |\n\nFiles without a method suffix default to GET. Method suffixes are case-insensitive and support `.get.ts`, `.post.ts`, `.put.ts`, `.patch.ts`, and `.delete.ts`.\n\nDynamic segments use `[name]` and are passed to the handler as `params.name`. Catch-all segments use `[*]` and are passed as `params['*']`; the catch-all value may contain `/` for nested paths. Static routes match before dynamic routes, and dynamic routes match before catch-all routes.\n\n## Basic Example\n\n```typescript\n// agents/api/status.get.ts -> GET /api/threads/:threadId/status\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state, params) => {\n const { messages, total } = await state.getMessages();\n return Response.json({\n threadId: state.threadId,\n messageCount: total,\n status: 'active',\n params,\n });\n});\n```\n\n## Handler Parameters\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `req` | `Request` | The incoming HTTP request |\n| `state` | `ThreadState` | Thread state with messages, identity, file system, `runCode`, etc. |\n| `params` | `Record<string, string>` | Route parameters captured from `[name]` and `[*]` path segments |\n\nNote: `state.execution` is always `null` in endpoints since the thread is at rest. `state.runCode()` is available from endpoints and is forwarded into the thread runtime; pass plain transferable option values there, and do function-backed sandbox bridges from tools or in-thread execution contexts.\n\n## ThreadState Methods\n\nAccess thread data through the state object:\n\n```typescript\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n // Thread identity\n console.log('Thread ID:', state.threadId);\n console.log('Agent ID:', state.agentId);\n console.log('User ID:', state.userId);\n\n // Message operations\n const { messages, total, hasMore } = await state.getMessages({\n limit: 100,\n offset: 0,\n order: 'desc',\n });\n\n // Thread env (thread scope + active descendants)\n const approvalGate = await state.env('TOPDOWN_APPROVAL_GATE');\n await state.setEnv('TOPDOWN_APPROVAL_GATE', approvalGate || 'open');\n\n // Durable per-thread JSON values\n const exports = (await state.getValue<number>('export_count')) ?? 0;\n await state.setValue('export_count', exports + 1);\n\n // File system operations\n const files = await state.findFiles('**/*.json');\n const data = await state.readFile('/data/config.json');\n\n // Resource loading\n const agent = await state.loadAgent('my-agent');\n const prompt = await state.loadPrompt('my-prompt');\n\n return Response.json({ messages, total });\n});\n```\n\n## POST with Request Body\n\n```typescript\n// agents/api/export.post.ts -> POST /api/threads/:threadId/export\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n const body = await req.json();\n const { format = 'json' } = body;\n\n const { messages } = await state.getMessages();\n\n if (format === 'csv') {\n const csv = messages.map(m => `${m.role},${m.content}`).join('\\n');\n return new Response(csv, {\n headers: { 'Content-Type': 'text/csv' },\n });\n }\n\n return Response.json(messages);\n});\n```\n\n## Nested Routes\n\nCreate directories for nested routes:\n\n```\nagents/api/\n\u251C\u2500\u2500 status.get.ts -> GET /api/threads/:threadId/status\n\u251C\u2500\u2500 export.post.ts -> POST /api/threads/:threadId/export\n\u2514\u2500\u2500 messages/\n \u251C\u2500\u2500 count.ts -> GET /api/threads/:threadId/messages/count\n \u251C\u2500\u2500 [id].ts -> GET /api/threads/:threadId/messages/:id\n \u2514\u2500\u2500 [*].ts -> GET /api/threads/:threadId/messages/*\n```\n\n## Error Handling\n\n```typescript\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n try {\n const data = await riskyOperation();\n return Response.json(data);\n } catch (error) {\n return Response.json({ error: error.message }, { status: 500 });\n }\n});\n```\n\n## File System Operations\n\n```typescript\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n // Read files\n const content = await state.readFile('/data/file.txt');\n\n // Write files\n await state.writeFile('/output/result.json', JSON.stringify(data), 'application/json');\n\n // List directory\n const { entries } = await state.readdirFile('/data');\n\n // Search files\n const matches = await state.grepFiles('pattern');\n const paths = await state.findFiles('**/*.ts');\n\n return Response.json({ success: true });\n});\n```\n\n## Best Practices\n\n- **Keep handlers fast** - endpoints are in the request path\n- **Paginate large queries** - use limit/offset for messages\n- **Validate input data** - check request body before processing\n- **Use descriptive file names** - `export.post.ts` not `ep1.ts`\n- **Return proper status codes** - 200, 400, 404, 500\n- **Import from spec** - use `@standardagents/spec` for `defineThreadEndpoint`\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/core-concepts/api\n";
14
14
 
15
15
  type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun';
16
16
  interface TemplateFile {
17
17
  path: string;
18
18
  content: string;
19
19
  message: string;
20
+ kind?: 'file' | 'symlink';
20
21
  }
21
22
  interface TemplateVersions {
22
23
  standardAgents: string;
23
24
  sip: string;
24
25
  vite: string;
25
26
  typescript: string;
26
- cloudflareVitePlugin: string;
27
- wrangler: string;
28
27
  zod?: string;
29
28
  }
30
29
  interface AgentBuilderProjectTemplateOptions {
31
30
  projectName: string;
32
31
  packageManager?: PackageManager | null;
33
32
  versions?: Partial<TemplateVersions>;
34
- compatibilityDate?: string;
35
- platformApiUrl?: string;
36
- includeDeployAutomation?: boolean;
37
33
  includeTemplateMetadata?: boolean;
38
34
  templateVersion?: string;
39
35
  }
40
36
  declare const FIRST_PARTY_PROVIDER_PACKAGES: readonly ["@standardagents/cloudflare", "@standardagents/cerebras", "@standardagents/google", "@standardagents/groq", "@standardagents/openai", "@standardagents/openrouter", "@standardagents/xai"];
41
37
  declare const DEFAULT_TEMPLATE_VERSIONS: TemplateVersions;
42
- declare const AGENTBUILDER_TEMPLATE_VERSION = "0.15.2";
43
- declare const DEFAULT_COMPATIBILITY_DATE = "2025-08-13";
38
+ declare const AGENTBUILDER_TEMPLATE_VERSION = "0.16.0";
44
39
  declare function packageNameFromProjectName(projectName: string): string;
45
40
  declare function renderPackageJson(options: AgentBuilderProjectTemplateOptions): string;
46
- declare function renderWranglerJson(options: AgentBuilderProjectTemplateOptions): string;
47
41
  declare function renderViteConfig(): string;
48
42
  declare function renderTsConfig(): string;
49
- declare function renderWorkerIndex(): string;
50
- declare function renderDurableThread(): string;
51
- declare function renderDurableAgentBuilder(): string;
52
43
  declare function renderGitignore(): string;
53
44
  declare function renderDevVarsExample(): string;
54
- declare function renderDeployHelper(): string;
55
- declare function renderDeployWorkflow(): string;
56
45
  declare function renderTemplateMetadata(options: AgentBuilderProjectTemplateOptions): string;
46
+ declare function renderAgentBuilderSupportFiles(options: AgentBuilderProjectTemplateOptions): TemplateFile[];
57
47
  declare function renderAgentBuilderProject(options: AgentBuilderProjectTemplateOptions): TemplateFile[];
58
48
 
59
- export { AGENTBUILDER_TEMPLATE_VERSION, AGENTS_CLAUDE_MD, API_CLAUDE_MD, type AgentBuilderProjectTemplateOptions, DEFAULT_COMPATIBILITY_DATE, DEFAULT_TEMPLATE_VERSIONS, FIRST_PARTY_PROVIDER_PACKAGES, HOOKS_CLAUDE_MD, MODELS_CLAUDE_MD, PROMPTS_CLAUDE_MD, type PackageManager, ROOT_CLAUDE_MD, TOOLS_CLAUDE_MD, type TemplateFile, type TemplateVersions, packageNameFromProjectName, renderAgentBuilderProject, renderDeployHelper, renderDeployWorkflow, renderDevVarsExample, renderDurableAgentBuilder, renderDurableThread, renderGitignore, renderPackageJson, renderTemplateMetadata, renderTsConfig, renderViteConfig, renderWorkerIndex, renderWranglerJson };
49
+ export { AGENTBUILDER_TEMPLATE_VERSION, AGENT_DEFINITIONS_AGENTS_MD as AGENTS_CLAUDE_MD, AGENT_DEFINITIONS_AGENTS_MD, API_AGENTS_MD, API_AGENTS_MD as API_CLAUDE_MD, type AgentBuilderProjectTemplateOptions, DEFAULT_TEMPLATE_VERSIONS, FIRST_PARTY_PROVIDER_PACKAGES, HOOKS_AGENTS_MD, HOOKS_AGENTS_MD as HOOKS_CLAUDE_MD, MODELS_AGENTS_MD, MODELS_AGENTS_MD as MODELS_CLAUDE_MD, PROMPTS_AGENTS_MD, PROMPTS_AGENTS_MD as PROMPTS_CLAUDE_MD, type PackageManager, ROOT_AGENTS_MD, ROOT_AGENTS_MD as ROOT_CLAUDE_MD, TOOLS_AGENTS_MD, TOOLS_AGENTS_MD as TOOLS_CLAUDE_MD, type TemplateFile, type TemplateVersions, packageNameFromProjectName, renderAgentBuilderProject, renderAgentBuilderSupportFiles, renderDevVarsExample, renderGitignore, renderPackageJson, renderTemplateMetadata, renderTsConfig, renderViteConfig };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/docs/root.ts
2
- var ROOT_CLAUDE_MD = `# Standard Agents
2
+ var ROOT_AGENTS_MD = `# Standard Agents
3
3
 
4
4
  This project uses Standard Agents - a framework for building AI agents on Cloudflare Workers.
5
5
 
@@ -64,25 +64,32 @@ defineAgent({
64
64
  ## File Structure
65
65
 
66
66
  \`\`\`
67
+ AGENTS.md # Project guidance for AI coding tools
68
+ CLAUDE.md -> AGENTS.md # Compatibility symlink
69
+ vite.config.ts # Uses builder(); Cloudflare config is generated
70
+ tsconfig.json # Includes agents and generated .agents types
67
71
  agents/
68
- \u251C\u2500\u2500 CLAUDE.md # This file
69
- \u251C\u2500\u2500 Thread.ts # Durable Object for conversation threads
70
- \u251C\u2500\u2500 AgentBuilder.ts # Durable Object for metadata
71
72
  \u251C\u2500\u2500 agents/ # Agent definitions (defineAgent)
72
- \u2502 \u2514\u2500\u2500 CLAUDE.md
73
+ \u2502 \u251C\u2500\u2500 AGENTS.md
74
+ \u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md
73
75
  \u251C\u2500\u2500 prompts/ # Prompt definitions (definePrompt)
74
- \u2502 \u2514\u2500\u2500 CLAUDE.md
76
+ \u2502 \u251C\u2500\u2500 AGENTS.md
77
+ \u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md
75
78
  \u251C\u2500\u2500 models/ # Model configurations (defineModel)
76
- \u2502 \u2514\u2500\u2500 CLAUDE.md
79
+ \u2502 \u251C\u2500\u2500 AGENTS.md
80
+ \u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md
77
81
  \u251C\u2500\u2500 tools/ # Custom tools (defineTool)
78
- \u2502 \u2514\u2500\u2500 CLAUDE.md
82
+ \u2502 \u251C\u2500\u2500 AGENTS.md
83
+ \u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md
79
84
  \u251C\u2500\u2500 hooks/ # Lifecycle hooks (defineHook)
80
- \u2502 \u2514\u2500\u2500 CLAUDE.md
85
+ \u2502 \u251C\u2500\u2500 AGENTS.md
86
+ \u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md
81
87
  \u2514\u2500\u2500 api/ # Thread API endpoints (defineThreadEndpoint)
82
- \u2514\u2500\u2500 CLAUDE.md
88
+ \u251C\u2500\u2500 AGENTS.md
89
+ \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md
83
90
  \`\`\`
84
91
 
85
- Files are **auto-discovered** at runtime. No manual registration needed.
92
+ The \`builder()\` Vite plugin generates the Worker entry, Durable Object bindings, Cloudflare Vite plugin configuration, and local \`.agents/\` support files at build time. Agent files are **auto-discovered** at runtime. No manual registration needed.
86
93
 
87
94
  ## ThreadState
88
95
 
@@ -193,7 +200,7 @@ Full documentation: https://docs.standardagentbuilder.com
193
200
  `;
194
201
 
195
202
  // src/docs/models.ts
196
- var MODELS_CLAUDE_MD = `# Model Definitions
203
+ var MODELS_AGENTS_MD = `# Model Definitions
197
204
 
198
205
  Models define which LLM provider and model to use for prompts.
199
206
 
@@ -246,7 +253,7 @@ as provider-executed server tools. Configure optional OpenRouter parameters with
246
253
  | Cheap Heavy | \`z-ai/glm-4.7\` | More capable, still affordable |
247
254
  | Heavy | \`google/gemini-3-pro-preview\` | Most capable, for complex tasks |
248
255
 
249
- **\u26A0\uFE0F Google Models**: When using Google models (\`google/gemini-*\`), you must enable \`reasoning\` in your prompt configuration or tool calls will fail. See the prompts CLAUDE.md for details.
256
+ **\u26A0\uFE0F Google Models**: When using Google models (\`google/gemini-*\`), you must enable \`reasoning\` in your prompt configuration or tool calls will fail. See the prompts AGENTS.md for details.
250
257
 
251
258
  ## Provider API Keys
252
259
 
@@ -303,7 +310,7 @@ Full reference: https://docs.standardagentbuilder.com/api-reference/define/model
303
310
  `;
304
311
 
305
312
  // src/docs/prompts.ts
306
- var PROMPTS_CLAUDE_MD = `# Prompt Definitions
313
+ var PROMPTS_AGENTS_MD = `# Prompt Definitions
307
314
 
308
315
  Prompts define system instructions, model selection, and available tools for LLM interactions.
309
316
 
@@ -493,7 +500,7 @@ export default definePrompt({
493
500
  });
494
501
  \`\`\`
495
502
 
496
- Prompt hooks take precedence over agent hooks. See \`agents/hooks/CLAUDE.md\` for details.
503
+ Prompt hooks take precedence over agent hooks. See \`agents/hooks/AGENTS.md\` for details.
497
504
 
498
505
  ## Best Practices
499
506
 
@@ -509,7 +516,7 @@ Full reference: https://docs.standardagentbuilder.com/api-reference/define/promp
509
516
  `;
510
517
 
511
518
  // src/docs/agents.ts
512
- var AGENTS_CLAUDE_MD = `# Agent Definitions
519
+ var AGENT_DEFINITIONS_AGENTS_MD = `# Agent Definitions
513
520
 
514
521
  Agents orchestrate conversations by defining prompts, stop conditions, and turn limits.
515
522
 
@@ -654,7 +661,7 @@ export default defineAgent({
654
661
  });
655
662
  \`\`\`
656
663
 
657
- Agent hooks run as a fallback when the active prompt has no hooks defined. Prompt hooks always take precedence. See \`agents/hooks/CLAUDE.md\` for details.
664
+ Agent hooks run as a fallback when the active prompt has no hooks defined. Prompt hooks always take precedence. See \`agents/hooks/AGENTS.md\` for details.
658
665
 
659
666
  ## Naming Convention
660
667
 
@@ -676,7 +683,7 @@ Full reference: https://docs.standardagentbuilder.com/api-reference/define/agent
676
683
  `;
677
684
 
678
685
  // src/docs/tools.ts
679
- var TOOLS_CLAUDE_MD = `# Custom Tools
686
+ var TOOLS_AGENTS_MD = `# Custom Tools
680
687
 
681
688
  Tools extend agent capabilities beyond text generation. They allow LLMs to fetch data, perform calculations, execute side effects, and chain to other prompts or agents.
682
689
 
@@ -929,7 +936,7 @@ Full reference: https://docs.standardagentbuilder.com/api-reference/define/tool
929
936
  `;
930
937
 
931
938
  // src/docs/hooks.ts
932
- var HOOKS_CLAUDE_MD = `# Lifecycle Hooks
939
+ var HOOKS_AGENTS_MD = `# Lifecycle Hooks
933
940
 
934
941
  Hooks intercept and modify agent execution at specific lifecycle points.
935
942
 
@@ -1144,7 +1151,7 @@ Full reference: https://docs.standardagentbuilder.com/api-reference/define/hook
1144
1151
  `;
1145
1152
 
1146
1153
  // src/docs/api.ts
1147
- var API_CLAUDE_MD = `# Thread-Specific API Endpoints
1154
+ var API_AGENTS_MD = `# Thread-Specific API Endpoints
1148
1155
 
1149
1156
  Define custom API endpoints that operate on specific threads with access to the thread's ThreadState.
1150
1157
 
@@ -1337,12 +1344,9 @@ var DEFAULT_TEMPLATE_VERSIONS = {
1337
1344
  sip: "latest",
1338
1345
  vite: "latest",
1339
1346
  typescript: "latest",
1340
- cloudflareVitePlugin: "latest",
1341
- wrangler: "latest",
1342
1347
  zod: "latest"
1343
1348
  };
1344
- var AGENTBUILDER_TEMPLATE_VERSION = "0.15.2";
1345
- var DEFAULT_COMPATIBILITY_DATE = "2025-08-13";
1349
+ var AGENTBUILDER_TEMPLATE_VERSION = "0.16.0";
1346
1350
  function ensureTrailingNewline(value) {
1347
1351
  return value.endsWith("\n") ? value : `${value}
1348
1352
  `;
@@ -1361,7 +1365,16 @@ function file(path, content, message) {
1361
1365
  return {
1362
1366
  path,
1363
1367
  content: ensureTrailingNewline(content),
1364
- message
1368
+ message,
1369
+ kind: "file"
1370
+ };
1371
+ }
1372
+ function symlink(path, target, message) {
1373
+ return {
1374
+ path,
1375
+ content: target,
1376
+ message,
1377
+ kind: "symlink"
1365
1378
  };
1366
1379
  }
1367
1380
  function renderPackageJson(options) {
@@ -1384,77 +1397,22 @@ function renderPackageJson(options) {
1384
1397
  scripts: {
1385
1398
  dev: "vite --host 0.0.0.0 --port 5173",
1386
1399
  build: "vite build",
1387
- typecheck: "tsc --noEmit",
1388
- "wrangler:types": "wrangler types"
1400
+ typecheck: "tsc --noEmit"
1389
1401
  },
1390
1402
  dependencies,
1391
1403
  devDependencies: {
1392
- "@cloudflare/vite-plugin": versions.cloudflareVitePlugin,
1393
1404
  typescript: versions.typescript,
1394
- vite: versions.vite,
1395
- wrangler: versions.wrangler
1405
+ vite: versions.vite
1396
1406
  }
1397
1407
  }, null, 2)}
1398
1408
  `;
1399
1409
  }
1400
- function renderWranglerJson(options) {
1401
- const compatibilityDate = options.compatibilityDate ?? DEFAULT_COMPATIBILITY_DATE;
1402
- const workerName = packageNameFromProjectName(options.projectName);
1403
- return `{
1404
- "$schema": "node_modules/wrangler/config-schema.json",
1405
- "name": "${workerName}",
1406
- "main": "worker/index.ts",
1407
- "compatibility_date": "${compatibilityDate}",
1408
- "compatibility_flags": ["nodejs_compat", "enable_ctx_exports"],
1409
- "observability": {
1410
- "enabled": true
1411
- },
1412
- "worker_loaders": [
1413
- {
1414
- "binding": "AGENT_BUILDER_CODE_LOADER"
1415
- }
1416
- ],
1417
- "vars": {
1418
- "AGENT_BUILDER_CODE_COMPATIBILITY_DATE": "${compatibilityDate}"
1419
- },
1420
- "assets": {
1421
- "directory": "dist/client",
1422
- "not_found_handling": "single-page-application",
1423
- "binding": "ASSETS",
1424
- "run_worker_first": ["/**"]
1425
- },
1426
- "durable_objects": {
1427
- "bindings": [
1428
- {
1429
- "name": "AGENT_BUILDER_THREAD",
1430
- "class_name": "DurableThread"
1431
- },
1432
- {
1433
- "name": "AGENT_BUILDER",
1434
- "class_name": "DurableAgentBuilder"
1435
- }
1436
- ]
1437
- },
1438
- "migrations": [
1439
- {
1440
- "tag": "v1",
1441
- "new_sqlite_classes": ["DurableThread"]
1442
- },
1443
- {
1444
- "tag": "v2",
1445
- "new_sqlite_classes": ["DurableAgentBuilder"]
1446
- }
1447
- ]
1448
- }
1449
- `;
1450
- }
1451
1410
  function renderViteConfig() {
1452
1411
  return `import { defineConfig } from "vite"
1453
- import { cloudflare } from "@cloudflare/vite-plugin"
1454
- import { agentbuilder } from "@standardagents/builder"
1412
+ import { builder } from "@standardagents/builder"
1455
1413
 
1456
1414
  export default defineConfig({
1457
- plugins: [agentbuilder({ mountPoint: "/" }), cloudflare()],
1415
+ plugins: [builder()],
1458
1416
  })
1459
1417
  `;
1460
1418
  }
@@ -1473,35 +1431,8 @@ function renderTsConfig() {
1473
1431
  "noEmit": true,
1474
1432
  "strict": true
1475
1433
  },
1476
- "include": ["worker", "agents"]
1477
- }
1478
- `;
1479
- }
1480
- function renderWorkerIndex() {
1481
- return `import { router, CodeExecutionBridge } from "virtual:@standardagents/builder"
1482
- import DurableThread from "../agents/Thread"
1483
- import DurableAgentBuilder from "../agents/AgentBuilder"
1484
-
1485
- export default {
1486
- async fetch(request, env) {
1487
- const res = await router(request, env)
1488
- return res ?? new Response(null, { status: 404 })
1489
- },
1490
- } satisfies ExportedHandler<Env>
1491
-
1492
- export { DurableThread, DurableAgentBuilder, CodeExecutionBridge }
1493
- `;
1494
- }
1495
- function renderDurableThread() {
1496
- return `import { DurableThread } from "virtual:@standardagents/builder"
1497
-
1498
- export default class Thread extends DurableThread {}
1499
- `;
1434
+ "include": ["agents", ".agents", "vite.config.ts"]
1500
1435
  }
1501
- function renderDurableAgentBuilder() {
1502
- return `import { DurableAgentBuilder } from "virtual:@standardagents/builder"
1503
-
1504
- export default class AgentBuilder extends DurableAgentBuilder {}
1505
1436
  `;
1506
1437
  }
1507
1438
  function renderGitignore() {
@@ -1538,133 +1469,6 @@ OPENROUTER_API_KEY=
1538
1469
  XAI_API_KEY=
1539
1470
  `;
1540
1471
  }
1541
- function renderDeployHelper() {
1542
- return `import fs from "node:fs";
1543
- import path from "node:path";
1544
-
1545
- function findBundleInDir(dir) {
1546
- const entries = fs.readdirSync(dir, { withFileTypes: true });
1547
- const files = entries
1548
- .filter((entry) => entry.isFile() && /\\.(m?js)$/.test(entry.name))
1549
- .sort((a, b) => {
1550
- const aIsIndex = a.name === "index.js" || a.name === "index.mjs" ? 0 : 1;
1551
- const bIsIndex = b.name === "index.js" || b.name === "index.mjs" ? 0 : 1;
1552
- if (aIsIndex !== bIsIndex) return aIsIndex - bIsIndex;
1553
- return fs.statSync(path.join(dir, b.name)).size - fs.statSync(path.join(dir, a.name)).size;
1554
- });
1555
-
1556
- for (const file of files) {
1557
- const filePath = path.join(dir, file.name);
1558
- const content = fs.readFileSync(filePath, "utf8");
1559
- if (content.includes("export default") || content.includes("export {")) {
1560
- return { path: filePath, content };
1561
- }
1562
- }
1563
-
1564
- for (const entry of entries) {
1565
- if (!entry.isDirectory() || entry.name === "client" || entry.name === "node_modules") continue;
1566
- const nested = findBundleInDir(path.join(dir, entry.name));
1567
- if (nested) return nested;
1568
- }
1569
- return null;
1570
- }
1571
-
1572
- function findWorkerBundle() {
1573
- for (const dir of [".wrangler/tmp", "dist"]) {
1574
- if (!fs.existsSync(dir)) continue;
1575
- const bundle = findBundleInDir(dir);
1576
- if (bundle) return bundle;
1577
- }
1578
- throw new Error("Could not find a Worker bundle in .wrangler/tmp or dist");
1579
- }
1580
-
1581
- const deployUrl = process.env.STANDARD_AGENTS_DEPLOY_URL;
1582
- const deployToken = process.env.STANDARD_AGENTS_DEPLOY_TOKEN;
1583
- const buildId = process.env.STANDARD_AGENTS_BUILD_ID;
1584
- if (!deployUrl || !deployToken || !buildId) {
1585
- throw new Error("Missing Standard Agents deployment environment");
1586
- }
1587
-
1588
- const bundle = findWorkerBundle();
1589
- const response = await fetch(deployUrl, {
1590
- method: "POST",
1591
- headers: {
1592
- "Authorization": \`Bearer \${deployToken}\`,
1593
- "Content-Type": "application/json",
1594
- },
1595
- body: JSON.stringify({
1596
- build_id: buildId,
1597
- script_content: bundle.content,
1598
- compatibility_date: process.env.STANDARD_AGENTS_COMPATIBILITY_DATE || undefined,
1599
- }),
1600
- });
1601
-
1602
- if (!response.ok) {
1603
- const text = await response.text();
1604
- throw new Error(\`Standard Agents deploy failed (\${response.status}): \${text}\`);
1605
- }
1606
-
1607
- console.log(\`Deployed Standard Agents Worker from \${bundle.path}\`);
1608
- `;
1609
- }
1610
- function renderDeployWorkflow() {
1611
- return `name: Standard Agents Deploy
1612
-
1613
- on:
1614
- repository_dispatch:
1615
- types: [standardagents-deploy]
1616
-
1617
- permissions:
1618
- contents: read
1619
-
1620
- jobs:
1621
- deploy:
1622
- runs-on: ubuntu-latest
1623
- env:
1624
- STANDARD_AGENTS_BUILD_ID: \${{ github.event.client_payload.build_id }}
1625
- STANDARD_AGENTS_DEPLOY_URL: \${{ github.event.client_payload.deploy_url }}
1626
- STANDARD_AGENTS_DEPLOY_TOKEN: \${{ github.event.client_payload.deploy_token }}
1627
- STANDARD_AGENTS_COMPATIBILITY_DATE: \${{ github.event.client_payload.compatibility_date }}
1628
- STANDARD_AGENTS_API_URL: \${{ github.event.client_payload.api_url }}
1629
- steps:
1630
- - uses: actions/checkout@v4
1631
- with:
1632
- ref: \${{ github.event.client_payload.commit_sha }}
1633
- - uses: actions/setup-node@v4
1634
- with:
1635
- node-version: 22
1636
- - name: Enable package managers
1637
- run: corepack enable
1638
- - name: Install dependencies
1639
- shell: bash
1640
- run: |
1641
- if [ -f pnpm-lock.yaml ]; then
1642
- pnpm install --frozen-lockfile || pnpm install
1643
- elif [ -f yarn.lock ]; then
1644
- yarn install --immutable || yarn install
1645
- elif [ -f bun.lockb ] || [ -f bun.lock ]; then
1646
- bun install --frozen-lockfile || bun install
1647
- elif [ -f package-lock.json ]; then
1648
- npm ci || npm install
1649
- else
1650
- npm install
1651
- fi
1652
- - name: Build
1653
- shell: bash
1654
- run: |
1655
- if [ -f pnpm-lock.yaml ]; then
1656
- pnpm run build
1657
- elif [ -f yarn.lock ]; then
1658
- yarn build
1659
- elif [ -f bun.lockb ] || [ -f bun.lock ]; then
1660
- bun run build
1661
- else
1662
- npm run build
1663
- fi
1664
- - name: Upload Worker
1665
- run: node .github/standardagents-deploy.mjs
1666
- `;
1667
- }
1668
1472
  function renderTemplateMetadata(options) {
1669
1473
  return `${JSON.stringify({
1670
1474
  generator: "@standardagents/agentbuilder-template",
@@ -1673,61 +1477,59 @@ function renderTemplateMetadata(options) {
1673
1477
  }, null, 2)}
1674
1478
  `;
1675
1479
  }
1480
+ function renderAgentBuilderSupportFiles(options) {
1481
+ return [
1482
+ file("package.json", renderPackageJson(options), "Add local AgentBuilder package manifest")
1483
+ ];
1484
+ }
1676
1485
  function renderAgentBuilderProject(options) {
1677
1486
  const files = [
1678
- file("package.json", renderPackageJson(options), "Add AgentBuilder package manifest"),
1679
1487
  file("tsconfig.json", renderTsConfig(), "Add TypeScript config"),
1680
1488
  file("vite.config.ts", renderViteConfig(), "Add Vite config"),
1681
- file("wrangler.jsonc", renderWranglerJson(options), "Add Wrangler config"),
1682
- file("worker/index.ts", renderWorkerIndex(), "Add Worker entrypoint"),
1683
- file("agents/Thread.ts", renderDurableThread(), "Add DurableThread"),
1684
- file("agents/AgentBuilder.ts", renderDurableAgentBuilder(), "Add DurableAgentBuilder"),
1685
- file("agents/agents/CLAUDE.md", AGENTS_CLAUDE_MD, "Add agent docs"),
1686
- file("agents/prompts/CLAUDE.md", PROMPTS_CLAUDE_MD, "Add prompt docs"),
1687
- file("agents/models/CLAUDE.md", MODELS_CLAUDE_MD, "Add model docs"),
1688
- file("agents/tools/CLAUDE.md", TOOLS_CLAUDE_MD, "Add tool docs"),
1689
- file("agents/hooks/CLAUDE.md", HOOKS_CLAUDE_MD, "Add hook docs"),
1690
- file("agents/api/CLAUDE.md", API_CLAUDE_MD, "Add API docs"),
1691
- file("CLAUDE.md", ROOT_CLAUDE_MD, "Add AgentBuilder project docs"),
1692
- file(".dev.vars.example", renderDevVarsExample(), "Add local env example"),
1693
- file(".gitignore", renderGitignore(), "Add gitignore")
1489
+ file("agents/agents/AGENTS.md", AGENT_DEFINITIONS_AGENTS_MD, "Add agent docs"),
1490
+ symlink("agents/agents/CLAUDE.md", "AGENTS.md", "Add Claude agent docs symlink"),
1491
+ file("agents/prompts/AGENTS.md", PROMPTS_AGENTS_MD, "Add prompt docs"),
1492
+ symlink("agents/prompts/CLAUDE.md", "AGENTS.md", "Add Claude prompt docs symlink"),
1493
+ file("agents/models/AGENTS.md", MODELS_AGENTS_MD, "Add model docs"),
1494
+ symlink("agents/models/CLAUDE.md", "AGENTS.md", "Add Claude model docs symlink"),
1495
+ file("agents/tools/AGENTS.md", TOOLS_AGENTS_MD, "Add tool docs"),
1496
+ symlink("agents/tools/CLAUDE.md", "AGENTS.md", "Add Claude tool docs symlink"),
1497
+ file("agents/hooks/AGENTS.md", HOOKS_AGENTS_MD, "Add hook docs"),
1498
+ symlink("agents/hooks/CLAUDE.md", "AGENTS.md", "Add Claude hook docs symlink"),
1499
+ file("agents/api/AGENTS.md", API_AGENTS_MD, "Add API docs"),
1500
+ symlink("agents/api/CLAUDE.md", "AGENTS.md", "Add Claude API docs symlink")
1694
1501
  ];
1695
1502
  if (options.includeTemplateMetadata) {
1696
1503
  files.push(file(".standardagents/template.json", renderTemplateMetadata(options), "Add Standard Agents template metadata"));
1697
1504
  }
1698
- if (options.includeDeployAutomation) {
1699
- files.push(
1700
- file(".github/standardagents-deploy.mjs", renderDeployHelper(), "Add Standard Agents deploy helper"),
1701
- file(".github/workflows/standardagents-deploy.yml", renderDeployWorkflow(), "Add Standard Agents deploy workflow")
1702
- );
1703
- }
1704
1505
  return files;
1705
1506
  }
1706
1507
  export {
1707
1508
  AGENTBUILDER_TEMPLATE_VERSION,
1708
- AGENTS_CLAUDE_MD,
1709
- API_CLAUDE_MD,
1710
- DEFAULT_COMPATIBILITY_DATE,
1509
+ AGENT_DEFINITIONS_AGENTS_MD as AGENTS_CLAUDE_MD,
1510
+ AGENT_DEFINITIONS_AGENTS_MD,
1511
+ API_AGENTS_MD,
1512
+ API_AGENTS_MD as API_CLAUDE_MD,
1711
1513
  DEFAULT_TEMPLATE_VERSIONS,
1712
1514
  FIRST_PARTY_PROVIDER_PACKAGES,
1713
- HOOKS_CLAUDE_MD,
1714
- MODELS_CLAUDE_MD,
1715
- PROMPTS_CLAUDE_MD,
1716
- ROOT_CLAUDE_MD,
1717
- TOOLS_CLAUDE_MD,
1515
+ HOOKS_AGENTS_MD,
1516
+ HOOKS_AGENTS_MD as HOOKS_CLAUDE_MD,
1517
+ MODELS_AGENTS_MD,
1518
+ MODELS_AGENTS_MD as MODELS_CLAUDE_MD,
1519
+ PROMPTS_AGENTS_MD,
1520
+ PROMPTS_AGENTS_MD as PROMPTS_CLAUDE_MD,
1521
+ ROOT_AGENTS_MD,
1522
+ ROOT_AGENTS_MD as ROOT_CLAUDE_MD,
1523
+ TOOLS_AGENTS_MD,
1524
+ TOOLS_AGENTS_MD as TOOLS_CLAUDE_MD,
1718
1525
  packageNameFromProjectName,
1719
1526
  renderAgentBuilderProject,
1720
- renderDeployHelper,
1721
- renderDeployWorkflow,
1527
+ renderAgentBuilderSupportFiles,
1722
1528
  renderDevVarsExample,
1723
- renderDurableAgentBuilder,
1724
- renderDurableThread,
1725
1529
  renderGitignore,
1726
1530
  renderPackageJson,
1727
1531
  renderTemplateMetadata,
1728
1532
  renderTsConfig,
1729
- renderViteConfig,
1730
- renderWorkerIndex,
1731
- renderWranglerJson
1533
+ renderViteConfig
1732
1534
  };
1733
1535
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/docs/root.ts","../src/docs/models.ts","../src/docs/prompts.ts","../src/docs/agents.ts","../src/docs/tools.ts","../src/docs/hooks.ts","../src/docs/api.ts","../src/index.ts"],"sourcesContent":["export const ROOT_CLAUDE_MD = `# Standard Agents\n\nThis project uses Standard Agents - a framework for building AI agents on Cloudflare Workers.\n\n## Architecture Overview\n\nStandard Agents uses a **composition model** where four core components work together:\n\n\\`\\`\\`\nModel → Prompt → Agent → Thread\n │ │ │ │\n │ │ │ └─ Conversation instance (Durable Object)\n │ │ └─ Orchestrates conversation flow\n │ └─ System instructions + tools\n └─ LLM provider configuration\n\\`\\`\\`\n\n**Models** define which LLM to use (provider, model ID, pricing, fallbacks).\n**Prompts** define what the LLM should do (system instructions, available tools).\n**Agents** orchestrate conversations (which prompt, stop conditions, turn limits).\n**Threads** are individual conversation instances with persistent storage.\n\n## How Components Compose\n\n### Basic Flow\n1. User creates a thread with an agent\n2. Agent uses its configured prompt\n3. Prompt specifies the model and tools\n4. LLM responds, potentially calling tools\n5. Tools execute and return results\n6. Loop continues until stop condition\n\n### Sub-Prompts (Prompts as Tools)\nPrompts can call other prompts as tools. This enables:\n- **Specialized reasoning**: A main prompt delegates to expert sub-prompts\n- **Structured outputs**: Sub-prompt validates and formats data\n- **Context isolation**: Sub-prompt gets fresh context without full history\n\n\\`\\`\\`typescript\n// Main prompt can call 'data_extractor' as a tool\ndefinePrompt({\n name: 'main_assistant',\n tools: ['data_extractor'], // Another prompt exposed as tool\n // ...\n});\n\\`\\`\\`\n\n### Agent Handoffs (Agents as Tools)\nAgents can delegate to other agents entirely:\n- **Specialization**: Route to domain-specific agents\n- **Escalation**: Hand off to more capable agents\n- **Workflows**: Chain agents for multi-step processes\n\n\\`\\`\\`typescript\ndefineAgent({\n name: 'triage_agent',\n exposeAsTool: true,\n toolDescription: 'Hand off to triage for initial assessment',\n // ...\n});\n\\`\\`\\`\n\n## File Structure\n\n\\`\\`\\`\nagents/\n├── CLAUDE.md # This file\n├── Thread.ts # Durable Object for conversation threads\n├── AgentBuilder.ts # Durable Object for metadata\n├── agents/ # Agent definitions (defineAgent)\n│ └── CLAUDE.md\n├── prompts/ # Prompt definitions (definePrompt)\n│ └── CLAUDE.md\n├── models/ # Model configurations (defineModel)\n│ └── CLAUDE.md\n├── tools/ # Custom tools (defineTool)\n│ └── CLAUDE.md\n├── hooks/ # Lifecycle hooks (defineHook)\n│ └── CLAUDE.md\n└── api/ # Thread API endpoints (defineThreadEndpoint)\n └── CLAUDE.md\n\\`\\`\\`\n\nFiles are **auto-discovered** at runtime. No manual registration needed.\n\n## ThreadState\n\n\\`ThreadState\\` is the state object available in tools and hooks:\n\n\\`\\`\\`typescript\ninterface ThreadState {\n // Identity (readonly)\n threadId: string; // Thread identifier\n agentId: string; // Agent identifier\n userId: string | null; // User identifier (if set)\n createdAt: number; // Creation timestamp\n children: SubagentRegistryEntry[]; // Resumable child registry\n terminated: number | null; // Soft-termination timestamp\n\n // Methods\n getMessages(options?): Promise<MessagesResult>; // Get conversation history\n injectMessage(input): Promise<Message>; // Add message to thread\n queueMessage(input): Promise<void>; // Queue message for next step\n loadModel(name): Promise<ModelConfig>; // Load model definition\n loadPrompt(name): Promise<PromptConfig>; // Load prompt definition\n loadAgent(name): Promise<AgentConfig>; // Load agent definition\n env(propertyName): Promise<string>; // Resolve env value for this thread\n setEnv(propertyName, value): Promise<void>; // Set thread env + propagate to active descendants\n getValue<T = unknown>(key: string): Promise<T | null>; // Read durable per-thread JSON value\n setValue(key: string, value: unknown): Promise<void>; // Write durable value; null/undefined deletes\n notifyParent(content): Promise<void>; // Explicitly queue a silent message to the parent\n setStatus(status): Promise<void>; // Update this child in the parent registry\n getChildThread(referenceId): Promise<ThreadState | null>; // Resolve child thread\n getParentThread(): Promise<ThreadState | null>; // Resolve parent thread\n terminate(): Promise<void>; // Soft-terminate thread\n runCode(source, options?): CodeExecution; // Run JS/TS in a fresh Dynamic Worker sandbox\n}\n\\`\\`\\`\n\n\\`runCode\\` has no implicit access to thread state, filesystem, network, timers, or host globals. Bridge only the exact capabilities needed through \\`imports\\` or \\`globals\\`; use \\`modules\\` for local relative ES modules; use \\`execute\\` to select the export and args to run. \\`modules\\` keys are graph-root relative paths; entry-source imports resolve from \\`filename\\` when supplied, including \\`../\\` parent paths that stay inside the supplied graph. TypeScript input is accepted by default and erased before evaluation. In thread endpoints, \\`runCode\\` is forwarded into the thread Durable Object; pass plain transferable options there and keep function-backed bridges in tools or in-thread execution contexts.\n\n## Subagents\n\n\\`dual_ai\\` agents can be used as subagents from prompt tool configs:\n\n- Each subagent runs in its own thread (\\`DurableThread\\`)\n- Parent/child linkage is tracked in thread metadata\n- Resumable children are visible in \\`state.children\\`\n- Parent threads create/message resumable children via built-ins (\\`subagent_create\\`, \\`subagent_message\\`)\n- Child completion results are queued back to the parent when \\`parentCommunication\\` is \\`implicit\\`\n- Explicit relationships can stay idle until code calls \\`state.notifyParent()\\` or \\`state.setStatus()\\`\n\nAccess in tools:\n\\`\\`\\`typescript\nexport default defineTool('...', schema, async (state, args) => {\n const threadId = state.threadId;\n const { messages } = await state.getMessages();\n const count = (await state.getValue<number>('invocation_count')) ?? 0;\n await state.setValue('invocation_count', count + 1);\n // ...\n});\n\\`\\`\\`\n\nAccess in hooks:\n\\`\\`\\`typescript\nexport default defineHook({\n hook: 'before_create_message',\n id: 'my_hook',\n execute: async (state, message) => {\n console.log(\\`Thread: \\${state.threadId}, Agent: \\${state.agentId}\\`);\n return message;\n }\n});\n\\`\\`\\`\n\n## Quick Reference\n\n| Function | Purpose | Directory |\n|----------|---------|-----------|\n| \\`defineModel()\\` | Configure LLM provider | \\`agents/models/\\` |\n| \\`definePrompt()\\` | System instructions + tools | \\`agents/prompts/\\` |\n| \\`defineAgent()\\` | Conversation orchestration | \\`agents/agents/\\` |\n| \\`defineTool()\\` | Custom tool functions | \\`agents/tools/\\` |\n| \\`defineHook()\\` | Lifecycle interception | \\`agents/hooks/\\` |\n| \\`defineThreadEndpoint()\\` | Custom API routes | \\`agents/api/\\` |\n\n## Runtime Utilities\n\nImport from \\`@standardagents/builder\\`:\n\n\\`\\`\\`typescript\nimport {\n queueTool, // Queue another tool for execution\n injectMessage, // Add message without triggering execution\n getMessages, // Retrieve message history\n emitThreadEvent, // Send custom WebSocket events\n} from '@standardagents/builder';\n\\`\\`\\`\n\n## Documentation\n\nFull documentation: https://docs.standardagentbuilder.com\n\n- [Architecture Overview](https://docs.standardagentbuilder.com/introduction/architecture)\n- [Models](https://docs.standardagentbuilder.com/core-concepts/models)\n- [Prompts](https://docs.standardagentbuilder.com/core-concepts/prompts)\n- [Agents](https://docs.standardagentbuilder.com/core-concepts/agents)\n- [Tools](https://docs.standardagentbuilder.com/core-concepts/tools)\n- [Hooks](https://docs.standardagentbuilder.com/core-concepts/hooks)\n- [ThreadState](https://docs.standardagentbuilder.com/core-concepts/threadstate)\n- [Thread API](https://docs.standardagentbuilder.com/core-concepts/api)\n`;\n","export const MODELS_CLAUDE_MD = `# Model Definitions\n\nModels define which LLM provider and model to use for prompts.\n\n## Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| \\`name\\` | \\`string\\` | Yes | Unique identifier for this model configuration |\n| \\`provider\\` | \\`'openai' \\\\| 'anthropic' \\\\| 'openrouter' \\\\| 'google' \\\\| 'cerebras' \\\\| 'groq' \\\\| 'xai'\\` | Yes | LLM provider |\n| \\`model\\` | \\`string\\` | Yes | Model ID sent to provider API |\n| \\`fallbacks\\` | \\`string[]\\` | No | Fallback model names to try if primary fails |\n| \\`inputPrice\\` | \\`number\\` | No | Cost per 1M input tokens (USD) |\n| \\`outputPrice\\` | \\`number\\` | No | Cost per 1M output tokens (USD) |\n| \\`cachedPrice\\` | \\`number\\` | No | Cost per 1M cached input tokens |\n| \\`includedProviders\\` | \\`string[]\\` | No | Provider prefixes for OpenRouter routing |\n| \\`providerTools\\` | \\`string[]\\` | No | Provider-built-in tool names to make available for prompts using this model |\n\n## Example\n\n\\`\\`\\`typescript\nimport { defineModel } from '@standardagents/builder';\n\nexport default defineModel({\n name: 'default',\n provider: 'openrouter',\n model: 'google/gemini-3-flash-preview',\n fallbacks: ['fast', 'cheap-heavy'],\n});\n\\`\\`\\`\n\n## Provider Tools\n\nProviders can expose built-in tools such as search, file search, code execution,\nor provider-specific tools through their \\`getTools()\\` implementation. Enable the\nprovider tool names on the model with \\`providerTools\\`; prompts can then include\nthose tools like normal tool names. Provider tools execute on the upstream\nprovider, not in AgentBuilder, and successful calls are logged as provider tool\nentries.\n\nOpenRouter exposes \\`web_search\\`, \\`web_fetch\\`, \\`datetime\\`, and \\`image_generation\\`\nas provider-executed server tools. Configure optional OpenRouter parameters with\n\\`providerOptions.serverTools\\` on the model.\n\n## Recommended Models (OpenRouter)\n\n| Use Case | Model ID | Description |\n|----------|----------|-------------|\n| Fast/Cheap | \\`z-ai/glm-4.5-air\\` | Quick responses, low cost |\n| Mid-tier | \\`google/gemini-3-flash-preview\\` | Good balance of speed and quality |\n| Cheap Heavy | \\`z-ai/glm-4.7\\` | More capable, still affordable |\n| Heavy | \\`google/gemini-3-pro-preview\\` | Most capable, for complex tasks |\n\n**⚠️ Google Models**: When using Google models (\\`google/gemini-*\\`), you must enable \\`reasoning\\` in your prompt configuration or tool calls will fail. See the prompts CLAUDE.md for details.\n\n## Provider API Keys\n\nSet these environment variables in \\`.dev.vars\\` (local) or Cloudflare secrets (production):\n\n| Provider | Environment Variable |\n|----------|---------------------|\n| Cerebras | \\`CEREBRAS_API_KEY\\` |\n| Groq | \\`GROQ_API_KEY\\` |\n| OpenAI | \\`OPENAI_API_KEY\\` |\n| Anthropic | \\`ANTHROPIC_API_KEY\\` |\n| OpenRouter | \\`OPENROUTER_API_KEY\\` |\n| Google | \\`GOOGLE_API_KEY\\` |\n| xAI | \\`XAI_API_KEY\\` |\n\nIf \\`STANDARD_AGENTS_API_KEY\\` is present and a provider-specific key is not set,\nfirst-party Standard Agents providers route through the hosted Standard Agents\nrouter. Setting a provider-specific key always uses that provider directly.\n\n## Fallback Strategy\n\nWhen a model fails, fallbacks are tried in order:\n1. Primary model (2 attempts)\n2. First fallback (2 attempts)\n3. Second fallback (2 attempts)\n4. ...and so on\n\nRetries occur on: network errors, rate limits (429), server errors (5xx), auth errors (401).\n\n## OpenRouter Configuration\n\nFor OpenRouter, use the full model path:\n\n\\`\\`\\`typescript\nexport default defineModel({\n name: 'heavy',\n provider: 'openrouter',\n model: 'google/gemini-3-pro-preview',\n includedProviders: ['google'], // Prefer Google's servers\n});\n\\`\\`\\`\n\n## Best Practices\n\n- **Name by use case**, not model ID (e.g., \\`fast\\`, \\`default\\`, \\`heavy\\`)\n- **Configure fallbacks** for production reliability\n- **Set pricing** for cost tracking in logs when your provider or runtime does not supply it automatically\n- **Cerebras note:** documented Cerebras models have built-in fallback pricing for request logs, but custom/private Cerebras models should still set \\`inputPrice\\` and \\`outputPrice\\`\n- **Use environment variables** for API keys, never hardcode\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/model\n`;\n","export const PROMPTS_CLAUDE_MD = `# Prompt Definitions\n\nPrompts define system instructions, model selection, and available tools for LLM interactions.\n\n## Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| \\`name\\` | \\`string\\` | Yes | Unique identifier for this prompt |\n| \\`toolDescription\\` | \\`string\\` | Yes | Description shown when used as a tool |\n| \\`prompt\\` | \\`string \\\\| StructuredPrompt\\` | Yes | System instructions |\n| \\`model\\` | \\`string\\` | Yes | Model name to use (references \\`agents/models/\\`) |\n| \\`tools\\` | \\`(string \\\\| ToolConfig \\\\| SubagentToolConfig)[]\\` | No | Available tools (include ai_human agent names for handoffs and dual_ai subagent configs) |\n| \\`includeChat\\` | \\`boolean\\` | No | Include full conversation history |\n| \\`includePastTools\\` | \\`boolean\\` | No | Include previous tool results |\n| \\`parallelToolCalls\\` | \\`boolean\\` | No | Allow multiple concurrent tool calls |\n| \\`toolChoice\\` | \\`'auto' \\\\| 'none' \\\\| 'required'\\` | No | Tool calling strategy |\n| \\`requiredSchema\\` | \\`z.ZodObject\\` | No | Input validation when called as tool |\n| \\`variables\\` | \\`VariableDefinition[]\\` | No | Variable declarations (\\`name\\`, \\`type\\`, \\`required\\`, \\`scoped\\`, \\`description\\`) |\n| \\`env\\` | \\`Record<string, string>\\` | No | Prompt-level default values for variables |\n| \\`hooks\\` | \\`string[]\\` | No | Hook IDs to run for this prompt (overrides agent hooks) |\n| \\`reasoning\\` | \\`ReasoningConfig\\` | No | Extended thinking configuration |\n\n## Basic Example\n\n\\`\\`\\`typescript\nimport { definePrompt } from '@standardagents/builder';\n\nexport default definePrompt({\n name: 'customer_support',\n toolDescription: 'Handle customer support inquiries',\n model: 'default',\n prompt: \\`You are a helpful customer support agent.\nAlways be polite and professional.\nIf you cannot help, escalate to a human.\\`,\n tools: ['search_knowledge_base', 'create_ticket'],\n includeChat: true,\n});\n\\`\\`\\`\n\n## Structured Prompts\n\nInclude other prompts for reusable instruction blocks:\n\n\\`\\`\\`typescript\nexport default definePrompt({\n name: 'main_assistant',\n toolDescription: 'Primary assistant',\n model: 'default',\n prompt: [\n { type: 'text', content: 'You are a helpful assistant.\\\\n\\\\n' },\n { type: 'include', prompt: 'common_rules' }, // Includes another prompt\n { type: 'env', property: 'ASSISTANT_TONE' }, // Inject variable value\n { type: 'text', content: '\\\\n\\\\nBe concise.' },\n ],\n});\n\\`\\`\\`\n\n\\`type: 'env'\\` inserts a resolved thread variable value. Use this only for non-secret values that are safe to expose to the LLM.\n\nThe sandboxed coding prompt declares \\`HTTP_HOST\\` as a text variable. Its URL helper uses that value as the origin for files exposed from the thread \\`public/\\` directory and endpoints exposed from the thread \\`api/\\` directory. Public URLs should usually omit extensions; extensionless public paths resolve \\`.html\\`, then \\`.js\\`, then \\`.ts\\`, then matching \\`index\\` files in the same order. Browser pages should reference only public files, \\`api/\\` endpoints, or absolute external URLs, using relative asset URLs like \\`./app\\` and \\`./api/todos\\`; private \\`src/\\` files are not served directly. Public \\`.ts\\` files are transformed to browser JavaScript and are not server endpoints. Server-side endpoints live under the thread filesystem \\`api/\\` directory, and the \\`api/\\` directory name stays in the public URL: \\`api/todo.ts\\` is \\`/api/threads/{threadId}/api/todo\\`, while \\`api/todo.ts\\` is not \\`/api/threads/{threadId}/todo\\` or \\`/api/threads/{threadId}/todos\\`. Endpoint files default-export a function that accepts \\`Request\\` and returns \\`Response\\` or \\`Promise<Response>\\`. Endpoint code can import \\`fetch\\`, \\`fs\\`, and \\`storage\\`, and can import private helpers with relative paths such as \\`../src/todo.ts\\`. When the coding agent creates a site, page, or endpoint, it should call \\`get_public_url\\` with the created file path and use the returned URL.\n\nSandboxed code and \\`api/\\` endpoints can persist small JSON-serializable runtime data through \\`import { storage } from \"storage\"\\`. Use \\`storage.get\\`, \\`storage.set\\`, \\`storage.delete\\`, and \\`storage.has\\` with stable logical keys. Do not expose, mention, or depend on internal storage key prefixes.\n\nThe sandboxed coding prompt includes \\`delete_file\\` for removing files or empty directories from the thread filesystem. Use it to clean up obsolete implementation files, stale public assets, and abandoned endpoint routes after the replacement is working.\n\n## Tool Configuration\n\nTools can be simple names or detailed configs:\n\n\\`\\`\\`typescript\ntools: [\n 'simple_tool', // Just the tool name\n {\n name: 'complex_tool',\n includeTextResponse: true, // Include sub-prompt text in result\n includeToolCalls: false, // Exclude sub-prompt tool calls\n includeErrors: true, // Include error details\n initUserMessageProperty: 'query', // Use this arg as initial message\n },\n],\n\\`\\`\\`\n\nProvider-built-in tools use the same \\`tools\\` list once the selected model enables\nthem with \\`providerTools\\`. AgentBuilder passes them to the provider and records\nprovider-reported calls in request logs; it does not execute those tools locally.\nGenerated prompt files may store these selections as \\`provider:<toolName>\\` to\ndistinguish provider tools from local tools with the same name.\n\n### Subagent Tool Configuration\n\nUse \\`SubagentToolConfig\\` when the tool is a \\`dual_ai\\` agent:\n\n\\`\\`\\`typescript\ntools: [\n // Blocking, non-resumable (default)\n { name: 'data_processor_agent' },\n\n // Non-blocking, resumable with a single instance\n {\n name: 'browser_agent',\n blocking: false,\n immediate: {\n nameEnv: 'BROWSER_AGENT_NAME',\n descriptionEnv: 'BROWSER_AGENT_DESCRIPTION',\n scopedEnv: ['BROWSER_AGENT_API_KEY'],\n },\n optional: 'ENABLE_BROWSER_AGENT',\n initAgentNameProperty: 'name',\n resumable: {\n receives_messages: 'side_a',\n maxInstances: 1,\n parentCommunication: 'explicit',\n },\n },\n]\n\\`\\`\\`\n\nWhen prompt-configured resumable dual_ai subagents exist, the runtime auto-injects:\n- \\`subagent_create\\` for spawning new child instances\n- \\`subagent_message\\` for messaging active resumable instances\n\n\\`subagent_create\\` requires a non-empty \\`name\\` for human-friendly child thread labels.\nAgentBuilder stores that argument as a \\`name:<value>\\` thread tag.\n\nSet \\`immediate: true\\` to run a tool automatically when the prompt activates.\nUse \\`immediate: { nameEnv, descriptionEnv, scopedEnv }\\` when you want safe per-instance bootstrap hints while keeping copied scoped env runtime-only.\nSet \\`optional: 'ENV_NAME'\\` to enable a subagent branch only when env resolves to \\`true\\`, \\`1\\`, or \\`yes\\`.\nSet \\`resumable.parentCommunication: 'explicit'\\` when the child should stay quiet until its own tools or hooks call \\`state.notifyParent()\\` or \\`state.setStatus()\\`.\nIf required scoped vars are missing, the runtime returns \\`error_code: \"subagent_env_required\"\\` with a temporary \\`GET/POST /api/threads/:threadId/variables/:requestId\\` endpoint in \\`error_data.endpoint\\`.\n\n## Input Validation\n\nValidate inputs when prompt is called as a tool:\n\n\\`\\`\\`typescript\nimport { z } from 'zod';\n\nexport default definePrompt({\n name: 'data_extractor',\n toolDescription: 'Extract structured data from text',\n model: 'default',\n prompt: 'Extract the requested data from the input.',\n requiredSchema: z.object({\n text: z.string().describe('Text to extract from'),\n fields: z.array(z.string()).describe('Fields to extract'),\n }),\n});\n\\`\\`\\`\n\n## Extended Thinking (Reasoning)\n\nEnable for complex reasoning tasks:\n\n\\`\\`\\`typescript\nexport default definePrompt({\n name: 'code_reviewer',\n toolDescription: 'Review code for issues',\n model: 'heavy',\n prompt: 'Review the code thoroughly...',\n reasoning: {\n effort: 'high', // 'low' | 'medium' | 'high'\n maxTokens: 16000, // Max thinking tokens\n exclude: true, // Don't include thinking in response\n },\n});\n\\`\\`\\`\n\n**⚠️ Google Models Require Reasoning**: When using Google models (\\`google/gemini-*\\`) via OpenRouter, you **must** include \\`reasoning\\` configuration or tool calls will fail. At minimum:\n\n\\`\\`\\`typescript\nreasoning: {\n effort: 'low', // Can be 'low', 'medium', or 'high'\n},\n\\`\\`\\`\n\n## Hooks\n\nAttach lifecycle hooks to a prompt:\n\n\\`\\`\\`typescript\nexport default definePrompt({\n name: 'customer_support',\n toolDescription: 'Handle customer support',\n model: 'default',\n prompt: 'You are a support agent...',\n hooks: ['limit_to_20', 'redact_pii'], // Hook IDs from agents/hooks/\n});\n\\`\\`\\`\n\nPrompt hooks take precedence over agent hooks. See \\`agents/hooks/CLAUDE.md\\` for details.\n\n## Best Practices\n\n- **Write clear instructions** - Structure with headers and bullet points\n- **Describe tools thoroughly** - LLMs decide based on descriptions\n- **Validate inputs with Zod** - Catch errors early\n- **Use \\`includeChat\\`** for conversational context\n- **Name by purpose**, not model (e.g., \\`support_agent\\` not \\`gpt4_prompt\\`)\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/prompt\n`;\n","export const AGENTS_CLAUDE_MD = `# Agent Definitions\n\nAgents orchestrate conversations by defining prompts, stop conditions, and turn limits.\n\n## Agent Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| \\`name\\` | \\`string\\` | Yes | Unique identifier for this agent |\n| \\`type\\` | \\`'ai_human' \\\\| 'dual_ai'\\` | No | Conversation type (default: \\`ai_human\\`) |\n| \\`sideA\\` | \\`SideConfig\\` | Yes | Configuration for side A (AI in ai_human) |\n| \\`sideB\\` | \\`SideConfig\\` | No | Configuration for side B (required for dual_ai) |\n| \\`maxSessionTurns\\` | \\`number\\` | No | Max total turns across both sides |\n| \\`exposeAsTool\\` | \\`boolean\\` | No | Allow other prompts to hand off to this agent |\n| \\`toolDescription\\` | \\`string\\` | No | Description when used as tool (required if exposeAsTool) |\n| \\`env\\` | \\`Record<string, string>\\` | No | Agent-level default variable values |\n| \\`hooks\\` | \\`string[]\\` | No | Hook IDs to run for this agent (fallback if prompt has no hooks) |\n| \\`tags\\` | \\`string[]\\` | No | Tags for categorization and filtering |\n\n## Side Configuration\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| \\`label\\` | \\`string\\` | No | Display name for this side |\n| \\`prompt\\` | \\`string\\` | Yes | Prompt name to use (references \\`agents/prompts/\\`) |\n| \\`stopOnResponse\\` | \\`boolean\\` | No | Stop turn when LLM returns text (default: true) |\n| \\`stopTool\\` | \\`string\\` | No | Tool that stops this side's turn |\n| \\`stopToolResponseProperty\\` | \\`string\\` | No | Property to extract from stop tool result |\n| \\`maxSteps\\` | \\`number\\` | No | Maximum step budget for this side |\n| \\`sessionStop\\` | \\`string \\\\| SessionToolBinding\\` | No | Terminal success lifecycle binding |\n| \\`sessionFail\\` | \\`string \\\\| SessionToolBinding\\` | No | Terminal failure lifecycle binding |\n| \\`sessionStatus\\` | \\`string \\\\| SessionToolBinding\\` | No | Non-terminal status lifecycle binding |\n| \\`manualStopCondition\\` | \\`boolean\\` | No | Enable custom stop handling via hooks |\n\n## Basic Example (AI-Human)\n\n\\`\\`\\`typescript\nimport { defineAgent } from '@standardagents/builder';\n\nexport default defineAgent({\n name: 'support_agent',\n type: 'ai_human',\n sideA: {\n label: 'Support',\n prompt: 'customer_support',\n stopOnResponse: true,\n sessionStop: 'close_ticket',\n maxSteps: 50,\n },\n tags: ['support', 'tier-1'],\n});\n\\`\\`\\`\n\n## Dual-AI Example\n\nTwo AI agents conversing (e.g., debate, iterative refinement):\n\n\\`\\`\\`typescript\nexport default defineAgent({\n name: 'code_review_debate',\n type: 'dual_ai',\n maxSessionTurns: 20,\n sideA: {\n label: 'Reviewer',\n prompt: 'code_reviewer',\n stopOnResponse: true,\n },\n sideB: {\n label: 'Developer',\n prompt: 'code_defender',\n stopOnResponse: true,\n },\n});\n\\`\\`\\`\n\n## Dual-AI Subagent Pattern\n\nWhen a \\`dual_ai\\` agent is used as a subagent tool, a common split is:\n- **sideA**: performs work (tools, data gathering, execution)\n- **sideB**: reflection, verification, and quality checks\n\n\\`\\`\\`typescript\nexport default defineAgent({\n name: 'research_subagent',\n type: 'dual_ai',\n exposeAsTool: true,\n toolDescription: 'Researches and validates findings autonomously',\n maxSessionTurns: 16,\n sideA: {\n label: 'Worker',\n prompt: 'research_worker',\n sessionStatus: 'set_subagent_status',\n sessionFail: 'fail_research_subagent',\n sessionStop: 'finish_subagent',\n },\n sideB: {\n label: 'Reviewer',\n prompt: 'research_reviewer',\n stopOnResponse: true,\n },\n});\n\\`\\`\\`\n\n## Agent Handoffs\n\nExpose an agent for handoffs from other prompts:\n\n\\`\\`\\`typescript\nexport default defineAgent({\n name: 'escalation_agent',\n type: 'ai_human',\n exposeAsTool: true,\n toolDescription: 'Escalate to senior support for complex issues',\n sideA: {\n prompt: 'senior_support',\n },\n});\n\\`\\`\\`\n\nOther prompts can then include the agent name in their \\`tools\\` array to enable handoffs.\n\n## Stop Conditions (Priority Order)\n\n1. **sessionFail** - Ends entire conversation with a terminal failure\n2. **sessionStop** - Ends entire conversation successfully\n3. **stopTool** - Ends current side's turn\n4. **maxSteps** - Ends side execution when the safety budget is reached\n5. **stopOnResponse** - Ends turn when LLM returns text\n6. **maxSessionTurns** - Ends conversation (hard limit: 250)\n\n## Hooks\n\nAttach lifecycle hooks at the agent level:\n\n\\`\\`\\`typescript\nexport default defineAgent({\n name: 'support_agent',\n type: 'ai_human',\n hooks: ['log_all_messages', 'sanitize_results'],\n sideA: {\n prompt: 'customer_support',\n },\n});\n\\`\\`\\`\n\nAgent hooks run as a fallback when the active prompt has no hooks defined. Prompt hooks always take precedence. See \\`agents/hooks/CLAUDE.md\\` for details.\n\n## Naming Convention\n\nAgent names **must** end with the \\`_agent\\` suffix (e.g., \\`support_agent\\`, \\`research_agent\\`).\nThis convention is enforced by the builder UI and makes agents easily identifiable in logs and code.\n\n## Best Practices\n\n- **Use descriptive names** (\\`customer_support_agent\\` not \\`agent1\\`)\n- **Always use the _agent suffix** - names like \\`support_agent\\`, \\`research_agent\\`\n- **Always set maxSteps or maxSessionTurns** as safety limits\n- **Match stop conditions to use case** - chat apps use stopOnResponse, workflows use stopTool\n- **Use labels** for clarity in logs and UI\n- **Organize with tags** for filtering\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/agent\n`;\n","export const TOOLS_CLAUDE_MD = `# Custom Tools\n\nTools extend agent capabilities beyond text generation. They allow LLMs to fetch data, perform calculations, execute side effects, and chain to other prompts or agents.\n\n## Function Signature\n\n\\`\\`\\`typescript\ndefineTool({\n description: string, // What the tool does (shown to LLM)\n args?: z.ZodObject, // Input validation schema (optional)\n execute: (state, args) => ToolResult, // Implementation\n variables?: VariableDefinition[], // Declared variables (optional)\n})\n\\`\\`\\`\n\n## Basic Example\n\n\\`\\`\\`typescript\nimport { defineTool } from '@standardagents/builder';\nimport { z } from 'zod';\n\nexport default defineTool({\n description: 'Search the knowledge base for articles matching a query',\n args: z.object({\n query: z.string().describe('Search query'),\n limit: z.number().optional().default(10).describe('Max results'),\n }),\n execute: async (state, args) => {\n const results = await searchKB(args.query, args.limit);\n return {\n status: 'success',\n result: JSON.stringify(results),\n };\n },\n});\n\\`\\`\\`\n\n## Argument Schemas\n\nTool args must be a top-level \\`z.object(...)\\`. Prefer explicit, bounded schemas made from strings, numbers, booleans, nulls, literals, enums, arrays, objects, optionals, nullables, and defaults. Avoid provider-visible recursive or open-ended schemas such as \\`z.unknown()\\`, \\`z.any()\\`, and \\`z.object({}).catchall(...)\\`; strict tool providers can reject the generated JSON Schema. If a tool needs arbitrary JSON input, accept it as a JSON string and parse it inside \\`execute\\`.\n\n## ToolResult Interface\n\n| Property | Type | Description |\n|----------|------|-------------|\n| \\`status\\` | \\`'success' \\\\| 'error'\\` | Whether the tool succeeded |\n| \\`result\\` | \\`string\\` | Tool output (required for success) |\n| \\`error\\` | \\`string\\` | Error message (for error status) |\n| \\`error_code\\` | \\`string\\` | Machine-readable error code |\n| \\`error_data\\` | \\`Record<string, unknown>\\` | Structured error payload |\n| \\`attachments\\` | \\`ToolAttachment[]\\` | Files to attach (images, etc.) |\n\n## ThreadState Access\n\nThe \\`state\\` parameter provides access to:\n\n\\`\\`\\`typescript\nexecute: async (state, args) => {\n // Thread information\n const threadId = state.thread.id;\n const thread = state.thread.instance;\n\n // Configuration\n const agentName = state.agent.name;\n const modelName = state.model.name;\n\n // Message history\n const messages = state.messages;\n\n // Thread variable resolution\n const apiKey = await state.env('GOOGLE_API_KEY');\n await state.setEnv('LAST_TOOL_RUN_AT', new Date().toISOString());\n\n // Durable per-thread JSON values\n const runCount = (await state.getValue<number>('run_count')) ?? 0;\n await state.setValue('run_count', runCount + 1);\n\n // Sandboxed JS/TS execution with explicit bridge capabilities\n const run = state.runCode('export async function main(path) { return await read(path) }', {\n execute: { fn: 'main', args: ['/notes.txt'] },\n globals: {\n read: async (path: string) => {\n const data = await state.readFile(path);\n return data ? new TextDecoder().decode(data) : null;\n },\n },\n });\n const codeResult = await run;\n\n // Parent state (for sub-prompts)\n const root = state.rootState;\n}\n\\`\\`\\`\n\nUse \\`state.runCode()\\` instead of \\`eval\\` or \\`new Function\\` for model- or user-authored JavaScript/TypeScript. The sandbox starts with no ambient host capabilities; provide imports/globals explicitly, use \\`modules\\` for local relative ES modules, use \\`execute\\` to select an export and pass args, use \\`report\\` for streamed observations, and call \\`run.terminate(reason)\\` from your own timeout budget when needed. \\`modules\\` keys are graph-root relative paths; entry-source imports resolve from \\`options.filename\\` when supplied. Relative module imports may use \\`./\\` and \\`../\\` as long as they resolve within the supplied module graph. In thread endpoints, \\`runCode\\` is forwarded into the thread Durable Object; pass plain transferable option values there, and do function-backed bridges from tools or in-thread execution contexts.\n\n## Tool Without Arguments\n\n\\`\\`\\`typescript\nexport default defineTool({\n description: 'Get current server time',\n execute: async (state) => {\n return {\n status: 'success',\n result: new Date().toISOString(),\n };\n },\n});\n\\`\\`\\`\n\n## Error Handling\n\nReturn errors gracefully instead of throwing:\n\n\\`\\`\\`typescript\nexport default defineTool({\n description: 'Fetch user data',\n args: z.object({ userId: z.string() }),\n execute: async (state, args) => {\n try {\n const user = await fetchUser(args.userId);\n return { status: 'success', result: JSON.stringify(user) };\n } catch (error) {\n return {\n status: 'error',\n error: \\`Failed to fetch user: \\${error.message}\\`,\n };\n }\n },\n});\n\\`\\`\\`\n\n## Queueing Additional Tools\n\nQueue another tool to run after the current one:\n\n\\`\\`\\`typescript\nimport { queueTool } from '@standardagents/builder';\n\nexport default defineTool({\n description: 'Create order and send confirmation',\n args: z.object({ items: z.array(z.string()) }),\n execute: async (state, args) => {\n const order = await createOrder(args.items);\n\n // Queue email tool to run next\n queueTool(state, 'send_confirmation_email', {\n orderId: order.id,\n email: state.thread.metadata.userEmail,\n });\n\n return { status: 'success', result: JSON.stringify(order) };\n },\n});\n\\`\\`\\`\n\n## Injecting Messages\n\nAdd messages without triggering re-execution:\n\n\\`\\`\\`typescript\nimport { injectMessage } from '@standardagents/builder';\n\nexport default defineTool({\n description: 'Log audit event',\n args: z.object({ event: z.string() }),\n execute: async (state, args) => {\n await injectMessage(state, {\n role: 'system',\n content: \\`[AUDIT] \\${args.event}\\`,\n });\n return { status: 'success', result: 'Logged' };\n },\n});\n\\`\\`\\`\n\n## Variables and Env\n\nTools can declare variable requirements with \\`variables\\`, including \\`required\\` and \\`description\\` metadata:\n\n\\`\\`\\`typescript\nexport default defineTool({\n description: 'Search uploaded documents',\n args: z.object({ query: z.string() }),\n execute: async (state, args) => {\n const vectorStoreId = await state.env('VECTOR_STORE_ID');\n const results = await searchVectorStore(vectorStoreId, args.query);\n return { status: 'success', result: JSON.stringify(results) };\n },\n variables: [\n {\n name: 'VECTOR_STORE_ID',\n type: 'text',\n required: true,\n scoped: false,\n description: 'OpenAI Vector Store ID',\n },\n ],\n});\n\\`\\`\\`\n\nUse \\`scoped: true\\` for per-instance values that should not inherit from parent thread env (for example per-account OAuth tokens on subagents).\n\n## Returning Attachments\n\nTools can return file attachments (e.g., generated images):\n\n\\`\\`\\`typescript\nexport default defineTool({\n description: 'Generate a chart from data',\n args: z.object({ data: z.array(z.number()) }),\n execute: async (state, args) => {\n const chartImage = await generateChart(args.data);\n return {\n status: 'success',\n result: 'Chart generated successfully',\n attachments: [{\n name: 'chart.png',\n mimeType: 'image/png',\n data: chartImage.base64,\n width: 800,\n height: 600,\n }],\n };\n },\n});\n\\`\\`\\`\n\n## Best Practices\n\n- **Write clear descriptions** - LLMs decide tool usage based on descriptions\n- **Describe all parameters** with \\`.describe()\\` in Zod schemas\n- **Handle errors gracefully** - return error status, don't throw\n- **Use snake_case** for file names (\\`search_knowledge_base.ts\\`)\n- **Keep tools focused** - one task per tool\n- **Use \\`state.rootState\\`** when queueing from sub-prompts\n\n## Supported Zod Types\n\n- Primitives: \\`string\\`, \\`number\\`, \\`boolean\\`, \\`null\\`\n- Enums: \\`z.enum(['a', 'b', 'c'])\\`\n- Arrays: \\`z.array(z.string())\\`\n- Objects: \\`z.object({ ... })\\`\n- Optional: \\`z.string().optional()\\`\n- Default: \\`z.number().default(10)\\`\n- Nullable: \\`z.string().nullable()\\`\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/tool\n`;\n","export const HOOKS_CLAUDE_MD = `# Lifecycle Hooks\n\nHooks intercept and modify agent execution at specific lifecycle points.\n\n## Available Hooks\n\n| Hook | Signature | Purpose |\n|------|-----------|---------|\n| \\`after_thread_created\\` | \\`(state: ThreadState) => void\\` | Initialize a newly created thread before execution |\n| \\`after_subagent_created\\` | \\`(state: ThreadState, childState: ThreadState) => void\\` | Run parent-side logic after a child thread is created |\n| \\`after_system_message\\` | \\`(state: ThreadState, systemMessage: string) => string \\\\| null \\\\| undefined\\` | Modify the rendered system message for a request |\n| \\`filter_messages\\` | \\`(state: ThreadState, messages: Message[]) => Message[]\\` | Filter raw messages before LLM context |\n| \\`prefilter_llm_history\\` | \\`(state: ThreadState, messages: LLMMessage[]) => LLMMessage[]\\` | Modify chat completion messages before LLM |\n| \\`before_create_message\\` | \\`(state: ThreadState, message: Message) => Message\\` | Modify message before database insert |\n| \\`after_create_message\\` | \\`(state: ThreadState, message: Message) => void\\` | Run logic after message created |\n| \\`before_update_message\\` | \\`(state: ThreadState, id: string, updates: Record) => Record\\` | Modify updates before message update |\n| \\`after_update_message\\` | \\`(state: ThreadState, message: Message) => void\\` | Run logic after message updated |\n| \\`before_store_tool_result\\` | \\`(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => HookToolResult\\` | Modify tool result before storage |\n| \\`after_tool_call_success\\` | \\`(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => HookToolResult \\\\| null\\` | Process successful tool execution |\n| \\`after_tool_call_failure\\` | \\`(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => HookToolResult \\\\| null\\` | Process failed tool execution |\n\nAll hooks receive \\`ThreadState\\` as their first parameter, providing access to thread identity, message history, resource loading, durable per-thread values via \\`getValue\\` / \\`setValue\\`, and sandboxed JS/TS execution via \\`runCode\\`.\n\n## Creating a Hook\n\nEach hook file exports a default \\`defineHook\\` call with three properties:\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'filter_messages', // Hook type\n id: 'limit_recent_messages', // Unique ID (snake_case)\n execute: async (state, messages) => {\n return messages.slice(-20);\n }\n});\n\\`\\`\\`\n\n## Hook Scoping\n\nHooks are scoped to **prompts** or **agents** via their ID:\n\n\\`\\`\\`typescript\n// In a prompt definition\ndefinePrompt({\n name: 'customer_support',\n hooks: ['limit_recent_messages', 'redact_pii'],\n // ...\n});\n\n// In an agent definition\ndefineAgent({\n name: 'support_agent',\n hooks: ['log_all_messages'],\n // ...\n});\n\\`\\`\\`\n\n- **Prompt hooks** take precedence over agent hooks\n- If a prompt defines hooks, only those run (agent hooks are skipped)\n- If no prompt hooks are defined, agent hooks run as fallback\n- Hooks are filtered by type at runtime\n\n## File Naming\n\nHook files can use **any name** — the hook type and ID are defined inside the file:\n\n\\`\\`\\`\nagents/hooks/\n├── my_filter.ts # Could contain any hook type\n├── redact_sensitive_data.ts\n├── log_tool_usage.ts\n└── add_metadata.ts\n\\`\\`\\`\n\n## Examples\n\n### Filter Messages (Limit Context)\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'filter_messages',\n id: 'limit_to_20',\n execute: async (state, messages) => {\n return messages.slice(-20);\n }\n});\n\\`\\`\\`\n\n### Prefilter LLM History (Redact Content)\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'prefilter_llm_history',\n id: 'redact_pii',\n execute: async (state, messages) => {\n return messages.map(msg => ({\n ...msg,\n content: typeof msg.content === 'string'\n ? msg.content.replace(/\\\\b\\\\d{4}-\\\\d{4}-\\\\d{4}-\\\\d{4}\\\\b/g, '[REDACTED]')\n : msg.content,\n }));\n }\n});\n\\`\\`\\`\n\n### Before Create Message (Add Metadata)\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'before_create_message',\n id: 'add_version_metadata',\n execute: async (state, message) => {\n if (message.role === 'user' && message.content) {\n return { ...message, content: \\`[v1.0] \\${message.content}\\` };\n }\n return message;\n }\n});\n\\`\\`\\`\n\n### Before Store Tool Result (Sanitize)\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'before_store_tool_result',\n id: 'sanitize_results',\n execute: async (state, toolCall, toolResult) => {\n // toolCall: { id, type: 'function', function: { name, arguments } }\n // toolResult: { status, result?, error?, stack?, attachments? }\n if (toolResult.result) {\n return { ...toolResult, result: toolResult.result.replace(/secret/gi, '[REDACTED]') };\n }\n return toolResult;\n }\n});\n\\`\\`\\`\n\n### After Tool Call Success (Logging)\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'after_tool_call_success',\n id: 'log_tool_success',\n execute: async (state, toolCall, result) => {\n console.log(\\`Tool \\${toolCall.function.name} succeeded\\`);\n return null; // Return null to use original result\n }\n});\n\\`\\`\\`\n\n### After Tool Call Failure (Recovery)\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'after_tool_call_failure',\n id: 'weather_fallback',\n execute: async (state, toolCall, result) => {\n if (toolCall.function.name === 'fetch_weather') {\n return {\n status: 'success',\n result: JSON.stringify({ temp: 'unavailable', fallback: true }),\n };\n }\n return null; // Use original error for other tools\n }\n});\n\\`\\`\\`\n\n## Hook Categories\n\n**Transformation hooks** (return modified data):\n- \\`after_system_message\\` (return replacement string, or null/undefined for no change)\n- \\`filter_messages\\`\n- \\`prefilter_llm_history\\`\n- \\`before_create_message\\`\n- \\`before_update_message\\`\n- \\`before_store_tool_result\\`\n- \\`after_tool_call_success\\` (return modified result or null)\n- \\`after_tool_call_failure\\` (return modified result or null)\n\n**Event hooks** (side effects only):\n- \\`after_thread_created\\`\n- \\`after_subagent_created\\`\n- \\`after_create_message\\`\n- \\`after_update_message\\`\n\n## Best Practices\n\n- **Keep hooks fast** - target <100ms execution\n- **Wrap in try-catch** - hooks continue on error (original data preserved)\n- **Use unique IDs** - hook IDs must be snake_case and unique across the project\n- **Scope appropriately** - assign hooks to prompts or agents that need them\n- **Document purpose** with clear comments\n- **Use for cross-cutting concerns** - logging, redaction, enrichment\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/hook\n`;\n","export const API_CLAUDE_MD = `# Thread-Specific API Endpoints\n\nDefine custom API endpoints that operate on specific threads with access to the thread's ThreadState.\n\n## File-Based Routing\n\n| File Pattern | HTTP Method | Route |\n|--------------|-------------|-------|\n| \\`name.ts\\` | GET | \\`/api/threads/:threadId/name\\` |\n| \\`name.get.ts\\` | GET | \\`/api/threads/:threadId/name\\` |\n| \\`name.post.ts\\` | POST | \\`/api/threads/:threadId/name\\` |\n| \\`name.put.ts\\` | PUT | \\`/api/threads/:threadId/name\\` |\n| \\`name.delete.ts\\` | DELETE | \\`/api/threads/:threadId/name\\` |\n| \\`index.ts\\` | GET | \\`/api/threads/:threadId\\` |\n| \\`nested/route.ts\\` | GET | \\`/api/threads/:threadId/nested/route\\` |\n| \\`items/[id].ts\\` | GET | \\`/api/threads/:threadId/items/:id\\` |\n| \\`files/[*].ts\\` | GET | \\`/api/threads/:threadId/files/*\\` |\n\nFiles without a method suffix default to GET. Method suffixes are case-insensitive and support \\`.get.ts\\`, \\`.post.ts\\`, \\`.put.ts\\`, \\`.patch.ts\\`, and \\`.delete.ts\\`.\n\nDynamic segments use \\`[name]\\` and are passed to the handler as \\`params.name\\`. Catch-all segments use \\`[*]\\` and are passed as \\`params['*']\\`; the catch-all value may contain \\`/\\` for nested paths. Static routes match before dynamic routes, and dynamic routes match before catch-all routes.\n\n## Basic Example\n\n\\`\\`\\`typescript\n// agents/api/status.get.ts -> GET /api/threads/:threadId/status\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state, params) => {\n const { messages, total } = await state.getMessages();\n return Response.json({\n threadId: state.threadId,\n messageCount: total,\n status: 'active',\n params,\n });\n});\n\\`\\`\\`\n\n## Handler Parameters\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| \\`req\\` | \\`Request\\` | The incoming HTTP request |\n| \\`state\\` | \\`ThreadState\\` | Thread state with messages, identity, file system, \\`runCode\\`, etc. |\n| \\`params\\` | \\`Record<string, string>\\` | Route parameters captured from \\`[name]\\` and \\`[*]\\` path segments |\n\nNote: \\`state.execution\\` is always \\`null\\` in endpoints since the thread is at rest. \\`state.runCode()\\` is available from endpoints and is forwarded into the thread runtime; pass plain transferable option values there, and do function-backed sandbox bridges from tools or in-thread execution contexts.\n\n## ThreadState Methods\n\nAccess thread data through the state object:\n\n\\`\\`\\`typescript\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n // Thread identity\n console.log('Thread ID:', state.threadId);\n console.log('Agent ID:', state.agentId);\n console.log('User ID:', state.userId);\n\n // Message operations\n const { messages, total, hasMore } = await state.getMessages({\n limit: 100,\n offset: 0,\n order: 'desc',\n });\n\n // Thread env (thread scope + active descendants)\n const approvalGate = await state.env('TOPDOWN_APPROVAL_GATE');\n await state.setEnv('TOPDOWN_APPROVAL_GATE', approvalGate || 'open');\n\n // Durable per-thread JSON values\n const exports = (await state.getValue<number>('export_count')) ?? 0;\n await state.setValue('export_count', exports + 1);\n\n // File system operations\n const files = await state.findFiles('**/*.json');\n const data = await state.readFile('/data/config.json');\n\n // Resource loading\n const agent = await state.loadAgent('my-agent');\n const prompt = await state.loadPrompt('my-prompt');\n\n return Response.json({ messages, total });\n});\n\\`\\`\\`\n\n## POST with Request Body\n\n\\`\\`\\`typescript\n// agents/api/export.post.ts -> POST /api/threads/:threadId/export\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n const body = await req.json();\n const { format = 'json' } = body;\n\n const { messages } = await state.getMessages();\n\n if (format === 'csv') {\n const csv = messages.map(m => \\`\\${m.role},\\${m.content}\\`).join('\\\\n');\n return new Response(csv, {\n headers: { 'Content-Type': 'text/csv' },\n });\n }\n\n return Response.json(messages);\n});\n\\`\\`\\`\n\n## Nested Routes\n\nCreate directories for nested routes:\n\n\\`\\`\\`\nagents/api/\n├── status.get.ts -> GET /api/threads/:threadId/status\n├── export.post.ts -> POST /api/threads/:threadId/export\n└── messages/\n ├── count.ts -> GET /api/threads/:threadId/messages/count\n ├── [id].ts -> GET /api/threads/:threadId/messages/:id\n └── [*].ts -> GET /api/threads/:threadId/messages/*\n\\`\\`\\`\n\n## Error Handling\n\n\\`\\`\\`typescript\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n try {\n const data = await riskyOperation();\n return Response.json(data);\n } catch (error) {\n return Response.json({ error: error.message }, { status: 500 });\n }\n});\n\\`\\`\\`\n\n## File System Operations\n\n\\`\\`\\`typescript\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n // Read files\n const content = await state.readFile('/data/file.txt');\n\n // Write files\n await state.writeFile('/output/result.json', JSON.stringify(data), 'application/json');\n\n // List directory\n const { entries } = await state.readdirFile('/data');\n\n // Search files\n const matches = await state.grepFiles('pattern');\n const paths = await state.findFiles('**/*.ts');\n\n return Response.json({ success: true });\n});\n\\`\\`\\`\n\n## Best Practices\n\n- **Keep handlers fast** - endpoints are in the request path\n- **Paginate large queries** - use limit/offset for messages\n- **Validate input data** - check request body before processing\n- **Use descriptive file names** - \\`export.post.ts\\` not \\`ep1.ts\\`\n- **Return proper status codes** - 200, 400, 404, 500\n- **Import from spec** - use \\`@standardagents/spec\\` for \\`defineThreadEndpoint\\`\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/core-concepts/api\n`;\n","import {\n AGENTS_CLAUDE_MD,\n API_CLAUDE_MD,\n HOOKS_CLAUDE_MD,\n MODELS_CLAUDE_MD,\n PROMPTS_CLAUDE_MD,\n ROOT_CLAUDE_MD,\n TOOLS_CLAUDE_MD,\n} from './docs/index.js'\n\nexport {\n AGENTS_CLAUDE_MD,\n API_CLAUDE_MD,\n HOOKS_CLAUDE_MD,\n MODELS_CLAUDE_MD,\n PROMPTS_CLAUDE_MD,\n ROOT_CLAUDE_MD,\n TOOLS_CLAUDE_MD,\n}\n\nexport type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun'\n\nexport interface TemplateFile {\n path: string\n content: string\n message: string\n}\n\nexport interface TemplateVersions {\n standardAgents: string\n sip: string\n vite: string\n typescript: string\n cloudflareVitePlugin: string\n wrangler: string\n zod?: string\n}\n\nexport interface AgentBuilderProjectTemplateOptions {\n projectName: string\n packageManager?: PackageManager | null\n versions?: Partial<TemplateVersions>\n compatibilityDate?: string\n platformApiUrl?: string\n includeDeployAutomation?: boolean\n includeTemplateMetadata?: boolean\n templateVersion?: string\n}\n\nexport const FIRST_PARTY_PROVIDER_PACKAGES = [\n '@standardagents/cloudflare',\n '@standardagents/cerebras',\n '@standardagents/google',\n '@standardagents/groq',\n '@standardagents/openai',\n '@standardagents/openrouter',\n '@standardagents/xai',\n] as const\n\nexport const DEFAULT_TEMPLATE_VERSIONS: TemplateVersions = {\n standardAgents: 'latest',\n sip: 'latest',\n vite: 'latest',\n typescript: 'latest',\n cloudflareVitePlugin: 'latest',\n wrangler: 'latest',\n zod: 'latest',\n}\n\nexport const AGENTBUILDER_TEMPLATE_VERSION = '0.15.2'\n\nexport const DEFAULT_COMPATIBILITY_DATE = '2025-08-13'\n\nfunction ensureTrailingNewline(value: string): string {\n return value.endsWith('\\n') ? value : `${value}\\n`\n}\n\nfunction mergeVersions(versions?: Partial<TemplateVersions>): TemplateVersions {\n return {\n ...DEFAULT_TEMPLATE_VERSIONS,\n ...versions,\n }\n}\n\nexport function packageNameFromProjectName(projectName: string): string {\n const normalized = projectName\n .toLowerCase()\n .replace(/^@[^/]+\\//, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n return normalized || 'agentbuilder-project'\n}\n\nfunction file(path: string, content: string, message: string): TemplateFile {\n return {\n path,\n content: ensureTrailingNewline(content),\n message,\n }\n}\n\nexport function renderPackageJson(options: AgentBuilderProjectTemplateOptions): string {\n const versions = mergeVersions(options.versions)\n const standardAgentsVersion = versions.standardAgents\n const dependencies: Record<string, string> = {\n '@standardagents/builder': standardAgentsVersion,\n '@standardagents/spec': standardAgentsVersion,\n '@standardagents/sip': versions.sip,\n zod: versions.zod ?? 'latest',\n }\n\n for (const providerPackage of FIRST_PARTY_PROVIDER_PACKAGES) {\n dependencies[providerPackage] = standardAgentsVersion\n }\n\n return `${JSON.stringify({\n name: packageNameFromProjectName(options.projectName),\n version: '0.0.0',\n private: true,\n type: 'module',\n scripts: {\n dev: 'vite --host 0.0.0.0 --port 5173',\n build: 'vite build',\n typecheck: 'tsc --noEmit',\n 'wrangler:types': 'wrangler types',\n },\n dependencies,\n devDependencies: {\n '@cloudflare/vite-plugin': versions.cloudflareVitePlugin,\n typescript: versions.typescript,\n vite: versions.vite,\n wrangler: versions.wrangler,\n },\n }, null, 2)}\\n`\n}\n\nexport function renderWranglerJson(options: AgentBuilderProjectTemplateOptions): string {\n const compatibilityDate = options.compatibilityDate ?? DEFAULT_COMPATIBILITY_DATE\n const workerName = packageNameFromProjectName(options.projectName)\n\n return `{\n \"$schema\": \"node_modules/wrangler/config-schema.json\",\n \"name\": \"${workerName}\",\n \"main\": \"worker/index.ts\",\n \"compatibility_date\": \"${compatibilityDate}\",\n \"compatibility_flags\": [\"nodejs_compat\", \"enable_ctx_exports\"],\n \"observability\": {\n \"enabled\": true\n },\n \"worker_loaders\": [\n {\n \"binding\": \"AGENT_BUILDER_CODE_LOADER\"\n }\n ],\n \"vars\": {\n \"AGENT_BUILDER_CODE_COMPATIBILITY_DATE\": \"${compatibilityDate}\"\n },\n \"assets\": {\n \"directory\": \"dist/client\",\n \"not_found_handling\": \"single-page-application\",\n \"binding\": \"ASSETS\",\n \"run_worker_first\": [\"/**\"]\n },\n \"durable_objects\": {\n \"bindings\": [\n {\n \"name\": \"AGENT_BUILDER_THREAD\",\n \"class_name\": \"DurableThread\"\n },\n {\n \"name\": \"AGENT_BUILDER\",\n \"class_name\": \"DurableAgentBuilder\"\n }\n ]\n },\n \"migrations\": [\n {\n \"tag\": \"v1\",\n \"new_sqlite_classes\": [\"DurableThread\"]\n },\n {\n \"tag\": \"v2\",\n \"new_sqlite_classes\": [\"DurableAgentBuilder\"]\n }\n ]\n}\n`\n}\n\nexport function renderViteConfig(): string {\n return `import { defineConfig } from \"vite\"\nimport { cloudflare } from \"@cloudflare/vite-plugin\"\nimport { agentbuilder } from \"@standardagents/builder\"\n\nexport default defineConfig({\n plugins: [agentbuilder({ mountPoint: \"/\" }), cloudflare()],\n})\n`\n}\n\nexport function renderTsConfig(): string {\n return `{\n \"compilerOptions\": {\n \"target\": \"ES2022\",\n \"useDefineForClassFields\": true,\n \"module\": \"ESNext\",\n \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n \"skipLibCheck\": true,\n \"moduleResolution\": \"Bundler\",\n \"allowImportingTsExtensions\": true,\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"noEmit\": true,\n \"strict\": true\n },\n \"include\": [\"worker\", \"agents\"]\n}\n`\n}\n\nexport function renderWorkerIndex(): string {\n return `import { router, CodeExecutionBridge } from \"virtual:@standardagents/builder\"\nimport DurableThread from \"../agents/Thread\"\nimport DurableAgentBuilder from \"../agents/AgentBuilder\"\n\nexport default {\n async fetch(request, env) {\n const res = await router(request, env)\n return res ?? new Response(null, { status: 404 })\n },\n} satisfies ExportedHandler<Env>\n\nexport { DurableThread, DurableAgentBuilder, CodeExecutionBridge }\n`\n}\n\nexport function renderDurableThread(): string {\n return `import { DurableThread } from \"virtual:@standardagents/builder\"\n\nexport default class Thread extends DurableThread {}\n`\n}\n\nexport function renderDurableAgentBuilder(): string {\n return `import { DurableAgentBuilder } from \"virtual:@standardagents/builder\"\n\nexport default class AgentBuilder extends DurableAgentBuilder {}\n`\n}\n\nexport function renderGitignore(): string {\n return `node_modules\ndist\n.wrangler\n.env\n.dev.vars\n`\n}\n\nexport function renderDevVarsExample(): string {\n return `# Standard Agents local development environment\n# Copy to .dev.vars for local-only Worker secrets.\n\n# Local data encryption key. Generate with: openssl rand -hex 32\nENCRYPTION_KEY=\n\n# Optional local admin password for development access.\nSUPER_ADMIN_PASSWORD=password\n\n# Platform connection. The CLI writes real values to .dev.vars for platform-created projects.\nSTANDARD_AGENTS_API_KEY=\nPLATFORM_ENDPOINT=\nSTANDARD_AGENTS_API_URL=\n\n# BYOK provider keys. When set, these keys override Standard Agents hosted routing for that provider.\nCLOUDFLARE_API_TOKEN=\nCLOUDFLARE_ACCOUNT_ID=\nCEREBRAS_API_KEY=\nGOOGLE_API_KEY=\nGROQ_API_KEY=\nOPENAI_API_KEY=\nOPENROUTER_API_KEY=\nXAI_API_KEY=\n`\n}\n\nexport function renderDeployHelper(): string {\n return `import fs from \"node:fs\";\nimport path from \"node:path\";\n\nfunction findBundleInDir(dir) {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n const files = entries\n .filter((entry) => entry.isFile() && /\\\\.(m?js)$/.test(entry.name))\n .sort((a, b) => {\n const aIsIndex = a.name === \"index.js\" || a.name === \"index.mjs\" ? 0 : 1;\n const bIsIndex = b.name === \"index.js\" || b.name === \"index.mjs\" ? 0 : 1;\n if (aIsIndex !== bIsIndex) return aIsIndex - bIsIndex;\n return fs.statSync(path.join(dir, b.name)).size - fs.statSync(path.join(dir, a.name)).size;\n });\n\n for (const file of files) {\n const filePath = path.join(dir, file.name);\n const content = fs.readFileSync(filePath, \"utf8\");\n if (content.includes(\"export default\") || content.includes(\"export {\")) {\n return { path: filePath, content };\n }\n }\n\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name === \"client\" || entry.name === \"node_modules\") continue;\n const nested = findBundleInDir(path.join(dir, entry.name));\n if (nested) return nested;\n }\n return null;\n}\n\nfunction findWorkerBundle() {\n for (const dir of [\".wrangler/tmp\", \"dist\"]) {\n if (!fs.existsSync(dir)) continue;\n const bundle = findBundleInDir(dir);\n if (bundle) return bundle;\n }\n throw new Error(\"Could not find a Worker bundle in .wrangler/tmp or dist\");\n}\n\nconst deployUrl = process.env.STANDARD_AGENTS_DEPLOY_URL;\nconst deployToken = process.env.STANDARD_AGENTS_DEPLOY_TOKEN;\nconst buildId = process.env.STANDARD_AGENTS_BUILD_ID;\nif (!deployUrl || !deployToken || !buildId) {\n throw new Error(\"Missing Standard Agents deployment environment\");\n}\n\nconst bundle = findWorkerBundle();\nconst response = await fetch(deployUrl, {\n method: \"POST\",\n headers: {\n \"Authorization\": \\`Bearer \\${deployToken}\\`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n build_id: buildId,\n script_content: bundle.content,\n compatibility_date: process.env.STANDARD_AGENTS_COMPATIBILITY_DATE || undefined,\n }),\n});\n\nif (!response.ok) {\n const text = await response.text();\n throw new Error(\\`Standard Agents deploy failed (\\${response.status}): \\${text}\\`);\n}\n\nconsole.log(\\`Deployed Standard Agents Worker from \\${bundle.path}\\`);\n`\n}\n\nexport function renderDeployWorkflow(): string {\n return `name: Standard Agents Deploy\n\non:\n repository_dispatch:\n types: [standardagents-deploy]\n\npermissions:\n contents: read\n\njobs:\n deploy:\n runs-on: ubuntu-latest\n env:\n STANDARD_AGENTS_BUILD_ID: \\${{ github.event.client_payload.build_id }}\n STANDARD_AGENTS_DEPLOY_URL: \\${{ github.event.client_payload.deploy_url }}\n STANDARD_AGENTS_DEPLOY_TOKEN: \\${{ github.event.client_payload.deploy_token }}\n STANDARD_AGENTS_COMPATIBILITY_DATE: \\${{ github.event.client_payload.compatibility_date }}\n STANDARD_AGENTS_API_URL: \\${{ github.event.client_payload.api_url }}\n steps:\n - uses: actions/checkout@v4\n with:\n ref: \\${{ github.event.client_payload.commit_sha }}\n - uses: actions/setup-node@v4\n with:\n node-version: 22\n - name: Enable package managers\n run: corepack enable\n - name: Install dependencies\n shell: bash\n run: |\n if [ -f pnpm-lock.yaml ]; then\n pnpm install --frozen-lockfile || pnpm install\n elif [ -f yarn.lock ]; then\n yarn install --immutable || yarn install\n elif [ -f bun.lockb ] || [ -f bun.lock ]; then\n bun install --frozen-lockfile || bun install\n elif [ -f package-lock.json ]; then\n npm ci || npm install\n else\n npm install\n fi\n - name: Build\n shell: bash\n run: |\n if [ -f pnpm-lock.yaml ]; then\n pnpm run build\n elif [ -f yarn.lock ]; then\n yarn build\n elif [ -f bun.lockb ] || [ -f bun.lock ]; then\n bun run build\n else\n npm run build\n fi\n - name: Upload Worker\n run: node .github/standardagents-deploy.mjs\n`\n}\n\nexport function renderTemplateMetadata(options: AgentBuilderProjectTemplateOptions): string {\n return `${JSON.stringify({\n generator: '@standardagents/agentbuilder-template',\n template_version: options.templateVersion ?? AGENTBUILDER_TEMPLATE_VERSION,\n project_name: options.projectName,\n }, null, 2)}\\n`\n}\n\nexport function renderAgentBuilderProject(options: AgentBuilderProjectTemplateOptions): TemplateFile[] {\n const files: TemplateFile[] = [\n file('package.json', renderPackageJson(options), 'Add AgentBuilder package manifest'),\n file('tsconfig.json', renderTsConfig(), 'Add TypeScript config'),\n file('vite.config.ts', renderViteConfig(), 'Add Vite config'),\n file('wrangler.jsonc', renderWranglerJson(options), 'Add Wrangler config'),\n file('worker/index.ts', renderWorkerIndex(), 'Add Worker entrypoint'),\n file('agents/Thread.ts', renderDurableThread(), 'Add DurableThread'),\n file('agents/AgentBuilder.ts', renderDurableAgentBuilder(), 'Add DurableAgentBuilder'),\n file('agents/agents/CLAUDE.md', AGENTS_CLAUDE_MD, 'Add agent docs'),\n file('agents/prompts/CLAUDE.md', PROMPTS_CLAUDE_MD, 'Add prompt docs'),\n file('agents/models/CLAUDE.md', MODELS_CLAUDE_MD, 'Add model docs'),\n file('agents/tools/CLAUDE.md', TOOLS_CLAUDE_MD, 'Add tool docs'),\n file('agents/hooks/CLAUDE.md', HOOKS_CLAUDE_MD, 'Add hook docs'),\n file('agents/api/CLAUDE.md', API_CLAUDE_MD, 'Add API docs'),\n file('CLAUDE.md', ROOT_CLAUDE_MD, 'Add AgentBuilder project docs'),\n file('.dev.vars.example', renderDevVarsExample(), 'Add local env example'),\n file('.gitignore', renderGitignore(), 'Add gitignore'),\n ]\n\n if (options.includeTemplateMetadata) {\n files.push(file('.standardagents/template.json', renderTemplateMetadata(options), 'Add Standard Agents template metadata'))\n }\n\n if (options.includeDeployAutomation) {\n files.push(\n file('.github/standardagents-deploy.mjs', renderDeployHelper(), 'Add Standard Agents deploy helper'),\n file('.github/workflows/standardagents-deploy.yml', renderDeployWorkflow(), 'Add Standard Agents deploy workflow'),\n )\n }\n\n return files\n}\n"],"mappings":";AAAO,IAAM,iBAAiB;AAAA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;AAAA,IACzE,KAAK,cAAc,gBAAgB,GAAG,eAAe;AAAA,EACvD;AAEA,MAAI,QAAQ,yBAAyB;AACnC,UAAM,KAAK,KAAK,iCAAiC,uBAAuB,OAAO,GAAG,uCAAuC,CAAC;AAAA,EAC5H;AAEA,MAAI,QAAQ,yBAAyB;AACnC,UAAM;AAAA,MACJ,KAAK,qCAAqC,mBAAmB,GAAG,mCAAmC;AAAA,MACnG,KAAK,+CAA+C,qBAAqB,GAAG,qCAAqC;AAAA,IACnH;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/docs/root.ts","../src/docs/models.ts","../src/docs/prompts.ts","../src/docs/agents.ts","../src/docs/tools.ts","../src/docs/hooks.ts","../src/docs/api.ts","../src/index.ts"],"sourcesContent":["export const ROOT_AGENTS_MD = `# Standard Agents\n\nThis project uses Standard Agents - a framework for building AI agents on Cloudflare Workers.\n\n## Architecture Overview\n\nStandard Agents uses a **composition model** where four core components work together:\n\n\\`\\`\\`\nModel → Prompt → Agent → Thread\n │ │ │ │\n │ │ │ └─ Conversation instance (Durable Object)\n │ │ └─ Orchestrates conversation flow\n │ └─ System instructions + tools\n └─ LLM provider configuration\n\\`\\`\\`\n\n**Models** define which LLM to use (provider, model ID, pricing, fallbacks).\n**Prompts** define what the LLM should do (system instructions, available tools).\n**Agents** orchestrate conversations (which prompt, stop conditions, turn limits).\n**Threads** are individual conversation instances with persistent storage.\n\n## How Components Compose\n\n### Basic Flow\n1. User creates a thread with an agent\n2. Agent uses its configured prompt\n3. Prompt specifies the model and tools\n4. LLM responds, potentially calling tools\n5. Tools execute and return results\n6. Loop continues until stop condition\n\n### Sub-Prompts (Prompts as Tools)\nPrompts can call other prompts as tools. This enables:\n- **Specialized reasoning**: A main prompt delegates to expert sub-prompts\n- **Structured outputs**: Sub-prompt validates and formats data\n- **Context isolation**: Sub-prompt gets fresh context without full history\n\n\\`\\`\\`typescript\n// Main prompt can call 'data_extractor' as a tool\ndefinePrompt({\n name: 'main_assistant',\n tools: ['data_extractor'], // Another prompt exposed as tool\n // ...\n});\n\\`\\`\\`\n\n### Agent Handoffs (Agents as Tools)\nAgents can delegate to other agents entirely:\n- **Specialization**: Route to domain-specific agents\n- **Escalation**: Hand off to more capable agents\n- **Workflows**: Chain agents for multi-step processes\n\n\\`\\`\\`typescript\ndefineAgent({\n name: 'triage_agent',\n exposeAsTool: true,\n toolDescription: 'Hand off to triage for initial assessment',\n // ...\n});\n\\`\\`\\`\n\n## File Structure\n\n\\`\\`\\`\nAGENTS.md # Project guidance for AI coding tools\nCLAUDE.md -> AGENTS.md # Compatibility symlink\nvite.config.ts # Uses builder(); Cloudflare config is generated\ntsconfig.json # Includes agents and generated .agents types\nagents/\n├── agents/ # Agent definitions (defineAgent)\n│ ├── AGENTS.md\n│ └── CLAUDE.md -> AGENTS.md\n├── prompts/ # Prompt definitions (definePrompt)\n│ ├── AGENTS.md\n│ └── CLAUDE.md -> AGENTS.md\n├── models/ # Model configurations (defineModel)\n│ ├── AGENTS.md\n│ └── CLAUDE.md -> AGENTS.md\n├── tools/ # Custom tools (defineTool)\n│ ├── AGENTS.md\n│ └── CLAUDE.md -> AGENTS.md\n├── hooks/ # Lifecycle hooks (defineHook)\n│ ├── AGENTS.md\n│ └── CLAUDE.md -> AGENTS.md\n└── api/ # Thread API endpoints (defineThreadEndpoint)\n ├── AGENTS.md\n └── CLAUDE.md -> AGENTS.md\n\\`\\`\\`\n\nThe \\`builder()\\` Vite plugin generates the Worker entry, Durable Object bindings, Cloudflare Vite plugin configuration, and local \\`.agents/\\` support files at build time. Agent files are **auto-discovered** at runtime. No manual registration needed.\n\n## ThreadState\n\n\\`ThreadState\\` is the state object available in tools and hooks:\n\n\\`\\`\\`typescript\ninterface ThreadState {\n // Identity (readonly)\n threadId: string; // Thread identifier\n agentId: string; // Agent identifier\n userId: string | null; // User identifier (if set)\n createdAt: number; // Creation timestamp\n children: SubagentRegistryEntry[]; // Resumable child registry\n terminated: number | null; // Soft-termination timestamp\n\n // Methods\n getMessages(options?): Promise<MessagesResult>; // Get conversation history\n injectMessage(input): Promise<Message>; // Add message to thread\n queueMessage(input): Promise<void>; // Queue message for next step\n loadModel(name): Promise<ModelConfig>; // Load model definition\n loadPrompt(name): Promise<PromptConfig>; // Load prompt definition\n loadAgent(name): Promise<AgentConfig>; // Load agent definition\n env(propertyName): Promise<string>; // Resolve env value for this thread\n setEnv(propertyName, value): Promise<void>; // Set thread env + propagate to active descendants\n getValue<T = unknown>(key: string): Promise<T | null>; // Read durable per-thread JSON value\n setValue(key: string, value: unknown): Promise<void>; // Write durable value; null/undefined deletes\n notifyParent(content): Promise<void>; // Explicitly queue a silent message to the parent\n setStatus(status): Promise<void>; // Update this child in the parent registry\n getChildThread(referenceId): Promise<ThreadState | null>; // Resolve child thread\n getParentThread(): Promise<ThreadState | null>; // Resolve parent thread\n terminate(): Promise<void>; // Soft-terminate thread\n runCode(source, options?): CodeExecution; // Run JS/TS in a fresh Dynamic Worker sandbox\n}\n\\`\\`\\`\n\n\\`runCode\\` has no implicit access to thread state, filesystem, network, timers, or host globals. Bridge only the exact capabilities needed through \\`imports\\` or \\`globals\\`; use \\`modules\\` for local relative ES modules; use \\`execute\\` to select the export and args to run. \\`modules\\` keys are graph-root relative paths; entry-source imports resolve from \\`filename\\` when supplied, including \\`../\\` parent paths that stay inside the supplied graph. TypeScript input is accepted by default and erased before evaluation. In thread endpoints, \\`runCode\\` is forwarded into the thread Durable Object; pass plain transferable options there and keep function-backed bridges in tools or in-thread execution contexts.\n\n## Subagents\n\n\\`dual_ai\\` agents can be used as subagents from prompt tool configs:\n\n- Each subagent runs in its own thread (\\`DurableThread\\`)\n- Parent/child linkage is tracked in thread metadata\n- Resumable children are visible in \\`state.children\\`\n- Parent threads create/message resumable children via built-ins (\\`subagent_create\\`, \\`subagent_message\\`)\n- Child completion results are queued back to the parent when \\`parentCommunication\\` is \\`implicit\\`\n- Explicit relationships can stay idle until code calls \\`state.notifyParent()\\` or \\`state.setStatus()\\`\n\nAccess in tools:\n\\`\\`\\`typescript\nexport default defineTool('...', schema, async (state, args) => {\n const threadId = state.threadId;\n const { messages } = await state.getMessages();\n const count = (await state.getValue<number>('invocation_count')) ?? 0;\n await state.setValue('invocation_count', count + 1);\n // ...\n});\n\\`\\`\\`\n\nAccess in hooks:\n\\`\\`\\`typescript\nexport default defineHook({\n hook: 'before_create_message',\n id: 'my_hook',\n execute: async (state, message) => {\n console.log(\\`Thread: \\${state.threadId}, Agent: \\${state.agentId}\\`);\n return message;\n }\n});\n\\`\\`\\`\n\n## Quick Reference\n\n| Function | Purpose | Directory |\n|----------|---------|-----------|\n| \\`defineModel()\\` | Configure LLM provider | \\`agents/models/\\` |\n| \\`definePrompt()\\` | System instructions + tools | \\`agents/prompts/\\` |\n| \\`defineAgent()\\` | Conversation orchestration | \\`agents/agents/\\` |\n| \\`defineTool()\\` | Custom tool functions | \\`agents/tools/\\` |\n| \\`defineHook()\\` | Lifecycle interception | \\`agents/hooks/\\` |\n| \\`defineThreadEndpoint()\\` | Custom API routes | \\`agents/api/\\` |\n\n## Runtime Utilities\n\nImport from \\`@standardagents/builder\\`:\n\n\\`\\`\\`typescript\nimport {\n queueTool, // Queue another tool for execution\n injectMessage, // Add message without triggering execution\n getMessages, // Retrieve message history\n emitThreadEvent, // Send custom WebSocket events\n} from '@standardagents/builder';\n\\`\\`\\`\n\n## Documentation\n\nFull documentation: https://docs.standardagentbuilder.com\n\n- [Architecture Overview](https://docs.standardagentbuilder.com/introduction/architecture)\n- [Models](https://docs.standardagentbuilder.com/core-concepts/models)\n- [Prompts](https://docs.standardagentbuilder.com/core-concepts/prompts)\n- [Agents](https://docs.standardagentbuilder.com/core-concepts/agents)\n- [Tools](https://docs.standardagentbuilder.com/core-concepts/tools)\n- [Hooks](https://docs.standardagentbuilder.com/core-concepts/hooks)\n- [ThreadState](https://docs.standardagentbuilder.com/core-concepts/threadstate)\n- [Thread API](https://docs.standardagentbuilder.com/core-concepts/api)\n`;\n\nexport const ROOT_CLAUDE_MD = ROOT_AGENTS_MD;\n","export const MODELS_AGENTS_MD = `# Model Definitions\n\nModels define which LLM provider and model to use for prompts.\n\n## Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| \\`name\\` | \\`string\\` | Yes | Unique identifier for this model configuration |\n| \\`provider\\` | \\`'openai' \\\\| 'anthropic' \\\\| 'openrouter' \\\\| 'google' \\\\| 'cerebras' \\\\| 'groq' \\\\| 'xai'\\` | Yes | LLM provider |\n| \\`model\\` | \\`string\\` | Yes | Model ID sent to provider API |\n| \\`fallbacks\\` | \\`string[]\\` | No | Fallback model names to try if primary fails |\n| \\`inputPrice\\` | \\`number\\` | No | Cost per 1M input tokens (USD) |\n| \\`outputPrice\\` | \\`number\\` | No | Cost per 1M output tokens (USD) |\n| \\`cachedPrice\\` | \\`number\\` | No | Cost per 1M cached input tokens |\n| \\`includedProviders\\` | \\`string[]\\` | No | Provider prefixes for OpenRouter routing |\n| \\`providerTools\\` | \\`string[]\\` | No | Provider-built-in tool names to make available for prompts using this model |\n\n## Example\n\n\\`\\`\\`typescript\nimport { defineModel } from '@standardagents/builder';\n\nexport default defineModel({\n name: 'default',\n provider: 'openrouter',\n model: 'google/gemini-3-flash-preview',\n fallbacks: ['fast', 'cheap-heavy'],\n});\n\\`\\`\\`\n\n## Provider Tools\n\nProviders can expose built-in tools such as search, file search, code execution,\nor provider-specific tools through their \\`getTools()\\` implementation. Enable the\nprovider tool names on the model with \\`providerTools\\`; prompts can then include\nthose tools like normal tool names. Provider tools execute on the upstream\nprovider, not in AgentBuilder, and successful calls are logged as provider tool\nentries.\n\nOpenRouter exposes \\`web_search\\`, \\`web_fetch\\`, \\`datetime\\`, and \\`image_generation\\`\nas provider-executed server tools. Configure optional OpenRouter parameters with\n\\`providerOptions.serverTools\\` on the model.\n\n## Recommended Models (OpenRouter)\n\n| Use Case | Model ID | Description |\n|----------|----------|-------------|\n| Fast/Cheap | \\`z-ai/glm-4.5-air\\` | Quick responses, low cost |\n| Mid-tier | \\`google/gemini-3-flash-preview\\` | Good balance of speed and quality |\n| Cheap Heavy | \\`z-ai/glm-4.7\\` | More capable, still affordable |\n| Heavy | \\`google/gemini-3-pro-preview\\` | Most capable, for complex tasks |\n\n**⚠️ Google Models**: When using Google models (\\`google/gemini-*\\`), you must enable \\`reasoning\\` in your prompt configuration or tool calls will fail. See the prompts AGENTS.md for details.\n\n## Provider API Keys\n\nSet these environment variables in \\`.dev.vars\\` (local) or Cloudflare secrets (production):\n\n| Provider | Environment Variable |\n|----------|---------------------|\n| Cerebras | \\`CEREBRAS_API_KEY\\` |\n| Groq | \\`GROQ_API_KEY\\` |\n| OpenAI | \\`OPENAI_API_KEY\\` |\n| Anthropic | \\`ANTHROPIC_API_KEY\\` |\n| OpenRouter | \\`OPENROUTER_API_KEY\\` |\n| Google | \\`GOOGLE_API_KEY\\` |\n| xAI | \\`XAI_API_KEY\\` |\n\nIf \\`STANDARD_AGENTS_API_KEY\\` is present and a provider-specific key is not set,\nfirst-party Standard Agents providers route through the hosted Standard Agents\nrouter. Setting a provider-specific key always uses that provider directly.\n\n## Fallback Strategy\n\nWhen a model fails, fallbacks are tried in order:\n1. Primary model (2 attempts)\n2. First fallback (2 attempts)\n3. Second fallback (2 attempts)\n4. ...and so on\n\nRetries occur on: network errors, rate limits (429), server errors (5xx), auth errors (401).\n\n## OpenRouter Configuration\n\nFor OpenRouter, use the full model path:\n\n\\`\\`\\`typescript\nexport default defineModel({\n name: 'heavy',\n provider: 'openrouter',\n model: 'google/gemini-3-pro-preview',\n includedProviders: ['google'], // Prefer Google's servers\n});\n\\`\\`\\`\n\n## Best Practices\n\n- **Name by use case**, not model ID (e.g., \\`fast\\`, \\`default\\`, \\`heavy\\`)\n- **Configure fallbacks** for production reliability\n- **Set pricing** for cost tracking in logs when your provider or runtime does not supply it automatically\n- **Cerebras note:** documented Cerebras models have built-in fallback pricing for request logs, but custom/private Cerebras models should still set \\`inputPrice\\` and \\`outputPrice\\`\n- **Use environment variables** for API keys, never hardcode\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/model\n`;\n\nexport const MODELS_CLAUDE_MD = MODELS_AGENTS_MD;\n","export const PROMPTS_AGENTS_MD = `# Prompt Definitions\n\nPrompts define system instructions, model selection, and available tools for LLM interactions.\n\n## Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| \\`name\\` | \\`string\\` | Yes | Unique identifier for this prompt |\n| \\`toolDescription\\` | \\`string\\` | Yes | Description shown when used as a tool |\n| \\`prompt\\` | \\`string \\\\| StructuredPrompt\\` | Yes | System instructions |\n| \\`model\\` | \\`string\\` | Yes | Model name to use (references \\`agents/models/\\`) |\n| \\`tools\\` | \\`(string \\\\| ToolConfig \\\\| SubagentToolConfig)[]\\` | No | Available tools (include ai_human agent names for handoffs and dual_ai subagent configs) |\n| \\`includeChat\\` | \\`boolean\\` | No | Include full conversation history |\n| \\`includePastTools\\` | \\`boolean\\` | No | Include previous tool results |\n| \\`parallelToolCalls\\` | \\`boolean\\` | No | Allow multiple concurrent tool calls |\n| \\`toolChoice\\` | \\`'auto' \\\\| 'none' \\\\| 'required'\\` | No | Tool calling strategy |\n| \\`requiredSchema\\` | \\`z.ZodObject\\` | No | Input validation when called as tool |\n| \\`variables\\` | \\`VariableDefinition[]\\` | No | Variable declarations (\\`name\\`, \\`type\\`, \\`required\\`, \\`scoped\\`, \\`description\\`) |\n| \\`env\\` | \\`Record<string, string>\\` | No | Prompt-level default values for variables |\n| \\`hooks\\` | \\`string[]\\` | No | Hook IDs to run for this prompt (overrides agent hooks) |\n| \\`reasoning\\` | \\`ReasoningConfig\\` | No | Extended thinking configuration |\n\n## Basic Example\n\n\\`\\`\\`typescript\nimport { definePrompt } from '@standardagents/builder';\n\nexport default definePrompt({\n name: 'customer_support',\n toolDescription: 'Handle customer support inquiries',\n model: 'default',\n prompt: \\`You are a helpful customer support agent.\nAlways be polite and professional.\nIf you cannot help, escalate to a human.\\`,\n tools: ['search_knowledge_base', 'create_ticket'],\n includeChat: true,\n});\n\\`\\`\\`\n\n## Structured Prompts\n\nInclude other prompts for reusable instruction blocks:\n\n\\`\\`\\`typescript\nexport default definePrompt({\n name: 'main_assistant',\n toolDescription: 'Primary assistant',\n model: 'default',\n prompt: [\n { type: 'text', content: 'You are a helpful assistant.\\\\n\\\\n' },\n { type: 'include', prompt: 'common_rules' }, // Includes another prompt\n { type: 'env', property: 'ASSISTANT_TONE' }, // Inject variable value\n { type: 'text', content: '\\\\n\\\\nBe concise.' },\n ],\n});\n\\`\\`\\`\n\n\\`type: 'env'\\` inserts a resolved thread variable value. Use this only for non-secret values that are safe to expose to the LLM.\n\nThe sandboxed coding prompt declares \\`HTTP_HOST\\` as a text variable. Its URL helper uses that value as the origin for files exposed from the thread \\`public/\\` directory and endpoints exposed from the thread \\`api/\\` directory. Public URLs should usually omit extensions; extensionless public paths resolve \\`.html\\`, then \\`.js\\`, then \\`.ts\\`, then matching \\`index\\` files in the same order. Browser pages should reference only public files, \\`api/\\` endpoints, or absolute external URLs, using relative asset URLs like \\`./app\\` and \\`./api/todos\\`; private \\`src/\\` files are not served directly. Public \\`.ts\\` files are transformed to browser JavaScript and are not server endpoints. Server-side endpoints live under the thread filesystem \\`api/\\` directory, and the \\`api/\\` directory name stays in the public URL: \\`api/todo.ts\\` is \\`/api/threads/{threadId}/api/todo\\`, while \\`api/todo.ts\\` is not \\`/api/threads/{threadId}/todo\\` or \\`/api/threads/{threadId}/todos\\`. Endpoint files default-export a function that accepts \\`Request\\` and returns \\`Response\\` or \\`Promise<Response>\\`. Endpoint code can import \\`fetch\\`, \\`fs\\`, and \\`storage\\`, and can import private helpers with relative paths such as \\`../src/todo.ts\\`. When the coding agent creates a site, page, or endpoint, it should call \\`get_public_url\\` with the created file path and use the returned URL.\n\nSandboxed code and \\`api/\\` endpoints can persist small JSON-serializable runtime data through \\`import { storage } from \"storage\"\\`. Use \\`storage.get\\`, \\`storage.set\\`, \\`storage.delete\\`, and \\`storage.has\\` with stable logical keys. Do not expose, mention, or depend on internal storage key prefixes.\n\nThe sandboxed coding prompt includes \\`delete_file\\` for removing files or empty directories from the thread filesystem. Use it to clean up obsolete implementation files, stale public assets, and abandoned endpoint routes after the replacement is working.\n\n## Tool Configuration\n\nTools can be simple names or detailed configs:\n\n\\`\\`\\`typescript\ntools: [\n 'simple_tool', // Just the tool name\n {\n name: 'complex_tool',\n includeTextResponse: true, // Include sub-prompt text in result\n includeToolCalls: false, // Exclude sub-prompt tool calls\n includeErrors: true, // Include error details\n initUserMessageProperty: 'query', // Use this arg as initial message\n },\n],\n\\`\\`\\`\n\nProvider-built-in tools use the same \\`tools\\` list once the selected model enables\nthem with \\`providerTools\\`. AgentBuilder passes them to the provider and records\nprovider-reported calls in request logs; it does not execute those tools locally.\nGenerated prompt files may store these selections as \\`provider:<toolName>\\` to\ndistinguish provider tools from local tools with the same name.\n\n### Subagent Tool Configuration\n\nUse \\`SubagentToolConfig\\` when the tool is a \\`dual_ai\\` agent:\n\n\\`\\`\\`typescript\ntools: [\n // Blocking, non-resumable (default)\n { name: 'data_processor_agent' },\n\n // Non-blocking, resumable with a single instance\n {\n name: 'browser_agent',\n blocking: false,\n immediate: {\n nameEnv: 'BROWSER_AGENT_NAME',\n descriptionEnv: 'BROWSER_AGENT_DESCRIPTION',\n scopedEnv: ['BROWSER_AGENT_API_KEY'],\n },\n optional: 'ENABLE_BROWSER_AGENT',\n initAgentNameProperty: 'name',\n resumable: {\n receives_messages: 'side_a',\n maxInstances: 1,\n parentCommunication: 'explicit',\n },\n },\n]\n\\`\\`\\`\n\nWhen prompt-configured resumable dual_ai subagents exist, the runtime auto-injects:\n- \\`subagent_create\\` for spawning new child instances\n- \\`subagent_message\\` for messaging active resumable instances\n\n\\`subagent_create\\` requires a non-empty \\`name\\` for human-friendly child thread labels.\nAgentBuilder stores that argument as a \\`name:<value>\\` thread tag.\n\nSet \\`immediate: true\\` to run a tool automatically when the prompt activates.\nUse \\`immediate: { nameEnv, descriptionEnv, scopedEnv }\\` when you want safe per-instance bootstrap hints while keeping copied scoped env runtime-only.\nSet \\`optional: 'ENV_NAME'\\` to enable a subagent branch only when env resolves to \\`true\\`, \\`1\\`, or \\`yes\\`.\nSet \\`resumable.parentCommunication: 'explicit'\\` when the child should stay quiet until its own tools or hooks call \\`state.notifyParent()\\` or \\`state.setStatus()\\`.\nIf required scoped vars are missing, the runtime returns \\`error_code: \"subagent_env_required\"\\` with a temporary \\`GET/POST /api/threads/:threadId/variables/:requestId\\` endpoint in \\`error_data.endpoint\\`.\n\n## Input Validation\n\nValidate inputs when prompt is called as a tool:\n\n\\`\\`\\`typescript\nimport { z } from 'zod';\n\nexport default definePrompt({\n name: 'data_extractor',\n toolDescription: 'Extract structured data from text',\n model: 'default',\n prompt: 'Extract the requested data from the input.',\n requiredSchema: z.object({\n text: z.string().describe('Text to extract from'),\n fields: z.array(z.string()).describe('Fields to extract'),\n }),\n});\n\\`\\`\\`\n\n## Extended Thinking (Reasoning)\n\nEnable for complex reasoning tasks:\n\n\\`\\`\\`typescript\nexport default definePrompt({\n name: 'code_reviewer',\n toolDescription: 'Review code for issues',\n model: 'heavy',\n prompt: 'Review the code thoroughly...',\n reasoning: {\n effort: 'high', // 'low' | 'medium' | 'high'\n maxTokens: 16000, // Max thinking tokens\n exclude: true, // Don't include thinking in response\n },\n});\n\\`\\`\\`\n\n**⚠️ Google Models Require Reasoning**: When using Google models (\\`google/gemini-*\\`) via OpenRouter, you **must** include \\`reasoning\\` configuration or tool calls will fail. At minimum:\n\n\\`\\`\\`typescript\nreasoning: {\n effort: 'low', // Can be 'low', 'medium', or 'high'\n},\n\\`\\`\\`\n\n## Hooks\n\nAttach lifecycle hooks to a prompt:\n\n\\`\\`\\`typescript\nexport default definePrompt({\n name: 'customer_support',\n toolDescription: 'Handle customer support',\n model: 'default',\n prompt: 'You are a support agent...',\n hooks: ['limit_to_20', 'redact_pii'], // Hook IDs from agents/hooks/\n});\n\\`\\`\\`\n\nPrompt hooks take precedence over agent hooks. See \\`agents/hooks/AGENTS.md\\` for details.\n\n## Best Practices\n\n- **Write clear instructions** - Structure with headers and bullet points\n- **Describe tools thoroughly** - LLMs decide based on descriptions\n- **Validate inputs with Zod** - Catch errors early\n- **Use \\`includeChat\\`** for conversational context\n- **Name by purpose**, not model (e.g., \\`support_agent\\` not \\`gpt4_prompt\\`)\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/prompt\n`;\n\nexport const PROMPTS_CLAUDE_MD = PROMPTS_AGENTS_MD;\n","export const AGENT_DEFINITIONS_AGENTS_MD = `# Agent Definitions\n\nAgents orchestrate conversations by defining prompts, stop conditions, and turn limits.\n\n## Agent Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| \\`name\\` | \\`string\\` | Yes | Unique identifier for this agent |\n| \\`type\\` | \\`'ai_human' \\\\| 'dual_ai'\\` | No | Conversation type (default: \\`ai_human\\`) |\n| \\`sideA\\` | \\`SideConfig\\` | Yes | Configuration for side A (AI in ai_human) |\n| \\`sideB\\` | \\`SideConfig\\` | No | Configuration for side B (required for dual_ai) |\n| \\`maxSessionTurns\\` | \\`number\\` | No | Max total turns across both sides |\n| \\`exposeAsTool\\` | \\`boolean\\` | No | Allow other prompts to hand off to this agent |\n| \\`toolDescription\\` | \\`string\\` | No | Description when used as tool (required if exposeAsTool) |\n| \\`env\\` | \\`Record<string, string>\\` | No | Agent-level default variable values |\n| \\`hooks\\` | \\`string[]\\` | No | Hook IDs to run for this agent (fallback if prompt has no hooks) |\n| \\`tags\\` | \\`string[]\\` | No | Tags for categorization and filtering |\n\n## Side Configuration\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| \\`label\\` | \\`string\\` | No | Display name for this side |\n| \\`prompt\\` | \\`string\\` | Yes | Prompt name to use (references \\`agents/prompts/\\`) |\n| \\`stopOnResponse\\` | \\`boolean\\` | No | Stop turn when LLM returns text (default: true) |\n| \\`stopTool\\` | \\`string\\` | No | Tool that stops this side's turn |\n| \\`stopToolResponseProperty\\` | \\`string\\` | No | Property to extract from stop tool result |\n| \\`maxSteps\\` | \\`number\\` | No | Maximum step budget for this side |\n| \\`sessionStop\\` | \\`string \\\\| SessionToolBinding\\` | No | Terminal success lifecycle binding |\n| \\`sessionFail\\` | \\`string \\\\| SessionToolBinding\\` | No | Terminal failure lifecycle binding |\n| \\`sessionStatus\\` | \\`string \\\\| SessionToolBinding\\` | No | Non-terminal status lifecycle binding |\n| \\`manualStopCondition\\` | \\`boolean\\` | No | Enable custom stop handling via hooks |\n\n## Basic Example (AI-Human)\n\n\\`\\`\\`typescript\nimport { defineAgent } from '@standardagents/builder';\n\nexport default defineAgent({\n name: 'support_agent',\n type: 'ai_human',\n sideA: {\n label: 'Support',\n prompt: 'customer_support',\n stopOnResponse: true,\n sessionStop: 'close_ticket',\n maxSteps: 50,\n },\n tags: ['support', 'tier-1'],\n});\n\\`\\`\\`\n\n## Dual-AI Example\n\nTwo AI agents conversing (e.g., debate, iterative refinement):\n\n\\`\\`\\`typescript\nexport default defineAgent({\n name: 'code_review_debate',\n type: 'dual_ai',\n maxSessionTurns: 20,\n sideA: {\n label: 'Reviewer',\n prompt: 'code_reviewer',\n stopOnResponse: true,\n },\n sideB: {\n label: 'Developer',\n prompt: 'code_defender',\n stopOnResponse: true,\n },\n});\n\\`\\`\\`\n\n## Dual-AI Subagent Pattern\n\nWhen a \\`dual_ai\\` agent is used as a subagent tool, a common split is:\n- **sideA**: performs work (tools, data gathering, execution)\n- **sideB**: reflection, verification, and quality checks\n\n\\`\\`\\`typescript\nexport default defineAgent({\n name: 'research_subagent',\n type: 'dual_ai',\n exposeAsTool: true,\n toolDescription: 'Researches and validates findings autonomously',\n maxSessionTurns: 16,\n sideA: {\n label: 'Worker',\n prompt: 'research_worker',\n sessionStatus: 'set_subagent_status',\n sessionFail: 'fail_research_subagent',\n sessionStop: 'finish_subagent',\n },\n sideB: {\n label: 'Reviewer',\n prompt: 'research_reviewer',\n stopOnResponse: true,\n },\n});\n\\`\\`\\`\n\n## Agent Handoffs\n\nExpose an agent for handoffs from other prompts:\n\n\\`\\`\\`typescript\nexport default defineAgent({\n name: 'escalation_agent',\n type: 'ai_human',\n exposeAsTool: true,\n toolDescription: 'Escalate to senior support for complex issues',\n sideA: {\n prompt: 'senior_support',\n },\n});\n\\`\\`\\`\n\nOther prompts can then include the agent name in their \\`tools\\` array to enable handoffs.\n\n## Stop Conditions (Priority Order)\n\n1. **sessionFail** - Ends entire conversation with a terminal failure\n2. **sessionStop** - Ends entire conversation successfully\n3. **stopTool** - Ends current side's turn\n4. **maxSteps** - Ends side execution when the safety budget is reached\n5. **stopOnResponse** - Ends turn when LLM returns text\n6. **maxSessionTurns** - Ends conversation (hard limit: 250)\n\n## Hooks\n\nAttach lifecycle hooks at the agent level:\n\n\\`\\`\\`typescript\nexport default defineAgent({\n name: 'support_agent',\n type: 'ai_human',\n hooks: ['log_all_messages', 'sanitize_results'],\n sideA: {\n prompt: 'customer_support',\n },\n});\n\\`\\`\\`\n\nAgent hooks run as a fallback when the active prompt has no hooks defined. Prompt hooks always take precedence. See \\`agents/hooks/AGENTS.md\\` for details.\n\n## Naming Convention\n\nAgent names **must** end with the \\`_agent\\` suffix (e.g., \\`support_agent\\`, \\`research_agent\\`).\nThis convention is enforced by the builder UI and makes agents easily identifiable in logs and code.\n\n## Best Practices\n\n- **Use descriptive names** (\\`customer_support_agent\\` not \\`agent1\\`)\n- **Always use the _agent suffix** - names like \\`support_agent\\`, \\`research_agent\\`\n- **Always set maxSteps or maxSessionTurns** as safety limits\n- **Match stop conditions to use case** - chat apps use stopOnResponse, workflows use stopTool\n- **Use labels** for clarity in logs and UI\n- **Organize with tags** for filtering\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/agent\n`;\n\nexport const AGENTS_CLAUDE_MD = AGENT_DEFINITIONS_AGENTS_MD;\n","export const TOOLS_AGENTS_MD = `# Custom Tools\n\nTools extend agent capabilities beyond text generation. They allow LLMs to fetch data, perform calculations, execute side effects, and chain to other prompts or agents.\n\n## Function Signature\n\n\\`\\`\\`typescript\ndefineTool({\n description: string, // What the tool does (shown to LLM)\n args?: z.ZodObject, // Input validation schema (optional)\n execute: (state, args) => ToolResult, // Implementation\n variables?: VariableDefinition[], // Declared variables (optional)\n})\n\\`\\`\\`\n\n## Basic Example\n\n\\`\\`\\`typescript\nimport { defineTool } from '@standardagents/builder';\nimport { z } from 'zod';\n\nexport default defineTool({\n description: 'Search the knowledge base for articles matching a query',\n args: z.object({\n query: z.string().describe('Search query'),\n limit: z.number().optional().default(10).describe('Max results'),\n }),\n execute: async (state, args) => {\n const results = await searchKB(args.query, args.limit);\n return {\n status: 'success',\n result: JSON.stringify(results),\n };\n },\n});\n\\`\\`\\`\n\n## Argument Schemas\n\nTool args must be a top-level \\`z.object(...)\\`. Prefer explicit, bounded schemas made from strings, numbers, booleans, nulls, literals, enums, arrays, objects, optionals, nullables, and defaults. Avoid provider-visible recursive or open-ended schemas such as \\`z.unknown()\\`, \\`z.any()\\`, and \\`z.object({}).catchall(...)\\`; strict tool providers can reject the generated JSON Schema. If a tool needs arbitrary JSON input, accept it as a JSON string and parse it inside \\`execute\\`.\n\n## ToolResult Interface\n\n| Property | Type | Description |\n|----------|------|-------------|\n| \\`status\\` | \\`'success' \\\\| 'error'\\` | Whether the tool succeeded |\n| \\`result\\` | \\`string\\` | Tool output (required for success) |\n| \\`error\\` | \\`string\\` | Error message (for error status) |\n| \\`error_code\\` | \\`string\\` | Machine-readable error code |\n| \\`error_data\\` | \\`Record<string, unknown>\\` | Structured error payload |\n| \\`attachments\\` | \\`ToolAttachment[]\\` | Files to attach (images, etc.) |\n\n## ThreadState Access\n\nThe \\`state\\` parameter provides access to:\n\n\\`\\`\\`typescript\nexecute: async (state, args) => {\n // Thread information\n const threadId = state.thread.id;\n const thread = state.thread.instance;\n\n // Configuration\n const agentName = state.agent.name;\n const modelName = state.model.name;\n\n // Message history\n const messages = state.messages;\n\n // Thread variable resolution\n const apiKey = await state.env('GOOGLE_API_KEY');\n await state.setEnv('LAST_TOOL_RUN_AT', new Date().toISOString());\n\n // Durable per-thread JSON values\n const runCount = (await state.getValue<number>('run_count')) ?? 0;\n await state.setValue('run_count', runCount + 1);\n\n // Sandboxed JS/TS execution with explicit bridge capabilities\n const run = state.runCode('export async function main(path) { return await read(path) }', {\n execute: { fn: 'main', args: ['/notes.txt'] },\n globals: {\n read: async (path: string) => {\n const data = await state.readFile(path);\n return data ? new TextDecoder().decode(data) : null;\n },\n },\n });\n const codeResult = await run;\n\n // Parent state (for sub-prompts)\n const root = state.rootState;\n}\n\\`\\`\\`\n\nUse \\`state.runCode()\\` instead of \\`eval\\` or \\`new Function\\` for model- or user-authored JavaScript/TypeScript. The sandbox starts with no ambient host capabilities; provide imports/globals explicitly, use \\`modules\\` for local relative ES modules, use \\`execute\\` to select an export and pass args, use \\`report\\` for streamed observations, and call \\`run.terminate(reason)\\` from your own timeout budget when needed. \\`modules\\` keys are graph-root relative paths; entry-source imports resolve from \\`options.filename\\` when supplied. Relative module imports may use \\`./\\` and \\`../\\` as long as they resolve within the supplied module graph. In thread endpoints, \\`runCode\\` is forwarded into the thread Durable Object; pass plain transferable option values there, and do function-backed bridges from tools or in-thread execution contexts.\n\n## Tool Without Arguments\n\n\\`\\`\\`typescript\nexport default defineTool({\n description: 'Get current server time',\n execute: async (state) => {\n return {\n status: 'success',\n result: new Date().toISOString(),\n };\n },\n});\n\\`\\`\\`\n\n## Error Handling\n\nReturn errors gracefully instead of throwing:\n\n\\`\\`\\`typescript\nexport default defineTool({\n description: 'Fetch user data',\n args: z.object({ userId: z.string() }),\n execute: async (state, args) => {\n try {\n const user = await fetchUser(args.userId);\n return { status: 'success', result: JSON.stringify(user) };\n } catch (error) {\n return {\n status: 'error',\n error: \\`Failed to fetch user: \\${error.message}\\`,\n };\n }\n },\n});\n\\`\\`\\`\n\n## Queueing Additional Tools\n\nQueue another tool to run after the current one:\n\n\\`\\`\\`typescript\nimport { queueTool } from '@standardagents/builder';\n\nexport default defineTool({\n description: 'Create order and send confirmation',\n args: z.object({ items: z.array(z.string()) }),\n execute: async (state, args) => {\n const order = await createOrder(args.items);\n\n // Queue email tool to run next\n queueTool(state, 'send_confirmation_email', {\n orderId: order.id,\n email: state.thread.metadata.userEmail,\n });\n\n return { status: 'success', result: JSON.stringify(order) };\n },\n});\n\\`\\`\\`\n\n## Injecting Messages\n\nAdd messages without triggering re-execution:\n\n\\`\\`\\`typescript\nimport { injectMessage } from '@standardagents/builder';\n\nexport default defineTool({\n description: 'Log audit event',\n args: z.object({ event: z.string() }),\n execute: async (state, args) => {\n await injectMessage(state, {\n role: 'system',\n content: \\`[AUDIT] \\${args.event}\\`,\n });\n return { status: 'success', result: 'Logged' };\n },\n});\n\\`\\`\\`\n\n## Variables and Env\n\nTools can declare variable requirements with \\`variables\\`, including \\`required\\` and \\`description\\` metadata:\n\n\\`\\`\\`typescript\nexport default defineTool({\n description: 'Search uploaded documents',\n args: z.object({ query: z.string() }),\n execute: async (state, args) => {\n const vectorStoreId = await state.env('VECTOR_STORE_ID');\n const results = await searchVectorStore(vectorStoreId, args.query);\n return { status: 'success', result: JSON.stringify(results) };\n },\n variables: [\n {\n name: 'VECTOR_STORE_ID',\n type: 'text',\n required: true,\n scoped: false,\n description: 'OpenAI Vector Store ID',\n },\n ],\n});\n\\`\\`\\`\n\nUse \\`scoped: true\\` for per-instance values that should not inherit from parent thread env (for example per-account OAuth tokens on subagents).\n\n## Returning Attachments\n\nTools can return file attachments (e.g., generated images):\n\n\\`\\`\\`typescript\nexport default defineTool({\n description: 'Generate a chart from data',\n args: z.object({ data: z.array(z.number()) }),\n execute: async (state, args) => {\n const chartImage = await generateChart(args.data);\n return {\n status: 'success',\n result: 'Chart generated successfully',\n attachments: [{\n name: 'chart.png',\n mimeType: 'image/png',\n data: chartImage.base64,\n width: 800,\n height: 600,\n }],\n };\n },\n});\n\\`\\`\\`\n\n## Best Practices\n\n- **Write clear descriptions** - LLMs decide tool usage based on descriptions\n- **Describe all parameters** with \\`.describe()\\` in Zod schemas\n- **Handle errors gracefully** - return error status, don't throw\n- **Use snake_case** for file names (\\`search_knowledge_base.ts\\`)\n- **Keep tools focused** - one task per tool\n- **Use \\`state.rootState\\`** when queueing from sub-prompts\n\n## Supported Zod Types\n\n- Primitives: \\`string\\`, \\`number\\`, \\`boolean\\`, \\`null\\`\n- Enums: \\`z.enum(['a', 'b', 'c'])\\`\n- Arrays: \\`z.array(z.string())\\`\n- Objects: \\`z.object({ ... })\\`\n- Optional: \\`z.string().optional()\\`\n- Default: \\`z.number().default(10)\\`\n- Nullable: \\`z.string().nullable()\\`\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/tool\n`;\n\nexport const TOOLS_CLAUDE_MD = TOOLS_AGENTS_MD;\n","export const HOOKS_AGENTS_MD = `# Lifecycle Hooks\n\nHooks intercept and modify agent execution at specific lifecycle points.\n\n## Available Hooks\n\n| Hook | Signature | Purpose |\n|------|-----------|---------|\n| \\`after_thread_created\\` | \\`(state: ThreadState) => void\\` | Initialize a newly created thread before execution |\n| \\`after_subagent_created\\` | \\`(state: ThreadState, childState: ThreadState) => void\\` | Run parent-side logic after a child thread is created |\n| \\`after_system_message\\` | \\`(state: ThreadState, systemMessage: string) => string \\\\| null \\\\| undefined\\` | Modify the rendered system message for a request |\n| \\`filter_messages\\` | \\`(state: ThreadState, messages: Message[]) => Message[]\\` | Filter raw messages before LLM context |\n| \\`prefilter_llm_history\\` | \\`(state: ThreadState, messages: LLMMessage[]) => LLMMessage[]\\` | Modify chat completion messages before LLM |\n| \\`before_create_message\\` | \\`(state: ThreadState, message: Message) => Message\\` | Modify message before database insert |\n| \\`after_create_message\\` | \\`(state: ThreadState, message: Message) => void\\` | Run logic after message created |\n| \\`before_update_message\\` | \\`(state: ThreadState, id: string, updates: Record) => Record\\` | Modify updates before message update |\n| \\`after_update_message\\` | \\`(state: ThreadState, message: Message) => void\\` | Run logic after message updated |\n| \\`before_store_tool_result\\` | \\`(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => HookToolResult\\` | Modify tool result before storage |\n| \\`after_tool_call_success\\` | \\`(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => HookToolResult \\\\| null\\` | Process successful tool execution |\n| \\`after_tool_call_failure\\` | \\`(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => HookToolResult \\\\| null\\` | Process failed tool execution |\n\nAll hooks receive \\`ThreadState\\` as their first parameter, providing access to thread identity, message history, resource loading, durable per-thread values via \\`getValue\\` / \\`setValue\\`, and sandboxed JS/TS execution via \\`runCode\\`.\n\n## Creating a Hook\n\nEach hook file exports a default \\`defineHook\\` call with three properties:\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'filter_messages', // Hook type\n id: 'limit_recent_messages', // Unique ID (snake_case)\n execute: async (state, messages) => {\n return messages.slice(-20);\n }\n});\n\\`\\`\\`\n\n## Hook Scoping\n\nHooks are scoped to **prompts** or **agents** via their ID:\n\n\\`\\`\\`typescript\n// In a prompt definition\ndefinePrompt({\n name: 'customer_support',\n hooks: ['limit_recent_messages', 'redact_pii'],\n // ...\n});\n\n// In an agent definition\ndefineAgent({\n name: 'support_agent',\n hooks: ['log_all_messages'],\n // ...\n});\n\\`\\`\\`\n\n- **Prompt hooks** take precedence over agent hooks\n- If a prompt defines hooks, only those run (agent hooks are skipped)\n- If no prompt hooks are defined, agent hooks run as fallback\n- Hooks are filtered by type at runtime\n\n## File Naming\n\nHook files can use **any name** — the hook type and ID are defined inside the file:\n\n\\`\\`\\`\nagents/hooks/\n├── my_filter.ts # Could contain any hook type\n├── redact_sensitive_data.ts\n├── log_tool_usage.ts\n└── add_metadata.ts\n\\`\\`\\`\n\n## Examples\n\n### Filter Messages (Limit Context)\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'filter_messages',\n id: 'limit_to_20',\n execute: async (state, messages) => {\n return messages.slice(-20);\n }\n});\n\\`\\`\\`\n\n### Prefilter LLM History (Redact Content)\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'prefilter_llm_history',\n id: 'redact_pii',\n execute: async (state, messages) => {\n return messages.map(msg => ({\n ...msg,\n content: typeof msg.content === 'string'\n ? msg.content.replace(/\\\\b\\\\d{4}-\\\\d{4}-\\\\d{4}-\\\\d{4}\\\\b/g, '[REDACTED]')\n : msg.content,\n }));\n }\n});\n\\`\\`\\`\n\n### Before Create Message (Add Metadata)\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'before_create_message',\n id: 'add_version_metadata',\n execute: async (state, message) => {\n if (message.role === 'user' && message.content) {\n return { ...message, content: \\`[v1.0] \\${message.content}\\` };\n }\n return message;\n }\n});\n\\`\\`\\`\n\n### Before Store Tool Result (Sanitize)\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'before_store_tool_result',\n id: 'sanitize_results',\n execute: async (state, toolCall, toolResult) => {\n // toolCall: { id, type: 'function', function: { name, arguments } }\n // toolResult: { status, result?, error?, stack?, attachments? }\n if (toolResult.result) {\n return { ...toolResult, result: toolResult.result.replace(/secret/gi, '[REDACTED]') };\n }\n return toolResult;\n }\n});\n\\`\\`\\`\n\n### After Tool Call Success (Logging)\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'after_tool_call_success',\n id: 'log_tool_success',\n execute: async (state, toolCall, result) => {\n console.log(\\`Tool \\${toolCall.function.name} succeeded\\`);\n return null; // Return null to use original result\n }\n});\n\\`\\`\\`\n\n### After Tool Call Failure (Recovery)\n\n\\`\\`\\`typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'after_tool_call_failure',\n id: 'weather_fallback',\n execute: async (state, toolCall, result) => {\n if (toolCall.function.name === 'fetch_weather') {\n return {\n status: 'success',\n result: JSON.stringify({ temp: 'unavailable', fallback: true }),\n };\n }\n return null; // Use original error for other tools\n }\n});\n\\`\\`\\`\n\n## Hook Categories\n\n**Transformation hooks** (return modified data):\n- \\`after_system_message\\` (return replacement string, or null/undefined for no change)\n- \\`filter_messages\\`\n- \\`prefilter_llm_history\\`\n- \\`before_create_message\\`\n- \\`before_update_message\\`\n- \\`before_store_tool_result\\`\n- \\`after_tool_call_success\\` (return modified result or null)\n- \\`after_tool_call_failure\\` (return modified result or null)\n\n**Event hooks** (side effects only):\n- \\`after_thread_created\\`\n- \\`after_subagent_created\\`\n- \\`after_create_message\\`\n- \\`after_update_message\\`\n\n## Best Practices\n\n- **Keep hooks fast** - target <100ms execution\n- **Wrap in try-catch** - hooks continue on error (original data preserved)\n- **Use unique IDs** - hook IDs must be snake_case and unique across the project\n- **Scope appropriately** - assign hooks to prompts or agents that need them\n- **Document purpose** with clear comments\n- **Use for cross-cutting concerns** - logging, redaction, enrichment\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/hook\n`;\n\nexport const HOOKS_CLAUDE_MD = HOOKS_AGENTS_MD;\n","export const API_AGENTS_MD = `# Thread-Specific API Endpoints\n\nDefine custom API endpoints that operate on specific threads with access to the thread's ThreadState.\n\n## File-Based Routing\n\n| File Pattern | HTTP Method | Route |\n|--------------|-------------|-------|\n| \\`name.ts\\` | GET | \\`/api/threads/:threadId/name\\` |\n| \\`name.get.ts\\` | GET | \\`/api/threads/:threadId/name\\` |\n| \\`name.post.ts\\` | POST | \\`/api/threads/:threadId/name\\` |\n| \\`name.put.ts\\` | PUT | \\`/api/threads/:threadId/name\\` |\n| \\`name.delete.ts\\` | DELETE | \\`/api/threads/:threadId/name\\` |\n| \\`index.ts\\` | GET | \\`/api/threads/:threadId\\` |\n| \\`nested/route.ts\\` | GET | \\`/api/threads/:threadId/nested/route\\` |\n| \\`items/[id].ts\\` | GET | \\`/api/threads/:threadId/items/:id\\` |\n| \\`files/[*].ts\\` | GET | \\`/api/threads/:threadId/files/*\\` |\n\nFiles without a method suffix default to GET. Method suffixes are case-insensitive and support \\`.get.ts\\`, \\`.post.ts\\`, \\`.put.ts\\`, \\`.patch.ts\\`, and \\`.delete.ts\\`.\n\nDynamic segments use \\`[name]\\` and are passed to the handler as \\`params.name\\`. Catch-all segments use \\`[*]\\` and are passed as \\`params['*']\\`; the catch-all value may contain \\`/\\` for nested paths. Static routes match before dynamic routes, and dynamic routes match before catch-all routes.\n\n## Basic Example\n\n\\`\\`\\`typescript\n// agents/api/status.get.ts -> GET /api/threads/:threadId/status\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state, params) => {\n const { messages, total } = await state.getMessages();\n return Response.json({\n threadId: state.threadId,\n messageCount: total,\n status: 'active',\n params,\n });\n});\n\\`\\`\\`\n\n## Handler Parameters\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| \\`req\\` | \\`Request\\` | The incoming HTTP request |\n| \\`state\\` | \\`ThreadState\\` | Thread state with messages, identity, file system, \\`runCode\\`, etc. |\n| \\`params\\` | \\`Record<string, string>\\` | Route parameters captured from \\`[name]\\` and \\`[*]\\` path segments |\n\nNote: \\`state.execution\\` is always \\`null\\` in endpoints since the thread is at rest. \\`state.runCode()\\` is available from endpoints and is forwarded into the thread runtime; pass plain transferable option values there, and do function-backed sandbox bridges from tools or in-thread execution contexts.\n\n## ThreadState Methods\n\nAccess thread data through the state object:\n\n\\`\\`\\`typescript\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n // Thread identity\n console.log('Thread ID:', state.threadId);\n console.log('Agent ID:', state.agentId);\n console.log('User ID:', state.userId);\n\n // Message operations\n const { messages, total, hasMore } = await state.getMessages({\n limit: 100,\n offset: 0,\n order: 'desc',\n });\n\n // Thread env (thread scope + active descendants)\n const approvalGate = await state.env('TOPDOWN_APPROVAL_GATE');\n await state.setEnv('TOPDOWN_APPROVAL_GATE', approvalGate || 'open');\n\n // Durable per-thread JSON values\n const exports = (await state.getValue<number>('export_count')) ?? 0;\n await state.setValue('export_count', exports + 1);\n\n // File system operations\n const files = await state.findFiles('**/*.json');\n const data = await state.readFile('/data/config.json');\n\n // Resource loading\n const agent = await state.loadAgent('my-agent');\n const prompt = await state.loadPrompt('my-prompt');\n\n return Response.json({ messages, total });\n});\n\\`\\`\\`\n\n## POST with Request Body\n\n\\`\\`\\`typescript\n// agents/api/export.post.ts -> POST /api/threads/:threadId/export\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n const body = await req.json();\n const { format = 'json' } = body;\n\n const { messages } = await state.getMessages();\n\n if (format === 'csv') {\n const csv = messages.map(m => \\`\\${m.role},\\${m.content}\\`).join('\\\\n');\n return new Response(csv, {\n headers: { 'Content-Type': 'text/csv' },\n });\n }\n\n return Response.json(messages);\n});\n\\`\\`\\`\n\n## Nested Routes\n\nCreate directories for nested routes:\n\n\\`\\`\\`\nagents/api/\n├── status.get.ts -> GET /api/threads/:threadId/status\n├── export.post.ts -> POST /api/threads/:threadId/export\n└── messages/\n ├── count.ts -> GET /api/threads/:threadId/messages/count\n ├── [id].ts -> GET /api/threads/:threadId/messages/:id\n └── [*].ts -> GET /api/threads/:threadId/messages/*\n\\`\\`\\`\n\n## Error Handling\n\n\\`\\`\\`typescript\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n try {\n const data = await riskyOperation();\n return Response.json(data);\n } catch (error) {\n return Response.json({ error: error.message }, { status: 500 });\n }\n});\n\\`\\`\\`\n\n## File System Operations\n\n\\`\\`\\`typescript\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n // Read files\n const content = await state.readFile('/data/file.txt');\n\n // Write files\n await state.writeFile('/output/result.json', JSON.stringify(data), 'application/json');\n\n // List directory\n const { entries } = await state.readdirFile('/data');\n\n // Search files\n const matches = await state.grepFiles('pattern');\n const paths = await state.findFiles('**/*.ts');\n\n return Response.json({ success: true });\n});\n\\`\\`\\`\n\n## Best Practices\n\n- **Keep handlers fast** - endpoints are in the request path\n- **Paginate large queries** - use limit/offset for messages\n- **Validate input data** - check request body before processing\n- **Use descriptive file names** - \\`export.post.ts\\` not \\`ep1.ts\\`\n- **Return proper status codes** - 200, 400, 404, 500\n- **Import from spec** - use \\`@standardagents/spec\\` for \\`defineThreadEndpoint\\`\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/core-concepts/api\n`;\n\nexport const API_CLAUDE_MD = API_AGENTS_MD;\n","import {\n AGENT_DEFINITIONS_AGENTS_MD,\n API_AGENTS_MD,\n HOOKS_AGENTS_MD,\n MODELS_AGENTS_MD,\n PROMPTS_AGENTS_MD,\n ROOT_AGENTS_MD,\n TOOLS_AGENTS_MD,\n} from './docs/index.js'\n\nexport {\n AGENT_DEFINITIONS_AGENTS_MD,\n AGENT_DEFINITIONS_AGENTS_MD as AGENTS_CLAUDE_MD,\n API_AGENTS_MD,\n API_AGENTS_MD as API_CLAUDE_MD,\n HOOKS_AGENTS_MD,\n HOOKS_AGENTS_MD as HOOKS_CLAUDE_MD,\n MODELS_AGENTS_MD,\n MODELS_AGENTS_MD as MODELS_CLAUDE_MD,\n PROMPTS_AGENTS_MD,\n PROMPTS_AGENTS_MD as PROMPTS_CLAUDE_MD,\n ROOT_AGENTS_MD,\n ROOT_AGENTS_MD as ROOT_CLAUDE_MD,\n TOOLS_AGENTS_MD,\n TOOLS_AGENTS_MD as TOOLS_CLAUDE_MD,\n}\n\nexport type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun'\n\nexport interface TemplateFile {\n path: string\n content: string\n message: string\n kind?: 'file' | 'symlink'\n}\n\nexport interface TemplateVersions {\n standardAgents: string\n sip: string\n vite: string\n typescript: string\n zod?: string\n}\n\nexport interface AgentBuilderProjectTemplateOptions {\n projectName: string\n packageManager?: PackageManager | null\n versions?: Partial<TemplateVersions>\n includeTemplateMetadata?: boolean\n templateVersion?: string\n}\n\nexport const FIRST_PARTY_PROVIDER_PACKAGES = [\n '@standardagents/cloudflare',\n '@standardagents/cerebras',\n '@standardagents/google',\n '@standardagents/groq',\n '@standardagents/openai',\n '@standardagents/openrouter',\n '@standardagents/xai',\n] as const\n\nexport const DEFAULT_TEMPLATE_VERSIONS: TemplateVersions = {\n standardAgents: 'latest',\n sip: 'latest',\n vite: 'latest',\n typescript: 'latest',\n zod: 'latest',\n}\n\nexport const AGENTBUILDER_TEMPLATE_VERSION = '0.16.0'\n\nfunction ensureTrailingNewline(value: string): string {\n return value.endsWith('\\n') ? value : `${value}\\n`\n}\n\nfunction mergeVersions(versions?: Partial<TemplateVersions>): TemplateVersions {\n return {\n ...DEFAULT_TEMPLATE_VERSIONS,\n ...versions,\n }\n}\n\nexport function packageNameFromProjectName(projectName: string): string {\n const normalized = projectName\n .toLowerCase()\n .replace(/^@[^/]+\\//, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n return normalized || 'agentbuilder-project'\n}\n\nfunction file(path: string, content: string, message: string): TemplateFile {\n return {\n path,\n content: ensureTrailingNewline(content),\n message,\n kind: 'file',\n }\n}\n\nfunction symlink(path: string, target: string, message: string): TemplateFile {\n return {\n path,\n content: target,\n message,\n kind: 'symlink',\n }\n}\n\nexport function renderPackageJson(options: AgentBuilderProjectTemplateOptions): string {\n const versions = mergeVersions(options.versions)\n const standardAgentsVersion = versions.standardAgents\n const dependencies: Record<string, string> = {\n '@standardagents/builder': standardAgentsVersion,\n '@standardagents/spec': standardAgentsVersion,\n '@standardagents/sip': versions.sip,\n zod: versions.zod ?? 'latest',\n }\n\n for (const providerPackage of FIRST_PARTY_PROVIDER_PACKAGES) {\n dependencies[providerPackage] = standardAgentsVersion\n }\n\n return `${JSON.stringify({\n name: packageNameFromProjectName(options.projectName),\n version: '0.0.0',\n private: true,\n type: 'module',\n scripts: {\n dev: 'vite --host 0.0.0.0 --port 5173',\n build: 'vite build',\n typecheck: 'tsc --noEmit',\n },\n dependencies,\n devDependencies: {\n typescript: versions.typescript,\n vite: versions.vite,\n },\n }, null, 2)}\\n`\n}\n\nexport function renderViteConfig(): string {\n return `import { defineConfig } from \"vite\"\nimport { builder } from \"@standardagents/builder\"\n\nexport default defineConfig({\n plugins: [builder()],\n})\n`\n}\n\nexport function renderTsConfig(): string {\n return `{\n \"compilerOptions\": {\n \"target\": \"ES2022\",\n \"useDefineForClassFields\": true,\n \"module\": \"ESNext\",\n \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n \"skipLibCheck\": true,\n \"moduleResolution\": \"Bundler\",\n \"allowImportingTsExtensions\": true,\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"noEmit\": true,\n \"strict\": true\n },\n \"include\": [\"agents\", \".agents\", \"vite.config.ts\"]\n}\n`\n}\n\nexport function renderGitignore(): string {\n return `node_modules\ndist\n.wrangler\n.env\n.dev.vars\n`\n}\n\nexport function renderDevVarsExample(): string {\n return `# Standard Agents local development environment\n# Copy to .dev.vars for local-only Worker secrets.\n\n# Local data encryption key. Generate with: openssl rand -hex 32\nENCRYPTION_KEY=\n\n# Optional local admin password for development access.\nSUPER_ADMIN_PASSWORD=password\n\n# Platform connection. The CLI writes real values to .dev.vars for platform-created projects.\nSTANDARD_AGENTS_API_KEY=\nPLATFORM_ENDPOINT=\nSTANDARD_AGENTS_API_URL=\n\n# BYOK provider keys. When set, these keys override Standard Agents hosted routing for that provider.\nCLOUDFLARE_API_TOKEN=\nCLOUDFLARE_ACCOUNT_ID=\nCEREBRAS_API_KEY=\nGOOGLE_API_KEY=\nGROQ_API_KEY=\nOPENAI_API_KEY=\nOPENROUTER_API_KEY=\nXAI_API_KEY=\n`\n}\n\nexport function renderTemplateMetadata(options: AgentBuilderProjectTemplateOptions): string {\n return `${JSON.stringify({\n generator: '@standardagents/agentbuilder-template',\n template_version: options.templateVersion ?? AGENTBUILDER_TEMPLATE_VERSION,\n project_name: options.projectName,\n }, null, 2)}\\n`\n}\n\nexport function renderAgentBuilderSupportFiles(options: AgentBuilderProjectTemplateOptions): TemplateFile[] {\n return [\n file('package.json', renderPackageJson(options), 'Add local AgentBuilder package manifest'),\n ]\n}\n\nexport function renderAgentBuilderProject(options: AgentBuilderProjectTemplateOptions): TemplateFile[] {\n const files: TemplateFile[] = [\n file('tsconfig.json', renderTsConfig(), 'Add TypeScript config'),\n file('vite.config.ts', renderViteConfig(), 'Add Vite config'),\n file('agents/agents/AGENTS.md', AGENT_DEFINITIONS_AGENTS_MD, 'Add agent docs'),\n symlink('agents/agents/CLAUDE.md', 'AGENTS.md', 'Add Claude agent docs symlink'),\n file('agents/prompts/AGENTS.md', PROMPTS_AGENTS_MD, 'Add prompt docs'),\n symlink('agents/prompts/CLAUDE.md', 'AGENTS.md', 'Add Claude prompt docs symlink'),\n file('agents/models/AGENTS.md', MODELS_AGENTS_MD, 'Add model docs'),\n symlink('agents/models/CLAUDE.md', 'AGENTS.md', 'Add Claude model docs symlink'),\n file('agents/tools/AGENTS.md', TOOLS_AGENTS_MD, 'Add tool docs'),\n symlink('agents/tools/CLAUDE.md', 'AGENTS.md', 'Add Claude tool docs symlink'),\n file('agents/hooks/AGENTS.md', HOOKS_AGENTS_MD, 'Add hook docs'),\n symlink('agents/hooks/CLAUDE.md', 'AGENTS.md', 'Add Claude hook docs symlink'),\n file('agents/api/AGENTS.md', API_AGENTS_MD, 'Add API docs'),\n symlink('agents/api/CLAUDE.md', 'AGENTS.md', 'Add Claude API docs symlink'),\n ]\n\n if (options.includeTemplateMetadata) {\n files.push(file('.standardagents/template.json', renderTemplateMetadata(options), 'Add Standard Agents template metadata'))\n }\n\n return files\n}\n"],"mappings":";AAAO,IAAM,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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F,SAAO,GAAG,KAAK,UAAU;AAAA,IACvB,WAAW;AAAA,IACX,kBAAkB,QAAQ,mBAAmB;AAAA,IAC7C,cAAc,QAAQ;AAAA,EACxB,GAAG,MAAM,CAAC,CAAC;AAAA;AACb;AAEO,SAAS,+BAA+B,SAA6D;AAC1G,SAAO;AAAA,IACL,KAAK,gBAAgB,kBAAkB,OAAO,GAAG,yCAAyC;AAAA,EAC5F;AACF;AAEO,SAAS,0BAA0B,SAA6D;AACrG,QAAM,QAAwB;AAAA,IAC5B,KAAK,iBAAiB,eAAe,GAAG,uBAAuB;AAAA,IAC/D,KAAK,kBAAkB,iBAAiB,GAAG,iBAAiB;AAAA,IAC5D,KAAK,2BAA2B,6BAA6B,gBAAgB;AAAA,IAC7E,QAAQ,2BAA2B,aAAa,+BAA+B;AAAA,IAC/E,KAAK,4BAA4B,mBAAmB,iBAAiB;AAAA,IACrE,QAAQ,4BAA4B,aAAa,gCAAgC;AAAA,IACjF,KAAK,2BAA2B,kBAAkB,gBAAgB;AAAA,IAClE,QAAQ,2BAA2B,aAAa,+BAA+B;AAAA,IAC/E,KAAK,0BAA0B,iBAAiB,eAAe;AAAA,IAC/D,QAAQ,0BAA0B,aAAa,8BAA8B;AAAA,IAC7E,KAAK,0BAA0B,iBAAiB,eAAe;AAAA,IAC/D,QAAQ,0BAA0B,aAAa,8BAA8B;AAAA,IAC7E,KAAK,wBAAwB,eAAe,cAAc;AAAA,IAC1D,QAAQ,wBAAwB,aAAa,6BAA6B;AAAA,EAC5E;AAEA,MAAI,QAAQ,yBAAyB;AACnC,UAAM,KAAK,KAAK,iCAAiC,uBAAuB,OAAO,GAAG,uCAAuC,CAAC;AAAA,EAC5H;AAEA,SAAO;AACT;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@standardagents/agentbuilder-template",
3
- "version": "0.15.2",
3
+ "version": "0.16.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public",