MCPcopy Create free account
hub / github.com/TanStack/ai / createContext

Function createContext

packages/ai-isolate-quickjs/src/isolate-driver.ts:80–183  ·  view source on GitHub ↗
(isolateConfig: IsolateConfig)

Source from the content-addressed store, hash-verified

78
79 return {
80 async createContext(isolateConfig: IsolateConfig): Promise<IsolateContext> {
81 const timeout = isolateConfig.timeout ?? defaultTimeout
82 const memoryLimitMb = isolateConfig.memoryLimit ?? defaultMemoryLimit
83 const maxStackSizeBytes = defaultMaxStackSize
84
85 // Create async QuickJS context (supports async host functions)
86 const vm = await newAsyncContext()
87
88 // Enforce heap and stack limits so OOM/stack overflow surface as JS errors
89 // instead of growing WASM memory until the host process OOMs.
90 vm.runtime.setMemoryLimit(memoryLimitMb * 1024 * 1024)
91 vm.runtime.setMaxStackSize(maxStackSizeBytes)
92
93 // Set up console.log capture
94 const logs: Array<string> = []
95
96 // Create console object
97 const consoleObj = vm.newObject()
98
99 // Helper to create console methods
100 const createConsoleMethod = (prefix: string) => {
101 return vm.newFunction(`console.${prefix}`, (...args) => {
102 const parts = args.map((arg) => {
103 const str = vm.getString(arg)
104 return str
105 })
106 const msg = prefix ? `${prefix}: ${parts.join(' ')}` : parts.join(' ')
107 logs.push(msg)
108 })
109 }
110
111 const logFn = createConsoleMethod('')
112 const errorFn = createConsoleMethod('ERROR')
113 const warnFn = createConsoleMethod('WARN')
114 const infoFn = createConsoleMethod('INFO')
115
116 vm.setProp(consoleObj, 'log', logFn)
117 vm.setProp(consoleObj, 'error', errorFn)
118 vm.setProp(consoleObj, 'warn', warnFn)
119 vm.setProp(consoleObj, 'info', infoFn)
120 vm.setProp(vm.global, 'console', consoleObj)
121
122 // Dispose console handles
123 logFn.dispose()
124 errorFn.dispose()
125 warnFn.dispose()
126 infoFn.dispose()
127 consoleObj.dispose()
128
129 // Inject each tool binding as an async function
130 for (const [name, binding] of Object.entries(isolateConfig.bindings)) {
131 // Create async function that calls back to host
132 // newAsyncifiedFunction receives QuickJS handles as arguments
133 const toolFn = vm.newAsyncifiedFunction(name, async (argsHandle) => {
134 try {
135 // Get the input argument - argsHandle is a QuickJS handle
136 const argsJson = vm.getString(argsHandle)
137 const args = JSON.parse(argsJson)

Callers

nothing calls this directly

Calls 4

createConsoleMethodFunction · 0.85
parseMethod · 0.80
disposeMethod · 0.45
executeMethod · 0.45

Tested by

no test coverage detected