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.
InstallationDirect link to Installation
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/psychoscript
pnpm add @mastra/psychoscript
yarn add @mastra/psychoscript
bun add @mastra/psychoscript
Requires Node.js 22.13 or later.
Usage exampleDirect link to Usage example
getOrder and refund are the order tools defined in Code mode on psychoscript.
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
executefunction. Provider-defined tools andexecuteitself are left out. - When the step sets
activeTools, the program can call only those tools. IfactiveToolsdoesn't includeexecute, 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:
createTool(), AI SDK tools, and tools already converted by an agent. Provider-defined tools and tools without an execute function are skipped.OptionsDirect link to Options
id?:
description?:
timeoutMs?:
maxCalls?:
maxConcurrentCalls?:
maxResultBytes?:
maxOutputBytes?:
maxLogBytes?:
maxLogLines?:
maxEventValueBytes?:
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?:
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?:
checkpointOnMutation?:
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?:
runningCheckpointTtlMs?:
suspendedCheckpointTtlMs?:
maxCheckpointBytes?:
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 globalsDirect link to Program globals
| Global | Description |
|---|---|
tools | tools["<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. |
console | log, 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.
ResultDirect 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
}
successisfalsewhen the program throws, times out, exceeds a limit, or is aborted.error.nameis then the psychoscript error kind (for exampleTimeoutExceeded),AbortError,CheckpointError, orPsychoscriptLimitError. 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.
resultis truncated tomaxOutputBytes.toolCallslists nested calls in start order with the tool's raw output. A call still running when the program ended hasstatus: 'error'and anerror.nameofTimeoutError,AbortError, orInterrupted.toolCallsOmittedis absent when no row was left out.
Progress eventsDirect 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 payloadDirect 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
}
checkpointis the cache key the resumed call continues from.callis the nested call that suspended.suspendPayloadis what the nested tool passed tosuspend(), capped atmaxEventValueBytes.resumeSchemais the JSON Schema of the resume data the nested tool expects. Absent for tools without a resume schema.toolCallsare the nested calls so far, in the same shape as the result'stoolCalls. The payload can reach the model, so the output of a tool withtoModelOutputis what that function returns.
Resume with agent.resumeStream(resumeData, { runId, toolCallId }) under the execute call's toolCallId.
ErrorsDirect link to Errors
| Error | When |
|---|---|
CheckpointError | Thrown 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. |
PsychoscriptLimitError | A 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. |
ExportsDirect link to Exports
| Export | Description |
|---|---|
PsychoscriptCodeModeProcessor | The 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_MARKER | The text that ends a truncated value. |
CheckpointError, PsychoscriptLimitError | See Errors. |
Types: PsychoscriptCodeModeOptions, PsychoscriptCodeModeProcessorOptions, PsychoscriptToolOptions, PsychoscriptCodeModeResult, CodeModeToolCall, CodeModeCallError, CodeModeProgressEvent, CodeModeCallStartEvent, CodeModeCallEndEvent, CodeModeLogEvent, and CodeModeSuspendPayload.