Skip to main content

Code mode on psychoscript

@mastra/psychoscript gives an agent an execute tool. The model writes one JavaScript program that calls the agent's tools, and the program runs on psychoscript, a confined JavaScript interpreter that runs in the agent's process. No sandbox, WebAssembly module, or native addon is involved.

psychoscript can snapshot a running program. The package uses these checkpoints so that nested tools can ask for approval or call suspend(), and so that a durable agent resumes a program after a restart instead of starting it over.

It's a separate package from createCodeMode(), with its own tool and options. Use createCodeMode() when you need a memory limit or a hard isolation boundary for untrusted programs. See Known limits.

Installation
Direct link to Installation

npm install @mastra/psychoscript

The package requires Node.js 22.13 or later and throws on older versions when the tool is created.

Add it to an agent
Direct link to Add it to an agent

Add PsychoscriptCodeModeProcessor to the agent's inputProcessors. On every step it adds execute over the tools the step resolved, including MCP, workspace, and request-scoped tools, and adds a paragraph to the system prompt that explains how to call them. The agent keeps its direct tools.

The examples on this page use two order tools:

src/mastra/tools/orders.ts
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'

const ORDERS_API = 'https://api.example.com/orders'

export const getOrder = createTool({
id: 'getOrder',
description: 'Look up an order by id',
inputSchema: z.object({ id: z.string() }),
outputSchema: z.object({ id: z.string(), total: z.number() }),
execute: async ({ id }) => {
const response = await fetch(`${ORDERS_API}/${id}`)
return response.json()
},
})

export const refund = createTool({
id: 'refund',
description: 'Refund an order',
inputSchema: z.object({ id: z.string(), amount: z.number() }),
outputSchema: z.object({ id: z.string(), refunded: z.number() }),
requireApproval: true,
execute: async ({ id, amount }) => {
const response = await fetch(`${ORDERS_API}/${id}/refund`, {
method: 'POST',
body: JSON.stringify({ amount }),
})
return response.json()
},
})

Add the processor to the agent:

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()],
})

Asked "What do orders A-1, A-2, and A-3 add up to?", the model can answer with one execute call:

const ids = ['A-1', 'A-2', 'A-3']
const orders = await Promise.all(ids.map(id => tools.getOrder({ id })))
return orders.reduce((sum, order) => sum + order.total, 0)

The lookups run in parallel and the model receives the sum.

Use the standalone tool
Direct link to Use the standalone tool

createPsychoscriptTool() builds the same tool over a fixed set of tools. Use it to limit what a program can call:

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

const execute = createPsychoscriptTool({ tools: { getOrder, refund } })

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

The standalone tool doesn't change the system prompt. createInstructions() returns the paragraph the processor adds.

Nested approval and suspend() need an agent run. When you call the tool's execute directly, for example in a test, a nested tool that asks for approval or suspends fails with an error the program can catch.

Inside the program
Direct link to Inside the program

The tool's input is { code: string }. The program has these globals:

  • tools["<name>"](input), or tools.<name>(input) for names that are valid identifiers, calls a tool with the same input and output as a direct call. The call runs the tool's full execute path, with its validation, request context, workspace, tracing, and abort signal.
  • describe(name) returns a tool's input and output types. Tool definitions sent to the model carry no output schema, so this is how a program learns the output shape.
  • search(query) finds tools by keyword in their names and descriptions.
  • console.log, info, debug, warn, and error write to the result's logs.

Programs are plain strict-mode JavaScript and end with return <value>. TypeScript, import, fetch, timers, Intl, private class fields (#x), static blocks, Symbol(), Proxy, and Reflect aren't available, and new works only on classes. The tool description and the system prompt tell the model so.

A program wrapped in a single markdown code fence runs without the fence. When a program fails to parse or uses unsupported syntax, the error message includes psychoscript's suggestions, so the model can fix the program.

A failing nested call throws an error the program can catch, as do an unknown tool name and invalid input. Exceeding maxCalls or maxResultBytes fails the whole program, even when the program catches the error.

Results
Direct link to Results

The tool result has success, result, logs, error, and toolCalls. A program that throws, times out, or exceeds a limit returns success: false instead of failing the tool call.

toolCalls has one row per nested call, with its input, output, status, and duration. Clients receive it and memory stores it, but the model gets the result without it.

For a tool that defines toModelOutput, the program receives what the model would see from a direct call, so it can't pass the model data the tool hides. describe() reports that tool's output as unknown, and the toolCalls rows keep the raw output.

The reference lists every field and the progress events clients receive while a program runs.

Approval and suspend
Direct link to Approval and suspend

A nested call that needs approval, or a nested tool that calls suspend(), pauses the execute call. The package checkpoints the program, and the program continues from that point after the response.

A nested call needs approval when one of these applies:

  • The tool sets requireApproval, or has a per-tool approval function (needsApprovalFn), which then decides alone.
  • The agent's requireToolApproval is a function. It's evaluated for each nested call with the nested tool's name and input.

A boolean requireToolApproval: true gates only the execute call. Approving execute approves the program, and nested calls aren't asked again.

Before asking, the package runs the tool's input validation and its beforeApproval hook, as a direct call does. A failed check fails that nested call without asking. The approver sees the nested tool's name and its full input in the usual approval UI. Approve or decline with approveToolCall() or declineToolCall() on the execute call's toolCallId. Approving runs that nested call and resumes the program. Declining denies the whole execute call, and the program never sees the decline.

For a nested suspend(), the tool-call-suspended chunk carries the nested tool's suspend payload and its resumeSchema as JSON Schema. Resume under the execute call's id, and the nested tool receives the data as resumeData:

const stream = await agent.resumeStream({ size: 'L' }, { runId, toolCallId })

autoResumeSuspendedTools isn't supported: it calls the tool again under a new id, so no checkpoint matches, and execute fails with a CheckpointError.

Before it pauses, the package gives the program's other running calls up to 30 seconds to finish and saves their results in the checkpoint. Calls still running after that are stopped and run again on resume. See human-in-the-loop for approval and resume on the client side.

Durability
Direct link to Durability

Checkpoints go to the cache option, else to the server cache of the Mastra instance the agent is registered with. A finished program deletes its checkpoint.

With the default in-memory cache, approval and suspend work within one process. Resuming after a restart or on another instance needs a persistent cache shared by every instance: Redis, Valkey, or Convex.

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { RedisServerCache } from '@mastra/redis'
import { Redis } from 'ioredis'
import { support } from './agents/support'

export const mastra = new Mastra({
agents: { support },
cache: new RedisServerCache({ client: new Redis(process.env.REDIS_URL!) }),
})

The in-memory cache keeps at most 1,000 entries by default. Under heavy cache use it can evict a paused program's checkpoint before the approval or resume data arrives.

A paused program's checkpoint expires after suspendedCheckpointTtlMs (7 days). What happens next depends on what the program waits for:

  • An approval answered after that starts the program over. Nested calls that finished before the pause run again, and a nested call that needs approval asks again.
  • Resume data for a nested suspend() sent after that makes execute fail with a CheckpointError. Resume data is never accepted without a checkpoint.

Restart recovery
Direct link to Restart recovery

After a restart, a durable agent reruns the interrupted execute call, on both the default and the evented engine. The program resumes from its latest checkpoint and doesn't rerun the nested calls that finished before it.

With checkpointOnMutation (on by default), the package checkpoints right after a nested call to a tool that may change something finishes. Calls that finish together, such as a Promise.all batch, share one checkpoint. A tool counts as read-only only when its MCP annotations set readOnlyHint: true or idempotentHint: true. A tool without annotations counts as mutating. Read-only calls are covered by a checkpoint at least every checkpointIntervalMs (5 seconds) while calls keep finishing. When mastra.shutdown() aborts a running program, the package writes a final checkpoint.

Annotate read-only tools to skip the extra checkpoints. In src/mastra/tools/orders.ts, getOrder only reads:

src/mastra/tools/orders.ts
export const getOrder = createTool({
id: 'getOrder',
description: 'Look up an order by id',
inputSchema: z.object({ id: z.string() }),
outputSchema: z.object({ id: z.string(), total: z.number() }),
mcp: { annotations: { readOnlyHint: true } },
execute: async ({ id }) => {
const response = await fetch(`${ORDERS_API}/${id}`)
return response.json()
},
})

In a measured run, 200 unannotated calls took about 183 ms of checkpointing and wrote about 4.8 MiB. With readOnlyHint: true, they took about 22 ms and wrote nothing.

Nested calls are at-least-once. After a crash, a finished mutating call runs again only if the crash happens after the tool finishes and before its checkpoint is saved. Read-only calls that finished after the last checkpoint run again, and so do calls that were in flight, including every pending call of a Promise.all. Make tools with side effects idempotent.

A checkpoint resumes only on the same psychoscript build. After you upgrade the package, a paused or interrupted program fails instead of resuming. A resumed program can call only the tools it could call when it started. If one of them was removed, a call to it fails with an error the program can catch.

Studio and Mastra Code
Direct link to Studio and Mastra Code

Mastra Code and Factory can run their coding agent with code mode. It's experimental and off by default:

  • In Mastra Code, turn on Experimental Code Mode in /settings, or set "experimentalCodeMode": true in settings.json, then restart.
  • In Factory, pass experimentalCodeMode: true in the Factory config.

Each nested call goes through Mastra Code's approval rules and hooks, as a direct call does. The execute call itself doesn't ask unless you add a rule for it.

Studio, Factory, and Mastra Code show each nested call as a row under the execute call, with its status and duration. Studio and Factory update rows while the program runs. Mastra Code shows them once the call ends.

To answer a nested suspend(), each client shows a form built from the nested tool's resumeSchema. Studio and Factory show it while the run waits. Mastra Code shows it as an inline prompt, and Esc cancels the run. A headless Mastra Code run stops with an error that names the waiting tool.

Known limits
Direct link to Known limits

  • psychoscript has no memory limit. A program can grow the host's heap until the process fails.
  • A single regular expression match can't be interrupted, so it can block the event loop past timeoutMs. Run untrusted programs in a separate process or worker.
  • timeoutMs has no default. When set, it also counts the time the program waits on nested tools.
  • A function-form requireToolApproval set on the agent run can't be evaluated when a durable agent step runs on a different process than the one that started the run. A program resumed there asks for approval of every nested call. A tool's own requireApproval works on every process.
  • If storing a nested approval request fails (core logs a warning and still suspends) and the process then crashes before the workflow saves its snapshot, recovery can treat the approval as granted.
  • When another worker takes over a stalled durable run, the stalled execution's final checkpoint isn't fenced and can overwrite a newer one.
  • After a page reload, a program paused on a nested approval shows only the call it waits on, until the execute call ends.