@langchain/quickjs 0.6.3-rc.0 → 0.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +0 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -2
- package/dist/index.js.map +1 -1
- package/package.json +5 -6
package/dist/index.cjs
CHANGED
|
@@ -1341,7 +1341,6 @@ function createCodeInterpreterMiddleware(options = {}) {
|
|
|
1341
1341
|
});
|
|
1342
1342
|
return (0, langchain.createMiddleware)({
|
|
1343
1343
|
name: "CodeInterpreterMiddleware",
|
|
1344
|
-
tracePolicy: { processInputs: langchain.omitPayload },
|
|
1345
1344
|
tools: [evalTool],
|
|
1346
1345
|
wrapModelCall: async (request, handler) => {
|
|
1347
1346
|
const agentTools = request.tools || [];
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["toJsonSchema","compile","BaseMessage","isCommand","Parser","tsPlugin","MagicString","program","newQuickJSAsyncWASMModuleFromVariant","PQueue","shouldInterruptAfterDeadline","raw","SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY","tool","z","createMiddleware","omitPayload"],"sources":["../src/errors.ts","../src/utils.ts","../src/coerce.ts","../src/transform.ts","../src/eval-queue.ts","../src/session.ts","../src/subagent-dispatch.ts","../src/middleware.ts"],"sourcesContent":["/**\n * Options for constructing a {@link PTCCallBudgetExceededError}.\n */\ninterface PTCCallBudgetExceededOptions {\n /**\n * The configured per-eval PTC call limit.\n */\n limit: number;\n\n /**\n * The call number that triggered the violation (always `limit + 1`).\n */\n attempted: number;\n\n /**\n * The name of the tool function that was called over budget.\n */\n functionName: string;\n}\n\n/**\n * Thrown when a single eval exhausts its configured PTC call budget.\n */\nexport class PTCCallBudgetExceededError extends Error {\n readonly limit: number;\n readonly attempted: number;\n readonly functionName: string;\n\n constructor(options: PTCCallBudgetExceededOptions) {\n super(\n `PTC call budget exceeded (limit=${options.limit}, attempted=${options.attempted}, function=${options.functionName})`,\n );\n this.name = \"PTCCallBudgetExceededError\";\n this.limit = options.limit;\n this.attempted = options.attempted;\n this.functionName = options.functionName;\n }\n}\n","import { compile } from \"json-schema-to-typescript\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport dedent from \"dedent\";\nimport type { ReplResult } from \"./types.js\";\n\n/**\n * Convert a snake_case or kebab-case string to camelCase.\n */\nexport function toCamelCase(name: string): string {\n return name.replace(/[-_]([a-z])/g, (_, c) => c.toUpperCase());\n}\n\n/**\n * Recursively collect all string values from an object, array, or primitive.\n */\nexport function collectStrings(obj: unknown): string[] {\n const result: string[] = [];\n function walk(val: unknown) {\n if (typeof val === \"string\") {\n result.push(val);\n } else if (Array.isArray(val)) {\n for (const item of val) walk(item);\n } else if (typeof val === \"object\" && val !== null) {\n for (const v of Object.values(val)) walk(v);\n }\n }\n walk(obj);\n return result;\n}\n\n/**\n * Format the result of a REPL evaluation for the agent.\n */\nexport function formatReplResult(result: ReplResult): string {\n const parts: string[] = [];\n\n if (result.logs.length > 0) {\n let logsText = result.logs.join(\"\\n\");\n if (result.logsDroppedChars > 0) {\n logsText += `\\n[truncated ${result.logsDroppedChars} chars]`;\n }\n parts.push(logsText);\n }\n\n if (result.ok) {\n if (result.value !== undefined) {\n const formatted =\n typeof result.value === \"string\"\n ? result.value\n : JSON.stringify(result.value, null, 2);\n parts.push(`→ ${formatted}`);\n }\n } else if (result.error) {\n const errName = result.error.name || \"Error\";\n const errMsg = result.error.message || \"Unknown error\";\n parts.push(`${errName}: ${errMsg}`);\n if (result.error.stack) {\n parts.push(result.error.stack);\n }\n }\n\n return parts.join(\"\\n\") || \"(no output)\";\n}\n\nexport function safeToJsonSchema(\n schema: unknown,\n): Record<string, unknown> | undefined {\n try {\n return toJsonSchema(schema as Parameters<typeof toJsonSchema>[0]) as Record<\n string,\n unknown\n >;\n } catch {\n return undefined;\n }\n}\n\nasync function schemaToInterface(\n jsonSchema: Record<string, unknown>,\n interfaceName: string,\n): Promise<string> {\n const compiled = await compile(\n { ...jsonSchema, additionalProperties: false },\n interfaceName,\n { bannerComment: \"\", additionalProperties: false },\n );\n return compiled.replace(/^export /, \"\").trimEnd();\n}\n\nexport function capitalize(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nexport async function toolToTypeSignature(\n name: string,\n description: string,\n jsonSchema: Record<string, unknown> | undefined,\n): Promise<string> {\n const inputType = `${capitalize(name)}Input`;\n\n if (!jsonSchema || !jsonSchema.properties) {\n return dedent`\n /**\n * ${description}\n */\n async tools.${name}(input: Record<string, unknown>): Promise<string>\n `;\n }\n\n const iface = await schemaToInterface(jsonSchema, inputType);\n return dedent`\n ${iface}\n\n /**\n * ${description}\n */\n async tools.${name}(input: ${inputType}): Promise<string>\n `;\n}\n","/**\n * Coercion of tool / subagent return values for the QuickJS bridge.\n *\n * The deepagents `task` tool resolves to a LangGraph `Command` whose payload\n * carries the subagent's final message(s) under `update.messages`; some tools\n * return a `ToolMessage` or a list of messages. The interpreter bridges need\n * the underlying output, not the envelope, so this unwraps those shapes to the\n * content the model actually cares about.\n */\nimport { isCommand, type Command } from \"@langchain/langgraph\";\nimport { BaseMessage } from \"@langchain/core/messages\";\n\n/**\n * Return the trailing message content from a `Command`'s `update.messages`,\n * scanning from the end for the last message that actually has content. Returns\n * the command unchanged when it has no message-shaped payload.\n */\nfunction extractCommandContent(command: Command): unknown {\n const update: unknown = command.update;\n const messages =\n update !== null && typeof update === \"object\"\n ? (update as { messages?: unknown }).messages\n : undefined;\n if (Array.isArray(messages)) {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (BaseMessage.isInstance(message) && message.content != null) {\n return message.content;\n }\n }\n }\n return command;\n}\n\n/**\n * Unwrap a LangChain `Command` / `ToolMessage` / message-list envelope to the\n * underlying content. Non-envelope values (strings, content-block arrays, plain\n * objects) are returned unchanged.\n *\n * @param value The raw value returned by a tool or subagent dispatch.\n * @returns The unwrapped content, or `value` itself when it isn't an envelope.\n */\nexport function unwrapToolEnvelope(value: unknown): unknown {\n if (typeof value === \"string\") return value;\n\n if (isCommand(value)) {\n const inner = extractCommandContent(value);\n return inner === value ? value : unwrapToolEnvelope(inner);\n }\n\n if (BaseMessage.isInstance(value)) {\n return unwrapToolEnvelope(value.content);\n }\n\n if (Array.isArray(value)) {\n for (let i = value.length - 1; i >= 0; i--) {\n const entry = value[i];\n if (BaseMessage.isInstance(entry)) {\n return unwrapToolEnvelope(entry.content);\n }\n if (isCommand(entry)) {\n const inner = extractCommandContent(entry);\n if (inner !== entry) return unwrapToolEnvelope(inner);\n }\n }\n return value;\n }\n\n return value;\n}\n","/**\n * AST-based code transform pipeline for the REPL.\n *\n * Transforms TypeScript/JavaScript code into plain JS that can be\n * evaluated inside QuickJS with proper state persistence:\n *\n * 1. Parse with acorn + acorn-typescript (handles TS syntax)\n * 2. Strip TypeScript-only nodes (type annotations, interfaces, etc.)\n * 3. Hoist top-level declarations to globalThis for cross-eval persistence\n * 4. Auto-return the last expression\n * 5. Wrap in async IIFE so top-level await works\n */\n\nimport { Parser } from \"acorn\";\nimport { tsPlugin } from \"@sveltejs/acorn-typescript\";\nimport { walk } from \"estree-walker\";\nimport MagicString from \"magic-string\";\nimport type {\n Node,\n Identifier,\n VariableDeclaration as EstreeVariableDeclaration,\n VariableDeclarator as EstreeVariableDeclarator,\n} from \"estree\";\n\nconst TSParser = Parser.extend(tsPlugin());\n\ntype AcornNode = Node & { start: number; end: number };\ntype AcornExpressionStatement = AcornNode & {\n type: \"ExpressionStatement\";\n expression: AcornNode;\n};\ntype AcornVariableDeclaration = EstreeVariableDeclaration & {\n start: number;\n end: number;\n declarations: AcornVariableDeclarator[];\n};\ntype AcornVariableDeclarator = EstreeVariableDeclarator & {\n start: number;\n end: number;\n id: AcornNode;\n init: AcornNode | null;\n};\n\n/**\n * Transform code for REPL evaluation.\n *\n * - Strips TypeScript syntax\n * - Hoists top-level variable declarations to globalThis\n * - Auto-returns the last expression\n * - Wraps in async IIFE for top-level await support\n */\nexport function transformForEval(code: string): string {\n let ast: AcornNode;\n try {\n ast = TSParser.parse(code, {\n ecmaVersion: \"latest\" as any,\n sourceType: \"module\",\n locations: true,\n }) as unknown as AcornNode;\n } catch {\n // If parsing fails, return the code as-is and let QuickJS report the error\n return `(async () => {\\n${code}\\n})()`;\n }\n\n const s = new MagicString(code);\n const program = ast as unknown as { body: AcornNode[] };\n const topLevelNodes = program.body;\n for (let i = 0; i < topLevelNodes.length; i++) {\n const node = topLevelNodes[i];\n\n // Remove TypeScript-only top-level declarations\n if (isTSOnlyNode(node)) {\n s.remove(node.start, node.end);\n continue;\n }\n\n // Remove import/export declarations (not supported in QuickJS eval)\n if (\n node.type === \"ImportDeclaration\" ||\n node.type === \"ExportNamedDeclaration\" ||\n node.type === \"ExportDefaultDeclaration\" ||\n node.type === \"ExportAllDeclaration\"\n ) {\n s.remove(node.start, node.end);\n continue;\n }\n\n // Hoist top-level variable declarations\n if (node.type === \"VariableDeclaration\") {\n hoistDeclaration(s, node as unknown as AcornVariableDeclaration);\n continue;\n }\n\n // Hoist function/class declarations to globalThis for cross-eval persistence\n if (\n node.type === \"FunctionDeclaration\" ||\n node.type === \"ClassDeclaration\"\n ) {\n stripTypeAnnotations(s, node);\n const name = (node as any).id?.name;\n if (name) {\n s.appendRight(node.end, `\\nglobalThis.${name} = ${name};`);\n }\n continue;\n }\n }\n\n // Strip type annotations from within expressions/statements\n for (const node of topLevelNodes) {\n if (isTSOnlyNode(node)) continue;\n if (\n node.type === \"ImportDeclaration\" ||\n node.type === \"ExportNamedDeclaration\" ||\n node.type === \"ExportDefaultDeclaration\" ||\n node.type === \"ExportAllDeclaration\"\n )\n continue;\n if (node.type !== \"VariableDeclaration\") {\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(s, n);\n },\n });\n }\n }\n\n // Auto-return the last expression. We insert `return (` before the\n // ExpressionStatement (to preserve any grouping parens like `({...})`),\n // but close `)` after the inner expression — not after the statement —\n // so any trailing semicolon stays outside: `return (expr);` not `return (expr;)`.\n const lastNode = findLastNonEmptyNode(topLevelNodes, s);\n if (lastNode && isExpression(lastNode)) {\n const { expression } = lastNode as AcornExpressionStatement;\n s.prependLeft(lastNode.start, \"return (\");\n s.appendRight(expression.end, \")\");\n }\n\n // Wrap in async IIFE\n s.prepend(\"(async () => {\\n\");\n s.append(\"\\n})()\");\n\n return s.toString();\n}\n\nfunction isTSOnlyNode(node: AcornNode): boolean {\n const t = node.type as string;\n if (\n t === \"TSTypeAliasDeclaration\" ||\n t === \"TSInterfaceDeclaration\" ||\n t === \"TSEnumDeclaration\" ||\n t === \"TSModuleDeclaration\" ||\n t === \"TSDeclareFunction\" ||\n t.startsWith(\"TS\")\n ) {\n return true;\n }\n // `declare const/let/var` — ambient variable declarations have no runtime effect\n if (t === \"VariableDeclaration\" && (node as any).declare === true) {\n return true;\n }\n // `import type { ... } from \"...\"` — type-only imports have no runtime effect\n if (t === \"ImportDeclaration\" && (node as any).importKind === \"type\") {\n return true;\n }\n // `export type { ... }` — type-only re-exports have no runtime effect\n if (t === \"ExportNamedDeclaration\" && (node as any).exportKind === \"type\") {\n return true;\n }\n return false;\n}\n\n/**\n * Rewrite a top-level VariableDeclaration to globalThis assignments.\n *\n * `const x = 1, y = 2` → `globalThis.x = 1; globalThis.y = 2`\n *\n */\nfunction hoistDeclaration(\n s: MagicString,\n decl: AcornVariableDeclaration,\n): void {\n const parts: string[] = [];\n\n for (const d of decl.declarations) {\n const id = d.id as AcornNode;\n if (id.type === \"Identifier\") {\n const initCode = d.init ? extractCleanInit(s, d) : \"undefined\";\n parts.push(\n `globalThis.${(id as unknown as Identifier).name} = ${initCode}`,\n );\n } else if (id.type === \"ObjectPattern\" || id.type === \"ArrayPattern\") {\n const bindings = extractBindingNames(d.id as any);\n const initCode = d.init ? extractCleanInit(s, d) : \"undefined\";\n const patternCode = extractCleanSource(s, d.id as AcornNode);\n parts.push(`var ${patternCode} = ${initCode}`);\n for (const name of bindings) {\n parts.push(`globalThis.${name} = ${name}`);\n }\n }\n }\n\n s.overwrite(decl.start, decl.end, parts.join(\"; \") + \";\");\n}\n\n/**\n * Extract the initializer code, stripping TypeScript annotations from\n * within the expression (e.g. `as Type`, generics, parameter types in\n * arrow functions).\n */\nfunction extractCleanInit(s: MagicString, d: AcornVariableDeclarator): string {\n if (!d.init) return \"undefined\";\n return extractCleanSource(s, d.init as AcornNode);\n}\n\nfunction extractBindingNames(pattern: any): string[] {\n const names: string[] = [];\n if (pattern.type === \"Identifier\") {\n if (pattern.name) names.push(pattern.name);\n } else if (pattern.type === \"ObjectPattern\") {\n for (const prop of pattern.properties || []) {\n if (prop.type === \"RestElement\") {\n names.push(...extractBindingNames(prop.argument));\n } else {\n names.push(...extractBindingNames(prop.value));\n }\n }\n } else if (pattern.type === \"ArrayPattern\") {\n for (const el of pattern.elements || []) {\n if (el) names.push(...extractBindingNames(el));\n }\n } else if (pattern.type === \"RestElement\") {\n names.push(...extractBindingNames(pattern.argument));\n } else if (pattern.type === \"AssignmentPattern\") {\n names.push(...extractBindingNames(pattern.left));\n }\n return names;\n}\n\nfunction stripTypeAnnotations(s: MagicString, node: AcornNode): void {\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(s, n);\n },\n });\n}\n\nfunction stripTypeAnnotationFromNode(s: MagicString, n: any, offset = 0): void {\n // Optional parameter marker: `b?: string` → `b`\n // The `?` sits between the identifier and the type annotation and must\n // be removed along with (or independently of) the type annotation.\n if (\n n.optional === true &&\n n.typeAnnotation &&\n n.typeAnnotation.start != null\n ) {\n // Remove `?: string` as a single span (the `?` is one char before `:`)\n s.remove(\n n.typeAnnotation.start - 1 - offset,\n n.typeAnnotation.end - offset,\n );\n } else if (n.optional === true && !n.typeAnnotation) {\n // `b?` with no type annotation — remove just the `?`\n const nameEnd =\n n.type === \"Identifier\" && typeof n.name === \"string\"\n ? n.start + n.name.length\n : null;\n if (nameEnd != null) {\n s.remove(nameEnd - offset, nameEnd + 1 - offset);\n }\n } else if (n.typeAnnotation && n.typeAnnotation.start != null) {\n // Regular type annotation without optional marker\n s.remove(n.typeAnnotation.start - offset, n.typeAnnotation.end - offset);\n }\n // Return type on functions\n if (n.returnType && n.returnType.start != null) {\n s.remove(n.returnType.start - offset, n.returnType.end - offset);\n }\n // Type parameters (generics)\n if (n.typeParameters && n.typeParameters.start != null) {\n s.remove(n.typeParameters.start - offset, n.typeParameters.end - offset);\n }\n // Type arguments on calls\n if (n.typeArguments && n.typeArguments.start != null) {\n s.remove(n.typeArguments.start - offset, n.typeArguments.end - offset);\n }\n // `as` expressions: keep the expression, remove `as Type`\n if (n.type === \"TSAsExpression\" && n.expression) {\n s.remove(n.expression.end - offset, n.end - offset);\n }\n // Non-null assertion: `x!` → `x`\n if (n.type === \"TSNonNullExpression\" && n.expression) {\n s.remove(n.expression.end - offset, n.end - offset);\n }\n // Satisfies expression: `x satisfies Type` → `x`\n if (n.type === \"TSSatisfiesExpression\" && n.expression) {\n s.remove(n.expression.end - offset, n.end - offset);\n }\n}\n\n/**\n * Extract a clean JS source string from an AST node, stripping all\n * TypeScript annotations. Works on a copy so the main MagicString is\n * not mutated.\n */\nfunction extractCleanSource(s: MagicString, node: AcornNode): string {\n const offset = node.start;\n const source = new MagicString(s.slice(node.start, node.end));\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(source, n, offset);\n },\n });\n return source.toString();\n}\n\nfunction findLastNonEmptyNode(\n nodes: AcornNode[],\n s: MagicString,\n): AcornNode | null {\n for (let i = nodes.length - 1; i >= 0; i--) {\n const node = nodes[i];\n // Skip nodes that were fully removed\n const slice = s.slice(node.start, node.end).trim();\n if (slice === \"\" || slice === \";\") continue;\n return node;\n }\n return null;\n}\n\nfunction isExpression(node: AcornNode): boolean {\n return node.type === \"ExpressionStatement\";\n}\n\n/**\n * Strip TypeScript type syntax from an ES-module source so QuickJS can\n * evaluate it as a standard JS module.\n *\n * Unlike `transformForEval`, this keeps `import`/`export` declarations,\n * does not hoist to `globalThis`, and does not wrap in an IIFE.\n * On parse failure the original source is returned unchanged.\n */\nexport function stripTypeSyntax(code: string): string {\n let ast: AcornNode;\n try {\n ast = TSParser.parse(code, {\n ecmaVersion: \"latest\",\n sourceType: \"module\",\n locations: true,\n }) as unknown as AcornNode;\n } catch {\n // Return the original source unchanged rather than throwing or returning an empty string.\n // We don't know why the parse failed - it could be a valid plain-JS file that hit an\n // acorn-typescript incompatibility, in which case returning it unchanged lets QuickJS\n // evaluate it correctly. If it's genuinely broken TS, QuickJS will surface the parse error\n // at evaluation time with a useful line/column.\n return code;\n }\n\n const magicString = new MagicString(code);\n const program = ast as unknown as { body: AcornNode[] };\n\n for (const node of program.body) {\n if (isTSOnlyNode(node)) {\n magicString.remove(node.start, node.end);\n continue;\n }\n\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(magicString, n);\n },\n });\n }\n\n return magicString.toString();\n}\n","/**\n * Serializes async operations on a shared WASM module.\n *\n * The quickjs-emscripten asyncify variant allows only one concurrent\n * async call per module instance. This queue enforces that constraint\n * by chaining operations into a promise queue — each caller waits for\n * the previous one to finish before executing.\n */\nexport class AsyncEvalQueue {\n private tail = Promise.resolve();\n\n /**\n * Enqueue an async operation. The operation will not start until all\n * previously enqueued operations have completed.\n */\n async enqueue<T>(fn: () => Promise<T>): Promise<T> {\n let release: () => void;\n const gate = new Promise<void>((r) => {\n release = r;\n });\n\n const prev = this.tail;\n this.tail = gate;\n\n return prev.then(async () => {\n try {\n return await fn();\n } finally {\n release();\n }\n });\n }\n}\n","/**\n * Core REPL engine built on quickjs-emscripten (asyncify variant).\n *\n * Host async functions (backend I/O, PTC tools) are exposed as\n * promise-returning functions inside the QuickJS guest. Guest code\n * uses `await` to consume them, enabling real concurrency via\n * `Promise.all`, `Promise.race`, etc.\n *\n * We still use the asyncify WASM variant because `evalCodeAsync` is\n * required to drive promise resolution from the host side.\n *\n * ## Architecture\n *\n * `ReplSession` is a serializable handle that can live in LangGraph state.\n * It holds an `id` that keys into a static session map. The heavy QuickJS\n * runtime is lazily started on the first `.eval()` call, making the session\n * safe across graph interrupts and checkpointing.\n */\n\nimport { shouldInterruptAfterDeadline } from \"quickjs-emscripten\";\nimport type { QuickJSHandle } from \"quickjs-emscripten\";\nimport { newQuickJSAsyncWASMModuleFromVariant } from \"quickjs-emscripten-core\";\nimport type {\n QuickJSAsyncContext,\n QuickJSAsyncRuntime,\n QuickJSAsyncWASMModule,\n} from \"quickjs-emscripten-core\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\n\nimport { PTCCallBudgetExceededError } from \"./errors.js\";\nimport type {\n ReplSessionOptions,\n ReplResult,\n SubagentBridgeOptions,\n} from \"./types.js\";\nimport { toCamelCase } from \"./utils.js\";\nimport { unwrapToolEnvelope } from \"./coerce.js\";\nimport { transformForEval } from \"./transform.js\";\nimport { AsyncEvalQueue } from \"./eval-queue.js\";\nimport PQueue from \"p-queue\";\n\nexport const DEFAULT_MEMORY_LIMIT = 64 * 1024 * 1024;\nexport const DEFAULT_MAX_STACK_SIZE = 320 * 1024;\nexport const DEFAULT_EXECUTION_TIMEOUT = 5_000;\nexport const DEFAULT_SESSION_ID = \"__default__\";\nexport const DEFAULT_MAX_PTC_CALLS = 256;\nexport const DEFAULT_MAX_RESULTS_CHARS = 4000;\nexport const DEFAULT_MAX_SUBAGENT_CONCURRENCY = 32;\n\nconst LINE_NUMBER_RE = /^\\s*\\d+(?:\\.\\d+)?\\t/;\n\nconst variantImport = import(\"@jitl/quickjs-ng-wasmfile-release-asyncify\");\n\n/**\n * Process-global eval queue. Serializes all evalCodeAsync calls across\n * sessions to enforce the asyncify one-at-a-time constraint.\n */\nconst sharedEvalQueue = new AsyncEvalQueue();\n\n/**\n * Process-global WASM module shared by all sessions.\n *\n * Each session creates its own runtime and context on this module,\n * providing full isolation for globals, heap, and stack. The module\n * itself is stateless between runtimes — only the compiled WASM code\n * and Emscripten infrastructure are shared.\n *\n * This is safe because:\n * - The module loader is synchronous (preloaded skill cache), so\n * imports don't cause asyncify suspensions.\n * - Tool injection uses the promise-based pattern (newFunction +\n * newPromise), not newAsyncifiedFunction, so tool calls don't\n * cause asyncify suspensions.\n * - The eval queue serializes evalCodeAsync calls to satisfy the\n * one-concurrent-async-call-per-module constraint.\n */\nlet sharedModulePromise: Promise<QuickJSAsyncWASMModule> | undefined;\n\nfunction getSharedModule(): Promise<QuickJSAsyncWASMModule> {\n if (!sharedModulePromise) {\n sharedModulePromise = (async () => {\n const variant = await variantImport;\n return newQuickJSAsyncWASMModuleFromVariant(\n (variant.default ?? variant) as any,\n );\n })();\n }\n return sharedModulePromise;\n}\n\n/**\n * Unwrap a PTC tool result to a plain string for use inside QuickJS.\n *\n * Tool results may arrive as a raw string, or as an array of LangChain\n * content blocks (`{ type: \"text\", text: \"...\" }`). Blocks are joined\n * with newlines; non-text block types are silently skipped. Anything\n * else (objects, nulls) is JSON-serialised as a fallback.\n *\n * @param result - Raw return value from `tool.invoke()`.\n * @returns Plain string representation of the tool output.\n */\nfunction extractToolText(result: unknown): string {\n // Unwrap LangChain Command / ToolMessage / message-list envelopes (e.g. a\n // PTC tool that returns a Command) before extracting text.\n result = unwrapToolEnvelope(result);\n\n if (typeof result === \"string\") {\n return result;\n }\n\n if (Array.isArray(result)) {\n const texts: string[] = [];\n for (const block of result) {\n if (\n typeof block === \"object\" &&\n block !== null &&\n (block as Record<string, unknown>).type === \"text\" &&\n typeof (block as Record<string, unknown>).text === \"string\"\n ) {\n texts.push((block as Record<string, unknown>).text as string);\n }\n }\n\n if (texts.length > 0) {\n return texts.join(\"\\n\");\n }\n }\n return JSON.stringify(result);\n}\n\n/**\n * Remove the `cat -n` line-number prefix from every line of a string.\n *\n * The filesystem backend formats file content with line numbers in the\n * form `\" N\\t\"` so human readers can navigate by line. That prefix\n * is useful for the agent but noise for QuickJS code that parses the\n * text programmatically (e.g. swarm reading `/context.txt`).\n *\n * The function is conservative: if any non-empty line lacks the prefix,\n * the text is returned unchanged so nothing is silently corrupted.\n *\n * @param text - Raw file content, possibly line-number prefixed.\n * @returns Content with line-number prefixes stripped, or the original\n * text if it doesn't match the expected format throughout.\n */\nfunction stripLineNumbers(text: string): string {\n const lines = text.split(\"\\n\");\n if (lines.length === 0) {\n return text;\n }\n\n if (!lines.every((l) => l === \"\" || LINE_NUMBER_RE.test(l))) {\n return text;\n }\n\n return lines.map((l) => l.replace(LINE_NUMBER_RE, \"\")).join(\"\\n\");\n}\n\n/**\n * Fixed-size character buffer for capturing console output from the QuickJS VM.\n *\n * Lines are accumulated up to `maxChars`. Once the cap is reached, excess\n * characters are counted as dropped rather than silently discarded without\n * attribution, so callers can surface a truncation notice to the user.\n */\nclass ConsoleBuffer {\n private readonly maxChars: number;\n private buffer: string = \"\";\n private droppedChars: number = 0;\n\n constructor(maxChars: number) {\n this.maxChars = Math.max(maxChars, 0);\n }\n\n /**\n * Append `line` to the buffer.\n *\n * If the buffer is already full the entire line is counted as dropped.\n * If `line` partially fits, the fitting prefix is stored and the remainder\n * is counted as dropped.\n */\n append(line: string): void {\n const remaining = this.maxChars - this.buffer.length;\n if (remaining <= 0) {\n this.droppedChars += line.length;\n return;\n }\n\n if (line.length <= remaining) {\n this.buffer += line;\n } else {\n this.buffer += line.slice(0, remaining);\n this.droppedChars += line.length - remaining;\n }\n }\n\n /**\n * Return the buffered output and dropped-character count as `[buffered,\n * droppedChars]`, then reset both to zero.\n */\n drain(): [string, number] {\n const out = this.buffer;\n const dropped = this.droppedChars;\n\n this.buffer = \"\";\n this.droppedChars = 0;\n\n return [out, dropped];\n }\n}\n\n/**\n * Sandboxed JavaScript REPL session backed by QuickJS WASM.\n *\n * Serializable — holds an `id` that keys into a static session map.\n * The QuickJS runtime is lazily started on the first `.eval()` call\n * and reconnected if a session with the same id already exists.\n * This makes it safe to store in LangGraph state across interrupts.\n */\nexport class ReplSession {\n private static sessions = new Map<string, ReplSession>();\n\n readonly id: string;\n\n private runtime: QuickJSAsyncRuntime | null = null;\n private context: QuickJSAsyncContext | null = null;\n private consoleBuffer: ConsoleBuffer = new ConsoleBuffer(\n DEFAULT_MAX_RESULTS_CHARS,\n );\n private options: ReplSessionOptions;\n private readonly maxPtcCalls: number | null;\n private ptcCallsRemaining: number | null = null;\n private subagentQueue: PQueue | null = null;\n private bridgeDispatchRef: {\n current: SubagentBridgeOptions[\"dispatch\"];\n } | null = null;\n\n /** Allowed keys in the subagent input object. */\n private static readonly SUBAGENT_ALLOWED_KEYS = new Set([\n \"description\",\n \"subagentType\",\n \"responseSchema\",\n ]);\n\n /**\n * Reset the shared WASM module. Forces the next session to instantiate\n * a fresh module. Only needed in tests where module state must be\n * isolated between test files.\n *\n * @internal\n */\n static resetSharedModule(): void {\n sharedModulePromise = undefined;\n }\n\n constructor(id: string, options: ReplSessionOptions = {}) {\n this.id = id;\n this.options = options;\n this.maxPtcCalls =\n options.maxPtcCalls !== undefined\n ? options.maxPtcCalls\n : DEFAULT_MAX_PTC_CALLS;\n }\n\n private async ensureStarted(): Promise<void> {\n if (this.runtime) return;\n\n const {\n memoryLimitBytes = DEFAULT_MEMORY_LIMIT,\n maxStackSizeBytes = DEFAULT_MAX_STACK_SIZE,\n tools,\n maxResultChars = DEFAULT_MAX_RESULTS_CHARS,\n captureConsole = true,\n } = this.options;\n\n const asyncModule = await getSharedModule();\n const runtime: QuickJSAsyncRuntime = asyncModule.newRuntime();\n runtime.setMemoryLimit(memoryLimitBytes);\n runtime.setMaxStackSize(maxStackSizeBytes);\n\n const context: QuickJSAsyncContext = runtime.newContext();\n this.runtime = runtime;\n this.context = context;\n\n this.consoleBuffer = new ConsoleBuffer(maxResultChars);\n if (captureConsole) {\n this.setupConsole();\n }\n\n if (tools !== undefined && tools.length > 0) {\n this.injectTools(tools);\n }\n\n const { subagentBridge } = this.options;\n if (subagentBridge) {\n this.subagentQueue = new PQueue({\n concurrency: subagentBridge.maxConcurrency,\n });\n this.injectSubagentBridge(subagentBridge.dispatch);\n }\n\n const sessionId = this.options.sessionId ?? \"default\";\n const sessionIdHandle = context.newString(sessionId);\n context.setProp(context.global, \"__sessionId__\", sessionIdHandle);\n sessionIdHandle.dispose();\n }\n\n /**\n * Initialise the per-eval PTC counter. Called at the top of every `eval()`.\n */\n private resetPtcBudget(): void {\n this.ptcCallsRemaining =\n this.maxPtcCalls === null ? null : this.maxPtcCalls;\n }\n\n /**\n * Decrement the PTC call counter and throw if the budget is exhausted.\n * `null` budget means unlimited — returns immediately without decrementing.\n */\n private consumePtcBudget(functionName: string): void {\n if (this.ptcCallsRemaining === null) {\n return;\n }\n\n if (this.ptcCallsRemaining > 0) {\n this.ptcCallsRemaining--;\n return;\n }\n\n const limit = this.maxPtcCalls ?? 0;\n throw new PTCCallBudgetExceededError({\n limit,\n attempted: limit + 1,\n functionName,\n });\n }\n\n /**\n * Get or create a session for the given id.\n *\n * Sessions are deduped by id — calling `getOrCreate` twice with the\n * same id returns the same instance. The QuickJS runtime is lazily\n * started on the first `.eval()` call.\n */\n static getOrCreate(\n id: string,\n options: ReplSessionOptions = {},\n ): ReplSession {\n const existing = ReplSession.sessions.get(id);\n if (existing) {\n return existing;\n }\n\n const session = new ReplSession(id, options);\n ReplSession.sessions.set(id, session);\n return session;\n }\n\n /**\n * Retrieve an existing session by id, or null if none exists.\n */\n static get(id: string): ReplSession | null {\n return ReplSession.sessions.get(id) ?? null;\n }\n\n /**\n * Returns true if any session exists whose key equals `threadId` or starts\n * with `threadId:`. Useful for tests that need to confirm a session was\n * created without knowing the full `threadId:middlewareId` key.\n */\n static hasAnyForThread(threadId: string): boolean {\n const prefix = `${threadId}:`;\n for (const key of ReplSession.sessions.keys()) {\n if (key === threadId || key.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Dispose and remove the session with the given key, if it exists.\n */\n static deleteSession(key: string): void {\n const session = ReplSession.sessions.get(key);\n if (session) {\n session.dispose();\n }\n }\n\n /**\n * Evaluate code in this session.\n *\n * Lazily starts the QuickJS runtime on the first call. Code is\n * transformed via an AST pipeline that strips TypeScript syntax,\n * hoists top-level declarations to globalThis for cross-eval\n * persistence, auto-returns the last expression, and wraps in an\n * async IIFE.\n */\n async eval(code: string, timeoutMs: number): Promise<ReplResult> {\n await this.ensureStarted();\n const runtime = this.runtime!;\n const context = this.context!;\n\n const drainLogs = (): { logs: string[]; logsDroppedChars: number } => {\n const [raw, dropped] = this.consoleBuffer.drain();\n return {\n logs: raw.length > 0 ? raw.split(\"\\n\").filter((l) => l.length > 0) : [],\n logsDroppedChars: dropped,\n };\n };\n\n this.resetPtcBudget();\n try {\n if (timeoutMs >= 0) {\n runtime.setInterruptHandler(\n shouldInterruptAfterDeadline(Date.now() + timeoutMs),\n );\n } else {\n runtime.setInterruptHandler(() => false);\n }\n\n const transformed = transformForEval(code);\n const result = await sharedEvalQueue.enqueue(() =>\n context.evalCodeAsync(transformed),\n );\n\n if (result.error) {\n const error = context.dump(result.error);\n result.error.dispose();\n return { ok: false, error, ...drainLogs() };\n }\n\n const promiseState = context.getPromiseState(result.value);\n\n if (promiseState.type === \"fulfilled\") {\n if (promiseState.notAPromise) {\n const value = context.dump(result.value);\n result.value.dispose();\n return { ok: true, value, ...drainLogs() };\n }\n const value = context.dump(promiseState.value);\n promiseState.value.dispose();\n result.value.dispose();\n return { ok: true, value, ...drainLogs() };\n }\n\n if (promiseState.type === \"rejected\") {\n const error = context.dump(promiseState.error);\n promiseState.error.dispose();\n result.value.dispose();\n return { ok: false, error, ...drainLogs() };\n }\n\n const noTimeout = timeoutMs < 0;\n const deadline = noTimeout ? Infinity : Date.now() + timeoutMs;\n while (noTimeout || Date.now() < deadline) {\n context.runtime.executePendingJobs();\n const state = context.getPromiseState(result.value);\n if (state.type === \"fulfilled\") {\n const value = context.dump(state.value);\n state.value.dispose();\n result.value.dispose();\n return { ok: true, value, ...drainLogs() };\n }\n if (state.type === \"rejected\") {\n const error = context.dump(state.error);\n state.error.dispose();\n result.value.dispose();\n return { ok: false, error, ...drainLogs() };\n }\n await new Promise((r) => setTimeout(r, 1));\n }\n\n result.value.dispose();\n return {\n ok: false,\n error: { message: \"Promise timed out — execution interrupted\" },\n ...drainLogs(),\n };\n } finally {\n this.ptcCallsRemaining = null;\n }\n }\n\n dispose(): void {\n try {\n this.context?.dispose();\n } catch {\n /* may already be disposed */\n }\n try {\n this.runtime?.dispose();\n } catch {\n /* may already be disposed */\n }\n this.runtime = null;\n this.context = null;\n ReplSession.sessions.delete(this.id);\n }\n\n toJSON(): { id: string } {\n return { id: this.id };\n }\n\n static fromJSON(data: { id: string }): ReplSession {\n return ReplSession.sessions.get(data.id) ?? new ReplSession(data.id);\n }\n\n /**\n * Clear the static session cache. Useful for testing.\n * @internal\n */\n static clearCache(): void {\n for (const session of ReplSession.sessions.values()) {\n session.dispose();\n }\n ReplSession.sessions.clear();\n }\n\n private setupConsole(): void {\n const context = this.context!;\n const consoleHandle = context.newObject();\n for (const method of [\"log\", \"warn\", \"error\", \"info\", \"debug\"] as const) {\n const fnHandle = context.newFunction(\n method,\n (...args: QuickJSHandle[]) => {\n const nativeArgs = args.map((a: QuickJSHandle) => context.dump(a));\n const formatted = nativeArgs\n .map((a: unknown) =>\n typeof a === \"object\" && a !== null\n ? JSON.stringify(a)\n : String(a),\n )\n .join(\" \");\n const line =\n method === \"log\" || method === \"info\" || method === \"debug\"\n ? formatted\n : `[${method}] ${formatted}`;\n this.consoleBuffer.append(line + \"\\n\");\n },\n );\n context.setProp(consoleHandle, method, fnHandle);\n fnHandle.dispose();\n }\n context.setProp(context.global, \"console\", consoleHandle);\n consoleHandle.dispose();\n }\n\n private injectTools(tools: StructuredToolInterface[]): void {\n const context = this.context!;\n const toolsNs = context.newObject();\n\n for (const t of tools) {\n const camelName = toCamelCase(t.name);\n const fnHandle = context.newFunction(\n camelName,\n (inputHandle: QuickJSHandle) => {\n const input = context.dump(inputHandle);\n const promise = context.newPromise();\n (async () => {\n try {\n this.consumePtcBudget(camelName);\n const rawInput =\n typeof input === \"object\" && input !== null ? input : {};\n const result = await t.invoke(rawInput);\n let text = extractToolText(result);\n if (t.name === \"read_file\") {\n text = stripLineNumbers(text);\n }\n const val = context.newString(text);\n promise.resolve(val);\n val.dispose();\n } catch (e: unknown) {\n const msg =\n e != null && typeof (e as Error).message === \"string\"\n ? (e as Error).message\n : String(e);\n const err = context.newError(`Tool '${t.name}' failed: ${msg}`);\n promise.reject(err);\n err.dispose();\n }\n promise.settled.then(context.runtime.executePendingJobs);\n })();\n return promise.handle;\n },\n );\n context.setProp(toolsNs, camelName, fnHandle);\n fnHandle.dispose();\n }\n\n context.setProp(context.global, \"tools\", toolsNs);\n toolsNs.dispose();\n }\n\n /**\n * Install the `task` global on the QuickJS context.\n *\n * Registers the host function directly as `globalThis.task`,\n * then freezes it via `evalCode`. Structured results (when\n * responseSchema is provided) are marshaled into native QuickJS\n * objects on the host side — no JS wrapper needed.\n */\n /**\n * Replace the active bridge dispatch with a fresh one.\n *\n * Call this before each eval so the dispatch closure carries\n * the current invocation's config (tracing callbacks, run ID, etc.)\n * rather than the stale config from session creation.\n */\n updateBridgeDispatch(dispatch: SubagentBridgeOptions[\"dispatch\"]): void {\n if (this.bridgeDispatchRef) {\n this.bridgeDispatchRef.current = dispatch;\n }\n }\n\n private injectSubagentBridge(\n dispatch: SubagentBridgeOptions[\"dispatch\"],\n ): void {\n const context = this.context!;\n const queue = this.subagentQueue!;\n\n this.bridgeDispatchRef = { current: dispatch };\n const ref = this.bridgeDispatchRef;\n\n const hostFn = context.newFunction(\"task\", (inputHandle: QuickJSHandle) => {\n const input = context.dump(inputHandle);\n const promise = context.newPromise();\n\n (async () => {\n try {\n if (\n input == null ||\n typeof input !== \"object\" ||\n Array.isArray(input)\n ) {\n throw new Error(\"task: expected an object argument\");\n }\n const raw = input as Record<string, unknown>;\n\n // Accept snake_case aliases so models don't need to know our convention\n const obj: Record<string, unknown> = { ...raw };\n if (\"subagent_type\" in obj) {\n obj.subagentType ??= obj.subagent_type;\n delete obj.subagent_type;\n }\n if (\"response_schema\" in obj) {\n obj.responseSchema ??= obj.response_schema;\n delete obj.response_schema;\n }\n\n const unknownKeys = Object.keys(obj).filter(\n (k) => !ReplSession.SUBAGENT_ALLOWED_KEYS.has(k),\n );\n if (unknownKeys.length > 0) {\n throw new Error(\n `task: unknown keys: ${unknownKeys.join(\", \")}. ` +\n `Allowed: ${[...ReplSession.SUBAGENT_ALLOWED_KEYS].join(\", \")}`,\n );\n }\n\n const { description, subagentType, responseSchema } = obj;\n\n if (typeof description !== \"string\" || description.length === 0) {\n throw new Error(\n \"task: 'description' is required and must be a non-empty string\",\n );\n }\n if (typeof subagentType !== \"string\" || subagentType.length === 0) {\n throw new Error(\n \"task: 'subagentType' is required and must be a non-empty string\",\n );\n }\n if (\n responseSchema !== undefined &&\n (responseSchema == null ||\n typeof responseSchema !== \"object\" ||\n Array.isArray(responseSchema))\n ) {\n throw new Error(\n \"task: 'responseSchema' must be a plain object (JSON Schema) when provided\",\n );\n }\n\n const result = await queue.add(() =>\n ref.current({\n description: description as string,\n subagentType: subagentType as string,\n ...(responseSchema !== undefined && {\n responseSchema: responseSchema as Record<string, unknown>,\n }),\n }),\n );\n if (typeof result === \"string\") {\n const val = context.newString(result);\n promise.resolve(val);\n val.dispose();\n } else {\n const jsonResult = context.evalCode(`(${JSON.stringify(result)})`);\n if (jsonResult.error) {\n const errDump = context.dump(jsonResult.error);\n jsonResult.error.dispose();\n throw new Error(\n `task: failed to marshal structured response: ${JSON.stringify(errDump)}`,\n );\n }\n promise.resolve(jsonResult.value);\n jsonResult.value.dispose();\n }\n } catch (e: unknown) {\n const msg =\n e != null && typeof (e as Error).message === \"string\"\n ? (e as Error).message\n : String(e);\n const err = context.newError(msg);\n promise.reject(err);\n err.dispose();\n }\n promise.settled.then(context.runtime.executePendingJobs);\n })();\n\n return promise.handle;\n });\n\n context.setProp(context.global, \"task\", hostFn);\n hostFn.dispose();\n\n context.evalCode(\n \"Object.freeze(globalThis.task);\" +\n \"Object.defineProperty(globalThis, 'task', {\" +\n \" value: globalThis.task,\" +\n \" writable: false,\" +\n \" configurable: false,\" +\n \"}); undefined\",\n );\n }\n}\n","const SCHEMA_MAX_BYTES = 4096;\nconst SCHEMA_MAX_DEPTH = 5;\nconst SCHEMA_MAX_PROPERTIES = 32;\n\n/**\n * Validate that a response schema does not exceed size, depth, or\n * property-count limits.\n *\n * @throws Error if any limit is exceeded.\n */\nexport function validateResponseSchema(schema: Record<string, unknown>): void {\n const serialized = JSON.stringify(schema);\n if (serialized.length > SCHEMA_MAX_BYTES) {\n throw new Error(\n `responseSchema exceeds ${SCHEMA_MAX_BYTES} byte limit (${serialized.length} bytes)`,\n );\n }\n\n function check(\n node: Record<string, unknown>,\n depth: number,\n propCount: { value: number },\n ): void {\n if (depth > SCHEMA_MAX_DEPTH) {\n throw new Error(\n `responseSchema exceeds maximum nesting depth of ${SCHEMA_MAX_DEPTH}`,\n );\n }\n const props = node.properties;\n if (props != null && typeof props === \"object\" && !Array.isArray(props)) {\n const propObj = props as Record<string, unknown>;\n propCount.value += Object.keys(propObj).length;\n if (propCount.value > SCHEMA_MAX_PROPERTIES) {\n throw new Error(\n `responseSchema exceeds maximum of ${SCHEMA_MAX_PROPERTIES} properties`,\n );\n }\n for (const value of Object.values(propObj)) {\n if (\n value != null &&\n typeof value === \"object\" &&\n !Array.isArray(value)\n ) {\n check(value as Record<string, unknown>, depth + 1, propCount);\n }\n }\n }\n const items = node.items;\n if (items != null && typeof items === \"object\" && !Array.isArray(items)) {\n check(items as Record<string, unknown>, depth + 1, propCount);\n }\n }\n\n check(schema, 0, { value: 0 });\n}\n","/**\n * Code Interpreter middleware for deepagents.\n *\n * Provides an `eval` tool that runs JavaScript in a WASM-sandboxed QuickJS\n * interpreter. Supports:\n * - Persistent state across evaluations (true REPL)\n * - Programmatic tool calling (PTC) — expose agent or custom tools inside the REPL\n */\n\nimport {\n createMiddleware,\n omitPayload,\n tool,\n type AgentMiddleware as _AgentMiddleware,\n} from \"langchain\";\nimport { z } from \"zod/v4\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY } from \"deepagents\";\n\nimport dedent from \"dedent\";\nimport type {\n CodeInterpreterMiddlewareOptions,\n SubagentBridgeOptions,\n} from \"./types.js\";\nimport {\n ReplSession,\n DEFAULT_EXECUTION_TIMEOUT,\n DEFAULT_MEMORY_LIMIT,\n DEFAULT_MAX_STACK_SIZE,\n DEFAULT_SESSION_ID,\n DEFAULT_MAX_PTC_CALLS,\n DEFAULT_MAX_RESULTS_CHARS,\n DEFAULT_MAX_SUBAGENT_CONCURRENCY,\n} from \"./session.js\";\nimport {\n formatReplResult,\n toCamelCase,\n toolToTypeSignature,\n safeToJsonSchema,\n} from \"./utils.js\";\nimport { validateResponseSchema } from \"./subagent-dispatch.js\";\nimport { unwrapToolEnvelope } from \"./coerce.js\";\n\n/**\n * These type-only imports are required for TypeScript's type inference to work\n * correctly with the langchain/langgraph middleware system. Without them, certain\n * generic type parameters fail to resolve properly, causing runtime issues with\n * tool schemas and message types.\n */\nimport type * as _zodTypes from \"@langchain/core/utils/types\";\nimport type * as _zodMeta from \"@langchain/langgraph/zod\";\nimport type * as _messages from \"@langchain/core/messages\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\n\nconst DEFAULT_TOOL_NAME = \"eval\";\n\n/**\n * Render the subagent dispatch prompt section for the system message.\n * Ported from the Python `_SUBAGENT_SYSTEM_PROMPT_TEMPLATE`.\n */\nfunction renderSubagentPrompt(toolName: string): string {\n return dedent`\n\n ### Dispatching Subagents with \\`task\\`\n\n \\`task\\` is your primitive for running configured subagents from inside the\n JavaScript REPL. Your job here is to DISTRIBUTE work, not to do it yourself:\n write JavaScript that fans work out to subagents and assembles their results.\n You handle the orchestration - fan-out, filtering, deduplication, multi-stage\n flow, and synthesis - in plain JavaScript.\n\n #### The primitive\n\n \\`\\`\\`javascript\n await task({\n description, // full autonomous task prompt\n subagentType, // configured subagent name\n responseSchema, // optional JSON Schema for structured output\n }); // -> Promise<unknown>\n \\`\\`\\`\n\n \\`task\\` runs a full agentic loop for the selected configured subagent. The\n subagent can use whatever tools it was configured with, iterate, inspect\n context, and return one final result. \\`subagentType\\` is required; use one of\n the configured subagent names.\n\n \\`description\\` is the only prompt the subagent receives for this dispatch. Make\n it complete: the goal, the constraints, what to inspect, and the exact shape\n or level of detail you expect back. Give context as locators — file paths and\n symbol names — not as pasted file contents. If you already read a file while\n exploring, still pass its path and let the subagent read it; do not paste back\n what you read. Each dispatch is stateless from the caller's perspective; you\n cannot send follow-up messages to the same subagent run.\n\n \\`responseSchema\\` is optional, but set it on any dispatch whose result feeds\n later code. A deterministic, typed shape is what lets you compose the next\n stage reliably — index it, sort it, compare fields, branch on it, merge it —\n instead of parsing free-form text. This is what makes a whole workflow\n composable as one script. When provided, the resolved value is already a typed\n JavaScript value matching the schema; do not call \\`JSON.parse\\` unless the\n subagent intentionally returned a JSON string. Dynamic schemas work for\n declarative subagents; runnable-backed subagents reject dynamic schemas because\n their runnable is already compiled.\n\n #### Approval model\n\n \\`task\\` dispatches from inside the already-running \\`${toolName}\\` call. It\n does not route through the parent agent's \\`ToolNode\\`-managed \\`task\\` tool and\n does not trigger parent-level \\`interrupt_on\\` / HITL approval for each dispatch.\n Declarative subagents still honor approval middleware configured inside their\n own spec. If you need approval before launching a subagent from the parent, use\n the normal \\`task\\` tool outside JavaScript or ensure the \\`${toolName}\\` call\n itself is approval-gated.\n\n #### Mental model\n\n Hold your work in JS: an array of items in, an array of results out. Merge each\n dispatch result back onto its item. Multi-stage analysis means: run a pass,\n filter or regroup the array in JS, then run another pass over the survivors.\n\n You can run the whole workflow in one \\`${toolName}\\` call or split it across\n several — both are fine. A single end-to-end script (generate, compare, pick a\n winner; or review every item, then synthesize) is clean when you can write it\n in one go; splitting is also fine when you want to inspect results between\n stages. Either way, don't redo work across calls — reuse what is already in\n scope (see \"Reuse what earlier evals left in scope\" below).\n\n #### Fan out with bounded concurrency\n\n Dispatch independent work in parallel with \\`Promise.all\\`, but in explicit\n batches around 10 so you do not launch hundreds of subagents at once. The bridge\n enforces a hard per-REPL cap of 32 concurrent subagent calls.\n\n \\`\\`\\`javascript\n const files = [\"/src/a.ts\", \"/src/b.ts\", \"/src/c.ts\"]; // found while exploring\n const batchSize = 10;\n const reviewed = [];\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n reviewed.push(...(await Promise.all(batch.map(async (file) => {\n const result = await task({\n description: \"Read \" + file + \" and review it for SQL injection. \" +\n \"Cite line numbers.\",\n subagentType: \"reviewer\",\n responseSchema: {\n type: \"object\",\n properties: {\n vulnerabilities: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n type: { type: \"string\" },\n line: { type: \"number\" },\n evidence: { type: \"string\" },\n },\n required: [\"type\", \"line\", \"evidence\"],\n },\n },\n },\n required: [\"vulnerabilities\"],\n },\n });\n return { file, ...result };\n }))));\n }\n \\`\\`\\`\n\n #### Explore with your own tools first, then distribute\n\n You already have your normal tools for reading, listing, globbing, and\n grepping files. Use them to explore and understand the task BEFORE you write\n the orchestration script. These are ordinary tool calls, separate from the\n \\`${toolName}\\` tool: read the data file, list or glob the directory, grep for\n what matters, then decide how to split the work.\n\n Never write \\`${toolName}\\` code that spawns a subagent just to read or parse a\n file or list a directory. That is a deterministic step you do yourself with a\n direct tool call; spending a whole agent loop on it is wasteful.\n\n Once you understand the shape of the work, you have creative freedom in how\n you split it:\n\n - One dispatch per file or per record, when the items are already separate.\n - Chunk a large input yourself — read it, split it, optionally write a small\n input file per chunk — and dispatch one subagent per chunk.\n - A cheap classification pass first, then deeper dispatches only for the items\n that warrant them.\n\n Then write JavaScript in the \\`${toolName}\\` tool that distributes the heavy,\n agentic work to subagents with \\`task()\\`: analyzing file contents, exploring a\n codebase, making judgment calls, rewriting code, or synthesizing a report.\n\n Hand each subagent a locator, not a payload. Subagents have their own file\n tools, so for anything that lives in a file — a file to review, rewrite, or\n audit — pass the path and let the subagent read it. Do NOT read a whole file\n just to paste its contents into the description; that bloats every dispatch\n and duplicates the file across them. Reserve inline content for small or\n derived data that has no path of its own: a single parsed record, or a chunk\n you split out of a larger input (write the chunk to its own file and pass that\n path if it is large). Assemble the results in JS.\n\n #### Compose multiple stages\n\n Filter the array in JS between passes. For example: first ask subagents for a\n cheap classification, filter to the risky items, then dispatch deeper reviews\n only for those items.\n\n \\`\\`\\`javascript\n const tagged = await Promise.all(files.map((file) =>\n task({\n description: \"Read \" + file + \" and classify it as handler, util, \" +\n \"test, or config.\",\n subagentType: \"reviewer\",\n responseSchema: {\n type: \"object\",\n properties: { kind: { type: \"string\" }, risky: { type: \"boolean\" } },\n required: [\"kind\", \"risky\"],\n },\n }).then((tag) => ({ file, ...tag }))\n ));\n\n const riskyHandlers = tagged.filter((it) => it.kind === \"handler\" && it.risky);\n const deepReviews = await Promise.all(riskyHandlers.map((it) =>\n task({\n description: \"Deep security review of \" + it.file + \". Cite line numbers.\",\n subagentType: \"reviewer\",\n }).then((review) => ({ ...it, review }))\n ));\n \\`\\`\\`\n\n #### Return results via the last expression, not \\`console.log\\`\n\n The value of the last expression in an \\`${toolName}\\` call (or a resolved\n top-level \\`await\\`) is returned to you as the result. Make that final\n expression the variable holding your result and read it from there.\n \\`console.log\\` is only for incidental debugging: its output is capped and\n truncated, while the returned value is not, so never \\`console.log\\` your\n actual results.\n\n Keep large intermediate sets in JS variables and return only a compact\n summary or a small slice, not the entire dataset. To persist full output,\n have a subagent write it, or write it with your own file tool outside the\n \\`${toolName}\\` call.\n\n #### Reuse what earlier evals left in scope\n\n The REPL is persistent within a turn: every top-level variable, function, and\n class you declare is kept and is available in your next \\`${toolName}\\` call\n (each is hoisted to global scope). So if a later step needs something an\n earlier eval produced or bound, **reference that variable by name** — do not\n write a new literal that re-types data a previous eval already returned or\n computed.\n\n If you catch yourself pasting a big array or object of values you produced in\n an earlier call, that is the tell: the variable is still in scope, so use it.\n Re-typing prior results as a fresh literal wastes tokens and drifts from what\n actually ran.\n\n \\`\\`\\`javascript\n // An earlier eval bound this:\n // const auditResults = await Promise.all(files.map(/* ...audit... */));\n\n // A later eval — reference it; do NOT paste the findings back in as a literal:\n const findings = auditResults.flatMap((r) =>\n r.findings.map((f) => ({ ...f, file: r.file }))\n );\n const verified = await Promise.all(findings.map((f) =>\n task({ description: \"Verify this finding: \" + f.evidence, subagentType: \"verifier\" })\n .then((v) => ({ ...f, ...v }))\n ));\n \\`\\`\\`\n\n #### When the user asks for a \"workflow\"\n\n If the user's request mentions running a \"workflow\" (or otherwise uses the\n word \"workflow\"), fan the work out to subagents rather than doing it all\n yourself. Explore with your own tools first as needed, then write JavaScript\n in the \\`${toolName}\\` tool that dispatches subagents with \\`task()\\` and\n assembles their results. The point is to distribute the heavy work in\n parallel, not to grind through it one tool call at a time.\n `;\n}\n\nfunction renderReplSystemPrompt(opts: {\n toolName: string;\n timeout: number;\n memoryLimitMb: number;\n hasPtc: boolean;\n}): string {\n const sideEffects = opts.hasPtc\n ? \" External side effects from inside the REPL are reachable only via the `tools.*` namespace documented below.\"\n : \" The REPL is pure computation; do any filesystem or other I/O with your normal tools, outside this tool.\";\n return dedent`\n ### Interpreter\n\n An \\`${opts.toolName}\\` tool is available. It runs JavaScript in a persistent REPL.\n - State (variables, functions) persists across tool calls within a single turn of conversation. They DO NOT persist across multiple turns.\n - Top-level \\`await\\` works; Promises resolve before the call returns.\n - Runtime sandbox: no built-in filesystem, network, stdlib, or wall-clock APIs (\\`fetch\\`, \\`require\\`, \\`fs\\`, \\`process\\`, real \\`Date.now()\\` are unavailable or stubbed).${sideEffects}\n - Timeout: ${opts.timeout}s per call. Memory: ${opts.memoryLimitMb} MB total.\n - \\`console.log\\` output is captured and returned alongside the result.\n `;\n}\n\n/**\n * Generate the PTC API Reference section for the system prompt.\n */\nexport async function generatePtcPrompt(\n tools: StructuredToolInterface[],\n): Promise<string> {\n if (tools.length === 0) return \"\";\n\n const signatures = await Promise.all(\n tools.map((t) => {\n const jsonSchema = t.schema ? safeToJsonSchema(t.schema) : undefined;\n return toolToTypeSignature(\n toCamelCase(t.name),\n t.description,\n jsonSchema,\n );\n }),\n );\n\n return dedent`\n\n ### API Reference — \\`tools\\` namespace\n\n The following agent tools are callable as async functions inside the REPL.\n Each takes a single object argument and returns a Promise that resolves to a string.\n Use \\`await\\` to call them. Promise APIs like \\`Promise.all\\` are also available.\n\n **Example usage:**\n \\`\\`\\`javascript\n // Call a tool\n const result = await tools.searchWeb({ query: \"QuickJS tutorial\" });\n console.log(result);\n\n // Concurrent calls\n const [a, b] = await Promise.all([\n tools.fetchData({ url: \"https://api.example.com/a\" }),\n tools.fetchData({ url: \"https://api.example.com/b\" }),\n ]);\n \\`\\`\\`\n\n **Available functions:**\n \\`\\`\\`typescript\n ${signatures.join(\"\\n\\n\")}\n \\`\\`\\`\n `;\n}\n\n/**\n * Resolves a mixed list of tool names and tool instances into a flat list of\n * StructuredToolInterface objects. Strings are looked up by name in agentTools;\n * instances are included directly without requiring agent registration. Strings\n * that don't match any agent tool are silently omitted.\n *\n * Throws if the subagent `task` tool is requested (by name or instance): it is\n * reserved for the `task()` global and cannot be a `tools.*` PTC member.\n */\nexport function resolveToolList(\n items: (string | StructuredToolInterface)[],\n agentTools: StructuredToolInterface[],\n): StructuredToolInterface[] {\n const agentByName = new Map(agentTools.map((t) => [t.name, t]));\n return items.flatMap((item) => {\n const name = typeof item === \"string\" ? item : item.name;\n if (name === \"task\") {\n throw new Error(\n \"The subagent `task` tool cannot be exposed via `ptc`. It is always \" +\n \"available as the top-level `task()` global inside the REPL (with \" +\n \"`subagentType` and `responseSchema` support); exposing it through the \" +\n \"`tools.*` namespace would create a second, conflicting dispatch path \" +\n 'that drops `responseSchema`. Remove \"task\" from `ptc`.',\n );\n }\n if (typeof item === \"string\") {\n const found = agentByName.get(item);\n return found ? [found] : [];\n }\n return [item];\n });\n}\n\n/**\n * Create the Code Interpreter middleware.\n */\nexport function createCodeInterpreterMiddleware(\n options: CodeInterpreterMiddlewareOptions = {},\n) {\n const {\n ptc,\n memoryLimitBytes = DEFAULT_MEMORY_LIMIT,\n maxStackSizeBytes = DEFAULT_MAX_STACK_SIZE,\n executionTimeoutMs = DEFAULT_EXECUTION_TIMEOUT,\n systemPrompt: customSystemPrompt = null,\n maxPtcCalls = DEFAULT_MAX_PTC_CALLS,\n maxResultChars = DEFAULT_MAX_RESULTS_CHARS,\n toolName = DEFAULT_TOOL_NAME,\n captureConsole = true,\n subagents = true,\n } = options;\n\n const maxSubagentConcurrency = subagents\n ? DEFAULT_MAX_SUBAGENT_CONCURRENCY\n : 0;\n\n if (maxPtcCalls !== null && maxPtcCalls !== undefined && maxPtcCalls < 1) {\n throw new Error(\"`maxPtcCalls` must be >= 1 or null\");\n }\n\n const middlewareId = crypto.randomUUID();\n\n let cachedPtcPrompt: string | null = null;\n let ptcTools: StructuredToolInterface[] = [];\n let taskTool: StructuredToolInterface | null = null;\n\n function filterToolsForPtc(\n allTools: StructuredToolInterface[],\n ): StructuredToolInterface[] {\n if (!ptc) return [];\n\n const candidates = allTools.filter((t) => t.name !== toolName);\n\n return resolveToolList(ptc, candidates);\n }\n\n function findTaskTool(\n tools: StructuredToolInterface[],\n ): StructuredToolInterface | null {\n return tools.find((t) => t.name === \"task\") ?? null;\n }\n\n function createBridgeDispatch(\n subagentTaskTool: StructuredToolInterface,\n config: LangGraphRunnableConfig,\n ): SubagentBridgeOptions[\"dispatch\"] {\n return async (input) => {\n const hasSchema = input.responseSchema != null;\n if (hasSchema) {\n validateResponseSchema(input.responseSchema!);\n }\n\n const toolConfig = {\n ...config,\n configurable: {\n ...config.configurable,\n ...(hasSchema && {\n [SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY]: input.responseSchema,\n }),\n },\n };\n\n const result = await subagentTaskTool.invoke(\n {\n description: input.description,\n subagent_type: input.subagentType,\n },\n toolConfig,\n );\n\n // The task tool resolves to a Command envelope; unwrap it to the\n // subagent's actual output before handing it back to the REPL.\n const content = unwrapToolEnvelope(result);\n\n if (hasSchema && typeof content === \"string\") {\n try {\n return JSON.parse(content);\n } catch {\n return content;\n }\n }\n return content;\n };\n }\n\n const evalTool = tool(\n async (input, config: LangGraphRunnableConfig) => {\n const threadId = config.configurable?.thread_id || DEFAULT_SESSION_ID;\n const sessionKey = `${threadId}:${middlewareId}`;\n\n const session = ReplSession.getOrCreate(sessionKey, {\n memoryLimitBytes,\n maxStackSizeBytes,\n maxPtcCalls,\n tools: ptcTools,\n maxResultChars,\n captureConsole,\n sessionId: threadId,\n subagentBridge:\n taskTool && maxSubagentConcurrency > 0\n ? {\n dispatch: createBridgeDispatch(taskTool, config),\n maxConcurrency: maxSubagentConcurrency,\n }\n : undefined,\n });\n\n if (taskTool && maxSubagentConcurrency > 0) {\n session.updateBridgeDispatch(createBridgeDispatch(taskTool, config));\n }\n\n const result = await session.eval(input.code, executionTimeoutMs);\n return formatReplResult(result);\n },\n {\n name: toolName,\n description: dedent`\n Evaluate TypeScript/JavaScript code in a sandboxed REPL. State persists across calls.\n Use console.log() for output. Returns the result of the last expression.\n If file or other tools are available, call them via the tools namespace: await tools.readFile({ path }).\n `,\n metadata: { ls_code_input_language: \"javascript\" },\n schema: z.object({\n code: z\n .string()\n .describe(\n \"TypeScript/JavaScript code to evaluate in the sandboxed REPL\",\n ),\n }),\n },\n );\n\n return createMiddleware({\n name: \"CodeInterpreterMiddleware\",\n tracePolicy: { processInputs: omitPayload },\n tools: [evalTool],\n wrapModelCall: async (request, handler) => {\n const agentTools = (request.tools || []) as StructuredToolInterface[];\n ptcTools = filterToolsForPtc(agentTools);\n\n if (!taskTool && maxSubagentConcurrency > 0) {\n taskTool = findTaskTool(agentTools);\n }\n\n if (ptcTools.length > 0 && !cachedPtcPrompt) {\n cachedPtcPrompt = await generatePtcPrompt(ptcTools);\n }\n\n const baseSystemPrompt =\n customSystemPrompt ||\n renderReplSystemPrompt({\n toolName,\n timeout: executionTimeoutMs / 1000,\n memoryLimitMb: Math.floor(memoryLimitBytes / (1024 * 1024)),\n hasPtc: ptcTools.length > 0,\n });\n\n const subagentPrompt =\n taskTool && maxSubagentConcurrency > 0\n ? renderSubagentPrompt(toolName)\n : \"\";\n\n const systemMessage = request.systemMessage\n .concat(baseSystemPrompt)\n .concat(subagentPrompt)\n .concat(cachedPtcPrompt || \"\");\n return handler({ ...request, systemMessage });\n },\n afterAgent: async (_state, runtime) => {\n const threadId = runtime.configurable?.thread_id ?? DEFAULT_SESSION_ID;\n const sessionKey = `${threadId}:${middlewareId}`;\n ReplSession.deleteSession(sessionKey);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,6BAAb,cAAgD,MAAM;CACpD;CACA;CACA;CAEA,YAAY,SAAuC;EACjD,MACE,mCAAmC,QAAQ,MAAM,cAAc,QAAQ,UAAU,aAAa,QAAQ,aAAa,EACrH;EACA,KAAK,OAAO;EACZ,KAAK,QAAQ,QAAQ;EACrB,KAAK,YAAY,QAAQ;EACzB,KAAK,eAAe,QAAQ;CAC9B;AACF;;;;;;AC7BA,SAAgB,YAAY,MAAsB;CAChD,OAAO,KAAK,QAAQ,iBAAiB,GAAG,MAAM,EAAE,YAAY,CAAC;AAC/D;;;;AAuBA,SAAgB,iBAAiB,QAA4B;CAC3D,MAAM,QAAkB,CAAC;CAEzB,IAAI,OAAO,KAAK,SAAS,GAAG;EAC1B,IAAI,WAAW,OAAO,KAAK,KAAK,IAAI;EACpC,IAAI,OAAO,mBAAmB,GAC5B,YAAY,gBAAgB,OAAO,iBAAiB;EAEtD,MAAM,KAAK,QAAQ;CACrB;CAEA,IAAI,OAAO,IACL;MAAA,OAAO,UAAU,KAAA,GAAW;GAC9B,MAAM,YACJ,OAAO,OAAO,UAAU,WACpB,OAAO,QACP,KAAK,UAAU,OAAO,OAAO,MAAM,CAAC;GAC1C,MAAM,KAAK,KAAK,WAAW;EAC7B;QACK,IAAI,OAAO,OAAO;EACvB,MAAM,UAAU,OAAO,MAAM,QAAQ;EACrC,MAAM,SAAS,OAA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B,eAAe,OAAO,SAAS,YAAY;GACzC,MAAM,aAAc,QAAQ,SAAS,CAAC;GACtC,WAAW,kBAAkB,UAAU;GAEvC,IAAI,CAAC,YAAY,yBAAyB,GACxC,WAAW,aAAa,UAAU;GAGpC,IAAI,SAAS,SAAS,KAAK,CAAC,iBAC1B,kBAAkB,MAAM,kBAAkB,QAAQ;GAGpD,MAAM,mBACJ,sBACA,uBAAuB;IACrB;IACA,SAAS,qBAAqB;IAC9B,eAAe,KAAK,MAAM,mBAAoB,OAAY;IAC1D,QAAQ,SAAS,SAAS;GAC5B,CAAC;GAEH,MAAM,iBACJ,YAAY,yBAAyB,IACjC,qBAAqB,QAAQ,IAC7B;GAEN,MAAM,gBAAgB,QAAQ,cAC3B,OAAO,gBAAgB,CAAC,CACxB,OAAO,cAAc,CAAC,CACtB,OAAO,mBAAmB,EAAE;GAC/B,OAAO,QAAQ;IAAE,GAAG;IAAS;GAAc,CAAC;EAC9C;EACA,YAAY,OAAO,QAAQ,YAAY;GAErC,MAAM,aAAa,GADF,QAAQ,cAAc,aAAA,cACR,GAAG;GAClC,YAAY,cAAc,UAAU;EACtC;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["toJsonSchema","compile","BaseMessage","isCommand","Parser","tsPlugin","MagicString","program","newQuickJSAsyncWASMModuleFromVariant","PQueue","shouldInterruptAfterDeadline","raw","SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY","tool","z","createMiddleware"],"sources":["../src/errors.ts","../src/utils.ts","../src/coerce.ts","../src/transform.ts","../src/eval-queue.ts","../src/session.ts","../src/subagent-dispatch.ts","../src/middleware.ts"],"sourcesContent":["/**\n * Options for constructing a {@link PTCCallBudgetExceededError}.\n */\ninterface PTCCallBudgetExceededOptions {\n /**\n * The configured per-eval PTC call limit.\n */\n limit: number;\n\n /**\n * The call number that triggered the violation (always `limit + 1`).\n */\n attempted: number;\n\n /**\n * The name of the tool function that was called over budget.\n */\n functionName: string;\n}\n\n/**\n * Thrown when a single eval exhausts its configured PTC call budget.\n */\nexport class PTCCallBudgetExceededError extends Error {\n readonly limit: number;\n readonly attempted: number;\n readonly functionName: string;\n\n constructor(options: PTCCallBudgetExceededOptions) {\n super(\n `PTC call budget exceeded (limit=${options.limit}, attempted=${options.attempted}, function=${options.functionName})`,\n );\n this.name = \"PTCCallBudgetExceededError\";\n this.limit = options.limit;\n this.attempted = options.attempted;\n this.functionName = options.functionName;\n }\n}\n","import { compile } from \"json-schema-to-typescript\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport dedent from \"dedent\";\nimport type { ReplResult } from \"./types.js\";\n\n/**\n * Convert a snake_case or kebab-case string to camelCase.\n */\nexport function toCamelCase(name: string): string {\n return name.replace(/[-_]([a-z])/g, (_, c) => c.toUpperCase());\n}\n\n/**\n * Recursively collect all string values from an object, array, or primitive.\n */\nexport function collectStrings(obj: unknown): string[] {\n const result: string[] = [];\n function walk(val: unknown) {\n if (typeof val === \"string\") {\n result.push(val);\n } else if (Array.isArray(val)) {\n for (const item of val) walk(item);\n } else if (typeof val === \"object\" && val !== null) {\n for (const v of Object.values(val)) walk(v);\n }\n }\n walk(obj);\n return result;\n}\n\n/**\n * Format the result of a REPL evaluation for the agent.\n */\nexport function formatReplResult(result: ReplResult): string {\n const parts: string[] = [];\n\n if (result.logs.length > 0) {\n let logsText = result.logs.join(\"\\n\");\n if (result.logsDroppedChars > 0) {\n logsText += `\\n[truncated ${result.logsDroppedChars} chars]`;\n }\n parts.push(logsText);\n }\n\n if (result.ok) {\n if (result.value !== undefined) {\n const formatted =\n typeof result.value === \"string\"\n ? result.value\n : JSON.stringify(result.value, null, 2);\n parts.push(`→ ${formatted}`);\n }\n } else if (result.error) {\n const errName = result.error.name || \"Error\";\n const errMsg = result.error.message || \"Unknown error\";\n parts.push(`${errName}: ${errMsg}`);\n if (result.error.stack) {\n parts.push(result.error.stack);\n }\n }\n\n return parts.join(\"\\n\") || \"(no output)\";\n}\n\nexport function safeToJsonSchema(\n schema: unknown,\n): Record<string, unknown> | undefined {\n try {\n return toJsonSchema(schema as Parameters<typeof toJsonSchema>[0]) as Record<\n string,\n unknown\n >;\n } catch {\n return undefined;\n }\n}\n\nasync function schemaToInterface(\n jsonSchema: Record<string, unknown>,\n interfaceName: string,\n): Promise<string> {\n const compiled = await compile(\n { ...jsonSchema, additionalProperties: false },\n interfaceName,\n { bannerComment: \"\", additionalProperties: false },\n );\n return compiled.replace(/^export /, \"\").trimEnd();\n}\n\nexport function capitalize(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nexport async function toolToTypeSignature(\n name: string,\n description: string,\n jsonSchema: Record<string, unknown> | undefined,\n): Promise<string> {\n const inputType = `${capitalize(name)}Input`;\n\n if (!jsonSchema || !jsonSchema.properties) {\n return dedent`\n /**\n * ${description}\n */\n async tools.${name}(input: Record<string, unknown>): Promise<string>\n `;\n }\n\n const iface = await schemaToInterface(jsonSchema, inputType);\n return dedent`\n ${iface}\n\n /**\n * ${description}\n */\n async tools.${name}(input: ${inputType}): Promise<string>\n `;\n}\n","/**\n * Coercion of tool / subagent return values for the QuickJS bridge.\n *\n * The deepagents `task` tool resolves to a LangGraph `Command` whose payload\n * carries the subagent's final message(s) under `update.messages`; some tools\n * return a `ToolMessage` or a list of messages. The interpreter bridges need\n * the underlying output, not the envelope, so this unwraps those shapes to the\n * content the model actually cares about.\n */\nimport { isCommand, type Command } from \"@langchain/langgraph\";\nimport { BaseMessage } from \"@langchain/core/messages\";\n\n/**\n * Return the trailing message content from a `Command`'s `update.messages`,\n * scanning from the end for the last message that actually has content. Returns\n * the command unchanged when it has no message-shaped payload.\n */\nfunction extractCommandContent(command: Command): unknown {\n const update: unknown = command.update;\n const messages =\n update !== null && typeof update === \"object\"\n ? (update as { messages?: unknown }).messages\n : undefined;\n if (Array.isArray(messages)) {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (BaseMessage.isInstance(message) && message.content != null) {\n return message.content;\n }\n }\n }\n return command;\n}\n\n/**\n * Unwrap a LangChain `Command` / `ToolMessage` / message-list envelope to the\n * underlying content. Non-envelope values (strings, content-block arrays, plain\n * objects) are returned unchanged.\n *\n * @param value The raw value returned by a tool or subagent dispatch.\n * @returns The unwrapped content, or `value` itself when it isn't an envelope.\n */\nexport function unwrapToolEnvelope(value: unknown): unknown {\n if (typeof value === \"string\") return value;\n\n if (isCommand(value)) {\n const inner = extractCommandContent(value);\n return inner === value ? value : unwrapToolEnvelope(inner);\n }\n\n if (BaseMessage.isInstance(value)) {\n return unwrapToolEnvelope(value.content);\n }\n\n if (Array.isArray(value)) {\n for (let i = value.length - 1; i >= 0; i--) {\n const entry = value[i];\n if (BaseMessage.isInstance(entry)) {\n return unwrapToolEnvelope(entry.content);\n }\n if (isCommand(entry)) {\n const inner = extractCommandContent(entry);\n if (inner !== entry) return unwrapToolEnvelope(inner);\n }\n }\n return value;\n }\n\n return value;\n}\n","/**\n * AST-based code transform pipeline for the REPL.\n *\n * Transforms TypeScript/JavaScript code into plain JS that can be\n * evaluated inside QuickJS with proper state persistence:\n *\n * 1. Parse with acorn + acorn-typescript (handles TS syntax)\n * 2. Strip TypeScript-only nodes (type annotations, interfaces, etc.)\n * 3. Hoist top-level declarations to globalThis for cross-eval persistence\n * 4. Auto-return the last expression\n * 5. Wrap in async IIFE so top-level await works\n */\n\nimport { Parser } from \"acorn\";\nimport { tsPlugin } from \"@sveltejs/acorn-typescript\";\nimport { walk } from \"estree-walker\";\nimport MagicString from \"magic-string\";\nimport type {\n Node,\n Identifier,\n VariableDeclaration as EstreeVariableDeclaration,\n VariableDeclarator as EstreeVariableDeclarator,\n} from \"estree\";\n\nconst TSParser = Parser.extend(tsPlugin());\n\ntype AcornNode = Node & { start: number; end: number };\ntype AcornExpressionStatement = AcornNode & {\n type: \"ExpressionStatement\";\n expression: AcornNode;\n};\ntype AcornVariableDeclaration = EstreeVariableDeclaration & {\n start: number;\n end: number;\n declarations: AcornVariableDeclarator[];\n};\ntype AcornVariableDeclarator = EstreeVariableDeclarator & {\n start: number;\n end: number;\n id: AcornNode;\n init: AcornNode | null;\n};\n\n/**\n * Transform code for REPL evaluation.\n *\n * - Strips TypeScript syntax\n * - Hoists top-level variable declarations to globalThis\n * - Auto-returns the last expression\n * - Wraps in async IIFE for top-level await support\n */\nexport function transformForEval(code: string): string {\n let ast: AcornNode;\n try {\n ast = TSParser.parse(code, {\n ecmaVersion: \"latest\" as any,\n sourceType: \"module\",\n locations: true,\n }) as unknown as AcornNode;\n } catch {\n // If parsing fails, return the code as-is and let QuickJS report the error\n return `(async () => {\\n${code}\\n})()`;\n }\n\n const s = new MagicString(code);\n const program = ast as unknown as { body: AcornNode[] };\n const topLevelNodes = program.body;\n for (let i = 0; i < topLevelNodes.length; i++) {\n const node = topLevelNodes[i];\n\n // Remove TypeScript-only top-level declarations\n if (isTSOnlyNode(node)) {\n s.remove(node.start, node.end);\n continue;\n }\n\n // Remove import/export declarations (not supported in QuickJS eval)\n if (\n node.type === \"ImportDeclaration\" ||\n node.type === \"ExportNamedDeclaration\" ||\n node.type === \"ExportDefaultDeclaration\" ||\n node.type === \"ExportAllDeclaration\"\n ) {\n s.remove(node.start, node.end);\n continue;\n }\n\n // Hoist top-level variable declarations\n if (node.type === \"VariableDeclaration\") {\n hoistDeclaration(s, node as unknown as AcornVariableDeclaration);\n continue;\n }\n\n // Hoist function/class declarations to globalThis for cross-eval persistence\n if (\n node.type === \"FunctionDeclaration\" ||\n node.type === \"ClassDeclaration\"\n ) {\n stripTypeAnnotations(s, node);\n const name = (node as any).id?.name;\n if (name) {\n s.appendRight(node.end, `\\nglobalThis.${name} = ${name};`);\n }\n continue;\n }\n }\n\n // Strip type annotations from within expressions/statements\n for (const node of topLevelNodes) {\n if (isTSOnlyNode(node)) continue;\n if (\n node.type === \"ImportDeclaration\" ||\n node.type === \"ExportNamedDeclaration\" ||\n node.type === \"ExportDefaultDeclaration\" ||\n node.type === \"ExportAllDeclaration\"\n )\n continue;\n if (node.type !== \"VariableDeclaration\") {\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(s, n);\n },\n });\n }\n }\n\n // Auto-return the last expression. We insert `return (` before the\n // ExpressionStatement (to preserve any grouping parens like `({...})`),\n // but close `)` after the inner expression — not after the statement —\n // so any trailing semicolon stays outside: `return (expr);` not `return (expr;)`.\n const lastNode = findLastNonEmptyNode(topLevelNodes, s);\n if (lastNode && isExpression(lastNode)) {\n const { expression } = lastNode as AcornExpressionStatement;\n s.prependLeft(lastNode.start, \"return (\");\n s.appendRight(expression.end, \")\");\n }\n\n // Wrap in async IIFE\n s.prepend(\"(async () => {\\n\");\n s.append(\"\\n})()\");\n\n return s.toString();\n}\n\nfunction isTSOnlyNode(node: AcornNode): boolean {\n const t = node.type as string;\n if (\n t === \"TSTypeAliasDeclaration\" ||\n t === \"TSInterfaceDeclaration\" ||\n t === \"TSEnumDeclaration\" ||\n t === \"TSModuleDeclaration\" ||\n t === \"TSDeclareFunction\" ||\n t.startsWith(\"TS\")\n ) {\n return true;\n }\n // `declare const/let/var` — ambient variable declarations have no runtime effect\n if (t === \"VariableDeclaration\" && (node as any).declare === true) {\n return true;\n }\n // `import type { ... } from \"...\"` — type-only imports have no runtime effect\n if (t === \"ImportDeclaration\" && (node as any).importKind === \"type\") {\n return true;\n }\n // `export type { ... }` — type-only re-exports have no runtime effect\n if (t === \"ExportNamedDeclaration\" && (node as any).exportKind === \"type\") {\n return true;\n }\n return false;\n}\n\n/**\n * Rewrite a top-level VariableDeclaration to globalThis assignments.\n *\n * `const x = 1, y = 2` → `globalThis.x = 1; globalThis.y = 2`\n *\n */\nfunction hoistDeclaration(\n s: MagicString,\n decl: AcornVariableDeclaration,\n): void {\n const parts: string[] = [];\n\n for (const d of decl.declarations) {\n const id = d.id as AcornNode;\n if (id.type === \"Identifier\") {\n const initCode = d.init ? extractCleanInit(s, d) : \"undefined\";\n parts.push(\n `globalThis.${(id as unknown as Identifier).name} = ${initCode}`,\n );\n } else if (id.type === \"ObjectPattern\" || id.type === \"ArrayPattern\") {\n const bindings = extractBindingNames(d.id as any);\n const initCode = d.init ? extractCleanInit(s, d) : \"undefined\";\n const patternCode = extractCleanSource(s, d.id as AcornNode);\n parts.push(`var ${patternCode} = ${initCode}`);\n for (const name of bindings) {\n parts.push(`globalThis.${name} = ${name}`);\n }\n }\n }\n\n s.overwrite(decl.start, decl.end, parts.join(\"; \") + \";\");\n}\n\n/**\n * Extract the initializer code, stripping TypeScript annotations from\n * within the expression (e.g. `as Type`, generics, parameter types in\n * arrow functions).\n */\nfunction extractCleanInit(s: MagicString, d: AcornVariableDeclarator): string {\n if (!d.init) return \"undefined\";\n return extractCleanSource(s, d.init as AcornNode);\n}\n\nfunction extractBindingNames(pattern: any): string[] {\n const names: string[] = [];\n if (pattern.type === \"Identifier\") {\n if (pattern.name) names.push(pattern.name);\n } else if (pattern.type === \"ObjectPattern\") {\n for (const prop of pattern.properties || []) {\n if (prop.type === \"RestElement\") {\n names.push(...extractBindingNames(prop.argument));\n } else {\n names.push(...extractBindingNames(prop.value));\n }\n }\n } else if (pattern.type === \"ArrayPattern\") {\n for (const el of pattern.elements || []) {\n if (el) names.push(...extractBindingNames(el));\n }\n } else if (pattern.type === \"RestElement\") {\n names.push(...extractBindingNames(pattern.argument));\n } else if (pattern.type === \"AssignmentPattern\") {\n names.push(...extractBindingNames(pattern.left));\n }\n return names;\n}\n\nfunction stripTypeAnnotations(s: MagicString, node: AcornNode): void {\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(s, n);\n },\n });\n}\n\nfunction stripTypeAnnotationFromNode(s: MagicString, n: any, offset = 0): void {\n // Optional parameter marker: `b?: string` → `b`\n // The `?` sits between the identifier and the type annotation and must\n // be removed along with (or independently of) the type annotation.\n if (\n n.optional === true &&\n n.typeAnnotation &&\n n.typeAnnotation.start != null\n ) {\n // Remove `?: string` as a single span (the `?` is one char before `:`)\n s.remove(\n n.typeAnnotation.start - 1 - offset,\n n.typeAnnotation.end - offset,\n );\n } else if (n.optional === true && !n.typeAnnotation) {\n // `b?` with no type annotation — remove just the `?`\n const nameEnd =\n n.type === \"Identifier\" && typeof n.name === \"string\"\n ? n.start + n.name.length\n : null;\n if (nameEnd != null) {\n s.remove(nameEnd - offset, nameEnd + 1 - offset);\n }\n } else if (n.typeAnnotation && n.typeAnnotation.start != null) {\n // Regular type annotation without optional marker\n s.remove(n.typeAnnotation.start - offset, n.typeAnnotation.end - offset);\n }\n // Return type on functions\n if (n.returnType && n.returnType.start != null) {\n s.remove(n.returnType.start - offset, n.returnType.end - offset);\n }\n // Type parameters (generics)\n if (n.typeParameters && n.typeParameters.start != null) {\n s.remove(n.typeParameters.start - offset, n.typeParameters.end - offset);\n }\n // Type arguments on calls\n if (n.typeArguments && n.typeArguments.start != null) {\n s.remove(n.typeArguments.start - offset, n.typeArguments.end - offset);\n }\n // `as` expressions: keep the expression, remove `as Type`\n if (n.type === \"TSAsExpression\" && n.expression) {\n s.remove(n.expression.end - offset, n.end - offset);\n }\n // Non-null assertion: `x!` → `x`\n if (n.type === \"TSNonNullExpression\" && n.expression) {\n s.remove(n.expression.end - offset, n.end - offset);\n }\n // Satisfies expression: `x satisfies Type` → `x`\n if (n.type === \"TSSatisfiesExpression\" && n.expression) {\n s.remove(n.expression.end - offset, n.end - offset);\n }\n}\n\n/**\n * Extract a clean JS source string from an AST node, stripping all\n * TypeScript annotations. Works on a copy so the main MagicString is\n * not mutated.\n */\nfunction extractCleanSource(s: MagicString, node: AcornNode): string {\n const offset = node.start;\n const source = new MagicString(s.slice(node.start, node.end));\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(source, n, offset);\n },\n });\n return source.toString();\n}\n\nfunction findLastNonEmptyNode(\n nodes: AcornNode[],\n s: MagicString,\n): AcornNode | null {\n for (let i = nodes.length - 1; i >= 0; i--) {\n const node = nodes[i];\n // Skip nodes that were fully removed\n const slice = s.slice(node.start, node.end).trim();\n if (slice === \"\" || slice === \";\") continue;\n return node;\n }\n return null;\n}\n\nfunction isExpression(node: AcornNode): boolean {\n return node.type === \"ExpressionStatement\";\n}\n\n/**\n * Strip TypeScript type syntax from an ES-module source so QuickJS can\n * evaluate it as a standard JS module.\n *\n * Unlike `transformForEval`, this keeps `import`/`export` declarations,\n * does not hoist to `globalThis`, and does not wrap in an IIFE.\n * On parse failure the original source is returned unchanged.\n */\nexport function stripTypeSyntax(code: string): string {\n let ast: AcornNode;\n try {\n ast = TSParser.parse(code, {\n ecmaVersion: \"latest\",\n sourceType: \"module\",\n locations: true,\n }) as unknown as AcornNode;\n } catch {\n // Return the original source unchanged rather than throwing or returning an empty string.\n // We don't know why the parse failed - it could be a valid plain-JS file that hit an\n // acorn-typescript incompatibility, in which case returning it unchanged lets QuickJS\n // evaluate it correctly. If it's genuinely broken TS, QuickJS will surface the parse error\n // at evaluation time with a useful line/column.\n return code;\n }\n\n const magicString = new MagicString(code);\n const program = ast as unknown as { body: AcornNode[] };\n\n for (const node of program.body) {\n if (isTSOnlyNode(node)) {\n magicString.remove(node.start, node.end);\n continue;\n }\n\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(magicString, n);\n },\n });\n }\n\n return magicString.toString();\n}\n","/**\n * Serializes async operations on a shared WASM module.\n *\n * The quickjs-emscripten asyncify variant allows only one concurrent\n * async call per module instance. This queue enforces that constraint\n * by chaining operations into a promise queue — each caller waits for\n * the previous one to finish before executing.\n */\nexport class AsyncEvalQueue {\n private tail = Promise.resolve();\n\n /**\n * Enqueue an async operation. The operation will not start until all\n * previously enqueued operations have completed.\n */\n async enqueue<T>(fn: () => Promise<T>): Promise<T> {\n let release: () => void;\n const gate = new Promise<void>((r) => {\n release = r;\n });\n\n const prev = this.tail;\n this.tail = gate;\n\n return prev.then(async () => {\n try {\n return await fn();\n } finally {\n release();\n }\n });\n }\n}\n","/**\n * Core REPL engine built on quickjs-emscripten (asyncify variant).\n *\n * Host async functions (backend I/O, PTC tools) are exposed as\n * promise-returning functions inside the QuickJS guest. Guest code\n * uses `await` to consume them, enabling real concurrency via\n * `Promise.all`, `Promise.race`, etc.\n *\n * We still use the asyncify WASM variant because `evalCodeAsync` is\n * required to drive promise resolution from the host side.\n *\n * ## Architecture\n *\n * `ReplSession` is a serializable handle that can live in LangGraph state.\n * It holds an `id` that keys into a static session map. The heavy QuickJS\n * runtime is lazily started on the first `.eval()` call, making the session\n * safe across graph interrupts and checkpointing.\n */\n\nimport { shouldInterruptAfterDeadline } from \"quickjs-emscripten\";\nimport type { QuickJSHandle } from \"quickjs-emscripten\";\nimport { newQuickJSAsyncWASMModuleFromVariant } from \"quickjs-emscripten-core\";\nimport type {\n QuickJSAsyncContext,\n QuickJSAsyncRuntime,\n QuickJSAsyncWASMModule,\n} from \"quickjs-emscripten-core\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\n\nimport { PTCCallBudgetExceededError } from \"./errors.js\";\nimport type {\n ReplSessionOptions,\n ReplResult,\n SubagentBridgeOptions,\n} from \"./types.js\";\nimport { toCamelCase } from \"./utils.js\";\nimport { unwrapToolEnvelope } from \"./coerce.js\";\nimport { transformForEval } from \"./transform.js\";\nimport { AsyncEvalQueue } from \"./eval-queue.js\";\nimport PQueue from \"p-queue\";\n\nexport const DEFAULT_MEMORY_LIMIT = 64 * 1024 * 1024;\nexport const DEFAULT_MAX_STACK_SIZE = 320 * 1024;\nexport const DEFAULT_EXECUTION_TIMEOUT = 5_000;\nexport const DEFAULT_SESSION_ID = \"__default__\";\nexport const DEFAULT_MAX_PTC_CALLS = 256;\nexport const DEFAULT_MAX_RESULTS_CHARS = 4000;\nexport const DEFAULT_MAX_SUBAGENT_CONCURRENCY = 32;\n\nconst LINE_NUMBER_RE = /^\\s*\\d+(?:\\.\\d+)?\\t/;\n\nconst variantImport = import(\"@jitl/quickjs-ng-wasmfile-release-asyncify\");\n\n/**\n * Process-global eval queue. Serializes all evalCodeAsync calls across\n * sessions to enforce the asyncify one-at-a-time constraint.\n */\nconst sharedEvalQueue = new AsyncEvalQueue();\n\n/**\n * Process-global WASM module shared by all sessions.\n *\n * Each session creates its own runtime and context on this module,\n * providing full isolation for globals, heap, and stack. The module\n * itself is stateless between runtimes — only the compiled WASM code\n * and Emscripten infrastructure are shared.\n *\n * This is safe because:\n * - The module loader is synchronous (preloaded skill cache), so\n * imports don't cause asyncify suspensions.\n * - Tool injection uses the promise-based pattern (newFunction +\n * newPromise), not newAsyncifiedFunction, so tool calls don't\n * cause asyncify suspensions.\n * - The eval queue serializes evalCodeAsync calls to satisfy the\n * one-concurrent-async-call-per-module constraint.\n */\nlet sharedModulePromise: Promise<QuickJSAsyncWASMModule> | undefined;\n\nfunction getSharedModule(): Promise<QuickJSAsyncWASMModule> {\n if (!sharedModulePromise) {\n sharedModulePromise = (async () => {\n const variant = await variantImport;\n return newQuickJSAsyncWASMModuleFromVariant(\n (variant.default ?? variant) as any,\n );\n })();\n }\n return sharedModulePromise;\n}\n\n/**\n * Unwrap a PTC tool result to a plain string for use inside QuickJS.\n *\n * Tool results may arrive as a raw string, or as an array of LangChain\n * content blocks (`{ type: \"text\", text: \"...\" }`). Blocks are joined\n * with newlines; non-text block types are silently skipped. Anything\n * else (objects, nulls) is JSON-serialised as a fallback.\n *\n * @param result - Raw return value from `tool.invoke()`.\n * @returns Plain string representation of the tool output.\n */\nfunction extractToolText(result: unknown): string {\n // Unwrap LangChain Command / ToolMessage / message-list envelopes (e.g. a\n // PTC tool that returns a Command) before extracting text.\n result = unwrapToolEnvelope(result);\n\n if (typeof result === \"string\") {\n return result;\n }\n\n if (Array.isArray(result)) {\n const texts: string[] = [];\n for (const block of result) {\n if (\n typeof block === \"object\" &&\n block !== null &&\n (block as Record<string, unknown>).type === \"text\" &&\n typeof (block as Record<string, unknown>).text === \"string\"\n ) {\n texts.push((block as Record<string, unknown>).text as string);\n }\n }\n\n if (texts.length > 0) {\n return texts.join(\"\\n\");\n }\n }\n return JSON.stringify(result);\n}\n\n/**\n * Remove the `cat -n` line-number prefix from every line of a string.\n *\n * The filesystem backend formats file content with line numbers in the\n * form `\" N\\t\"` so human readers can navigate by line. That prefix\n * is useful for the agent but noise for QuickJS code that parses the\n * text programmatically (e.g. swarm reading `/context.txt`).\n *\n * The function is conservative: if any non-empty line lacks the prefix,\n * the text is returned unchanged so nothing is silently corrupted.\n *\n * @param text - Raw file content, possibly line-number prefixed.\n * @returns Content with line-number prefixes stripped, or the original\n * text if it doesn't match the expected format throughout.\n */\nfunction stripLineNumbers(text: string): string {\n const lines = text.split(\"\\n\");\n if (lines.length === 0) {\n return text;\n }\n\n if (!lines.every((l) => l === \"\" || LINE_NUMBER_RE.test(l))) {\n return text;\n }\n\n return lines.map((l) => l.replace(LINE_NUMBER_RE, \"\")).join(\"\\n\");\n}\n\n/**\n * Fixed-size character buffer for capturing console output from the QuickJS VM.\n *\n * Lines are accumulated up to `maxChars`. Once the cap is reached, excess\n * characters are counted as dropped rather than silently discarded without\n * attribution, so callers can surface a truncation notice to the user.\n */\nclass ConsoleBuffer {\n private readonly maxChars: number;\n private buffer: string = \"\";\n private droppedChars: number = 0;\n\n constructor(maxChars: number) {\n this.maxChars = Math.max(maxChars, 0);\n }\n\n /**\n * Append `line` to the buffer.\n *\n * If the buffer is already full the entire line is counted as dropped.\n * If `line` partially fits, the fitting prefix is stored and the remainder\n * is counted as dropped.\n */\n append(line: string): void {\n const remaining = this.maxChars - this.buffer.length;\n if (remaining <= 0) {\n this.droppedChars += line.length;\n return;\n }\n\n if (line.length <= remaining) {\n this.buffer += line;\n } else {\n this.buffer += line.slice(0, remaining);\n this.droppedChars += line.length - remaining;\n }\n }\n\n /**\n * Return the buffered output and dropped-character count as `[buffered,\n * droppedChars]`, then reset both to zero.\n */\n drain(): [string, number] {\n const out = this.buffer;\n const dropped = this.droppedChars;\n\n this.buffer = \"\";\n this.droppedChars = 0;\n\n return [out, dropped];\n }\n}\n\n/**\n * Sandboxed JavaScript REPL session backed by QuickJS WASM.\n *\n * Serializable — holds an `id` that keys into a static session map.\n * The QuickJS runtime is lazily started on the first `.eval()` call\n * and reconnected if a session with the same id already exists.\n * This makes it safe to store in LangGraph state across interrupts.\n */\nexport class ReplSession {\n private static sessions = new Map<string, ReplSession>();\n\n readonly id: string;\n\n private runtime: QuickJSAsyncRuntime | null = null;\n private context: QuickJSAsyncContext | null = null;\n private consoleBuffer: ConsoleBuffer = new ConsoleBuffer(\n DEFAULT_MAX_RESULTS_CHARS,\n );\n private options: ReplSessionOptions;\n private readonly maxPtcCalls: number | null;\n private ptcCallsRemaining: number | null = null;\n private subagentQueue: PQueue | null = null;\n private bridgeDispatchRef: {\n current: SubagentBridgeOptions[\"dispatch\"];\n } | null = null;\n\n /** Allowed keys in the subagent input object. */\n private static readonly SUBAGENT_ALLOWED_KEYS = new Set([\n \"description\",\n \"subagentType\",\n \"responseSchema\",\n ]);\n\n /**\n * Reset the shared WASM module. Forces the next session to instantiate\n * a fresh module. Only needed in tests where module state must be\n * isolated between test files.\n *\n * @internal\n */\n static resetSharedModule(): void {\n sharedModulePromise = undefined;\n }\n\n constructor(id: string, options: ReplSessionOptions = {}) {\n this.id = id;\n this.options = options;\n this.maxPtcCalls =\n options.maxPtcCalls !== undefined\n ? options.maxPtcCalls\n : DEFAULT_MAX_PTC_CALLS;\n }\n\n private async ensureStarted(): Promise<void> {\n if (this.runtime) return;\n\n const {\n memoryLimitBytes = DEFAULT_MEMORY_LIMIT,\n maxStackSizeBytes = DEFAULT_MAX_STACK_SIZE,\n tools,\n maxResultChars = DEFAULT_MAX_RESULTS_CHARS,\n captureConsole = true,\n } = this.options;\n\n const asyncModule = await getSharedModule();\n const runtime: QuickJSAsyncRuntime = asyncModule.newRuntime();\n runtime.setMemoryLimit(memoryLimitBytes);\n runtime.setMaxStackSize(maxStackSizeBytes);\n\n const context: QuickJSAsyncContext = runtime.newContext();\n this.runtime = runtime;\n this.context = context;\n\n this.consoleBuffer = new ConsoleBuffer(maxResultChars);\n if (captureConsole) {\n this.setupConsole();\n }\n\n if (tools !== undefined && tools.length > 0) {\n this.injectTools(tools);\n }\n\n const { subagentBridge } = this.options;\n if (subagentBridge) {\n this.subagentQueue = new PQueue({\n concurrency: subagentBridge.maxConcurrency,\n });\n this.injectSubagentBridge(subagentBridge.dispatch);\n }\n\n const sessionId = this.options.sessionId ?? \"default\";\n const sessionIdHandle = context.newString(sessionId);\n context.setProp(context.global, \"__sessionId__\", sessionIdHandle);\n sessionIdHandle.dispose();\n }\n\n /**\n * Initialise the per-eval PTC counter. Called at the top of every `eval()`.\n */\n private resetPtcBudget(): void {\n this.ptcCallsRemaining =\n this.maxPtcCalls === null ? null : this.maxPtcCalls;\n }\n\n /**\n * Decrement the PTC call counter and throw if the budget is exhausted.\n * `null` budget means unlimited — returns immediately without decrementing.\n */\n private consumePtcBudget(functionName: string): void {\n if (this.ptcCallsRemaining === null) {\n return;\n }\n\n if (this.ptcCallsRemaining > 0) {\n this.ptcCallsRemaining--;\n return;\n }\n\n const limit = this.maxPtcCalls ?? 0;\n throw new PTCCallBudgetExceededError({\n limit,\n attempted: limit + 1,\n functionName,\n });\n }\n\n /**\n * Get or create a session for the given id.\n *\n * Sessions are deduped by id — calling `getOrCreate` twice with the\n * same id returns the same instance. The QuickJS runtime is lazily\n * started on the first `.eval()` call.\n */\n static getOrCreate(\n id: string,\n options: ReplSessionOptions = {},\n ): ReplSession {\n const existing = ReplSession.sessions.get(id);\n if (existing) {\n return existing;\n }\n\n const session = new ReplSession(id, options);\n ReplSession.sessions.set(id, session);\n return session;\n }\n\n /**\n * Retrieve an existing session by id, or null if none exists.\n */\n static get(id: string): ReplSession | null {\n return ReplSession.sessions.get(id) ?? null;\n }\n\n /**\n * Returns true if any session exists whose key equals `threadId` or starts\n * with `threadId:`. Useful for tests that need to confirm a session was\n * created without knowing the full `threadId:middlewareId` key.\n */\n static hasAnyForThread(threadId: string): boolean {\n const prefix = `${threadId}:`;\n for (const key of ReplSession.sessions.keys()) {\n if (key === threadId || key.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Dispose and remove the session with the given key, if it exists.\n */\n static deleteSession(key: string): void {\n const session = ReplSession.sessions.get(key);\n if (session) {\n session.dispose();\n }\n }\n\n /**\n * Evaluate code in this session.\n *\n * Lazily starts the QuickJS runtime on the first call. Code is\n * transformed via an AST pipeline that strips TypeScript syntax,\n * hoists top-level declarations to globalThis for cross-eval\n * persistence, auto-returns the last expression, and wraps in an\n * async IIFE.\n */\n async eval(code: string, timeoutMs: number): Promise<ReplResult> {\n await this.ensureStarted();\n const runtime = this.runtime!;\n const context = this.context!;\n\n const drainLogs = (): { logs: string[]; logsDroppedChars: number } => {\n const [raw, dropped] = this.consoleBuffer.drain();\n return {\n logs: raw.length > 0 ? raw.split(\"\\n\").filter((l) => l.length > 0) : [],\n logsDroppedChars: dropped,\n };\n };\n\n this.resetPtcBudget();\n try {\n if (timeoutMs >= 0) {\n runtime.setInterruptHandler(\n shouldInterruptAfterDeadline(Date.now() + timeoutMs),\n );\n } else {\n runtime.setInterruptHandler(() => false);\n }\n\n const transformed = transformForEval(code);\n const result = await sharedEvalQueue.enqueue(() =>\n context.evalCodeAsync(transformed),\n );\n\n if (result.error) {\n const error = context.dump(result.error);\n result.error.dispose();\n return { ok: false, error, ...drainLogs() };\n }\n\n const promiseState = context.getPromiseState(result.value);\n\n if (promiseState.type === \"fulfilled\") {\n if (promiseState.notAPromise) {\n const value = context.dump(result.value);\n result.value.dispose();\n return { ok: true, value, ...drainLogs() };\n }\n const value = context.dump(promiseState.value);\n promiseState.value.dispose();\n result.value.dispose();\n return { ok: true, value, ...drainLogs() };\n }\n\n if (promiseState.type === \"rejected\") {\n const error = context.dump(promiseState.error);\n promiseState.error.dispose();\n result.value.dispose();\n return { ok: false, error, ...drainLogs() };\n }\n\n const noTimeout = timeoutMs < 0;\n const deadline = noTimeout ? Infinity : Date.now() + timeoutMs;\n while (noTimeout || Date.now() < deadline) {\n context.runtime.executePendingJobs();\n const state = context.getPromiseState(result.value);\n if (state.type === \"fulfilled\") {\n const value = context.dump(state.value);\n state.value.dispose();\n result.value.dispose();\n return { ok: true, value, ...drainLogs() };\n }\n if (state.type === \"rejected\") {\n const error = context.dump(state.error);\n state.error.dispose();\n result.value.dispose();\n return { ok: false, error, ...drainLogs() };\n }\n await new Promise((r) => setTimeout(r, 1));\n }\n\n result.value.dispose();\n return {\n ok: false,\n error: { message: \"Promise timed out — execution interrupted\" },\n ...drainLogs(),\n };\n } finally {\n this.ptcCallsRemaining = null;\n }\n }\n\n dispose(): void {\n try {\n this.context?.dispose();\n } catch {\n /* may already be disposed */\n }\n try {\n this.runtime?.dispose();\n } catch {\n /* may already be disposed */\n }\n this.runtime = null;\n this.context = null;\n ReplSession.sessions.delete(this.id);\n }\n\n toJSON(): { id: string } {\n return { id: this.id };\n }\n\n static fromJSON(data: { id: string }): ReplSession {\n return ReplSession.sessions.get(data.id) ?? new ReplSession(data.id);\n }\n\n /**\n * Clear the static session cache. Useful for testing.\n * @internal\n */\n static clearCache(): void {\n for (const session of ReplSession.sessions.values()) {\n session.dispose();\n }\n ReplSession.sessions.clear();\n }\n\n private setupConsole(): void {\n const context = this.context!;\n const consoleHandle = context.newObject();\n for (const method of [\"log\", \"warn\", \"error\", \"info\", \"debug\"] as const) {\n const fnHandle = context.newFunction(\n method,\n (...args: QuickJSHandle[]) => {\n const nativeArgs = args.map((a: QuickJSHandle) => context.dump(a));\n const formatted = nativeArgs\n .map((a: unknown) =>\n typeof a === \"object\" && a !== null\n ? JSON.stringify(a)\n : String(a),\n )\n .join(\" \");\n const line =\n method === \"log\" || method === \"info\" || method === \"debug\"\n ? formatted\n : `[${method}] ${formatted}`;\n this.consoleBuffer.append(line + \"\\n\");\n },\n );\n context.setProp(consoleHandle, method, fnHandle);\n fnHandle.dispose();\n }\n context.setProp(context.global, \"console\", consoleHandle);\n consoleHandle.dispose();\n }\n\n private injectTools(tools: StructuredToolInterface[]): void {\n const context = this.context!;\n const toolsNs = context.newObject();\n\n for (const t of tools) {\n const camelName = toCamelCase(t.name);\n const fnHandle = context.newFunction(\n camelName,\n (inputHandle: QuickJSHandle) => {\n const input = context.dump(inputHandle);\n const promise = context.newPromise();\n (async () => {\n try {\n this.consumePtcBudget(camelName);\n const rawInput =\n typeof input === \"object\" && input !== null ? input : {};\n const result = await t.invoke(rawInput);\n let text = extractToolText(result);\n if (t.name === \"read_file\") {\n text = stripLineNumbers(text);\n }\n const val = context.newString(text);\n promise.resolve(val);\n val.dispose();\n } catch (e: unknown) {\n const msg =\n e != null && typeof (e as Error).message === \"string\"\n ? (e as Error).message\n : String(e);\n const err = context.newError(`Tool '${t.name}' failed: ${msg}`);\n promise.reject(err);\n err.dispose();\n }\n promise.settled.then(context.runtime.executePendingJobs);\n })();\n return promise.handle;\n },\n );\n context.setProp(toolsNs, camelName, fnHandle);\n fnHandle.dispose();\n }\n\n context.setProp(context.global, \"tools\", toolsNs);\n toolsNs.dispose();\n }\n\n /**\n * Install the `task` global on the QuickJS context.\n *\n * Registers the host function directly as `globalThis.task`,\n * then freezes it via `evalCode`. Structured results (when\n * responseSchema is provided) are marshaled into native QuickJS\n * objects on the host side — no JS wrapper needed.\n */\n /**\n * Replace the active bridge dispatch with a fresh one.\n *\n * Call this before each eval so the dispatch closure carries\n * the current invocation's config (tracing callbacks, run ID, etc.)\n * rather than the stale config from session creation.\n */\n updateBridgeDispatch(dispatch: SubagentBridgeOptions[\"dispatch\"]): void {\n if (this.bridgeDispatchRef) {\n this.bridgeDispatchRef.current = dispatch;\n }\n }\n\n private injectSubagentBridge(\n dispatch: SubagentBridgeOptions[\"dispatch\"],\n ): void {\n const context = this.context!;\n const queue = this.subagentQueue!;\n\n this.bridgeDispatchRef = { current: dispatch };\n const ref = this.bridgeDispatchRef;\n\n const hostFn = context.newFunction(\"task\", (inputHandle: QuickJSHandle) => {\n const input = context.dump(inputHandle);\n const promise = context.newPromise();\n\n (async () => {\n try {\n if (\n input == null ||\n typeof input !== \"object\" ||\n Array.isArray(input)\n ) {\n throw new Error(\"task: expected an object argument\");\n }\n const raw = input as Record<string, unknown>;\n\n // Accept snake_case aliases so models don't need to know our convention\n const obj: Record<string, unknown> = { ...raw };\n if (\"subagent_type\" in obj) {\n obj.subagentType ??= obj.subagent_type;\n delete obj.subagent_type;\n }\n if (\"response_schema\" in obj) {\n obj.responseSchema ??= obj.response_schema;\n delete obj.response_schema;\n }\n\n const unknownKeys = Object.keys(obj).filter(\n (k) => !ReplSession.SUBAGENT_ALLOWED_KEYS.has(k),\n );\n if (unknownKeys.length > 0) {\n throw new Error(\n `task: unknown keys: ${unknownKeys.join(\", \")}. ` +\n `Allowed: ${[...ReplSession.SUBAGENT_ALLOWED_KEYS].join(\", \")}`,\n );\n }\n\n const { description, subagentType, responseSchema } = obj;\n\n if (typeof description !== \"string\" || description.length === 0) {\n throw new Error(\n \"task: 'description' is required and must be a non-empty string\",\n );\n }\n if (typeof subagentType !== \"string\" || subagentType.length === 0) {\n throw new Error(\n \"task: 'subagentType' is required and must be a non-empty string\",\n );\n }\n if (\n responseSchema !== undefined &&\n (responseSchema == null ||\n typeof responseSchema !== \"object\" ||\n Array.isArray(responseSchema))\n ) {\n throw new Error(\n \"task: 'responseSchema' must be a plain object (JSON Schema) when provided\",\n );\n }\n\n const result = await queue.add(() =>\n ref.current({\n description: description as string,\n subagentType: subagentType as string,\n ...(responseSchema !== undefined && {\n responseSchema: responseSchema as Record<string, unknown>,\n }),\n }),\n );\n if (typeof result === \"string\") {\n const val = context.newString(result);\n promise.resolve(val);\n val.dispose();\n } else {\n const jsonResult = context.evalCode(`(${JSON.stringify(result)})`);\n if (jsonResult.error) {\n const errDump = context.dump(jsonResult.error);\n jsonResult.error.dispose();\n throw new Error(\n `task: failed to marshal structured response: ${JSON.stringify(errDump)}`,\n );\n }\n promise.resolve(jsonResult.value);\n jsonResult.value.dispose();\n }\n } catch (e: unknown) {\n const msg =\n e != null && typeof (e as Error).message === \"string\"\n ? (e as Error).message\n : String(e);\n const err = context.newError(msg);\n promise.reject(err);\n err.dispose();\n }\n promise.settled.then(context.runtime.executePendingJobs);\n })();\n\n return promise.handle;\n });\n\n context.setProp(context.global, \"task\", hostFn);\n hostFn.dispose();\n\n context.evalCode(\n \"Object.freeze(globalThis.task);\" +\n \"Object.defineProperty(globalThis, 'task', {\" +\n \" value: globalThis.task,\" +\n \" writable: false,\" +\n \" configurable: false,\" +\n \"}); undefined\",\n );\n }\n}\n","const SCHEMA_MAX_BYTES = 4096;\nconst SCHEMA_MAX_DEPTH = 5;\nconst SCHEMA_MAX_PROPERTIES = 32;\n\n/**\n * Validate that a response schema does not exceed size, depth, or\n * property-count limits.\n *\n * @throws Error if any limit is exceeded.\n */\nexport function validateResponseSchema(schema: Record<string, unknown>): void {\n const serialized = JSON.stringify(schema);\n if (serialized.length > SCHEMA_MAX_BYTES) {\n throw new Error(\n `responseSchema exceeds ${SCHEMA_MAX_BYTES} byte limit (${serialized.length} bytes)`,\n );\n }\n\n function check(\n node: Record<string, unknown>,\n depth: number,\n propCount: { value: number },\n ): void {\n if (depth > SCHEMA_MAX_DEPTH) {\n throw new Error(\n `responseSchema exceeds maximum nesting depth of ${SCHEMA_MAX_DEPTH}`,\n );\n }\n const props = node.properties;\n if (props != null && typeof props === \"object\" && !Array.isArray(props)) {\n const propObj = props as Record<string, unknown>;\n propCount.value += Object.keys(propObj).length;\n if (propCount.value > SCHEMA_MAX_PROPERTIES) {\n throw new Error(\n `responseSchema exceeds maximum of ${SCHEMA_MAX_PROPERTIES} properties`,\n );\n }\n for (const value of Object.values(propObj)) {\n if (\n value != null &&\n typeof value === \"object\" &&\n !Array.isArray(value)\n ) {\n check(value as Record<string, unknown>, depth + 1, propCount);\n }\n }\n }\n const items = node.items;\n if (items != null && typeof items === \"object\" && !Array.isArray(items)) {\n check(items as Record<string, unknown>, depth + 1, propCount);\n }\n }\n\n check(schema, 0, { value: 0 });\n}\n","/**\n * Code Interpreter middleware for deepagents.\n *\n * Provides an `eval` tool that runs JavaScript in a WASM-sandboxed QuickJS\n * interpreter. Supports:\n * - Persistent state across evaluations (true REPL)\n * - Programmatic tool calling (PTC) — expose agent or custom tools inside the REPL\n */\n\nimport {\n createMiddleware,\n tool,\n type AgentMiddleware as _AgentMiddleware,\n} from \"langchain\";\nimport { z } from \"zod/v4\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY } from \"deepagents\";\n\nimport dedent from \"dedent\";\nimport type {\n CodeInterpreterMiddlewareOptions,\n SubagentBridgeOptions,\n} from \"./types.js\";\nimport {\n ReplSession,\n DEFAULT_EXECUTION_TIMEOUT,\n DEFAULT_MEMORY_LIMIT,\n DEFAULT_MAX_STACK_SIZE,\n DEFAULT_SESSION_ID,\n DEFAULT_MAX_PTC_CALLS,\n DEFAULT_MAX_RESULTS_CHARS,\n DEFAULT_MAX_SUBAGENT_CONCURRENCY,\n} from \"./session.js\";\nimport {\n formatReplResult,\n toCamelCase,\n toolToTypeSignature,\n safeToJsonSchema,\n} from \"./utils.js\";\nimport { validateResponseSchema } from \"./subagent-dispatch.js\";\nimport { unwrapToolEnvelope } from \"./coerce.js\";\n\n/**\n * These type-only imports are required for TypeScript's type inference to work\n * correctly with the langchain/langgraph middleware system. Without them, certain\n * generic type parameters fail to resolve properly, causing runtime issues with\n * tool schemas and message types.\n */\nimport type * as _zodTypes from \"@langchain/core/utils/types\";\nimport type * as _zodMeta from \"@langchain/langgraph/zod\";\nimport type * as _messages from \"@langchain/core/messages\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\n\nconst DEFAULT_TOOL_NAME = \"eval\";\n\n/**\n * Render the subagent dispatch prompt section for the system message.\n * Ported from the Python `_SUBAGENT_SYSTEM_PROMPT_TEMPLATE`.\n */\nfunction renderSubagentPrompt(toolName: string): string {\n return dedent`\n\n ### Dispatching Subagents with \\`task\\`\n\n \\`task\\` is your primitive for running configured subagents from inside the\n JavaScript REPL. Your job here is to DISTRIBUTE work, not to do it yourself:\n write JavaScript that fans work out to subagents and assembles their results.\n You handle the orchestration - fan-out, filtering, deduplication, multi-stage\n flow, and synthesis - in plain JavaScript.\n\n #### The primitive\n\n \\`\\`\\`javascript\n await task({\n description, // full autonomous task prompt\n subagentType, // configured subagent name\n responseSchema, // optional JSON Schema for structured output\n }); // -> Promise<unknown>\n \\`\\`\\`\n\n \\`task\\` runs a full agentic loop for the selected configured subagent. The\n subagent can use whatever tools it was configured with, iterate, inspect\n context, and return one final result. \\`subagentType\\` is required; use one of\n the configured subagent names.\n\n \\`description\\` is the only prompt the subagent receives for this dispatch. Make\n it complete: the goal, the constraints, what to inspect, and the exact shape\n or level of detail you expect back. Give context as locators — file paths and\n symbol names — not as pasted file contents. If you already read a file while\n exploring, still pass its path and let the subagent read it; do not paste back\n what you read. Each dispatch is stateless from the caller's perspective; you\n cannot send follow-up messages to the same subagent run.\n\n \\`responseSchema\\` is optional, but set it on any dispatch whose result feeds\n later code. A deterministic, typed shape is what lets you compose the next\n stage reliably — index it, sort it, compare fields, branch on it, merge it —\n instead of parsing free-form text. This is what makes a whole workflow\n composable as one script. When provided, the resolved value is already a typed\n JavaScript value matching the schema; do not call \\`JSON.parse\\` unless the\n subagent intentionally returned a JSON string. Dynamic schemas work for\n declarative subagents; runnable-backed subagents reject dynamic schemas because\n their runnable is already compiled.\n\n #### Approval model\n\n \\`task\\` dispatches from inside the already-running \\`${toolName}\\` call. It\n does not route through the parent agent's \\`ToolNode\\`-managed \\`task\\` tool and\n does not trigger parent-level \\`interrupt_on\\` / HITL approval for each dispatch.\n Declarative subagents still honor approval middleware configured inside their\n own spec. If you need approval before launching a subagent from the parent, use\n the normal \\`task\\` tool outside JavaScript or ensure the \\`${toolName}\\` call\n itself is approval-gated.\n\n #### Mental model\n\n Hold your work in JS: an array of items in, an array of results out. Merge each\n dispatch result back onto its item. Multi-stage analysis means: run a pass,\n filter or regroup the array in JS, then run another pass over the survivors.\n\n You can run the whole workflow in one \\`${toolName}\\` call or split it across\n several — both are fine. A single end-to-end script (generate, compare, pick a\n winner; or review every item, then synthesize) is clean when you can write it\n in one go; splitting is also fine when you want to inspect results between\n stages. Either way, don't redo work across calls — reuse what is already in\n scope (see \"Reuse what earlier evals left in scope\" below).\n\n #### Fan out with bounded concurrency\n\n Dispatch independent work in parallel with \\`Promise.all\\`, but in explicit\n batches around 10 so you do not launch hundreds of subagents at once. The bridge\n enforces a hard per-REPL cap of 32 concurrent subagent calls.\n\n \\`\\`\\`javascript\n const files = [\"/src/a.ts\", \"/src/b.ts\", \"/src/c.ts\"]; // found while exploring\n const batchSize = 10;\n const reviewed = [];\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n reviewed.push(...(await Promise.all(batch.map(async (file) => {\n const result = await task({\n description: \"Read \" + file + \" and review it for SQL injection. \" +\n \"Cite line numbers.\",\n subagentType: \"reviewer\",\n responseSchema: {\n type: \"object\",\n properties: {\n vulnerabilities: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n type: { type: \"string\" },\n line: { type: \"number\" },\n evidence: { type: \"string\" },\n },\n required: [\"type\", \"line\", \"evidence\"],\n },\n },\n },\n required: [\"vulnerabilities\"],\n },\n });\n return { file, ...result };\n }))));\n }\n \\`\\`\\`\n\n #### Explore with your own tools first, then distribute\n\n You already have your normal tools for reading, listing, globbing, and\n grepping files. Use them to explore and understand the task BEFORE you write\n the orchestration script. These are ordinary tool calls, separate from the\n \\`${toolName}\\` tool: read the data file, list or glob the directory, grep for\n what matters, then decide how to split the work.\n\n Never write \\`${toolName}\\` code that spawns a subagent just to read or parse a\n file or list a directory. That is a deterministic step you do yourself with a\n direct tool call; spending a whole agent loop on it is wasteful.\n\n Once you understand the shape of the work, you have creative freedom in how\n you split it:\n\n - One dispatch per file or per record, when the items are already separate.\n - Chunk a large input yourself — read it, split it, optionally write a small\n input file per chunk — and dispatch one subagent per chunk.\n - A cheap classification pass first, then deeper dispatches only for the items\n that warrant them.\n\n Then write JavaScript in the \\`${toolName}\\` tool that distributes the heavy,\n agentic work to subagents with \\`task()\\`: analyzing file contents, exploring a\n codebase, making judgment calls, rewriting code, or synthesizing a report.\n\n Hand each subagent a locator, not a payload. Subagents have their own file\n tools, so for anything that lives in a file — a file to review, rewrite, or\n audit — pass the path and let the subagent read it. Do NOT read a whole file\n just to paste its contents into the description; that bloats every dispatch\n and duplicates the file across them. Reserve inline content for small or\n derived data that has no path of its own: a single parsed record, or a chunk\n you split out of a larger input (write the chunk to its own file and pass that\n path if it is large). Assemble the results in JS.\n\n #### Compose multiple stages\n\n Filter the array in JS between passes. For example: first ask subagents for a\n cheap classification, filter to the risky items, then dispatch deeper reviews\n only for those items.\n\n \\`\\`\\`javascript\n const tagged = await Promise.all(files.map((file) =>\n task({\n description: \"Read \" + file + \" and classify it as handler, util, \" +\n \"test, or config.\",\n subagentType: \"reviewer\",\n responseSchema: {\n type: \"object\",\n properties: { kind: { type: \"string\" }, risky: { type: \"boolean\" } },\n required: [\"kind\", \"risky\"],\n },\n }).then((tag) => ({ file, ...tag }))\n ));\n\n const riskyHandlers = tagged.filter((it) => it.kind === \"handler\" && it.risky);\n const deepReviews = await Promise.all(riskyHandlers.map((it) =>\n task({\n description: \"Deep security review of \" + it.file + \". Cite line numbers.\",\n subagentType: \"reviewer\",\n }).then((review) => ({ ...it, review }))\n ));\n \\`\\`\\`\n\n #### Return results via the last expression, not \\`console.log\\`\n\n The value of the last expression in an \\`${toolName}\\` call (or a resolved\n top-level \\`await\\`) is returned to you as the result. Make that final\n expression the variable holding your result and read it from there.\n \\`console.log\\` is only for incidental debugging: its output is capped and\n truncated, while the returned value is not, so never \\`console.log\\` your\n actual results.\n\n Keep large intermediate sets in JS variables and return only a compact\n summary or a small slice, not the entire dataset. To persist full output,\n have a subagent write it, or write it with your own file tool outside the\n \\`${toolName}\\` call.\n\n #### Reuse what earlier evals left in scope\n\n The REPL is persistent within a turn: every top-level variable, function, and\n class you declare is kept and is available in your next \\`${toolName}\\` call\n (each is hoisted to global scope). So if a later step needs something an\n earlier eval produced or bound, **reference that variable by name** — do not\n write a new literal that re-types data a previous eval already returned or\n computed.\n\n If you catch yourself pasting a big array or object of values you produced in\n an earlier call, that is the tell: the variable is still in scope, so use it.\n Re-typing prior results as a fresh literal wastes tokens and drifts from what\n actually ran.\n\n \\`\\`\\`javascript\n // An earlier eval bound this:\n // const auditResults = await Promise.all(files.map(/* ...audit... */));\n\n // A later eval — reference it; do NOT paste the findings back in as a literal:\n const findings = auditResults.flatMap((r) =>\n r.findings.map((f) => ({ ...f, file: r.file }))\n );\n const verified = await Promise.all(findings.map((f) =>\n task({ description: \"Verify this finding: \" + f.evidence, subagentType: \"verifier\" })\n .then((v) => ({ ...f, ...v }))\n ));\n \\`\\`\\`\n\n #### When the user asks for a \"workflow\"\n\n If the user's request mentions running a \"workflow\" (or otherwise uses the\n word \"workflow\"), fan the work out to subagents rather than doing it all\n yourself. Explore with your own tools first as needed, then write JavaScript\n in the \\`${toolName}\\` tool that dispatches subagents with \\`task()\\` and\n assembles their results. The point is to distribute the heavy work in\n parallel, not to grind through it one tool call at a time.\n `;\n}\n\nfunction renderReplSystemPrompt(opts: {\n toolName: string;\n timeout: number;\n memoryLimitMb: number;\n hasPtc: boolean;\n}): string {\n const sideEffects = opts.hasPtc\n ? \" External side effects from inside the REPL are reachable only via the `tools.*` namespace documented below.\"\n : \" The REPL is pure computation; do any filesystem or other I/O with your normal tools, outside this tool.\";\n return dedent`\n ### Interpreter\n\n An \\`${opts.toolName}\\` tool is available. It runs JavaScript in a persistent REPL.\n - State (variables, functions) persists across tool calls within a single turn of conversation. They DO NOT persist across multiple turns.\n - Top-level \\`await\\` works; Promises resolve before the call returns.\n - Runtime sandbox: no built-in filesystem, network, stdlib, or wall-clock APIs (\\`fetch\\`, \\`require\\`, \\`fs\\`, \\`process\\`, real \\`Date.now()\\` are unavailable or stubbed).${sideEffects}\n - Timeout: ${opts.timeout}s per call. Memory: ${opts.memoryLimitMb} MB total.\n - \\`console.log\\` output is captured and returned alongside the result.\n `;\n}\n\n/**\n * Generate the PTC API Reference section for the system prompt.\n */\nexport async function generatePtcPrompt(\n tools: StructuredToolInterface[],\n): Promise<string> {\n if (tools.length === 0) return \"\";\n\n const signatures = await Promise.all(\n tools.map((t) => {\n const jsonSchema = t.schema ? safeToJsonSchema(t.schema) : undefined;\n return toolToTypeSignature(\n toCamelCase(t.name),\n t.description,\n jsonSchema,\n );\n }),\n );\n\n return dedent`\n\n ### API Reference — \\`tools\\` namespace\n\n The following agent tools are callable as async functions inside the REPL.\n Each takes a single object argument and returns a Promise that resolves to a string.\n Use \\`await\\` to call them. Promise APIs like \\`Promise.all\\` are also available.\n\n **Example usage:**\n \\`\\`\\`javascript\n // Call a tool\n const result = await tools.searchWeb({ query: \"QuickJS tutorial\" });\n console.log(result);\n\n // Concurrent calls\n const [a, b] = await Promise.all([\n tools.fetchData({ url: \"https://api.example.com/a\" }),\n tools.fetchData({ url: \"https://api.example.com/b\" }),\n ]);\n \\`\\`\\`\n\n **Available functions:**\n \\`\\`\\`typescript\n ${signatures.join(\"\\n\\n\")}\n \\`\\`\\`\n `;\n}\n\n/**\n * Resolves a mixed list of tool names and tool instances into a flat list of\n * StructuredToolInterface objects. Strings are looked up by name in agentTools;\n * instances are included directly without requiring agent registration. Strings\n * that don't match any agent tool are silently omitted.\n *\n * Throws if the subagent `task` tool is requested (by name or instance): it is\n * reserved for the `task()` global and cannot be a `tools.*` PTC member.\n */\nexport function resolveToolList(\n items: (string | StructuredToolInterface)[],\n agentTools: StructuredToolInterface[],\n): StructuredToolInterface[] {\n const agentByName = new Map(agentTools.map((t) => [t.name, t]));\n return items.flatMap((item) => {\n const name = typeof item === \"string\" ? item : item.name;\n if (name === \"task\") {\n throw new Error(\n \"The subagent `task` tool cannot be exposed via `ptc`. It is always \" +\n \"available as the top-level `task()` global inside the REPL (with \" +\n \"`subagentType` and `responseSchema` support); exposing it through the \" +\n \"`tools.*` namespace would create a second, conflicting dispatch path \" +\n 'that drops `responseSchema`. Remove \"task\" from `ptc`.',\n );\n }\n if (typeof item === \"string\") {\n const found = agentByName.get(item);\n return found ? [found] : [];\n }\n return [item];\n });\n}\n\n/**\n * Create the Code Interpreter middleware.\n */\nexport function createCodeInterpreterMiddleware(\n options: CodeInterpreterMiddlewareOptions = {},\n) {\n const {\n ptc,\n memoryLimitBytes = DEFAULT_MEMORY_LIMIT,\n maxStackSizeBytes = DEFAULT_MAX_STACK_SIZE,\n executionTimeoutMs = DEFAULT_EXECUTION_TIMEOUT,\n systemPrompt: customSystemPrompt = null,\n maxPtcCalls = DEFAULT_MAX_PTC_CALLS,\n maxResultChars = DEFAULT_MAX_RESULTS_CHARS,\n toolName = DEFAULT_TOOL_NAME,\n captureConsole = true,\n subagents = true,\n } = options;\n\n const maxSubagentConcurrency = subagents\n ? DEFAULT_MAX_SUBAGENT_CONCURRENCY\n : 0;\n\n if (maxPtcCalls !== null && maxPtcCalls !== undefined && maxPtcCalls < 1) {\n throw new Error(\"`maxPtcCalls` must be >= 1 or null\");\n }\n\n const middlewareId = crypto.randomUUID();\n\n let cachedPtcPrompt: string | null = null;\n let ptcTools: StructuredToolInterface[] = [];\n let taskTool: StructuredToolInterface | null = null;\n\n function filterToolsForPtc(\n allTools: StructuredToolInterface[],\n ): StructuredToolInterface[] {\n if (!ptc) return [];\n\n const candidates = allTools.filter((t) => t.name !== toolName);\n\n return resolveToolList(ptc, candidates);\n }\n\n function findTaskTool(\n tools: StructuredToolInterface[],\n ): StructuredToolInterface | null {\n return tools.find((t) => t.name === \"task\") ?? null;\n }\n\n function createBridgeDispatch(\n subagentTaskTool: StructuredToolInterface,\n config: LangGraphRunnableConfig,\n ): SubagentBridgeOptions[\"dispatch\"] {\n return async (input) => {\n const hasSchema = input.responseSchema != null;\n if (hasSchema) {\n validateResponseSchema(input.responseSchema!);\n }\n\n const toolConfig = {\n ...config,\n configurable: {\n ...config.configurable,\n ...(hasSchema && {\n [SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY]: input.responseSchema,\n }),\n },\n };\n\n const result = await subagentTaskTool.invoke(\n {\n description: input.description,\n subagent_type: input.subagentType,\n },\n toolConfig,\n );\n\n // The task tool resolves to a Command envelope; unwrap it to the\n // subagent's actual output before handing it back to the REPL.\n const content = unwrapToolEnvelope(result);\n\n if (hasSchema && typeof content === \"string\") {\n try {\n return JSON.parse(content);\n } catch {\n return content;\n }\n }\n return content;\n };\n }\n\n const evalTool = tool(\n async (input, config: LangGraphRunnableConfig) => {\n const threadId = config.configurable?.thread_id || DEFAULT_SESSION_ID;\n const sessionKey = `${threadId}:${middlewareId}`;\n\n const session = ReplSession.getOrCreate(sessionKey, {\n memoryLimitBytes,\n maxStackSizeBytes,\n maxPtcCalls,\n tools: ptcTools,\n maxResultChars,\n captureConsole,\n sessionId: threadId,\n subagentBridge:\n taskTool && maxSubagentConcurrency > 0\n ? {\n dispatch: createBridgeDispatch(taskTool, config),\n maxConcurrency: maxSubagentConcurrency,\n }\n : undefined,\n });\n\n if (taskTool && maxSubagentConcurrency > 0) {\n session.updateBridgeDispatch(createBridgeDispatch(taskTool, config));\n }\n\n const result = await session.eval(input.code, executionTimeoutMs);\n return formatReplResult(result);\n },\n {\n name: toolName,\n description: dedent`\n Evaluate TypeScript/JavaScript code in a sandboxed REPL. State persists across calls.\n Use console.log() for output. Returns the result of the last expression.\n If file or other tools are available, call them via the tools namespace: await tools.readFile({ path }).\n `,\n metadata: { ls_code_input_language: \"javascript\" },\n schema: z.object({\n code: z\n .string()\n .describe(\n \"TypeScript/JavaScript code to evaluate in the sandboxed REPL\",\n ),\n }),\n },\n );\n\n return createMiddleware({\n name: \"CodeInterpreterMiddleware\",\n tools: [evalTool],\n wrapModelCall: async (request, handler) => {\n const agentTools = (request.tools || []) as StructuredToolInterface[];\n ptcTools = filterToolsForPtc(agentTools);\n\n if (!taskTool && maxSubagentConcurrency > 0) {\n taskTool = findTaskTool(agentTools);\n }\n\n if (ptcTools.length > 0 && !cachedPtcPrompt) {\n cachedPtcPrompt = await generatePtcPrompt(ptcTools);\n }\n\n const baseSystemPrompt =\n customSystemPrompt ||\n renderReplSystemPrompt({\n toolName,\n timeout: executionTimeoutMs / 1000,\n memoryLimitMb: Math.floor(memoryLimitBytes / (1024 * 1024)),\n hasPtc: ptcTools.length > 0,\n });\n\n const subagentPrompt =\n taskTool && maxSubagentConcurrency > 0\n ? renderSubagentPrompt(toolName)\n : \"\";\n\n const systemMessage = request.systemMessage\n .concat(baseSystemPrompt)\n .concat(subagentPrompt)\n .concat(cachedPtcPrompt || \"\");\n return handler({ ...request, systemMessage });\n },\n afterAgent: async (_state, runtime) => {\n const threadId = runtime.configurable?.thread_id ?? DEFAULT_SESSION_ID;\n const sessionKey = `${threadId}:${middlewareId}`;\n ReplSession.deleteSession(sessionKey);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,6BAAb,cAAgD,MAAM;CACpD;CACA;CACA;CAEA,YAAY,SAAuC;EACjD,MACE,mCAAmC,QAAQ,MAAM,cAAc,QAAQ,UAAU,aAAa,QAAQ,aAAa,EACrH;EACA,KAAK,OAAO;EACZ,KAAK,QAAQ,QAAQ;EACrB,KAAK,YAAY,QAAQ;EACzB,KAAK,eAAe,QAAQ;CAC9B;AACF;;;;;;AC7BA,SAAgB,YAAY,MAAsB;CAChD,OAAO,KAAK,QAAQ,iBAAiB,GAAG,MAAM,EAAE,YAAY,CAAC;AAC/D;;;;AAuBA,SAAgB,iBAAiB,QAA4B;CAC3D,MAAM,QAAkB,CAAC;CAEzB,IAAI,OAAO,KAAK,SAAS,GAAG;EAC1B,IAAI,WAAW,OAAO,KAAK,KAAK,IAAI;EACpC,IAAI,OAAO,mBAAmB,GAC5B,YAAY,gBAAgB,OAAO,iBAAiB;EAEtD,MAAM,KAAK,QAAQ;CACrB;CAEA,IAAI,OAAO,IACL;MAAA,OAAO,UAAU,KAAA,GAAW;GAC9B,MAAM,YACJ,OAAO,OAAO,UAAU,WACpB,OAAO,QACP,KAAK,UAAU,OAAO,OAAO,MAAM,CAAC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CAEA,QAAA,GAAOC,UAAAA,iBAAAA,CAAiB;EACtB,MAAM;EACN,OAAO,CAAC,QAAQ;EAChB,eAAe,OAAO,SAAS,YAAY;GACzC,MAAM,aAAc,QAAQ,SAAS,CAAC;GACtC,WAAW,kBAAkB,UAAU;GAEvC,IAAI,CAAC,YAAY,yBAAyB,GACxC,WAAW,aAAa,UAAU;GAGpC,IAAI,SAAS,SAAS,KAAK,CAAC,iBAC1B,kBAAkB,MAAM,kBAAkB,QAAQ;GAGpD,MAAM,mBACJ,sBACA,uBAAuB;IACrB;IACA,SAAS,qBAAqB;IAC9B,eAAe,KAAK,MAAM,mBAAoB,OAAY;IAC1D,QAAQ,SAAS,SAAS;GAC5B,CAAC;GAEH,MAAM,iBACJ,YAAY,yBAAyB,IACjC,qBAAqB,QAAQ,IAC7B;GAEN,MAAM,gBAAgB,QAAQ,cAC3B,OAAO,gBAAgB,CAAC,CACxB,OAAO,cAAc,CAAC,CACtB,OAAO,mBAAmB,EAAE;GAC/B,OAAO,QAAQ;IAAE,GAAG;IAAS;GAAc,CAAC;EAC9C;EACA,YAAY,OAAO,QAAQ,YAAY;GAErC,MAAM,aAAa,GADF,QAAQ,cAAc,aAAA,cACR,GAAG;GAClC,YAAY,cAAc,UAAU;EACtC;CACF,CAAC;AACH"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createMiddleware,
|
|
1
|
+
import { createMiddleware, tool } from "langchain";
|
|
2
2
|
import { z } from "zod/v4";
|
|
3
3
|
import { SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY } from "deepagents";
|
|
4
4
|
import dedent from "dedent";
|
|
@@ -1315,7 +1315,6 @@ function createCodeInterpreterMiddleware(options = {}) {
|
|
|
1315
1315
|
});
|
|
1316
1316
|
return createMiddleware({
|
|
1317
1317
|
name: "CodeInterpreterMiddleware",
|
|
1318
|
-
tracePolicy: { processInputs: omitPayload },
|
|
1319
1318
|
tools: [evalTool],
|
|
1320
1319
|
wrapModelCall: async (request, handler) => {
|
|
1321
1320
|
const agentTools = request.tools || [];
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["program","raw"],"sources":["../src/errors.ts","../src/utils.ts","../src/coerce.ts","../src/transform.ts","../src/eval-queue.ts","../src/session.ts","../src/subagent-dispatch.ts","../src/middleware.ts"],"sourcesContent":["/**\n * Options for constructing a {@link PTCCallBudgetExceededError}.\n */\ninterface PTCCallBudgetExceededOptions {\n /**\n * The configured per-eval PTC call limit.\n */\n limit: number;\n\n /**\n * The call number that triggered the violation (always `limit + 1`).\n */\n attempted: number;\n\n /**\n * The name of the tool function that was called over budget.\n */\n functionName: string;\n}\n\n/**\n * Thrown when a single eval exhausts its configured PTC call budget.\n */\nexport class PTCCallBudgetExceededError extends Error {\n readonly limit: number;\n readonly attempted: number;\n readonly functionName: string;\n\n constructor(options: PTCCallBudgetExceededOptions) {\n super(\n `PTC call budget exceeded (limit=${options.limit}, attempted=${options.attempted}, function=${options.functionName})`,\n );\n this.name = \"PTCCallBudgetExceededError\";\n this.limit = options.limit;\n this.attempted = options.attempted;\n this.functionName = options.functionName;\n }\n}\n","import { compile } from \"json-schema-to-typescript\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport dedent from \"dedent\";\nimport type { ReplResult } from \"./types.js\";\n\n/**\n * Convert a snake_case or kebab-case string to camelCase.\n */\nexport function toCamelCase(name: string): string {\n return name.replace(/[-_]([a-z])/g, (_, c) => c.toUpperCase());\n}\n\n/**\n * Recursively collect all string values from an object, array, or primitive.\n */\nexport function collectStrings(obj: unknown): string[] {\n const result: string[] = [];\n function walk(val: unknown) {\n if (typeof val === \"string\") {\n result.push(val);\n } else if (Array.isArray(val)) {\n for (const item of val) walk(item);\n } else if (typeof val === \"object\" && val !== null) {\n for (const v of Object.values(val)) walk(v);\n }\n }\n walk(obj);\n return result;\n}\n\n/**\n * Format the result of a REPL evaluation for the agent.\n */\nexport function formatReplResult(result: ReplResult): string {\n const parts: string[] = [];\n\n if (result.logs.length > 0) {\n let logsText = result.logs.join(\"\\n\");\n if (result.logsDroppedChars > 0) {\n logsText += `\\n[truncated ${result.logsDroppedChars} chars]`;\n }\n parts.push(logsText);\n }\n\n if (result.ok) {\n if (result.value !== undefined) {\n const formatted =\n typeof result.value === \"string\"\n ? result.value\n : JSON.stringify(result.value, null, 2);\n parts.push(`→ ${formatted}`);\n }\n } else if (result.error) {\n const errName = result.error.name || \"Error\";\n const errMsg = result.error.message || \"Unknown error\";\n parts.push(`${errName}: ${errMsg}`);\n if (result.error.stack) {\n parts.push(result.error.stack);\n }\n }\n\n return parts.join(\"\\n\") || \"(no output)\";\n}\n\nexport function safeToJsonSchema(\n schema: unknown,\n): Record<string, unknown> | undefined {\n try {\n return toJsonSchema(schema as Parameters<typeof toJsonSchema>[0]) as Record<\n string,\n unknown\n >;\n } catch {\n return undefined;\n }\n}\n\nasync function schemaToInterface(\n jsonSchema: Record<string, unknown>,\n interfaceName: string,\n): Promise<string> {\n const compiled = await compile(\n { ...jsonSchema, additionalProperties: false },\n interfaceName,\n { bannerComment: \"\", additionalProperties: false },\n );\n return compiled.replace(/^export /, \"\").trimEnd();\n}\n\nexport function capitalize(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nexport async function toolToTypeSignature(\n name: string,\n description: string,\n jsonSchema: Record<string, unknown> | undefined,\n): Promise<string> {\n const inputType = `${capitalize(name)}Input`;\n\n if (!jsonSchema || !jsonSchema.properties) {\n return dedent`\n /**\n * ${description}\n */\n async tools.${name}(input: Record<string, unknown>): Promise<string>\n `;\n }\n\n const iface = await schemaToInterface(jsonSchema, inputType);\n return dedent`\n ${iface}\n\n /**\n * ${description}\n */\n async tools.${name}(input: ${inputType}): Promise<string>\n `;\n}\n","/**\n * Coercion of tool / subagent return values for the QuickJS bridge.\n *\n * The deepagents `task` tool resolves to a LangGraph `Command` whose payload\n * carries the subagent's final message(s) under `update.messages`; some tools\n * return a `ToolMessage` or a list of messages. The interpreter bridges need\n * the underlying output, not the envelope, so this unwraps those shapes to the\n * content the model actually cares about.\n */\nimport { isCommand, type Command } from \"@langchain/langgraph\";\nimport { BaseMessage } from \"@langchain/core/messages\";\n\n/**\n * Return the trailing message content from a `Command`'s `update.messages`,\n * scanning from the end for the last message that actually has content. Returns\n * the command unchanged when it has no message-shaped payload.\n */\nfunction extractCommandContent(command: Command): unknown {\n const update: unknown = command.update;\n const messages =\n update !== null && typeof update === \"object\"\n ? (update as { messages?: unknown }).messages\n : undefined;\n if (Array.isArray(messages)) {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (BaseMessage.isInstance(message) && message.content != null) {\n return message.content;\n }\n }\n }\n return command;\n}\n\n/**\n * Unwrap a LangChain `Command` / `ToolMessage` / message-list envelope to the\n * underlying content. Non-envelope values (strings, content-block arrays, plain\n * objects) are returned unchanged.\n *\n * @param value The raw value returned by a tool or subagent dispatch.\n * @returns The unwrapped content, or `value` itself when it isn't an envelope.\n */\nexport function unwrapToolEnvelope(value: unknown): unknown {\n if (typeof value === \"string\") return value;\n\n if (isCommand(value)) {\n const inner = extractCommandContent(value);\n return inner === value ? value : unwrapToolEnvelope(inner);\n }\n\n if (BaseMessage.isInstance(value)) {\n return unwrapToolEnvelope(value.content);\n }\n\n if (Array.isArray(value)) {\n for (let i = value.length - 1; i >= 0; i--) {\n const entry = value[i];\n if (BaseMessage.isInstance(entry)) {\n return unwrapToolEnvelope(entry.content);\n }\n if (isCommand(entry)) {\n const inner = extractCommandContent(entry);\n if (inner !== entry) return unwrapToolEnvelope(inner);\n }\n }\n return value;\n }\n\n return value;\n}\n","/**\n * AST-based code transform pipeline for the REPL.\n *\n * Transforms TypeScript/JavaScript code into plain JS that can be\n * evaluated inside QuickJS with proper state persistence:\n *\n * 1. Parse with acorn + acorn-typescript (handles TS syntax)\n * 2. Strip TypeScript-only nodes (type annotations, interfaces, etc.)\n * 3. Hoist top-level declarations to globalThis for cross-eval persistence\n * 4. Auto-return the last expression\n * 5. Wrap in async IIFE so top-level await works\n */\n\nimport { Parser } from \"acorn\";\nimport { tsPlugin } from \"@sveltejs/acorn-typescript\";\nimport { walk } from \"estree-walker\";\nimport MagicString from \"magic-string\";\nimport type {\n Node,\n Identifier,\n VariableDeclaration as EstreeVariableDeclaration,\n VariableDeclarator as EstreeVariableDeclarator,\n} from \"estree\";\n\nconst TSParser = Parser.extend(tsPlugin());\n\ntype AcornNode = Node & { start: number; end: number };\ntype AcornExpressionStatement = AcornNode & {\n type: \"ExpressionStatement\";\n expression: AcornNode;\n};\ntype AcornVariableDeclaration = EstreeVariableDeclaration & {\n start: number;\n end: number;\n declarations: AcornVariableDeclarator[];\n};\ntype AcornVariableDeclarator = EstreeVariableDeclarator & {\n start: number;\n end: number;\n id: AcornNode;\n init: AcornNode | null;\n};\n\n/**\n * Transform code for REPL evaluation.\n *\n * - Strips TypeScript syntax\n * - Hoists top-level variable declarations to globalThis\n * - Auto-returns the last expression\n * - Wraps in async IIFE for top-level await support\n */\nexport function transformForEval(code: string): string {\n let ast: AcornNode;\n try {\n ast = TSParser.parse(code, {\n ecmaVersion: \"latest\" as any,\n sourceType: \"module\",\n locations: true,\n }) as unknown as AcornNode;\n } catch {\n // If parsing fails, return the code as-is and let QuickJS report the error\n return `(async () => {\\n${code}\\n})()`;\n }\n\n const s = new MagicString(code);\n const program = ast as unknown as { body: AcornNode[] };\n const topLevelNodes = program.body;\n for (let i = 0; i < topLevelNodes.length; i++) {\n const node = topLevelNodes[i];\n\n // Remove TypeScript-only top-level declarations\n if (isTSOnlyNode(node)) {\n s.remove(node.start, node.end);\n continue;\n }\n\n // Remove import/export declarations (not supported in QuickJS eval)\n if (\n node.type === \"ImportDeclaration\" ||\n node.type === \"ExportNamedDeclaration\" ||\n node.type === \"ExportDefaultDeclaration\" ||\n node.type === \"ExportAllDeclaration\"\n ) {\n s.remove(node.start, node.end);\n continue;\n }\n\n // Hoist top-level variable declarations\n if (node.type === \"VariableDeclaration\") {\n hoistDeclaration(s, node as unknown as AcornVariableDeclaration);\n continue;\n }\n\n // Hoist function/class declarations to globalThis for cross-eval persistence\n if (\n node.type === \"FunctionDeclaration\" ||\n node.type === \"ClassDeclaration\"\n ) {\n stripTypeAnnotations(s, node);\n const name = (node as any).id?.name;\n if (name) {\n s.appendRight(node.end, `\\nglobalThis.${name} = ${name};`);\n }\n continue;\n }\n }\n\n // Strip type annotations from within expressions/statements\n for (const node of topLevelNodes) {\n if (isTSOnlyNode(node)) continue;\n if (\n node.type === \"ImportDeclaration\" ||\n node.type === \"ExportNamedDeclaration\" ||\n node.type === \"ExportDefaultDeclaration\" ||\n node.type === \"ExportAllDeclaration\"\n )\n continue;\n if (node.type !== \"VariableDeclaration\") {\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(s, n);\n },\n });\n }\n }\n\n // Auto-return the last expression. We insert `return (` before the\n // ExpressionStatement (to preserve any grouping parens like `({...})`),\n // but close `)` after the inner expression — not after the statement —\n // so any trailing semicolon stays outside: `return (expr);` not `return (expr;)`.\n const lastNode = findLastNonEmptyNode(topLevelNodes, s);\n if (lastNode && isExpression(lastNode)) {\n const { expression } = lastNode as AcornExpressionStatement;\n s.prependLeft(lastNode.start, \"return (\");\n s.appendRight(expression.end, \")\");\n }\n\n // Wrap in async IIFE\n s.prepend(\"(async () => {\\n\");\n s.append(\"\\n})()\");\n\n return s.toString();\n}\n\nfunction isTSOnlyNode(node: AcornNode): boolean {\n const t = node.type as string;\n if (\n t === \"TSTypeAliasDeclaration\" ||\n t === \"TSInterfaceDeclaration\" ||\n t === \"TSEnumDeclaration\" ||\n t === \"TSModuleDeclaration\" ||\n t === \"TSDeclareFunction\" ||\n t.startsWith(\"TS\")\n ) {\n return true;\n }\n // `declare const/let/var` — ambient variable declarations have no runtime effect\n if (t === \"VariableDeclaration\" && (node as any).declare === true) {\n return true;\n }\n // `import type { ... } from \"...\"` — type-only imports have no runtime effect\n if (t === \"ImportDeclaration\" && (node as any).importKind === \"type\") {\n return true;\n }\n // `export type { ... }` — type-only re-exports have no runtime effect\n if (t === \"ExportNamedDeclaration\" && (node as any).exportKind === \"type\") {\n return true;\n }\n return false;\n}\n\n/**\n * Rewrite a top-level VariableDeclaration to globalThis assignments.\n *\n * `const x = 1, y = 2` → `globalThis.x = 1; globalThis.y = 2`\n *\n */\nfunction hoistDeclaration(\n s: MagicString,\n decl: AcornVariableDeclaration,\n): void {\n const parts: string[] = [];\n\n for (const d of decl.declarations) {\n const id = d.id as AcornNode;\n if (id.type === \"Identifier\") {\n const initCode = d.init ? extractCleanInit(s, d) : \"undefined\";\n parts.push(\n `globalThis.${(id as unknown as Identifier).name} = ${initCode}`,\n );\n } else if (id.type === \"ObjectPattern\" || id.type === \"ArrayPattern\") {\n const bindings = extractBindingNames(d.id as any);\n const initCode = d.init ? extractCleanInit(s, d) : \"undefined\";\n const patternCode = extractCleanSource(s, d.id as AcornNode);\n parts.push(`var ${patternCode} = ${initCode}`);\n for (const name of bindings) {\n parts.push(`globalThis.${name} = ${name}`);\n }\n }\n }\n\n s.overwrite(decl.start, decl.end, parts.join(\"; \") + \";\");\n}\n\n/**\n * Extract the initializer code, stripping TypeScript annotations from\n * within the expression (e.g. `as Type`, generics, parameter types in\n * arrow functions).\n */\nfunction extractCleanInit(s: MagicString, d: AcornVariableDeclarator): string {\n if (!d.init) return \"undefined\";\n return extractCleanSource(s, d.init as AcornNode);\n}\n\nfunction extractBindingNames(pattern: any): string[] {\n const names: string[] = [];\n if (pattern.type === \"Identifier\") {\n if (pattern.name) names.push(pattern.name);\n } else if (pattern.type === \"ObjectPattern\") {\n for (const prop of pattern.properties || []) {\n if (prop.type === \"RestElement\") {\n names.push(...extractBindingNames(prop.argument));\n } else {\n names.push(...extractBindingNames(prop.value));\n }\n }\n } else if (pattern.type === \"ArrayPattern\") {\n for (const el of pattern.elements || []) {\n if (el) names.push(...extractBindingNames(el));\n }\n } else if (pattern.type === \"RestElement\") {\n names.push(...extractBindingNames(pattern.argument));\n } else if (pattern.type === \"AssignmentPattern\") {\n names.push(...extractBindingNames(pattern.left));\n }\n return names;\n}\n\nfunction stripTypeAnnotations(s: MagicString, node: AcornNode): void {\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(s, n);\n },\n });\n}\n\nfunction stripTypeAnnotationFromNode(s: MagicString, n: any, offset = 0): void {\n // Optional parameter marker: `b?: string` → `b`\n // The `?` sits between the identifier and the type annotation and must\n // be removed along with (or independently of) the type annotation.\n if (\n n.optional === true &&\n n.typeAnnotation &&\n n.typeAnnotation.start != null\n ) {\n // Remove `?: string` as a single span (the `?` is one char before `:`)\n s.remove(\n n.typeAnnotation.start - 1 - offset,\n n.typeAnnotation.end - offset,\n );\n } else if (n.optional === true && !n.typeAnnotation) {\n // `b?` with no type annotation — remove just the `?`\n const nameEnd =\n n.type === \"Identifier\" && typeof n.name === \"string\"\n ? n.start + n.name.length\n : null;\n if (nameEnd != null) {\n s.remove(nameEnd - offset, nameEnd + 1 - offset);\n }\n } else if (n.typeAnnotation && n.typeAnnotation.start != null) {\n // Regular type annotation without optional marker\n s.remove(n.typeAnnotation.start - offset, n.typeAnnotation.end - offset);\n }\n // Return type on functions\n if (n.returnType && n.returnType.start != null) {\n s.remove(n.returnType.start - offset, n.returnType.end - offset);\n }\n // Type parameters (generics)\n if (n.typeParameters && n.typeParameters.start != null) {\n s.remove(n.typeParameters.start - offset, n.typeParameters.end - offset);\n }\n // Type arguments on calls\n if (n.typeArguments && n.typeArguments.start != null) {\n s.remove(n.typeArguments.start - offset, n.typeArguments.end - offset);\n }\n // `as` expressions: keep the expression, remove `as Type`\n if (n.type === \"TSAsExpression\" && n.expression) {\n s.remove(n.expression.end - offset, n.end - offset);\n }\n // Non-null assertion: `x!` → `x`\n if (n.type === \"TSNonNullExpression\" && n.expression) {\n s.remove(n.expression.end - offset, n.end - offset);\n }\n // Satisfies expression: `x satisfies Type` → `x`\n if (n.type === \"TSSatisfiesExpression\" && n.expression) {\n s.remove(n.expression.end - offset, n.end - offset);\n }\n}\n\n/**\n * Extract a clean JS source string from an AST node, stripping all\n * TypeScript annotations. Works on a copy so the main MagicString is\n * not mutated.\n */\nfunction extractCleanSource(s: MagicString, node: AcornNode): string {\n const offset = node.start;\n const source = new MagicString(s.slice(node.start, node.end));\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(source, n, offset);\n },\n });\n return source.toString();\n}\n\nfunction findLastNonEmptyNode(\n nodes: AcornNode[],\n s: MagicString,\n): AcornNode | null {\n for (let i = nodes.length - 1; i >= 0; i--) {\n const node = nodes[i];\n // Skip nodes that were fully removed\n const slice = s.slice(node.start, node.end).trim();\n if (slice === \"\" || slice === \";\") continue;\n return node;\n }\n return null;\n}\n\nfunction isExpression(node: AcornNode): boolean {\n return node.type === \"ExpressionStatement\";\n}\n\n/**\n * Strip TypeScript type syntax from an ES-module source so QuickJS can\n * evaluate it as a standard JS module.\n *\n * Unlike `transformForEval`, this keeps `import`/`export` declarations,\n * does not hoist to `globalThis`, and does not wrap in an IIFE.\n * On parse failure the original source is returned unchanged.\n */\nexport function stripTypeSyntax(code: string): string {\n let ast: AcornNode;\n try {\n ast = TSParser.parse(code, {\n ecmaVersion: \"latest\",\n sourceType: \"module\",\n locations: true,\n }) as unknown as AcornNode;\n } catch {\n // Return the original source unchanged rather than throwing or returning an empty string.\n // We don't know why the parse failed - it could be a valid plain-JS file that hit an\n // acorn-typescript incompatibility, in which case returning it unchanged lets QuickJS\n // evaluate it correctly. If it's genuinely broken TS, QuickJS will surface the parse error\n // at evaluation time with a useful line/column.\n return code;\n }\n\n const magicString = new MagicString(code);\n const program = ast as unknown as { body: AcornNode[] };\n\n for (const node of program.body) {\n if (isTSOnlyNode(node)) {\n magicString.remove(node.start, node.end);\n continue;\n }\n\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(magicString, n);\n },\n });\n }\n\n return magicString.toString();\n}\n","/**\n * Serializes async operations on a shared WASM module.\n *\n * The quickjs-emscripten asyncify variant allows only one concurrent\n * async call per module instance. This queue enforces that constraint\n * by chaining operations into a promise queue — each caller waits for\n * the previous one to finish before executing.\n */\nexport class AsyncEvalQueue {\n private tail = Promise.resolve();\n\n /**\n * Enqueue an async operation. The operation will not start until all\n * previously enqueued operations have completed.\n */\n async enqueue<T>(fn: () => Promise<T>): Promise<T> {\n let release: () => void;\n const gate = new Promise<void>((r) => {\n release = r;\n });\n\n const prev = this.tail;\n this.tail = gate;\n\n return prev.then(async () => {\n try {\n return await fn();\n } finally {\n release();\n }\n });\n }\n}\n","/**\n * Core REPL engine built on quickjs-emscripten (asyncify variant).\n *\n * Host async functions (backend I/O, PTC tools) are exposed as\n * promise-returning functions inside the QuickJS guest. Guest code\n * uses `await` to consume them, enabling real concurrency via\n * `Promise.all`, `Promise.race`, etc.\n *\n * We still use the asyncify WASM variant because `evalCodeAsync` is\n * required to drive promise resolution from the host side.\n *\n * ## Architecture\n *\n * `ReplSession` is a serializable handle that can live in LangGraph state.\n * It holds an `id` that keys into a static session map. The heavy QuickJS\n * runtime is lazily started on the first `.eval()` call, making the session\n * safe across graph interrupts and checkpointing.\n */\n\nimport { shouldInterruptAfterDeadline } from \"quickjs-emscripten\";\nimport type { QuickJSHandle } from \"quickjs-emscripten\";\nimport { newQuickJSAsyncWASMModuleFromVariant } from \"quickjs-emscripten-core\";\nimport type {\n QuickJSAsyncContext,\n QuickJSAsyncRuntime,\n QuickJSAsyncWASMModule,\n} from \"quickjs-emscripten-core\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\n\nimport { PTCCallBudgetExceededError } from \"./errors.js\";\nimport type {\n ReplSessionOptions,\n ReplResult,\n SubagentBridgeOptions,\n} from \"./types.js\";\nimport { toCamelCase } from \"./utils.js\";\nimport { unwrapToolEnvelope } from \"./coerce.js\";\nimport { transformForEval } from \"./transform.js\";\nimport { AsyncEvalQueue } from \"./eval-queue.js\";\nimport PQueue from \"p-queue\";\n\nexport const DEFAULT_MEMORY_LIMIT = 64 * 1024 * 1024;\nexport const DEFAULT_MAX_STACK_SIZE = 320 * 1024;\nexport const DEFAULT_EXECUTION_TIMEOUT = 5_000;\nexport const DEFAULT_SESSION_ID = \"__default__\";\nexport const DEFAULT_MAX_PTC_CALLS = 256;\nexport const DEFAULT_MAX_RESULTS_CHARS = 4000;\nexport const DEFAULT_MAX_SUBAGENT_CONCURRENCY = 32;\n\nconst LINE_NUMBER_RE = /^\\s*\\d+(?:\\.\\d+)?\\t/;\n\nconst variantImport = import(\"@jitl/quickjs-ng-wasmfile-release-asyncify\");\n\n/**\n * Process-global eval queue. Serializes all evalCodeAsync calls across\n * sessions to enforce the asyncify one-at-a-time constraint.\n */\nconst sharedEvalQueue = new AsyncEvalQueue();\n\n/**\n * Process-global WASM module shared by all sessions.\n *\n * Each session creates its own runtime and context on this module,\n * providing full isolation for globals, heap, and stack. The module\n * itself is stateless between runtimes — only the compiled WASM code\n * and Emscripten infrastructure are shared.\n *\n * This is safe because:\n * - The module loader is synchronous (preloaded skill cache), so\n * imports don't cause asyncify suspensions.\n * - Tool injection uses the promise-based pattern (newFunction +\n * newPromise), not newAsyncifiedFunction, so tool calls don't\n * cause asyncify suspensions.\n * - The eval queue serializes evalCodeAsync calls to satisfy the\n * one-concurrent-async-call-per-module constraint.\n */\nlet sharedModulePromise: Promise<QuickJSAsyncWASMModule> | undefined;\n\nfunction getSharedModule(): Promise<QuickJSAsyncWASMModule> {\n if (!sharedModulePromise) {\n sharedModulePromise = (async () => {\n const variant = await variantImport;\n return newQuickJSAsyncWASMModuleFromVariant(\n (variant.default ?? variant) as any,\n );\n })();\n }\n return sharedModulePromise;\n}\n\n/**\n * Unwrap a PTC tool result to a plain string for use inside QuickJS.\n *\n * Tool results may arrive as a raw string, or as an array of LangChain\n * content blocks (`{ type: \"text\", text: \"...\" }`). Blocks are joined\n * with newlines; non-text block types are silently skipped. Anything\n * else (objects, nulls) is JSON-serialised as a fallback.\n *\n * @param result - Raw return value from `tool.invoke()`.\n * @returns Plain string representation of the tool output.\n */\nfunction extractToolText(result: unknown): string {\n // Unwrap LangChain Command / ToolMessage / message-list envelopes (e.g. a\n // PTC tool that returns a Command) before extracting text.\n result = unwrapToolEnvelope(result);\n\n if (typeof result === \"string\") {\n return result;\n }\n\n if (Array.isArray(result)) {\n const texts: string[] = [];\n for (const block of result) {\n if (\n typeof block === \"object\" &&\n block !== null &&\n (block as Record<string, unknown>).type === \"text\" &&\n typeof (block as Record<string, unknown>).text === \"string\"\n ) {\n texts.push((block as Record<string, unknown>).text as string);\n }\n }\n\n if (texts.length > 0) {\n return texts.join(\"\\n\");\n }\n }\n return JSON.stringify(result);\n}\n\n/**\n * Remove the `cat -n` line-number prefix from every line of a string.\n *\n * The filesystem backend formats file content with line numbers in the\n * form `\" N\\t\"` so human readers can navigate by line. That prefix\n * is useful for the agent but noise for QuickJS code that parses the\n * text programmatically (e.g. swarm reading `/context.txt`).\n *\n * The function is conservative: if any non-empty line lacks the prefix,\n * the text is returned unchanged so nothing is silently corrupted.\n *\n * @param text - Raw file content, possibly line-number prefixed.\n * @returns Content with line-number prefixes stripped, or the original\n * text if it doesn't match the expected format throughout.\n */\nfunction stripLineNumbers(text: string): string {\n const lines = text.split(\"\\n\");\n if (lines.length === 0) {\n return text;\n }\n\n if (!lines.every((l) => l === \"\" || LINE_NUMBER_RE.test(l))) {\n return text;\n }\n\n return lines.map((l) => l.replace(LINE_NUMBER_RE, \"\")).join(\"\\n\");\n}\n\n/**\n * Fixed-size character buffer for capturing console output from the QuickJS VM.\n *\n * Lines are accumulated up to `maxChars`. Once the cap is reached, excess\n * characters are counted as dropped rather than silently discarded without\n * attribution, so callers can surface a truncation notice to the user.\n */\nclass ConsoleBuffer {\n private readonly maxChars: number;\n private buffer: string = \"\";\n private droppedChars: number = 0;\n\n constructor(maxChars: number) {\n this.maxChars = Math.max(maxChars, 0);\n }\n\n /**\n * Append `line` to the buffer.\n *\n * If the buffer is already full the entire line is counted as dropped.\n * If `line` partially fits, the fitting prefix is stored and the remainder\n * is counted as dropped.\n */\n append(line: string): void {\n const remaining = this.maxChars - this.buffer.length;\n if (remaining <= 0) {\n this.droppedChars += line.length;\n return;\n }\n\n if (line.length <= remaining) {\n this.buffer += line;\n } else {\n this.buffer += line.slice(0, remaining);\n this.droppedChars += line.length - remaining;\n }\n }\n\n /**\n * Return the buffered output and dropped-character count as `[buffered,\n * droppedChars]`, then reset both to zero.\n */\n drain(): [string, number] {\n const out = this.buffer;\n const dropped = this.droppedChars;\n\n this.buffer = \"\";\n this.droppedChars = 0;\n\n return [out, dropped];\n }\n}\n\n/**\n * Sandboxed JavaScript REPL session backed by QuickJS WASM.\n *\n * Serializable — holds an `id` that keys into a static session map.\n * The QuickJS runtime is lazily started on the first `.eval()` call\n * and reconnected if a session with the same id already exists.\n * This makes it safe to store in LangGraph state across interrupts.\n */\nexport class ReplSession {\n private static sessions = new Map<string, ReplSession>();\n\n readonly id: string;\n\n private runtime: QuickJSAsyncRuntime | null = null;\n private context: QuickJSAsyncContext | null = null;\n private consoleBuffer: ConsoleBuffer = new ConsoleBuffer(\n DEFAULT_MAX_RESULTS_CHARS,\n );\n private options: ReplSessionOptions;\n private readonly maxPtcCalls: number | null;\n private ptcCallsRemaining: number | null = null;\n private subagentQueue: PQueue | null = null;\n private bridgeDispatchRef: {\n current: SubagentBridgeOptions[\"dispatch\"];\n } | null = null;\n\n /** Allowed keys in the subagent input object. */\n private static readonly SUBAGENT_ALLOWED_KEYS = new Set([\n \"description\",\n \"subagentType\",\n \"responseSchema\",\n ]);\n\n /**\n * Reset the shared WASM module. Forces the next session to instantiate\n * a fresh module. Only needed in tests where module state must be\n * isolated between test files.\n *\n * @internal\n */\n static resetSharedModule(): void {\n sharedModulePromise = undefined;\n }\n\n constructor(id: string, options: ReplSessionOptions = {}) {\n this.id = id;\n this.options = options;\n this.maxPtcCalls =\n options.maxPtcCalls !== undefined\n ? options.maxPtcCalls\n : DEFAULT_MAX_PTC_CALLS;\n }\n\n private async ensureStarted(): Promise<void> {\n if (this.runtime) return;\n\n const {\n memoryLimitBytes = DEFAULT_MEMORY_LIMIT,\n maxStackSizeBytes = DEFAULT_MAX_STACK_SIZE,\n tools,\n maxResultChars = DEFAULT_MAX_RESULTS_CHARS,\n captureConsole = true,\n } = this.options;\n\n const asyncModule = await getSharedModule();\n const runtime: QuickJSAsyncRuntime = asyncModule.newRuntime();\n runtime.setMemoryLimit(memoryLimitBytes);\n runtime.setMaxStackSize(maxStackSizeBytes);\n\n const context: QuickJSAsyncContext = runtime.newContext();\n this.runtime = runtime;\n this.context = context;\n\n this.consoleBuffer = new ConsoleBuffer(maxResultChars);\n if (captureConsole) {\n this.setupConsole();\n }\n\n if (tools !== undefined && tools.length > 0) {\n this.injectTools(tools);\n }\n\n const { subagentBridge } = this.options;\n if (subagentBridge) {\n this.subagentQueue = new PQueue({\n concurrency: subagentBridge.maxConcurrency,\n });\n this.injectSubagentBridge(subagentBridge.dispatch);\n }\n\n const sessionId = this.options.sessionId ?? \"default\";\n const sessionIdHandle = context.newString(sessionId);\n context.setProp(context.global, \"__sessionId__\", sessionIdHandle);\n sessionIdHandle.dispose();\n }\n\n /**\n * Initialise the per-eval PTC counter. Called at the top of every `eval()`.\n */\n private resetPtcBudget(): void {\n this.ptcCallsRemaining =\n this.maxPtcCalls === null ? null : this.maxPtcCalls;\n }\n\n /**\n * Decrement the PTC call counter and throw if the budget is exhausted.\n * `null` budget means unlimited — returns immediately without decrementing.\n */\n private consumePtcBudget(functionName: string): void {\n if (this.ptcCallsRemaining === null) {\n return;\n }\n\n if (this.ptcCallsRemaining > 0) {\n this.ptcCallsRemaining--;\n return;\n }\n\n const limit = this.maxPtcCalls ?? 0;\n throw new PTCCallBudgetExceededError({\n limit,\n attempted: limit + 1,\n functionName,\n });\n }\n\n /**\n * Get or create a session for the given id.\n *\n * Sessions are deduped by id — calling `getOrCreate` twice with the\n * same id returns the same instance. The QuickJS runtime is lazily\n * started on the first `.eval()` call.\n */\n static getOrCreate(\n id: string,\n options: ReplSessionOptions = {},\n ): ReplSession {\n const existing = ReplSession.sessions.get(id);\n if (existing) {\n return existing;\n }\n\n const session = new ReplSession(id, options);\n ReplSession.sessions.set(id, session);\n return session;\n }\n\n /**\n * Retrieve an existing session by id, or null if none exists.\n */\n static get(id: string): ReplSession | null {\n return ReplSession.sessions.get(id) ?? null;\n }\n\n /**\n * Returns true if any session exists whose key equals `threadId` or starts\n * with `threadId:`. Useful for tests that need to confirm a session was\n * created without knowing the full `threadId:middlewareId` key.\n */\n static hasAnyForThread(threadId: string): boolean {\n const prefix = `${threadId}:`;\n for (const key of ReplSession.sessions.keys()) {\n if (key === threadId || key.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Dispose and remove the session with the given key, if it exists.\n */\n static deleteSession(key: string): void {\n const session = ReplSession.sessions.get(key);\n if (session) {\n session.dispose();\n }\n }\n\n /**\n * Evaluate code in this session.\n *\n * Lazily starts the QuickJS runtime on the first call. Code is\n * transformed via an AST pipeline that strips TypeScript syntax,\n * hoists top-level declarations to globalThis for cross-eval\n * persistence, auto-returns the last expression, and wraps in an\n * async IIFE.\n */\n async eval(code: string, timeoutMs: number): Promise<ReplResult> {\n await this.ensureStarted();\n const runtime = this.runtime!;\n const context = this.context!;\n\n const drainLogs = (): { logs: string[]; logsDroppedChars: number } => {\n const [raw, dropped] = this.consoleBuffer.drain();\n return {\n logs: raw.length > 0 ? raw.split(\"\\n\").filter((l) => l.length > 0) : [],\n logsDroppedChars: dropped,\n };\n };\n\n this.resetPtcBudget();\n try {\n if (timeoutMs >= 0) {\n runtime.setInterruptHandler(\n shouldInterruptAfterDeadline(Date.now() + timeoutMs),\n );\n } else {\n runtime.setInterruptHandler(() => false);\n }\n\n const transformed = transformForEval(code);\n const result = await sharedEvalQueue.enqueue(() =>\n context.evalCodeAsync(transformed),\n );\n\n if (result.error) {\n const error = context.dump(result.error);\n result.error.dispose();\n return { ok: false, error, ...drainLogs() };\n }\n\n const promiseState = context.getPromiseState(result.value);\n\n if (promiseState.type === \"fulfilled\") {\n if (promiseState.notAPromise) {\n const value = context.dump(result.value);\n result.value.dispose();\n return { ok: true, value, ...drainLogs() };\n }\n const value = context.dump(promiseState.value);\n promiseState.value.dispose();\n result.value.dispose();\n return { ok: true, value, ...drainLogs() };\n }\n\n if (promiseState.type === \"rejected\") {\n const error = context.dump(promiseState.error);\n promiseState.error.dispose();\n result.value.dispose();\n return { ok: false, error, ...drainLogs() };\n }\n\n const noTimeout = timeoutMs < 0;\n const deadline = noTimeout ? Infinity : Date.now() + timeoutMs;\n while (noTimeout || Date.now() < deadline) {\n context.runtime.executePendingJobs();\n const state = context.getPromiseState(result.value);\n if (state.type === \"fulfilled\") {\n const value = context.dump(state.value);\n state.value.dispose();\n result.value.dispose();\n return { ok: true, value, ...drainLogs() };\n }\n if (state.type === \"rejected\") {\n const error = context.dump(state.error);\n state.error.dispose();\n result.value.dispose();\n return { ok: false, error, ...drainLogs() };\n }\n await new Promise((r) => setTimeout(r, 1));\n }\n\n result.value.dispose();\n return {\n ok: false,\n error: { message: \"Promise timed out — execution interrupted\" },\n ...drainLogs(),\n };\n } finally {\n this.ptcCallsRemaining = null;\n }\n }\n\n dispose(): void {\n try {\n this.context?.dispose();\n } catch {\n /* may already be disposed */\n }\n try {\n this.runtime?.dispose();\n } catch {\n /* may already be disposed */\n }\n this.runtime = null;\n this.context = null;\n ReplSession.sessions.delete(this.id);\n }\n\n toJSON(): { id: string } {\n return { id: this.id };\n }\n\n static fromJSON(data: { id: string }): ReplSession {\n return ReplSession.sessions.get(data.id) ?? new ReplSession(data.id);\n }\n\n /**\n * Clear the static session cache. Useful for testing.\n * @internal\n */\n static clearCache(): void {\n for (const session of ReplSession.sessions.values()) {\n session.dispose();\n }\n ReplSession.sessions.clear();\n }\n\n private setupConsole(): void {\n const context = this.context!;\n const consoleHandle = context.newObject();\n for (const method of [\"log\", \"warn\", \"error\", \"info\", \"debug\"] as const) {\n const fnHandle = context.newFunction(\n method,\n (...args: QuickJSHandle[]) => {\n const nativeArgs = args.map((a: QuickJSHandle) => context.dump(a));\n const formatted = nativeArgs\n .map((a: unknown) =>\n typeof a === \"object\" && a !== null\n ? JSON.stringify(a)\n : String(a),\n )\n .join(\" \");\n const line =\n method === \"log\" || method === \"info\" || method === \"debug\"\n ? formatted\n : `[${method}] ${formatted}`;\n this.consoleBuffer.append(line + \"\\n\");\n },\n );\n context.setProp(consoleHandle, method, fnHandle);\n fnHandle.dispose();\n }\n context.setProp(context.global, \"console\", consoleHandle);\n consoleHandle.dispose();\n }\n\n private injectTools(tools: StructuredToolInterface[]): void {\n const context = this.context!;\n const toolsNs = context.newObject();\n\n for (const t of tools) {\n const camelName = toCamelCase(t.name);\n const fnHandle = context.newFunction(\n camelName,\n (inputHandle: QuickJSHandle) => {\n const input = context.dump(inputHandle);\n const promise = context.newPromise();\n (async () => {\n try {\n this.consumePtcBudget(camelName);\n const rawInput =\n typeof input === \"object\" && input !== null ? input : {};\n const result = await t.invoke(rawInput);\n let text = extractToolText(result);\n if (t.name === \"read_file\") {\n text = stripLineNumbers(text);\n }\n const val = context.newString(text);\n promise.resolve(val);\n val.dispose();\n } catch (e: unknown) {\n const msg =\n e != null && typeof (e as Error).message === \"string\"\n ? (e as Error).message\n : String(e);\n const err = context.newError(`Tool '${t.name}' failed: ${msg}`);\n promise.reject(err);\n err.dispose();\n }\n promise.settled.then(context.runtime.executePendingJobs);\n })();\n return promise.handle;\n },\n );\n context.setProp(toolsNs, camelName, fnHandle);\n fnHandle.dispose();\n }\n\n context.setProp(context.global, \"tools\", toolsNs);\n toolsNs.dispose();\n }\n\n /**\n * Install the `task` global on the QuickJS context.\n *\n * Registers the host function directly as `globalThis.task`,\n * then freezes it via `evalCode`. Structured results (when\n * responseSchema is provided) are marshaled into native QuickJS\n * objects on the host side — no JS wrapper needed.\n */\n /**\n * Replace the active bridge dispatch with a fresh one.\n *\n * Call this before each eval so the dispatch closure carries\n * the current invocation's config (tracing callbacks, run ID, etc.)\n * rather than the stale config from session creation.\n */\n updateBridgeDispatch(dispatch: SubagentBridgeOptions[\"dispatch\"]): void {\n if (this.bridgeDispatchRef) {\n this.bridgeDispatchRef.current = dispatch;\n }\n }\n\n private injectSubagentBridge(\n dispatch: SubagentBridgeOptions[\"dispatch\"],\n ): void {\n const context = this.context!;\n const queue = this.subagentQueue!;\n\n this.bridgeDispatchRef = { current: dispatch };\n const ref = this.bridgeDispatchRef;\n\n const hostFn = context.newFunction(\"task\", (inputHandle: QuickJSHandle) => {\n const input = context.dump(inputHandle);\n const promise = context.newPromise();\n\n (async () => {\n try {\n if (\n input == null ||\n typeof input !== \"object\" ||\n Array.isArray(input)\n ) {\n throw new Error(\"task: expected an object argument\");\n }\n const raw = input as Record<string, unknown>;\n\n // Accept snake_case aliases so models don't need to know our convention\n const obj: Record<string, unknown> = { ...raw };\n if (\"subagent_type\" in obj) {\n obj.subagentType ??= obj.subagent_type;\n delete obj.subagent_type;\n }\n if (\"response_schema\" in obj) {\n obj.responseSchema ??= obj.response_schema;\n delete obj.response_schema;\n }\n\n const unknownKeys = Object.keys(obj).filter(\n (k) => !ReplSession.SUBAGENT_ALLOWED_KEYS.has(k),\n );\n if (unknownKeys.length > 0) {\n throw new Error(\n `task: unknown keys: ${unknownKeys.join(\", \")}. ` +\n `Allowed: ${[...ReplSession.SUBAGENT_ALLOWED_KEYS].join(\", \")}`,\n );\n }\n\n const { description, subagentType, responseSchema } = obj;\n\n if (typeof description !== \"string\" || description.length === 0) {\n throw new Error(\n \"task: 'description' is required and must be a non-empty string\",\n );\n }\n if (typeof subagentType !== \"string\" || subagentType.length === 0) {\n throw new Error(\n \"task: 'subagentType' is required and must be a non-empty string\",\n );\n }\n if (\n responseSchema !== undefined &&\n (responseSchema == null ||\n typeof responseSchema !== \"object\" ||\n Array.isArray(responseSchema))\n ) {\n throw new Error(\n \"task: 'responseSchema' must be a plain object (JSON Schema) when provided\",\n );\n }\n\n const result = await queue.add(() =>\n ref.current({\n description: description as string,\n subagentType: subagentType as string,\n ...(responseSchema !== undefined && {\n responseSchema: responseSchema as Record<string, unknown>,\n }),\n }),\n );\n if (typeof result === \"string\") {\n const val = context.newString(result);\n promise.resolve(val);\n val.dispose();\n } else {\n const jsonResult = context.evalCode(`(${JSON.stringify(result)})`);\n if (jsonResult.error) {\n const errDump = context.dump(jsonResult.error);\n jsonResult.error.dispose();\n throw new Error(\n `task: failed to marshal structured response: ${JSON.stringify(errDump)}`,\n );\n }\n promise.resolve(jsonResult.value);\n jsonResult.value.dispose();\n }\n } catch (e: unknown) {\n const msg =\n e != null && typeof (e as Error).message === \"string\"\n ? (e as Error).message\n : String(e);\n const err = context.newError(msg);\n promise.reject(err);\n err.dispose();\n }\n promise.settled.then(context.runtime.executePendingJobs);\n })();\n\n return promise.handle;\n });\n\n context.setProp(context.global, \"task\", hostFn);\n hostFn.dispose();\n\n context.evalCode(\n \"Object.freeze(globalThis.task);\" +\n \"Object.defineProperty(globalThis, 'task', {\" +\n \" value: globalThis.task,\" +\n \" writable: false,\" +\n \" configurable: false,\" +\n \"}); undefined\",\n );\n }\n}\n","const SCHEMA_MAX_BYTES = 4096;\nconst SCHEMA_MAX_DEPTH = 5;\nconst SCHEMA_MAX_PROPERTIES = 32;\n\n/**\n * Validate that a response schema does not exceed size, depth, or\n * property-count limits.\n *\n * @throws Error if any limit is exceeded.\n */\nexport function validateResponseSchema(schema: Record<string, unknown>): void {\n const serialized = JSON.stringify(schema);\n if (serialized.length > SCHEMA_MAX_BYTES) {\n throw new Error(\n `responseSchema exceeds ${SCHEMA_MAX_BYTES} byte limit (${serialized.length} bytes)`,\n );\n }\n\n function check(\n node: Record<string, unknown>,\n depth: number,\n propCount: { value: number },\n ): void {\n if (depth > SCHEMA_MAX_DEPTH) {\n throw new Error(\n `responseSchema exceeds maximum nesting depth of ${SCHEMA_MAX_DEPTH}`,\n );\n }\n const props = node.properties;\n if (props != null && typeof props === \"object\" && !Array.isArray(props)) {\n const propObj = props as Record<string, unknown>;\n propCount.value += Object.keys(propObj).length;\n if (propCount.value > SCHEMA_MAX_PROPERTIES) {\n throw new Error(\n `responseSchema exceeds maximum of ${SCHEMA_MAX_PROPERTIES} properties`,\n );\n }\n for (const value of Object.values(propObj)) {\n if (\n value != null &&\n typeof value === \"object\" &&\n !Array.isArray(value)\n ) {\n check(value as Record<string, unknown>, depth + 1, propCount);\n }\n }\n }\n const items = node.items;\n if (items != null && typeof items === \"object\" && !Array.isArray(items)) {\n check(items as Record<string, unknown>, depth + 1, propCount);\n }\n }\n\n check(schema, 0, { value: 0 });\n}\n","/**\n * Code Interpreter middleware for deepagents.\n *\n * Provides an `eval` tool that runs JavaScript in a WASM-sandboxed QuickJS\n * interpreter. Supports:\n * - Persistent state across evaluations (true REPL)\n * - Programmatic tool calling (PTC) — expose agent or custom tools inside the REPL\n */\n\nimport {\n createMiddleware,\n omitPayload,\n tool,\n type AgentMiddleware as _AgentMiddleware,\n} from \"langchain\";\nimport { z } from \"zod/v4\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY } from \"deepagents\";\n\nimport dedent from \"dedent\";\nimport type {\n CodeInterpreterMiddlewareOptions,\n SubagentBridgeOptions,\n} from \"./types.js\";\nimport {\n ReplSession,\n DEFAULT_EXECUTION_TIMEOUT,\n DEFAULT_MEMORY_LIMIT,\n DEFAULT_MAX_STACK_SIZE,\n DEFAULT_SESSION_ID,\n DEFAULT_MAX_PTC_CALLS,\n DEFAULT_MAX_RESULTS_CHARS,\n DEFAULT_MAX_SUBAGENT_CONCURRENCY,\n} from \"./session.js\";\nimport {\n formatReplResult,\n toCamelCase,\n toolToTypeSignature,\n safeToJsonSchema,\n} from \"./utils.js\";\nimport { validateResponseSchema } from \"./subagent-dispatch.js\";\nimport { unwrapToolEnvelope } from \"./coerce.js\";\n\n/**\n * These type-only imports are required for TypeScript's type inference to work\n * correctly with the langchain/langgraph middleware system. Without them, certain\n * generic type parameters fail to resolve properly, causing runtime issues with\n * tool schemas and message types.\n */\nimport type * as _zodTypes from \"@langchain/core/utils/types\";\nimport type * as _zodMeta from \"@langchain/langgraph/zod\";\nimport type * as _messages from \"@langchain/core/messages\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\n\nconst DEFAULT_TOOL_NAME = \"eval\";\n\n/**\n * Render the subagent dispatch prompt section for the system message.\n * Ported from the Python `_SUBAGENT_SYSTEM_PROMPT_TEMPLATE`.\n */\nfunction renderSubagentPrompt(toolName: string): string {\n return dedent`\n\n ### Dispatching Subagents with \\`task\\`\n\n \\`task\\` is your primitive for running configured subagents from inside the\n JavaScript REPL. Your job here is to DISTRIBUTE work, not to do it yourself:\n write JavaScript that fans work out to subagents and assembles their results.\n You handle the orchestration - fan-out, filtering, deduplication, multi-stage\n flow, and synthesis - in plain JavaScript.\n\n #### The primitive\n\n \\`\\`\\`javascript\n await task({\n description, // full autonomous task prompt\n subagentType, // configured subagent name\n responseSchema, // optional JSON Schema for structured output\n }); // -> Promise<unknown>\n \\`\\`\\`\n\n \\`task\\` runs a full agentic loop for the selected configured subagent. The\n subagent can use whatever tools it was configured with, iterate, inspect\n context, and return one final result. \\`subagentType\\` is required; use one of\n the configured subagent names.\n\n \\`description\\` is the only prompt the subagent receives for this dispatch. Make\n it complete: the goal, the constraints, what to inspect, and the exact shape\n or level of detail you expect back. Give context as locators — file paths and\n symbol names — not as pasted file contents. If you already read a file while\n exploring, still pass its path and let the subagent read it; do not paste back\n what you read. Each dispatch is stateless from the caller's perspective; you\n cannot send follow-up messages to the same subagent run.\n\n \\`responseSchema\\` is optional, but set it on any dispatch whose result feeds\n later code. A deterministic, typed shape is what lets you compose the next\n stage reliably — index it, sort it, compare fields, branch on it, merge it —\n instead of parsing free-form text. This is what makes a whole workflow\n composable as one script. When provided, the resolved value is already a typed\n JavaScript value matching the schema; do not call \\`JSON.parse\\` unless the\n subagent intentionally returned a JSON string. Dynamic schemas work for\n declarative subagents; runnable-backed subagents reject dynamic schemas because\n their runnable is already compiled.\n\n #### Approval model\n\n \\`task\\` dispatches from inside the already-running \\`${toolName}\\` call. It\n does not route through the parent agent's \\`ToolNode\\`-managed \\`task\\` tool and\n does not trigger parent-level \\`interrupt_on\\` / HITL approval for each dispatch.\n Declarative subagents still honor approval middleware configured inside their\n own spec. If you need approval before launching a subagent from the parent, use\n the normal \\`task\\` tool outside JavaScript or ensure the \\`${toolName}\\` call\n itself is approval-gated.\n\n #### Mental model\n\n Hold your work in JS: an array of items in, an array of results out. Merge each\n dispatch result back onto its item. Multi-stage analysis means: run a pass,\n filter or regroup the array in JS, then run another pass over the survivors.\n\n You can run the whole workflow in one \\`${toolName}\\` call or split it across\n several — both are fine. A single end-to-end script (generate, compare, pick a\n winner; or review every item, then synthesize) is clean when you can write it\n in one go; splitting is also fine when you want to inspect results between\n stages. Either way, don't redo work across calls — reuse what is already in\n scope (see \"Reuse what earlier evals left in scope\" below).\n\n #### Fan out with bounded concurrency\n\n Dispatch independent work in parallel with \\`Promise.all\\`, but in explicit\n batches around 10 so you do not launch hundreds of subagents at once. The bridge\n enforces a hard per-REPL cap of 32 concurrent subagent calls.\n\n \\`\\`\\`javascript\n const files = [\"/src/a.ts\", \"/src/b.ts\", \"/src/c.ts\"]; // found while exploring\n const batchSize = 10;\n const reviewed = [];\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n reviewed.push(...(await Promise.all(batch.map(async (file) => {\n const result = await task({\n description: \"Read \" + file + \" and review it for SQL injection. \" +\n \"Cite line numbers.\",\n subagentType: \"reviewer\",\n responseSchema: {\n type: \"object\",\n properties: {\n vulnerabilities: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n type: { type: \"string\" },\n line: { type: \"number\" },\n evidence: { type: \"string\" },\n },\n required: [\"type\", \"line\", \"evidence\"],\n },\n },\n },\n required: [\"vulnerabilities\"],\n },\n });\n return { file, ...result };\n }))));\n }\n \\`\\`\\`\n\n #### Explore with your own tools first, then distribute\n\n You already have your normal tools for reading, listing, globbing, and\n grepping files. Use them to explore and understand the task BEFORE you write\n the orchestration script. These are ordinary tool calls, separate from the\n \\`${toolName}\\` tool: read the data file, list or glob the directory, grep for\n what matters, then decide how to split the work.\n\n Never write \\`${toolName}\\` code that spawns a subagent just to read or parse a\n file or list a directory. That is a deterministic step you do yourself with a\n direct tool call; spending a whole agent loop on it is wasteful.\n\n Once you understand the shape of the work, you have creative freedom in how\n you split it:\n\n - One dispatch per file or per record, when the items are already separate.\n - Chunk a large input yourself — read it, split it, optionally write a small\n input file per chunk — and dispatch one subagent per chunk.\n - A cheap classification pass first, then deeper dispatches only for the items\n that warrant them.\n\n Then write JavaScript in the \\`${toolName}\\` tool that distributes the heavy,\n agentic work to subagents with \\`task()\\`: analyzing file contents, exploring a\n codebase, making judgment calls, rewriting code, or synthesizing a report.\n\n Hand each subagent a locator, not a payload. Subagents have their own file\n tools, so for anything that lives in a file — a file to review, rewrite, or\n audit — pass the path and let the subagent read it. Do NOT read a whole file\n just to paste its contents into the description; that bloats every dispatch\n and duplicates the file across them. Reserve inline content for small or\n derived data that has no path of its own: a single parsed record, or a chunk\n you split out of a larger input (write the chunk to its own file and pass that\n path if it is large). Assemble the results in JS.\n\n #### Compose multiple stages\n\n Filter the array in JS between passes. For example: first ask subagents for a\n cheap classification, filter to the risky items, then dispatch deeper reviews\n only for those items.\n\n \\`\\`\\`javascript\n const tagged = await Promise.all(files.map((file) =>\n task({\n description: \"Read \" + file + \" and classify it as handler, util, \" +\n \"test, or config.\",\n subagentType: \"reviewer\",\n responseSchema: {\n type: \"object\",\n properties: { kind: { type: \"string\" }, risky: { type: \"boolean\" } },\n required: [\"kind\", \"risky\"],\n },\n }).then((tag) => ({ file, ...tag }))\n ));\n\n const riskyHandlers = tagged.filter((it) => it.kind === \"handler\" && it.risky);\n const deepReviews = await Promise.all(riskyHandlers.map((it) =>\n task({\n description: \"Deep security review of \" + it.file + \". Cite line numbers.\",\n subagentType: \"reviewer\",\n }).then((review) => ({ ...it, review }))\n ));\n \\`\\`\\`\n\n #### Return results via the last expression, not \\`console.log\\`\n\n The value of the last expression in an \\`${toolName}\\` call (or a resolved\n top-level \\`await\\`) is returned to you as the result. Make that final\n expression the variable holding your result and read it from there.\n \\`console.log\\` is only for incidental debugging: its output is capped and\n truncated, while the returned value is not, so never \\`console.log\\` your\n actual results.\n\n Keep large intermediate sets in JS variables and return only a compact\n summary or a small slice, not the entire dataset. To persist full output,\n have a subagent write it, or write it with your own file tool outside the\n \\`${toolName}\\` call.\n\n #### Reuse what earlier evals left in scope\n\n The REPL is persistent within a turn: every top-level variable, function, and\n class you declare is kept and is available in your next \\`${toolName}\\` call\n (each is hoisted to global scope). So if a later step needs something an\n earlier eval produced or bound, **reference that variable by name** — do not\n write a new literal that re-types data a previous eval already returned or\n computed.\n\n If you catch yourself pasting a big array or object of values you produced in\n an earlier call, that is the tell: the variable is still in scope, so use it.\n Re-typing prior results as a fresh literal wastes tokens and drifts from what\n actually ran.\n\n \\`\\`\\`javascript\n // An earlier eval bound this:\n // const auditResults = await Promise.all(files.map(/* ...audit... */));\n\n // A later eval — reference it; do NOT paste the findings back in as a literal:\n const findings = auditResults.flatMap((r) =>\n r.findings.map((f) => ({ ...f, file: r.file }))\n );\n const verified = await Promise.all(findings.map((f) =>\n task({ description: \"Verify this finding: \" + f.evidence, subagentType: \"verifier\" })\n .then((v) => ({ ...f, ...v }))\n ));\n \\`\\`\\`\n\n #### When the user asks for a \"workflow\"\n\n If the user's request mentions running a \"workflow\" (or otherwise uses the\n word \"workflow\"), fan the work out to subagents rather than doing it all\n yourself. Explore with your own tools first as needed, then write JavaScript\n in the \\`${toolName}\\` tool that dispatches subagents with \\`task()\\` and\n assembles their results. The point is to distribute the heavy work in\n parallel, not to grind through it one tool call at a time.\n `;\n}\n\nfunction renderReplSystemPrompt(opts: {\n toolName: string;\n timeout: number;\n memoryLimitMb: number;\n hasPtc: boolean;\n}): string {\n const sideEffects = opts.hasPtc\n ? \" External side effects from inside the REPL are reachable only via the `tools.*` namespace documented below.\"\n : \" The REPL is pure computation; do any filesystem or other I/O with your normal tools, outside this tool.\";\n return dedent`\n ### Interpreter\n\n An \\`${opts.toolName}\\` tool is available. It runs JavaScript in a persistent REPL.\n - State (variables, functions) persists across tool calls within a single turn of conversation. They DO NOT persist across multiple turns.\n - Top-level \\`await\\` works; Promises resolve before the call returns.\n - Runtime sandbox: no built-in filesystem, network, stdlib, or wall-clock APIs (\\`fetch\\`, \\`require\\`, \\`fs\\`, \\`process\\`, real \\`Date.now()\\` are unavailable or stubbed).${sideEffects}\n - Timeout: ${opts.timeout}s per call. Memory: ${opts.memoryLimitMb} MB total.\n - \\`console.log\\` output is captured and returned alongside the result.\n `;\n}\n\n/**\n * Generate the PTC API Reference section for the system prompt.\n */\nexport async function generatePtcPrompt(\n tools: StructuredToolInterface[],\n): Promise<string> {\n if (tools.length === 0) return \"\";\n\n const signatures = await Promise.all(\n tools.map((t) => {\n const jsonSchema = t.schema ? safeToJsonSchema(t.schema) : undefined;\n return toolToTypeSignature(\n toCamelCase(t.name),\n t.description,\n jsonSchema,\n );\n }),\n );\n\n return dedent`\n\n ### API Reference — \\`tools\\` namespace\n\n The following agent tools are callable as async functions inside the REPL.\n Each takes a single object argument and returns a Promise that resolves to a string.\n Use \\`await\\` to call them. Promise APIs like \\`Promise.all\\` are also available.\n\n **Example usage:**\n \\`\\`\\`javascript\n // Call a tool\n const result = await tools.searchWeb({ query: \"QuickJS tutorial\" });\n console.log(result);\n\n // Concurrent calls\n const [a, b] = await Promise.all([\n tools.fetchData({ url: \"https://api.example.com/a\" }),\n tools.fetchData({ url: \"https://api.example.com/b\" }),\n ]);\n \\`\\`\\`\n\n **Available functions:**\n \\`\\`\\`typescript\n ${signatures.join(\"\\n\\n\")}\n \\`\\`\\`\n `;\n}\n\n/**\n * Resolves a mixed list of tool names and tool instances into a flat list of\n * StructuredToolInterface objects. Strings are looked up by name in agentTools;\n * instances are included directly without requiring agent registration. Strings\n * that don't match any agent tool are silently omitted.\n *\n * Throws if the subagent `task` tool is requested (by name or instance): it is\n * reserved for the `task()` global and cannot be a `tools.*` PTC member.\n */\nexport function resolveToolList(\n items: (string | StructuredToolInterface)[],\n agentTools: StructuredToolInterface[],\n): StructuredToolInterface[] {\n const agentByName = new Map(agentTools.map((t) => [t.name, t]));\n return items.flatMap((item) => {\n const name = typeof item === \"string\" ? item : item.name;\n if (name === \"task\") {\n throw new Error(\n \"The subagent `task` tool cannot be exposed via `ptc`. It is always \" +\n \"available as the top-level `task()` global inside the REPL (with \" +\n \"`subagentType` and `responseSchema` support); exposing it through the \" +\n \"`tools.*` namespace would create a second, conflicting dispatch path \" +\n 'that drops `responseSchema`. Remove \"task\" from `ptc`.',\n );\n }\n if (typeof item === \"string\") {\n const found = agentByName.get(item);\n return found ? [found] : [];\n }\n return [item];\n });\n}\n\n/**\n * Create the Code Interpreter middleware.\n */\nexport function createCodeInterpreterMiddleware(\n options: CodeInterpreterMiddlewareOptions = {},\n) {\n const {\n ptc,\n memoryLimitBytes = DEFAULT_MEMORY_LIMIT,\n maxStackSizeBytes = DEFAULT_MAX_STACK_SIZE,\n executionTimeoutMs = DEFAULT_EXECUTION_TIMEOUT,\n systemPrompt: customSystemPrompt = null,\n maxPtcCalls = DEFAULT_MAX_PTC_CALLS,\n maxResultChars = DEFAULT_MAX_RESULTS_CHARS,\n toolName = DEFAULT_TOOL_NAME,\n captureConsole = true,\n subagents = true,\n } = options;\n\n const maxSubagentConcurrency = subagents\n ? DEFAULT_MAX_SUBAGENT_CONCURRENCY\n : 0;\n\n if (maxPtcCalls !== null && maxPtcCalls !== undefined && maxPtcCalls < 1) {\n throw new Error(\"`maxPtcCalls` must be >= 1 or null\");\n }\n\n const middlewareId = crypto.randomUUID();\n\n let cachedPtcPrompt: string | null = null;\n let ptcTools: StructuredToolInterface[] = [];\n let taskTool: StructuredToolInterface | null = null;\n\n function filterToolsForPtc(\n allTools: StructuredToolInterface[],\n ): StructuredToolInterface[] {\n if (!ptc) return [];\n\n const candidates = allTools.filter((t) => t.name !== toolName);\n\n return resolveToolList(ptc, candidates);\n }\n\n function findTaskTool(\n tools: StructuredToolInterface[],\n ): StructuredToolInterface | null {\n return tools.find((t) => t.name === \"task\") ?? null;\n }\n\n function createBridgeDispatch(\n subagentTaskTool: StructuredToolInterface,\n config: LangGraphRunnableConfig,\n ): SubagentBridgeOptions[\"dispatch\"] {\n return async (input) => {\n const hasSchema = input.responseSchema != null;\n if (hasSchema) {\n validateResponseSchema(input.responseSchema!);\n }\n\n const toolConfig = {\n ...config,\n configurable: {\n ...config.configurable,\n ...(hasSchema && {\n [SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY]: input.responseSchema,\n }),\n },\n };\n\n const result = await subagentTaskTool.invoke(\n {\n description: input.description,\n subagent_type: input.subagentType,\n },\n toolConfig,\n );\n\n // The task tool resolves to a Command envelope; unwrap it to the\n // subagent's actual output before handing it back to the REPL.\n const content = unwrapToolEnvelope(result);\n\n if (hasSchema && typeof content === \"string\") {\n try {\n return JSON.parse(content);\n } catch {\n return content;\n }\n }\n return content;\n };\n }\n\n const evalTool = tool(\n async (input, config: LangGraphRunnableConfig) => {\n const threadId = config.configurable?.thread_id || DEFAULT_SESSION_ID;\n const sessionKey = `${threadId}:${middlewareId}`;\n\n const session = ReplSession.getOrCreate(sessionKey, {\n memoryLimitBytes,\n maxStackSizeBytes,\n maxPtcCalls,\n tools: ptcTools,\n maxResultChars,\n captureConsole,\n sessionId: threadId,\n subagentBridge:\n taskTool && maxSubagentConcurrency > 0\n ? {\n dispatch: createBridgeDispatch(taskTool, config),\n maxConcurrency: maxSubagentConcurrency,\n }\n : undefined,\n });\n\n if (taskTool && maxSubagentConcurrency > 0) {\n session.updateBridgeDispatch(createBridgeDispatch(taskTool, config));\n }\n\n const result = await session.eval(input.code, executionTimeoutMs);\n return formatReplResult(result);\n },\n {\n name: toolName,\n description: dedent`\n Evaluate TypeScript/JavaScript code in a sandboxed REPL. State persists across calls.\n Use console.log() for output. Returns the result of the last expression.\n If file or other tools are available, call them via the tools namespace: await tools.readFile({ path }).\n `,\n metadata: { ls_code_input_language: \"javascript\" },\n schema: z.object({\n code: z\n .string()\n .describe(\n \"TypeScript/JavaScript code to evaluate in the sandboxed REPL\",\n ),\n }),\n },\n );\n\n return createMiddleware({\n name: \"CodeInterpreterMiddleware\",\n tracePolicy: { processInputs: omitPayload },\n tools: [evalTool],\n wrapModelCall: async (request, handler) => {\n const agentTools = (request.tools || []) as StructuredToolInterface[];\n ptcTools = filterToolsForPtc(agentTools);\n\n if (!taskTool && maxSubagentConcurrency > 0) {\n taskTool = findTaskTool(agentTools);\n }\n\n if (ptcTools.length > 0 && !cachedPtcPrompt) {\n cachedPtcPrompt = await generatePtcPrompt(ptcTools);\n }\n\n const baseSystemPrompt =\n customSystemPrompt ||\n renderReplSystemPrompt({\n toolName,\n timeout: executionTimeoutMs / 1000,\n memoryLimitMb: Math.floor(memoryLimitBytes / (1024 * 1024)),\n hasPtc: ptcTools.length > 0,\n });\n\n const subagentPrompt =\n taskTool && maxSubagentConcurrency > 0\n ? renderSubagentPrompt(toolName)\n : \"\";\n\n const systemMessage = request.systemMessage\n .concat(baseSystemPrompt)\n .concat(subagentPrompt)\n .concat(cachedPtcPrompt || \"\");\n return handler({ ...request, systemMessage });\n },\n afterAgent: async (_state, runtime) => {\n const threadId = runtime.configurable?.thread_id ?? DEFAULT_SESSION_ID;\n const sessionKey = `${threadId}:${middlewareId}`;\n ReplSession.deleteSession(sessionKey);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuBA,IAAa,6BAAb,cAAgD,MAAM;CACpD;CACA;CACA;CAEA,YAAY,SAAuC;EACjD,MACE,mCAAmC,QAAQ,MAAM,cAAc,QAAQ,UAAU,aAAa,QAAQ,aAAa,EACrH;EACA,KAAK,OAAO;EACZ,KAAK,QAAQ,QAAQ;EACrB,KAAK,YAAY,QAAQ;EACzB,KAAK,eAAe,QAAQ;CAC9B;AACF;;;;;;AC7BA,SAAgB,YA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ACH,OAAO,CAAC,CACR,SACC,8DACF,EACJ,CAAC;CACH,CACF;CAEA,OAAO,iBAAiB;EACtB,MAAM;EACN,aAAa,EAAE,eAAe,YAAY;EAC1C,OAAO,CAAC,QAAQ;EAChB,eAAe,OAAO,SAAS,YAAY;GACzC,MAAM,aAAc,QAAQ,SAAS,CAAC;GACtC,WAAW,kBAAkB,UAAU;GAEvC,IAAI,CAAC,YAAY,yBAAyB,GACxC,WAAW,aAAa,UAAU;GAGpC,IAAI,SAAS,SAAS,KAAK,CAAC,iBAC1B,kBAAkB,MAAM,kBAAkB,QAAQ;GAGpD,MAAM,mBACJ,sBACA,uBAAuB;IACrB;IACA,SAAS,qBAAqB;IAC9B,eAAe,KAAK,MAAM,mBAAoB,OAAY;IAC1D,QAAQ,SAAS,SAAS;GAC5B,CAAC;GAEH,MAAM,iBACJ,YAAY,yBAAyB,IACjC,qBAAqB,QAAQ,IAC7B;GAEN,MAAM,gBAAgB,QAAQ,cAC3B,OAAO,gBAAgB,CAAC,CACxB,OAAO,cAAc,CAAC,CACtB,OAAO,mBAAmB,EAAE;GAC/B,OAAO,QAAQ;IAAE,GAAG;IAAS;GAAc,CAAC;EAC9C;EACA,YAAY,OAAO,QAAQ,YAAY;GAErC,MAAM,aAAa,GADF,QAAQ,cAAc,aAAA,cACR,GAAG;GAClC,YAAY,cAAc,UAAU;EACtC;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["program","raw"],"sources":["../src/errors.ts","../src/utils.ts","../src/coerce.ts","../src/transform.ts","../src/eval-queue.ts","../src/session.ts","../src/subagent-dispatch.ts","../src/middleware.ts"],"sourcesContent":["/**\n * Options for constructing a {@link PTCCallBudgetExceededError}.\n */\ninterface PTCCallBudgetExceededOptions {\n /**\n * The configured per-eval PTC call limit.\n */\n limit: number;\n\n /**\n * The call number that triggered the violation (always `limit + 1`).\n */\n attempted: number;\n\n /**\n * The name of the tool function that was called over budget.\n */\n functionName: string;\n}\n\n/**\n * Thrown when a single eval exhausts its configured PTC call budget.\n */\nexport class PTCCallBudgetExceededError extends Error {\n readonly limit: number;\n readonly attempted: number;\n readonly functionName: string;\n\n constructor(options: PTCCallBudgetExceededOptions) {\n super(\n `PTC call budget exceeded (limit=${options.limit}, attempted=${options.attempted}, function=${options.functionName})`,\n );\n this.name = \"PTCCallBudgetExceededError\";\n this.limit = options.limit;\n this.attempted = options.attempted;\n this.functionName = options.functionName;\n }\n}\n","import { compile } from \"json-schema-to-typescript\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport dedent from \"dedent\";\nimport type { ReplResult } from \"./types.js\";\n\n/**\n * Convert a snake_case or kebab-case string to camelCase.\n */\nexport function toCamelCase(name: string): string {\n return name.replace(/[-_]([a-z])/g, (_, c) => c.toUpperCase());\n}\n\n/**\n * Recursively collect all string values from an object, array, or primitive.\n */\nexport function collectStrings(obj: unknown): string[] {\n const result: string[] = [];\n function walk(val: unknown) {\n if (typeof val === \"string\") {\n result.push(val);\n } else if (Array.isArray(val)) {\n for (const item of val) walk(item);\n } else if (typeof val === \"object\" && val !== null) {\n for (const v of Object.values(val)) walk(v);\n }\n }\n walk(obj);\n return result;\n}\n\n/**\n * Format the result of a REPL evaluation for the agent.\n */\nexport function formatReplResult(result: ReplResult): string {\n const parts: string[] = [];\n\n if (result.logs.length > 0) {\n let logsText = result.logs.join(\"\\n\");\n if (result.logsDroppedChars > 0) {\n logsText += `\\n[truncated ${result.logsDroppedChars} chars]`;\n }\n parts.push(logsText);\n }\n\n if (result.ok) {\n if (result.value !== undefined) {\n const formatted =\n typeof result.value === \"string\"\n ? result.value\n : JSON.stringify(result.value, null, 2);\n parts.push(`→ ${formatted}`);\n }\n } else if (result.error) {\n const errName = result.error.name || \"Error\";\n const errMsg = result.error.message || \"Unknown error\";\n parts.push(`${errName}: ${errMsg}`);\n if (result.error.stack) {\n parts.push(result.error.stack);\n }\n }\n\n return parts.join(\"\\n\") || \"(no output)\";\n}\n\nexport function safeToJsonSchema(\n schema: unknown,\n): Record<string, unknown> | undefined {\n try {\n return toJsonSchema(schema as Parameters<typeof toJsonSchema>[0]) as Record<\n string,\n unknown\n >;\n } catch {\n return undefined;\n }\n}\n\nasync function schemaToInterface(\n jsonSchema: Record<string, unknown>,\n interfaceName: string,\n): Promise<string> {\n const compiled = await compile(\n { ...jsonSchema, additionalProperties: false },\n interfaceName,\n { bannerComment: \"\", additionalProperties: false },\n );\n return compiled.replace(/^export /, \"\").trimEnd();\n}\n\nexport function capitalize(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nexport async function toolToTypeSignature(\n name: string,\n description: string,\n jsonSchema: Record<string, unknown> | undefined,\n): Promise<string> {\n const inputType = `${capitalize(name)}Input`;\n\n if (!jsonSchema || !jsonSchema.properties) {\n return dedent`\n /**\n * ${description}\n */\n async tools.${name}(input: Record<string, unknown>): Promise<string>\n `;\n }\n\n const iface = await schemaToInterface(jsonSchema, inputType);\n return dedent`\n ${iface}\n\n /**\n * ${description}\n */\n async tools.${name}(input: ${inputType}): Promise<string>\n `;\n}\n","/**\n * Coercion of tool / subagent return values for the QuickJS bridge.\n *\n * The deepagents `task` tool resolves to a LangGraph `Command` whose payload\n * carries the subagent's final message(s) under `update.messages`; some tools\n * return a `ToolMessage` or a list of messages. The interpreter bridges need\n * the underlying output, not the envelope, so this unwraps those shapes to the\n * content the model actually cares about.\n */\nimport { isCommand, type Command } from \"@langchain/langgraph\";\nimport { BaseMessage } from \"@langchain/core/messages\";\n\n/**\n * Return the trailing message content from a `Command`'s `update.messages`,\n * scanning from the end for the last message that actually has content. Returns\n * the command unchanged when it has no message-shaped payload.\n */\nfunction extractCommandContent(command: Command): unknown {\n const update: unknown = command.update;\n const messages =\n update !== null && typeof update === \"object\"\n ? (update as { messages?: unknown }).messages\n : undefined;\n if (Array.isArray(messages)) {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (BaseMessage.isInstance(message) && message.content != null) {\n return message.content;\n }\n }\n }\n return command;\n}\n\n/**\n * Unwrap a LangChain `Command` / `ToolMessage` / message-list envelope to the\n * underlying content. Non-envelope values (strings, content-block arrays, plain\n * objects) are returned unchanged.\n *\n * @param value The raw value returned by a tool or subagent dispatch.\n * @returns The unwrapped content, or `value` itself when it isn't an envelope.\n */\nexport function unwrapToolEnvelope(value: unknown): unknown {\n if (typeof value === \"string\") return value;\n\n if (isCommand(value)) {\n const inner = extractCommandContent(value);\n return inner === value ? value : unwrapToolEnvelope(inner);\n }\n\n if (BaseMessage.isInstance(value)) {\n return unwrapToolEnvelope(value.content);\n }\n\n if (Array.isArray(value)) {\n for (let i = value.length - 1; i >= 0; i--) {\n const entry = value[i];\n if (BaseMessage.isInstance(entry)) {\n return unwrapToolEnvelope(entry.content);\n }\n if (isCommand(entry)) {\n const inner = extractCommandContent(entry);\n if (inner !== entry) return unwrapToolEnvelope(inner);\n }\n }\n return value;\n }\n\n return value;\n}\n","/**\n * AST-based code transform pipeline for the REPL.\n *\n * Transforms TypeScript/JavaScript code into plain JS that can be\n * evaluated inside QuickJS with proper state persistence:\n *\n * 1. Parse with acorn + acorn-typescript (handles TS syntax)\n * 2. Strip TypeScript-only nodes (type annotations, interfaces, etc.)\n * 3. Hoist top-level declarations to globalThis for cross-eval persistence\n * 4. Auto-return the last expression\n * 5. Wrap in async IIFE so top-level await works\n */\n\nimport { Parser } from \"acorn\";\nimport { tsPlugin } from \"@sveltejs/acorn-typescript\";\nimport { walk } from \"estree-walker\";\nimport MagicString from \"magic-string\";\nimport type {\n Node,\n Identifier,\n VariableDeclaration as EstreeVariableDeclaration,\n VariableDeclarator as EstreeVariableDeclarator,\n} from \"estree\";\n\nconst TSParser = Parser.extend(tsPlugin());\n\ntype AcornNode = Node & { start: number; end: number };\ntype AcornExpressionStatement = AcornNode & {\n type: \"ExpressionStatement\";\n expression: AcornNode;\n};\ntype AcornVariableDeclaration = EstreeVariableDeclaration & {\n start: number;\n end: number;\n declarations: AcornVariableDeclarator[];\n};\ntype AcornVariableDeclarator = EstreeVariableDeclarator & {\n start: number;\n end: number;\n id: AcornNode;\n init: AcornNode | null;\n};\n\n/**\n * Transform code for REPL evaluation.\n *\n * - Strips TypeScript syntax\n * - Hoists top-level variable declarations to globalThis\n * - Auto-returns the last expression\n * - Wraps in async IIFE for top-level await support\n */\nexport function transformForEval(code: string): string {\n let ast: AcornNode;\n try {\n ast = TSParser.parse(code, {\n ecmaVersion: \"latest\" as any,\n sourceType: \"module\",\n locations: true,\n }) as unknown as AcornNode;\n } catch {\n // If parsing fails, return the code as-is and let QuickJS report the error\n return `(async () => {\\n${code}\\n})()`;\n }\n\n const s = new MagicString(code);\n const program = ast as unknown as { body: AcornNode[] };\n const topLevelNodes = program.body;\n for (let i = 0; i < topLevelNodes.length; i++) {\n const node = topLevelNodes[i];\n\n // Remove TypeScript-only top-level declarations\n if (isTSOnlyNode(node)) {\n s.remove(node.start, node.end);\n continue;\n }\n\n // Remove import/export declarations (not supported in QuickJS eval)\n if (\n node.type === \"ImportDeclaration\" ||\n node.type === \"ExportNamedDeclaration\" ||\n node.type === \"ExportDefaultDeclaration\" ||\n node.type === \"ExportAllDeclaration\"\n ) {\n s.remove(node.start, node.end);\n continue;\n }\n\n // Hoist top-level variable declarations\n if (node.type === \"VariableDeclaration\") {\n hoistDeclaration(s, node as unknown as AcornVariableDeclaration);\n continue;\n }\n\n // Hoist function/class declarations to globalThis for cross-eval persistence\n if (\n node.type === \"FunctionDeclaration\" ||\n node.type === \"ClassDeclaration\"\n ) {\n stripTypeAnnotations(s, node);\n const name = (node as any).id?.name;\n if (name) {\n s.appendRight(node.end, `\\nglobalThis.${name} = ${name};`);\n }\n continue;\n }\n }\n\n // Strip type annotations from within expressions/statements\n for (const node of topLevelNodes) {\n if (isTSOnlyNode(node)) continue;\n if (\n node.type === \"ImportDeclaration\" ||\n node.type === \"ExportNamedDeclaration\" ||\n node.type === \"ExportDefaultDeclaration\" ||\n node.type === \"ExportAllDeclaration\"\n )\n continue;\n if (node.type !== \"VariableDeclaration\") {\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(s, n);\n },\n });\n }\n }\n\n // Auto-return the last expression. We insert `return (` before the\n // ExpressionStatement (to preserve any grouping parens like `({...})`),\n // but close `)` after the inner expression — not after the statement —\n // so any trailing semicolon stays outside: `return (expr);` not `return (expr;)`.\n const lastNode = findLastNonEmptyNode(topLevelNodes, s);\n if (lastNode && isExpression(lastNode)) {\n const { expression } = lastNode as AcornExpressionStatement;\n s.prependLeft(lastNode.start, \"return (\");\n s.appendRight(expression.end, \")\");\n }\n\n // Wrap in async IIFE\n s.prepend(\"(async () => {\\n\");\n s.append(\"\\n})()\");\n\n return s.toString();\n}\n\nfunction isTSOnlyNode(node: AcornNode): boolean {\n const t = node.type as string;\n if (\n t === \"TSTypeAliasDeclaration\" ||\n t === \"TSInterfaceDeclaration\" ||\n t === \"TSEnumDeclaration\" ||\n t === \"TSModuleDeclaration\" ||\n t === \"TSDeclareFunction\" ||\n t.startsWith(\"TS\")\n ) {\n return true;\n }\n // `declare const/let/var` — ambient variable declarations have no runtime effect\n if (t === \"VariableDeclaration\" && (node as any).declare === true) {\n return true;\n }\n // `import type { ... } from \"...\"` — type-only imports have no runtime effect\n if (t === \"ImportDeclaration\" && (node as any).importKind === \"type\") {\n return true;\n }\n // `export type { ... }` — type-only re-exports have no runtime effect\n if (t === \"ExportNamedDeclaration\" && (node as any).exportKind === \"type\") {\n return true;\n }\n return false;\n}\n\n/**\n * Rewrite a top-level VariableDeclaration to globalThis assignments.\n *\n * `const x = 1, y = 2` → `globalThis.x = 1; globalThis.y = 2`\n *\n */\nfunction hoistDeclaration(\n s: MagicString,\n decl: AcornVariableDeclaration,\n): void {\n const parts: string[] = [];\n\n for (const d of decl.declarations) {\n const id = d.id as AcornNode;\n if (id.type === \"Identifier\") {\n const initCode = d.init ? extractCleanInit(s, d) : \"undefined\";\n parts.push(\n `globalThis.${(id as unknown as Identifier).name} = ${initCode}`,\n );\n } else if (id.type === \"ObjectPattern\" || id.type === \"ArrayPattern\") {\n const bindings = extractBindingNames(d.id as any);\n const initCode = d.init ? extractCleanInit(s, d) : \"undefined\";\n const patternCode = extractCleanSource(s, d.id as AcornNode);\n parts.push(`var ${patternCode} = ${initCode}`);\n for (const name of bindings) {\n parts.push(`globalThis.${name} = ${name}`);\n }\n }\n }\n\n s.overwrite(decl.start, decl.end, parts.join(\"; \") + \";\");\n}\n\n/**\n * Extract the initializer code, stripping TypeScript annotations from\n * within the expression (e.g. `as Type`, generics, parameter types in\n * arrow functions).\n */\nfunction extractCleanInit(s: MagicString, d: AcornVariableDeclarator): string {\n if (!d.init) return \"undefined\";\n return extractCleanSource(s, d.init as AcornNode);\n}\n\nfunction extractBindingNames(pattern: any): string[] {\n const names: string[] = [];\n if (pattern.type === \"Identifier\") {\n if (pattern.name) names.push(pattern.name);\n } else if (pattern.type === \"ObjectPattern\") {\n for (const prop of pattern.properties || []) {\n if (prop.type === \"RestElement\") {\n names.push(...extractBindingNames(prop.argument));\n } else {\n names.push(...extractBindingNames(prop.value));\n }\n }\n } else if (pattern.type === \"ArrayPattern\") {\n for (const el of pattern.elements || []) {\n if (el) names.push(...extractBindingNames(el));\n }\n } else if (pattern.type === \"RestElement\") {\n names.push(...extractBindingNames(pattern.argument));\n } else if (pattern.type === \"AssignmentPattern\") {\n names.push(...extractBindingNames(pattern.left));\n }\n return names;\n}\n\nfunction stripTypeAnnotations(s: MagicString, node: AcornNode): void {\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(s, n);\n },\n });\n}\n\nfunction stripTypeAnnotationFromNode(s: MagicString, n: any, offset = 0): void {\n // Optional parameter marker: `b?: string` → `b`\n // The `?` sits between the identifier and the type annotation and must\n // be removed along with (or independently of) the type annotation.\n if (\n n.optional === true &&\n n.typeAnnotation &&\n n.typeAnnotation.start != null\n ) {\n // Remove `?: string` as a single span (the `?` is one char before `:`)\n s.remove(\n n.typeAnnotation.start - 1 - offset,\n n.typeAnnotation.end - offset,\n );\n } else if (n.optional === true && !n.typeAnnotation) {\n // `b?` with no type annotation — remove just the `?`\n const nameEnd =\n n.type === \"Identifier\" && typeof n.name === \"string\"\n ? n.start + n.name.length\n : null;\n if (nameEnd != null) {\n s.remove(nameEnd - offset, nameEnd + 1 - offset);\n }\n } else if (n.typeAnnotation && n.typeAnnotation.start != null) {\n // Regular type annotation without optional marker\n s.remove(n.typeAnnotation.start - offset, n.typeAnnotation.end - offset);\n }\n // Return type on functions\n if (n.returnType && n.returnType.start != null) {\n s.remove(n.returnType.start - offset, n.returnType.end - offset);\n }\n // Type parameters (generics)\n if (n.typeParameters && n.typeParameters.start != null) {\n s.remove(n.typeParameters.start - offset, n.typeParameters.end - offset);\n }\n // Type arguments on calls\n if (n.typeArguments && n.typeArguments.start != null) {\n s.remove(n.typeArguments.start - offset, n.typeArguments.end - offset);\n }\n // `as` expressions: keep the expression, remove `as Type`\n if (n.type === \"TSAsExpression\" && n.expression) {\n s.remove(n.expression.end - offset, n.end - offset);\n }\n // Non-null assertion: `x!` → `x`\n if (n.type === \"TSNonNullExpression\" && n.expression) {\n s.remove(n.expression.end - offset, n.end - offset);\n }\n // Satisfies expression: `x satisfies Type` → `x`\n if (n.type === \"TSSatisfiesExpression\" && n.expression) {\n s.remove(n.expression.end - offset, n.end - offset);\n }\n}\n\n/**\n * Extract a clean JS source string from an AST node, stripping all\n * TypeScript annotations. Works on a copy so the main MagicString is\n * not mutated.\n */\nfunction extractCleanSource(s: MagicString, node: AcornNode): string {\n const offset = node.start;\n const source = new MagicString(s.slice(node.start, node.end));\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(source, n, offset);\n },\n });\n return source.toString();\n}\n\nfunction findLastNonEmptyNode(\n nodes: AcornNode[],\n s: MagicString,\n): AcornNode | null {\n for (let i = nodes.length - 1; i >= 0; i--) {\n const node = nodes[i];\n // Skip nodes that were fully removed\n const slice = s.slice(node.start, node.end).trim();\n if (slice === \"\" || slice === \";\") continue;\n return node;\n }\n return null;\n}\n\nfunction isExpression(node: AcornNode): boolean {\n return node.type === \"ExpressionStatement\";\n}\n\n/**\n * Strip TypeScript type syntax from an ES-module source so QuickJS can\n * evaluate it as a standard JS module.\n *\n * Unlike `transformForEval`, this keeps `import`/`export` declarations,\n * does not hoist to `globalThis`, and does not wrap in an IIFE.\n * On parse failure the original source is returned unchanged.\n */\nexport function stripTypeSyntax(code: string): string {\n let ast: AcornNode;\n try {\n ast = TSParser.parse(code, {\n ecmaVersion: \"latest\",\n sourceType: \"module\",\n locations: true,\n }) as unknown as AcornNode;\n } catch {\n // Return the original source unchanged rather than throwing or returning an empty string.\n // We don't know why the parse failed - it could be a valid plain-JS file that hit an\n // acorn-typescript incompatibility, in which case returning it unchanged lets QuickJS\n // evaluate it correctly. If it's genuinely broken TS, QuickJS will surface the parse error\n // at evaluation time with a useful line/column.\n return code;\n }\n\n const magicString = new MagicString(code);\n const program = ast as unknown as { body: AcornNode[] };\n\n for (const node of program.body) {\n if (isTSOnlyNode(node)) {\n magicString.remove(node.start, node.end);\n continue;\n }\n\n walk(node as any, {\n enter(n: any) {\n stripTypeAnnotationFromNode(magicString, n);\n },\n });\n }\n\n return magicString.toString();\n}\n","/**\n * Serializes async operations on a shared WASM module.\n *\n * The quickjs-emscripten asyncify variant allows only one concurrent\n * async call per module instance. This queue enforces that constraint\n * by chaining operations into a promise queue — each caller waits for\n * the previous one to finish before executing.\n */\nexport class AsyncEvalQueue {\n private tail = Promise.resolve();\n\n /**\n * Enqueue an async operation. The operation will not start until all\n * previously enqueued operations have completed.\n */\n async enqueue<T>(fn: () => Promise<T>): Promise<T> {\n let release: () => void;\n const gate = new Promise<void>((r) => {\n release = r;\n });\n\n const prev = this.tail;\n this.tail = gate;\n\n return prev.then(async () => {\n try {\n return await fn();\n } finally {\n release();\n }\n });\n }\n}\n","/**\n * Core REPL engine built on quickjs-emscripten (asyncify variant).\n *\n * Host async functions (backend I/O, PTC tools) are exposed as\n * promise-returning functions inside the QuickJS guest. Guest code\n * uses `await` to consume them, enabling real concurrency via\n * `Promise.all`, `Promise.race`, etc.\n *\n * We still use the asyncify WASM variant because `evalCodeAsync` is\n * required to drive promise resolution from the host side.\n *\n * ## Architecture\n *\n * `ReplSession` is a serializable handle that can live in LangGraph state.\n * It holds an `id` that keys into a static session map. The heavy QuickJS\n * runtime is lazily started on the first `.eval()` call, making the session\n * safe across graph interrupts and checkpointing.\n */\n\nimport { shouldInterruptAfterDeadline } from \"quickjs-emscripten\";\nimport type { QuickJSHandle } from \"quickjs-emscripten\";\nimport { newQuickJSAsyncWASMModuleFromVariant } from \"quickjs-emscripten-core\";\nimport type {\n QuickJSAsyncContext,\n QuickJSAsyncRuntime,\n QuickJSAsyncWASMModule,\n} from \"quickjs-emscripten-core\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\n\nimport { PTCCallBudgetExceededError } from \"./errors.js\";\nimport type {\n ReplSessionOptions,\n ReplResult,\n SubagentBridgeOptions,\n} from \"./types.js\";\nimport { toCamelCase } from \"./utils.js\";\nimport { unwrapToolEnvelope } from \"./coerce.js\";\nimport { transformForEval } from \"./transform.js\";\nimport { AsyncEvalQueue } from \"./eval-queue.js\";\nimport PQueue from \"p-queue\";\n\nexport const DEFAULT_MEMORY_LIMIT = 64 * 1024 * 1024;\nexport const DEFAULT_MAX_STACK_SIZE = 320 * 1024;\nexport const DEFAULT_EXECUTION_TIMEOUT = 5_000;\nexport const DEFAULT_SESSION_ID = \"__default__\";\nexport const DEFAULT_MAX_PTC_CALLS = 256;\nexport const DEFAULT_MAX_RESULTS_CHARS = 4000;\nexport const DEFAULT_MAX_SUBAGENT_CONCURRENCY = 32;\n\nconst LINE_NUMBER_RE = /^\\s*\\d+(?:\\.\\d+)?\\t/;\n\nconst variantImport = import(\"@jitl/quickjs-ng-wasmfile-release-asyncify\");\n\n/**\n * Process-global eval queue. Serializes all evalCodeAsync calls across\n * sessions to enforce the asyncify one-at-a-time constraint.\n */\nconst sharedEvalQueue = new AsyncEvalQueue();\n\n/**\n * Process-global WASM module shared by all sessions.\n *\n * Each session creates its own runtime and context on this module,\n * providing full isolation for globals, heap, and stack. The module\n * itself is stateless between runtimes — only the compiled WASM code\n * and Emscripten infrastructure are shared.\n *\n * This is safe because:\n * - The module loader is synchronous (preloaded skill cache), so\n * imports don't cause asyncify suspensions.\n * - Tool injection uses the promise-based pattern (newFunction +\n * newPromise), not newAsyncifiedFunction, so tool calls don't\n * cause asyncify suspensions.\n * - The eval queue serializes evalCodeAsync calls to satisfy the\n * one-concurrent-async-call-per-module constraint.\n */\nlet sharedModulePromise: Promise<QuickJSAsyncWASMModule> | undefined;\n\nfunction getSharedModule(): Promise<QuickJSAsyncWASMModule> {\n if (!sharedModulePromise) {\n sharedModulePromise = (async () => {\n const variant = await variantImport;\n return newQuickJSAsyncWASMModuleFromVariant(\n (variant.default ?? variant) as any,\n );\n })();\n }\n return sharedModulePromise;\n}\n\n/**\n * Unwrap a PTC tool result to a plain string for use inside QuickJS.\n *\n * Tool results may arrive as a raw string, or as an array of LangChain\n * content blocks (`{ type: \"text\", text: \"...\" }`). Blocks are joined\n * with newlines; non-text block types are silently skipped. Anything\n * else (objects, nulls) is JSON-serialised as a fallback.\n *\n * @param result - Raw return value from `tool.invoke()`.\n * @returns Plain string representation of the tool output.\n */\nfunction extractToolText(result: unknown): string {\n // Unwrap LangChain Command / ToolMessage / message-list envelopes (e.g. a\n // PTC tool that returns a Command) before extracting text.\n result = unwrapToolEnvelope(result);\n\n if (typeof result === \"string\") {\n return result;\n }\n\n if (Array.isArray(result)) {\n const texts: string[] = [];\n for (const block of result) {\n if (\n typeof block === \"object\" &&\n block !== null &&\n (block as Record<string, unknown>).type === \"text\" &&\n typeof (block as Record<string, unknown>).text === \"string\"\n ) {\n texts.push((block as Record<string, unknown>).text as string);\n }\n }\n\n if (texts.length > 0) {\n return texts.join(\"\\n\");\n }\n }\n return JSON.stringify(result);\n}\n\n/**\n * Remove the `cat -n` line-number prefix from every line of a string.\n *\n * The filesystem backend formats file content with line numbers in the\n * form `\" N\\t\"` so human readers can navigate by line. That prefix\n * is useful for the agent but noise for QuickJS code that parses the\n * text programmatically (e.g. swarm reading `/context.txt`).\n *\n * The function is conservative: if any non-empty line lacks the prefix,\n * the text is returned unchanged so nothing is silently corrupted.\n *\n * @param text - Raw file content, possibly line-number prefixed.\n * @returns Content with line-number prefixes stripped, or the original\n * text if it doesn't match the expected format throughout.\n */\nfunction stripLineNumbers(text: string): string {\n const lines = text.split(\"\\n\");\n if (lines.length === 0) {\n return text;\n }\n\n if (!lines.every((l) => l === \"\" || LINE_NUMBER_RE.test(l))) {\n return text;\n }\n\n return lines.map((l) => l.replace(LINE_NUMBER_RE, \"\")).join(\"\\n\");\n}\n\n/**\n * Fixed-size character buffer for capturing console output from the QuickJS VM.\n *\n * Lines are accumulated up to `maxChars`. Once the cap is reached, excess\n * characters are counted as dropped rather than silently discarded without\n * attribution, so callers can surface a truncation notice to the user.\n */\nclass ConsoleBuffer {\n private readonly maxChars: number;\n private buffer: string = \"\";\n private droppedChars: number = 0;\n\n constructor(maxChars: number) {\n this.maxChars = Math.max(maxChars, 0);\n }\n\n /**\n * Append `line` to the buffer.\n *\n * If the buffer is already full the entire line is counted as dropped.\n * If `line` partially fits, the fitting prefix is stored and the remainder\n * is counted as dropped.\n */\n append(line: string): void {\n const remaining = this.maxChars - this.buffer.length;\n if (remaining <= 0) {\n this.droppedChars += line.length;\n return;\n }\n\n if (line.length <= remaining) {\n this.buffer += line;\n } else {\n this.buffer += line.slice(0, remaining);\n this.droppedChars += line.length - remaining;\n }\n }\n\n /**\n * Return the buffered output and dropped-character count as `[buffered,\n * droppedChars]`, then reset both to zero.\n */\n drain(): [string, number] {\n const out = this.buffer;\n const dropped = this.droppedChars;\n\n this.buffer = \"\";\n this.droppedChars = 0;\n\n return [out, dropped];\n }\n}\n\n/**\n * Sandboxed JavaScript REPL session backed by QuickJS WASM.\n *\n * Serializable — holds an `id` that keys into a static session map.\n * The QuickJS runtime is lazily started on the first `.eval()` call\n * and reconnected if a session with the same id already exists.\n * This makes it safe to store in LangGraph state across interrupts.\n */\nexport class ReplSession {\n private static sessions = new Map<string, ReplSession>();\n\n readonly id: string;\n\n private runtime: QuickJSAsyncRuntime | null = null;\n private context: QuickJSAsyncContext | null = null;\n private consoleBuffer: ConsoleBuffer = new ConsoleBuffer(\n DEFAULT_MAX_RESULTS_CHARS,\n );\n private options: ReplSessionOptions;\n private readonly maxPtcCalls: number | null;\n private ptcCallsRemaining: number | null = null;\n private subagentQueue: PQueue | null = null;\n private bridgeDispatchRef: {\n current: SubagentBridgeOptions[\"dispatch\"];\n } | null = null;\n\n /** Allowed keys in the subagent input object. */\n private static readonly SUBAGENT_ALLOWED_KEYS = new Set([\n \"description\",\n \"subagentType\",\n \"responseSchema\",\n ]);\n\n /**\n * Reset the shared WASM module. Forces the next session to instantiate\n * a fresh module. Only needed in tests where module state must be\n * isolated between test files.\n *\n * @internal\n */\n static resetSharedModule(): void {\n sharedModulePromise = undefined;\n }\n\n constructor(id: string, options: ReplSessionOptions = {}) {\n this.id = id;\n this.options = options;\n this.maxPtcCalls =\n options.maxPtcCalls !== undefined\n ? options.maxPtcCalls\n : DEFAULT_MAX_PTC_CALLS;\n }\n\n private async ensureStarted(): Promise<void> {\n if (this.runtime) return;\n\n const {\n memoryLimitBytes = DEFAULT_MEMORY_LIMIT,\n maxStackSizeBytes = DEFAULT_MAX_STACK_SIZE,\n tools,\n maxResultChars = DEFAULT_MAX_RESULTS_CHARS,\n captureConsole = true,\n } = this.options;\n\n const asyncModule = await getSharedModule();\n const runtime: QuickJSAsyncRuntime = asyncModule.newRuntime();\n runtime.setMemoryLimit(memoryLimitBytes);\n runtime.setMaxStackSize(maxStackSizeBytes);\n\n const context: QuickJSAsyncContext = runtime.newContext();\n this.runtime = runtime;\n this.context = context;\n\n this.consoleBuffer = new ConsoleBuffer(maxResultChars);\n if (captureConsole) {\n this.setupConsole();\n }\n\n if (tools !== undefined && tools.length > 0) {\n this.injectTools(tools);\n }\n\n const { subagentBridge } = this.options;\n if (subagentBridge) {\n this.subagentQueue = new PQueue({\n concurrency: subagentBridge.maxConcurrency,\n });\n this.injectSubagentBridge(subagentBridge.dispatch);\n }\n\n const sessionId = this.options.sessionId ?? \"default\";\n const sessionIdHandle = context.newString(sessionId);\n context.setProp(context.global, \"__sessionId__\", sessionIdHandle);\n sessionIdHandle.dispose();\n }\n\n /**\n * Initialise the per-eval PTC counter. Called at the top of every `eval()`.\n */\n private resetPtcBudget(): void {\n this.ptcCallsRemaining =\n this.maxPtcCalls === null ? null : this.maxPtcCalls;\n }\n\n /**\n * Decrement the PTC call counter and throw if the budget is exhausted.\n * `null` budget means unlimited — returns immediately without decrementing.\n */\n private consumePtcBudget(functionName: string): void {\n if (this.ptcCallsRemaining === null) {\n return;\n }\n\n if (this.ptcCallsRemaining > 0) {\n this.ptcCallsRemaining--;\n return;\n }\n\n const limit = this.maxPtcCalls ?? 0;\n throw new PTCCallBudgetExceededError({\n limit,\n attempted: limit + 1,\n functionName,\n });\n }\n\n /**\n * Get or create a session for the given id.\n *\n * Sessions are deduped by id — calling `getOrCreate` twice with the\n * same id returns the same instance. The QuickJS runtime is lazily\n * started on the first `.eval()` call.\n */\n static getOrCreate(\n id: string,\n options: ReplSessionOptions = {},\n ): ReplSession {\n const existing = ReplSession.sessions.get(id);\n if (existing) {\n return existing;\n }\n\n const session = new ReplSession(id, options);\n ReplSession.sessions.set(id, session);\n return session;\n }\n\n /**\n * Retrieve an existing session by id, or null if none exists.\n */\n static get(id: string): ReplSession | null {\n return ReplSession.sessions.get(id) ?? null;\n }\n\n /**\n * Returns true if any session exists whose key equals `threadId` or starts\n * with `threadId:`. Useful for tests that need to confirm a session was\n * created without knowing the full `threadId:middlewareId` key.\n */\n static hasAnyForThread(threadId: string): boolean {\n const prefix = `${threadId}:`;\n for (const key of ReplSession.sessions.keys()) {\n if (key === threadId || key.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Dispose and remove the session with the given key, if it exists.\n */\n static deleteSession(key: string): void {\n const session = ReplSession.sessions.get(key);\n if (session) {\n session.dispose();\n }\n }\n\n /**\n * Evaluate code in this session.\n *\n * Lazily starts the QuickJS runtime on the first call. Code is\n * transformed via an AST pipeline that strips TypeScript syntax,\n * hoists top-level declarations to globalThis for cross-eval\n * persistence, auto-returns the last expression, and wraps in an\n * async IIFE.\n */\n async eval(code: string, timeoutMs: number): Promise<ReplResult> {\n await this.ensureStarted();\n const runtime = this.runtime!;\n const context = this.context!;\n\n const drainLogs = (): { logs: string[]; logsDroppedChars: number } => {\n const [raw, dropped] = this.consoleBuffer.drain();\n return {\n logs: raw.length > 0 ? raw.split(\"\\n\").filter((l) => l.length > 0) : [],\n logsDroppedChars: dropped,\n };\n };\n\n this.resetPtcBudget();\n try {\n if (timeoutMs >= 0) {\n runtime.setInterruptHandler(\n shouldInterruptAfterDeadline(Date.now() + timeoutMs),\n );\n } else {\n runtime.setInterruptHandler(() => false);\n }\n\n const transformed = transformForEval(code);\n const result = await sharedEvalQueue.enqueue(() =>\n context.evalCodeAsync(transformed),\n );\n\n if (result.error) {\n const error = context.dump(result.error);\n result.error.dispose();\n return { ok: false, error, ...drainLogs() };\n }\n\n const promiseState = context.getPromiseState(result.value);\n\n if (promiseState.type === \"fulfilled\") {\n if (promiseState.notAPromise) {\n const value = context.dump(result.value);\n result.value.dispose();\n return { ok: true, value, ...drainLogs() };\n }\n const value = context.dump(promiseState.value);\n promiseState.value.dispose();\n result.value.dispose();\n return { ok: true, value, ...drainLogs() };\n }\n\n if (promiseState.type === \"rejected\") {\n const error = context.dump(promiseState.error);\n promiseState.error.dispose();\n result.value.dispose();\n return { ok: false, error, ...drainLogs() };\n }\n\n const noTimeout = timeoutMs < 0;\n const deadline = noTimeout ? Infinity : Date.now() + timeoutMs;\n while (noTimeout || Date.now() < deadline) {\n context.runtime.executePendingJobs();\n const state = context.getPromiseState(result.value);\n if (state.type === \"fulfilled\") {\n const value = context.dump(state.value);\n state.value.dispose();\n result.value.dispose();\n return { ok: true, value, ...drainLogs() };\n }\n if (state.type === \"rejected\") {\n const error = context.dump(state.error);\n state.error.dispose();\n result.value.dispose();\n return { ok: false, error, ...drainLogs() };\n }\n await new Promise((r) => setTimeout(r, 1));\n }\n\n result.value.dispose();\n return {\n ok: false,\n error: { message: \"Promise timed out — execution interrupted\" },\n ...drainLogs(),\n };\n } finally {\n this.ptcCallsRemaining = null;\n }\n }\n\n dispose(): void {\n try {\n this.context?.dispose();\n } catch {\n /* may already be disposed */\n }\n try {\n this.runtime?.dispose();\n } catch {\n /* may already be disposed */\n }\n this.runtime = null;\n this.context = null;\n ReplSession.sessions.delete(this.id);\n }\n\n toJSON(): { id: string } {\n return { id: this.id };\n }\n\n static fromJSON(data: { id: string }): ReplSession {\n return ReplSession.sessions.get(data.id) ?? new ReplSession(data.id);\n }\n\n /**\n * Clear the static session cache. Useful for testing.\n * @internal\n */\n static clearCache(): void {\n for (const session of ReplSession.sessions.values()) {\n session.dispose();\n }\n ReplSession.sessions.clear();\n }\n\n private setupConsole(): void {\n const context = this.context!;\n const consoleHandle = context.newObject();\n for (const method of [\"log\", \"warn\", \"error\", \"info\", \"debug\"] as const) {\n const fnHandle = context.newFunction(\n method,\n (...args: QuickJSHandle[]) => {\n const nativeArgs = args.map((a: QuickJSHandle) => context.dump(a));\n const formatted = nativeArgs\n .map((a: unknown) =>\n typeof a === \"object\" && a !== null\n ? JSON.stringify(a)\n : String(a),\n )\n .join(\" \");\n const line =\n method === \"log\" || method === \"info\" || method === \"debug\"\n ? formatted\n : `[${method}] ${formatted}`;\n this.consoleBuffer.append(line + \"\\n\");\n },\n );\n context.setProp(consoleHandle, method, fnHandle);\n fnHandle.dispose();\n }\n context.setProp(context.global, \"console\", consoleHandle);\n consoleHandle.dispose();\n }\n\n private injectTools(tools: StructuredToolInterface[]): void {\n const context = this.context!;\n const toolsNs = context.newObject();\n\n for (const t of tools) {\n const camelName = toCamelCase(t.name);\n const fnHandle = context.newFunction(\n camelName,\n (inputHandle: QuickJSHandle) => {\n const input = context.dump(inputHandle);\n const promise = context.newPromise();\n (async () => {\n try {\n this.consumePtcBudget(camelName);\n const rawInput =\n typeof input === \"object\" && input !== null ? input : {};\n const result = await t.invoke(rawInput);\n let text = extractToolText(result);\n if (t.name === \"read_file\") {\n text = stripLineNumbers(text);\n }\n const val = context.newString(text);\n promise.resolve(val);\n val.dispose();\n } catch (e: unknown) {\n const msg =\n e != null && typeof (e as Error).message === \"string\"\n ? (e as Error).message\n : String(e);\n const err = context.newError(`Tool '${t.name}' failed: ${msg}`);\n promise.reject(err);\n err.dispose();\n }\n promise.settled.then(context.runtime.executePendingJobs);\n })();\n return promise.handle;\n },\n );\n context.setProp(toolsNs, camelName, fnHandle);\n fnHandle.dispose();\n }\n\n context.setProp(context.global, \"tools\", toolsNs);\n toolsNs.dispose();\n }\n\n /**\n * Install the `task` global on the QuickJS context.\n *\n * Registers the host function directly as `globalThis.task`,\n * then freezes it via `evalCode`. Structured results (when\n * responseSchema is provided) are marshaled into native QuickJS\n * objects on the host side — no JS wrapper needed.\n */\n /**\n * Replace the active bridge dispatch with a fresh one.\n *\n * Call this before each eval so the dispatch closure carries\n * the current invocation's config (tracing callbacks, run ID, etc.)\n * rather than the stale config from session creation.\n */\n updateBridgeDispatch(dispatch: SubagentBridgeOptions[\"dispatch\"]): void {\n if (this.bridgeDispatchRef) {\n this.bridgeDispatchRef.current = dispatch;\n }\n }\n\n private injectSubagentBridge(\n dispatch: SubagentBridgeOptions[\"dispatch\"],\n ): void {\n const context = this.context!;\n const queue = this.subagentQueue!;\n\n this.bridgeDispatchRef = { current: dispatch };\n const ref = this.bridgeDispatchRef;\n\n const hostFn = context.newFunction(\"task\", (inputHandle: QuickJSHandle) => {\n const input = context.dump(inputHandle);\n const promise = context.newPromise();\n\n (async () => {\n try {\n if (\n input == null ||\n typeof input !== \"object\" ||\n Array.isArray(input)\n ) {\n throw new Error(\"task: expected an object argument\");\n }\n const raw = input as Record<string, unknown>;\n\n // Accept snake_case aliases so models don't need to know our convention\n const obj: Record<string, unknown> = { ...raw };\n if (\"subagent_type\" in obj) {\n obj.subagentType ??= obj.subagent_type;\n delete obj.subagent_type;\n }\n if (\"response_schema\" in obj) {\n obj.responseSchema ??= obj.response_schema;\n delete obj.response_schema;\n }\n\n const unknownKeys = Object.keys(obj).filter(\n (k) => !ReplSession.SUBAGENT_ALLOWED_KEYS.has(k),\n );\n if (unknownKeys.length > 0) {\n throw new Error(\n `task: unknown keys: ${unknownKeys.join(\", \")}. ` +\n `Allowed: ${[...ReplSession.SUBAGENT_ALLOWED_KEYS].join(\", \")}`,\n );\n }\n\n const { description, subagentType, responseSchema } = obj;\n\n if (typeof description !== \"string\" || description.length === 0) {\n throw new Error(\n \"task: 'description' is required and must be a non-empty string\",\n );\n }\n if (typeof subagentType !== \"string\" || subagentType.length === 0) {\n throw new Error(\n \"task: 'subagentType' is required and must be a non-empty string\",\n );\n }\n if (\n responseSchema !== undefined &&\n (responseSchema == null ||\n typeof responseSchema !== \"object\" ||\n Array.isArray(responseSchema))\n ) {\n throw new Error(\n \"task: 'responseSchema' must be a plain object (JSON Schema) when provided\",\n );\n }\n\n const result = await queue.add(() =>\n ref.current({\n description: description as string,\n subagentType: subagentType as string,\n ...(responseSchema !== undefined && {\n responseSchema: responseSchema as Record<string, unknown>,\n }),\n }),\n );\n if (typeof result === \"string\") {\n const val = context.newString(result);\n promise.resolve(val);\n val.dispose();\n } else {\n const jsonResult = context.evalCode(`(${JSON.stringify(result)})`);\n if (jsonResult.error) {\n const errDump = context.dump(jsonResult.error);\n jsonResult.error.dispose();\n throw new Error(\n `task: failed to marshal structured response: ${JSON.stringify(errDump)}`,\n );\n }\n promise.resolve(jsonResult.value);\n jsonResult.value.dispose();\n }\n } catch (e: unknown) {\n const msg =\n e != null && typeof (e as Error).message === \"string\"\n ? (e as Error).message\n : String(e);\n const err = context.newError(msg);\n promise.reject(err);\n err.dispose();\n }\n promise.settled.then(context.runtime.executePendingJobs);\n })();\n\n return promise.handle;\n });\n\n context.setProp(context.global, \"task\", hostFn);\n hostFn.dispose();\n\n context.evalCode(\n \"Object.freeze(globalThis.task);\" +\n \"Object.defineProperty(globalThis, 'task', {\" +\n \" value: globalThis.task,\" +\n \" writable: false,\" +\n \" configurable: false,\" +\n \"}); undefined\",\n );\n }\n}\n","const SCHEMA_MAX_BYTES = 4096;\nconst SCHEMA_MAX_DEPTH = 5;\nconst SCHEMA_MAX_PROPERTIES = 32;\n\n/**\n * Validate that a response schema does not exceed size, depth, or\n * property-count limits.\n *\n * @throws Error if any limit is exceeded.\n */\nexport function validateResponseSchema(schema: Record<string, unknown>): void {\n const serialized = JSON.stringify(schema);\n if (serialized.length > SCHEMA_MAX_BYTES) {\n throw new Error(\n `responseSchema exceeds ${SCHEMA_MAX_BYTES} byte limit (${serialized.length} bytes)`,\n );\n }\n\n function check(\n node: Record<string, unknown>,\n depth: number,\n propCount: { value: number },\n ): void {\n if (depth > SCHEMA_MAX_DEPTH) {\n throw new Error(\n `responseSchema exceeds maximum nesting depth of ${SCHEMA_MAX_DEPTH}`,\n );\n }\n const props = node.properties;\n if (props != null && typeof props === \"object\" && !Array.isArray(props)) {\n const propObj = props as Record<string, unknown>;\n propCount.value += Object.keys(propObj).length;\n if (propCount.value > SCHEMA_MAX_PROPERTIES) {\n throw new Error(\n `responseSchema exceeds maximum of ${SCHEMA_MAX_PROPERTIES} properties`,\n );\n }\n for (const value of Object.values(propObj)) {\n if (\n value != null &&\n typeof value === \"object\" &&\n !Array.isArray(value)\n ) {\n check(value as Record<string, unknown>, depth + 1, propCount);\n }\n }\n }\n const items = node.items;\n if (items != null && typeof items === \"object\" && !Array.isArray(items)) {\n check(items as Record<string, unknown>, depth + 1, propCount);\n }\n }\n\n check(schema, 0, { value: 0 });\n}\n","/**\n * Code Interpreter middleware for deepagents.\n *\n * Provides an `eval` tool that runs JavaScript in a WASM-sandboxed QuickJS\n * interpreter. Supports:\n * - Persistent state across evaluations (true REPL)\n * - Programmatic tool calling (PTC) — expose agent or custom tools inside the REPL\n */\n\nimport {\n createMiddleware,\n tool,\n type AgentMiddleware as _AgentMiddleware,\n} from \"langchain\";\nimport { z } from \"zod/v4\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY } from \"deepagents\";\n\nimport dedent from \"dedent\";\nimport type {\n CodeInterpreterMiddlewareOptions,\n SubagentBridgeOptions,\n} from \"./types.js\";\nimport {\n ReplSession,\n DEFAULT_EXECUTION_TIMEOUT,\n DEFAULT_MEMORY_LIMIT,\n DEFAULT_MAX_STACK_SIZE,\n DEFAULT_SESSION_ID,\n DEFAULT_MAX_PTC_CALLS,\n DEFAULT_MAX_RESULTS_CHARS,\n DEFAULT_MAX_SUBAGENT_CONCURRENCY,\n} from \"./session.js\";\nimport {\n formatReplResult,\n toCamelCase,\n toolToTypeSignature,\n safeToJsonSchema,\n} from \"./utils.js\";\nimport { validateResponseSchema } from \"./subagent-dispatch.js\";\nimport { unwrapToolEnvelope } from \"./coerce.js\";\n\n/**\n * These type-only imports are required for TypeScript's type inference to work\n * correctly with the langchain/langgraph middleware system. Without them, certain\n * generic type parameters fail to resolve properly, causing runtime issues with\n * tool schemas and message types.\n */\nimport type * as _zodTypes from \"@langchain/core/utils/types\";\nimport type * as _zodMeta from \"@langchain/langgraph/zod\";\nimport type * as _messages from \"@langchain/core/messages\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\n\nconst DEFAULT_TOOL_NAME = \"eval\";\n\n/**\n * Render the subagent dispatch prompt section for the system message.\n * Ported from the Python `_SUBAGENT_SYSTEM_PROMPT_TEMPLATE`.\n */\nfunction renderSubagentPrompt(toolName: string): string {\n return dedent`\n\n ### Dispatching Subagents with \\`task\\`\n\n \\`task\\` is your primitive for running configured subagents from inside the\n JavaScript REPL. Your job here is to DISTRIBUTE work, not to do it yourself:\n write JavaScript that fans work out to subagents and assembles their results.\n You handle the orchestration - fan-out, filtering, deduplication, multi-stage\n flow, and synthesis - in plain JavaScript.\n\n #### The primitive\n\n \\`\\`\\`javascript\n await task({\n description, // full autonomous task prompt\n subagentType, // configured subagent name\n responseSchema, // optional JSON Schema for structured output\n }); // -> Promise<unknown>\n \\`\\`\\`\n\n \\`task\\` runs a full agentic loop for the selected configured subagent. The\n subagent can use whatever tools it was configured with, iterate, inspect\n context, and return one final result. \\`subagentType\\` is required; use one of\n the configured subagent names.\n\n \\`description\\` is the only prompt the subagent receives for this dispatch. Make\n it complete: the goal, the constraints, what to inspect, and the exact shape\n or level of detail you expect back. Give context as locators — file paths and\n symbol names — not as pasted file contents. If you already read a file while\n exploring, still pass its path and let the subagent read it; do not paste back\n what you read. Each dispatch is stateless from the caller's perspective; you\n cannot send follow-up messages to the same subagent run.\n\n \\`responseSchema\\` is optional, but set it on any dispatch whose result feeds\n later code. A deterministic, typed shape is what lets you compose the next\n stage reliably — index it, sort it, compare fields, branch on it, merge it —\n instead of parsing free-form text. This is what makes a whole workflow\n composable as one script. When provided, the resolved value is already a typed\n JavaScript value matching the schema; do not call \\`JSON.parse\\` unless the\n subagent intentionally returned a JSON string. Dynamic schemas work for\n declarative subagents; runnable-backed subagents reject dynamic schemas because\n their runnable is already compiled.\n\n #### Approval model\n\n \\`task\\` dispatches from inside the already-running \\`${toolName}\\` call. It\n does not route through the parent agent's \\`ToolNode\\`-managed \\`task\\` tool and\n does not trigger parent-level \\`interrupt_on\\` / HITL approval for each dispatch.\n Declarative subagents still honor approval middleware configured inside their\n own spec. If you need approval before launching a subagent from the parent, use\n the normal \\`task\\` tool outside JavaScript or ensure the \\`${toolName}\\` call\n itself is approval-gated.\n\n #### Mental model\n\n Hold your work in JS: an array of items in, an array of results out. Merge each\n dispatch result back onto its item. Multi-stage analysis means: run a pass,\n filter or regroup the array in JS, then run another pass over the survivors.\n\n You can run the whole workflow in one \\`${toolName}\\` call or split it across\n several — both are fine. A single end-to-end script (generate, compare, pick a\n winner; or review every item, then synthesize) is clean when you can write it\n in one go; splitting is also fine when you want to inspect results between\n stages. Either way, don't redo work across calls — reuse what is already in\n scope (see \"Reuse what earlier evals left in scope\" below).\n\n #### Fan out with bounded concurrency\n\n Dispatch independent work in parallel with \\`Promise.all\\`, but in explicit\n batches around 10 so you do not launch hundreds of subagents at once. The bridge\n enforces a hard per-REPL cap of 32 concurrent subagent calls.\n\n \\`\\`\\`javascript\n const files = [\"/src/a.ts\", \"/src/b.ts\", \"/src/c.ts\"]; // found while exploring\n const batchSize = 10;\n const reviewed = [];\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n reviewed.push(...(await Promise.all(batch.map(async (file) => {\n const result = await task({\n description: \"Read \" + file + \" and review it for SQL injection. \" +\n \"Cite line numbers.\",\n subagentType: \"reviewer\",\n responseSchema: {\n type: \"object\",\n properties: {\n vulnerabilities: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n type: { type: \"string\" },\n line: { type: \"number\" },\n evidence: { type: \"string\" },\n },\n required: [\"type\", \"line\", \"evidence\"],\n },\n },\n },\n required: [\"vulnerabilities\"],\n },\n });\n return { file, ...result };\n }))));\n }\n \\`\\`\\`\n\n #### Explore with your own tools first, then distribute\n\n You already have your normal tools for reading, listing, globbing, and\n grepping files. Use them to explore and understand the task BEFORE you write\n the orchestration script. These are ordinary tool calls, separate from the\n \\`${toolName}\\` tool: read the data file, list or glob the directory, grep for\n what matters, then decide how to split the work.\n\n Never write \\`${toolName}\\` code that spawns a subagent just to read or parse a\n file or list a directory. That is a deterministic step you do yourself with a\n direct tool call; spending a whole agent loop on it is wasteful.\n\n Once you understand the shape of the work, you have creative freedom in how\n you split it:\n\n - One dispatch per file or per record, when the items are already separate.\n - Chunk a large input yourself — read it, split it, optionally write a small\n input file per chunk — and dispatch one subagent per chunk.\n - A cheap classification pass first, then deeper dispatches only for the items\n that warrant them.\n\n Then write JavaScript in the \\`${toolName}\\` tool that distributes the heavy,\n agentic work to subagents with \\`task()\\`: analyzing file contents, exploring a\n codebase, making judgment calls, rewriting code, or synthesizing a report.\n\n Hand each subagent a locator, not a payload. Subagents have their own file\n tools, so for anything that lives in a file — a file to review, rewrite, or\n audit — pass the path and let the subagent read it. Do NOT read a whole file\n just to paste its contents into the description; that bloats every dispatch\n and duplicates the file across them. Reserve inline content for small or\n derived data that has no path of its own: a single parsed record, or a chunk\n you split out of a larger input (write the chunk to its own file and pass that\n path if it is large). Assemble the results in JS.\n\n #### Compose multiple stages\n\n Filter the array in JS between passes. For example: first ask subagents for a\n cheap classification, filter to the risky items, then dispatch deeper reviews\n only for those items.\n\n \\`\\`\\`javascript\n const tagged = await Promise.all(files.map((file) =>\n task({\n description: \"Read \" + file + \" and classify it as handler, util, \" +\n \"test, or config.\",\n subagentType: \"reviewer\",\n responseSchema: {\n type: \"object\",\n properties: { kind: { type: \"string\" }, risky: { type: \"boolean\" } },\n required: [\"kind\", \"risky\"],\n },\n }).then((tag) => ({ file, ...tag }))\n ));\n\n const riskyHandlers = tagged.filter((it) => it.kind === \"handler\" && it.risky);\n const deepReviews = await Promise.all(riskyHandlers.map((it) =>\n task({\n description: \"Deep security review of \" + it.file + \". Cite line numbers.\",\n subagentType: \"reviewer\",\n }).then((review) => ({ ...it, review }))\n ));\n \\`\\`\\`\n\n #### Return results via the last expression, not \\`console.log\\`\n\n The value of the last expression in an \\`${toolName}\\` call (or a resolved\n top-level \\`await\\`) is returned to you as the result. Make that final\n expression the variable holding your result and read it from there.\n \\`console.log\\` is only for incidental debugging: its output is capped and\n truncated, while the returned value is not, so never \\`console.log\\` your\n actual results.\n\n Keep large intermediate sets in JS variables and return only a compact\n summary or a small slice, not the entire dataset. To persist full output,\n have a subagent write it, or write it with your own file tool outside the\n \\`${toolName}\\` call.\n\n #### Reuse what earlier evals left in scope\n\n The REPL is persistent within a turn: every top-level variable, function, and\n class you declare is kept and is available in your next \\`${toolName}\\` call\n (each is hoisted to global scope). So if a later step needs something an\n earlier eval produced or bound, **reference that variable by name** — do not\n write a new literal that re-types data a previous eval already returned or\n computed.\n\n If you catch yourself pasting a big array or object of values you produced in\n an earlier call, that is the tell: the variable is still in scope, so use it.\n Re-typing prior results as a fresh literal wastes tokens and drifts from what\n actually ran.\n\n \\`\\`\\`javascript\n // An earlier eval bound this:\n // const auditResults = await Promise.all(files.map(/* ...audit... */));\n\n // A later eval — reference it; do NOT paste the findings back in as a literal:\n const findings = auditResults.flatMap((r) =>\n r.findings.map((f) => ({ ...f, file: r.file }))\n );\n const verified = await Promise.all(findings.map((f) =>\n task({ description: \"Verify this finding: \" + f.evidence, subagentType: \"verifier\" })\n .then((v) => ({ ...f, ...v }))\n ));\n \\`\\`\\`\n\n #### When the user asks for a \"workflow\"\n\n If the user's request mentions running a \"workflow\" (or otherwise uses the\n word \"workflow\"), fan the work out to subagents rather than doing it all\n yourself. Explore with your own tools first as needed, then write JavaScript\n in the \\`${toolName}\\` tool that dispatches subagents with \\`task()\\` and\n assembles their results. The point is to distribute the heavy work in\n parallel, not to grind through it one tool call at a time.\n `;\n}\n\nfunction renderReplSystemPrompt(opts: {\n toolName: string;\n timeout: number;\n memoryLimitMb: number;\n hasPtc: boolean;\n}): string {\n const sideEffects = opts.hasPtc\n ? \" External side effects from inside the REPL are reachable only via the `tools.*` namespace documented below.\"\n : \" The REPL is pure computation; do any filesystem or other I/O with your normal tools, outside this tool.\";\n return dedent`\n ### Interpreter\n\n An \\`${opts.toolName}\\` tool is available. It runs JavaScript in a persistent REPL.\n - State (variables, functions) persists across tool calls within a single turn of conversation. They DO NOT persist across multiple turns.\n - Top-level \\`await\\` works; Promises resolve before the call returns.\n - Runtime sandbox: no built-in filesystem, network, stdlib, or wall-clock APIs (\\`fetch\\`, \\`require\\`, \\`fs\\`, \\`process\\`, real \\`Date.now()\\` are unavailable or stubbed).${sideEffects}\n - Timeout: ${opts.timeout}s per call. Memory: ${opts.memoryLimitMb} MB total.\n - \\`console.log\\` output is captured and returned alongside the result.\n `;\n}\n\n/**\n * Generate the PTC API Reference section for the system prompt.\n */\nexport async function generatePtcPrompt(\n tools: StructuredToolInterface[],\n): Promise<string> {\n if (tools.length === 0) return \"\";\n\n const signatures = await Promise.all(\n tools.map((t) => {\n const jsonSchema = t.schema ? safeToJsonSchema(t.schema) : undefined;\n return toolToTypeSignature(\n toCamelCase(t.name),\n t.description,\n jsonSchema,\n );\n }),\n );\n\n return dedent`\n\n ### API Reference — \\`tools\\` namespace\n\n The following agent tools are callable as async functions inside the REPL.\n Each takes a single object argument and returns a Promise that resolves to a string.\n Use \\`await\\` to call them. Promise APIs like \\`Promise.all\\` are also available.\n\n **Example usage:**\n \\`\\`\\`javascript\n // Call a tool\n const result = await tools.searchWeb({ query: \"QuickJS tutorial\" });\n console.log(result);\n\n // Concurrent calls\n const [a, b] = await Promise.all([\n tools.fetchData({ url: \"https://api.example.com/a\" }),\n tools.fetchData({ url: \"https://api.example.com/b\" }),\n ]);\n \\`\\`\\`\n\n **Available functions:**\n \\`\\`\\`typescript\n ${signatures.join(\"\\n\\n\")}\n \\`\\`\\`\n `;\n}\n\n/**\n * Resolves a mixed list of tool names and tool instances into a flat list of\n * StructuredToolInterface objects. Strings are looked up by name in agentTools;\n * instances are included directly without requiring agent registration. Strings\n * that don't match any agent tool are silently omitted.\n *\n * Throws if the subagent `task` tool is requested (by name or instance): it is\n * reserved for the `task()` global and cannot be a `tools.*` PTC member.\n */\nexport function resolveToolList(\n items: (string | StructuredToolInterface)[],\n agentTools: StructuredToolInterface[],\n): StructuredToolInterface[] {\n const agentByName = new Map(agentTools.map((t) => [t.name, t]));\n return items.flatMap((item) => {\n const name = typeof item === \"string\" ? item : item.name;\n if (name === \"task\") {\n throw new Error(\n \"The subagent `task` tool cannot be exposed via `ptc`. It is always \" +\n \"available as the top-level `task()` global inside the REPL (with \" +\n \"`subagentType` and `responseSchema` support); exposing it through the \" +\n \"`tools.*` namespace would create a second, conflicting dispatch path \" +\n 'that drops `responseSchema`. Remove \"task\" from `ptc`.',\n );\n }\n if (typeof item === \"string\") {\n const found = agentByName.get(item);\n return found ? [found] : [];\n }\n return [item];\n });\n}\n\n/**\n * Create the Code Interpreter middleware.\n */\nexport function createCodeInterpreterMiddleware(\n options: CodeInterpreterMiddlewareOptions = {},\n) {\n const {\n ptc,\n memoryLimitBytes = DEFAULT_MEMORY_LIMIT,\n maxStackSizeBytes = DEFAULT_MAX_STACK_SIZE,\n executionTimeoutMs = DEFAULT_EXECUTION_TIMEOUT,\n systemPrompt: customSystemPrompt = null,\n maxPtcCalls = DEFAULT_MAX_PTC_CALLS,\n maxResultChars = DEFAULT_MAX_RESULTS_CHARS,\n toolName = DEFAULT_TOOL_NAME,\n captureConsole = true,\n subagents = true,\n } = options;\n\n const maxSubagentConcurrency = subagents\n ? DEFAULT_MAX_SUBAGENT_CONCURRENCY\n : 0;\n\n if (maxPtcCalls !== null && maxPtcCalls !== undefined && maxPtcCalls < 1) {\n throw new Error(\"`maxPtcCalls` must be >= 1 or null\");\n }\n\n const middlewareId = crypto.randomUUID();\n\n let cachedPtcPrompt: string | null = null;\n let ptcTools: StructuredToolInterface[] = [];\n let taskTool: StructuredToolInterface | null = null;\n\n function filterToolsForPtc(\n allTools: StructuredToolInterface[],\n ): StructuredToolInterface[] {\n if (!ptc) return [];\n\n const candidates = allTools.filter((t) => t.name !== toolName);\n\n return resolveToolList(ptc, candidates);\n }\n\n function findTaskTool(\n tools: StructuredToolInterface[],\n ): StructuredToolInterface | null {\n return tools.find((t) => t.name === \"task\") ?? null;\n }\n\n function createBridgeDispatch(\n subagentTaskTool: StructuredToolInterface,\n config: LangGraphRunnableConfig,\n ): SubagentBridgeOptions[\"dispatch\"] {\n return async (input) => {\n const hasSchema = input.responseSchema != null;\n if (hasSchema) {\n validateResponseSchema(input.responseSchema!);\n }\n\n const toolConfig = {\n ...config,\n configurable: {\n ...config.configurable,\n ...(hasSchema && {\n [SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY]: input.responseSchema,\n }),\n },\n };\n\n const result = await subagentTaskTool.invoke(\n {\n description: input.description,\n subagent_type: input.subagentType,\n },\n toolConfig,\n );\n\n // The task tool resolves to a Command envelope; unwrap it to the\n // subagent's actual output before handing it back to the REPL.\n const content = unwrapToolEnvelope(result);\n\n if (hasSchema && typeof content === \"string\") {\n try {\n return JSON.parse(content);\n } catch {\n return content;\n }\n }\n return content;\n };\n }\n\n const evalTool = tool(\n async (input, config: LangGraphRunnableConfig) => {\n const threadId = config.configurable?.thread_id || DEFAULT_SESSION_ID;\n const sessionKey = `${threadId}:${middlewareId}`;\n\n const session = ReplSession.getOrCreate(sessionKey, {\n memoryLimitBytes,\n maxStackSizeBytes,\n maxPtcCalls,\n tools: ptcTools,\n maxResultChars,\n captureConsole,\n sessionId: threadId,\n subagentBridge:\n taskTool && maxSubagentConcurrency > 0\n ? {\n dispatch: createBridgeDispatch(taskTool, config),\n maxConcurrency: maxSubagentConcurrency,\n }\n : undefined,\n });\n\n if (taskTool && maxSubagentConcurrency > 0) {\n session.updateBridgeDispatch(createBridgeDispatch(taskTool, config));\n }\n\n const result = await session.eval(input.code, executionTimeoutMs);\n return formatReplResult(result);\n },\n {\n name: toolName,\n description: dedent`\n Evaluate TypeScript/JavaScript code in a sandboxed REPL. State persists across calls.\n Use console.log() for output. Returns the result of the last expression.\n If file or other tools are available, call them via the tools namespace: await tools.readFile({ path }).\n `,\n metadata: { ls_code_input_language: \"javascript\" },\n schema: z.object({\n code: z\n .string()\n .describe(\n \"TypeScript/JavaScript code to evaluate in the sandboxed REPL\",\n ),\n }),\n },\n );\n\n return createMiddleware({\n name: \"CodeInterpreterMiddleware\",\n tools: [evalTool],\n wrapModelCall: async (request, handler) => {\n const agentTools = (request.tools || []) as StructuredToolInterface[];\n ptcTools = filterToolsForPtc(agentTools);\n\n if (!taskTool && maxSubagentConcurrency > 0) {\n taskTool = findTaskTool(agentTools);\n }\n\n if (ptcTools.length > 0 && !cachedPtcPrompt) {\n cachedPtcPrompt = await generatePtcPrompt(ptcTools);\n }\n\n const baseSystemPrompt =\n customSystemPrompt ||\n renderReplSystemPrompt({\n toolName,\n timeout: executionTimeoutMs / 1000,\n memoryLimitMb: Math.floor(memoryLimitBytes / (1024 * 1024)),\n hasPtc: ptcTools.length > 0,\n });\n\n const subagentPrompt =\n taskTool && maxSubagentConcurrency > 0\n ? renderSubagentPrompt(toolName)\n : \"\";\n\n const systemMessage = request.systemMessage\n .concat(baseSystemPrompt)\n .concat(subagentPrompt)\n .concat(cachedPtcPrompt || \"\");\n return handler({ ...request, systemMessage });\n },\n afterAgent: async (_state, runtime) => {\n const threadId = runtime.configurable?.thread_id ?? DEFAULT_SESSION_ID;\n const sessionKey = `${threadId}:${middlewareId}`;\n ReplSession.deleteSession(sessionKey);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuBA,IAAa,6BAAb,cAAgD,MAAM;CACpD;CACA;CACA;CAEA,YAAY,SAAuC;EACjD,MACE,mCAAmC,QAAQ,MAAM,cAAc,QAAQ,UAAU,aAAa,QAAQ,aAAa,EACrH;EACA,KAAK,OAAO;EACZ,KAAK,QAAQ,QAAQ;EACrB,KAAK,YAAY,QAAQ;EACzB,KAAK,eAAe,QAAQ;CAC9B;AACF;;;;;;AC7BA,SAAgB,YAAY,MAAsB;CAChD,OAAO,KAAK,QAAQ,iBAAiB,GAAG,MAAM,EAAE,YAAY,CAAC;AAC/D;;;;AAuBA,SAAgB,iBAAiB,QAA4B;CAC3D,MAAM,QAAkB,CAAC;CAEzB,IAAI,OAAO,KAAK,SAAS,GAAG;EAC1B,IAAI,WAAW,OAAO,KAAK,KAAK,IAAI;EACpC,IAAI,OAAO,mBAAmB,GAC5B,YAAY,gBAAgB,OAAO,iBAAiB;EAEtD,MAAM,KAAK,QAAQ;CACrB;CAEA,IAAI,OAAO,IACL;MAAA,OAAO,UAAU,KAAA,GAAW;GAC9B,MAAM,YACJ,OAAO,OAAO,UAAU,WACpB,OAAO,QACP,KAAK,UAAU,OAAO,OAAO,MAAM,CAAC;GAC1C,MAAM,KAAK,KAAK,WAAW;EAC7B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AY,yBAAyB,IACjC,qBAAqB,QAAQ,IAC7B;GAEN,MAAM,gBAAgB,QAAQ,cAC3B,OAAO,gBAAgB,CAAC,CACxB,OAAO,cAAc,CAAC,CACtB,OAAO,mBAAmB,EAAE;GAC/B,OAAO,QAAQ;IAAE,GAAG;IAAS;GAAc,CAAC;EAC9C;EACA,YAAY,OAAO,QAAQ,YAAY;GAErC,MAAM,aAAa,GADF,QAAQ,cAAc,aAAA,cACR,GAAG;GAClC,YAAY,cAAc,UAAU;EACtC;CACF,CAAC;AACH"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@langchain/quickjs",
|
|
3
|
-
"version": "0.6.3
|
|
3
|
+
"version": "0.6.3",
|
|
4
4
|
"description": "Sandboxed JavaScript REPL for deepagents using QuickJS (WASM)",
|
|
5
5
|
"main": "./dist/index.cjs",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -40,25 +40,24 @@
|
|
|
40
40
|
"quickjs-emscripten-core": "^0.32.0"
|
|
41
41
|
},
|
|
42
42
|
"peerDependencies": {
|
|
43
|
-
"deepagents": ">=1.13.4-rc.0"
|
|
44
|
-
"langchain": "^1.5.11-rc.0"
|
|
43
|
+
"deepagents": ">=1.13.4-rc.0"
|
|
45
44
|
},
|
|
46
45
|
"devDependencies": {
|
|
47
46
|
"@langchain/core": "^1.2.9",
|
|
48
|
-
"@langchain/langgraph": "^1.4.
|
|
47
|
+
"@langchain/langgraph": "^1.4.10",
|
|
49
48
|
"@tsconfig/recommended": "^1.0.13",
|
|
50
49
|
"@types/dedent": "^0.7.2",
|
|
51
50
|
"@types/estree": "^1.0.8",
|
|
52
51
|
"@types/node": "^26.1.0",
|
|
53
52
|
"@vitest/coverage-v8": "^4.0.18",
|
|
54
53
|
"dotenv": "^17.2.3",
|
|
55
|
-
"langchain": "^1.5.
|
|
54
|
+
"langchain": "^1.5.10",
|
|
56
55
|
"tsdown": "^0.22.1",
|
|
57
56
|
"tsx": "^4.21.0",
|
|
58
57
|
"typescript": "^7.0.2",
|
|
59
58
|
"vitest": "^4.0.18",
|
|
60
59
|
"zod": "^4.3.6",
|
|
61
|
-
"deepagents": "1.13.4
|
|
60
|
+
"deepagents": "1.13.4"
|
|
62
61
|
},
|
|
63
62
|
"exports": {
|
|
64
63
|
".": {
|