Skip to main content

PsychoscriptCodeModeProcessor

@mastra/psychoscript adds an execute tool that runs a model-written JavaScript program on psychoscript. PsychoscriptCodeModeProcessor adds the tool over the tools each step resolved. createPsychoscriptTool() builds it over a fixed set of tools. Both take the same options. See Code mode on psychoscript for setup and behavior.

Installation
Direct link to Installation

npm install @mastra/psychoscript

Requires Node.js 22.13 or later.

Usage example
Direct link to Usage example

getOrder and refund are the order tools defined in Code mode on psychoscript.

src/mastra/agents/support.ts
import { Agent } from '@mastra/core/agent'
import { PsychoscriptCodeModeProcessor } from '@mastra/psychoscript'
import { getOrder, refund } from '../tools/orders'

export const support = new Agent({
id: 'support',
name: 'support',
instructions: 'You help customers with their orders.',
model: 'openai/gpt-6.2-sol',
tools: { getOrder, refund },
inputProcessors: [new PsychoscriptCodeModeProcessor()],
})

new PsychoscriptCodeModeProcessor(options)
Direct link to new-psychoscriptcodemodeprocessoroptions

An input processor. On every step it adds the execute tool and a system prompt paragraph, from createInstructions(), that tells the model its other tools are callable in code.

  • The program can call every tool of the step that runs on the host and has an execute function. Provider-defined tools and execute itself are left out.
  • When the step sets activeTools, the program can call only those tools. If activeTools doesn't include execute, the processor adds nothing.
  • The checkpoint saves the names of the tools the program could call when it started, and a resumed program keeps to them. A program whose checkpoint expired starts over with the step's current tools.
  • When the step has no callable tools, the processor adds nothing.

options is PsychoscriptCodeModeOptions. The constructor throws a RangeError for an invalid limit and an Error on Node.js older than 22.

createPsychoscriptTool(options)
Direct link to createpsychoscripttooloptions

Returns Tool<{ code: string }, PsychoscriptCodeModeResult> with the id from options.id. It throws the same errors as the processor constructor. It doesn't add system prompt instructions.

options is PsychoscriptToolOptions: PsychoscriptCodeModeOptions plus tools.

tools:

Record<string, unknown>
The tools the program can call, keyed by the name it calls them by. Accepts Mastra tools from createTool(), AI SDK tools, and tools already converted by an agent. Provider-defined tools and tools without an execute function are skipped.

Options
Direct link to Options

id?:

string
= 'execute'
The tool's id and the name the model calls it by.

description?:

string
Replaces the tool description the model sees.

timeoutMs?:

number
Active-time budget for one program, in milliseconds. Counts the time the program runs, including time it waits on nested tools, added up across resumes. Time paused on an approval or a nested suspend, and time between a crash and recovery, doesn't count. Unset by default.

maxCalls?:

number
= 1000
Most nested tool calls one program can start. The first call over it fails the whole program.

maxConcurrentCalls?:

number
= 16
Most nested tool calls running at once. The rest wait in order.

maxResultBytes?:

number
Largest nested tool result, in JSON bytes. A larger one fails the whole program. Unset by default.

maxOutputBytes?:

number
= 64000
Largest program return value kept in the result, in JSON bytes. A larger one is truncated.

maxLogBytes?:

number
= 16000
Most bytes of console output kept.

maxLogLines?:

number
= 200
Most console lines kept.

maxEventValueBytes?:

number
= 4096
Largest input, output, or log message in a progress event or a toolCalls item, in JSON bytes. A larger value becomes a string ending in TRUNCATION_MARKER. Below 2 bytes not even an empty JSON string fits, so the value is left out: input, output, and a call's error are omitted, and a log line isn't streamed, though the result's logs still keep it.

maxToolCallsBytes?:

number
= 64000
Total JSON bytes of toolCalls in the final result, which memory stores. Rows over the budget lose their input and output first, then are left out and counted in toolCallsOmitted.

cache?:

MastraServerCache
Where checkpoints live. Defaults to the Mastra instance's server cache, or to a cache local to the package when the tool runs without Mastra. Resuming after a restart or on another instance needs a persistent cache such as Redis, Valkey, or Convex.

checkpointOnMutation?:

boolean
= true
Checkpoint right after a nested call finishes, unless the tool's MCP annotations (mcp.annotations) set readOnlyHint: true or idempotentHint: true. A tool without annotations counts as mutating. Calls that finish while a checkpoint is being taken share the next one.

checkpointIntervalMs?:

number
= 5000
Checkpoint at least this often while nested calls keep finishing, in milliseconds. Covers read-only calls, and is also how long a failed checkpoint waits before the next attempt.

runningCheckpointTtlMs?:

number
= 3600000 (1 hour)
How long a checkpoint of a running program is kept, in milliseconds.

suspendedCheckpointTtlMs?:

number
= 604800000 (7 days)
How long a checkpoint of a program waiting for approval or resume data is kept, in milliseconds.

maxCheckpointBytes?:

number
= 16000000
Largest psychoscript snapshot, in bytes. A larger periodic checkpoint is skipped, and a larger suspension fails the program. The cache stores it base64-encoded, about 4/3 of this size.

Counts and durations must be positive integers. maxResultBytes, maxOutputBytes, maxLogBytes, maxLogLines, maxEventValueBytes, and maxToolCallsBytes also accept 0. An invalid value throws a RangeError at construction.

Program globals
Direct link to Program globals

GlobalDescription
toolstools["<name>"](input), or tools.<name>(input) for identifier names, calls a tool and returns a promise. The input crosses as JSON: functions are dropped and promises are awaited. The program receives the tool's output, or what its toModelOutput returns when it defines one. A json or text value is unwrapped, and an error-text or error-json value is thrown.
describe(name)Returns { name, description, signature, input, output }. input and output are TypeScript-like type strings, and output is unknown for a tool with toModelOutput. Throws for an unknown name.
search(query, limit?)Returns { name, description }[] for tools matching the keywords, best first. limit defaults to 10, at most 50.
consolelog, info, debug, warn, and error write to logs. warn and error lines start with [warn] and [error].

A nested call's toolCallId is its key in toolCalls.

Result
Direct link to Result

PsychoscriptCodeModeResult is what memory stores and clients receive in tool-result. The model receives it without toolCalls and toolCallsOmitted.

interface PsychoscriptCodeModeResult {
success: boolean
result?: unknown
logs?: string[]
error?: { message: string; name?: string; line?: number }
toolCalls?: CodeModeToolCall[]
toolCallsOmitted?: number
}

interface CodeModeToolCall {
key: string
tool: string
status: 'success' | 'error' | 'suspended'
input?: unknown
output?: unknown
error?: { message: string; name?: string }
durationMs?: number
}
  • success is false when the program throws, times out, exceeds a limit, or is aborted. error.name is then the psychoscript error kind (for example TimeoutExceeded), AbortError, CheckpointError, or PsychoscriptLimitError. psychoscript's suggestions for the error follow the message on separate lines.
  • A program wrapped in a single markdown code fence runs without the fence.
  • result is truncated to maxOutputBytes.
  • toolCalls lists nested calls in start order with the tool's raw output. A call still running when the program ended has status: 'error' and an error.name of TimeoutError, AbortError, or Interrupted.
  • toolCallsOmitted is absent when no row was left out.

Progress events
Direct link to Progress events

While a program runs, the tool writes CodeModeProgressEvent values through the call's writer. Clients receive each as a tool-output chunk of the execute call.

type CodeModeProgressEvent =
| {
type: 'code-mode-call'
key: string
tool: string
status: 'running'
input?: unknown
startedAt: number
}
| {
type: 'code-mode-call'
key: string
tool: string
status: 'success' | 'error' | 'suspended'
output?: unknown
error?: { message: string; name?: string }
durationMs: number
}
| { type: 'code-mode-log'; message: string }

key is unique per nested call within the run, and the second event for a key updates the same row. Before the tool pauses for a nested approval or suspend, it writes a suspended event for that call. A resumed run replays the events of calls that finished before the pause.

Suspend payload
Direct link to Suspend payload

When a nested tool calls suspend(), execute suspends with a CodeModeSuspendPayload, which arrives as suspendPayload of the tool-call-suspended chunk. For a nested approval, core replaces the payload with its own approval record.

interface CodeModeSuspendPayload {
type: 'code-mode-suspended'
checkpoint: string
call: { key: string; tool: string }
suspendPayload?: unknown
resumeSchema?: Record<string, unknown>
toolCalls?: CodeModeToolCall[]
toolCallsOmitted?: number
}
  • checkpoint is the cache key the resumed call continues from.
  • call is the nested call that suspended.
  • suspendPayload is what the nested tool passed to suspend(), capped at maxEventValueBytes.
  • resumeSchema is the JSON Schema of the resume data the nested tool expects. Absent for tools without a resume schema.
  • toolCalls are the nested calls so far, in the same shape as the result's toolCalls. The payload can reach the model, so the output of a tool with toModelOutput is what that function returns.

Resume with agent.resumeStream(resumeData, { runId, toolCallId }) under the execute call's toolCallId.

Errors
Direct link to Errors

ErrorWhen
CheckpointErrorThrown by execute when a checkpoint is malformed, or when resume data arrives for a call with no checkpoint: the checkpoint expired, or autoResumeSuspendedTools called the tool again under a new id. Also the result's error.name when the program can't be checkpointed to suspend.
PsychoscriptLimitErrorA program exceeds maxCalls or maxResultBytes. The result has success: false and this error, even when the program caught it. The class has option and value.

Exports
Direct link to Exports

ExportDescription
PsychoscriptCodeModeProcessorThe input processor.
createPsychoscriptTool()Builds the execute tool over a fixed set of tools.
createInstructions(toolId)Returns the system prompt paragraph the processor adds.
toModelOutput()Removes toolCalls and toolCallsOmitted from a result. The tool uses it for what the model sees.
DEFAULT_TOOL_ID'execute'
TRUNCATION_MARKERThe text that ends a truncated value.
CheckpointError, PsychoscriptLimitErrorSee Errors.

Types: PsychoscriptCodeModeOptions, PsychoscriptCodeModeProcessorOptions, PsychoscriptToolOptions, PsychoscriptCodeModeResult, CodeModeToolCall, CodeModeCallError, CodeModeProgressEvent, CodeModeCallStartEvent, CodeModeCallEndEvent, CodeModeLogEvent, and CodeModeSuspendPayload.