Interface SouledAgentOptions

Options for souledAgent. Identical to AgentOptions, but soul is required.

interface SouledAgentOptions {
    usageLedger?: AgentOSUsageLedgerOptions;
    chainOfThought?: string | boolean;
    fallbackProviders?: FallbackProviderEntry[];
    onFallback?: ((error, fallbackProvider) => void);
    router?: IModelRouter;
    hostPolicy?: HostLLMPolicy;
    budget?: SpendBudget | SpendBudgetOptions;
    policyTier?: "safe" | "standard" | "mature" | "private-adult";
    routerParams?: Partial<ModelRouteParams>;
    responseSchema?: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>;
    onBeforeGeneration?: ((context) => Promise<void | GenerationHookContext>);
    onAfterGeneration?: ((result) => Promise<void | GenerationHookResult>);
    onBeforeToolExecution?: ((info) => Promise<null | ToolCallHookInfo>);
    memoryProvider?: AgentMemoryProvider;
    memoryProviderOptions?: MemoryProviderHookOptions;
    skills?: SkillEntry[];
    systemBlocks?: SystemContentBlock[];
    cache?: false | {
        ttl?: "5m" | "1h";
    };
    history?: false | Partial<SessionHistoryConfig>;
    runtime?: "legacy" | "gmi";
    cognition?: CognitionProfile | CognitionConfig;
    learning?: null | boolean | LearningConfig;
    agencies?: AgencyLaunchOptions;
    voice?: VoiceConfig & {
        session?: {
            factory: VoiceSessionFactory;
            agent: {
                name: string;
                prompt: string;
                language: string;
                reasoning: {
                    modelId: string;
                    modelRevision: string;
                    protocol: {
                        id: "openai-chat-completions";
                        version: 1;
                    };
                    usageUnits: {
                        input_token: "token";
                        output_token: "token";
                        reasoning_token: "token";
                        cached_input_token: "token";
                        reasoningInOutput: boolean;
                    };
                    attemptLimits: {
                        maxAttempts: number;
                        perAttempt: {
                            input_token: number;
                            output_token: number;
                            reasoning_token: number;
                            cached_input_token: number;
                            request: number;
                        };
                    };
                    cancellation: "native_abort" | "process_exit" | "unsupported";
                    provider: "local";
                    manifestDigest: string;
                    fallbacks: ({
                        modelId: ...;
                        modelRevision: ...;
                        protocol: ...;
                        usageUnits: ...;
                        attemptLimits: ...;
                        cancellation: ...;
                        provider: ...;
                        manifestDigest: ...;
                    } | {
                        modelId: ...;
                        modelRevision: ...;
                        protocol: ...;
                        usageUnits: ...;
                        attemptLimits: ...;
                        cancellation: ...;
                        provider: ...;
                        endpointRef: ...;
                        endpointRevision: ...;
                        credentialRef?: ...;
                    })[];
                } | {
                    modelId: string;
                    modelRevision: string;
                    protocol: {
                        id: "openai-chat-completions";
                        version: 1;
                    };
                    usageUnits: {
                        input_token: "token";
                        output_token: "token";
                        reasoning_token: "token";
                        cached_input_token: "token";
                        reasoningInOutput: boolean;
                    };
                    attemptLimits: {
                        maxAttempts: number;
                        perAttempt: {
                            input_token: number;
                            output_token: number;
                            reasoning_token: number;
                            cached_input_token: number;
                            request: number;
                        };
                    };
                    cancellation: "native_abort" | "process_exit" | "unsupported";
                    provider: "registered_endpoint";
                    endpointRef: string;
                    endpointRevision: number;
                    credentialRef?: string;
                    fallbacks: ({
                        modelId: ...;
                        modelRevision: ...;
                        protocol: ...;
                        usageUnits: ...;
                        attemptLimits: ...;
                        cancellation: ...;
                        provider: ...;
                        manifestDigest: ...;
                    } | {
                        modelId: ...;
                        modelRevision: ...;
                        protocol: ...;
                        usageUnits: ...;
                        attemptLimits: ...;
                        cancellation: ...;
                        provider: ...;
                        endpointRef: ...;
                        endpointRevision: ...;
                        credentialRef?: ...;
                    })[];
                };
                voice: {
                    id: string;
                    revision: string;
                };
                stt: {
                    providerId: string;
                    modelId: string;
                    modelRevision: string;
                    mode: "streaming" | "batch";
                    sampleRate: number;
                    codec: "pcm_s16le" | "pcm_f32le" | "opus" | "mp3" | "wav";
                    optionsRef?: string;
                    credentialRef?: string;
                };
                tts: {
                    providerId: string;
                    modelId: string;
                    modelRevision: string;
                    mode: "streaming" | "batch";
                    sampleRate: number;
                    codec: "pcm_s16le" | "pcm_f32le" | "opus" | "mp3" | "wav";
                    optionsRef?: string;
                    credentialRef?: string;
                };
                vad: {
                    providerId: string;
                    modelId: string;
                    modelRevision: string;
                    threshold: number;
                    optionsRef?: string;
                };
                endpoint: {
                    providerId: string;
                    modelId: string;
                    modelRevision: string;
                    optionsRef?: string;
                };
                providerPolicy: {
                    mode: "provider" | "local" | "hosted";
                    providerIds: string[];
                    purposes: ("stt" | "tts" | "vad" | "endpoint" | "reasoning")[];
                    fallback: "none" | "allowlisted";
                };
                limits: {
                    maxDurationSeconds: number;
                    setupTimeoutMs: number;
                    reconnectGraceMs: number;
                    silenceTimeoutMs: number;
                    cleanupTimeoutMs: number;
                    maxTurns: number;
                };
                allowedToolRefs: string[];
                transcriptPolicy: {
                    mode: "none";
                } | {
                    mode: "delivery";
                    deliveryTtlSeconds: number;
                } | {
                    mode: "retained";
                    retentionSeconds: number;
                };
                webhookRef: null | string;
                version: 1;
                agentId: string;
                scopeId: string;
                revision: number;
                state: "active" | "archived";
                createdAt: number;
                updatedAt: number;
            };
        };
    };
    soul: NonNullable<undefined | string | {
        content: string;
    } | {
        path: string;
    }>;
    model?: string;
    provider?: string;
    instructions?: string;
    name?: string;
    apiKey?: string;
    baseUrl?: string;
    personality?: Partial<{
        honesty: number;
        emotionality: number;
        extraversion: number;
        agreeableness: number;
        conscientiousness: number;
        openness: number;
        honestyHumility: number;
        honesty_humility: number;
        opennessToExperience: number;
    }>;
    tools?: AdaptableToolInput;
    maxSteps?: number;
    maxTokens?: number;
    thinking?: false | {
        budgetTokens: number;
    };
    effort?: string;
    customModelParams?: Record<string, unknown>;
    memory?: boolean | MemoryConfig;
    rag?: RagConfig;
    discovery?: DiscoveryConfig;
    guardrails?: string[] | GuardrailsConfig;
    security?: {
        tier: SecurityTier;
    };
    permissions?: PermissionsConfig;
    hitl?: HitlConfig;
    emergent?: EmergentConfig;
    avatar?: AvatarConfig;
    channels?: Record<string, Record<string, unknown>>;
    output?: unknown;
    provenance?: AgencyProvenanceConfig;
    observability?: ObservabilityConfig;
    on?: AgencyCallbacks;
    controls?: ResourceControls;
    dependsOn?: string[];
    cognitiveMechanisms?: CognitiveMechanismsConfig;
    verifyCitations?: VerifyCitationsConfig;
}

Hierarchy (view full)

Properties

Top-level usage ledger shorthand. When present, forwarded to observability.usageLedger internally.

chainOfThought?: string | boolean

Chain-of-thought reasoning instruction.

  • false — disable CoT injection.
  • true (default for agents) — inject the default CoT instruction when tools are present.
  • string — inject a custom CoT instruction when tools are present.
fallbackProviders?: FallbackProviderEntry[]

Ordered list of fallback providers to try when the primary provider fails with a retryable error (HTTP 402/429/5xx, network errors).

Defaults to auto-built chain when omitted — fallback is on by default. Pass [] for strict single-provider mode, or supply a custom array to control the chain. Applied to every generate(), stream(), and session.send() / session.stream() call made through this agent.

onFallback?: ((error, fallbackProvider) => void)

Callback invoked when a fallback provider is about to be tried.

Type declaration

    • (error, fallbackProvider): void
    • Parameters

      • error: Error

        The error that triggered the fallback.

      • fallbackProvider: string

        The provider identifier being tried next.

      Returns void

router?: IModelRouter

Model router for intelligent provider selection per-call.

hostPolicy?: HostLLMPolicy

Host-level routing hints forwarded to the high-level generation helpers.

One spend budget for every call this agent and its sessions make: each provider call is checked against what is left before it is made and recorded after it, and AgentSession.recordExternalCost charges costs made outside AgentOS to it. Settings make one SpendBudget for the agent; pass an instance to share it wider. With runtime: 'gmi' every completion call a GMI makes is checked against it before it is sent, metaprompts and self-reflection included; its cognitive memory's embeddings and the learning layer's own calls are not counted. A seat's turn (sessionSeat(), or a member a launched team seats) is checked against it and charged to it beside the budget its team's call carries, and so is a team the seat's turn launches; its refusal of a seat's call runs the carried budget's onLimitReached function, as a refusal by that budget's parent does.

policyTier?: "safe" | "standard" | "mature" | "private-adult"

Caller's intended content policy tier, forwarded to every generate() / stream() / session call this agent makes (same contract as GenerateTextOptions.policyTier): on 'mature' / 'private-adult' with no explicit fallbackProviders, the auto-built fallback chain leads with the tier's uncensored legs so a content-policy refusal from the primary re-routes to a model that can complete the request, and the model router receives the tier as a routing hint. Unset, the chain follows the tier the call otherwise resolves to (a host policy's tier or the router's default tier); with no tier anywhere it is the availability-only chain. A per-call policyTier in extra overrides this value.

routerParams?: Partial<ModelRouteParams>

Routing hints passed to the model router's selectModel() call.

Useful for declaring capability requirements up-front so the router can pick a model that actually supports what the agent needs:

agent({
name: 'World Architect',
router: policyAwareRouter,
routerParams: { requiredCapabilities: ['json_mode'] },
responseSchema: WorldIdentitySchema,
});

When omitted, the router receives a minimal default params object (taskHint only, plus function_calling in requiredCapabilities when tools are declared).

responseSchema?: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

Optional Zod schema for validating the LLM's structured output.

When provided, the agent's generate() result includes a parsed field with the Zod-validated and typed output. JSON extraction and validation happen after generation. On validation failure, the agent retries internally (up to controls.maxValidationRetries ?? 1).

When omitted, behavior is unchanged — result.parsed is undefined. This is a non-breaking additive change.

Example

import { z } from 'zod';
const myAgent = agent({
name: 'Extractor',
instructions: 'Extract entities as JSON',
responseSchema: z.object({ entities: z.array(z.string()) }),
});
const result = await myAgent.generate('Find entities in: ...');
console.log(result.parsed?.entities); // string[]
onBeforeGeneration?: ((context) => Promise<void | GenerationHookContext>)

Pre-generation hook, called before each LLM step. On the GMI path with learning on, its system is the persona's base prompt, which holds no personality section; the system text in messages holds the section after the base prompt.

Type declaration

onAfterGeneration?: ((result) => Promise<void | GenerationHookResult>)

Post-generation hook, called after each LLM step.

Type declaration

onBeforeToolExecution?: ((info) => Promise<null | ToolCallHookInfo>)

Pre-tool-execution hook.

Type declaration

memoryProvider?: AgentMemoryProvider

Optional memory provider. When provided, memory auto-wires on all four agent call paths (see AgentMemoryProvider for hook contract).

  • getContext runs before each LLM call; result prepended as a system message.
  • observe runs as fire-and-forget after each LLM call, except schema calls, which observe only the accepted exchange after validation.
memoryProviderOptions?: MemoryProviderHookOptions

Optional tunables for the automatic memoryProvider hooks. timeoutMs bounds each getContext call before the turn ships without memory (default MEMORY_TIMEOUT_MS, 5000); tokenBudget is forwarded to getContext as the recall ceiling (default DEFAULT_MEMORY_TOKEN_BUDGET, 2000). Both fall back to the historical module constants when omitted.

skills?: SkillEntry[]

Optional skill entries to inject into the system prompt. Skill content is appended to the system prompt as markdown sections.

systemBlocks?: SystemContentBlock[]

Structured system prompt blocks with cache breakpoints. When provided, takes precedence over the assembled string from instructions, name, personality, and skills. Use this for prompt caching support with Anthropic.

cache?: false | {
    ttl?: "5m" | "1h";
}

Per-call prompt-cache control forwarded to every generate / stream / session call this agent makes (same contract as GenerateTextOptions.cache): false sends zero cache markers; { ttl: '1h' } re-times the auto markers — including the moving conversation-history tail — onto the 1-hour cache. Set '1h' for agent loops whose steps gap past the 5-minute default cache TTL (multi-minute tool executions between LLM steps), where the default-paced history marker expires between steps and every step re-writes the whole prefix. Unset -> the provider's default marker pacing.

Type declaration

  • Optional ttl?: "5m" | "1h"
history?: false | Partial<SessionHistoryConfig>

Session conversation-history policy. Sessions maintain a lossless transcript by default — independent of the memory subsystem — bounded past maxTokens (default 120K estimated) by chunk-amortized whole-block eviction. false restores stateless sessions (the pre-0.10 memory: false behavior). Partial objects override individual bounds.

runtime?: "legacy" | "gmi"

Which engine serves this agent. 'legacy' (the default) calls the model through generateText and streamText; 'gmi' serves every session with a Generalized Mind Instance (docs/GMI.md, "GMIs from agent()").

GMI profile when runtime is 'gmi': 'light' (the default), 'full', or each switch set in a CognitionConfig.

learning?: null | boolean | LearningConfig

The learning layer when runtime is 'gmi' (docs/GMI.md, "Learning"). Unset, false or null: off, and the agent runs as it did before the layer existed. true or a LearningConfig: the agent's GMIs send the personality section as a system prompt of its own on every turn, and each session opened with a user id is bound to a learner. The legacy runtime ignores it.

Temporary teams this agent launches from a turn, with runtime: 'gmi': launch: true registers the launch_agency tool, which runs an agency() team on one goal and returns its answer as the call's result, and the other fields bound every launch (depth, seats, launches in flight, budget share and pool, deadline, members a launch may seat by key, hitl). Every bound is checked, and the members record read, at construction: a member put in the record afterwards is never seated. Off unless launch is true; the legacy runtime throws when it is, and its construction warning names agencies when another field is set, since it applies none of them.

voice?: VoiceConfig & {
    session?: {
        factory: VoiceSessionFactory;
        agent: {
            name: string;
            prompt: string;
            language: string;
            reasoning: {
                modelId: string;
                modelRevision: string;
                protocol: {
                    id: "openai-chat-completions";
                    version: 1;
                };
                usageUnits: {
                    input_token: "token";
                    output_token: "token";
                    reasoning_token: "token";
                    cached_input_token: "token";
                    reasoningInOutput: boolean;
                };
                attemptLimits: {
                    maxAttempts: number;
                    perAttempt: {
                        input_token: number;
                        output_token: number;
                        reasoning_token: number;
                        cached_input_token: number;
                        request: number;
                    };
                };
                cancellation: "native_abort" | "process_exit" | "unsupported";
                provider: "local";
                manifestDigest: string;
                fallbacks: ({
                    modelId: ...;
                    modelRevision: ...;
                    protocol: ...;
                    usageUnits: ...;
                    attemptLimits: ...;
                    cancellation: ...;
                    provider: ...;
                    manifestDigest: ...;
                } | {
                    modelId: ...;
                    modelRevision: ...;
                    protocol: ...;
                    usageUnits: ...;
                    attemptLimits: ...;
                    cancellation: ...;
                    provider: ...;
                    endpointRef: ...;
                    endpointRevision: ...;
                    credentialRef?: ...;
                })[];
            } | {
                modelId: string;
                modelRevision: string;
                protocol: {
                    id: "openai-chat-completions";
                    version: 1;
                };
                usageUnits: {
                    input_token: "token";
                    output_token: "token";
                    reasoning_token: "token";
                    cached_input_token: "token";
                    reasoningInOutput: boolean;
                };
                attemptLimits: {
                    maxAttempts: number;
                    perAttempt: {
                        input_token: number;
                        output_token: number;
                        reasoning_token: number;
                        cached_input_token: number;
                        request: number;
                    };
                };
                cancellation: "native_abort" | "process_exit" | "unsupported";
                provider: "registered_endpoint";
                endpointRef: string;
                endpointRevision: number;
                credentialRef?: string;
                fallbacks: ({
                    modelId: ...;
                    modelRevision: ...;
                    protocol: ...;
                    usageUnits: ...;
                    attemptLimits: ...;
                    cancellation: ...;
                    provider: ...;
                    manifestDigest: ...;
                } | {
                    modelId: ...;
                    modelRevision: ...;
                    protocol: ...;
                    usageUnits: ...;
                    attemptLimits: ...;
                    cancellation: ...;
                    provider: ...;
                    endpointRef: ...;
                    endpointRevision: ...;
                    credentialRef?: ...;
                })[];
            };
            voice: {
                id: string;
                revision: string;
            };
            stt: {
                providerId: string;
                modelId: string;
                modelRevision: string;
                mode: "streaming" | "batch";
                sampleRate: number;
                codec: "pcm_s16le" | "pcm_f32le" | "opus" | "mp3" | "wav";
                optionsRef?: string;
                credentialRef?: string;
            };
            tts: {
                providerId: string;
                modelId: string;
                modelRevision: string;
                mode: "streaming" | "batch";
                sampleRate: number;
                codec: "pcm_s16le" | "pcm_f32le" | "opus" | "mp3" | "wav";
                optionsRef?: string;
                credentialRef?: string;
            };
            vad: {
                providerId: string;
                modelId: string;
                modelRevision: string;
                threshold: number;
                optionsRef?: string;
            };
            endpoint: {
                providerId: string;
                modelId: string;
                modelRevision: string;
                optionsRef?: string;
            };
            providerPolicy: {
                mode: "provider" | "local" | "hosted";
                providerIds: string[];
                purposes: ("stt" | "tts" | "vad" | "endpoint" | "reasoning")[];
                fallback: "none" | "allowlisted";
            };
            limits: {
                maxDurationSeconds: number;
                setupTimeoutMs: number;
                reconnectGraceMs: number;
                silenceTimeoutMs: number;
                cleanupTimeoutMs: number;
                maxTurns: number;
            };
            allowedToolRefs: string[];
            transcriptPolicy: {
                mode: "none";
            } | {
                mode: "delivery";
                deliveryTtlSeconds: number;
            } | {
                mode: "retained";
                retentionSeconds: number;
            };
            webhookRef: null | string;
            version: 1;
            agentId: string;
            scopeId: string;
            revision: number;
            state: "active" | "archived";
            createdAt: number;
            updatedAt: number;
        };
    };
}

Explicit runtime binding. No provider is discovered from the process environment for this path.

Type declaration

  • Optional session?: {
        factory: VoiceSessionFactory;
        agent: {
            name: string;
            prompt: string;
            language: string;
            reasoning: {
                modelId: string;
                modelRevision: string;
                protocol: {
                    id: "openai-chat-completions";
                    version: 1;
                };
                usageUnits: {
                    input_token: "token";
                    output_token: "token";
                    reasoning_token: "token";
                    cached_input_token: "token";
                    reasoningInOutput: boolean;
                };
                attemptLimits: {
                    maxAttempts: number;
                    perAttempt: {
                        input_token: number;
                        output_token: number;
                        reasoning_token: number;
                        cached_input_token: number;
                        request: number;
                    };
                };
                cancellation: "native_abort" | "process_exit" | "unsupported";
                provider: "local";
                manifestDigest: string;
                fallbacks: ({
                    modelId: ...;
                    modelRevision: ...;
                    protocol: ...;
                    usageUnits: ...;
                    attemptLimits: ...;
                    cancellation: ...;
                    provider: ...;
                    manifestDigest: ...;
                } | {
                    modelId: ...;
                    modelRevision: ...;
                    protocol: ...;
                    usageUnits: ...;
                    attemptLimits: ...;
                    cancellation: ...;
                    provider: ...;
                    endpointRef: ...;
                    endpointRevision: ...;
                    credentialRef?: ...;
                })[];
            } | {
                modelId: string;
                modelRevision: string;
                protocol: {
                    id: "openai-chat-completions";
                    version: 1;
                };
                usageUnits: {
                    input_token: "token";
                    output_token: "token";
                    reasoning_token: "token";
                    cached_input_token: "token";
                    reasoningInOutput: boolean;
                };
                attemptLimits: {
                    maxAttempts: number;
                    perAttempt: {
                        input_token: number;
                        output_token: number;
                        reasoning_token: number;
                        cached_input_token: number;
                        request: number;
                    };
                };
                cancellation: "native_abort" | "process_exit" | "unsupported";
                provider: "registered_endpoint";
                endpointRef: string;
                endpointRevision: number;
                credentialRef?: string;
                fallbacks: ({
                    modelId: ...;
                    modelRevision: ...;
                    protocol: ...;
                    usageUnits: ...;
                    attemptLimits: ...;
                    cancellation: ...;
                    provider: ...;
                    manifestDigest: ...;
                } | {
                    modelId: ...;
                    modelRevision: ...;
                    protocol: ...;
                    usageUnits: ...;
                    attemptLimits: ...;
                    cancellation: ...;
                    provider: ...;
                    endpointRef: ...;
                    endpointRevision: ...;
                    credentialRef?: ...;
                })[];
            };
            voice: {
                id: string;
                revision: string;
            };
            stt: {
                providerId: string;
                modelId: string;
                modelRevision: string;
                mode: "streaming" | "batch";
                sampleRate: number;
                codec: "pcm_s16le" | "pcm_f32le" | "opus" | "mp3" | "wav";
                optionsRef?: string;
                credentialRef?: string;
            };
            tts: {
                providerId: string;
                modelId: string;
                modelRevision: string;
                mode: "streaming" | "batch";
                sampleRate: number;
                codec: "pcm_s16le" | "pcm_f32le" | "opus" | "mp3" | "wav";
                optionsRef?: string;
                credentialRef?: string;
            };
            vad: {
                providerId: string;
                modelId: string;
                modelRevision: string;
                threshold: number;
                optionsRef?: string;
            };
            endpoint: {
                providerId: string;
                modelId: string;
                modelRevision: string;
                optionsRef?: string;
            };
            providerPolicy: {
                mode: "provider" | "local" | "hosted";
                providerIds: string[];
                purposes: ("stt" | "tts" | "vad" | "endpoint" | "reasoning")[];
                fallback: "none" | "allowlisted";
            };
            limits: {
                maxDurationSeconds: number;
                setupTimeoutMs: number;
                reconnectGraceMs: number;
                silenceTimeoutMs: number;
                cleanupTimeoutMs: number;
                maxTurns: number;
            };
            allowedToolRefs: string[];
            transcriptPolicy: {
                mode: "none";
            } | {
                mode: "delivery";
                deliveryTtlSeconds: number;
            } | {
                mode: "retained";
                retentionSeconds: number;
            };
            webhookRef: null | string;
            version: 1;
            agentId: string;
            scopeId: string;
            revision: number;
            state: "active" | "archived";
            createdAt: number;
            updatedAt: number;
        };
    }
    • factory: VoiceSessionFactory
    • agent: {
          name: string;
          prompt: string;
          language: string;
          reasoning: {
              modelId: string;
              modelRevision: string;
              protocol: {
                  id: "openai-chat-completions";
                  version: 1;
              };
              usageUnits: {
                  input_token: "token";
                  output_token: "token";
                  reasoning_token: "token";
                  cached_input_token: "token";
                  reasoningInOutput: boolean;
              };
              attemptLimits: {
                  maxAttempts: number;
                  perAttempt: {
                      input_token: number;
                      output_token: number;
                      reasoning_token: number;
                      cached_input_token: number;
                      request: number;
                  };
              };
              cancellation: "native_abort" | "process_exit" | "unsupported";
              provider: "local";
              manifestDigest: string;
              fallbacks: ({
                  modelId: ...;
                  modelRevision: ...;
                  protocol: ...;
                  usageUnits: ...;
                  attemptLimits: ...;
                  cancellation: ...;
                  provider: ...;
                  manifestDigest: ...;
              } | {
                  modelId: ...;
                  modelRevision: ...;
                  protocol: ...;
                  usageUnits: ...;
                  attemptLimits: ...;
                  cancellation: ...;
                  provider: ...;
                  endpointRef: ...;
                  endpointRevision: ...;
                  credentialRef?: ...;
              })[];
          } | {
              modelId: string;
              modelRevision: string;
              protocol: {
                  id: "openai-chat-completions";
                  version: 1;
              };
              usageUnits: {
                  input_token: "token";
                  output_token: "token";
                  reasoning_token: "token";
                  cached_input_token: "token";
                  reasoningInOutput: boolean;
              };
              attemptLimits: {
                  maxAttempts: number;
                  perAttempt: {
                      input_token: number;
                      output_token: number;
                      reasoning_token: number;
                      cached_input_token: number;
                      request: number;
                  };
              };
              cancellation: "native_abort" | "process_exit" | "unsupported";
              provider: "registered_endpoint";
              endpointRef: string;
              endpointRevision: number;
              credentialRef?: string;
              fallbacks: ({
                  modelId: ...;
                  modelRevision: ...;
                  protocol: ...;
                  usageUnits: ...;
                  attemptLimits: ...;
                  cancellation: ...;
                  provider: ...;
                  manifestDigest: ...;
              } | {
                  modelId: ...;
                  modelRevision: ...;
                  protocol: ...;
                  usageUnits: ...;
                  attemptLimits: ...;
                  cancellation: ...;
                  provider: ...;
                  endpointRef: ...;
                  endpointRevision: ...;
                  credentialRef?: ...;
              })[];
          };
          voice: {
              id: string;
              revision: string;
          };
          stt: {
              providerId: string;
              modelId: string;
              modelRevision: string;
              mode: "streaming" | "batch";
              sampleRate: number;
              codec: "pcm_s16le" | "pcm_f32le" | "opus" | "mp3" | "wav";
              optionsRef?: string;
              credentialRef?: string;
          };
          tts: {
              providerId: string;
              modelId: string;
              modelRevision: string;
              mode: "streaming" | "batch";
              sampleRate: number;
              codec: "pcm_s16le" | "pcm_f32le" | "opus" | "mp3" | "wav";
              optionsRef?: string;
              credentialRef?: string;
          };
          vad: {
              providerId: string;
              modelId: string;
              modelRevision: string;
              threshold: number;
              optionsRef?: string;
          };
          endpoint: {
              providerId: string;
              modelId: string;
              modelRevision: string;
              optionsRef?: string;
          };
          providerPolicy: {
              mode: "provider" | "local" | "hosted";
              providerIds: string[];
              purposes: ("stt" | "tts" | "vad" | "endpoint" | "reasoning")[];
              fallback: "none" | "allowlisted";
          };
          limits: {
              maxDurationSeconds: number;
              setupTimeoutMs: number;
              reconnectGraceMs: number;
              silenceTimeoutMs: number;
              cleanupTimeoutMs: number;
              maxTurns: number;
          };
          allowedToolRefs: string[];
          transcriptPolicy: {
              mode: "none";
          } | {
              mode: "delivery";
              deliveryTtlSeconds: number;
          } | {
              mode: "retained";
              retentionSeconds: number;
          };
          webhookRef: null | string;
          version: 1;
          agentId: string;
          scopeId: string;
          revision: number;
          state: "active" | "archived";
          createdAt: number;
          updatedAt: number;
      }
      • name: string
      • prompt: string
      • language: string
      • reasoning: {
            modelId: string;
            modelRevision: string;
            protocol: {
                id: "openai-chat-completions";
                version: 1;
            };
            usageUnits: {
                input_token: "token";
                output_token: "token";
                reasoning_token: "token";
                cached_input_token: "token";
                reasoningInOutput: boolean;
            };
            attemptLimits: {
                maxAttempts: number;
                perAttempt: {
                    input_token: number;
                    output_token: number;
                    reasoning_token: number;
                    cached_input_token: number;
                    request: number;
                };
            };
            cancellation: "native_abort" | "process_exit" | "unsupported";
            provider: "local";
            manifestDigest: string;
            fallbacks: ({
                modelId: ...;
                modelRevision: ...;
                protocol: ...;
                usageUnits: ...;
                attemptLimits: ...;
                cancellation: ...;
                provider: ...;
                manifestDigest: ...;
            } | {
                modelId: ...;
                modelRevision: ...;
                protocol: ...;
                usageUnits: ...;
                attemptLimits: ...;
                cancellation: ...;
                provider: ...;
                endpointRef: ...;
                endpointRevision: ...;
                credentialRef?: ...;
            })[];
        } | {
            modelId: string;
            modelRevision: string;
            protocol: {
                id: "openai-chat-completions";
                version: 1;
            };
            usageUnits: {
                input_token: "token";
                output_token: "token";
                reasoning_token: "token";
                cached_input_token: "token";
                reasoningInOutput: boolean;
            };
            attemptLimits: {
                maxAttempts: number;
                perAttempt: {
                    input_token: number;
                    output_token: number;
                    reasoning_token: number;
                    cached_input_token: number;
                    request: number;
                };
            };
            cancellation: "native_abort" | "process_exit" | "unsupported";
            provider: "registered_endpoint";
            endpointRef: string;
            endpointRevision: number;
            credentialRef?: string;
            fallbacks: ({
                modelId: ...;
                modelRevision: ...;
                protocol: ...;
                usageUnits: ...;
                attemptLimits: ...;
                cancellation: ...;
                provider: ...;
                manifestDigest: ...;
            } | {
                modelId: ...;
                modelRevision: ...;
                protocol: ...;
                usageUnits: ...;
                attemptLimits: ...;
                cancellation: ...;
                provider: ...;
                endpointRef: ...;
                endpointRevision: ...;
                credentialRef?: ...;
            })[];
        }
      • voice: {
            id: string;
            revision: string;
        }
        • id: string
        • revision: string
      • stt: {
            providerId: string;
            modelId: string;
            modelRevision: string;
            mode: "streaming" | "batch";
            sampleRate: number;
            codec: "pcm_s16le" | "pcm_f32le" | "opus" | "mp3" | "wav";
            optionsRef?: string;
            credentialRef?: string;
        }
        • providerId: string
        • modelId: string
        • modelRevision: string
        • mode: "streaming" | "batch"
        • sampleRate: number
        • codec: "pcm_s16le" | "pcm_f32le" | "opus" | "mp3" | "wav"
        • Optional optionsRef?: string
        • Optional credentialRef?: string
      • tts: {
            providerId: string;
            modelId: string;
            modelRevision: string;
            mode: "streaming" | "batch";
            sampleRate: number;
            codec: "pcm_s16le" | "pcm_f32le" | "opus" | "mp3" | "wav";
            optionsRef?: string;
            credentialRef?: string;
        }
        • providerId: string
        • modelId: string
        • modelRevision: string
        • mode: "streaming" | "batch"
        • sampleRate: number
        • codec: "pcm_s16le" | "pcm_f32le" | "opus" | "mp3" | "wav"
        • Optional optionsRef?: string
        • Optional credentialRef?: string
      • vad: {
            providerId: string;
            modelId: string;
            modelRevision: string;
            threshold: number;
            optionsRef?: string;
        }
        • providerId: string
        • modelId: string
        • modelRevision: string
        • threshold: number
        • Optional optionsRef?: string
      • endpoint: {
            providerId: string;
            modelId: string;
            modelRevision: string;
            optionsRef?: string;
        }
        • providerId: string
        • modelId: string
        • modelRevision: string
        • Optional optionsRef?: string
      • providerPolicy: {
            mode: "provider" | "local" | "hosted";
            providerIds: string[];
            purposes: ("stt" | "tts" | "vad" | "endpoint" | "reasoning")[];
            fallback: "none" | "allowlisted";
        }
        • mode: "provider" | "local" | "hosted"
        • providerIds: string[]
        • purposes: ("stt" | "tts" | "vad" | "endpoint" | "reasoning")[]
        • fallback: "none" | "allowlisted"
      • limits: {
            maxDurationSeconds: number;
            setupTimeoutMs: number;
            reconnectGraceMs: number;
            silenceTimeoutMs: number;
            cleanupTimeoutMs: number;
            maxTurns: number;
        }
        • maxDurationSeconds: number
        • setupTimeoutMs: number
        • reconnectGraceMs: number
        • silenceTimeoutMs: number
        • cleanupTimeoutMs: number
        • maxTurns: number
      • allowedToolRefs: string[]
      • transcriptPolicy: {
            mode: "none";
        } | {
            mode: "delivery";
            deliveryTtlSeconds: number;
        } | {
            mode: "retained";
            retentionSeconds: number;
        }
      • webhookRef: null | string
      • version: 1
      • agentId: string
      • scopeId: string
      • revision: number
      • state: "active" | "archived"
      • createdAt: number
      • updatedAt: number
soul: NonNullable<undefined | string | {
    content: string;
} | {
    path: string;
}>

Per-agent identity loaded from a SOUL.md workspace (the OpenClaw / aaronjmars-soul.md convention). Three forms are accepted:

  • Workspace path — points at a directory containing SOUL.md and optional companion files (STYLE.md, IDENTITY.md, AGENTS.md, MEMORY.md, examples/):

    agent({ provider: 'anthropic', soul: '~/.agentos/agents/aria' });
    
  • Direct file path — points at a single SOUL.md file:

    agent({ provider: 'anthropic', soul: './personas/aria.soul.md' });
    
  • Inline content — pass the soul markdown directly (useful for tests and ephemeral agents):

    agent({ provider: 'anthropic', soul: { content: SOUL_MARKDOWN_STRING } });
    

Loading semantics: at agent boot the runtime reads SOUL.md, parses YAML frontmatter into an IPersonaDefinition (HEXACO traits, voice, mood, hardLimits), and injects the markdown body as the FIRST system message — before instructions, chainOfThought, personality, or skills. STYLE.md is appended as a second system message when present.

See

  • loadSoul in @framers/agentos/cognition/substrate/personas/SoulLoader for the loader implementation and full SOUL.md format spec.
  • https://github.com/aaronjmars/soul.md for the cross-framework convention.
model?: string

Model identifier. Accepted in two formats:

  • Plain model name (e.g. "gpt-4o") when provider is also set. Preferred.
  • "provider:model" combined string (e.g. "openai:gpt-4o").
provider?: string

Provider name (e.g. "openai", "anthropic", "ollama"). Auto-detected from environment API keys when omitted.

instructions?: string

Free-form system instructions prepended to the system prompt.

name?: string

Display name for the agent, injected into the system prompt.

apiKey?: string

Override the provider API key instead of reading from environment variables.

baseUrl?: string

Override the provider base URL (useful for local proxies or Ollama). An empty or whitespace-only value is unset: a same-provider setDefaultProvider() URL, then the provider's URL variable, apply as with none. A seat of an agency with a blank value takes the agency-level baseUrl as a seat with none does.

personality?: Partial<{
    honesty: number;
    emotionality: number;
    extraversion: number;
    agreeableness: number;
    conscientiousness: number;
    openness: number;
    honestyHumility: number;
    honesty_humility: number;
    opennessToExperience: number;
}>

HEXACO-inspired personality trait overrides (0–1 scale). Encoded as a human-readable trait string appended to the system prompt. The SOUL.md spellings honestyHumility / honesty_humility and opennessToExperience are accepted for honesty and openness; when both spellings are given, the canonical key wins.

Type declaration

  • honesty: number
  • emotionality: number
  • extraversion: number
  • agreeableness: number
  • conscientiousness: number
  • openness: number
  • honestyHumility: number
  • honesty_humility: number
  • opennessToExperience: number

Tools available to the agent on every call.

Accepts:

  • a named high-level tool map
  • an ExternalToolRegistry (Record, Map, or iterable)
  • a prompt-only ToolDefinitionForLLM[]
maxSteps?: number

Maximum number of agentic steps (LLM calls) per invocation. Defaults to 5.

maxTokens?: number

Upper bound on completion tokens for each LLM call the agent makes. Forwarded to the underlying generateText / streamText call on every generate(), stream(), and session.send() invocation.

Caps tail spend when a model misbehaves and yaps past the intended output size. Omit to use the provider default — AnthropicProvider defaults to 16000 (set 2026-05-17; was 4096), OpenAIProvider defaults to 4096, GeminiProvider defaults to 8192. Set to ~2× the agent's typical response size so normal calls finish naturally and only runaway generations hit the cap.

Example

// Cap a roleplay agent at 1024 — short turns, fast feedback.
const companion = agent({
provider: 'anthropic',
model: 'claude-sonnet-4-6',
instructions: 'Reply in character. 2-3 sentences.',
maxTokens: 1024,
});

// Tool-use agent emitting verbose JSON — go big so structured
// output doesn't truncate mid-token. Opus 4.7 supports 32000.
const codegen = agent({
provider: 'anthropic',
model: 'claude-opus-4-7',
tools: { GenerateCode, RunTests, JudgeOutput },
maxTokens: 16000,
});
thinking?: false | {
    budgetTokens: number;
}

Extended-thinking switch forwarded to Claude models on every generate() / stream() / session call this agent makes. Any positive budgetTokens turns adaptive thinking on (the number itself is not sent). false turns thinking off with the model's own off shape; Opus 5.5, Fable and Mythos always think. Omitted keeps the model's default: thinking on for Opus 5 and later, Sonnet 5 and later, Fable and Mythos, off for older models. Other providers ignore it.

Type declaration

  • budgetTokens: number

Example

const codegen = agent({
provider: 'anthropic',
model: 'claude-opus-5',
tools: { GenerateCode, RunTests, JudgeOutput },
maxTokens: 24000,
thinking: { budgetTokens: 8000 },
});
effort?: string

Reasoning-effort control forwarded to every generate/stream/session call. On effort-capable Claude models (Opus 4.5+, Sonnet 4.6, Fable/Mythos 5) the provider sends output_config.effort (low|medium|high|xhigh|max). On OpenAI reasoning models (o-series, GPT-5.x) the provider sends reasoning_effort (chat) / reasoning.effort (Responses), with max clamping to xhigh — OpenAI's ceiling — and a model-aware guard capping xhigh → high on ids not probe-verified for xhigh (gpt-5.5/5.6 families are verified). Independent of thinking; ignored on unsupported models/values. Works per-agent in agency() rosters — each sub-agent may pin its own depth.

customModelParams?: Record<string, unknown>

Provider-specific TOP-LEVEL request-payload parameters forwarded verbatim on every generate/stream/session call via ModelCompletionOptions.customModelParams. Providers spread these onto the outgoing request body — the escape hatch for params the typed options don't model, e.g. OpenRouter provider-routing preferences:

customModelParams: { provider: { sort: 'throughput' } }
memory?: boolean | MemoryConfig

Memory configuration. agent() reads it only with runtime: 'gmi', where true or a MemoryConfig turns on cognitive memory for the agent's sessions (its embedding and consolidation fields are read) and false keeps it off, also under cognition: 'full'. A session's message history is set by history, not by this field.

rag?: RagConfig

Retrieval-Augmented Generation configuration.

discovery?: DiscoveryConfig

Runtime capability discovery configuration.

guardrails?: string[] | GuardrailsConfig

Guardrail policy identifiers or structured config. agency() evaluates none of them (see GuardrailsConfig), and agent() does not apply them.

  • string[] — shorthand; agency() reads it as the output list.
  • GuardrailsConfig — separate input and output lists.
security?: {
    tier: SecurityTier;
}

Security tier. Accepted and not enforced (see SecurityTier).

Type declaration

  • tier: SecurityTier
permissions?: PermissionsConfig

Tool and resource permission fields. Accepted and not enforced (see PermissionsConfig).

hitl?: HitlConfig

Human-in-the-loop approval configuration.

emergent?: EmergentConfig

Emergent agent synthesis configuration.

avatar?: AvatarConfig

Avatar visual presentation configuration.

channels?: Record<string, Record<string, unknown>>

Channel adapter configurations keyed by channel name. Values are channel-specific option objects passed through opaquely.

output?: unknown

Output schema for structured generation. Accepts a Zod schema at runtime; typed as unknown here to avoid a hard dependency on the zod package in the types layer.

provenance?: AgencyProvenanceConfig

Provenance and audit-trail configuration.

observability?: ObservabilityConfig

Observability and telemetry configuration.

Event callbacks fired at various lifecycle points during the run. agency() fires them for its run. A gmi() agent fires them only for the teams it launches with launch_agency (agencies.launch), each named launch:<agencyId>, and for those launches' failures; its own turns fire none, and neither does agent() without runtime: 'gmi'.

controls?: ResourceControls

Resource limits (tokens, cost, time). agency() and the full runtime enforce every field against the entire run. The lightweight agent() helper forwards two of them per call: maxTotalTokens caps each LLM call's completion output (mapped to maxTokens when no explicit maxTokens is set, NOT the prompt+completion run total) and maxDurationMs bounds each LLM request (mapped to requestTimeout). The remaining fields stay agency()-only.

dependsOn?: string[]

Names of other agents in the agency that must complete before this agent runs. Used with strategy: 'graph' to build an explicit dependency DAG. Agents with no dependsOn, or an empty one, are roots and run first. agency() throws AgencyConfigError, naming the agent, for a value that is not an array of names.

Example

`dependsOn: ['researcher']` — this agent waits for `researcher` to finish.
cognitiveMechanisms?: CognitiveMechanismsConfig

Cognitive mechanisms config: the eight memory mechanisms of CognitiveMemoryManager (reconsolidation, retrieval-induced forgetting, involuntary recall, feeling of knowing, temporal gist, schema encoding, source-confidence decay and emotion regulation). Pass {} for the defaults, or override fields per mechanism.

The mechanisms run inside a CognitiveMemoryManager initialized with this config (CognitiveMemoryConfig.cognitiveMechanisms). agent() without runtime: 'gmi' and agency() construct no memory manager, so they log a warning and leave this field unused; agent({ runtime: 'gmi' }) with memory on passes it to the agent's memory manager. On the full runtime, a gmiManagerConfig.cognitiveMemoryFactory builds the manager for each GMI.

verifyCitations?: VerifyCitationsConfig

Verify citations after generate() and default-runtime session calls.

When set, generate() produces the answer, then fetches sources for the user's input with the configured retriever and scores each atomic claim of the answer against them via CitationVerifier. The resulting VerifiedResponse is attached to the result's grounding field — no separate verifier.verify(text, sources) call needed. On the default runtime, session.send() also checks its reply and session.stream() exposes a grounding promise that runs after its text completes. Direct stream() and GMI session calls do not verify. When the retriever returns no sources, or retrieval or the verifier fails, grounding stays unset and the answer is returned as generated.

Pass a config object with the embedding function and the source retriever the verifier should use:

Example

const docsAgent = agent({
provider: 'openai',
model: 'gpt-4o',
verifyCitations: {
embedFn: async (texts) => (await embeddingManager.generateEmbeddings({ texts })).embeddings,
retrieve: (query) => retriever.search(query),
},
});

const result = await docsAgent.generate('How do I configure a guardrail?');
console.log(result.text);
console.log(result.grounding?.overallGrounded);
for (const claim of result.grounding?.claims ?? []) {
if (claim.verdict !== 'supported') console.warn(claim.text);
}