@blaxel/core 0.2.49-preview.111 → 0.2.49

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.
@@ -36,4 +36,5 @@ __exportStar(require("./filesystem/index.js"), exports);
36
36
  __exportStar(require("./codegen/index.js"), exports);
37
37
  __exportStar(require("./sandbox.js"), exports);
38
38
  __exportStar(require("./types.js"), exports);
39
+ __exportStar(require("./interpreter.js"), exports);
39
40
  // Re-export everything from client except ClientOptions to avoid conflict
@@ -0,0 +1,400 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CodeInterpreter = void 0;
4
+ const logger_js_1 = require("../common/logger.js");
5
+ const settings_js_1 = require("../common/settings.js");
6
+ const sandbox_js_1 = require("./sandbox.js");
7
+ class CodeInterpreter extends sandbox_js_1.SandboxInstance {
8
+ static DEFAULT_IMAGE = "blaxel/jupyter-server";
9
+ static DEFAULT_PORTS = [
10
+ { name: "jupyter", target: 8888, protocol: "HTTP" },
11
+ ];
12
+ static DEFAULT_LIFECYCLE = {
13
+ expirationPolicies: [{ type: "ttl-idle", value: "30m", action: "delete" }],
14
+ };
15
+ _sandboxConfig;
16
+ constructor(sandbox) {
17
+ super(sandbox);
18
+ this._sandboxConfig = sandbox;
19
+ }
20
+ static async get(sandboxName) {
21
+ const base = await sandbox_js_1.SandboxInstance.get(sandboxName);
22
+ // Create a minimal config - the base instance already has the sandbox data
23
+ // We'll rely on the process property for URL/headers access
24
+ const config = {
25
+ metadata: base.metadata,
26
+ spec: base.spec,
27
+ status: base.status,
28
+ events: base.events,
29
+ };
30
+ return new CodeInterpreter(config);
31
+ }
32
+ static async create(sandbox, { safe = true } = {}) {
33
+ const payload = {
34
+ image: CodeInterpreter.DEFAULT_IMAGE,
35
+ ports: CodeInterpreter.DEFAULT_PORTS,
36
+ lifecycle: CodeInterpreter.DEFAULT_LIFECYCLE,
37
+ };
38
+ const allowedCopyKeys = new Set(["name", "envs", "memory", "region", "headers"]);
39
+ if (sandbox && typeof sandbox === "object") {
40
+ if (Array.isArray(sandbox)) {
41
+ // Skip arrays
42
+ }
43
+ else if ("metadata" in sandbox || "spec" in sandbox) {
44
+ // It's a Sandbox object
45
+ const sandboxObj = sandbox;
46
+ if (sandboxObj.metadata?.name) {
47
+ payload["name"] = sandboxObj.metadata.name;
48
+ }
49
+ if (sandboxObj.spec?.runtime) {
50
+ if (sandboxObj.spec.runtime.envs) {
51
+ payload["envs"] = sandboxObj.spec.runtime.envs;
52
+ }
53
+ if (sandboxObj.spec.runtime.memory) {
54
+ payload["memory"] = sandboxObj.spec.runtime.memory;
55
+ }
56
+ }
57
+ if (sandboxObj.spec?.region) {
58
+ payload["region"] = sandboxObj.spec.region;
59
+ }
60
+ }
61
+ else if ("name" in sandbox || "image" in sandbox || "memory" in sandbox) {
62
+ // It's a SandboxCreateConfiguration or dict-like object
63
+ const sandboxDict = sandbox;
64
+ for (const k of allowedCopyKeys) {
65
+ const value = sandboxDict[k];
66
+ if (value !== null && value !== undefined) {
67
+ payload[k] = value;
68
+ }
69
+ }
70
+ }
71
+ }
72
+ const baseInstance = await sandbox_js_1.SandboxInstance.create(payload, { safe });
73
+ // Create config from the instance - preserve any forceUrl/headers if provided in input
74
+ const config = {
75
+ metadata: baseInstance.metadata,
76
+ spec: baseInstance.spec,
77
+ status: baseInstance.status,
78
+ events: baseInstance.events,
79
+ };
80
+ // Preserve forceUrl and headers from input if it was a dict-like object
81
+ if (sandbox && typeof sandbox === "object" && !Array.isArray(sandbox)) {
82
+ if ("forceUrl" in sandbox && typeof sandbox.forceUrl === "string") {
83
+ config.forceUrl = sandbox.forceUrl;
84
+ }
85
+ if ("headers" in sandbox && typeof sandbox.headers === "object") {
86
+ config.headers = sandbox.headers;
87
+ }
88
+ if ("params" in sandbox && typeof sandbox.params === "object") {
89
+ config.params = sandbox.params;
90
+ }
91
+ }
92
+ return new CodeInterpreter(config);
93
+ }
94
+ get _jupyterUrl() {
95
+ return this.process.url;
96
+ }
97
+ static OutputMessage = class {
98
+ text;
99
+ timestamp;
100
+ isStderr;
101
+ constructor(text, timestamp, isStderr) {
102
+ this.text = text;
103
+ this.timestamp = timestamp;
104
+ this.isStderr = isStderr;
105
+ }
106
+ };
107
+ static Result = class {
108
+ constructor(kwargs = {}) {
109
+ for (const [k, v] of Object.entries(kwargs)) {
110
+ this[k] = v;
111
+ }
112
+ }
113
+ };
114
+ static ExecutionError = class {
115
+ name;
116
+ value;
117
+ traceback;
118
+ constructor(name, value, traceback) {
119
+ this.name = name;
120
+ this.value = value;
121
+ this.traceback = traceback;
122
+ }
123
+ };
124
+ static Logs = class {
125
+ stdout = [];
126
+ stderr = [];
127
+ };
128
+ static Execution = class {
129
+ results = [];
130
+ logs = new CodeInterpreter.Logs();
131
+ error = null;
132
+ executionCount = null;
133
+ };
134
+ static Context = class {
135
+ id;
136
+ constructor(id) {
137
+ this.id = id;
138
+ }
139
+ static fromJson(data) {
140
+ return new CodeInterpreter.Context(String(data.id || data.context_id || ""));
141
+ }
142
+ };
143
+ _parseOutput(execution, output, onStdout, onStderr, onResult, onError) {
144
+ let data;
145
+ try {
146
+ data = JSON.parse(output);
147
+ }
148
+ catch {
149
+ // Fallback: treat as stdout text-only message
150
+ execution.logs.stdout.push(output);
151
+ if (onStdout) {
152
+ return onStdout(new CodeInterpreter.OutputMessage(output, null, false));
153
+ }
154
+ return null;
155
+ }
156
+ let dataType = "";
157
+ if (typeof data.type === "string") {
158
+ dataType = data.type;
159
+ }
160
+ else if (data.type !== null &&
161
+ data.type !== undefined &&
162
+ typeof data.type !== "object") {
163
+ const typeValue = data.type;
164
+ dataType = String(typeValue);
165
+ }
166
+ const restData = { ...data };
167
+ delete restData.type;
168
+ if (dataType === "result") {
169
+ const result = new CodeInterpreter.Result(restData);
170
+ execution.results.push(result);
171
+ if (onResult) {
172
+ return onResult(result);
173
+ }
174
+ }
175
+ else if (dataType === "stdout") {
176
+ let text = "";
177
+ if (typeof data.text === "string") {
178
+ text = data.text;
179
+ }
180
+ else if (data.text !== null &&
181
+ data.text !== undefined &&
182
+ typeof data.text !== "object") {
183
+ const textValue = data.text;
184
+ text = String(textValue);
185
+ }
186
+ execution.logs.stdout.push(text);
187
+ if (onStdout) {
188
+ return onStdout(new CodeInterpreter.OutputMessage(text, typeof data.timestamp === "number" ? data.timestamp : null, false));
189
+ }
190
+ }
191
+ else if (dataType === "stderr") {
192
+ let text = "";
193
+ if (typeof data.text === "string") {
194
+ text = data.text;
195
+ }
196
+ else if (data.text !== null &&
197
+ data.text !== undefined &&
198
+ typeof data.text !== "object") {
199
+ const textValue = data.text;
200
+ text = String(textValue);
201
+ }
202
+ execution.logs.stderr.push(text);
203
+ if (onStderr) {
204
+ return onStderr(new CodeInterpreter.OutputMessage(text, typeof data.timestamp === "number" ? data.timestamp : null, true));
205
+ }
206
+ }
207
+ else if (dataType === "error") {
208
+ let errorName = "";
209
+ if (typeof data.name === "string") {
210
+ errorName = data.name;
211
+ }
212
+ else if (data.name !== null &&
213
+ data.name !== undefined &&
214
+ typeof data.name !== "object") {
215
+ const nameValue = data.name;
216
+ errorName = String(nameValue);
217
+ }
218
+ execution.error = new CodeInterpreter.ExecutionError(errorName, data.value, data.traceback);
219
+ if (onError) {
220
+ return onError(execution.error);
221
+ }
222
+ }
223
+ else if (dataType === "number_of_executions") {
224
+ execution.executionCount =
225
+ typeof data.execution_count === "number" ? data.execution_count : null;
226
+ }
227
+ return null;
228
+ }
229
+ async runCode(code, options = {}) {
230
+ const { language = null, context = null, onStdout, onStderr, onResult, onError, envs = null, timeout = null, } = options;
231
+ const DEFAULT_TIMEOUT = 60.0;
232
+ if (language && context) {
233
+ throw new Error("You can provide context or language, but not both at the same time.");
234
+ }
235
+ const readTimeout = timeout === 0 ? null : timeout ?? DEFAULT_TIMEOUT;
236
+ const contextId = context?.id ?? null;
237
+ const body = {
238
+ code,
239
+ context_id: contextId,
240
+ language,
241
+ env_vars: envs,
242
+ };
243
+ const execution = new CodeInterpreter.Execution();
244
+ const headers = this._sandboxConfig.forceUrl
245
+ ? this._sandboxConfig.headers
246
+ : settings_js_1.settings.headers;
247
+ const controller = new AbortController();
248
+ let timeoutId = null;
249
+ // Set up timeout
250
+ if (readTimeout !== null) {
251
+ timeoutId = setTimeout(() => {
252
+ controller.abort();
253
+ }, readTimeout * 1000);
254
+ }
255
+ try {
256
+ const response = await fetch(`${this._jupyterUrl}/port/8888/execute`, {
257
+ method: "POST",
258
+ headers: {
259
+ ...headers,
260
+ "Content-Type": "application/json",
261
+ },
262
+ body: JSON.stringify(body),
263
+ signal: controller.signal,
264
+ });
265
+ if (response.status >= 400) {
266
+ let bodyText = "<unavailable>";
267
+ try {
268
+ bodyText = await response.text();
269
+ }
270
+ catch {
271
+ // Ignore errors
272
+ }
273
+ const method = "POST";
274
+ const url = `${this._jupyterUrl}/port/8888/execute`;
275
+ const reason = response.statusText;
276
+ const details = "Execution failed\n" +
277
+ `- method: ${method}\n- url: ${url}\n- status: ${response.status} ${reason}\n` +
278
+ `- response-headers: ${JSON.stringify(Object.fromEntries(response.headers.entries()))}\n- body:\n${bodyText}`;
279
+ logger_js_1.logger.debug(details);
280
+ throw new Error(details);
281
+ }
282
+ if (!response.body) {
283
+ throw new Error("No response body");
284
+ }
285
+ const reader = response.body.getReader();
286
+ const decoder = new TextDecoder();
287
+ let buffer = "";
288
+ try {
289
+ while (true) {
290
+ const result = await reader.read();
291
+ if (result.done)
292
+ break;
293
+ const value = result.value;
294
+ if (value instanceof Uint8Array) {
295
+ buffer += decoder.decode(value, { stream: true });
296
+ const lines = buffer.split(/\r?\n/);
297
+ buffer = lines.pop() || "";
298
+ for (const line of lines) {
299
+ if (!line)
300
+ continue;
301
+ try {
302
+ this._parseOutput(execution, line, onStdout, onStderr, onResult, onError);
303
+ }
304
+ catch {
305
+ // Fallback: treat as stdout text-only message
306
+ execution.logs.stdout.push(line);
307
+ if (onStdout) {
308
+ onStdout(new CodeInterpreter.OutputMessage(line, null, false));
309
+ }
310
+ }
311
+ }
312
+ }
313
+ }
314
+ }
315
+ finally {
316
+ reader.releaseLock();
317
+ }
318
+ }
319
+ catch (error) {
320
+ if (error &&
321
+ typeof error === "object" &&
322
+ "name" in error &&
323
+ error.name === "AbortError") {
324
+ throw new Error("Request timeout");
325
+ }
326
+ throw error;
327
+ }
328
+ finally {
329
+ if (timeoutId) {
330
+ clearTimeout(timeoutId);
331
+ }
332
+ }
333
+ return execution;
334
+ }
335
+ async createCodeContext(options = {}) {
336
+ const { cwd = null, language = null, requestTimeout = null } = options;
337
+ const data = {};
338
+ if (language) {
339
+ data.language = language;
340
+ }
341
+ if (cwd) {
342
+ data.cwd = cwd;
343
+ }
344
+ const headers = this._sandboxConfig.forceUrl
345
+ ? this._sandboxConfig.headers
346
+ : settings_js_1.settings.headers;
347
+ const controller = new AbortController();
348
+ let timeoutId = null;
349
+ if (requestTimeout !== null) {
350
+ timeoutId = setTimeout(() => {
351
+ controller.abort();
352
+ }, requestTimeout * 1000);
353
+ }
354
+ try {
355
+ const response = await fetch(`${this._jupyterUrl}/port/8888/contexts`, {
356
+ method: "POST",
357
+ headers: {
358
+ ...headers,
359
+ "Content-Type": "application/json",
360
+ },
361
+ body: JSON.stringify(data),
362
+ signal: controller.signal,
363
+ });
364
+ if (response.status >= 400) {
365
+ let bodyText = "<unavailable>";
366
+ try {
367
+ bodyText = await response.text();
368
+ }
369
+ catch {
370
+ // Ignore errors
371
+ }
372
+ const method = "POST";
373
+ const url = `${this._jupyterUrl}/port/8888/contexts`;
374
+ const reason = response.statusText;
375
+ const details = "Create context failed\n" +
376
+ `- method: ${method}\n- url: ${url}\n- status: ${response.status} ${reason}\n` +
377
+ `- response-headers: ${JSON.stringify(Object.fromEntries(response.headers.entries()))}\n- body:\n${bodyText}`;
378
+ logger_js_1.logger.debug(details);
379
+ throw new Error(details);
380
+ }
381
+ const responseData = (await response.json());
382
+ return CodeInterpreter.Context.fromJson(responseData);
383
+ }
384
+ catch (error) {
385
+ if (error &&
386
+ typeof error === "object" &&
387
+ "name" in error &&
388
+ error.name === "AbortError") {
389
+ throw new Error("Request timeout");
390
+ }
391
+ throw error;
392
+ }
393
+ finally {
394
+ if (timeoutId) {
395
+ clearTimeout(timeoutId);
396
+ }
397
+ }
398
+ }
399
+ }
400
+ exports.CodeInterpreter = CodeInterpreter;
@@ -42,10 +42,6 @@ class McpTool {
42
42
  this.client = new index_js_1.Client({
43
43
  name: this.name,
44
44
  version: "1.0.0",
45
- }, {
46
- capabilities: {
47
- tools: {},
48
- },
49
45
  });
50
46
  }
51
47
  get fallbackUrl() {
@@ -3,3 +3,4 @@ export * from "./filesystem/index.js";
3
3
  export * from "./codegen/index.js";
4
4
  export * from "./sandbox.js";
5
5
  export * from "./types.js";
6
+ export * from "./interpreter.js";
@@ -0,0 +1,71 @@
1
+ import { Sandbox, SandboxLifecycle, Port } from "../client/types.gen.js";
2
+ import { SandboxInstance } from "./sandbox.js";
3
+ import { SandboxConfiguration, SandboxCreateConfiguration } from "./types.js";
4
+ export declare class CodeInterpreter extends SandboxInstance {
5
+ static readonly DEFAULT_IMAGE = "blaxel/jupyter-server";
6
+ static readonly DEFAULT_PORTS: Port[];
7
+ static readonly DEFAULT_LIFECYCLE: SandboxLifecycle;
8
+ private _sandboxConfig;
9
+ constructor(sandbox: SandboxConfiguration);
10
+ static get(sandboxName: string): Promise<CodeInterpreter>;
11
+ static create(sandbox?: Sandbox | SandboxCreateConfiguration | Record<string, any> | null, { safe }?: {
12
+ safe?: boolean;
13
+ }): Promise<CodeInterpreter>;
14
+ get _jupyterUrl(): string;
15
+ static OutputMessage: {
16
+ new (text: string, timestamp: number | null, isStderr: boolean): {
17
+ text: string;
18
+ timestamp: number | null;
19
+ isStderr: boolean;
20
+ };
21
+ };
22
+ static Result: {
23
+ new (kwargs?: Record<string, unknown>): {
24
+ [key: string]: unknown;
25
+ };
26
+ };
27
+ static ExecutionError: {
28
+ new (name: string, value: any, traceback: any): {
29
+ name: string;
30
+ value: any;
31
+ traceback: any;
32
+ };
33
+ };
34
+ static Logs: {
35
+ new (): {
36
+ stdout: string[];
37
+ stderr: string[];
38
+ };
39
+ };
40
+ static Execution: {
41
+ new (): {
42
+ results: InstanceType<typeof CodeInterpreter.Result>[];
43
+ logs: InstanceType<typeof CodeInterpreter.Logs>;
44
+ error: InstanceType<typeof CodeInterpreter.ExecutionError> | null;
45
+ executionCount: number | null;
46
+ };
47
+ };
48
+ static Context: {
49
+ new (id: string): {
50
+ id: string;
51
+ };
52
+ fromJson(data: Record<string, any>): InstanceType<typeof CodeInterpreter.Context>;
53
+ };
54
+ private _parseOutput;
55
+ runCode(code: string, options?: {
56
+ language?: string | null;
57
+ context?: InstanceType<typeof CodeInterpreter.Context> | null;
58
+ onStdout?: (msg: InstanceType<typeof CodeInterpreter.OutputMessage>) => void;
59
+ onStderr?: (msg: InstanceType<typeof CodeInterpreter.OutputMessage>) => void;
60
+ onResult?: (result: InstanceType<typeof CodeInterpreter.Result>) => void;
61
+ onError?: (error: InstanceType<typeof CodeInterpreter.ExecutionError>) => void;
62
+ envs?: Record<string, string> | null;
63
+ timeout?: number | null;
64
+ requestTimeout?: number | null;
65
+ }): Promise<InstanceType<typeof CodeInterpreter.Execution>>;
66
+ createCodeContext(options?: {
67
+ cwd?: string | null;
68
+ language?: string | null;
69
+ requestTimeout?: number | null;
70
+ }): Promise<InstanceType<typeof CodeInterpreter.Context>>;
71
+ }