Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Fix naming for listing running sandboxes and add section to docs

Jakub Novak1e1bd00b9c0a
diff --git a/apps/docs/src/app/sandbox/api/metadata/page.mdx b/apps/docs/src/app/sandbox/api/metadata/page.mdx
new file mode 100644
index 000000000..f23a3c2cb
--- /dev/null
+++ b/apps/docs/src/app/sandbox/api/metadata/page.mdx
@@ -0,0 +1,8 @@
+## Sandbox metadata
+
+You can assign metadata to your sandbox. This metadata will be available if you call `Sandbox.list()`. This can be useful in situation where each of your users have dedicated sandbox and the time between the steps of the integration is long. You can use the metadata to store the user id and reconnect to it later.
+
+<CodeGroupAutoload
+ path="basics/metadata"
+ isRunnable={true}
+/>
diff --git a/apps/docs/src/app/sandbox/api/reconnect/page.mdx b/apps/docs/src/app/sandbox/api/reconnect/page.mdx
index a271438c7..6aed66c26 100644
--- a/apps/docs/src/app/sandbox/api/reconnect/page.mdx
+++ b/apps/docs/src/app/sandbox/api/reconnect/page.mdx
@@ -37,3 +37,6 @@ You can then reconnect to the sandbox from anywhere.
isRunnable={false}
/>
+
+## Use sandbox metadata
+Sandbox metadata can be very useful to store information about the sandbox. You can use it to store the user ID or any other information you need to keep track of and then use this info for reconnecting to the sandbox. You can read more about sandbox metadata [here](/sandbox/api/metadata).
\ No newline at end of file
diff --git a/apps/docs/src/code/js/basics/metadata.js b/apps/docs/src/code/js/basics/metadata.js
new file mode 100644
index 000000000..7f0a73265
--- /dev/null
+++ b/apps/docs/src/code/js/basics/metadata.js
@@ -0,0 +1,23 @@
+import { Sandbox } from '@e2b/sdk'
+
+const sandbox = await Sandbox.create({
+ template: 'base',
+ metadata: { userID: 'uniqueID' } // $HighlightLine
+})
+// Keep the sandbox alive for 60 seconds
+await sandbox.keepAlive(60_000)
+// You can even close the script
+
+// Later, can be even from another process
+// List all running sandboxes
+const runningSandboxes = await Sandbox.list()
+// Find the sandbox by metadata
+const found = runningSandboxes.find(s => s.metadata?.userID === 'uniqueID')
+if (found) {
+ // Sandbox found, we can reconnect to it
+ const sandbox = await Sandbox.reconnect(found.sandboxID)
+} else {
+ // Sandbox not found
+}
+
+await sandbox.close()
diff --git a/apps/docs/src/code/python/basics/metadata.py b/apps/docs/src/code/python/basics/metadata.py
new file mode 100644
index 000000000..781c318d4
--- /dev/null
+++ b/apps/docs/src/code/python/basics/metadata.py
@@ -0,0 +1,24 @@
+from e2b import Sandbox
+
+sandbox = Sandbox.create(
+ template='base',
+ metadata={"user_id": "uniqueID"}, # $HighlightLine
+)
+
+# Keep the sandbox alive for 60 seconds
+sandbox.keep_alive(60)
+# You can even close the script
+
+# Later, can be even from another process
+# List all running sandboxes
+running_sandboxes = Sandbox.list()
+
+# Find the sandbox by metadata
+for running_sandbox in running_sandboxes:
+ if running_sandbox.metadata.get("user_id", "") == 'uniqueID':
+ sandbox = Sandbox.reconnect(running_sandbox.sandbox_id)
+else:
+ pass
+ # Sandbox not found
+
+sandbox.close()
diff --git a/apps/docs/src/components/Navigation/routes.tsx b/apps/docs/src/components/Navigation/routes.tsx
index 74e6e09e2..a078d77fb 100644
--- a/apps/docs/src/components/Navigation/routes.tsx
+++ b/apps/docs/src/components/Navigation/routes.tsx
@@ -1,9 +1,11 @@
import {
Boxes,
+ Braces,
ChevronRightSquare,
Cpu,
DollarSign,
FileDown,
+ File,
FileUp,
Folder,
FolderTree,
@@ -11,12 +13,14 @@ import {
HeartHandshake,
KeyRound,
Link,
+ PencilRuler,
+ PlaySquare,
+ RefreshCw,
Settings,
ShieldQuestion,
+ TerminalSquare,
Timer,
Variable,
- PencilRuler,
- File, TerminalSquare, RefreshCw, PlaySquare,
} from 'lucide-react'
import logoOpenAI from '@/images/logos/openai.svg'
@@ -297,6 +301,16 @@ export const routes = [
title: 'Connect to running sandbox',
href: '/sandbox/api/reconnect',
},
+ {
+ icon: (
+ <Braces
+ strokeWidth={1}
+ size={20}
+ />
+ ),
+ title: 'Sandbox metadata',
+ href: '/sandbox/api/metadata',
+ },
],
},
{
diff --git a/packages/js-sdk/src/sandbox/sandboxConnection.ts b/packages/js-sdk/src/sandbox/sandboxConnection.ts
index 834419671..e864ce351 100644
--- a/packages/js-sdk/src/sandbox/sandboxConnection.ts
+++ b/packages/js-sdk/src/sandbox/sandboxConnection.ts
@@ -37,6 +37,12 @@ export interface SandboxMetadata {
[key: string]: string;
}
+export interface RunningInstance {
+ sandboxID: string;
+ templateID: string;
+ metadata?: SandboxMetadata;
+}
+
export interface SandboxConnectionOpts {
/**
* Sandbox Template ID or name.
@@ -137,11 +143,11 @@ export class SandboxConnection {
* List all running sandboxes
* @param apiKey API key to use for authentication. If not provided, the `E2B_API_KEY` environment variable will be used.
*/
- static async list(apiKey?: string) {
+ static async list(apiKey?: string): Promise<RunningInstance[]> {
apiKey = getApiKey(apiKey)
try {
const res = await listSandboxes(apiKey, {})
- return res.data
+ return res.data.map((instance) => ({ sandboxID: instance.instanceID, templateID: instance.envID, metadata: instance.metadata }))
} catch (e) {
if (e instanceof listSandboxes.Error) {
const error = e.getActualType()
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_connection.py b/packages/python-sdk/e2b/sandbox/sandbox_connection.py
index 9c2c679e8..bafd984e9 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_connection.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_connection.py
@@ -48,6 +48,12 @@ class SubscriptionArgs(BaseModel):
params: List[Any] = []
+class RunningSandboxes(BaseModel):
+ sandbox_id: str
+ template_id: str
+ metadata: Dict[str, str]
+
+
class SandboxConnection:
_refresh_retries = 4
_on_close_child: Optional[Callable[[], Any]] = None
@@ -453,7 +459,7 @@ class SandboxConnection:
self._close()
@staticmethod
- def list(api_key: Optional[str] = None) -> List[models.RunningInstance]:
+ def list(api_key: Optional[str] = None) -> List[RunningSandboxes]:
"""
List all running sandboxes.
@@ -461,4 +467,13 @@ class SandboxConnection:
"""
api_key = get_api_key(api_key)
with E2BApiClient(api_key=api_key) as api_client:
- return client.InstancesApi(api_client).instances_get()
+ running_sandboxes = client.InstancesApi(api_client).instances_get()
+
+ return [
+ RunningSandboxes(
+ sandbox_id=s.instance_id,
+ template_id=s.env_id,
+ metadata=s.metadata or {},
+ )
+ for s in running_sandboxes
+ ]
diff --git a/packages/python-sdk/tests/test_list_sandboxes.py b/packages/python-sdk/tests/test_list_sandboxes.py
index fce0a1915..ac0e802dc 100644
--- a/packages/python-sdk/tests/test_list_sandboxes.py
+++ b/packages/python-sdk/tests/test_list_sandboxes.py
@@ -8,12 +8,16 @@ def test_list_running_sandboxes():
running_sandboxes = list(
filter(
- lambda s: s.metadata and s.metadata.get("n", "").startswith("py"),
+ lambda s: s.metadata.get("n", "").startswith("py"),
Sandbox.list(),
)
)
assert len(running_sandboxes) == 3
- assert set(map(lambda x: x.metadata["n"], running_sandboxes)) == {"py0", "py1", "py2"}
+ assert set(map(lambda x: x.metadata["n"], running_sandboxes)) == {
+ "py0",
+ "py1",
+ "py2",
+ }
for sandbox in sandboxes:
sandbox.close()