(isolateConfig: IsolateConfig)
| 136 | |
| 137 | return { |
| 138 | async createContext(isolateConfig: IsolateConfig): Promise<IsolateContext> { |
| 139 | const memoryLimit = isolateConfig.memoryLimit ?? defaultMemoryLimit |
| 140 | const timeout = isolateConfig.timeout ?? defaultTimeout |
| 141 | |
| 142 | // Create isolate with memory limit |
| 143 | const isolate = new ivm.Isolate({ memoryLimit }) |
| 144 | |
| 145 | // Create context |
| 146 | const context = await isolate.createContext() |
| 147 | |
| 148 | // Get reference to global object |
| 149 | const jail = context.global |
| 150 | |
| 151 | // Set up global reference |
| 152 | await jail.set('global', jail.derefInto()) |
| 153 | |
| 154 | // Set up console.log capture |
| 155 | const logs: Array<string> = [] |
| 156 | await jail.set( |
| 157 | '__captureLog', |
| 158 | new ivm.Reference((msg: string) => { |
| 159 | logs.push(msg) |
| 160 | }), |
| 161 | ) |
| 162 | |
| 163 | // Inject console object |
| 164 | await context.eval(` |
| 165 | const console = { |
| 166 | log: (...args) => { |
| 167 | const msg = args.map(a => |
| 168 | typeof a === 'object' ? JSON.stringify(a) : String(a) |
| 169 | ).join(' '); |
| 170 | __captureLog.applySync(undefined, [msg]); |
| 171 | }, |
| 172 | error: (...args) => { |
| 173 | const msg = 'ERROR: ' + args.map(a => |
| 174 | typeof a === 'object' ? JSON.stringify(a) : String(a) |
| 175 | ).join(' '); |
| 176 | __captureLog.applySync(undefined, [msg]); |
| 177 | }, |
| 178 | warn: (...args) => { |
| 179 | const msg = 'WARN: ' + args.map(a => |
| 180 | typeof a === 'object' ? JSON.stringify(a) : String(a) |
| 181 | ).join(' '); |
| 182 | __captureLog.applySync(undefined, [msg]); |
| 183 | }, |
| 184 | info: (...args) => { |
| 185 | const msg = 'INFO: ' + args.map(a => |
| 186 | typeof a === 'object' ? JSON.stringify(a) : String(a) |
| 187 | ).join(' '); |
| 188 | __captureLog.applySync(undefined, [msg]); |
| 189 | }, |
| 190 | }; |
| 191 | `) |
| 192 | |
| 193 | // Inject each tool binding |
| 194 | for (const [name, binding] of Object.entries(isolateConfig.bindings)) { |
| 195 | // Create an async Reference that executes the tool |
no test coverage detected