@alibaba-group/opensandbox-code-interpreter 0.1.1 → 0.1.2-dev0

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.
Files changed (39) hide show
  1. package/dist/cjs/index.cjs +294 -0
  2. package/dist/cjs/index.cjs.map +1 -0
  3. package/dist/index.d.ts +90 -9
  4. package/dist/index.js +266 -16
  5. package/dist/index.js.map +1 -1
  6. package/package.json +6 -3
  7. package/dist/adapters/codesAdapter.d.ts +0 -31
  8. package/dist/adapters/codesAdapter.d.ts.map +0 -1
  9. package/dist/adapters/codesAdapter.js +0 -147
  10. package/dist/adapters/codesAdapter.js.map +0 -1
  11. package/dist/adapters/openapiError.d.ts +0 -5
  12. package/dist/adapters/openapiError.d.ts.map +0 -1
  13. package/dist/adapters/openapiError.js +0 -36
  14. package/dist/adapters/openapiError.js.map +0 -1
  15. package/dist/adapters/sse.d.ts +0 -9
  16. package/dist/adapters/sse.d.ts.map +0 -1
  17. package/dist/adapters/sse.js +0 -84
  18. package/dist/adapters/sse.js.map +0 -1
  19. package/dist/factory/adapterFactory.d.ts +0 -13
  20. package/dist/factory/adapterFactory.d.ts.map +0 -1
  21. package/dist/factory/adapterFactory.js +0 -15
  22. package/dist/factory/adapterFactory.js.map +0 -1
  23. package/dist/factory/defaultAdapterFactory.d.ts +0 -7
  24. package/dist/factory/defaultAdapterFactory.d.ts.map +0 -1
  25. package/dist/factory/defaultAdapterFactory.js +0 -34
  26. package/dist/factory/defaultAdapterFactory.js.map +0 -1
  27. package/dist/index.d.ts.map +0 -1
  28. package/dist/interpreter.d.ts +0 -26
  29. package/dist/interpreter.d.ts.map +0 -1
  30. package/dist/interpreter.js +0 -51
  31. package/dist/interpreter.js.map +0 -1
  32. package/dist/models.d.ts +0 -18
  33. package/dist/models.d.ts.map +0 -1
  34. package/dist/models.js +0 -22
  35. package/dist/models.js.map +0 -1
  36. package/dist/services/codes.d.ts +0 -31
  37. package/dist/services/codes.d.ts.map +0 -1
  38. package/dist/services/codes.js +0 -15
  39. package/dist/services/codes.js.map +0 -1
@@ -0,0 +1,294 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ CodeInterpreter: () => CodeInterpreter,
24
+ DefaultAdapterFactory: () => DefaultAdapterFactory,
25
+ SupportedLanguages: () => SupportedLanguage,
26
+ createDefaultAdapterFactory: () => createDefaultAdapterFactory
27
+ });
28
+ module.exports = __toCommonJS(index_exports);
29
+
30
+ // src/interpreter.ts
31
+ var import_opensandbox4 = require("@alibaba-group/opensandbox");
32
+
33
+ // src/factory/defaultAdapterFactory.ts
34
+ var import_internal = require("@alibaba-group/opensandbox/internal");
35
+
36
+ // src/adapters/codesAdapter.ts
37
+ var import_opensandbox3 = require("@alibaba-group/opensandbox");
38
+
39
+ // src/adapters/openapiError.ts
40
+ var import_opensandbox = require("@alibaba-group/opensandbox");
41
+ function throwOnOpenApiFetchError(result, fallbackMessage) {
42
+ if (!result.error) return;
43
+ const requestId = result.response.headers.get("x-request-id") ?? void 0;
44
+ const status = result.response.status ?? 0;
45
+ const err = result.error;
46
+ const message = err?.message ?? err?.error?.message ?? fallbackMessage;
47
+ const code = err?.code ?? err?.error?.code;
48
+ const msg = err?.message ?? err?.error?.message ?? message;
49
+ throw new import_opensandbox.SandboxApiException({
50
+ message: msg,
51
+ statusCode: status,
52
+ requestId,
53
+ error: code ? new import_opensandbox.SandboxError(String(code), String(msg ?? "")) : new import_opensandbox.SandboxError(import_opensandbox.SandboxError.UNEXPECTED_RESPONSE, String(msg ?? "")),
54
+ rawBody: result.error
55
+ });
56
+ }
57
+
58
+ // src/adapters/sse.ts
59
+ var import_opensandbox2 = require("@alibaba-group/opensandbox");
60
+ function tryParseJson(line) {
61
+ try {
62
+ return JSON.parse(line);
63
+ } catch {
64
+ return void 0;
65
+ }
66
+ }
67
+ async function* parseJsonEventStream(res, opts) {
68
+ if (!res.ok) {
69
+ const text = await res.text().catch(() => "");
70
+ const parsed = tryParseJson(text);
71
+ const err = parsed && typeof parsed === "object" ? parsed : void 0;
72
+ const requestId = res.headers.get("x-request-id") ?? void 0;
73
+ const message = err?.message ?? opts?.fallbackErrorMessage ?? `Stream request failed (status=${res.status})`;
74
+ const code = err?.code ? String(err.code) : import_opensandbox2.SandboxError.UNEXPECTED_RESPONSE;
75
+ throw new import_opensandbox2.SandboxApiException({
76
+ message,
77
+ statusCode: res.status,
78
+ requestId,
79
+ error: new import_opensandbox2.SandboxError(code, err?.message ? String(err.message) : message),
80
+ rawBody: parsed ?? text
81
+ });
82
+ }
83
+ if (!res.body) return;
84
+ const reader = res.body.getReader();
85
+ const decoder = new TextDecoder("utf-8");
86
+ let buf = "";
87
+ while (true) {
88
+ const { value, done } = await reader.read();
89
+ if (done) break;
90
+ buf += decoder.decode(value, { stream: true });
91
+ let idx;
92
+ while ((idx = buf.indexOf("\n")) >= 0) {
93
+ const rawLine = buf.slice(0, idx);
94
+ buf = buf.slice(idx + 1);
95
+ const line = rawLine.trim();
96
+ if (!line) continue;
97
+ if (line.startsWith(":")) continue;
98
+ if (line.startsWith("event:") || line.startsWith("id:") || line.startsWith("retry:")) continue;
99
+ const jsonLine = line.startsWith("data:") ? line.slice("data:".length).trim() : line;
100
+ if (!jsonLine) continue;
101
+ const parsed = tryParseJson(jsonLine);
102
+ if (!parsed) continue;
103
+ yield parsed;
104
+ }
105
+ }
106
+ const last = buf.trim();
107
+ if (last) {
108
+ const jsonLine = last.startsWith("data:") ? last.slice("data:".length).trim() : last;
109
+ const parsed = tryParseJson(jsonLine);
110
+ if (parsed) yield parsed;
111
+ }
112
+ }
113
+
114
+ // src/adapters/codesAdapter.ts
115
+ function joinUrl(baseUrl, pathname) {
116
+ const base = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
117
+ const path = pathname.startsWith("/") ? pathname : `/${pathname}`;
118
+ return `${base}${path}`;
119
+ }
120
+ var CodesAdapter = class {
121
+ constructor(client, opts) {
122
+ this.client = client;
123
+ this.opts = opts;
124
+ this.fetch = opts.fetch ?? fetch;
125
+ }
126
+ fetch;
127
+ async createContext(language) {
128
+ const body = { language };
129
+ const { data, error, response } = await this.client.POST("/code/context", {
130
+ body
131
+ });
132
+ throwOnOpenApiFetchError({ error, response }, "Create code context failed");
133
+ const ok = data;
134
+ if (!ok || typeof ok !== "object") {
135
+ throw new Error("Create code context failed: unexpected response shape");
136
+ }
137
+ if (typeof ok.language !== "string" || !ok.language) {
138
+ throw new Error("Create code context failed: missing language");
139
+ }
140
+ return { id: ok.id, language: ok.language };
141
+ }
142
+ async getContext(contextId) {
143
+ if (!contextId?.trim()) {
144
+ throw new import_opensandbox3.InvalidArgumentException({ message: "contextId cannot be empty" });
145
+ }
146
+ const { data, error, response } = await this.client.GET("/code/contexts/{context_id}", {
147
+ params: { path: { context_id: contextId } }
148
+ });
149
+ throwOnOpenApiFetchError({ error, response }, "Get code context failed");
150
+ const ok = data;
151
+ if (!ok || typeof ok !== "object") {
152
+ throw new Error("Get code context failed: unexpected response shape");
153
+ }
154
+ if (typeof ok.language !== "string" || !ok.language) {
155
+ throw new Error("Get code context failed: missing language");
156
+ }
157
+ return { id: ok.id, language: ok.language };
158
+ }
159
+ async listContexts(language) {
160
+ const { data, error, response } = await this.client.GET("/code/contexts", {
161
+ params: language ? { query: { language } } : void 0
162
+ });
163
+ throwOnOpenApiFetchError({ error, response }, "List code contexts failed");
164
+ const ok = data;
165
+ if (!Array.isArray(ok)) {
166
+ throw new Error("List code contexts failed: unexpected response shape");
167
+ }
168
+ return ok.filter((c) => c && typeof c === "object").map((c) => ({ id: c.id, language: c.language }));
169
+ }
170
+ async deleteContext(contextId) {
171
+ if (!contextId?.trim()) {
172
+ throw new import_opensandbox3.InvalidArgumentException({ message: "contextId cannot be empty" });
173
+ }
174
+ const { error, response } = await this.client.DELETE("/code/contexts/{context_id}", {
175
+ params: { path: { context_id: contextId } }
176
+ });
177
+ throwOnOpenApiFetchError({ error, response }, "Delete code context failed");
178
+ }
179
+ async deleteContexts(language) {
180
+ const { error, response } = await this.client.DELETE("/code/contexts", {
181
+ params: { query: { language } }
182
+ });
183
+ throwOnOpenApiFetchError({ error, response }, "Delete code contexts failed");
184
+ }
185
+ async interrupt(contextId) {
186
+ const { error, response } = await this.client.DELETE("/code", {
187
+ params: { query: { id: contextId } }
188
+ });
189
+ throwOnOpenApiFetchError({ error, response }, "Interrupt code failed");
190
+ }
191
+ async *runStream(req, signal) {
192
+ const url = joinUrl(this.opts.baseUrl, "/code");
193
+ const body = JSON.stringify(req);
194
+ const res = await this.fetch(url, {
195
+ method: "POST",
196
+ headers: {
197
+ "accept": "text/event-stream",
198
+ "content-type": "application/json",
199
+ ...this.opts.headers ?? {}
200
+ },
201
+ body,
202
+ signal
203
+ });
204
+ for await (const ev of parseJsonEventStream(res, { fallbackErrorMessage: "Run code failed" })) {
205
+ yield ev;
206
+ }
207
+ }
208
+ async run(code, opts = {}) {
209
+ if (!code.trim()) {
210
+ throw new import_opensandbox3.InvalidArgumentException({ message: "Code cannot be empty" });
211
+ }
212
+ if (opts.context && opts.language) {
213
+ throw new import_opensandbox3.InvalidArgumentException({ message: "Provide either opts.context or opts.language, not both" });
214
+ }
215
+ const context = opts.context ?? (opts.language ? { language: opts.language } : { language: "python" });
216
+ const req = {
217
+ code,
218
+ context: { id: context.id, language: context.language }
219
+ };
220
+ const execution = {
221
+ logs: { stdout: [], stderr: [] },
222
+ result: []
223
+ };
224
+ const dispatcher = new import_opensandbox3.ExecutionEventDispatcher(execution, opts.handlers);
225
+ for await (const ev of this.runStream(req, opts.signal)) {
226
+ await dispatcher.dispatch(ev);
227
+ }
228
+ return execution;
229
+ }
230
+ };
231
+
232
+ // src/factory/defaultAdapterFactory.ts
233
+ var DefaultAdapterFactory = class {
234
+ createCodes(opts) {
235
+ const client = (0, import_internal.createExecdClient)({
236
+ baseUrl: opts.execdBaseUrl,
237
+ headers: opts.sandbox.connectionConfig.headers,
238
+ fetch: opts.sandbox.connectionConfig.fetch
239
+ });
240
+ return new CodesAdapter(client, {
241
+ baseUrl: opts.execdBaseUrl,
242
+ headers: opts.sandbox.connectionConfig.headers,
243
+ // Streaming calls (SSE) use a dedicated fetch, aligned with Kotlin/Python SDKs.
244
+ fetch: opts.sandbox.connectionConfig.sseFetch
245
+ });
246
+ }
247
+ };
248
+ function createDefaultAdapterFactory() {
249
+ return new DefaultAdapterFactory();
250
+ }
251
+
252
+ // src/interpreter.ts
253
+ var CodeInterpreter = class _CodeInterpreter {
254
+ constructor(sandbox, codes) {
255
+ this.sandbox = sandbox;
256
+ this.codes = codes;
257
+ }
258
+ static async create(sandbox, opts = {}) {
259
+ const execdBaseUrl = await sandbox.getEndpointUrl(import_opensandbox4.DEFAULT_EXECD_PORT);
260
+ const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();
261
+ const codes = adapterFactory.createCodes({ sandbox, execdBaseUrl });
262
+ return new _CodeInterpreter(sandbox, codes);
263
+ }
264
+ get id() {
265
+ return this.sandbox.id;
266
+ }
267
+ get files() {
268
+ return this.sandbox.files;
269
+ }
270
+ get commands() {
271
+ return this.sandbox.commands;
272
+ }
273
+ get metrics() {
274
+ return this.sandbox.metrics;
275
+ }
276
+ };
277
+
278
+ // src/models.ts
279
+ var SupportedLanguage = {
280
+ PYTHON: "python",
281
+ JAVA: "java",
282
+ GO: "go",
283
+ TYPESCRIPT: "typescript",
284
+ JAVASCRIPT: "javascript",
285
+ BASH: "bash"
286
+ };
287
+ // Annotate the CommonJS export names for ESM import in node:
288
+ 0 && (module.exports = {
289
+ CodeInterpreter,
290
+ DefaultAdapterFactory,
291
+ SupportedLanguages,
292
+ createDefaultAdapterFactory
293
+ });
294
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +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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]}
package/dist/index.d.ts CHANGED
@@ -1,9 +1,90 @@
1
- export { CodeInterpreter } from "./interpreter.js";
2
- export type { CodeInterpreterCreateOptions } from "./interpreter.js";
3
- export type { AdapterFactory } from "./factory/adapterFactory.js";
4
- export { DefaultAdapterFactory, createDefaultAdapterFactory } from "./factory/defaultAdapterFactory.js";
5
- export type { CodeContext, SupportedLanguage } from "./models.js";
6
- export { SupportedLanguage as SupportedLanguages } from "./models.js";
7
- export type { Codes } from "./services/codes.js";
8
- export type { Execution, ExecutionComplete, ExecutionError, ExecutionHandlers, ExecutionInit, ExecutionResult, OutputMessage, } from "@alibaba-group/opensandbox";
9
- //# sourceMappingURL=index.d.ts.map
1
+ import * as _alibaba_group_opensandbox from '@alibaba-group/opensandbox';
2
+ import { ExecutionHandlers, Execution, ServerStreamEvent, Sandbox } from '@alibaba-group/opensandbox';
3
+ export { Execution, ExecutionComplete, ExecutionError, ExecutionHandlers, ExecutionInit, ExecutionResult, OutputMessage } from '@alibaba-group/opensandbox';
4
+
5
+ declare const SupportedLanguage: {
6
+ readonly PYTHON: "python";
7
+ readonly JAVA: "java";
8
+ readonly GO: "go";
9
+ readonly TYPESCRIPT: "typescript";
10
+ readonly JAVASCRIPT: "javascript";
11
+ readonly BASH: "bash";
12
+ };
13
+ type SupportedLanguage = (typeof SupportedLanguage)[keyof typeof SupportedLanguage];
14
+ interface CodeContext {
15
+ id?: string;
16
+ language: SupportedLanguage | (string & {});
17
+ }
18
+ interface RunCodeRequest {
19
+ code: string;
20
+ context: CodeContext;
21
+ }
22
+
23
+ interface Codes {
24
+ createContext(language: SupportedLanguage): Promise<CodeContext>;
25
+ /**
26
+ * Get an existing context by id.
27
+ */
28
+ getContext(contextId: string): Promise<CodeContext>;
29
+ /**
30
+ * List active contexts. If language is provided, filters by language/runtime.
31
+ */
32
+ listContexts(language?: SupportedLanguage): Promise<CodeContext[]>;
33
+ /**
34
+ * Delete a context by id.
35
+ */
36
+ deleteContext(contextId: string): Promise<void>;
37
+ /**
38
+ * Delete all contexts under the specified language/runtime.
39
+ */
40
+ deleteContexts(language: SupportedLanguage): Promise<void>;
41
+ run(code: string, opts?: {
42
+ context?: CodeContext;
43
+ language?: SupportedLanguage;
44
+ handlers?: ExecutionHandlers;
45
+ signal?: AbortSignal;
46
+ }): Promise<Execution>;
47
+ runStream(req: RunCodeRequest, signal?: AbortSignal): AsyncIterable<ServerStreamEvent>;
48
+ interrupt(contextId: string): Promise<void>;
49
+ }
50
+
51
+ interface CreateCodesStackOptions {
52
+ sandbox: Sandbox;
53
+ execdBaseUrl: string;
54
+ }
55
+ /**
56
+ * Factory abstraction for Code Interpreter SDK to decouple from concrete adapters/clients.
57
+ */
58
+ interface AdapterFactory {
59
+ createCodes(opts: CreateCodesStackOptions): Codes;
60
+ }
61
+
62
+ interface CodeInterpreterCreateOptions {
63
+ adapterFactory?: AdapterFactory;
64
+ }
65
+ /**
66
+ * Code interpreter facade (JS/TS).
67
+ *
68
+ * This class wraps an existing {@link Sandbox} and provides a high-level API for code execution.
69
+ *
70
+ * - Use {@link codes} to create contexts and run code.
71
+ * - {@link files}, {@link commands}, and {@link metrics} are exposed for convenience and are
72
+ * the same instances as on the underlying {@link Sandbox}.
73
+ */
74
+ declare class CodeInterpreter {
75
+ readonly sandbox: Sandbox;
76
+ readonly codes: Codes;
77
+ private constructor();
78
+ static create(sandbox: Sandbox, opts?: CodeInterpreterCreateOptions): Promise<CodeInterpreter>;
79
+ get id(): string;
80
+ get files(): _alibaba_group_opensandbox.SandboxFiles;
81
+ get commands(): _alibaba_group_opensandbox.ExecdCommands;
82
+ get metrics(): _alibaba_group_opensandbox.ExecdMetrics;
83
+ }
84
+
85
+ declare class DefaultAdapterFactory implements AdapterFactory {
86
+ createCodes(opts: CreateCodesStackOptions): Codes;
87
+ }
88
+ declare function createDefaultAdapterFactory(): AdapterFactory;
89
+
90
+ export { type AdapterFactory, type CodeContext, CodeInterpreter, type CodeInterpreterCreateOptions, type Codes, DefaultAdapterFactory, SupportedLanguage, SupportedLanguage as SupportedLanguages, createDefaultAdapterFactory };