Add code mode
Let the model write one short script that calls many tools and returns only what matters.
Code mode gives the model one tool, codemode, whose only input is a JavaScript program. The
script calls your resolved tools as await tools.<id>(args), filters and aggregates their results
inside a confined sandbox, and returns a small value. Nested results never enter the conversation;
only the script output and return value do. Use it for paginated, bulk, and aggregate work that
would otherwise cost one model turn per tool call.
Install:
pnpm add @yolk-sdk/codemode@canary @yolk-sdk/agent@canary effect@4.2.0Requires Node.js 22.19 or later. The executors are server-only: ./node on Node, ./cloudflare
in a Cloudflare Worker.
Subpaths
| Subpath | Use for |
|---|---|
@yolk-sdk/codemode | makeCodeModeTool (with the stage global for staged plans), the CodeModeExecutor interface, catalog and search helpers, codeModeStoreFromToolResults, makeClassifierTool |
@yolk-sdk/codemode/node | makePiCodeModeExecutor: a fresh QuickJS (WebAssembly) VM in a worker thread per script |
@yolk-sdk/codemode/cloudflare | makeDynamicWorkerCodeModeExecutor: a fresh Dynamic Worker isolate without network access per script (Cloudflare Workers) |
Set up
Add the code mode tool next to your other tool modules. This fragment assumes host-owned
HostContext, hostModules, and hostContext values.
import { Effect } from 'effect'
import { resolveTools } from '@yolk-sdk/agent/tools'
import { makeCodeModeTool } from '@yolk-sdk/codemode'
import { makePiCodeModeExecutor } from '@yolk-sdk/codemode/node'
// Module scope: one executor per process, so its concurrency cap is per process.
const executor = makePiCodeModeExecutor({ maxConcurrentExecutions: 4 })
const codemode = makeCodeModeTool<HostContext>({ executor })
const program = Effect.gen(function* () {
const toolSet = yield* resolveTools(
[{ id: 'codemode', tools: [codemode] }, ...hostModules],
hostContext
)
return toolSet
})Pass toolSet.tools and the executor layer to the loop as usual. By default the resolved
codemode definition lists the tools scripts can call; with many or changing tools, deliver that
catalog as an instruction instead (see Deliver the catalog as instructions).
Cloudflare Workers
A Worker cannot start the pi executor's worker thread. Run scripts in Dynamic Workers instead: each execution loads a fresh isolate with no network access through a Worker Loader binding, evaluates the same prelude, tools guard, and rejection codes as the Node executor, and calls your tools back over RPC.
import { env } from 'cloudflare:workers'
import { makeCodeModeTool } from '@yolk-sdk/codemode'
import { makeDynamicWorkerCodeModeExecutor } from '@yolk-sdk/codemode/cloudflare'
// The binding is read when a script runs, so the executor can live at module scope.
const executor = makeDynamicWorkerCodeModeExecutor({ loader: () => env.LOADER })
const codemode = makeCodeModeTool<HostContext>({ executor })Declare the Worker Loader binding in the Worker's configuration ("worker_loaders": [{ "binding": "LOADER" }] in Wrangler; the binding name is yours). memoryLimitBytes and a concurrency cap do
not apply.
cpuMs(default 500) becomes the isolate's CPU limit and is the real ceiling of a script; a script past it fails with atimeout. The timeout and abort signal only answer the caller early: a synchronous loop keeps running until its CPU limit.- An execution that ends at its CPU limit (or times out, or is aborted) keeps the output the script printed before its last tool or global call, which is when output reaches your Worker; output printed after that call is lost.
- When an execution ends, tool calls still pending are rejected at once and their signal aborts, and later calls are rejected without running, so an unawaited call never keeps a Dynamic Worker in flight (Cloudflare allows 4 per request, 10 per Durable Object).
- Loader and isolate failures reach the caller as fixed messages, never the runtime's error text (see Log executor failures).
- Every execution loads one Dynamic Worker, and each is billed.
- A tool's
streamedArgument(for examplefile_save'scontent) of 64 Ki characters or more reaches your Worker as a byte stream beside the call, never as one JSON string; the tool reads it withtoolStreamedArgument. Counting and encoding it is the script's CPU.
Log executor failures
Both executors answer their own failures (not the script's) with fixed messages, so runtime error
text, which may carry host details or secrets, never reaches the script or the model. Pass
onInternalError to log the original error:
const executor = makeDynamicWorkerCodeModeExecutor({
loader: () => env.LOADER,
// Host logs only: `cause` may carry secrets.
onInternalError: ({ stage, cause }) => logger.error('code mode executor failed', { stage, cause })
})stage is load (the sandbox could not be created or loaded), isolate (it failed while
running), cpu-limit (a Dynamic Worker past its CPU limit), or host-call (a Dynamic Worker
call's RPC to your Worker failed). makePiCodeModeExecutor takes the same option and reports load
and isolate. It is called once per such failure, never for script errors, tool rejections,
timeouts, or aborts, and whatever it throws is ignored. A script can fake a host-call report (its
isolate sends it), so at most 10 are accepted per execution.
Next.js
Keep the engine out of the bundle so its worker file and quickjs.wasm stay on disk:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
serverExternalPackages: ['@yolk-sdk/codemode', '@earendil-works/pi-codemode', 'quickjs-wasi']
}
export default nextConfigNext file tracing then includes the worker file and the wasm module automatically. If you bundle
the engine anyway, pass wasm and workerUrl to makePiCodeModeExecutor.
Vercel Workflow
Run the code mode call inside your tool-batch step ('use step'), like any other tool call. Never
run scripts inside a 'use workflow' function: the workflow sandbox cannot host the engine, every
nested call would become durable events, and a busy loop could not be stopped.
- Pass
deadlineso the script timeout fits the step's remaining function budget. The timeout is clamped to the deadline minus 5 seconds and never drops below 1 second. - Steps are at-least-once: supply a durable tool ledger (see Survive step re-execution). Step retry settings alone do not stop a redelivered step from running the script again.
- The step output holds the bounded script result and the bounded nested-call record, never raw nested results.
const codemode = makeCodeModeTool<HostContext>({
executor,
deadline: context => context.stepDeadlineMs // epoch milliseconds, host-owned
})Choose what scripts can call
Exposure is set on each tool with callableBy and, for code-mode-only tools, discovery:
| Setting | Model calls it | Scripts call it | In the codemode description |
|---|---|---|---|
callableBy: 'all' (default) | yes | yes | one line: how scripts call it and what it resolves to (outside the budget) |
callableBy: 'model' | yes | no | no |
callableBy: 'codemode', discovery: 'listed' | no | yes | TypeScript declaration, within the inline budget |
callableBy: 'codemode', discovery: 'search' | no | yes | never; scripts find it with searchTools() |
callableBy: 'codemode', discovery: 'pinned' | no | yes | TypeScript declaration, always, outside the inline budget |
An all tool with loading: 'deferred' (see Defer rarely used tools)
is not in the model's context until loaded, so the catalog treats it like a search tool.
import { Effect } from 'effect'
import { makeTool } from '@yolk-sdk/agent/tools'
// With `output`, explicit type arguments are three: context, parameters, output.
const listInvoices = makeTool<HostContext, typeof ListInvoicesParams, typeof InvoicePage>({
name: 'list_invoices',
description: 'List invoices, newest first, one page at a time.',
parameters: ListInvoicesParams, // host-owned Effect Schema
output: InvoicePage, // calls resolve to the JSON encoding of this shape
access: 'read',
callableBy: 'codemode',
discovery: 'search',
execute: ({ params }) => listInvoicePage(params).pipe(Effect.map(page => ({ output: page })))
})- Approval, input, interaction, and background tools, and the
questionandsubagenttools, never run from code mode. Marking themallbehaves asmodel; marking themcodemodefails resolution, except an approval-gated tool you markstaging, which may be stage-only. Stageable tools can be staged for one review instead (see Stage approval-gated writes). codemode-only tools are never sent to model providers.- Listed tools fill an inline budget (default 3,000 estimated tokens) fairly across tool modules:
each round every module places its cheapest remaining tool.
alltools are already declared to the model, so their lines sit outside the budget. searchtools contribute nothing to the description: no namespace heading, hint, or count. Adding or removing them, even a whole module of them, leaves the description byte-identical and the prompt cache intact. One fixed line always tells scripts to find unlisted tools withsearchTools()(each hit has its call signature) ordescribeNamespace().- Give a module a
description({ id, description, tools }) to show it under the module's heading, return it fromdescribeNamespace(), and make it searchable. - Tools that poll (no timers in scripts) should stay
callableBy: 'model'until they offer a wait parameter.
Connector and MCP tools
Generated tools take the same exposure (callableBy, discovery, loading) through an exposure
option: one value for every tool, or a resolver per tool. Connector modules resolve per action ((actionId, action) => exposure, where
action carries the declared access); MCP definitions resolve per listed tool
((tool, serverName) => exposure). This marks every connector action as a code-mode-only search
tool:
import { makeConnectorToolModule } from '@yolk-sdk/connectors/agent'
import { GithubConnector } from '@yolk-sdk/connectors/github'
const github = makeConnectorToolModule<HostContext>(GithubConnector, {
integration: githubIntegration, // host-owned
layer: connectorLayer, // host-owned
exposure: { callableBy: 'codemode', discovery: 'search' }
})For MCP, pass exposure to mcpToolToToolDef or in the listing options; each resolved def
then carries it:
import { listMcpServerTools } from '@yolk-sdk/mcp/client'
const tools = listMcpServerTools(serverConfig, {
exposure: tool =>
tool.annotations?.['readOnlyHint'] === true
? { callableBy: 'codemode', discovery: 'search' }
: { callableBy: 'model' }
})The fail-closed rules above still apply: resolution fails when an exposure contradicts the tool
(for example codemode on a non-stageable registration that requires approval).
Deliver the catalog as instructions
makeCodeModeTool({ executor, catalog: 'instructions' }) keeps the codemode description
invariant and delivers the catalog as a host instruction instead: every namespace with its tool
count and description, listed tools within the inline budget, and pinned tools always. A
changed catalog is appended to the conversation, whole, so connecting or disconnecting tools never
rewrites the cached request prefix (tool definitions and earlier messages).
const codemode = makeCodeModeTool<HostContext>({ executor, catalog: 'instructions' })
const toolSet =
yield * resolveTools([{ id: 'codemode', tools: [codemode] }, ...hostModules], hostContext)
// run() appends the catalog instruction when it changed:
run({ messages, systemPrompt, tools: toolSet.tools, instructions: toolSet.instructions, model })- Durable hosts driving
runModelTurnappend and persistinstructionMessages(transcript, toolSet.instructions)from@yolk-sdk/agent/loopbefore each model step (see Host instructions). - Hosts that cannot append messages to their conversation can render the instruction into the
system prompt (
instruction.render(instruction.state), only whileinstruction.stateis defined:undefinedrenders the removal notice); a catalog change then invalidates the cache from the system prompt on. - Custom compaction must keep
latestInstructionMessages(...)after its summary, as window compaction does.catalog: 'description'(the default) keeps the catalog in the description.
What scripts see
codeis the body of an async function: top-levelawaitandreturnwork. Simple TypeScript annotations are stripped; enums and namespaces are rejected with a clear error.tools.<id>(args)runs the tool through the resolved tool set with your host context: inputs are decoded, disabled tools stay unavailable, and registration wrappers run. A tool with an output schema resolves to its declared value (a typed result without a value rejects withreturned an invalid result); a tool without one resolves to its text (string). A call rejects with anErrorwhen the tool returns an error result, witherror.codewhen the tool reports a code. Unknown names suggest close matches. Calls still running when the script ends are cancelled.- Files are typed fields of results:
FileRef { fileId, name, mimeType, size }orFileUnavailable { unavailable, name, mimeType }. Script values never contain file labels. Pass thefileIds to other tools; file bytes never enter the script (Move files between tools). - Arguments make a JSON round trip, and the tool decodes them exactly as it decodes model calls:
- The argument is read once, the way
JSON.stringifyreads it (each getter andtoJSONruns once), into a checked JSON copy, and that copy is what the call sends. - A key set to
undefinedis absent, andnullon an optional argument means absent. - An unknown key rejects the call with a hint that names the keys allowed there.
- Values JSON would silently change reject inside the script before the call is made (it never
runs and is not recorded):
NaN,Infinity, invalidDates,undefinedor functions in arrays,Map,Set, functions, symbols, bigints, cycles, and class instances. For exampletools.search: argument at limit is NaN; pass a finite number or omit the key. - Values with
toJSONpass as their JSON, checked by the same rules: a validDatebecomes its ISO string. An error thrown by a getter ortoJSONrejects the call with that error. - An argument with more than 100000 values or nested more than 64 levels deep is rejected too
(
tools.search: argument has more than 100000 values; split the work across calls). - The checks use built-ins captured before the script runs, and the copy has no prototypes, so
a script that changes
Array.prototype,Date, or other built-ins cannot change what is checked or sent.
- The argument is read once, the way
- A rejected call's message starts with the call's label:
tools.<id>, ortools["<name>"]for a tool whose identifier an earlier tool already uses (scripts call it by that name when the name is still free; a tool whose identifier and name are both taken is unreachable). Error results, argument rejections,beforeNestedCallfailures, and themaxNestedCallslimit read<label>: <message>. Only the message anderror.code(a tool's error code, or the code of aCodeModeNestedCallRefused) cross into the script.ToolResult.nestedCallsrecords the tool's own message without the prefix. - A nested call that is interrupted rejects with
<label> was cancelled.; one whose tool fails with a defect rejects with<label> failed unexpectedly.and is recorded aserror. - A nested call that paused for a person's input
(an MCP server asking a form) rejects like any error result, with
error.code === 'input_required'. It has not completed. Whether or not the script caught the rejection, the result'sstructuredContent.codemode.inputRequiredlists every such pause (ToolInputRequiredRefs{ reviewToolName, pauseIds }, merged per review tool), and a notice after the bounded output names the review call, for examplereview_input({"pauseIds":["p1"]}). Work that needs the value continues in a new script from the review result, never by calling the tool again. - Globals:
text(),console.log(),image(),exit(),ALL_TOOLS,searchTools(query, { limit?, namespace? }),describeTool(name),describeNamespace(name), andstore(key, value)/load(key).searchToolshits include a one-linesignature(argument and result types), so scripts call a found tool withoutdescribeTool. The description tells the model to call a tool whose exact name it already knows without searching, and never to call a tool in the same script that found it (an unseen hit could be a write). Large fetched data can be kept withstore()and filtered later instead of fetched again. - No Node.js, network, filesystem,
require,fetch, or timers.
The result starts with Script completed or Script failed, then the wall time, the output in
order, and the JSON return value. A failed script keeps its partial output, the error, and the tool
calls already made, which are not undone. ToolResult.nestedCalls records every nested call (id,
name, compact arguments, status, duration, truncated error, usage) for your audit log, up to
maxNestedCalls entries, with per-status counts over all calls; the model never sees it.
toolResultMessageFromResult drops nestedCalls and usage, and the loop does not add
ToolResult.usage (nested and classifier token spend) to run usage; read both from the ToolResult
or tool events. ToolResult.usageIncomplete: true means that sum under-counts: a nested call
reported incomplete usage (its own usageIncomplete, kept on its record), for example a
classification the classifier answered without usage.
Survive step re-execution
Resolve tools with a durable ledger (resolveTools(modules, context, { ledger: { store } }), see
Ledger writes). The codemode call is
itself ledgered, so a re-executed call never runs its script again:
-
Completed earlier: the stored result is returned.
-
Still running in another execution: the call waits for it, up to
maxWaitMsordeadline. -
Abandoned (the earlier execution crashed): an interrupted error result lists that script's ledgered nested calls as applied, failed, or unknown (started without a recorded result), says they were not undone, and asks the model to verify before repeating work. The model sees the text listing; hosts get the same entries in
structuredContent.codemode:// structuredContent of an interrupted result (CodeModeStructuredContent) type Interrupted = { codemode: { ok: false interrupted: true interruptedCalls: { // In sequence order. args: compact JSON, cut with a trailing '…' (then no longer JSON). calls: Array<{ key: string // ledger key, `<toolCallId>/<seq>` toolName: string args: string status: 'applied' | 'failed' | 'unknown' }> complete: boolean // false when calls were dropped or arguments cut (here or by the ledger) counts: { applied: number; failed: number; unknown: number } // every entry, dropped too } } }It is plain JSON (
CodeModeStructuredContent,CodeModeInterruptedCalls) bounded likenestedCalls: at mostmaxNestedCallscalls, 8 KiB of arguments per call, 32 KiB in total.failedmeans the call recorded aToolErroror an error result;unknownmeans it started without a recorded result and may have been applied. When the ledger cannot list the nested calls, the result stays interrupted, tells the model they may already have been applied, and carriesinterruptedCallsUnavailable: trueinstead ofinterruptedCalls.
Nested write calls are ledgered under <toolCallId>/<seq> and receive idempotencyKey. Calls the
ledger policy skips (by default read-only calls) are not listed. Scripts are never replayed.
Stage approval-gated writes
Bulk work on an approval-gated tool would otherwise need one approval per call. Mark the tool stageable, and a script can record the calls into a plan that a person reviews once, unticking any they do not want. Nothing runs while the script runs.
import { Effect } from 'effect'
import { ToolApprovalPolicy } from '@yolk-sdk/agent/protocol'
import { makePlanReviewTool, makeTool, resolveTools } from '@yolk-sdk/agent/tools'
const updateRecord = makeTool<HostContext, typeof UpdateRecordParams>({
name: 'update_record',
description: 'Update the fields of a record.',
parameters: UpdateRecordParams, // host-owned Effect Schema, for example { id, status }
access: 'write',
approval: ToolApprovalPolicy.make({ mode: 'manual' }),
// Optional, side-effect free: the before → after diff shown on approvals and plan reviews.
changePreview: ({ params, context }) => describeRecordChange(context, params), // host-owned
staging: {
// Optional, side-effect free. A precheck failure rejects the person's selection.
precheck: ({ params, context }) => assertStillExpected(context, params) // host-owned
},
execute: ({ params, context, idempotencyKey }) => applyUpdate(context, params, idempotencyKey)
})
const toolSet = Effect.gen(function* () {
return yield* resolveTools(
[{ id: 'host', tools: [codemode, makePlanReviewTool<HostContext>()] }, recordsModule],
hostContext,
{
interactionHost: scopedReceipts, // host-owned InteractionHost
plans: { store: planStore }, // host-owned ToolPlanStore, scoped to the conversation
ledger: { store: ledgerStore }
}
)
})makeInMemoryToolPlanStore is the reference store for tests; production stores persist plans
(Schema.toCodecJson(ToolPlan)) where later turns can read them. A script then stages calls:
const records = await tools.list_records({ status: 'draft' })
for (const record of records) {
await stage('update_record', { id: record.id, status: 'published' })
}
return records.lengthstage(name, args)validates the arguments with the tool's decoder and resolves to{ staged: true, key, index }. It executes and ledgers nothing.- Once a script stages, it may only run
readtools; a script that already ran a write tool cannot stage. Duplicate calls (same tool and arguments) are rejected. A plan holds at most 500 calls and 1 MiB of arguments (plans: { maxCalls, maxArgsBytes }). The code mode optionstaging: { maxCalls }can only lower it. Calls past a limit are rejected, never truncated. - A successful script saves the plan once and its result tells the model to call
review_plan({ planId, planDigest }); hosts readstructuredContent.codemode.plan({ id, digest, count, reviewToolName }). A failed script discards its staged calls. stageexists only when the resolution hasplans, aninteractionHost, and one plan review tool. Voice and subagent resolutions without them never get it.staging: falseturns it off for one code mode tool.
The review is an action-backed interaction: render the
tool_plan_review kind, accept { selectedKeys }, and resume as for any interaction. Yolk then
applies exactly the selected calls in staged order, once; a call that pauses for input is reported
input_required and does not stop the apply. Each staged call is previewed with the
tool's changePreview, the same change preview direct
approvals show.
Per-call authority: applied plan calls do not pass through beforeNestedCall or decorators
around your ToolExecutor: they run inside the review action. Pass the same per-call authorizer as
makePlanReviewTool({ beforeCall }); it is the only per-call host hook for applied calls.
Stage-only tools
A stageable approval-gated tool may be callableBy: 'codemode' (usually with
discovery: 'search'): it is never declared to the model and costs no context. Scripts find it
with searchTools() (hits carry stageOnly: true and the stage() signature), read it with describeTool() (rendered as the
stage() call), and can only stage() it; a direct tools.<name>() call rejects with a hint to
stage it. Resolution warns when a stage-only tool resolves without plans, where it would be
unreachable. Model-callable stageable tools (callableBy: 'all', deferred or not) are searchable,
describable, and stageable from scripts the same way; deferred ones are not named in the
description's Stageable list.
Make tools ready for code mode
Scripts can only use what a tool declares and returns. For each tool scripts may call:
- Declare
output(an Effect Schema) and return{ output: value }: Yolk encodes it withSchema.toCodecJson(output)(soChunkandDateTimereach scripts as arrays and ISO strings) and a value that does not encode fails the call. Files areToolFilefields: returnnew FileBytes({ bytes, name, mimeType })and scripts get aFileRef. Tools withoutoutputreturn{ content }, and scripts get their text. Fail withmodelVisibleToolError({ code })to give scriptserror.code. See ADR 0013. resolveToolschecks every typed result against its output schema before scripts see it (excess properties rejected); a value that does not match makes the call reject withreturned an invalid result. Raw registrations that setdef.outputSchemasupplydecodeOutput(toolOutputDecoder(schema), ormcpToolOutputDecoderfor MCP tools), or resolution fails withoutput_validation_required.- Give each module a
description({ id, description, tools }): scripts read it under the namespace heading, fromdescribeNamespace(), and throughsearchTools(). - Custom
invalidParamsMessagecallbacks should end withwithToolArgumentsErrorHint(message, error)from@yolk-sdk/agent/tools, so an unknown key names the allowed keys and a number or boolean sent as a string names the literal to send (the default message already does). - Keep polling, outbound-message, and human-in-the-loop tools
callableBy: 'model'.
Package tools follow these rules: connector modules take the connector description (override with
the description option) and return JSON-encoded action results, knowledge tools declare
KnowledgeLookupOutput/KnowledgeManageOutput, and the sandbox tool declares SandboxToolOutput.
Keep state between scripts
store() writes from successful scripts come back in
structuredContent.codemode.storeWrites. Rebuild the store from the transcript and pass it back
with loadStore; this works the same in stateless routes, Workflow steps, and Durable Objects:
import { Effect } from 'effect'
import { codeModeStoreFromToolResults, makeCodeModeTool } from '@yolk-sdk/codemode'
const codemode = makeCodeModeTool<HostContext>({
executor,
// `{ toolName, result }` for prior tool results, oldest first (host-owned lookup).
loadStore: context => Effect.succeed(codeModeStoreFromToolResults(context.priorToolResults))
})codeModeStoreFromToolResults applies only results whose toolName is the code mode tool's name
(default codemode; pass { toolName } if you renamed it), so another tool cannot inject store
writes by returning code-mode-shaped structuredContent. Transcript ToolResultMessages carry no
tool name: pair each with the name of the assistant tool call it answers.
Values are small JSON only: 256 KiB per value and 1 MiB in total (characters of JSON, as the engine counts them). Scripts get an error beyond them, and the rebuilt store drops offending writes and keeps the previous value.
Classify items from scripts
makeClassifierTool exposes a classifier model as a codemode +
listed read tool named classify. Scripts classify one item per call; calls beyond
maxConcurrency (default 100 per script, keyed by the parent tool call id) queue. All scripts
together also share a process cap: processLimiter defaults to defaultClassifierProcessLimiter
(200 concurrent classifications per process, shared by every classifier tool); build a separate
one with makeClassifierConcurrencyLimiter(max) or pass false to disable it.
import { Effect } from 'effect'
import { ClassifierModel } from '@yolk-sdk/agent/classification'
import { makeClassifierTool } from '@yolk-sdk/codemode'
const classifyTool = Effect.gen(function* () {
const model = yield* ClassifierModel
return makeClassifierTool<HostContext>({ classify: model, maxConcurrency: 100 })
})A script can then triage a whole inbox in one tool call:
const messages = await tools.list_messages({ folder: 'inbox', limit: 50 })
const results = await Promise.all(
messages.map(message =>
tools.classify({
state: { subject: message.subject, from: message.from },
questions: { urgent: { type: 'boolean', instructions: 'Does this need a reply today?' } }
})
)
)
return messages.filter((_, index) => results[index].answers.urgent.probability > 0.7).map(m => m.id)Each call reports token usage on the nested-call record; the cost (costUsd) stays in the
classifier result's structuredContent.usage. Classifier errors reject the call with a safe
message. The classifier tool is a read marked invokesModel: true, so
readOnlyNestedCallGate refuses it unless its admitModelCall admits it.
Run a script outside a model turn
A host can run a script itself, with no model and no tool call, for example a background check on a
schedule. runCodeModeScript runs it over the same tools, dispatch path, limits, deadline clamp,
store, and nested-call hooks as the codemode tool (which runs every script through it), and
returns what happened as data instead of model-visible text.
import { Effect } from 'effect'
import { resolveTools } from '@yolk-sdk/agent/tools'
import { readOnlyNestedCallGate, runCodeModeScript } from '@yolk-sdk/codemode'
import { makePiCodeModeExecutor } from '@yolk-sdk/codemode/node'
const executor = makePiCodeModeExecutor()
const runCheck = (checkId: string, code: string, state: unknown) =>
Effect.gen(function* () {
const toolSet = yield* resolveTools(hostModules, hostContext) // host-owned
const result = yield* runCodeModeScript({
executor,
code,
// Nested calls get ids `<parentCallId>/<seq>` (their ledger keys): pick an id unique per run.
nested: toolSet.nestedExecutor({ parentCallId: checkId }),
parentCallId: checkId,
store: { state }, // the script reads it with load('state')
limits: { timeoutMs: 60_000 },
beforeNestedCall: readOnlyNestedCallGate()
})
// A refused call fails the check even when the script caught the rejection.
if (result.calls.some(call => call.refusal !== undefined)) return { failed: 'refused call' }
return result.ok ? { value: result.value } : { failed: result.error.message }
})ResolvedToolSet.nestedExecutor({ parentCallId })gives the nested tool access a nested-access registration gets, bound toparentCallIdinstead of a tool call: the sametools(code-mode callable, outside the fail-closed set),execute(decoding, registration wrappers, the ledger), andaccess. It never offers staging: a staged plan needs a model turn to review it.- The result:
ok;value(the script's JSON return value) andstoreWriteswhen it succeeded,error(kind,message) when it failed;output(text and images, unbounded);calls(every nested call with its id, arguments, status, effective access, error, andrefusal);nestedCalls(the bounded record),usage,usageIncomplete,inputRequired,timeoutMsandwallTimeMs. It never fails; interrupting the effect aborts the script and cancels running nested calls. deadlineis epoch milliseconds, as for the tool;storeis whatload(key)reads. Pass inputs such as a carried-over state throughstore.- The
codemodetool keeps the return value in its model-visible text only:structuredContent.codemodestays{ ok, storeWrites?, plan?, inputRequired? }, because it is persisted with the transcript and an unbounded value would grow it. Hosts that need the value run the script withrunCodeModeScript.
Allow only reads
readOnlyNestedCallGate(options?) is a ready-made beforeNestedCall for runCodeModeScript or
makeCodeModeTool. It admits a call only when its effective access is read (a registration's
isReadCall counts, so a list call of a write tool passes) and the tool is neither
approval-gated nor marked invokesModel. It
fails closed: a tool without effective access is refused. Every refusal is a
CodeModeNestedCallRefused whose code the script sees as error.code and the call's refusal
keeps:
| Code | Refused call |
|---|---|
unavailable | the resolution has no such script-callable tool |
approval_required | the tool is approval-gated |
invokes_model | the tool calls a model when it runs (for example classify) |
not_read | the call's effective access is write or destructive |
Two options relax one check each. Both are predicates over the same input as beforeNestedCall
({ call, tool, access }) and admit when they return true:
admitrelaxes only the access check, for a write the host knows only reads (for example a remote tool its server marks read-only):readOnlyNestedCallGate({ admit: ({ tool }) => readOnlyRemoteTools.has(tool.def.name) }).admitModelCallrelaxes only the model check, for model calls whose cost the host accepts, such as a boundedclassifybut not an open-ended child run:readOnlyNestedCallGate({ admitModelCall: ({ tool }) => tool.def.name === 'classify' }). It is asked only about tools markedinvokesModel. An admitted call still has to read (effective accessread, oradmit), so a write markedinvokesModelis still refused asnot_read; approval-gated and unavailable tools stay refused.
A hook that throws or dies (an admit or admitModelCall that throws included) refuses the call
too, with the message The call could not be admitted. and no code, so counting refusals counts
it.
Your own beforeNestedCall hooks receive the same input (call, tool, access, and with
makeCodeModeTool the context) and may fail with a plain message or a
new CodeModeNestedCallRefused({ code, message }).
Limits
| Limit | Default | Notes |
|---|---|---|
timeoutMs | 120000 | includes nested calls and queue time; clamped by deadline |
memoryLimitBytes | 64 MiB | VM heap cap; allocations beyond it fail inside the script |
maxNestedCalls | 256 | later calls reject and do not run; also sizes the nestedCalls record (at most 4096) |
maxOutputChars | 40000 | the result keeps the head and tail with an omission marker in between |
maxImages | 8 | later images are dropped with an omission note |
maxImageBytes | 4 MiB | base64 image data in total; an image beyond it is dropped with a note |
Set them with makeCodeModeTool({ limits: { ... } }). The executor's maxConcurrentExecutions
(default 4) caps concurrent scripts per executor; Fluid compute shares instances between requests.
If an executor does not stop at timeoutMs, the tool returns a timeout failure 5 seconds later
and aborts the executor's signal.
Security notes
-
Scripts run in a fresh QuickJS VM compiled to WebAssembly, in a fresh worker thread. The only capability is calling the injected tools and helpers; timeouts, aborts, and runaway regular expressions stop the worker without blocking your event loop.
-
Nested calls are ordinary tool calls with your host context. Code mode adds no permissions: the tools you expose to scripts are the authority you grant, and the
codemodetool itself iswriteaccess. -
Decorators you wrap around the
ToolExecutor(outsideResolvedToolSet.execute), such as a per-call run-admission or stop check, see only thecodemodecall, never the nested calls of its script. Put per-call checks inbeforeNestedCallor in registration-level wrappers, and the same check in the plan review'sbeforeCallfor staged calls:const codemode = makeCodeModeTool<HostContext>({ executor, // Fails with a message to reject the nested call; it is recorded as an error and never runs. beforeNestedCall: ({ call, context }) => assertRunActive(context, call), // host-owned // Observes each admitted call: outcome 'success' | 'failure' | 'interrupted'. A failing hook // (even one that throws) is logged and never changes the call's result. afterNestedCall: ({ call, outcome, durationMs, context }) => auditNestedCall(context, call, outcome, durationMs) // host-owned }) -
A script fails once it has printed 16 Mi characters or 100,000
text(),image()andconsole.*items, on both executors. The result is bounded afterwards (maxOutputChars,maxImages,maxImageBytes). -
Built-ins are frozen and built-in globals are read-only before the script runs, on both executors, so scripts cannot patch them (assignments fail silently, or throw in strict code).
-
The worker inherits a copy of the host's
process.env. Scripts cannot read it (the VM has noprocess), but keep that in mind for engine-level vulnerabilities. -
The VM's clock and
Math.randomcome from the engine's WASI shim. -
Approvals inside scripts are not supported; approval-gated tools never run from code mode. Staged calls run only after a person accepts a plan review, through the same execute path and ledger.
-
Node prints one
ExperimentalWarningper process forstripTypeScriptTypes.
Other runtimes
CodeModeExecutor is a plain interface. Hosts on Workers or other runtimes can supply their own
engine and keep the same tool, catalog, store, and result handling. Custom executors must apply the
same argument rules as the pi executor (see What scripts see) and prefix
rejections with CodeModeExecutorTool.callLabel, which makeCodeModeTool sets.