@standardagents/agentbuilder-template 0.45.1 → 0.45.3
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 +49 -12
- package/dist/index.js +1427 -1658
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -1,22 +1,48 @@
|
|
|
1
|
-
declare const ROOT_AGENTS_MD = "# Standard Agents\n\nThis project uses Standard Agents - a framework for building AI agents on Cloudflare Workers.\n\n## Architecture Overview\n\nStandard Agents uses a **composition model** where four core components work together:\n\n```\nModel \u2192 Prompt \u2192 Agent \u2192 Thread\n \u2502 \u2502 \u2502 \u2502\n \u2502 \u2502 \u2502 \u2514\u2500 Conversation instance (Durable Object)\n \u2502 \u2502 \u2514\u2500 Orchestrates conversation flow\n \u2502 \u2514\u2500 System instructions + tools\n \u2514\u2500 LLM provider configuration\n```\n\n**Models** define which LLM to use (provider, model ID, pricing, fallbacks).\n**Prompts** define what the LLM should do (system instructions, available tools).\n**Agents** orchestrate conversations. An agent has exactly two sides; each side is backed by a human (`{ human: true }`), a prompt (`{ prompt: 'name' }`), or a handler (`{ handler: 'name' }` \u2014 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## Packaging and Definition Visibility\n\nThe packer follows side `subagents` relationships and includes child agents\nand their dependencies. This includes hidden children and relationships with\n`as`. The package includes referenced handlers and exports a `handlers`\nregistry. The pack and unpack dialogs list handlers. Unpack analysis reports an agent\u2019s handlers and side `subagents` relationships.\nIn the pack dialog, a handler defaults to extract. Shared handlers default to copy. Extract removes\nthe local file; copy keeps it. Dependencies reached by another local agent,\nincluding through its children, default to copy.\n\nThe runtime discovers packages in `node_modules` and `agents/packed/`.\nIt loads definitions from lazy registries and `__meta` exported by each\npackage entry module. A malformed `package.json` or missing or invalid\n`__meta` produces a warning and the runtime skips that package.\n\n`ThreadState.loadModel`, `loadPrompt`, and `loadAgent` enforce package\nvisibility. Global code can load unpacked definitions and packed entry agents.\nPacked code can load its own definitions and other packages' entry agents.\nA packed model cannot fall back to a host model with the same short name.\nA refused load returns the same not-found error as a missing definition.\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\npnpm-workspace.yaml # Dependency script approvals for pnpm projects\nagents/\n\u251C\u2500\u2500 agents/ # Agent definitions (defineAgent)\n\u2502 \u251C\u2500\u2500 AGENTS.md\n\u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n\u251C\u2500\u2500 prompts/ # Prompt definitions (definePrompt)\n\u2502 \u251C\u2500\u2500 AGENTS.md\n\u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n\u251C\u2500\u2500 handlers/ # Handler definitions (defineHandler)\n\u2502 \u251C\u2500\u2500 AGENTS.md\n\u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n\u251C\u2500\u2500 models/ # Model configurations (defineModel)\n\u2502 \u251C\u2500\u2500 AGENTS.md\n\u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n\u251C\u2500\u2500 providers/ # Provider definitions (defineProvider)\n\u2502 \u251C\u2500\u2500 AGENTS.md\n\u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n\u251C\u2500\u2500 tools/ # Custom tools (defineTool)\n\u2502 \u251C\u2500\u2500 AGENTS.md\n\u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n\u251C\u2500\u2500 hooks/ # Lifecycle hooks (defineHook)\n\u2502 \u251C\u2500\u2500 AGENTS.md\n\u2502 \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n\u2514\u2500\u2500 api/ # Thread API endpoints (defineThreadEndpoint)\n \u251C\u2500\u2500 AGENTS.md\n \u2514\u2500\u2500 CLAUDE.md -> AGENTS.md\n```\n\nThe `builder()` Vite plugin generates the Worker entry, Durable Object bindings, Cloudflare Vite plugin configuration, and local `.agents/` support files at build time. Agent files are **auto-discovered** at runtime. No manual registration needed.\n\nStandalone local pnpm init approves `esbuild` and `workerd` before installing dependencies.\nThe project policy lives in `pnpm-workspace.yaml`.\nThe manifest also declares `pnpm.onlyBuiltDependencies` for pnpm 10.\nThe YAML declares the project root for pnpm 9 compatibility.\nWith pnpm 9 or pnpm 10 before 10.6, `pnpm add --workspace-root <package>` targets that project root.\npnpm 11 may warn that the legacy manifest field is ignored.\nThe YAML supplies its build approvals.\nAn existing project policy is preserved.\nLocal OpenRouter setup explicitly denies the SDK's optional model-type check.\nThat checker writes no runtime artifacts.\nThe CLI detects unsupported legacy layouts with pnpm's parser.\nThose layouts use `--ignore-workspace` during installation and foreground startup.\nSupported layouts retain their YAML build approvals.\nAn enclosing pnpm workspace retains its policy and installation boundary.\nContributor `--workspace` projects use their own policy boundary.\nThe generated policy exempts `@standardagents/*` from `minimumReleaseAge`.\nThat exemption permits installation on the release day.\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, newest first by default\n getMessage(id): Promise<Message | null>; // Find a persisted message by ID\n updateMessage(id, updates): Promise<Message>; // Update a persisted message\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 status(): Promise<ThreadStatus>; // Run status { state: 'idle'|'running'|'failed', since, reason }\n log(entry): Promise<void>; // App log row { name, message?, level?, status?, trigger?, request?, response?, error?, duration_ms?, cost?, data? }; no message, no execution\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`state.status()` returns the authoritative run status. `reason` is the raw\nstop code of the last run (`stop_on_response`, `awaiting_human`,\n`hook_blocked`, `step_error`, \u2026); a run that handed the turn to a human\nside is `idle`. Clients get the same value from `GET /api/threads/:id`\n(`status`) and from `thread_status` stream frames (snapshot on connect, then\neach change), so never poll for it. It is unrelated to `setStatus()`.\n\n`state.log({ name, message, level, status, trigger, request, response, error, duration_ms, cost, data })`\nrecords an application log row (`kind: 'app'`) shown with the thread's logs;\nonly `name` is required. For an operation, record its outcome (`status`:\nsuccess | error | skipped), what caused it (`trigger: { kind, id?, summary? }`),\nwhat was sent (`request`), what came back (`response` or `error`), and its\n`duration_ms` and `cost` (USD; counted in the thread's cost totals). It never creates a message or starts\nexecution; oversized fields are truncated (name 120 chars, message and error\n4 KiB, data JSON 16 KiB, request and response JSON 64 KiB each).\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` forwards functions in imports, globals, and execution arguments as callable proxies. Call `run.terminate(reason)` to stop the sandbox. A caller disconnect also stops the run. When `report` is supplied, the host receives reports during the run and `run.reports` updates as reports arrive.\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\u2192child 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";
|
|
1
|
+
declare const ROOT_AGENTS_MD = "# Building agents in this project\n\nThis project builds AI agents with Standard Agents. You define agents as TypeScript files under `agents/`. The framework discovers them, runs them, and serves a builder UI for testing them. There is no registration step and no Cloudflare configuration to write.\n\nEach directory under `agents/` has its own `AGENTS.md` with the full reference for that kind of file. This file covers what the pieces are, the agent the project starts with, and how to build your own.\n\n## The pieces\n\n```text\nModel -> Prompt -> Agent -> Thread\n```\n\n- A **model** names an LLM and the provider that serves it.\n- A **prompt** holds system instructions, picks a model, and lists the tools the model may call.\n- An **agent** is a conversation between two sides. Each side is a person (`{ human: true }`), a prompt (`{ prompt: 'name' }`), or a handler (`{ handler: 'name' }`, plain code).\n- A **thread** is one running conversation with an agent. It has its own message history, files, and key-value store.\n\n| Function | What it defines | Directory |\n|----------|-----------------|-----------|\n| `defineModel()` | An LLM and its provider | `agents/models/` |\n| `defineProvider()` | A custom provider endpoint | `agents/providers/` |\n| `definePrompt()` | Instructions, model, and tools | `agents/prompts/` |\n| `defineAgent()` | The two sides of a conversation | `agents/agents/` |\n| `defineTool()` | A function the model can call | `agents/tools/` |\n| `defineHook()` | Code that runs at lifecycle points | `agents/hooks/` |\n| `defineHandler()` | Code that takes a side's turns | `agents/handlers/` |\n| `defineThreadEndpoint()` | An HTTP route on a thread | `agents/api/` |\n| `defineUserEndpoint()` | An HTTP route on a user | `agents/users/` |\n\nImport `defineThreadEndpoint` and `defineUserEndpoint` from `@standardagents/spec`. Import the rest from `@standardagents/builder`.\n\n## The starter agent\n\nA project created through the Standard Agents platform starts with one working agent, **Guide**. It answers questions about building agents and about the Standard Agent Specification. Run the project, choose **Guide**, and send a message; it needs no file edits and no provider key.\n\n| File | What it is |\n|------|------------|\n| `agents/agents/guide_agent.ts` | The agent `guide_agent`: the prompt `guide` on one side, a person on the other |\n| `agents/prompts/guide.ts` | The prompt `guide`: its instructions, the model `low_cost`, and the tool `read_docs` |\n| `agents/models/low_cost.ts` | The model `low_cost`: a low-cost open model served by Novita AI, paid for by the platform account key |\n| `agents/tools/read_docs.ts` | The tool `read_docs`: reads a page from the builder documentation or the specification site, and no other site |\n\nGuide reads the published documentation each time it answers, so it stays current without a code change. It cannot read or change the files in this project.\n\nThese four are ordinary definition files. Read them as a working example, change them, or delete them once the project has its own agents. Before deleting `agents/models/low_cost.ts` or `agents/tools/read_docs.ts`, check that no other prompt uses them. If a project does not have these files, nothing else depends on them.\n\n## Build your first agent\n\nA working agent needs three files: a model, a prompt that uses it, and an agent that uses the prompt. Create them as written.\n\n```typescript\n// agents/models/default.ts\nimport { defineModel } from '@standardagents/builder';\nimport { openai } from '@standardagents/openai';\n\nexport default defineModel({\n name: 'default',\n provider: openai,\n model: 'gpt-5.4-mini',\n});\n```\n\n```typescript\n// agents/prompts/assistant.ts\nimport { definePrompt } from '@standardagents/builder';\n\nexport default definePrompt({\n name: 'assistant',\n toolDescription: 'A general-purpose assistant',\n model: 'default',\n prompt: 'You are a helpful assistant. Answer clearly and briefly.',\n includeChat: true,\n});\n```\n\n```typescript\n// agents/agents/assistant_agent.ts\nimport { defineAgent } from '@standardagents/builder';\n\nexport default defineAgent({\n name: 'assistant_agent',\n title: 'Assistant',\n description: 'Answers questions in a chat.',\n sideA: { label: 'Assistant', prompt: 'assistant' },\n sideB: { label: 'You', human: true },\n});\n```\n\nThen run the project and talk to the agent:\n\n```bash\npnpm dev\n```\n\nOpen `http://localhost:5173`, sign in with your Standard Agents account, choose **Assistant**, and send a message. A project with no account link signs in with the `SUPER_ADMIN_PASSWORD` set in `.dev.vars` instead. Use the package manager whose lockfile is in the project (`npm run dev`, `yarn dev`, or `bun run dev` work the same way). If port 5173 is in use, the dev server takes the next free port and prints its address.\n\nNew and changed files under `agents/` load without a restart. Restart the dev server after you install a package or change `.dev.vars`.\n\n## Model access and keys\n\nThis project is linked to a Standard Agents platform account. The CLI wrote that account's key to `.dev.vars` as `STANDARD_AGENTS_API_KEY`, and deployed projects receive it automatically. The key covers every provider package this project installs, so the example above runs without any provider account:\n\n| Provider | Package | Import |\n|----------|---------|--------|\n| OpenAI | `@standardagents/openai` | `openai` |\n| Anthropic | `@standardagents/anthropic` | `anthropic` |\n| Google | `@standardagents/google` | `google` |\n| OpenRouter | `@standardagents/openrouter` | `openrouter` |\n| xAI | `@standardagents/xai` | `xai` |\n| Groq | `@standardagents/groq` | `groq` |\n| Cerebras | `@standardagents/cerebras` | `cerebras` |\n| DeepInfra | `@standardagents/deepinfra` | `deepinfra` |\n| Novita AI | `@standardagents/novita` | `novita` |\n| Cloudflare Workers AI | `@standardagents/cloudflare` | `cloudflare` |\n\nUsage through the platform key is billed to the platform account. To use your own provider account, set that provider's key in `.dev.vars`; see `agents/models/AGENTS.md`. A project without `STANDARD_AGENTS_API_KEY` needs a provider key for each provider it uses.\n\nNever guess a model ID. Take it from the provider's published model list, or from the current model guide:\n\n```bash\nnpx @standardagents/cli@latest current-models\n```\n\n`.dev.vars` holds secrets and is ignored by Git. Do not commit it or copy its values into source files.\n\n## Check your work\n\n- `pnpm typecheck` reports type errors in definition files.\n- The dev server terminal prints `Failed to import <kind> <name>` when a definition file cannot load.\n- The builder UI shows the same failure in a banner at the top of the page. A model, prompt, or agent that fails to load is missing from its list until the file is fixed.\n- A `Cannot find module` failure names a package that is not installed. Add it with the project's package manager, then restart the dev server.\n- Each thread in the builder UI has a Logs tab with every model request, tool call, and error.\n\n## Project layout\n\n```text\nAGENTS.md This guide\nCLAUDE.md -> AGENTS.md The same file, for tools that read CLAUDE.md\npackage.json Dependencies; the project owns its versions\nvite.config.ts Loads the builder() plugin\ntsconfig.json\npnpm-workspace.yaml pnpm settings for this project\n.dev.vars Local secrets (not committed)\nagents/\n\u251C\u2500\u2500 agents/ Agent definitions; starts with guide_agent.ts\n\u251C\u2500\u2500 prompts/ Prompt definitions; starts with guide.ts\n\u251C\u2500\u2500 models/ Model definitions; starts with low_cost.ts\n\u251C\u2500\u2500 providers/ Custom provider definitions\n\u251C\u2500\u2500 tools/ Tools the model can call; starts with read_docs.ts\n\u251C\u2500\u2500 hooks/ Lifecycle hooks\n\u251C\u2500\u2500 handlers/ Code-backed sides\n\u251C\u2500\u2500 api/ Thread HTTP endpoints\n\u2514\u2500\u2500 users/ User HTTP endpoints\n```\n\nEvery directory under `agents/` contains an `AGENTS.md` and a `CLAUDE.md` link to it. The `builder()` plugin generates the Worker entry, the Cloudflare configuration, and the `.agents/` type files. Do not add a Wrangler config, a Worker entry file, or the Cloudflare Vite plugin.\n\n## Naming\n\n- A model, prompt, or agent is named by its `name` field. Keep the file name the same.\n- A tool or handler is named by its file name: `agents/tools/search_docs.ts` is the tool `search_docs`.\n- A hook is named by its `id` field.\n- Use `snake_case` for all of these. End agent names with `_agent`.\n- A tool, a prompt, and an agent exposed as a tool share one namespace. Give them different names.\n\n## Composing agents\n\nA prompt's `tools` array can hold three kinds of names:\n\n- A tool from `agents/tools/`.\n- Another prompt. The model calls it as a tool and gets its answer back. Use this for one focused model step, such as extraction or rewriting.\n- An agent with `exposeAsTool: true`. Calling it hands the same thread to that agent.\n\nAn agent side can also declare `subagents`. Each subagent runs in its own thread, and the parent starts and messages it with built-in tools. Use a subagent for work that takes several steps or needs its own review loop. See `agents/agents/AGENTS.md`.\n\nPrefer several small agents with a few tools each over one agent with many tools. Models choose tools more reliably from a short list.\n\n## ThreadState\n\nTools, hooks, handlers, and thread endpoints receive a `ThreadState` for the thread they run in. The members used most:\n\n```text\nstate.threadId, state.agentId, state.userId Identity\nstate.arguments Arguments the thread was created with\nstate.getMessages({ limit, offset, order }) Message history: { messages, total, hasMore }\nstate.injectMessage({ role, content }) Add a message to the thread\nstate.queueMessage({ role, content }) Send a message that starts a turn\nstate.getValue(key) / state.setValue(key, v) Durable JSON values for this thread\nstate.env(name) / state.setEnv(name, value) Thread variables\nstate.readFile / writeFile / findFiles ... The thread's file system\nstate.queueTool(name, args) Run another tool after this one\nstate.invokeTool(name, args) Run another tool and wait for its result\nstate.emit(event, data) Send a live event to connected clients\nstate.user() The thread's user, or null\nstate.children / state.getChildThread(ref) Subagent threads\nstate.stopSession({ result }) End the current session\nstate.runCode(source, options) Run JavaScript or TypeScript in a sandbox\nstate.execution The running turn, or null when the thread is at rest\n```\n\n`agents/tools/AGENTS.md` shows these in use. The full type is `ThreadState` in `@standardagents/spec`.\n\n## Development from another machine\n\nThe `dev` script binds the dev server to `127.0.0.1`, so other machines cannot reach it. Keep it that way: `.dev.vars` holds a live account key.\n\nTo work from another machine, forward a hostname you trust to the local port, for example through an SSH tunnel or a private reverse proxy. Then list that exact hostname for both Vite and the builder:\n\n```typescript\n// vite.config.ts\nimport { defineConfig } from 'vite';\nimport { builder } from '@standardagents/builder';\n\nconst devHost = 'dev-machine.example.com';\n\nexport default defineConfig({\n plugins: [builder({ trustedDevHosts: [devHost] })],\n server: { allowedHosts: [devHost] },\n});\n```\n\nAnyone who can reach the dev server through a listed hostname can attempt to sign in to it. `trustedDevHosts` rejects wildcards, schemes, ports, and paths, and has no effect on a deployed project.\n\n## Deploy\n\nOn a plan that includes deployment, the platform builds and deploys this project each time you push a commit:\n\n```bash\ngit push\n```\n\n`npx @standardagents/cli@latest deploy` does the same push. The local `build` script stops with a message on purpose: builds run on the platform, from the committed `package.json` and lockfile. Commit both.\n\n## More documentation\n\n- Reference for each definition type: the `AGENTS.md` in its directory.\n- Guides and API reference: https://docs.standardagentbuilder.com\n- For coding agents, a longer design guide: `npx @standardagents/cli@latest skill`\n";
|
|
2
2
|
|
|
3
|
-
declare const MODELS_AGENTS_MD = "# Model
|
|
3
|
+
declare const MODELS_AGENTS_MD = "# Model definitions\n\nA model definition names an LLM and the provider that serves it. Prompts refer to a model by its `name`.\n\n## Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `name` | `string` | Yes | The name prompts use to select this model |\n| `provider` | provider import | Yes | A provider imported from its package, or a provider from `agents/providers/` |\n| `model` | `string` | Yes | The model ID the provider expects |\n| `fallbacks` | `string[]` | No | Names of other models in this project to try when this one fails |\n| `inputPrice` | `number` | No | USD per 1M input tokens, for cost tracking |\n| `outputPrice` | `number` | No | USD per 1M output tokens |\n| `cachedPrice` | `number` | No | USD per 1M cached input tokens |\n| `includedProviders` | `string[]` | No | OpenRouter only: upstream providers to prefer |\n| `providerTools` | `string[]` | No | Provider-run tools this model offers to prompts |\n| `providerOptions` | `object` | No | Default request options for this provider |\n| `capabilities` | `object` | No | Overrides for what the model supports |\n\n## A first model\n\n```typescript\n// agents/models/fast.ts\nimport { defineModel } from '@standardagents/builder';\nimport { openai } from '@standardagents/openai';\n\nexport default defineModel({\n name: 'fast',\n provider: openai,\n model: 'gpt-5.4-nano',\n});\n```\n\nThis works in a platform-linked project as written. The project already installs `@standardagents/openai`, and the platform key in `.dev.vars` pays for the request.\n\n## Providers this project has\n\n`package.json` lists every provider package below as a dependency, so each import resolves without an install step.\n\n| Provider | Package | Import | Your own key |\n|----------|---------|--------|--------------|\n| OpenAI | `@standardagents/openai` | `openai` | `OPENAI_API_KEY` |\n| Anthropic | `@standardagents/anthropic` | `anthropic` | `ANTHROPIC_API_KEY` |\n| Google | `@standardagents/google` | `google` | `GOOGLE_API_KEY` |\n| OpenRouter | `@standardagents/openrouter` | `openrouter` | `OPENROUTER_API_KEY` |\n| xAI | `@standardagents/xai` | `xai` | `XAI_API_KEY` |\n| Groq | `@standardagents/groq` | `groq` | `GROQ_API_KEY` |\n| Cerebras | `@standardagents/cerebras` | `cerebras` | `CEREBRAS_API_KEY` |\n| DeepInfra | `@standardagents/deepinfra` | `deepinfra` | `DEEPINFRA_API_KEY` |\n| Novita AI | `@standardagents/novita` | `novita` | `NOVITA_API_KEY` |\n| Cloudflare Workers AI | `@standardagents/cloudflare` | `cloudflare` | `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` |\n\nIf `package.json` does not list a provider package, add it with the project's package manager (for example `pnpm add @standardagents/openai`) and restart the dev server. A model whose provider package is missing fails with `Cannot find module`, and the builder UI shows that failure in a banner.\n\n## Keys\n\nThe project needs no provider account. When no key is set for a provider, requests to it use `STANDARD_AGENTS_API_KEY`, the platform account key that the CLI wrote to `.dev.vars`. The platform bills that usage to the account.\n\nTo use your own provider account, set the variable from the last column of the table in `.dev.vars`. A provider key always takes precedence over the platform key for that provider. For a deployed project, set the same variable in the project's settings on the platform.\n\nA provider you define in `agents/providers/` always uses its own key. The platform key does not cover it.\n\nA model whose provider has no key fails its run. The thread transcript names the variable to set and where to set it, and the Providers page in the builder UI marks the provider \"Not configured\". A missing key is not retried on the same model; fallback models on other providers still run. For other failures, the transcript shows the kind of failure and the thread's Logs tab holds the full error.\n\n## Choosing a model ID\n\nModel IDs change often. Take them from the provider's published model list instead of writing them from memory. Two commands help:\n\n```bash\nnpx @standardagents/cli@latest current-models\nnpx @standardagents/cli@latest available-models --provider=openai\n```\n\nThe first prints a current guide to which models suit which work. The second lists every ID a provider serves, and needs that provider's own key in `.dev.vars`; the platform key alone is not enough for it.\n\nOpenRouter IDs include the lab, such as `google/gemini-2.5-flash`. Other providers use the lab's own ID, such as `gpt-5.4-mini`.\n\n## Fallbacks\n\n`fallbacks` names other models defined in this project. Each must exist in `agents/models/`.\n\n```typescript\n// agents/models/reliable.ts\nimport { defineModel } from '@standardagents/builder';\nimport { openrouter } from '@standardagents/openrouter';\n\nexport default defineModel({\n name: 'reliable',\n provider: openrouter,\n model: 'google/gemini-2.5-flash',\n fallbacks: ['fast'],\n});\n```\n\nA failed request is retried once on the same model, then each fallback is tried in order with the same two attempts. Network errors, rate limits (429), server errors (5xx), and authentication errors (401) trigger a retry.\n\n## Provider tools\n\nSome providers run tools on their own servers, such as web search. List the ones a model should offer in `providerTools`. A prompt that uses the model can then put those names in its `tools`.\n\n```typescript\n// agents/models/researcher.ts\nimport { defineModel } from '@standardagents/builder';\nimport { openrouter } from '@standardagents/openrouter';\n\nexport default defineModel({\n name: 'researcher',\n provider: openrouter,\n model: 'google/gemini-2.5-flash',\n providerTools: ['web_search', 'web_fetch'],\n});\n```\n\nOpenRouter offers `web_search`, `web_fetch`, `datetime`, and `image_generation`. Provider tools run at the provider, and their calls appear in the thread's logs.\n\n## Custom providers\n\nTo reach an API that is compatible with an installed provider package but has its own endpoint and key, define a provider in `agents/providers/` and import it here. See `agents/providers/AGENTS.md`.\n\n## Practices\n\n- Name a model for its job (`fast`, `default`, `researcher`), so a prompt does not change when the model ID does.\n- Set `inputPrice` and `outputPrice` for a custom or private model. First-party providers report cost for the models they list.\n- Keep keys in `.dev.vars` and in platform settings. Never write a key in a source file.\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/model\n";
|
|
4
4
|
|
|
5
|
-
declare const PROVIDERS_AGENTS_MD = "# Provider
|
|
5
|
+
declare const PROVIDERS_AGENTS_MD = "# Provider definitions\n\nMost projects never need this directory. The provider packages listed in `agents/models/AGENTS.md` already cover the major model providers.\n\nDefine a provider when an API is compatible with one of those packages but has its own endpoint, key, or behavior. A provider definition wraps a base provider package with different connection settings.\n\n## Example\n\n```typescript\n// agents/providers/acme.ts\nimport { defineProvider, providerEnv, providerValue } from '@standardagents/builder';\nimport { openai } from '@standardagents/openai';\n\nexport default defineProvider({\n name: 'acme',\n label: 'Acme AI',\n baseProvider: openai,\n config: {\n apiKey: providerEnv('ACME_API_KEY', {\n valueType: 'secret',\n required: true,\n description: 'Acme AI API key.',\n }),\n baseUrl: providerValue('https://api.acme.example/v1'),\n },\n});\n```\n\nA model imports the provider as a default import:\n\n```typescript\n// agents/models/acme_chat.ts\nimport { defineModel } from '@standardagents/builder';\nimport acme from '../providers/acme';\n\nexport default defineModel({\n name: 'acme_chat',\n provider: acme,\n model: 'acme-chat-1',\n});\n```\n\nReplace the endpoint, the model ID, and the variable name with the real ones for the API you are connecting. Set `ACME_API_KEY` in `.dev.vars` for local work and in the project's platform settings for a deployed project.\n\n## Configuration values\n\n- `providerEnv(name, options)` reads a variable at run time. Use it for keys and for values that differ between environments. `options` accepts `valueType` (`'secret'`, `'url'`, or `'text'`), `required`, `default`, and `description`.\n- `providerValue(value)` is a constant written in the file. Never use it for a key.\n\nA custom provider always uses the key it declares. The platform account key does not cover it.\n\n## Overrides\n\n`overrides` can replace or wrap methods of the base provider, such as `getModels`, `getIcon`, `getTools`, `generate`, and `stream`. Inside an override, call `next()` to run the base provider's version and return your own value to replace it.\n\nWhen an override catches an upstream failure and rethrows it, throw a `ProviderError` from `@standardagents/builder` so the thread's logs name the failing service:\n\n```text\nthrow new ProviderError(message, 'server_error', status, retryAfter, {\n cause: error,\n origin: 'provider:acme',\n upstream: 'acme-backend',\n});\n```\n\n`origin` identifies the provider as `provider:<name>`. `upstream` names the backend when it differs from the provider.\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/model\n";
|
|
6
6
|
|
|
7
|
-
declare const PROMPTS_AGENTS_MD = "# Prompt Definitions\n\nPrompts define system instructions, model selection, and available tools for LLM interactions.\n\n## Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `name` | `string` | Yes | Unique identifier for this prompt |\n| `toolDescription` | `string` | Yes | Description shown when used as a tool |\n| `prompt` | `string \\| StructuredPrompt` | Yes | System instructions |\n| `model` | `string` | Yes | Model name to use (references `agents/models/`) |\n| `tools` | `(string \\| ToolConfig)[]` | No | Available tools: tool names, sub-prompt names, provider tools, and exposed agent names for handoffs. Subagent relationships never appear here \u2014 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| `historyLimit` | `number` | No | With `includeChat`, load only the newest top-level messages: at least N and under 2N, the cut moving N at a time (prompt-cache stable). Execution history and `filter_messages` see only that window; stored history is untouched |\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| `providerOptions` | `Record<string, unknown>` | No | Provider-specific request options |\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\nA circular prompt include raises an error that names the include chain. A prompt can include the same partial through different paths.\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` \u2014 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` \u2014 creates (or continues) an instance. Its `agent` argument enumerates the side's enabled relationship *names* (`as`, defaulting to the unqualified part of `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` \u2014 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\n`subagent_create` accepts `agent`, `name`, and `arguments`.\nThe relationship maps its initial message and attachments from `arguments`.\nCreate-or-continue applies the same mappings to the existing child.\nWithout a mapped message value, Builder uses the optional top-level `message` before falling back to serialized arguments.\nEmpty arguments produce the JSON activation payload {}.\nThe relationship contributes missing message and attachment fields to the model-facing argument schema.\nThe model-facing schema and runtime accept optional top-level `message` and `attachments`.\nThese fields are AgentBuilder extensions beyond Spec 0.2.0 Subagents \u00A75 for existing callers such as Standard Code Mux.\nRelationships should migrate to `initUserMessageProperty` and mapped `arguments`.\nStrict providers may require these keys on the wire with null values to omit them.\nMapped arguments take precedence over these compatibility fields.\nRelationship-only fields initialize messages without becoming persistent child arguments.\n\nPersistence is universal: every child instance is a persistent thread. Session end never terminates a child \u2014 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\nBlocking creation and continuation return the session result through the tool result.\nThat session has no implicit completion message.\nCreate-or-continue acquires child execution before persisting its input.\nAdmission failure leaves the continuation input unsent.\nA separate `subagent_message` activation retains implicit delivery under `parentCommunication: 'implicit'`.\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\nProvider options merge from model defaults to prompt overrides. Later values win.\n\n## Extended Thinking (Reasoning)\n\nA prompt can set `reasoning.level` from 0 to 100. An unset level uses the model's default. Level 0 disables reasoning when the model supports a disabling control. Otherwise, the provider selects the lowest reasoning setting. A model with no reasoning control receives no control. Each provider maps the level to the nearest option the model declares.\n\nA prompt's `reasoning.level` replaces a native effort value in `providerOptions`. Other `providerOptions` keys remain. Without a level, `providerOptions` apply as provided. Native effort values in a model's `providerOptions` remain valid.\n\nSaved prompt input with `reasoning.effort` fails validation. A published package prompt with `reasoning.effort` loads with a warning. The runtime ignores that field.\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 level: 100, // 0 to 100\n maxTokens: 16000, // Max thinking tokens\n exclude: true, // Don't include thinking in response\n },\n});\n```\n\n**\u26A0\uFE0F Google Models Require Reasoning**: When using Google models (`google/gemini-*`) via OpenRouter, you **must** include `reasoning` configuration or tool calls will fail. At minimum:\n\n```typescript\nreasoning: {\n level: 33, // 0 to 100\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";
|
|
7
|
+
declare const PROMPTS_AGENTS_MD = "# Prompt definitions\n\nA prompt holds the system instructions for a model, selects the model, and lists the tools the model may call. An agent side that is backed by a prompt runs it on every turn.\n\n## Properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `name` | `string` | Yes | The name agents and other prompts use to refer to this prompt |\n| `toolDescription` | `string` | Yes | What this prompt does. Shown to a model that can call it as a tool |\n| `prompt` | `string` or parts array | Yes | The system instructions |\n| `model` | `string` | Yes | The `name` of a model in `agents/models/` |\n| `tools` | array | No | Names of tools, other prompts, provider tools, and agents exposed as tools |\n| `includeChat` | `boolean` | No | Send the conversation history with each request. Default `false` |\n| `includePastTools` | `boolean` | No | Send earlier tool calls and their results with each request. Default `false` |\n| `historyLimit` | `number` | No | With `includeChat`, send only the newest messages: at least this many and fewer than twice as many |\n| `parallelToolCalls` | `boolean` | No | Let the model call several tools in one step. Default `false` |\n| `toolChoice` | `'auto'`, `'none'`, or `'required'` | No | Whether the model may, must not, or must call a tool |\n| `requiredSchema` | Zod object | No | Arguments this prompt takes when it is called as a tool or started as a subagent |\n| `variables` | array | No | Variables this prompt needs: `name`, `type`, `required`, `scoped`, `description` |\n| `env` | `Record<string, string>` | No | Default values for variables |\n| `hooks` | `string[]` | No | Hook IDs to run for this prompt. Replaces the agent's hooks |\n| `reasoning` | `object` | No | Reasoning settings: `level`, `maxTokens`, `exclude` |\n| `providerOptions` | `object` | No | Request options for the model's provider |\n\n## A prompt with tools\n\n```typescript\n// agents/prompts/customer_support.ts\nimport { definePrompt } from '@standardagents/builder';\n\nexport default definePrompt({\n name: 'customer_support',\n toolDescription: 'Answer customer support questions',\n model: 'default',\n prompt: `You are a customer support agent for an online store.\n\nSearch the knowledge base before you answer a product question.\nIf the knowledge base does not cover the question, create a ticket and tell the customer a person will follow up.\nWhen the customer confirms the issue is resolved, close the conversation with a one-sentence summary.`,\n tools: ['search_knowledge_base', 'create_ticket', 'close_conversation'],\n includeChat: true,\n includePastTools: true,\n});\n```\n\nThe model `default` is defined in the root `AGENTS.md`. The three tools are defined in `agents/tools/AGENTS.md`.\n\n## History settings\n\nA prompt sees only its system instructions and the newest message unless you turn history on.\n\n- Set `includeChat: true` for any prompt that holds a conversation.\n- Set `includePastTools: true` when the model must read a tool's result to continue, which is the usual case for a prompt with tools. Without it, each request omits earlier tool calls and results, and the model may repeat a call until it reaches its step limit.\n- Leave `includePastTools` off when the tools only cause side effects or when their output is large or sensitive.\n\n## Reusing instructions\n\n`prompt` can be an array of parts. An `include` part inserts another prompt's instructions. An `env` part inserts the value of a variable.\n\n```typescript\n// agents/prompts/house_rules.ts\nimport { definePrompt } from '@standardagents/builder';\n\nexport default definePrompt({\n name: 'house_rules',\n toolDescription: 'Shared rules for every customer-facing prompt',\n model: 'default',\n prompt: 'Never share one customer\\'s information with another. Never promise a refund; create a ticket instead.',\n});\n```\n\n```typescript\n// agents/prompts/billing_support.ts\nimport { definePrompt } from '@standardagents/builder';\n\nexport default definePrompt({\n name: 'billing_support',\n toolDescription: 'Answer billing questions',\n model: 'default',\n prompt: [\n { type: 'text', content: 'You answer billing questions for an online store.\\n\\n' },\n { type: 'include', prompt: 'house_rules' },\n { type: 'text', content: '\\n\\nReply in this tone: ' },\n { type: 'env', property: 'SUPPORT_TONE' },\n ],\n variables: [\n { name: 'SUPPORT_TONE', type: 'text', required: false, scoped: false, description: 'Tone of voice for replies' },\n ],\n env: { SUPPORT_TONE: 'friendly and brief' },\n tools: ['create_ticket'],\n includeChat: true,\n includePastTools: true,\n});\n```\n\nAn `env` part puts the value in front of the model. Use it only for values that are safe for the model and the user to see. A prompt that includes itself, directly or through another prompt, fails to load with an error that names the chain.\n\n## Prompts as tools\n\nAny prompt can be listed in another prompt's `tools`. The calling model sees `toolDescription` and the arguments in `requiredSchema`, and gets the prompt's answer as the tool result. The called prompt runs once, with its own instructions and model.\n\n```typescript\n// agents/prompts/order_extractor.ts\nimport { definePrompt } from '@standardagents/builder';\nimport { z } from 'zod';\n\nexport default definePrompt({\n name: 'order_extractor',\n toolDescription: 'Extract the order number and the problem from a customer message',\n model: 'default',\n prompt: 'Extract the order number and a one-sentence description of the problem. Reply with JSON: {\"orderNumber\": string | null, \"problem\": string}.',\n requiredSchema: z.object({\n message: z.string().describe('The customer message to read'),\n }),\n});\n```\n\n```typescript\n// agents/prompts/returns_support.ts\nimport { definePrompt } from '@standardagents/builder';\n\nexport default definePrompt({\n name: 'returns_support',\n toolDescription: 'Handle return requests',\n model: 'default',\n prompt: 'You handle return requests. Use order_extractor on the first message, then create a ticket for the return.',\n tools: [\n { name: 'order_extractor', includeTextResponse: true, initUserMessageProperty: 'message' },\n 'create_ticket',\n ],\n includeChat: true,\n includePastTools: true,\n});\n```\n\nThe object form configures a prompt used as a tool:\n\n| Option | Meaning |\n|--------|---------|\n| `includeTextResponse` | Return the prompt's text answer in the tool result |\n| `includeToolCalls` | Return the tool calls the prompt made |\n| `includeErrors` | Return errors the prompt hit |\n| `initUserMessageProperty` | The argument to send as the prompt's user message |\n| `initAttachmentsProperty` | The argument that holds file paths to attach |\n\n## Other entries in `tools`\n\n- **Provider tools.** When the prompt's model lists `providerTools`, put those names in `tools`. See `agents/models/AGENTS.md`.\n- **Agents.** An agent with `exposeAsTool: true` can be listed by name. Calling it hands the thread to that agent.\n- **Subagents are not listed here.** They are declared on the agent side, in `subagents`. For a prompt on such a side, the runtime adds three tools itself: `subagents`, `subagent_create`, and `subagent_message`. See `agents/agents/AGENTS.md`.\n\n## Reasoning\n\n`reasoning.level` runs from 0 to 100. Each provider maps it to the nearest setting the model has. Leave it unset to use the model's default. Level 0 turns reasoning off when the model allows that.\n\n```typescript\n// agents/prompts/escalation_review.ts\nimport { definePrompt } from '@standardagents/builder';\n\nexport default definePrompt({\n name: 'escalation_review',\n toolDescription: 'Decide whether a support conversation needs a manager',\n model: 'default',\n prompt: 'Read the conversation and decide whether a manager must step in. Answer \"escalate\" or \"continue\" with one sentence of reasoning.',\n includeChat: true,\n reasoning: {\n level: 66,\n exclude: true,\n },\n});\n```\n\n`exclude: true` keeps the reasoning text out of the reply. `maxTokens` caps reasoning tokens for models that take a budget. Do not set `reasoning.effort`; it is rejected.\n\nGoogle models reached through OpenRouter (`google/gemini-*`) need a reasoning level before they call tools reliably. Set `reasoning: { level: 33 }` or higher on a prompt that gives one of those models tools.\n\n## Hooks\n\n`hooks` lists hook IDs from `agents/hooks/` that run for this prompt. When a prompt lists hooks, the agent's hooks do not run for it. See `agents/hooks/AGENTS.md`.\n\n## Practices\n\n- Write instructions for the realistic cases, including what to do when a tool fails or the answer is unknown.\n- Tell the model when to use each tool. The model decides from the tool's description and your instructions.\n- Name a prompt for its job (`customer_support`), not its model.\n- Keep one job per prompt. Give a second job to a second prompt and call it as a tool.\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/prompt\n";
|
|
8
8
|
|
|
9
|
-
declare 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\" \u2014 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 \u2014 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 \u2014 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** \u2014 `{ 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 when called, with or without `stopToolResponseProperty` |\n| `stopToolResponseProperty` | `string` | No | Property to extract from the stop tool result. This option requires `stopTool`. |\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** \u2014 the primary conversational interface renders wherever a `human` backing is.\n- **Perspective** \u2014 `role: 'user'` is the side B perspective, `role: 'assistant'` is the side A perspective, for queueing, injection, and rendering alike.\n- **Subagent eligibility** \u2014 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** \u2014 `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 \u2014 the cap is a voluntary safety valve, and prompt and handler authors own their termination discipline.\n\n## Example: Assistant (human \u00D7 prompt)\n\nThe everyday user-facing assistant \u2014 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 \u00D7 prompt)\n\nTwo models converse; each side sees itself as `assistant` and the other as `user`. `maxSessionTurns` is optional but strongly recommended here \u2014 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 \u00D7 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` \u2014 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 \u2014 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\u2192child 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 the unqualified part of `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 \u2014 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\nBlocking `subagent_create` returns the session result through its tool result.\nThat session has no implicit completion message.\nWith `maxInstances: 1`, a repeated call continues the existing child.\nContinuation acquires execution before persisting its input.\nAdmission failure leaves the continuation input unsent.\nA separate `subagent_message` activation retains implicit delivery under `parentCommunication: 'implicit'`.\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** \u2014 end the session (success / terminal failure)\n2. **stopTool** \u2014 ends the current side's turn\n3. **stopOnResponse** \u2014 ends the turn when the LLM returns text without tool calls\n4. **Safety limits** \u2014 `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 \u2014 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 \u2014\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 \u00D7 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";
|
|
9
|
+
declare const AGENT_DEFINITIONS_AGENTS_MD = "# Agent definitions\n\nAn agent is a conversation between two sides, `sideA` and `sideB`. Each side is backed by exactly one of three things:\n\n| Backing | Who takes the side's turns | Written as |\n|---------|----------------------------|------------|\n| Human | A person, through the builder UI or your own client | `{ human: true }` |\n| Prompt | A model, running a prompt from `agents/prompts/` | `{ prompt: 'name' }` |\n| Handler | Code from `agents/handlers/` | `{ handler: 'name' }` |\n\nWrite both sides. There is no default for a missing side. Side A is the `assistant` role in the message history and side B is the `user` role.\n\n## A chat assistant\n\nA person on side B talks to a model on side A.\n\n```typescript\n// agents/agents/support_agent.ts\nimport { defineAgent } from '@standardagents/builder';\n\nexport default defineAgent({\n name: 'support_agent',\n title: 'Customer Support',\n description: 'Answers customer questions from the knowledge base and opens tickets.',\n sideA: {\n label: 'Support',\n prompt: 'customer_support',\n sessionStop: { name: 'close_conversation', messageProperty: 'summary' },\n maxSteps: 30,\n },\n sideB: { label: 'Customer', human: true },\n hooks: ['log_tool_use'],\n});\n```\n\nThe prompt `customer_support` is in `agents/prompts/AGENTS.md`, the tool `close_conversation` is in `agents/tools/AGENTS.md`, and the hook `log_tool_use` is in `agents/hooks/AGENTS.md`.\n\n## Agent properties\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `name` | `string` | Yes | The agent's name. Use `snake_case` and end it with `_agent` |\n| `sideA` | side | Yes | Side A |\n| `sideB` | side | Yes | Side B |\n| `title` | `string` | No | Display name |\n| `description` | `string` | No | What the agent does |\n| `icon` | `string` | No | A URL, a data URI, or a path under the project's `public/` directory such as `/icons/support.svg` |\n| `maxSessionTurns` | `number` | No | The most exchanges one session may take |\n| `exposeAsTool` | `boolean` | No | Let prompts and other agents call this agent |\n| `toolDescription` | `string` | With `exposeAsTool` | What a calling model is told about this agent |\n| `primary` | `boolean` | No | Set `false` to hide the agent from agent lists. Default `true` |\n| `env` | `Record<string, string>` | No | Default variable values |\n| `hooks` | `string[]` | No | Hook IDs to run. A prompt's own `hooks` replace these for that prompt |\n| `parentHooks` | array | No | Hooks this agent adds to an agent that composes it |\n\n## Side properties\n\nA human side takes `human: true` and an optional `label`. Nothing else is allowed on it.\n\nA prompt side:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `prompt` | `string` | Required. The `name` of a prompt |\n| `label` | `string` | Display name for the side |\n| `stopOnResponse` | `boolean` | End the side's turn when the model replies without calling a tool. Default `true` |\n| `stopTool` | `string` | A tool that ends the side's turn when called |\n| `stopToolResponseProperty` | `string` | The property of the stop tool's result to use as the side's reply |\n| `maxSteps` | `number` | The most model requests this side makes in one turn |\n| `sessionStop` | binding | The tool that ends the session successfully |\n| `sessionFail` | binding | The tool that ends the session as failed |\n| `sessionStatus` | binding | The tool that reports progress without ending the session |\n| `subagents` | array | Child agents this side can start |\n\nA handler side takes `handler` (required), `label`, and `subagents`.\n\nA binding names a tool and the arguments to read from its call:\n\n```text\nsessionStop: {\n name: 'close_conversation', // the tool\n messageProperty: 'summary', // the argument that becomes the result text\n attachmentsProperty: 'files', // the argument that holds file paths\n}\n```\n\nThe bound tool must also be listed in the prompt's `tools`, and must exist in `agents/tools/`.\n\n## Turns and sessions\n\nA **turn** is one side acting until it stops. A **session** is the exchange of turns until the work is done.\n\nA prompt side's turn ends at the first of these:\n\n1. It calls its `sessionStop` or `sessionFail` tool. The session ends too.\n2. It calls its `stopTool`.\n3. The model replies with text and no tool call, when `stopOnResponse` is `true`.\n4. It reaches `maxSteps`.\n\nA handler side's turn ends when its function returns. A human side's turn ends when the person sends a message.\n\nA session also ends when it reaches `maxSessionTurns`. There is no default. Without it, a run stops only at a fallback ceiling of 250 model steps.\n\n## Two models working together\n\nBoth sides can be prompts. Each side sees its own messages as `assistant` and the other side's as `user`. Use this shape for work that benefits from review. Give the sides different jobs, name the tool that ends the session, and set `maxSessionTurns`, because nothing else stops two models.\n\n```typescript\n// agents/agents/draft_agent.ts\nimport { defineAgent } from '@standardagents/builder';\n\nexport default defineAgent({\n name: 'draft_agent',\n title: 'Draft and Review',\n description: 'Writes a reply to a customer and revises it until a reviewer approves.',\n exposeAsTool: true,\n toolDescription: 'Write a reviewed reply to a customer from a short brief',\n maxSessionTurns: 8,\n sideA: {\n label: 'Writer',\n prompt: 'draft_writer',\n },\n sideB: {\n label: 'Reviewer',\n prompt: 'draft_reviewer',\n sessionStop: { name: 'approve_draft', messageProperty: 'final_text' },\n },\n});\n```\n\n```typescript\n// agents/prompts/draft_writer.ts\nimport { definePrompt } from '@standardagents/builder';\nimport { z } from 'zod';\n\nexport default definePrompt({\n name: 'draft_writer',\n toolDescription: 'Write a reply to a customer from a brief',\n model: 'default',\n prompt: 'Write a reply to the customer described in the brief. When the reviewer asks for changes, send a complete revised reply.',\n requiredSchema: z.object({\n brief: z.string().describe('Who the customer is, what they asked, and what the reply must say'),\n }),\n includeChat: true,\n});\n```\n\n```typescript\n// agents/prompts/draft_reviewer.ts\nimport { definePrompt } from '@standardagents/builder';\n\nexport default definePrompt({\n name: 'draft_reviewer',\n toolDescription: 'Review a draft reply to a customer',\n model: 'default',\n prompt: `Review the draft for accuracy, tone, and length.\nIf it is ready to send, call approve_draft with the final text.\nOtherwise reply with the specific changes you need.`,\n tools: ['approve_draft'],\n includeChat: true,\n includePastTools: true,\n});\n```\n\nThe tool `approve_draft` is in `agents/tools/AGENTS.md`.\n\n## Subagents\n\nA side can start other agents as children. Each child runs in its own thread with its own history. Declare the children on the side that uses them:\n\n```typescript\n// agents/agents/coordinator_agent.ts\nimport { defineAgent } from '@standardagents/builder';\n\nexport default defineAgent({\n name: 'coordinator_agent',\n title: 'Support Coordinator',\n description: 'Talks to the customer and delegates reply writing to a reviewed drafting agent.',\n sideA: {\n label: 'Coordinator',\n prompt: 'coordinator',\n subagents: [\n {\n agent: 'draft_agent',\n blocking: true,\n maxInstances: 1,\n initUserMessageProperty: 'brief',\n },\n ],\n },\n sideB: { label: 'Customer', human: true },\n});\n```\n\n```typescript\n// agents/prompts/coordinator.ts\nimport { definePrompt } from '@standardagents/builder';\n\nexport default definePrompt({\n name: 'coordinator',\n toolDescription: 'Coordinate customer support and delegate reply writing',\n model: 'default',\n prompt: `You coordinate customer support.\nFor a reply that needs care, call subagent_create with agent \"draft_agent\", a short name, and a brief in arguments.\nSend the customer the text it returns.`,\n includeChat: true,\n includePastTools: true,\n});\n```\n\nAny agent can be a child. Give it `exposeAsTool: true` and a `toolDescription` so the parent's model is told what it does. Do not list the child in the prompt's `tools`. For a prompt side with subagents, the runtime adds three tools on its own:\n\n| Tool | What it does |\n|------|--------------|\n| `subagents` | Lists the children that exist, with their status |\n| `subagent_create` | Starts a child. Takes `agent` (the relationship name), `name` (a label for this child), and `arguments` |\n| `subagent_message` | Sends a message to an existing child |\n\n`arguments` follows the `requiredSchema` of the child's side A prompt. The child reads them as `state.arguments` and as prompt variables.\n\nRelationship options:\n\n| Option | Meaning |\n|--------|---------|\n| `agent` | Required. The child agent's `name` |\n| `as` | The relationship name the model sees. Defaults to the agent name. Use it to compose one agent twice |\n| `description` | Overrides the child's `toolDescription` for this relationship |\n| `blocking` | `subagent_create` waits for the child's session and returns its result |\n| `maxInstances` | The most children of this relationship. With `blocking` and `1`, a repeated call continues the same child |\n| `immediate` | Start the child when the thread is created |\n| `parentCommunication` | `'implicit'` (default) sends the child's result to the parent as a message. `'explicit'` sends nothing unless the child calls `state.notifyParent()` |\n| `initUserMessageProperty` | The argument to send as the child's first message |\n| `initAttachmentsProperty` | The argument that holds file paths to attach |\n| `initAgentNameProperty` | The argument to use as the child's display name |\n| `scopedEnv` | Variables the child must be given and does not inherit |\n| `optional` | A variable name. The relationship is enabled only when that variable is `true` |\n| `hidden` | Keep the relationship out of the model's tools. Code can still start it |\n\nA child's thread is never deleted when its session ends. The parent can message the same child again later. Only `state.terminate()` ends a child for good.\n\n## Handing a thread to another agent\n\nAn agent with `exposeAsTool: true` can also be listed in a prompt's `tools`. Calling it hands the same thread, with its history, to that agent.\n\n```typescript\n// agents/agents/billing_agent.ts\nimport { defineAgent } from '@standardagents/builder';\n\nexport default defineAgent({\n name: 'billing_agent',\n title: 'Billing Support',\n description: 'Answers billing questions.',\n exposeAsTool: true,\n toolDescription: 'Hand the conversation to billing support for invoice, charge, and refund questions',\n primary: false,\n sideA: { label: 'Billing', prompt: 'billing_support' },\n sideB: { label: 'Customer', human: true },\n});\n```\n\n```typescript\n// agents/agents/triage_agent.ts\nimport { defineAgent } from '@standardagents/builder';\n\nexport default defineAgent({\n name: 'triage_agent',\n title: 'Support Triage',\n description: 'Greets the customer and routes billing questions to billing support.',\n sideA: { label: 'Triage', prompt: 'triage' },\n sideB: { label: 'Customer', human: true },\n});\n```\n\n```typescript\n// agents/prompts/triage.ts\nimport { definePrompt } from '@standardagents/builder';\n\nexport default definePrompt({\n name: 'triage',\n toolDescription: 'Greet a customer and route the conversation',\n model: 'default',\n prompt: 'Greet the customer and find out what they need. For a billing question, call billing_agent. Answer anything else yourself.',\n tools: ['billing_agent'],\n includeChat: true,\n});\n```\n\nThe prompt `billing_support` is in `agents/prompts/AGENTS.md`.\n\n## Definitions that are rejected\n\nAn agent fails to load when:\n\n- Both sides are human.\n- A side has no backing, or more than one of `human`, `prompt`, and `handler`.\n- A human side has anything other than `human` and `label`.\n- A handler side has `maxSteps`, a stop setting, or a session binding.\n- A side names a prompt or handler that does not exist.\n- `exposeAsTool` is `true` and `toolDescription` is missing.\n- A relationship name is used on both sides, or matches a tool name or one of the three subagent tool names.\n\nA failed agent is missing from the builder UI's agent list, and the UI shows the error in a banner.\n\n## Practices\n\n- Give every agent a `title`, a `description`, and side labels. They appear in the builder UI and in logs.\n- Keep an agent to one domain with a short tool list. Compose agents for wider work.\n- In a prompt-and-prompt agent, set `maxSessionTurns` and bind a `sessionStop` tool.\n- Use a prompt as a tool for one model step. Use a subagent when the work needs several steps or a review.\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/agent\n";
|
|
10
10
|
|
|
11
|
-
declare const HANDLERS_AGENTS_MD = "# Handler
|
|
11
|
+
declare const HANDLERS_AGENTS_MD = "# Handler definitions\n\nA handler is a function that takes one side's turns in a conversation. When an agent side is `{ handler: 'name' }`, the runtime calls that function once for each message that arrives on the side. No model is called for that side.\n\nUse a handler for a side that should act by rule: forwarding messages, replying from a lookup, or starting other agents.\n\nA handler is not a tool (a model does not call it) and not a hook (it owns the turn instead of observing it). It is referenced from one place only: the `handler` property of an agent side.\n\n## Defining a handler\n\nThe file name is the handler's name: `agents/handlers/office_hours.ts` defines `office_hours`.\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `description` | `string` | No | What the handler does |\n| `execute` | `(state, message) => Promise<void>` | Yes | The turn |\n\n```typescript\n// agents/handlers/office_hours.ts\nimport { defineHandler } from '@standardagents/builder';\n\nexport default defineHandler({\n description: 'Replies with the support hours. Uses no model.',\n execute: async (state, message) => {\n const text = typeof message.content === 'string' ? message.content.toLowerCase() : '';\n const reply = text.includes('hours')\n ? 'Support is open Monday to Friday, 9:00 to 17:00 UTC.'\n : 'Ask me about our support hours.';\n\n await state.injectMessage({ role: 'assistant', content: reply });\n },\n});\n```\n\n```typescript\n// agents/agents/office_hours_agent.ts\nimport { defineAgent } from '@standardagents/builder';\n\nexport default defineAgent({\n name: 'office_hours_agent',\n title: 'Office Hours',\n description: 'Answers questions about support hours without calling a model.',\n sideA: { label: 'Hours', handler: 'office_hours' },\n sideB: { label: 'Customer', human: true },\n});\n```\n\n`message` is the stored message that started the turn, with its `id`, `role`, `content`, and `metadata`. `state` is the full `ThreadState`, the same one tools receive; see `agents/tools/AGENTS.md`.\n\nA handler speaks by calling `state.injectMessage()` with its own side's role: `assistant` for side A, `user` for side B. Nothing is sent on its behalf.\n\n## How a handler turn runs\n\n1. A message arrives on the handler's side.\n2. The runtime calls `execute` once with the thread state and that message.\n3. `execute` returns. The turn is over.\n\n- Each message is delivered once, in the order the messages were stored.\n- One handler call runs at a time per thread. Messages that arrive during a call wait their turn.\n- A handler side has no `maxSteps`, `stopOnResponse`, `stopTool`, or session bindings. To end the session, call `state.stopSession()`.\n- A handler turn counts toward the agent's `maxSessionTurns`.\n\n## Errors\n\nWhen `execute` throws:\n\n- The turn is marked failed and the error appears in the thread's logs.\n- The message that started the turn stays stored. It is not delivered again.\n- The session continues. The next message gets a new call.\n\nTo end the session on an error, catch it and call `state.stopSession()`.\n\n## Subagents\n\nA handler side can declare `subagents`, with the same options as a prompt side (see `agents/agents/AGENTS.md`). A handler reaches its children through `state`: `state.children` lists them, and `state.getChildThread(reference)` returns a child's thread state, whose `queueMessage()` sends it a message. A handler needs no tools for this.\n\n## Avoiding stalls and loops\n\n- Do not wait inside a handler for work that needs another message on the same thread. Messages queue behind the running call, so that wait never ends. Forward with `queueMessage()` and handle the answer as a later turn.\n- A handler that replies to every message, opposite a prompt side, never stops. Reply only when there is something to say, set `maxSessionTurns` on the agent, or call `state.stopSession()` when the work is done.\n\n## Practices\n\n- Keep handlers short and rule-based. Work that needs judgment belongs in a prompt.\n- End sessions explicitly with `state.stopSession()`.\n- Put a capability that a model should be able to call in a tool, not a handler.\n\n## Documentation\n\nAgent reference: https://docs.standardagentbuilder.com/api-reference/define/agent\n";
|
|
12
12
|
|
|
13
|
-
declare const TOOLS_AGENTS_MD = "# Custom Tools\n\nTools extend agent capabilities beyond text generation. They allow LLMs to fetch data, perform calculations, execute side effects, and chain to other prompts or agents.\n\n## Function Signature\n\n```typescript\ndefineTool({\n description: string, // What the tool does (shown to LLM)\n args?: z.ZodObject, // Input validation schema (optional)\n execute: (state, args) => ToolResult, // Implementation\n variables?: VariableDefinition[], // Declared variables (optional)\n 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\nTool variable definitions preserve `scoped: true`. A scoped variable blocks inheritance from the parent thread environment.\n\n`defineTool()` preserves `annotations` unchanged.\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) \u2014 for\n // per-user personalization or entitlement checks. Null when user-less.\n const user = await state.user();\n\n // A thread sees its owner's skills and enabled shared skills.\n // Load a skill body when it applies. Mutations require an instance admin.\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` forwards functions in imports, globals, and execution arguments as callable proxies. Call `run.terminate(reason)` to stop the sandbox. A caller disconnect also stops the run. When `report` is supplied, the host receives reports during the run and `run.reports` updates as reports arrive.\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";
|
|
13
|
+
declare const TOOLS_AGENTS_MD = "# Tools\n\nA tool is a function a model can call. Each file in this directory defines one tool, and the file name is the tool's name: `search_knowledge_base.ts` defines `search_knowledge_base`. Use `snake_case` file names. A prompt offers a tool to its model by listing the name in `tools`.\n\n## Shape\n\n```text\ndefineTool({\n description, // Required. What the tool does. The model reads this to decide when to call it\n args, // A z.object(...) describing the arguments. Omit for a tool with none\n execute, // Required. async (state, args) => ToolResult\n variables, // Variables the tool needs\n progressArgument, // The argument that holds a short progress label for the UI\n})\n```\n\n`execute` returns a `ToolResult`:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `status` | `'success'` or `'error'` | Required |\n| `result` | `string` | The output the model reads. Use JSON for structured data |\n| `error` | `string` | The message the model reads when `status` is `'error'` |\n| `error_code` | `string` | A stable code for the failure |\n| `error_data` | `object` | Structured details about the failure |\n| `attachments` | array | Files to attach, each `{ name, mimeType, data }` with base64 `data` |\n\n## A tool with arguments\n\n```typescript\n// agents/tools/search_knowledge_base.ts\nimport { defineTool } from '@standardagents/builder';\nimport { z } from 'zod';\n\nexport default defineTool({\n description: 'Search the store knowledge base. Returns up to `limit` articles with a title, a URL, and an excerpt.',\n args: z.object({\n query: z.string().describe('What to search for, in plain words'),\n limit: z.number().int().min(1).max(10).default(5).describe('How many articles to return'),\n }),\n variables: [\n {\n name: 'KNOWLEDGE_BASE_URL',\n type: 'text',\n required: true,\n scoped: false,\n description: 'Base URL of the knowledge base search API',\n },\n ],\n execute: async (state, args) => {\n const baseUrl = await state.env('KNOWLEDGE_BASE_URL');\n if (!baseUrl) {\n return { status: 'error', error: 'KNOWLEDGE_BASE_URL is not set.', error_code: 'not_configured' };\n }\n\n const url = new URL('/search', baseUrl);\n url.searchParams.set('q', args.query);\n url.searchParams.set('limit', String(args.limit));\n\n const response = await fetch(url);\n if (!response.ok) {\n return {\n status: 'error',\n error: `The knowledge base returned HTTP ${response.status}.`,\n error_code: 'upstream_error',\n };\n }\n\n return { status: 'success', result: await response.text() };\n },\n});\n```\n\nReturn an error result for a failure the model can react to, as above. The model reads `error` and can retry or tell the user. Let unexpected exceptions throw; the runtime records them in the thread's logs.\n\n## Arguments\n\n`args` must be a `z.object(...)`. Build it from strings, numbers, booleans, enums, literals, arrays, and nested objects, with `.optional()`, `.nullable()`, and `.default()` as needed. Add `.describe()` to every field; the model reads the descriptions.\n\nAvoid `z.any()`, `z.unknown()`, and open-ended records. Some providers reject the schemas they produce. For free-form JSON, take a string argument and parse it in `execute`.\n\n## Thread state\n\n`state` is the thread the tool runs in. This tool stores a record in the thread's key-value store and reads the thread's user:\n\n```typescript\n// agents/tools/create_ticket.ts\nimport { defineTool } from '@standardagents/builder';\nimport { z } from 'zod';\n\nexport default defineTool({\n description: 'Open a support ticket for a person to follow up. Returns the ticket ID.',\n args: z.object({\n subject: z.string().describe('One line that names the problem'),\n details: z.string().describe('Everything a support person needs to act on the ticket'),\n }),\n execute: async (state, args) => {\n const user = await state.user();\n const ticket = {\n id: `T-${crypto.randomUUID().slice(0, 8)}`,\n subject: args.subject,\n details: args.details,\n openedBy: user?.email ?? null,\n };\n\n await state.setValue(`ticket:${ticket.id}`, ticket);\n state.emit('ticket_created', { id: ticket.id });\n\n return { status: 'success', result: JSON.stringify({ ticketId: ticket.id }) };\n },\n});\n```\n\nEach ticket has its own key. `getValue()` followed by `setValue()` is two separate steps, so code that reads a shared list, changes it, and writes it back can overwrite a record that other code just added. Store each record under its own key.\n\nWhat `state` offers:\n\n| Use | Members |\n|-----|---------|\n| Identity | `threadId`, `agentId`, `userId`, `arguments` |\n| Messages | `getMessages()`, `getMessage(id)`, `injectMessage()`, `queueMessage()`, `updateMessage()` |\n| Durable values | `getValue(key)`, `setValue(key, value)`; a `null` value deletes the key |\n| Variables | `env(name)`, `setEnv(name, value)` |\n| Files | `readFile`, `writeFile`, `readdirFile`, `statFile`, `moveFile`, `renameFile`, `unlinkFile`, `mkdirFile`, `findFiles`, `grepFiles` |\n| Other tools | `queueTool(name, args)`, `invokeTool(name, args)` |\n| Live events | `emit(event, data)` |\n| User | `user()` returns the thread's user or `null` |\n| Subagents | `children`, `getChildThread(reference)`, `getParentThread()`, `notifyParent()`, `setStatus()` |\n| Session | `stopSession()`, `execution` |\n| Sandbox | `runCode(source, options)` |\n| Logs | `log({ name, message, data })` adds a row to the thread's logs |\n\n`getMessages()` returns `{ messages, total, hasMore }`, newest first. Pass `{ order: 'asc' }` for oldest first, and `limit` and `offset` to page.\n\n## Tools without arguments, and session tools\n\nA tool bound as an agent side's `sessionStop` ends the session when the model calls it. The binding reads the result text from one of the tool's arguments, so the tool itself can be small:\n\n```typescript\n// agents/tools/close_conversation.ts\nimport { defineTool } from '@standardagents/builder';\nimport { z } from 'zod';\n\nexport default defineTool({\n description: 'Close the conversation once the customer confirms the issue is resolved.',\n args: z.object({\n summary: z.string().describe('One sentence that says how the issue was resolved'),\n }),\n execute: async (state, args) => {\n await state.setValue('resolution', args.summary);\n return { status: 'success', result: 'Conversation closed.' };\n },\n});\n```\n\n```typescript\n// agents/tools/approve_draft.ts\nimport { defineTool } from '@standardagents/builder';\nimport { z } from 'zod';\n\nexport default defineTool({\n description: 'Approve the draft and finish. Call this only when the draft is ready to send.',\n args: z.object({\n final_text: z.string().describe('The approved reply, complete and ready to send'),\n }),\n execute: async () => {\n return { status: 'success', result: 'Draft approved.' };\n },\n});\n```\n\n```typescript\n// agents/tools/current_time.ts\nimport { defineTool } from '@standardagents/builder';\n\nexport default defineTool({\n description: 'Get the current date and time in UTC as an ISO 8601 string.',\n execute: async () => {\n return { status: 'success', result: new Date().toISOString() };\n },\n});\n```\n\nTo end a session from code instead of a binding, call `await state.stopSession({ result: '...' })` inside `execute`.\n\n## Running another tool\n\n`state.queueTool(name, args)` runs another tool after the current one finishes. `state.invokeTool(name, args)` runs it now and returns its result.\n\n```typescript\n// agents/tools/escalate_to_manager.ts\nimport { defineTool } from '@standardagents/builder';\nimport { z } from 'zod';\n\nexport default defineTool({\n description: 'Escalate the conversation to a manager. Opens a ticket and records the escalation.',\n args: z.object({\n reason: z.string().describe('Why a manager is needed'),\n }),\n execute: async (state, args) => {\n const ticket = await state.invokeTool('create_ticket', {\n subject: 'Manager escalation',\n details: args.reason,\n });\n if (ticket.status === 'error') {\n return ticket;\n }\n\n await state.injectMessage({\n role: 'system',\n content: `Escalated to a manager: ${args.reason}`,\n silent: true,\n });\n\n return { status: 'success', result: ticket.result ?? 'Escalated.' };\n },\n});\n```\n\n`injectMessage` adds a message to the thread without starting a turn. `silent: true` keeps it out of the chat view.\n\n## Files and attachments\n\nEach thread has its own file system. A tool can write a file there and attach files to its result.\n\n```typescript\n// agents/tools/export_transcript.ts\nimport { defineTool } from '@standardagents/builder';\n\nexport default defineTool({\n description: 'Save the conversation so far as a text file in the thread and return its path.',\n execute: async (state) => {\n const { messages } = await state.getMessages({ order: 'asc', limit: 200 });\n const transcript = messages\n .filter((message) => typeof message.content === 'string' && message.content.length > 0)\n .map((message) => `${message.role}: ${message.content}`)\n .join('\\n');\n\n const path = '/exports/transcript.txt';\n await state.writeFile(path, transcript, 'text/plain');\n\n return { status: 'success', result: JSON.stringify({ path }) };\n },\n});\n```\n\n## Variables\n\nDeclare the variables a tool reads in `variables`, so the project records what the tool needs. Read a value with `await state.env('NAME')`.\n\nSet `scoped: true` for a value that belongs to one thread and must not be inherited from a parent thread, such as a per-account token given to a subagent.\n\nValues come from, in order: the thread, the agent's `env`, the prompt's `env`, the user, and the project's variables. Put secrets in `.dev.vars` locally and in the project's platform settings when deployed.\n\n## Sandboxed code\n\nUse `state.runCode()` to run JavaScript or TypeScript that a model or a user wrote. Never use `eval` or `new Function`. The sandbox has no network, file, or thread access. Pass in only the functions the code may call.\n\n```typescript\n// agents/tools/calculate.ts\nimport { defineTool } from '@standardagents/builder';\nimport { z } from 'zod';\n\nexport default defineTool({\n description: 'Evaluate a JavaScript arithmetic expression such as \"(19.99 * 3) * 1.08\" and return the number.',\n args: z.object({\n expression: z.string().describe('A JavaScript expression that evaluates to a number'),\n }),\n execute: async (state, args) => {\n const run = await state.runCode(`export function main() { return (${args.expression}); }`, {\n execute: { fn: 'main', args: [] },\n });\n\n if (run.status !== 'success') {\n return { status: 'error', error: run.error?.message ?? 'The expression could not be evaluated.' };\n }\n return { status: 'success', result: String(run.result) };\n },\n});\n```\n\n## Practices\n\n- Write the description for the model: what the tool does, when to call it, and what it returns.\n- Keep one job per tool.\n- Research a third-party API from its current documentation before you write a tool for it.\n- Check `state` before you add a dependency. Files, key-value storage, scheduling, and user data are built in.\n- Never put a secret in a tool file. Read it with `state.env()`.\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/tool\n";
|
|
14
14
|
|
|
15
|
-
declare const HOOKS_AGENTS_MD = "# Lifecycle Hooks\n\nHooks intercept and modify agent execution at specific lifecycle points.\n\n## Available Hooks\n\n| Hook | Signature | Purpose |\n|------|-----------|---------|\n| `after_thread_created` | `(state: ThreadState) => void` | Initialize a newly created thread before execution |\n| `after_subagent_created` | `(state: ThreadState, childState: ThreadState) => void` | Run parent-side logic after a child thread is created |\n| `after_system_message` | `(state: ThreadState, systemMessage: string) => string \\| null \\| undefined` | Modify the rendered system message before the history snapshot |\n| `filter_messages` | `(state: ThreadState, messages: Message[]) => Message[]` | Build the request context from one stable history snapshot per model request (only the newest window when the prompt sets `historyLimit`) |\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 for a persisted message before its 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\nPacked thread hooks receive a `ThreadState` in their owning package namespace.\nEvery hook can use `state.loadPrompt('own')` to load a package-local prompt.\nThis includes `before_create_message`.\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\nWhen the active prompt sets `historyLimit` (N), the snapshot and\n`state.execution.messageHistory` hold only the newest top-level rows: at least N\nand fewer than 2N, the cut moving N at a time. A hook looking for an older marker\n(a compaction summary, a task header) may not see it; stored history is untouched.\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** \u2014 the hook type and ID are defined inside the file:\n\n```\nagents/hooks/\n\u251C\u2500\u2500 my_filter.ts # Could contain any hook type\n\u251C\u2500\u2500 redact_sensitive_data.ts\n\u251C\u2500\u2500 log_tool_usage.ts\n\u2514\u2500\u2500 add_metadata.ts\n```\n\n## Examples\n\n### Filter Messages (Limit Context)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'filter_messages',\n id: 'limit_to_20',\n execute: async (state, messages) => {\n return messages.slice(-20);\n }\n});\n```\n\n### Prefilter LLM History (Redact Content)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'prefilter_llm_history',\n id: 'redact_pii',\n execute: async (state, messages) => {\n return messages.map(msg => ({\n ...msg,\n content: typeof msg.content === 'string'\n ? msg.content.replace(/\\b\\d{4}-\\d{4}-\\d{4}-\\d{4}\\b/g, '[REDACTED]')\n : msg.content,\n }));\n }\n});\n```\n\n### Before Create Message (Add Metadata)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'before_create_message',\n id: 'add_version_metadata',\n execute: async (state, message) => {\n if (message.role === 'user' && message.content) {\n return { ...message, content: `[v1.0] ${message.content}` };\n }\n return message;\n }\n});\n```\n\n### Before Store Tool Result (Sanitize)\n\n```typescript\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'before_store_tool_result',\n id: 'sanitize_results',\n execute: async (state, toolCall, toolResult) => {\n // toolCall: { id, type: 'function', function: { name, arguments } }\n // toolResult: { status, result?, error?, stack?, attachments? }\n if (toolResult.result) {\n return { ...toolResult, result: toolResult.result.replace(/secret/gi, '[REDACTED]') };\n }\n return toolResult;\n }\n});\n```\n\n### After Tool Call Success (Logging)\n\n> Warning: In `after_tool_call_success` / `after_tool_call_failure`,\n> returning `null` does NOT mean \"keep the original result\" \u2014 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 \u2014 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 \u2014 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 \u2014 possibly modified \u2014 result; `null` REMOVES the tool call from history)\n- `after_tool_call_failure` (return the \u2014 possibly modified \u2014 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 \u2014 the session\nstops with a visible assistant message BEFORE any LLM request \u2014 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";
|
|
15
|
+
declare const HOOKS_AGENTS_MD = "# Lifecycle hooks\n\nA hook is a function the runtime calls at a fixed point in a thread's life: before a message is stored, before a model request is sent, after a tool runs. Use hooks for behavior that cuts across prompts, such as trimming history, redacting data, and logging.\n\n## Defining a hook\n\nEach file exports one hook. `hook` is the point it runs at, `id` is its name, and `execute` is the function. The file name can be anything; `id` is what agents and prompts refer to. `id` must be `snake_case` and unique in the project.\n\n```typescript\n// agents/hooks/limit_history.ts\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'filter_messages',\n id: 'limit_history',\n execute: async (state, messages) => {\n return messages.slice(-40);\n },\n});\n```\n\nA hook does nothing until an agent or a prompt lists its `id`:\n\n```text\ndefineAgent({ name: 'support_agent', hooks: ['log_tool_use'], ... })\ndefinePrompt({ name: 'customer_support', hooks: ['limit_history'], ... })\n```\n\n- A prompt's `hooks` replace the agent's `hooks` while that prompt runs.\n- A prompt with no `hooks` uses the agent's.\n- Work that happens outside a prompt, such as creating the thread, uses the agent's.\n\n## Hook points\n\nHooks that change data return the new value.\n\n| Hook | Arguments after `state` | Returns | Runs |\n|------|-------------------------|---------|------|\n| `after_system_message` | `systemMessage: string` | `string`, or nothing to keep it | After the system instructions are built for a request |\n| `filter_messages` | `messages: Message[]` | `Message[]` | Once per model request, on the stored history |\n| `prefilter_llm_history` | `messages: LLMMessage[]` | `LLMMessage[]` | Just before the request is sent, on provider-format messages |\n| `before_create_message` | `message: Message` | `Message` | Before a message is stored |\n| `before_update_message` | `id: string, updates` | `updates` | Before a stored message is changed |\n| `before_store_tool_result` | `toolCall, result` | `result` | Before a tool result is stored |\n| `after_tool_call_success` | `toolCall, result` | `result`, or `null` to drop the call | After a tool succeeds |\n| `after_tool_call_failure` | `toolCall, result` | `result`, or `null` to drop the call | After a tool fails |\n\nHooks that observe return nothing.\n\n| Hook | Arguments after `state` | Runs |\n|------|-------------------------|------|\n| `after_thread_created` | none | When a thread is created, before its first turn |\n| `after_subagent_created` | `childState` | In the parent, after a subagent thread is created |\n| `after_create_message` | `message: Message` | After a message is stored |\n| `after_update_message` | `message: Message` | After a stored message is changed |\n| `tool_call_started` | `toolCall, progress?` | When the model starts a tool call |\n| `tool_call_done` | `toolCall, result` | After a tool call finishes |\n\nEvery hook receives a final `context` argument that says whether the prompt, the agent, or a composed child agent listed it.\n\n`toolCall` is `{ id, type: 'function', function: { name, arguments } }`, where `arguments` is a JSON string. `result` is `{ status, result?, error?, attachments? }`.\n\n## Examples\n\nRedact data before it reaches the model:\n\n```typescript\n// agents/hooks/redact_card_numbers.ts\nimport { defineHook } from '@standardagents/builder';\n\nconst CARD_NUMBER = /\\b(?:\\d[ -]?){13,16}\\b/g;\n\nexport default defineHook({\n hook: 'prefilter_llm_history',\n id: 'redact_card_numbers',\n execute: async (state, messages) => {\n return messages.map((message) =>\n typeof message.content === 'string'\n ? { ...message, content: message.content.replace(CARD_NUMBER, '[card number removed]') }\n : message,\n );\n },\n});\n```\n\nLog every tool call. This hook returns `result` unchanged:\n\n```typescript\n// agents/hooks/log_tool_use.ts\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'after_tool_call_success',\n id: 'log_tool_use',\n execute: async (state, toolCall, result) => {\n console.log(`[${state.threadId}] ${toolCall.function.name} succeeded`);\n return result;\n },\n});\n```\n\nIn `after_tool_call_success` and `after_tool_call_failure`, returning `null` removes the tool call and its result from the history. A hook that only observes must return the `result` it was given.\n\nReplace a failed result with a fallback the model can use:\n\n```typescript\n// agents/hooks/knowledge_base_fallback.ts\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'after_tool_call_failure',\n id: 'knowledge_base_fallback',\n execute: async (state, toolCall, result) => {\n if (toolCall.function.name !== 'search_knowledge_base') {\n return result;\n }\n return {\n status: 'success',\n result: JSON.stringify({ articles: [], note: 'The knowledge base is unavailable. Open a ticket instead.' }),\n };\n },\n});\n```\n\nShorten large tool results before they are stored:\n\n```typescript\n// agents/hooks/truncate_tool_results.ts\nimport { defineHook } from '@standardagents/builder';\n\nconst MAX_LENGTH = 8000;\n\nexport default defineHook({\n hook: 'before_store_tool_result',\n id: 'truncate_tool_results',\n execute: async (state, toolCall, result) => {\n if (!result.result || result.result.length <= MAX_LENGTH) {\n return result;\n }\n return { ...result, result: `${result.result.slice(0, MAX_LENGTH)}\\n[truncated]` };\n },\n});\n```\n\nSet up a new thread:\n\n```typescript\n// agents/hooks/record_thread_start.ts\nimport { defineHook } from '@standardagents/builder';\n\nexport default defineHook({\n hook: 'after_thread_created',\n id: 'record_thread_start',\n execute: async (state) => {\n await state.setValue('started_at', new Date().toISOString());\n },\n});\n```\n\n## How a request is built\n\nFor each model request the runtime:\n\n1. Builds the system instructions and runs `after_system_message`.\n2. Takes one snapshot of the stored history.\n3. Runs `filter_messages` once on that snapshot.\n4. Converts the result to the provider's format and runs `prefilter_llm_history`.\n\nThese hooks shape what the model sees. They do not change the stored history. With `historyLimit` set on the prompt, the snapshot holds only the newest messages, so a hook cannot see older ones.\n\n## Errors\n\nA hook that throws is logged and skipped, and the data it was given is used unchanged. One exception lets a hook stop a turn on purpose: a `prefilter_llm_history` hook can throw an error with `block: true`. No model request is sent, and the error message is shown as the assistant's reply.\n\n```typescript\n// agents/hooks/enforce_message_limit.ts\nimport { defineHook } from '@standardagents/builder';\n\nconst MAX_MESSAGES = 200;\n\nexport default defineHook({\n hook: 'prefilter_llm_history',\n id: 'enforce_message_limit',\n execute: async (state, messages) => {\n const { total } = await state.getMessages({ limit: 1 });\n if (total > MAX_MESSAGES) {\n throw Object.assign(new Error('This conversation has reached its limit. Start a new one.'), { block: true });\n }\n return messages;\n },\n});\n```\n\n`before_create_message` is the other exception: when it throws during `state.injectMessage()`, the message is not stored.\n\n## User hooks\n\nThree hooks run for a user instead of a thread. They receive a `UserState` (see `agents/users/AGENTS.md`), run for every user, and are not listed on an agent or prompt.\n\n| Hook | Arguments | Runs |\n|------|-----------|------|\n| `user_client_attached` | `user, client` | A client connects to the user's event stream |\n| `user_client_detached` | `user, client` | A client disconnects |\n| `user_value_changed` | `user, key` | One of the user's durable values changes |\n\n## Practices\n\n- Keep hooks fast. Request hooks run before every model request.\n- Return the value you were given when you have nothing to change.\n- Use a hook for behavior shared across prompts. Put behavior that belongs to one tool in that tool.\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/api-reference/define/hook\n";
|
|
16
16
|
|
|
17
|
-
declare const API_AGENTS_MD = "# Thread-Specific API Endpoints\n\nDefine custom API endpoints that operate on specific threads with access to the thread's ThreadState.\n\nUnmatched thread endpoint paths return JSON with HTTP 404.\nA method without a matching endpoint route also returns HTTP 404.\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 \u2014 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 \u2014 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. In thread endpoints, `runCode` forwards functions in imports, globals, and execution arguments as callable proxies. Call `run.terminate(reason)` to stop the sandbox. A caller disconnect also stops the run. When `report` is supplied, the host receives reports during the run and `run.reports` updates as reports arrive. `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\n`getMessages()` returns messages newest first by default. Set `order: 'asc'` for oldest first.\n`getMessage(id)` finds persisted messages at any depth. It also finds pending messages from the message list. It returns `null` for unknown IDs.\n`updateMessage(id, updates)` updates a persisted message. It returns the updated `Message`.\nUpdates to missing or pending messages fail before update hooks run.\nMessage results include `reasoning_content`, `reasoning_details`, `prompt`, and available subagent fields: `subagent_id`, `subagent_name`, `subagent_title`, `subagent_description`, `subagent_status`, `subagent_relationship`, `subagent_blocking`, `subagent_thread_name`, and `subagent_spawn_group_id`.\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`state.loadModel`, `state.loadPrompt`, and `state.loadAgent` enforce package\nvisibility. Global code can load unpacked definitions and packed entry agents.\nPacked code can load its own definitions and other packages' entry agents.\nA packed model cannot fall back to a host model with the same short name.\nA refused load returns the same not-found error as a missing definition.\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({ order: 'asc' });\n\n if (format === 'csv') {\n const csv = messages.map(m => `${m.role},${m.content}`).join('\\n');\n return new Response(csv, {\n headers: { 'Content-Type': 'text/csv' },\n });\n }\n\n return Response.json(messages);\n});\n```\n\n## Nested Routes\n\nCreate directories for nested routes:\n\n```\nagents/api/\n\u251C\u2500\u2500 status.get.ts -> GET /api/threads/:threadId/status\n\u251C\u2500\u2500 export.post.ts -> POST /api/threads/:threadId/export\n\u2514\u2500\u2500 messages/\n \u251C\u2500\u2500 count.ts -> GET /api/threads/:threadId/messages/count\n \u251C\u2500\u2500 [id].ts -> GET /api/threads/:threadId/messages/:id\n \u2514\u2500\u2500 [*].ts -> GET /api/threads/:threadId/messages/*\n```\n\n## Error Handling\n\nAgentBuilder returns JSON for every failed request under `/api/`.\nThe response preserves the HTTP status.\nThe body uses `{ \"error\": { \"code\": \"internal_error\", \"message\": \"...\" }, \"requestId\": \"...\" }`.\nThe `X-Request-ID` header matches `requestId`.\nFailed responses use `Cache-Control: no-store`.\n\nAn uncaught exception returns HTTP 500 with code `internal_error`.\nThe server log contains the exception and request ID.\nThe response message omits exception details.\nAuthentication infrastructure failures return HTTP 503 with code `auth_unavailable`.\nPlatform network failures, unexpected HTTP statuses, and invalid payloads return HTTP 502 with code `platform_unreachable`.\nCheck `PLATFORM_ENDPOINT` and platform availability after that error.\nAn explicit platform credential or membership denial uses code `platform_auth_rejected` during local bootstrap.\nUnknown API paths return HTTP 404 with code `not_found`.\n\nRead `error.message` to display a failure.\nInclude `requestId` in a support report.\nReturned legacy JSON errors retain their extra fields and response headers.\nThe router converts their `error` field to the structured envelope.\nA legacy string error with a separate message retains its code in the envelope.\nIts separate message becomes the envelope message.\nWebSocket upgrades and successful responses retain their existing behavior.\nThis error contract is an AgentBuilder extension.\n\nHandlers can return domain errors with an appropriate HTTP status:\n\n```typescript\nreturn Response.json({ error: 'Invalid JSON body' }, { status: 400 });\n```\n\nLet unexpected exceptions reach the runtime boundary.\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";
|
|
17
|
+
declare const API_AGENTS_MD = "# Thread endpoints\n\nA thread endpoint is an HTTP route that runs against one thread. Each file in this directory becomes a route under `/api/threads/:threadId/`, and receives that thread's `ThreadState`. Use endpoints to give your own front end or service access to a thread's data.\n\n## Routing\n\nThe file path sets the route. A suffix before `.ts` sets the method; a file without one answers `GET`.\n\n| File | Method | Route |\n|------|--------|-------|\n| `summary.ts` | GET | `/api/threads/:threadId/summary` |\n| `summary.get.ts` | GET | `/api/threads/:threadId/summary` |\n| `notes.post.ts` | POST | `/api/threads/:threadId/notes` |\n| `notes/[id].put.ts` | PUT | `/api/threads/:threadId/notes/:id` |\n| `notes/[id].delete.ts` | DELETE | `/api/threads/:threadId/notes/:id` |\n| `files/[*].ts` | GET | `/api/threads/:threadId/files/*` |\n\n- Suffixes are `.get`, `.post`, `.put`, `.patch`, and `.delete`.\n- `[name]` matches one path segment and arrives as `params.name`.\n- `[*]` matches the rest of the path, slashes included, and arrives as `params['*']`.\n- A fixed route wins over `[name]`, and `[name]` wins over `[*]`.\n- A path or method with no matching file returns HTTP 404 as JSON.\n\n## Defining an endpoint\n\nImport `defineThreadEndpoint` from `@standardagents/spec`.\n\n```typescript\n// agents/api/summary.get.ts\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state) => {\n const { messages, total } = await state.getMessages({ limit: 5 });\n\n return Response.json({\n threadId: state.threadId,\n agent: state.agentId,\n messageCount: total,\n latest: messages.map((message) => ({ role: message.role, content: message.content })),\n });\n});\n```\n\nThe function receives:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `req` | `Request` | The HTTP request |\n| `state` | `ThreadState` | The thread. See `agents/tools/AGENTS.md` for its members |\n| `params` | `Record<string, string>` | Values from `[name]` and `[*]` segments |\n| `auth` | `{ caller, threadAccess }` | Who is calling, and whether they may access this thread |\n\nThe thread is at rest while an endpoint runs, so `state.execution` is `null` and `state.stopSession()` is not available.\n\n## Reading a request body\n\n```typescript\n// agents/api/notes.post.ts\nimport { defineThreadEndpoint } from '@standardagents/spec';\nimport { z } from 'zod';\n\nconst NoteInput = z.object({\n text: z.string().min(1).max(2000),\n});\n\nexport default defineThreadEndpoint(async (req, state) => {\n const input = NoteInput.safeParse(await req.json().catch(() => null));\n if (!input.success) {\n return Response.json({ error: 'Send a JSON body with a \"text\" string.' }, { status: 400 });\n }\n\n const note = { id: crypto.randomUUID(), text: input.data.text, createdAt: new Date().toISOString() };\n\n await state.setValue(`note:${note.id}`, note);\n state.emit('notes_changed', { id: note.id });\n\n return Response.json(note, { status: 201 });\n});\n```\n\nEach note has its own key. Requests to a thread endpoint can run at the same time, and `getValue()` followed by `setValue()` is two separate steps. An endpoint that read one shared list, changed it, and wrote it back could overwrite a note that another request had just added. Give each record its own key, as above, so no request rewrites another's data.\n\n`state.emit()` sends a live event to clients connected to the thread. Events are not stored. A client that reconnects must read the data again.\n\n## Route parameters\n\n```typescript\n// agents/api/notes/[id].delete.ts\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(async (req, state, params) => {\n const key = `note:${params.id}`;\n if ((await state.getValue(key)) === null) {\n return Response.json({ error: 'No note has that ID.' }, { status: 404 });\n }\n\n await state.setValue(key, null);\n state.emit('notes_changed', { id: params.id });\n\n return new Response(null, { status: 204 });\n});\n```\n\nSetting a value to `null` deletes its key.\n\n## Access\n\nAn endpoint requires an authenticated caller who may access the thread. The runtime checks both before your function runs, and `auth.caller` is always set.\n\nPass `{ access: 'public' }` to accept requests with no credentials. `auth.caller` is then `null` for an anonymous request, and `auth.threadAccess` says whether a signed-in caller may access the thread.\n\n```typescript\n// agents/api/files/[*].ts\nimport { defineThreadEndpoint } from '@standardagents/spec';\n\nexport default defineThreadEndpoint(\n async (req, state, params, auth) => {\n const path = `/${params['*'] ?? ''}`;\n const isShared = path.startsWith('/public/') && !path.includes('..');\n if (!auth.threadAccess && !isShared) {\n return new Response(null, { status: 404 });\n }\n\n const [data, stat] = await Promise.all([state.readFile(path), state.statFile(path)]);\n if (!data || !stat) {\n return new Response(null, { status: 404 });\n }\n\n return new Response(data, {\n headers: {\n 'Content-Type': stat.mimeType,\n 'Content-Disposition': 'attachment',\n 'X-Content-Type-Options': 'nosniff',\n },\n });\n },\n { access: 'public' },\n);\n```\n\nAnyone with the URL can call a public endpoint. Validate the path, and never return private thread data to an anonymous caller.\n\nServe thread files as downloads, as this example does. Endpoints share an origin with the builder UI and its APIs. An HTML or SVG file shown inline would run its scripts with the access of whoever opened the link. `Content-Disposition: attachment` makes the browser save the file, and `X-Content-Type-Options: nosniff` stops it from guessing a different type.\n\n## Thread files\n\nEach thread has its own file system, reached through `state`:\n\n| Method | Does |\n|--------|------|\n| `readFile(path)` | Returns the file's bytes as an `ArrayBuffer`, or `null` |\n| `writeFile(path, data, mimeType)` | Creates or replaces a file |\n| `statFile(path)` | Returns the file's details, or `null` |\n| `readdirFile(path)` | Returns `{ entries }` for a directory |\n| `moveFile(from, to)` / `renameFile(path, newName)` | Moves or renames. Does not overwrite |\n| `unlinkFile(path)` | Deletes a file |\n| `findFiles(pattern)` | Returns `{ paths }` matching a glob such as `**/*.json` |\n| `grepFiles(pattern)` | Searches file contents |\n\n## Errors\n\nReturn an error as JSON with the right status:\n\n```text\nreturn Response.json({ error: 'Send a JSON body with a \"text\" string.' }, { status: 400 });\n```\n\nThe runtime rewrites every failed `/api/` response into one shape, and adds a request ID:\n\n```text\n{ \"error\": { \"code\": \"internal_error\", \"message\": \"...\" }, \"requestId\": \"...\" }\n```\n\nLet unexpected exceptions throw. The caller receives HTTP 500 with code `internal_error` and no exception details; the dev server terminal and the deployed project's logs hold the exception and the same request ID.\n\n## Practices\n\n- Validate request bodies before you use them.\n- Page large reads with `limit` and `offset`.\n- Name files for what they do: `export.post.ts`, not `ep1.ts`.\n- Keep endpoints quick. Start long work with `state.queueMessage()` and let the agent do it.\n\n## Documentation\n\nFull reference: https://docs.standardagentbuilder.com/core-concepts/api\n";
|
|
18
18
|
|
|
19
|
-
declare const USERS_AGENTS_MD = "# User
|
|
19
|
+
declare const USERS_AGENTS_MD = "# User endpoints\n\nA user endpoint is an HTTP route that runs for one user instead of one thread. Each file in this directory becomes a route under `/api/users/me/`. Use user endpoints for data that spans a user's threads: preferences, quotas, counters, and registries.\n\nFor one user, only one user endpoint runs at a time, and each run sees every write made by the runs before it. That makes this the safe place to check a limit and then update it.\n\n## Routing\n\nRouting follows the same rules as thread endpoints: the path sets the route, a suffix sets the method, and `[name]` and `[*]` capture segments.\n\n| File | Method | Route |\n|------|--------|-------|\n| `preferences.ts` | GET | `/api/users/me/preferences` |\n| `preferences.put.ts` | PUT | `/api/users/me/preferences` |\n| `quota/spend.post.ts` | POST | `/api/users/me/quota/spend` |\n| `items/[id].ts` | GET | `/api/users/me/items/:id` |\n\n`me` is the signed-in caller. An administrator can call the same endpoints for another user at `/api/users/:id/...`.\n\n## Defining a user endpoint\n\nImport `defineUserEndpoint` from `@standardagents/spec`. The function receives the request, a `UserState`, and the route parameters.\n\n```typescript\n// agents/users/quota/spend.post.ts\nimport { defineUserEndpoint } from '@standardagents/spec';\nimport { z } from 'zod';\n\nconst SpendInput = z.object({\n amount: z.number().int().positive(),\n});\n\nconst DAILY_LIMIT = 100;\n\nexport default defineUserEndpoint(async (req, user) => {\n const input = SpendInput.safeParse(await req.json().catch(() => null));\n if (!input.success) {\n return Response.json({ error: 'Send a JSON body with a positive integer \"amount\".' }, { status: 400 });\n }\n\n const key = `quota.${new Date().toISOString().slice(0, 10)}`;\n const used = (await user.getValue<number>(key)) ?? 0;\n if (used + input.data.amount > DAILY_LIMIT) {\n return Response.json({ ok: false, used, limit: DAILY_LIMIT }, { status: 429 });\n }\n\n await user.setValue(key, used + input.data.amount);\n user.emit('quota_changed', { used: used + input.data.amount, limit: DAILY_LIMIT });\n\n return Response.json({ ok: true, used: used + input.data.amount, limit: DAILY_LIMIT });\n});\n```\n\n## UserState\n\n| Member | Does |\n|--------|------|\n| `userId` | The user's ID |\n| `identity()` | Returns the user's profile: `id`, `username`, `email`, `role`, `roles` |\n| `getValue(key)` / `setValue(key, value)` | Durable JSON values for this user. A `null` value deletes the key |\n| `listValues({ prefix, limit, offset })` | Lists the user's values |\n| `env(name)` | Reads a variable |\n| `emit(event, data)` | Sends a live event to the user's connected clients |\n| `listThreads({ agentId, limit, offset })` | Lists the user's threads |\n| `thread(threadId)` | Returns the `ThreadState` of one of the user's threads |\n\nDo not store credentials in user values. They are plain JSON.\n\n## Calling a user endpoint from a thread\n\nTools, hooks, handlers, and thread endpoints reach the user through `state.user()`. `call()` runs a user endpoint by its path under `agents/users/`, with the same one-at-a-time guarantee.\n\n```typescript\n// agents/tools/spend_quota.ts\nimport { defineTool } from '@standardagents/builder';\nimport { z } from 'zod';\n\nexport default defineTool({\n description: 'Spend units of the user\\'s daily quota before doing metered work. Fails when the quota is used up.',\n args: z.object({\n amount: z.number().int().positive().describe('How many units to spend'),\n }),\n execute: async (state, args) => {\n const user = await state.user();\n if (!user) {\n return { status: 'error', error: 'This thread has no user.', error_code: 'no_user' };\n }\n\n const response = await user.call('quota/spend', { amount: args.amount });\n if (!response.ok) {\n return { status: 'error', error: 'The daily quota is used up.', error_code: 'quota_exceeded' };\n }\n return { status: 'success', result: await response.text() };\n },\n});\n```\n\nA user endpoint can tell how it was called from the `X-Standard-Agents-Caller` request header, which the runtime sets and callers cannot forge: `user` for the user's own HTTP request, `admin` for an administrator, and `thread` for a call from `state.user().call()`. Check for `thread` in an endpoint that only your agents should be able to change.\n\n## Roles\n\nA user's application roles are strings assigned in the project's user settings on the platform. Their meaning is up to you. Read them from the identity and check them in every request that needs one:\n\n```typescript\n// agents/users/reports.ts\nimport { defineUserEndpoint } from '@standardagents/spec';\n\nexport default defineUserEndpoint(async (req, user) => {\n const identity = await user.identity();\n const roles = identity.roles ?? [];\n if (!roles.includes('reports:read')) {\n return Response.json({ error: 'Forbidden' }, { status: 403 });\n }\n\n const threads = await user.listThreads({ limit: 20 });\n return Response.json({ threads });\n});\n```\n\nRoles are matched exactly; a suffix such as `:*` has no special meaning. A user with no roles gets no access. Never read roles from a request body or from user values.\n\n## Live events\n\nA client can open a WebSocket to `/api/users/me/stream` and receive every `user.emit()` as `{ \"event\": string, \"data\": unknown }`. Events are not stored. Read the durable values again after connecting or reconnecting.\n\n## Documentation\n\nSpecification: https://standardagentspec.com/0.2.0/specification/users\n";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The starter agent a new platform project ships with: one model, one prompt,
|
|
23
|
+
* one tool, and one agent, so the first message gets an answer before the
|
|
24
|
+
* user writes a file.
|
|
25
|
+
*
|
|
26
|
+
* It answers questions about building agents and about the Standard Agent
|
|
27
|
+
* Specification by reading the two public documentation sites at request
|
|
28
|
+
* time, so its answers follow the published pages instead of this release.
|
|
29
|
+
*
|
|
30
|
+
* Each body is an ordinary definition file that uses only published
|
|
31
|
+
* `define*` functions and `fetch`. It reads no project file and no secret.
|
|
32
|
+
* `src/__tests__/generated-docs.test.ts` compiles these files in a rendered
|
|
33
|
+
* project and runs the tool.
|
|
34
|
+
*/
|
|
35
|
+
/** The specification version this release implements; the guide answers for it. */
|
|
36
|
+
declare const STARTER_SPECIFICATION_VERSION = "0.2.0";
|
|
37
|
+
/**
|
|
38
|
+
* The starter agent's files, in dependency order. Project paths are stable:
|
|
39
|
+
* the root `AGENTS.md` names them, and no documentation example reuses one.
|
|
40
|
+
*/
|
|
41
|
+
declare const STARTER_AGENT_FILES: ReadonlyArray<{
|
|
42
|
+
path: string;
|
|
43
|
+
content: string;
|
|
44
|
+
label: string;
|
|
45
|
+
}>;
|
|
20
46
|
|
|
21
47
|
type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun';
|
|
22
48
|
interface TemplateFile {
|
|
@@ -63,7 +89,7 @@ declare const FIRST_PARTY_PROVIDER_PACKAGES: readonly ["@standardagents/anthropi
|
|
|
63
89
|
* binaries.
|
|
64
90
|
*/
|
|
65
91
|
declare const APPROVED_DEPENDENCY_BUILD_SCRIPTS: readonly ["@google/genai", "@openrouter/sdk", "esbuild", "protobufjs", "sharp", "workerd"];
|
|
66
|
-
declare const AGENTBUILDER_TEMPLATE_VERSION = "0.45.
|
|
92
|
+
declare const AGENTBUILDER_TEMPLATE_VERSION = "0.45.3";
|
|
67
93
|
declare const DEFAULT_TEMPLATE_VERSIONS: TemplateVersions;
|
|
68
94
|
declare function packageNameFromProjectName(projectName: string): string;
|
|
69
95
|
declare function renderPackageJson(options: AgentBuilderProjectTemplateOptions): string;
|
|
@@ -82,7 +108,18 @@ declare function renderTsConfig(): string;
|
|
|
82
108
|
declare function renderGitignore(): string;
|
|
83
109
|
declare function renderDevVarsExample(): string;
|
|
84
110
|
declare function renderTemplateMetadata(options: AgentBuilderProjectTemplateOptions): string;
|
|
111
|
+
/**
|
|
112
|
+
* Every AGENTS.md a generated project carries, keyed by its directory.
|
|
113
|
+
* The project root comes first; `'.'` is the root. Hosted project creation
|
|
114
|
+
* and the CLI scaffold both read this list, so a directory the root guide
|
|
115
|
+
* names always exists with its own guide.
|
|
116
|
+
*/
|
|
117
|
+
declare const AGENT_DOCS: ReadonlyArray<{
|
|
118
|
+
directory: string;
|
|
119
|
+
content: string;
|
|
120
|
+
label: string;
|
|
121
|
+
}>;
|
|
85
122
|
declare function renderAgentBuilderSupportFiles(options: AgentBuilderProjectTemplateOptions): TemplateFile[];
|
|
86
123
|
declare function renderAgentBuilderProject(options: AgentBuilderProjectTemplateOptions): TemplateFile[];
|
|
87
124
|
|
|
88
|
-
export { AGENTBUILDER_TEMPLATE_VERSION, AGENT_DEFINITIONS_AGENTS_MD as AGENTS_CLAUDE_MD, AGENT_DEFINITIONS_AGENTS_MD, API_AGENTS_MD, API_AGENTS_MD as API_CLAUDE_MD, APPROVED_DEPENDENCY_BUILD_SCRIPTS, type AgentBuilderProjectTemplateOptions, DEFAULT_TEMPLATE_VERSIONS, FIRST_PARTY_PROVIDER_PACKAGES, HANDLERS_AGENTS_MD, HANDLERS_AGENTS_MD as HANDLERS_CLAUDE_MD, HOOKS_AGENTS_MD, HOOKS_AGENTS_MD as HOOKS_CLAUDE_MD, MODELS_AGENTS_MD, MODELS_AGENTS_MD as MODELS_CLAUDE_MD, PROMPTS_AGENTS_MD, PROMPTS_AGENTS_MD as PROMPTS_CLAUDE_MD, PROVIDERS_AGENTS_MD, PROVIDERS_AGENTS_MD as PROVIDERS_CLAUDE_MD, type PackageManager, ROOT_AGENTS_MD, ROOT_AGENTS_MD as ROOT_CLAUDE_MD, TOOLS_AGENTS_MD, TOOLS_AGENTS_MD as TOOLS_CLAUDE_MD, type TemplateFile, type TemplateVersions, USERS_AGENTS_MD, USERS_AGENTS_MD as USERS_CLAUDE_MD, packageNameFromProjectName, renderAgentBuilderProject, renderAgentBuilderSupportFiles, renderDevVarsExample, renderGitignore, renderPackageJson, renderPnpmWorkspaceYaml, renderTemplateMetadata, renderTsConfig, renderViteConfig };
|
|
125
|
+
export { AGENTBUILDER_TEMPLATE_VERSION, AGENT_DEFINITIONS_AGENTS_MD as AGENTS_CLAUDE_MD, AGENT_DEFINITIONS_AGENTS_MD, AGENT_DOCS, API_AGENTS_MD, API_AGENTS_MD as API_CLAUDE_MD, APPROVED_DEPENDENCY_BUILD_SCRIPTS, type AgentBuilderProjectTemplateOptions, DEFAULT_TEMPLATE_VERSIONS, FIRST_PARTY_PROVIDER_PACKAGES, HANDLERS_AGENTS_MD, HANDLERS_AGENTS_MD as HANDLERS_CLAUDE_MD, HOOKS_AGENTS_MD, HOOKS_AGENTS_MD as HOOKS_CLAUDE_MD, MODELS_AGENTS_MD, MODELS_AGENTS_MD as MODELS_CLAUDE_MD, PROMPTS_AGENTS_MD, PROMPTS_AGENTS_MD as PROMPTS_CLAUDE_MD, PROVIDERS_AGENTS_MD, PROVIDERS_AGENTS_MD as PROVIDERS_CLAUDE_MD, type PackageManager, ROOT_AGENTS_MD, ROOT_AGENTS_MD as ROOT_CLAUDE_MD, STARTER_AGENT_FILES, STARTER_SPECIFICATION_VERSION, TOOLS_AGENTS_MD, TOOLS_AGENTS_MD as TOOLS_CLAUDE_MD, type TemplateFile, type TemplateVersions, USERS_AGENTS_MD, USERS_AGENTS_MD as USERS_CLAUDE_MD, packageNameFromProjectName, renderAgentBuilderProject, renderAgentBuilderSupportFiles, renderDevVarsExample, renderGitignore, renderPackageJson, renderPnpmWorkspaceYaml, renderTemplateMetadata, renderTsConfig, renderViteConfig };
|