Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Reformat
Tomas Valentaf73c34230794
diff --git a/packages/js-sdk/src/api/metadata.ts b/packages/js-sdk/src/api/metadata.tsindex 61d4d377e..19f13c665 100644--- a/packages/js-sdk/src/api/metadata.ts+++ b/packages/js-sdk/src/api/metadata.ts@@ -2,7 +2,7 @@ import platform from 'platform'import { version } from '../../package.json'-declare let window: any;+declare let window: anyexport const defaultHeaders = {browser: (typeof window !== 'undefined' && platform.name) || 'undefined',diff --git a/packages/js-sdk/src/sandbox/filesystemWatcher.ts b/packages/js-sdk/src/sandbox/filesystemWatcher.tsindex aa36ca69c..ce1664d24 100644--- a/packages/js-sdk/src/sandbox/filesystemWatcher.ts+++ b/packages/js-sdk/src/sandbox/filesystemWatcher.ts@@ -19,7 +19,7 @@ export interface FilesystemEvent {isDir: boolean;}-export type FilesystemEventListener = (event: FilesystemEvent) => Promise<void> | void;+export type FilesystemEventListener = (event: FilesystemEvent) => Promise<void> | voidclass FilesystemWatcher {// Listeners to filesystem events.diff --git a/packages/js-sdk/src/sandbox/rpc.ts b/packages/js-sdk/src/sandbox/rpc.tsindex 0a4f968ca..2bacb3856 100644--- a/packages/js-sdk/src/sandbox/rpc.ts+++ b/packages/js-sdk/src/sandbox/rpc.ts@@ -1,26 +1,26 @@// Based on https://github.com/radarsu/rpc-websocket-client-import IWebSocket from 'isomorphic-ws';+import IWebSocket from 'isomorphic-ws'-import { id } from '../utils/id';+import { id } from '../utils/id'export type RpcEventFunction = (// @ts-ignoree: IWebSocket.OpenEvent | IWebSocket.ErrorEvent-) => void;-export type RpcMessageEventFunction = (e: IWebSocket.MessageEvent) => void;-export type RpcCloseEventFunction = (e: IWebSocket.CloseEvent) => void;+) => void+export type RpcMessageEventFunction = (e: IWebSocket.MessageEvent) => void+export type RpcCloseEventFunction = (e: IWebSocket.CloseEvent) => void-export type RpcNotificationEvent = (data: IRpcNotification) => void;-export type RpcRequestEvent = (data: IRpcRequest) => void;-export type RpcSuccessResponseEvent = (data: IRpcSuccessResponse) => void;-export type RpcErrorResponseEvent = (data: IRpcErrorResponse) => void;+export type RpcNotificationEvent = (data: IRpcNotification) => void+export type RpcRequestEvent = (data: IRpcRequest) => void+export type RpcSuccessResponseEvent = (data: IRpcSuccessResponse) => void+export type RpcErrorResponseEvent = (data: IRpcErrorResponse) => voidexport enum RpcVersions {RPC_VERSION = '2.0'}-export type RpcId = string | number;+export type RpcId = string | numberexport interface IRpcData {method: string;@@ -64,31 +64,31 @@ export type RpcUnidentifiedMessage =| IRpcRequest| IRpcNotification| IRpcSuccessResponse- | IRpcErrorResponse;+ | IRpcErrorResponseexport class RpcWebSocketClient {// native websocket- public ws: IWebSocket;+ public ws: IWebSocket- public onOpenHandlers: RpcEventFunction[] = [];- public onAnyMessageHandlers: RpcMessageEventFunction[] = [];+ public onOpenHandlers: RpcEventFunction[] = []+ public onAnyMessageHandlers: RpcMessageEventFunction[] = []- public onNotification: RpcNotificationEvent[] = [];- public onRequest: RpcRequestEvent[] = [];- public onSuccessResponse: RpcSuccessResponseEvent[] = [];- public onErrorResponse: RpcErrorResponseEvent[] = [];+ public onNotification: RpcNotificationEvent[] = []+ public onRequest: RpcRequestEvent[] = []+ public onSuccessResponse: RpcSuccessResponseEvent[] = []+ public onErrorResponse: RpcErrorResponseEvent[] = []- public onErrorHandlers: RpcEventFunction[] = [];- public onCloseHandlers: RpcCloseEventFunction[] = [];+ public onErrorHandlers: RpcEventFunction[] = []+ public onCloseHandlers: RpcCloseEventFunction[] = []public config: IRpcWebSocketConfig = {responseTimeout: 10000- };+ }private idAwaiter: {[id: string]: (data?: any) => void;- } = {};+ } = {}// constructor/**@@ -97,7 +97,7 @@ export class RpcWebSocketClient {* @memberof RpcWebSocketClient*/public constructor() {- this.ws = undefined as any;+ this.ws = undefined as any}// public@@ -108,13 +108,13 @@ export class RpcWebSocketClient {* @memberof RpcWebSocketClient*/public connect(url: string, protocols?: string | string[]) {- this.ws = new IWebSocket(url, protocols);- return this.listen();+ this.ws = new IWebSocket(url, protocols)+ return this.listen()}// eventspublic onOpen(fn: RpcEventFunction) {- this.onOpenHandlers.push(fn);+ this.onOpenHandlers.push(fn)}/**@@ -124,15 +124,15 @@ export class RpcWebSocketClient {* @memberof RpcWebSocketClient*/public onAnyMessage(fn: RpcMessageEventFunction) {- this.onAnyMessageHandlers.push(fn);+ this.onAnyMessageHandlers.push(fn)}public onError(fn: RpcEventFunction) {- this.onErrorHandlers.push(fn);+ this.onErrorHandlers.push(fn)}public onClose(fn: RpcCloseEventFunction) {- this.onCloseHandlers.push(fn);+ this.onCloseHandlers.push(fn)}/**@@ -142,50 +142,50 @@ export class RpcWebSocketClient {* @memberof RpcWebSocketClient*/public listenMessages() {- let previousOnMessage: RpcMessageEventFunction | undefined;+ let previousOnMessage: RpcMessageEventFunction | undefinedif (this.ws.onmessage) {- previousOnMessage = this.ws.onmessage.bind(this.ws);+ previousOnMessage = this.ws.onmessage.bind(this.ws)}this.ws.onmessage = (e: IWebSocket.MessageEvent) => {if (previousOnMessage) {- previousOnMessage(e);+ previousOnMessage(e)}for (const handler of this.onAnyMessageHandlers) {- handler(e);+ handler(e)}- const data: RpcUnidentifiedMessage = JSON.parse(e.data.toString());+ const data: RpcUnidentifiedMessage = JSON.parse(e.data.toString())if (this.isNotification(data)) {// notificationfor (const handler of this.onNotification) {- handler(data);+ handler(data)}} else if (this.isRequest(data)) {// requestfor (const handler of this.onRequest) {- handler(data);+ handler(data)}// responses} else if (this.isSuccessResponse(data)) {// successfor (const handler of this.onSuccessResponse) {- handler(data);+ handler(data)}// resolve awaiting function- this.idAwaiter[data.id](data.result);+ this.idAwaiter[data.id](data.result)} else if (this.isErrorResponse(data)) {// errorfor (const handler of this.onErrorResponse) {- handler(data);+ handler(data)}// resolve awaiting function- this.idAwaiter[data.id](data.error);+ this.idAwaiter[data.id](data.error)}- };+ }}// communication@@ -199,38 +199,38 @@ export class RpcWebSocketClient {*/public call(method: string, params?: any) {return new Promise((resolve, reject) => {- const data = this.buildRequest(method, params);+ const data = this.buildRequest(method, params)// give limited time for response- let timeout: number | NodeJS.Timeout;+ let timeout: number | NodeJS.Timeoutif (this.config.responseTimeout) {timeout = setTimeout(() => {// stop waiting for response- delete this.idAwaiter[data.id];+ delete this.idAwaiter[data.id]reject(new Error(`Awaiting response to "${method}" with id: ${data.id} timed out.`)- );- }, this.config.responseTimeout);+ )+ }, this.config.responseTimeout)}// expect responsethis.idAwaiter[data.id] = (responseData?: any) => {// stop timeout- clearInterval(timeout as number);+ clearInterval(timeout as number)// stop waiting for response- delete this.idAwaiter[data.id];+ delete this.idAwaiter[data.id]if (this.isRpcError(responseData)) {- reject(new Error(`RPC Error (${responseData.code}): ${responseData.message}`));- return;+ reject(new Error(`RPC Error (${responseData.code}): ${responseData.message}`))+ return}- resolve(responseData);- };+ resolve(responseData)+ }- const json = JSON.stringify(data);- this.ws.send(json);- });+ const json = JSON.stringify(data)+ this.ws.send(json)+ })}/**@@ -240,7 +240,7 @@ export class RpcWebSocketClient {* @memberof RpcWebSocketClient*/public notify(method: string, params?: any) {- this.ws.send(JSON.stringify(this.buildNotification(method, params)));+ this.ws.send(JSON.stringify(this.buildNotification(method, params)))}// setup@@ -251,7 +251,7 @@ export class RpcWebSocketClient {* @memberof RpcWebSocketClient*/public customId(idFn: () => string) {- this.idFn = idFn;+ this.idFn = idFn}/**@@ -259,10 +259,10 @@ export class RpcWebSocketClient {* @memberof RpcWebSocketClient*/public noRpc() {- this.buildRequest = this.buildRequestBase;- this.buildNotification = this.buildNotificationBase;- this.buildRpcSuccessResponse = this.buildRpcSuccessResponseBase;- this.buildRpcErrorResponse = this.buildRpcErrorResponseBase;+ this.buildRequest = this.buildRequestBase+ this.buildNotification = this.buildNotificationBase+ this.buildRpcSuccessResponse = this.buildRpcSuccessResponseBase+ this.buildRpcErrorResponse = this.buildRpcErrorResponseBase}/**@@ -271,7 +271,7 @@ export class RpcWebSocketClient {* @memberof RpcWebSocketClient*/public configure(options: IRpcWebSocketConfig) {- Object.assign(this.config, options);+ Object.assign(this.config, options)}/**@@ -281,7 +281,7 @@ export class RpcWebSocketClient {* @memberof RpcWebSocketClient*/public changeSocket(ws: IWebSocket) {- this.ws = ws;+ this.ws = ws}// private@@ -292,68 +292,68 @@ export class RpcWebSocketClient {// @ts-ignorethis.ws.onopen = (e: IWebSocket.OpenEvent) => {for (const handler of this.onOpenHandlers) {- handler(e);+ handler(e)}- resolve(e);- };+ resolve(e)+ }// listen for messages- this.listenMessages();+ this.listenMessages()// called before onclosethis.ws.onerror = (e: IWebSocket.ErrorEvent) => {for (const handler of this.onErrorHandlers) {- handler(e);+ handler(e)}- };+ }this.ws.onclose = (e: IWebSocket.CloseEvent) => {for (const handler of this.onCloseHandlers) {- handler(e);+ handler(e)}- reject(new Error(`WebSocket closed with code: ${e.code} and reason: ${e.reason}`));- };- });+ reject(new Error(`WebSocket closed with code: ${e.code} and reason: ${e.reason}`))+ }+ })}// requestprivate buildRequest(method: string, params?: any): IRpcRequest {- const data = this.buildRequestBase(method, params);- data.jsonrpc = RpcVersions.RPC_VERSION;- return data;+ const data = this.buildRequestBase(method, params)+ data.jsonrpc = RpcVersions.RPC_VERSION+ return data}private buildRequestBase(method: string, params?: any): IRpcRequest {- const data: IRpcRequest = {} as any;- data.id = this.idFn();- data.method = method;+ const data: IRpcRequest = {} as any+ data.id = this.idFn()+ data.method = methodif (params) {- data.params = params;+ data.params = params}- return data;+ return data}// notificationprivate buildNotification(method: string, params?: any): IRpcNotification {- const data = this.buildNotificationBase(method, params);- data.jsonrpc = RpcVersions.RPC_VERSION;- return data;+ const data = this.buildNotificationBase(method, params)+ data.jsonrpc = RpcVersions.RPC_VERSION+ return data}private buildNotificationBase(method: string,params?: any): IRpcNotification {- const data: IRpcNotification = {} as any;- data.method = method;+ const data: IRpcNotification = {} as any+ data.method = methodif (params) {- data.params = params;+ data.params = params}- return data;+ return data}// success response@@ -361,19 +361,19 @@ export class RpcWebSocketClient {id: RpcId,result: any): IRpcSuccessResponse {- const data = this.buildRpcSuccessResponseBase(id, result);- data.jsonrpc = RpcVersions.RPC_VERSION;- return data;+ const data = this.buildRpcSuccessResponseBase(id, result)+ data.jsonrpc = RpcVersions.RPC_VERSION+ return data}private buildRpcSuccessResponseBase(id: RpcId,result: any): IRpcSuccessResponse {- const data: IRpcSuccessResponse = {} as any;- data.id = id;- data.result = result;- return data;+ const data: IRpcSuccessResponse = {} as any+ data.id = id+ data.result = result+ return data}// error response@@ -381,51 +381,51 @@ export class RpcWebSocketClient {id: RpcId,error: IRpcError): IRpcErrorResponse {- const data = this.buildRpcErrorResponseBase(id, error);- data.jsonrpc = RpcVersions.RPC_VERSION;- return data;+ const data = this.buildRpcErrorResponseBase(id, error)+ data.jsonrpc = RpcVersions.RPC_VERSION+ return data}private buildRpcErrorResponseBase(id: RpcId,error: IRpcError): IRpcErrorResponse {- const data: IRpcErrorResponse = {} as any;- data.id = id;- data.error = error;- return data;+ const data: IRpcErrorResponse = {} as any+ data.id = id+ data.error = error+ return data}private idFn(): RpcId {- return id(12);+ return id(12)}// testsprivate isNotification(data: RpcUnidentifiedMessage): data is IRpcNotification {- return !(data as any).id;+ return !(data as any).id}private isRequest(data: RpcUnidentifiedMessage): data is IRpcRequest {- return (data as any).method;+ return (data as any).method}private isSuccessResponse(data: RpcUnidentifiedMessage): data is IRpcSuccessResponse {// eslint-disable-next-line no-prototype-builtins- return data.hasOwnProperty(`result`);+ return data.hasOwnProperty('result')}private isErrorResponse(data: RpcUnidentifiedMessage): data is IRpcErrorResponse {// eslint-disable-next-line no-prototype-builtins- return data.hasOwnProperty(`error`);+ return data.hasOwnProperty('error')}private isRpcError(data: any): data is IRpcError {- return typeof data?.code !== 'undefined';+ return typeof data?.code !== 'undefined'}}diff --git a/packages/js-sdk/src/sandbox/sandboxConnection.ts b/packages/js-sdk/src/sandbox/sandboxConnection.tsindex fadfe7234..3094c92ed 100644--- a/packages/js-sdk/src/sandbox/sandboxConnection.ts+++ b/packages/js-sdk/src/sandbox/sandboxConnection.ts@@ -201,7 +201,7 @@ export class SandboxConnection {const shortID = sandboxID.split('-')[0]try {- await killSandbox(apiKey, {sandboxID: shortID})+ await killSandbox(apiKey, { sandboxID: shortID })} catch (e) {if (e instanceof killSandbox.Error) {const error = e.getActualType()diff --git a/packages/js-sdk/src/sandbox/terminal.ts b/packages/js-sdk/src/sandbox/terminal.tsindex 394e9c322..a800ec5eb 100644--- a/packages/js-sdk/src/sandbox/terminal.ts+++ b/packages/js-sdk/src/sandbox/terminal.ts@@ -109,7 +109,7 @@ export type TerminalOpts = {* Timeout for terminal start in milliseconds (default is 60 seconds)*/timeout?: number;-};+}/*** Manager for starting and interacting with terminal sessions in the sandbox.diff --git a/packages/js-sdk/src/templates/dataAnalysis.ts b/packages/js-sdk/src/templates/dataAnalysis.tsindex c8c4416bc..0f95df2f2 100644--- a/packages/js-sdk/src/templates/dataAnalysis.ts+++ b/packages/js-sdk/src/templates/dataAnalysis.ts@@ -39,13 +39,13 @@ export class DataAnalysis extends Sandbox {* Creates a new Sandbox from the template.* @returns New Sandbox*/- static override async create(): Promise<DataAnalysis>;+ static override async create(): Promise<DataAnalysis>/*** Creates a new Sandbox from the specified options.* @param opts Sandbox options* @returns New Sandbox*/- static override async create(opts: SandboxOpts): Promise<DataAnalysis>;+ static override async create(opts: SandboxOpts): Promise<DataAnalysis>static override async create(opts?: SandboxOpts) {const sandbox = new DataAnalysis({ ...opts ? opts : {} })await sandbox._open({ timeout: opts?.timeout })diff --git a/packages/js-sdk/src/utils/timeout.d.ts b/packages/js-sdk/src/utils/timeout.d.tsindex 31fa4d628..727799d2f 100644--- a/packages/js-sdk/src/utils/timeout.d.ts+++ b/packages/js-sdk/src/utils/timeout.d.ts@@ -1,6 +1,6 @@export class TimeoutError extends Error {- readonly name: 'TimeoutError';- constructor(message?: string);+ readonly name: 'TimeoutError'+ constructor(message?: string)}export type ClearablePromise<T> = {@@ -8,7 +8,7 @@ export type ClearablePromise<T> = {Clear the timeout.*/clear: () => void;-} & Promise<T>;+} & Promise<T>export type Options<ReturnType> = {/**@@ -116,7 +116,7 @@ export type Options<ReturnType> = {```*/signal?: globalThis.AbortSignal;-};+}/**Timeout a promise after a specified amount of time.@@ -143,9 +143,9 @@ await pTimeout(delayedPromise(), {*/export default function pTimeout<ValueType, ReturnType = ValueType>(input: PromiseLike<ValueType>,- options: Options<ReturnType> & {message: false}-): ClearablePromise<ValueType | ReturnType | undefined>;+ options: Options<ReturnType> & { message: false }+): ClearablePromise<ValueType | ReturnType | undefined>export default function pTimeout<ValueType, ReturnType = ValueType>(input: PromiseLike<ValueType>,options: Options<ReturnType>-): ClearablePromise<ValueType | ReturnType>;\ No newline at end of file+): ClearablePromise<ValueType | ReturnType>\ No newline at end of filediff --git a/packages/js-sdk/src/utils/timeout.js b/packages/js-sdk/src/utils/timeout.jsindex e07eefeb2..458886c15 100644--- a/packages/js-sdk/src/utils/timeout.js+++ b/packages/js-sdk/src/utils/timeout.js@@ -1,7 +1,7 @@export class TimeoutError extends Error {constructor(message) {- super(message);- this.name = 'TimeoutError';+ super(message)+ this.name = 'TimeoutError'}}@@ -11,9 +11,9 @@ DOMException is thrown instead of this Error when DOMException is available.*/export class AbortError extends Error {constructor(message) {- super();- this.name = 'AbortError';- this.message = message;+ super()+ this.name = 'AbortError'+ this.message = message}}@@ -22,7 +22,7 @@ TODO: Remove AbortError and just throw DOMException when targeting Node 18.*/const getDOMException = errorMessage => globalThis.DOMException === undefined? new AbortError(errorMessage)- : new DOMException(errorMessage);+ : new DOMException(errorMessage)/**TODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.@@ -30,10 +30,10 @@ TODO: Remove below function and just 'reject(signal.reason)' when targeting Nodeconst getAbortedReason = signal => {const reason = signal.reason === undefined? getDOMException('This operation was aborted.')- : signal.reason;+ : signal.reason- return reason instanceof Error ? reason : getDOMException(reason);-};+ return reason instanceof Error ? reason : getDOMException(reason)+}export default function pTimeout(promise, options) {const {@@ -41,76 +41,76 @@ export default function pTimeout(promise, options) {fallback,message,customTimers = { setTimeout, clearTimeout },- } = options;+ } = options- let timer;+ let timerconst wrappedPromise = new Promise((resolve, reject) => {if (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {- throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);+ throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``)}if (options.signal) {- const { signal } = options;+ const { signal } = optionsif (signal.aborted) {- reject(getAbortedReason(signal));+ reject(getAbortedReason(signal))}signal.addEventListener('abort', () => {- reject(getAbortedReason(signal));- });+ reject(getAbortedReason(signal))+ })}if (milliseconds === Number.POSITIVE_INFINITY) {- promise.then(resolve, reject);- return;+ promise.then(resolve, reject)+ return}// We create the error outside of `setTimeout` to preserve the stack trace.- const timeoutError = new TimeoutError();+ const timeoutError = new TimeoutError()timer = customTimers.setTimeout.call(undefined, () => {if (fallback) {try {- resolve(fallback());+ resolve(fallback())} catch (error) {- reject(error);+ reject(error)}- return;+ return}if (typeof promise.cancel === 'function') {- promise.cancel();+ promise.cancel()}if (message === false) {- resolve();+ resolve()} else if (message instanceof Error) {- reject(message);+ reject(message)} else {- timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;- reject(timeoutError);+ timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`+ reject(timeoutError)}}, milliseconds);(async () => {try {- resolve(await promise);+ resolve(await promise)} catch (error) {- reject(error);+ reject(error)}- })();- });+ })()+ })const cancelablePromise = wrappedPromise.finally(() => {- cancelablePromise.clear();- });+ cancelablePromise.clear()+ })cancelablePromise.clear = () => {- customTimers.clearTimeout.call(undefined, timer);- timer = undefined;- };+ customTimers.clearTimeout.call(undefined, timer)+ timer = undefined+ }- return cancelablePromise;+ return cancelablePromise}\ No newline at end of file