vercel/ai · error · CodeModeSourceTooLargeError

CODE_MODE_SOURCE_TOO_LARGE

CODE_MODE_SOURCE_TOO_LARGE

Error message

Code mode source exceeds the ${maxBytes} byte size limit.

What it means

runCodeMode enforces an execution policy limit maxSourceBytes (default 256 KiB) on the JavaScript source passed to the sandbox. assertSourceSize measures the source in bytes (Buffer.byteLength, so multibyte characters count fully) and throws CodeModeSourceTooLargeError with actual and maximum byte counts when the limit is exceeded. The check is skipped only when maxSourceBytes is not a valid positive integer run limit.

Source

Thrown at packages/code-mode/src/run-code-mode.ts:200

    maxConsoleOutputBytes:
      policy.maxConsoleOutputBytes ?? DEFAULT_MAX_CONSOLE_OUTPUT_BYTES,
    maxSourceBytes: policy.maxSourceBytes ?? DEFAULT_MAX_SOURCE_BYTES,
    maxToolInputBytes: policy.maxToolInputBytes ?? DEFAULT_MAX_TOOL_INPUT_BYTES,
    maxToolOutputBytes:
      policy.maxToolOutputBytes ?? DEFAULT_MAX_TOOL_OUTPUT_BYTES,
    maxBridgeRequests: policy.maxBridgeRequests ?? DEFAULT_MAX_BRIDGE_REQUESTS,
    maxInFlightBridgeRequests:
      policy.maxInFlightBridgeRequests ?? DEFAULT_MAX_IN_FLIGHT_BRIDGE_REQUESTS,
  };
}

function assertSourceSize(source: string, maxBytes: number): void {
  if (!isValidRunLimit(maxBytes)) {
    return;
  }
  const bytes = Buffer.byteLength(source);
  if (bytes > maxBytes) {
    throw new CodeModeSourceTooLargeError(bytes, maxBytes);
  }
}

function createCodeModeSource(js: string, toolNames: string[]): string {
  const bindings = Object.fromEntries(
    toolNames.map((toolName, index) => [toolName, `__codeMode.tool${index}`]),
  );
  const bindingSource = Object.entries(bindings)
    .map(([name, reference]) => `${JSON.stringify(name)}:${reference}`)
    .join(',');
  return `const __codeModeBindings={${bindingSource}};const tools=new Proxy(Object.create(null),{get(_target,name){const binding=__codeModeBindings[name];return typeof binding==="function"?(input)=>binding(input):(input)=>__codeMode.missing(String(name),input);}});const __codeModeResult=await(async()=>{\n${js}\n})();if(__codeModeResult===undefined)return undefined;return JSON.parse(JSON.stringify(__codeModeResult));`;
}

function createHostFunctions({
  codeModeErrors,
  input,
  outerToolCallId,
  policy,

View on GitHub (pinned to 69428b1f8b)

Solutions

  1. Reduce the size of the generated source: split the work into multiple smaller code-mode invocations.
  2. Move large constant data out of the source and fetch it via a host tool at runtime.
  3. Raise maxSourceBytes in options.executionPolicy if the default 256 KiB is too small for your workload.

Example fix

// before
await runCodeMode({ js: codeWithDataBlob, tools });
// after
await runCodeMode({
  js: codeThatCallsGetDataTool,
  tools: { ...tools, getData },
  options: { executionPolicy: { maxSourceBytes: 512 * 1024 } },
});
Defensive patterns

Strategy: validation

Validate before calling

import { Buffer } from 'node:buffer';
const maxBytes = 256 * 1024; // match executionPolicy.maxSourceBytes
if (Buffer.byteLength(js, 'utf8') > maxBytes) {
  throw new Error(`code-mode source is ${Buffer.byteLength(js)} bytes, limit is ${maxBytes}`);
}

Try / catch

try {
  await runCodeMode({ js, tools, options });
} catch (error) {
  if (CodeModeSourceTooLargeError.isInstance(error)) {
    // error.byteLength / error.maxBytes — split the source or raise the limit
  } else throw error;
}

Prevention

When it happens

Trigger: Calling runCodeMode (or the code-mode tool) with input.js larger than policy.maxSourceBytes — most often when code is generated by an LLM or assembled by concatenating many helper snippets.

Common situations: LLM-generated code rambling past the limit; embedding large embedded data blobs (base64 strings) in source instead of passing them as tool inputs; setting a very low maxSourceBytes in executionPolicy for safety and hitting it with normal code.

Related errors


AI-assisted analysis of vercel/ai@69428b1f8b (2026-08-30). Data as JSON: /api/errors/834980f2746ce34e. Report an issue: GitHub.