}
| { type: 'image-delta'; index: number; data: string }
| { type: 'image-done'; index: number; image: ProviderGeneratedImage }
| { type: 'finish'; finishReason: ProviderResponse['finishReason']; usage: ProviderUsage }
| { type: 'error'; error: string; code?: string };
// Errors
type ErrorOrigin =
| `provider:${string}`
| 'platform-router'
| 'runtime'
| `tool:${string}`
| `hook:${string}`;
class ProviderError extends Error {
code: 'rate_limit' | 'invalid_request' | 'auth_error' | 'server_error' | 'timeout' | 'unknown';
statusCode?: number;
retryAfter?: number;
origin?: ErrorOrigin;
upstream?: string;
}
```
---
Source: https://standardagentspec.org/0.2.0/specification/models
# Models
A model definition specifies which Large Language Model (LLM) to use for inference and how to connect to it. Models are referenced by name from prompt definitions and serve as the foundation of the agent system.
Decision inference is defined separately by
[Decisions](/0.2.0/specification/threads/decisions). Decision providers do not
back prompts and do not require a conversational model definition.
## 1. Model Definition
### 1.1 Required Properties
A model definition **MUST** include the following properties:
| Property | Type | Description |
|----------|------|-------------|
| `name` | `string` | Unique identifier for this model. Used when referencing from prompts. |
| `provider` | `ProviderFactory` | Factory function that creates a provider instance. |
| `model` | `string` | The model identifier sent to the provider API. |
### 1.2 Optional Properties
A model definition **MAY** include the following properties:
| Property | Type | Description |
|----------|------|-------------|
| `fallbacks` | `string[]` | Names of fallback models to try if this model fails. |
| `includedProviders` | `string[]` | Provider routing preferences for multi-provider gateways. |
| `inputPrice` | `number` | Cost per 1 million input tokens in USD. |
| `outputPrice` | `number` | Cost per 1 million output tokens in USD. |
| `cachedPrice` | `number` | Cost per 1 million cached input tokens in USD. |
| `capabilities` | `ModelCapabilities` | Feature support and limits for this model. |
| `providerOptions` | `InferProviderOptions` | Provider-specific default options for this model. Type is inferred from the provider's schema. |
| `providerTools` | `string[]` | Provider-embedded tools available for this model. |
## 2. Provider Reference
The `provider` property accepts a provider factory function imported from a provider package. See the [Providers](/0.2.0/specification/providers) specification for the provider interface.
## 3. Fallback Chains
### 3.1 Fallback Behavior
When a model definition includes `fallbacks`, implementations **SHOULD**:
1. Attempt the primary model first
2. If the primary model fails after exhausting retries, try each fallback in order
3. Continue until a model succeeds or all fallbacks are exhausted
### 3.2 Fallback References
Fallback model names **MUST** reference other defined models by their `name` property. Implementations **SHOULD** validate that all referenced fallback models exist at startup.
## 4. Pricing Configuration
### 4.1 Token Pricing
Pricing properties are used for cost tracking and reporting. All prices are expressed in USD per 1 million tokens.
| Property | Description |
|----------|-------------|
| `inputPrice` | Cost for input/prompt tokens |
| `outputPrice` | Cost for output/completion tokens |
| `cachedPrice` | Cost for cached input tokens (when provider supports caching) |
### 4.2 Pricing Priority
Pricing configuration is optional. Providers **MAY** return pricing information per-request (e.g. in response headers or metadata). When provider-reported pricing is available:
- Provider-reported pricing **SHOULD** take priority over static model configuration.
- Static pricing serves as a fallback when provider pricing is unavailable.
- Implementations **MUST** restrict cost information to authorized parties.
## 5. Capabilities
### 5.1 Capability Properties
The `capabilities` object describes features and limits for the model:
| Property | Type | Description |
|----------|------|-------------|
| `reasoningLevels` | `Record` | Maps 0-100 scale to model's native reasoning values. |
| `supportsImages` | `boolean` | Whether the model accepts image inputs. |
| `supportsToolCalls` | `boolean` | Whether the model supports tool/function calling. |
| `supportsStreaming` | `boolean` | Whether the model supports streaming responses. |
| `supportsJsonMode` | `boolean` | Whether the model supports JSON response format. |
| `maxContextTokens` | `number` | Maximum input context window size. |
| `maxOutputTokens` | `number` | Maximum output tokens per response. |
### 5.2 Reasoning Levels
The `reasoningLevels` property maps the 0-100 reasoning scale to model-specific values:
```typescript
// OpenAI o-series models
reasoningLevels: { 0: null, 33: 'low', 66: 'medium', 100: 'high' }
// Binary reasoning (on/off)
reasoningLevels: { 0: null, 100: 'enabled' }
// No reasoning support
reasoningLevels: { 0: null }
```
### 5.3 Default Capabilities
When `capabilities` is not specified or a property is omitted:
- `supportsImages`: Defaults to `false`
- `supportsToolCalls`: Defaults to `true`
- `supportsStreaming`: Defaults to `true`
- `supportsJsonMode`: Defaults to `false`
- `reasoningLevels`: Defaults to `{ 0: null }` (no reasoning)
## 6. Validation
Implementations **MUST** validate that:
1. `name` is non-empty, unique, and does not contain spaces
2. `provider` is a valid provider factory function
3. `model` is not an empty string
Implementations **SHOULD** validate that all `fallbacks` entries reference valid model names.
## 7. TypeScript Reference
```typescript
import type { z, ZodTypeAny } from 'zod';
interface ProviderFactoryConfig {
apiKey: string;
baseUrl?: string;
timeout?: number;
}
/**
* Provider factory with optional typed providerOptions schema.
* The schema property allows type inference and runtime validation.
*/
interface ProviderFactoryWithOptions {
(config: ProviderFactoryConfig): Provider;
/** Zod schema for provider-specific options */
providerOptions?: TOptions;
}
// ProviderFactory is an alias for backward compatibility
type ProviderFactory = ProviderFactoryWithOptions;
/**
* Extract providerOptions type from a provider factory.
* Returns the inferred input type from the provider's Zod schema.
*/
type InferProviderOptions =
P extends ProviderFactoryWithOptions
? S extends ZodTypeAny
? z.input
: Record
: Record;
interface ModelCapabilities {
reasoningLevels?: Record;
supportsImages?: boolean;
supportsToolCalls?: boolean;
supportsStreaming?: boolean;
supportsJsonMode?: boolean;
maxContextTokens?: number;
maxOutputTokens?: number;
}
interface ModelDefinition<
N extends string = string,
P extends ProviderFactoryWithOptions = ProviderFactoryWithOptions
> {
name: N;
provider: P;
model: string;
includedProviders?: string[];
fallbacks?: string[];
inputPrice?: number;
outputPrice?: number;
cachedPrice?: number;
capabilities?: ModelCapabilities;
providerOptions?: InferProviderOptions;
providerTools?: string[];
}
function defineModel>(
options: ModelDefinition
): ModelDefinition;
```
## 8. Typed Provider Options
### 8.1 Overview
Provider packages can export a Zod schema that defines the shape of their `providerOptions`. This enables:
- **TypeScript autocomplete**: IDE suggestions for valid options
- **Type checking**: Compile-time errors for invalid options
- **Runtime validation**: Errors thrown if options don't match schema
### 8.2 How It Works
Provider factories can attach a `providerOptions` property containing a Zod schema:
```typescript
// Inside @standardagents/openai
import { z } from 'zod';
export const openaiProviderOptions = z.object({
service_tier: z.enum(['auto', 'default', 'flex']).optional(),
user: z.string().optional(),
seed: z.number().int().optional(),
frequency_penalty: z.number().min(-2).max(2).optional(),
presence_penalty: z.number().min(-2).max(2).optional(),
}).passthrough();
export const openai: ProviderFactoryWithOptions =
Object.assign(
(config) => new OpenAIProvider(config),
{ providerOptions: openaiProviderOptions }
);
```
When you use this provider with `defineModel`, TypeScript automatically infers the correct type for `providerOptions`:
```typescript
import { defineModel } from '@standardagents/builder';
import { openai } from '@standardagents/openai';
export default defineModel({
name: 'gpt-4o',
provider: openai,
model: 'gpt-4o',
providerOptions: {
service_tier: 'flex', // TypeScript knows this is valid
// typo_field: 'x', // TypeScript ERROR: unknown property
},
});
```
### 8.3 Runtime Validation
When `defineModel` is called, if the provider has a schema and `providerOptions` are provided, the options are validated at runtime:
```typescript
// This throws an error at runtime:
defineModel({
name: 'test',
provider: openai,
model: 'gpt-4o',
providerOptions: {
service_tier: 'invalid', // Error: Invalid enum value
},
});
// Error: Invalid providerOptions for model 'test': service_tier: Invalid enum value
```
### 8.4 Provider Schema Examples
**OpenAI** (`@standardagents/openai`):
```typescript
providerOptions: {
service_tier: 'default' | 'auto' | 'flex',
user: string,
seed: number,
frequency_penalty: number, // -2.0 to 2.0
presence_penalty: number, // -2.0 to 2.0
logprobs: boolean,
top_logprobs: number, // 0-20
store: boolean,
metadata: Record,
}
```
**OpenRouter** (`@standardagents/openrouter`):
```typescript
providerOptions: {
provider: {
order: string[], // Provider slugs to try in order
allow_fallbacks: boolean,
require_parameters: boolean,
data_collection: 'allow' | 'deny',
zdr: boolean, // Zero Data Retention
only: string[], // Restrict to these providers
ignore: string[], // Skip these providers
sort: 'price' | 'throughput' | 'latency',
max_price: {
prompt: number,
completion: number,
request: number,
image: number,
},
quantizations: string[],
preferred_min_throughput: number,
preferred_max_latency: number,
},
}
```
**DeepInfra** (`@standardagents/deepinfra`):
```typescript
providerOptions: {
reasoning_effort: 'none' | 'low' | 'medium' | 'high',
service_tier: 'default' | 'priority' | 'flex',
prompt_cache_key: string,
seed: number,
top_k: number,
min_p: number,
}
```
### 8.5 Sampling Parameters
`providerOptions` is the intended home for sampling and generation parameters — `temperature`, `top_p`, `top_k`, `max_tokens`, `min_p`, seeds, and penalty settings. `defineModel` deliberately has no first-class fields for these: the right values are model-family-specific (one model wants `temperature: 0.3` for deterministic tool loops, another's vendor recommends `1.0` and degrades below it), so they belong on the model definition, next to the model they tune. Options set here are merged onto every request made with the model, after the runtime's standard fields, so they also act as overrides.
```typescript
import { defineModel } from '@standardagents/builder';
import { novita } from '@standardagents/novita';
export default defineModel({
name: 'minimax_m3',
provider: novita,
model: 'minimax/minimax-m3',
// Vendor-recommended sampling rides with the model, not the prompt.
providerOptions: { temperature: 1.0, top_p: 0.95, top_k: 40, max_tokens: 32768 },
});
```
> Tip: Prefer the model vendor's published sampling recommendations over provider defaults, and record them here explicitly — an unset parameter silently rides whatever the provider defaults to, which can change under you.
A prompt can set a [reasoning level and visibility](/0.2.0/specification/prompts#6-reasoning-configuration). Sampling settings belong to the model.
### 8.6 Backward Compatibility
- Providers without a schema still work (accept `Record`)
- Existing model definitions continue to work without changes
- Schema validation is opt-in (only runs if provider exports a schema)
## 9. Examples
### 9.1 Basic Model Definition
```typescript
import { defineModel } from '@standardagents/builder';
import { openai } from '@standardagents/openai';
export default defineModel({
name: 'gpt-4o',
provider: openai,
model: 'gpt-4o',
});
```
### 9.2 Model with Pricing and Capabilities
```typescript
import { defineModel } from '@standardagents/builder';
import { openai } from '@standardagents/openai';
export default defineModel({
name: 'gpt-4o',
provider: openai,
model: 'gpt-4o',
inputPrice: 2.5,
outputPrice: 10,
capabilities: {
supportsImages: true,
supportsToolCalls: true,
supportsJsonMode: true,
maxContextTokens: 128000,
},
});
```
### 9.3 Model with Reasoning Levels
```typescript
import { defineModel } from '@standardagents/builder';
import { openai } from '@standardagents/openai';
export default defineModel({
name: 'o3',
provider: openai,
model: 'o3',
inputPrice: 10,
outputPrice: 40,
capabilities: {
reasoningLevels: { 0: null, 33: 'low', 66: 'medium', 100: 'high' },
supportsImages: true,
supportsToolCalls: true,
},
});
```
### 9.4 Model with Fallback Chain
```typescript
import { defineModel } from '@standardagents/builder';
import { openai } from '@standardagents/openai';
export default defineModel({
name: 'primary-model',
provider: openai,
model: 'gpt-4o',
fallbacks: ['gpt-4-turbo', 'gpt-3.5-turbo'],
inputPrice: 2.5,
outputPrice: 10,
});
```
### 9.5 OpenRouter with Typed Provider Options
```typescript
import { defineModel } from '@standardagents/builder';
import { openrouter } from '@standardagents/openrouter';
export default defineModel({
name: 'claude-3-opus',
provider: openrouter,
model: 'anthropic/claude-3-opus',
inputPrice: 15,
outputPrice: 75,
capabilities: {
supportsImages: true,
supportsToolCalls: true,
},
providerOptions: {
provider: {
zdr: true, // TypeScript knows this is boolean
only: ['anthropic'], // TypeScript knows this is string[]
max_price: {
prompt: 1, // TypeScript autocompletes this structure
completion: 5,
},
},
},
});
```
### 9.6 OpenAI with Typed Provider Options
```typescript
import { defineModel } from '@standardagents/builder';
import { openai } from '@standardagents/openai';
export default defineModel({
name: 'gpt-4o-flex',
provider: openai,
model: 'gpt-4o',
inputPrice: 2.5,
outputPrice: 10,
providerOptions: {
service_tier: 'flex', // TypeScript knows: 'auto' | 'default' | 'flex'
seed: 42, // TypeScript knows this is number
frequency_penalty: 0.5, // TypeScript validates: -2.0 to 2.0
},
});
```
### 9.7 Model with Provider Tools
```typescript
import { defineModel } from '@standardagents/builder';
import { openai } from '@standardagents/openai';
export default defineModel({
name: 'gpt-4o-with-tools',
provider: openai,
model: 'gpt-4o',
inputPrice: 2.5,
outputPrice: 10,
providerTools: ['web_search', 'file_search', 'code_interpreter'],
capabilities: {
supportsImages: true,
supportsToolCalls: true,
},
});
```
Provider tools are built-in capabilities embedded in the provider (e.g., OpenAI's web search, file search, code interpreter). See the [Providers specification](/0.2.0/specification/providers#9-provider-tools) for how providers expose tools.
---
Source: https://standardagentspec.org/0.2.0/specification/tools
# Tools
Tools are callable capabilities exposed to models during execution.
## 1. Tool Categories
| Type | Description | Where Defined |
|------|-------------|---------------|
| Function tool | Custom executable logic | `defineTool()` |
| Prompt tool | Nested prompt invocation | `definePrompt()`, named in another prompt's `tools` |
| Agent tool | Agent handoff callable | `defineAgent({ exposeAsTool: true })` |
Function tools that evaluate model- or user-authored JavaScript or TypeScript **SHOULD** do so through [`state.runCode`](/0.2.0/specification/threads/code-execution) rather than `eval` or `new Function`. The sandbox enforces isolation, memory caps, and caller-initiated termination.
## 2. Function Tool Definition
```typescript
defineTool({
description: 'Search indexed docs',
args: z.object({ query: z.string() }),
execute: async (state, args) => {
const vectorStoreId = await state.env('VECTOR_STORE_ID');
return { status: 'success', result: '...' };
},
variables: [
{
name: 'VECTOR_STORE_ID',
type: 'text',
required: true,
description: 'Vector store identifier',
},
],
});
```
### 2.1 Tool Dependencies
A function tool **MAY** declare `uses` as an array of names of tools, prompts, or agents it may invoke by name through `state.invokeTool()` or `state.queueTool()`. Names may be local or [qualified](/0.2.0/distribution/packaging#qualified-names).
```typescript
uses: ['validate_input', 'format_output'] as const
```
A packed tool **MUST** declare the targets it invokes by name. A package **MUST** include its required tool dependencies. When a `uses` list is supplied, the runtime **MUST** reject an invocation of a target outside the list. `queueTool()` throws an error for an undeclared target. `invokeTool()` returns an error result for an undeclared target. An empty list permits no targets. When `uses` is omitted, this restriction does not apply.
## 3. Variable Declarations
Tool and prompt definitions can declare required variables:
```typescript
interface VariableDefinition {
name: string;
type: 'text' | 'secret';
required: boolean;
scoped?: boolean;
description: string;
}
```
Semantics:
- `required: true` means execution cannot continue until a value resolves.
- `type: 'secret'` indicates sensitive values that should be encrypted at rest.
- `scoped: true` blocks inheritance from parent thread env for that variable name.
- Scoped variables still flow downward from the thread where they are declared/provided to descendants in that subtree.
## 4. Prompt Tool Configuration
When a prompt is used as a tool, callers can configure return shaping and initial input mapping:
```typescript
interface SubpromptConfig {
name: string;
includeTextResponse?: boolean;
includeToolCalls?: boolean;
includeErrors?: boolean;
initUserMessageProperty?: string;
initAttachmentsProperty?: string;
}
```
## 5. Subagent Composition
Subagent relationships are **not tool configuration**; a prompt `tools` entry attempting to configure one is a definition-time error.
Relationships are declared on the owning agent *side* (`SideConfig.subagents`), and the lifecycle tools (`subagents`, `subagent_create`, `subagent_message`) are runtime-injected for a prompt-backed side's non-hidden relationships. The relationship names `subagents`, `subagent_create`, and `subagent_message` are reserved in the tool namespace.
See [Subagents](/0.2.0/specification/subagents) for the `SubagentRelationship` type, ownership rules, lifecycle tool contracts, and cross-thread semantics.
## 6. Attachment Semantics Across Threads
When tool-driven subagent communication crosses thread boundaries:
- parent -> child attachment paths must be copied to child-local paths
- child -> parent attachment paths must be copied to parent-local paths
Returned attachment references must always be valid for the receiving thread filesystem.
## 7. Progress Reporting
A function tool **MAY** declare a `progressArgument` naming an argument whose value is a short, human-readable description of what the tool call is doing — for example `fixing index.html`.
```typescript
defineTool({
description: 'Write a file to the workspace',
progressArgument: 'description',
args: z.object({
description: z.string().describe('e.g. "writing index.html"'),
path: z.string(),
content: z.string(),
}),
execute: async (state, args) => {
return { status: 'success', result: '...' };
},
});
```
Semantics:
- `progressArgument` controls when the [`tool_call_started`](/0.2.0/specification/hooks#51-tool_call_started) hook and the matching `tool_call_started` thread event fire.
- When set, the runtime **SHOULD** wait until *just this argument* has finished streaming from the model — not the whole tool call — and surface its value as `progress`. This lets a UI show what a tool is about to do before a large argument (such as a file's `content`) finishes generating.
- When unset, `tool_call_started` fires as soon as the tool call appears in the model stream: its name is known, but its arguments **MAY** still be incomplete and `progress` is `undefined`.
- The named argument **SHOULD** be declared early in the `args` schema and kept short so it completes quickly.
- If the model never emits the named argument, `tool_call_started` still fires once the tool call finishes, with `progress` undefined.
## 8. Annotations
A function tool **MAY** declare `annotations`: an object of implementation-specific hints, keyed by the runtime or tool that reads them.
```typescript
type ToolAnnotations = Record;
defineTool({
description: 'Run a TypeScript module in a sandbox',
args: z.object({ code: z.string() }),
annotations: {
agentbuilder: { codemode: { codeArgument: 'code', language: 'typescript' } },
},
execute: async (state, args) => {
return { status: 'success', result: '...' };
},
});
```
Semantics:
- Annotations are non-normative. This specification defines no annotation keys, and their meaning belongs to whoever owns the key.
- `defineTool()` **MUST** return `annotations` unchanged on the tool definition.
- A runtime **MAY** read keys it understands, typically to choose how it displays a tool call, and **MUST** ignore keys it does not.
- Annotations **MUST NOT** change argument validation, execution, the tool's results, or what is sent to the model. A tool behaves identically in a runtime that ignores them.
## 9. Conformance Notes
Implementations **MUST**:
- validate tool args against the declared schema.
- execute local tools sequentially in the order they were returned.
- persist tool results as messages before advancing.
- persist tool errors as tool result messages rather than halting execution.
- preserve tool `annotations` and never let them affect execution.
---
Source: https://standardagentspec.org/0.2.0/specification/effects
# Effects
Effects are scheduled side-effect handlers that run outside normal tool execution. They are ideal for delayed notifications, background cleanup, and async operations that should not block a model step.
## 1. Effect Definition
### 1.1 Purpose
Unlike tools, effects:
- do not return output to the LLM
- can be delayed for future execution
- run independently from immediate conversation turn processing
### 1.2 defineEffect
Effects **MUST** be declared with `defineEffect()` and exported as the default export from a file in `agents/effects/`.
With args schema:
```typescript
import { z } from 'zod';
import { defineEffect } from '@standardagents/spec';
export default defineEffect(
'Send a reminder email',
z.object({
to: z.string().email(),
subject: z.string(),
body: z.string(),
}),
async (state, args) => {
// runtime-specific implementation
}
);
```
Without args schema:
```typescript
import { defineEffect } from '@standardagents/spec';
export default defineEffect(
'Clean up stale records',
async (state) => {
// runtime-specific implementation
}
);
```
### 1.3 Naming
- Effect names are file-based (`agents/effects/send_digest.ts` => `send_digest`)
- Names **SHOULD** use `snake_case`
- Names **MUST** be unique within the active namespace
## 2. Scheduling Effects
Effects are scheduled through `ThreadState.scheduleEffect(name, args, delay?)`.
```typescript
await state.scheduleEffect(
'send_reminder_email',
{ to: 'user@example.com', subject: 'Reminder', body: 'Hello!' },
30 * 60 * 1000
);
```
### 2.1 Packed Effect Names
Runtimes should support [qualified names](/0.2.0/distribution/packaging#qualified-names) for packed effects.
Example:
```typescript
await state.scheduleEffect('standardagent-sales/send_digest', { accountId: 'acct_123' }, 0);
```
This avoids collisions between global and package-local effect names.
## 3. Execution Semantics
Runtimes:
- **MUST** enqueue effects asynchronously for execution.
- **MUST** preserve scheduled `args` until execution time.
- **SHOULD** expose inspection and cancellation APIs (`getScheduledEffects`, `removeScheduledEffect`).
- **SHOULD** keep effect handlers idempotent.
Effect execution is runtime-managed and may occur after the invoking conversation has completed.
## 4. Type Definitions
```typescript
export type Effect =
Args extends ToolArgs
? (state: State, args: z.infer) => Promise | void
: (state: State) => Promise | void;
export type EffectDefinition =
[string, Args, Effect];
```
See also:
- [Threads](/0.2.0/specification/threads) for the scheduling APIs on `ThreadState`
- [Code Execution](/0.2.0/specification/threads/code-execution) for effects that evaluate JS/TS via `state.runCode`
- [Packaging](/0.2.0/distribution/packaging) for packed effect export structure
---
Source: https://standardagentspec.org/0.2.0/specification/prompts
# Prompts
A prompt defines how each request to an LLM is crafted. It specifies system instructions, a model reference, available tools, and behavioral configuration that shapes how the agent responds.
## 1. Prompt Definition
Each prompt specifies system instructions, a model reference, and optional configuration for tools, input validation, and response behavior.
### 1.1 Required Properties
A prompt definition **MUST** include the following properties:
| Property | Type | Description |
|----------|------|-------------|
| `name` | `string` | Unique identifier for this prompt |
| `toolDescription` | `string` | Description shown when prompt is exposed as a tool |
| `prompt` | `PromptContent` | System prompt content (string or structured) |
| `model` | `string` | Model reference to use for this prompt |
### 1.2 Optional Properties
A prompt definition **MAY** include the following properties:
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `includeChat` | `boolean` | `false` | Include full chat history |
| `includePastTools` | `boolean` | `false` | Include past tool results |
| `parallelToolCalls` | `boolean` | Provider default | Allow parallel tool execution |
| `toolChoice` | `'auto' \| 'none' \| 'required'` | `'auto'` | Tool calling strategy |
| `requiredSchema` | `ZodSchema` | - | Input validation schema |
| `tools` | `(string \| PromptToolConfig \| SubpromptConfig)[]` | - | Available tools, sub-prompts, and handoff agent tools. Subagent relationships are **not** declared here — see [§3.4](#34-subagent-lifecycle-tools) |
| `variables` | `VariableDefinition[]` | - | Variable declarations consumed by this prompt |
| `env` | `Record` | - | Prompt-level default environment variable values |
| `reasoning` | `ReasoningConfig` | - | Extended thinking config |
| `recentImageThreshold` | `number` | `10` | Messages to keep images |
| `hooks` | `string[]` | - | Hook IDs to run for this prompt |
An explicit `parallelToolCalls` value controls the provider option. When omitted, the provider default applies.
## 2. Prompt Content
### 2.1 String Prompts
The simplest form is a plain string containing the system instructions:
```typescript
prompt: 'You are a helpful assistant. Be concise and accurate.'
```
System prompts **MUST NOT** contain secrets or sensitive credentials. Implementations **MUST** sanitize prompt content that incorporates untrusted input to prevent injection.
### 2.2 Structured Prompts
For composition and reuse, prompts can be structured arrays of parts:
```typescript
prompt: [
{ type: 'text', content: 'You are a helpful assistant.\n\n' },
{ type: 'include', prompt: 'common_rules' },
{ type: 'text', content: '\n\nBe concise.' },
]
```
### 2.3 Prompt Parts
#### 2.3.1 Text Parts
Text parts contain static content:
| Property | Type | Description |
|----------|------|-------------|
| `type` | `'text'` | Discriminator |
| `content` | `string` | Text content |
#### 2.3.2 Include Parts
Include parts reference other prompts:
| Property | Type | Description |
|----------|------|-------------|
| `type` | `'include'` | Discriminator |
| `prompt` | `string` | Name of prompt to include |
### 2.4 Include Resolution
When a prompt includes another prompt:
1. Implementations **MUST** recursively resolve all includes
2. Implementations **MUST** detect and reject circular includes
3. The included prompt's content is inserted at the include location
4. Only the `prompt` field is included (not tools, model, etc.)
## 3. Tool Configuration
### 3.1 Simple Tool References
Tools can be referenced by name:
```typescript
tools: ['search_docs', 'create_ticket', 'send_email']
```
### 3.2 Tool Configuration with Environment Values
Tools can be configured with thread variable values using `env`. This allows prompts to provide default values for tools that need runtime configuration:
```typescript
tools: [
'search_docs', // Simple reference
{
name: 'file_search', // Tool with env configuration
env: {
VECTOR_STORE_ID: 'vs_abc123',
},
},
]
```
| Property | Type | Description |
|----------|------|-------------|
| `name` | `string` | Name of the tool |
| `env` | `Record` | Environment variable values for this tool |
| `options` | `Record` | Static tool options |
Prompt-level `env` values serve as defaults. They can be overridden by higher-precedence sources. See the [Tools specification](/0.2.0/specification/tools) for variable declaration details.
### 3.3 Sub-Prompt Tool Configuration
When a prompt is used as a tool by another prompt, the caller can configure how results are returned. These options **only apply to sub-prompts**, not to regular function tools.
Since sub-prompts return their results as tool call responses, all output must be serialized into a single text string. The configuration options control what gets included in that string.
```typescript
tools: [
'search_docs', // Simple reference (function tool)
{
name: 'summarize_document', // Sub-prompt with configuration
includeTextResponse: true,
includeToolCalls: false,
includeErrors: true,
initUserMessageProperty: 'document',
},
{
name: 'analyze_image', // Sub-prompt with attachment configuration
initUserMessageProperty: 'question',
initAttachmentsProperty: 'image_path',
},
{
name: 'support_handoff', // Handoff agent (human-sided) with initial message
initUserMessageProperty: 'customer_query',
},
]
```
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `name` | `string` | Required | Name of the sub-prompt or agent to call |
| `includeTextResponse` | `boolean` | `true` | Include the sub-prompt's text response in the result string |
| `includeToolCalls` | `boolean` | `true` | Serialize tool calls made by the sub-prompt (and their results) into the result string |
| `includeErrors` | `boolean` | `true` | Serialize any errors from the sub-prompt into the result string |
| `initUserMessageProperty` | `string` | - | Use this argument property as the initial user message when invoking the sub-prompt or agent |
| `initAttachmentsProperty` | `string` | - | Use this argument property (file path or array of paths) as attachments in the initial user message |
The `initUserMessageProperty` is useful when the sub-prompt expects conversational input. For example, if `initUserMessageProperty: 'query'` is set and the caller passes `{ query: 'What is X?' }`, the sub-prompt receives "What is X?" as its initial user message.
The `initAttachmentsProperty` allows passing file attachments (images, documents) to the sub-prompt. The property value should be a file path string or an array of paths. For example, if `initAttachmentsProperty: 'image'` is set and the caller passes `{ image: '/attachments/photo.jpg' }`, the sub-prompt receives the image as an attachment.
> **Tip:** Combine `initUserMessageProperty` with `includeChat: false` on the sub-prompt. The sub-prompt then receives only its own system prompt and the initial user message — a smaller, focused context that reduces token usage.
### 3.4 Subagent Lifecycle Tools
Prompts do not declare subagent relationships, and a `tools` entry attempting to configure one **MUST** be rejected at definition time.
When a prompt backs an agent side that declares [`subagents` relationships](/0.2.0/specification/subagents), the runtime automatically injects the lifecycle tools — `subagents`, `subagent_create`, and `subagent_message` — scoped to that side's non-hidden relationships. The prompt does nothing to receive them; the *side's declaration* is the grant. The same prompt reused on a side with no relationships receives no lifecycle tools — composition relationships never travel with prompts.
The names `subagents`, `subagent_create`, and `subagent_message` are reserved in the tool namespace.
## 4. Tool Choice Strategy
### 4.1 Strategy Values
The `toolChoice` property controls how the LLM calls tools:
| Value | Behavior |
|-------|----------|
| `'auto'` | Model decides when to call tools (default) |
| `'none'` | The model must not call tools (definitions may still be sent) |
| `'required'` | Force the model to call at least one tool |
### 4.2 Tool Choice Behavior
When `toolChoice` is `'required'`:
- The LLM **MUST** include at least one tool call in its response
- Implementations **SHOULD** retry if the LLM fails to call a tool
When `toolChoice` is `'none'`:
- The LLM **MUST NOT** call a tool in its response
- Implementations **MUST** pass `toolChoice: 'none'` to the provider with any tool definitions they send
- Tool definitions **MAY** still be sent. Sending them keeps the request prefix identical to that of a prompt that shares the same tools, which preserves provider prompt caching. An implementation that sends no tool definitions may omit the tool choice.
## 5. Input Validation
### 5.1 Required Schema
The `requiredSchema` property defines inputs when the prompt is called as a tool:
```typescript
requiredSchema: z.object({
query: z.string().describe('Search query'),
limit: z.number().optional().default(10).describe('Max results'),
})
```
### 5.2 Schema Usage
When a required schema is provided:
1. Implementations **MUST** validate inputs against the schema
2. Implementations **MUST** generate JSON Schema for LLM tool definitions
3. Field descriptions from `.describe()` **SHOULD** be included
User inputs **MUST** be validated before inclusion in prompts.
> **Tip:** TypeScript implementations can use the `PromptInput` helper to extract the inferred input type from a prompt's schema: `type SearchInput = PromptInput`.
## 6. Reasoning Configuration
### 6.1 Reasoning Properties
For models with extended thinking capabilities:
| Property | Type | Description |
|----------|------|-------------|
| `level` | `number` | Reasoning level from 0 to 100 |
| `maxTokens` | `number` | Max tokens for reasoning |
| `exclude` | `boolean` | Exclude reasoning from response |
| `include` | `boolean` | Supply the persisted reasoning of earlier messages on later requests. Defaults to `true` |
### 6.2 Reasoning Levels
The `level` property uses the [reasoning scale](/0.2.0/specification/providers#22-reasoning-levels). An unset `level` uses the model's default reasoning behavior. A level of `0` requests no reasoning.
### 6.3 Reasoning Visibility
- When `exclude` is `true`, reasoning is used internally but not returned
- When `include` is `true` or unset, the runtime supplies the persisted reasoning of earlier assistant messages on later requests ([Messages §1.3](/0.2.0/specification/threads/messages#13-reasoning))
- When `include` is `false`, the runtime does not supply it. The reasoning stays in the persisted message record
- These can be combined for different use cases
## 7. Image Context Management
The `recentImageThreshold` property controls how images are handled in conversation context:
- Images in the most recent N messages are kept as full image content
- Older images are replaced with text descriptions
- Helps manage context window usage in long conversations
## 8. Hook Scoping
The `hooks` property declares which hooks run when this prompt is active. Hook IDs reference hooks defined in `agents/hooks/` using `defineHook()`.
```typescript
definePrompt({
name: 'customer_support',
// ...
hooks: ['limit_to_20_messages', 'log_tool_calls', 'redact_credit_cards'],
});
```
**Behavior:**
- When `hooks` is non-empty, only those hooks form the prompt base set
- When `hooks` is omitted or empty, the runtime falls back to agent-level hooks
- Hook IDs reference the `id` property from `defineHook({ hook, id, execute })`
- See the [Hooks specification](/0.2.0/specification/hooks) for hook definition details
This allows different prompts within the same agent to use different hooks. For example, a classifier prompt might skip message filtering hooks while a support prompt includes them.
## 9. Validation
### 9.1 Required Field Validation
Implementations **MUST** validate that:
1. `name` is a non-empty string
2. `toolDescription` is a non-empty string
3. `model` references a defined model
4. `prompt` is either a string or valid structured array
### 9.2 Optional Field Validation
Implementations **MUST** validate that:
1. `toolChoice` is one of: `'auto'`, `'none'`, `'required'`
2. `reasoning.level` is a number from 0 to 100
3. `recentImageThreshold` is a positive integer
## 10. TypeScript Reference
```typescript
/**
* Text part of a structured prompt.
*/
interface PromptTextPart {
type: 'text';
content: string;
}
/**
* Include part referencing another prompt.
*/
interface PromptIncludePart {
type: 'include';
prompt: string;
}
/**
* Union of prompt part types.
*/
type PromptPart = PromptTextPart | PromptIncludePart;
/**
* Structured prompt array.
*/
type StructuredPrompt = PromptPart[];
/**
* Prompt content (string or structured).
*/
type PromptContent = string | StructuredPrompt;
/**
* Configuration for tools with env values.
*/
interface PromptToolConfig {
name: string;
env?: Record;
options?: Record;
}
/**
* Configuration for sub-prompts or agents used as tools.
* These options control how results are returned and how initial messages are constructed.
*/
interface SubpromptConfig {
name: T;
includeTextResponse?: boolean;
includeToolCalls?: boolean;
includeErrors?: boolean;
initUserMessageProperty?: string;
initAttachmentsProperty?: string;
}
/**
* Reasoning configuration.
*/
interface ReasoningConfig {
level?: number;
maxTokens?: number;
exclude?: boolean;
include?: boolean;
}
/**
* Prompt definition configuration.
*/
interface PromptDefinition<
N extends string = string,
S extends ToolArgs = ToolArgs,
> {
name: N;
toolDescription: string;
prompt: PromptContent;
model: string;
includeChat?: boolean;
includePastTools?: boolean;
parallelToolCalls?: boolean;
toolChoice?: 'auto' | 'none' | 'required';
requiredSchema?: S;
tools?: (string | PromptToolConfig | SubpromptConfig)[];
variables?: Array<{
name: string;
type: 'text' | 'secret';
required: boolean;
description: string;
}>;
env?: Record;
reasoning?: ReasoningConfig;
recentImageThreshold?: number;
hooks?: string[];
}
/**
* Helper type for input inference.
*/
type PromptInput =
T['requiredSchema'] extends ToolArgs
? z.infer
: never;
/**
* Define a prompt configuration.
*/
function definePrompt(
options: PromptDefinition
): PromptDefinition;
```
## 11. Examples
### 11.1 Basic Prompt
```typescript
import { definePrompt } from '@standardagents/spec';
export default definePrompt({
name: 'assistant',
toolDescription: 'General purpose assistant',
model: 'conversational',
prompt: 'You are a helpful assistant. Be concise and accurate.',
});
```
### 11.2 Prompt with Tools
```typescript
import { definePrompt } from '@standardagents/spec';
import { z } from 'zod';
export default definePrompt({
name: 'customer_support',
toolDescription: 'Handle customer support inquiries',
model: 'conversational',
prompt: `You are a customer support agent.
Always be polite and try to resolve issues quickly.
If you cannot help, offer to escalate.`,
tools: ['search_knowledge_base', 'create_ticket'],
includeChat: true,
requiredSchema: z.object({
query: z.string().describe('The customer inquiry'),
}),
});
```
### 11.3 Structured Prompt with Includes
```typescript
import { definePrompt } from '@standardagents/spec';
export default definePrompt({
name: 'sales_agent',
toolDescription: 'Handle sales inquiries',
model: 'conversational',
prompt: [
{ type: 'text', content: 'You are a sales representative.\n\n' },
{ type: 'include', prompt: 'company_info' },
{ type: 'include', prompt: 'product_catalog' },
{ type: 'text', content: '\n\nBe helpful and persuasive.' },
],
tools: ['get_pricing', 'schedule_demo'],
});
```
### 11.4 Prompt with Reasoning
```typescript
import { definePrompt } from '@standardagents/spec';
export default definePrompt({
name: 'code_reviewer',
toolDescription: 'Review code for issues and improvements',
model: 'heavy',
prompt: 'You are an expert code reviewer. Analyze code thoroughly.',
reasoning: {
level: 100,
maxTokens: 4096,
exclude: false,
},
});
```
### 11.5 Prompt with Hooks
```typescript
import { definePrompt } from '@standardagents/spec';
export default definePrompt({
name: 'customer_support',
toolDescription: 'Handle customer support inquiries',
model: 'conversational',
prompt: 'You are a customer support agent. Be helpful and concise.',
tools: ['search_knowledge_base', 'create_ticket'],
includeChat: true,
hooks: ['limit_to_20_messages', 'log_tool_calls', 'redact_credit_cards'],
});
```
---
Source: https://standardagentspec.org/0.2.0/specification/handlers
# Handlers
A handler is a function that takes one side's turns in a conversation. When a side of an [agent](/0.2.0/specification/agents) is backed by a handler, the runtime does not call a model to answer an inbound message — it calls the handler function once, with the thread state and the message, and whatever that function does is the side's turn.
A handler is **not** a hook (hooks decorate turns owned by something else, and their failures are non-fatal), **not** a tool (tools are capabilities a turn-owner chooses to invoke), and **not** an effect (effects run outside the conversation flow). Its only role is backing a side of an agent.
## 1. Handler Definition
Handlers live in their own definition directory (`agents/handlers/` in the conventional layout) and are created with `defineHandler()`:
```typescript
// agents/handlers/relay_pipe.ts
import { defineHandler } from '@standardagents/spec';
export default defineHandler({
description: 'Forwards inbound user traffic to the assistant child and relays answers back.',
execute: async (state, message) => {
// full ThreadState — forward, respond, spawn, stop, read/write KV
},
});
```
| Property | Type | Description |
|----------|------|-------------|
| `description` | `string` | Optional human-facing summary |
| `execute` | `(state: ThreadState, message: Message) => Promise` | The turn implementation |
The `message` parameter is the full persisted [`Message`](/0.2.0/specification/threads/messages#1-message-structure) — id, role, content, silent flag, metadata, timestamps. It is not a narrowed view: handlers are trusted definition code, like tools.
## 2. Referencing a Handler
A handler is referenced from exactly one place: the `handler` property of a [side configuration](/0.2.0/specification/agents#12-sideconfig).
```typescript
defineAgent({
name: 'relay_agent',
sideA: { handler: 'relay_pipe', subagents: [{ agent: 'assistant_agent', maxInstances: 1 }] },
sideB: { human: true },
});
```
Handlers **MUST NOT** be referenced by prompt `tools` arrays, hook lists, or effect schedules. Implementations **MUST** reject such references at definition time. This keeps the taxonomy crisp — code that wants a capability writes a tool; code that wants to decorate writes a hook; code that owns turns is a handler.
## 3. Execution Model
A handler-backed side's turn is:
1. An inbound message arrives on the side's perspective.
2. The runtime invokes the handler once with the thread's `ThreadState` and that message.
3. The invocation returns (or throws). The turn is complete.
There are no steps, no tool-choice loop, and no model requests for this side. Consequences:
- `maxSteps`, `stopOnResponse`, `stopTool`, and session bindings are not legal on handler sides — a handler turn has no steps to cap and ends when `execute` returns. Handlers end sessions explicitly via [`state.stopSession()`](/0.2.0/specification/threads#9-subagent-hierarchy-communication-and-termination).
- When the agent sets `maxSessionTurns`, a handler turn counts toward the exchange cap exactly like a prompt turn — exchange counting is uniform across backings.
## 4. Delivery Semantics
Delivery to a handler is **exactly-once per message**:
- The runtime **MUST** invoke the handler exactly once for each inbound message on the side's perspective, in message persistence order.
- The runtime **MUST NOT** invoke a handler concurrently for the same thread. Messages that arrive while a handler turn is in flight **MUST** wait in the queue and be delivered one at a time, in order, after the current turn completes.
- The runtime **MUST NOT** automatically redeliver a message whose handler invocation failed. Retry is a userland decision (re-send the message).
> **Warning:** Because queued messages wait behind the in-flight turn, a long-running handler stalls its thread. In particular, a handler that awaits a `blocking` child session holds the delivery slot for that session's entire duration — and if that child can only finish after *another* inbound message on this thread, the thread deadlocks. Relay-style handlers **SHOULD** forward without blocking (`queueMessage` toward the child) and treat the child's replies as ordinary later turns.
Cross-thread fan-in ordering (two children queueing toward the same parent handler) is implementation-defined; only per-thread persistence order is guaranteed.
## 5. Error Semantics
A handler that throws is **fatal to the turn, and only the turn**:
- The turn is marked failed. The error **MUST** be surfaced on the runtime's request/execution log as a runtime-origin failure — a throwing handler never silently swallows a message.
- The inbound message stays persisted. Nothing is rolled back.
- The **session continues**: the failure does not end the session, terminate the thread, or poison the queue. The next inbound message gets a fresh handler invocation.
This is deliberately unlike hooks (whose failures are non-fatal to the turn they decorate) and unlike session failure (`sessionFail` / `stopSession`), which a handler must invoke explicitly if an error should end the session.
## 6. Capabilities
A handler receives the full [`ThreadState`](/0.2.0/specification/threads) and may do anything tools can do:
- **Forward** — `(await state.getChildThread(ref)).queueMessage(...)` toward a child, or `state.notifyParent(...)` toward a parent.
- **Respond** — `state.injectMessage({ role, content })` in its own side's role (`assistant` for side A, `user` for side B — see [perspective mapping](/0.2.0/specification/threads/messages#4-queueing-messages)).
- **Spawn** — create child instances of the side's declared [relationships](/0.2.0/specification/subagents) via lifecycle APIs.
- **Control** — `state.stopSession()`, `state.setStatus()`, effects, environment, key-value store, filesystem.
Handlers need no tool grants for children: the side's `subagents` declarations establish existence and lifecycle, and the handler reaches children through `ThreadState` directly. (The injected lifecycle *tools* exist for prompts — a handler calls the same operations as code.)
## 7. The Outbound Boundary
Handlers get no auto-injected reply channel. If a handler (or the side it feeds) should speak to a user or an external surface, that is userland code — a tool or handler calling the messaging surface it chooses (the `message_user` pattern).
This is a deliberate specification boundary: **the runtime routes inbound; userland decides outbound.** A runtime-injected "reply" channel was considered and rejected — it would hard-code one outbound topology into the spec and every runtime, where a five-line userland call expresses any of them.
## 8. Livelock Discipline
Handler sides do not run away on their own — a handler runs only when a message arrives. But a handler that *replies to every inbound message* paired with a prompt-backed side creates a message ping-pong with no natural stop. Handler authors own their termination discipline:
- reply conditionally, not unconditionally;
- or set `maxSessionTurns` on the agent (available on every shape) as a hard safety valve;
- or end the session explicitly with `state.stopSession()` when the work is done.
## 9. Worked Example: the Relay
A user-facing thread that does **zero model work**: every inbound user message is forwarded verbatim to a composed assistant child; every child answer is relayed back out through userland messaging. One handler expresses the entire surface:
```typescript
// agents/handlers/relay_pipe.ts
export default defineHandler({
description: 'Pipe user traffic to the assistant child; relay answers outward.',
execute: async (state, message) => {
const child = state.children.find(c => c.relationship === 'assistant_agent');
if (child) {
const thread = await state.getChildThread(child.reference);
await thread?.queueMessage({ role: 'user', content: message.content ?? '' });
}
},
});
// agents/agents/relay_agent.ts
export default defineAgent({
name: 'relay_agent',
sideA: {
handler: 'relay_pipe',
subagents: [{
agent: 'assistant_agent',
maxInstances: 1,
immediate: true, // spawned at thread creation — see Subagents §3
parentCommunication: 'explicit',
}],
},
sideB: { human: true },
});
```
The child's answers arrive as inbound messages on side A (the owning side) and get their own handler turns, where the handler calls the project's outbound messaging tool. No model participates at any point.
## 10. TypeScript Reference
```typescript
interface HandlerDefinition {
description?: string;
execute: (state: ThreadState, message: Message) => Promise;
}
function defineHandler(options: HandlerDefinition): HandlerDefinition;
```
Handler names participate in the [type registry](/0.2.0/specification/type-registry) via `HandlerRegistry`, so `HandlerSide.handler` narrows to defined handler names when generation is active.
---
Source: https://standardagentspec.org/0.2.0/specification/agents
# Agents
An agent is the top-level conversation orchestrator in Standard Agents. An agent has **exactly two sides**, and each side is **backed** by exactly one of three things: a human, a prompt, or a handler. There is no agent "type": everything about how an agent converses, composes, and terminates is **derived from the backings** of its two sides.
A consistent division of responsibility runs through this page and every page it links to: prompts and handlers own turns, tools provide capabilities, hooks decorate turns, effects defer work, and subagent relationships define composition.
## 1. Sides and Backings
### 1.1 The Three Backings
| Backing | Who takes this side's turns | Declared as |
|---------|-----------------------------|-------------|
| **Human** | A person, via whatever interface the runtime provides | `{ human: true }` |
| **Prompt** | A model, driven by a [prompt](/0.2.0/specification/prompts) | `{ prompt: 'name', ... }` |
| **Handler** | Deterministic code — a [handler](/0.2.0/specification/handlers) | `{ handler: 'name', ... }` |
A **handler** is a function the runtime calls to take that side's turns — not a hook, not a tool, and not an effect. See [Handlers](/0.2.0/specification/handlers).
For a **human** backing, the specification defines only the waiting state: when it is a human-backed side's turn, the session parks awaiting human input, and the turn is fulfilled by an inbound message on that side's perspective. The specification deliberately does **not** define who the person is or how their input arrives — identity, notification, and reply surfaces are runtime and interface concerns.
### 1.2 SideConfig
A side's configuration is discriminated by its backing: exactly one of `human`, `prompt`, or `handler` **MUST** be present.
**HumanSide**
| Property | Type | Description |
|----------|------|-------------|
| `human` | `true` | Required discriminator |
| `label` | `string` | Optional UI/log label |
No other properties are legal on a human side. In particular, `subagents` is a definition-time error (nothing on a human side can invoke them), and stop/session bindings are meaningless.
**PromptSide**
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `prompt` | `string` | Required | Prompt name for this side |
| `label` | `string` | - | UI/log label |
| `subagents` | `SubagentRelationship[]` | - | Side-owned child relationships. See [Subagents](/0.2.0/specification/subagents) |
| `stopOnResponse` | `boolean` | `true` | Stop side turn on text response without tool calls |
| `stopTool` | `string` | - | Stop side turn when this tool is called |
| `stopToolResponseProperty` | `string` | - | Extracted property for stop tool outcomes |
| `maxSteps` | `number` | - | Per-side step safety limit |
| `sessionStop` | `SessionToolBinding` | - | End session successfully (object form only, see [§3](#3-sessiontoolbinding)) |
| `sessionFail` | `SessionToolBinding` | - | End session with failure |
| `sessionStatus` | `SessionToolBinding` | - | Publish status updates |
**HandlerSide**
| Property | Type | Description |
|----------|------|-------------|
| `handler` | `string` | Required — handler name for this side |
| `label` | `string` | Optional UI/log label |
| `subagents` | `SubagentRelationship[]` | Side-owned child relationships. See [Subagents](/0.2.0/specification/subagents) |
Handler sides have no `maxSteps`, `stopOnResponse`, or session bindings: a handler turn is a single invocation, and handlers end sessions through `ThreadState` APIs (`state.stopSession()`) rather than declarative bindings.
### 1.3 Derivations
The following rules are derived from the sides' backings and are never declared separately:
- **Chat surface** — the primary conversational interface renders wherever a `human` backing is. A human on side A is legal.
- **Perspective** — role mapping is the single source of perspective truth: `role: 'user'` is the side B perspective, `role: 'assistant'` is the side A perspective — for queueing, injection, and rendering alike. See [Messages](/0.2.0/specification/threads/messages#4-queueing-messages).
- **Subagent eligibility** — *any* agent may be composed as a subagent. Composing a child with a human side puts a person's step inside the composition: the child session pauses until that person responds ([§7](#7-human-in-the-loop-composition)).
- **Termination discipline** — `maxSessionTurns` is *optional on every agent shape*. Exchange counting is uniform across backings: a handler turn counts like a prompt turn when a cap is set. Two prompt-backed sides can ping-pong indefinitely, and a handler that replies to every inbound message can livelock against a prompt side just as hard — the cap is a voluntary safety valve available everywhere, and prompt and handler authors own their termination discipline.
## 2. AgentDefinition
### 2.1 Required
| Property | Type | Description |
|----------|------|-------------|
| `name` | `string` | Unique agent identifier |
| `sideA` | `SideConfig` | Side A configuration |
| `sideB` | `SideConfig` | Side B configuration |
Both sides are explicit. There is no implicit "missing side B is a human" default — if a person takes side B's turns, write `sideB: { human: true }`.
### 2.2 Optional
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `maxSessionTurns` | `number` | - | Session exchange safety cap ([§1.3](#13-derivations)) |
| `title` | `string` | - | Human-readable label |
| `description` | `string` | - | Agent summary |
| `icon` | `string` | - | Display icon |
| `primary` | `boolean` | `true` | Whether the agent is a user-facing entry point. Clients omit non-primary agents from agent pickers. A non-primary agent remains addressable |
| `exposeAsTool` | `boolean` | `false` | Expose callable entrypoint ([§5](#5-tool-exposure)) |
| `toolDescription` | `string` | - | Callable description |
| `env` | `Record` | - | Agent-level default variable values |
| `hooks` | `string[]` | - | Fallback hook IDs |
| `parentHooks` | `ParentHookRequirement[]` | - | Required hooks automatically contributed to a direct parent composition ([§6](#6-required-parent-hooks)) |
`AgentDefinition` also accepts optional packaging metadata — `packageName`, `version`, `author`, `license` — consumed only when the agent is packed for distribution. See [Packaging](/0.2.0/distribution/packaging).
## 3. SessionToolBinding
Session lifecycle bindings use the object form:
```typescript
interface SessionToolBinding {
name: string;
messageProperty?: string;
attachmentsProperty?: string;
}
```
- `name`: tool that controls the lifecycle action
- `messageProperty`: which arg field becomes lifecycle message text
- `attachmentsProperty`: which arg field contains attachment path(s)
For composed children, mapped stop/fail payloads are the canonical child → parent result/failure payload.
## 4. Stop Semantics
Runtime stop evaluation order for prompt-backed sides:
1. session-level terminal bindings (`sessionStop` / `sessionFail`)
2. side-level stop bindings (`stopTool`)
3. response stop (`stopOnResponse`)
4. safety limits (`maxSteps`, `maxSessionTurns`)
A handler-backed side's turn ends when its handler invocation returns ([Handlers §3](/0.2.0/specification/handlers#3-execution-model)). A human-backed side's turn ends when the human's inbound message is persisted.
## 5. Tool Exposure
When `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.
Composition into a **child thread** is not a prompt-tools concern: it is declared as a `SubagentRelationship` on the composing side. See [Subagents](/0.2.0/specification/subagents). `exposeAsTool` + `toolDescription` are the composability contract — `toolDescription` is the default model-facing description when the agent is composed, and any agent may be composed.
## 6. Required Parent Hooks
An exposed agent MAY declare thread-scoped hooks that are required for the composed relationship to work correctly:
```typescript
interface ParentHookRequirement {
hook: string;
reason: string;
stage?: 'before_parent' | 'after_parent';
}
defineAgent({
name: 'gmail_agent',
exposeAsTool: true,
parentHooks: [{
hook: 'gmail_context',
reason: 'Makes newly synchronized Gmail context visible to the coordinator.',
stage: 'before_parent',
}],
// ...
});
```
Downloading or installing a package is inert. Declaring a `SubagentRelationship` targeting the agent (or adding it to an enabled parent prompt as a handoff) is what composes it, and composing it **MUST** activate every `parentHooks` requirement automatically. A second accept-list is not required: composition UIs **MUST** disclose the hook ID, reason, and stage before the relationship is added or enabled.
The following rules are normative:
- Any agent with `exposeAsTool: true` MAY declare `parentHooks` — any agent is composable, so any exposed agent may carry composition requirements.
- Requirements apply only to direct parent relationships; they do not propagate transitively through the child graph.
- `optional` relationships contribute hooks only while their flag is enabled. `hidden: true` affects model visibility, not composition, so hidden enabled relationships still contribute their required hooks.
- Each requirement names a thread-scoped hook in the child's own package namespace. User-scoped hooks cannot be required on a parent.
- The hook receives the parent's `ThreadState` and remains active for the lifetime of the enabled relationship. It applies during every prompt on either side of the parent.
- Missing, invalid, or unloadable required hooks **MUST** fail composition closed. Runtimes must not silently run a partially installed child.
- Duplicate hook IDs within one child's `parentHooks` declaration are invalid.
Required parent hooks are part of the child's public behavioral contract, not an installer side effect. Optional child features that would change this contract require a separately configured child definition; absence from a required list does not mean "best effort." Ordering and provenance are defined in [Hooks §1.3](/0.2.0/specification/hooks#13-hook-scoping).
## 7. Human-in-the-Loop Composition
Because any agent may be composed as a child, composing an agent with a human side puts a person's step inside an otherwise automated composition. When execution reaches the human-backed side's turn, the child session pauses: the child's registry status becomes `awaiting_human`, and the session resumes when a human's inbound message arrives on that side's perspective.
This is a deliberate capability, not an accident of the model. The canonical use is an **approval gate**:
```typescript
// agents/agents/approval_gate.ts — a child that asks a person before proceeding
export default defineAgent({
name: 'approval_gate',
exposeAsTool: true,
toolDescription: 'Request human approval for a proposed action. Returns the decision.',
sideA: {
prompt: 'approval_presenter', // renders the request, records the outcome
sessionStop: { name: 'record_decision', messageProperty: 'decision' },
},
sideB: { human: true }, // the approver
});
```
An orchestrator declares this child on one of its sides (see [Subagents](/0.2.0/specification/subagents)), spawns it with the proposed action, and the child parks in `awaiting_human` until the approver responds. The runtime does not define who sees the parked session or through which interface they answer — only the waiting state and its fulfillment.
Definition-time note: `subagents` on the *human* side of any agent remains an error — the human side of an approval gate cannot own children.
## 8. Definition-Time Errors
Implementations **MUST** reject the following at definition time:
1. Both sides human — **reserved**. The mediated human↔human thread is coherent and the restriction may lift in a later version, but 0.2.0 runtimes MUST reject it.
2. `subagents` declared on a human-backed side.
3. A side with zero backings, or more than one of `human` / `prompt` / `handler`.
4. A handler side referencing an undefined handler; a prompt side referencing an undefined prompt.
5. A relationship name (`as`) appearing on both sides of one agent, colliding with another tool name, or colliding with a reserved lifecycle tool name — see [Subagents §2](/0.2.0/specification/subagents#2-ownership-rules).
6. Session bindings (`sessionStop` / `sessionFail` / `sessionStatus`), `maxSteps`, or stop bindings on a non-prompt side.
7. A session binding that is not in object form ([§3](#3-sessiontoolbinding)).
Validation issues **SHOULD** be reported as a structured list (`code`, `severity`, `message`, `path`) so tooling can surface every problem in one pass.
## 9. Examples
### 9.1 Assistant (human × prompt)
The everyday user-facing assistant — a person on side B, a model on side A:
```typescript
defineAgent({
name: 'assistant',
sideA: { prompt: 'assistant' },
sideB: { human: true },
});
```
### 9.2 Worker / Reviewer (prompt × prompt)
Two models converse; each side sees itself as `assistant` and the other as `user`. `maxSessionTurns` is optional but strongly recommended here — nothing external stops two models:
```typescript
defineAgent({
name: 'asset_subagent',
maxSessionTurns: 40,
exposeAsTool: true,
toolDescription: 'Generate and QA top-down game assets.',
sideA: {
label: 'Worker',
prompt: 'asset_worker',
stopOnResponse: true,
sessionFail: {
name: 'fail_asset',
messageProperty: 'reason',
attachmentsProperty: 'attachments',
},
},
sideB: {
label: 'Reviewer',
prompt: 'asset_reviewer',
stopOnResponse: false,
sessionStop: {
name: 'approve_asset',
messageProperty: 'summary',
attachmentsProperty: 'attachments',
},
sessionStatus: {
name: 'update_asset_status',
messageProperty: 'status',
},
},
});
```
### 9.3 Relay (handler × human)
A 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. The full pattern is worked through in [Handlers §9](/0.2.0/specification/handlers#9-worked-example-the-relay):
```typescript
defineAgent({
name: 'relay_agent',
sideA: {
handler: 'relay_pipe',
subagents: [{ agent: 'assistant_agent', maxInstances: 1 }],
},
sideB: { human: true },
});
```
## 10. TypeScript Reference
```typescript
type SideConfig = HumanSide | PromptSide | HandlerSide;
interface HumanSide {
human: true;
label?: string;
}
interface PromptSide {
prompt: string; // StandardAgentSpec.Prompts
label?: string;
subagents?: SubagentRelationship[]; // see /0.2.0/specification/subagents
stopOnResponse?: boolean;
stopTool?: string;
stopToolResponseProperty?: string;
maxSteps?: number;
sessionStop?: SessionToolBinding;
sessionFail?: SessionToolBinding;
sessionStatus?: SessionToolBinding;
}
interface HandlerSide {
handler: string; // StandardAgentSpec.Handlers
label?: string;
subagents?: SubagentRelationship[];
}
interface SessionToolBinding {
name: string;
messageProperty?: string;
attachmentsProperty?: string;
}
interface ParentHookRequirement {
hook: string;
reason: string;
stage?: 'before_parent' | 'after_parent';
}
interface AgentDefinition {
name: N;
sideA: SideConfig;
sideB: SideConfig;
maxSessionTurns?: number;
title?: string;
description?: string;
icon?: string;
primary?: boolean;
exposeAsTool?: boolean;
toolDescription?: string;
env?: Record;
hooks?: string[];
parentHooks?: ParentHookRequirement[];
// Packaging metadata: packageName, version, author, license
}
function defineAgent(
options: AgentDefinition
): AgentDefinition;
```
---
Source: https://standardagentspec.org/0.2.0/specification/subagents
# Subagents
A **subagent** is any agent composed as a child of another agent. The child runs in its own isolated [thread](/0.2.0/specification/threads) — messages, filesystem, queue, lifecycle — linked to the parent through the thread hierarchy and the parent's child registry.
Any agent may be composed as a child; composing one with a human side [puts a person's step inside the composition](/0.2.0/specification/agents#7-human-in-the-loop-composition). A subagent relationship is part of the agent's structure: it is declared on the agent side that owns it, never inside a prompt's `tools` array.
## 1. SubagentRelationship
Relationships are declared in the `subagents` array of a prompt- or handler-backed [side](/0.2.0/specification/agents#12-sideconfig):
```typescript
interface SubagentRelationship {
agent: string; // which agent definition to instantiate
as?: string; // relationship name; defaults to the unqualified agent name
description?: string; // model-facing override; falls back to the child's toolDescription
maxInstances?: number; // unset = unbounded
immediate?: boolean | { // spawn at THREAD CREATION
nameEnv?: string;
descriptionEnv?: string;
scopedEnv?: string[];
};
blocking?: boolean; // subagent_create awaits session close and returns its result
parentCommunication?: 'implicit' | 'explicit';
scopedEnv?: string[];
initUserMessageProperty?: string;
initAttachmentsProperty?: string;
initAgentNameProperty?: string;
optional?: string; // env flag gating this branch
hidden?: boolean; // spawnable by code, invisible to models
}
```
| Property | Description |
|----------|-------------|
| `agent` | The agent definition to instantiate. It accepts a [qualified name](/0.2.0/distribution/packaging#qualified-names) for a packed entry agent. Any agent is eligible. `exposeAsTool: true` marks an agent as designed for composition. It also supplies the default `toolDescription`. |
| `as` | The **relationship name** identifies the relationship in tools, registries, and references. It defaults to the unqualified part of `agent`. Two relationships may target the same `agent` under different `as` names ([§2.3](#23-aliases)). |
| `description` | Model-facing description override for this relationship. |
| `maxInstances` | Cap on simultaneous instances. When reached, creation attempts **SHOULD** return a tool error explaining the cap and suggesting messaging an existing instance. |
| `immediate` | Spawn at **thread creation**, before any side takes a turn ([§3.2](#32-immediate-spawning)). |
| `blocking` | `subagent_create` waits for the child session to close and returns its result ([§3.3](#33-blocking-and-create-or-continue)). |
| `parentCommunication` | `implicit` (default) auto-queues child completion/failure to the parent; `explicit` leaves escalation to tools, hooks, and handlers ([§6.4](#64-child--parent-explicit-escalation)). |
| `scopedEnv` | Environment values copied into the child thread; runtime-only transfer data. |
| `initUserMessageProperty` / `initAttachmentsProperty` / `initAgentNameProperty` | Map creation arguments into the child's initial user message, attachments, and display name. |
| `optional` | The branch is enabled only when the named environment flag resolves to `true`, `1`, or `yes` (case-insensitive). Disabled branches are unavailable for creation and runtime invocation. |
| `hidden` | The relationship stays declared — code paths can still spawn the child — but it is excluded from every LLM request's tool surface. For infrastructure children the model must never invoke. |
For example, `{ agent: '@scope/pkg/researcher' }` has the relationship name `researcher`. Relationship names are tool names. They cannot contain a slash.
## 2. Ownership Rules
### 2.1 The Owning Side
A relationship **belongs to the side that declares it**. Ownership determines where child traffic lands: `notifyParent` content, implicit completion/failure messages, and status-bearing queue traffic from instances of the relationship are delivered on the **owning side's perspective** — queued in the role that prompts the owning side's next turn (`user` for a side-A-owned relationship, `assistant` for a side-B-owned relationship, per the [perspective mapping](/0.2.0/specification/threads/messages#4-queueing-messages)).
### 2.2 Single Owner
A relationship name (`as`, defaulted or explicit) may appear on **at most one side** of an agent. Declaring the same name on both sides is a definition-time error. The sibling side has no model-facing path to those children; code paths via `ThreadState` remain available to it. Cross-side grants (one side auditing the other side's children through granted tools) are deliberately deferred — a door recorded closed, to be reopened with a real use case.
### 2.3 Aliases
Two relationships may target the same `agent` under different `as` names — for example, two calendar teams with different `scopedEnv`:
```typescript
sideA: {
prompt: 'coordinator',
subagents: [
{ agent: 'calendar_agent', as: 'work_calendar', scopedEnv: ['WORK_CAL_ID'] },
{ agent: 'calendar_agent', as: 'personal_calendar', scopedEnv: ['PERSONAL_CAL_ID'] },
],
},
```
Everything model-facing — tool schemas, registries, lifecycle references — uses the relationship name. The `agent` argument of `subagent_create` / `subagent_message` enumerates **relationship names, not agent names**.
### 2.4 Reserved Names
Relationship names share the tool namespace. A relationship name that collides with another tool name is a definition-time error, and the injected lifecycle tool names — `subagents`, `subagent_create`, `subagent_message` — are explicitly **reserved**: a colliding `as` **MUST** be rejected with a dedicated validation code.
### 2.5 Visibility
- **Prompt-backed owning side**: the side's prompt automatically receives the lifecycle tools ([§5](#5-lifecycle-tools)) for the side's non-hidden relationships. Prompts do **not** declare relationships in `tools` — a `tools` entry attempting to configure a subagent relationship is a definition-time error.
- **Handler-backed owning side**: handlers need no tool grant; they reach children through `ThreadState` directly. The declaration's job for a handler side is existence, configuration, and lifecycle.
- **Human-backed side**: may not own relationships (definition-time error) — nothing there can invoke them.
## 3. Spawning
### 3.1 Creation Paths
Instances are created by:
- the injected `subagent_create` lifecycle tool (prompt-backed sides),
- runtime code (`invokeTool` / `queueTool` on the lifecycle surface, or dedicated runtime APIs) from tools, hooks, and handlers,
- `immediate` configuration at thread creation.
### 3.2 Immediate Spawning
`immediate` relationships spawn at **thread creation**, before any side takes a turn — immediate children exist even when the first inbound message arrives instantly, and when the owning side is a handler with no prompt to activate. Immediate spawning is recursive: if an immediate child's own sides declare immediate relationships, those spawn as the child thread activates.
In the object form:
- runtimes **MAY** use `nameEnv` and `descriptionEnv` as model-visible hints when deriving initial child arguments via a bootstrap pass.
- runtimes **MUST** treat `scopedEnv` as runtime-only transfer data.
- runtimes **MUST NOT** expose `scopedEnv` values to the model unless the same env name is explicitly designated by `nameEnv` or `descriptionEnv`.
### 3.3 Blocking and Create-or-Continue
`blocking: true` makes `subagent_create` await the child session's close and return its result payload.
When `blocking: true` is combined with `maxInstances: 1` and an instance already exists, `subagent_create` **MUST** behave as **create-or-continue**: message the existing instance and await *that* session's close, rather than erroring on the cap. This is what callers invariably mean by "run the child again."
> **Warning:** A [handler](/0.2.0/specification/handlers#4-delivery-semantics) that awaits a blocking child holds its thread's one-at-a-time delivery slot for the whole child session. Prefer non-blocking spawning from handlers.
## 4. Instance Lifecycle
### 4.1 Persistence Is Universal
**Every child instance is a persistent thread.** There are no disposable instances and no opt-in persistence wrapper — there is one lifecycle:
- **Session end never terminates a thread.** When a child session ends — stop, fail, error, or turn-cap — the registry status transitions (`running` → `idle` / `failed`), the thread remains addressable, and a later message starts a **new session with history intact**. Runtimes **MUST NOT** destroy or orphan child threads on any session-finalization path.
- **Only explicit termination destroys an instance**: `state.terminate()`, operator action, or a parent teardown policy.
- `blocking` is purely a *waiting style* — whether the creating call awaits the session — and is orthogonal to persistence.
What a runtime does with old or idle threads — archival, eviction, listing policy — is **out of scope for this specification**; retention is entirely the runtime's business.
### 4.2 Registry
Instances are tracked in the parent's `ThreadState.children`:
```typescript
interface SubagentRegistryEntry {
reference: string; // stable instance reference (UUID)
relationship: string; // the relationship name (`as`)
name: string; // the child agent definition name
title?: string;
description: string;
blocking?: boolean;
threadName?: string;
initialArguments?: Record;
spawnGroupId?: string;
createdAt?: number;
status: string; // e.g. running | idle | failed | awaiting_human | terminated
parentCommunication?: 'implicit' | 'explicit';
}
```
`relationship` is the composition identity (which declared relationship spawned this instance); `name` is the implementing agent. Aliased relationships targeting the same agent are distinguished by `relationship`.
Child visibility is pull-based: runtimes inject the `subagents` query tool ([§5](#5-lifecycle-tools)) and **MUST NOT** additionally inject an ambient registry system message — a registry block that mutates between requests invalidates provider prefix caches and reads as out-of-dialogue state. Completions arrive as messages.
### 4.3 Human-in-the-Loop Children
A child whose current turn belongs to a human-backed side parks with registry status `awaiting_human`. The session resumes when human input arrives on that side's perspective; the specification defines only this waiting state, not who supplies the input or through which interface ([Agents §7](/0.2.0/specification/agents#7-human-in-the-loop-composition)).
## 5. Lifecycle Tools
For a prompt-backed side with non-hidden relationships, runtimes inject three built-in tools scoped to that side's declarations:
- **`subagents`** — the pull-based visibility surface. Takes no arguments; returns the registry snapshot for the side's relationships — reference, relationship name, agent name, status, working-status text, initial arguments, creation time. Injected tool descriptions **SHOULD** direct the model to call `subagents` before `subagent_create` so existing instances are reused rather than duplicated.
- **`subagent_create`** — creates (or continues, [§3.3](#33-blocking-and-create-or-continue)) an instance. Its `agent` argument **MUST** enumerate the side's enabled relationship *names*. It **MUST** require a non-empty `name` argument for the spawned instance; runtimes **SHOULD** persist this as a human-readable child thread display name.
- **`subagent_message`** — queues a message to an existing instance by reference.
All lifecycle references use relationship names, never an internal agent identifier that differs from them. Runtimes **MUST** reject lifecycle invocations that target undeclared or disabled relationships without creating a child.
`subagent_create` **SHOULD** expose a structured `arguments` object whose schema is dictated by the receiving child ([§5.1](#51-persistent-invocation-arguments)).
### 5.1 Persistent Invocation Arguments
The invocation arguments a subagent accepts are dictated solely by the *receiving* agent, through the `requiredSchema` of its 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 — see [§6.1](#61-parent--child).) Required schema fields are mandatory; optional fields are suggested.
Unlike a plain tool call, these arguments are **not** ephemeral:
- runtimes **MUST** validate them against the schema and persist the validated arguments for the life of the child thread.
- runtimes **MUST** hydrate them into `ThreadState.arguments` and prompt variable interpolation for **both** child sides on every activation — the initial invocation and every later resume — so spawn-time context (a stylist child that needs sizes and preferences, say) is available for as long as the thread lives.
- if required arguments are missing, runtimes **MUST** reject creation with a structured `subagent_arguments_required` error rather than spawning the child.
### 5.2 Scoped Variable Bootstrap
If `subagent_create` cannot proceed because required scoped variables for the child graph are missing, runtimes **SHOULD** return a structured error (e.g. `subagent_env_required`) with a request ID and expose a temporary bootstrap endpoint:
- `GET /threads/{parent_thread_id}/variables/{request_id}` — returns required/missing variable names.
- `POST /threads/{parent_thread_id}/variables/{request_id}` — stores the provided values and immediately boots the deferred child using the original creation payload.
## 6. Parent ↔ Child Communication
### 6.1 Parent → Child
- initial invocation mapping (`initUserMessageProperty`, `initAttachmentsProperty`)
- ongoing messaging (`subagent_message`, or `queueMessage` on the child's `ThreadState` from code)
Parent traffic enters the child in the **side B perspective** (`role: 'user'`): the child's side A acts on it, exactly as it would for an external caller. Routing is structural in both directions — parent→child entry is uniform, and child→parent delivery is determined by the relationship's owning side ([§2.1](#21-the-owning-side)).
Attachment paths **MUST** be copied from the parent filesystem to the child filesystem before queuing ([§7](#7-attachment-copying)).
### 6.2 Child → Parent: Completion and Failure
When the child session ends via `sessionStop` and the effective `parentCommunication` is `implicit`, the parent receives a queued silent message **on the owning side's perspective**:
```text
Subagent (reference: {uuid}) has returned the following result:
{result}
```
`sessionFail` similarly delivers a failure message. Returned attachments (if any) are copied child → parent and included as parent-local paths. Session end transitions registry status — it never terminates the child thread ([§4.1](#41-persistence-is-universal)).
### 6.3 Child → Parent: Status
`sessionStatus` (and `state.setStatus()`) updates the parent's registry status text without ending child execution.
### 6.4 Child → Parent: Explicit Escalation
When the effective `parentCommunication` is `explicit`, runtimes **MUST NOT** auto-queue completion/failure to the parent. Because the auto-queued completion is what triggers a parent turn, `explicit` means a child's finish does not wake the parent at all. Tools, hooks, and handlers escalate deliberately:
- `state.notifyParent(content)`
- `state.setStatus(status)`
- `state.stopSession({ result, notifyParent, status })`
Such children deliver results through another channel — the parent's key-value store, for example — which the parent picks up on its next natural turn.
### 6.5 Provenance Metadata
Runtimes **SHOULD** set standard, OPTIONAL provenance metadata on cross-thread traffic (see [Messages §1.1](/0.2.0/specification/threads/messages#11-provenance-metadata-conventions)):
- `metadata.subagent_id` — the child instance reference a message relates to.
- `metadata.forwarded_from` — the origin thread/message of forwarded content.
These conventions replace ad-hoc bracket-tag prefixes in userland relay code. They are conventions, not requirements.
## 7. Attachment Copying
Subagent communication that crosses thread boundaries **MUST** copy filesystem references:
- parent → child for initial and ongoing messaging attachments
- child → parent for completion and failure payload attachments
The destination thread **MUST** receive destination-local attachment paths.
## 8. Queue and Termination
These are properties of the underlying thread, not of subagents specifically. See [Threads](/0.2.0/specification/threads):
- queued messages are durable and ordered; injected before the next step when executing, otherwise forcing the next turn.
- `terminate()` is the *only* soft-destruction path: it aborts in-flight execution, rejects new execution and queued-message entry, and updates parent registry status to `terminated`.
## 9. Example
A coordinator owning an aliased pair of calendar teams and a blocking research child:
```typescript
defineAgent({
name: 'assistant_agent',
sideA: {
prompt: 'coordinator',
subagents: [
{ agent: 'calendar_agent', as: 'work_calendar', scopedEnv: ['WORK_CAL_ID'] },
{ agent: 'calendar_agent', as: 'personal_calendar', scopedEnv: ['PERSONAL_CAL_ID'] },
{ agent: 'research_agent', blocking: true, maxInstances: 1 },
{ agent: 'approval_gate' }, // human-in-the-loop child — parks awaiting_human
],
},
sideB: { human: true },
});
```
The coordinator's prompt automatically receives `subagents`, `subagent_create`, and `subagent_message`, with `subagent_create.agent` enumerating `'work_calendar' | 'personal_calendar' | 'research_agent' | 'approval_gate'`.
---
Source: https://standardagentspec.org/0.2.0/specification/threads
# Threads
A thread is an instance of an agent — the runtime execution context where conversations happen. Each thread has isolated storage for messages and files, maintains its own conversation history, and can be handed off between agents while preserving full context.
This page covers the core ideas: what a thread is, its identity, the `ThreadState` interface, and the small primitives that live directly on it (resource loading, tool invocation, effects, events, context, runtime context, subagent hierarchy, lifecycle). Larger surfaces have their own pages:
- [Messages](/0.2.0/specification/threads/messages) — reading, injecting, queuing, updating, deleting
- [File System](/0.2.0/specification/threads/filesystem) — per-thread file storage, streaming, search
- [Code Execution](/0.2.0/specification/threads/code-execution) — isolated JS/TS sandbox via `runCode`
- [Runtime Streams](/0.2.0/specification/threads/runtime-streams) — optional live byte streams supplied by the execution host
- [Execution State](/0.2.0/specification/threads/execution-state) — step counts, turn control, cancellation
- [Decisions](/0.2.0/specification/threads/decisions) — explicit context and typed question evaluation
- [Thread Endpoints](/0.2.0/specification/threads/endpoints) — HTTP APIs that receive a `ThreadState`
- [Thread Client API](/0.2.0/specification/threads/client-api) — runtime HTTP routes and the WebSocket stream for creating, reading, messaging, and watching threads
## 1. Thread Definition
A thread is an **instance** of an agent with isolated storage for messages and files.
### 1.1 Agent Assignment
The agent assigned to a thread can change over time while preserving all history and context. This is called a **handoff**.
| Scenario | Behavior |
|----------|----------|
| **Tool handoff** | Calling an exposed agent with a human side as a tool transfers control to that agent |
| **Manual handoff** | Queue a tool call to an agent to trigger handoff programmatically |
| **Subagent composition** | Instantiating a side-declared relationship creates an isolated child thread (no handoff) — see [Subagents](/0.2.0/specification/subagents) |
Handoffs enable workflows where specialized agents handle different parts of a conversation — a triage agent routes to support, support escalates to billing — all within the same thread with full context preserved.
### 1.2 ThreadState Interface
`ThreadState` is the unified interface for all thread operations. It provides a consistent API for interacting with threads regardless of context — whether from tools during execution, hooks, or HTTP endpoints.
#### 1.2.1 Properties
| Property | Type | Description |
|----------|------|-------------|
| `threadId` | `string` | Unique thread identifier (readonly) |
| `agentId` | `string` | Owning agent name (readonly) |
| `userId` | `string \| null` | Associated user (readonly) |
| `createdAt` | `number` | Creation timestamp in microseconds (readonly) |
| `children` | `SubagentRegistryEntry[]` | Child subagent registry (readonly) |
| `terminated` | `number \| null` | Termination timestamp in microseconds, or null when active (readonly) |
| `arguments` | `Record` | Arguments supplied when this thread was created or invoked. Subagent initial arguments appear here. See [Thread Arguments](#61-thread-arguments) |
| `runtimeStreams` | `RuntimeStreams \| undefined` | Optional live runtime byte streams. Feature-detect before use. See [Runtime Streams](/0.2.0/specification/threads/runtime-streams) |
| `context` | `Record` | Mutable per-execution scratch storage. See [Context Storage](#62-per-execution-context) |
| `execution` | `ExecutionState \| null` | Execution state during active execution, null at rest. See [Execution State](/0.2.0/specification/threads/execution-state) |
| `_notPackableRuntimeContext` | `Record \| undefined` | Runtime-specific context (non-portable). See [Runtime Context](#10-runtime-context-non-portable) |
#### 1.2.2 Methods
The methods directory below is grouped by topic. Topics with their own page link out; the rest are documented on this page.
**Messages** — [Messages →](/0.2.0/specification/threads/messages)
| Method | Returns | Description |
|--------|---------|-------------|
| `getMessages(options?)` | `Promise` | Get messages with pagination |
| `getMessage(messageId)` | `Promise` | Get single message by ID |
| `injectMessage(input)` | `Promise` | Inject a new message |
| `queueMessage(input)` | `Promise` | Queue a message for delivery on next step |
| `updateMessage(messageId, updates)` | `Promise` | Update existing message |
| `deleteMessage(messageId)` | `Promise` | Delete a message |
**File System** — [File System →](/0.2.0/specification/threads/filesystem)
| Method | Returns | Description |
|--------|---------|-------------|
| `writeFile(path, data, mimeType, options?)` | `Promise` | Write file |
| `readFile(path)` | `Promise` | Read file content |
| `readFileStream(path, options?)` | `Promise \| null>` | Stream large files |
| `statFile(path)` | `Promise` | Get file metadata |
| `readdirFile(path)` | `Promise` | List directory |
| `unlinkFile(path)` | `Promise` | Delete file |
| `mkdirFile(path)` | `Promise` | Create directory |
| `rmdirFile(path)` | `Promise` | Remove directory |
| `getFileStats()` | `Promise` | Get filesystem stats |
| `grepFiles(pattern)` | `Promise` | Search file contents |
| `findFiles(pattern)` | `Promise` | Find files by glob |
| `getFileThumbnail(path)` | `Promise` | Get image thumbnail |
**Code Execution** — [Code Execution →](/0.2.0/specification/threads/code-execution)
| Method | Returns | Description |
|--------|---------|-------------|
| `runCode(source, options?)` | `CodeExecution` | Execute JS/TS source in an isolated sandbox; returns a thenable handle with `terminate()` |
**Subagent Hierarchy** — see [§9 Subagent Hierarchy](#9-subagent-hierarchy-communication-and-termination)
| Method | Returns | Description |
|--------|---------|-------------|
| `getChildThread(referenceId)` | `Promise` | Resolve child thread by subagent reference |
| `getParentThread()` | `Promise` | Resolve parent thread for this thread |
| `notifyParent(content)` | `Promise` | Queue a silent message to this thread's parent |
| `setStatus(status)` | `Promise` | Update this thread's status in the parent registry when present |
| `stopSession(options?)` | `Promise` | Terminally stop the active agent session — never the thread itself; optional `notifyParent` and `status` trigger those parent side effects |
**Resource Loading** — see [§2 Resource Loading](#2-resource-loading)
| Method | Returns | Description |
|--------|---------|-------------|
| `loadModel(name)` | `Promise` | Load model definition |
| `loadPrompt(name)` | `Promise` | Load prompt definition |
| `loadAgent(name)` | `Promise` | Load agent definition |
| `getPromptNames()` | `string[]` | List available prompts |
| `getAgentNames()` | `string[]` | List available agents |
| `getModelNames()` | `string[]` | List available models |
| `env(propertyName)` | `Promise` | Resolve environment variable using thread/agent/prompt/user/instance precedence |
| `instanceEnv?(propertyName)` | `Promise` | Optionally resolve only the runtime-instance value for security-sensitive trust anchors |
| `envType(propertyName)` | `Promise<'text' \| 'secret'>` | Resolve display/redaction classification for an environment value |
| `setEnv(propertyName, value, options?)` | `Promise` | Set a thread environment variable, optionally choosing `text` or `secret`, and propagate to active descendants |
**Tool Invocation** — see [§3 Tool Invocation](#3-tool-invocation)
| Method | Returns | Description |
|--------|---------|-------------|
| `queueTool(toolName, args)` | `void` | Queue tool for async execution |
| `invokeTool(toolName, args)` | `Promise` | Invoke tool and wait for result |
**Effect Scheduling** — see [§4 Effect Scheduling](#4-effect-scheduling)
| Method | Returns | Description |
|--------|---------|-------------|
| `scheduleEffect(name, args, delay?)` | `Promise` | Schedule effect, returns effect ID |
| `getScheduledEffects(name?)` | `Promise` | Get pending effects |
| `removeScheduledEffect(id)` | `Promise` | Cancel scheduled effect |
**Events** — see [§5 Events](#5-events)
| Method | Returns | Description |
|--------|---------|-------------|
| `emit(event, data)` | `void` | Emit event to connected clients |
**Durable Key-Value Store** — see [§7 Durable Key-Value Store](#7-durable-key-value-store)
| Method | Returns | Description |
|--------|---------|-------------|
| `getValue(key)` | `Promise` | Read a value from the thread's durable key-value store |
| `setValue(key, value)` | `Promise` | Write a JSON-serializable value; `null`/`undefined` deletes the key |
**Run status** — see [Execution State §4](/0.2.0/specification/threads/execution-state#4-run-status)
| Method | Returns | Description |
|--------|---------|-------------|
| `status()` | `Promise` | Authoritative run status: `idle`, `running`, or `failed`, with `since` and the last stop `reason` |
**Decision inference** — [Decisions →](/0.2.0/specification/threads/decisions)
| Method | Returns | Description |
|--------|---------|-------------|
| `decide(options)` | `Promise>` | Evaluate explicit context and typed questions without adding messages |
**User identity**
| Method | Returns | Description |
|--------|---------|-------------|
| `user()` | `Promise` | Profile of the thread's user (identity fields only — id, username, role, roles, permissions, email, display_name, avatar_url; never credentials). `roles` optionally contains opaque application roles from the trusted identity authority; see [Users](/0.2.0/specification/users#application-roles). `null` for user-less threads. |
**Skills** — see [§7.4 Agent Skills](#74-agent-skills)
| Method | Returns | Description |
|--------|---------|-------------|
| `skills.list(options?)` | `Promise` | Installed skills (enabled only unless `includeDisabled`) |
| `skills.get(name)` | `Promise<{ metadata, skillMd } \| null>` | A skill's metadata + SKILL.md source |
| `skills.readFile(name, path)` | `Promise` | One bundled file's text |
| `skills.install(files)` | `Promise` | Install/replace a skill; requires mutation authorization |
| `skills.setEnabled(name, enabled)` | `Promise` | Enable/disable a skill; requires mutation authorization |
| `skills.remove(name)` | `Promise` | Uninstall a skill; requires mutation authorization |
**Lifecycle** — see [§8 Lifecycle](#8-lifecycle)
| Method | Returns | Description |
|--------|---------|-------------|
| `terminate()` | `Promise` | Soft-terminate the thread |
### 1.3 Access Contexts
`ThreadState` is provided in different contexts:
| Context | Execution State | Use Case |
|---------|-----------------|----------|
| Tools | Present | During agent execution |
| Hooks | Present | Lifecycle interception |
| Endpoints | Null | HTTP API access |
## 2. Resource Loading
### 2.1 Loading Definitions
`ThreadState` provides access to registered definitions:
```typescript
const model = await state.loadModel('gpt-4o');
const prompt = await state.loadPrompt('support-prompt');
const agent = await state.loadAgent('customer-support');
```
### 2.2 Listing Resources
```typescript
const prompts = state.getPromptNames();
const agents = state.getAgentNames();
const models = state.getModelNames();
```
### 2.3 Environment Variable Resolution
```typescript
const apiKey = await state.env('GOOGLE_API_KEY');
if (!state.instanceEnv) throw new Error('Instance env is required');
const trustedServiceUrl = await state.instanceEnv('TRUSTED_SERVICE_URL');
if (!trustedServiceUrl) throw new Error('Trusted service URL is required');
await state.setEnv('TOPDOWN_APPROVAL_GATE', 'open');
await state.setEnv('PUBLIC_LABEL', 'QA', { type: 'text' });
await state.setEnv('API_TOKEN', 'secret-token', { type: 'secret' });
```
`env(propertyName)` resolves in this order:
1. Thread environment variables
2. Agent definition defaults (`agent.env`)
3. Prompt definition defaults (`prompt.env`)
4. User-account environment variables
5. Runtime instance environment variables
The optional `instanceEnv(propertyName)` capability reads exclusively from the
runtime instance. It must not consider thread, agent, prompt, or user values.
It returns `undefined` when the key is not configured and rejects when the
runtime cannot read its instance environment.
Use it when a value establishes a trust boundary, such as a service endpoint
and the credential sent to that endpoint. Consumers that require this boundary
must feature-detect the method and fail closed if the capability is unavailable
or the required instance value is missing.
`envType(propertyName)` returns the display/redaction classification for a resolved environment value. Unknown or non-thread sources default to `secret`. Values marked `secret` should be redacted from tool output and logs; values marked `text` may be displayed.
`setEnv(propertyName, value, options?)` writes to thread storage and propagates recursively to active descendants. Pass `{ type: 'text' }` or `{ type: 'secret' }` to choose the display/redaction classification. Omitting `type` preserves any existing classification for that key, or defaults a new key to `secret`. During propagation, descendants must filter out inherited values for variable names marked `scoped` in that descendant's agent graph. Terminated descendants are skipped.
Thread, user, and instance environment values should be encrypted at rest when the runtime supports encrypted storage.
For subagent creation, runtimes may require missing scoped variables to be provided through a pending request flow before boot can continue. See [Subagents §5.2](/0.2.0/specification/subagents#52-scoped-variable-bootstrap).
## 3. Tool Invocation
### 3.1 Queuing Tools
Queue a tool for asynchronous execution:
```typescript
state.queueTool('send_email', {
to: 'user@example.com',
subject: 'Hello',
body: 'Message content',
});
```
If the thread is currently executing, the tool is added to the queue. Otherwise, a new execution is started.
### 3.2 Direct Invocation
Invoke a tool and wait for the result:
```typescript
const result = await state.invokeTool('get_weather', {
location: 'San Francisco',
});
if (result.status === 'success') {
console.log(result.result);
}
```
## 4. Effect Scheduling
Effects are scheduled operations that run outside the normal tool execution context. Unlike tools which execute immediately during conversation, effects:
- Run **independently** of the conversation flow
- Can be **scheduled with delays**
- Execute with their own **ThreadState** context
- Are ideal for **side effects** that don't need immediate results
Effect definition syntax is specified in [Effects](/0.2.0/specification/effects). Packed effects may use [qualified names](/0.2.0/distribution/packaging#qualified-names) to avoid collisions.
### 4.1 Scheduling Effects
```typescript
const effectId = await state.scheduleEffect(
'send_reminder_email',
{ to: 'user@example.com', subject: 'Reminder' },
30 * 60 * 1000 // delay in milliseconds
);
```
| Parameter | Type | Description |
|-----------|------|-------------|
| `name` | `string` | Effect name (file in `agents/effects/`) |
| `args` | `Record` | Arguments passed to effect handler |
| `delay` | `number` | Delay in milliseconds (default: 0 for immediate) |
Returns a unique effect ID (UUID) that can be used to cancel the effect.
### 4.2 ScheduledEffect Record
| Property | Type | Description |
|----------|------|-------------|
| `id` | `string` | Unique effect ID (UUID) |
| `name` | `string` | Effect name |
| `args` | `Record` | Arguments to be passed |
| `scheduledAt` | `number` | Scheduled execution time (microseconds) |
| `createdAt` | `number` | When effect was scheduled (microseconds) |
### 4.3 Managing Scheduled Effects
```typescript
const effects = await state.getScheduledEffects();
const reminders = await state.getScheduledEffects('send_reminder_email');
const removed = await state.removeScheduledEffect(effectId);
if (removed) {
console.log('Effect cancelled');
}
```
## 5. Events
### 5.1 Emitting Events
Send custom events to connected clients:
```typescript
state.emit('progress', {
step: 3,
total: 10,
message: 'Processing data...',
});
```
Events are delivered at most once to every client connected to the [thread stream](/0.2.0/specification/threads/client-api#16-thread-stream), as an `event` frame:
```json
{ "type": "event", "eventType": "progress", "data": { "step": 3, "total": 10 }, "timestamp": 1727870000000 }
```
### 5.2 Event Guidelines
- Event names **SHOULD** be lowercase with underscores
- Event data **MUST** be JSON-serializable
- Events **SHOULD NOT** contain sensitive information
## 6. Thread Arguments and Context Storage
### 6.1 Thread Arguments
`arguments` is the read-only argument object supplied when the thread was
created or invoked.
For subagent threads, runtimes **MUST** restore the creation-time
`subagent_create.arguments` object into `ThreadState.arguments` on every run and
when exposing the child through endpoints, hooks, effects, or other
`ThreadState` access. Both child sides see the same argument object:
```typescript
const initialArgs = state.arguments;
const shirtSize = state.arguments.shirt_size;
```
Runtimes should keep the durable copy with child thread metadata/properties.
They should also expose top-level argument keys to prompt variable interpolation,
for whichever child side is currently rendering, including included prompts,
without requiring callers to put those values in `state.context`.
### 6.2 Per-Execution Context
The `context` property is mutable execution-scoped scratch storage for values
that should be shared while the current agent run is being assembled and
executed. It is used for:
- sharing derived values between tools, hooks, effects, and runtime lifecycle code during one execution
- runtime-internal coordination data that should not become a thread argument
For example:
```typescript
state.context.userData = { id: 123, name: 'Alice' };
// Retrieve in another tool call
const user = state.context.userData;
```
Runtimes may seed `context` at execution start with runtime coordination data.
User code may mutate it during execution, and later
participants in that same execution see those mutations.
Invocation or creation arguments belong in [`arguments`](#61-thread-arguments),
not in `context`.
### 6.3 Context Limitations
| Aspect | Behavior |
|--------|----------|
| **Scope** | Single execution only |
| **Persistence** | Mutations are lost after execution ends |
| **Type** | `Record` |
| **Size** | No enforced limit |
For persistent storage across executions, use the [durable key-value store](#7-durable-key-value-store), the [file system](/0.2.0/specification/threads/filesystem), or external storage.
## 7. Durable Key-Value Store
`getValue` and `setValue` provide a simple durable key-value store scoped to the thread. Values persist across executions, tool calls, hook invocations, and endpoint requests for the lifetime of the thread.
It is one of two ways to store persistent data on a thread, alongside the [file system](/0.2.0/specification/threads/filesystem).
### 7.1 Reading and Writing Values
```typescript
const count = (await state.getValue('invocation_count')) ?? 0;
await state.setValue('invocation_count', count + 1);
await state.setValue('preferences', { theme: 'dark', locale: 'en-US' });
const prefs = await state.getValue<{ theme: string; locale: string }>('preferences');
```
### 7.2 Semantics
| Aspect | Behavior |
|--------|----------|
| **Scope** | Per-thread; not shared with parent, child, or sibling threads |
| **Persistence** | Durable across executions for the lifetime of the thread |
| **Value type** | Any JSON-serializable value (objects, arrays, strings, numbers, booleans, `null`) |
| **Missing keys** | `getValue` returns `null` |
| **Deletion** | `setValue(key, null)` or `setValue(key, undefined)` deletes the key |
| **Subagents** | Values are **not** automatically copied to spawned child threads |
### 7.3 Comparison With Other Storage
| Surface | Scope | Persistence | Intended Use |
|---------|-------|-------------|--------------|
| `arguments` | Thread invocation | Durable when backed by thread metadata/properties | Creation/invocation arguments exposed to thread code and prompt interpolation |
| `context` | Single execution | Ephemeral | Mutable scratch state shared during one execution |
| `getValue` / `setValue` | Thread | Durable | Small structured state scoped to the thread |
| `env` / `envType` / `setEnv` | Thread → agent → prompt → user → instance | Durable (encrypted at rest when supported) | Configuration and secrets with layered resolution and display/redaction metadata |
| File system | Thread | Durable | Large or binary payloads |
Runtime semantics and conformance requirements for the durable key-value store live in [Runtime §15](/0.2.0/infrastructure/runtime#15-durable-key-value-store).
### 7.4 Agent Skills
`state.skills` exposes the calling thread owner's Agent Skills library plus any administrator-reviewed skills explicitly shared by the runtime. Skills follow the [Agent Skills](https://agentskills.io) standard: a folder whose root `SKILL.md` opens with YAML frontmatter carrying a required `name` (lowercase kebab-case, ≤64 chars) and `description` (≤1024 chars), optionally accompanied by scripts, references, and assets.
Requirements:
- Skills are stored server-side and scoped to the calling principal. A principal's private skills **MUST NOT** be visible to another principal. Runtimes **MAY** add an explicitly shared, administrator-reviewed library and **MUST NOT** require client-side storage for skill content.
- When an owner-scoped skill and a shared skill have the same name, the owner-scoped skill **MUST** take precedence for that owner.
- A skill's identity **MUST** come from its `SKILL.md` frontmatter — never from a caller-supplied name — and installs **MUST** validate the frontmatter against the standard.
- Runtimes **MUST** authorize mutations and confine them to the calling principal's scope. Multi-tenant runtimes **MUST NOT** allow ordinary tenant agent code to install, replace, enable, disable, or remove shared skills; an administrative or equivalently trusted principal is required for shared-library changes.
- Runtimes **SHOULD** surface skills to agents with progressive disclosure: only `name` + `description` ride in ambient context; the `SKILL.md` body (and bundled files) load on demand when the agent judges the skill applicable.
- Disabled skills stay installed but **MUST** be hidden from ambient agent context.
```typescript
const available = await state.skills.list();
const skill = await state.skills.get('pdf-processing');
const script = await state.skills.readFile('pdf-processing', 'scripts/extract.py');
await state.skills.install([{ path: 'SKILL.md', content: '---\nname: commit-style\ndescription: ...\n---\n...' }]);
```
## 8. Lifecycle
`terminate()` is a soft shutdown:
- Marks the thread inactive and sets `terminated`
- Aborts in-flight execution
- Rejects future `queueMessage()` and execution attempts
- Parent registries should reflect `'terminated'` status
```typescript
await state.terminate();
```
## 9. Subagent Hierarchy, Communication, and Termination
Subagent-aware runtimes expose parent/child thread relationships through `ThreadState`:
```typescript
const child = await state.getChildThread(referenceId);
const parent = await state.getParentThread();
```
`children` entries track child instance references and status/projection metadata:
```typescript
interface SubagentRegistryEntry {
reference: string;
relationship: string; // the relationship name (`as`) that spawned this instance
name: string; // the child agent definition name
title?: string;
description: string;
blocking?: boolean;
threadName?: string;
initialArguments?: Record;
spawnGroupId?: string;
createdAt?: number;
status: string;
parentCommunication?: 'implicit' | 'explicit';
}
```
Every child instance is a persistent thread: session end (stop, fail, error, or turn-cap) transitions `status` and **never terminates the thread** — only explicit termination does. See [Subagents §4](/0.2.0/specification/subagents#4-instance-lifecycle).
`initialArguments` stores the structured values supplied at child creation. The registry copy is parent-visible metadata; the durable child-side source should live with the child thread's own metadata/properties and be exposed to both child sides as `ThreadState.arguments` and prompt interpolation variables.
See [Subagents](/0.2.0/specification/subagents) for the full lifecycle, communication modes, and cross-thread semantics.
### 9.1 Cross-Thread Attachment Copying
When communication crosses thread boundaries, filesystem references must be copied:
- parent → child for invocation/messaging attachments
- child → parent for completion/failure payload attachments
Returned attachment paths must be valid in the receiving thread filesystem.
### 9.2 Lifecycle Status Messages
Runtimes may persist synthesized status messages (for example, system messages tagged with `metadata.status_kind`) to make cross-thread lifecycle events observable in message feeds.
### 9.3 Parent Messaging
Children can push information up the hierarchy without waiting for completion:
```typescript
await state.notifyParent('halfway through the batch');
await state.setStatus('running');
await state.stopSession({
result: 'waiting for input',
notifyParent: 'Please answer the clarification question',
status: 'waiting for clarification',
});
```
`stopSession()` is distinct from `state.execution.stop()`: it marks the active agent session as terminal for lifecycle/subagent purposes. It **MUST NOT** terminate the thread — the thread remains addressable and a later message starts a new session with history intact. By default it only stops the session; `notifyParent` and `status` are optional side effects.
If a child has no parent thread, `notifyParent()` does not queue anything externally; `setStatus()` similarly becomes a no-op when there is no parent registry entry. Clients can still render the originating tool call or log entry as outbound parent communication.
## 10. Runtime Context (Non-Portable)
The `_notPackableRuntimeContext` property allows runtime implementations to inject platform-specific context.
| Property | Type | Description |
|----------|------|-------------|
| `_notPackableRuntimeContext` | `Record \| undefined` | Runtime-specific context injected by the implementation |
### 10.1 Portability
Tools that access `_notPackableRuntimeContext` cannot be packed, shared, or published to tool registries.
### 10.2 Example: Accessing a Host-Provided Binding
```typescript
import { defineTool } from '@standardagents/builder';
import { z } from 'zod';
export default defineTool({
description: 'Query internal database',
args: z.object({ userId: z.string() }),
execute: async (state, args) => {
const env = state._notPackableRuntimeContext?.env as HostEnv | undefined;
if (!env?.DATABASE) {
return { status: 'error', error: 'Database not available' };
}
const result = await env.DATABASE
.prepare('SELECT * FROM users WHERE id = ?')
.bind(args.userId)
.first();
return { status: 'success', result: JSON.stringify(result) };
},
});
```
> **Tip:** The shape of `_notPackableRuntimeContext` is runtime-defined. Typical implementations expose either a handle to host bindings (databases, key-value stores, object storage) under `env`, or a process/environment handle for server-style runtimes. Consult your runtime's documentation for the specific contract.
## 11. Conformance Requirements
### 11.1 Thread Lifecycle
1. **Creation**: Thread created with metadata
2. **Execution**: Agent processes messages
3. **At Rest**: Thread accessible via endpoints
4. **Resumption**: New execution on next message
### 11.2 Platform Independence
`ThreadState` is an abstract interface. Implementations **MUST NOT** expose:
- Storage implementation details
- Platform-specific bindings
- Internal state management
### 11.3 Error Handling
Methods that return promises **SHOULD** throw on:
- Resource not found (loadModel, loadPrompt, loadAgent)
- Invalid parameters
- Storage errors
Methods **SHOULD NOT** throw on:
- Empty results (return empty arrays/null instead)
- Missing optional data
## 12. TypeScript Reference
```typescript
/**
* Thread state interface - the unified API for thread interactions.
* Available to tools, hooks, and endpoints.
*/
interface ThreadState {
// ─────────────────────────────────────────────────────────────────────────
// Identity (readonly)
// ─────────────────────────────────────────────────────────────────────────
readonly threadId: string;
readonly agentId: string;
readonly userId: string | null;
readonly createdAt: number;
readonly children: SubagentRegistryEntry[];
readonly terminated: number | null;
readonly arguments: Record;
// ─────────────────────────────────────────────────────────────────────────
// Messages — see /threads/messages
// ─────────────────────────────────────────────────────────────────────────
getMessages(options?: GetMessagesOptions): Promise;
getMessage(messageId: string): Promise;
injectMessage(input: InjectMessageInput): Promise;
queueMessage(input: QueueMessageInput): Promise;
updateMessage(messageId: string, updates: MessageUpdates): Promise;
deleteMessage(messageId: string): Promise;
// ─────────────────────────────────────────────────────────────────────────
// Resource Loading
// ─────────────────────────────────────────────────────────────────────────
loadModel(name: string): Promise;
loadPrompt(name: string): Promise;
loadAgent(name: string): Promise;
getChildThread(referenceId: string): Promise;
getParentThread(): Promise;
getPromptNames(): string[];
getAgentNames(): string[];
getModelNames(): string[];
env(propertyName: string): Promise;
instanceEnv?(propertyName: string): Promise;
envType(propertyName: string): Promise<'text' | 'secret'>;
setEnv(
propertyName: string,
value: string,
options?: { type?: 'text' | 'secret' }
): Promise;
notifyParent(content: string): Promise;
setStatus(status: string): Promise;
stopSession(options?: {
result?: string;
notifyParent?: string;
status?: string;
}): Promise;
// ─────────────────────────────────────────────────────────────────────────
// Tool Invocation
// ─────────────────────────────────────────────────────────────────────────
queueTool(toolName: string, args: Record): void;
invokeTool(toolName: string, args: Record): Promise;
// ─────────────────────────────────────────────────────────────────────────
// Effect Scheduling
// ─────────────────────────────────────────────────────────────────────────
scheduleEffect(name: string, args: Record, delay?: number): Promise;
getScheduledEffects(name?: string): Promise;
removeScheduledEffect(id: string): Promise;
// ─────────────────────────────────────────────────────────────────────────
// Events
// ─────────────────────────────────────────────────────────────────────────
emit(event: string, data: unknown): void;
// ─────────────────────────────────────────────────────────────────────────
// Context Storage
// ─────────────────────────────────────────────────────────────────────────
context: Record;
// ─────────────────────────────────────────────────────────────────────────
// Durable Key-Value Store
// ─────────────────────────────────────────────────────────────────────────
getValue(key: string): Promise;
setValue(key: string, value: unknown): Promise;
status(): Promise;
decide(options: DecideOptions): Promise>;
// ─────────────────────────────────────────────────────────────────────────
// File System — see /threads/filesystem
// ─────────────────────────────────────────────────────────────────────────
writeFile(path: string, data: ArrayBuffer | string, mimeType: string, options?: WriteFileOptions): Promise;
readFile(path: string): Promise;
readFileStream(path: string, options?: ReadFileStreamOptions): Promise | null>;
statFile(path: string): Promise;
readdirFile(path: string): Promise;
unlinkFile(path: string): Promise;
mkdirFile(path: string): Promise;
rmdirFile(path: string): Promise;
getFileStats(): Promise;
grepFiles(pattern: string): Promise;
findFiles(pattern: string): Promise;
getFileThumbnail(path: string): Promise;
// ─────────────────────────────────────────────────────────────────────────
// Code Execution — see /threads/code-execution
// ─────────────────────────────────────────────────────────────────────────
runCode(source: string, options?: CodeExecutionOptions): CodeExecution;
// ─────────────────────────────────────────────────────────────────────────
// Execution State — see /threads/execution-state
// ─────────────────────────────────────────────────────────────────────────
execution: ExecutionState | null;
terminate(): Promise;
// ─────────────────────────────────────────────────────────────────────────
// Runtime Context (Non-Portable)
// ─────────────────────────────────────────────────────────────────────────
readonly _notPackableRuntimeContext?: Record;
}
/**
* A scheduled effect pending execution.
*/
interface ScheduledEffect {
id: string;
name: string;
args: Record;
scheduledAt: number; // microseconds
createdAt: number; // microseconds
}
```
---
Source: https://standardagentspec.org/0.2.0/specification/threads/messages
# Messages
Each thread owns an ordered, persistent list of messages — the conversation history the agent reasons over. Tools, hooks, and endpoints read, inject, queue, and update these messages through `ThreadState`.
This page documents the message record, the APIs for manipulating the list, and delivery semantics for queued messages. Thread identity, execution state, and everything else about threads live on the [Threads](/0.2.0/specification/threads) parent page.
> **Note:** The APIs on this page mutate persisted message storage. To modify, inject, or filter messages **non-destructively** — only for the current model call, with the stored history untouched — use [Hooks](/0.2.0/specification/hooks), specifically `filter_messages`, `prefilter_llm_history`, `before_create_message`, and `before_update_message`.
## 1. Message Structure
| Property | Type | Description |
|----------|------|-------------|
| `id` | `string` | Unique message ID |
| `role` | `'system' \| 'user' \| 'assistant' \| 'tool'` | Message role |
| `content` | `string \| null` | Message content |
| `name` | `string \| null` | Tool name (for tool results) |
| `tool_calls` | `string \| null` | JSON-encoded array of tool calls. Each entry is `{ id: string, type: 'function', function: { name: string, arguments: string } }`, where `arguments` is itself JSON-encoded |
| `tool_call_id` | `string \| null` | Tool call ID (for results) |
| `tool_status` | `'success' \| 'error' \| null` | Outcome of the tool call (for results) |
| `status` | `'pending' \| 'completed' \| 'failed' \| null` | Lifecycle state. `pending` while the message is queued or still being generated |
| `attachments` | `AttachmentRef[] \| null` | Files delivered with the message ([§1.2](#12-attachment-references)) |
| `reasoning_content` | `string \| null` | Model reasoning text returned with an assistant message ([§1.3](#13-reasoning)) |
| `reasoning_details` | `string \| null` | Provider-specific reasoning data returned with an assistant message, JSON-encoded ([§1.3](#13-reasoning)) |
| `prompt` | `string \| null` | Name of the prompt that produced the message |
| `created_at` | `number` | Creation timestamp |
| `parent_id` | `string \| null` | Parent message (sub-prompts) |
| `depth` | `number` | Nesting depth (0 = top-level) |
| `silent` | `boolean` | Client-presentation flag. Ordinary UI lists hide the message. The message remains eligible for model context and request-context hooks. |
| `metadata` | `Record` | Custom metadata (may include runtime status markers such as `status_kind`) |
| `subagent_id` | `string \| null` | Subagent reference UUID associated with the message |
| `subagent_relationship` | `string \| null` | Projected relationship name (`as`) of the child (when available) |
| `subagent_name` | `string \| null` | Projected child agent name (when available) |
| `subagent_title` | `string \| null` | Projected child agent title (when available) |
| `subagent_description` | `string \| null` | Projected child description (when available) |
| `subagent_status` | `string \| null` | Projected child status (when available) |
| `subagent_blocking` | `boolean \| null` | Projected blocking flag (when available) |
| `subagent_thread_name` | `string \| null` | Projected human-friendly child instance name (when available) |
| `subagent_spawn_group_id` | `string \| null` | Projected spawn grouping identifier (when available) |
### 1.1 Provenance Metadata Conventions
Runtimes **SHOULD** set the following OPTIONAL `metadata` keys on messages whose content crossed a thread boundary, so relays and orchestrators need no ad-hoc bracket-tag prefixes:
| Key | Meaning |
|-----|---------|
| `metadata.subagent_id` | The child instance reference this message relates to |
| `metadata.forwarded_from` | The origin thread or message of forwarded content |
These are conventions, not requirements: consumers **MUST** tolerate their absence, and runtimes **MUST NOT** rely on them for routing correctness.
### 1.2 Attachment References
An attachment is a file in the thread's [file system](/0.2.0/specification/threads/filesystem) that a message references.
```typescript
interface AttachmentRef {
id: string;
type: 'file';
path: string; // path in the thread file system
name: string; // file name
mimeType: string;
size: number; // bytes
width?: number; // pixels, for images
height?: number; // pixels, for images
description?: string;
}
```
### 1.3 Reasoning
Many models require the reasoning of their earlier turns to be returned to them on later requests. Reasoning is therefore part of the persisted message record.
1. When a model returns reasoning with an assistant message, the runtime **MUST** persist it with that message: the reasoning text in `reasoning_content`, and any provider-specific reasoning data in `reasoning_details`.
2. On a later request in the same thread, the runtime **MUST** supply the persisted reasoning of each assistant message that remains in the request context after [context assembly](/0.2.0/infrastructure/runtime#4-context-assembly) and request-context hooks, in a form the selected provider and model accept. The exception is a prompt that sets [`reasoning.include`](/0.2.0/specification/prompts#6-reasoning-configuration) to `false`: for that prompt's requests the runtime **MUST NOT** supply persisted reasoning.
3. The runtime **MUST NOT** supply the reasoning of a message that is excluded from the request context.
4. When the selected provider or model does not accept a message's `reasoning_details`, the runtime **MUST** omit them from the request or convert them to a form it accepts. It **MUST NOT** send them unchanged. The persisted record is not altered.
5. `reasoning_content` **MUST** be `null` or absent when, and only when, the model returned no reasoning text for the message. `reasoning_details` **MUST** be `null` or absent when, and only when, the model returned no provider-specific reasoning data for the message.
## 2. Reading Messages
```typescript
// Get recent messages
const { messages, total, hasMore } = await state.getMessages({
limit: 50,
order: 'desc',
});
// Get a single message
const message = await state.getMessage('msg-123');
```
### 2.1 Query Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `limit` | `number` | - | Max messages to return |
| `offset` | `number` | 0 | Messages to skip |
| `order` | `'asc' \| 'desc'` | `'desc'` | Sort order |
| `includeSilent` | `boolean` | false | Include silent messages in this query. This option affects read APIs only. |
| `maxDepth` | `number` | - | Max nesting depth |
## 3. Injecting Messages
Messages can be injected into the conversation:
```typescript
const message = await state.injectMessage({
role: 'user',
content: 'Additional context...',
silent: true, // Hide from ordinary UI lists
metadata: { source: 'tool' },
});
```
### 3.1 Persistence and lifecycle
`injectMessage()` creates a persisted conversation message. The same contract applies during active execution and at rest.
- Implementations **MUST** invoke `before_create_message` and `after_create_message` for every successful injection. See [Hooks §4](/0.2.0/specification/hooks#4-message-lifecycle-hooks).
- The returned promise **MUST** resolve after the message is persisted and available through thread message APIs (`getMessage`, `getMessages`).
- `injectMessage()` **MUST NOT** recursively restart request-context hooks (`filter_messages`, `prefilter_llm_history`).
### 3.2 Presentation (`silent`)
`silent` is a client-presentation flag.
- Clients **MUST** hide silent messages from ordinary message lists unless the caller sets `includeSilent: true`.
- Silent messages **MUST** remain eligible for model context.
- Silent messages **MUST** participate in the ordinary request-context hooks.
- `silent` **MUST NOT** change persistence, lifecycle hooks, or same-execution visibility.
### 3.3 Same-execution visibility
During an active execution, a successfully injected message **MUST** become observable to subsequent tools and hooks in that execution.
[`execution.messageHistory`](/0.2.0/specification/threads/execution-state#22-live-execution-history) **MUST** represent live chronological persisted execution history. It **MUST** include silent messages. Synthetic or transformed messages returned by request-context hooks **MUST** remain confined to the request context.
### 3.4 Context snapshot assignment
Each model-context assembly takes a stable snapshot of eligible persisted history. See [Runtime §4](/0.2.0/infrastructure/runtime#4-context-assembly) and [Hooks §3.4](/0.2.0/specification/hooks#34-stored-history-and-the-request-context).
- Messages persisted before the snapshot **MUST** be eligible for that assembly.
- Messages injected after the snapshot begins **MUST** become eligible for the following context assembly.
## 4. Queueing Messages
Messages can be queued for delivery on the next execution step:
```typescript
await state.queueMessage({
role: 'user', // the side B perspective
content: 'Follow-up task',
silent: true,
});
```
**Perspective mapping (canonical statement).** Message roles are the single source of perspective truth, for queueing, injection, and rendering alike:
- `role: 'user'` is the **side B** perspective — a message side A acts on.
- `role: 'assistant'` is the **side A** perspective — a message side B acts on.
This mapping is independent of what backs each side (human, prompt, or handler). Subagent traffic delivered to a parent lands in the perspective that prompts the relationship's *owning side* to take its turn — see [Subagents §2.1](/0.2.0/specification/subagents#21-the-owning-side).
Queue semantics:
- If the thread is executing, queued messages are injected before the next LLM request.
- If the thread is idle, queueing forces a new turn.
- Queued messages are processed in order.
## 5. Updating Messages
Existing messages can be updated:
```typescript
const updated = await state.updateMessage('msg-123', {
content: 'Updated content',
metadata: { edited: true },
});
```
## 6. Deleting Messages
```typescript
const deleted = await state.deleteMessage('msg-123');
```
Returns `true` if the message was found and removed, `false` otherwise. Tool-result messages cascade with their parent assistant message.
## 7. Conformance Scenarios
A conforming runtime **MUST** satisfy these portable scenarios.
| Scenario | Observable result |
|----------|-------------------|
| Inject during active execution | `before_create_message` and `after_create_message` each run once. `getMessage` returns the persisted record. Later tools and hooks in the same execution observe the message on `execution.messageHistory`. |
| Inject at rest | The same lifecycle hooks run. The message is available through thread message APIs before the next execution starts. |
| Silent and visible injection | Both records persist. Both appear on `execution.messageHistory`. Both are eligible for the next context snapshot. Ordinary UI queries omit the silent record unless `includeSilent` is true. |
| `filter_messages` edits the request context | Trimming, compaction, redaction, and synthetic messages affect the provider request. `execution.messageHistory` continues to list the live persisted records. |
| Inject from `filter_messages` | Lifecycle hooks run. Context assembly does not restart. The injected message is absent from the current provider request and eligible for the following assembly. |
| Inject from `prefilter_llm_history` | Same snapshot assignment as injection from `filter_messages`. |
| Inject from `after_system_message` | The message is persisted before the history snapshot. It is eligible for the current assembly and passes through `filter_messages`. |
---
Source: https://standardagentspec.org/0.2.0/specification/threads/filesystem
# File System
Each thread has an isolated file system for storing files, images, and other binary data. It is addressable through `ThreadState` and survives execution cycles — two separate invocations of the same thread see the same file tree.
This page documents the file system APIs. For an overview of threads themselves, see [Threads](/0.2.0/specification/threads).
## 1. File Record
Files are represented by the `FileRecord` type:
| Property | Type | Description |
|----------|------|-------------|
| `path` | `string` | File path (relative to thread root) |
| `name` | `string` | File name |
| `mimeType` | `string` | MIME type |
| `storage` | `string` | Implementation-defined storage identifier |
| `size` | `number` | File size in bytes |
| `isDirectory` | `boolean` | Whether this is a directory |
| `metadata` | `Record` | Custom metadata |
| `width` | `number` | Image width in pixels (if applicable) |
| `height` | `number` | Image height in pixels (if applicable) |
## 2. Writing Files
```typescript
// Write a text file
const record = await state.writeFile(
'/data/config.json',
JSON.stringify({ key: 'value' }),
'application/json'
);
// Write a binary file with metadata
const imageRecord = await state.writeFile(
'/images/photo.jpg',
imageBuffer,
'image/jpeg',
{ width: 1920, height: 1080 }
);
```
## 3. Reading Files
```typescript
// Read file content
const data = await state.readFile('/data/config.json');
if (data) {
const text = new TextDecoder().decode(data);
const config = JSON.parse(text);
}
// Get file metadata without reading content
const info = await state.statFile('/images/photo.jpg');
if (info) {
console.log(`Size: ${info.size} bytes`);
}
```
## 4. Directory Operations
```typescript
// Create a directory
await state.mkdirFile('/documents');
// List directory contents
const { entries } = await state.readdirFile('/documents');
for (const entry of entries) {
console.log(`${entry.isDirectory ? 'DIR' : 'FILE'}: ${entry.name}`);
}
// Remove an empty directory
await state.rmdirFile('/documents');
// Delete a file
await state.unlinkFile('/data/config.json');
```
## 5. Moving and Renaming
`moveFile` relocates a file or directory to a new path, and `renameFile`
changes an entry's name while keeping it in the same directory. Both return
the moved entry's `FileRecord` at its new path.
```typescript
// Move a file to a different directory
await state.moveFile('/drafts/post.md', '/published/post.md');
// Move an entire directory — the whole subtree moves with it
await state.moveFile('/tmp/work', '/archive/2024/work');
// Rename in place (newName must not contain path separators)
await state.renameFile('/notes/draft.txt', 'final.txt');
```
Both operations apply to files and directories. Moving a directory relocates
its entire subtree, preserving the relative layout of its contents.
Constraints:
1. **Source must exist.** Moving a missing path throws.
2. **Destination must be free.** `moveFile` does not overwrite; if the
destination path (or a subtree rooted at it) already exists, it throws.
Delete or move the existing entry first.
3. **No moving a directory into itself.** A directory cannot be moved to its
own path or to one of its descendants (e.g. `/a` → `/a/b`).
4. **`renameFile` names are bare.** `newName` must not contain `/`; use
`moveFile` to change an entry's directory.
## 6. Search Operations
```typescript
// Search file contents
const grepResults = await state.grepFiles('error');
for (const result of grepResults) {
console.log(`${result.path}:`);
for (const match of result.matches) {
console.log(` Line ${match.line}: ${match.content}`);
}
}
// Find files by glob pattern
const { paths } = await state.findFiles('**/*.json');
console.log('JSON files:', paths);
```
## 7. File Statistics
```typescript
const stats = await state.getFileStats();
console.log(`Files: ${stats.fileCount}`);
console.log(`Directories: ${stats.directoryCount}`);
console.log(`Total size: ${stats.totalSize} bytes`);
```
## 8. Image Thumbnails
```typescript
const thumbnail = await state.getFileThumbnail('/images/photo.jpg');
if (thumbnail) {
// Use thumbnail data
}
```
## 9. Streaming Files
For large files, `readFileStream` provides memory-efficient access by yielding data in chunks.
### 9.1 Method
```typescript
readFileStream(
path: string,
options?: ReadFileStreamOptions
): Promise | null>
```
### 9.2 Options
| Property | Type | Description |
|----------|------|-------------|
| `signal` | `AbortSignal` | Optional abort signal for cancellation |
### 9.3 FileChunk
| Property | Type | Description |
|----------|------|-------------|
| `data` | `Uint8Array` | Raw binary data for this chunk |
| `index` | `number` | 0-based index of this chunk |
| `totalChunks` | `number` | Total number of chunks |
| `isLast` | `boolean` | Whether this is the final chunk |
### 9.4 Behavior
1. **File Not Found**: Returns `null` if the file does not exist.
2. **External Files**: Returns `null` for files whose `storage` identifier references an external system (object storage, a remote URL, etc.). External files must be fetched using their storage location.
3. **Small Files**: Files under the chunk threshold are yielded as a single chunk with `index: 0`, `totalChunks: 1`, and `isLast: true`.
4. **Chunked Files**: Large files yield multiple chunks in sequential order (0, 1, 2...).
5. **Ordering Guarantee**: Chunks are always yielded in sequential order. Implementations **MUST NOT** yield chunks out of order.
6. **Abort Signal**: When triggered, the stream stops yielding new chunks. Already-yielded chunks remain valid.
### 9.5 Example: Processing Large File
```typescript
const stream = await state.readFileStream('/uploads/video.mp4');
if (!stream) {
throw new Error('File not found');
}
for await (const chunk of stream) {
console.log(`Progress: ${chunk.index + 1}/${chunk.totalChunks}`);
// Process chunk.data without loading entire file into memory
}
```
### 9.6 Example: HTTP Streaming Response
```typescript
const stream = await state.readFileStream('/uploads/large-file.bin');
if (!stream) {
return new Response('Not Found', { status: 404 });
}
const readable = new ReadableStream({
async start(controller) {
for await (const chunk of stream) {
controller.enqueue(chunk.data);
}
controller.close();
}
});
return new Response(readable, {
headers: { 'Content-Type': 'application/octet-stream' }
});
```
---
Source: https://standardagentspec.org/0.2.0/specification/threads/code-execution
# Code Execution
Code execution lets an agent run JavaScript or TypeScript source on demand inside an isolated sandbox. The sandbox has **no global access** to its host — every capability (`fs`, `fetch`, `console`, custom business logic) is explicitly bridged in through `imports` and `globals`. Results flow back via the export selected by `options.execute` or through bridged "report" callbacks.
This page is the caller-facing contract: how to invoke `runCode`, what options it accepts, what shape the result has, and the **limitations** agent authors need to know when writing code that will run inside the sandbox. For the runtime-side mechanics (isolate setup, enforcement, implementation approaches), see [Runtime §13 Code Execution Runtime](/0.2.0/infrastructure/runtime#13-code-execution-runtime).
## 1. What You Get
When you call `state.runCode(source, options)`:
- The source runs as an ES module in a fresh sandbox with no host capabilities.
- Anything you pass through `options.imports` is resolvable as a bare-specifier import inside the sandbox.
- Anything you pass through `options.globals` is resolvable as a free identifier inside the sandbox.
- `options.execute` chooses which module export to run and which arguments to pass. It defaults to `{ fn: 'default', args: [] }`.
- The call returns a [`CodeExecution` handle](#22-codeexecution-handle) — awaitable, terminatable, with a live `reports` view.
- The spec does not mandate a wall-clock timeout; callers impose their own by calling `handle.terminate()`.
Code execution is not a Node.js runtime, a web runtime, or a Worker runtime. It is a plain ECMAScript evaluator. The surface is identical across host platforms.
## 2. API Surface
Code execution is invoked through `ThreadState.runCode()`, which returns a `CodeExecution` handle. The handle is awaitable and exposes a `terminate()` method for caller-initiated cancellation.
### 2.1 Signature
```typescript
runCode(
source: string,
options?: CodeExecutionOptions,
): CodeExecution;
```
| Parameter | Type | Description |
|-----------|------|-------------|
| `source` | `string` | JavaScript or TypeScript source text. Treated as an ECMAScript module. |
| `options` | `CodeExecutionOptions` | Export selection, imports, globals, memory cap, and language hints. |
### 2.2 CodeExecution Handle
```typescript
interface CodeExecution extends PromiseLike {
/** Stop the run. Idempotent. Settles the handle with `status: 'terminated'`. */
terminate(reason?: string): void;
/** `true` until the handle settles. */
readonly running: boolean;
/** Snapshot of values emitted via the `report` bridge so far, in call order. */
readonly reports: readonly unknown[];
}
```
- The handle is a `PromiseLike`; `await run` yields the final result.
- `terminate(reason?)` stops the run. Subsequent calls are no-ops. When `reason` is provided, it surfaces in `result.error.message`.
- `running` flips to `false` once the handle settles.
- `reports` is a live, append-only view of values emitted via the `report` bridge. The same values appear in `CodeExecutionResult.reports` when the run ends.
Callers that need a time budget layer one on themselves:
```typescript
const run = state.runCode(source, options);
const budget = setTimeout(() => run.terminate('30s budget'), 30_000);
const result = await run;
clearTimeout(budget);
```
### 2.3 Example
```typescript
const run = state.runCode(
`
import { readFile } from 'fs';
import { report } from 'supervisor';
const message = await getMessage();
if (/username/.test(message)) {
report({ topic: 'username', message });
}
export async function scan() {
return { scanned: true };
}
`,
{
execute: { fn: 'scan', args: [] },
imports: {
fs: {
readFile: async (path: string) => state.readFile(path),
},
supervisor: {
report: (payload: unknown) => {
// host-side sink
},
},
},
globals: {
console: { log: (...args: unknown[]) => {} },
getMessage: async () => 'latest user message',
},
},
);
const result = await run;
if (result.status === 'success') {
// result.result is the resolved scan() return value: { scanned: true }
}
```
## 3. CodeExecutionOptions
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `execute` | `{ fn?: string; args?: unknown[] }` | `{ fn: 'default', args: [] }` | Export to execute and arguments to pass if the export is a function. Use `fn: 'default'` for the default export. |
| `imports` | `Record>` | `{}` | Map of module specifier → named exports exposed to the sandbox. Resolves bare-specifier imports only. |
| `modules` | `Record` | `{}` | Additional relative ES modules available to the sandbox, keyed by relative specifier such as `'./helpers.js'`. |
| `globals` | `Record` | `{}` | Map of identifier → value installed on the sandbox's module scope. |
| `language` | `'javascript' \| 'typescript'` | `'typescript'` | Source language. TypeScript source is stripped of types before evaluation; no type checking is performed. |
| `memoryLimitBytes` | `number` | runtime-defined | Maximum sandbox heap in bytes. Exceeding this settles the handle with `status: 'memory'`. |
| `filename` | `string` | `''` | Label used in stack traces and error sources. |
| `report` | `(value: unknown) => void` | — | Optional host-side sink invoked for every value emitted through the built-in `report` bridge. Collected values are also exposed on the handle's live `reports` array and in the final `CodeExecutionResult.reports`. |
Unknown keys on `options` are rejected.
Deadlines are **not** an option. The caller implements their own budget by calling `handle.terminate()` ([§2.2](#22-codeexecution-handle)).
### 3.1 Execute
`execute` selects the module export that becomes `CodeExecutionResult.result`.
```typescript
const run = state.runCode(
`
export function increment(n: number): number {
return n + 1;
}
export default function fallback() {
return 123;
}
`,
{
execute: { fn: 'increment', args: [100] },
},
);
```
Rules:
- When `execute` is omitted, the runtime behaves as if `{ fn: 'default', args: [] }` was supplied.
- `fn` names the export to execute. Use `'default'` for the default export.
- If the selected export is a function, the runtime calls it with `args` inside the sandbox and awaits any returned thenable.
- If the selected export is not a function, `args` MUST be omitted or empty and the export value itself becomes the result.
- Missing selected exports fail the run with `status: 'link_error'`.
- `args` use the same marshaling rules as other sandbox boundary values.
### 3.2 Imports
`imports` maps a bare specifier to an object of named exports.
```typescript
imports: {
fs: {
readFile: async (path) => { /* ... */ },
writeFile: async (path, data) => { /* ... */ },
},
}
```
Inside the sandbox:
```typescript
import { readFile, writeFile } from 'fs';
import * as fs from 'fs'; // namespace import of the same object
```
The default export of a bridged module is the value at key `default`:
```typescript
imports: { greeter: { default: (name) => `hi, ${name}` } }
// inside: import greet from 'greeter';
```
Rules:
- Only **bare specifiers** are resolvable from `options.imports` (`'fs'`, `'supervisor'`, `'@scope/pkg'`). Relative specifiers resolve from `options.modules`; URL (`'https://…'`) specifiers fail at module link time.
- Specifiers are not resolved from any host package resolver, node_modules, CDN, or virtual module registry — only from `options.imports` or `options.modules`.
- Importing an unknown specifier fails linkage.
- Named-export mismatches (`import { x }` where `x` is missing) fail linkage.
### 3.3 Modules
`modules` provides local relative ES modules to the sandbox.
```typescript
const run = state.runCode(
`
import { add } from './math.js';
export const result = add(1, 2);
`,
{
execute: { fn: 'result' },
modules: {
'./math.js': 'export const add = (a, b) => a + b;',
},
},
);
```
Rules:
- Keys MUST be relative specifiers from the module graph root, such as `'./helpers.js'` or `'./lib/math.js'`.
- Entry source imports resolve from `filename` when one is supplied.
- Entry and module source MAY import sibling or parent modules with `./` and `../` specifiers when those imports resolve within the supplied module graph.
- Values are JavaScript or TypeScript module source and are evaluated inside the same sandbox.
- `modules` are not host filesystem reads and do not grant package, URL, CDN, or `node_modules` access.
### 3.4 Globals
`globals` installs identifiers at module scope. They are **not** installed on `globalThis`.
```typescript
globals: {
console: { log: (...args) => {} },
getMessage: async () => '...',
}
```
Inside the sandbox:
```typescript
console.log('hi'); // works
const m = await getMessage(); // works
globalThis.console; // undefined — globals are not on globalThis
```
This distinction matters for the [limitations](#6-limitations) — sandbox code cannot enumerate bridged capabilities via `Object.keys(globalThis)`.
### 3.5 Bridged Value Marshaling
Values cross the sandbox boundary in both directions (host → sandbox via `imports`/`globals`, sandbox → host via call arguments and return values).
| Host value | Sandbox view | Notes |
|-----------|--------------|-------|
| `string`, `number`, `boolean`, `null`, `undefined`, `bigint` | Same primitive | Cloned by value. |
| Plain object / array / `Map` / `Set` / `Date` / typed array | Structured clone | Deep copy; no shared reference. |
| `Function` | Callable proxy | Calls forward serialized args to host; return value (or resolved promise) marshaled back. |
| `Promise` | `Promise` | Resolves/rejects asynchronously inside sandbox. |
| `ArrayBuffer` / `Uint8Array` | Same binary view | Cloned. |
| Class instance, `WeakMap`, `WeakRef`, symbol with host identity | **Not transferable** | May throw a `SerializationError`. |
Bridged functions do not expose host `this` or host closure state to the sandbox beyond their explicit arguments.
Asynchronous bridges are supported: a bridged function may return a `Promise`, and the sandbox's `await` unwraps it.
## 4. CodeExecutionResult
```typescript
interface CodeExecutionResult {
status: 'success' | 'error' | 'memory' | 'terminated' | 'link_error';
result?: unknown;
reports: unknown[];
logs: CodeExecutionLog[];
error?: CodeExecutionError;
durationMs: number;
memoryUsedBytes?: number;
}
```
| Field | Type | Description |
|-------|------|-------------|
| `status` | enum | Outcome classification. See [§4.1](#41-status-values). |
| `result` | `unknown` | Resolved selected export, after optionally calling it with `execute.args` and awaiting top-level promises. Omitted on non-success outcomes. |
| `reports` | `unknown[]` | Values emitted through the `report` bridge, in call order. Empty array if unused. |
| `logs` | `CodeExecutionLog[]` | Captured `console.*` calls when the runtime installs a capturing `console`. Empty when the caller supplies its own. |
| `error` | `CodeExecutionError` | Present iff `status` is not `'success'`. |
| `durationMs` | `number` | Wall-clock execution time in milliseconds, from `runCode()` invocation to handle settlement. |
| `memoryUsedBytes` | `number` | Peak sandbox heap in bytes when the engine exposes heap-usage measurement; omitted otherwise. |
### 4.1 Status Values
| Status | Meaning |
|--------|---------|
| `success` | Module evaluated; selected export resolved. |
| `error` | Uncaught runtime error inside the sandbox. |
| `memory` | `memoryLimitBytes` exceeded. |
| `terminated` | Caller called `handle.terminate()`, or the runtime's own safety cap fired. `error.message` distinguishes the two (including any `reason` the caller passed). |
| `link_error` | Module graph failed to link (unknown specifier, missing named export, parse error). |
### 4.2 CodeExecutionError
```typescript
interface CodeExecutionError {
name: string;
message: string;
stack?: string;
/** Module specifier that failed to link, when applicable. */
specifier?: string;
/** Source filename associated with line and column, when available. */
filename?: string;
/** 1-based line in source, when available. */
line?: number;
/** 1-based column in source, when available. */
column?: number;
}
```
Errors raised by bridged functions are reflected into the sandbox as a regular thrown error. Host-side stack traces do not leak into the sandbox result.
### 4.3 CodeExecutionLog
```typescript
interface CodeExecutionLog {
level: 'log' | 'info' | 'warn' | 'error' | 'debug';
args: unknown[];
timestamp: number;
}
```
Only populated when the runtime installs a capturing `console` (typically when the caller does not provide one via `options.globals`).
## 5. Result Channels
The sandbox has **two** channels for returning data. They coexist and can both be used in the same run.
### 5.1 Configured Export
The canonical success result is the module export selected by `options.execute`. By default this is the module's default export:
```typescript
export default { summary: 'ok', matches: 3 };
```
After module evaluation, the runtime resolves the configured export as follows:
1. Read `module.namespace[execute.fn]`, where `execute.fn` defaults to `'default'`.
2. If it is a function (including an async function), **call it with `execute.args`** inside the sandbox. The result of that call is then processed by step 3.
3. If the current candidate is a `Promise` (or thenable), **await it**. Repeat this step until the value is no longer a thenable.
4. Marshal the final value into `CodeExecutionResult.result`.
All four of these produce the same surface for callers:
```typescript
export default 42; // result === 42
export default async () => 42; // result === 42
export default () => Promise.resolve(42); // result === 42
export default Promise.resolve(42); // result === 42
```
Named exports are selected with `execute.fn`:
```typescript
export function increment(n: number) {
return n + 1;
}
// state.runCode(source, { execute: { fn: 'increment', args: [100] } })
// result === 101
```
If the selected export is missing, the run settles with `status: 'link_error'`. If the selected export is not a function and `execute.args` is non-empty, the run settles with `status: 'error'`. If the selected export function throws (or its returned promise rejects), the run settles with `status: 'error'` and the thrown value in `error.message` — identical to any other uncaught runtime error.
### 5.2 Bridge Reports
For streaming or multi-value output, pass a `report` callback into the sandbox as a bridged function:
```typescript
const run = state.runCode(source, {
imports: {
supervisor: {
report: (payload) => telemetry.push(payload),
},
},
});
```
Every `report(x)` call runs the host sink synchronously (or returns its promise).
When `options.report` is supplied, the runtime installs a built-in `report` global that forwards values to it, and pushes each reported value into `CodeExecutionResult.reports` in call order.
Use whichever channel fits: configured export for "this code computes one answer"; reports for "this code scans and flags N things."
## 6. Limitations
These are the things your sandboxed source code **cannot** do. They are a design property of code execution, not a configuration knob.
### 6.1 No Host Capabilities on `globalThis`
The sandbox's `globalThis` contains only ECMAScript intrinsics (`Object`, `Array`, `Promise`, `Math`, `JSON`, `Map`, `Set`, `Date`, `RegExp`, `Error`, typed arrays, `BigInt`, `Symbol`, `Reflect`, `Proxy`, `structuredClone`) plus `globalThis`, `undefined`, `NaN`, `Infinity`.
It does **not** contain `process`, `global`, `window`, `self`, `document`, `require`, `Deno`, `Bun`, `fetch`, `Request`, `Response`, `URL`, `URLSearchParams`, `WebSocket`, `WebAssembly`, `crypto`, `setTimeout`, `setInterval`, `setImmediate`, `performance`, `atob`, `btoa`, `TextEncoder`, or `TextDecoder` — unless the caller explicitly installed one via `globals`.
If your code needs any of those, bridge them in.
### 6.2 No Dynamic Code Loading
Inside the sandbox:
- `eval` is absent or throws.
- `Function`, `AsyncFunction`, and `GeneratorFunction` constructors throw when called with source strings.
- Dynamic `import(...)` only resolves specifiers present in `options.imports` or `options.modules`; URL imports reject.
### 6.3 No Shared Memory With the Host
- No `SharedArrayBuffer`, no `Atomics`, no postMessage-style channels.
- Bridged values cross the boundary by **deep clone** ([§3.5](#35-bridged-value-marshaling)). A sandbox mutation of a received object does not affect the host-side source object.
### 6.4 No Runtime-Imposed Deadline
The spec does not enforce a wall-clock timeout. `handle.terminate()` signals the sandbox to stop at the next yield point — usually a few milliseconds, but a pure-synchronous tight loop may run until the runtime's own safety cap fires.
Callers **SHOULD**:
- wrap untrusted code with their own `setTimeout` + `handle.terminate()`, as shown in [§2.2](#22-codeexecution-handle); and
- where the run may be CPU-bound, treat the platform safety cap as the worst-case upper bound.
### 6.5 Memory Is Capped
If you set `memoryLimitBytes`, exceeding it settles the handle with `status: 'memory'`. If you omit it, a runtime-defined default applies. Plan allocations accordingly.
### 6.6 Timers Are Not Bridged Automatically
The sandbox has a working microtask queue — `Promise`, `await`, and `queueMicrotask` behave normally. But `setTimeout` / `setInterval` are absent unless the caller bridges them.
### 6.7 Nondeterministic Intrinsics Are Present
`Date.now()` and `Math.random()` work inside the sandbox and are nondeterministic. If you need determinism, bridge deterministic replacements through `globals`.
### 6.8 Each Run Is Fresh
Every call to `runCode` gets its own isolate. State — module caches, intrinsic mutations, top-level variables — does **not** carry over between runs. If you need persistence, write to thread storage through a bridged function.
## 7. TypeScript Support
When `language` is `'typescript'` (the default):
- The runtime accepts TypeScript source.
- Types are erased before evaluation. Type errors are ignored — only syntax errors block linkage.
- `import type`, `export type`, `satisfies`, `as`, generics, enums, and namespaces are all accepted at the erasure layer.
- `tsconfig.json` is **not** consulted. No path aliases, no `paths`, no `baseUrl`.
When `language` is `'javascript'`, the source is parsed as standard ECMAScript modules with no transformation.
## 8. Module Semantics
- Source is evaluated as an **ES module**. `import`, `export`, and top-level `await` are available.
- There is one entry module per `runCode` call plus any caller-supplied `options.modules`.
- `imports` entries are synthetic modules: their namespace is a frozen copy of the host-provided object.
- `modules` entries are source-backed ES modules available by relative specifier.
- `import.meta` exposes only `{ url: string }` where `url` is a synthetic `sandbox:` URL. Host paths are not exposed.
## 9. Interaction With Thread State
`runCode` is a method on `ThreadState`. It runs on behalf of a thread, but the sandbox **does not** receive `state` implicitly. If you want the sandbox to read thread messages, files, or env, bridge the specific capabilities you want to expose:
```typescript
await state.runCode(source, {
imports: {
thread: {
readFile: (path) => state.readFile(path),
getMessages: (opts) => state.getMessages(opts),
emit: (event, data) => state.emit(event, data),
},
},
});
```
This is intentional: bridges are a capability boundary. Leaking `state` would let sandboxed code invoke arbitrary tools, mutate thread env, or terminate the thread — the opposite of what isolation means.
Bridged functions run on the host side and can await thread operations, schedule effects, emit events, or call tools.
## 10. Usage Patterns
### 10.1 Single-Value Computation
```typescript
const { result } = await state.runCode(
`
const n = input.reduce((a, b) => a + b, 0);
export default n;
`,
{ globals: { input: [1, 2, 3] } },
);
// result === 6
```
### 10.2 Flagging Multiple Items
```typescript
const result = await state.runCode(
`
import { report } from 'supervisor';
for (const row of rows) {
if (row.flagged) report(row.id);
}
`,
{
globals: { rows: await loadRows() },
imports: {
supervisor: { report: (id) => flaggedIds.add(id) },
},
},
);
```
### 10.3 Running Model-Authored Code With a Deadline
```typescript
const userCode = llmResponse.code; // untrusted, produced by an LLM
const run = state.runCode(userCode, {
memoryLimitBytes: 64 * 1024 * 1024,
globals: {
input: await state.readFile('/data/input.json'),
},
});
const deadline = setTimeout(() => run.terminate('2s budget'), 2_000);
const result = await run;
clearTimeout(deadline);
if (result.status !== 'success') {
// surface result.error to the model as a tool error
}
```
### 10.4 Composing With Tools
Custom tools can be thin wrappers around `runCode`:
```typescript
export default defineTool({
description: 'Evaluate an expression against thread data',
args: z.object({ code: z.string() }),
execute: async (state, { code }) => {
const run = state.runCode(code, {
imports: {
thread: { readFile: (p) => state.readFile(p) },
},
});
const deadline = setTimeout(() => run.terminate('2s budget'), 2_000);
const result = await run;
clearTimeout(deadline);
return result.status === 'success'
? { status: 'success', result: JSON.stringify(result.result) }
: { status: 'error', error: result.error?.message ?? 'run failed' };
},
});
```
## 11. Security Considerations
- **Untrusted source**. Source from an LLM or remote user is untrusted. The sandbox and its limitations ([§6](#6-limitations)) are the barriers against escape. Do not relax them based on source inspection.
- **Bridged callables are the attack surface**. Once a function crosses the boundary, the sandbox may call it repeatedly with any serializable arguments. Bridged functions **MUST** validate arguments against an explicit schema and **SHOULD** enforce their own call-rate budget when they perform expensive work.
- **Host-side data exposure**. Bridged functions run on the host and can reach any state the host closure captures. They **MUST NOT** return values that were not deliberately exposed — secrets, other threads' state, and unrelated environment variables **MUST NOT** be reachable through a bridge unless the caller explicitly passed them.
- **Runaway execution**. Callers evaluating untrusted code **MUST** enforce their own deadline via `setTimeout` + `handle.terminate()`. `terminate()` settles at the next yield point; for CPU-bound loops, the platform safety cap is the effective worst case.
- **Memory exhaustion**. Callers **SHOULD** set `memoryLimitBytes` explicitly when evaluating untrusted code.
- **Log redaction**. Captured `logs` may contain values derived from `globals`. Treat `logs` with the same confidentiality level as the most sensitive input passed into `globals` or `imports`.
## 12. TypeScript Reference
```typescript
interface CodeExecutionOptions {
execute?: {
fn?: string;
args?: unknown[];
};
imports?: Record>;
modules?: Record;
globals?: Record;
language?: 'javascript' | 'typescript';
memoryLimitBytes?: number;
filename?: string;
report?: (value: unknown) => void;
}
interface CodeExecution extends PromiseLike {
terminate(reason?: string): void;
readonly running: boolean;
readonly reports: readonly unknown[];
}
interface CodeExecutionResult {
status: 'success' | 'error' | 'memory' | 'terminated' | 'link_error';
result?: unknown;
reports: unknown[];
logs: CodeExecutionLog[];
error?: CodeExecutionError;
durationMs: number;
memoryUsedBytes?: number;
}
interface CodeExecutionLog {
level: 'log' | 'info' | 'warn' | 'error' | 'debug';
args: unknown[];
timestamp: number;
}
interface CodeExecutionError {
name: string;
message: string;
stack?: string;
specifier?: string;
filename?: string;
line?: number;
column?: number;
}
```
---
Source: https://standardagentspec.org/0.2.0/specification/threads/runtime-streams
# Runtime Streams
Runtime streams are an optional `ThreadState` capability for opening live,
runtime-authorized byte streams. They let portable agent code exchange opaque
bytes with an execution host without specifying what the capability means or
how a runtime transports it.
## 1. Types
```typescript
interface RuntimeStreamRequest {
capability: string;
metadata?: Record;
timeoutMs?: number;
}
interface RuntimeByteStream {
readonly readable: ReadableStream;
readonly writable: WritableStream;
readonly closed: Promise<{ ok: boolean; error?: string }>;
close(reason?: string): void;
}
type RuntimeStreamErrorCode =
| 'unsupported'
| 'unavailable'
| 'refused'
| 'timeout';
type RuntimeStreamResult =
| { ok: true; stream: RuntimeByteStream }
| { ok: false; error: string; code?: RuntimeStreamErrorCode };
interface RuntimeStreams {
open(request: RuntimeStreamRequest): Promise;
}
interface ThreadState {
readonly runtimeStreams?: RuntimeStreams;
}
```
## 2. Optional Capability
`runtimeStreams` is optional. Existing runtimes may omit it and remain
conformant, so agent code must feature-detect it before opening a stream.
Capability names and metadata are opaque to this specification. Runtimes own
capability authorization and may refuse any request. A runtime must not infer
portable semantics from a capability name or interpret metadata in a shared
layer.
## 3. Direction and Lifetime
- `readable` carries bytes from the execution host to the runtime.
- `writable` carries bytes from the runtime to the execution host.
- Streams are live, non-durable resources. They never park and do not survive
an execution-host disconnect.
- Closing the writable side is a graceful half-close: the host may continue
sending bytes through `readable`.
- `close(reason?)` aborts the complete stream and is idempotent.
- `closed` settles exactly once with the final stream outcome.
## 4. Neutral Example
This tool sends media bytes to a workstation-hosted transcoder and reads the
encoded result. The example demonstrates feature detection, opening, writing,
reading, and cleanup.
```typescript
const runtimeStreams = state.runtimeStreams;
if (!runtimeStreams) {
return { status: 'error', error: 'This runtime has no workstation streams.' };
}
const opened = await runtimeStreams.open({
capability: 'workstation_transcoder',
metadata: { inputFormat: 'wav', outputFormat: 'opus' },
timeoutMs: 10_000,
});
if (!opened.ok) {
return { status: 'error', error: opened.error, error_code: opened.code };
}
const { stream } = opened;
try {
const writer = stream.writable.getWriter();
try {
await writer.write(sourceMedia);
await writer.close();
} finally {
writer.releaseLock();
}
const reader = stream.readable.getReader();
const chunks: Uint8Array[] = [];
try {
for (;;) {
const { value, done } = await reader.read();
if (done) break;
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const outcome = await stream.closed;
if (!outcome.ok) throw new Error(outcome.error ?? 'Transcoder stream failed.');
return { status: 'success', result: `Received ${chunks.length} encoded chunks.` };
} finally {
stream.close();
}
```
## 5. Conformance
A runtime that implements `runtimeStreams` must preserve byte ordering in both
directions, support graceful writable half-close and complete abort, and settle
`closed` once for every successfully opened stream. `open()` should report
refusal without creating a stream, return `unavailable` when the selected
execution host is absent, and return `timeout` when stream opening exceeds the
requested or runtime-defined deadline.
---
Source: https://standardagentspec.org/0.2.0/specification/threads/execution-state
# Execution State
`ThreadState.execution` is present while a thread is actively running (during tool calls, hook invocations, sub-prompts) and `null` when the thread is at rest (from endpoints, external callers). Execution state carries step counts, the active dual-side, cancellation, and controls for stopping or forcing turns.
For everything else about threads, see [Threads](/0.2.0/specification/threads).
## 1. Availability
The `execution` property is:
- **Present** during active execution (tools, hooks)
- **Null** when accessing at rest (endpoints)
```typescript
if (state.execution) {
console.log(`Step ${state.execution.stepCount}`);
}
```
## 2. Execution Properties
| Property | Type | Description |
|----------|------|-------------|
| `flowId` | `string` | Unique execution ID |
| `currentSide` | `'a' \| 'b'` | The side whose turn is executing |
| `stepCount` | `number` | Total LLM request/response cycles |
| `sideAStepCount` | `number` | Side A steps |
| `sideBStepCount` | `number` | Side B steps |
| `stopped` | `boolean` | Execution stopped |
| `stoppedBy` | `'a' \| 'b' \| undefined` | Who stopped |
| `messageHistory` | `Message[]` | Live chronological persisted execution history, including silent messages |
| `abortSignal` | `AbortSignal` | Cancellation signal |
| `promptPath` | `string[]` | Path from root to current prompt |
### 2.1 Prompt Path
The `promptPath` property tracks the current position in the prompt hierarchy:
- At root level: `['my_prompt']`
- Inside a sub-prompt: `['my_prompt', 'sub_prompt']`
- After handoff: `['new_agent_prompt']`
This allows tools and hooks to understand their execution context depth.
### 2.2 Live execution history
`execution.messageHistory` **MUST** represent live chronological persisted execution history.
- A successful [`injectMessage()`](/0.2.0/specification/threads/messages#3-injecting-messages) **MUST** make that record observable on `execution.messageHistory` to later tools and hooks in the same execution.
- Silent messages **MUST** remain on `execution.messageHistory`.
- Synthetic or transformed messages produced by `filter_messages` or `prefilter_llm_history` **MUST** remain confined to the request context. They **MUST NOT** replace `execution.messageHistory`.
The provider request is assembled from a separate snapshot. See [Runtime §4](/0.2.0/infrastructure/runtime#4-context-assembly).
### 2.3 Handler turns
During a [handler](/0.2.0/specification/handlers)-backed side's turn, `execution` is present and `currentSide` reflects that side, but no LLM request/response cycles occur: `stepCount` and the per-side step counts advance only with model steps, so a handler turn contributes zero steps. When the agent sets `maxSessionTurns`, the handler turn still counts toward the session exchange cap — exchange counting is uniform across backings.
## 3. Controlling Execution
```typescript
// Force next turn to a specific side
state.execution.forceTurn('b');
// Stop execution after current operation
state.execution.stop();
// Use abort signal for cancellation
fetch(url, { signal: state.execution.abortSignal });
```
`state.execution.stop()` stops the current execution loop. It does not by itself satisfy a subagent/session terminal boundary. To terminally end the active agent session, use [`state.stopSession()`](/0.2.0/specification/threads#9-subagent-hierarchy-communication-and-termination).
## 4. Run Status
`ThreadState.execution` describes a run from inside it. The **run status**
describes the thread from outside: whether an execution is in flight, and how
the last one ended. It is available everywhere `ThreadState` is, and to
clients without polling.
```typescript
type ThreadRunState = 'idle' | 'running' | 'failed';
interface ThreadStatus {
state: ThreadRunState;
since: number; // microseconds since epoch, like created_at
reason?: string | null; // raw stop reason code of the last transition out of running
}
const status = await state.status();
```
### 4.1 States
| State | Meaning |
|-------|---------|
| `idle` | No execution is running and the last run did not fail — or the thread has never run (`since` is `0`, `reason` is `null`). |
| `running` | An execution is in flight. `reason` is `null`. |
| `failed` | The last run ended in an error. |
The run status describes **execution, not turn ownership**. A run that ends by
handing the turn to a human-backed side settles as `idle`; its `reason` (for
example `awaiting_human`, `stop_on_response`, or `stop_tool`) carries the
detail. The subagent registry keeps its own `awaiting_human` status for
children (see [Subagents](/0.2.0/specification/subagents)).
### 4.2 Reasons
`reason` is the run's stop reason code. Runtimes **SHOULD** use these codes
where they apply and **MAY** add others; clients **MUST** treat unknown codes
as opaque.
| Settles as | Codes |
|------------|-------|
| `idle` | `stop_on_response`, `stop_tool`, `awaiting_human`, `forced_human_turn`, `hook_blocked`, `aborted`, `aborted_by_user`, `session_stop`, `state_stop_session`, `max_total_steps`, `max_side_steps`, `max_session_turns`, `handler_idle` |
| `failed` | `step_error`, `repeated_tool_error`, `session_fail`, `fatal_error`, `execution_lost` |
### 4.3 Requirements
- Runtimes **MUST** set `running` when any execution of the thread starts and **MUST** settle it (`idle` or `failed`) when that execution ends, including when it throws.
- Runtimes **MUST** persist the status with the thread so it survives restarts.
- Runtimes **MUST NOT** leave a thread `running` once its executor is gone (eviction, deploy, crash). A lost execution settles to `failed` with reason `execution_lost`; a later recovery run sets `running` again.
- `since` **MUST** change only when `state` or `reason` changes.
- `status()` is unrelated to `setStatus(label)`, which writes a label into this thread's entry in its parent's subagent registry.
### 4.4 Client delivery
Run status is push-only. Runtimes that expose the
[thread stream](/0.2.0/specification/threads/client-api#16-thread-stream)
**MUST** send a status frame immediately after accepting each stream
connection (a snapshot) and again on every change:
```json
{ "type": "thread_status", "status": { "state": "running", "since": 1727870000000000, "reason": null } }
```
A reconnecting client resynchronizes from the snapshot; clients **SHOULD NOT**
poll for run status. The [thread read route](/0.2.0/specification/threads/client-api#8-reading-a-thread)
returns the same `status` object.
## 5. TypeScript Reference
```typescript
interface ExecutionState {
readonly flowId: string;
readonly currentSide: 'a' | 'b';
readonly stepCount: number;
readonly sideAStepCount: number;
readonly sideBStepCount: number;
readonly stopped: boolean;
readonly stoppedBy?: 'a' | 'b';
readonly messageHistory: Message[]; // live persisted execution history
readonly abortSignal: AbortSignal;
readonly promptPath: string[];
forceTurn(side: 'a' | 'b'): void;
stop(): void;
}
```
---
Source: https://standardagentspec.org/0.2.0/specification/threads/decisions
# Decisions
A decision evaluates named, typed questions against caller-supplied context.
`ThreadState.decide()` returns the answers without advancing the conversation.
For the rest of the `ThreadState` surface, see [Threads](/0.2.0/specification/threads).
## 1. Thread Interface
```typescript
interface DecideOptions
extends DecisionRequest {
provider: DecisionProviderFactory;
}
interface ThreadState {
decide(
options: DecideOptions
): Promise>;
}
```
The `provider` property identifies the factory used for the invocation. A
decision does not require a conversational [model definition](/0.2.0/specification/models).
`decide()` **MUST** be available both during active execution and when
`state.execution` is `null`.
The `decide(state, options)` helper exported by `@standardagents/spec` is
equivalent to `state.decide(options)`.
## 2. Request Types
```typescript
type DecisionJson =
| string
| number
| boolean
| null
| DecisionJson[]
| { [key: string]: DecisionJson };
type DecisionContext =
| string
| DecisionJson[]
| { [key: string]: DecisionJson };
interface DecisionRequest {
model: string;
context: DecisionContext;
questions: Q;
signal?: AbortSignal;
}
```
| Property | Semantics |
|----------|-----------|
| `model` | Provider model identifier for this invocation. |
| `context` | Explicit context shared by the questions. Structured values **MUST** retain their JSON structure. |
| `questions` | Map of question identifiers to question definitions. Each identifier associates a question with its answer. |
| `signal` | Optional cancellation signal for the request. |
Question definitions are invocation inputs. They are not provider connection
configuration.
## 3. Question Types
```typescript
type DecisionQuestion =
| {
type: 'choice';
instructions: DecisionContext;
options: Record;
}
| {
type: 'score';
instructions: DecisionContext;
levels: DecisionContext[];
}
| {
type: 'boolean';
instructions: DecisionContext;
criteria?: { true?: DecisionContext; false?: DecisionContext };
};
type DecisionQuestions = Record;
```
`instructions` defines the evaluation to perform. Structured instructions,
option descriptions, levels, and criteria **MUST** retain their JSON structure.
| Type | Semantics |
|------|-----------|
| `choice` | Select an outcome from `options`. Each key identifies an outcome; its value describes that outcome. A `null` value supplies no additional description. |
| `score` | Evaluate against the ordered `levels` rubric. Level indices start at zero; array order defines the scale. |
| `boolean` | Estimate the probability that the condition in `instructions` is true. Optional `criteria.true` and `criteria.false` describe the two outcomes. |
Providers **MUST** preserve these semantics when translating requests. A
provider **MUST** reject inputs it cannot represent rather than silently omit
or reinterpret them. Question-count and context-size limits are
provider-defined.
## 4. Result Types
```typescript
interface DecisionChoiceAnswer {
type: 'choice';
choice: string;
probabilities: Record;
confidence?: number;
}
interface DecisionScoreAnswer {
type: 'score';
score: number;
probabilities: Record;
legend: Record;
confidence?: number;
}
interface DecisionBooleanAnswer {
type: 'boolean';
probability: number;
}
type DecisionAnswer =
| DecisionChoiceAnswer
| DecisionScoreAnswer
| DecisionBooleanAnswer;
type DecisionAnswers = {
[K in keyof Q]: Q[K] extends { type: 'choice' } ? DecisionChoiceAnswer
: Q[K] extends { type: 'score' } ? DecisionScoreAnswer
: Q[K] extends { type: 'boolean' } ? DecisionBooleanAnswer
: DecisionAnswer;
};
interface DecisionResult {
model: string;
answers: DecisionAnswers;
usage: ProviderUsage;
metadata?: Record;
}
```
| Property | Semantics |
|----------|-----------|
| `model` | The model that performed the evaluation, including the resolved version when the request uses an alias. |
| `answers` | Answers keyed by request question identifier, with an answer type corresponding to each question type. |
| `usage` | Standard `ProviderUsage`: token counts and optional cost and pricing fields. |
| `metadata` | Optional provider-specific result information. |
### 4.1 Answer Semantics
- `choice` identifies the selected option. Its `probabilities` map associates option identifiers with their probabilities.
- `score` is the probability-weighted value of the zero-based level indices. It **MAY** be fractional. Its `probabilities` map associates level indices with probabilities, and `legend` associates those indices with rubric descriptions.
- `probability` on a boolean answer is P(true).
- Probabilities and `confidence` values are numbers in **[0, 1]**. Confidence is provider-reported and is distinct from an individual outcome probability.
Providers **MUST** preserve complete probability distributions, score legends,
and available confidence values. Provider rounding information **MAY** be
included in `metadata`. Rounded probabilities **MUST NOT** be silently
renormalized.
Providers and runtimes **MUST NOT** coerce a boolean probability to a boolean
or apply an application threshold. Thresholds and subsequent actions are
caller-defined.
## 5. Provider Interface
```typescript
interface DecisionProviderInterface {
readonly name: string;
readonly specificationVersion: '1';
readonly kind: 'decision';
decide(
request: DecisionRequest
): Promise>;
getModels?(filter?: string): Promise;
getIcon?(modelId?: string): string | undefined;
}
interface DecisionProviderFactory {
(config: ProviderFactoryConfig): DecisionProviderInterface;
configSlots?: ProviderConfigSlots;
}
```
A decision provider **MUST** implement `decide()` and declare
`kind: 'decision'`. Conversational `generate()` and `stream()` methods are
not required by this interface.
Factories receive standard `ProviderFactoryConfig`. Transport overrides and
credential isolation follow the [Provider specification](/0.2.0/specification/providers).
The runtime resolves thread-scoped credentials and provider connection
configuration. User- or thread-scoped destination overrides **MUST NOT**
redirect inherited credentials.
## 6. Conversation Semantics
Invoking `decide()` **MUST NOT** implicitly:
- read conversation messages to assemble context;
- add, modify, or remove conversation messages;
- execute tools;
- start a conversational turn.
Adding an answer to conversation history requires a separate call to a
[message API](/0.2.0/specification/threads/messages).
---
Source: https://standardagentspec.org/0.2.0/specification/threads/endpoints
# Thread Endpoints
Thread endpoints expose HTTP APIs for thread-specific operations. They automatically look up threads by ID and provide a `ThreadState` instance to the handler.
For the rest of the `ThreadState` surface, see [Threads](/0.2.0/specification/threads).
## 1. Defining Thread Endpoints
```typescript
import { defineThreadEndpoint } from '@standardagents/spec';
export default defineThreadEndpoint(async (req, state, params) => {
const { messages, total } = await state.getMessages({ limit: 10 });
return Response.json({
threadId: state.threadId,
messageCount: total,
params,
});
});
```
## 2. File-Based Routing
Thread endpoints are file-based. Runtimes mount endpoint files beneath the requested thread ID:
```text
{runtime_prefix}/{threadId}/{endpoint_path}
```
The runtime chooses the prefix. The endpoint path is derived from the endpoint file path using these rules:
| File path | Method | Endpoint path |
|-----------|--------|---------------|
| `foo.ts` | GET | `/foo` |
| `bar.post.ts` | POST | `/bar` |
| `index.ts` | GET | `/` |
| `foobar/index.ts` | GET | `/foobar` |
| `foobar/other.ts` | GET | `/foobar/other` |
| `foobar/[id].ts` | GET | `/foobar/{id}` |
| `foobar/[*].ts` | GET | `/foobar/{*}` |
Files without a method suffix are GET endpoints. A method suffix is the final filename segment before `.ts`; runtimes MUST support at least `.get.ts`, `.post.ts`, `.put.ts`, `.patch.ts`, and `.delete.ts`. Method suffix matching is case-insensitive.
`index.ts` maps to the containing directory path. Static routes take precedence over dynamic routes. Dynamic routes take precedence over catch-all routes.
A dynamic segment is written `[name]` and captures exactly one path segment into `params.name`. A catch-all segment is written `[*]` and captures zero or more remaining path segments into `params['*']`. The catch-all value includes `/` separators when the match spans multiple segments.
Packed thread endpoints use the same route namespace as local thread endpoints. They are still addressed beneath the runtime's thread ID prefix, not beneath a package-specific URL prefix:
```text
{runtime_prefix}/{threadId}/{endpoint_path}
```
Requests beneath the thread endpoint prefix that do not match any local or packed thread endpoint route MUST return HTTP 404.
## 3. Handler Signature
Thread endpoint handlers receive:
| Parameter | Type | Description |
|-----------|------|-------------|
| `req` | `Request` | The incoming HTTP request |
| `state` | `ThreadState` | Thread state for the requested thread |
| `params` | `Record` | Route parameters captured from dynamic or catch-all endpoint path segments |
| `auth` | `ThreadEndpointAuth` | The request's authentication context (see [Access and Authentication](#4-access-and-authentication)) |
The supplied `ThreadState` includes the standard thread surface, including `runCode`. Handlers that do not consume trailing parameters may omit them.
The handler **MUST** return a `Response` object.
## 4. Access and Authentication
Every endpoint has an access level, declared at definition time:
```typescript
import { defineThreadEndpoint } from '@standardagents/spec';
export default defineThreadEndpoint(
async (req, state, params, auth) => {
return Response.json({
threadId: state.threadId,
authorized: auth.threadAccess,
});
},
{ access: 'public' }
);
```
| Access level | Requirements |
|--------------|-------------|
| `authenticated` (default) | The runtime **MUST** authenticate the request and enforce its thread access policy before invoking the handler. Requests that fail authentication or authorization **MUST** be rejected without invoking the handler. |
| `public` | The runtime **MUST** invoke the handler regardless of the request's authentication state. The runtime **MUST** still attempt caller resolution: a request presenting credentials the runtime can verify is attributed to that caller; any other request is treated as anonymous rather than rejected. |
When no access level is declared, the access level is `authenticated`. The declaration is attached to the handler itself, so packed thread endpoints carry their access level with them and are subject to the same requirements as local thread endpoints.
The fourth handler argument is the authentication context:
| Property | Type | Requirements |
|----------|------|-------------|
| `caller` | `ThreadUser \| null` | **MUST** be the authenticated identity when the request presented credentials the runtime verified, and `null` otherwise. For an endpoint whose access level is `authenticated`, `caller` is always non-null. |
| `threadAccess` | `boolean` | **MUST** be `true` if and only if the runtime's thread access policy grants the resolved caller access to the requested thread. **MUST** be `false` when `caller` is `null`. For an endpoint whose access level is `authenticated`, `threadAccess` is always `true`. |
`caller` uses the same `ThreadUser` identity shape as `state.user()` — identity fields only, never credentials. Note that `caller` identifies who is making the request, while `state.userId` identifies who owns the thread; the two frequently differ.
The mechanism by which a runtime authenticates requests (sessions, API keys, or otherwise) is implementation-defined. This specification defines only the identity contract observable by endpoint code.
## 5. Endpoint Context
When accessing a thread via an endpoint, `state.execution` is always `null` because the thread is not actively executing:
```typescript
export default defineThreadEndpoint(async (req, state) => {
// Execution is always null in endpoints
if (state.execution === null) {
// Thread is at rest, not executing
}
return Response.json({ threadId: state.threadId });
});
```
## 6. Error Handling
The runtime answers the conditions below itself, before any package code runs.
| Condition | Status |
|-----------|--------|
| The addressed thread does not exist | `404` |
| The request carries no thread ID | `400` |
| No thread endpoint route matches the path under the thread endpoint prefix | `404` |
1. For each condition, the runtime **MUST** return the status in the table.
2. Each of these responses **MUST** carry the error body of the [Thread Client API](/0.2.0/specification/threads/client-api#32-bodies-and-errors): `{ "error": { "code": string, "message": string } }`. The body **MAY** carry other members. A client decides the outcome from the status.
3. The response a thread endpoint's own handler returns, including an error response, is the package's to define.
## 7. Examples
**Get Thread Messages:**
```typescript
import { defineThreadEndpoint } from '@standardagents/spec';
export default defineThreadEndpoint(async (req, state) => {
const url = new URL(req.url);
const limit = parseInt(url.searchParams.get('limit') || '50');
const offset = parseInt(url.searchParams.get('offset') || '0');
const result = await state.getMessages({ limit, offset, order: 'desc' });
return Response.json(result);
});
```
**Export Thread Data:**
```typescript
import { defineThreadEndpoint } from '@standardagents/spec';
export default defineThreadEndpoint(async (req, state) => {
const { messages } = await state.getMessages({ order: 'asc' });
return Response.json({
exportedAt: new Date().toISOString(),
thread: {
id: state.threadId,
agent: state.agentId,
user: state.userId,
createdAt: state.createdAt,
},
messages,
});
});
```
**List Thread Files:**
```typescript
import { defineThreadEndpoint } from '@standardagents/spec';
export default defineThreadEndpoint(async (req, state) => {
const { entries } = await state.readdirFile('/');
return Response.json({ files: entries });
});
```
---
Source: https://standardagentspec.org/0.2.0/specification/threads/client-api
# Thread Client API
The **thread client API** is the set of HTTP routes and the WebSocket stream through which a client lists agents, creates, reads, renames, deletes, messages, stops, and observes threads, and reads the files that messages reference. The runtime defines it. Packages do not.
[Thread endpoints](/0.2.0/specification/threads/endpoints) are a separate surface: routes that a package defines beneath a thread. The in-process forms of the operations in this section are specified by [`ThreadState`](/0.2.0/specification/threads) and [`UserState`](/0.2.0/specification/users).
## 1. Scope
1. A runtime **SHOULD** expose the thread client API.
2. A runtime that exposes it **MUST** implement every route in §2 as specified in this section.
3. A runtime **MAY** define routes, query parameters, request fields, response fields, and stream frame types beyond those specified here.
4. A client **MUST** ignore response fields and stream frame types it does not recognize.
5. Sign-in, which is how a caller obtains a credential, is implementation-defined.
6. Thread retention is runtime-defined.
## 2. Routes
```text
POST {runtime_prefix}/auth/websocket-ticket
GET {runtime_prefix}/agents
POST {runtime_prefix}/threads
GET {runtime_prefix}/threads
GET {runtime_prefix}/threads/{threadId}
PATCH {runtime_prefix}/threads/{threadId}
DELETE {runtime_prefix}/threads/{threadId}
GET {runtime_prefix}/threads/{threadId}/messages
POST {runtime_prefix}/threads/{threadId}/messages
DELETE {runtime_prefix}/threads/{threadId}/messages/{messageId}
GET {runtime_prefix}/threads/{threadId}/fs/{path}
POST {runtime_prefix}/threads/{threadId}/stop
GET {runtime_prefix}/threads/{threadId}/stream (WebSocket upgrade)
```
1. The runtime chooses `{runtime_prefix}`.
2. [Thread endpoints](/0.2.0/specification/threads/endpoints) are mounted beneath the same `{runtime_prefix}/threads/{threadId}/` prefix. The endpoint paths `messages`, `fs`, `stop`, and `stream`, and every path beneath `messages/` and `fs/`, are reserved for this API. A package **SHOULD NOT** define thread endpoints at those paths.
## 3. Common Requirements
### 3.1 Authentication and access
1. Every route **MUST** require an authenticated caller.
2. The runtime **MUST** accept a credential presented in the request header `Authorization: Bearer {credential}` on every HTTP route.
3. The runtime **MUST** accept a stream ticket (§4) on the thread stream upgrade (§16).
4. The runtime **MUST NOT** accept a long-lived credential in a URL.
5. A runtime **MAY** accept other credential transports, such as a session cookie.
6. A route addressed to a thread **MUST** enforce the runtime's thread access policy for the resolved caller before it reads or changes the thread.
### 3.2 Bodies and errors
1. Request and response bodies **MUST** be JSON, except the file response in §14.
2. Property names are case-sensitive and **MUST** be spelled exactly as given in this section.
3. A failed request **MUST** return a non-2xx status with the body `{ "error": { "code": string, "message": string } }`. The body **MAY** carry other members. A client **MUST** decide the outcome from the status. The `code` and `message` values are informational. A refused stream upgrade (§16) is a failed request: the runtime **MUST** answer it with an HTTP response that carries the status and this body, and **MUST NOT** close the connection without one.
4. For each condition in the table below, the runtime **MUST** return the corresponding status.
5. For an internal failure or temporary unavailability, the runtime **MUST** return a `5xx` status. It **MUST NOT** report such a failure with a status from the table.
6. Termination closes a thread to new work only. Every route other than message sending (§12) **MUST** behave on a terminated thread as it does on an open thread.
| Status | Condition |
|--------|-----------|
| `400` | The request is malformed or fails validation |
| `401` | The caller is not authenticated |
| `403` | The caller is denied access to the thread |
| `404` | The addressed thread, message, or file, or the agent named in a create request, does not exist |
| `423` | A message is sent (§12) to a terminated thread |
### 3.3 Timestamps
| Value | Unit |
|-------|------|
| Thread `created_at`, `last_activity_at`, `last_message_at` | Seconds since the Unix epoch |
| Thread `terminated` | Microseconds since the Unix epoch |
| Message `created_at` | Microseconds since the Unix epoch |
| `ThreadStatus.since` | Microseconds since the Unix epoch |
| `event` frame `timestamp` | Milliseconds since the Unix epoch |
## 4. Stream Tickets
```text
POST {runtime_prefix}/auth/websocket-ticket
```
A **stream ticket** is a short-lived, single-use credential that authorizes one WebSocket upgrade.
```typescript
interface StreamTicketRequest {
pathname: string // path of the WebSocket URL, including {runtime_prefix}
}
interface StreamTicketResponse {
ticket: string
expires_in: number // seconds
}
```
1. A successful request **MUST** return `200` with a `StreamTicketResponse` and the response header `Cache-Control: no-store`.
2. The runtime **MUST** return `400` when `pathname` is absent, is not a normalized path beneath `{runtime_prefix}`, or contains a query or fragment. A path is normalized when it has no `.` or `..` segment, no empty segment, no trailing slash, and no percent-encoded `.`, `/`, or `\` (`%2E`, `%2F`, `%5C`, in either letter case).
3. A client presents the ticket as the query parameter `ticket` on the WebSocket upgrade request.
4. The runtime **MUST** authenticate an upgrade that presents a valid ticket as the caller who requested the ticket.
5. A ticket **MUST** be valid only for an upgrade whose path equals `pathname`. The comparison is of the exact strings.
6. A ticket **MUST** be valid for at most one upgrade.
7. A ticket **MUST** expire no later than `expires_in` seconds after it is issued. `expires_in` **SHOULD NOT** exceed `60`.
8. The runtime **MUST** reject an upgrade that presents an unknown, expired, used, or mismatched ticket with `401`.
9. A ticket authorizes a stream upgrade only. The runtime **MUST NOT** accept it as a bearer credential.
## 5. Listing Agents
```text
GET {runtime_prefix}/agents
```
| Query parameter | Default | Meaning |
|-----------------|---------|---------|
| `primary` | absent | `true` restricts the result to agents whose `primary` is `true` |
```typescript
interface AgentList {
agents: AgentListEntry[]
}
interface AgentListEntry {
id: string // the value a create request passes as agent_id
name: string
title: string
description: string | null
icon: string | null
primary: boolean
side_a_backing: 'human' | 'prompt' | 'handler'
side_b_backing: 'human' | 'prompt' | 'handler'
}
```
1. A successful request **MUST** return `200` with an `AgentList`.
2. The runtime **MUST** accept every listed `id` as the `agent_id` of a create request (§6) from the same caller.
3. `title` **MUST** be the agent's `title`, or its `name` when the agent defines no title.
4. `primary` **MUST** be `false` when the [agent definition](/0.2.0/specification/agents#22-optional) sets `primary: false`, and `true` otherwise.
5. `side_a_backing` and `side_b_backing` **MUST** report the [backing](/0.2.0/specification/agents) of each side.
6. The caller's **creatable set** is every agent for which the caller may create a thread (§6). Of a [packed](/0.2.0/distribution/packaging) package's agents, only its entry agents are in it. A non-primary agent is in it.
7. A request without `primary` **MUST** return the whole creatable set, and no other agent.
8. A request that sets `primary=true` **MUST** return exactly the agents of the creatable set whose `primary` is `true`.
## 6. Creating a Thread
```text
POST {runtime_prefix}/threads
```
```typescript
interface CreateThreadRequest {
agent_id: string // an AgentListEntry id
tags?: string[]
env?: Record // thread-level environment values
}
interface CreateThreadResponse {
threadId: string
agent_id: string
}
```
1. The runtime **MUST** set the owner of the new thread from the authenticated caller. The request **MUST NOT** be able to name a different owner.
2. Creating a thread **MUST NOT** start an execution.
3. A successful request **MUST** return `200` with a `CreateThreadResponse`.
4. The runtime **MUST** return `400` when `agent_id` is absent or is not a string, when `tags` is present and is not an array of strings, or when `env` is present and is not a JSON object whose values are all strings.
5. The runtime **MUST** return `404` when `agent_id` is a string that is not the `id` of an agent in the caller's creatable set (§5). A filter on an agent list request does not change that set.
## 7. Listing Threads
```text
GET {runtime_prefix}/threads
```
| Query parameter | Default | Meaning |
|-----------------|---------|---------|
| `limit` | `50` | Maximum number of threads returned |
| `offset` | `0` | Number of threads skipped |
| `agent_id` | — | Restricts the result to threads of the named agent |
```typescript
interface ThreadList {
threads: ThreadListEntry[]
total: number
hasMore: boolean
}
interface ThreadListEntry {
id: string
agent_id: string
user_id: string | null // owner; null when the thread has none
tags: string[]
parent: string | null // parent thread id; null for a root thread
terminated: number | null // termination time; null while the thread is open
created_at: number
last_activity_at: number
last_message_preview: string | null
last_message_at: number | null
status: ThreadRunState // 'idle' | 'running' | 'failed'
status_reason: string | null // failure reason while status is 'failed', else null
agent: {
name: string
title: string
description?: string
icon?: string
side_a_backing?: 'human' | 'prompt' | 'handler'
side_b_backing?: 'human' | 'prompt' | 'handler'
}
}
```
1. A successful request **MUST** return `200` with a `ThreadList`.
2. A caller without administrative rights **MUST** receive only threads that the caller owns.
3. The runtime **MUST** return threads in descending `last_activity_at` order unless the request selects another order through a runtime-defined parameter. The order of threads with equal `last_activity_at` is runtime-defined.
4. `total` **MUST** be the number of threads matching the request before `limit` and `offset` are applied.
5. `hasMore` **MUST** be `true` if and only if matching threads exist beyond the returned page.
6. `last_activity_at` **MUST** equal `created_at` for a thread with no later activity.
7. `last_message_preview` is a plain-text excerpt of a recent message in the thread, or `null`. Its source message and length are runtime-defined.
8. `agent.title` **MUST** be the agent's `name` when the agent defines no title or its definition is no longer available.
9. `ThreadListEntry.status` is the [run state](/0.2.0/specification/threads/execution-state#4-run-status) only. It is not a `ThreadStatus` object.
## 8. Reading a Thread
```text
GET {runtime_prefix}/threads/{threadId}
```
```typescript
interface ThreadRead {
thread: {
id: string
agent_id: string
user_id: string | null
tags: string[]
parent: string | null
terminated: number | null
created_at: number
}
agent: {
id: string
title: string
description?: string
icon?: string
side_a_backing: 'human' | 'prompt' | 'handler'
side_b_backing: 'human' | 'prompt' | 'handler'
} | null
status: ThreadStatus
}
```
1. A successful request **MUST** return `200` with a `ThreadRead`.
2. `status` **MUST** equal the [`ThreadStatus`](/0.2.0/specification/threads/execution-state#4-run-status) that `state.status()` resolves for the thread.
3. `agent` **MUST** be `null` when the thread's agent definition is no longer available.
## 9. Updating a Thread
```text
PATCH {runtime_prefix}/threads/{threadId}
```
```typescript
interface UpdateThreadRequest {
tags?: string[]
}
interface UpdateThreadResponse {
id: string
agent_id: string
user_id: string | null
tags: string[]
created_at: number
}
```
1. When `tags` is present, the runtime **MUST** replace the thread's tags with the given array.
2. A successful request **MUST** return `200` with an `UpdateThreadResponse` that reflects the update.
3. The runtime **MUST** return `400` when `tags` is not an array of strings, or when the request names no field the runtime updates.
## 10. Deleting a Thread
```text
DELETE {runtime_prefix}/threads/{threadId}
```
```typescript
interface DeleteThreadResponse {
success: true
threadId: string
deletedThreadIds: string[]
deletedCount: number
}
```
The **deletion set** of a request is the addressed thread and every descendant thread.
1. Before it deletes anything, the runtime **MUST** make every thread in the deletion set unavailable to new work. From that point each such thread **MUST** reject new messages, **MUST NOT** start an execution, and **MUST NOT** create a child thread.
2. A child thread created beneath a thread in the deletion set before requirement 1 takes effect **MUST** be part of the deletion set.
3. The runtime **MUST** abort every execution in flight in the deletion set, and **MUST** discard every queued message and scheduled [effect](/0.2.0/specification/effects) of those threads.
4. The runtime **MUST** close every [thread stream](#16-thread-stream) connection to a thread in the deletion set with WebSocket close code `1000`.
5. The runtime **MUST** delete the messages, files, and stored values of every thread in the deletion set.
6. The runtime **MUST** return `200` with a `DeleteThreadResponse` only once requirements 1 to 5 hold. `deletedThreadIds` **MUST** list every thread in the deletion set, including `threadId`.
7. After a successful request, no execution of a deleted thread may persist state or start work, and every route addressed to a deleted thread **MUST** return `404`. That includes a request to its stream route that is not a WebSocket upgrade.
8. When deletion fails part-way, the runtime **MUST** return a `5xx` status (§3.2). Every thread in the deletion set **MUST** remain unavailable to new work, and the addressed thread **MUST** remain addressable so that the request can be repeated.
9. A repeated request **MUST** complete the deletion.
## 11. Reading Messages
```text
GET {runtime_prefix}/threads/{threadId}/messages
```
| Query parameter | Default | Meaning |
|-----------------|---------|---------|
| `limit` | `100` | Maximum number of messages returned |
| `offset` | `0` | Number of messages skipped from the start of the selection |
| `order` | `desc` | `desc` selects from the newest message backwards. `asc` selects from the oldest message forwards |
| `includeSilent` | `false` | `true` includes [silent](/0.2.0/specification/threads/messages#32-presentation-silent) messages. Any other value is `false` |
| `depth` | `0` | Maximum message depth included |
```typescript
interface MessagesPage {
messages: Message[]
total: number
hasMore: boolean
}
```
1. A successful request **MUST** return `200` with a `MessagesPage`.
2. Each entry of `messages` **MUST** be a [message record](/0.2.0/specification/threads/messages#1-message-structure) in its decoded form: `attachments` is an array or `null`, and `silent` is a boolean.
3. Under `order=desc`, the runtime **MUST** return the selected messages in ascending `created_at` order, so the newest selected message is last.
4. The runtime **MUST** exclude silent messages unless `includeSilent` is `true`.
5. The runtime **MUST** exclude messages whose `depth` exceeds the `depth` parameter.
6. Under `order=asc`, the runtime **MUST** return the selected messages in ascending `created_at` order.
7. `total` **MUST** be the number of messages that satisfy `includeSilent` and `depth`, before `limit` and `offset` are applied.
8. `hasMore` **MUST** be `true` if and only if matching messages exist beyond the returned page: that is, when `offset` plus the number of returned messages is less than `total`.
9. The order of messages with equal `created_at` is runtime-defined. It **MUST** be the same on every read.
## 12. Sending a Message
```text
POST {runtime_prefix}/threads/{threadId}/messages
```
```typescript
interface SendMessageRequest {
role: 'user' | 'assistant' | 'system'
content?: string
attachments?: Attachment[]
}
interface Attachment {
name: string // file name
mimeType: string
data: string // base64-encoded bytes
width?: number // images
height?: number // images
thumbnail?: string // base64-encoded bytes
}
interface SendMessageResponse {
status: 'queued'
messageId: string
}
```
1. The runtime **MUST** return `400` when `role` is absent or is not one of the three values above.
2. The runtime **MUST** return `400` when `content` is empty or absent and `attachments` is empty or absent. Content that holds only white space is empty.
3. The runtime **MUST** return `423` when the thread is terminated.
4. The runtime **MUST** store each attachment in the thread's [file system](/0.2.0/specification/threads/filesystem) and reference it from the message's `attachments` as an [`AttachmentRef`](/0.2.0/specification/threads/messages#12-attachment-references). When an attachment's `data` is not valid base64, or the attachment cannot be stored, the runtime **MUST NOT** accept the message: it returns `400` for invalid `data` and a `5xx` status for a storage failure.
5. The runtime **MUST** accept the message durably and return `202` with a `SendMessageResponse` without waiting for the resulting execution.
6. The runtime **MUST NOT** return `202` for a message it did not accept durably. When acceptance fails, the runtime **MUST** return a `5xx` status (§3.2), and the message **MUST NOT** be delivered.
7. The runtime **MUST** deliver the accepted message with the semantics of [`queueMessage`](/0.2.0/specification/threads/messages#4-queueing-messages).
8. `messageId` **MUST** be the `id` of the message record once it is persisted.
9. The runtime **MUST** publish the accepted message to the thread stream (§16) as a `message_data` frame carrying that `messageId`. Until the message is persisted, the frame's record has `status: 'pending'`.
## 13. Deleting a Message
```text
DELETE {runtime_prefix}/threads/{threadId}/messages/{messageId}
```
1. The runtime **MUST** delete the message with the semantics of [`deleteMessage`](/0.2.0/specification/threads/messages#6-deleting-messages).
2. A successful request **MUST** return `200` with the body `{ "success": true }`.
3. The runtime **MUST** return `404` when the thread holds no message with that id.
4. This section defines no stream frame for a deletion.
## 14. Reading a File
```text
GET {runtime_prefix}/threads/{threadId}/fs/{path}
```
`{path}` is the file's path in the thread's [file system](/0.2.0/specification/threads/filesystem) without its leading `/`, with each path segment percent-encoded. The `path` of an [`AttachmentRef`](/0.2.0/specification/threads/messages#12-attachment-references) is such a path.
1. For a stored file, a successful request **MUST** return `200` with the file's bytes as the response body.
2. The response **MUST** carry the file's MIME type in `Content-Type` and the header `X-Content-Type-Options: nosniff`.
3. The runtime **MUST** send `Content-Disposition: attachment` for a file whose MIME type is `text/html`, `image/svg+xml`, or `application/xhtml+xml`.
4. The runtime **MUST** return `404` when no file exists at the path.
5. The response for a path that names a directory is implementation-defined.
## 15. Stopping Execution
```text
POST {runtime_prefix}/threads/{threadId}/stop
```
1. The request has no body.
2. The runtime **MUST** abort the execution in flight on the thread, if one exists. That run **MUST** settle as `idle` with reason `aborted_by_user`.
3. The route **MUST** be idempotent. A request addressed to a thread with no execution in flight **MUST** succeed and **MUST NOT** change the thread: it stores no message and sends no stream frame.
4. A successful request **MUST** return `200` with the body `{ "status": "stopped" }`.
5. A request that aborts an execution **MAY** record the stop in the thread as one message. The result of a tool call that the stop aborted is not counted as that message.
## 16. Thread Stream
```text
GET {runtime_prefix}/threads/{threadId}/stream (WebSocket upgrade)
```
| Query parameter | Default | Meaning |
|-----------------|---------|---------|
| `ticket` | absent | A stream ticket (§4) |
| `depth` | `0` | Maximum message depth delivered on this connection |
| `includeSilent` | `false` | `true` delivers [silent](/0.2.0/specification/threads/messages#32-presentation-silent) messages on this connection. Any other value is `false` |
| `reasoning` | absent | Any value other than the empty string, `0`, or `false` opts this connection in to `reasoning_chunk` frames |
1. The runtime **MUST** reject a request that is not a WebSocket upgrade with `400`.
2. The runtime **MUST** accept multiple concurrent connections to one thread.
### 16.1 Server frames
```typescript
type ThreadStreamFrame =
| { type: 'thread_status'; status: ThreadStatus }
| { type: 'message_data'; message_id: string; depth: number; data: Message }
| { type: 'message_chunk'; message_id: string; depth: number; chunk: string }
| { type: 'reasoning_chunk'; message_id: string; depth: number; chunk: string }
| { type: 'event'; eventType: string; data: unknown; timestamp: number }
```
1. Every frame the runtime sends **MUST** be a text frame containing a JSON object with a string `type`. The heartbeat reply (§16.3) is the only exception.
2. `thread_status` carries the thread's [run status](/0.2.0/specification/threads/execution-state#4-run-status).
3. `message_data` carries a complete [message record](/0.2.0/specification/threads/messages#1-message-structure) in `data`: every member that a message read (§11) returns for that message **MUST** be present with the same value. While the message is still being generated, its `status` is `'pending'` and its `content` may be incomplete. `message_id` **MUST** equal `data.id`.
4. The record in a `message_data` frame **MUST** have the same form as the record returned by message reads (§11): `attachments` is an array or `null`, and `silent` is a boolean. A runtime **MUST NOT** send a stored encoding of a field in place of that form.
5. `message_chunk` carries a fragment of the visible content of the assistant message identified by `message_id`.
6. `reasoning_chunk` carries a transient fragment of model reasoning that accompanies the assistant message identified by `message_id`.
7. `event` carries one [`state.emit(eventType, data)`](/0.2.0/specification/threads#5-events) call. When the call passes no `data`, the frame's `data` is `null`.
8. The `depth` of a `message_data`, `message_chunk`, or `reasoning_chunk` frame **MUST** equal the `depth` of the message identified by `message_id`.
### 16.2 Delivery
1. The first frame on every accepted connection **MUST** be a `thread_status` frame carrying the current run status.
2. The runtime **MUST** send a `thread_status` frame on every change of run status.
3. The runtime **MUST** send a `message_data` frame when a message is created and when a message is updated.
4. The runtime **MUST** send `message_chunk` frames for one `message_id` in generation order.
5. The runtime **MUST NOT** send a `reasoning_chunk` frame on a connection that did not opt in.
6. The runtime **MUST NOT** send a `message_data`, `message_chunk`, or `reasoning_chunk` frame whose `depth` exceeds the connection's `depth`.
7. The runtime **MUST NOT** send a `message_data` frame for a silent message on a connection that did not set `includeSilent`.
8. `thread_status` and `event` frames **MUST NOT** be filtered by `depth`.
9. Delivery is at-most-once. The stream carries no history and no acknowledgements.
10. A client **MUST** treat `message_data` as a replacement for any record it holds with the same `message_id`.
11. The content of a `message_data` frame is authoritative. It supersedes the `message_chunk` fragments received for the same `message_id`.
12. The `reasoning` opt-in governs `reasoning_chunk` frames only. A `reasoning_chunk` fragment is transient: it is not stored, and it cannot be read back.
13. The runtime **MUST** persist the reasoning a model returns with an assistant message in that message's `reasoning_content` and `reasoning_details` ([Messages §1.3](/0.2.0/specification/threads/messages#13-reasoning)).
14. The runtime **MUST** carry `reasoning_content` and `reasoning_details` identically in message reads (§11) and in `message_data` frames, on every connection regardless of the `reasoning` opt-in.
15. When the provider delivers an assistant message's content incrementally, that is in more than one delta, the runtime **MUST** send that content as `message_chunk` frames as it arrives, to every connection whose `depth` is at least the message's `depth`.
16. When the provider delivers reasoning incrementally, the runtime **MUST** send it as `reasoning_chunk` frames to every connection that opted in and whose `depth` is at least the message's `depth`.
### 16.3 Heartbeat
1. A client **MAY** send the text frame `stream_ping`.
2. The runtime **MUST** answer `stream_ping` with the text frame `stream_pong`, on the connection that sent it and on no other. Neither frame is JSON.
3. A heartbeat **MUST NOT** start or alter an execution.
4. All other client-to-server frames are implementation-defined.
## 17. Conformance
Requirements 2 to 12 apply to a runtime that exposes the thread client API.
| # | Requirement | Level |
|---|-------------|-------|
| 1 | Expose the thread client API (§1) | SHOULD |
| 2 | Every route in §2, mounted beneath `{runtime_prefix}` | MUST |
| 3 | Bearer credentials, stream tickets, and thread access enforcement (§3.1, §4) | MUST |
| 4 | Error statuses, `5xx` for internal failures, and the `{ "error": { "code", "message" } }` body (§3.2) | MUST |
| 5 | Agent listing (§5) | MUST |
| 6 | Thread creation, listing, and reading (§6, §7, §8) | MUST |
| 7 | Thread update and deletion (§9, §10) | MUST |
| 8 | Message reading, filtering, and deletion (§11, §13) | MUST |
| 9 | Durable, asynchronous message sending (§12) | MUST |
| 10 | File reading (§14) | MUST |
| 11 | Idempotent stop (§15) | MUST |
| 12 | Stream frames, delivery, and heartbeat (§16) | MUST |
## Appendix A. Example (Non-normative)
```typescript
const base = 'https://runtime.example/api';
const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
const post = (path: string, body: unknown) =>
fetch(`${base}${path}`, { method: 'POST', headers, body: JSON.stringify(body) }).then((r) => r.json());
const { agents } = await fetch(`${base}/agents`, { headers }).then((r) => r.json());
const { threadId } = await post('/threads', { agent_id: agents[0].id });
const streamUrl = new URL(`${base}/threads/${threadId}/stream`);
const { ticket } = await post('/auth/websocket-ticket', { pathname: streamUrl.pathname });
streamUrl.protocol = 'wss:';
streamUrl.searchParams.set('ticket', ticket);
const drafts = new Map();
const socket = new WebSocket(streamUrl);
socket.onmessage = ({ data }) => {
if (data === 'stream_pong') return;
const frame = JSON.parse(data);
switch (frame.type) {
case 'thread_status':
console.log('run state:', frame.status.state);
break;
case 'message_chunk':
drafts.set(frame.message_id, (drafts.get(frame.message_id) ?? '') + frame.chunk);
break;
case 'message_data':
drafts.delete(frame.message_id);
console.log(frame.data.role, frame.data.content);
break;
}
};
await post(`/threads/${threadId}/messages`, { role: 'user', content: 'Where is my order?' });
```
---
Source: https://standardagentspec.org/0.2.0/specification/users
# Users
> **Status: draft proposal.** Not yet part of the frozen specification surface.
A **user** is a scope owned by a runtime principal. It comprises durable values, packaged HTTP endpoints, an event stream, and credential grants. Threads reference users; the surfaces in this section are addressable independently of any thread.
## 1. Identity
1. A runtime MUST resolve every authenticated request to a stable user id.
2. A runtime with exactly one principal MUST resolve all requests to a single constant user id.
3. A thread MAY have no user. For such threads, `state.user()` MUST resolve `null` and every surface in this section MUST be unavailable.
4. The identity record exposes only the following fields. Credential material MUST NOT appear in it.
```typescript
interface UserIdentity {
id: string
username?: string | null
email?: string | null
display_name?: string | null
avatar_url?: string | null
role?: string | null
roles?: string[]
permissions?: string[] | null
}
```
### Application roles
`roles` is an optional list of opaque, case-sensitive application role strings
supplied by the runtime's trusted identity authority. It is distinct from the
runtime-defined `role` and `permissions` fields. An absent or empty list grants
no application roles. No role string implies a built-in runtime privilege, and
the specification defines no wildcard expansion or role hierarchy.
Applications may adopt names such as `reports:read` or `releases:canary` and
check them before protected operations. A name ending in `:*` has meaning only
when application code explicitly implements that convention. Clients and
user-writable values MUST NOT be accepted as the source of authoritative roles.
A runtime that supplies roles MUST expose them through `UserState.identity()`
and the identity returned by `ThreadState.user()`. Runtimes MUST document their
authorization freshness boundary; an identity may be a snapshot within one
request or execution. Applications should authorize each protected request or
execution instead of persisting a previously granted decision indefinitely.
## 2. UserState
User endpoints (§3) receive a `UserState`:
```typescript
interface UserState {
userId: string
identity(): Promise
getValue(key: string): Promise
setValue(key: string, value: unknown): Promise
listValues(options?: { prefix?: string; limit?: number; offset?: number }):
Promise<{ entries: { key: string; value: unknown; updated_at: number }[]; total: number }>
env(name: string): Promise
instanceEnv?(name: string): Promise
emit(event: string, data?: unknown): void
clients(): Promise