interpreter.ts
1 // Copyright 2026 Alibaba Group Holding Ltd. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 import { DEFAULT_EXECD_PORT } from "@alibaba-group/opensandbox"; 16 import type { Sandbox } from "@alibaba-group/opensandbox"; 17 18 import { createDefaultAdapterFactory } from "./factory/defaultAdapterFactory.js"; 19 import type { AdapterFactory } from "./factory/adapterFactory.js"; 20 import type { Codes } from "./services/codes.js"; 21 22 export interface CodeInterpreterCreateOptions { 23 adapterFactory?: AdapterFactory; 24 } 25 26 /** 27 * Code interpreter facade (JS/TS). 28 * 29 * This class wraps an existing {@link Sandbox} and provides a high-level API for code execution. 30 * 31 * - Use {@link codes} to create contexts and run code. 32 * - {@link files}, {@link commands}, and {@link metrics} are exposed for convenience and are 33 * the same instances as on the underlying {@link Sandbox}. 34 */ 35 export class CodeInterpreter { 36 private constructor( 37 readonly sandbox: Sandbox, 38 readonly codes: Codes, 39 ) {} 40 41 static async create(sandbox: Sandbox, opts: CodeInterpreterCreateOptions = {}): Promise<CodeInterpreter> { 42 const endpoint = await sandbox.getEndpoint(DEFAULT_EXECD_PORT); 43 const execdBaseUrl = `${sandbox.connectionConfig.protocol}://${endpoint.endpoint}`; 44 const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory(); 45 const codes = adapterFactory.createCodes({ 46 sandbox, 47 execdBaseUrl, 48 endpointHeaders: endpoint.headers, 49 }); 50 51 return new CodeInterpreter(sandbox, codes); 52 } 53 54 get id() { 55 return this.sandbox.id; 56 } 57 58 get files() { 59 return this.sandbox.files; 60 } 61 62 get commands() { 63 return this.sandbox.commands; 64 } 65 66 get metrics() { 67 return this.sandbox.metrics; 68 } 69 }