@alibaba-group/opensandbox-code-interpreter 0.1.3-dev1 → 0.1.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/README.md +2 -2
- package/dist/cjs/index.cjs +13 -4
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
- package/src/factory/adapterFactory.ts +2 -1
- package/src/factory/defaultAdapterFactory.ts +7 -3
- package/src/interpreter.ts +8 -3
package/README.md
CHANGED
|
@@ -49,7 +49,7 @@ const config = new ConnectionConfig({
|
|
|
49
49
|
// 2. Create a Sandbox with the code-interpreter image + runtime versions
|
|
50
50
|
const sandbox = await Sandbox.create({
|
|
51
51
|
connectionConfig: config,
|
|
52
|
-
image: "opensandbox/code-interpreter:v1.0.
|
|
52
|
+
image: "opensandbox/code-interpreter:v1.0.2",
|
|
53
53
|
entrypoint: ["/opt/opensandbox/code-interpreter.sh"],
|
|
54
54
|
env: {
|
|
55
55
|
PYTHON_VERSION: "3.11",
|
|
@@ -99,7 +99,7 @@ You can specify the desired version of a programming language by setting the cor
|
|
|
99
99
|
```ts
|
|
100
100
|
const sandbox = await Sandbox.create({
|
|
101
101
|
connectionConfig: config,
|
|
102
|
-
image: "opensandbox/code-interpreter:v1.0.
|
|
102
|
+
image: "opensandbox/code-interpreter:v1.0.2",
|
|
103
103
|
entrypoint: ["/opt/opensandbox/code-interpreter.sh"],
|
|
104
104
|
env: {
|
|
105
105
|
JAVA_VERSION: "17",
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -232,14 +232,18 @@ var CodesAdapter = class {
|
|
|
232
232
|
// src/factory/defaultAdapterFactory.ts
|
|
233
233
|
var DefaultAdapterFactory = class {
|
|
234
234
|
createCodes(opts) {
|
|
235
|
+
const headers = {
|
|
236
|
+
...opts.sandbox.connectionConfig.headers ?? {},
|
|
237
|
+
...opts.endpointHeaders ?? {}
|
|
238
|
+
};
|
|
235
239
|
const client = (0, import_internal.createExecdClient)({
|
|
236
240
|
baseUrl: opts.execdBaseUrl,
|
|
237
|
-
headers
|
|
241
|
+
headers,
|
|
238
242
|
fetch: opts.sandbox.connectionConfig.fetch
|
|
239
243
|
});
|
|
240
244
|
return new CodesAdapter(client, {
|
|
241
245
|
baseUrl: opts.execdBaseUrl,
|
|
242
|
-
headers
|
|
246
|
+
headers,
|
|
243
247
|
// Streaming calls (SSE) use a dedicated fetch, aligned with Kotlin/Python SDKs.
|
|
244
248
|
fetch: opts.sandbox.connectionConfig.sseFetch
|
|
245
249
|
});
|
|
@@ -256,9 +260,14 @@ var CodeInterpreter = class _CodeInterpreter {
|
|
|
256
260
|
this.codes = codes;
|
|
257
261
|
}
|
|
258
262
|
static async create(sandbox, opts = {}) {
|
|
259
|
-
const
|
|
263
|
+
const endpoint = await sandbox.getEndpoint(import_opensandbox4.DEFAULT_EXECD_PORT);
|
|
264
|
+
const execdBaseUrl = `${sandbox.connectionConfig.protocol}://${endpoint.endpoint}`;
|
|
260
265
|
const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();
|
|
261
|
-
const codes = adapterFactory.createCodes({
|
|
266
|
+
const codes = adapterFactory.createCodes({
|
|
267
|
+
sandbox,
|
|
268
|
+
execdBaseUrl,
|
|
269
|
+
endpointHeaders: endpoint.headers
|
|
270
|
+
});
|
|
262
271
|
return new _CodeInterpreter(sandbox, codes);
|
|
263
272
|
}
|
|
264
273
|
get id() {
|
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts","../../src/interpreter.ts","../../src/factory/defaultAdapterFactory.ts","../../src/adapters/codesAdapter.ts","../../src/adapters/openapiError.ts","../../src/adapters/sse.ts","../../src/models.ts"],"sourcesContent":["// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport { CodeInterpreter } from \"./interpreter.js\";\nexport type { CodeInterpreterCreateOptions } from \"./interpreter.js\";\n\nexport type { AdapterFactory } from \"./factory/adapterFactory.js\";\nexport { DefaultAdapterFactory, createDefaultAdapterFactory } from \"./factory/defaultAdapterFactory.js\";\n\nexport type { CodeContext, SupportedLanguage } from \"./models.js\";\nexport { SupportedLanguage as SupportedLanguages } from \"./models.js\";\n\nexport type { Codes } from \"./services/codes.js\";\n\nexport type {\n Execution,\n ExecutionComplete,\n ExecutionError,\n ExecutionHandlers,\n ExecutionInit,\n ExecutionResult,\n OutputMessage,\n} from \"@alibaba-group/opensandbox\";","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { DEFAULT_EXECD_PORT } from \"@alibaba-group/opensandbox\";\nimport type { Sandbox } from \"@alibaba-group/opensandbox\";\n\nimport { createDefaultAdapterFactory } from \"./factory/defaultAdapterFactory.js\";\nimport type { AdapterFactory } from \"./factory/adapterFactory.js\";\nimport type { Codes } from \"./services/codes.js\";\n\nexport interface CodeInterpreterCreateOptions {\n adapterFactory?: AdapterFactory;\n}\n\n/**\n * Code interpreter facade (JS/TS).\n *\n * This class wraps an existing {@link Sandbox} and provides a high-level API for code execution.\n *\n * - Use {@link codes} to create contexts and run code.\n * - {@link files}, {@link commands}, and {@link metrics} are exposed for convenience and are\n * the same instances as on the underlying {@link Sandbox}.\n */\nexport class CodeInterpreter {\n private constructor(\n readonly sandbox: Sandbox,\n readonly codes: Codes,\n ) {}\n\n static async create(sandbox: Sandbox, opts: CodeInterpreterCreateOptions = {}): Promise<CodeInterpreter> {\n const execdBaseUrl = await sandbox.getEndpointUrl(DEFAULT_EXECD_PORT);\n const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();\n const codes = adapterFactory.createCodes({ sandbox, execdBaseUrl });\n\n return new CodeInterpreter(sandbox, codes);\n }\n\n get id() {\n return this.sandbox.id;\n }\n\n get files() {\n return this.sandbox.files;\n }\n\n get commands() {\n return this.sandbox.commands;\n }\n\n get metrics() {\n return this.sandbox.metrics;\n }\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { createExecdClient } from \"@alibaba-group/opensandbox/internal\";\nimport type { AdapterFactory, CreateCodesStackOptions } from \"./adapterFactory.js\";\nimport { CodesAdapter } from \"../adapters/codesAdapter.js\";\nimport type { Codes } from \"../services/codes.js\";\n\nexport class DefaultAdapterFactory implements AdapterFactory {\n createCodes(opts: CreateCodesStackOptions): Codes {\n const client = createExecdClient({\n baseUrl: opts.execdBaseUrl,\n headers: opts.sandbox.connectionConfig.headers,\n fetch: opts.sandbox.connectionConfig.fetch,\n });\n\n return new CodesAdapter(client, {\n baseUrl: opts.execdBaseUrl,\n headers: opts.sandbox.connectionConfig.headers,\n // Streaming calls (SSE) use a dedicated fetch, aligned with Kotlin/Python SDKs.\n fetch: opts.sandbox.connectionConfig.sseFetch,\n });\n }\n}\n\nexport function createDefaultAdapterFactory(): AdapterFactory {\n return new DefaultAdapterFactory();\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { ExecdClient, ExecdPaths } from \"@alibaba-group/opensandbox/internal\";\nimport type { ServerStreamEvent } from \"@alibaba-group/opensandbox\";\nimport type { Execution, ExecutionHandlers } from \"@alibaba-group/opensandbox\";\nimport {\n ExecutionEventDispatcher,\n InvalidArgumentException,\n} from \"@alibaba-group/opensandbox\";\n\nimport type { Codes } from \"../services/codes.js\";\nimport type { CodeContext, SupportedLanguage } from \"../models.js\";\nimport { throwOnOpenApiFetchError } from \"./openapiError.js\";\nimport { parseJsonEventStream } from \"./sse.js\";\n\ntype ApiCreateContextRequest =\n ExecdPaths[\"/code/context\"][\"post\"][\"requestBody\"][\"content\"][\"application/json\"];\ntype ApiCreateContextOk =\n ExecdPaths[\"/code/context\"][\"post\"][\"responses\"][200][\"content\"][\"application/json\"];\ntype ApiGetContextOk =\n ExecdPaths[\"/code/contexts/{context_id}\"][\"get\"][\"responses\"][200][\"content\"][\"application/json\"];\ntype ApiListContextsOk =\n ExecdPaths[\"/code/contexts\"][\"get\"][\"responses\"][200][\"content\"][\"application/json\"];\ntype ApiRunCodeRequest =\n ExecdPaths[\"/code\"][\"post\"][\"requestBody\"][\"content\"][\"application/json\"];\n\n/**\n * Single-layer codes adapter for the Code Interpreter SDK.\n *\n * - Handles HTTP/SSE streaming via the underlying execd adapter\n * - Builds the structured {@link Execution} result for `run(...)`\n */\nfunction joinUrl(baseUrl: string, pathname: string): string {\n const base = baseUrl.endsWith(\"/\") ? baseUrl.slice(0, -1) : baseUrl;\n const path = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n return `${base}${path}`;\n}\n\nexport class CodesAdapter implements Codes {\n private readonly fetch: typeof fetch;\n\n constructor(\n private readonly client: ExecdClient,\n private readonly opts: { baseUrl: string; fetch?: typeof fetch; headers?: Record<string, string> },\n ) {\n this.fetch = opts.fetch ?? fetch;\n }\n\n async createContext(language: SupportedLanguage): Promise<CodeContext> {\n const body: ApiCreateContextRequest = { language };\n const { data, error, response } = await this.client.POST(\"/code/context\", {\n body,\n });\n throwOnOpenApiFetchError({ error, response }, \"Create code context failed\");\n const ok = data as ApiCreateContextOk | undefined;\n if (!ok || typeof ok !== \"object\") {\n throw new Error(\"Create code context failed: unexpected response shape\");\n }\n if (typeof ok.language !== \"string\" || !ok.language) {\n throw new Error(\"Create code context failed: missing language\");\n }\n return { id: ok.id, language: ok.language };\n }\n\n async getContext(contextId: string): Promise<CodeContext> {\n if (!contextId?.trim()) {\n throw new InvalidArgumentException({ message: \"contextId cannot be empty\" });\n }\n const { data, error, response } = await this.client.GET(\"/code/contexts/{context_id}\", {\n params: { path: { context_id: contextId } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Get code context failed\");\n const ok = data as ApiGetContextOk | undefined;\n if (!ok || typeof ok !== \"object\") {\n throw new Error(\"Get code context failed: unexpected response shape\");\n }\n if (typeof (ok as any).language !== \"string\" || !(ok as any).language) {\n throw new Error(\"Get code context failed: missing language\");\n }\n return { id: (ok as any).id, language: (ok as any).language };\n }\n\n async listContexts(language?: SupportedLanguage): Promise<CodeContext[]> {\n const { data, error, response } = await this.client.GET(\"/code/contexts\", {\n params: language ? { query: { language } } : undefined,\n } as any);\n throwOnOpenApiFetchError({ error, response }, \"List code contexts failed\");\n const ok = data as ApiListContextsOk | undefined;\n if (!Array.isArray(ok)) {\n throw new Error(\"List code contexts failed: unexpected response shape\");\n }\n return ok\n .filter((c) => c && typeof c === \"object\")\n .map((c: any) => ({ id: c.id, language: c.language as any }));\n }\n\n async deleteContext(contextId: string): Promise<void> {\n if (!contextId?.trim()) {\n throw new InvalidArgumentException({ message: \"contextId cannot be empty\" });\n }\n const { error, response } = await this.client.DELETE(\"/code/contexts/{context_id}\", {\n params: { path: { context_id: contextId } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Delete code context failed\");\n }\n\n async deleteContexts(language: SupportedLanguage): Promise<void> {\n const { error, response } = await this.client.DELETE(\"/code/contexts\", {\n params: { query: { language } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Delete code contexts failed\");\n }\n\n async interrupt(contextId: string): Promise<void> {\n const { error, response } = await this.client.DELETE(\"/code\", {\n params: { query: { id: contextId } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Interrupt code failed\");\n }\n\n async *runStream(req: ApiRunCodeRequest, signal?: AbortSignal): AsyncIterable<ServerStreamEvent> {\n const url = joinUrl(this.opts.baseUrl, \"/code\");\n const body = JSON.stringify(req);\n const res = await this.fetch(url, {\n method: \"POST\",\n headers: {\n \"accept\": \"text/event-stream\",\n \"content-type\": \"application/json\",\n ...(this.opts.headers ?? {}),\n },\n body,\n signal,\n });\n\n for await (const ev of parseJsonEventStream<ServerStreamEvent>(res, { fallbackErrorMessage: \"Run code failed\" })) {\n yield ev;\n }\n }\n\n async run(\n code: string,\n opts: { context?: CodeContext; language?: SupportedLanguage; handlers?: ExecutionHandlers; signal?: AbortSignal } = {},\n ): Promise<Execution> {\n if (!code.trim()) {\n throw new InvalidArgumentException({ message: \"Code cannot be empty\" });\n }\n\n if (opts.context && opts.language) {\n throw new InvalidArgumentException({ message: \"Provide either opts.context or opts.language, not both\" });\n }\n\n const context: CodeContext =\n opts.context ??\n (opts.language\n ? { language: opts.language }\n : { language: \"python\" });\n\n // Make the OpenAPI contract explicit so backend schema changes surface quickly.\n const req: ApiRunCodeRequest = {\n code,\n context: { id: context.id, language: context.language },\n };\n\n const execution: Execution = {\n logs: { stdout: [], stderr: [] },\n result: [],\n };\n const dispatcher = new ExecutionEventDispatcher(execution, opts.handlers);\n\n for await (const ev of this.runStream(req, opts.signal)) {\n await dispatcher.dispatch(ev as any);\n }\n\n return execution;\n }\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { SandboxApiException, SandboxError } from \"@alibaba-group/opensandbox\";\n\nexport function throwOnOpenApiFetchError(\n result: { error?: unknown; response: Response },\n fallbackMessage: string,\n): void {\n if (!result.error) return;\n\n const requestId = result.response.headers.get(\"x-request-id\") ?? undefined;\n const status = (result.response as any).status ?? 0;\n\n const err = result.error as any;\n const message =\n err?.message ??\n err?.error?.message ??\n fallbackMessage;\n\n const code = err?.code ?? err?.error?.code;\n const msg = err?.message ?? err?.error?.message ?? message;\n\n throw new SandboxApiException({\n message: msg,\n statusCode: status,\n requestId,\n error: code\n ? new SandboxError(String(code), String(msg ?? \"\"))\n : new SandboxError(SandboxError.UNEXPECTED_RESPONSE, String(msg ?? \"\")),\n rawBody: result.error,\n });\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { SandboxApiException, SandboxError } from \"@alibaba-group/opensandbox\";\n\nfunction tryParseJson(line: string): unknown | undefined {\n try {\n return JSON.parse(line);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Parses an SSE-like stream that may be either:\n * - standard SSE frames (`data: {...}\\n\\n`)\n * - newline-delimited JSON (one JSON object per line)\n */\nexport async function* parseJsonEventStream<T>(\n res: Response,\n opts?: { fallbackErrorMessage?: string },\n): AsyncIterable<T> {\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n const parsed = tryParseJson(text);\n const err = parsed && typeof parsed === \"object\" ? (parsed as any) : undefined;\n const requestId = res.headers.get(\"x-request-id\") ?? undefined;\n const message = err?.message ?? opts?.fallbackErrorMessage ?? `Stream request failed (status=${res.status})`;\n const code = err?.code ? String(err.code) : SandboxError.UNEXPECTED_RESPONSE;\n throw new SandboxApiException({\n message,\n statusCode: res.status,\n requestId,\n error: new SandboxError(code, err?.message ? String(err.message) : message),\n rawBody: parsed ?? text,\n });\n }\n\n if (!res.body) return;\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder(\"utf-8\");\n let buf = \"\";\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n\n buf += decoder.decode(value, { stream: true });\n let idx: number;\n\n while ((idx = buf.indexOf(\"\\n\")) >= 0) {\n const rawLine = buf.slice(0, idx);\n buf = buf.slice(idx + 1);\n\n const line = rawLine.trim();\n if (!line) continue;\n\n // Support standard SSE \"data:\" prefix\n if (line.startsWith(\":\")) continue;\n if (line.startsWith(\"event:\") || line.startsWith(\"id:\") || line.startsWith(\"retry:\")) continue;\n\n const jsonLine = line.startsWith(\"data:\") ? line.slice(\"data:\".length).trim() : line;\n if (!jsonLine) continue;\n\n const parsed = tryParseJson(jsonLine);\n if (!parsed) continue;\n yield parsed as T;\n }\n }\n\n // flush last line if exists\n const last = buf.trim();\n if (last) {\n const jsonLine = last.startsWith(\"data:\") ? last.slice(\"data:\".length).trim() : last;\n const parsed = tryParseJson(jsonLine);\n if (parsed) yield parsed as T;\n }\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport const SupportedLanguage = {\n PYTHON: \"python\",\n JAVA: \"java\",\n GO: \"go\",\n TYPESCRIPT: \"typescript\",\n JAVASCRIPT: \"javascript\",\n BASH: \"bash\",\n} as const;\n\nexport type SupportedLanguage =\n (typeof SupportedLanguage)[keyof typeof SupportedLanguage];\n\nexport interface CodeContext {\n id?: string;\n language: SupportedLanguage | (string & {});\n}\n\nexport interface RunCodeRequest {\n code: string;\n context: CodeContext;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACcA,IAAAA,sBAAmC;;;ACAnC,sBAAkC;;;ACGlC,IAAAC,sBAGO;;;ACNP,yBAAkD;AAE3C,SAAS,yBACd,QACA,iBACM;AACN,MAAI,CAAC,OAAO,MAAO;AAEnB,QAAM,YAAY,OAAO,SAAS,QAAQ,IAAI,cAAc,KAAK;AACjE,QAAM,SAAU,OAAO,SAAiB,UAAU;AAElD,QAAM,MAAM,OAAO;AACnB,QAAM,UACJ,KAAK,WACL,KAAK,OAAO,WACZ;AAEF,QAAM,OAAO,KAAK,QAAQ,KAAK,OAAO;AACtC,QAAM,MAAM,KAAK,WAAW,KAAK,OAAO,WAAW;AAEnD,QAAM,IAAI,uCAAoB;AAAA,IAC5B,SAAS;AAAA,IACT,YAAY;AAAA,IACZ;AAAA,IACA,OAAO,OACH,IAAI,gCAAa,OAAO,IAAI,GAAG,OAAO,OAAO,EAAE,CAAC,IAChD,IAAI,gCAAa,gCAAa,qBAAqB,OAAO,OAAO,EAAE,CAAC;AAAA,IACxE,SAAS,OAAO;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AAO,SAAkB,OAAqC,CAAC,GAA6B;AACvG,UAAM,eAAe,MAAM,QAAQ,eAAe,sCAAkB;AACpE,UAAM,iBAAiB,KAAK,kBAAkB,4BAA4B;AAC1E,UAAM,QAAQ,eAAe,YAAY,EAAE,SAAS,aAAa,CAAC;AAElE,WAAO,IAAI,iBAAgB,SAAS,KAAK;AAAA,EAC3C;AAAA,EAEA,IAAI,KAAK;AACP,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,QAAQ;AACV,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,WAAW;AACb,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,UAAU;AACZ,WAAO,KAAK,QAAQ;AAAA,EACtB;AACF;;;AKjDO,IAAM,oBAAoB;AAAA,EAC/B,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,IAAI;AAAA,EACJ,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,MAAM;AACR;","names":["import_opensandbox","import_opensandbox","import_opensandbox"]}
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts","../../src/interpreter.ts","../../src/factory/defaultAdapterFactory.ts","../../src/adapters/codesAdapter.ts","../../src/adapters/openapiError.ts","../../src/adapters/sse.ts","../../src/models.ts"],"sourcesContent":["// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport { CodeInterpreter } from \"./interpreter.js\";\nexport type { CodeInterpreterCreateOptions } from \"./interpreter.js\";\n\nexport type { AdapterFactory } from \"./factory/adapterFactory.js\";\nexport { DefaultAdapterFactory, createDefaultAdapterFactory } from \"./factory/defaultAdapterFactory.js\";\n\nexport type { CodeContext, SupportedLanguage } from \"./models.js\";\nexport { SupportedLanguage as SupportedLanguages } from \"./models.js\";\n\nexport type { Codes } from \"./services/codes.js\";\n\nexport type {\n Execution,\n ExecutionComplete,\n ExecutionError,\n ExecutionHandlers,\n ExecutionInit,\n ExecutionResult,\n OutputMessage,\n} from \"@alibaba-group/opensandbox\";","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { DEFAULT_EXECD_PORT } from \"@alibaba-group/opensandbox\";\nimport type { Sandbox } from \"@alibaba-group/opensandbox\";\n\nimport { createDefaultAdapterFactory } from \"./factory/defaultAdapterFactory.js\";\nimport type { AdapterFactory } from \"./factory/adapterFactory.js\";\nimport type { Codes } from \"./services/codes.js\";\n\nexport interface CodeInterpreterCreateOptions {\n adapterFactory?: AdapterFactory;\n}\n\n/**\n * Code interpreter facade (JS/TS).\n *\n * This class wraps an existing {@link Sandbox} and provides a high-level API for code execution.\n *\n * - Use {@link codes} to create contexts and run code.\n * - {@link files}, {@link commands}, and {@link metrics} are exposed for convenience and are\n * the same instances as on the underlying {@link Sandbox}.\n */\nexport class CodeInterpreter {\n private constructor(\n readonly sandbox: Sandbox,\n readonly codes: Codes,\n ) {}\n\n static async create(sandbox: Sandbox, opts: CodeInterpreterCreateOptions = {}): Promise<CodeInterpreter> {\n const endpoint = await sandbox.getEndpoint(DEFAULT_EXECD_PORT);\n const execdBaseUrl = `${sandbox.connectionConfig.protocol}://${endpoint.endpoint}`;\n const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();\n const codes = adapterFactory.createCodes({\n sandbox,\n execdBaseUrl,\n endpointHeaders: endpoint.headers,\n });\n\n return new CodeInterpreter(sandbox, codes);\n }\n\n get id() {\n return this.sandbox.id;\n }\n\n get files() {\n return this.sandbox.files;\n }\n\n get commands() {\n return this.sandbox.commands;\n }\n\n get metrics() {\n return this.sandbox.metrics;\n }\n}\n","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { createExecdClient } from \"@alibaba-group/opensandbox/internal\";\nimport type { AdapterFactory, CreateCodesStackOptions } from \"./adapterFactory.js\";\nimport { CodesAdapter } from \"../adapters/codesAdapter.js\";\nimport type { Codes } from \"../services/codes.js\";\n\nexport class DefaultAdapterFactory implements AdapterFactory {\n createCodes(opts: CreateCodesStackOptions): Codes {\n const headers: Record<string, string> = {\n ...(opts.sandbox.connectionConfig.headers ?? {}),\n ...(opts.endpointHeaders ?? {}),\n };\n const client = createExecdClient({\n baseUrl: opts.execdBaseUrl,\n headers,\n fetch: opts.sandbox.connectionConfig.fetch,\n });\n\n return new CodesAdapter(client, {\n baseUrl: opts.execdBaseUrl,\n headers,\n // Streaming calls (SSE) use a dedicated fetch, aligned with Kotlin/Python SDKs.\n fetch: opts.sandbox.connectionConfig.sseFetch,\n });\n }\n}\n\nexport function createDefaultAdapterFactory(): AdapterFactory {\n return new DefaultAdapterFactory();\n}\n","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { ExecdClient, ExecdPaths } from \"@alibaba-group/opensandbox/internal\";\nimport type { ServerStreamEvent } from \"@alibaba-group/opensandbox\";\nimport type { Execution, ExecutionHandlers } from \"@alibaba-group/opensandbox\";\nimport {\n ExecutionEventDispatcher,\n InvalidArgumentException,\n} from \"@alibaba-group/opensandbox\";\n\nimport type { Codes } from \"../services/codes.js\";\nimport type { CodeContext, SupportedLanguage } from \"../models.js\";\nimport { throwOnOpenApiFetchError } from \"./openapiError.js\";\nimport { parseJsonEventStream } from \"./sse.js\";\n\ntype ApiCreateContextRequest =\n ExecdPaths[\"/code/context\"][\"post\"][\"requestBody\"][\"content\"][\"application/json\"];\ntype ApiCreateContextOk =\n ExecdPaths[\"/code/context\"][\"post\"][\"responses\"][200][\"content\"][\"application/json\"];\ntype ApiGetContextOk =\n ExecdPaths[\"/code/contexts/{context_id}\"][\"get\"][\"responses\"][200][\"content\"][\"application/json\"];\ntype ApiListContextsOk =\n ExecdPaths[\"/code/contexts\"][\"get\"][\"responses\"][200][\"content\"][\"application/json\"];\ntype ApiRunCodeRequest =\n ExecdPaths[\"/code\"][\"post\"][\"requestBody\"][\"content\"][\"application/json\"];\n\n/**\n * Single-layer codes adapter for the Code Interpreter SDK.\n *\n * - Handles HTTP/SSE streaming via the underlying execd adapter\n * - Builds the structured {@link Execution} result for `run(...)`\n */\nfunction joinUrl(baseUrl: string, pathname: string): string {\n const base = baseUrl.endsWith(\"/\") ? baseUrl.slice(0, -1) : baseUrl;\n const path = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n return `${base}${path}`;\n}\n\nexport class CodesAdapter implements Codes {\n private readonly fetch: typeof fetch;\n\n constructor(\n private readonly client: ExecdClient,\n private readonly opts: { baseUrl: string; fetch?: typeof fetch; headers?: Record<string, string> },\n ) {\n this.fetch = opts.fetch ?? fetch;\n }\n\n async createContext(language: SupportedLanguage): Promise<CodeContext> {\n const body: ApiCreateContextRequest = { language };\n const { data, error, response } = await this.client.POST(\"/code/context\", {\n body,\n });\n throwOnOpenApiFetchError({ error, response }, \"Create code context failed\");\n const ok = data as ApiCreateContextOk | undefined;\n if (!ok || typeof ok !== \"object\") {\n throw new Error(\"Create code context failed: unexpected response shape\");\n }\n if (typeof ok.language !== \"string\" || !ok.language) {\n throw new Error(\"Create code context failed: missing language\");\n }\n return { id: ok.id, language: ok.language };\n }\n\n async getContext(contextId: string): Promise<CodeContext> {\n if (!contextId?.trim()) {\n throw new InvalidArgumentException({ message: \"contextId cannot be empty\" });\n }\n const { data, error, response } = await this.client.GET(\"/code/contexts/{context_id}\", {\n params: { path: { context_id: contextId } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Get code context failed\");\n const ok = data as ApiGetContextOk | undefined;\n if (!ok || typeof ok !== \"object\") {\n throw new Error(\"Get code context failed: unexpected response shape\");\n }\n if (typeof (ok as any).language !== \"string\" || !(ok as any).language) {\n throw new Error(\"Get code context failed: missing language\");\n }\n return { id: (ok as any).id, language: (ok as any).language };\n }\n\n async listContexts(language?: SupportedLanguage): Promise<CodeContext[]> {\n const { data, error, response } = await this.client.GET(\"/code/contexts\", {\n params: language ? { query: { language } } : undefined,\n } as any);\n throwOnOpenApiFetchError({ error, response }, \"List code contexts failed\");\n const ok = data as ApiListContextsOk | undefined;\n if (!Array.isArray(ok)) {\n throw new Error(\"List code contexts failed: unexpected response shape\");\n }\n return ok\n .filter((c) => c && typeof c === \"object\")\n .map((c: any) => ({ id: c.id, language: c.language as any }));\n }\n\n async deleteContext(contextId: string): Promise<void> {\n if (!contextId?.trim()) {\n throw new InvalidArgumentException({ message: \"contextId cannot be empty\" });\n }\n const { error, response } = await this.client.DELETE(\"/code/contexts/{context_id}\", {\n params: { path: { context_id: contextId } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Delete code context failed\");\n }\n\n async deleteContexts(language: SupportedLanguage): Promise<void> {\n const { error, response } = await this.client.DELETE(\"/code/contexts\", {\n params: { query: { language } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Delete code contexts failed\");\n }\n\n async interrupt(contextId: string): Promise<void> {\n const { error, response } = await this.client.DELETE(\"/code\", {\n params: { query: { id: contextId } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Interrupt code failed\");\n }\n\n async *runStream(req: ApiRunCodeRequest, signal?: AbortSignal): AsyncIterable<ServerStreamEvent> {\n const url = joinUrl(this.opts.baseUrl, \"/code\");\n const body = JSON.stringify(req);\n const res = await this.fetch(url, {\n method: \"POST\",\n headers: {\n \"accept\": \"text/event-stream\",\n \"content-type\": \"application/json\",\n ...(this.opts.headers ?? {}),\n },\n body,\n signal,\n });\n\n for await (const ev of parseJsonEventStream<ServerStreamEvent>(res, { fallbackErrorMessage: \"Run code failed\" })) {\n yield ev;\n }\n }\n\n async run(\n code: string,\n opts: { context?: CodeContext; language?: SupportedLanguage; handlers?: ExecutionHandlers; signal?: AbortSignal } = {},\n ): Promise<Execution> {\n if (!code.trim()) {\n throw new InvalidArgumentException({ message: \"Code cannot be empty\" });\n }\n\n if (opts.context && opts.language) {\n throw new InvalidArgumentException({ message: \"Provide either opts.context or opts.language, not both\" });\n }\n\n const context: CodeContext =\n opts.context ??\n (opts.language\n ? { language: opts.language }\n : { language: \"python\" });\n\n // Make the OpenAPI contract explicit so backend schema changes surface quickly.\n const req: ApiRunCodeRequest = {\n code,\n context: { id: context.id, language: context.language },\n };\n\n const execution: Execution = {\n logs: { stdout: [], stderr: [] },\n result: [],\n };\n const dispatcher = new ExecutionEventDispatcher(execution, opts.handlers);\n\n for await (const ev of this.runStream(req, opts.signal)) {\n await dispatcher.dispatch(ev as any);\n }\n\n return execution;\n }\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { SandboxApiException, SandboxError } from \"@alibaba-group/opensandbox\";\n\nexport function throwOnOpenApiFetchError(\n result: { error?: unknown; response: Response },\n fallbackMessage: string,\n): void {\n if (!result.error) return;\n\n const requestId = result.response.headers.get(\"x-request-id\") ?? undefined;\n const status = (result.response as any).status ?? 0;\n\n const err = result.error as any;\n const message =\n err?.message ??\n err?.error?.message ??\n fallbackMessage;\n\n const code = err?.code ?? err?.error?.code;\n const msg = err?.message ?? err?.error?.message ?? message;\n\n throw new SandboxApiException({\n message: msg,\n statusCode: status,\n requestId,\n error: code\n ? new SandboxError(String(code), String(msg ?? \"\"))\n : new SandboxError(SandboxError.UNEXPECTED_RESPONSE, String(msg ?? \"\")),\n rawBody: result.error,\n });\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { SandboxApiException, SandboxError } from \"@alibaba-group/opensandbox\";\n\nfunction tryParseJson(line: string): unknown | undefined {\n try {\n return JSON.parse(line);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Parses an SSE-like stream that may be either:\n * - standard SSE frames (`data: {...}\\n\\n`)\n * - newline-delimited JSON (one JSON object per line)\n */\nexport async function* parseJsonEventStream<T>(\n res: Response,\n opts?: { fallbackErrorMessage?: string },\n): AsyncIterable<T> {\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n const parsed = tryParseJson(text);\n const err = parsed && typeof parsed === \"object\" ? (parsed as any) : undefined;\n const requestId = res.headers.get(\"x-request-id\") ?? undefined;\n const message = err?.message ?? opts?.fallbackErrorMessage ?? `Stream request failed (status=${res.status})`;\n const code = err?.code ? String(err.code) : SandboxError.UNEXPECTED_RESPONSE;\n throw new SandboxApiException({\n message,\n statusCode: res.status,\n requestId,\n error: new SandboxError(code, err?.message ? String(err.message) : message),\n rawBody: parsed ?? text,\n });\n }\n\n if (!res.body) return;\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder(\"utf-8\");\n let buf = \"\";\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n\n buf += decoder.decode(value, { stream: true });\n let idx: number;\n\n while ((idx = buf.indexOf(\"\\n\")) >= 0) {\n const rawLine = buf.slice(0, idx);\n buf = buf.slice(idx + 1);\n\n const line = rawLine.trim();\n if (!line) continue;\n\n // Support standard SSE \"data:\" prefix\n if (line.startsWith(\":\")) continue;\n if (line.startsWith(\"event:\") || line.startsWith(\"id:\") || line.startsWith(\"retry:\")) continue;\n\n const jsonLine = line.startsWith(\"data:\") ? line.slice(\"data:\".length).trim() : line;\n if (!jsonLine) continue;\n\n const parsed = tryParseJson(jsonLine);\n if (!parsed) continue;\n yield parsed as T;\n }\n }\n\n // flush last line if exists\n const last = buf.trim();\n if (last) {\n const jsonLine = last.startsWith(\"data:\") ? last.slice(\"data:\".length).trim() : last;\n const parsed = tryParseJson(jsonLine);\n if (parsed) yield parsed as T;\n }\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport const SupportedLanguage = {\n PYTHON: \"python\",\n JAVA: \"java\",\n GO: \"go\",\n TYPESCRIPT: \"typescript\",\n JAVASCRIPT: \"javascript\",\n BASH: \"bash\",\n} as const;\n\nexport type SupportedLanguage =\n (typeof SupportedLanguage)[keyof typeof SupportedLanguage];\n\nexport interface CodeContext {\n id?: string;\n language: SupportedLanguage | (string & {});\n}\n\nexport interface RunCodeRequest {\n code: string;\n context: CodeContext;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACcA,IAAAA,sBAAmC;;;ACAnC,sBAAkC;;;ACGlC,IAAAC,sBAGO;;;ACNP,yBAAkD;AAE3C,SAAS,yBACd,QACA,iBACM;AACN,MAAI,CAAC,OAAO,MAAO;AAEnB,QAAM,YAAY,OAAO,SAAS,QAAQ,IAAI,cAAc,KAAK;AACjE,QAAM,SAAU,OAAO,SAAiB,UAAU;AAElD,QAAM,MAAM,OAAO;AACnB,QAAM,UACJ,KAAK,WACL,KAAK,OAAO,WACZ;AAEF,QAAM,OAAO,KAAK,QAAQ,KAAK,OAAO;AACtC,QAAM,MAAM,KAAK,WAAW,KAAK,OAAO,WAAW;AAEnD,QAAM,IAAI,uCAAoB;AAAA,IAC5B,SAAS;AAAA,IACT,YAAY;AAAA,IACZ;AAAA,IACA,OAAO,OACH,IAAI,gCAAa,OAAO,IAAI,GAAG,OAAO,OAAO,EAAE,CAAC,IAChD,IAAI,gCAAa,gCAAa,qBAAqB,OAAO,OAAO,EAAE,CAAC;AAAA,IACxE,SAAS,OAAO;AAAA,EAClB,CAAC;AACH;;;AC7BA,IAAAC,sBAAkD;AAElD,SAAS,aAAa,MAAmC;AACvD,MAAI;AACF,WAAO,KAAK,MAAM,IAAI;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOA,gBAAuB,qBACrB,KACA,MACkB;AAClB,MAAI,CAAC,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AAChF,UAAM,iBAAiB,KAAK,kBAAkB,4BAA4B;AAC1E,UAAM,QAAQ,eAAe,YAAY;AAAA,MACvC;AAAA,MACA;AAAA,MACA,iBAAiB,SAAS;AAAA,IAC5B,CAAC;AAED,WAAO,IAAI,iBAAgB,SAAS,KAAK;AAAA,EAC3C;AAAA,EAEA,IAAI,KAAK;AACP,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,QAAQ;AACV,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,WAAW;AACb,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,UAAU;AACZ,WAAO,KAAK,QAAQ;AAAA,EACtB;AACF;;;AKtDO,IAAM,oBAAoB;AAAA,EAC/B,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,IAAI;AAAA,EACJ,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,MAAM;AACR;","names":["import_opensandbox","import_opensandbox","import_opensandbox"]}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -206,14 +206,18 @@ var CodesAdapter = class {
|
|
|
206
206
|
// src/factory/defaultAdapterFactory.ts
|
|
207
207
|
var DefaultAdapterFactory = class {
|
|
208
208
|
createCodes(opts) {
|
|
209
|
+
const headers = {
|
|
210
|
+
...opts.sandbox.connectionConfig.headers ?? {},
|
|
211
|
+
...opts.endpointHeaders ?? {}
|
|
212
|
+
};
|
|
209
213
|
const client = createExecdClient({
|
|
210
214
|
baseUrl: opts.execdBaseUrl,
|
|
211
|
-
headers
|
|
215
|
+
headers,
|
|
212
216
|
fetch: opts.sandbox.connectionConfig.fetch
|
|
213
217
|
});
|
|
214
218
|
return new CodesAdapter(client, {
|
|
215
219
|
baseUrl: opts.execdBaseUrl,
|
|
216
|
-
headers
|
|
220
|
+
headers,
|
|
217
221
|
// Streaming calls (SSE) use a dedicated fetch, aligned with Kotlin/Python SDKs.
|
|
218
222
|
fetch: opts.sandbox.connectionConfig.sseFetch
|
|
219
223
|
});
|
|
@@ -230,9 +234,14 @@ var CodeInterpreter = class _CodeInterpreter {
|
|
|
230
234
|
this.codes = codes;
|
|
231
235
|
}
|
|
232
236
|
static async create(sandbox, opts = {}) {
|
|
233
|
-
const
|
|
237
|
+
const endpoint = await sandbox.getEndpoint(DEFAULT_EXECD_PORT);
|
|
238
|
+
const execdBaseUrl = `${sandbox.connectionConfig.protocol}://${endpoint.endpoint}`;
|
|
234
239
|
const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();
|
|
235
|
-
const codes = adapterFactory.createCodes({
|
|
240
|
+
const codes = adapterFactory.createCodes({
|
|
241
|
+
sandbox,
|
|
242
|
+
execdBaseUrl,
|
|
243
|
+
endpointHeaders: endpoint.headers
|
|
244
|
+
});
|
|
236
245
|
return new _CodeInterpreter(sandbox, codes);
|
|
237
246
|
}
|
|
238
247
|
get id() {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/interpreter.ts","../src/factory/defaultAdapterFactory.ts","../src/adapters/codesAdapter.ts","../src/adapters/openapiError.ts","../src/adapters/sse.ts","../src/models.ts"],"sourcesContent":["// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { DEFAULT_EXECD_PORT } from \"@alibaba-group/opensandbox\";\nimport type { Sandbox } from \"@alibaba-group/opensandbox\";\n\nimport { createDefaultAdapterFactory } from \"./factory/defaultAdapterFactory.js\";\nimport type { AdapterFactory } from \"./factory/adapterFactory.js\";\nimport type { Codes } from \"./services/codes.js\";\n\nexport interface CodeInterpreterCreateOptions {\n adapterFactory?: AdapterFactory;\n}\n\n/**\n * Code interpreter facade (JS/TS).\n *\n * This class wraps an existing {@link Sandbox} and provides a high-level API for code execution.\n *\n * - Use {@link codes} to create contexts and run code.\n * - {@link files}, {@link commands}, and {@link metrics} are exposed for convenience and are\n * the same instances as on the underlying {@link Sandbox}.\n */\nexport class CodeInterpreter {\n private constructor(\n readonly sandbox: Sandbox,\n readonly codes: Codes,\n ) {}\n\n static async create(sandbox: Sandbox, opts: CodeInterpreterCreateOptions = {}): Promise<CodeInterpreter> {\n const execdBaseUrl = await sandbox.getEndpointUrl(DEFAULT_EXECD_PORT);\n const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();\n const codes = adapterFactory.createCodes({ sandbox, execdBaseUrl });\n\n return new CodeInterpreter(sandbox, codes);\n }\n\n get id() {\n return this.sandbox.id;\n }\n\n get files() {\n return this.sandbox.files;\n }\n\n get commands() {\n return this.sandbox.commands;\n }\n\n get metrics() {\n return this.sandbox.metrics;\n }\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { createExecdClient } from \"@alibaba-group/opensandbox/internal\";\nimport type { AdapterFactory, CreateCodesStackOptions } from \"./adapterFactory.js\";\nimport { CodesAdapter } from \"../adapters/codesAdapter.js\";\nimport type { Codes } from \"../services/codes.js\";\n\nexport class DefaultAdapterFactory implements AdapterFactory {\n createCodes(opts: CreateCodesStackOptions): Codes {\n const client = createExecdClient({\n baseUrl: opts.execdBaseUrl,\n headers: opts.sandbox.connectionConfig.headers,\n fetch: opts.sandbox.connectionConfig.fetch,\n });\n\n return new CodesAdapter(client, {\n baseUrl: opts.execdBaseUrl,\n headers: opts.sandbox.connectionConfig.headers,\n // Streaming calls (SSE) use a dedicated fetch, aligned with Kotlin/Python SDKs.\n fetch: opts.sandbox.connectionConfig.sseFetch,\n });\n }\n}\n\nexport function createDefaultAdapterFactory(): AdapterFactory {\n return new DefaultAdapterFactory();\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { ExecdClient, ExecdPaths } from \"@alibaba-group/opensandbox/internal\";\nimport type { ServerStreamEvent } from \"@alibaba-group/opensandbox\";\nimport type { Execution, ExecutionHandlers } from \"@alibaba-group/opensandbox\";\nimport {\n ExecutionEventDispatcher,\n InvalidArgumentException,\n} from \"@alibaba-group/opensandbox\";\n\nimport type { Codes } from \"../services/codes.js\";\nimport type { CodeContext, SupportedLanguage } from \"../models.js\";\nimport { throwOnOpenApiFetchError } from \"./openapiError.js\";\nimport { parseJsonEventStream } from \"./sse.js\";\n\ntype ApiCreateContextRequest =\n ExecdPaths[\"/code/context\"][\"post\"][\"requestBody\"][\"content\"][\"application/json\"];\ntype ApiCreateContextOk =\n ExecdPaths[\"/code/context\"][\"post\"][\"responses\"][200][\"content\"][\"application/json\"];\ntype ApiGetContextOk =\n ExecdPaths[\"/code/contexts/{context_id}\"][\"get\"][\"responses\"][200][\"content\"][\"application/json\"];\ntype ApiListContextsOk =\n ExecdPaths[\"/code/contexts\"][\"get\"][\"responses\"][200][\"content\"][\"application/json\"];\ntype ApiRunCodeRequest =\n ExecdPaths[\"/code\"][\"post\"][\"requestBody\"][\"content\"][\"application/json\"];\n\n/**\n * Single-layer codes adapter for the Code Interpreter SDK.\n *\n * - Handles HTTP/SSE streaming via the underlying execd adapter\n * - Builds the structured {@link Execution} result for `run(...)`\n */\nfunction joinUrl(baseUrl: string, pathname: string): string {\n const base = baseUrl.endsWith(\"/\") ? baseUrl.slice(0, -1) : baseUrl;\n const path = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n return `${base}${path}`;\n}\n\nexport class CodesAdapter implements Codes {\n private readonly fetch: typeof fetch;\n\n constructor(\n private readonly client: ExecdClient,\n private readonly opts: { baseUrl: string; fetch?: typeof fetch; headers?: Record<string, string> },\n ) {\n this.fetch = opts.fetch ?? fetch;\n }\n\n async createContext(language: SupportedLanguage): Promise<CodeContext> {\n const body: ApiCreateContextRequest = { language };\n const { data, error, response } = await this.client.POST(\"/code/context\", {\n body,\n });\n throwOnOpenApiFetchError({ error, response }, \"Create code context failed\");\n const ok = data as ApiCreateContextOk | undefined;\n if (!ok || typeof ok !== \"object\") {\n throw new Error(\"Create code context failed: unexpected response shape\");\n }\n if (typeof ok.language !== \"string\" || !ok.language) {\n throw new Error(\"Create code context failed: missing language\");\n }\n return { id: ok.id, language: ok.language };\n }\n\n async getContext(contextId: string): Promise<CodeContext> {\n if (!contextId?.trim()) {\n throw new InvalidArgumentException({ message: \"contextId cannot be empty\" });\n }\n const { data, error, response } = await this.client.GET(\"/code/contexts/{context_id}\", {\n params: { path: { context_id: contextId } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Get code context failed\");\n const ok = data as ApiGetContextOk | undefined;\n if (!ok || typeof ok !== \"object\") {\n throw new Error(\"Get code context failed: unexpected response shape\");\n }\n if (typeof (ok as any).language !== \"string\" || !(ok as any).language) {\n throw new Error(\"Get code context failed: missing language\");\n }\n return { id: (ok as any).id, language: (ok as any).language };\n }\n\n async listContexts(language?: SupportedLanguage): Promise<CodeContext[]> {\n const { data, error, response } = await this.client.GET(\"/code/contexts\", {\n params: language ? { query: { language } } : undefined,\n } as any);\n throwOnOpenApiFetchError({ error, response }, \"List code contexts failed\");\n const ok = data as ApiListContextsOk | undefined;\n if (!Array.isArray(ok)) {\n throw new Error(\"List code contexts failed: unexpected response shape\");\n }\n return ok\n .filter((c) => c && typeof c === \"object\")\n .map((c: any) => ({ id: c.id, language: c.language as any }));\n }\n\n async deleteContext(contextId: string): Promise<void> {\n if (!contextId?.trim()) {\n throw new InvalidArgumentException({ message: \"contextId cannot be empty\" });\n }\n const { error, response } = await this.client.DELETE(\"/code/contexts/{context_id}\", {\n params: { path: { context_id: contextId } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Delete code context failed\");\n }\n\n async deleteContexts(language: SupportedLanguage): Promise<void> {\n const { error, response } = await this.client.DELETE(\"/code/contexts\", {\n params: { query: { language } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Delete code contexts failed\");\n }\n\n async interrupt(contextId: string): Promise<void> {\n const { error, response } = await this.client.DELETE(\"/code\", {\n params: { query: { id: contextId } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Interrupt code failed\");\n }\n\n async *runStream(req: ApiRunCodeRequest, signal?: AbortSignal): AsyncIterable<ServerStreamEvent> {\n const url = joinUrl(this.opts.baseUrl, \"/code\");\n const body = JSON.stringify(req);\n const res = await this.fetch(url, {\n method: \"POST\",\n headers: {\n \"accept\": \"text/event-stream\",\n \"content-type\": \"application/json\",\n ...(this.opts.headers ?? {}),\n },\n body,\n signal,\n });\n\n for await (const ev of parseJsonEventStream<ServerStreamEvent>(res, { fallbackErrorMessage: \"Run code failed\" })) {\n yield ev;\n }\n }\n\n async run(\n code: string,\n opts: { context?: CodeContext; language?: SupportedLanguage; handlers?: ExecutionHandlers; signal?: AbortSignal } = {},\n ): Promise<Execution> {\n if (!code.trim()) {\n throw new InvalidArgumentException({ message: \"Code cannot be empty\" });\n }\n\n if (opts.context && opts.language) {\n throw new InvalidArgumentException({ message: \"Provide either opts.context or opts.language, not both\" });\n }\n\n const context: CodeContext =\n opts.context ??\n (opts.language\n ? { language: opts.language }\n : { language: \"python\" });\n\n // Make the OpenAPI contract explicit so backend schema changes surface quickly.\n const req: ApiRunCodeRequest = {\n code,\n context: { id: context.id, language: context.language },\n };\n\n const execution: Execution = {\n logs: { stdout: [], stderr: [] },\n result: [],\n };\n const dispatcher = new ExecutionEventDispatcher(execution, opts.handlers);\n\n for await (const ev of this.runStream(req, opts.signal)) {\n await dispatcher.dispatch(ev as any);\n }\n\n return execution;\n }\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { SandboxApiException, SandboxError } from \"@alibaba-group/opensandbox\";\n\nexport function throwOnOpenApiFetchError(\n result: { error?: unknown; response: Response },\n fallbackMessage: string,\n): void {\n if (!result.error) return;\n\n const requestId = result.response.headers.get(\"x-request-id\") ?? undefined;\n const status = (result.response as any).status ?? 0;\n\n const err = result.error as any;\n const message =\n err?.message ??\n err?.error?.message ??\n fallbackMessage;\n\n const code = err?.code ?? err?.error?.code;\n const msg = err?.message ?? err?.error?.message ?? message;\n\n throw new SandboxApiException({\n message: msg,\n statusCode: status,\n requestId,\n error: code\n ? new SandboxError(String(code), String(msg ?? \"\"))\n : new SandboxError(SandboxError.UNEXPECTED_RESPONSE, String(msg ?? \"\")),\n rawBody: result.error,\n });\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { SandboxApiException, SandboxError } from \"@alibaba-group/opensandbox\";\n\nfunction tryParseJson(line: string): unknown | undefined {\n try {\n return JSON.parse(line);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Parses an SSE-like stream that may be either:\n * - standard SSE frames (`data: {...}\\n\\n`)\n * - newline-delimited JSON (one JSON object per line)\n */\nexport async function* parseJsonEventStream<T>(\n res: Response,\n opts?: { fallbackErrorMessage?: string },\n): AsyncIterable<T> {\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n const parsed = tryParseJson(text);\n const err = parsed && typeof parsed === \"object\" ? (parsed as any) : undefined;\n const requestId = res.headers.get(\"x-request-id\") ?? undefined;\n const message = err?.message ?? opts?.fallbackErrorMessage ?? `Stream request failed (status=${res.status})`;\n const code = err?.code ? String(err.code) : SandboxError.UNEXPECTED_RESPONSE;\n throw new SandboxApiException({\n message,\n statusCode: res.status,\n requestId,\n error: new SandboxError(code, err?.message ? String(err.message) : message),\n rawBody: parsed ?? text,\n });\n }\n\n if (!res.body) return;\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder(\"utf-8\");\n let buf = \"\";\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n\n buf += decoder.decode(value, { stream: true });\n let idx: number;\n\n while ((idx = buf.indexOf(\"\\n\")) >= 0) {\n const rawLine = buf.slice(0, idx);\n buf = buf.slice(idx + 1);\n\n const line = rawLine.trim();\n if (!line) continue;\n\n // Support standard SSE \"data:\" prefix\n if (line.startsWith(\":\")) continue;\n if (line.startsWith(\"event:\") || line.startsWith(\"id:\") || line.startsWith(\"retry:\")) continue;\n\n const jsonLine = line.startsWith(\"data:\") ? line.slice(\"data:\".length).trim() : line;\n if (!jsonLine) continue;\n\n const parsed = tryParseJson(jsonLine);\n if (!parsed) continue;\n yield parsed as T;\n }\n }\n\n // flush last line if exists\n const last = buf.trim();\n if (last) {\n const jsonLine = last.startsWith(\"data:\") ? last.slice(\"data:\".length).trim() : last;\n const parsed = tryParseJson(jsonLine);\n if (parsed) yield parsed as T;\n }\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport const SupportedLanguage = {\n PYTHON: \"python\",\n JAVA: \"java\",\n GO: \"go\",\n TYPESCRIPT: \"typescript\",\n JAVASCRIPT: \"javascript\",\n BASH: \"bash\",\n} as const;\n\nexport type SupportedLanguage =\n (typeof SupportedLanguage)[keyof typeof SupportedLanguage];\n\nexport interface CodeContext {\n id?: string;\n language: SupportedLanguage | (string & {});\n}\n\nexport interface RunCodeRequest {\n code: string;\n context: CodeContext;\n}"],"mappings":";AAcA,SAAS,0BAA0B;;;ACAnC,SAAS,yBAAyB;;;ACGlC;AAAA,EACE;AAAA,EACA;AAAA,OACK;;;ACNP,SAAS,qBAAqB,oBAAoB;AAE3C,SAAS,yBACd,QACA,iBACM;AACN,MAAI,CAAC,OAAO,MAAO;AAEnB,QAAM,YAAY,OAAO,SAAS,QAAQ,IAAI,cAAc,KAAK;AACjE,QAAM,SAAU,OAAO,SAAiB,UAAU;AAElD,QAAM,MAAM,OAAO;AACnB,QAAM,UACJ,KAAK,WACL,KAAK,OAAO,WACZ;AAEF,QAAM,OAAO,KAAK,QAAQ,KAAK,OAAO;AACtC,QAAM,MAAM,KAAK,WAAW,KAAK,OAAO,WAAW;AAEnD,QAAM,IAAI,oBAAoB;AAAA,IAC5B,SAAS;AAAA,IACT,YAAY;AAAA,IACZ;AAAA,IACA,OAAO,OACH,IAAI,aAAa,OAAO,IAAI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AC5D,SAAO,IAAI,sBAAsB;AACnC;;;ADJO,IAAM,kBAAN,MAAM,iBAAgB;AAAA,EACnB,YACG,SACA,OACT;AAFS;AACA;AAAA,EACR;AAAA,EAEH,aAAa,OAAO,SAAkB,OAAqC,CAAC,GAA6B;AACvG,UAAM,eAAe,MAAM,QAAQ,eAAe,kBAAkB;AACpE,UAAM,iBAAiB,KAAK,kBAAkB,4BAA4B;AAC1E,UAAM,QAAQ,eAAe,YAAY,EAAE,SAAS,aAAa,CAAC;AAElE,WAAO,IAAI,iBAAgB,SAAS,KAAK;AAAA,EAC3C;AAAA,EAEA,IAAI,KAAK;AACP,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,QAAQ;AACV,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,WAAW;AACb,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EAEA,IAAI,UAAU;AACZ,WAAO,KAAK,QAAQ;AAAA,EACtB;AACF;;;AKjDO,IAAM,oBAAoB;AAAA,EAC/B,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,IAAI;AAAA,EACJ,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,MAAM;AACR;","names":["SandboxApiException","SandboxError"]}
|
|
1
|
+
{"version":3,"sources":["../src/interpreter.ts","../src/factory/defaultAdapterFactory.ts","../src/adapters/codesAdapter.ts","../src/adapters/openapiError.ts","../src/adapters/sse.ts","../src/models.ts"],"sourcesContent":["// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { DEFAULT_EXECD_PORT } from \"@alibaba-group/opensandbox\";\nimport type { Sandbox } from \"@alibaba-group/opensandbox\";\n\nimport { createDefaultAdapterFactory } from \"./factory/defaultAdapterFactory.js\";\nimport type { AdapterFactory } from \"./factory/adapterFactory.js\";\nimport type { Codes } from \"./services/codes.js\";\n\nexport interface CodeInterpreterCreateOptions {\n adapterFactory?: AdapterFactory;\n}\n\n/**\n * Code interpreter facade (JS/TS).\n *\n * This class wraps an existing {@link Sandbox} and provides a high-level API for code execution.\n *\n * - Use {@link codes} to create contexts and run code.\n * - {@link files}, {@link commands}, and {@link metrics} are exposed for convenience and are\n * the same instances as on the underlying {@link Sandbox}.\n */\nexport class CodeInterpreter {\n private constructor(\n readonly sandbox: Sandbox,\n readonly codes: Codes,\n ) {}\n\n static async create(sandbox: Sandbox, opts: CodeInterpreterCreateOptions = {}): Promise<CodeInterpreter> {\n const endpoint = await sandbox.getEndpoint(DEFAULT_EXECD_PORT);\n const execdBaseUrl = `${sandbox.connectionConfig.protocol}://${endpoint.endpoint}`;\n const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();\n const codes = adapterFactory.createCodes({\n sandbox,\n execdBaseUrl,\n endpointHeaders: endpoint.headers,\n });\n\n return new CodeInterpreter(sandbox, codes);\n }\n\n get id() {\n return this.sandbox.id;\n }\n\n get files() {\n return this.sandbox.files;\n }\n\n get commands() {\n return this.sandbox.commands;\n }\n\n get metrics() {\n return this.sandbox.metrics;\n }\n}\n","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { createExecdClient } from \"@alibaba-group/opensandbox/internal\";\nimport type { AdapterFactory, CreateCodesStackOptions } from \"./adapterFactory.js\";\nimport { CodesAdapter } from \"../adapters/codesAdapter.js\";\nimport type { Codes } from \"../services/codes.js\";\n\nexport class DefaultAdapterFactory implements AdapterFactory {\n createCodes(opts: CreateCodesStackOptions): Codes {\n const headers: Record<string, string> = {\n ...(opts.sandbox.connectionConfig.headers ?? {}),\n ...(opts.endpointHeaders ?? {}),\n };\n const client = createExecdClient({\n baseUrl: opts.execdBaseUrl,\n headers,\n fetch: opts.sandbox.connectionConfig.fetch,\n });\n\n return new CodesAdapter(client, {\n baseUrl: opts.execdBaseUrl,\n headers,\n // Streaming calls (SSE) use a dedicated fetch, aligned with Kotlin/Python SDKs.\n fetch: opts.sandbox.connectionConfig.sseFetch,\n });\n }\n}\n\nexport function createDefaultAdapterFactory(): AdapterFactory {\n return new DefaultAdapterFactory();\n}\n","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { ExecdClient, ExecdPaths } from \"@alibaba-group/opensandbox/internal\";\nimport type { ServerStreamEvent } from \"@alibaba-group/opensandbox\";\nimport type { Execution, ExecutionHandlers } from \"@alibaba-group/opensandbox\";\nimport {\n ExecutionEventDispatcher,\n InvalidArgumentException,\n} from \"@alibaba-group/opensandbox\";\n\nimport type { Codes } from \"../services/codes.js\";\nimport type { CodeContext, SupportedLanguage } from \"../models.js\";\nimport { throwOnOpenApiFetchError } from \"./openapiError.js\";\nimport { parseJsonEventStream } from \"./sse.js\";\n\ntype ApiCreateContextRequest =\n ExecdPaths[\"/code/context\"][\"post\"][\"requestBody\"][\"content\"][\"application/json\"];\ntype ApiCreateContextOk =\n ExecdPaths[\"/code/context\"][\"post\"][\"responses\"][200][\"content\"][\"application/json\"];\ntype ApiGetContextOk =\n ExecdPaths[\"/code/contexts/{context_id}\"][\"get\"][\"responses\"][200][\"content\"][\"application/json\"];\ntype ApiListContextsOk =\n ExecdPaths[\"/code/contexts\"][\"get\"][\"responses\"][200][\"content\"][\"application/json\"];\ntype ApiRunCodeRequest =\n ExecdPaths[\"/code\"][\"post\"][\"requestBody\"][\"content\"][\"application/json\"];\n\n/**\n * Single-layer codes adapter for the Code Interpreter SDK.\n *\n * - Handles HTTP/SSE streaming via the underlying execd adapter\n * - Builds the structured {@link Execution} result for `run(...)`\n */\nfunction joinUrl(baseUrl: string, pathname: string): string {\n const base = baseUrl.endsWith(\"/\") ? baseUrl.slice(0, -1) : baseUrl;\n const path = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n return `${base}${path}`;\n}\n\nexport class CodesAdapter implements Codes {\n private readonly fetch: typeof fetch;\n\n constructor(\n private readonly client: ExecdClient,\n private readonly opts: { baseUrl: string; fetch?: typeof fetch; headers?: Record<string, string> },\n ) {\n this.fetch = opts.fetch ?? fetch;\n }\n\n async createContext(language: SupportedLanguage): Promise<CodeContext> {\n const body: ApiCreateContextRequest = { language };\n const { data, error, response } = await this.client.POST(\"/code/context\", {\n body,\n });\n throwOnOpenApiFetchError({ error, response }, \"Create code context failed\");\n const ok = data as ApiCreateContextOk | undefined;\n if (!ok || typeof ok !== \"object\") {\n throw new Error(\"Create code context failed: unexpected response shape\");\n }\n if (typeof ok.language !== \"string\" || !ok.language) {\n throw new Error(\"Create code context failed: missing language\");\n }\n return { id: ok.id, language: ok.language };\n }\n\n async getContext(contextId: string): Promise<CodeContext> {\n if (!contextId?.trim()) {\n throw new InvalidArgumentException({ message: \"contextId cannot be empty\" });\n }\n const { data, error, response } = await this.client.GET(\"/code/contexts/{context_id}\", {\n params: { path: { context_id: contextId } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Get code context failed\");\n const ok = data as ApiGetContextOk | undefined;\n if (!ok || typeof ok !== \"object\") {\n throw new Error(\"Get code context failed: unexpected response shape\");\n }\n if (typeof (ok as any).language !== \"string\" || !(ok as any).language) {\n throw new Error(\"Get code context failed: missing language\");\n }\n return { id: (ok as any).id, language: (ok as any).language };\n }\n\n async listContexts(language?: SupportedLanguage): Promise<CodeContext[]> {\n const { data, error, response } = await this.client.GET(\"/code/contexts\", {\n params: language ? { query: { language } } : undefined,\n } as any);\n throwOnOpenApiFetchError({ error, response }, \"List code contexts failed\");\n const ok = data as ApiListContextsOk | undefined;\n if (!Array.isArray(ok)) {\n throw new Error(\"List code contexts failed: unexpected response shape\");\n }\n return ok\n .filter((c) => c && typeof c === \"object\")\n .map((c: any) => ({ id: c.id, language: c.language as any }));\n }\n\n async deleteContext(contextId: string): Promise<void> {\n if (!contextId?.trim()) {\n throw new InvalidArgumentException({ message: \"contextId cannot be empty\" });\n }\n const { error, response } = await this.client.DELETE(\"/code/contexts/{context_id}\", {\n params: { path: { context_id: contextId } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Delete code context failed\");\n }\n\n async deleteContexts(language: SupportedLanguage): Promise<void> {\n const { error, response } = await this.client.DELETE(\"/code/contexts\", {\n params: { query: { language } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Delete code contexts failed\");\n }\n\n async interrupt(contextId: string): Promise<void> {\n const { error, response } = await this.client.DELETE(\"/code\", {\n params: { query: { id: contextId } },\n });\n throwOnOpenApiFetchError({ error, response }, \"Interrupt code failed\");\n }\n\n async *runStream(req: ApiRunCodeRequest, signal?: AbortSignal): AsyncIterable<ServerStreamEvent> {\n const url = joinUrl(this.opts.baseUrl, \"/code\");\n const body = JSON.stringify(req);\n const res = await this.fetch(url, {\n method: \"POST\",\n headers: {\n \"accept\": \"text/event-stream\",\n \"content-type\": \"application/json\",\n ...(this.opts.headers ?? {}),\n },\n body,\n signal,\n });\n\n for await (const ev of parseJsonEventStream<ServerStreamEvent>(res, { fallbackErrorMessage: \"Run code failed\" })) {\n yield ev;\n }\n }\n\n async run(\n code: string,\n opts: { context?: CodeContext; language?: SupportedLanguage; handlers?: ExecutionHandlers; signal?: AbortSignal } = {},\n ): Promise<Execution> {\n if (!code.trim()) {\n throw new InvalidArgumentException({ message: \"Code cannot be empty\" });\n }\n\n if (opts.context && opts.language) {\n throw new InvalidArgumentException({ message: \"Provide either opts.context or opts.language, not both\" });\n }\n\n const context: CodeContext =\n opts.context ??\n (opts.language\n ? { language: opts.language }\n : { language: \"python\" });\n\n // Make the OpenAPI contract explicit so backend schema changes surface quickly.\n const req: ApiRunCodeRequest = {\n code,\n context: { id: context.id, language: context.language },\n };\n\n const execution: Execution = {\n logs: { stdout: [], stderr: [] },\n result: [],\n };\n const dispatcher = new ExecutionEventDispatcher(execution, opts.handlers);\n\n for await (const ev of this.runStream(req, opts.signal)) {\n await dispatcher.dispatch(ev as any);\n }\n\n return execution;\n }\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { SandboxApiException, SandboxError } from \"@alibaba-group/opensandbox\";\n\nexport function throwOnOpenApiFetchError(\n result: { error?: unknown; response: Response },\n fallbackMessage: string,\n): void {\n if (!result.error) return;\n\n const requestId = result.response.headers.get(\"x-request-id\") ?? undefined;\n const status = (result.response as any).status ?? 0;\n\n const err = result.error as any;\n const message =\n err?.message ??\n err?.error?.message ??\n fallbackMessage;\n\n const code = err?.code ?? err?.error?.code;\n const msg = err?.message ?? err?.error?.message ?? message;\n\n throw new SandboxApiException({\n message: msg,\n statusCode: status,\n requestId,\n error: code\n ? new SandboxError(String(code), String(msg ?? \"\"))\n : new SandboxError(SandboxError.UNEXPECTED_RESPONSE, String(msg ?? \"\")),\n rawBody: result.error,\n });\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { SandboxApiException, SandboxError } from \"@alibaba-group/opensandbox\";\n\nfunction tryParseJson(line: string): unknown | undefined {\n try {\n return JSON.parse(line);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Parses an SSE-like stream that may be either:\n * - standard SSE frames (`data: {...}\\n\\n`)\n * - newline-delimited JSON (one JSON object per line)\n */\nexport async function* parseJsonEventStream<T>(\n res: Response,\n opts?: { fallbackErrorMessage?: string },\n): AsyncIterable<T> {\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n const parsed = tryParseJson(text);\n const err = parsed && typeof parsed === \"object\" ? (parsed as any) : undefined;\n const requestId = res.headers.get(\"x-request-id\") ?? undefined;\n const message = err?.message ?? opts?.fallbackErrorMessage ?? `Stream request failed (status=${res.status})`;\n const code = err?.code ? String(err.code) : SandboxError.UNEXPECTED_RESPONSE;\n throw new SandboxApiException({\n message,\n statusCode: res.status,\n requestId,\n error: new SandboxError(code, err?.message ? String(err.message) : message),\n rawBody: parsed ?? text,\n });\n }\n\n if (!res.body) return;\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder(\"utf-8\");\n let buf = \"\";\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n\n buf += decoder.decode(value, { stream: true });\n let idx: number;\n\n while ((idx = buf.indexOf(\"\\n\")) >= 0) {\n const rawLine = buf.slice(0, idx);\n buf = buf.slice(idx + 1);\n\n const line = rawLine.trim();\n if (!line) continue;\n\n // Support standard SSE \"data:\" prefix\n if (line.startsWith(\":\")) continue;\n if (line.startsWith(\"event:\") || line.startsWith(\"id:\") || line.startsWith(\"retry:\")) continue;\n\n const jsonLine = line.startsWith(\"data:\") ? line.slice(\"data:\".length).trim() : line;\n if (!jsonLine) continue;\n\n const parsed = tryParseJson(jsonLine);\n if (!parsed) continue;\n yield parsed as T;\n }\n }\n\n // flush last line if exists\n const last = buf.trim();\n if (last) {\n const jsonLine = last.startsWith(\"data:\") ? last.slice(\"data:\".length).trim() : last;\n const parsed = tryParseJson(jsonLine);\n if (parsed) yield parsed as T;\n }\n}","// Copyright 2026 Alibaba Group Holding Ltd.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport const SupportedLanguage = {\n PYTHON: \"python\",\n JAVA: \"java\",\n GO: \"go\",\n TYPESCRIPT: \"typescript\",\n JAVASCRIPT: \"javascript\",\n BASH: \"bash\",\n} as const;\n\nexport type SupportedLanguage =\n (typeof SupportedLanguage)[keyof typeof SupportedLanguage];\n\nexport interface CodeContext {\n id?: string;\n language: SupportedLanguage | (string & {});\n}\n\nexport interface RunCodeRequest {\n code: string;\n context: CodeContext;\n}"],"mappings":";AAcA,SAAS,0BAA0B;;;ACAnC,SAAS,yBAAyB;;;ACGlC;AAAA,EACE;AAAA,EACA;AAAA,OACK;;;ACNP,SAAS,qBAAqB,oBAAoB;AAE3C,SAAS,yBACd,QACA,iBACM;AACN,MAAI,CAAC,OAAO,MAAO;AAEnB,QAAM,YAAY,OAAO,SAAS,QAAQ,IAAI,cAAc,KAAK;AACjE,QAAM,SAAU,OAAO,S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Exception","SandboxError"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alibaba-group/opensandbox-code-interpreter",
|
|
3
|
-
"version": "0.1.3
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "OpenSandbox Code Interpreter TypeScript/JavaScript SDK",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"bugs": {
|
|
24
24
|
"url": "https://github.com/alibaba/OpenSandbox/issues"
|
|
25
25
|
},
|
|
26
|
-
"homepage": "https://
|
|
26
|
+
"homepage": "https://open-sandbox.ai",
|
|
27
27
|
"files": [
|
|
28
28
|
"dist",
|
|
29
29
|
"src"
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"node": ">=20"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@alibaba-group/opensandbox": "^0.1.
|
|
35
|
+
"@alibaba-group/opensandbox": "^0.1.5"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
38
|
"@eslint/js": "^9.39.2",
|
|
@@ -43,6 +43,7 @@
|
|
|
43
43
|
},
|
|
44
44
|
"scripts": {
|
|
45
45
|
"build": "tsup",
|
|
46
|
+
"test": "pnpm run build && node --test tests/*.test.mjs",
|
|
46
47
|
"lint": "eslint src --max-warnings 0",
|
|
47
48
|
"clean": "rm -rf dist"
|
|
48
49
|
}
|
|
@@ -18,6 +18,7 @@ import type { Codes } from "../services/codes.js";
|
|
|
18
18
|
export interface CreateCodesStackOptions {
|
|
19
19
|
sandbox: Sandbox;
|
|
20
20
|
execdBaseUrl: string;
|
|
21
|
+
endpointHeaders?: Record<string, string>;
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
/**
|
|
@@ -25,4 +26,4 @@ export interface CreateCodesStackOptions {
|
|
|
25
26
|
*/
|
|
26
27
|
export interface AdapterFactory {
|
|
27
28
|
createCodes(opts: CreateCodesStackOptions): Codes;
|
|
28
|
-
}
|
|
29
|
+
}
|
|
@@ -19,15 +19,19 @@ import type { Codes } from "../services/codes.js";
|
|
|
19
19
|
|
|
20
20
|
export class DefaultAdapterFactory implements AdapterFactory {
|
|
21
21
|
createCodes(opts: CreateCodesStackOptions): Codes {
|
|
22
|
+
const headers: Record<string, string> = {
|
|
23
|
+
...(opts.sandbox.connectionConfig.headers ?? {}),
|
|
24
|
+
...(opts.endpointHeaders ?? {}),
|
|
25
|
+
};
|
|
22
26
|
const client = createExecdClient({
|
|
23
27
|
baseUrl: opts.execdBaseUrl,
|
|
24
|
-
headers
|
|
28
|
+
headers,
|
|
25
29
|
fetch: opts.sandbox.connectionConfig.fetch,
|
|
26
30
|
});
|
|
27
31
|
|
|
28
32
|
return new CodesAdapter(client, {
|
|
29
33
|
baseUrl: opts.execdBaseUrl,
|
|
30
|
-
headers
|
|
34
|
+
headers,
|
|
31
35
|
// Streaming calls (SSE) use a dedicated fetch, aligned with Kotlin/Python SDKs.
|
|
32
36
|
fetch: opts.sandbox.connectionConfig.sseFetch,
|
|
33
37
|
});
|
|
@@ -36,4 +40,4 @@ export class DefaultAdapterFactory implements AdapterFactory {
|
|
|
36
40
|
|
|
37
41
|
export function createDefaultAdapterFactory(): AdapterFactory {
|
|
38
42
|
return new DefaultAdapterFactory();
|
|
39
|
-
}
|
|
43
|
+
}
|
package/src/interpreter.ts
CHANGED
|
@@ -39,9 +39,14 @@ export class CodeInterpreter {
|
|
|
39
39
|
) {}
|
|
40
40
|
|
|
41
41
|
static async create(sandbox: Sandbox, opts: CodeInterpreterCreateOptions = {}): Promise<CodeInterpreter> {
|
|
42
|
-
const
|
|
42
|
+
const endpoint = await sandbox.getEndpoint(DEFAULT_EXECD_PORT);
|
|
43
|
+
const execdBaseUrl = `${sandbox.connectionConfig.protocol}://${endpoint.endpoint}`;
|
|
43
44
|
const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();
|
|
44
|
-
const codes = adapterFactory.createCodes({
|
|
45
|
+
const codes = adapterFactory.createCodes({
|
|
46
|
+
sandbox,
|
|
47
|
+
execdBaseUrl,
|
|
48
|
+
endpointHeaders: endpoint.headers,
|
|
49
|
+
});
|
|
45
50
|
|
|
46
51
|
return new CodeInterpreter(sandbox, codes);
|
|
47
52
|
}
|
|
@@ -61,4 +66,4 @@ export class CodeInterpreter {
|
|
|
61
66
|
get metrics() {
|
|
62
67
|
return this.sandbox.metrics;
|
|
63
68
|
}
|
|
64
|
-
}
|
|
69
|
+
}
|