{"version":3,"sources":["../src/tools/code-mode/stub-generator.ts","../src/workspace/errors.ts","../src/tools/code-mode/runner.ts","../src/tools/code-mode/transport.ts","../src/tools/code-mode/code-mode.ts"],"names":["isStandardSchemaWithJSON","standardSchemaToJSONSchema","SAFE_IDENT","mkdtemp","join","tmpdir","randomBytes","writeFile","pathToFileURL","handleFrame","notifyCall","notifyResult","rm","z","createTool","isValidationError"],"mappings":";;;;;;;;;;;;AAsBA,IAAM,UAAA,GAAa,4BAAA;AAMZ,SAAS,qBAAqB,MAAA,EAAmD;AACtF,EAAA,IAAI,MAAA,KAAW,QAAW,OAAO,SAAA;AACjC,EAAA,IAAI,OAAO,MAAA,KAAW,SAAA,EAAW,OAAO,SAAS,SAAA,GAAY,OAAA;AAG7D,EAAA,IAAI,OAAO,KAAA,KAAU,MAAA,EAAW,OAAO,OAAA,CAAQ,OAAO,KAAK,CAAA;AAC3D,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,MAAA,CAAO,IAAI,CAAA,EAAG;AAC9B,IAAA,OAAO,MAAA,CAAO,IAAA,CAAK,MAAA,GAAS,MAAA,CAAO,IAAA,CAAK,IAAI,OAAO,CAAA,CAAE,IAAA,CAAK,KAAK,CAAA,GAAI,OAAA;AAAA,EACrE;AAGA,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,KAAA,IAAS,MAAA,CAAO,KAAA;AACrC,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,IAAK,MAAM,MAAA,EAAQ;AACxC,IAAA,OAAO,KAAA,CAAM,GAAA,CAAI,oBAAoB,CAAA,CAAE,KAAK,KAAK,CAAA;AAAA,EACnD;AAEA,EAAA,MAAM,IAAA,GAAO,aAAA,CAAc,MAAA,CAAO,IAAI,CAAA;AAEtC,EAAA,IAAI,IAAA,KAAS,QAAA,IAAY,MAAA,CAAO,UAAA,EAAY;AAC1C,IAAA,OAAO,WAAW,MAAM,CAAA;AAAA,EAC1B;AACA,EAAA,IAAI,IAAA,K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AAA,OAAO,IAAI,OAAA,CAAQ,IAAA;AAAA,QAAK,aAAa,EAAE,CAAA,CAAA;AAAA,QAAI,MACzC,UAAU,GAAA,CAAI;AAAA,UACZ,OAAA;AAAA,UACA,OAAA,EAAS,IAAA;AAAA,UACT,OAAA;AAAA,UACA,QAAA;AAAA,UACA,OAAA;AAAA,UACA,aAAa,GAAA,EAAK,WAAA;AAAA,UAClB,cAAA,EAAgB,CAAC,IAAA,EAAM,IAAA,KAAS,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,yBAAA,EAA2B,EAAE,IAAA,EAAM,IAAA,EAAM,CAAA;AAAA,UACjG,gBAAA,EAAkB,CAAC,IAAA,EAAM,UAAA,EAAY,UACnC,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,KAAA,GAAQ,UAAU,MAAA,EAAQ,2BAAA,EAA6B,EAAE,IAAA,EAAM,YAAY;AAAA,SAC9F;AAAA,OACH;AAAA,IACF;AAAA,GACD,CAAA;AACH;AAWO,SAAS,cAAA,CAAe,QAAwB,SAAA,EAA+C;AACpG,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,kBAAA,CAAmB,MAAA,EAAQ,SAAS,CAAA;AAAA,IAC1C,YAAA,EAAc,2BAA2B,MAAM;AAAA,GACjD;AACF","file":"chunk-XEHGVQJW.cjs","sourcesContent":["/**\n * Code Mode — Type stub generation\n *\n * Converts Mastra tools into TypeScript `declare function external_<id>(...)`\n * stubs and assembles the instructions the model sees. The pipeline is:\n *\n *   tool.inputSchema (StandardSchemaWithJSON)\n *     -> standardSchemaToJSONSchema()  (already in core, zod v3 + v4 + arktype)\n *     -> jsonSchemaToTsString()        (this file, synchronous, dependency-free)\n *     -> stub string\n *\n * Only the subset of JSON Schema that tool schemas actually produce is handled;\n * anything else degrades to `unknown`.\n */\n\nimport type { JSONSchema7, JSONSchema7Definition, JSONSchema7TypeName } from 'json-schema';\nimport type { ToolsInput } from '../../agent/types';\nimport { isStandardSchemaWithJSON, standardSchemaToJSONSchema } from '../../schema';\nimport type { StandardSchemaWithJSON } from '../../schema';\nimport type { CodeModeConfig } from './types';\n\n/** A valid TypeScript identifier? (used to decide quoting of object keys). */\nconst SAFE_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * Convert a JSON Schema (draft-07) node into a TypeScript type string.\n * Unsupported constructs return `unknown`.\n */\nexport function jsonSchemaToTsString(schema: JSONSchema7Definition | undefined): string {\n  if (schema === undefined) return 'unknown';\n  if (typeof schema === 'boolean') return schema ? 'unknown' : 'never';\n\n  // enum / const\n  if (schema.const !== undefined) return literal(schema.const);\n  if (Array.isArray(schema.enum)) {\n    return schema.enum.length ? schema.enum.map(literal).join(' | ') : 'never';\n  }\n\n  // unions\n  const union = schema.anyOf ?? schema.oneOf;\n  if (Array.isArray(union) && union.length) {\n    return union.map(jsonSchemaToTsString).join(' | ');\n  }\n\n  const type = normalizeType(schema.type);\n\n  if (type === 'object' || schema.properties) {\n    return objectType(schema);\n  }\n  if (type === 'array' || schema.items) {\n    return arrayType(schema);\n  }\n\n  switch (type) {\n    case 'string':\n      return 'string';\n    case 'number':\n    case 'integer':\n      return 'number';\n    case 'boolean':\n      return 'boolean';\n    case 'null':\n      return 'null';\n    default:\n      return 'unknown';\n  }\n}\n\nfunction normalizeType(type: JSONSchema7['type']): JSONSchema7TypeName | undefined {\n  if (Array.isArray(type)) {\n    // e.g. ['string', 'null'] — caller folds null in via nullability; pick the\n    // first non-null for the base type.\n    return type.find(t => t !== 'null');\n  }\n  return type;\n}\n\nfunction objectType(schema: JSONSchema7): string {\n  const props = schema.properties ?? {};\n  const required = new Set(schema.required ?? []);\n  const keys = Object.keys(props);\n\n  if (!keys.length) {\n    // Free-form object.\n    const additional = schema.additionalProperties;\n    if (additional !== undefined && additional !== false) {\n      const valueType = typeof additional === 'object' ? jsonSchemaToTsString(additional) : 'unknown';\n      return `Record<string, ${valueType}>`;\n    }\n    return 'Record<string, unknown>';\n  }\n\n  const fields = keys.map(key => {\n    const optional = !required.has(key) ? '?' : '';\n    const k = SAFE_IDENT.test(key) ? key : JSON.stringify(key);\n    return `${k}${optional}: ${jsonSchemaToTsString(props[key])}`;\n  });\n  return `{ ${fields.join('; ')} }`;\n}\n\nfunction arrayType(schema: JSONSchema7): string {\n  const items = schema.items;\n  if (Array.isArray(items)) {\n    // Tuple.\n    return `[${items.map(jsonSchemaToTsString).join(', ')}]`;\n  }\n  const inner = jsonSchemaToTsString(items);\n  // Use `Array<...>` form for top-level unions so `A | B[]` isn't misread as\n  // `A | (B[])`. Object literals and other forms use the `T[]` shorthand.\n  return isTopLevelUnion(inner) ? `Array<${inner}>` : `${inner}[]`;\n}\n\n/** True if `ts` is a union at the top level (a ` | ` not nested in braces/brackets). */\nfunction isTopLevelUnion(ts: string): boolean {\n  let depth = 0;\n  for (let i = 0; i < ts.length; i++) {\n    const c = ts[i];\n    if (c === '{' || c === '[' || c === '(' || c === '<') depth++;\n    else if (c === '}' || c === ']' || c === ')' || c === '>') depth--;\n    else if (c === '|' && depth === 0) return true;\n  }\n  return false;\n}\n\nfunction literal(value: unknown): string {\n  if (typeof value === 'string') return JSON.stringify(value);\n  if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n  if (value === null) return 'null';\n  return 'unknown';\n}\n\nfunction schemaToTs(schema: unknown, io: 'input' | 'output'): string {\n  if (!isStandardSchemaWithJSON(schema)) return 'unknown';\n  try {\n    const json = standardSchemaToJSONSchema(schema as StandardSchemaWithJSON, { io });\n    return jsonSchemaToTsString(json as JSONSchema7);\n  } catch {\n    return 'unknown';\n  }\n}\n\n/** Strip non-identifier characters so a tool id is a legal function-name suffix. */\nfunction sanitizeId(id: string): string {\n  const cleaned = id.replace(/[^A-Za-z0-9_$]/g, '_');\n  return SAFE_IDENT.test(cleaned) ? cleaned : `_${cleaned}`;\n}\n\n/** A single tool's TS declaration plus the original/sanitized id mapping. */\nexport interface CodeModeStub {\n  /** Original tool id (key used by the RPC dispatcher). */\n  toolId: string;\n  /** Sanitized identifier used in `external_<name>`. */\n  externalName: string;\n  /** The full `declare function ...` line(s). */\n  declaration: string;\n}\n\n/** Generate stubs for every tool in the config. */\nexport function generateStubs(tools: ToolsInput): CodeModeStub[] {\n  // Two distinct tool ids can sanitize to the same `external_*` name (e.g.\n  // `a-b` and `a_b`). Without this check the later binding would silently\n  // overwrite the earlier one in the runner, so fail fast instead.\n  const seen = new Map<string, string>();\n  return Object.entries(tools).map(([key, tool]) => {\n    const toolId = (tool as { id?: string }).id ?? key;\n    const description = (tool as { description?: string }).description;\n    const inputType = schemaToTs((tool as { inputSchema?: unknown }).inputSchema, 'input');\n    const outputType = schemaToTs((tool as { outputSchema?: unknown }).outputSchema, 'output');\n    const externalName = sanitizeId(toolId);\n\n    const prior = seen.get(externalName);\n    if (prior !== undefined && prior !== toolId) {\n      throw new Error(`Code Mode tool id collision: \"${prior}\" and \"${toolId}\" both map to external_${externalName}`);\n    }\n    seen.set(externalName, toolId);\n\n    const doc = description ? `/** ${description.replace(/\\*\\//g, '* /')} */\\n` : '';\n    const declaration = `${doc}declare function external_${externalName}(input: ${inputType}): Promise<${outputType}>;`;\n\n    return { toolId, externalName, declaration };\n  });\n}\n\nconst USAGE_CONTRACT = `# Code Mode\n\nYou have an \\`execute_typescript\\` tool. Instead of calling tools one at a time,\nwrite a single TypeScript program that orchestrates them and returns one result.\n\nRules:\n- Call the available tools via the \\`external_*\\` functions declared below. Each\n  returns a Promise — \\`await\\` it.\n- Batch independent calls with \\`Promise.all\\`. Do arithmetic and data shaping in\n  JavaScript, not in your head.\n- End the program by \\`return\\`-ing the final value (objects/arrays are fine).\n- The program runs in a sandbox: no access to the host filesystem, network, or\n  process. The only capabilities are the \\`external_*\\` functions.\n- Use \\`console.log\\` for debugging; logs are captured and returned.\n\nAvailable functions:`;\n\n/** Build the full instructions string (usage contract + stubs). */\nexport function createCodeModeInstructions(config: CodeModeConfig): string {\n  const stubs = generateStubs(config.tools);\n  const declarations = stubs.map(s => s.declaration).join('\\n\\n');\n  return `${USAGE_CONTRACT}\\n\\n${declarations}`;\n}\n","/**\n * Workspace Errors\n *\n * Error classes for workspace operations.\n */\n\nimport type { WorkspaceStatus } from './types';\n\n// =============================================================================\n// Base Error\n// =============================================================================\n\nexport class WorkspaceError extends Error {\n  constructor(\n    message: string,\n    public readonly code: string,\n    public readonly workspaceId?: string,\n  ) {\n    super(message);\n    this.name = 'WorkspaceError';\n  }\n}\n\n// =============================================================================\n// Availability Errors\n// =============================================================================\n\nexport class WorkspaceNotAvailableError extends WorkspaceError {\n  constructor() {\n    super('Workspace not available. Ensure the agent has a workspace configured.', 'NO_WORKSPACE');\n    this.name = 'WorkspaceNotAvailableError';\n  }\n}\n\nexport class FilesystemNotAvailableError extends WorkspaceError {\n  constructor() {\n    super('Workspace does not have a filesystem configured', 'NO_FILESYSTEM');\n    this.name = 'FilesystemNotAvailableError';\n  }\n}\n\nexport class SandboxNotAvailableError extends WorkspaceError {\n  constructor(message?: string) {\n    super(message ?? 'Workspace does not have a sandbox configured', 'NO_SANDBOX');\n    this.name = 'SandboxNotAvailableError';\n  }\n}\n\nexport class SandboxFeatureNotSupportedError extends WorkspaceError {\n  constructor(feature: 'executeCommand' | 'installPackage' | 'processes') {\n    super(`Sandbox does not support ${feature}`, 'FEATURE_NOT_SUPPORTED');\n    this.name = 'SandboxFeatureNotSupportedError';\n  }\n}\n\nexport class SearchNotAvailableError extends WorkspaceError {\n  constructor() {\n    super('Workspace does not have search configured (enable bm25 or provide vectorStore + embedder)', 'NO_SEARCH');\n    this.name = 'SearchNotAvailableError';\n  }\n}\n\n// =============================================================================\n// State Errors\n// =============================================================================\n\nexport class WorkspaceNotReadyError extends WorkspaceError {\n  constructor(workspaceId: string, status: WorkspaceStatus) {\n    super(`Workspace is not ready (status: ${status})`, 'NOT_READY', workspaceId);\n    this.name = 'WorkspaceNotReadyError';\n  }\n}\n\nexport class WorkspaceReadOnlyError extends WorkspaceError {\n  constructor(operation: string) {\n    super(`Workspace is in read-only mode. Cannot perform: ${operation}`, 'READ_ONLY');\n    this.name = 'WorkspaceReadOnlyError';\n  }\n}\n\n// =============================================================================\n// Filesystem Errors\n// =============================================================================\n\nexport class FilesystemError extends Error {\n  constructor(\n    message: string,\n    public readonly code: string,\n    public readonly path: string,\n  ) {\n    super(message);\n    this.name = 'FilesystemError';\n  }\n}\n\nexport class FileNotFoundError extends FilesystemError {\n  constructor(path: string) {\n    super(`File not found: ${path}`, 'ENOENT', path);\n    this.name = 'FileNotFoundError';\n  }\n}\n\nexport class DirectoryNotFoundError extends FilesystemError {\n  constructor(path: string) {\n    super(`Directory not found: ${path}`, 'ENOENT', path);\n    this.name = 'DirectoryNotFoundError';\n  }\n}\n\nexport class FileExistsError extends FilesystemError {\n  constructor(path: string) {\n    super(`File already exists: ${path}`, 'EEXIST', path);\n    this.name = 'FileExistsError';\n  }\n}\n\nexport class IsDirectoryError extends FilesystemError {\n  constructor(path: string) {\n    super(`Path is a directory: ${path}`, 'EISDIR', path);\n    this.name = 'IsDirectoryError';\n  }\n}\n\nexport class NotDirectoryError extends FilesystemError {\n  constructor(path: string) {\n    super(`Path is not a directory: ${path}`, 'ENOTDIR', path);\n    this.name = 'NotDirectoryError';\n  }\n}\n\nexport class DirectoryNotEmptyError extends FilesystemError {\n  constructor(path: string) {\n    super(`Directory not empty: ${path}`, 'ENOTEMPTY', path);\n    this.name = 'DirectoryNotEmptyError';\n  }\n}\n\nexport class PermissionError extends FilesystemError {\n  constructor(\n    path: string,\n    public readonly operation: string,\n  ) {\n    super(`Permission denied: ${operation} on ${path}`, 'EACCES', path);\n    this.name = 'PermissionError';\n  }\n}\n\nexport class FileReadRequiredError extends FilesystemError {\n  constructor(path: string, reason: string) {\n    super(reason, 'EREAD_REQUIRED', path);\n    this.name = 'FileReadRequiredError';\n  }\n}\n\nexport class StaleFileError extends FilesystemError {\n  constructor(\n    path: string,\n    public readonly expectedMtime: Date,\n    public readonly actualMtime: Date,\n  ) {\n    super(\n      `File was modified externally: ${path} (expected mtime ${expectedMtime.toISOString()}, actual ${actualMtime.toISOString()})`,\n      'ESTALE',\n      path,\n    );\n    this.name = 'StaleFileError';\n  }\n}\n\n/**\n * Error thrown when a filesystem operation is attempted before initialization.\n */\nexport class FilesystemNotReadyError extends FilesystemError {\n  constructor(id: string) {\n    super(`Filesystem \"${id}\" is not ready. Call init() first or use ensureReady().`, 'ENOTREADY', id);\n    this.name = 'FilesystemNotReadyError';\n  }\n}\n","/**\n * Code Mode — Sandbox runner\n *\n * Builds the JavaScript program that runs *inside* the sandbox. The runner:\n *  - defines an `external_<name>` function per allow-listed tool, each of which\n *    emits a JSON-RPC request on the protocol channel and awaits its response\n *    (matched by `id`, so `Promise.all` calls resolve independently);\n *  - wraps the model's program in an async function, captures `console.*`, and\n *    emits a terminal `done` frame.\n *\n * Protocol (host <-> runner), newline-delimited JSON on stdout/stdin:\n *  - Frames the runner emits are prefixed with FRAME_PREFIX so the host can\n *    tell them apart from any stray output. Forms: `rpc`, `log`, `done`.\n *  - The host writes `rpc-result` frames to the runner stdin (no prefix).\n */\n\n/** Marks a line on stdout as a Code Mode protocol frame. */\nexport const FRAME_PREFIX = '\\u0000CODEMODE\\u0000';\n\nexport interface BuildRunnerOptions {\n  /**\n   * Module specifier the runner imports to obtain the user program. The\n   * referenced module must `export default` an async function (the wrapped\n   * model code). Written as a sibling `.ts` file so the sandbox's `node`\n   * strips the TypeScript types natively at import time.\n   */\n  programModule: string;\n  /** Map of `external_<name>` -> original tool id used in the RPC request. */\n  externals: Array<{ externalName: string; toolId: string }>;\n}\n\n/**\n * Wrap the model's TypeScript program as a default-exported async function\n * module. Written to a `.ts` file; Node strips the type annotations at import.\n * Top-level `return`, `await`, and `const` work because the body lives inside\n * an async function.\n */\nexport function buildProgramModule(program: string): string {\n  return `export default async function () {\\n${program}\\n}\\n`;\n}\n\n/**\n * Produce the full runner source to write into the sandbox and run with node.\n */\nexport function buildRunner({ programModule, externals }: BuildRunnerOptions): string {\n  // `buildRunner` is exported, so a caller could pass a non-sanitized name.\n  // External names become global property suffixes, so reject anything that\n  // isn't a legal identifier instead of producing an unusable global.\n  const SAFE_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n  const seen = new Map<string, string>();\n  for (const { externalName, toolId } of externals) {\n    if (!SAFE_IDENT.test(externalName)) {\n      throw new Error(`Invalid Code Mode external identifier: ${externalName}`);\n    }\n    // Two tool ids can sanitize to the same external name (e.g. `a-b` and\n    // `a_b` both become `a_b`). The install loop below would silently overwrite\n    // the earlier global, leaving one tool unreachable. Fail fast instead.\n    const existing = seen.get(externalName);\n    if (existing) {\n      throw new Error(\n        `Code Mode external identifier collision: tools \"${existing}\" and \"${toolId}\" both map to external_${externalName}`,\n      );\n    }\n    seen.set(externalName, toolId);\n  }\n\n  // Externals are emitted as JSON data, not interpolated identifiers. The\n  // runner installs each `external_<name>` global in a loop using bracket\n  // assignment, so no caller-derived string is ever spliced into the generated\n  // source as code. This keeps tool ids strictly data, even if `sanitize`\n  // changes.\n  const externalsJson = JSON.stringify(externals.map(({ externalName, toolId }) => ({ externalName, toolId })));\n\n  return `'use strict';\nconst FRAME_PREFIX = ${JSON.stringify(FRAME_PREFIX)};\n\nfunction __emit(frame) {\n  process.stdout.write(FRAME_PREFIX + JSON.stringify(frame) + '\\\\n');\n}\n\n// ---- console capture -------------------------------------------------------\nfor (const level of ['log', 'info', 'warn', 'error']) {\n  console[level] = (...args) => {\n    const message = args\n      .map((a) => (typeof a === 'string' ? a : safeStringify(a)))\n      .join(' ');\n    __emit({ type: 'log', level, message });\n  };\n}\nfunction safeStringify(value) {\n  try { return JSON.stringify(value); } catch { return String(value); }\n}\n\n// ---- RPC bridge ------------------------------------------------------------\nlet __nextId = 0;\nconst __pending = new Map();\n\nfunction __rpc(tool, args) {\n  const id = __nextId++;\n  return new Promise((resolve, reject) => {\n    __pending.set(id, { resolve, reject });\n    __emit({ type: 'rpc', id, tool, args });\n  });\n}\n\nlet __stdinBuffer = '';\nprocess.stdin.setEncoding('utf8');\nprocess.stdin.on('data', (chunk) => {\n  __stdinBuffer += chunk;\n  let idx;\n  while ((idx = __stdinBuffer.indexOf('\\\\n')) >= 0) {\n    const line = __stdinBuffer.slice(0, idx);\n    __stdinBuffer = __stdinBuffer.slice(idx + 1);\n    if (!line) continue;\n    let frame;\n    try { frame = JSON.parse(line); } catch { continue; }\n    if (frame && frame.type === 'rpc-result') {\n      const entry = __pending.get(frame.id);\n      if (!entry) continue;\n      __pending.delete(frame.id);\n      if (frame.ok) entry.resolve(frame.result);\n      else {\n        const err = new Error(frame.error?.message || 'external tool failed');\n        if (frame.error?.name) err.name = frame.error.name;\n        entry.reject(err);\n      }\n    }\n  }\n});\n\n// ---- externals -------------------------------------------------------------\nfor (const { externalName, toolId } of ${externalsJson}) {\n  globalThis['external_' + externalName] = (input) => __rpc(toolId, input);\n}\n\n// ---- user program ----------------------------------------------------------\n// The program lives in a sibling .ts module exporting a default async function;\n// node strips its TypeScript types natively on import.\nasync function __main() {\n  const mod = await import(${JSON.stringify(programModule)});\n  return await mod.default();\n}\n\n__main()\n  .then((result) => {\n    __emit({ type: 'done', ok: true, result });\n    process.exit(0);\n  })\n  .catch((error) => {\n    __emit({\n      type: 'done',\n      ok: false,\n      error: { message: error?.message ?? String(error), name: error?.name },\n    });\n    process.exit(0);\n  });\n`;\n}\n","/**\n * Code Mode — stdio JSON-RPC transport (v1)\n *\n * Runs the runner inside the sandbox via `sandbox.processes.spawn`, parses\n * protocol frames off stdout, dispatches `external_*` calls back to the host,\n * and writes results to the runner stdin. Abstracted behind\n * {@link CodeModeTransport} so socket/file-queue transports can be added for\n * remote sandboxes later.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport { SandboxFeatureNotSupportedError } from '../../workspace/errors';\nimport { buildRunner, buildProgramModule, FRAME_PREFIX } from './runner';\nimport type { CodeModeRunnerFrame, CodeModeToolResult, CodeModeTransport } from './types';\n\n/**\n * Default transport: writes the runner to a temp dir, spawns\n * `node <runner>`, and bridges RPC over stdio.\n */\nexport class StdioCodeModeTransport implements CodeModeTransport {\n  async run(opts: Parameters<CodeModeTransport['run']>[0]): Promise<CodeModeToolResult> {\n    const { sandbox, program, toolIds, dispatch, timeout, abortSignal, onExternalCall, onExternalResult } = opts;\n\n    if (!sandbox.processes) {\n      throw new SandboxFeatureNotSupportedError('processes');\n    }\n\n    const externals = toolIds.map(toolId => ({ toolId, externalName: sanitize(toolId) }));\n    const allowList = new Set(toolIds);\n\n    const dir = await mkdtemp(join(tmpdir(), 'mastra-code-mode-'));\n    const suffix = randomBytes(4).toString('hex');\n    // The model's TypeScript program is written to its own .ts module; node\n    // strips the type annotations when the runner imports it (see the\n    // --experimental-strip-types flag on the spawn below).\n    const programPath = join(dir, `program-${suffix}.ts`);\n    await writeFile(programPath, buildProgramModule(program), 'utf8');\n    const runnerSource = buildRunner({ programModule: pathToFileURL(programPath).href, externals });\n    const runnerPath = join(dir, `runner-${suffix}.mjs`);\n    await writeFile(runnerPath, runnerSource, 'utf8');\n\n    const logs: string[] = [];\n    let done: CodeModeToolResult | undefined;\n    let stdoutBuffer = '';\n\n    // Resolved once a terminal `done` frame arrives.\n    let resolveDone!: () => void;\n    const donePromise = new Promise<void>(resolve => {\n      resolveDone = resolve;\n    });\n\n    try {\n      // `--experimental-strip-types` lets node import the program's `.ts`\n      // module on Node 22.6–22.17 (where type-stripping is still flagged). On\n      // Node 22.18+/24, where stripping is the default, the flag is accepted as\n      // a harmless no-op, so this works across the versions CI and users run.\n      const handle = await sandbox.processes.spawn(`node --experimental-strip-types ${runnerPath}`, {\n        cwd: dir,\n        abortSignal,\n        onStdout: (chunk: string) => {\n          stdoutBuffer += chunk;\n          let idx: number;\n          while ((idx = stdoutBuffer.indexOf('\\n')) >= 0) {\n            const line = stdoutBuffer.slice(0, idx);\n            stdoutBuffer = stdoutBuffer.slice(idx + 1);\n            if (!line.startsWith(FRAME_PREFIX)) continue;\n            let frame: CodeModeRunnerFrame;\n            try {\n              frame = JSON.parse(line.slice(FRAME_PREFIX.length));\n            } catch {\n              continue;\n            }\n            handleFrame(frame);\n          }\n        },\n      });\n\n      function handleFrame(frame: CodeModeRunnerFrame): void {\n        switch (frame.type) {\n          case 'log':\n            logs.push(frame.message);\n            return;\n          case 'done':\n            done = frame.ok\n              ? { success: true, result: frame.result, logs }\n              : { success: false, error: frame.error, logs };\n            resolveDone();\n            return;\n          case 'rpc':\n            // `serveRpc` awaits `respond`, which writes to the child's stdin and\n            // can reject if the process already exited/was killed. Swallow that\n            // so it never surfaces as an unhandled rejection.\n            void serveRpc(frame.id, frame.tool, frame.args).catch(() => {});\n            return;\n        }\n      }\n\n      // Observer hooks are caller-supplied and best-effort: a throwing hook must\n      // never prevent `respond()` from running, or the matching in-sandbox promise\n      // would hang until the timeout.\n      function notifyCall(tool: string, args: unknown): void {\n        try {\n          onExternalCall?.(tool, args);\n        } catch {\n          /* observer errors are non-fatal */\n        }\n      }\n      function notifyResult(tool: string, durationMs: number, error?: Error): void {\n        try {\n          onExternalResult?.(tool, durationMs, error);\n        } catch {\n          /* observer errors are non-fatal */\n        }\n      }\n\n      async function serveRpc(id: number, tool: string, args: unknown): Promise<void> {\n        const started = Date.now();\n        notifyCall(tool, args);\n        // Allow-list enforcement: never invoke a tool that wasn't exposed.\n        if (!allowList.has(tool)) {\n          notifyResult(tool, Date.now() - started, new Error('not allowed'));\n          await respond(id, false, undefined, {\n            message: `Tool \"${tool}\" is not available in Code Mode`,\n            name: 'NotAllowedError',\n          });\n          return;\n        }\n        try {\n          const result = await dispatch(tool, args);\n          notifyResult(tool, Date.now() - started);\n          await respond(id, true, result);\n        } catch (error: any) {\n          notifyResult(tool, Date.now() - started, error);\n          await respond(id, false, undefined, {\n            message: error?.message ?? String(error),\n            name: error?.name,\n          });\n        }\n      }\n\n      async function respond(\n        id: number,\n        ok: boolean,\n        result?: unknown,\n        error?: { message: string; name?: string },\n      ): Promise<void> {\n        await handle.sendStdin(JSON.stringify({ type: 'rpc-result', id, ok, result, error }) + '\\n');\n      }\n\n      // Race completion against process exit and the timeout. Including process\n      // exit means a runner that dies without emitting `done` resolves\n      // immediately instead of waiting out the full timeout.\n      let timer: NodeJS.Timeout | undefined;\n      const timeoutPromise = new Promise<'timeout'>(resolve => {\n        timer = setTimeout(() => resolve('timeout'), timeout);\n      });\n      const exitPromise = handle.wait().then(() => 'exited' as const);\n\n      const outcome = await Promise.race([\n        donePromise.then(() => 'done' as const),\n        exitPromise.catch(() => 'exited' as const),\n        timeoutPromise,\n      ]);\n      if (timer) clearTimeout(timer);\n\n      if (outcome === 'timeout') {\n        await handle.kill().catch(() => {});\n        return {\n          success: false,\n          logs,\n          error: { message: `Code Mode execution timed out after ${timeout}ms`, name: 'TimeoutError' },\n        };\n      }\n\n      // Either `done` arrived or the process exited. If we raced ahead of a\n      // `done` frame still in flight, give it a brief beat to land.\n      if (!done) {\n        await exitPromise.catch(() => {});\n      }\n\n      return (\n        done ?? {\n          success: false,\n          logs,\n          error: { message: 'Program exited without returning a result', name: 'NoResultError' },\n        }\n      );\n    } finally {\n      await rm(dir, { recursive: true, force: true }).catch(() => {});\n    }\n  }\n}\n\nfunction sanitize(id: string): string {\n  const cleaned = id.replace(/[^A-Za-z0-9_$]/g, '_');\n  return /^[A-Za-z_$]/.test(cleaned) ? cleaned : `_${cleaned}`;\n}\n","/**\n * Code Mode — tool factory\n *\n * `createCodeMode(config)` returns the `execute_typescript` tool plus the\n * generated `instructions`. The tool transpiles the model's TypeScript to JS,\n * runs it in a WorkspaceSandbox via the transport, and bridges each\n * `external_*` call back to the real Mastra tool on the host.\n */\n\nimport { z } from 'zod/v4';\nimport type { WorkspaceSandbox } from '../../workspace/sandbox/sandbox';\nimport { createTool } from '../tool';\nimport type { Tool } from '../tool';\nimport { isValidationError } from '../validation';\nimport { createCodeModeInstructions } from './stub-generator';\nimport { StdioCodeModeTransport } from './transport';\nimport type { CodeModeConfig, CodeModeToolDispatcher, CodeModeToolResult, CodeModeTransport } from './types';\n\nconst DEFAULT_TIMEOUT = 30_000;\nconst DEFAULT_TOOL_NAME = 'execute_typescript';\n\nconst codeModeInputSchema = z.object({\n  code: z\n    .string()\n    .describe(\n      'A TypeScript program that orchestrates the available external_* tools and returns a final value. ' +\n        'Use Promise.all to batch calls; do arithmetic in JS. End with `return <value>`.',\n    ),\n});\n\nconst codeModeOutputSchema = z.object({\n  success: z.boolean(),\n  result: z.unknown().optional(),\n  logs: z.array(z.string()).optional(),\n  error: z\n    .object({\n      message: z.string(),\n      name: z.string().optional(),\n      line: z.number().optional(),\n    })\n    .optional(),\n});\n\n/** Result of {@link createCodeMode}: the tool plus its generated instructions. */\nexport interface CodeModeResult {\n  tool: Tool<any, any>;\n  instructions: string;\n}\n\n/** Resolve the tool key -> tool map keyed by the tool's effective id. */\nfunction indexToolsById(config: CodeModeConfig): Map<string, { execute?: (args: any, ctx: any) => Promise<any> }> {\n  const map = new Map();\n  for (const [key, tool] of Object.entries(config.tools)) {\n    const id = (tool as { id?: string }).id ?? key;\n    map.set(id, tool);\n  }\n  return map;\n}\n\n/**\n * Create only the `execute_typescript` tool. Most callers want\n * {@link createCodeMode}, which also returns the matching instructions.\n */\nexport function createCodeModeTool(\n  config: CodeModeConfig,\n  transport: CodeModeTransport = new StdioCodeModeTransport(),\n) {\n  const timeout = config.timeout ?? DEFAULT_TIMEOUT;\n  const id = config.id ?? DEFAULT_TOOL_NAME;\n  const toolsById = indexToolsById(config);\n  const toolIds = [...toolsById.keys()];\n\n  return createTool({\n    id,\n    description:\n      'Execute a TypeScript program that orchestrates the available tools in a sandbox. ' +\n      'Prefer this over calling tools one at a time when a task needs multiple tool calls, ' +\n      'batching, aggregation, or arithmetic.',\n    inputSchema: codeModeInputSchema,\n    outputSchema: codeModeOutputSchema,\n    execute: async ({ code }, ctx): Promise<CodeModeToolResult> => {\n      // Resolve sandbox: explicit config -> workspace from context. There is no\n      // implicit fallback: Code Mode runs model-authored code, so the execution\n      // boundary must be chosen deliberately. To run locally (host privileges),\n      // pass `sandbox: new LocalSandbox()` explicitly.\n      const sandbox: WorkspaceSandbox | undefined = config.sandbox ?? ctx?.workspace?.sandbox;\n      if (!sandbox) {\n        throw new Error(\n          'Code Mode requires a sandbox to run model-authored code, but none was configured. ' +\n            'Pass one to createCodeMode({ tools, sandbox }), or run the agent in a workspace that provides a sandbox. ' +\n            'To execute on the host (host privileges — only for trusted/local use), pass `sandbox: new LocalSandbox()`.',\n        );\n      }\n\n      // Each external_* call re-enters the real Mastra tool pipeline (validation,\n      // request-context checks, tracing) on the host, with the outer tool's context.\n      const dispatch: CodeModeToolDispatcher = async (toolId, args) => {\n        const tool = toolsById.get(toolId);\n        if (!tool?.execute) {\n          throw new Error(`Tool \"${toolId}\" is not available in Code Mode`);\n        }\n        const result = await tool.execute(args, {\n          mastra: ctx?.mastra,\n          requestContext: ctx?.requestContext,\n          abortSignal: ctx?.abortSignal,\n          workspace: ctx?.workspace,\n        });\n        if (isValidationError(result)) {\n          throw new Error(result.message ?? `Invalid input for tool \"${toolId}\"`);\n        }\n        return result;\n      };\n\n      // The TypeScript program is written to a .ts module by the transport;\n      // the sandbox's node strips the type annotations natively at import.\n      return ctx.observe.span(`code-mode:${id}`, () =>\n        transport.run({\n          sandbox,\n          program: code,\n          toolIds,\n          dispatch,\n          timeout,\n          abortSignal: ctx?.abortSignal,\n          onExternalCall: (tool, args) => ctx.observe.log('info', 'code-mode external call', { tool, args }),\n          onExternalResult: (tool, durationMs, error) =>\n            ctx.observe.log(error ? 'error' : 'info', 'code-mode external result', { tool, durationMs }),\n        }),\n      );\n    },\n  }) as unknown as Tool<any, any>;\n}\n\n/**\n * Create Code Mode: the `execute_typescript` tool plus generated instructions.\n *\n * @example\n * ```ts\n * const { tool, instructions } = createCodeMode({ tools: { getTopProducts, getProductRatings } });\n * const agent = new Agent({ instructions: ['You are helpful.', instructions], tools: { [tool.id]: tool } });\n * ```\n */\nexport function createCodeMode(config: CodeModeConfig, transport?: CodeModeTransport): CodeModeResult {\n  return {\n    tool: createCodeModeTool(config, transport),\n    instructions: createCodeModeInstructions(config),\n  };\n}\n"]}