@standardagents/agentbuilder-template 0.40.13 → 0.41.1
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 +9 -7
- package/dist/index.js +332 -128
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/docs/root.ts","../src/docs/models.ts","../src/docs/providers.ts","../src/docs/prompts.ts","../src/docs/agents.ts","../src/docs/tools.ts","../src/docs/hooks.ts","../src/docs/api.ts","../src/docs/users.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## Packability and Runtime Portability\n\nTreat an agent project as an installable Standard Agent package, not as a\nprivileged extension of one runtime. Everything required for the declared\nagents to execute must use capabilities defined by the Standard Agent\nSpecification and exported with the package.\n\nDo not make required behavior depend on private Durable Object methods,\nimplementation-specific storage schemas or bindings, undocumented HTTP or\nWebSocket events, product sidecars that replace runtime behavior, or\nThreadState._notPackableRuntimeContext. Client-side state may be an\noptimistic cache, but it must not become the only source of truth for agent\nsemantics.\n\nIf the specification lacks a required primitive, define the runtime-neutral\ncapability in @standardagents/spec, document it in the public specification,\nimplement it generically in the runtime, and add conformance coverage before\nthe agent relies on it. Authentication, billing, deployment, and branded UI\nservices may remain external as long as they are not required for the packed\nagent's core execution semantics.\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├── providers/ # Provider definitions (defineProvider)\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\nFor remote local development, opt exact hostnames into the authoring boundary:\n\n\\`\\`\\`typescript\nbuilder({ trustedDevHosts: ['macbookserver.tail13bd39.ts.net'] })\n\\`\\`\\`\n\nThis never changes hosted behavior. Adding a hostname grants anyone who can\nreach the dev server through that name the ability to attempt authoring access;\nsame-origin and normal authoring credential checks still apply. Wildcards,\nschemes, ports, and paths are rejected.\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 arguments: Record<string, unknown>; // Invocation or subagent creation args\n context: Record<string, unknown>; // Current-execution scratch data\n runtimeStreams?: RuntimeStreams; // Optional live execution-host byte streams\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 emit(event, data): void; // Broadcast a custom event to connected thread clients\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>; // Queue a silent message to the parent when one exists\n setStatus(status): Promise<void>; // Update this child in the parent registry; no-op without a parent\n stopSession(options?): Promise<void>; // Terminally stop the current agent session\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\\`state.arguments\\` is read-only thread invocation data. Resumable \\`subagent_create.arguments\\` persists with the child thread, is visible to both child sides, and is also available as prompt variables. Use \\`state.context\\` only for mutable scratch data during the current execution; it is not durable storage.\n\n\\`state.runtimeStreams\\` is optional. Feature-detect it before opening a live\nbyte stream. Capability names and metadata are runtime-defined; streams never\npark or survive an execution-host disconnect. See the tools guide for a full\nfeature-detection, write, read, and cleanup example.\n\n\\`state.emit(event, data)\\` works from tools, hooks, and thread endpoints. In\nan endpoint it broadcasts immediately even though there is no active\nexecution, which is useful for invalidating client snapshots after a durable\n\\`setValue()\\`. Events are not durable; clients must re-read state after\nreconnecting.\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- \\`subagent_create.arguments\\` is validated from the receiving child side's prompt schema and persists as \\`ThreadState.arguments\\` plus prompt variables for the life of the child thread\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()\\`; use \\`state.stopSession({ result, notifyParent, status })\\` when a tool should also terminally end the child session\n- A resumable child's session ending never terminates its thread. The same reference remains addressable for later \\`subagent_message\\` calls; only explicit \\`state.terminate()\\` tears the thread down.\n\nAccess in tools:\n\\`\\`\\`typescript\nexport default defineTool('...', schema, async (state, args) => {\n const threadId = state.threadId;\n const creationArgs = state.arguments;\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| \\`defineProvider()\\` | Custom provider endpoints and overrides | \\`agents/providers/\\` |\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 cost safety\n\nAgentBuilder bounds each Durable Object alarm invocation to 1,000,000 SQLite\nrows read and 10,000 rows written. A breach persistently quarantines that one\nobject, clears its alarm, preserves all storage, and requires an explicit\nresume. Routine alarm rows are deleted when completed; effect history remains\navailable with bounded retention. Deployments integrated with Brolly configure\n\\`BROLLY_CONTROL_PUBLIC_KEY_JWK\\` and \\`BROLLY_ACCOUNT_ID\\`; the built-in signed\n\\`POST /api/auth/brolly-control\\` route can then quarantine an exact object ID.\n\nDo not expose the Brolly private signing key to the AgentBuilder Worker. Do not\ndisable the retention sweeper except as a temporary rollback while diagnosing\na deployment.\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/flowstate)\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\\` | \\`ProviderFactory\\` | Yes | Imported provider factory such as \\`openrouter\\`, \\`openai\\`, or a local provider from \\`agents/providers\\` |\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';\nimport { openrouter } from '@standardagents/openrouter';\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 | \\`nvidia/nemotron-3-ultra-550b-a55b\\` | Frontier open reasoning and orchestration, 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| Cloudflare Workers AI | \\`CLOUDFLARE_API_TOKEN\\` + \\`CLOUDFLARE_ACCOUNT_ID\\` |\n| Cerebras | \\`CEREBRAS_API_KEY\\` |\n| DeepInfra | \\`DEEPINFRA_API_KEY\\` |\n| Groq | \\`GROQ_API_KEY\\` |\n| Novita AI | \\`NOVITA_API_KEY\\` |\n| OpenAI | \\`OPENAI_API_KEY\\` |\n| Anthropic | \\`ANTHROPIC_API_KEY\\` |\n| OpenRouter | \\`OPENROUTER_API_KEY\\` |\n| Baseten Model APIs | \\`BASETEN_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## User-Defined Providers\n\nCreate \\`agents/providers/<name>.ts\\` when a provider is compatible with an existing\nprovider package but needs its own API key, endpoint, icon, model list, pricing, or\nother provider behavior.\n\n\\`\\`\\`typescript\n// agents/providers/darkbloom.ts\nimport { defineProvider, providerEnv } from '@standardagents/builder';\nimport { openai } from '@standardagents/openai';\n\nexport default defineProvider({\n name: 'darkbloom',\n label: 'Darkbloom',\n baseProvider: openai,\n config: {\n apiKey: providerEnv('DARKBLOOM_API_KEY', { valueType: 'secret' }),\n baseUrl: providerEnv('DARKBLOOM_BASE_URL', {\n valueType: 'url',\n default: 'https://api.darkbloom.dev/v1',\n }),\n },\n});\n\\`\\`\\`\n\n\\`\\`\\`typescript\n// agents/models/darkbloom_chat.ts\nimport { defineModel } from '@standardagents/builder';\nimport darkbloom from '../providers/darkbloom';\n\nexport default defineModel({\n name: 'darkbloom_chat',\n provider: darkbloom,\n model: 'darkbloom-chat',\n});\n\\`\\`\\`\n\nProvider \\`overrides\\` can replace behavior such as \\`getModels\\`, \\`getIcon\\`,\n\\`getTools\\`, pricing/capability lookup, \\`generate\\`, or \\`stream\\`. Call \\`next()\\`\ninside an override to compose with the base provider; return your own value to\nreplace it.\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\nimport { defineModel } from '@standardagents/builder';\nimport { openrouter } from '@standardagents/openrouter';\n\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 attach provider-owned \\`usage.cost\\` values for request logs, but custom/private Cerebras models should still set \\`inputPrice\\` and \\`outputPrice\\`\n- **DeepInfra note:** the provider reads live pricing from \\`/v1/models\\` and preserves response-level \\`usage.estimated_cost\\`; custom catalog endpoints can be configured with the provider's \\`modelsUrl\\` slot\n- **Novita note:** the Novita provider reads live catalog pricing from \\`/openai/v1/models\\`, including cache-read prices when available, but custom/private Novita models should still set \\`inputPrice\\`, \\`outputPrice\\`, and \\`cachedPrice\\`\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 PROVIDERS_AGENTS_MD = `# Provider Definitions\n\nProvider definitions create named provider factories that wrap a base provider\npackage with connection config and optional method overrides.\n\nUse \\`defineProvider()\\` and export the result as the default export:\n\n\\`\\`\\`typescript\nimport { defineProvider, providerEnv, providerValue } from '@standardagents/builder';\nimport { openai } from '@standardagents/openai';\n\nexport default defineProvider({\n name: 'my_openai_compatible_provider',\n label: 'My OpenAI-compatible Provider',\n baseProvider: openai,\n config: {\n apiKey: providerEnv('MY_PROVIDER_API_KEY', {\n valueType: 'secret',\n required: true,\n description: 'Provider API key.',\n }),\n baseUrl: providerValue('https://api.example.com/v1'),\n },\n});\n\\`\\`\\`\n\nModels can then import the provider definition and use it like any other provider\nfactory:\n\n\\`\\`\\`typescript\nimport { defineModel } from '@standardagents/builder';\nimport myProvider from '../providers/my_openai_compatible_provider';\n\nexport default defineModel({\n name: 'custom_fast',\n provider: myProvider,\n model: 'gpt-4o-mini',\n});\n\\`\\`\\`\n\nProvider \\`overrides\\` can replace behavior such as \\`getModels\\`, \\`getIcon\\`,\n\\`getTools\\`, pricing/capability lookup, \\`generate\\`, or \\`stream\\`. Call \\`next()\\`\ninside an override to compose with the base provider; return your own value to\nreplace it.\n\nKeep credentials in secret env values. Do not hardcode API keys in provider\ndefinition files.\n\n## Error attribution\n\nWhen an override catches and rethrows an upstream failure, preserve structured\nattribution with \\`ProviderError\\` instead of putting the provider name only in\nthe message:\n\n\\`\\`\\`typescript\nimport { ProviderError } from '@standardagents/builder';\n\nthrow new ProviderError(message, 'server_error', status, retryAfter, {\n cause: error,\n origin: 'provider:my_openai_compatible_provider',\n upstream: 'example-backend',\n});\n\\`\\`\\`\n\n\\`origin\\` is machine-readable (\\`provider:<id>\\` for provider failures), while\n\\`upstream\\` names the actual backend when it differs from the adapter. Builder\nrequest logs retain these fields and render them separately from the human\nmessage. Do not make operators infer the failing layer from prose.\n`;\n\nexport const PROVIDERS_CLAUDE_MD = PROVIDERS_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 and injects its resolved value with a structured \\`{ type: 'env', property: 'HTTP_HOST' }\\` prompt part. 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\nThe sandboxed coding prompt includes \\`set_goal\\` (write the whole goal: a short \\`summary\\`, a \\`description\\` that is the user's objective in their own words captured verbatim, plus ordered steps) and \\`update_goal_step\\` (flip one step's status as you start/finish it), and should check work incrementally, checking steps off as it goes and finishing with a summary once every step is done. \\`coding_validate_typescript\\` is only an early signal; for real verification, call helper exports with \\`coding_run\\`, get public URLs for pages or endpoints, then probe those URLs from \\`coding_run\\` using \\`import { fetch } from \"fetch\"\\`. Side-effecting endpoint checks should use disposable data and clean up through the endpoint, storage, or file cleanup path when practical. The prompt also includes \\`fetch_url\\` for reading known external public http(s) pages; use the \\`coding_run\\` fetch bridge for custom methods, headers, request bodies, or thread endpoint checks.\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 // The same agent exposed under a task-specific tool name: \\`name\\` is what\n // the model calls; \\`agent\\` is the dual_ai agent that implements it.\n { name: 'summarize_report', agent: 'data_processor_agent', blocking: true },\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\\`subagent_create.arguments\\` is shaped by the prompt schema on the child side selected by \\`resumable.receives_messages\\`.\nAgentBuilder persists those initial arguments with the child thread, exposes them as \\`ThreadState.arguments\\` and prompt variables, and keeps them visible to both child sides for later resumptions.\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()\\`, \\`state.setStatus()\\`, or \\`state.stopSession({ result, notifyParent, status })\\`.\nSet top-level \\`parentCommunication: 'explicit'\\` on a NON-resumable subagent when its completion should not be auto-queued to the parent (so it never wakes the parent) — for background children that deliver results through another channel, e.g. the parent's thread KV. \\`resumable.parentCommunication\\` takes precedence when both are set.\nSet \\`hidden: true\\` to keep a subagent relationship declared and spawnable by runtime code (\\`state.invokeTool()\\`/\\`queueTool()\\` from hooks) while excluding its tool from every LLM request — the model can never call it (for infrastructure children like a background compaction agent).\nAdding an enabled child relationship automatically activates the child's\ndisclosed \\`parentHooks\\` on this parent. Disabled optional relationships do\nnot; hidden enabled relationships do. \\`name\\` is the relationship provenance\nand \\`agent ?? name\\` identifies the implementing child.\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| \\`primary\\` | \\`boolean\\` | No | Default true. Set false on internal handoff-target agents (e.g. domain-gearbox variants) to hide them from top-level UI agent lists; they stay fully addressable for handoffs and thread resumption |\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| \\`parentHooks\\` | \\`ParentHookRequirement[]\\` | No | Hooks an exposed dual-AI child automatically contributes to each direct parent |\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\nAn exposed \\`dual_ai\\` child can declare required parent integration hooks:\n\n\\`\\`\\`typescript\nparentHooks: [{\n hook: 'sync_gmail_context',\n reason: 'Makes synchronized Gmail context available to the coordinator.',\n stage: 'before_parent', // default: after_parent\n}],\n\\`\\`\\`\n\nInstalling the package is inert. Adding this child to a prompt activates the\nhook automatically on that direct parent and composition UIs can show the\n\\`reason\\` first. Disabled optional relationships contribute nothing; enabled\nhidden relationships still contribute hooks. Required hooks run with the\nparent's \\`ThreadState\\`, load from the child's package namespace, and fail\ncomposition closed if missing. User-scope hooks cannot be listed.\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## Icons\n\nGive an agent a custom icon with the \\`icon\\` property: a full URL, a data URI,\nor a site-relative path served from your project's \\`public/\\` directory —\n\\`icon: '/icons/support.svg'\\` expects the file at \\`public/icons/support.svg\\`.\nThe file is served in dev and deployed with your project's assets. Agents\nwithout an icon (or whose icon fails to load) render a generated identicon,\nand the dashboard warns when a site-relative icon path has no matching file.\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 progressArgument?: string, // Arg holding a short progress label, e.g. \"writing index.html\"\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 const creationArgs = state.arguments; // Invocation or subagent creation args\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 // The thread's user profile (identity only, never credentials) — for\n // per-user personalization or entitlement checks. Null when user-less.\n const user = await state.user();\n\n // Instance-GLOBAL Agent Skills library (agentskills.io SKILL.md format).\n // Skills install once and are visible to every thread; load a skill's body\n // only when it's applicable (progressive disclosure).\n const skills = await state.skills.list();\n const skill = await state.skills.get('pdf-processing');\n const script = await state.skills.readFile('pdf-processing', 'scripts/extract.py');\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### Optional Runtime Streams\n\nSome runtimes expose live, authorized byte streams through\n\\`state.runtimeStreams\\`. Always feature-detect the optional surface. The\nfollowing neutral example streams media to a workstation-hosted transcoder,\nhalf-closes the writable side, reads the encoded result, and cleans up:\n\n\\`\\`\\`typescript\nconst runtimeStreams = state.runtimeStreams;\nif (!runtimeStreams) {\n return { status: 'error', error: 'This runtime has no workstation streams.' };\n}\n\nconst opened = await runtimeStreams.open({\n capability: 'workstation_transcoder',\n metadata: { inputFormat: 'wav', outputFormat: 'opus' },\n timeoutMs: 10_000,\n});\nif (!opened.ok) {\n return { status: 'error', error: opened.error, error_code: opened.code };\n}\n\ntry {\n const writer = opened.stream.writable.getWriter();\n try {\n await writer.write(sourceMedia);\n await writer.close();\n } finally {\n writer.releaseLock();\n }\n\n const reader = opened.stream.readable.getReader();\n const encoded: Uint8Array[] = [];\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n encoded.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n const closed = await opened.stream.closed;\n if (!closed.ok) throw new Error(closed.error ?? 'Transcoding failed.');\n return { status: 'success', result: \\`Received \\${encoded.length} chunks.\\` };\n} finally {\n opened.stream.close();\n}\n\\`\\`\\`\n\n\\`readable\\` carries host-to-runtime bytes; \\`writable\\` carries\nruntime-to-host bytes. Streams are live and non-durable. \\`close()\\` is\nidempotent, and the \\`closed\\` promise settles once.\n\nSandboxed coding code must not use ambient network globals. For HTTP inside \\`coding_run\\`, import \\`{ fetch }\\` from \\`\"fetch\"\\`; the bridge supports \\`fetch(url, init)\\` with methods, headers, and bodies, and returns a Response-like object with \\`text()\\`, \\`json()\\`, \\`arrayBuffer()\\`, and \\`headers.get()\\`. The sandboxed coding prompt includes \\`fetch_url\\` for reading known external public http(s) pages as Markdown. Use the \\`coding_run\\` fetch bridge instead for custom methods, headers, request bodies, or checks against thread public file/API endpoint URLs returned by \\`get_public_url\\`.\n\nSandboxed coding agents should verify runtime behavior as they work. \\`coding_validate_typescript\\` is useful but incomplete; call helper exports with \\`coding_run\\`, probe pages and endpoints with \\`coding_run\\` plus the fetch bridge, inspect status/body, and clean up disposable side-effecting test data when practical.\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## Stopping Sessions\n\n\\`state.execution.stop()\\` stops the current execution loop. To terminally end the active agent session, including blocking subagent runs that expect a session boundary, use \\`state.stopSession()\\`:\n\n\\`\\`\\`typescript\nawait state.stopSession({\n result: 'Waiting for clarification',\n notifyParent: 'Please clarify the request',\n status: 'waiting for clarification',\n});\n\\`\\`\\`\n\n\\`notifyParent\\` queues a silent message to the parent when one exists; \\`status\\` is ignored without a parent registry entry. Omit \\`notifyParent\\` and \\`status\\` when stopping should not send a parent message or update child status.\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 before the history snapshot |\n| \\`filter_messages\\` | \\`(state: ThreadState, messages: Message[]) => Message[]\\` | Build the request context from one stable history snapshot per model request |\n| \\`prefilter_llm_history\\` | \\`(state: ThreadState, messages: LLMMessage[]) => LLMMessage[]\\` | Modify transformed provider messages before dispatch |\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| \\`user_client_attached\\` | \\`(user: UserState, client: { id, kind? }) => void\\` | User-scope: a socket attached to the user event stream |\n| \\`user_client_detached\\` | \\`(user: UserState, client: { id, kind? }) => void\\` | User-scope: a socket detached |\n| \\`user_value_changed\\` | \\`(user: UserState, key: string) => void\\` | User-scope: a durable user value changed (any writer) |\n| \\`tool_call_started\\` | \\`(state: ThreadState, toolCall: HookToolCall, progress?: string) => void\\` | Observe a tool call when it starts streaming (before it runs) |\n| \\`tool_call_done\\` | \\`(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => void\\` | Observe a tool call after it finishes (success or failure) |\n\nUser-scope hooks receive \\`UserState\\`. All thread hooks receive \\`ThreadState\\`\nfirst and \\`HookExecutionContext\\` last. The context source is prompt, agent, or\nchild provenance; child provenance includes \\`relationshipName\\`, resolved\n\\`agentName\\`, and optional package signature.\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- Enabled direct children contribute their declared \\`parentHooks\\`\n- Ordering is child \\`before_parent\\`, prompt-or-agent base, child \\`after_parent\\`\n- Child requirements load from the child's package and run on the parent state\n- Disabled optional children contribute nothing; hidden enabled children still do\n- Installing alone is inert; adding the child relationship activates its disclosed hooks\n- Hooks are filtered by type at runtime\n- At-rest operations have no active prompt and use agent-level hooks\n\n## History and the Request Context\n\nEach provider request runs \\`after_system_message\\`, takes one stable persisted-history\nsnapshot, runs \\`filter_messages\\` exactly once, transforms the result, and then runs\n\\`prefilter_llm_history\\`. These request-context hooks do not replace\n\\`state.execution.messageHistory\\`. Messages injected by \\`after_system_message\\` enter\nthe current snapshot. Messages injected by either request-context hook enter the\nfollowing snapshot. Silent messages remain eligible unless a request-context hook removes\nthem.\n\n## Create-Message Lifecycle\n\n\\`before_create_message\\` and \\`after_create_message\\` run for runtime insertion\npaths, including \\`injectMessage()\\` (active and at rest), agent-handoff user\nmessages, and generated-asset path messages. A \\`before_create_message\\` hook\nthat throws during \\`injectMessage()\\` rejects the injection and nothing is\npersisted. Other runtime insertions log the failure and keep the last good\nmessage.\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> Warning: In \\`after_tool_call_success\\` / \\`after_tool_call_failure\\`,\n> returning \\`null\\` does NOT mean \"keep the original result\" — it tells the\n> runtime to **REMOVE the tool call from history and skip storing the result**\n> (the assistant tool-call message is deleted). A side-effect-only hook MUST\n> return the \\`result\\` it received.\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 result; // ALWAYS return the result — null would DELETE the tool call\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 result; // keep the original error — null would DELETE the tool call\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 the — possibly modified — result; \\`null\\` REMOVES the tool call from history)\n- \\`after_tool_call_failure\\` (return the — possibly modified — result; \\`null\\` REMOVES the tool call from history)\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## Blocking a step from a hook\n\nHook failures are normally non-fatal (logged and ignored). A\n\\`prefilter_llm_history\\` hook may deliberately BLOCK the step — the session\nstops with a visible assistant message BEFORE any LLM request — by throwing an\nerror that carries \\`block: true\\`:\n\n\\`\\`\\`typescript\nthrow Object.assign(new Error('Thread limit reached'), { block: true });\n\\`\\`\\`\n\nUse this for entitlement/policy gates (e.g. per-user concurrency leases).\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, \\`arguments\\`, file system, \\`runCode\\`, etc. |\n| \\`params\\` | \\`Record<string, string>\\` | Route parameters captured from \\`[name]\\` and \\`[*]\\` path segments |\n| \\`auth\\` | \\`ThreadEndpointAuth\\` | The request's authentication context: \\`caller\\` (the authenticated identity, or \\`null\\` for anonymous requests) and \\`threadAccess\\` (whether the caller passes the runtime's access policy for this thread) |\n\n## Access Levels\n\nEndpoints are \\`authenticated\\` by default: the runtime authenticates the\nrequest and enforces thread access before your handler runs, and \\`auth.caller\\`\nis always present. Declare \\`{ access: 'public' }\\` to accept anonymous\nrequests — the runtime still resolves \\`auth.caller\\` when credentials are\npresented, so one endpoint can serve both audiences:\n\n\\`\\`\\`typescript\n// agents/api/shared/[*].ts -> GET /api/threads/:threadId/shared/<path>\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(\n async (req, state, params, auth) => {\n if (!auth.threadAccess && !isShared(params['*'])) {\n return new Response(null, { status: 404 });\n }\n // serve the file...\n },\n { access: 'public' }\n);\n\\`\\`\\`\n\nA public endpoint is reachable by anyone who has the URL — treat it like an\ninternet-facing route: validate the path, reject early, and never echo\nprivate state to anonymous callers.\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. \\`state.emit(event, data)\\` broadcasts a custom WebSocket event from endpoints as well as active executions; use it as an invalidation hint after persisting durable state, not as a replacement for reconnect recovery.\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 console.log('Arguments:', state.arguments);\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 state.emit('export_count_changed', { 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 // Move or rename files and directories (does not overwrite an existing destination)\n await state.moveFile('/data/file.txt', '/archive/file.txt');\n await state.renameFile('/output/result.json', 'final.json');\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","export const USERS_AGENTS_MD = `# User Endpoints\n\nDefine user-scoped API endpoints — HTTP handlers that operate on a USER\n(durable cross-thread state) rather than a single thread. They execute inside\nthe per-user hub with a serialization guarantee: at most one user endpoint\nruns at a time per user, and each observes all prior completed writes. That\nmakes this directory the home for quotas, leases, counters, registries, and\nany other user-level logic where lost updates matter.\n\nSpecification: https://standardagentspec.com/0.1.0/specification/users\n\n## File-Based Routing\n\n| File Pattern | HTTP Method | Route |\n|--------------|-------------|-------|\n| \\`name.ts\\` | GET | \\`/api/users/me/name\\` |\n| \\`name.post.ts\\` | POST | \\`/api/users/me/name\\` |\n| \\`pkg/name.post.ts\\` | POST | \\`/api/users/me/pkg/name\\` |\n| \\`items/[id].ts\\` | GET | \\`/api/users/me/items/:id\\` |\n| \\`files/[*].ts\\` | GET | \\`/api/users/me/files/*\\` |\n\nRouting rules match thread endpoints (method suffixes, nested directories,\n\\`[param]\\`, \\`[*]\\`). Root your endpoints in a directory named for your\npackage so installed packages coexist. Administrators can address any user's\nendpoints at \\`/api/users/:id/...\\`.\n\n## Basic Example\n\n\\`\\`\\`typescript\n// agents/users/quota.post.ts → POST /api/users/me/quota\nimport { defineUserEndpoint } from '@standardagents/spec';\n\nexport default defineUserEndpoint(async (req, user, params) => {\n const used = (await user.getValue<number>('quota.used')) ?? 0;\n const limit = Number(await user.getValue('quota.limit')) || 0;\n const { amount } = await req.json();\n if (used + amount > limit) {\n return Response.json({ ok: false, used, limit }, { status: 429 });\n }\n await user.setValue('quota.used', used + amount);\n user.emit('quota_changed', { used: used + amount, limit });\n return Response.json({ ok: true });\n});\n\\`\\`\\`\n\n## UserState\n\nHandlers receive a \\`UserState\\`: \\`userId\\`, \\`identity()\\`, durable values\n(\\`getValue\\`/\\`setValue\\`/\\`listValues\\`), \\`env()\\`, \\`emit()\\` (broadcast on\nthe user event stream at \\`/api/users/me/stream\\`), \\`listThreads()\\`,\n\\`fetch(grant, url, init)\\` (privileged fetch through a credential grant), and\n\\`thread(threadId)\\` (raise one of the user's threads at rest).\n\n## Caller Channels\n\nHandlers can distinguish who invoked them via the\n\\`X-Standard-Agents-Caller\\` request header, which the runtime stamps and\nun-forgeably overwrites on public routes: \\`user\\` (the user's own HTTP\nrequest), \\`admin\\` (administrative addressing), or \\`thread\\` (a\nruntime-internal \\`state.user().call()\\`). Gate enforcement-critical\nmutations (quotas, leases) on the \\`thread\\` channel.\n\n## Reaching the User Scope from Threads\n\nTools, hooks, and thread endpoints call user endpoints through the thread's\nuser handle:\n\n\\`\\`\\`typescript\nconst user = await state.user();\nawait user?.call('quota', { amount: 1 }); // serialized, atomic\n\\`\\`\\`\n\n## Live Events\n\nClients subscribe to \\`GET /api/users/me/stream\\` (WebSocket) and receive every\n\\`emit()\\` as \\`{ \"event\": string, \"data\": unknown }\\`. The stream is live-only:\nre-read durable state on connect and reconnect.\n`;\n\nexport const USERS_CLAUDE_MD = USERS_AGENTS_MD;\n","import {\n AGENT_DEFINITIONS_AGENTS_MD,\n API_AGENTS_MD,\n USERS_AGENTS_MD,\n HOOKS_AGENTS_MD,\n MODELS_AGENTS_MD,\n PROVIDERS_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 USERS_AGENTS_MD,\n USERS_AGENTS_MD as USERS_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 PROVIDERS_AGENTS_MD,\n PROVIDERS_AGENTS_MD as PROVIDERS_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 * Include a working `vite build` script in the rendered package manifest.\n * Only the platform build runner should set this. Local manifests get a\n * guard script instead, because customer projects build and deploy on the\n * Standard Agents platform after a git push — never on the user's machine.\n */\n includeBuildScript?: boolean\n}\n\nexport const FIRST_PARTY_PROVIDER_PACKAGES = [\n '@standardagents/anthropic',\n '@standardagents/cloudflare',\n '@standardagents/cerebras',\n '@standardagents/deepinfra',\n '@standardagents/google',\n '@standardagents/groq',\n '@standardagents/novita',\n '@standardagents/openai',\n '@standardagents/openrouter',\n '@standardagents/xai',\n] as const\n\n/**\n * Dependency packages whose install scripts the generated project approves.\n * pnpm 10 blocks dependency build scripts by default and, under CI (the\n * platform build runner sets CI=true), fails the install outright with\n * ERR_PNPM_IGNORED_BUILDS. These are the script-running packages in the\n * default dependency tree (native binaries and codegen) that the project\n * needs for installs and builds to work.\n *\n * The same list feeds THREE approval surfaces: pnpm's\n * package.json#pnpm.onlyBuiltDependencies (pre-11), pnpm-workspace.yaml's\n * onlyBuiltDependencies/allowBuilds (11+), and npm 12's\n * package.json#allowScripts — npm 12 silently skips unapproved dependency\n * install scripts, which leaves a fresh project without workerd/esbuild\n * binaries.\n */\nexport const APPROVED_DEPENDENCY_BUILD_SCRIPTS = [\n '@google/genai',\n '@openrouter/sdk',\n 'esbuild',\n 'protobufjs',\n 'sharp',\n 'workerd',\n] as const\n\n// Pin first-party @standardagents/* packages to a controlled major range\n// rather than \"latest\". Floating on \"latest\" let the installed builder drift\n// out of sync with the generated provider list (e.g. builder shipped the\n// anthropic provider while a stale template omitted it), breaking the build.\n// Caret on a 0.x version accepts patch releases automatically but holds the\n// minor, so only an intentional \"major\" bump of these packages re-challenges\n// the pin. Bump these together when the platform adopts a new release line.\nexport const DEFAULT_TEMPLATE_VERSIONS: TemplateVersions = {\n standardAgents: '^0.35.5',\n sip: '^1.0.1',\n vite: 'latest',\n typescript: 'latest',\n zod: 'latest',\n}\n\nexport const AGENTBUILDER_TEMPLATE_VERSION = '0.40.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 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: options.includeBuildScript\n ? 'vite build'\n : \"echo 'Standard Agents projects build and deploy on the platform. Push your commit (git push or agents deploy) to trigger a build.' && exit 1\",\n typecheck: 'tsc --noEmit',\n },\n dependencies,\n devDependencies: {\n typescript: versions.typescript,\n vite: versions.vite,\n },\n pnpm: {\n onlyBuiltDependencies: [...APPROVED_DEPENDENCY_BUILD_SCRIPTS],\n },\n // npm 12 skips unapproved install scripts (name-only entries approve any\n // version — these dependencies float). Ignored by npm <12 and pnpm.\n allowScripts: Object.fromEntries(\n APPROVED_DEPENDENCY_BUILD_SCRIPTS.map((name) => [name, true]),\n ),\n }, null, 2)}\\n`\n}\n\n/**\n * pnpm 11 no longer reads the package.json#pnpm field — install-script\n * approvals live in pnpm-workspace.yaml. The manifest keeps the legacy\n * pnpm.onlyBuiltDependencies for older pnpm; this file is the pnpm 11+ home.\n * Without an approval, esbuild/workerd never run their install scripts and\n * `vite build` fails on the platform build runner.\n */\nexport function renderPnpmWorkspaceYaml(): string {\n const listEntries = APPROVED_DEPENDENCY_BUILD_SCRIPTS\n .map((name) => ` - \"${name}\"`)\n .join('\\n')\n const mapEntries = APPROVED_DEPENDENCY_BUILD_SCRIPTS\n .map((name) => ` \"${name}\": true`)\n .join('\\n')\n // pnpm 10.4+ reads onlyBuiltDependencies; v11 replaced it with the\n // allowBuilds map. Each version ignores the other's key, so ship both.\n // pnpm 11's default minimum-release-age policy rejects same-day releases;\n // Standard Agents ships first-party packages the day they're cut, so the\n // scope is exempted (third-party packages keep the protection).\n return `onlyBuiltDependencies:\\n${listEntries}\\nallowBuilds:\\n${mapEntries}\\nminimumReleaseAgeExclude:\\n - \"@standardagents/*\"\\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 // package.json AND the lockfile are committed: the project owns its\n // @standardagents/* versions and the platform build installs them frozen for\n // byte-exact, reproducible deploys (the build runner uses whichever package\n // manager the committed lockfile implies). Only secrets, dependencies, and\n // local build/dev state are ignored.\n return `node_modules\ndist\n.agents\n.wrangler\n.env\n.dev.vars\n.agentbuilder-dev.log\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=\nDEEPINFRA_API_KEY=\nGOOGLE_API_KEY=\nGROQ_API_KEY=\nNOVITA_API_KEY=\nOPENAI_API_KEY=\nOPENROUTER_API_KEY=\nANTHROPIC_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 // The project owns its @standardagents/* versions: the committed manifest is\n // the source of truth the platform build honors (what you test locally is\n // what deploys). It ships a guard `build` script that refuses to build\n // off-platform; the build runner swaps in the real `vite build` at build\n // time. Never set includeBuildScript here — a working local build would let\n // a half-configured checkout deploy from the wrong place.\n file('package.json', renderPackageJson({ ...options, includeBuildScript: false }), 'Add package manifest'),\n // Committed alongside package.json so a freshly cloned repo ignores\n // node_modules, lockfiles, secrets, and local build state without depending\n // on the CLI to generate a .gitignore after clone.\n file('.gitignore', renderGitignore(), 'Add gitignore'),\n // pnpm 11 reads install-script approvals from pnpm-workspace.yaml (the\n // package.json#pnpm field is ignored since v11); older pnpm reads the\n // manifest — both are committed so every runner generation builds.\n file('pnpm-workspace.yaml', renderPnpmWorkspaceYaml(), 'Add pnpm settings'),\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/providers/AGENTS.md', PROVIDERS_AGENTS_MD, 'Add provider docs'),\n symlink('agents/providers/CLAUDE.md', 'AGENTS.md', 'Add Claude provider 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 file('agents/users/AGENTS.md', USERS_AGENTS_MD, 'Add user endpoint docs'),\n symlink('agents/users/CLAUDE.md', 'AGENTS.md', 'Add Claude user endpoint 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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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gB;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,8BAA8B,qBAAqB,mBAAmB;AAAA,IAC3E,QAAQ,8BAA8B,aAAa,kCAAkC;AAAA,IACrF,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,IAC1E,KAAK,0BAA0B,iBAAiB,wBAAwB;AAAA,IACxE,QAAQ,0BAA0B,aAAa,uCAAuC;AAAA,EACxF;AAEA,MAAI,QAAQ,yBAAyB;AACnC,UAAM,KAAK,KAAK,iCAAiC,uBAAuB,OAAO,GAAG,uCAAuC,CAAC;AAAA,EAC5H;AAEA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/docs/root.ts","../src/docs/models.ts","../src/docs/providers.ts","../src/docs/prompts.ts","../src/docs/agents.ts","../src/docs/handlers.ts","../src/docs/tools.ts","../src/docs/hooks.ts","../src/docs/api.ts","../src/docs/users.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. An agent has exactly two sides; each side is backed by a human (\\`{ human: true }\\`), a prompt (\\`{ prompt: 'name' }\\`), or a handler (\\`{ handler: 'name' }\\` — deterministic code from \\`agents/handlers/\\`).\n**Threads** are individual conversation instances with persistent storage.\n\n## Packability and Runtime Portability\n\nTreat an agent project as an installable Standard Agent package, not as a\nprivileged extension of one runtime. Everything required for the declared\nagents to execute must use capabilities defined by the Standard Agent\nSpecification and exported with the package.\n\nDo not make required behavior depend on private Durable Object methods,\nimplementation-specific storage schemas or bindings, undocumented HTTP or\nWebSocket events, product sidecars that replace runtime behavior, or\nThreadState._notPackableRuntimeContext. Client-side state may be an\noptimistic cache, but it must not become the only source of truth for agent\nsemantics.\n\nIf the specification lacks a required primitive, define the runtime-neutral\ncapability in @standardagents/spec, document it in the public specification,\nimplement it generically in the runtime, and add conformance coverage before\nthe agent relies on it. Authentication, billing, deployment, and branded UI\nservices may remain external as long as they are not required for the packed\nagent's core execution semantics.\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├── handlers/ # Handler definitions (defineHandler)\n│ ├── AGENTS.md\n│ └── CLAUDE.md -> AGENTS.md\n├── models/ # Model configurations (defineModel)\n│ ├── AGENTS.md\n│ └── CLAUDE.md -> AGENTS.md\n├── providers/ # Provider definitions (defineProvider)\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\nFor remote local development, opt exact hostnames into the authoring boundary:\n\n\\`\\`\\`typescript\nbuilder({ trustedDevHosts: ['macbookserver.tail13bd39.ts.net'] })\n\\`\\`\\`\n\nThis never changes hosted behavior. Adding a hostname grants anyone who can\nreach the dev server through that name the ability to attempt authoring access;\nsame-origin and normal authoring credential checks still apply. Wildcards,\nschemes, ports, and paths are rejected.\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[]; // Child instance registry\n terminated: number | null; // Soft-termination timestamp\n arguments: Record<string, unknown>; // Invocation or subagent creation args\n context: Record<string, unknown>; // Current-execution scratch data\n runtimeStreams?: RuntimeStreams; // Optional live execution-host byte streams\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 emit(event, data): void; // Broadcast a custom event to connected thread clients\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>; // Queue a silent message to the parent when one exists\n setStatus(status): Promise<void>; // Update this child in the parent registry; no-op without a parent\n stopSession(options?): Promise<void>; // Terminally stop the current agent session\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\\`state.arguments\\` is read-only thread invocation data. Resumable \\`subagent_create.arguments\\` persists with the child thread, is visible to both child sides, and is also available as prompt variables. Use \\`state.context\\` only for mutable scratch data during the current execution; it is not durable storage.\n\n\\`state.runtimeStreams\\` is optional. Feature-detect it before opening a live\nbyte stream. Capability names and metadata are runtime-defined; streams never\npark or survive an execution-host disconnect. See the tools guide for a full\nfeature-detection, write, read, and cleanup example.\n\n\\`state.emit(event, data)\\` works from tools, hooks, and thread endpoints. In\nan endpoint it broadcasts immediately even though there is no active\nexecution, which is useful for invalidating client snapshots after a durable\n\\`setValue()\\`. Events are not durable; clients must re-read state after\nreconnecting.\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\nA subagent is any agent composed as a child of another agent. Relationships are declared in the \\`subagents\\` array of a prompt- or handler-backed agent side (never inside a prompt's \\`tools\\` array):\n\n- Each subagent runs in its own thread (\\`DurableThread\\`)\n- Parent/child linkage is tracked in thread metadata; instances are visible in \\`state.children\\`\n- The relationship's owning side is where child traffic lands; parent→child traffic enters in the child's side B perspective (\\`role: 'user'\\`), so the child's side A acts on it\n- For a prompt-backed owning side, the runtime injects the lifecycle tools \\`subagents\\`, \\`subagent_create\\`, and \\`subagent_message\\`; handler-backed sides reach children through \\`ThreadState\\` directly\n- \\`subagent_create.arguments\\` is validated from the receiving child's side A prompt schema and persists as \\`ThreadState.arguments\\` plus prompt variables for the life of the child thread\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()\\`; use \\`state.stopSession({ result, notifyParent, status })\\` when a tool should also terminally end the child session\n- Persistence is universal: a child's session ending never terminates its thread. The same reference remains addressable for later \\`subagent_message\\` calls; only explicit \\`state.terminate()\\` tears the thread down.\n\nAccess in tools:\n\\`\\`\\`typescript\nexport default defineTool('...', schema, async (state, args) => {\n const threadId = state.threadId;\n const creationArgs = state.arguments;\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| \\`defineProvider()\\` | Custom provider endpoints and overrides | \\`agents/providers/\\` |\n| \\`definePrompt()\\` | System instructions + tools | \\`agents/prompts/\\` |\n| \\`defineHandler()\\` | Deterministic side turns | \\`agents/handlers/\\` |\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 cost safety\n\nAgentBuilder bounds each Durable Object alarm invocation to 1,000,000 SQLite\nrows read and 10,000 rows written. A breach persistently quarantines that one\nobject, clears its alarm, preserves all storage, and requires an explicit\nresume. Routine alarm rows are deleted when completed; effect history remains\navailable with bounded retention. Deployments integrated with Brolly configure\n\\`BROLLY_CONTROL_PUBLIC_KEY_JWK\\` and \\`BROLLY_ACCOUNT_ID\\`; the built-in signed\n\\`POST /api/auth/brolly-control\\` route can then quarantine an exact object ID.\n\nDo not expose the Brolly private signing key to the AgentBuilder Worker. Do not\ndisable the retention sweeper except as a temporary rollback while diagnosing\na deployment.\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/flowstate)\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\\` | \\`ProviderFactory\\` | Yes | Imported provider factory such as \\`openrouter\\`, \\`openai\\`, or a local provider from \\`agents/providers\\` |\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';\nimport { openrouter } from '@standardagents/openrouter';\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 | \\`nvidia/nemotron-3-ultra-550b-a55b\\` | Frontier open reasoning and orchestration, 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| Cloudflare Workers AI | \\`CLOUDFLARE_API_TOKEN\\` + \\`CLOUDFLARE_ACCOUNT_ID\\` |\n| Cerebras | \\`CEREBRAS_API_KEY\\` |\n| DeepInfra | \\`DEEPINFRA_API_KEY\\` |\n| Groq | \\`GROQ_API_KEY\\` |\n| Novita AI | \\`NOVITA_API_KEY\\` |\n| OpenAI | \\`OPENAI_API_KEY\\` |\n| Anthropic | \\`ANTHROPIC_API_KEY\\` |\n| OpenRouter | \\`OPENROUTER_API_KEY\\` |\n| Baseten Model APIs | \\`BASETEN_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## User-Defined Providers\n\nCreate \\`agents/providers/<name>.ts\\` when a provider is compatible with an existing\nprovider package but needs its own API key, endpoint, icon, model list, pricing, or\nother provider behavior.\n\n\\`\\`\\`typescript\n// agents/providers/darkbloom.ts\nimport { defineProvider, providerEnv } from '@standardagents/spec';\nimport { openai } from '@standardagents/openai';\n\nexport default defineProvider({\n name: 'darkbloom',\n label: 'Darkbloom',\n baseProvider: openai,\n config: {\n apiKey: providerEnv('DARKBLOOM_API_KEY', { valueType: 'secret' }),\n baseUrl: providerEnv('DARKBLOOM_BASE_URL', {\n valueType: 'url',\n default: 'https://api.darkbloom.dev/v1',\n }),\n },\n});\n\\`\\`\\`\n\n\\`\\`\\`typescript\n// agents/models/darkbloom_chat.ts\nimport { defineModel } from '@standardagents/builder';\nimport darkbloom from '../providers/darkbloom';\n\nexport default defineModel({\n name: 'darkbloom_chat',\n provider: darkbloom,\n model: 'darkbloom-chat',\n});\n\\`\\`\\`\n\nProvider \\`overrides\\` can replace behavior such as \\`getModels\\`, \\`getIcon\\`,\n\\`getTools\\`, pricing/capability lookup, \\`generate\\`, or \\`stream\\`. Call \\`next()\\`\ninside an override to compose with the base provider; return your own value to\nreplace it.\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\nimport { defineModel } from '@standardagents/builder';\nimport { openrouter } from '@standardagents/openrouter';\n\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 attach provider-owned \\`usage.cost\\` values for request logs, but custom/private Cerebras models should still set \\`inputPrice\\` and \\`outputPrice\\`\n- **DeepInfra note:** the provider reads live pricing from \\`/v1/models\\` and preserves response-level \\`usage.estimated_cost\\`; custom catalog endpoints can be configured with the provider's \\`modelsUrl\\` slot\n- **Novita note:** the Novita provider reads live catalog pricing from \\`/openai/v1/models\\`, including cache-read prices when available, but custom/private Novita models should still set \\`inputPrice\\`, \\`outputPrice\\`, and \\`cachedPrice\\`\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 PROVIDERS_AGENTS_MD = `# Provider Definitions\n\nProvider definitions create named provider factories that wrap a base provider\npackage with connection config and optional method overrides.\n\nUse \\`defineProvider()\\` and export the result as the default export:\n\n\\`\\`\\`typescript\nimport { defineProvider, providerEnv, providerValue } from '@standardagents/spec';\nimport { openai } from '@standardagents/openai';\n\nexport default defineProvider({\n name: 'my_openai_compatible_provider',\n label: 'My OpenAI-compatible Provider',\n baseProvider: openai,\n config: {\n apiKey: providerEnv('MY_PROVIDER_API_KEY', {\n valueType: 'secret',\n required: true,\n description: 'Provider API key.',\n }),\n baseUrl: providerValue('https://api.example.com/v1'),\n },\n});\n\\`\\`\\`\n\nModels can then import the provider definition and use it like any other provider\nfactory:\n\n\\`\\`\\`typescript\nimport { defineModel } from '@standardagents/builder';\nimport myProvider from '../providers/my_openai_compatible_provider';\n\nexport default defineModel({\n name: 'custom_fast',\n provider: myProvider,\n model: 'gpt-4o-mini',\n});\n\\`\\`\\`\n\nProvider \\`overrides\\` can replace behavior such as \\`getModels\\`, \\`getIcon\\`,\n\\`getTools\\`, pricing/capability lookup, \\`generate\\`, or \\`stream\\`. Call \\`next()\\`\ninside an override to compose with the base provider; return your own value to\nreplace it.\n\nKeep credentials in secret env values. Do not hardcode API keys in provider\ndefinition files.\n\n## Error attribution\n\nWhen an override catches and rethrows an upstream failure, preserve structured\nattribution with \\`ProviderError\\` instead of putting the provider name only in\nthe message:\n\n\\`\\`\\`typescript\nimport { ProviderError } from '@standardagents/builder';\n\nthrow new ProviderError(message, 'server_error', status, retryAfter, {\n cause: error,\n origin: 'provider:my_openai_compatible_provider',\n upstream: 'example-backend',\n});\n\\`\\`\\`\n\n\\`origin\\` is machine-readable (\\`provider:<id>\\` for provider failures), while\n\\`upstream\\` names the actual backend when it differs from the adapter. Builder\nrequest logs retain these fields and render them separately from the human\nmessage. Do not make operators infer the failing layer from prose.\n`;\n\nexport const PROVIDERS_CLAUDE_MD = PROVIDERS_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)[]\\` | No | Available tools: tool names, sub-prompt names, provider tools, and exposed agent names for handoffs. Subagent relationships never appear here — they are declared on the agent side's \\`subagents\\` array |\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 and injects its resolved value with a structured \\`{ type: 'env', property: 'HTTP_HOST' }\\` prompt part. 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\nThe sandboxed coding prompt includes \\`set_goal\\` (write the whole goal: a short \\`summary\\`, a \\`description\\` that is the user's objective in their own words captured verbatim, plus ordered steps) and \\`update_goal_step\\` (flip one step's status as you start/finish it), and should check work incrementally, checking steps off as it goes and finishing with a summary once every step is done. \\`coding_validate_typescript\\` is only an early signal; for real verification, call helper exports with \\`coding_run\\`, get public URLs for pages or endpoints, then probe those URLs from \\`coding_run\\` using \\`import { fetch } from \"fetch\"\\`. Side-effecting endpoint checks should use disposable data and clean up through the endpoint, storage, or file cleanup path when practical. The prompt also includes \\`fetch_url\\` for reading known external public http(s) pages; use the \\`coding_run\\` fetch bridge for custom methods, headers, request bodies, or thread endpoint checks.\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### Subagents Come From the Side, Not the Tools Array\n\nComposition into a child thread is not a prompt-tools concern. A subagent relationship is part of the agent's structure: it is declared in the \\`subagents\\` array of the agent side this prompt backs, never inside the prompt's \\`tools\\` array (a \\`tools\\` entry attempting to configure a subagent relationship is a definition-time error). The side's declaration is the grant:\n\n\\`\\`\\`typescript\n// agents/agents/assistant_agent.ts\nsideA: {\n prompt: 'coordinator',\n subagents: [\n { agent: 'calendar_agent', as: 'work_calendar', scopedEnv: ['WORK_CAL_ID'] },\n { agent: 'calendar_agent', as: 'personal_calendar', scopedEnv: ['PERSONAL_CAL_ID'] },\n { agent: 'research_agent', blocking: true, maxInstances: 1 },\n { agent: 'compaction_agent', hidden: true },\n { agent: 'browser_agent', optional: 'ENABLE_BROWSER_AGENT' },\n ],\n},\n\\`\\`\\`\n\nFor a prompt-backed side with non-hidden relationships, the runtime automatically injects three lifecycle tools scoped to that side's declarations:\n\n- \\`subagents\\` — pull-based visibility: returns the registry snapshot (reference, relationship name, agent name, status, initial arguments, creation time). Call it before \\`subagent_create\\` so existing instances are reused rather than duplicated.\n- \\`subagent_create\\` — creates (or continues) an instance. Its \\`agent\\` argument enumerates the side's enabled relationship *names* (\\`as\\`, defaulting to \\`agent\\`), never internal agent identifiers. It requires a non-empty \\`name\\` for the spawned instance; AgentBuilder stores that as a \\`name:<value>\\` thread tag for human-friendly labels.\n- \\`subagent_message\\` — queues a message to an existing instance by reference.\n\nThese three names are reserved; a relationship \\`as\\` that collides with them (or with any other tool name) is a definition-time error.\n\n\\`subagent_create.arguments\\` is shaped by the \\`requiredSchema\\` of the receiving child's side A prompt (parent traffic enters the child in the side B perspective, \\`role: 'user'\\`, so side A acts on it exactly as for an external caller). AgentBuilder validates and persists those arguments for the life of the child thread, exposes them as \\`ThreadState.arguments\\` and prompt variables to **both** child sides, and rehydrates them on every later activation. Missing required arguments fail creation with a structured \\`subagent_arguments_required\\` error.\n\nPersistence is universal: every child instance is a persistent thread. Session end never terminates a child — a later \\`subagent_message\\` starts a new session with history intact; only explicit \\`state.terminate()\\` destroys an instance. \\`blocking: true\\` makes \\`subagent_create\\` await the child session's close and return its result; combined with \\`maxInstances: 1\\` and an existing instance it behaves as create-or-continue.\n\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\nSee \\`agents/agents/AGENTS.md\\` for the full \\`SubagentRelationship\\` option list (\\`immediate\\`, \\`optional\\`, \\`hidden\\`, \\`parentCommunication\\`, init mappings) and the ownership rules.\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\nAn agent is the top-level conversation orchestrator. An agent has **exactly two sides**, and each side is **backed** by exactly one of three things: a human, a prompt, or a handler. There is no agent \"type\" — everything about how an agent converses, composes, and terminates is derived from the backings of its two sides.\n\n| Backing | Who takes this side's turns | Declared as |\n|---------|-----------------------------|-------------|\n| **Human** | A person, via whatever interface the runtime provides | \\`{ human: true }\\` |\n| **Prompt** | A model, driven by a prompt from \\`agents/prompts/\\` | \\`{ prompt: 'name', ... }\\` |\n| **Handler** | Deterministic code from \\`agents/handlers/\\` | \\`{ handler: 'name', ... }\\` |\n\nBoth sides are explicit. There is no implicit \"missing side B is a human\" default — if a person takes side B's turns, write \\`sideB: { human: true }\\`.\n\n## Agent Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| \\`name\\` | \\`string\\` | Yes | Unique identifier for this agent |\n| \\`sideA\\` | \\`SideConfig\\` | Yes | Side A configuration (backing-discriminated) |\n| \\`sideB\\` | \\`SideConfig\\` | Yes | Side B configuration (backing-discriminated) |\n| \\`maxSessionTurns\\` | \\`number\\` | No | Session exchange safety cap — optional on every agent shape |\n| \\`title\\` | \\`string\\` | No | Human-readable label |\n| \\`description\\` | \\`string\\` | No | Agent summary |\n| \\`icon\\` | \\`string\\` | No | Display icon (see Icons below) |\n| \\`exposeAsTool\\` | \\`boolean\\` | No | Expose a callable entrypoint for handoffs and composition |\n| \\`primary\\` | \\`boolean\\` | No | Default true. Set false on internal handoff-target agents (e.g. domain-gearbox variants) to hide them from top-level UI agent lists; they stay fully addressable for handoffs and thread resumption |\n| \\`toolDescription\\` | \\`string\\` | No | Default model-facing description when this agent is composed or handed off to (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| \\`parentHooks\\` | \\`ParentHookRequirement[]\\` | No | Required hooks automatically contributed to a direct parent composition (legal on any exposed agent) |\n| \\`tags\\` | \\`string[]\\` | No | Tags for categorization and filtering |\n\n## Side Configuration\n\nA side's configuration is discriminated by its backing: exactly one of \\`human\\`, \\`prompt\\`, or \\`handler\\` must be present.\n\n**Human side** — \\`{ human: true, label? }\\`. No other properties are legal on a human side. In particular, \\`subagents\\` on a human side is a definition-time error (nothing there can invoke them), and stop/session bindings are meaningless.\n\n**Prompt side**\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| \\`prompt\\` | \\`string\\` | Yes | Prompt name to use (references \\`agents/prompts/\\`) |\n| \\`label\\` | \\`string\\` | No | Display name for this side |\n| \\`subagents\\` | \\`SubagentRelationship[]\\` | No | Side-owned child relationships (see Subagent Relationships below) |\n| \\`stopOnResponse\\` | \\`boolean\\` | No | Stop side turn on text response without tool calls (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\\` | \\`SessionToolBinding\\` | No | Terminal success lifecycle binding (object form only) |\n| \\`sessionFail\\` | \\`SessionToolBinding\\` | No | Terminal failure lifecycle binding (object form only) |\n| \\`sessionStatus\\` | \\`SessionToolBinding\\` | No | Non-terminal status lifecycle binding (object form only) |\n\n**Handler side**\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| \\`handler\\` | \\`string\\` | Yes | Handler name for this side (references \\`agents/handlers/\\`) |\n| \\`label\\` | \\`string\\` | No | Display name for this side |\n| \\`subagents\\` | \\`SubagentRelationship[]\\` | No | Side-owned child relationships |\n\nHandler sides have no \\`maxSteps\\`, \\`stopOnResponse\\`, or session bindings: a handler turn is a single invocation, and handlers end sessions through \\`state.stopSession()\\` rather than declarative bindings. See \\`agents/handlers/AGENTS.md\\`.\n\nSession lifecycle bindings use the object form only:\n\n\\`\\`\\`typescript\nsessionStop: {\n name: 'complete_work', // tool that controls the lifecycle action\n messageProperty: 'summary', // arg field that becomes lifecycle message text\n attachmentsProperty: 'files', // arg field containing attachment path(s)\n}\n\\`\\`\\`\n\n## Derivations\n\nThese follow from the backings and are never declared separately:\n\n- **Chat surface** — the primary conversational interface renders wherever a \\`human\\` backing is.\n- **Perspective** — \\`role: 'user'\\` is the side B perspective, \\`role: 'assistant'\\` is the side A perspective, for queueing, injection, and rendering alike.\n- **Subagent eligibility** — any agent may be composed as a subagent. Composing a child with a human side puts a person's step inside the composition (the child parks \\`awaiting_human\\` until that person responds).\n- **Termination discipline** — \\`maxSessionTurns\\` is optional on every agent shape, with uniform exchange counting across backings (a handler turn counts like a prompt turn). Two prompt-backed sides can ping-pong indefinitely — the cap is a voluntary safety valve, and prompt and handler authors own their termination discipline.\n\n## Example: Assistant (human × prompt)\n\nThe everyday user-facing assistant — a person on side B, a model on side A:\n\n\\`\\`\\`typescript\nimport { defineAgent } from '@standardagents/builder';\n\nexport default defineAgent({\n name: 'support_agent',\n sideA: {\n label: 'Support',\n prompt: 'customer_support',\n stopOnResponse: true,\n sessionStop: { name: 'close_ticket' },\n maxSteps: 50,\n },\n sideB: { human: true },\n tags: ['support', 'tier-1'],\n});\n\\`\\`\\`\n\n## Example: Worker / Reviewer (prompt × prompt)\n\nTwo models converse; each side sees itself as \\`assistant\\` and the other as \\`user\\`. \\`maxSessionTurns\\` is optional but strongly recommended here — nothing external stops two models:\n\n\\`\\`\\`typescript\nexport default defineAgent({\n name: 'research_agent',\n maxSessionTurns: 20,\n exposeAsTool: true,\n toolDescription: 'Researches and validates findings autonomously',\n sideA: {\n label: 'Worker',\n prompt: 'research_worker',\n stopOnResponse: true,\n sessionStatus: { name: 'set_research_status', messageProperty: 'status' },\n sessionFail: { name: 'fail_research', messageProperty: 'reason' },\n },\n sideB: {\n label: 'Reviewer',\n prompt: 'research_reviewer',\n stopOnResponse: true,\n sessionStop: { name: 'approve_research', messageProperty: 'summary' },\n },\n});\n\\`\\`\\`\n\n## Example: Relay (handler × human)\n\nA deterministic, model-less surface: a person talks to a handler that forwards traffic to a composed child and relays answers back. Zero LLM calls happen on this thread:\n\n\\`\\`\\`typescript\nexport default defineAgent({\n name: 'relay_agent',\n sideA: {\n handler: 'relay_pipe',\n subagents: [{ agent: 'assistant_agent', maxInstances: 1 }],\n },\n sideB: { human: true },\n});\n\\`\\`\\`\n\nThe \\`relay_pipe\\` handler lives in \\`agents/handlers/relay_pipe.ts\\` — the full worked example is in \\`agents/handlers/AGENTS.md\\`.\n\n## Subagent Relationships\n\nComposition into a child thread is declared on the side that owns it — never inside a prompt's \\`tools\\` array. The side's declaration is the grant:\n\n\\`\\`\\`typescript\nsideA: {\n prompt: 'coordinator',\n subagents: [\n { agent: 'calendar_agent', as: 'work_calendar', scopedEnv: ['WORK_CAL_ID'] },\n { agent: 'calendar_agent', as: 'personal_calendar', scopedEnv: ['PERSONAL_CAL_ID'] },\n { agent: 'research_agent', blocking: true, maxInstances: 1 },\n ],\n},\n\\`\\`\\`\n\n- The owning side is where child traffic lands: completion, failure, and status messages arrive on the owning side's perspective. Parent→child traffic enters in the child's side B perspective (\\`role: 'user'\\`), so the child's side A acts on it.\n- A relationship name (\\`as\\`, defaulting to \\`agent\\`) may appear on at most one side, must not collide with another tool name, and must not collide with the reserved lifecycle tool names \\`subagents\\`, \\`subagent_create\\`, \\`subagent_message\\`.\n- For a prompt-backed owning side, the runtime injects those lifecycle tools automatically. Handler-backed owning sides need no tool grant — handlers reach children through \\`ThreadState\\` directly.\n- **Persistence is universal**: every child instance is a persistent thread. Session end never terminates a thread; only explicit \\`state.terminate()\\` destroys an instance. \\`blocking\\` is purely a waiting style.\n\nSee \\`agents/prompts/AGENTS.md\\` for the lifecycle tools from the prompt's point of view, and the relationship option list (\\`immediate\\`, \\`optional\\`, \\`hidden\\`, \\`parentCommunication\\`, init mappings).\n\n## Agent Handoffs\n\nWhen \\`exposeAsTool: true\\`, an agent referenced directly in a prompt's \\`tools\\` array is a **handoff**: the tool call transfers control of the *same thread* to the target agent, preserving history. Handoff requires the target agent to have a human side matching the thread's conversational surface.\n\n\\`\\`\\`typescript\nexport default defineAgent({\n name: 'escalation_agent',\n exposeAsTool: true,\n toolDescription: 'Escalate to senior support for complex issues',\n sideA: { prompt: 'senior_support' },\n sideB: { human: true },\n});\n\\`\\`\\`\n\n## Stop Semantics\n\nRuntime stop evaluation order for prompt-backed sides:\n\n1. **sessionStop / sessionFail** — end the session (success / terminal failure)\n2. **stopTool** — ends the current side's turn\n3. **stopOnResponse** — ends the turn when the LLM returns text without tool calls\n4. **Safety limits** — \\`maxSteps\\` (per side), \\`maxSessionTurns\\` (per session, hard limit: 250)\n\nA handler-backed side's turn ends when its handler invocation returns. A human-backed side's turn ends when the human's inbound message is persisted.\n\n## Definition-Time Errors\n\nThese shapes are rejected when definitions load:\n\n1. Both sides human (reserved — may lift in a later version)\n2. \\`subagents\\` declared on a human-backed side\n3. A side with zero backings, or more than one of \\`human\\` / \\`prompt\\` / \\`handler\\`\n4. A handler side referencing an undefined handler; a prompt side referencing an undefined prompt\n5. A relationship name (\\`as\\`) appearing on both sides, colliding with another tool name, or colliding with a reserved lifecycle tool name\n6. Session bindings, \\`maxSteps\\`, or stop bindings on a non-prompt side\n7. A session binding that is not in object form\n\n## Hooks\n\nAttach lifecycle hooks at the agent level:\n\n\\`\\`\\`typescript\nexport default defineAgent({\n name: 'support_agent',\n hooks: ['log_all_messages', 'sanitize_results'],\n sideA: { prompt: 'customer_support' },\n sideB: { human: true },\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\nAny exposed agent can declare required parent integration hooks:\n\n\\`\\`\\`typescript\nparentHooks: [{\n hook: 'sync_gmail_context',\n reason: 'Makes synchronized Gmail context available to the coordinator.',\n stage: 'before_parent', // default: after_parent\n}],\n\\`\\`\\`\n\nInstalling the package is inert. Declaring a relationship targeting this agent\n(or adding it to a prompt as a handoff) activates the hook automatically on\nthat direct parent, and composition UIs disclose the \\`reason\\` first. Disabled\noptional relationships contribute nothing; enabled hidden relationships still\ncontribute hooks. Required hooks run with the parent's \\`ThreadState\\`, load\nfrom the child's package namespace, and fail composition closed if missing.\nUser-scope hooks cannot be listed.\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## Icons\n\nGive an agent a custom icon with the \\`icon\\` property: a full URL, a data URI,\nor a site-relative path served from your project's \\`public/\\` directory —\n\\`icon: '/icons/support.svg'\\` expects the file at \\`public/icons/support.svg\\`.\nThe file is served in dev and deployed with your project's assets. Agents\nwithout an icon (or whose icon fails to load) render a generated identicon,\nand the dashboard warns when a site-relative icon path has no matching file.\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- **Write sideB explicitly** - there is no implicit default; a user-facing agent ends with \\`sideB: { human: true }\\`\n- **Cap prompt × prompt agents** - set \\`maxSessionTurns\\` when both sides are prompt-backed; nothing external stops two models\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 HANDLERS_AGENTS_MD = `# Handler Definitions\n\nA handler is a function that takes one side's turns in a conversation. When a side of an agent is backed by a handler, the runtime does not call a model to answer an inbound message — it calls the handler function once, with the thread state and the message, and whatever that function does is the side's turn.\n\nA handler is **not** a hook (hooks decorate turns owned by something else, and their failures are non-fatal), **not** a tool (tools are capabilities a turn-owner chooses to invoke), and **not** an effect (effects run outside the conversation flow). Its only role is backing a side of an agent. Handlers may not be referenced by prompt \\`tools\\` arrays, hook lists, or effect schedules — such references are definition-time errors.\n\n## Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| \\`description\\` | \\`string\\` | No | Human-facing summary |\n| \\`execute\\` | \\`(state: ThreadState, message: Message) => Promise<void>\\` | Yes | The turn implementation |\n\nThe handler's name comes from its filename: \\`agents/handlers/relay_pipe.ts\\` defines the handler \\`relay_pipe\\`. The \\`message\\` parameter is the full persisted message — id, role, content, silent flag, metadata, timestamps. Handlers are trusted definition code, like tools.\n\n## Basic Example\n\n\\`\\`\\`typescript\n// agents/handlers/relay_pipe.ts\nimport { defineHandler } from '@standardagents/builder';\n\nexport default defineHandler({\n description: 'Forwards inbound user traffic to the assistant child and relays answers back.',\n execute: async (state, message) => {\n // full ThreadState — forward, respond, spawn, stop, read/write KV\n },\n});\n\\`\\`\\`\n\nReference it from exactly one place: the \\`handler\\` property of an agent side:\n\n\\`\\`\\`typescript\nexport default defineAgent({\n name: 'relay_agent',\n sideA: { handler: 'relay_pipe', subagents: [{ agent: 'assistant_agent', maxInstances: 1 }] },\n sideB: { human: true },\n});\n\\`\\`\\`\n\n## Execution Model\n\nA handler-backed side's turn is:\n\n1. An inbound message arrives on the side's perspective.\n2. The runtime invokes the handler once with the thread's \\`ThreadState\\` and that message.\n3. The invocation returns (or throws). The turn is complete.\n\nThere are no steps, no tool-choice loop, and no model requests for this side. \\`maxSteps\\`, \\`stopOnResponse\\`, \\`stopTool\\`, and session bindings are not legal on handler sides — a handler turn has no steps to cap and ends when \\`execute\\` returns. Handlers end sessions explicitly via \\`state.stopSession()\\`. When the agent sets \\`maxSessionTurns\\`, a handler turn counts toward the exchange cap exactly like a prompt turn.\n\n## Delivery Semantics\n\nDelivery to a handler is **exactly-once per message**:\n\n- The handler is invoked exactly once for each inbound message on the side's perspective, in message persistence order.\n- The handler is never invoked concurrently for the same thread. Messages that arrive while a handler turn is in flight wait in the queue and are delivered one at a time, in order.\n- A message whose handler invocation failed is not automatically redelivered. Retry is a userland decision (re-send the message).\n\n**Warning:** Because queued messages wait behind the in-flight turn, a long-running handler stalls its thread. A handler that awaits a \\`blocking\\` child session holds the delivery slot for that session's entire duration — and if that child can only finish after *another* inbound message on this thread, the thread deadlocks. Relay-style handlers should forward without blocking (\\`queueMessage\\` toward the child) and treat the child's replies as ordinary later turns.\n\n## Error Semantics\n\nA handler that throws is **fatal to the turn, and only the turn**:\n\n- The turn is marked failed and the error is surfaced in the runtime's request/execution log as a runtime-origin failure — a throwing handler never silently swallows a message.\n- The inbound message stays persisted. Nothing is rolled back.\n- The **session continues**: the failure does not end the session, terminate the thread, or poison the queue. The next inbound message gets a fresh handler invocation.\n\nIf an error should end the session, the handler must do so explicitly with \\`state.stopSession()\\`.\n\n## Capabilities\n\nA handler receives the full \\`ThreadState\\` and may do anything tools can do:\n\n- **Forward** — \\`(await state.getChildThread(ref)).queueMessage(...)\\` toward a child, or \\`state.notifyParent(...)\\` toward a parent.\n- **Respond** — \\`state.injectMessage({ role, content })\\` in its own side's role (\\`assistant\\` for side A, \\`user\\` for side B).\n- **Spawn** — create child instances of the side's declared \\`subagents\\` relationships via lifecycle APIs.\n- **Control** — \\`state.stopSession()\\`, \\`state.setStatus()\\`, effects, environment, key-value store, filesystem.\n\nHandlers need no tool grants for children: the side's \\`subagents\\` declarations establish existence and lifecycle, and the handler reaches children through \\`ThreadState\\` directly. (The injected lifecycle *tools* exist for prompts — a handler calls the same operations as code.)\n\n## The Outbound Boundary\n\nHandlers get no auto-injected reply channel. If a handler (or the side it feeds) should speak to a user or an external surface, that is userland code — a tool or handler calling the messaging surface it chooses (the \\`message_user\\` pattern). **The runtime routes inbound; userland decides outbound.**\n\n## Livelock Discipline\n\nHandler sides do not run away on their own — a handler runs only when a message arrives. But a handler that *replies to every inbound message* paired with a prompt-backed side creates a message ping-pong with no natural stop. Handler authors own their termination discipline:\n\n- reply conditionally, not unconditionally;\n- or set \\`maxSessionTurns\\` on the agent (available on every shape) as a hard safety valve;\n- or end the session explicitly with \\`state.stopSession()\\` when the work is done.\n\n## Worked Example: the Relay\n\nA user-facing thread that does **zero model work**: every inbound user message is forwarded verbatim to a composed assistant child; every child answer is relayed back out through userland messaging. One handler expresses the entire surface:\n\n\\`\\`\\`typescript\n// agents/handlers/relay_pipe.ts\nimport { defineHandler } from '@standardagents/builder';\n\nexport default defineHandler({\n description: 'Pipe user traffic to the assistant child; relay answers outward.',\n execute: async (state, message) => {\n const child = state.children.find(c => c.relationship === 'assistant_agent');\n if (child) {\n const thread = await state.getChildThread(child.reference);\n await thread?.queueMessage({ role: 'user', content: message.content ?? '' });\n }\n },\n});\n\n// agents/agents/relay_agent.ts\nimport { defineAgent } from '@standardagents/builder';\n\nexport default defineAgent({\n name: 'relay_agent',\n sideA: {\n handler: 'relay_pipe',\n subagents: [{\n agent: 'assistant_agent',\n maxInstances: 1,\n immediate: true, // spawned at thread creation\n parentCommunication: 'explicit',\n }],\n },\n sideB: { human: true },\n});\n\\`\\`\\`\n\nThe child's answers arrive as inbound messages on side A (the owning side) and get their own handler turns, where the handler calls the project's outbound messaging tool. No model participates at any point.\n\n## Best Practices\n\n- **Forward without blocking** — queue toward children and treat their replies as later turns; never hold the delivery slot on a child session\n- **Reply conditionally** — an unconditional reply opposite a prompt side is a ping-pong\n- **End sessions explicitly** — \\`state.stopSession()\\` when the work is done; there are no declarative session bindings on handler sides\n- **Keep handlers deterministic** — code that wants a model writes a prompt; code that wants a capability writes a tool; code that decorates writes a hook\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/handler\n`;\n\nexport const HANDLERS_CLAUDE_MD = HANDLERS_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 progressArgument?: string, // Arg holding a short progress label, e.g. \"writing index.html\"\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 const creationArgs = state.arguments; // Invocation or subagent creation args\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 // The thread's user profile (identity only, never credentials) — for\n // per-user personalization or entitlement checks. Null when user-less.\n const user = await state.user();\n\n // Instance-GLOBAL Agent Skills library (agentskills.io SKILL.md format).\n // Skills install once and are visible to every thread; load a skill's body\n // only when it's applicable (progressive disclosure).\n const skills = await state.skills.list();\n const skill = await state.skills.get('pdf-processing');\n const script = await state.skills.readFile('pdf-processing', 'scripts/extract.py');\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### Optional Runtime Streams\n\nSome runtimes expose live, authorized byte streams through\n\\`state.runtimeStreams\\`. Always feature-detect the optional surface. The\nfollowing neutral example streams media to a workstation-hosted transcoder,\nhalf-closes the writable side, reads the encoded result, and cleans up:\n\n\\`\\`\\`typescript\nconst runtimeStreams = state.runtimeStreams;\nif (!runtimeStreams) {\n return { status: 'error', error: 'This runtime has no workstation streams.' };\n}\n\nconst opened = await runtimeStreams.open({\n capability: 'workstation_transcoder',\n metadata: { inputFormat: 'wav', outputFormat: 'opus' },\n timeoutMs: 10_000,\n});\nif (!opened.ok) {\n return { status: 'error', error: opened.error, error_code: opened.code };\n}\n\ntry {\n const writer = opened.stream.writable.getWriter();\n try {\n await writer.write(sourceMedia);\n await writer.close();\n } finally {\n writer.releaseLock();\n }\n\n const reader = opened.stream.readable.getReader();\n const encoded: Uint8Array[] = [];\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n encoded.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n const closed = await opened.stream.closed;\n if (!closed.ok) throw new Error(closed.error ?? 'Transcoding failed.');\n return { status: 'success', result: \\`Received \\${encoded.length} chunks.\\` };\n} finally {\n opened.stream.close();\n}\n\\`\\`\\`\n\n\\`readable\\` carries host-to-runtime bytes; \\`writable\\` carries\nruntime-to-host bytes. Streams are live and non-durable. \\`close()\\` is\nidempotent, and the \\`closed\\` promise settles once.\n\nSandboxed coding code must not use ambient network globals. For HTTP inside \\`coding_run\\`, import \\`{ fetch }\\` from \\`\"fetch\"\\`; the bridge supports \\`fetch(url, init)\\` with methods, headers, and bodies, and returns a Response-like object with \\`text()\\`, \\`json()\\`, \\`arrayBuffer()\\`, and \\`headers.get()\\`. The sandboxed coding prompt includes \\`fetch_url\\` for reading known external public http(s) pages as Markdown. Use the \\`coding_run\\` fetch bridge instead for custom methods, headers, request bodies, or checks against thread public file/API endpoint URLs returned by \\`get_public_url\\`.\n\nSandboxed coding agents should verify runtime behavior as they work. \\`coding_validate_typescript\\` is useful but incomplete; call helper exports with \\`coding_run\\`, probe pages and endpoints with \\`coding_run\\` plus the fetch bridge, inspect status/body, and clean up disposable side-effecting test data when practical.\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## Stopping Sessions\n\n\\`state.execution.stop()\\` stops the current execution loop. To terminally end the active agent session, including blocking subagent runs that expect a session boundary, use \\`state.stopSession()\\`:\n\n\\`\\`\\`typescript\nawait state.stopSession({\n result: 'Waiting for clarification',\n notifyParent: 'Please clarify the request',\n status: 'waiting for clarification',\n});\n\\`\\`\\`\n\n\\`notifyParent\\` queues a silent message to the parent when one exists; \\`status\\` is ignored without a parent registry entry. Omit \\`notifyParent\\` and \\`status\\` when stopping should not send a parent message or update child status.\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 before the history snapshot |\n| \\`filter_messages\\` | \\`(state: ThreadState, messages: Message[]) => Message[]\\` | Build the request context from one stable history snapshot per model request |\n| \\`prefilter_llm_history\\` | \\`(state: ThreadState, messages: LLMMessage[]) => LLMMessage[]\\` | Modify transformed provider messages before dispatch |\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| \\`user_client_attached\\` | \\`(user: UserState, client: { id, kind? }) => void\\` | User-scope: a socket attached to the user event stream |\n| \\`user_client_detached\\` | \\`(user: UserState, client: { id, kind? }) => void\\` | User-scope: a socket detached |\n| \\`user_value_changed\\` | \\`(user: UserState, key: string) => void\\` | User-scope: a durable user value changed (any writer) |\n| \\`tool_call_started\\` | \\`(state: ThreadState, toolCall: HookToolCall, progress?: string) => void\\` | Observe a tool call when it starts streaming (before it runs) |\n| \\`tool_call_done\\` | \\`(state: ThreadState, toolCall: HookToolCall, result: HookToolResult) => void\\` | Observe a tool call after it finishes (success or failure) |\n\nUser-scope hooks receive \\`UserState\\`. All thread hooks receive \\`ThreadState\\`\nfirst and \\`HookExecutionContext\\` last. The context source is prompt, agent, or\nchild provenance; child provenance includes \\`relationshipName\\`, resolved\n\\`agentName\\`, and optional package signature.\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- Enabled direct children contribute their declared \\`parentHooks\\`\n- Ordering is child \\`before_parent\\`, prompt-or-agent base, child \\`after_parent\\`\n- Child requirements load from the child's package and run on the parent state\n- Disabled optional children contribute nothing; hidden enabled children still do\n- Installing alone is inert; adding the child relationship activates its disclosed hooks\n- Hooks are filtered by type at runtime\n- At-rest operations have no active prompt and use agent-level hooks\n\n## History and the Request Context\n\nEach provider request runs \\`after_system_message\\`, takes one stable persisted-history\nsnapshot, runs \\`filter_messages\\` exactly once, transforms the result, and then runs\n\\`prefilter_llm_history\\`. These request-context hooks do not replace\n\\`state.execution.messageHistory\\`. Messages injected by \\`after_system_message\\` enter\nthe current snapshot. Messages injected by either request-context hook enter the\nfollowing snapshot. Silent messages remain eligible unless a request-context hook removes\nthem.\n\n## Create-Message Lifecycle\n\n\\`before_create_message\\` and \\`after_create_message\\` run for runtime insertion\npaths, including \\`injectMessage()\\` (active and at rest), agent-handoff user\nmessages, and generated-asset path messages. A \\`before_create_message\\` hook\nthat throws during \\`injectMessage()\\` rejects the injection and nothing is\npersisted. Other runtime insertions log the failure and keep the last good\nmessage.\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> Warning: In \\`after_tool_call_success\\` / \\`after_tool_call_failure\\`,\n> returning \\`null\\` does NOT mean \"keep the original result\" — it tells the\n> runtime to **REMOVE the tool call from history and skip storing the result**\n> (the assistant tool-call message is deleted). A side-effect-only hook MUST\n> return the \\`result\\` it received.\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 result; // ALWAYS return the result — null would DELETE the tool call\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 result; // keep the original error — null would DELETE the tool call\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 the — possibly modified — result; \\`null\\` REMOVES the tool call from history)\n- \\`after_tool_call_failure\\` (return the — possibly modified — result; \\`null\\` REMOVES the tool call from history)\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## Blocking a step from a hook\n\nHook failures are normally non-fatal (logged and ignored). A\n\\`prefilter_llm_history\\` hook may deliberately BLOCK the step — the session\nstops with a visible assistant message BEFORE any LLM request — by throwing an\nerror that carries \\`block: true\\`:\n\n\\`\\`\\`typescript\nthrow Object.assign(new Error('Thread limit reached'), { block: true });\n\\`\\`\\`\n\nUse this for entitlement/policy gates (e.g. per-user concurrency leases).\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, \\`arguments\\`, file system, \\`runCode\\`, etc. |\n| \\`params\\` | \\`Record<string, string>\\` | Route parameters captured from \\`[name]\\` and \\`[*]\\` path segments |\n| \\`auth\\` | \\`ThreadEndpointAuth\\` | The request's authentication context: \\`caller\\` (the authenticated identity, or \\`null\\` for anonymous requests) and \\`threadAccess\\` (whether the caller passes the runtime's access policy for this thread) |\n\n## Access Levels\n\nEndpoints are \\`authenticated\\` by default: the runtime authenticates the\nrequest and enforces thread access before your handler runs, and \\`auth.caller\\`\nis always present. Declare \\`{ access: 'public' }\\` to accept anonymous\nrequests — the runtime still resolves \\`auth.caller\\` when credentials are\npresented, so one endpoint can serve both audiences:\n\n\\`\\`\\`typescript\n// agents/api/shared/[*].ts -> GET /api/threads/:threadId/shared/<path>\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(\n async (req, state, params, auth) => {\n if (!auth.threadAccess && !isShared(params['*'])) {\n return new Response(null, { status: 404 });\n }\n // serve the file...\n },\n { access: 'public' }\n);\n\\`\\`\\`\n\nA public endpoint is reachable by anyone who has the URL — treat it like an\ninternet-facing route: validate the path, reject early, and never echo\nprivate state to anonymous callers.\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. \\`state.emit(event, data)\\` broadcasts a custom WebSocket event from endpoints as well as active executions; use it as an invalidation hint after persisting durable state, not as a replacement for reconnect recovery.\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 console.log('Arguments:', state.arguments);\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 state.emit('export_count_changed', { 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 // Move or rename files and directories (does not overwrite an existing destination)\n await state.moveFile('/data/file.txt', '/archive/file.txt');\n await state.renameFile('/output/result.json', 'final.json');\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","export const USERS_AGENTS_MD = `# User Endpoints\n\nDefine user-scoped API endpoints — HTTP handlers that operate on a USER\n(durable cross-thread state) rather than a single thread. They execute inside\nthe per-user hub with a serialization guarantee: at most one user endpoint\nruns at a time per user, and each observes all prior completed writes. That\nmakes this directory the home for quotas, leases, counters, registries, and\nany other user-level logic where lost updates matter.\n\nSpecification: https://standardagentspec.com/0.1.0/specification/users\n\n## File-Based Routing\n\n| File Pattern | HTTP Method | Route |\n|--------------|-------------|-------|\n| \\`name.ts\\` | GET | \\`/api/users/me/name\\` |\n| \\`name.post.ts\\` | POST | \\`/api/users/me/name\\` |\n| \\`pkg/name.post.ts\\` | POST | \\`/api/users/me/pkg/name\\` |\n| \\`items/[id].ts\\` | GET | \\`/api/users/me/items/:id\\` |\n| \\`files/[*].ts\\` | GET | \\`/api/users/me/files/*\\` |\n\nRouting rules match thread endpoints (method suffixes, nested directories,\n\\`[param]\\`, \\`[*]\\`). Root your endpoints in a directory named for your\npackage so installed packages coexist. Administrators can address any user's\nendpoints at \\`/api/users/:id/...\\`.\n\n## Basic Example\n\n\\`\\`\\`typescript\n// agents/users/quota.post.ts → POST /api/users/me/quota\nimport { defineUserEndpoint } from '@standardagents/spec';\n\nexport default defineUserEndpoint(async (req, user, params) => {\n const used = (await user.getValue<number>('quota.used')) ?? 0;\n const limit = Number(await user.getValue('quota.limit')) || 0;\n const { amount } = await req.json();\n if (used + amount > limit) {\n return Response.json({ ok: false, used, limit }, { status: 429 });\n }\n await user.setValue('quota.used', used + amount);\n user.emit('quota_changed', { used: used + amount, limit });\n return Response.json({ ok: true });\n});\n\\`\\`\\`\n\n## UserState\n\nHandlers receive a \\`UserState\\`: \\`userId\\`, \\`identity()\\`, durable values\n(\\`getValue\\`/\\`setValue\\`/\\`listValues\\`), \\`env()\\`, \\`emit()\\` (broadcast on\nthe user event stream at \\`/api/users/me/stream\\`), \\`listThreads()\\`,\n\\`fetch(grant, url, init)\\` (privileged fetch through a credential grant), and\n\\`thread(threadId)\\` (raise one of the user's threads at rest).\n\n## Caller Channels\n\nHandlers can distinguish who invoked them via the\n\\`X-Standard-Agents-Caller\\` request header, which the runtime stamps and\nun-forgeably overwrites on public routes: \\`user\\` (the user's own HTTP\nrequest), \\`admin\\` (administrative addressing), or \\`thread\\` (a\nruntime-internal \\`state.user().call()\\`). Gate enforcement-critical\nmutations (quotas, leases) on the \\`thread\\` channel.\n\n## Reaching the User Scope from Threads\n\nTools, hooks, and thread endpoints call user endpoints through the thread's\nuser handle:\n\n\\`\\`\\`typescript\nconst user = await state.user();\nawait user?.call('quota', { amount: 1 }); // serialized, atomic\n\\`\\`\\`\n\n## Live Events\n\nClients subscribe to \\`GET /api/users/me/stream\\` (WebSocket) and receive every\n\\`emit()\\` as \\`{ \"event\": string, \"data\": unknown }\\`. The stream is live-only:\nre-read durable state on connect and reconnect.\n`;\n\nexport const USERS_CLAUDE_MD = USERS_AGENTS_MD;\n","import {\n AGENT_DEFINITIONS_AGENTS_MD,\n API_AGENTS_MD,\n USERS_AGENTS_MD,\n HANDLERS_AGENTS_MD,\n HOOKS_AGENTS_MD,\n MODELS_AGENTS_MD,\n PROVIDERS_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 HANDLERS_AGENTS_MD,\n HANDLERS_AGENTS_MD as HANDLERS_CLAUDE_MD,\n USERS_AGENTS_MD,\n USERS_AGENTS_MD as USERS_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 PROVIDERS_AGENTS_MD,\n PROVIDERS_AGENTS_MD as PROVIDERS_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 * Include a working `vite build` script in the rendered package manifest.\n * Only the platform build runner should set this. Local manifests get a\n * guard script instead, because customer projects build and deploy on the\n * Standard Agents platform after a git push — never on the user's machine.\n */\n includeBuildScript?: boolean\n}\n\nexport const FIRST_PARTY_PROVIDER_PACKAGES = [\n '@standardagents/anthropic',\n '@standardagents/cloudflare',\n '@standardagents/cerebras',\n '@standardagents/deepinfra',\n '@standardagents/google',\n '@standardagents/groq',\n '@standardagents/novita',\n '@standardagents/openai',\n '@standardagents/openrouter',\n '@standardagents/xai',\n] as const\n\n/**\n * Dependency packages whose install scripts the generated project approves.\n * pnpm 10 blocks dependency build scripts by default and, under CI (the\n * platform build runner sets CI=true), fails the install outright with\n * ERR_PNPM_IGNORED_BUILDS. These are the script-running packages in the\n * default dependency tree (native binaries and codegen) that the project\n * needs for installs and builds to work.\n *\n * The same list feeds THREE approval surfaces: pnpm's\n * package.json#pnpm.onlyBuiltDependencies (pre-11), pnpm-workspace.yaml's\n * onlyBuiltDependencies/allowBuilds (11+), and npm 12's\n * package.json#allowScripts — npm 12 silently skips unapproved dependency\n * install scripts, which leaves a fresh project without workerd/esbuild\n * binaries.\n */\nexport const APPROVED_DEPENDENCY_BUILD_SCRIPTS = [\n '@google/genai',\n '@openrouter/sdk',\n 'esbuild',\n 'protobufjs',\n 'sharp',\n 'workerd',\n] as const\n\n// Pin first-party @standardagents/* packages to a controlled major range\n// rather than \"latest\". Floating on \"latest\" let the installed builder drift\n// out of sync with the generated provider list (e.g. builder shipped the\n// anthropic provider while a stale template omitted it), breaking the build.\n// Caret on a 0.x version accepts patch releases automatically but holds the\n// minor, so only an intentional \"major\" bump of these packages re-challenges\n// the pin. Bump these together when the platform adopts a new release line.\nexport const DEFAULT_TEMPLATE_VERSIONS: TemplateVersions = {\n standardAgents: '^0.35.5',\n sip: '^1.0.1',\n vite: 'latest',\n typescript: 'latest',\n zod: 'latest',\n}\n\nexport const AGENTBUILDER_TEMPLATE_VERSION = '0.41.1'\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: options.includeBuildScript\n ? 'vite build'\n : \"echo 'Standard Agents projects build and deploy on the platform. Push your commit (git push or agents deploy) to trigger a build.' && exit 1\",\n typecheck: 'tsc --noEmit',\n },\n dependencies,\n devDependencies: {\n typescript: versions.typescript,\n vite: versions.vite,\n },\n pnpm: {\n onlyBuiltDependencies: [...APPROVED_DEPENDENCY_BUILD_SCRIPTS],\n },\n // npm 12 skips unapproved install scripts (name-only entries approve any\n // version — these dependencies float). Ignored by npm <12 and pnpm.\n allowScripts: Object.fromEntries(\n APPROVED_DEPENDENCY_BUILD_SCRIPTS.map((name) => [name, true]),\n ),\n }, null, 2)}\\n`\n}\n\n/**\n * pnpm 11 no longer reads the package.json#pnpm field — install-script\n * approvals live in pnpm-workspace.yaml. The manifest keeps the legacy\n * pnpm.onlyBuiltDependencies for older pnpm; this file is the pnpm 11+ home.\n * Without an approval, esbuild/workerd never run their install scripts and\n * `vite build` fails on the platform build runner.\n */\nexport function renderPnpmWorkspaceYaml(): string {\n const listEntries = APPROVED_DEPENDENCY_BUILD_SCRIPTS\n .map((name) => ` - \"${name}\"`)\n .join('\\n')\n const mapEntries = APPROVED_DEPENDENCY_BUILD_SCRIPTS\n .map((name) => ` \"${name}\": true`)\n .join('\\n')\n // pnpm 10.4+ reads onlyBuiltDependencies; v11 replaced it with the\n // allowBuilds map. Each version ignores the other's key, so ship both.\n // pnpm 11's default minimum-release-age policy rejects same-day releases;\n // Standard Agents ships first-party packages the day they're cut, so the\n // scope is exempted (third-party packages keep the protection).\n return `onlyBuiltDependencies:\\n${listEntries}\\nallowBuilds:\\n${mapEntries}\\nminimumReleaseAgeExclude:\\n - \"@standardagents/*\"\\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 // package.json AND the lockfile are committed: the project owns its\n // @standardagents/* versions and the platform build installs them frozen for\n // byte-exact, reproducible deploys (the build runner uses whichever package\n // manager the committed lockfile implies). Only secrets, dependencies, and\n // local build/dev state are ignored.\n return `node_modules\ndist\n.agents\n.wrangler\n.env\n.dev.vars\n.agentbuilder-dev.log\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=\nDEEPINFRA_API_KEY=\nGOOGLE_API_KEY=\nGROQ_API_KEY=\nNOVITA_API_KEY=\nOPENAI_API_KEY=\nOPENROUTER_API_KEY=\nANTHROPIC_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 // The project owns its @standardagents/* versions: the committed manifest is\n // the source of truth the platform build honors (what you test locally is\n // what deploys). It ships a guard `build` script that refuses to build\n // off-platform; the build runner swaps in the real `vite build` at build\n // time. Never set includeBuildScript here — a working local build would let\n // a half-configured checkout deploy from the wrong place.\n file('package.json', renderPackageJson({ ...options, includeBuildScript: false }), 'Add package manifest'),\n // Committed alongside package.json so a freshly cloned repo ignores\n // node_modules, lockfiles, secrets, and local build state without depending\n // on the CLI to generate a .gitignore after clone.\n file('.gitignore', renderGitignore(), 'Add gitignore'),\n // pnpm 11 reads install-script approvals from pnpm-workspace.yaml (the\n // package.json#pnpm field is ignored since v11); older pnpm reads the\n // manifest — both are committed so every runner generation builds.\n file('pnpm-workspace.yaml', renderPnpmWorkspaceYaml(), 'Add pnpm settings'),\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/handlers/AGENTS.md', HANDLERS_AGENTS_MD, 'Add handler docs'),\n symlink('agents/handlers/CLAUDE.md', 'AGENTS.md', 'Add Claude handler 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/providers/AGENTS.md', PROVIDERS_AGENTS_MD, 'Add provider docs'),\n symlink('agents/providers/CLAUDE.md', 'AGENTS.md', 'Add Claude provider 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 file('agents/users/AGENTS.md', USERS_AGENTS_MD, 'Add user endpoint docs'),\n symlink('agents/users/CLAUDE.md', 'AGENTS.md', 'Add Claude user endpoint 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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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