Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Imrpove connection config; [WIP] Rework Python SDK

Tomas Valenta5bfcc9a20e36
diff --git a/Makefile b/Makefile
index e98eb4eaf..435924980 100644
--- a/Makefile
+++ b/Makefile
@@ -5,7 +5,7 @@ update-api-spec:
generate:
- # cd packages/python-sdk && make generate
+ cd packages/python-sdk && make generate
cd packages/js-sdk && pnpm generate
cd packages/connect-python && make bin/protoc-gen-connect-python
cd spec && buf generate
\ No newline at end of file
diff --git a/packages/js-sdk/example.mts b/packages/js-sdk/example.mts
index 1394d744a..280642c39 100644
--- a/packages/js-sdk/example.mts
+++ b/packages/js-sdk/example.mts
@@ -13,4 +13,7 @@ const sandbox = await Sandbox.create({
})
console.log(sandbox.id)
+await sandbox.uploadFile(Buffer.from('hello world'), 'test.txt')
+
+
await sandbox.close()
diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.ts
index 81c0fddb7..96bd7cfbe 100644
--- a/packages/js-sdk/src/api/index.ts
+++ b/packages/js-sdk/src/api/index.ts
@@ -3,44 +3,22 @@ import type { OpArgType, TypedFetch } from 'openapi-typescript-fetch'
import type { components, paths } from './schema.gen'
import { defaultHeaders } from './metadata'
-import { DOMAIN, DEBUG } from '../constants'
+import { ConnectionConfig } from '../connectionConfig'
const { Fetcher } = fetcher
-export interface APIOpts {
- domain?: string
- debug?: boolean
-}
-
class APIClient {
private client = Fetcher.for<paths>()
- constructor(private opts?: APIOpts) {
+ constructor(private config: ConnectionConfig) {
this.client.configure({
- baseUrl: this.apiHost,
+ baseUrl: this.config.apiUrl,
init: {
headers: defaultHeaders,
},
})
}
-
- get debug() {
- return this.opts?.debug ?? DEBUG
- }
-
- get domain() {
- return this.opts?.domain ?? DOMAIN
- }
-
- get apiDomain() {
- return this.debug ? 'localhost:3000' : `api.${this.domain}`
- }
-
- get apiHost() {
- return `${this.debug ? 'http' : 'https'}://${this.apiDomain}`
- }
-
get api() {
return this.client
}
diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.ts
index 43833ea46..d558f355c 100644
--- a/packages/js-sdk/src/api/schema.gen.ts
+++ b/packages/js-sdk/src/api/schema.gen.ts
@@ -113,9 +113,9 @@ export interface paths {
"application/json": {
/**
* Format: int32
- * @description Duration in seconds from the current time after which the sandbox should expire
+ * @description Timeout in seconds from the current time after which the sandbox should expire
*/
- duration?: number;
+ timeout: number;
};
};
};
@@ -323,6 +323,7 @@ export interface components {
/**
* Format: int32
* @description Time to live for the sandbox in seconds.
+ * @default 15
*/
timeout?: number;
metadata?: components["schemas"]["SandboxMetadata"];
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.ts
new file mode 100644
index 000000000..1796e963c
--- /dev/null
+++ b/packages/js-sdk/src/connectionConfig.ts
@@ -0,0 +1,39 @@
+import { AuthenticationError } from './sandbox/errors'
+
+const DOMAIN = process?.env?.E2B_DOMAIN || 'e2b.dev'
+const DEBUG = (process?.env?.E2B_DEBUG || 'false').toLowerCase() === 'true'
+const API_KEY = process?.env?.E2B_API_KEY
+
+export interface ConnectionOpts {
+ apiKey?: string
+ domain?: string
+ debug?: boolean
+}
+
+export class ConnectionConfig {
+ readonly debug: boolean
+ readonly domain: string
+ readonly apiUrl: string
+
+ private readonly _apiKey?: string
+
+ constructor(opts: ConnectionOpts) {
+ this._apiKey = opts.apiKey || API_KEY
+ this.debug = opts.debug || DEBUG
+ this.domain = opts.domain || DOMAIN
+
+ this.apiUrl = this.debug ? 'http://localhost:3000' : `https://api.${this.domain}`
+ }
+
+ get apiKey() {
+ if (!this._apiKey) {
+ throw new AuthenticationError(
+ 'API key is required, please visit https://e2b.dev/docs to get your API key. ' +
+ 'You can either set the environment variable `E2B_API_KEY` ' +
+ "or you can pass it directly to the sandbox like Sandbox.create({ apiKey: 'e2b_...' })",
+ )
+ }
+
+ return this._apiKey
+ }
+}
diff --git a/packages/js-sdk/src/constants.ts b/packages/js-sdk/src/constants.ts
deleted file mode 100644
index 205fb3c57..000000000
--- a/packages/js-sdk/src/constants.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-export const DEBUG = (process?.env?.E2B_DEBUG || 'false').toLowerCase() === 'true'
-export const DOMAIN = process?.env?.E2B_DOMAIN || 'e2b.dev'
-export const API_DOMAIN = DEBUG ? 'localhost:3000' : `api.${DOMAIN}`
-export const API_HOST = `${DEBUG ? 'http' : 'https'}://${API_DOMAIN}`
-
-export const RPC_PORT = 49982
-
-export const FILE_ROUTE = '/file'
\ No newline at end of file
diff --git a/packages/js-sdk/src/envd/filesystem/v1/filesystem_connect.ts b/packages/js-sdk/src/envd/filesystem/v1/filesystem_connect.ts
index 0e5a76a46..6bd194472 100644
--- a/packages/js-sdk/src/envd/filesystem/v1/filesystem_connect.ts
+++ b/packages/js-sdk/src/envd/filesystem/v1/filesystem_connect.ts
@@ -3,7 +3,7 @@
/* eslint-disable */
// @ts-nocheck
-import { CopyRequest, CopyResponse, CreateDirRequest, CreateDirResponse, ListDirRequest, ListDirResponse, RemoveRequest, RemoveResponse, RenameRequest, RenameResponse, StatRequest, StatResponse, WatchRequest, WatchResponse } from "./filesystem_pb.js";
+import { ListRequest, ListResponse, RemoveRequest, RemoveResponse, StatRequest, StatResponse, WatchRequest, WatchResponse } from "./filesystem_pb.js";
import { MethodKind } from "@bufbuild/protobuf";
/**
@@ -22,21 +22,12 @@ export const FilesystemService = {
kind: MethodKind.Unary,
},
/**
- * @generated from rpc envd.filesystem.v1.FilesystemService.CreateDir
+ * @generated from rpc envd.filesystem.v1.FilesystemService.List
*/
- createDir: {
- name: "CreateDir",
- I: CreateDirRequest,
- O: CreateDirResponse,
- kind: MethodKind.Unary,
- },
- /**
- * @generated from rpc envd.filesystem.v1.FilesystemService.ListDir
- */
- listDir: {
- name: "ListDir",
- I: ListDirRequest,
- O: ListDirResponse,
+ list: {
+ name: "List",
+ I: ListRequest,
+ O: ListResponse,
kind: MethodKind.Unary,
},
/**
@@ -48,15 +39,6 @@ export const FilesystemService = {
O: WatchResponse,
kind: MethodKind.ServerStreaming,
},
- /**
- * @generated from rpc envd.filesystem.v1.FilesystemService.Rename
- */
- rename: {
- name: "Rename",
- I: RenameRequest,
- O: RenameResponse,
- kind: MethodKind.Unary,
- },
/**
* @generated from rpc envd.filesystem.v1.FilesystemService.Remove
*/
@@ -66,15 +48,6 @@ export const FilesystemService = {
O: RemoveResponse,
kind: MethodKind.Unary,
},
- /**
- * @generated from rpc envd.filesystem.v1.FilesystemService.Copy
- */
- copy: {
- name: "Copy",
- I: CopyRequest,
- O: CopyResponse,
- kind: MethodKind.Unary,
- },
}
} as const;
diff --git a/packages/js-sdk/src/envd/filesystem/v1/filesystem_pb.ts b/packages/js-sdk/src/envd/filesystem/v1/filesystem_pb.ts
index 4b480075b..ebfdec853 100644
--- a/packages/js-sdk/src/envd/filesystem/v1/filesystem_pb.ts
+++ b/packages/js-sdk/src/envd/filesystem/v1/filesystem_pb.ts
@@ -5,7 +5,6 @@
import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf";
import { Message, proto3 } from "@bufbuild/protobuf";
-import { Credentials } from "../../permissions/v1/permissions_pb.js";
/**
* @generated from enum envd.filesystem.v1.FileType
@@ -78,162 +77,70 @@ proto3.util.setEnumType(EventType, "envd.filesystem.v1.EventType", [
]);
/**
- * @generated from message envd.filesystem.v1.CreateDirRequest
+ * @generated from message envd.filesystem.v1.RemoveRequest
*/
-export class CreateDirRequest extends Message<CreateDirRequest> {
+export class RemoveRequest extends Message<RemoveRequest> {
/**
* @generated from field: string path = 1;
*/
path = "";
- /**
- * @generated from field: string mode = 3;
- */
- mode = "";
-
- /**
- * @generated from field: envd.permissions.v1.Credentials owner = 4;
- */
- owner?: Credentials;
-
- constructor(data?: PartialMessage<CreateDirRequest>) {
+ constructor(data?: PartialMessage<RemoveRequest>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.filesystem.v1.CreateDirRequest";
+ static readonly typeName = "envd.filesystem.v1.RemoveRequest";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "path", kind: "scalar", T: 9 /* ScalarType.STRING */ },
- { no: 3, name: "mode", kind: "scalar", T: 9 /* ScalarType.STRING */ },
- { no: 4, name: "owner", kind: "message", T: Credentials },
- ]);
-
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): CreateDirRequest {
- return new CreateDirRequest().fromBinary(bytes, options);
- }
-
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): CreateDirRequest {
- return new CreateDirRequest().fromJson(jsonValue, options);
- }
-
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): CreateDirRequest {
- return new CreateDirRequest().fromJsonString(jsonString, options);
- }
-
- static equals(a: CreateDirRequest | PlainMessage<CreateDirRequest> | undefined, b: CreateDirRequest | PlainMessage<CreateDirRequest> | undefined): boolean {
- return proto3.util.equals(CreateDirRequest, a, b);
- }
-}
-
-/**
- * @generated from message envd.filesystem.v1.CreateDirResponse
- */
-export class CreateDirResponse extends Message<CreateDirResponse> {
- constructor(data?: PartialMessage<CreateDirResponse>) {
- super();
- proto3.util.initPartial(data, this);
- }
-
- static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.filesystem.v1.CreateDirResponse";
- static readonly fields: FieldList = proto3.util.newFieldList(() => [
- ]);
-
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): CreateDirResponse {
- return new CreateDirResponse().fromBinary(bytes, options);
- }
-
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): CreateDirResponse {
- return new CreateDirResponse().fromJson(jsonValue, options);
- }
-
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): CreateDirResponse {
- return new CreateDirResponse().fromJsonString(jsonString, options);
- }
-
- static equals(a: CreateDirResponse | PlainMessage<CreateDirResponse> | undefined, b: CreateDirResponse | PlainMessage<CreateDirResponse> | undefined): boolean {
- return proto3.util.equals(CreateDirResponse, a, b);
- }
-}
-
-/**
- * @generated from message envd.filesystem.v1.CopyRequest
- */
-export class CopyRequest extends Message<CopyRequest> {
- /**
- * @generated from field: string source = 1;
- */
- source = "";
-
- /**
- * @generated from field: string destination = 2;
- */
- destination = "";
-
- /**
- * @generated from field: string mode = 3;
- */
- mode = "";
-
- constructor(data?: PartialMessage<CopyRequest>) {
- super();
- proto3.util.initPartial(data, this);
- }
-
- static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.filesystem.v1.CopyRequest";
- static readonly fields: FieldList = proto3.util.newFieldList(() => [
- { no: 1, name: "source", kind: "scalar", T: 9 /* ScalarType.STRING */ },
- { no: 2, name: "destination", kind: "scalar", T: 9 /* ScalarType.STRING */ },
- { no: 3, name: "mode", kind: "scalar", T: 9 /* ScalarType.STRING */ },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): CopyRequest {
- return new CopyRequest().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): RemoveRequest {
+ return new RemoveRequest().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): CopyRequest {
- return new CopyRequest().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): RemoveRequest {
+ return new RemoveRequest().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): CopyRequest {
- return new CopyRequest().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): RemoveRequest {
+ return new RemoveRequest().fromJsonString(jsonString, options);
}
- static equals(a: CopyRequest | PlainMessage<CopyRequest> | undefined, b: CopyRequest | PlainMessage<CopyRequest> | undefined): boolean {
- return proto3.util.equals(CopyRequest, a, b);
+ static equals(a: RemoveRequest | PlainMessage<RemoveRequest> | undefined, b: RemoveRequest | PlainMessage<RemoveRequest> | undefined): boolean {
+ return proto3.util.equals(RemoveRequest, a, b);
}
}
/**
- * @generated from message envd.filesystem.v1.CopyResponse
+ * @generated from message envd.filesystem.v1.RemoveResponse
*/
-export class CopyResponse extends Message<CopyResponse> {
- constructor(data?: PartialMessage<CopyResponse>) {
+export class RemoveResponse extends Message<RemoveResponse> {
+ constructor(data?: PartialMessage<RemoveResponse>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.filesystem.v1.CopyResponse";
+ static readonly typeName = "envd.filesystem.v1.RemoveResponse";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): CopyResponse {
- return new CopyResponse().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): RemoveResponse {
+ return new RemoveResponse().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): CopyResponse {
- return new CopyResponse().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): RemoveResponse {
+ return new RemoveResponse().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): CopyResponse {
- return new CopyResponse().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): RemoveResponse {
+ return new RemoveResponse().fromJsonString(jsonString, options);
}
- static equals(a: CopyResponse | PlainMessage<CopyResponse> | undefined, b: CopyResponse | PlainMessage<CopyResponse> | undefined): boolean {
- return proto3.util.equals(CopyResponse, a, b);
+ static equals(a: RemoveResponse | PlainMessage<RemoveResponse> | undefined, b: RemoveResponse | PlainMessage<RemoveResponse> | undefined): boolean {
+ return proto3.util.equals(RemoveResponse, a, b);
}
}
@@ -311,154 +218,6 @@ export class StatResponse extends Message<StatResponse> {
}
}
-/**
- * @generated from message envd.filesystem.v1.RemoveRequest
- */
-export class RemoveRequest extends Message<RemoveRequest> {
- /**
- * @generated from field: string path = 1;
- */
- path = "";
-
- /**
- * @generated from field: bool recursive = 2;
- */
- recursive = false;
-
- constructor(data?: PartialMessage<RemoveRequest>) {
- super();
- proto3.util.initPartial(data, this);
- }
-
- static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.filesystem.v1.RemoveRequest";
- static readonly fields: FieldList = proto3.util.newFieldList(() => [
- { no: 1, name: "path", kind: "scalar", T: 9 /* ScalarType.STRING */ },
- { no: 2, name: "recursive", kind: "scalar", T: 8 /* ScalarType.BOOL */ },
- ]);
-
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): RemoveRequest {
- return new RemoveRequest().fromBinary(bytes, options);
- }
-
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): RemoveRequest {
- return new RemoveRequest().fromJson(jsonValue, options);
- }
-
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): RemoveRequest {
- return new RemoveRequest().fromJsonString(jsonString, options);
- }
-
- static equals(a: RemoveRequest | PlainMessage<RemoveRequest> | undefined, b: RemoveRequest | PlainMessage<RemoveRequest> | undefined): boolean {
- return proto3.util.equals(RemoveRequest, a, b);
- }
-}
-
-/**
- * @generated from message envd.filesystem.v1.RemoveResponse
- */
-export class RemoveResponse extends Message<RemoveResponse> {
- constructor(data?: PartialMessage<RemoveResponse>) {
- super();
- proto3.util.initPartial(data, this);
- }
-
- static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.filesystem.v1.RemoveResponse";
- static readonly fields: FieldList = proto3.util.newFieldList(() => [
- ]);
-
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): RemoveResponse {
- return new RemoveResponse().fromBinary(bytes, options);
- }
-
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): RemoveResponse {
- return new RemoveResponse().fromJson(jsonValue, options);
- }
-
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): RemoveResponse {
- return new RemoveResponse().fromJsonString(jsonString, options);
- }
-
- static equals(a: RemoveResponse | PlainMessage<RemoveResponse> | undefined, b: RemoveResponse | PlainMessage<RemoveResponse> | undefined): boolean {
- return proto3.util.equals(RemoveResponse, a, b);
- }
-}
-
-/**
- * @generated from message envd.filesystem.v1.RenameRequest
- */
-export class RenameRequest extends Message<RenameRequest> {
- /**
- * @generated from field: string source = 1;
- */
- source = "";
-
- /**
- * @generated from field: string destination = 2;
- */
- destination = "";
-
- constructor(data?: PartialMessage<RenameRequest>) {
- super();
- proto3.util.initPartial(data, this);
- }
-
- static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.filesystem.v1.RenameRequest";
- static readonly fields: FieldList = proto3.util.newFieldList(() => [
- { no: 1, name: "source", kind: "scalar", T: 9 /* ScalarType.STRING */ },
- { no: 2, name: "destination", kind: "scalar", T: 9 /* ScalarType.STRING */ },
- ]);
-
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): RenameRequest {
- return new RenameRequest().fromBinary(bytes, options);
- }
-
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): RenameRequest {
- return new RenameRequest().fromJson(jsonValue, options);
- }
-
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): RenameRequest {
- return new RenameRequest().fromJsonString(jsonString, options);
- }
-
- static equals(a: RenameRequest | PlainMessage<RenameRequest> | undefined, b: RenameRequest | PlainMessage<RenameRequest> | undefined): boolean {
- return proto3.util.equals(RenameRequest, a, b);
- }
-}
-
-/**
- * @generated from message envd.filesystem.v1.RenameResponse
- */
-export class RenameResponse extends Message<RenameResponse> {
- constructor(data?: PartialMessage<RenameResponse>) {
- super();
- proto3.util.initPartial(data, this);
- }
-
- static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.filesystem.v1.RenameResponse";
- static readonly fields: FieldList = proto3.util.newFieldList(() => [
- ]);
-
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): RenameResponse {
- return new RenameResponse().fromBinary(bytes, options);
- }
-
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): RenameResponse {
- return new RenameResponse().fromJson(jsonValue, options);
- }
-
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): RenameResponse {
- return new RenameResponse().fromJsonString(jsonString, options);
- }
-
- static equals(a: RenameResponse | PlainMessage<RenameResponse> | undefined, b: RenameResponse | PlainMessage<RenameResponse> | undefined): boolean {
- return proto3.util.equals(RenameResponse, a, b);
- }
-}
-
/**
* @generated from message envd.filesystem.v1.EntryInfo
*/
@@ -503,76 +262,76 @@ export class EntryInfo extends Message<EntryInfo> {
}
/**
- * @generated from message envd.filesystem.v1.ListDirRequest
+ * @generated from message envd.filesystem.v1.ListRequest
*/
-export class ListDirRequest extends Message<ListDirRequest> {
+export class ListRequest extends Message<ListRequest> {
/**
* @generated from field: string path = 1;
*/
path = "";
- constructor(data?: PartialMessage<ListDirRequest>) {
+ constructor(data?: PartialMessage<ListRequest>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.filesystem.v1.ListDirRequest";
+ static readonly typeName = "envd.filesystem.v1.ListRequest";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "path", kind: "scalar", T: 9 /* ScalarType.STRING */ },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): ListDirRequest {
- return new ListDirRequest().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): ListRequest {
+ return new ListRequest().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): ListDirRequest {
- return new ListDirRequest().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): ListRequest {
+ return new ListRequest().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): ListDirRequest {
- return new ListDirRequest().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): ListRequest {
+ return new ListRequest().fromJsonString(jsonString, options);
}
- static equals(a: ListDirRequest | PlainMessage<ListDirRequest> | undefined, b: ListDirRequest | PlainMessage<ListDirRequest> | undefined): boolean {
- return proto3.util.equals(ListDirRequest, a, b);
+ static equals(a: ListRequest | PlainMessage<ListRequest> | undefined, b: ListRequest | PlainMessage<ListRequest> | undefined): boolean {
+ return proto3.util.equals(ListRequest, a, b);
}
}
/**
- * @generated from message envd.filesystem.v1.ListDirResponse
+ * @generated from message envd.filesystem.v1.ListResponse
*/
-export class ListDirResponse extends Message<ListDirResponse> {
+export class ListResponse extends Message<ListResponse> {
/**
* @generated from field: repeated envd.filesystem.v1.EntryInfo entries = 1;
*/
entries: EntryInfo[] = [];
- constructor(data?: PartialMessage<ListDirResponse>) {
+ constructor(data?: PartialMessage<ListResponse>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.filesystem.v1.ListDirResponse";
+ static readonly typeName = "envd.filesystem.v1.ListResponse";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "entries", kind: "message", T: EntryInfo, repeated: true },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): ListDirResponse {
- return new ListDirResponse().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): ListResponse {
+ return new ListResponse().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): ListDirResponse {
- return new ListDirResponse().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): ListResponse {
+ return new ListResponse().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): ListDirResponse {
- return new ListDirResponse().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): ListResponse {
+ return new ListResponse().fromJsonString(jsonString, options);
}
- static equals(a: ListDirResponse | PlainMessage<ListDirResponse> | undefined, b: ListDirResponse | PlainMessage<ListDirResponse> | undefined): boolean {
- return proto3.util.equals(ListDirResponse, a, b);
+ static equals(a: ListResponse | PlainMessage<ListResponse> | undefined, b: ListResponse | PlainMessage<ListResponse> | undefined): boolean {
+ return proto3.util.equals(ListResponse, a, b);
}
}
diff --git a/packages/js-sdk/src/envd/process/v1/process_connect.ts b/packages/js-sdk/src/envd/process/v1/process_connect.ts
index 108ba8618..7aa7f6d76 100644
--- a/packages/js-sdk/src/envd/process/v1/process_connect.ts
+++ b/packages/js-sdk/src/envd/process/v1/process_connect.ts
@@ -3,7 +3,7 @@
/* eslint-disable */
// @ts-nocheck
-import { ListProcessesRequest, ListProcessesResponse, ReconnectProcessRequest, ReconnectProcessResponse, SendProcessInputRequest, SendProcessInputResponse, SendProcessInputStreamRequest, SendProcessInputStreamResponse, SendProcessSignalRequest, SendProcessSignalResponse, StartProcessRequest, StartProcessResponse, UpdateProcessRequest, UpdateProcessResponse } from "./process_pb.js";
+import { ConnectRequest, ConnectResponse, ListRequest, ListResponse, SendInputRequest, SendInputResponse, SendSignalRequest, SendSignalResponse, StartRequest, StartResponse, StreamInputRequest, StreamInputResponse, UpdateRequest, UpdateResponse } from "./process_pb.js";
import { MethodKind } from "@bufbuild/protobuf";
/**
@@ -13,68 +13,68 @@ export const ProcessService = {
typeName: "envd.process.v1.ProcessService",
methods: {
/**
- * @generated from rpc envd.process.v1.ProcessService.ListProcesses
+ * @generated from rpc envd.process.v1.ProcessService.List
*/
- listProcesses: {
- name: "ListProcesses",
- I: ListProcessesRequest,
- O: ListProcessesResponse,
+ list: {
+ name: "List",
+ I: ListRequest,
+ O: ListResponse,
kind: MethodKind.Unary,
},
/**
- * @generated from rpc envd.process.v1.ProcessService.ReconnectProcess
+ * @generated from rpc envd.process.v1.ProcessService.Connect
*/
- reconnectProcess: {
- name: "ReconnectProcess",
- I: ReconnectProcessRequest,
- O: ReconnectProcessResponse,
+ connect: {
+ name: "Connect",
+ I: ConnectRequest,
+ O: ConnectResponse,
kind: MethodKind.ServerStreaming,
},
/**
- * @generated from rpc envd.process.v1.ProcessService.StartProcess
+ * @generated from rpc envd.process.v1.ProcessService.Start
*/
- startProcess: {
- name: "StartProcess",
- I: StartProcessRequest,
- O: StartProcessResponse,
+ start: {
+ name: "Start",
+ I: StartRequest,
+ O: StartResponse,
kind: MethodKind.ServerStreaming,
},
/**
- * @generated from rpc envd.process.v1.ProcessService.UpdateProcess
+ * @generated from rpc envd.process.v1.ProcessService.Update
*/
- updateProcess: {
- name: "UpdateProcess",
- I: UpdateProcessRequest,
- O: UpdateProcessResponse,
+ update: {
+ name: "Update",
+ I: UpdateRequest,
+ O: UpdateResponse,
kind: MethodKind.Unary,
},
/**
* Client input stream ensures ordering of messages
*
- * @generated from rpc envd.process.v1.ProcessService.SendProcessInputStream
+ * @generated from rpc envd.process.v1.ProcessService.StreamInput
*/
- sendProcessInputStream: {
- name: "SendProcessInputStream",
- I: SendProcessInputStreamRequest,
- O: SendProcessInputStreamResponse,
+ streamInput: {
+ name: "StreamInput",
+ I: StreamInputRequest,
+ O: StreamInputResponse,
kind: MethodKind.ClientStreaming,
},
/**
- * @generated from rpc envd.process.v1.ProcessService.SendProcessInput
+ * @generated from rpc envd.process.v1.ProcessService.SendInput
*/
- sendProcessInput: {
- name: "SendProcessInput",
- I: SendProcessInputRequest,
- O: SendProcessInputResponse,
+ sendInput: {
+ name: "SendInput",
+ I: SendInputRequest,
+ O: SendInputResponse,
kind: MethodKind.Unary,
},
/**
- * @generated from rpc envd.process.v1.ProcessService.SendProcessSignal
+ * @generated from rpc envd.process.v1.ProcessService.SendSignal
*/
- sendProcessSignal: {
- name: "SendProcessSignal",
- I: SendProcessSignalRequest,
- O: SendProcessSignalResponse,
+ sendSignal: {
+ name: "SendSignal",
+ I: SendSignalRequest,
+ O: SendSignalResponse,
kind: MethodKind.Unary,
},
}
diff --git a/packages/js-sdk/src/envd/process/v1/process_pb.ts b/packages/js-sdk/src/envd/process/v1/process_pb.ts
index 8d05a7c6e..a6181cee4 100644
--- a/packages/js-sdk/src/envd/process/v1/process_pb.ts
+++ b/packages/js-sdk/src/envd/process/v1/process_pb.ts
@@ -5,7 +5,6 @@
import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf";
import { Message, proto3 } from "@bufbuild/protobuf";
-import { Credentials } from "../../permissions/v1/permissions_pb.js";
/**
* @generated from enum envd.process.v1.Signal
@@ -169,77 +168,120 @@ export class ProcessConfig extends Message<ProcessConfig> {
}
/**
- * @generated from message envd.process.v1.ListProcessesRequest
+ * @generated from message envd.process.v1.ListRequest
*/
-export class ListProcessesRequest extends Message<ListProcessesRequest> {
- constructor(data?: PartialMessage<ListProcessesRequest>) {
+export class ListRequest extends Message<ListRequest> {
+ constructor(data?: PartialMessage<ListRequest>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.ListProcessesRequest";
+ static readonly typeName = "envd.process.v1.ListRequest";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): ListProcessesRequest {
- return new ListProcessesRequest().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): ListRequest {
+ return new ListRequest().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): ListProcessesRequest {
- return new ListProcessesRequest().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): ListRequest {
+ return new ListRequest().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): ListProcessesRequest {
- return new ListProcessesRequest().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): ListRequest {
+ return new ListRequest().fromJsonString(jsonString, options);
}
- static equals(a: ListProcessesRequest | PlainMessage<ListProcessesRequest> | undefined, b: ListProcessesRequest | PlainMessage<ListProcessesRequest> | undefined): boolean {
- return proto3.util.equals(ListProcessesRequest, a, b);
+ static equals(a: ListRequest | PlainMessage<ListRequest> | undefined, b: ListRequest | PlainMessage<ListRequest> | undefined): boolean {
+ return proto3.util.equals(ListRequest, a, b);
}
}
/**
- * @generated from message envd.process.v1.ListProcessesResponse
+ * @generated from message envd.process.v1.ListResponse
*/
-export class ListProcessesResponse extends Message<ListProcessesResponse> {
+export class ListResponse extends Message<ListResponse> {
/**
* @generated from field: repeated envd.process.v1.ProcessConfig processes = 1;
*/
processes: ProcessConfig[] = [];
- constructor(data?: PartialMessage<ListProcessesResponse>) {
+ constructor(data?: PartialMessage<ListResponse>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.ListProcessesResponse";
+ static readonly typeName = "envd.process.v1.ListResponse";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "processes", kind: "message", T: ProcessConfig, repeated: true },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): ListProcessesResponse {
- return new ListProcessesResponse().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): ListResponse {
+ return new ListResponse().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): ListProcessesResponse {
- return new ListProcessesResponse().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): ListResponse {
+ return new ListResponse().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): ListProcessesResponse {
- return new ListProcessesResponse().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): ListResponse {
+ return new ListResponse().fromJsonString(jsonString, options);
}
- static equals(a: ListProcessesResponse | PlainMessage<ListProcessesResponse> | undefined, b: ListProcessesResponse | PlainMessage<ListProcessesResponse> | undefined): boolean {
- return proto3.util.equals(ListProcessesResponse, a, b);
+ static equals(a: ListResponse | PlainMessage<ListResponse> | undefined, b: ListResponse | PlainMessage<ListResponse> | undefined): boolean {
+ return proto3.util.equals(ListResponse, a, b);
}
}
/**
- * @generated from message envd.process.v1.StartProcessRequest
+ * @generated from message envd.process.v1.Credential
*/
-export class StartProcessRequest extends Message<StartProcessRequest> {
+export class Credential extends Message<Credential> {
+ /**
+ * @generated from oneof envd.process.v1.Credential.credential
+ */
+ credential: {
+ /**
+ * @generated from field: string username = 1;
+ */
+ value: string;
+ case: "username";
+ } | { case: undefined; value?: undefined } = { case: undefined };
+
+ constructor(data?: PartialMessage<Credential>) {
+ super();
+ proto3.util.initPartial(data, this);
+ }
+
+ static readonly runtime: typeof proto3 = proto3;
+ static readonly typeName = "envd.process.v1.Credential";
+ static readonly fields: FieldList = proto3.util.newFieldList(() => [
+ { no: 1, name: "username", kind: "scalar", T: 9 /* ScalarType.STRING */, oneof: "credential" },
+ ]);
+
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Credential {
+ return new Credential().fromBinary(bytes, options);
+ }
+
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Credential {
+ return new Credential().fromJson(jsonValue, options);
+ }
+
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Credential {
+ return new Credential().fromJsonString(jsonString, options);
+ }
+
+ static equals(a: Credential | PlainMessage<Credential> | undefined, b: Credential | PlainMessage<Credential> | undefined): boolean {
+ return proto3.util.equals(Credential, a, b);
+ }
+}
+
+/**
+ * @generated from message envd.process.v1.StartRequest
+ */
+export class StartRequest extends Message<StartRequest> {
/**
* @generated from field: envd.process.v1.ProcessConfig process = 1;
*/
@@ -251,44 +293,44 @@ export class StartProcessRequest extends Message<StartProcessRequest> {
pty?: PTY;
/**
- * @generated from field: envd.permissions.v1.Credentials owner = 3;
+ * @generated from field: envd.process.v1.Credential owner = 3;
*/
- owner?: Credentials;
+ owner?: Credential;
- constructor(data?: PartialMessage<StartProcessRequest>) {
+ constructor(data?: PartialMessage<StartRequest>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.StartProcessRequest";
+ static readonly typeName = "envd.process.v1.StartRequest";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "process", kind: "message", T: ProcessConfig },
{ no: 2, name: "pty", kind: "message", T: PTY, opt: true },
- { no: 3, name: "owner", kind: "message", T: Credentials },
+ { no: 3, name: "owner", kind: "message", T: Credential },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): StartProcessRequest {
- return new StartProcessRequest().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): StartRequest {
+ return new StartRequest().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): StartProcessRequest {
- return new StartProcessRequest().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): StartRequest {
+ return new StartRequest().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): StartProcessRequest {
- return new StartProcessRequest().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): StartRequest {
+ return new StartRequest().fromJsonString(jsonString, options);
}
- static equals(a: StartProcessRequest | PlainMessage<StartProcessRequest> | undefined, b: StartProcessRequest | PlainMessage<StartProcessRequest> | undefined): boolean {
- return proto3.util.equals(StartProcessRequest, a, b);
+ static equals(a: StartRequest | PlainMessage<StartRequest> | undefined, b: StartRequest | PlainMessage<StartRequest> | undefined): boolean {
+ return proto3.util.equals(StartRequest, a, b);
}
}
/**
- * @generated from message envd.process.v1.UpdateProcessRequest
+ * @generated from message envd.process.v1.UpdateRequest
*/
-export class UpdateProcessRequest extends Message<UpdateProcessRequest> {
+export class UpdateRequest extends Message<UpdateRequest> {
/**
* @generated from field: envd.process.v1.ProcessSelector process = 1;
*/
@@ -299,63 +341,63 @@ export class UpdateProcessRequest extends Message<UpdateProcessRequest> {
*/
pty?: PTY;
- constructor(data?: PartialMessage<UpdateProcessRequest>) {
+ constructor(data?: PartialMessage<UpdateRequest>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.UpdateProcessRequest";
+ static readonly typeName = "envd.process.v1.UpdateRequest";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "process", kind: "message", T: ProcessSelector },
{ no: 2, name: "pty", kind: "message", T: PTY, opt: true },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): UpdateProcessRequest {
- return new UpdateProcessRequest().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): UpdateRequest {
+ return new UpdateRequest().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): UpdateProcessRequest {
- return new UpdateProcessRequest().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): UpdateRequest {
+ return new UpdateRequest().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): UpdateProcessRequest {
- return new UpdateProcessRequest().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): UpdateRequest {
+ return new UpdateRequest().fromJsonString(jsonString, options);
}
- static equals(a: UpdateProcessRequest | PlainMessage<UpdateProcessRequest> | undefined, b: UpdateProcessRequest | PlainMessage<UpdateProcessRequest> | undefined): boolean {
- return proto3.util.equals(UpdateProcessRequest, a, b);
+ static equals(a: UpdateRequest | PlainMessage<UpdateRequest> | undefined, b: UpdateRequest | PlainMessage<UpdateRequest> | undefined): boolean {
+ return proto3.util.equals(UpdateRequest, a, b);
}
}
/**
- * @generated from message envd.process.v1.UpdateProcessResponse
+ * @generated from message envd.process.v1.UpdateResponse
*/
-export class UpdateProcessResponse extends Message<UpdateProcessResponse> {
- constructor(data?: PartialMessage<UpdateProcessResponse>) {
+export class UpdateResponse extends Message<UpdateResponse> {
+ constructor(data?: PartialMessage<UpdateResponse>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.UpdateProcessResponse";
+ static readonly typeName = "envd.process.v1.UpdateResponse";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): UpdateProcessResponse {
- return new UpdateProcessResponse().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): UpdateResponse {
+ return new UpdateResponse().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): UpdateProcessResponse {
- return new UpdateProcessResponse().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): UpdateResponse {
+ return new UpdateResponse().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): UpdateProcessResponse {
- return new UpdateProcessResponse().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): UpdateResponse {
+ return new UpdateResponse().fromJsonString(jsonString, options);
}
- static equals(a: UpdateProcessResponse | PlainMessage<UpdateProcessResponse> | undefined, b: UpdateProcessResponse | PlainMessage<UpdateProcessResponse> | undefined): boolean {
- return proto3.util.equals(UpdateProcessResponse, a, b);
+ static equals(a: UpdateResponse | PlainMessage<UpdateResponse> | undefined, b: UpdateResponse | PlainMessage<UpdateResponse> | undefined): boolean {
+ return proto3.util.equals(UpdateResponse, a, b);
}
}
@@ -559,83 +601,83 @@ export class ProcessEvent_EndEvent extends Message<ProcessEvent_EndEvent> {
}
/**
- * @generated from message envd.process.v1.StartProcessResponse
+ * @generated from message envd.process.v1.StartResponse
*/
-export class StartProcessResponse extends Message<StartProcessResponse> {
+export class StartResponse extends Message<StartResponse> {
/**
* @generated from field: envd.process.v1.ProcessEvent event = 1;
*/
event?: ProcessEvent;
- constructor(data?: PartialMessage<StartProcessResponse>) {
+ constructor(data?: PartialMessage<StartResponse>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.StartProcessResponse";
+ static readonly typeName = "envd.process.v1.StartResponse";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "event", kind: "message", T: ProcessEvent },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): StartProcessResponse {
- return new StartProcessResponse().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): StartResponse {
+ return new StartResponse().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): StartProcessResponse {
- return new StartProcessResponse().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): StartResponse {
+ return new StartResponse().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): StartProcessResponse {
- return new StartProcessResponse().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): StartResponse {
+ return new StartResponse().fromJsonString(jsonString, options);
}
- static equals(a: StartProcessResponse | PlainMessage<StartProcessResponse> | undefined, b: StartProcessResponse | PlainMessage<StartProcessResponse> | undefined): boolean {
- return proto3.util.equals(StartProcessResponse, a, b);
+ static equals(a: StartResponse | PlainMessage<StartResponse> | undefined, b: StartResponse | PlainMessage<StartResponse> | undefined): boolean {
+ return proto3.util.equals(StartResponse, a, b);
}
}
/**
- * @generated from message envd.process.v1.ReconnectProcessResponse
+ * @generated from message envd.process.v1.ConnectResponse
*/
-export class ReconnectProcessResponse extends Message<ReconnectProcessResponse> {
+export class ConnectResponse extends Message<ConnectResponse> {
/**
* @generated from field: envd.process.v1.ProcessEvent event = 1;
*/
event?: ProcessEvent;
- constructor(data?: PartialMessage<ReconnectProcessResponse>) {
+ constructor(data?: PartialMessage<ConnectResponse>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.ReconnectProcessResponse";
+ static readonly typeName = "envd.process.v1.ConnectResponse";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "event", kind: "message", T: ProcessEvent },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): ReconnectProcessResponse {
- return new ReconnectProcessResponse().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): ConnectResponse {
+ return new ConnectResponse().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): ReconnectProcessResponse {
- return new ReconnectProcessResponse().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): ConnectResponse {
+ return new ConnectResponse().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): ReconnectProcessResponse {
- return new ReconnectProcessResponse().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): ConnectResponse {
+ return new ConnectResponse().fromJsonString(jsonString, options);
}
- static equals(a: ReconnectProcessResponse | PlainMessage<ReconnectProcessResponse> | undefined, b: ReconnectProcessResponse | PlainMessage<ReconnectProcessResponse> | undefined): boolean {
- return proto3.util.equals(ReconnectProcessResponse, a, b);
+ static equals(a: ConnectResponse | PlainMessage<ConnectResponse> | undefined, b: ConnectResponse | PlainMessage<ConnectResponse> | undefined): boolean {
+ return proto3.util.equals(ConnectResponse, a, b);
}
}
/**
- * @generated from message envd.process.v1.SendProcessInputRequest
+ * @generated from message envd.process.v1.SendInputRequest
*/
-export class SendProcessInputRequest extends Message<SendProcessInputRequest> {
+export class SendInputRequest extends Message<SendInputRequest> {
/**
* @generated from field: envd.process.v1.ProcessSelector process = 1;
*/
@@ -646,63 +688,63 @@ export class SendProcessInputRequest extends Message<SendProcessInputRequest> {
*/
input?: ProcessInput;
- constructor(data?: PartialMessage<SendProcessInputRequest>) {
+ constructor(data?: PartialMessage<SendInputRequest>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.SendProcessInputRequest";
+ static readonly typeName = "envd.process.v1.SendInputRequest";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "process", kind: "message", T: ProcessSelector },
{ no: 2, name: "input", kind: "message", T: ProcessInput },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): SendProcessInputRequest {
- return new SendProcessInputRequest().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): SendInputRequest {
+ return new SendInputRequest().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): SendProcessInputRequest {
- return new SendProcessInputRequest().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): SendInputRequest {
+ return new SendInputRequest().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): SendProcessInputRequest {
- return new SendProcessInputRequest().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): SendInputRequest {
+ return new SendInputRequest().fromJsonString(jsonString, options);
}
- static equals(a: SendProcessInputRequest | PlainMessage<SendProcessInputRequest> | undefined, b: SendProcessInputRequest | PlainMessage<SendProcessInputRequest> | undefined): boolean {
- return proto3.util.equals(SendProcessInputRequest, a, b);
+ static equals(a: SendInputRequest | PlainMessage<SendInputRequest> | undefined, b: SendInputRequest | PlainMessage<SendInputRequest> | undefined): boolean {
+ return proto3.util.equals(SendInputRequest, a, b);
}
}
/**
- * @generated from message envd.process.v1.SendProcessInputResponse
+ * @generated from message envd.process.v1.SendInputResponse
*/
-export class SendProcessInputResponse extends Message<SendProcessInputResponse> {
- constructor(data?: PartialMessage<SendProcessInputResponse>) {
+export class SendInputResponse extends Message<SendInputResponse> {
+ constructor(data?: PartialMessage<SendInputResponse>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.SendProcessInputResponse";
+ static readonly typeName = "envd.process.v1.SendInputResponse";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): SendProcessInputResponse {
- return new SendProcessInputResponse().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): SendInputResponse {
+ return new SendInputResponse().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): SendProcessInputResponse {
- return new SendProcessInputResponse().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): SendInputResponse {
+ return new SendInputResponse().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): SendProcessInputResponse {
- return new SendProcessInputResponse().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): SendInputResponse {
+ return new SendInputResponse().fromJsonString(jsonString, options);
}
- static equals(a: SendProcessInputResponse | PlainMessage<SendProcessInputResponse> | undefined, b: SendProcessInputResponse | PlainMessage<SendProcessInputResponse> | undefined): boolean {
- return proto3.util.equals(SendProcessInputResponse, a, b);
+ static equals(a: SendInputResponse | PlainMessage<SendInputResponse> | undefined, b: SendInputResponse | PlainMessage<SendInputResponse> | undefined): boolean {
+ return proto3.util.equals(SendInputResponse, a, b);
}
}
@@ -757,164 +799,164 @@ export class ProcessInput extends Message<ProcessInput> {
}
/**
- * @generated from message envd.process.v1.SendProcessInputStreamRequest
+ * @generated from message envd.process.v1.StreamInputRequest
*/
-export class SendProcessInputStreamRequest extends Message<SendProcessInputStreamRequest> {
+export class StreamInputRequest extends Message<StreamInputRequest> {
/**
- * @generated from oneof envd.process.v1.SendProcessInputStreamRequest.event
+ * @generated from oneof envd.process.v1.StreamInputRequest.event
*/
event: {
/**
- * @generated from field: envd.process.v1.SendProcessInputStreamRequest.StartEvent start = 1;
+ * @generated from field: envd.process.v1.StreamInputRequest.StartEvent start = 1;
*/
- value: SendProcessInputStreamRequest_StartEvent;
+ value: StreamInputRequest_StartEvent;
case: "start";
} | {
/**
- * @generated from field: envd.process.v1.SendProcessInputStreamRequest.DataEvent data = 2;
+ * @generated from field: envd.process.v1.StreamInputRequest.DataEvent data = 2;
*/
- value: SendProcessInputStreamRequest_DataEvent;
+ value: StreamInputRequest_DataEvent;
case: "data";
} | { case: undefined; value?: undefined } = { case: undefined };
- constructor(data?: PartialMessage<SendProcessInputStreamRequest>) {
+ constructor(data?: PartialMessage<StreamInputRequest>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.SendProcessInputStreamRequest";
+ static readonly typeName = "envd.process.v1.StreamInputRequest";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
- { no: 1, name: "start", kind: "message", T: SendProcessInputStreamRequest_StartEvent, oneof: "event" },
- { no: 2, name: "data", kind: "message", T: SendProcessInputStreamRequest_DataEvent, oneof: "event" },
+ { no: 1, name: "start", kind: "message", T: StreamInputRequest_StartEvent, oneof: "event" },
+ { no: 2, name: "data", kind: "message", T: StreamInputRequest_DataEvent, oneof: "event" },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): SendProcessInputStreamRequest {
- return new SendProcessInputStreamRequest().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): StreamInputRequest {
+ return new StreamInputRequest().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): SendProcessInputStreamRequest {
- return new SendProcessInputStreamRequest().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): StreamInputRequest {
+ return new StreamInputRequest().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): SendProcessInputStreamRequest {
- return new SendProcessInputStreamRequest().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): StreamInputRequest {
+ return new StreamInputRequest().fromJsonString(jsonString, options);
}
- static equals(a: SendProcessInputStreamRequest | PlainMessage<SendProcessInputStreamRequest> | undefined, b: SendProcessInputStreamRequest | PlainMessage<SendProcessInputStreamRequest> | undefined): boolean {
- return proto3.util.equals(SendProcessInputStreamRequest, a, b);
+ static equals(a: StreamInputRequest | PlainMessage<StreamInputRequest> | undefined, b: StreamInputRequest | PlainMessage<StreamInputRequest> | undefined): boolean {
+ return proto3.util.equals(StreamInputRequest, a, b);
}
}
/**
- * @generated from message envd.process.v1.SendProcessInputStreamRequest.StartEvent
+ * @generated from message envd.process.v1.StreamInputRequest.StartEvent
*/
-export class SendProcessInputStreamRequest_StartEvent extends Message<SendProcessInputStreamRequest_StartEvent> {
+export class StreamInputRequest_StartEvent extends Message<StreamInputRequest_StartEvent> {
/**
* @generated from field: envd.process.v1.ProcessSelector process = 1;
*/
process?: ProcessSelector;
- constructor(data?: PartialMessage<SendProcessInputStreamRequest_StartEvent>) {
+ constructor(data?: PartialMessage<StreamInputRequest_StartEvent>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.SendProcessInputStreamRequest.StartEvent";
+ static readonly typeName = "envd.process.v1.StreamInputRequest.StartEvent";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "process", kind: "message", T: ProcessSelector },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): SendProcessInputStreamRequest_StartEvent {
- return new SendProcessInputStreamRequest_StartEvent().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): StreamInputRequest_StartEvent {
+ return new StreamInputRequest_StartEvent().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): SendProcessInputStreamRequest_StartEvent {
- return new SendProcessInputStreamRequest_StartEvent().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): StreamInputRequest_StartEvent {
+ return new StreamInputRequest_StartEvent().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): SendProcessInputStreamRequest_StartEvent {
- return new SendProcessInputStreamRequest_StartEvent().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): StreamInputRequest_StartEvent {
+ return new StreamInputRequest_StartEvent().fromJsonString(jsonString, options);
}
- static equals(a: SendProcessInputStreamRequest_StartEvent | PlainMessage<SendProcessInputStreamRequest_StartEvent> | undefined, b: SendProcessInputStreamRequest_StartEvent | PlainMessage<SendProcessInputStreamRequest_StartEvent> | undefined): boolean {
- return proto3.util.equals(SendProcessInputStreamRequest_StartEvent, a, b);
+ static equals(a: StreamInputRequest_StartEvent | PlainMessage<StreamInputRequest_StartEvent> | undefined, b: StreamInputRequest_StartEvent | PlainMessage<StreamInputRequest_StartEvent> | undefined): boolean {
+ return proto3.util.equals(StreamInputRequest_StartEvent, a, b);
}
}
/**
- * @generated from message envd.process.v1.SendProcessInputStreamRequest.DataEvent
+ * @generated from message envd.process.v1.StreamInputRequest.DataEvent
*/
-export class SendProcessInputStreamRequest_DataEvent extends Message<SendProcessInputStreamRequest_DataEvent> {
+export class StreamInputRequest_DataEvent extends Message<StreamInputRequest_DataEvent> {
/**
* @generated from field: envd.process.v1.ProcessInput input = 2;
*/
input?: ProcessInput;
- constructor(data?: PartialMessage<SendProcessInputStreamRequest_DataEvent>) {
+ constructor(data?: PartialMessage<StreamInputRequest_DataEvent>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.SendProcessInputStreamRequest.DataEvent";
+ static readonly typeName = "envd.process.v1.StreamInputRequest.DataEvent";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 2, name: "input", kind: "message", T: ProcessInput },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): SendProcessInputStreamRequest_DataEvent {
- return new SendProcessInputStreamRequest_DataEvent().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): StreamInputRequest_DataEvent {
+ return new StreamInputRequest_DataEvent().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): SendProcessInputStreamRequest_DataEvent {
- return new SendProcessInputStreamRequest_DataEvent().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): StreamInputRequest_DataEvent {
+ return new StreamInputRequest_DataEvent().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): SendProcessInputStreamRequest_DataEvent {
- return new SendProcessInputStreamRequest_DataEvent().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): StreamInputRequest_DataEvent {
+ return new StreamInputRequest_DataEvent().fromJsonString(jsonString, options);
}
- static equals(a: SendProcessInputStreamRequest_DataEvent | PlainMessage<SendProcessInputStreamRequest_DataEvent> | undefined, b: SendProcessInputStreamRequest_DataEvent | PlainMessage<SendProcessInputStreamRequest_DataEvent> | undefined): boolean {
- return proto3.util.equals(SendProcessInputStreamRequest_DataEvent, a, b);
+ static equals(a: StreamInputRequest_DataEvent | PlainMessage<StreamInputRequest_DataEvent> | undefined, b: StreamInputRequest_DataEvent | PlainMessage<StreamInputRequest_DataEvent> | undefined): boolean {
+ return proto3.util.equals(StreamInputRequest_DataEvent, a, b);
}
}
/**
- * @generated from message envd.process.v1.SendProcessInputStreamResponse
+ * @generated from message envd.process.v1.StreamInputResponse
*/
-export class SendProcessInputStreamResponse extends Message<SendProcessInputStreamResponse> {
- constructor(data?: PartialMessage<SendProcessInputStreamResponse>) {
+export class StreamInputResponse extends Message<StreamInputResponse> {
+ constructor(data?: PartialMessage<StreamInputResponse>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.SendProcessInputStreamResponse";
+ static readonly typeName = "envd.process.v1.StreamInputResponse";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): SendProcessInputStreamResponse {
- return new SendProcessInputStreamResponse().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): StreamInputResponse {
+ return new StreamInputResponse().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): SendProcessInputStreamResponse {
- return new SendProcessInputStreamResponse().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): StreamInputResponse {
+ return new StreamInputResponse().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): SendProcessInputStreamResponse {
- return new SendProcessInputStreamResponse().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): StreamInputResponse {
+ return new StreamInputResponse().fromJsonString(jsonString, options);
}
- static equals(a: SendProcessInputStreamResponse | PlainMessage<SendProcessInputStreamResponse> | undefined, b: SendProcessInputStreamResponse | PlainMessage<SendProcessInputStreamResponse> | undefined): boolean {
- return proto3.util.equals(SendProcessInputStreamResponse, a, b);
+ static equals(a: StreamInputResponse | PlainMessage<StreamInputResponse> | undefined, b: StreamInputResponse | PlainMessage<StreamInputResponse> | undefined): boolean {
+ return proto3.util.equals(StreamInputResponse, a, b);
}
}
/**
- * @generated from message envd.process.v1.SendProcessSignalRequest
+ * @generated from message envd.process.v1.SendSignalRequest
*/
-export class SendProcessSignalRequest extends Message<SendProcessSignalRequest> {
+export class SendSignalRequest extends Message<SendSignalRequest> {
/**
* @generated from field: envd.process.v1.ProcessSelector process = 1;
*/
@@ -925,100 +967,100 @@ export class SendProcessSignalRequest extends Message<SendProcessSignalRequest>
*/
signal = Signal.UNSPECIFIED;
- constructor(data?: PartialMessage<SendProcessSignalRequest>) {
+ constructor(data?: PartialMessage<SendSignalRequest>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.SendProcessSignalRequest";
+ static readonly typeName = "envd.process.v1.SendSignalRequest";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "process", kind: "message", T: ProcessSelector },
{ no: 2, name: "signal", kind: "enum", T: proto3.getEnumType(Signal) },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): SendProcessSignalRequest {
- return new SendProcessSignalRequest().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): SendSignalRequest {
+ return new SendSignalRequest().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): SendProcessSignalRequest {
- return new SendProcessSignalRequest().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): SendSignalRequest {
+ return new SendSignalRequest().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): SendProcessSignalRequest {
- return new SendProcessSignalRequest().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): SendSignalRequest {
+ return new SendSignalRequest().fromJsonString(jsonString, options);
}
- static equals(a: SendProcessSignalRequest | PlainMessage<SendProcessSignalRequest> | undefined, b: SendProcessSignalRequest | PlainMessage<SendProcessSignalRequest> | undefined): boolean {
- return proto3.util.equals(SendProcessSignalRequest, a, b);
+ static equals(a: SendSignalRequest | PlainMessage<SendSignalRequest> | undefined, b: SendSignalRequest | PlainMessage<SendSignalRequest> | undefined): boolean {
+ return proto3.util.equals(SendSignalRequest, a, b);
}
}
/**
- * @generated from message envd.process.v1.SendProcessSignalResponse
+ * @generated from message envd.process.v1.SendSignalResponse
*/
-export class SendProcessSignalResponse extends Message<SendProcessSignalResponse> {
- constructor(data?: PartialMessage<SendProcessSignalResponse>) {
+export class SendSignalResponse extends Message<SendSignalResponse> {
+ constructor(data?: PartialMessage<SendSignalResponse>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.SendProcessSignalResponse";
+ static readonly typeName = "envd.process.v1.SendSignalResponse";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): SendProcessSignalResponse {
- return new SendProcessSignalResponse().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): SendSignalResponse {
+ return new SendSignalResponse().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): SendProcessSignalResponse {
- return new SendProcessSignalResponse().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): SendSignalResponse {
+ return new SendSignalResponse().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): SendProcessSignalResponse {
- return new SendProcessSignalResponse().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): SendSignalResponse {
+ return new SendSignalResponse().fromJsonString(jsonString, options);
}
- static equals(a: SendProcessSignalResponse | PlainMessage<SendProcessSignalResponse> | undefined, b: SendProcessSignalResponse | PlainMessage<SendProcessSignalResponse> | undefined): boolean {
- return proto3.util.equals(SendProcessSignalResponse, a, b);
+ static equals(a: SendSignalResponse | PlainMessage<SendSignalResponse> | undefined, b: SendSignalResponse | PlainMessage<SendSignalResponse> | undefined): boolean {
+ return proto3.util.equals(SendSignalResponse, a, b);
}
}
/**
- * @generated from message envd.process.v1.ReconnectProcessRequest
+ * @generated from message envd.process.v1.ConnectRequest
*/
-export class ReconnectProcessRequest extends Message<ReconnectProcessRequest> {
+export class ConnectRequest extends Message<ConnectRequest> {
/**
* @generated from field: envd.process.v1.ProcessSelector process = 1;
*/
process?: ProcessSelector;
- constructor(data?: PartialMessage<ReconnectProcessRequest>) {
+ constructor(data?: PartialMessage<ConnectRequest>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
- static readonly typeName = "envd.process.v1.ReconnectProcessRequest";
+ static readonly typeName = "envd.process.v1.ConnectRequest";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "process", kind: "message", T: ProcessSelector },
]);
- static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): ReconnectProcessRequest {
- return new ReconnectProcessRequest().fromBinary(bytes, options);
+ static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): ConnectRequest {
+ return new ConnectRequest().fromBinary(bytes, options);
}
- static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): ReconnectProcessRequest {
- return new ReconnectProcessRequest().fromJson(jsonValue, options);
+ static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): ConnectRequest {
+ return new ConnectRequest().fromJson(jsonValue, options);
}
- static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): ReconnectProcessRequest {
- return new ReconnectProcessRequest().fromJsonString(jsonString, options);
+ static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): ConnectRequest {
+ return new ConnectRequest().fromJsonString(jsonString, options);
}
- static equals(a: ReconnectProcessRequest | PlainMessage<ReconnectProcessRequest> | undefined, b: ReconnectProcessRequest | PlainMessage<ReconnectProcessRequest> | undefined): boolean {
- return proto3.util.equals(ReconnectProcessRequest, a, b);
+ static equals(a: ConnectRequest | PlainMessage<ConnectRequest> | undefined, b: ConnectRequest | PlainMessage<ConnectRequest> | undefined): boolean {
+ return proto3.util.equals(ConnectRequest, a, b);
}
}
diff --git a/packages/js-sdk/src/error.ts b/packages/js-sdk/src/error.ts
deleted file mode 100644
index 410cdb22e..000000000
--- a/packages/js-sdk/src/error.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export class AuthenticationError extends Error {
- constructor(message: any) {
- super(message)
- this.name = 'AuthenticationError'
- }
-}
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index be37605d3..936c3e00a 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -1,28 +1,12 @@
export { APIClient, withAPIKey, withAccessToken } from './api'
export type { components, paths } from './api'
-export { DOMAIN, API_HOST } from './constants'
-export type { SandboxOpts, DownloadFileFormat } from './sandboxFile'
-export type { OpenPort } from './sandbox/codeSnippet'
-export { Terminal, TerminalOutput } from './sandbox/terminal'
-export type { TerminalManager } from './sandbox/terminal'
-export type { FilesystemManager, FileInfo } from './sandbox/filesystem'
-export {
- default as FilesystemWatcher,
- FilesystemOperation,
-} from './sandbox/filesystemWatcher'
-export type {
- FilesystemEvent,
- FilesystemEventListener,
-} from './sandbox/filesystemWatcher'
+export { ConnectionConfig } from './connectionConfig'
+export type { ConnectionOpts } from './connectionConfig'
-export { AuthenticationError, CurrentWorkingDirectoryDoesntExistError, TimeoutError } from './error'
-export { Process, ProcessMessage, ProcessOutput } from './sandbox/process'
-export type { ProcessManager } from './sandbox/process'
-export type { EnvVars } from './sandbox/envVars'
-import { Sandbox } from './sandbox'
+export { AuthenticationError, SandboxError } from './sandbox/errors'
-export type { SandboxMetadata, RunningSandbox } from './sandbox/sandboxConnection'
+import { Sandbox } from './sandbox'
export { Sandbox }
export default Sandbox
diff --git a/packages/js-sdk/src/utils/array.ts b/packages/js-sdk/src/sandbox/array.ts
similarity index 100%
rename from packages/js-sdk/src/utils/array.ts
rename to packages/js-sdk/src/sandbox/array.ts
diff --git a/packages/js-sdk/src/sandbox/errors.ts b/packages/js-sdk/src/sandbox/errors.ts
new file mode 100644
index 000000000..769c153bf
--- /dev/null
+++ b/packages/js-sdk/src/sandbox/errors.ts
@@ -0,0 +1,13 @@
+export class SandboxError extends Error {
+ constructor(message: any) {
+ super(message)
+ this.name = 'SandboxError'
+ }
+}
+
+export class AuthenticationError extends SandboxError {
+ constructor(message: any) {
+ super(message)
+ this.name = 'AuthenticationError'
+ }
+}
diff --git a/packages/js-sdk/src/utils/filesystem.ts b/packages/js-sdk/src/sandbox/filesystem.ts
similarity index 95%
rename from packages/js-sdk/src/utils/filesystem.ts
rename to packages/js-sdk/src/sandbox/filesystem.ts
index c0815b518..c7e8fde2b 100644
--- a/packages/js-sdk/src/utils/filesystem.ts
+++ b/packages/js-sdk/src/sandbox/filesystem.ts
@@ -1,6 +1,6 @@
import path from 'path-browserify'
-import { Logger } from '../sandbox/sandboxConnection'
+import { Logger } from './logger'
export const resolvePath = (
inputPath: string,
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index 244d0d727..ace3d5aa1 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -1,37 +1,39 @@
-import { APIOpts } from '../api'
-import { RPC_PORT, DEBUG, DOMAIN } from '../constants'
-import { getApiKey } from '../utils/apiKey'
import { SandboxApi } from './sandboxApi'
import { SandboxRpc } from './rpc'
import { Logger } from './logger'
-import { SandboxMetadata } from './metadata'
+import { SandboxFiles } from './sandboxFiles'
+import { ConnectionOpts, ConnectionConfig } from '../connectionConfig'
-export interface SandboxOpts extends APIOpts {
- apiKey?: string
- /**
- * Domain to use for the API requests. If not provided, the `E2B_DOMAIN` environment variable will be used.
- */
- domain?: string
+export interface SandboxOpts extends ConnectionOpts {
/**
* A dictionary of strings that is stored alongside the running sandbox.
* You can see this metadata when you list running sandboxes.
*/
- metadata?: SandboxMetadata
+ metadata?: { [key: string]: string }
logger?: Logger
timeout?: number
}
+const SANDBOX_SERVER_PORT = 49982
+
+
export class Sandbox extends SandboxApi {
protected static readonly defaultTemplate = 'base'
+ private readonly connectionConfig: ConnectionConfig
+
private readonly rpc: SandboxRpc
+ private readonly files: SandboxFiles
- constructor(readonly sandboxID: string, private readonly opts: Omit<SandboxOpts, 'timeout' | 'metadata' | 'template' | ''>) {
+ constructor(readonly sandboxID: string, opts: Omit<SandboxOpts, 'timeout' | 'metadata'> = {}) {
super()
- const rpcUrl = `${this.debug ? 'http' : 'https'}://${this.getHostname(RPC_PORT)}`
+ this.connectionConfig = new ConnectionConfig(opts)
+
+ const sandboxServerUrl = `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHostname(SANDBOX_SERVER_PORT)}`
- this.rpc = new SandboxRpc(rpcUrl)
+ this.rpc = new SandboxRpc(sandboxServerUrl)
+ this.files = new SandboxFiles(sandboxServerUrl)
}
get filesystem() {
@@ -42,22 +44,10 @@ export class Sandbox extends SandboxApi {
return this.rpc.process
}
- private get debug() {
- return this.opts?.debug ?? DEBUG
- }
-
- private get domain() {
- return this.opts?.domain ?? DOMAIN
- }
-
- private get apiKey() {
- return getApiKey(this.opts?.apiKey)
- }
-
/**
* Creates a new Sandbox from the specified options.
*/
- static async spawn<S extends typeof Sandbox>(this: S, template = this.defaultTemplate, opts: SandboxOpts = {}): Promise<InstanceType<S>> {
+ static async spawn<S extends typeof Sandbox>(this: S, template = this.defaultTemplate, opts?: SandboxOpts): Promise<InstanceType<S>> {
const sandboxID = await this.createSandbox(template, opts)
return new this(sandboxID, opts) as InstanceType<S>
@@ -66,7 +56,7 @@ export class Sandbox extends SandboxApi {
/**
* Connects to an existing Sandbox.
*/
- static async connect<S extends typeof Sandbox>(this: S, sandboxID: string, opts: Omit<SandboxOpts, 'id' | 'template'> = {}): Promise<InstanceType<S>> {
+ static async connect<S extends typeof Sandbox>(this: S, sandboxID: string, opts?: Omit<SandboxOpts, 'metadata' | 'timeout'>): Promise<InstanceType<S>> {
return new this(sandboxID, opts) as InstanceType<S>
}
@@ -79,35 +69,18 @@ export class Sandbox extends SandboxApi {
* @returns Hostname of the sandbox or sandbox's port
*/
getHostname(port: number) {
- if (this.debug) {
- if (port) {
- return `localhost:${port}`
- }
-
- return 'localhost'
- }
-
- const hostname = `${this.sandboxID}.${this.domain}`
- if (port) {
- return `${port}-${hostname}`
+ if (this.connectionConfig.debug) {
+ return `localhost:${port}`
}
- return hostname
+ return `${port}-${this.sandboxID}.${this.connectionConfig.domain}`
}
async setTimeout(timeout: number) {
- await SandboxApi.setTimeout(this.sandboxID, timeout, {
- apiKey: this.apiKey,
- domain: this.domain,
- debug: this.debug,
- })
+ await SandboxApi.setTimeout(this.sandboxID, timeout, this.connectionConfig)
}
async kill() {
- await SandboxApi.kill(this.sandboxID, {
- apiKey: this.apiKey,
- domain: this.domain,
- debug: this.debug,
- })
+ await SandboxApi.kill(this.sandboxID, this.connectionConfig)
}
}
diff --git a/packages/js-sdk/src/sandbox/metadata.ts b/packages/js-sdk/src/sandbox/metadata.ts
deleted file mode 100644
index d3d8d0725..000000000
--- a/packages/js-sdk/src/sandbox/metadata.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export type SandboxMetadata = {
- [key: string]: string
-}
diff --git a/packages/js-sdk/src/sandbox/process.ts b/packages/js-sdk/src/sandbox/process.ts
index 4de41032c..0f8c495bc 100644
--- a/packages/js-sdk/src/sandbox/process.ts
+++ b/packages/js-sdk/src/sandbox/process.ts
@@ -1,6 +1,6 @@
import { EnvVars } from './envVars'
import { CallOpts, SandboxConnection } from './sandboxConnection'
-import { withTimeout } from '../utils/promise'
+import { withTimeout } from './promise'
export const processService = 'process'
diff --git a/packages/js-sdk/src/utils/promise.ts b/packages/js-sdk/src/sandbox/promise.ts
similarity index 100%
rename from packages/js-sdk/src/utils/promise.ts
rename to packages/js-sdk/src/sandbox/promise.ts
diff --git a/packages/js-sdk/src/sandbox/rpc/filesystem.ts b/packages/js-sdk/src/sandbox/rpc/filesystem.ts
index 499c0d26d..246614c50 100644
--- a/packages/js-sdk/src/sandbox/rpc/filesystem.ts
+++ b/packages/js-sdk/src/sandbox/rpc/filesystem.ts
@@ -7,14 +7,12 @@ import {
import { FilesystemService } from '../../envd/filesystem/v1/filesystem_connect'
import {
- CopyRequest,
FilesystemEvent,
- ListDirRequest,
- ListDirResponse,
RemoveRequest,
- RenameRequest,
StatRequest,
StatResponse,
+ ListRequest,
+ ListResponse,
WatchRequest,
} from '../../envd/filesystem/v1/filesystem_pb'
@@ -24,16 +22,8 @@ export class Filesystem {
constructor(private readonly transport: Transport) { }
- async copy(params: PlainMessage<CopyRequest>): Promise<void> {
- await this.service.copy(params)
- }
-
- async createDir(params: PlainMessage<CopyRequest>): Promise<void> {
- await this.service.createDir(params)
- }
-
- async listDir(params: PlainMessage<ListDirRequest>): Promise<ListDirResponse['entries']> {
- const res = await this.service.listDir(params)
+ async list(params: PlainMessage<ListRequest>): Promise<ListResponse['entries']> {
+ const res = await this.service.list(params)
return res.entries
}
@@ -41,10 +31,6 @@ export class Filesystem {
await this.service.remove(params)
}
- async rename(params: PlainMessage<RenameRequest>): Promise<void> {
- await this.service.rename(params)
- }
-
async exists(params: PlainMessage<StatRequest>): Promise<StatResponse['entry']> {
const res = await this.service.stat(params)
return res.entry
diff --git a/packages/js-sdk/src/sandbox/rpc/process.ts b/packages/js-sdk/src/sandbox/rpc/process.ts
index beaa4a6ae..7101f459f 100644
--- a/packages/js-sdk/src/sandbox/rpc/process.ts
+++ b/packages/js-sdk/src/sandbox/rpc/process.ts
@@ -7,22 +7,22 @@ import {
import { ProcessService } from '../../envd/process/v1/process_connect'
import {
- ListProcessesRequest,
- ListProcessesResponse,
+ ListRequest,
+ ListResponse,
ProcessEvent_EndEvent,
ProcessEvent_StartEvent,
- ReconnectProcessRequest,
- ReconnectProcessResponse,
- SendProcessInputRequest,
- SendProcessInputStreamRequest,
- SendProcessSignalRequest,
+ ConnectRequest,
+ ConnectResponse,
+ SendInputRequest,
+ StreamInputRequest,
+ SendSignalRequest,
Signal,
- StartProcessRequest,
- StartProcessResponse,
- UpdateProcessRequest,
+ StartRequest,
+ StartResponse,
+ UpdateRequest,
} from '../../envd/process/v1/process_pb'
-import { concatUint8Arrays } from '../../utils/array'
-import { createDeferredPromise } from '../../utils/promise'
+import { concatUint8Arrays } from '../array'
+import { createDeferredPromise } from '../promise'
// TODO: Sane defaults
// TODO: Reconnect vs connect
@@ -34,13 +34,13 @@ export class Process {
constructor(private readonly transport: Transport) { }
- async list(params: PlainMessage<ListProcessesRequest>): Promise<ListProcessesResponse['processes']> {
- const res = await this.service.listProcesses(params)
+ async list(params: PlainMessage<ListRequest>): Promise<ListResponse['processes']> {
+ const res = await this.service.list(params)
return res.processes
}
async start(
- params: PlainMessage<StartProcessRequest>,
+ params: PlainMessage<StartRequest>,
{
onStderr,
onStdout,
@@ -51,7 +51,7 @@ export class Process {
) {
const controller = new AbortController()
- const res = this.service.startProcess(params, {
+ const res = this.service.start(params, {
signal: controller.signal,
})
@@ -82,7 +82,7 @@ export class Process {
}
private async handleProcessStream(
- stream: AsyncIterable<StartProcessResponse | ReconnectProcessResponse>,
+ stream: AsyncIterable<StartResponse | ConnectResponse>,
{
onStderr,
onStdout,
@@ -147,8 +147,8 @@ export class Process {
}
}
- private async reconnect(
- params: PlainMessage<ReconnectProcessRequest>,
+ private async connect(
+ params: PlainMessage<ConnectRequest>,
{
onStderr,
onStdout,
@@ -165,7 +165,7 @@ export class Process {
const controller = new AbortController()
- const res = this.service.reconnectProcess(params, {
+ const res = this.service.connect(params, {
signal: controller.signal,
})
@@ -192,22 +192,22 @@ export class Process {
}
}
- private async sendSignal(params: PlainMessage<SendProcessSignalRequest>): Promise<void> {
- await this.service.sendProcessSignal(params)
+ private async sendSignal(params: PlainMessage<SendSignalRequest>): Promise<void> {
+ await this.service.sendSignal(params)
}
- private async sendInput(params: PlainMessage<SendProcessInputRequest>): Promise<void> {
- await this.service.sendProcessInput(params)
+ private async sendInput(params: PlainMessage<SendInputRequest>): Promise<void> {
+ await this.service.sendInput(params)
}
- private async update(params: PlainMessage<UpdateProcessRequest>): Promise<void> {
- await this.service.updateProcess(params)
+ private async update(params: PlainMessage<UpdateRequest>): Promise<void> {
+ await this.service.update(params)
}
- private async streamInput(params: AsyncIterable<PlainMessage<SendProcessInputStreamRequest>>) {
+ private async streamInput(params: AsyncIterable<PlainMessage<StreamInputRequest>>) {
const controller = new AbortController()
- this.service.sendProcessInputStream(params, {
+ this.service.streamInput(params, {
signal: controller.signal,
})
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index ceabcb7be..f97e91605 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -1,52 +1,48 @@
-import { APIClient, APIOpts, withAPIKey } from '../api'
-import { getApiKey } from '../utils/apiKey'
-
-export type SandboxMetadata = {
- [key: string]: string
-}
+import { APIClient, withAPIKey } from '../api'
+import { ConnectionConfig, ConnectionOpts } from '../connectionConfig'
export interface RunningSandbox {
sandboxID: string
templateID: string
- alias?: string
- metadata?: SandboxMetadata
+ name?: string
+ metadata?: { [key: string]: string }
startedAt: Date
}
+// TODO: Add requestTimeout
+
export class SandboxApi {
static async kill(
sandboxID: string,
- opts: APIOpts & { apiKey?: string } = {}
+ opts: ConnectionOpts = {}
): Promise<void> {
- const apiKey = getApiKey(opts.apiKey)
+ const config = new ConnectionConfig(opts)
// TODO: Ensure the short id/long id works with kill
- const client = new APIClient(opts)
+ const client = new APIClient(config)
const killSandbox = withAPIKey(
client.api.path('/sandboxes/{sandboxID}').method('delete').create(),
)
- await killSandbox(apiKey, { sandboxID })
+ await killSandbox(config.apiKey, { sandboxID })
}
- static async list(opts: APIOpts & { apiKey?: string } = {}): Promise<RunningSandbox[]> {
- const apiKey = getApiKey(opts.apiKey)
+ static async list(opts: ConnectionOpts = {}): Promise<RunningSandbox[]> {
+ const config = new ConnectionConfig(opts)
- const client = new APIClient(opts)
+ const client = new APIClient(config)
const listSandboxes = withAPIKey(
client.api.path('/sandboxes').method('get').create(),
)
- const res = await listSandboxes(apiKey, {})
+ const res = await listSandboxes(config.apiKey, {})
return res.data.map((sandbox) => ({
sandboxID: this.getSandboxID(sandbox),
templateID: sandbox.templateID,
- cpuCount: sandbox.cpuCount,
- memoryMB: sandbox.memoryMB,
- ...(sandbox.alias && { alias: sandbox.alias }),
+ ...(sandbox.alias && { name: sandbox.alias }),
...(sandbox.metadata && { metadata: sandbox.metadata }),
startedAt: new Date(sandbox.startedAt),
}))
@@ -54,20 +50,19 @@ export class SandboxApi {
protected static async createSandbox(
template: string,
- opts: APIOpts & {
- metadata?: SandboxMetadata,
- apiKey?: string,
+ opts: ConnectionOpts & {
+ metadata?: { [key: string]: string },
timeout?: number,
} = {}): Promise<string> {
- const apiKey = getApiKey(opts.apiKey)
+ const config = new ConnectionConfig(opts)
- const client = new APIClient(opts)
+ const client = new APIClient(config)
const createSandbox = withAPIKey(
client.api.path('/sandboxes').method('post').create(),
)
- const res = await createSandbox(apiKey, {
+ const res = await createSandbox(config.apiKey, {
templateID: template,
metadata: opts.metadata,
timeout: opts.timeout,
@@ -79,20 +74,18 @@ export class SandboxApi {
protected static async setTimeout(
sandboxID: string,
timeout: number,
- opts: APIOpts & {
- apiKey?: string,
- } = {}): Promise<void> {
- const apiKey = getApiKey(opts.apiKey)
+ opts: ConnectionOpts = {}): Promise<void> {
+ const config = new ConnectionConfig(opts)
- const client = new APIClient(opts)
+ const client = new APIClient(config)
const setSandboxTimeout = withAPIKey(
client.api.path('/sandboxes/{sandboxID}/timeout').method('post').create(),
)
- await setSandboxTimeout(apiKey, {
+ await setSandboxTimeout(config.apiKey, {
sandboxID,
- duration: timeout,
+ timeout,
})
}
diff --git a/packages/js-sdk/src/sandbox/sandboxFiles.ts b/packages/js-sdk/src/sandbox/sandboxFiles.ts
index c09a4fb37..ea3e1c3e2 100644
--- a/packages/js-sdk/src/sandbox/sandboxFiles.ts
+++ b/packages/js-sdk/src/sandbox/sandboxFiles.ts
@@ -8,36 +8,28 @@ export type DownloadFileFormat =
export class SandboxFiles {
-
-
-
-
- constructor(private readonly url: string) {
+ constructor(private readonly file_server_url: string) {
}
-
/**
-* URL that can be used to download or upload file to the sandbox via a multipart/form-data POST request.
-* This is useful if you're uploading files directly from the browser.
-* The file will be uploaded to the user's home directory with the same name.
-* If a file with the same name already exists, it will be overwritten.
-*/
- get fileURL() {
- const protocol = this.getProtocol('http', this.opts.__debug_devEnv !== 'local')
- const hostname = this.getHostname(this.opts.__debug_port || ENVD_PORT)
- return `${protocol}://${hostname}${FILE_ROUTE}`
+ * URL that can be used to download or upload file to the sandbox via a multipart/form-data POST request.
+ * This is useful if you're uploading files directly from the browser.
+ * The file will be uploaded to the user's home directory with the same name.
+ * If a file with the same name already exists, it will be overwritten.
+ */
+ get fileUrl(): string {
+ // We need to handle the route without any query parameters
}
-
/**
- * Uploads a file to the sandbox.
- * The file will be uploaded to the user's home directory with the same name.
- * If a file with the same name already exists, it will be overwritten.
- *
- * **You can use the {@link Sandbox.fileURL} property and upload file directly via POST multipart/form-data**
- *
- */
+ * Uploads a file to the sandbox.
+ * The file will be uploaded to the user's home directory with the same name.
+ * If a file with the same name already exists, it will be overwritten.
+ *
+ * **You can use the {@link Sandbox.fileURL} property and upload file directly via POST multipart/form-data**
+ *
+ */
async uploadFile(file: Buffer | Blob, filename: string) {
const body = new FormData()
diff --git a/packages/js-sdk/src/utils/apiKey.ts b/packages/js-sdk/src/utils/apiKey.ts
deleted file mode 100644
index 368ed3006..000000000
--- a/packages/js-sdk/src/utils/apiKey.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { AuthenticationError } from '../error'
-
-export function getApiKey(apiKey?: string): string {
- apiKey = apiKey || process?.env?.E2B_API_KEY
-
- if (!apiKey) {
- throw new AuthenticationError(
- 'API key is required, please visit https://e2b.dev/docs to get your API key. ' +
- 'You can either set the environment variable `E2B_API_KEY` ' +
- "or you can pass it directly to the sandbox like Sandbox.create({ apiKey: 'e2b_...' })",
- )
- }
-
- return apiKey
-}
\ No newline at end of file
diff --git a/packages/js-sdk/src/utils/wait.ts b/packages/js-sdk/src/utils/wait.ts
deleted file mode 100644
index fff60676d..000000000
--- a/packages/js-sdk/src/utils/wait.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-function wait(ms: number) {
- return new Promise(resolve => setTimeout(resolve, ms))
-}
-
-export default wait
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index 96237920a..3bed12e77 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -7,47 +7,14 @@ E2B Sandbox is a secure sandboxed cloud environment made for AI agents and AI
apps. Sandboxes allow AI agents and apps to have long running cloud secure
environments. In these environments, large language models can use the same
tools as humans do.
-
-
-```py
-from e2b import Sandbox
-
-# Create sandbox
-sandbox = Sandbox()
-
-# Let an LLM use the sandbox here
-
-# Close sandbox once done
-sandbox.close()
-```
"""
from .api import (
E2BApiClient,
client,
)
-from .constants import DOMAIN
+from .connection_config import ConnectionConfig
from .sandbox import (
Sandbox,
- FilesystemOperation,
- FilesystemWatcher,
- FileInfo,
- FilesystemEvent,
- FilesystemManager,
- TerminalManager,
- Terminal,
- ProcessManager,
- Process,
- OpenPort,
- EnvVars,
- SandboxException,
- TerminalException,
- ProcessException,
- CurrentWorkingDirectoryDoesntExistException,
- FilesystemException,
- RpcException,
- ProcessMessage,
- ProcessOutput,
- TerminalOutput,
- RunningSandbox,
)
+from .sandbox.exceptions import SandboxException, AuthenticationException
diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.py
index 6336778e9..9bcaa3615 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -1,7 +1,6 @@
from importlib.metadata import version
-from typing import Union
-from e2b.constants import DOMAIN, PROTOCOL, DEBUG
+from e2b.connection_config import ConnectionConfig
from e2b.api.metadata import default_headers
@@ -19,21 +18,16 @@ else:
class E2BApiClient(client.ApiClient):
def __init__(
self,
- api_key: Union[str, None] = None,
- access_token: Union[str, None] = None,
- domain: str = DOMAIN,
+ config: ConnectionConfig,
*args,
**kwargs,
):
- prefix = "" if DEBUG else f"api."
- api_host = f"{PROTOCOL}://{prefix}{domain}"
-
# Defining the host is optional and defaults to https://api.e2b.dev
# See configuration.py for a list of all supported configuration parameters.
- configuration = client.Configuration(host=api_host)
+ configuration = client.Configuration(host=config.api_url)
- configuration.api_key["ApiKeyAuth"] = api_key
- configuration.access_token = access_token
+ configuration.api_key["ApiKeyAuth"] = config.api_key
+ configuration.access_token = config.access_token
super().__init__(configuration, *args, **kwargs)
self.default_headers = default_headers
diff --git a/packages/python-sdk/e2b/api/metadata.py b/packages/python-sdk/e2b/api/metadata.py
index 52e6820fd..0e46292f2 100644
--- a/packages/python-sdk/e2b/api/metadata.py
+++ b/packages/python-sdk/e2b/api/metadata.py
@@ -7,6 +7,7 @@ default_headers = {
"lang_version": platform.python_version(),
"machine": platform.machine(),
"os": platform.platform(),
+ # TODO: Should this be disabled?
# "package_version": metadata.version("e2b"),
"processor": platform.processor(),
"publisher": "e2b",
diff --git a/packages/python-sdk/e2b/api/v1/client/models/new_sandbox.py b/packages/python-sdk/e2b/api/v1/client/models/new_sandbox.py
index 052eb1fb5..e8fba9c91 100644
--- a/packages/python-sdk/e2b/api/v1/client/models/new_sandbox.py
+++ b/packages/python-sdk/e2b/api/v1/client/models/new_sandbox.py
@@ -31,7 +31,7 @@ class NewSandbox(BaseModel):
..., alias="templateID", description="Identifier of the required template"
)
timeout: Optional[conint(strict=True, ge=0)] = Field(
- None, description="Time to live for the sandbox in seconds."
+ 15, description="Time to live for the sandbox in seconds."
)
metadata: Optional[Dict[str, StrictStr]] = None
additional_properties: Dict[str, Any] = {}
@@ -80,7 +80,7 @@ class NewSandbox(BaseModel):
_obj = NewSandbox.parse_obj(
{
"template_id": obj.get("templateID"),
- "timeout": obj.get("timeout"),
+ "timeout": obj.get("timeout") if obj.get("timeout") is not None else 15,
"metadata": obj.get("metadata"),
}
)
diff --git a/packages/python-sdk/e2b/api/v1/client/models/sandboxes_sandbox_id_timeout_post_request.py b/packages/python-sdk/e2b/api/v1/client/models/sandboxes_sandbox_id_timeout_post_request.py
index fd515c8ed..def5117ba 100644
--- a/packages/python-sdk/e2b/api/v1/client/models/sandboxes_sandbox_id_timeout_post_request.py
+++ b/packages/python-sdk/e2b/api/v1/client/models/sandboxes_sandbox_id_timeout_post_request.py
@@ -18,7 +18,7 @@ import re # noqa: F401
import json
-from typing import Any, Dict, Optional
+from typing import Any, Dict
from pydantic import BaseModel, Field, conint
@@ -27,12 +27,12 @@ class SandboxesSandboxIDTimeoutPostRequest(BaseModel):
SandboxesSandboxIDTimeoutPostRequest
"""
- duration: Optional[conint(strict=True, ge=0)] = Field(
- None,
- description="Duration in seconds from the current time after which the sandbox should expire",
+ timeout: conint(strict=True, ge=0) = Field(
+ ...,
+ description="Timeout in seconds from the current time after which the sandbox should expire",
)
additional_properties: Dict[str, Any] = {}
- __properties = ["duration"]
+ __properties = ["timeout"]
class Config:
"""Pydantic configuration"""
@@ -75,7 +75,7 @@ class SandboxesSandboxIDTimeoutPostRequest(BaseModel):
return SandboxesSandboxIDTimeoutPostRequest.parse_obj(obj)
_obj = SandboxesSandboxIDTimeoutPostRequest.parse_obj(
- {"duration": obj.get("duration")}
+ {"timeout": obj.get("timeout")}
)
# store additional fields in additional_properties
for _key in obj.keys():
diff --git a/packages/python-sdk/e2b/api/v2/client/models/new_sandbox.py b/packages/python-sdk/e2b/api/v2/client/models/new_sandbox.py
index 92a034d70..aafac2ba2 100644
--- a/packages/python-sdk/e2b/api/v2/client/models/new_sandbox.py
+++ b/packages/python-sdk/e2b/api/v2/client/models/new_sandbox.py
@@ -38,7 +38,7 @@ class NewSandbox(BaseModel):
description="Identifier of the required template", alias="templateID"
)
timeout: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(
- default=None, description="Time to live for the sandbox in seconds."
+ default=15, description="Time to live for the sandbox in seconds."
)
metadata: Optional[Dict[str, StrictStr]] = None
additional_properties: Dict[str, Any] = {}
@@ -97,7 +97,7 @@ class NewSandbox(BaseModel):
_obj = cls.model_validate(
{
"templateID": obj.get("templateID"),
- "timeout": obj.get("timeout"),
+ "timeout": obj.get("timeout") if obj.get("timeout") is not None else 15,
"metadata": obj.get("metadata"),
}
)
diff --git a/packages/python-sdk/e2b/api/v2/client/models/sandboxes_sandbox_id_timeout_post_request.py b/packages/python-sdk/e2b/api/v2/client/models/sandboxes_sandbox_id_timeout_post_request.py
index 859dc2855..1c52c913f 100644
--- a/packages/python-sdk/e2b/api/v2/client/models/sandboxes_sandbox_id_timeout_post_request.py
+++ b/packages/python-sdk/e2b/api/v2/client/models/sandboxes_sandbox_id_timeout_post_request.py
@@ -18,7 +18,7 @@ import re # noqa: F401
import json
-from typing import Any, ClassVar, Dict, List, Optional
+from typing import Any, ClassVar, Dict, List
from pydantic import BaseModel
from pydantic import Field
from typing_extensions import Annotated
@@ -34,12 +34,11 @@ class SandboxesSandboxIDTimeoutPostRequest(BaseModel):
SandboxesSandboxIDTimeoutPostRequest
""" # noqa: E501
- duration: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(
- default=None,
- description="Duration in seconds from the current time after which the sandbox should expire",
+ timeout: Annotated[int, Field(strict=True, ge=0)] = Field(
+ description="Timeout in seconds from the current time after which the sandbox should expire"
)
additional_properties: Dict[str, Any] = {}
- __properties: ClassVar[List[str]] = ["duration"]
+ __properties: ClassVar[List[str]] = ["timeout"]
model_config = {"populate_by_name": True, "validate_assignment": True}
@@ -91,7 +90,7 @@ class SandboxesSandboxIDTimeoutPostRequest(BaseModel):
if not isinstance(obj, dict):
return cls.model_validate(obj)
- _obj = cls.model_validate({"duration": obj.get("duration")})
+ _obj = cls.model_validate({"timeout": obj.get("timeout")})
# store additional fields in additional_properties
for _key in obj.keys():
if _key not in cls.__properties:
diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.py
new file mode 100644
index 000000000..b85ac677c
--- /dev/null
+++ b/packages/python-sdk/e2b/connection_config.py
@@ -0,0 +1,37 @@
+import os
+
+from typing import Optional
+from e2b.sandbox.exceptions import AuthenticationException
+
+
+DOMAIN = os.getenv("E2B_DOMAIN", "e2b.dev")
+DEBUG = os.getenv("E2B_DEBUG", "false") == "true"
+API_KEY = os.getenv("E2B_API_KEY")
+ACCESS_TOKEN = os.getenv("E2B_ACCESS_TOKEN")
+
+
+class ConnectionConfig:
+ @property
+ def api_key(self):
+ if self._api_key is None:
+ raise AuthenticationException(
+ "API key is required, please visit https://e2b.dev/docs to get your API key. "
+ "You can either set the environment variable `E2B_API_KEY` "
+ 'or you can pass it directly to the sandbox like Sandbox(api_key="e2b_...")',
+ )
+
+ return self._api_key
+
+ def __init__(
+ self,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ api_key: Optional[str] = None,
+ access_token: Optional[str] = None,
+ ):
+ self.domain = domain or DOMAIN
+ self.debug = debug or DEBUG
+ self._api_key = api_key or API_KEY
+ self.access_token = access_token or ACCESS_TOKEN
+
+ self.api_url = "http://localhost:3000" if debug else f"https://api.{domain}"
diff --git a/packages/python-sdk/e2b/constants.py b/packages/python-sdk/e2b/constants.py
deleted file mode 100644
index a7fdf380a..000000000
--- a/packages/python-sdk/e2b/constants.py
+++ /dev/null
@@ -1,15 +0,0 @@
-import os
-
-SANDBOX_REFRESH_PERIOD = 5 # seconds
-
-TIMEOUT = 60
-
-SECURE = os.getenv("E2B_SECURE", "TRUE").upper() == "TRUE"
-DEBUG = os.getenv("E2B_DEBUG") or False
-PROTOCOL = "https" if SECURE and not DEBUG else "http"
-
-DOMAIN = os.getenv("E2B_DOMAIN") or (DEBUG and "localhost:3000") or "e2b.dev"
-
-ENVD_PORT = 49982
-WS_ROUTE = "/ws"
-FILE_ROUTE = "/file"
diff --git a/packages/python-sdk/e2b/sandbox/__init__.py b/packages/python-sdk/e2b/sandbox/__init__.py
index 47a0d1873..919f42e3f 100644
--- a/packages/python-sdk/e2b/sandbox/__init__.py
+++ b/packages/python-sdk/e2b/sandbox/__init__.py
@@ -1,34 +1 @@
-from .code_snippet import OpenPort
-from .env_vars import EnvVars
-from .exception import (
- CurrentWorkingDirectoryDoesntExistException,
- FilesystemException,
- ProcessException,
- RpcException,
- SandboxException,
- TerminalException,
- TimeoutException,
- AuthenticationException,
- SandboxNotOpenException,
- UnsupportedRuntimeException,
- MultipleExceptions,
-)
-from .filesystem import FileInfo, FilesystemManager
-from .filesystem_watcher import (
- FilesystemEvent,
- FilesystemOperation,
- FilesystemWatcher,
-)
from .main import Sandbox
-from .process import (
- Process,
- ProcessManager,
- ProcessMessage,
- ProcessOutput,
-)
-from .terminal import (
- Terminal,
- TerminalManager,
- TerminalOutput,
-)
-from .sandbox_connection import RunningSandbox
diff --git a/packages/python-sdk/e2b/sandbox/code_snippet.py b/packages/python-sdk/e2b/sandbox/code_snippet.py
deleted file mode 100644
index d1a96afb0..000000000
--- a/packages/python-sdk/e2b/sandbox/code_snippet.py
+++ /dev/null
@@ -1,54 +0,0 @@
-from typing import Any, Callable, ClassVar, List, Optional
-from pydantic import BaseModel
-
-from e2b.sandbox.exception import MultipleExceptions, RpcException, SandboxException
-from e2b.sandbox.sandbox_connection import SandboxConnection, SubscriptionArgs
-
-
-class OpenPort(BaseModel):
- ip: str
- port: int
- state: str
-
-
-ScanOpenedPortsHandler = Callable[[List[OpenPort]], Any]
-
-
-class CodeSnippetManager(BaseModel):
- # TODO: Change to model_config = ConfigDict(arbitrary_types_allowed=True) when only pydantic 2.0 is used
- class Config:
- arbitrary_types_allowed = True
-
- service_name: ClassVar[str] = "codeSnippet"
- sandbox: SandboxConnection
-
- on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None
-
- def _subscribe(self):
- def on_scan_ports(ports: List[dict]):
- ports = [
- OpenPort(
- ip=port["Ip"],
- port=port["Port"],
- state=port["State"],
- )
- for port in ports
- ]
- if self.on_scan_ports:
- self.on_scan_ports(ports)
-
- if self.on_scan_ports:
- try:
- self.sandbox._handle_subscriptions(
- SubscriptionArgs(
- service=self.service_name,
- handler=on_scan_ports,
- method="scanOpenedPorts",
- )
- )
- except RpcException as e:
- raise SandboxException(e.message) from e
- except MultipleExceptions as e:
- raise SandboxException("Failed to subscribe to RPC services") from e
-
- return self
diff --git a/packages/python-sdk/e2b/sandbox/constants.py b/packages/python-sdk/e2b/sandbox/constants.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/packages/python-sdk/e2b/sandbox/env_vars.py b/packages/python-sdk/e2b/sandbox/env_vars.py
deleted file mode 100644
index ece9e8f31..000000000
--- a/packages/python-sdk/e2b/sandbox/env_vars.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from typing import Dict
-
-EnvVars = Dict[str, str]
diff --git a/packages/python-sdk/e2b/sandbox/exception.py b/packages/python-sdk/e2b/sandbox/exception.py
deleted file mode 100644
index 8565733f9..000000000
--- a/packages/python-sdk/e2b/sandbox/exception.py
+++ /dev/null
@@ -1,58 +0,0 @@
-from typing import Dict, List, Optional
-
-
-class SandboxException(Exception):
- pass
-
-
-class SandboxNotOpenException(Exception):
- pass
-
-
-class RpcException(SandboxException):
- def __init__(
- self,
- message: str,
- code: int,
- id: str,
- data: Optional[Dict] = None,
- ):
- super().__init__(message)
- self.data = data
- self.code = code
- self.message = message
- self.id = id
-
-
-class MultipleExceptions(SandboxException):
- def __init__(self, message: str, exceptions: List[Exception]):
- super().__init__(f"Multiple exceptions occurred: {message}")
- self.exceptions = exceptions
-
-
-class FilesystemException(SandboxException):
- pass
-
-
-class ProcessException(SandboxException):
- pass
-
-
-class CurrentWorkingDirectoryDoesntExistException(ProcessException):
- pass
-
-
-class TerminalException(SandboxException):
- pass
-
-
-class AuthenticationException(SandboxException):
- pass
-
-
-class UnsupportedRuntimeException(SandboxException):
- pass
-
-
-class TimeoutException(SandboxException):
- pass
diff --git a/packages/python-sdk/e2b/sandbox/exceptions.py b/packages/python-sdk/e2b/sandbox/exceptions.py
new file mode 100644
index 000000000..e7b8429cf
--- /dev/null
+++ b/packages/python-sdk/e2b/sandbox/exceptions.py
@@ -0,0 +1,6 @@
+class SandboxException(Exception):
+ pass
+
+
+class AuthenticationException(SandboxException):
+ pass
diff --git a/packages/python-sdk/e2b/sandbox/filesystem.py b/packages/python-sdk/e2b/sandbox/filesystem.py
index 105f3a1bb..b301e565e 100644
--- a/packages/python-sdk/e2b/sandbox/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox/filesystem.py
@@ -1,189 +1,29 @@
-import base64
-import logging
-from typing import Any, List, Optional
+import warnings
-from pydantic import BaseModel
+from pathlib import PurePosixPath
+from typing import Optional
-from e2b.constants import TIMEOUT
-from e2b.sandbox.exception import FilesystemException, RpcException
-from e2b.sandbox.filesystem_watcher import FilesystemWatcher
-from e2b.sandbox.sandbox_connection import SandboxConnection
-from e2b.utils.filesystem import resolve_path
-logger = logging.getLogger(__name__)
+def resolve_path(path: str, cwd: Optional[str] = None) -> str:
+ warning = f"Path starts with {{0}} and cwd isn't set. The path {path} will evaluate to `{{1}}`, which may not be what you want."
+ if path.startswith("./"):
+ result = PurePosixPath(cwd or "/home/user", path).as_posix()
+ if not cwd:
+ warnings.warn(warning.format("./", result))
+ return result
+ if path.startswith("../"):
+ result = PurePosixPath(cwd or "/home/user", path).as_posix()
+ if not cwd:
+ warnings.warn(warning.format("../", result))
+ return result
-class FileInfo(BaseModel):
- """
- Information about a file or a directory in the sandbox.
- """
+ if path.startswith("~/"):
+ result = PurePosixPath("/home/user", path[2:]).as_posix()
+ warnings.warn(warning.format("~/", result))
+ return result
- is_dir: bool
- name: str
+ if not path.startswith("/") and cwd:
+ return PurePosixPath(cwd, path).as_posix()
-
-class FilesystemManager:
- """
- Manager for interacting with the filesystem in the sandbox.
- """
-
- _service_name = "filesystem"
-
- def __init__(self, sandbox: SandboxConnection):
- self._sandbox = sandbox
-
- @property
- def cwd(self) -> Optional[str]:
- return self._sandbox.cwd
-
- def read_bytes(self, path: str, timeout: Optional[float] = TIMEOUT) -> bytes:
- """
- Read the whole content of a file as a byte array.
- This can be used when you cannot represent the data as an UTF-8 string.
-
- :param path: path to a file
- :param timeout: timeout for the call
- :return: byte array representing the content of a file
- """
- path = resolve_path(path, self.cwd)
- result: str = self._sandbox._call(
- self._service_name, "readBase64", [path], timeout=timeout
- )
- return base64.b64decode(result)
-
- def write_bytes(
- self, path: str, content: bytes, timeout: Optional[float] = TIMEOUT
- ) -> None:
- """
- Write content to a file as a byte array.
- This can be used when you cannot represent the data as an UTF-8 string.
-
- A new file will be created if it doesn't exist.
- If the file already exists, it will be overwritten.
-
- :param path: path to a file
- :param timeout: timeout for the call
- :param content: byte array representing the content to write
- """
- path = resolve_path(path, self.cwd)
- base64_content = base64.b64encode(content).decode("utf-8")
- self._sandbox._call(
- self._service_name, "writeBase64", [path, base64_content], timeout=timeout
- )
-
- def read(self, path: str, timeout: Optional[float] = TIMEOUT) -> str:
- """
- Read the whole content of a file as an array of bytes.
-
- :param path: Path to a file
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
- :return: Content of a file
- """
- logger.debug(f"Reading file {path}")
-
- path = resolve_path(path, self.cwd)
- try:
- result: str = self._sandbox._call(
- self._service_name, "read", [path], timeout=timeout
- )
- logger.debug(f"Read file {path}")
- return result
- except RpcException as e:
- raise FilesystemException(e.message) from e
-
- def write(
- self, path: str, content: str, timeout: Optional[float] = TIMEOUT
- ) -> None:
- """
- Write content to a file.
-
- A new file will be created if it doesn't exist.
- If the file already exists, it will be overwritten.
-
- :param path: Path to a file
- :param content: Content to write
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
- """
- logger.debug(f"Writing file {path}")
-
- path = resolve_path(path, self.cwd)
- try:
- self._sandbox._call(
- self._service_name, "write", [path, content], timeout=timeout
- )
- logger.debug(f"Wrote file {path}")
- except RpcException as e:
- raise FilesystemException(e.message) from e
-
- def remove(self, path: str, timeout: Optional[float] = TIMEOUT) -> None:
- """
- Remove a file or a directory.
-
- :param path: Path to a file or a directory
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
- """
- logger.debug(f"Removing file {path}")
-
- path = resolve_path(path, self.cwd)
- try:
- self._sandbox._call(self._service_name, "remove", [path], timeout=timeout)
- logger.debug(f"Removed file {path}")
- except RpcException as e:
- raise FilesystemException(e.message) from e
-
- def list(self, path: str, timeout: Optional[float] = TIMEOUT) -> List[FileInfo]:
- """
- List files in a directory.
-
- :param path: Path to a directory
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
-
- :return: Array of files in a directory
- """
- logger.debug(f"Listing files in {path}")
-
- path = resolve_path(path, self.cwd)
- try:
- result: List[Any] = self._sandbox._call(
- self._service_name, "list", [path], timeout=timeout
- )
- logger.debug(f"Listed files in {path}, result: {result}")
- return [
- FileInfo(is_dir=file_info["isDir"], name=file_info["name"])
- for file_info in result
- ]
- except RpcException as e:
- raise FilesystemException(e.message) from e
-
- def make_dir(self, path: str, timeout: Optional[float] = TIMEOUT) -> None:
- """
- Create a new directory and all directories along the way if needed on the specified path.
-
- :param path: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
- """
- logger.debug(f"Creating directory {path}")
-
- path = resolve_path(path, self.cwd)
- try:
- self._sandbox._call(self._service_name, "makeDir", [path], timeout=timeout)
- logger.debug(f"Created directory {path}")
- except RpcException as e:
- raise FilesystemException(e.message) from e
-
- def watch_dir(self, path: str) -> FilesystemWatcher:
- """
- Watches directory for filesystem events.
-
- :param path: Path to a directory that will be watched
-
- :return: New watcher
- """
- logger.debug(f"Watching directory {path}")
-
- path = resolve_path(path, self.cwd)
- return FilesystemWatcher(
- connection=self._sandbox,
- path=path,
- service_name=self._service_name,
- )
+ return path
diff --git a/packages/python-sdk/e2b/sandbox/filesystem_watcher.py b/packages/python-sdk/e2b/sandbox/filesystem_watcher.py
deleted file mode 100644
index df7095842..000000000
--- a/packages/python-sdk/e2b/sandbox/filesystem_watcher.py
+++ /dev/null
@@ -1,115 +0,0 @@
-import logging
-
-from enum import Enum
-from typing import Any, Callable, Optional, Set
-
-from pydantic import BaseModel
-
-from e2b.constants import TIMEOUT
-from e2b.sandbox.exception import FilesystemException, RpcException
-from e2b.sandbox.sandbox_connection import SandboxConnection
-from e2b.utils.str import snake_case_to_camel_case
-
-logger = logging.getLogger(__name__)
-
-
-class FilesystemOperation(str, Enum):
- Create = "Create"
- Write = "Write"
- Remove = "Remove"
- Rename = "Rename"
- Chmod = "Chmod"
-
-
-class FilesystemEvent(BaseModel):
- path: str
- name: str
- operation: FilesystemOperation
- timestamp: int
- """
- Unix epoch in nanoseconds
- """
- is_dir: bool
-
- class Config:
- alias_generator = snake_case_to_camel_case
-
-
-class FilesystemWatcher:
- @property
- def path(self) -> str:
- """
- The path to watch.
- """
- return self._path
-
- def __init__(
- self,
- connection: SandboxConnection,
- path: str,
- service_name: str,
- ):
- self._connection = connection
- self._path = path
- self._service_name = service_name
- self._unsubscribe: Optional[Callable[[], Any]] = None
- self._listeners: Set[Callable[[FilesystemEvent], Any]] = set()
-
- def start(self, timeout: Optional[float] = TIMEOUT) -> None:
- """
- Start the filesystem watcher.
-
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
- """
- if self._unsubscribe:
- return
-
- logger.debug("Starting filesystem watcher for %s", self.path)
- try:
- self._unsubscribe = self._connection._subscribe(
- self._service_name,
- self._handle_filesystem_events,
- "watchDir",
- self.path,
- timeout=timeout,
- )
- logger.debug("Started filesystem watcher for %s", self.path)
- except RpcException as e:
- raise FilesystemException(e.message) from e
-
- def stop(self) -> None:
- """
- Stop the filesystem watcher.
- """
- logger.debug("Stopping filesystem watcher for %s", self.path)
-
- self._listeners.clear()
- if self._unsubscribe:
- try:
- self._unsubscribe()
- self._unsubscribe = None
- logger.debug("Stopped filesystem watcher for %s", self.path)
- except RpcException as e:
- raise FilesystemException(e.message) from e
-
- def add_event_listener(self, listener: Callable[[FilesystemEvent], Any]):
- """
- Add a listener for filesystem events.
-
- :param listener: Listener to add
-
- :return: Function that removes the listener
- """
- logger.debug("Adding filesystem watcher listener for %s", self.path)
-
- self._listeners.add(listener)
-
- def delete_listener() -> None:
- self._listeners.remove(listener)
-
- return delete_listener
-
- def _handle_filesystem_events(self, event: dict) -> None:
- event = FilesystemEvent(**event)
- for listener in self._listeners:
- listener(event)
diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.py
index 89b4c9f70..5123933ce 100644
--- a/packages/python-sdk/e2b/sandbox/main.py
+++ b/packages/python-sdk/e2b/sandbox/main.py
@@ -1,291 +1,98 @@
import logging
-import urllib.parse
-import requests
-import threading
-from os import path
-from typing import Any, Callable, Dict, List, Literal, Optional, IO, Union
+from typing import Optional, Dict
-from e2b.api import models
-from e2b.constants import TIMEOUT, ENVD_PORT, FILE_ROUTE, DOMAIN
-from e2b.sandbox.code_snippet import CodeSnippetManager, OpenPort
-from e2b.sandbox.env_vars import EnvVars
-from e2b.sandbox.filesystem import FilesystemManager
-from e2b.sandbox.process import ProcessManager, ProcessMessage
-from e2b.sandbox.sandbox_connection import SandboxConnection
-from e2b.sandbox.terminal import TerminalManager
+from e2b.sandbox.rpc.main import SandboxRpc
+from e2b.sandbox.sandbox_api import SandboxApi
+from e2b.sandbox.sandbox_files import SandboxFiles
+from e2b.connection_config import ConnectionConfig
logger = logging.getLogger(__name__)
+SANDBOX_SERVER_PORT = 49982
-class Sandbox(SandboxConnection):
- """
- E2B cloud sandbox gives your agent a full cloud development environment that's sandboxed.
-
- That means:
- - Access to Linux OS
- - Using filesystem (create, list, and delete files and dirs)
- - Run processes
- - Sandboxed - you can run any code
- - Access to the internet
-
- Check usage docs - https://e2b.dev/docs/sandbox/overview
-
- These cloud sandboxes are meant to be used for agents. Like a sandboxed playgrounds, where the agent can do whatever it wants.
- """
-
- @property
- def process(self) -> ProcessManager:
- """
- Process manager used to run commands.
- """
- return self._process
-
- @property
- def terminal(self) -> TerminalManager:
- """
- Terminal manager used to create interactive terminals.
- """
- return self._terminal
-
- @property
- def filesystem(self) -> FilesystemManager:
- """
- Filesystem manager used to manage files.
- """
- return self._filesystem
+class Sandbox(SandboxApi):
def __init__(
self,
template: str = "base",
- id: Optional[str] = None,
- api_key: Optional[str] = None,
- cwd: Optional[str] = None,
- env_vars: Optional[EnvVars] = None,
- on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
- on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
- on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
- on_exit: Optional[Union[Callable[[int], Any], Callable[[], Any]]] = None,
+ timeout: Optional[int] = None,
metadata: Optional[Dict[str, str]] = None,
- timeout: Optional[float] = TIMEOUT,
- domain: str = DOMAIN,
- _sandbox: Optional[models.Sandbox] = None,
- _debug_hostname: Optional[str] = None,
- _debug_port: Optional[int] = None,
- _debug_dev_env: Optional[Literal["remote", "local"]] = None,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ sandbox_id: Optional[str] = None,
):
- """
- Create a new cloud sandbox.
-
- :param id: [Deprecated] Use `template` param instead.
- :param template: ID of the sandbox template or the name of prepared template. If not specified a 'base' template will be used.
- Can be one of the following premade sandbox templates or a custom sandbox template ID:
- - `base` - A basic sandbox with a Linux environment
-
- :param api_key: The API key to use, if not provided, the `E2B_API_KEY` environment variable is used
- :param cwd: The current working directory to use
- :param env_vars: A dictionary of environment variables to be used for all processes
- :param on_scan_ports: A callback to handle opened ports
- :param on_stdout: A default callback that is called when stdout with a newline is received from the process
- :param on_stderr: A default callback that is called when stderr with a newline is received from the process
- :param on_exit: A default callback that is called when the process exits
- :param metadata: A dictionary of strings that is stored alongside the running sandbox. You can see this metadata when you list running sandboxes.
- :param timeout: Timeout for sandbox to initialize in seconds, default is 60 seconds
- :param domain: The domain to use for the API
- """
+ super().__init__()
- template = id or template or "base"
-
- if id:
- logger.warning("The id parameter is deprecated, use template instead.")
-
- logger.info(
- f"Creating sandbox {template if isinstance(template, str) else type(template)}"
+ self._connection_config = ConnectionConfig(
+ api_key=api_key,
+ domain=domain,
+ debug=debug,
)
- if cwd and cwd.startswith("~"):
- cwd = cwd.replace("~", "/home/user")
- self._code_snippet = CodeSnippetManager(
- sandbox=self,
- on_scan_ports=on_scan_ports,
+ if sandbox_id is None:
+ self.sandbox_id = self._create_sandbox(
+ template=template,
+ api_key=api_key,
+ timeout=timeout,
+ metadata=metadata,
+ domain=domain,
+ debug=debug,
+ )
+ else:
+ self.sandbox_id = sandbox_id
+
+ sandbox_server_url = (
+ f"{'http' if debug else 'https'}://{self.get_hostname(SANDBOX_SERVER_PORT)}"
)
- self._on_stdout = on_stdout
- self._on_stderr = on_stderr
+ self._rpc = SandboxRpc(url=sandbox_server_url)
+ self._files = SandboxFiles(sandbox_server_url)
- default_env_vars = {"PYTHONUNBUFFERED": "1"}
+ @property
+ def filesystem(self):
+ return self._rpc.filesystem
- self._terminal = TerminalManager(sandbox=self)
- self._filesystem = FilesystemManager(sandbox=self)
- self._process = ProcessManager(
- sandbox=self,
- on_stdout=on_stdout,
- on_stderr=on_stderr,
- on_exit=on_exit,
- )
- super().__init__(
- template=template,
- api_key=api_key,
- cwd=cwd,
- env_vars={
- **default_env_vars,
- **(env_vars or {}),
- },
- metadata=metadata,
- _sandbox=_sandbox,
- _debug_hostname=_debug_hostname,
- _debug_port=_debug_port,
- _debug_dev_env=_debug_dev_env,
- timeout=timeout,
- domain=domain,
- )
+ @property
+ def process(self):
+ return self._rpc.process
- def _handle_start_cmd_logs(self):
- def run_in_thread():
- self.process.start(
- "sudo journalctl --follow --lines=all -o cat _SYSTEMD_UNIT=start_cmd.service",
- cwd="/",
- env_vars={},
- )
+ def get_hostname(self, port: int) -> str:
+ if self._connection_config.debug:
+ return f"localhost:{port}"
- thread = threading.Thread(target=run_in_thread)
- thread.start()
+ return f"{port}-{self.sandbox_id}.{self._connection_config.domain}"
@classmethod
- def reconnect(
+ def connect(
cls,
sandbox_id: str,
- cwd: Optional[str] = None,
- env_vars: Optional[EnvVars] = None,
- on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
- on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
- on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
- on_exit: Optional[Union[Callable[[int], Any], Callable[[], Any]]] = None,
- timeout: Optional[float] = TIMEOUT,
api_key: Optional[str] = None,
- domain: str = DOMAIN,
- _debug_hostname: Optional[str] = None,
- _debug_port: Optional[int] = None,
- _debug_dev_env: Optional[Literal["remote", "local"]] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
):
- """
- Reconnects to a previously created sandbox.
-
- :param sandbox_id: ID of the sandbox to reconnect to
- :param cwd: The current working directory to use
- :param env_vars: A dictionary of environment variables to be used for all processes
- :param on_scan_ports: A callback to handle opened ports
- :param on_stdout: A default callback that is called when stdout with a newline is received from the process
- :param on_stderr: A default callback that is called when stderr with a newline is received from the process
- :param on_exit: A default callback that is called when the process exits
- :param timeout: Timeout for sandbox to initialize in seconds, default is 60 seconds
- :param api_key: The API key to use, if not provided, the `E2B_API_KEY` environment variable is used
- :param domain: The domain to use for the API
-
- ```py
- sandbox = Sandbox()
- id = sandbox.id
- sandbox.keep_alive(300)
- sandbox.close()
-
- # Reconnect to the sandbox
- reconnected_sandbox = Sandbox.reconnect(id)
- ```
-
- """
-
- logger.info(f"Reconnecting to sandbox {sandbox_id}")
- sandbox_id, client_id = sandbox_id.split("-")
return cls(
- cwd=cwd,
- env_vars=env_vars,
- on_scan_ports=on_scan_ports,
- on_stdout=on_stdout,
- on_stderr=on_stderr,
- on_exit=on_exit,
- timeout=timeout,
+ sandbox_id=sandbox_id,
api_key=api_key,
domain=domain,
- _sandbox=models.Sandbox(
- sandbox_id=sandbox_id,
- client_id=client_id,
- template_id=getattr(cls, "sandbox_template_id", "unknown"),
- ),
+ debug=debug,
)
- def _open(
+ def set_timeout(
self,
- metadata: Optional[Dict[str, str]] = None,
- timeout: Optional[float] = TIMEOUT,
+ timeout: int,
) -> None:
- """
- Open the sandbox.
-
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
- """
- logger.info(f"Opening sandbox {self._template}")
- super()._open(metadata=metadata, timeout=timeout)
- # self._code_snippet._subscribe()
- logger.info(f"Sandbox {self._template} opened")
-
- # if self.cwd:
- # self.filesystem.make_dir(self.cwd)
-
- # if self._on_stderr or self._on_stdout:
- # self._handle_start_cmd_logs()
-
- def file_url(self) -> str:
- """
- Return a URL that can be used to upload files to the sandbox via a multipart/form-data POST request.
- This is useful if you're uploading files directly from the browser.
- The file will be uploaded to the user's home directory with the same name.
- If a file with the same name already exists, it will be overwritten.
- """
- hostname = self.get_hostname(self._debug_port or ENVD_PORT)
- protocol = self.get_protocol(secure=self._debug_dev_env != "local")
+ # TODO: Ensure the ** works
- file_url = f"{protocol}://{hostname}{FILE_ROUTE}"
-
- return file_url
-
- def upload_file(self, file: IO, timeout: Optional[float] = TIMEOUT) -> str:
- """
- Upload a file to the sandbox.
- The file will be uploaded to the user's home (`/home/user`) directory with the same name.
- If a file with the same name already exists, it will be overwritten.
-
- :param file: The file to upload
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
- """
- files = {"file": file}
- r = requests.post(self.file_url(), files=files, timeout=timeout)
- if r.status_code != 200:
- raise Exception(f"Failed to upload file: {r.reason} {r.text}")
-
- filename = path.basename(file.name)
- return f"/home/user/{filename}"
-
- def download_file(
- self, remote_path: str, timeout: Optional[float] = TIMEOUT
- ) -> bytes:
- """
- Download a file from the sandbox and returns it's content as bytes.
-
- :param remote_path: The path of the file to download
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
- """
- encoded_path = urllib.parse.quote(remote_path)
- url = f"{self.file_url()}?path={encoded_path}"
- r = requests.get(url, timeout=timeout)
-
- if r.status_code != 200:
- raise Exception(
- f"Failed to download file '{remote_path}'. {r.reason} {r.text}"
- )
- return r.content
-
- def __enter__(self):
- return self
+ super().set_timeout(
+ sandbox_id=self.sandbox_id,
+ timeout=timeout,
+ **self._connection_config.__dict__,
+ )
- def __exit__(self, exc_type, exc_value, traceback):
- self.close()
+ def kill(self) -> None:
+ super().kill(
+ sandbox_id=self.sandbox_id,
+ **self._connection_config.__dict__,
+ )
diff --git a/packages/python-sdk/e2b/sandbox/out.py b/packages/python-sdk/e2b/sandbox/out.py
deleted file mode 100644
index ead553da5..000000000
--- a/packages/python-sdk/e2b/sandbox/out.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from enum import Enum
-from pydantic import BaseModel
-
-
-class OutType(str, Enum):
- Stdout = "Stdout"
- Stderr = "Stderr"
-
-
-class OutResponse(BaseModel):
- type: OutType
- timestamp: int
- """
- Unix epoch in nanoseconds.
- """
- line: str
-
-
-class OutStdoutResponse(OutResponse):
- type: OutType = OutType.Stdout
-
-
-class OutStderrResponse(OutResponse):
- type: OutType = OutType.Stderr
diff --git a/packages/python-sdk/e2b/sandbox/process.py b/packages/python-sdk/e2b/sandbox/process.py
index 043493833..43ef71b16 100644
--- a/packages/python-sdk/e2b/sandbox/process.py
+++ b/packages/python-sdk/e2b/sandbox/process.py
@@ -1,429 +1,429 @@
-from __future__ import annotations
-
-import logging
-import re
-import inspect
-import threading
-import time
-from concurrent.futures import Future
-from typing import (
- Any,
- Callable,
- ClassVar,
- Dict,
- List,
- Optional,
- Union,
-)
-from pydantic import BaseModel
-
-from e2b.constants import TIMEOUT
-from e2b.sandbox.env_vars import EnvVars
-from e2b.sandbox.exception import (
- MultipleExceptions,
- ProcessException,
- RpcException,
- CurrentWorkingDirectoryDoesntExistException,
- TimeoutException,
-)
-from e2b.sandbox.out import OutStderrResponse, OutStdoutResponse
-from e2b.sandbox.sandbox_connection import SandboxConnection, SubscriptionArgs
-from e2b.utils.id import create_id
-
-logger = logging.getLogger(__name__)
-
-
-class ProcessMessage(BaseModel):
- """
- A message from a process.
- """
-
- line: str
- error: bool = False
- timestamp: int
- """
- Unix epoch in nanoseconds
- """
-
- def __str__(self):
- return self.line
-
-
-class ProcessOutput(BaseModel):
- """
- Output from a process.
- """
-
- delimiter: ClassVar[str] = "\n"
- messages: List[ProcessMessage] = []
-
- error: bool = False
- exit_code: Optional[int] = None
-
- @property
- def stdout(self) -> str:
- """
- The stdout from the process.
- """
- return self.delimiter.join(out.line for out in self.messages if not out.error)
-
- @property
- def stderr(self) -> str:
- """
- The stderr from the process.
- """
- return self.delimiter.join(out.line for out in self.messages if out.error)
-
- def _insert_by_timestamp(self, message: ProcessMessage):
- """Insert an out based on its timestamp using insertion sort."""
- i = len(self.messages) - 1
- while i >= 0 and self.messages[i].timestamp > message.timestamp:
- i -= 1
- self.messages.insert(i + 1, message)
-
- def _add_stdout(self, message: ProcessMessage):
- self._insert_by_timestamp(message)
-
- def _add_stderr(self, message: ProcessMessage):
- self.error = True
- self._insert_by_timestamp(message)
-
-
-class Process:
- """
- A process running in the sandbox.
- """
-
- def __init__(
- self,
- process_id: str,
- sandbox: SandboxConnection,
- trigger_exit: Callable[[], Any],
- finished: Future[ProcessOutput],
- output: ProcessOutput,
- ):
- self._process_id = process_id
- self._sandbox = sandbox
- self._trigger_exit = trigger_exit
- self._finished = finished
- self._output = output
-
- @property
- def exit_code(self) -> Optional[int]:
- """
- The exit code of the last process started by this manager.
- """
- if not self.finished:
- raise ProcessException("Process has not finished yet")
- return self.output.exit_code
-
- @property
- def output(self) -> ProcessOutput:
- """
- The output from the process.
- """
- return self._output
-
- @property
- def stdout(self) -> str:
- """
- The stdout from the process.
- """
- return self._output.stdout
-
- @property
- def stderr(self) -> str:
- """
- The stderr from the process.
- """
- return self._output.stderr
-
- @property
- def error(self) -> bool:
- """
- True if the process has written to stderr.
- """
- return self._output.error
-
- @property
- def output_messages(self) -> List[ProcessMessage]:
- """
- The output messages from the process.
- """
- return self._output.messages
-
- @property
- def finished(self):
- """
- A future that is resolved when the process exits.
- """
- return self._finished
-
- @property
- def process_id(self) -> str:
- """
- The process id used to identify the process in the sandbox.
- This is not the system process id of the process running in the sandbox.
- """
- return self._process_id
-
- def wait(self, timeout: Optional[float] = None) -> ProcessOutput:
- """
- Wait for the process to exit.
-
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out. If set to None, the method will continue to wait until it completes, regardless of time
- """
- start_time = time.time()
- while timeout is None or time.time() - start_time < timeout:
- if self._finished.done():
- return self._finished.result()
- time.sleep(0.1)
- if not self._sandbox.is_open:
- break
-
- raise TimeoutException(f"Process did not finish within {timeout} seconds")
-
- def send_stdin(self, data: str, timeout: Optional[float] = TIMEOUT) -> None:
- """
- Send data to the process stdin.
-
- :param data: Data to send
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
- """
- try:
- self._sandbox._call(
- ProcessManager._service_name,
- "stdin",
- [self.process_id, data],
- timeout=timeout,
- )
- except RpcException as e:
- raise ProcessException(e.message) from e
-
- def kill(self, timeout: Optional[float] = TIMEOUT) -> None:
- """
- Kill the process.
-
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
- """
- try:
- self._sandbox._call(
- ProcessManager._service_name, "kill", [self.process_id], timeout=timeout
- )
- except RpcException as e:
- raise ProcessException(e.message) from e
- self._trigger_exit()
-
-
-class ProcessManager:
- """
- Manager for starting and interacting with processes in the sandbox.
- """
-
- _service_name = "process"
-
- def __init__(
- self,
- sandbox: SandboxConnection,
- on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
- on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
- on_exit: Optional[Union[Callable[[int], Any], Callable[[], Any]]] = None,
- ):
- self._sandbox = sandbox
- self._process_cleanup: List[Callable[[], Any]] = []
- self._on_stdout = on_stdout
- self._on_stderr = on_stderr
- self._on_exit = on_exit
-
- def start(
- self,
- cmd: str,
- on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
- on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
- on_exit: Optional[Union[Callable[[int], Any], Callable[[], Any]]] = None,
- env_vars: Optional[EnvVars] = None,
- cwd: str = "",
- rootdir: str = "", # DEPRECATED
- process_id: Optional[str] = None,
- timeout: Optional[float] = TIMEOUT,
- ) -> Process:
- logger.info(f"Starting process: {cmd}")
- env_vars = env_vars or {}
- env_vars = {**self._sandbox.env_vars, **env_vars}
-
- on_stdout = on_stdout or self._on_stdout
- on_stderr = on_stderr or self._on_stderr
- on_exit = on_exit or self._on_exit
-
- future_exit = Future()
- process_id = process_id or create_id(12)
-
- unsub_all: Optional[Callable] = None
-
- output = ProcessOutput()
-
- def handle_exit(exit_code: int):
- output.exit_code = exit_code
- logger.info(f"Process {process_id} exited with exit code {exit_code}")
- if not future_exit.done():
- future_exit.set_result(True)
-
- def handle_stdout(data: Dict[Any, Any]):
- out = OutStdoutResponse(**data)
-
- message = ProcessMessage(
- line=out.line,
- timestamp=out.timestamp,
- error=False,
- )
-
- output._add_stdout(message)
- if on_stdout:
- try:
- on_stdout(message)
- except TypeError as error:
- logger.exception(f"Error in on_stdout callback: {error}")
-
- def handle_stderr(data: Dict[Any, Any]):
- out = OutStderrResponse(**data)
-
- message = ProcessMessage(
- line=out.line,
- timestamp=out.timestamp,
- error=True,
- )
-
- output._add_stderr(message)
- if on_stderr:
- try:
- on_stderr(message)
- except TypeError as error:
- logger.exception(f"Error in on_stdout callback: {error}")
-
- try:
- subscription_args = [
- SubscriptionArgs(
- service=self._service_name,
- handler=handle_exit,
- method="onExit",
- params=[process_id],
- ),
- SubscriptionArgs(
- service=self._service_name,
- handler=handle_stdout,
- method="onStdout",
- params=[process_id],
- ),
- SubscriptionArgs(
- service=self._service_name,
- handler=handle_stderr,
- method="onStderr",
- params=[process_id],
- ),
- ]
- unsub_all = self._sandbox._handle_subscriptions(*subscription_args)
-
- except (RpcException, MultipleExceptions) as e:
- future_exit.cancel()
-
- if isinstance(e, RpcException):
- raise ProcessException(e.message) from e
- elif isinstance(e, MultipleExceptions):
- raise ProcessException(
- "Failed to subscribe to RPC services necessary for starting process"
- ) from e
-
- future_exit_handler_finish: Future[ProcessOutput] = Future()
-
- def exit_handler():
- future_exit.result()
- logger.info(f"Handling process exit (id: {process_id})")
- if unsub_all:
- unsub_all()
- if on_exit:
- sig = inspect.signature(on_exit)
- params = sig.parameters.values()
- try:
- if len(params) == 0:
- on_exit()
- else:
- on_exit(output.exit_code or 0)
- except TypeError as error:
- logger.exception(f"Error in on_exit callback: {error}")
- future_exit_handler_finish.set_result(output)
-
- threading.Thread(
- name="e2b-process-exit-handler", daemon=True, target=exit_handler
- ).start()
-
- def trigger_exit():
- logger.info(f"Exiting the process (id: {process_id})")
- if not future_exit.done():
- future_exit.set_result(None)
-
- future_exit_handler_finish.result()
- logger.debug(f"Exited the process (id: {process_id})")
-
- try:
- if not cwd and rootdir:
- cwd = rootdir
- logger.warning("The rootdir parameter is deprecated, use cwd instead.")
-
- if not cwd and self._sandbox.cwd:
- cwd = self._sandbox.cwd
-
- self._sandbox._call(
- self._service_name,
- "start",
- [
- process_id,
- cmd,
- env_vars,
- cwd,
- ],
- timeout=timeout,
- )
- logger.info(f"Started process (id: {process_id})")
- return Process(
- output=output,
- sandbox=self._sandbox,
- process_id=process_id,
- trigger_exit=trigger_exit,
- finished=future_exit_handler_finish,
- )
- except RpcException as e:
- trigger_exit()
- if re.match(
- r"error starting process '\w+': fork/exec /bin/bash: no such file or directory",
- e.message,
- ):
- raise CurrentWorkingDirectoryDoesntExistException(
- "Failed to start the process. You are trying set `cwd` to a directory that does not exist."
- ) from e
- raise ProcessException(e.message) from e
- except TimeoutError as e:
- logger.error(f"Timeout error during starting the process: {cmd}")
- trigger_exit()
- raise e
-
- def start_and_wait(
- self,
- cmd: str,
- on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
- on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
- on_exit: Optional[Callable[[int], Any]] = None,
- env_vars: Optional[EnvVars] = None,
- cwd: str = "",
- process_id: Optional[str] = None,
- timeout: Optional[float] = TIMEOUT,
- ) -> ProcessOutput:
- return self.start(
- cmd,
- on_stdout=on_stdout,
- on_stderr=on_stderr,
- on_exit=on_exit,
- env_vars=env_vars,
- cwd=cwd,
- process_id=process_id,
- timeout=timeout,
- ).wait()
+# from __future__ import annotations
+
+# import logging
+# import re
+# import inspect
+# import threading
+# import time
+# from concurrent.futures import Future
+# from typing import (
+# Any,
+# Callable,
+# ClassVar,
+# Dict,
+# List,
+# Optional,
+# Union,
+# )
+# from pydantic import BaseModel
+
+# from e2b.constants import TIMEOUT
+# from e2b.sandbox.env_vars import EnvVars
+# from e2b.exceptions import (
+# MultipleExceptions,
+# ProcessException,
+# RpcException,
+# CurrentWorkingDirectoryDoesntExistException,
+# TimeoutException,
+# )
+# from e2b.sandbox.out import OutStderrResponse, OutStdoutResponse
+# from e2b.sandbox.sandbox_connection import SandboxConnection, SubscriptionArgs
+# from e2b.utils.id import create_id
+
+# logger = logging.getLogger(__name__)
+
+
+# class ProcessMessage(BaseModel):
+# """
+# A message from a process.
+# """
+
+# line: str
+# error: bool = False
+# timestamp: int
+# """
+# Unix epoch in nanoseconds
+# """
+
+# def __str__(self):
+# return self.line
+
+
+# class ProcessOutput(BaseModel):
+# """
+# Output from a process.
+# """
+
+# delimiter: ClassVar[str] = "\n"
+# messages: List[ProcessMessage] = []
+
+# error: bool = False
+# exit_code: Optional[int] = None
+
+# @property
+# def stdout(self) -> str:
+# """
+# The stdout from the process.
+# """
+# return self.delimiter.join(out.line for out in self.messages if not out.error)
+
+# @property
+# def stderr(self) -> str:
+# """
+# The stderr from the process.
+# """
+# return self.delimiter.join(out.line for out in self.messages if out.error)
+
+# def _insert_by_timestamp(self, message: ProcessMessage):
+# """Insert an out based on its timestamp using insertion sort."""
+# i = len(self.messages) - 1
+# while i >= 0 and self.messages[i].timestamp > message.timestamp:
+# i -= 1
+# self.messages.insert(i + 1, message)
+
+# def _add_stdout(self, message: ProcessMessage):
+# self._insert_by_timestamp(message)
+
+# def _add_stderr(self, message: ProcessMessage):
+# self.error = True
+# self._insert_by_timestamp(message)
+
+
+# class Process:
+# """
+# A process running in the sandbox.
+# """
+
+# def __init__(
+# self,
+# process_id: str,
+# sandbox: SandboxConnection,
+# trigger_exit: Callable[[], Any],
+# finished: Future[ProcessOutput],
+# output: ProcessOutput,
+# ):
+# self._process_id = process_id
+# self._sandbox = sandbox
+# self._trigger_exit = trigger_exit
+# self._finished = finished
+# self._output = output
+
+# @property
+# def exit_code(self) -> Optional[int]:
+# """
+# The exit code of the last process started by this manager.
+# """
+# if not self.finished:
+# raise ProcessException("Process has not finished yet")
+# return self.output.exit_code
+
+# @property
+# def output(self) -> ProcessOutput:
+# """
+# The output from the process.
+# """
+# return self._output
+
+# @property
+# def stdout(self) -> str:
+# """
+# The stdout from the process.
+# """
+# return self._output.stdout
+
+# @property
+# def stderr(self) -> str:
+# """
+# The stderr from the process.
+# """
+# return self._output.stderr
+
+# @property
+# def error(self) -> bool:
+# """
+# True if the process has written to stderr.
+# """
+# return self._output.error
+
+# @property
+# def output_messages(self) -> List[ProcessMessage]:
+# """
+# The output messages from the process.
+# """
+# return self._output.messages
+
+# @property
+# def finished(self):
+# """
+# A future that is resolved when the process exits.
+# """
+# return self._finished
+
+# @property
+# def process_id(self) -> str:
+# """
+# The process id used to identify the process in the sandbox.
+# This is not the system process id of the process running in the sandbox.
+# """
+# return self._process_id
+
+# def wait(self, timeout: Optional[float] = None) -> ProcessOutput:
+# """
+# Wait for the process to exit.
+
+# :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out. If set to None, the method will continue to wait until it completes, regardless of time
+# """
+# start_time = time.time()
+# while timeout is None or time.time() - start_time < timeout:
+# if self._finished.done():
+# return self._finished.result()
+# time.sleep(0.1)
+# if not self._sandbox.is_open:
+# break
+
+# raise TimeoutException(f"Process did not finish within {timeout} seconds")
+
+# def send_stdin(self, data: str, timeout: Optional[float] = TIMEOUT) -> None:
+# """
+# Send data to the process stdin.
+
+# :param data: Data to send
+# :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+# """
+# try:
+# self._sandbox._call(
+# ProcessManager._service_name,
+# "stdin",
+# [self.process_id, data],
+# timeout=timeout,
+# )
+# except RpcException as e:
+# raise ProcessException(e.message) from e
+
+# def kill(self, timeout: Optional[float] = TIMEOUT) -> None:
+# """
+# Kill the process.
+
+# :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+# """
+# try:
+# self._sandbox._call(
+# ProcessManager._service_name, "kill", [self.process_id], timeout=timeout
+# )
+# except RpcException as e:
+# raise ProcessException(e.message) from e
+# self._trigger_exit()
+
+
+# class ProcessManager:
+# """
+# Manager for starting and interacting with processes in the sandbox.
+# """
+
+# _service_name = "process"
+
+# def __init__(
+# self,
+# sandbox: SandboxConnection,
+# on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
+# on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
+# on_exit: Optional[Union[Callable[[int], Any], Callable[[], Any]]] = None,
+# ):
+# self._sandbox = sandbox
+# self._process_cleanup: List[Callable[[], Any]] = []
+# self._on_stdout = on_stdout
+# self._on_stderr = on_stderr
+# self._on_exit = on_exit
+
+# def start(
+# self,
+# cmd: str,
+# on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
+# on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
+# on_exit: Optional[Union[Callable[[int], Any], Callable[[], Any]]] = None,
+# env_vars: Optional[EnvVars] = None,
+# cwd: str = "",
+# rootdir: str = "", # DEPRECATED
+# process_id: Optional[str] = None,
+# timeout: Optional[float] = TIMEOUT,
+# ) -> Process:
+# logger.info(f"Starting process: {cmd}")
+# env_vars = env_vars or {}
+# env_vars = {**self._sandbox.env_vars, **env_vars}
+
+# on_stdout = on_stdout or self._on_stdout
+# on_stderr = on_stderr or self._on_stderr
+# on_exit = on_exit or self._on_exit
+
+# future_exit = Future()
+# process_id = process_id or create_id(12)
+
+# unsub_all: Optional[Callable] = None
+
+# output = ProcessOutput()
+
+# def handle_exit(exit_code: int):
+# output.exit_code = exit_code
+# logger.info(f"Process {process_id} exited with exit code {exit_code}")
+# if not future_exit.done():
+# future_exit.set_result(True)
+
+# def handle_stdout(data: Dict[Any, Any]):
+# out = OutStdoutResponse(**data)
+
+# message = ProcessMessage(
+# line=out.line,
+# timestamp=out.timestamp,
+# error=False,
+# )
+
+# output._add_stdout(message)
+# if on_stdout:
+# try:
+# on_stdout(message)
+# except TypeError as error:
+# logger.exception(f"Error in on_stdout callback: {error}")
+
+# def handle_stderr(data: Dict[Any, Any]):
+# out = OutStderrResponse(**data)
+
+# message = ProcessMessage(
+# line=out.line,
+# timestamp=out.timestamp,
+# error=True,
+# )
+
+# output._add_stderr(message)
+# if on_stderr:
+# try:
+# on_stderr(message)
+# except TypeError as error:
+# logger.exception(f"Error in on_stdout callback: {error}")
+
+# try:
+# subscription_args = [
+# SubscriptionArgs(
+# service=self._service_name,
+# handler=handle_exit,
+# method="onExit",
+# params=[process_id],
+# ),
+# SubscriptionArgs(
+# service=self._service_name,
+# handler=handle_stdout,
+# method="onStdout",
+# params=[process_id],
+# ),
+# SubscriptionArgs(
+# service=self._service_name,
+# handler=handle_stderr,
+# method="onStderr",
+# params=[process_id],
+# ),
+# ]
+# unsub_all = self._sandbox._handle_subscriptions(*subscription_args)
+
+# except (RpcException, MultipleExceptions) as e:
+# future_exit.cancel()
+
+# if isinstance(e, RpcException):
+# raise ProcessException(e.message) from e
+# elif isinstance(e, MultipleExceptions):
+# raise ProcessException(
+# "Failed to subscribe to RPC services necessary for starting process"
+# ) from e
+
+# future_exit_handler_finish: Future[ProcessOutput] = Future()
+
+# def exit_handler():
+# future_exit.result()
+# logger.info(f"Handling process exit (id: {process_id})")
+# if unsub_all:
+# unsub_all()
+# if on_exit:
+# sig = inspect.signature(on_exit)
+# params = sig.parameters.values()
+# try:
+# if len(params) == 0:
+# on_exit()
+# else:
+# on_exit(output.exit_code or 0)
+# except TypeError as error:
+# logger.exception(f"Error in on_exit callback: {error}")
+# future_exit_handler_finish.set_result(output)
+
+# threading.Thread(
+# name="e2b-process-exit-handler", daemon=True, target=exit_handler
+# ).start()
+
+# def trigger_exit():
+# logger.info(f"Exiting the process (id: {process_id})")
+# if not future_exit.done():
+# future_exit.set_result(None)
+
+# future_exit_handler_finish.result()
+# logger.debug(f"Exited the process (id: {process_id})")
+
+# try:
+# if not cwd and rootdir:
+# cwd = rootdir
+# logger.warning("The rootdir parameter is deprecated, use cwd instead.")
+
+# if not cwd and self._sandbox.cwd:
+# cwd = self._sandbox.cwd
+
+# self._sandbox._call(
+# self._service_name,
+# "start",
+# [
+# process_id,
+# cmd,
+# env_vars,
+# cwd,
+# ],
+# timeout=timeout,
+# )
+# logger.info(f"Started process (id: {process_id})")
+# return Process(
+# output=output,
+# sandbox=self._sandbox,
+# process_id=process_id,
+# trigger_exit=trigger_exit,
+# finished=future_exit_handler_finish,
+# )
+# except RpcException as e:
+# trigger_exit()
+# if re.match(
+# r"error starting process '\w+': fork/exec /bin/bash: no such file or directory",
+# e.message,
+# ):
+# raise CurrentWorkingDirectoryDoesntExistException(
+# "Failed to start the process. You are trying set `cwd` to a directory that does not exist."
+# ) from e
+# raise ProcessException(e.message) from e
+# except TimeoutError as e:
+# logger.error(f"Timeout error during starting the process: {cmd}")
+# trigger_exit()
+# raise e
+
+# def start_and_wait(
+# self,
+# cmd: str,
+# on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
+# on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
+# on_exit: Optional[Callable[[int], Any]] = None,
+# env_vars: Optional[EnvVars] = None,
+# cwd: str = "",
+# process_id: Optional[str] = None,
+# timeout: Optional[float] = TIMEOUT,
+# ) -> ProcessOutput:
+# return self.start(
+# cmd,
+# on_stdout=on_stdout,
+# on_stderr=on_stderr,
+# on_exit=on_exit,
+# env_vars=env_vars,
+# cwd=cwd,
+# process_id=process_id,
+# timeout=timeout,
+# ).wait()
diff --git a/packages/python-sdk/e2b/sandbox/rpc/__init__.py b/packages/python-sdk/e2b/sandbox/rpc/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/packages/python-sdk/e2b/sandbox/rpc/filesystem.py b/packages/python-sdk/e2b/sandbox/rpc/filesystem.py
new file mode 100644
index 000000000..a81f6f5bf
--- /dev/null
+++ b/packages/python-sdk/e2b/sandbox/rpc/filesystem.py
@@ -0,0 +1,8 @@
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class Filesystem:
+ def __init__(self) -> None:
+ pass
diff --git a/packages/python-sdk/e2b/sandbox/rpc/main.py b/packages/python-sdk/e2b/sandbox/rpc/main.py
new file mode 100644
index 000000000..7b28a3b53
--- /dev/null
+++ b/packages/python-sdk/e2b/sandbox/rpc/main.py
@@ -0,0 +1,9 @@
+from e2b.sandbox.rpc.filesystem import Filesystem
+from e2b.sandbox.rpc.process import Process
+
+
+class SandboxRpc:
+ def __init__(self, url: str):
+
+ self.filesystem = Filesystem()
+ self.process = Process()
diff --git a/packages/python-sdk/e2b/sandbox/rpc/process.py b/packages/python-sdk/e2b/sandbox/rpc/process.py
new file mode 100644
index 000000000..84971fd79
--- /dev/null
+++ b/packages/python-sdk/e2b/sandbox/rpc/process.py
@@ -0,0 +1,8 @@
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class Process:
+ def __init__(self) -> None:
+ pass
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.py
new file mode 100644
index 000000000..0609ab492
--- /dev/null
+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py
@@ -0,0 +1,104 @@
+import logging
+
+from typing import Optional, Dict, List
+from pydantic import BaseModel
+from datetime import datetime
+
+from e2b.api import E2BApiClient, models, client
+from e2b.connection_config import ConnectionConfig
+
+logger = logging.getLogger(__name__)
+
+
+class RunningSandbox(BaseModel):
+ sandbox_id: str
+ template_id: str
+ name: Optional[str]
+ metadata: Optional[Dict[str, str]]
+ started_at: datetime
+
+
+# TODO: Add requestTimeout
+
+
+class SandboxApi:
+ @staticmethod
+ def list(
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ ) -> List[RunningSandbox]:
+ config = ConnectionConfig(api_key=api_key, domain=domain, debug=debug)
+
+ with E2BApiClient(config) as api_client:
+ return [
+ RunningSandbox(
+ sandbox_id=SandboxApi._get_sandbox_id(
+ sandbox.sandbox_id,
+ sandbox.client_id,
+ ),
+ template_id=sandbox.template_id,
+ name=sandbox.alias,
+ metadata=sandbox.metadata,
+ started_at=sandbox.started_at,
+ )
+ for sandbox in client.SandboxesApi(api_client).sandboxes_get()
+ ]
+
+ @staticmethod
+ def kill(
+ sandbox_id: str,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ ) -> None:
+ config = ConnectionConfig(api_key=api_key, domain=domain, debug=debug)
+
+ # TODO: Ensure the short id/long id works with kill
+
+ with E2BApiClient(config) as api_client:
+ client.SandboxesApi(api_client).sandboxes_sandbox_id_delete(
+ sandbox_id,
+ )
+
+ @staticmethod
+ def set_timeout(
+ sandbox_id: str,
+ timeout: int,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ ) -> None:
+ config = ConnectionConfig(api_key=api_key, domain=domain, debug=debug)
+
+ with E2BApiClient(config) as api_client:
+ client.SandboxesApi(api_client).sandboxes_sandbox_id_timeout_post(
+ sandbox_id,
+ models.SandboxesSandboxIDTimeoutPostRequest(timeout=timeout),
+ )
+
+ @staticmethod
+ def _create_sandbox(
+ template: str,
+ metadata: Optional[Dict[str, str]] = None,
+ timeout: Optional[int] = None,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ ) -> str:
+ config = ConnectionConfig(api_key=api_key, domain=domain, debug=debug)
+
+ with E2BApiClient(config) as api_client:
+ res = client.SandboxesApi(api_client).sandboxes_post(
+ models.NewSandbox(
+ templateID=template,
+ metadata=metadata,
+ timeout=timeout,
+ ),
+ )
+
+ return SandboxApi._get_sandbox_id(res.sandbox_id, res.client_id)
+
+ @staticmethod
+ def _get_sandbox_id(sandbox_id: str, client_id: str) -> str:
+ return f"{sandbox_id}-{client_id}"
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_connection.py b/packages/python-sdk/e2b/sandbox/sandbox_connection.py
deleted file mode 100644
index 5cd8a560b..000000000
--- a/packages/python-sdk/e2b/sandbox/sandbox_connection.py
+++ /dev/null
@@ -1,511 +0,0 @@
-import concurrent
-import logging
-import threading
-import traceback
-import warnings
-
-from concurrent.futures import ThreadPoolExecutor, CancelledError
-from time import sleep
-from typing import Any, Callable, List, Literal, Optional, Union, Dict
-from datetime import datetime
-from e2b.grpc.main import call_grpc
-from pydantic import BaseModel
-from urllib3.exceptions import ReadTimeoutError, MaxRetryError, ConnectTimeoutError
-
-from e2b.api import E2BApiClient, exceptions, models, client
-from e2b.constants import (
- DOMAIN,
- SANDBOX_REFRESH_PERIOD,
- TIMEOUT,
- ENVD_PORT,
- WS_ROUTE,
- SECURE,
-)
-from e2b.sandbox.env_vars import EnvVars
-from e2b.sandbox.exception import (
- MultipleExceptions,
- SandboxException,
- TimeoutException,
- SandboxNotOpenException,
-)
-from e2b.sandbox.sandbox_rpc import Notification, SandboxRpc
-from e2b.utils.api_key import get_api_key
-from e2b.utils.future import DeferredFuture
-from e2b.utils.str import camel_case_to_snake_case
-
-logger = logging.getLogger(__name__)
-
-
-class Subscription(BaseModel):
- service: str
- id: str
- handler: Callable[[Any], None]
-
-
-class SubscriptionArgs(BaseModel):
- service: str
- handler: Callable[[Any], None]
- method: str
- params: List[Any] = []
-
-
-class RunningSandbox(BaseModel):
- sandbox_id: str
- template_id: str
- alias: Optional[str]
- metadata: Optional[Dict[str, str]]
- cpu_count: int
- memory_mb: int
- started_at: datetime
-
-
-class SandboxConnection:
- _refresh_retries = 4
- _on_close_child: Optional[Callable[[], Any]] = None
-
- @property
- def id(self) -> str:
- """
- The sandbox ID.
-
- You can use this ID to reconnect to the sandbox later.
- """
- if not self._sandbox:
- raise SandboxException("Sandbox is not running.")
- return f"{self._sandbox.sandbox_id}-{self._sandbox.client_id}"
-
- @property
- def finished(self):
- """
- A future that is resolved when the sandbox exits.
- """
- return self._finished
-
- @property
- def is_open(self) -> bool:
- """
- Whether the sandbox is open.
- """
- return self._is_open
-
- def __init__(
- self,
- template: str,
- api_key: Optional[str] = None,
- cwd: Optional[str] = None,
- env_vars: Optional[EnvVars] = None,
- metadata: Optional[Dict[str, str]] = None,
- timeout: Optional[float] = TIMEOUT,
- domain: Optional[str] = None,
- _sandbox: Optional[models.Sandbox] = None,
- _debug_hostname: Optional[str] = None,
- _debug_port: Optional[int] = None,
- _debug_dev_env: Optional[Literal["remote", "local"]] = None,
- ):
- api_key = get_api_key(api_key)
-
- self.cwd = cwd
- """
- Default working directory used in the sandbox.
-
- You can change the working directory by setting the `cwd` property.
- """
- self.env_vars = env_vars or {}
- """
- Default environment variables used in the sandbox.
-
- You can change the environment variables by setting the `env_vars` property.
- """
- self._template = template
- self._api_key = api_key
- self._debug_hostname = _debug_hostname
- self._debug_port = _debug_port
- self._debug_dev_env = _debug_dev_env
- self._sandbox = _sandbox
- self.domain = domain or DOMAIN
-
- self._api_client = E2BApiClient(api_key=self._api_key, domain=self.domain)
- self._is_open = False
- self._process_cleanup: List[Callable[[], Any]] = []
- self._subscribers = {}
- self._rpc: Optional[SandboxRpc] = None
- self._finished = DeferredFuture(self._process_cleanup)
-
- logger.info(f"Sandbox for template {self._template} initialized")
-
- self._open(metadata=metadata, timeout=timeout)
-
- @classmethod
- def create(cls, *args, **kwargs):
- warnings.warn("Sandbox.create() is deprecated, use Sandbox() instead")
- return cls(*args, **kwargs)
-
- def get_hostname(self, port: Optional[int] = None) -> str:
- """
- Get the hostname for the sandbox or for the specified sandbox's port.
-
- :param port: Specify if you want to connect to a specific port of the sandbox
-
- :return: Hostname of the sandbox or sandbox's port
- """
-
- if self._debug_hostname:
- if port and self._debug_dev_env == "remote":
- return f"{port}-{self._debug_hostname}"
- elif port:
- return f"{self._debug_hostname}:{port}"
- else:
- return self._debug_hostname
- else:
- if not self._sandbox:
- raise SandboxException("Sandbox is not running.")
-
- hostname = f"{self.id}.{self.domain}"
-
- if port:
- return f"{port}-{hostname}"
-
- return hostname
-
- @staticmethod
- def get_protocol(base_protocol: str = "http", secure: bool = SECURE) -> str:
- """
- The function decides whether to use the secure or insecure protocol.
-
- :param base_protocol: Specify the specific protocol you want to use. Do not include the `s` in `https` or `wss`.
- :param secure: Specify whether you want to use the secure protocol or not.
-
- :return: Protocol for the connection to the sandbox
- """
- return f"{base_protocol}s" if secure else base_protocol
-
- def keep_alive(self, duration: int) -> None:
- """
- Keep the sandbox alive for the specified duration.
-
- :param duration: Duration in seconds. Must be between 0 and 3600 seconds.
- """
- if not 0 <= duration <= 3600:
- raise ValueError("Duration must be between 0 and 3600 seconds")
-
- api = client.SandboxesApi(self._api_client)
- try:
- api.sandboxes_sandbox_id_refreshes_post(
- self._sandbox.sandbox_id,
- client.SandboxesSandboxIDRefreshesPostRequest(duration=duration),
- )
- logger.debug(
- f"Sandbox will be kept alive without connection for next {duration} seconds."
- )
- except exceptions.ApiException as e:
- if e.status == 404:
- raise SandboxException(
- f"Sandbox {self.id} failed because it cannot be found"
- ) from e
- else:
- raise e
-
- def close(self) -> None:
- """
- Close the sandbox and unsubscribe from all the subscriptions.
- """
- self._close()
- logger.info(f"Sandbox closed")
-
- def _close(self):
- if self._is_open and self._sandbox:
- logger.info(f"Closing sandbox {self._sandbox.template_id} (id: {self.id})")
- self._is_open = False
- if self._rpc:
- self._rpc.close()
-
- if self._on_close_child:
- self._on_close_child()
-
- for cleanup in self._process_cleanup:
- cleanup()
- self._process_cleanup.clear()
-
- def _open(
- self,
- metadata: Optional[Dict[str, str]] = None,
- timeout: Optional[float] = TIMEOUT,
- ) -> None:
- """
- Open a connection to a new sandbox.
-
- You must call this method before using the sandbox.
- """
- if self._is_open:
- raise SandboxException("Sandbox connect was already called")
- else:
- self._is_open = True
-
- if not self._sandbox and not self._debug_hostname:
- try:
- api = client.SandboxesApi(self._api_client)
-
- self._sandbox = api.sandboxes_post(
- models.NewSandbox(templateID=self._template, metadata=metadata),
- _request_timeout=timeout,
- )
- logger.info(
- f"Sandbox {self._sandbox.template_id} created (id:{self.id})"
- )
- except ReadTimeoutError as e:
- logger.error(f"Failed to acquire sandbox")
- self._close()
- raise TimeoutException(
- f"Failed to acquire sandbox: {e}",
- ) from e
- except MaxRetryError as e:
- if isinstance(e.reason, ConnectTimeoutError):
- raise TimeoutException(
- f"Failed to acquire sandbox: {e}",
- ) from e
- raise e
- except Exception as e:
- logger.error(f"Failed to acquire sandbox")
- self._close()
- raise e
-
- if not self._debug_hostname:
- self._start_refreshing()
-
- try:
- url = self.get_hostname(self._debug_port or ENVD_PORT)
- print(f"url: {url}")
-
- a = call_grpc(f"http://{url}")
- b = call_grpc(f"http://{url}")
-
- for i, j in zip(a, b):
- print(i, j)
-
- # print([e for e in r.entries])
-
- # self._connect_rpc(timeout)
- except Exception as e:
- logger.error(e)
- self._close()
- raise e
-
- def _connect_rpc(self, timeout: Optional[float] = TIMEOUT):
- hostname = self.get_hostname(self._debug_port or ENVD_PORT)
- protocol = self.get_protocol("ws", self._debug_dev_env != "local")
- sandbox_url = f"{protocol}://{hostname}{WS_ROUTE}"
-
- self._rpc = SandboxRpc(
- url=sandbox_url,
- on_message=self._handle_notification,
- )
- self._rpc.connect(timeout=timeout)
-
- def _start_refreshing(self):
- threading.Thread(
- target=self._refresh,
- daemon=True,
- name="e2b-sandbox-refresh",
- ).start()
-
- def _call(
- self,
- service: str,
- method: str,
- params: Optional[List[Any]] = None,
- timeout: Optional[float] = TIMEOUT,
- ) -> Any:
- if not params:
- params = []
-
- if not self.is_open:
- raise SandboxNotOpenException("Sandbox is not open")
-
- if not self._rpc:
- raise SandboxException("Sandbox is not connected")
-
- return self._rpc.send_message(f"{service}_{method}", params, timeout)
-
- def _handle_subscriptions(
- self,
- *subscription_args: SubscriptionArgs,
- ):
- results: List[Union[Callable, None, Exception]] = []
- with ThreadPoolExecutor(thread_name_prefix="process-subscribe") as executor:
- futures = []
- for args in subscription_args:
- future = executor.submit(
- self._subscribe,
- args.service,
- args.handler,
- args.method,
- *args.params,
- )
- futures.append(future)
-
- for future in concurrent.futures.as_completed(futures):
- results.append(future.result())
-
- results = [sub for sub in results if sub]
- process_exceptions = [e for e in results if isinstance(e, Exception)]
-
- def unsub_all():
- def unsub_func():
- for unsub in results:
- if not isinstance(unsub, Exception):
- try:
- unsub()
- except (CancelledError, SandboxNotOpenException, KeyError):
- pass
-
- threading.Thread(
- name="process-unsubscribe",
- daemon=True,
- target=unsub_func,
- ).start()
-
- if len(process_exceptions) > 0:
- unsub_all()
-
- if len(process_exceptions) == 1:
- raise process_exceptions[0]
-
- error_message = "\n"
-
- for i, s in enumerate(process_exceptions):
- tb = s.__traceback__ # Get the traceback object
- stack_trace = "\n".join(traceback.extract_tb(tb).format())
- error_message += f'\n[{i}]: {type(s).__name__}("{s}"):\n{stack_trace}\n'
-
- raise MultipleExceptions(
- message=error_message,
- exceptions=process_exceptions,
- )
-
- return unsub_all
-
- def _unsubscribe(self, sub_id: str, timeout: Optional[float] = TIMEOUT):
- sub = self._subscribers[sub_id]
- self._call(sub.service, "unsubscribe", [sub.id], timeout=timeout)
- del self._subscribers[sub_id]
- logger.debug(f"Unsubscribed (sub_id: {sub_id})")
-
- def _subscribe(
- self,
- service: str,
- handler: Callable[[Any], Any],
- method: str,
- *params,
- timeout: Optional[float] = TIMEOUT,
- ) -> Callable[[], None]:
- sub_id = self._call(service, "subscribe", [method, *params], timeout=timeout)
- if not isinstance(sub_id, str):
- raise Exception(f"Failed to subscribe: {camel_case_to_snake_case(method)}")
-
- self._subscribers[sub_id] = Subscription(
- service=service, id=sub_id, handler=handler
- )
- logger.debug(
- f"Subscribed to {service} {camel_case_to_snake_case(method)} (sub id: {sub_id})"
- )
-
- def unsub():
- self._unsubscribe(sub_id, timeout=timeout)
-
- return unsub
-
- def _handle_notification(self, data: Notification):
- logger.debug(f"Notification {data}")
-
- for id, sub in self._subscribers.items():
- if id == data.params["subscription"]:
- sub.handler(data.params["result"])
-
- def _refresh(self):
- if not self._sandbox:
- logger.info("No sandbox to refresh. Sandbox was not created")
- return
-
- try:
- logger.info(
- f"Started refreshing sandbox {self._sandbox.template_id} (id: {self.id})"
- )
-
- current_retry = 0
- api = client.SandboxesApi(self._api_client)
- while True:
- if not self._is_open:
- logger.debug(f"Cannot refresh sandbox - it was closed. {self.id}")
- return
- sleep(SANDBOX_REFRESH_PERIOD)
- try:
- api.sandboxes_sandbox_id_refreshes_post(
- self._sandbox.sandbox_id,
- client.SandboxesSandboxIDRefreshesPostRequest(duration=0),
- )
- logger.debug(f"Refreshed sandbox {self.id}")
- except exceptions.ApiException as e:
- if e.status == 404:
- raise SandboxException(
- f"Sandbox {self.id} failed because it cannot be found"
- ) from e
- else:
- if current_retry < self._refresh_retries:
- logger.error(
- f"Refreshing sandbox {self.id} failed. Retrying..."
- )
- current_retry += 1
- else:
- logger.error(
- f"Refreshing sandbox {self.id} failed. Max retries exceeded"
- )
- raise e
- finally:
- if self._sandbox:
- logger.info(f"Stopped refreshing sandbox (id: {self.id})")
- else:
- logger.info("No sandbox to stop refreshing. Sandbox was not created")
-
- self._close()
-
- @staticmethod
- def list(
- api_key: Optional[str] = None, domain: str = DOMAIN
- ) -> List[RunningSandbox]:
- """
- List all running sandboxes.
-
- :param api_key: API key to use for authentication.
- :param domain: Domain to use for the API.
- If not provided, the `E2B_API_KEY` environment variable will be used.
- """
- api_key = get_api_key(api_key)
-
- with E2BApiClient(api_key=api_key, domain=domain) as api_client:
- return [
- RunningSandbox(
- sandbox_id=f"{sandbox.sandbox_id}-{sandbox.client_id}",
- **sandbox.dict(exclude={"sandbox_id", "client_id"}),
- )
- for sandbox in client.SandboxesApi(api_client).sandboxes_get()
- ]
-
- @staticmethod
- def kill(
- sandbox_id: str, api_key: Optional[str] = None, domain: str = DOMAIN
- ) -> None:
- """
- Kill the running sandbox specified by the sandbox ID.
-
- :param sandbox_id: ID of the sandbox to kill.
- :param api_key: API key to use for authentication.
- :param domain: Domain to use for the API.
- If not provided, the `E2B_API_KEY` environment variable will be used.
- """
- api_key = get_api_key(api_key)
-
- short_id = sandbox_id.split("-")[0]
- with E2BApiClient(api_key=api_key, domain=domain) as api_client:
- return client.SandboxesApi(api_client).sandboxes_sandbox_id_delete(
- sandbox_id=short_id
- )
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_files.py b/packages/python-sdk/e2b/sandbox/sandbox_files.py
new file mode 100644
index 000000000..eb66657a7
--- /dev/null
+++ b/packages/python-sdk/e2b/sandbox/sandbox_files.py
@@ -0,0 +1,58 @@
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class SandboxFiles:
+ def __init__(self, file_server_url: str) -> None:
+ pass
+
+ def file_url(self) -> str:
+ """
+ Return a URL that can be used to upload files to the sandbox via a multipart/form-data POST request.
+ This is useful if you're uploading files directly from the browser.
+ The file will be uploaded to the user's home directory with the same name.
+ If a file with the same name already exists, it will be overwritten.
+ """
+ hostname = self.get_hostname(self._debug_port or ENVD_PORT)
+ protocol = self.get_protocol(secure=self._debug_dev_env != "local")
+
+ file_url = f"{protocol}://{hostname}{FILE_ROUTE}"
+
+ return file_url
+
+ def upload_file(self, file: IO, timeout: Optional[float] = TIMEOUT) -> str:
+ """
+ Upload a file to the sandbox.
+ The file will be uploaded to the user's home (`/home/user`) directory with the same name.
+ If a file with the same name already exists, it will be overwritten.
+
+ :param file: The file to upload
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+ """
+ files = {"file": file}
+ r = requests.post(self.file_url(), files=files, timeout=timeout)
+ if r.status_code != 200:
+ raise Exception(f"Failed to upload file: {r.reason} {r.text}")
+
+ filename = path.basename(file.name)
+ return f"/home/user/{filename}"
+
+ def download_file(
+ self, remote_path: str, timeout: Optional[float] = TIMEOUT
+ ) -> bytes:
+ """
+ Download a file from the sandbox and returns it's content as bytes.
+
+ :param remote_path: The path of the file to download
+ :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
+ """
+ encoded_path = urllib.parse.quote(remote_path)
+ url = f"{self.file_url()}?path={encoded_path}"
+ r = requests.get(url, timeout=timeout)
+
+ if r.status_code != 200:
+ raise Exception(
+ f"Failed to download file '{remote_path}'. {r.reason} {r.text}"
+ )
+ return r.content
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_rpc.py b/packages/python-sdk/e2b/sandbox/sandbox_rpc.py
deleted file mode 100644
index b5c3abebb..000000000
--- a/packages/python-sdk/e2b/sandbox/sandbox_rpc.py
+++ /dev/null
@@ -1,195 +0,0 @@
-from __future__ import annotations
-
-import json
-import logging
-import threading
-import time
-
-from concurrent.futures import TimeoutError
-from queue import Queue
-from threading import Event
-from typing import Any, Callable, Dict, Iterator, List, Union, Optional
-from jsonrpcclient import Error, Ok, request_json
-from jsonrpcclient.id_generators import decimal as decimal_id_generator
-from jsonrpcclient.responses import Response
-from pydantic import BaseModel, PrivateAttr, ConfigDict
-from websockets.typing import Data
-
-from e2b.constants import TIMEOUT
-from e2b.sandbox.exception import RpcException, TimeoutException, SandboxException
-from e2b.sandbox.websocket_client import WebSocket
-from e2b.utils.future import DeferredFuture
-
-logger = logging.getLogger(__name__)
-
-
-class Notification(BaseModel):
- """Nofification."""
-
- method: str
- params: Dict
-
-
-Message = Union[Response, Notification]
-
-
-def to_response_or_notification(response: Dict[str, Any]) -> Message:
- """Create a Response namedtuple from a dict."""
- if "error" in response:
- return Error(
- response["error"]["code"],
- response["error"]["message"],
- response["error"].get("data"),
- response["id"],
- )
- elif "result" in response and "id" in response:
- return Ok(response["result"], response["id"])
-
- elif "params" in response:
- return Notification(method=response["method"], params=response["params"])
-
- raise ValueError("Invalid response", response)
-
-
-class SandboxRpc(BaseModel):
- model_config = ConfigDict(arbitrary_types_allowed=True)
-
- url: str
- on_message: Callable[[Notification], None]
-
- _id_generator: Iterator[int] = PrivateAttr(default_factory=decimal_id_generator)
- _waiting_for_replies: Dict[int, DeferredFuture] = PrivateAttr(default_factory=dict)
- _queue_in: Queue = PrivateAttr(default_factory=Queue)
- _queue_out: Queue = PrivateAttr(default_factory=Queue)
- _process_cleanup: List[Callable[[], Any]] = PrivateAttr(default_factory=list)
- _websocket_task: Optional[threading.Thread] = PrivateAttr(default=None)
- _closed: bool = PrivateAttr(default=False)
-
- def process_messages(self):
- while True:
- data = self._queue_out.get()
- logger.debug(f"WebSocket received message: {data}".strip())
- self._receive_message(data)
- self._queue_out.task_done()
-
- def connect(self, timeout: float = TIMEOUT):
- started = Event()
- stopped = Event()
- self._process_cleanup.append(stopped.set)
-
- threading.Thread(
- target=self.process_messages, daemon=True, name="e2b-process-messages"
- ).start()
-
- threading.Thread(
- target=WebSocket(
- url=self.url,
- queue_in=self._queue_in,
- queue_out=self._queue_out,
- started=started,
- stopped=stopped,
- ).run,
- daemon=True,
- name="e2b-websocket",
- ).start()
-
- logger.info("WebSocket waiting to start")
-
- try:
- start_time = time.time()
- while (
- not started.is_set()
- and time.time() - start_time < timeout
- and not self._closed
- ):
- time.sleep(0.1)
-
- if not started.is_set():
- logger.error("WebSocket failed to start")
- raise TimeoutException("WebSocket failed to start")
- except BaseException as e:
- self.close()
- raise SandboxException(f"WebSocket failed to start: {e}") from e
-
- logger.info("WebSocket started")
-
- def send_message(
- self,
- method: str,
- params: List[Any],
- timeout: Optional[float],
- ) -> Any:
- timeout = timeout or TIMEOUT
-
- id = next(self._id_generator)
- request = request_json(method, params, id)
- future_reply = DeferredFuture(self._process_cleanup)
-
- try:
- self._waiting_for_replies[id] = future_reply
- logger.debug(f"WebSocket queueing message: {request}")
- self._queue_in.put(request)
- logger.debug(f"WebSocket waiting for reply: {request}")
- try:
- r = future_reply.result(timeout=timeout)
- except TimeoutError as e:
- logger.error(f"WebSocket timed out while waiting for: {request} {e}")
- raise TimeoutException(
- f"WebSocket timed out while waiting for: {request} {e}"
- ) from e
- return r
- except Exception as e:
- logger.error(f"WebSocket received error while waiting for: {request} {e}")
- raise e
- finally:
- del self._waiting_for_replies[id]
- logger.debug(f"WebSocket removed waiting handler for {id}")
-
- def _receive_message(self, data: Data):
- logger.debug(f"Processing message: {data}".strip())
-
- message = to_response_or_notification(json.loads(data))
-
- logger.debug(
- f"Current waiting handlers: {list(self._waiting_for_replies.keys())}"
- )
- if isinstance(message, Ok):
- if (
- message.id in self._waiting_for_replies
- and self._waiting_for_replies[message.id]
- ):
- self._waiting_for_replies[message.id](message.result)
- return
- elif isinstance(message, Error):
- if (
- message.id in self._waiting_for_replies
- and self._waiting_for_replies[message.id]
- ):
- self._waiting_for_replies[message.id].reject(
- RpcException(
- code=message.code,
- message=message.message,
- id=message.id,
- data=message.data,
- )
- )
- return
-
- elif isinstance(message, Notification):
- self.on_message(message)
-
- def _close(self):
- self._closed = True
-
- for cancel in self._process_cleanup:
- cancel()
-
- self._process_cleanup.clear()
-
- # .copy() prevents a RuntimeError: dictionary changed size during iteration
- for handler in self._waiting_for_replies.copy().values():
- handler.cancel()
- del handler
-
- def close(self):
- self._close()
diff --git a/packages/python-sdk/e2b/sandbox/terminal.py b/packages/python-sdk/e2b/sandbox/terminal.py
deleted file mode 100644
index 83c468e46..000000000
--- a/packages/python-sdk/e2b/sandbox/terminal.py
+++ /dev/null
@@ -1,256 +0,0 @@
-from __future__ import annotations
-
-
-import logging
-import threading
-from concurrent.futures import Future
-from typing import Any, Callable, Optional
-
-from pydantic import BaseModel
-
-from e2b.constants import TIMEOUT
-from e2b.sandbox.env_vars import EnvVars
-from e2b.sandbox.exception import MultipleExceptions, RpcException, TerminalException
-from e2b.sandbox.sandbox_connection import SandboxConnection, SubscriptionArgs
-from e2b.utils.id import create_id
-
-logger = logging.getLogger(__file__)
-
-
-class TerminalOutput(BaseModel):
- data: str = ""
-
- def _add_data(self, data: str) -> None:
- self.data += data
-
-
-class Terminal:
- """
- Terminal session.
- """
-
- @property
- def data(self) -> str:
- """
- Terminal output data.
- """
- return self._output.data
-
- @property
- def output(self) -> TerminalOutput:
- """
- Terminal output.
- """
- return self._output
-
- @property
- def finished(self):
- """
- A future that is resolved when the terminal session exits.
- """
- return self._finished
-
- @property
- def terminal_id(self) -> str:
- """
- The terminal id used to identify the terminal in the session.
- """
- return self._terminal_id
-
- def wait(self):
- """
- Wait till the terminal session exits.
- """
- return self.finished.result()
-
- def __init__(
- self,
- terminal_id: str,
- sandbox: SandboxConnection,
- trigger_exit: Callable[[], Any],
- finished: Future[TerminalOutput],
- output: TerminalOutput,
- ):
- self._terminal_id = terminal_id
- self._sandbox = sandbox
- self._trigger_exit = trigger_exit
- self._finished = finished
- self._output = output
-
- def send_data(self, data: str, timeout: Optional[float] = TIMEOUT) -> None:
- """
- Send data to the terminal standard input.
-
- :param data: Data to send
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
- """
- try:
- self._sandbox._call(
- TerminalManager._service_name,
- "data",
- [self.terminal_id, data],
- timeout=timeout,
- )
- except RpcException as e:
- raise TerminalException(e.message) from e
-
- def resize(self, cols: int, rows: int, timeout: Optional[float] = TIMEOUT) -> None:
- """
- Resizes the terminal tty.
-
- :param cols: Number of columns
- :param rows: Number of rows
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
- """
- try:
- self._sandbox._call(
- TerminalManager._service_name,
- "resize",
- [self.terminal_id, cols, rows],
- timeout=timeout,
- )
- except RpcException as e:
- raise TerminalException(e.message) from e
-
- def kill(self, timeout: Optional[float] = TIMEOUT) -> None:
- """
- Kill the terminal session.
-
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
- """
- try:
- self._sandbox._call(
- TerminalManager._service_name,
- "destroy",
- [self.terminal_id],
- timeout=timeout,
- )
- except RpcException as e:
- raise TerminalException(e.message) from e
- self._trigger_exit()
-
-
-class TerminalManager:
- """
- Manager for starting and interacting with terminal sessions in the sandbox.
- """
-
- _service_name = "terminal"
-
- def __init__(self, sandbox: SandboxConnection):
- self._sandbox = sandbox
-
- def start(
- self,
- on_data: Callable[[str], Any],
- cols: int,
- rows: int,
- cwd: str = "",
- terminal_id: Optional[str] = None,
- on_exit: Optional[Callable[[], Any]] = None,
- cmd: Optional[str] = None,
- env_vars: Optional[EnvVars] = None,
- timeout: Optional[float] = TIMEOUT,
- ) -> Terminal:
- """
- Start a new terminal session.
-
- :param on_data: Callback that will be called when the terminal sends data
- :param cwd: Working directory where will the terminal start
- :param terminal_id: Unique identifier of the terminal session
- :param on_exit: Callback that will be called when the terminal exits
- :param cols: Number of columns the terminal will have. This affects rendering
- :param rows: Number of rows the terminal will have. This affects rendering
- :param cmd: If the `cmd` parameter is defined it will be executed as a command
- and this terminal session will exit when the command exits
- :param env_vars: Environment variables that will be accessible inside of the terminal
- :param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time
-
- :return: Terminal session
- """
- env_vars = self._sandbox.env_vars.update(env_vars or {})
-
- future_exit = Future()
- terminal_id = terminal_id or create_id(12)
-
- unsub_all: Optional[Callable[[], Any]] = None
-
- output = TerminalOutput()
-
- def handle_data(data: str):
- output._add_data(data)
- on_data(data)
-
- try:
- unsub_all = self._sandbox._handle_subscriptions(
- SubscriptionArgs(
- service=self._service_name,
- handler=handle_data,
- method="onData",
- params=[terminal_id],
- ),
- SubscriptionArgs(
- service=self._service_name,
- handler=lambda result: future_exit.set_result(result),
- method="onExit",
- params=[terminal_id],
- ),
- )
- except (RpcException, MultipleExceptions) as e:
- future_exit.cancel()
-
- if isinstance(e, RpcException):
- raise TerminalException(e.message) from e
- elif isinstance(e, MultipleExceptions):
- raise TerminalException(
- "Failed to subscribe to RPC services necessary for starting terminal"
- ) from e
-
- # TODO: Handle exit handler finish for exits (the same for processes)
- future_exit_handler_finish: Future[TerminalOutput] = Future()
-
- def exit_handler():
- future_exit.result()
-
- if unsub_all:
- unsub_all()
-
- if on_exit:
- on_exit()
- future_exit_handler_finish.set_result(output)
-
- threading.Thread(
- name="e2b-terminal-exit-handler", daemon=True, target=exit_handler
- ).start()
-
- def trigger_exit():
- future_exit.set_result(None)
- future_exit_handler_finish.result()
-
- try:
- if not cwd and self._sandbox.cwd:
- cwd = self._sandbox.cwd
-
- self._sandbox._call(
- self._service_name,
- "start",
- [
- terminal_id,
- cols,
- rows,
- env_vars if env_vars else {},
- cmd,
- cwd,
- ],
- timeout=timeout,
- )
- return Terminal(
- terminal_id=terminal_id,
- sandbox=self._sandbox,
- trigger_exit=trigger_exit,
- finished=future_exit_handler_finish,
- output=output,
- )
- except RpcException as e:
- trigger_exit()
- raise TerminalException(e.message) from e
diff --git a/packages/python-sdk/e2b/sandbox/websocket_client.py b/packages/python-sdk/e2b/sandbox/websocket_client.py
deleted file mode 100644
index 65ead1136..000000000
--- a/packages/python-sdk/e2b/sandbox/websocket_client.py
+++ /dev/null
@@ -1,120 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import logging
-
-from queue import Queue
-from threading import Event
-from typing import Any, Callable, List, Optional
-
-from websockets.legacy.client import WebSocketClientProtocol, connect
-from websockets.exceptions import ConnectionClosed
-from websockets.typing import Data
-
-logger = logging.getLogger(__name__)
-
-
-class WebSocket:
- def __init__(
- self,
- url: str,
- started: Event,
- stopped: Event,
- queue_in: Queue[dict],
- queue_out: Queue[Data],
- ):
- self._ws: Optional[WebSocketClientProtocol] = None
- self.url = url
- self.started = started
- self.stopped = stopped
- self._process_cleanup: List[Callable[[], Any]] = []
- self._queue_in = queue_in
- self._queue_out = queue_out
-
- def run(self):
- loop = asyncio.new_event_loop()
- asyncio.set_event_loop(loop)
-
- loop.run_until_complete(self.async_run())
-
- async def async_run(self):
- await self._connect()
- await self.close()
-
- async def _send_message(self):
- logger.debug("WebSocket starting to send messages")
- while True:
- if self._queue_in.empty():
- await asyncio.sleep(0)
- continue
- message = self._queue_in.get()
- logger.debug(f"WebSocket message to send: {message}")
- if self._ws:
- await self._ws.send(message)
- logger.debug(f"WebSocket message sent: {message}")
- self._queue_in.task_done()
- else:
- logger.error("No WebSocket connection")
-
- async def _receive_message(self):
- try:
- if not self._ws:
- logger.error("No WebSocket connection")
- return
- async for message in self._ws:
- logger.debug(f"WebSocket received message: {message}".strip())
- self._queue_out.put(message)
- except Exception as e:
- logger.error(f"WebSocket received error while receiving messages: {e}")
-
- async def _connect(self):
- logger.debug(f"WebSocket connecting to {self.url}")
-
- ws_logger = logger.getChild("websockets.client")
- ws_logger.setLevel(logging.ERROR)
-
- websocket_connector = connect(
- self.url,
- max_size=None,
- max_queue=None,
- logger=ws_logger,
- )
-
- websocket_connector.BACKOFF_MIN = 1
- websocket_connector.BACKOFF_FACTOR = 1
- websocket_connector.BACKOFF_INITIAL = 0.2 # type: ignore
-
- async for websocket in websocket_connector:
- try:
- self._ws = websocket
- self.started.set()
- logger.info(f"WebSocket connected to {self.url}")
-
- send_task = asyncio.create_task(
- self._send_message(), name="send_message"
- )
- self._process_cleanup.append(send_task.cancel)
-
- receive_task = asyncio.create_task(
- self._receive_message(), name="receive_message"
- )
- self._process_cleanup.append(receive_task.cancel)
-
- while not self.stopped.is_set():
- await asyncio.sleep(0)
-
- logger.info("WebSocket stopped")
- break
- except ConnectionClosed:
- logger.warning("WebSocket disconnected, it will try to reconnect")
- if self.stopped.is_set():
- break
-
- async def close(self):
- for cancel in self._process_cleanup:
- cancel()
-
- self._process_cleanup.clear()
-
- if self._ws:
- await self._ws.close()
diff --git a/packages/python-sdk/e2b/utils/api_key.py b/packages/python-sdk/e2b/utils/api_key.py
deleted file mode 100644
index edddf0be1..000000000
--- a/packages/python-sdk/e2b/utils/api_key.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from os import getenv
-from typing import Optional
-
-from e2b.sandbox.exception import AuthenticationException
-
-
-def get_api_key(api_key: Optional[str]) -> str:
- api_key = api_key or getenv("E2B_API_KEY")
-
- if api_key is None:
- raise AuthenticationException(
- "API key is required, please visit https://e2b.dev/docs to get your API key. "
- "You can either set the environment variable `E2B_API_KEY` "
- 'or you can pass it directly to the sandbox like Sandbox(api_key="e2b_...")',
- )
-
- return api_key
diff --git a/packages/python-sdk/e2b/utils/filesystem.py b/packages/python-sdk/e2b/utils/filesystem.py
deleted file mode 100644
index b301e565e..000000000
--- a/packages/python-sdk/e2b/utils/filesystem.py
+++ /dev/null
@@ -1,29 +0,0 @@
-import warnings
-
-from pathlib import PurePosixPath
-from typing import Optional
-
-
-def resolve_path(path: str, cwd: Optional[str] = None) -> str:
- warning = f"Path starts with {{0}} and cwd isn't set. The path {path} will evaluate to `{{1}}`, which may not be what you want."
- if path.startswith("./"):
- result = PurePosixPath(cwd or "/home/user", path).as_posix()
- if not cwd:
- warnings.warn(warning.format("./", result))
- return result
-
- if path.startswith("../"):
- result = PurePosixPath(cwd or "/home/user", path).as_posix()
- if not cwd:
- warnings.warn(warning.format("../", result))
- return result
-
- if path.startswith("~/"):
- result = PurePosixPath("/home/user", path[2:]).as_posix()
- warnings.warn(warning.format("~/", result))
- return result
-
- if not path.startswith("/") and cwd:
- return PurePosixPath(cwd, path).as_posix()
-
- return path
diff --git a/packages/python-sdk/e2b/utils/future.py b/packages/python-sdk/e2b/utils/future.py
deleted file mode 100644
index 269de3090..000000000
--- a/packages/python-sdk/e2b/utils/future.py
+++ /dev/null
@@ -1,46 +0,0 @@
-import asyncio
-from asyncio import AbstractEventLoop
-
-from concurrent.futures import Future, CancelledError
-from typing import Any, Awaitable, Callable, Generic, List, Optional, TypeVar
-
-T = TypeVar("T")
-
-
-# Check if using event is not better for most use cases
-class DeferredFuture(Generic[T]):
- def __init__(self, cleanup_list: Optional[List[Callable[[], Any]]] = None):
- self._future = Future()
- if cleanup_list is not None:
- cleanup_list.append(self.cancel)
-
- def __call__(self, result: T):
- if not self._future.done():
- self._future.set_result(result)
-
- def result(self, timeout: Optional[float] = None) -> T:
- try:
- return self._future.result(timeout=timeout)
- # The thread was interrupted while waiting, it's okay to release the thread
- except CancelledError:
- pass
-
- def done(self) -> bool:
- return self._future.done()
-
- def cancel(self):
- if not self._future.done():
- self._future.cancel()
-
- def reject(self, reason: Exception):
- if not self._future.done():
- self._future.set_exception(reason)
-
-
-def run_async_func_in_loop(loop: AbstractEventLoop, coro: Awaitable):
- asyncio.set_event_loop(loop)
-
- try:
- return loop.run_until_complete(coro)
- finally:
- loop.close()
diff --git a/packages/python-sdk/e2b/utils/id.py b/packages/python-sdk/e2b/utils/id.py
deleted file mode 100644
index 16ee60c37..000000000
--- a/packages/python-sdk/e2b/utils/id.py
+++ /dev/null
@@ -1,8 +0,0 @@
-import random
-import string
-
-characters = string.ascii_letters + string.digits
-
-
-def create_id(length: int):
- return "".join(random.choices(characters, k=length))
diff --git a/packages/python-sdk/e2b/utils/noop.py b/packages/python-sdk/e2b/utils/noop.py
deleted file mode 100644
index 8e7b9233a..000000000
--- a/packages/python-sdk/e2b/utils/noop.py
+++ /dev/null
@@ -1,2 +0,0 @@
-async def noop():
- return None
diff --git a/packages/python-sdk/e2b/utils/str.py b/packages/python-sdk/e2b/utils/str.py
deleted file mode 100644
index d1fe47fed..000000000
--- a/packages/python-sdk/e2b/utils/str.py
+++ /dev/null
@@ -1,10 +0,0 @@
-import re
-
-
-def camel_case_to_snake_case(text: str) -> str:
- return re.sub(r"(?<!^)(?=[A-Z])", "_", text).lower()
-
-
-def snake_case_to_camel_case(text: str) -> str:
- string_split = text.split("_")
- return string_split[0] + "".join(word.capitalize() for word in string_split[1:])
diff --git a/packages/python-sdk/e2b/utils/threads.py b/packages/python-sdk/e2b/utils/threads.py
deleted file mode 100644
index b87eafcd9..000000000
--- a/packages/python-sdk/e2b/utils/threads.py
+++ /dev/null
@@ -1,30 +0,0 @@
-import queue
-import sys
-
-from concurrent.futures import ThreadPoolExecutor
-
-
-def shutdown_executor(executor: ThreadPoolExecutor):
- py_version = sys.version_info
- if (py_version.major == 3) and (py_version.minor < 9):
- # py versions less than 3.9
- # Executor#shutdown does not accept
- # cancel_futures keyword
- # manually shutdown
- # code taken from https://github.com/python/cpython/blob/3.9/Lib/concurrent/futures/thread.py#L216
-
- # prevent new tasks from being submitted
- executor.shutdown(wait=False)
- while True:
- # cancel all waiting tasks
- try:
- work_item = executor._work_queue.get_nowait()
-
- except queue.Empty:
- break
-
- if work_item is not None:
- work_item.future.cancel()
-
- else:
- executor.shutdown(wait=False, cancel_futures=True)
diff --git a/packages/python-sdk/envd/filesystem/v1/filesystem_connect.py b/packages/python-sdk/envd/filesystem/v1/filesystem_connect.py
index 4d5fb44ef..99432fc4c 100644
--- a/packages/python-sdk/envd/filesystem/v1/filesystem_connect.py
+++ b/packages/python-sdk/envd/filesystem/v1/filesystem_connect.py
@@ -18,18 +18,10 @@ class FilesystemServiceClient:
json=json,
**opts
)
- self._create_dir = connect.Client(
+ self._list = connect.Client(
pool=pool,
- url=f"{base_url}/{FilesystemServiceName}/CreateDir",
- response_type=envd_dot_filesystem_dot_v1_dot_filesystem__pb2.CreateDirResponse,
- compressor=compressor,
- json=json,
- **opts
- )
- self._list_dir = connect.Client(
- pool=pool,
- url=f"{base_url}/{FilesystemServiceName}/ListDir",
- response_type=envd_dot_filesystem_dot_v1_dot_filesystem__pb2.ListDirResponse,
+ url=f"{base_url}/{FilesystemServiceName}/List",
+ response_type=envd_dot_filesystem_dot_v1_dot_filesystem__pb2.ListResponse,
compressor=compressor,
json=json,
**opts
@@ -42,14 +34,6 @@ class FilesystemServiceClient:
json=json,
**opts
)
- self._rename = connect.Client(
- pool=pool,
- url=f"{base_url}/{FilesystemServiceName}/Rename",
- response_type=envd_dot_filesystem_dot_v1_dot_filesystem__pb2.RenameResponse,
- compressor=compressor,
- json=json,
- **opts
- )
self._remove = connect.Client(
pool=pool,
url=f"{base_url}/{FilesystemServiceName}/Remove",
@@ -58,32 +42,15 @@ class FilesystemServiceClient:
json=json,
**opts
)
- self._copy = connect.Client(
- pool=pool,
- url=f"{base_url}/{FilesystemServiceName}/Copy",
- response_type=envd_dot_filesystem_dot_v1_dot_filesystem__pb2.CopyResponse,
- compressor=compressor,
- json=json,
- **opts
- )
def stat(self, req: envd_dot_filesystem_dot_v1_dot_filesystem__pb2.StatRequest, **opts) -> envd_dot_filesystem_dot_v1_dot_filesystem__pb2.StatResponse:
return self._stat.call_unary(req, **opts)
- def create_dir(self, req: envd_dot_filesystem_dot_v1_dot_filesystem__pb2.CreateDirRequest, **opts) -> envd_dot_filesystem_dot_v1_dot_filesystem__pb2.CreateDirResponse:
- return self._create_dir.call_unary(req, **opts)
-
- def list_dir(self, req: envd_dot_filesystem_dot_v1_dot_filesystem__pb2.ListDirRequest, **opts) -> envd_dot_filesystem_dot_v1_dot_filesystem__pb2.ListDirResponse:
- return self._list_dir.call_unary(req, **opts)
+ def list(self, req: envd_dot_filesystem_dot_v1_dot_filesystem__pb2.ListRequest, **opts) -> envd_dot_filesystem_dot_v1_dot_filesystem__pb2.ListResponse:
+ return self._list.call_unary(req, **opts)
def watch(self, req: envd_dot_filesystem_dot_v1_dot_filesystem__pb2.WatchRequest , **opts) -> Generator[envd_dot_filesystem_dot_v1_dot_filesystem__pb2.WatchResponse, Any, None]:
return self._watch.call_server_stream(req, **opts)
- def rename(self, req: envd_dot_filesystem_dot_v1_dot_filesystem__pb2.RenameRequest, **opts) -> envd_dot_filesystem_dot_v1_dot_filesystem__pb2.RenameResponse:
- return self._rename.call_unary(req, **opts)
-
def remove(self, req: envd_dot_filesystem_dot_v1_dot_filesystem__pb2.RemoveRequest, **opts) -> envd_dot_filesystem_dot_v1_dot_filesystem__pb2.RemoveResponse:
return self._remove.call_unary(req, **opts)
-
- def copy(self, req: envd_dot_filesystem_dot_v1_dot_filesystem__pb2.CopyRequest, **opts) -> envd_dot_filesystem_dot_v1_dot_filesystem__pb2.CopyResponse:
- return self._copy.call_unary(req, **opts)
diff --git a/packages/python-sdk/envd/filesystem/v1/filesystem_pb2.py b/packages/python-sdk/envd/filesystem/v1/filesystem_pb2.py
index 3affed467..021cd200a 100644
--- a/packages/python-sdk/envd/filesystem/v1/filesystem_pb2.py
+++ b/packages/python-sdk/envd/filesystem/v1/filesystem_pb2.py
@@ -12,11 +12,9 @@ from google.protobuf.internal import builder as _builder
_sym_db = _symbol_database.Default()
-from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
-from envd.permissions.v1 import permissions_pb2 as envd_dot_permissions_dot_v1_dot_permissions__pb2
-DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n#envd/filesystem/v1/filesystem.proto\x12\x12\x65nvd.filesystem.v1\x1a\x1fgoogle/protobuf/timestamp.proto\x1a%envd/permissions/v1/permissions.proto\"r\n\x10\x43reateDirRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\x12\x12\n\x04mode\x18\x03 \x01(\tR\x04mode\x12\x36\n\x05owner\x18\x04 \x01(\x0b\x32 .envd.permissions.v1.CredentialsR\x05owner\"\x13\n\x11\x43reateDirResponse\"[\n\x0b\x43opyRequest\x12\x16\n\x06source\x18\x01 \x01(\tR\x06source\x12 \n\x0b\x64\x65stination\x18\x02 \x01(\tR\x0b\x64\x65stination\x12\x12\n\x04mode\x18\x03 \x01(\tR\x04mode\"\x0e\n\x0c\x43opyResponse\"!\n\x0bStatRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\"C\n\x0cStatResponse\x12\x33\n\x05\x65ntry\x18\x01 \x01(\x0b\x32\x1d.envd.filesystem.v1.EntryInfoR\x05\x65ntry\"A\n\rRemoveRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\x12\x1c\n\trecursive\x18\x02 \x01(\x08R\trecursive\"\x10\n\x0eRemoveResponse\"I\n\rRenameRequest\x12\x16\n\x06source\x18\x01 \x01(\tR\x06source\x12 \n\x0b\x64\x65stination\x18\x02 \x01(\tR\x0b\x64\x65stination\"\x10\n\x0eRenameResponse\"Q\n\tEntryInfo\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x30\n\x04type\x18\x02 \x01(\x0e\x32\x1c.envd.filesystem.v1.FileTypeR\x04type\"$\n\x0eListDirRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\"J\n\x0fListDirResponse\x12\x37\n\x07\x65ntries\x18\x01 \x03(\x0b\x32\x1d.envd.filesystem.v1.EntryInfoR\x07\x65ntries\"\"\n\x0cWatchRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\"J\n\rWatchResponse\x12\x39\n\x05\x65vent\x18\x01 \x01(\x0b\x32#.envd.filesystem.v1.FilesystemEventR\x05\x65vent\"X\n\x0f\x46ilesystemEvent\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\x12\x31\n\x04type\x18\x02 \x01(\x0e\x32\x1d.envd.filesystem.v1.EventTypeR\x04type*R\n\x08\x46ileType\x12\x19\n\x15\x46ILE_TYPE_UNSPECIFIED\x10\x00\x12\x12\n\x0e\x46ILE_TYPE_FILE\x10\x01\x12\x17\n\x13\x46ILE_TYPE_DIRECTORY\x10\x02*\x98\x01\n\tEventType\x12\x1a\n\x16\x45VENT_TYPE_UNSPECIFIED\x10\x00\x12\x15\n\x11\x45VENT_TYPE_CREATE\x10\x01\x12\x14\n\x10\x45VENT_TYPE_WRITE\x10\x02\x12\x15\n\x11\x45VENT_TYPE_REMOVE\x10\x03\x12\x15\n\x11\x45VENT_TYPE_RENAME\x10\x04\x12\x14\n\x10\x45VENT_TYPE_CHMOD\x10\x05\x32\xc9\x04\n\x11\x46ilesystemService\x12I\n\x04Stat\x12\x1f.envd.filesystem.v1.StatRequest\x1a .envd.filesystem.v1.StatResponse\x12X\n\tCreateDir\x12$.envd.filesystem.v1.CreateDirRequest\x1a%.envd.filesystem.v1.CreateDirResponse\x12R\n\x07ListDir\x12\".envd.filesystem.v1.ListDirRequest\x1a#.envd.filesystem.v1.ListDirResponse\x12N\n\x05Watch\x12 .envd.filesystem.v1.WatchRequest\x1a!.envd.filesystem.v1.WatchResponse0\x01\x12O\n\x06Rename\x12!.envd.filesystem.v1.RenameRequest\x1a\".envd.filesystem.v1.RenameResponse\x12O\n\x06Remove\x12!.envd.filesystem.v1.RemoveRequest\x1a\".envd.filesystem.v1.RemoveResponse\x12I\n\x04\x43opy\x12\x1f.envd.filesystem.v1.CopyRequest\x1a .envd.filesystem.v1.CopyResponseB\x93\x01\n\x16\x63om.envd.filesystem.v1B\x0f\x46ilesystemProtoP\x01\xa2\x02\x03\x45\x46X\xaa\x02\x12\x45nvd.Filesystem.V1\xca\x02\x12\x45nvd\\Filesystem\\V1\xe2\x02\x1e\x45nvd\\Filesystem\\V1\\GPBMetadata\xea\x02\x14\x45nvd::Filesystem::V1b\x06proto3')
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n#envd/filesystem/v1/filesystem.proto\x12\x12\x65nvd.filesystem.v1\"#\n\rRemoveRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\"\x10\n\x0eRemoveResponse\"!\n\x0bStatRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\"C\n\x0cStatResponse\x12\x33\n\x05\x65ntry\x18\x01 \x01(\x0b\x32\x1d.envd.filesystem.v1.EntryInfoR\x05\x65ntry\"Q\n\tEntryInfo\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x30\n\x04type\x18\x02 \x01(\x0e\x32\x1c.envd.filesystem.v1.FileTypeR\x04type\"!\n\x0bListRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\"G\n\x0cListResponse\x12\x37\n\x07\x65ntries\x18\x01 \x03(\x0b\x32\x1d.envd.filesystem.v1.EntryInfoR\x07\x65ntries\"\"\n\x0cWatchRequest\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\"J\n\rWatchResponse\x12\x39\n\x05\x65vent\x18\x01 \x01(\x0b\x32#.envd.filesystem.v1.FilesystemEventR\x05\x65vent\"X\n\x0f\x46ilesystemEvent\x12\x12\n\x04path\x18\x01 \x01(\tR\x04path\x12\x31\n\x04type\x18\x02 \x01(\x0e\x32\x1d.envd.filesystem.v1.EventTypeR\x04type*R\n\x08\x46ileType\x12\x19\n\x15\x46ILE_TYPE_UNSPECIFIED\x10\x00\x12\x12\n\x0e\x46ILE_TYPE_FILE\x10\x01\x12\x17\n\x13\x46ILE_TYPE_DIRECTORY\x10\x02*\x98\x01\n\tEventType\x12\x1a\n\x16\x45VENT_TYPE_UNSPECIFIED\x10\x00\x12\x15\n\x11\x45VENT_TYPE_CREATE\x10\x01\x12\x14\n\x10\x45VENT_TYPE_WRITE\x10\x02\x12\x15\n\x11\x45VENT_TYPE_REMOVE\x10\x03\x12\x15\n\x11\x45VENT_TYPE_RENAME\x10\x04\x12\x14\n\x10\x45VENT_TYPE_CHMOD\x10\x05\x32\xca\x02\n\x11\x46ilesystemService\x12I\n\x04Stat\x12\x1f.envd.filesystem.v1.StatRequest\x1a .envd.filesystem.v1.StatResponse\x12I\n\x04List\x12\x1f.envd.filesystem.v1.ListRequest\x1a .envd.filesystem.v1.ListResponse\x12N\n\x05Watch\x12 .envd.filesystem.v1.WatchRequest\x1a!.envd.filesystem.v1.WatchResponse0\x01\x12O\n\x06Remove\x12!.envd.filesystem.v1.RemoveRequest\x1a\".envd.filesystem.v1.RemoveResponseB\x93\x01\n\x16\x63om.envd.filesystem.v1B\x0f\x46ilesystemProtoP\x01\xa2\x02\x03\x45\x46X\xaa\x02\x12\x45nvd.Filesystem.V1\xca\x02\x12\x45nvd\\Filesystem\\V1\xe2\x02\x1e\x45nvd\\Filesystem\\V1\\GPBMetadata\xea\x02\x14\x45nvd::Filesystem::V1b\x06proto3')
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
@@ -24,42 +22,30 @@ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'envd.filesystem.v1.filesyst
if not _descriptor._USE_C_DESCRIPTORS:
_globals['DESCRIPTOR']._loaded_options = None
_globals['DESCRIPTOR']._serialized_options = b'\n\026com.envd.filesystem.v1B\017FilesystemProtoP\001\242\002\003EFX\252\002\022Envd.Filesystem.V1\312\002\022Envd\\Filesystem\\V1\342\002\036Envd\\Filesystem\\V1\\GPBMetadata\352\002\024Envd::Filesystem::V1'
- _globals['_FILETYPE']._serialized_start=1058
- _globals['_FILETYPE']._serialized_end=1140
- _globals['_EVENTTYPE']._serialized_start=1143
- _globals['_EVENTTYPE']._serialized_end=1295
- _globals['_CREATEDIRREQUEST']._serialized_start=131
- _globals['_CREATEDIRREQUEST']._serialized_end=245
- _globals['_CREATEDIRRESPONSE']._serialized_start=247
- _globals['_CREATEDIRRESPONSE']._serialized_end=266
- _globals['_COPYREQUEST']._serialized_start=268
- _globals['_COPYREQUEST']._serialized_end=359
- _globals['_COPYRESPONSE']._serialized_start=361
- _globals['_COPYRESPONSE']._serialized_end=375
- _globals['_STATREQUEST']._serialized_start=377
- _globals['_STATREQUEST']._serialized_end=410
- _globals['_STATRESPONSE']._serialized_start=412
- _globals['_STATRESPONSE']._serialized_end=479
- _globals['_REMOVEREQUEST']._serialized_start=481
- _globals['_REMOVEREQUEST']._serialized_end=546
- _globals['_REMOVERESPONSE']._serialized_start=548
- _globals['_REMOVERESPONSE']._serialized_end=564
- _globals['_RENAMEREQUEST']._serialized_start=566
- _globals['_RENAMEREQUEST']._serialized_end=639
- _globals['_RENAMERESPONSE']._serialized_start=641
- _globals['_RENAMERESPONSE']._serialized_end=657
- _globals['_ENTRYINFO']._serialized_start=659
- _globals['_ENTRYINFO']._serialized_end=740
- _globals['_LISTDIRREQUEST']._serialized_start=742
- _globals['_LISTDIRREQUEST']._serialized_end=778
- _globals['_LISTDIRRESPONSE']._serialized_start=780
- _globals['_LISTDIRRESPONSE']._serialized_end=854
- _globals['_WATCHREQUEST']._serialized_start=856
- _globals['_WATCHREQUEST']._serialized_end=890
- _globals['_WATCHRESPONSE']._serialized_start=892
- _globals['_WATCHRESPONSE']._serialized_end=966
- _globals['_FILESYSTEMEVENT']._serialized_start=968
- _globals['_FILESYSTEMEVENT']._serialized_end=1056
- _globals['_FILESYSTEMSERVICE']._serialized_start=1298
- _globals['_FILESYSTEMSERVICE']._serialized_end=1883
+ _globals['_FILETYPE']._serialized_start=611
+ _globals['_FILETYPE']._serialized_end=693
+ _globals['_EVENTTYPE']._serialized_start=696
+ _globals['_EVENTTYPE']._serialized_end=848
+ _globals['_REMOVEREQUEST']._serialized_start=59
+ _globals['_REMOVEREQUEST']._serialized_end=94
+ _globals['_REMOVERESPONSE']._serialized_start=96
+ _globals['_REMOVERESPONSE']._serialized_end=112
+ _globals['_STATREQUEST']._serialized_start=114
+ _globals['_STATREQUEST']._serialized_end=147
+ _globals['_STATRESPONSE']._serialized_start=149
+ _globals['_STATRESPONSE']._serialized_end=216
+ _globals['_ENTRYINFO']._serialized_start=218
+ _globals['_ENTRYINFO']._serialized_end=299
+ _globals['_LISTREQUEST']._serialized_start=301
+ _globals['_LISTREQUEST']._serialized_end=334
+ _globals['_LISTRESPONSE']._serialized_start=336
+ _globals['_LISTRESPONSE']._serialized_end=407
+ _globals['_WATCHREQUEST']._serialized_start=409
+ _globals['_WATCHREQUEST']._serialized_end=443
+ _globals['_WATCHRESPONSE']._serialized_start=445
+ _globals['_WATCHRESPONSE']._serialized_end=519
+ _globals['_FILESYSTEMEVENT']._serialized_start=521
+ _globals['_FILESYSTEMEVENT']._serialized_end=609
+ _globals['_FILESYSTEMSERVICE']._serialized_start=851
+ _globals['_FILESYSTEMSERVICE']._serialized_end=1181
# @@protoc_insertion_point(module_scope)
diff --git a/packages/python-sdk/envd/filesystem/v1/filesystem_pb2.pyi b/packages/python-sdk/envd/filesystem/v1/filesystem_pb2.pyi
index 8e0d7c1d1..c5068c5f1 100644
--- a/packages/python-sdk/envd/filesystem/v1/filesystem_pb2.pyi
+++ b/packages/python-sdk/envd/filesystem/v1/filesystem_pb2.pyi
@@ -1,5 +1,3 @@
-from google.protobuf import timestamp_pb2 as _timestamp_pb2
-from envd.permissions.v1 import permissions_pb2 as _permissions_pb2
from google.protobuf.internal import containers as _containers
from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
from google.protobuf import descriptor as _descriptor
@@ -32,31 +30,13 @@ EVENT_TYPE_REMOVE: EventType
EVENT_TYPE_RENAME: EventType
EVENT_TYPE_CHMOD: EventType
-class CreateDirRequest(_message.Message):
- __slots__ = ("path", "mode", "owner")
+class RemoveRequest(_message.Message):
+ __slots__ = ("path",)
PATH_FIELD_NUMBER: _ClassVar[int]
- MODE_FIELD_NUMBER: _ClassVar[int]
- OWNER_FIELD_NUMBER: _ClassVar[int]
path: str
- mode: str
- owner: _permissions_pb2.Credentials
- def __init__(self, path: _Optional[str] = ..., mode: _Optional[str] = ..., owner: _Optional[_Union[_permissions_pb2.Credentials, _Mapping]] = ...) -> None: ...
-
-class CreateDirResponse(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
-class CopyRequest(_message.Message):
- __slots__ = ("source", "destination", "mode")
- SOURCE_FIELD_NUMBER: _ClassVar[int]
- DESTINATION_FIELD_NUMBER: _ClassVar[int]
- MODE_FIELD_NUMBER: _ClassVar[int]
- source: str
- destination: str
- mode: str
- def __init__(self, source: _Optional[str] = ..., destination: _Optional[str] = ..., mode: _Optional[str] = ...) -> None: ...
+ def __init__(self, path: _Optional[str] = ...) -> None: ...
-class CopyResponse(_message.Message):
+class RemoveResponse(_message.Message):
__slots__ = ()
def __init__(self) -> None: ...
@@ -72,30 +52,6 @@ class StatResponse(_message.Message):
entry: EntryInfo
def __init__(self, entry: _Optional[_Union[EntryInfo, _Mapping]] = ...) -> None: ...
-class RemoveRequest(_message.Message):
- __slots__ = ("path", "recursive")
- PATH_FIELD_NUMBER: _ClassVar[int]
- RECURSIVE_FIELD_NUMBER: _ClassVar[int]
- path: str
- recursive: bool
- def __init__(self, path: _Optional[str] = ..., recursive: bool = ...) -> None: ...
-
-class RemoveResponse(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
-class RenameRequest(_message.Message):
- __slots__ = ("source", "destination")
- SOURCE_FIELD_NUMBER: _ClassVar[int]
- DESTINATION_FIELD_NUMBER: _ClassVar[int]
- source: str
- destination: str
- def __init__(self, source: _Optional[str] = ..., destination: _Optional[str] = ...) -> None: ...
-
-class RenameResponse(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
class EntryInfo(_message.Message):
__slots__ = ("name", "type")
NAME_FIELD_NUMBER: _ClassVar[int]
@@ -104,13 +60,13 @@ class EntryInfo(_message.Message):
type: FileType
def __init__(self, name: _Optional[str] = ..., type: _Optional[_Union[FileType, str]] = ...) -> None: ...
-class ListDirRequest(_message.Message):
+class ListRequest(_message.Message):
__slots__ = ("path",)
PATH_FIELD_NUMBER: _ClassVar[int]
path: str
def __init__(self, path: _Optional[str] = ...) -> None: ...
-class ListDirResponse(_message.Message):
+class ListResponse(_message.Message):
__slots__ = ("entries",)
ENTRIES_FIELD_NUMBER: _ClassVar[int]
entries: _containers.RepeatedCompositeFieldContainer[EntryInfo]
diff --git a/packages/python-sdk/envd/network/v1/network_connect.py b/packages/python-sdk/envd/network/v1/network_connect.py
deleted file mode 100644
index 6d87a60c9..000000000
--- a/packages/python-sdk/envd/network/v1/network_connect.py
+++ /dev/null
@@ -1,40 +0,0 @@
-# Code generated by protoc-gen-connect-python 0.1.0.dev2, DO NOT EDIT.
-from typing import Any, Generator
-
-import connect
-
-from envd.network.v1 import network_pb2 as envd_dot_network_dot_v1_dot_network__pb2
-
-NetworkServiceName = "envd.network.v1.NetworkService"
-
-
-class NetworkServiceClient:
- def __init__(self, base_url, *, pool=None, compressor=None, json=False, **opts):
- self._list_ports = connect.Client(
- pool=pool,
- url=f"{base_url}/{NetworkServiceName}/ListPorts",
- response_type=envd_dot_network_dot_v1_dot_network__pb2.ListPortsResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
- self._watch_ports = connect.Client(
- pool=pool,
- url=f"{base_url}/{NetworkServiceName}/WatchPorts",
- response_type=envd_dot_network_dot_v1_dot_network__pb2.WatchPortsResponse,
- compressor=compressor,
- json=json,
- **opts,
- )
-
- def list_ports(
- self, req: envd_dot_network_dot_v1_dot_network__pb2.ListPortsRequest, **opts
- ) -> envd_dot_network_dot_v1_dot_network__pb2.ListPortsResponse:
- return self._list_ports.call_unary(req, **opts)
-
- def watch_ports(
- self, req: envd_dot_network_dot_v1_dot_network__pb2.WatchPortsRequest, **opts
- ) -> Generator[
- envd_dot_network_dot_v1_dot_network__pb2.WatchPortsResponse, Any, None
- ]:
- return self._watch_ports.call_server_stream(req, **opts)
diff --git a/packages/python-sdk/envd/network/v1/network_pb2.py b/packages/python-sdk/envd/network/v1/network_pb2.py
deleted file mode 100644
index 8bd702703..000000000
--- a/packages/python-sdk/envd/network/v1/network_pb2.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# -*- coding: utf-8 -*-
-# Generated by the protocol buffer compiler. DO NOT EDIT!
-# source: envd/network/v1/network.proto
-# Protobuf Python Version: 5.26.1
-"""Generated protocol buffer code."""
-from google.protobuf import descriptor as _descriptor
-from google.protobuf import descriptor_pool as _descriptor_pool
-from google.protobuf import symbol_database as _symbol_database
-from google.protobuf.internal import builder as _builder
-
-# @@protoc_insertion_point(imports)
-
-_sym_db = _symbol_database.Default()
-
-
-from envd.permissions.v1 import (
- permissions_pb2 as envd_dot_permissions_dot_v1_dot_permissions__pb2,
-)
-
-
-DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
- b'\n\x1d\x65nvd/network/v1/network.proto\x12\x0f\x65nvd.network.v1\x1a%envd/permissions/v1/permissions.proto"\x12\n\x10ListPortsRequest"@\n\x11ListPortsResponse\x12+\n\x05ports\x18\x01 \x03(\x0b\x32\x15.envd.network.v1.PortR\x05ports"H\n\x11WatchPortsRequest\x12\x33\n\x06\x66ilter\x18\x01 \x01(\x0b\x32\x1b.envd.network.v1.PortFilterR\x06\x66ilter""\n\nPortFilter\x12\x14\n\x05ports\x18\x01 \x03(\rR\x05ports"A\n\x12WatchPortsResponse\x12+\n\x05\x65vent\x18\x01 \x01(\x0b\x32\x15.envd.network.v1.PortR\x05\x65vent"L\n\x04Port\x12\x12\n\x04port\x18\x01 \x01(\rR\x04port\x12\x30\n\x05state\x18\x02 \x01(\x0e\x32\x1a.envd.network.v1.PortStateR\x05state*S\n\tPortState\x12\x1a\n\x16PORT_STATE_UNSPECIFIED\x10\x00\x12\x13\n\x0fPORT_STATE_OPEN\x10\x01\x12\x15\n\x11PORT_STATE_CLOSED\x10\x02\x32\xbd\x01\n\x0eNetworkService\x12R\n\tListPorts\x12!.envd.network.v1.ListPortsRequest\x1a".envd.network.v1.ListPortsResponse\x12W\n\nWatchPorts\x12".envd.network.v1.WatchPortsRequest\x1a#.envd.network.v1.WatchPortsResponse0\x01\x42\x81\x01\n\x13\x63om.envd.network.v1B\x0cNetworkProtoP\x01\xa2\x02\x03\x45NX\xaa\x02\x0f\x45nvd.Network.V1\xca\x02\x0f\x45nvd\\Network\\V1\xe2\x02\x1b\x45nvd\\Network\\V1\\GPBMetadata\xea\x02\x11\x45nvd::Network::V1b\x06proto3'
-)
-
-_globals = globals()
-_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
-_builder.BuildTopDescriptorsAndMessages(
- DESCRIPTOR, "envd.network.v1.network_pb2", _globals
-)
-if not _descriptor._USE_C_DESCRIPTORS:
- _globals["DESCRIPTOR"]._loaded_options = None
- _globals[
- "DESCRIPTOR"
- ]._serialized_options = b"\n\023com.envd.network.v1B\014NetworkProtoP\001\242\002\003ENX\252\002\017Envd.Network.V1\312\002\017Envd\\Network\\V1\342\002\033Envd\\Network\\V1\\GPBMetadata\352\002\021Envd::Network::V1"
- _globals["_PORTSTATE"]._serialized_start = 430
- _globals["_PORTSTATE"]._serialized_end = 513
- _globals["_LISTPORTSREQUEST"]._serialized_start = 89
- _globals["_LISTPORTSREQUEST"]._serialized_end = 107
- _globals["_LISTPORTSRESPONSE"]._serialized_start = 109
- _globals["_LISTPORTSRESPONSE"]._serialized_end = 173
- _globals["_WATCHPORTSREQUEST"]._serialized_start = 175
- _globals["_WATCHPORTSREQUEST"]._serialized_end = 247
- _globals["_PORTFILTER"]._serialized_start = 249
- _globals["_PORTFILTER"]._serialized_end = 283
- _globals["_WATCHPORTSRESPONSE"]._serialized_start = 285
- _globals["_WATCHPORTSRESPONSE"]._serialized_end = 350
- _globals["_PORT"]._serialized_start = 352
- _globals["_PORT"]._serialized_end = 428
- _globals["_NETWORKSERVICE"]._serialized_start = 516
- _globals["_NETWORKSERVICE"]._serialized_end = 705
-# @@protoc_insertion_point(module_scope)
diff --git a/packages/python-sdk/envd/network/v1/network_pb2.pyi b/packages/python-sdk/envd/network/v1/network_pb2.pyi
deleted file mode 100644
index 502e83172..000000000
--- a/packages/python-sdk/envd/network/v1/network_pb2.pyi
+++ /dev/null
@@ -1,66 +0,0 @@
-from envd.permissions.v1 import permissions_pb2 as _permissions_pb2
-from google.protobuf.internal import containers as _containers
-from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
-from google.protobuf import descriptor as _descriptor
-from google.protobuf import message as _message
-from typing import (
- ClassVar as _ClassVar,
- Iterable as _Iterable,
- Mapping as _Mapping,
- Optional as _Optional,
- Union as _Union,
-)
-
-DESCRIPTOR: _descriptor.FileDescriptor
-
-class PortState(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
- __slots__ = ()
- PORT_STATE_UNSPECIFIED: _ClassVar[PortState]
- PORT_STATE_OPEN: _ClassVar[PortState]
- PORT_STATE_CLOSED: _ClassVar[PortState]
-
-PORT_STATE_UNSPECIFIED: PortState
-PORT_STATE_OPEN: PortState
-PORT_STATE_CLOSED: PortState
-
-class ListPortsRequest(_message.Message):
- __slots__ = ()
- def __init__(self) -> None: ...
-
-class ListPortsResponse(_message.Message):
- __slots__ = ("ports",)
- PORTS_FIELD_NUMBER: _ClassVar[int]
- ports: _containers.RepeatedCompositeFieldContainer[Port]
- def __init__(
- self, ports: _Optional[_Iterable[_Union[Port, _Mapping]]] = ...
- ) -> None: ...
-
-class WatchPortsRequest(_message.Message):
- __slots__ = ("filter",)
- FILTER_FIELD_NUMBER: _ClassVar[int]
- filter: PortFilter
- def __init__(
- self, filter: _Optional[_Union[PortFilter, _Mapping]] = ...
- ) -> None: ...
-
-class PortFilter(_message.Message):
- __slots__ = ("ports",)
- PORTS_FIELD_NUMBER: _ClassVar[int]
- ports: _containers.RepeatedScalarFieldContainer[int]
- def __init__(self, ports: _Optional[_Iterable[int]] = ...) -> None: ...
-
-class WatchPortsResponse(_message.Message):
- __slots__ = ("event",)
- EVENT_FIELD_NUMBER: _ClassVar[int]
- event: Port
- def __init__(self, event: _Optional[_Union[Port, _Mapping]] = ...) -> None: ...
-
-class Port(_message.Message):
- __slots__ = ("port", "state")
- PORT_FIELD_NUMBER: _ClassVar[int]
- STATE_FIELD_NUMBER: _ClassVar[int]
- port: int
- state: PortState
- def __init__(
- self, port: _Optional[int] = ..., state: _Optional[_Union[PortState, str]] = ...
- ) -> None: ...
diff --git a/packages/python-sdk/envd/permissions/v1/permissions_pb2.py b/packages/python-sdk/envd/permissions/v1/permissions_pb2.py
deleted file mode 100644
index a14acb403..000000000
--- a/packages/python-sdk/envd/permissions/v1/permissions_pb2.py
+++ /dev/null
@@ -1,27 +0,0 @@
-# -*- coding: utf-8 -*-
-# Generated by the protocol buffer compiler. DO NOT EDIT!
-# source: envd/permissions/v1/permissions.proto
-# Protobuf Python Version: 5.26.1
-"""Generated protocol buffer code."""
-from google.protobuf import descriptor as _descriptor
-from google.protobuf import descriptor_pool as _descriptor_pool
-from google.protobuf import symbol_database as _symbol_database
-from google.protobuf.internal import builder as _builder
-# @@protoc_insertion_point(imports)
-
-_sym_db = _symbol_database.Default()
-
-
-
-
-DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n%envd/permissions/v1/permissions.proto\x12\x13\x65nvd.permissions.v1\":\n\x0b\x43redentials\x12\x1c\n\x08username\x18\x01 \x01(\tH\x00R\x08usernameB\r\n\x0b\x63redentialsB\x99\x01\n\x17\x63om.envd.permissions.v1B\x10PermissionsProtoP\x01\xa2\x02\x03\x45PX\xaa\x02\x13\x45nvd.Permissions.V1\xca\x02\x13\x45nvd\\Permissions\\V1\xe2\x02\x1f\x45nvd\\Permissions\\V1\\GPBMetadata\xea\x02\x15\x45nvd::Permissions::V1b\x06proto3')
-
-_globals = globals()
-_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
-_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'envd.permissions.v1.permissions_pb2', _globals)
-if not _descriptor._USE_C_DESCRIPTORS:
- _globals['DESCRIPTOR']._loaded_options = None
- _globals['DESCRIPTOR']._serialized_options = b'\n\027com.envd.permissions.v1B\020PermissionsProtoP\001\242\002\003EPX\252\002\023Envd.Permissions.V1\312\002\023Envd\\Permissions\\V1\342\002\037Envd\\Permissions\\V1\\GPBMetadata\352\002\025Envd::Permissions::V1'
- _globals['_CREDENTIALS']._serialized_start=62
- _globals['_CREDENTIALS']._serialized_end=120
-# @@protoc_insertion_point(module_scope)
diff --git a/packages/python-sdk/envd/permissions/v1/permissions_pb2.pyi b/packages/python-sdk/envd/permissions/v1/permissions_pb2.pyi
deleted file mode 100644
index f6dd4882a..000000000
--- a/packages/python-sdk/envd/permissions/v1/permissions_pb2.pyi
+++ /dev/null
@@ -1,11 +0,0 @@
-from google.protobuf import descriptor as _descriptor
-from google.protobuf import message as _message
-from typing import ClassVar as _ClassVar, Optional as _Optional
-
-DESCRIPTOR: _descriptor.FileDescriptor
-
-class Credentials(_message.Message):
- __slots__ = ("username",)
- USERNAME_FIELD_NUMBER: _ClassVar[int]
- username: str
- def __init__(self, username: _Optional[str] = ...) -> None: ...
diff --git a/packages/python-sdk/envd/process/v1/process_connect.py b/packages/python-sdk/envd/process/v1/process_connect.py
index 21b6cb518..0bec00c57 100644
--- a/packages/python-sdk/envd/process/v1/process_connect.py
+++ b/packages/python-sdk/envd/process/v1/process_connect.py
@@ -10,80 +10,80 @@ ProcessServiceName = "envd.process.v1.ProcessService"
class ProcessServiceClient:
def __init__(self, base_url, *, pool=None, compressor=None, json=False, **opts):
- self._list_processes = connect.Client(
+ self._list = connect.Client(
pool=pool,
- url=f"{base_url}/{ProcessServiceName}/ListProcesses",
- response_type=envd_dot_process_dot_v1_dot_process__pb2.ListProcessesResponse,
+ url=f"{base_url}/{ProcessServiceName}/List",
+ response_type=envd_dot_process_dot_v1_dot_process__pb2.ListResponse,
compressor=compressor,
json=json,
**opts
)
- self._reconnect_process = connect.Client(
+ self._connect = connect.Client(
pool=pool,
- url=f"{base_url}/{ProcessServiceName}/ReconnectProcess",
- response_type=envd_dot_process_dot_v1_dot_process__pb2.ReconnectProcessResponse,
+ url=f"{base_url}/{ProcessServiceName}/Connect",
+ response_type=envd_dot_process_dot_v1_dot_process__pb2.ConnectResponse,
compressor=compressor,
json=json,
**opts
)
- self._start_process = connect.Client(
+ self._start = connect.Client(
pool=pool,
- url=f"{base_url}/{ProcessServiceName}/StartProcess",
- response_type=envd_dot_process_dot_v1_dot_process__pb2.StartProcessResponse,
+ url=f"{base_url}/{ProcessServiceName}/Start",
+ response_type=envd_dot_process_dot_v1_dot_process__pb2.StartResponse,
compressor=compressor,
json=json,
**opts
)
- self._update_process = connect.Client(
+ self._update = connect.Client(
pool=pool,
- url=f"{base_url}/{ProcessServiceName}/UpdateProcess",
- response_type=envd_dot_process_dot_v1_dot_process__pb2.UpdateProcessResponse,
+ url=f"{base_url}/{ProcessServiceName}/Update",
+ response_type=envd_dot_process_dot_v1_dot_process__pb2.UpdateResponse,
compressor=compressor,
json=json,
**opts
)
- self._send_process_input_stream = connect.Client(
+ self._stream_input = connect.Client(
pool=pool,
- url=f"{base_url}/{ProcessServiceName}/SendProcessInputStream",
- response_type=envd_dot_process_dot_v1_dot_process__pb2.SendProcessInputStreamResponse,
+ url=f"{base_url}/{ProcessServiceName}/StreamInput",
+ response_type=envd_dot_process_dot_v1_dot_process__pb2.StreamInputResponse,
compressor=compressor,
json=json,
**opts
)
- self._send_process_input = connect.Client(
+ self._send_input = connect.Client(
pool=pool,
- url=f"{base_url}/{ProcessServiceName}/SendProcessInput",
- response_type=envd_dot_process_dot_v1_dot_process__pb2.SendProcessInputResponse,
+ url=f"{base_url}/{ProcessServiceName}/SendInput",
+ response_type=envd_dot_process_dot_v1_dot_process__pb2.SendInputResponse,
compressor=compressor,
json=json,
**opts
)
- self._send_process_signal = connect.Client(
+ self._send_signal = connect.Client(
pool=pool,
- url=f"{base_url}/{ProcessServiceName}/SendProcessSignal",
- response_type=envd_dot_process_dot_v1_dot_process__pb2.SendProcessSignalResponse,
+ url=f"{base_url}/{ProcessServiceName}/SendSignal",
+ response_type=envd_dot_process_dot_v1_dot_process__pb2.SendSignalResponse,
compressor=compressor,
json=json,
**opts
)
- def list_processes(self, req: envd_dot_process_dot_v1_dot_process__pb2.ListProcessesRequest, **opts) -> envd_dot_process_dot_v1_dot_process__pb2.ListProcessesResponse:
- return self._list_processes.call_unary(req, **opts)
+ def list(self, req: envd_dot_process_dot_v1_dot_process__pb2.ListRequest, **opts) -> envd_dot_process_dot_v1_dot_process__pb2.ListResponse:
+ return self._list.call_unary(req, **opts)
- def reconnect_process(self, req: envd_dot_process_dot_v1_dot_process__pb2.ReconnectProcessRequest , **opts) -> Generator[envd_dot_process_dot_v1_dot_process__pb2.ReconnectProcessResponse, Any, None]:
- return self._reconnect_process.call_server_stream(req, **opts)
+ def connect(self, req: envd_dot_process_dot_v1_dot_process__pb2.ConnectRequest , **opts) -> Generator[envd_dot_process_dot_v1_dot_process__pb2.ConnectResponse, Any, None]:
+ return self._connect.call_server_stream(req, **opts)
- def start_process(self, req: envd_dot_process_dot_v1_dot_process__pb2.StartProcessRequest , **opts) -> Generator[envd_dot_process_dot_v1_dot_process__pb2.StartProcessResponse, Any, None]:
- return self._start_process.call_server_stream(req, **opts)
+ def start(self, req: envd_dot_process_dot_v1_dot_process__pb2.StartRequest , **opts) -> Generator[envd_dot_process_dot_v1_dot_process__pb2.StartResponse, Any, None]:
+ return self._start.call_server_stream(req, **opts)
- def update_process(self, req: envd_dot_process_dot_v1_dot_process__pb2.UpdateProcessRequest, **opts) -> envd_dot_process_dot_v1_dot_process__pb2.UpdateProcessResponse:
- return self._update_process.call_unary(req, **opts)
+ def update(self, req: envd_dot_process_dot_v1_dot_process__pb2.UpdateRequest, **opts) -> envd_dot_process_dot_v1_dot_process__pb2.UpdateResponse:
+ return self._update.call_unary(req, **opts)
- def send_process_input_stream(self, req: envd_dot_process_dot_v1_dot_process__pb2.SendProcessInputStreamRequest, **opts) -> envd_dot_process_dot_v1_dot_process__pb2.SendProcessInputStreamResponse:
- return self._send_process_input_stream.call_client_stream(req, **opts)
+ def stream_input(self, req: envd_dot_process_dot_v1_dot_process__pb2.StreamInputRequest, **opts) -> envd_dot_process_dot_v1_dot_process__pb2.StreamInputResponse:
+ return self._stream_input.call_client_stream(req, **opts)
- def send_process_input(self, req: envd_dot_process_dot_v1_dot_process__pb2.SendProcessInputRequest, **opts) -> envd_dot_process_dot_v1_dot_process__pb2.SendProcessInputResponse:
- return self._send_process_input.call_unary(req, **opts)
+ def send_input(self, req: envd_dot_process_dot_v1_dot_process__pb2.SendInputRequest, **opts) -> envd_dot_process_dot_v1_dot_process__pb2.SendInputResponse:
+ return self._send_input.call_unary(req, **opts)
- def send_process_signal(self, req: envd_dot_process_dot_v1_dot_process__pb2.SendProcessSignalRequest, **opts) -> envd_dot_process_dot_v1_dot_process__pb2.SendProcessSignalResponse:
- return self._send_process_signal.call_unary(req, **opts)
+ def send_signal(self, req: envd_dot_process_dot_v1_dot_process__pb2.SendSignalRequest, **opts) -> envd_dot_process_dot_v1_dot_process__pb2.SendSignalResponse:
+ return self._send_signal.call_unary(req, **opts)
diff --git a/packages/python-sdk/envd/process/v1/process_pb2.py b/packages/python-sdk/envd/process/v1/process_pb2.py
index 42e3fbb3d..e9631f037 100644
--- a/packages/python-sdk/envd/process/v1/process_pb2.py
+++ b/packages/python-sdk/envd/process/v1/process_pb2.py
@@ -12,10 +12,9 @@ from google.protobuf.internal import builder as _builder
_sym_db = _symbol_database.Default()
-from envd.permissions.v1 import permissions_pb2 as envd_dot_permissions_dot_v1_dot_permissions__pb2
-DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1d\x65nvd/process/v1/process.proto\x12\x0f\x65nvd.process.v1\x1a%envd/permissions/v1/permissions.proto\"d\n\x03PTY\x12-\n\x04size\x18\x01 \x01(\x0b\x32\x19.envd.process.v1.PTY.SizeR\x04size\x1a.\n\x04Size\x12\x12\n\x04\x63ols\x18\x01 \x01(\rR\x04\x63ols\x12\x12\n\x04rows\x18\x02 \x01(\rR\x04rows\"\xbe\x01\n\rProcessConfig\x12\x10\n\x03\x63md\x18\x01 \x01(\tR\x03\x63md\x12\x12\n\x04\x61rgs\x18\x02 \x03(\tR\x04\x61rgs\x12<\n\x04\x65nvs\x18\x03 \x03(\x0b\x32(.envd.process.v1.ProcessConfig.EnvsEntryR\x04\x65nvs\x12\x10\n\x03\x63wd\x18\x04 \x01(\tR\x03\x63wd\x1a\x37\n\tEnvsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x02\x38\x01\"\x16\n\x14ListProcessesRequest\"U\n\x15ListProcessesResponse\x12<\n\tprocesses\x18\x01 \x03(\x0b\x32\x1e.envd.process.v1.ProcessConfigR\tprocesses\"\xbc\x01\n\x13StartProcessRequest\x12\x38\n\x07process\x18\x01 \x01(\x0b\x32\x1e.envd.process.v1.ProcessConfigR\x07process\x12+\n\x03pty\x18\x02 \x01(\x0b\x32\x14.envd.process.v1.PTYH\x00R\x03pty\x88\x01\x01\x12\x36\n\x05owner\x18\x03 \x01(\x0b\x32 .envd.permissions.v1.CredentialsR\x05ownerB\x06\n\x04_pty\"\x87\x01\n\x14UpdateProcessRequest\x12:\n\x07process\x18\x01 \x01(\x0b\x32 .envd.process.v1.ProcessSelectorR\x07process\x12+\n\x03pty\x18\x02 \x01(\x0b\x32\x14.envd.process.v1.PTYH\x00R\x03pty\x88\x01\x01\x42\x06\n\x04_pty\"\x17\n\x15UpdateProcessResponse\"\xc6\x03\n\x0cProcessEvent\x12@\n\x05start\x18\x01 \x01(\x0b\x32(.envd.process.v1.ProcessEvent.StartEventH\x00R\x05start\x12=\n\x04\x64\x61ta\x18\x02 \x01(\x0b\x32\'.envd.process.v1.ProcessEvent.DataEventH\x00R\x04\x64\x61ta\x12:\n\x03\x65nd\x18\x03 \x01(\x0b\x32&.envd.process.v1.ProcessEvent.EndEventH\x00R\x03\x65nd\x1a\x1e\n\nStartEvent\x12\x10\n\x03pid\x18\x01 \x01(\rR\x03pid\x1aI\n\tDataEvent\x12\x18\n\x06stdout\x18\x01 \x01(\x0cH\x00R\x06stdout\x12\x18\n\x06stderr\x18\x02 \x01(\x0cH\x00R\x06stderrB\x08\n\x06output\x1a\x84\x01\n\x08\x45ndEvent\x12\x1b\n\texit_code\x18\x01 \x01(\x11R\x08\x65xitCode\x12\x1e\n\nterminated\x18\x02 \x01(\x08R\nterminated\x12\x16\n\x06status\x18\x03 \x01(\tR\x06status\x12\x19\n\x05\x65rror\x18\x04 \x01(\tH\x00R\x05\x65rror\x88\x01\x01\x42\x08\n\x06_errorB\x07\n\x05\x65vent\"K\n\x14StartProcessResponse\x12\x33\n\x05\x65vent\x18\x01 \x01(\x0b\x32\x1d.envd.process.v1.ProcessEventR\x05\x65vent\"O\n\x18ReconnectProcessResponse\x12\x33\n\x05\x65vent\x18\x01 \x01(\x0b\x32\x1d.envd.process.v1.ProcessEventR\x05\x65vent\"\x8a\x01\n\x17SendProcessInputRequest\x12:\n\x07process\x18\x01 \x01(\x0b\x32 .envd.process.v1.ProcessSelectorR\x07process\x12\x33\n\x05input\x18\x02 \x01(\x0b\x32\x1d.envd.process.v1.ProcessInputR\x05input\"\x1a\n\x18SendProcessInputResponse\"C\n\x0cProcessInput\x12\x16\n\x05stdin\x18\x01 \x01(\x0cH\x00R\x05stdin\x12\x12\n\x03tty\x18\x02 \x01(\x0cH\x00R\x03ttyB\x07\n\x05input\"\xd7\x02\n\x1dSendProcessInputStreamRequest\x12Q\n\x05start\x18\x01 \x01(\x0b\x32\x39.envd.process.v1.SendProcessInputStreamRequest.StartEventH\x00R\x05start\x12N\n\x04\x64\x61ta\x18\x02 \x01(\x0b\x32\x38.envd.process.v1.SendProcessInputStreamRequest.DataEventH\x00R\x04\x64\x61ta\x1aH\n\nStartEvent\x12:\n\x07process\x18\x01 \x01(\x0b\x32 .envd.process.v1.ProcessSelectorR\x07process\x1a@\n\tDataEvent\x12\x33\n\x05input\x18\x02 \x01(\x0b\x32\x1d.envd.process.v1.ProcessInputR\x05inputB\x07\n\x05\x65vent\" \n\x1eSendProcessInputStreamResponse\"\x87\x01\n\x18SendProcessSignalRequest\x12:\n\x07process\x18\x01 \x01(\x0b\x32 .envd.process.v1.ProcessSelectorR\x07process\x12/\n\x06signal\x18\x02 \x01(\x0e\x32\x17.envd.process.v1.SignalR\x06signal\"\x1b\n\x19SendProcessSignalResponse\"U\n\x17ReconnectProcessRequest\x12:\n\x07process\x18\x01 \x01(\x0b\x32 .envd.process.v1.ProcessSelectorR\x07process\"1\n\x0fProcessSelector\x12\x12\n\x03pid\x18\x01 \x01(\rH\x00R\x03pidB\n\n\x08selector*H\n\x06Signal\x12\x16\n\x12SIGNAL_UNSPECIFIED\x10\x00\x12\x12\n\x0eSIGNAL_SIGTERM\x10\x0f\x12\x12\n\x0eSIGNAL_SIGKILL\x10\t2\xec\x05\n\x0eProcessService\x12^\n\rListProcesses\x12%.envd.process.v1.ListProcessesRequest\x1a&.envd.process.v1.ListProcessesResponse\x12i\n\x10ReconnectProcess\x12(.envd.process.v1.ReconnectProcessRequest\x1a).envd.process.v1.ReconnectProcessResponse0\x01\x12]\n\x0cStartProcess\x12$.envd.process.v1.StartProcessRequest\x1a%.envd.process.v1.StartProcessResponse0\x01\x12^\n\rUpdateProcess\x12%.envd.process.v1.UpdateProcessRequest\x1a&.envd.process.v1.UpdateProcessResponse\x12{\n\x16SendProcessInputStream\x12..envd.process.v1.SendProcessInputStreamRequest\x1a/.envd.process.v1.SendProcessInputStreamResponse(\x01\x12g\n\x10SendProcessInput\x12(.envd.process.v1.SendProcessInputRequest\x1a).envd.process.v1.SendProcessInputResponse\x12j\n\x11SendProcessSignal\x12).envd.process.v1.SendProcessSignalRequest\x1a*.envd.process.v1.SendProcessSignalResponseB\x81\x01\n\x13\x63om.envd.process.v1B\x0cProcessProtoP\x01\xa2\x02\x03\x45PX\xaa\x02\x0f\x45nvd.Process.V1\xca\x02\x0f\x45nvd\\Process\\V1\xe2\x02\x1b\x45nvd\\Process\\V1\\GPBMetadata\xea\x02\x11\x45nvd::Process::V1b\x06proto3')
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1d\x65nvd/process/v1/process.proto\x12\x0f\x65nvd.process.v1\"d\n\x03PTY\x12-\n\x04size\x18\x01 \x01(\x0b\x32\x19.envd.process.v1.PTY.SizeR\x04size\x1a.\n\x04Size\x12\x12\n\x04\x63ols\x18\x01 \x01(\rR\x04\x63ols\x12\x12\n\x04rows\x18\x02 \x01(\rR\x04rows\"\xbe\x01\n\rProcessConfig\x12\x10\n\x03\x63md\x18\x01 \x01(\tR\x03\x63md\x12\x12\n\x04\x61rgs\x18\x02 \x03(\tR\x04\x61rgs\x12<\n\x04\x65nvs\x18\x03 \x03(\x0b\x32(.envd.process.v1.ProcessConfig.EnvsEntryR\x04\x65nvs\x12\x10\n\x03\x63wd\x18\x04 \x01(\tR\x03\x63wd\x1a\x37\n\tEnvsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x02\x38\x01\"\r\n\x0bListRequest\"L\n\x0cListResponse\x12<\n\tprocesses\x18\x01 \x03(\x0b\x32\x1e.envd.process.v1.ProcessConfigR\tprocesses\"8\n\nCredential\x12\x1c\n\x08username\x18\x01 \x01(\tH\x00R\x08usernameB\x0c\n\ncredential\"\xb0\x01\n\x0cStartRequest\x12\x38\n\x07process\x18\x01 \x01(\x0b\x32\x1e.envd.process.v1.ProcessConfigR\x07process\x12+\n\x03pty\x18\x02 \x01(\x0b\x32\x14.envd.process.v1.PTYH\x00R\x03pty\x88\x01\x01\x12\x31\n\x05owner\x18\x03 \x01(\x0b\x32\x1b.envd.process.v1.CredentialR\x05ownerB\x06\n\x04_pty\"\x80\x01\n\rUpdateRequest\x12:\n\x07process\x18\x01 \x01(\x0b\x32 .envd.process.v1.ProcessSelectorR\x07process\x12+\n\x03pty\x18\x02 \x01(\x0b\x32\x14.envd.process.v1.PTYH\x00R\x03pty\x88\x01\x01\x42\x06\n\x04_pty\"\x10\n\x0eUpdateResponse\"\xc6\x03\n\x0cProcessEvent\x12@\n\x05start\x18\x01 \x01(\x0b\x32(.envd.process.v1.ProcessEvent.StartEventH\x00R\x05start\x12=\n\x04\x64\x61ta\x18\x02 \x01(\x0b\x32\'.envd.process.v1.ProcessEvent.DataEventH\x00R\x04\x64\x61ta\x12:\n\x03\x65nd\x18\x03 \x01(\x0b\x32&.envd.process.v1.ProcessEvent.EndEventH\x00R\x03\x65nd\x1a\x1e\n\nStartEvent\x12\x10\n\x03pid\x18\x01 \x01(\rR\x03pid\x1aI\n\tDataEvent\x12\x18\n\x06stdout\x18\x01 \x01(\x0cH\x00R\x06stdout\x12\x18\n\x06stderr\x18\x02 \x01(\x0cH\x00R\x06stderrB\x08\n\x06output\x1a\x84\x01\n\x08\x45ndEvent\x12\x1b\n\texit_code\x18\x01 \x01(\x11R\x08\x65xitCode\x12\x1e\n\nterminated\x18\x02 \x01(\x08R\nterminated\x12\x16\n\x06status\x18\x03 \x01(\tR\x06status\x12\x19\n\x05\x65rror\x18\x04 \x01(\tH\x00R\x05\x65rror\x88\x01\x01\x42\x08\n\x06_errorB\x07\n\x05\x65vent\"D\n\rStartResponse\x12\x33\n\x05\x65vent\x18\x01 \x01(\x0b\x32\x1d.envd.process.v1.ProcessEventR\x05\x65vent\"F\n\x0f\x43onnectResponse\x12\x33\n\x05\x65vent\x18\x01 \x01(\x0b\x32\x1d.envd.process.v1.ProcessEventR\x05\x65vent\"\x83\x01\n\x10SendInputRequest\x12:\n\x07process\x18\x01 \x01(\x0b\x32 .envd.process.v1.ProcessSelectorR\x07process\x12\x33\n\x05input\x18\x02 \x01(\x0b\x32\x1d.envd.process.v1.ProcessInputR\x05input\"\x13\n\x11SendInputResponse\"C\n\x0cProcessInput\x12\x16\n\x05stdin\x18\x01 \x01(\x0cH\x00R\x05stdin\x12\x12\n\x03tty\x18\x02 \x01(\x0cH\x00R\x03ttyB\x07\n\x05input\"\xb6\x02\n\x12StreamInputRequest\x12\x46\n\x05start\x18\x01 \x01(\x0b\x32..envd.process.v1.StreamInputRequest.StartEventH\x00R\x05start\x12\x43\n\x04\x64\x61ta\x18\x02 \x01(\x0b\x32-.envd.process.v1.StreamInputRequest.DataEventH\x00R\x04\x64\x61ta\x1aH\n\nStartEvent\x12:\n\x07process\x18\x01 \x01(\x0b\x32 .envd.process.v1.ProcessSelectorR\x07process\x1a@\n\tDataEvent\x12\x33\n\x05input\x18\x02 \x01(\x0b\x32\x1d.envd.process.v1.ProcessInputR\x05inputB\x07\n\x05\x65vent\"\x15\n\x13StreamInputResponse\"\x80\x01\n\x11SendSignalRequest\x12:\n\x07process\x18\x01 \x01(\x0b\x32 .envd.process.v1.ProcessSelectorR\x07process\x12/\n\x06signal\x18\x02 \x01(\x0e\x32\x17.envd.process.v1.SignalR\x06signal\"\x14\n\x12SendSignalResponse\"L\n\x0e\x43onnectRequest\x12:\n\x07process\x18\x01 \x01(\x0b\x32 .envd.process.v1.ProcessSelectorR\x07process\"1\n\x0fProcessSelector\x12\x12\n\x03pid\x18\x01 \x01(\rH\x00R\x03pidB\n\n\x08selector*H\n\x06Signal\x12\x16\n\x12SIGNAL_UNSPECIFIED\x10\x00\x12\x12\n\x0eSIGNAL_SIGTERM\x10\x0f\x12\x12\n\x0eSIGNAL_SIGKILL\x10\t2\xc1\x04\n\x0eProcessService\x12\x43\n\x04List\x12\x1c.envd.process.v1.ListRequest\x1a\x1d.envd.process.v1.ListResponse\x12N\n\x07\x43onnect\x12\x1f.envd.process.v1.ConnectRequest\x1a .envd.process.v1.ConnectResponse0\x01\x12H\n\x05Start\x12\x1d.envd.process.v1.StartRequest\x1a\x1e.envd.process.v1.StartResponse0\x01\x12I\n\x06Update\x12\x1e.envd.process.v1.UpdateRequest\x1a\x1f.envd.process.v1.UpdateResponse\x12Z\n\x0bStreamInput\x12#.envd.process.v1.StreamInputRequest\x1a$.envd.process.v1.StreamInputResponse(\x01\x12R\n\tSendInput\x12!.envd.process.v1.SendInputRequest\x1a\".envd.process.v1.SendInputResponse\x12U\n\nSendSignal\x12\".envd.process.v1.SendSignalRequest\x1a#.envd.process.v1.SendSignalResponseB\x81\x01\n\x13\x63om.envd.process.v1B\x0cProcessProtoP\x01\xa2\x02\x03\x45PX\xaa\x02\x0f\x45nvd.Process.V1\xca\x02\x0f\x45nvd\\Process\\V1\xe2\x02\x1b\x45nvd\\Process\\V1\\GPBMetadata\xea\x02\x11\x45nvd::Process::V1b\x06proto3')
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
@@ -25,60 +24,62 @@ if not _descriptor._USE_C_DESCRIPTORS:
_globals['DESCRIPTOR']._serialized_options = b'\n\023com.envd.process.v1B\014ProcessProtoP\001\242\002\003EPX\252\002\017Envd.Process.V1\312\002\017Envd\\Process\\V1\342\002\033Envd\\Process\\V1\\GPBMetadata\352\002\021Envd::Process::V1'
_globals['_PROCESSCONFIG_ENVSENTRY']._loaded_options = None
_globals['_PROCESSCONFIG_ENVSENTRY']._serialized_options = b'8\001'
- _globals['_SIGNAL']._serialized_start=2387
- _globals['_SIGNAL']._serialized_end=2459
- _globals['_PTY']._serialized_start=89
- _globals['_PTY']._serialized_end=189
- _globals['_PTY_SIZE']._serialized_start=143
- _globals['_PTY_SIZE']._serialized_end=189
- _globals['_PROCESSCONFIG']._serialized_start=192
- _globals['_PROCESSCONFIG']._serialized_end=382
- _globals['_PROCESSCONFIG_ENVSENTRY']._serialized_start=327
- _globals['_PROCESSCONFIG_ENVSENTRY']._serialized_end=382
- _globals['_LISTPROCESSESREQUEST']._serialized_start=384
- _globals['_LISTPROCESSESREQUEST']._serialized_end=406
- _globals['_LISTPROCESSESRESPONSE']._serialized_start=408
- _globals['_LISTPROCESSESRESPONSE']._serialized_end=493
- _globals['_STARTPROCESSREQUEST']._serialized_start=496
- _globals['_STARTPROCESSREQUEST']._serialized_end=684
- _globals['_UPDATEPROCESSREQUEST']._serialized_start=687
- _globals['_UPDATEPROCESSREQUEST']._serialized_end=822
- _globals['_UPDATEPROCESSRESPONSE']._serialized_start=824
- _globals['_UPDATEPROCESSRESPONSE']._serialized_end=847
- _globals['_PROCESSEVENT']._serialized_start=850
- _globals['_PROCESSEVENT']._serialized_end=1304
- _globals['_PROCESSEVENT_STARTEVENT']._serialized_start=1055
- _globals['_PROCESSEVENT_STARTEVENT']._serialized_end=1085
- _globals['_PROCESSEVENT_DATAEVENT']._serialized_start=1087
- _globals['_PROCESSEVENT_DATAEVENT']._serialized_end=1160
- _globals['_PROCESSEVENT_ENDEVENT']._serialized_start=1163
- _globals['_PROCESSEVENT_ENDEVENT']._serialized_end=1295
- _globals['_STARTPROCESSRESPONSE']._serialized_start=1306
- _globals['_STARTPROCESSRESPONSE']._serialized_end=1381
- _globals['_RECONNECTPROCESSRESPONSE']._serialized_start=1383
- _globals['_RECONNECTPROCESSRESPONSE']._serialized_end=1462
- _globals['_SENDPROCESSINPUTREQUEST']._serialized_start=1465
- _globals['_SENDPROCESSINPUTREQUEST']._serialized_end=1603
- _globals['_SENDPROCESSINPUTRESPONSE']._serialized_start=1605
- _globals['_SENDPROCESSINPUTRESPONSE']._serialized_end=1631
- _globals['_PROCESSINPUT']._serialized_start=1633
- _globals['_PROCESSINPUT']._serialized_end=1700
- _globals['_SENDPROCESSINPUTSTREAMREQUEST']._serialized_start=1703
- _globals['_SENDPROCESSINPUTSTREAMREQUEST']._serialized_end=2046
- _globals['_SENDPROCESSINPUTSTREAMREQUEST_STARTEVENT']._serialized_start=1899
- _globals['_SENDPROCESSINPUTSTREAMREQUEST_STARTEVENT']._serialized_end=1971
- _globals['_SENDPROCESSINPUTSTREAMREQUEST_DATAEVENT']._serialized_start=1973
- _globals['_SENDPROCESSINPUTSTREAMREQUEST_DATAEVENT']._serialized_end=2037
- _globals['_SENDPROCESSINPUTSTREAMRESPONSE']._serialized_start=2048
- _globals['_SENDPROCESSINPUTSTREAMRESPONSE']._serialized_end=2080
- _globals['_SENDPROCESSSIGNALREQUEST']._serialized_start=2083
- _globals['_SENDPROCESSSIGNALREQUEST']._serialized_end=2218
- _globals['_SENDPROCESSSIGNALRESPONSE']._serialized_start=2220
- _globals['_SENDPROCESSSIGNALRESPONSE']._serialized_end=2247
- _globals['_RECONNECTPROCESSREQUEST']._serialized_start=2249
- _globals['_RECONNECTPROCESSREQUEST']._serialized_end=2334
- _globals['_PROCESSSELECTOR']._serialized_start=2336
- _globals['_PROCESSSELECTOR']._serialized_end=2385
- _globals['_PROCESSSERVICE']._serialized_start=2462
- _globals['_PROCESSSERVICE']._serialized_end=3210
+ _globals['_SIGNAL']._serialized_start=2265
+ _globals['_SIGNAL']._serialized_end=2337
+ _globals['_PTY']._serialized_start=50
+ _globals['_PTY']._serialized_end=150
+ _globals['_PTY_SIZE']._serialized_start=104
+ _globals['_PTY_SIZE']._serialized_end=150
+ _globals['_PROCESSCONFIG']._serialized_start=153
+ _globals['_PROCESSCONFIG']._serialized_end=343
+ _globals['_PROCESSCONFIG_ENVSENTRY']._serialized_start=288
+ _globals['_PROCESSCONFIG_ENVSENTRY']._serialized_end=343
+ _globals['_LISTREQUEST']._serialized_start=345
+ _globals['_LISTREQUEST']._serialized_end=358
+ _globals['_LISTRESPONSE']._serialized_start=360
+ _globals['_LISTRESPONSE']._serialized_end=436
+ _globals['_CREDENTIAL']._serialized_start=438
+ _globals['_CREDENTIAL']._serialized_end=494
+ _globals['_STARTREQUEST']._serialized_start=497
+ _globals['_STARTREQUEST']._serialized_end=673
+ _globals['_UPDATEREQUEST']._serialized_start=676
+ _globals['_UPDATEREQUEST']._serialized_end=804
+ _globals['_UPDATERESPONSE']._serialized_start=806
+ _globals['_UPDATERESPONSE']._serialized_end=822
+ _globals['_PROCESSEVENT']._serialized_start=825
+ _globals['_PROCESSEVENT']._serialized_end=1279
+ _globals['_PROCESSEVENT_STARTEVENT']._serialized_start=1030
+ _globals['_PROCESSEVENT_STARTEVENT']._serialized_end=1060
+ _globals['_PROCESSEVENT_DATAEVENT']._serialized_start=1062
+ _globals['_PROCESSEVENT_DATAEVENT']._serialized_end=1135
+ _globals['_PROCESSEVENT_ENDEVENT']._serialized_start=1138
+ _globals['_PROCESSEVENT_ENDEVENT']._serialized_end=1270
+ _globals['_STARTRESPONSE']._serialized_start=1281
+ _globals['_STARTRESPONSE']._serialized_end=1349
+ _globals['_CONNECTRESPONSE']._serialized_start=1351
+ _globals['_CONNECTRESPONSE']._serialized_end=1421
+ _globals['_SENDINPUTREQUEST']._serialized_start=1424
+ _globals['_SENDINPUTREQUEST']._serialized_end=1555
+ _globals['_SENDINPUTRESPONSE']._serialized_start=1557
+ _globals['_SENDINPUTRESPONSE']._serialized_end=1576
+ _globals['_PROCESSINPUT']._serialized_start=1578
+ _globals['_PROCESSINPUT']._serialized_end=1645
+ _globals['_STREAMINPUTREQUEST']._serialized_start=1648
+ _globals['_STREAMINPUTREQUEST']._serialized_end=1958
+ _globals['_STREAMINPUTREQUEST_STARTEVENT']._serialized_start=1811
+ _globals['_STREAMINPUTREQUEST_STARTEVENT']._serialized_end=1883
+ _globals['_STREAMINPUTREQUEST_DATAEVENT']._serialized_start=1885
+ _globals['_STREAMINPUTREQUEST_DATAEVENT']._serialized_end=1949
+ _globals['_STREAMINPUTRESPONSE']._serialized_start=1960
+ _globals['_STREAMINPUTRESPONSE']._serialized_end=1981
+ _globals['_SENDSIGNALREQUEST']._serialized_start=1984
+ _globals['_SENDSIGNALREQUEST']._serialized_end=2112
+ _globals['_SENDSIGNALRESPONSE']._serialized_start=2114
+ _globals['_SENDSIGNALRESPONSE']._serialized_end=2134
+ _globals['_CONNECTREQUEST']._serialized_start=2136
+ _globals['_CONNECTREQUEST']._serialized_end=2212
+ _globals['_PROCESSSELECTOR']._serialized_start=2214
+ _globals['_PROCESSSELECTOR']._serialized_end=2263
+ _globals['_PROCESSSERVICE']._serialized_start=2340
+ _globals['_PROCESSSERVICE']._serialized_end=2917
# @@protoc_insertion_point(module_scope)
diff --git a/packages/python-sdk/envd/process/v1/process_pb2.pyi b/packages/python-sdk/envd/process/v1/process_pb2.pyi
index 12139bba1..63f05f848 100644
--- a/packages/python-sdk/envd/process/v1/process_pb2.pyi
+++ b/packages/python-sdk/envd/process/v1/process_pb2.pyi
@@ -1,4 +1,3 @@
-from envd.permissions.v1 import permissions_pb2 as _permissions_pb2
from google.protobuf.internal import containers as _containers
from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
from google.protobuf import descriptor as _descriptor
@@ -48,27 +47,33 @@ class ProcessConfig(_message.Message):
cwd: str
def __init__(self, cmd: _Optional[str] = ..., args: _Optional[_Iterable[str]] = ..., envs: _Optional[_Mapping[str, str]] = ..., cwd: _Optional[str] = ...) -> None: ...
-class ListProcessesRequest(_message.Message):
+class ListRequest(_message.Message):
__slots__ = ()
def __init__(self) -> None: ...
-class ListProcessesResponse(_message.Message):
+class ListResponse(_message.Message):
__slots__ = ("processes",)
PROCESSES_FIELD_NUMBER: _ClassVar[int]
processes: _containers.RepeatedCompositeFieldContainer[ProcessConfig]
def __init__(self, processes: _Optional[_Iterable[_Union[ProcessConfig, _Mapping]]] = ...) -> None: ...
-class StartProcessRequest(_message.Message):
+class Credential(_message.Message):
+ __slots__ = ("username",)
+ USERNAME_FIELD_NUMBER: _ClassVar[int]
+ username: str
+ def __init__(self, username: _Optional[str] = ...) -> None: ...
+
+class StartRequest(_message.Message):
__slots__ = ("process", "pty", "owner")
PROCESS_FIELD_NUMBER: _ClassVar[int]
PTY_FIELD_NUMBER: _ClassVar[int]
OWNER_FIELD_NUMBER: _ClassVar[int]
process: ProcessConfig
pty: PTY
- owner: _permissions_pb2.Credentials
- def __init__(self, process: _Optional[_Union[ProcessConfig, _Mapping]] = ..., pty: _Optional[_Union[PTY, _Mapping]] = ..., owner: _Optional[_Union[_permissions_pb2.Credentials, _Mapping]] = ...) -> None: ...
+ owner: Credential
+ def __init__(self, process: _Optional[_Union[ProcessConfig, _Mapping]] = ..., pty: _Optional[_Union[PTY, _Mapping]] = ..., owner: _Optional[_Union[Credential, _Mapping]] = ...) -> None: ...
-class UpdateProcessRequest(_message.Message):
+class UpdateRequest(_message.Message):
__slots__ = ("process", "pty")
PROCESS_FIELD_NUMBER: _ClassVar[int]
PTY_FIELD_NUMBER: _ClassVar[int]
@@ -76,7 +81,7 @@ class UpdateProcessRequest(_message.Message):
pty: PTY
def __init__(self, process: _Optional[_Union[ProcessSelector, _Mapping]] = ..., pty: _Optional[_Union[PTY, _Mapping]] = ...) -> None: ...
-class UpdateProcessResponse(_message.Message):
+class UpdateResponse(_message.Message):
__slots__ = ()
def __init__(self) -> None: ...
@@ -113,19 +118,19 @@ class ProcessEvent(_message.Message):
end: ProcessEvent.EndEvent
def __init__(self, start: _Optional[_Union[ProcessEvent.StartEvent, _Mapping]] = ..., data: _Optional[_Union[ProcessEvent.DataEvent, _Mapping]] = ..., end: _Optional[_Union[ProcessEvent.EndEvent, _Mapping]] = ...) -> None: ...
-class StartProcessResponse(_message.Message):
+class StartResponse(_message.Message):
__slots__ = ("event",)
EVENT_FIELD_NUMBER: _ClassVar[int]
event: ProcessEvent
def __init__(self, event: _Optional[_Union[ProcessEvent, _Mapping]] = ...) -> None: ...
-class ReconnectProcessResponse(_message.Message):
+class ConnectResponse(_message.Message):
__slots__ = ("event",)
EVENT_FIELD_NUMBER: _ClassVar[int]
event: ProcessEvent
def __init__(self, event: _Optional[_Union[ProcessEvent, _Mapping]] = ...) -> None: ...
-class SendProcessInputRequest(_message.Message):
+class SendInputRequest(_message.Message):
__slots__ = ("process", "input")
PROCESS_FIELD_NUMBER: _ClassVar[int]
INPUT_FIELD_NUMBER: _ClassVar[int]
@@ -133,7 +138,7 @@ class SendProcessInputRequest(_message.Message):
input: ProcessInput
def __init__(self, process: _Optional[_Union[ProcessSelector, _Mapping]] = ..., input: _Optional[_Union[ProcessInput, _Mapping]] = ...) -> None: ...
-class SendProcessInputResponse(_message.Message):
+class SendInputResponse(_message.Message):
__slots__ = ()
def __init__(self) -> None: ...
@@ -145,7 +150,7 @@ class ProcessInput(_message.Message):
tty: bytes
def __init__(self, stdin: _Optional[bytes] = ..., tty: _Optional[bytes] = ...) -> None: ...
-class SendProcessInputStreamRequest(_message.Message):
+class StreamInputRequest(_message.Message):
__slots__ = ("start", "data")
class StartEvent(_message.Message):
__slots__ = ("process",)
@@ -159,15 +164,15 @@ class SendProcessInputStreamRequest(_message.Message):
def __init__(self, input: _Optional[_Union[ProcessInput, _Mapping]] = ...) -> None: ...
START_FIELD_NUMBER: _ClassVar[int]
DATA_FIELD_NUMBER: _ClassVar[int]
- start: SendProcessInputStreamRequest.StartEvent
- data: SendProcessInputStreamRequest.DataEvent
- def __init__(self, start: _Optional[_Union[SendProcessInputStreamRequest.StartEvent, _Mapping]] = ..., data: _Optional[_Union[SendProcessInputStreamRequest.DataEvent, _Mapping]] = ...) -> None: ...
+ start: StreamInputRequest.StartEvent
+ data: StreamInputRequest.DataEvent
+ def __init__(self, start: _Optional[_Union[StreamInputRequest.StartEvent, _Mapping]] = ..., data: _Optional[_Union[StreamInputRequest.DataEvent, _Mapping]] = ...) -> None: ...
-class SendProcessInputStreamResponse(_message.Message):
+class StreamInputResponse(_message.Message):
__slots__ = ()
def __init__(self) -> None: ...
-class SendProcessSignalRequest(_message.Message):
+class SendSignalRequest(_message.Message):
__slots__ = ("process", "signal")
PROCESS_FIELD_NUMBER: _ClassVar[int]
SIGNAL_FIELD_NUMBER: _ClassVar[int]
@@ -175,11 +180,11 @@ class SendProcessSignalRequest(_message.Message):
signal: Signal
def __init__(self, process: _Optional[_Union[ProcessSelector, _Mapping]] = ..., signal: _Optional[_Union[Signal, str]] = ...) -> None: ...
-class SendProcessSignalResponse(_message.Message):
+class SendSignalResponse(_message.Message):
__slots__ = ()
def __init__(self) -> None: ...
-class ReconnectProcessRequest(_message.Message):
+class ConnectRequest(_message.Message):
__slots__ = ("process",)
PROCESS_FIELD_NUMBER: _ClassVar[int]
process: ProcessSelector
diff --git a/packages/python-sdk/tests/test_timeout.py b/packages/python-sdk/tests/test_timeout.py
index 202c690b2..2ff79ce84 100644
--- a/packages/python-sdk/tests/test_timeout.py
+++ b/packages/python-sdk/tests/test_timeout.py
@@ -3,7 +3,7 @@ from typing import Optional
import pytest
from e2b import Sandbox
-from e2b.sandbox.exception import TimeoutException
+from e2b.sandbox.exceptions import TimeoutException
def test_create_sandbox_timeout():
diff --git a/spec/envd/envd.yaml b/spec/envd/envd.yaml
index 04c69f9da..8b3960f68 100644
--- a/spec/envd/envd.yaml
+++ b/spec/envd/envd.yaml
@@ -4,9 +4,6 @@ info:
version: 0.1.0
description: API for managing files' content and controlling envd
-servers:
- - url: /v1
-
paths:
/host/sync:
post:
@@ -17,16 +14,7 @@ paths:
500:
$ref: "#/components/responses/InternalServerError"
- /health:
- get:
- summary: Check the health of the envd
- responses:
- 204:
- description: The envd is healthy
- 500:
- $ref: "#/components/responses/InternalServerError"
-
- /filesystem/files/{path}:
+ /files/{path}:
get:
summary: Download a file
parameters:
@@ -36,13 +24,14 @@ paths:
$ref: "#/components/responses/DownloadSuccess"
400:
$ref: "#/components/responses/DirectoryPathError"
+ 500:
+ $ref: "#/components/responses/InternalServerError"
put:
- summary: Upload a file
+ summary: Upload a file and ensure the parent directories exist. If the file exists, it will be overwritten.
parameters:
- $ref: "#/components/parameters/FilePath"
- $ref: "#/components/parameters/User"
- $ref: "#/components/parameters/Mode"
- - $ref: "#/components/parameters/Overwrite"
requestBody:
$ref: "#/components/requestBodies/File"
responses:
@@ -50,10 +39,10 @@ paths:
$ref: "#/components/responses/ExistingFileUploadSuccess"
201:
$ref: "#/components/responses/NewFileUploadSuccess"
- 409:
- $ref: "#/components/responses/ConflictError"
400:
$ref: "#/components/responses/DirectoryPathError"
+ 500:
+ $ref: "#/components/responses/InternalServerError"
components:
parameters:
@@ -82,14 +71,6 @@ components:
type: string
pattern: "^[0-7]{3,4}$"
default: "0777"
- Overwrite:
- name: overwrite
- in: query
- required: false
- description: Overwrite the file if it exists
- schema:
- type: boolean
- default: true
requestBodies:
File:
@@ -137,13 +118,7 @@ components:
format: binary
description: The file content
DirectoryPathError:
- description: Bad Request - The specified path is a directory. Only files can be downloaded.
- content:
- application/json:
- schema:
- $ref: "#/components/schemas/Error"
- ConflictError:
- description: Conflict - The file already exists and overwrite is false.
+ description: Bad Request - The specified path is a directory.
content:
application/json:
schema:
diff --git a/spec/envd/filesystem/v1/filesystem.proto b/spec/envd/filesystem/v1/filesystem.proto
index becb441f3..a108b8534 100644
--- a/spec/envd/filesystem/v1/filesystem.proto
+++ b/spec/envd/filesystem/v1/filesystem.proto
@@ -1,42 +1,19 @@
syntax = "proto3";
-import "google/protobuf/timestamp.proto";
-
-import "envd/permissions/v1/permissions.proto";
-
package envd.filesystem.v1;
service FilesystemService {
rpc Stat(StatRequest) returns (StatResponse);
-
- rpc CreateDir(CreateDirRequest) returns (CreateDirResponse);
- rpc ListDir(ListDirRequest) returns (ListDirResponse);
-
+ rpc List(ListRequest) returns (ListResponse);
rpc Watch(WatchRequest) returns (stream WatchResponse);
- rpc Rename(RenameRequest) returns (RenameResponse);
rpc Remove(RemoveRequest) returns (RemoveResponse);
-
- rpc Copy(CopyRequest) returns (CopyResponse);
}
-message CreateDirRequest {
+message RemoveRequest {
string path = 1;
-
- string mode = 3;
-
- envd.permissions.v1.Credentials owner = 4;
}
-message CreateDirResponse {}
-
-message CopyRequest {
- string source = 1;
- string destination = 2;
-
- string mode = 3;
-}
-
-message CopyResponse {}
+message RemoveResponse {}
message StatRequest {
string path = 1;
@@ -46,21 +23,6 @@ message StatResponse {
EntryInfo entry = 1;
}
-message RemoveRequest {
- string path = 1;
-
- bool recursive = 2;
-}
-
-message RemoveResponse {}
-
-message RenameRequest {
- string source = 1;
- string destination = 2;
-}
-
-message RenameResponse {}
-
message EntryInfo {
string name = 1;
FileType type = 2;
@@ -72,11 +34,11 @@ enum FileType {
FILE_TYPE_DIRECTORY = 2;
}
-message ListDirRequest {
+message ListRequest {
string path = 1;
}
-message ListDirResponse {
+message ListResponse {
repeated EntryInfo entries = 1;
}
diff --git a/spec/envd/permissions/v1/permissions.proto b/spec/envd/permissions/v1/permissions.proto
deleted file mode 100644
index aa7580153..000000000
--- a/spec/envd/permissions/v1/permissions.proto
+++ /dev/null
@@ -1,9 +0,0 @@
-syntax = "proto3";
-
-package envd.permissions.v1;
-
-message Credentials {
- oneof credentials {
- string username = 1;
- }
-}
diff --git a/spec/envd/process/v1/process.proto b/spec/envd/process/v1/process.proto
index c8128a9f0..cdf7b47db 100644
--- a/spec/envd/process/v1/process.proto
+++ b/spec/envd/process/v1/process.proto
@@ -1,21 +1,19 @@
syntax = "proto3";
-import "envd/permissions/v1/permissions.proto";
-
package envd.process.v1;
service ProcessService {
- rpc ListProcesses(ListProcessesRequest) returns (ListProcessesResponse);
+ rpc List(ListRequest) returns (ListResponse);
- rpc ReconnectProcess(ReconnectProcessRequest) returns (stream ReconnectProcessResponse);
- rpc StartProcess(StartProcessRequest) returns (stream StartProcessResponse);
+ rpc Connect(ConnectRequest) returns (stream ConnectResponse);
+ rpc Start(StartRequest) returns (stream StartResponse);
- rpc UpdateProcess(UpdateProcessRequest) returns (UpdateProcessResponse);
+ rpc Update(UpdateRequest) returns (UpdateResponse);
// Client input stream ensures ordering of messages
- rpc SendProcessInputStream(stream SendProcessInputStreamRequest) returns (SendProcessInputStreamResponse);
- rpc SendProcessInput(SendProcessInputRequest) returns (SendProcessInputResponse);
- rpc SendProcessSignal(SendProcessSignalRequest) returns (SendProcessSignalResponse);
+ rpc StreamInput(stream StreamInputRequest) returns (StreamInputResponse);
+ rpc SendInput(SendInputRequest) returns (SendInputResponse);
+ rpc SendSignal(SendSignalRequest) returns (SendSignalResponse);
}
message PTY {
@@ -35,26 +33,32 @@ message ProcessConfig {
string cwd = 4;
}
-message ListProcessesRequest {}
+message ListRequest {}
-message ListProcessesResponse {
+message ListResponse {
repeated ProcessConfig processes = 1;
}
-message StartProcessRequest {
+message Credential {
+ oneof credential {
+ string username = 1;
+ }
+}
+
+message StartRequest {
ProcessConfig process = 1;
optional PTY pty = 2;
- envd.permissions.v1.Credentials owner = 3;
+ Credential owner = 3;
}
-message UpdateProcessRequest {
+message UpdateRequest {
ProcessSelector process = 1;
optional PTY pty = 2;
}
-message UpdateProcessResponse {}
+message UpdateResponse {}
message ProcessEvent {
oneof event {
@@ -82,21 +86,21 @@ message ProcessEvent {
}
}
-message StartProcessResponse {
+message StartResponse {
ProcessEvent event = 1;
}
-message ReconnectProcessResponse {
+message ConnectResponse {
ProcessEvent event = 1;
}
-message SendProcessInputRequest {
+message SendInputRequest {
ProcessSelector process = 1;
ProcessInput input = 2;
}
-message SendProcessInputResponse {}
+message SendInputResponse {}
message ProcessInput {
oneof input {
@@ -105,7 +109,7 @@ message ProcessInput {
}
}
-message SendProcessInputStreamRequest {
+message StreamInputRequest {
oneof event {
StartEvent start = 1;
DataEvent data = 2;
@@ -120,7 +124,7 @@ message SendProcessInputStreamRequest {
}
}
-message SendProcessInputStreamResponse {}
+message StreamInputResponse {}
enum Signal {
SIGNAL_UNSPECIFIED = 0;
@@ -128,15 +132,15 @@ enum Signal {
SIGNAL_SIGKILL = 9;
}
-message SendProcessSignalRequest {
+message SendSignalRequest {
ProcessSelector process = 1;
Signal signal = 2;
}
-message SendProcessSignalResponse {}
+message SendSignalResponse {}
-message ReconnectProcessRequest {
+message ConnectRequest {
ProcessSelector process = 1;
}
diff --git a/spec/openapi.yml b/spec/openapi.yml
index d995aecb1..7bd0370ee 100644
--- a/spec/openapi.yml
+++ b/spec/openapi.yml
@@ -170,6 +170,7 @@ components:
type: integer
format: int32
minimum: 0
+ default: 15
description: Time to live for the sandbox in seconds.
metadata:
$ref: "#/components/schemas/SandboxMetadata"
@@ -382,14 +383,15 @@ paths:
- ApiKeyAuth: []
tags: [sandboxes]
requestBody:
- required: false
content:
application/json:
schema:
type: object
+ required:
+ - timeout
properties:
- duration:
- description: Duration in seconds from the current time after which the sandbox should expire
+ timeout:
+ description: Timeout in seconds from the current time after which the sandbox should expire
type: integer
format: int32
minimum: 0