Skip to main content

Harness class

Added in: @mastra/core@1.5.0

warning

The Harness class is in alpha stage and subject to change. It won't follow semantic versioning guarantees until it graduates from experimental status. Use with caution and expect breaking changes in minor versions.

The Harness class orchestrates multiple agent modes, shared state, memory, and storage. It provides a control layer that a TUI or other UI can drive to manage threads, switch models and modes, send messages, handle tool approvals, and track events.

Usage example
Direct link to Usage example

import { Harness } from '@mastra/core/harness'
import { LibSQLStore } from '@mastra/libsql'
import { z } from 'zod'

const harness = new Harness({
id: 'my-coding-agent',
storage: new LibSQLStore({ url: 'file:./data.db' }),
stateSchema: z.object({
currentModelId: z.string().optional(),
}),
modes: [
{ id: 'plan', name: 'Plan', default: true, agent: planAgent },
{ id: 'build', name: 'Build', agent: buildAgent },
],
})

harness.subscribe(event => {
if (event.type === 'message_update') {
renderMessage(event.message)
}
})

await harness.init()
await harness.selectOrCreateThread()
await harness.sendMessage({ content: 'Hello!' })

Constructor parameters
Direct link to Constructor parameters

id:

string
Unique identifier for this harness instance.

resourceId?:

string
Resource ID for grouping threads (e.g., project identifier). Threads are scoped to this resource ID. Defaults to `id`.

storage?:

MastraCompositeStore
Storage backend for persistence (threads, messages, state).

stateSchema?:

z.ZodObject
Zod schema defining the shape of harness state. Used for validation and extracting defaults.

initialState?:

Partial<z.infer<TState>>
Initial state values. Must conform to the schema if provided.

memory?:

MastraMemory
Memory configuration shared across all modes. Propagated to mode agents that don't have their own memory.

modes:

HarnessMode[]
Available agent modes. At least one mode is required. Each mode defines an agent and optional defaults.
HarnessMode

id:

string
Unique identifier for this mode (e.g., `"plan"`, `"build"`).

name?:

string
Human-readable name for display.

default?:

boolean
Whether this is the default mode when the harness starts.

defaultModelId?:

string
Default model ID for this mode (e.g., `"anthropic/claude-sonnet-4-20250514"`). Used when no per-mode model has been explicitly selected.

color?:

string
Hex color for the mode indicator (e.g., `"#7c3aed"`).

agent:

Agent | ((state) => Agent)
The agent for this mode. It can be a static Agent instance or a function that receives harness state and returns an Agent.

tools?:

ToolsInput | ((ctx) => ToolsInput)
Tools available to all agents across all modes. It can be a static tools object or a dynamic function that receives the request context.

workspace?:

Workspace | WorkspaceConfig | ((ctx) => Workspace)
Workspace configuration. Accepts a pre-constructed Workspace, a WorkspaceConfig for the harness to construct internally, or a dynamic factory function.

subagents?:

HarnessSubagent[]
Subagent definitions. When provided, the harness creates a built-in `subagent` tool that parent agents can call to spawn focused subagents.
HarnessSubagent

id:

string
Unique identifier for this subagent type (e.g., `"explore"`, `"execute"`).

name:

string
Human-readable name shown in tool output.

description:

string
Description of what this subagent does. Used in the auto-generated tool description.

instructions:

string
System prompt for this subagent.

tools?:

ToolsInput
Tools this subagent has direct access to.

allowedHarnessTools?:

string[]
Tool IDs from the harness's shared `tools` config. Merged with `tools` above to let subagents use a subset of harness tools.

allowedWorkspaceTools?:

string[]
Workspace tool names the subagent is allowed to use. Uses the exposed names (after any renames via workspace tool config). When set, workspace tools not in this list are hidden from the model. Non-workspace tools are never affected. When omitted, all workspace tools are visible.

defaultModelId?:

string
Default model ID for this subagent type.

maxSteps?:

number
Optional maximum number of steps for the spawned subagent. Defaults to `50` when omitted.

stopWhen?:

LoopOptions['stopWhen']
Optional stop condition for the spawned subagent.

resolveModel?:

(modelId: string) => MastraLanguageModel
Converts a model ID string (e.g., `"anthropic/claude-sonnet-4"`) to a language model instance. Used by subagents and observational memory model resolution.

omConfig?:

HarnessOMConfig
Default configuration for observational memory (observer/reflector model IDs and thresholds).

heartbeatHandlers?:

HeartbeatHandler[]
Periodic background tasks started during `init()`. Use for gateway sync, cache refresh, and similar tasks.

idGenerator?:

() => string
= timestamp + random string
Custom ID generator for Harness-managed IDs such as threads and mode-run identifiers.

modelAuthChecker?:

ModelAuthChecker
Custom auth checker for model providers. Return `true`/`false` to override the default environment variable check, or `undefined` to fall back to defaults.

modelUseCountProvider?:

ModelUseCountProvider
Provides per-model use counts for sorting and display in `listAvailableModels()`.

toolCategoryResolver?:

(toolName: string) => ToolCategory | null
Maps tool names to permission categories (`'read'`, `'edit'`, `'execute'`, `'mcp'`, `'other'`). Used by the permission system to resolve category-level policies.

threadLock?:

{ acquire, release }
Thread locking callbacks to prevent concurrent access from multiple processes. `acquire` should throw if the lock is held.

Properties
Direct link to Properties

id:

string
Harness identifier, set at construction.

Methods
Direct link to Methods

Lifecycle
Direct link to Lifecycle

init()
Direct link to init

Initialize the harness. Loads storage, initializes the workspace, propagates memory and workspace to mode agents, and starts heartbeat handlers. Call this before using the harness.

await harness.init()

selectOrCreateThread()
Direct link to selectorcreatethread

Select the most recent thread for the current resource, or create one if none exist. Loads thread metadata and acquires a thread lock.

const thread = await harness.selectOrCreateThread()

destroy()
Direct link to destroy

Stop all heartbeat handlers and clean up resources.

await harness.destroy()

State
Direct link to State

getState()
Direct link to getstate

Return a read-only snapshot of the current harness state.

const state = harness.getState()

setState(updates)
Direct link to setstateupdates

Update the harness state. Validates against stateSchema if provided, and emits a state_changed event with the new state and changed keys.

await harness.setState({ currentModelId: 'anthropic/claude-sonnet-4-20250514' })

Modes
Direct link to Modes

listModes()
Direct link to listmodes

Return all configured HarnessMode instances.

const modes = harness.listModes()

getCurrentModeId()
Direct link to getcurrentmodeid

Return the ID of the currently active mode.

const modeId = harness.getCurrentModeId()

getCurrentMode()
Direct link to getcurrentmode

Return the HarnessMode object for the current mode.

const mode = harness.getCurrentMode()

switchMode({ modeId })
Direct link to switchmode-modeid-

Switch to a different mode. Aborts any in-progress generation, saves the current model to the outgoing mode, loads the incoming mode's model, and emits mode_changed and model_changed events.

await harness.switchMode({ modeId: 'build' })

Models
Direct link to Models

getCurrentModelId()
Direct link to getcurrentmodelid

Return the ID of the currently selected model from state.

const modelId = harness.getCurrentModelId()

getModelName()
Direct link to getmodelname

Return a short display name from the current model ID. For example, "claude-sonnet-4" from "anthropic/claude-sonnet-4".

const name = harness.getModelName()

getFullModelId()
Direct link to getfullmodelid

Return the complete model ID string.

const fullId = harness.getFullModelId()

hasModelSelected()
Direct link to hasmodelselected

Check if a model ID is currently selected.

if (harness.hasModelSelected()) {
// Ready to send messages
}

switchModel({ modelId, scope?, modeId? })
Direct link to switchmodel-modelid-scope-modeid-

Switch the active model. When scope is 'thread', the model ID is persisted to thread metadata so it's restored when switching back. Emits a model_changed event.

// Set for current session only
await harness.switchModel({ modelId: 'anthropic/claude-sonnet-4-20250514' })

// Persist to the current thread
await harness.switchModel({ modelId: 'anthropic/claude-sonnet-4-20250514', scope: 'thread' })

getCurrentModelAuthStatus()
Direct link to getcurrentmodelauthstatus

Check if the current model's provider has authentication configured. Uses modelAuthChecker if provided, falling back to environment variable checks from the provider registry.

const status = await harness.getCurrentModelAuthStatus()
// { hasAuth: true, apiKeyEnvVar: 'ANTHROPIC_API_KEY' }

listAvailableModels()
Direct link to listavailablemodels

Retrieve all available models from the provider registry, including their authentication status and use counts.

const models = await harness.listAvailableModels()
// [{ id, provider, modelName, hasApiKey, apiKeyEnvVar, useCount }]

Threads
Direct link to Threads

getCurrentThreadId()
Direct link to getcurrentthreadid

Return the ID of the currently active thread.

const threadId = harness.getCurrentThreadId()

createThread({ title? })
Direct link to createthread-title-

Create a new thread. Initializes thread metadata, saves it to storage, acquires a thread lock, and emits a thread_created event.

const thread = await harness.createThread({ title: 'New conversation' })

switchThread({ threadId })
Direct link to switchthread-threadid-

Switch to a different thread. Aborts any in-progress operations, acquires a lock on the new thread, releases the lock on the previous thread, loads the thread's metadata, and emits a thread_changed event.

await harness.switchThread({ threadId: 'thread-abc123' })

listThreads(options?)
Direct link to listthreadsoptions

List threads from storage. By default, only threads for the current resource are returned.

// List threads for current resource
const threads = await harness.listThreads()

// List all threads across resources
const allThreads = await harness.listThreads({ allResources: true })

renameThread({ title })
Direct link to renamethread-title-

Update the title of the current thread.

await harness.renameThread({ title: 'Updated title' })

cloneThread({ sourceThreadId?, title?, resourceId? })
Direct link to clonethread-sourcethreadid-title-resourceid-

Clone an existing thread and switch to the clone. Copies all messages, acquires a lock on the new thread, releases the lock on the previous thread, and emits a thread_created event. If sourceThreadId is omitted, the current thread is cloned. When Observational Memory is enabled, OM records are cloned with remapped message IDs.

// Clone the current thread
const cloned = await harness.cloneThread()

// Clone a specific thread with a custom title
const cloned = await harness.cloneThread({
sourceThreadId: 'thread-abc123',
title: 'Alternative approach',
})

See Memory.cloneThread() for details on what gets cloned.

getResourceId()
Direct link to getresourceid

Return the current resource ID.

const resourceId = harness.getResourceId()

setResourceId({ resourceId })
Direct link to setresourceid-resourceid-

Set the resource ID and clear the current thread.

harness.setResourceId({ resourceId: 'project-xyz' })

getSession()
Direct link to getsession

Return current session information including thread ID, mode ID, and the list of threads.

const session = await harness.getSession()
// { currentThreadId, currentModeId, threads }

Messages
Direct link to Messages

sendMessage({ content, files?, requestContext? })
Direct link to sendmessage-content-files-requestcontext-

Send a message to the current agent. Creates a thread if none exists, builds a RequestContext and toolsets, and streams the agent's response. Handles tool calls, approvals, and errors automatically. If you provide requestContext, the harness forwards it to tools and subagents during the run.

await harness.sendMessage({ content: 'Explain the authentication flow' })

listMessages(options?)
Direct link to listmessagesoptions

Retrieve messages for the current thread.

const messages = await harness.listMessages()

// Limit to the last 50 messages
const recent = await harness.listMessages({ limit: 50 })

listMessagesForThread({ threadId, limit? })
Direct link to listmessagesforthread-threadid-limit-

Retrieve messages for a specific thread.

const messages = await harness.listMessagesForThread({ threadId: 'thread-abc123' })

getFirstUserMessageForThread({ threadId })
Direct link to getfirstusermessageforthread-threadid-

Retrieve the first user message for a given thread.

const firstMsg = await harness.getFirstUserMessageForThread({ threadId: 'thread-abc123' })

Memory
Direct link to Memory

The memory property exposes thread management operations. These are also available as top-level methods on the harness.

memory.createThread({ title? })
Direct link to memorycreatethread-title-

Create a new thread. Same as harness.createThread().

memory.switchThread({ threadId })
Direct link to memoryswitchthread-threadid-

Switch to a different thread. Same as harness.switchThread().

memory.listThreads(options?)
Direct link to memorylistthreadsoptions

List threads from storage. Same as harness.listThreads().

memory.renameThread({ title })
Direct link to memoryrenamethread-title-

Update the title of the current thread. Same as harness.renameThread().

memory.deleteThread({ threadId })
Direct link to memorydeletethread-threadid-

Delete a thread and all its messages from storage. If the deleted thread is the currently active thread, the thread lock is released and the harness clears its active thread. Emits a thread_deleted event.

await harness.memory.deleteThread({ threadId: 'thread-abc123' })

Flow control
Direct link to Flow control

abort()
Direct link to abort

Abort any in-progress generation.

harness.abort()

steer({ content, requestContext? })
Direct link to steer-content-requestcontext-

Steer the agent mid-stream by injecting an instruction into the current generation.

harness.steer({ content: 'Focus on security implications' })

followUp({ content, requestContext? })
Direct link to followup-content-requestcontext-

Queue a follow-up message to be sent after the current generation completes. If no operation is running, sends the message immediately.

harness.followUp({ content: 'Now apply those changes' })

Tool approvals
Direct link to Tool approvals

respondToToolApproval({ decision, requestContext? })
Direct link to respondtotoolapproval-decision-requestcontext-

Respond to a pending tool approval request. Called when a tool_approval_required event is received.

harness.respondToToolApproval({ decision: 'approve' })
harness.respondToToolApproval({ decision: 'decline' })

Questions and plans
Direct link to Questions and plans

respondToQuestion({ questionId, answer })
Direct link to respondtoquestion-questionid-answer-

Respond to a pending question from the ask_user built-in tool.

harness.respondToQuestion({ questionId: 'q-123', answer: 'Yes, proceed with the refactor' })

respondToPlanApproval({ planId, response })
Direct link to respondtoplanapproval-planid-response-

Respond to a pending plan approval from the submit_plan built-in tool. The response object contains action ('approved' or 'rejected') and an optional feedback string.

harness.respondToPlanApproval({ planId: 'plan-123', response: { action: 'approved' } })
harness.respondToPlanApproval({
planId: 'plan-123',
response: { action: 'rejected', feedback: 'Needs more detail' },
})

Permissions
Direct link to Permissions

grantSessionCategory({ category })
Direct link to grantsessioncategory-category-

Grant a tool category for the current session. Tools in this category are auto-approved without prompting.

harness.grantSessionCategory({ category: 'edit' })

grantSessionTool({ toolName })
Direct link to grantsessiontool-toolname-

Grant a specific tool for the current session.

harness.grantSessionTool({ toolName: 'mastra_workspace_execute_command' })

getSessionGrants()
Direct link to getsessiongrants

Return currently granted session categories and tools.

const grants = harness.getSessionGrants()
// { categories: Set<string>, tools: Set<string> }

setPermissionForCategory({ category, policy })
Direct link to setpermissionforcategory-category-policy-

Set the permission policy for a tool category.

harness.setPermissionForCategory({ category: 'execute', policy: 'ask' })

setPermissionForTool({ toolName, policy })
Direct link to setpermissionfortool-toolname-policy-

Set the permission policy for a specific tool. Per-tool policies take precedence over category policies.

harness.setPermissionForTool({ toolName: 'dangerous_tool', policy: 'deny' })

getPermissionRules()
Direct link to getpermissionrules

Return the current permission rules.

const rules = harness.getPermissionRules()
// { categories: { execute: 'ask' }, tools: { dangerous_tool: 'deny' } }

getToolCategory({ toolName })
Direct link to gettoolcategory-toolname-

Resolve a tool's category using the configured toolCategoryResolver.

const category = harness.getToolCategory({ toolName: 'mastra_workspace_write_file' })
// 'edit'

Workspace
Direct link to Workspace

getWorkspace()
Direct link to getworkspace

Return the current workspace instance, or undefined if no workspace is configured or it hasn't been resolved yet.

const workspace = harness.getWorkspace()

resolveWorkspace({ requestContext? })
Direct link to resolveworkspace-requestcontext-

Eagerly resolve and cache the workspace. For dynamic workspaces (factory function), this triggers the factory and caches the result so getWorkspace() returns it. Returns the resolved workspace or undefined if none is configured.

const workspace = await harness.resolveWorkspace()

hasWorkspace()
Direct link to hasworkspace

Return whether a workspace is configured (static, config-based, or dynamic).

if (harness.hasWorkspace()) {
const workspace = await harness.resolveWorkspace()
}

isWorkspaceReady()
Direct link to isworkspaceready

Return whether the workspace is ready to use. For dynamic workspaces (factory function), always returns true. For static workspaces, returns true after init() succeeds.

if (harness.isWorkspaceReady()) {
const workspace = harness.getWorkspace()
}

destroyWorkspace()
Direct link to destroyworkspace

Destroy the workspace and release resources. Only applies to static workspaces — dynamic workspaces aren't destroyed.

await harness.destroyWorkspace()

Observational memory
Direct link to Observational memory

loadOMProgress()
Direct link to loadomprogress

Load observational memory records for the current thread and emit an om_status event with reconstructed progress.

await harness.loadOMProgress()

getObservationalMemoryRecord()
Direct link to getobservationalmemoryrecord

Return the full ObservationalMemoryRecord for the current thread and resource, or null if no thread is selected or no record exists.

const record = await harness.getObservationalMemoryRecord()

if (record) {
console.log(record.activeObservations)
console.log(record.generationCount)
console.log(record.observationTokenCount)
}

getObserverModelId()
Direct link to getobservermodelid

Return the observer model ID from state or the default from omConfig.

const modelId = harness.getObserverModelId()

getReflectorModelId()
Direct link to getreflectormodelid

Return the reflector model ID from state or the default from omConfig.

const modelId = harness.getReflectorModelId()

switchObserverModel({ modelId })
Direct link to switchobservermodel-modelid-

Switch the observer model. Persists the setting to thread metadata and emits an om_model_changed event.

await harness.switchObserverModel({ modelId: 'anthropic/claude-haiku-3.5' })

switchReflectorModel({ modelId })
Direct link to switchreflectormodel-modelid-

Switch the reflector model. Persists the setting to thread metadata and emits an om_model_changed event.

await harness.switchReflectorModel({ modelId: 'anthropic/claude-haiku-3.5' })

getObservationThreshold()
Direct link to getobservationthreshold

Return the observation threshold in tokens from state or the default from omConfig.

const threshold = harness.getObservationThreshold()

getReflectionThreshold()
Direct link to getreflectionthreshold

Return the reflection threshold in tokens from state or the default from omConfig.

const threshold = harness.getReflectionThreshold()

Subagents
Direct link to Subagents

getSubagentModelId({ agentType? })
Direct link to getsubagentmodelid-agenttype-

Retrieve the subagent model ID. Prioritizes per-type settings over the global setting.

const modelId = harness.getSubagentModelId({ agentType: 'explore' })

setSubagentModelId({ modelId, agentType? })
Direct link to setsubagentmodelid-modelid-agenttype-

Set the subagent model ID. Pass an agentType to set a per-type override, or omit it to set the global default. Persists to thread settings and emits a subagent_model_changed event.

// Set global subagent model
await harness.setSubagentModelId({ modelId: 'anthropic/claude-sonnet-4-20250514' })

// Set per-type model
await harness.setSubagentModelId({ modelId: 'anthropic/claude-haiku-3.5', agentType: 'explore' })

Events
Direct link to Events

subscribe(listener)
Direct link to subscribelistener

Register an event listener. Returns an unsubscribe function.

const unsubscribe = harness.subscribe(event => {
switch (event.type) {
case 'message_update':
renderMessage(event.message)
break
case 'tool_approval_required':
showApprovalPrompt(event.toolName)
break
case 'error':
console.error(event.error)
break
}
})

// Later:
unsubscribe()

Events
Direct link to Events

The harness emits events through registered listeners. The following table lists the available event types:

Event typeDescription
mode_changedThe active mode changed.
model_changedThe active model changed.
thread_changedThe active thread changed.
thread_createdA new thread was created.
thread_deletedA thread was deleted.
state_changedHarness state was updated.
agent_startThe agent started processing.
agent_endThe agent finished processing.
message_startA new message started streaming.
message_updateA message was updated with new content.
message_endA message finished streaming.
tool_startA tool call started.
tool_approval_requiredA tool call requires user approval.
tool_updateA tool call was updated with progress.
tool_endA tool call finished.
tool_input_startTool input started streaming.
tool_input_deltaTool input received a streaming delta.
tool_input_endTool input finished streaming.
usage_updateToken usage was updated.
errorAn error occurred.
infoAn informational message was emitted.
follow_up_queuedA follow-up message was queued.
workspace_status_changedThe workspace status changed.
workspace_readyThe workspace finished initializing.
workspace_errorThe workspace encountered an error.
om_statusObservational memory status update.
om_observation_startAn observation started.
om_observation_endAn observation completed.
om_reflection_startA reflection started.
om_reflection_endA reflection completed.
ask_questionThe agent asked a question via the ask_user tool.
plan_approval_requiredThe agent submitted a plan for approval via the submit_plan tool.
plan_approvedA plan was approved.
subagent_startA subagent started processing.
subagent_text_deltaA subagent emitted a text delta.
subagent_tool_startA subagent started a tool call.
subagent_tool_endA subagent finished a tool call.
subagent_endA subagent finished processing.
subagent_model_changedA subagent's model changed.
task_updatedA task list was updated.

Built-in tools
Direct link to Built-in tools

The harness provides built-in tools to agents in every mode:

ToolDescription
ask_userAsk the user a question and wait for their response.
submit_planSubmit a plan for user review and approval.
task_writeCreate or update a structured task list for tracking progress.
task_checkCheck the completion status of the current task list.
subagentSpawn a focused subagent with constrained tools (only available when subagents is configured).