Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Handle relative paths in filesystem (#168)

Jakub Novák90eb9e861c03
diff --git a/.changeset/smart-berries-relate.md b/.changeset/smart-berries-relate.md
new file mode 100644
index 000000000..477c0da2d
--- /dev/null
+++ b/.changeset/smart-berries-relate.md
@@ -0,0 +1,6 @@
+---
+'@e2b/python-sdk': minor
+'@e2b/sdk': minor
+---
+
+- Relative paths handling
diff --git a/apps/docs/src/app/playgrounds/cwd/page.mdx b/apps/docs/src/app/playgrounds/cwd/page.mdx
new file mode 100644
index 000000000..d03a804ee
--- /dev/null
+++ b/apps/docs/src/app/playgrounds/cwd/page.mdx
@@ -0,0 +1,29 @@
+export const metadata = {
+ title: 'E2B Documentation - Cloud for AI Agents Apps',
+ description: 'AI Playgrounds Working Directory',
+}
+
+export const sections = [
+ { title: 'Filesystem', id: 'filesystem' },
+ { title: 'Process', id: 'process' },
+]
+
+# Current Working Directory
+
+### Current working directory for whole session
+
+You can set working directory either for session. If not set, it will default to home directory - `/home/user`.
+
+<CodeGroupAutoload path="cwd/session" />
+
+### Current Working Directory Filesystem
+
+All filesystem operations are relative to current working directory.
+
+<CodeGroupAutoload path="cwd/filesystem"/>
+
+### Process
+
+If you set working directory for session, all processes will inherit it. You can override it for each process.
+
+<CodeGroupAutoload path="cwd/process"/>
diff --git a/apps/docs/src/code/js/cwd/filesystem.js b/apps/docs/src/code/js/cwd/filesystem.js
new file mode 100644
index 000000000..51f361e66
--- /dev/null
+++ b/apps/docs/src/code/js/cwd/filesystem.js
@@ -0,0 +1,22 @@
+import { Session } from '@e2b/sdk'
+
+const session = await Session.create({
+ id: 'Nodejs',
+ apiKey: process.env.E2B_API_KEY,
+ cwd: '/home/user/code', // $HighlightLine
+})
+
+await session.filesystem.write('hello.txt', 'Welcome to E2B!') // $HighlightLine
+const proc = await session.process.start({ cmd: 'cat /home/user/code/hello.txt' })
+await proc.finished
+const out = proc.output.stdout
+console.log(out)
+// output: "Welcome to E2B!"
+
+await session.filesystem.write('../hello.txt', 'We hope you have a great day!') // $HighlightLine
+const proc2 = await session.process.start({ cmd: 'cat /home/user/hello.txt' })
+await proc2.finished
+console.log(proc2.output.stdout)
+// output: "We hope you have a great day!"
+
+await session.close()
diff --git a/apps/docs/src/code/js/cwd/process.js b/apps/docs/src/code/js/cwd/process.js
new file mode 100644
index 000000000..ec21d6bcc
--- /dev/null
+++ b/apps/docs/src/code/js/cwd/process.js
@@ -0,0 +1,19 @@
+import { Session } from '@e2b/sdk'
+
+const session = await Session.create({
+ id: 'Nodejs',
+ apiKey: process.env.E2B_API_KEY,
+ cwd: '/code', // $HighlightLine
+})
+
+const sessionCwd = await session.process.start({ cmd: 'pwd' }) // $HighlightLine
+await sessionCwd.finished
+console.log(sessionCwd.output.stdout)
+// output: /code
+
+const processCwd = await session.process.start({ cmd: 'pwd', cwd: '/home' }) // $HighlightLine
+await processCwd.finished
+console.log(processCwd.output.stdout)
+// output: /home
+
+await session.close()
diff --git a/apps/docs/src/code/js/cwd/session.js b/apps/docs/src/code/js/cwd/session.js
new file mode 100644
index 000000000..ca0628322
--- /dev/null
+++ b/apps/docs/src/code/js/cwd/session.js
@@ -0,0 +1,12 @@
+import { Session } from '@e2b/sdk'
+
+const session = await Session.create({
+ id: 'Nodejs',
+ apiKey: process.env.E2B_API_KEY,
+ cwd: '/code', // $HighlightLine
+})
+
+// You can also change the cwd of an existing session
+session.cwd = '/home' // $HighlightLine
+
+await session.close()
diff --git a/apps/docs/src/code/python/cwd/filesystem.py b/apps/docs/src/code/python/cwd/filesystem.py
new file mode 100644
index 000000000..9e087fd4f
--- /dev/null
+++ b/apps/docs/src/code/python/cwd/filesystem.py
@@ -0,0 +1,27 @@
+import asyncio
+from os import getenv
+from e2b import Session
+
+E2B_API_KEY = getenv("E2B_API_KEY")
+
+async def main():
+ session = await Session.create(
+ id="Python3", cwd="/home/user/code" # $HighlightLine
+ )
+ await session.filesystem.write("hello.txt", "Welcome to E2B!") # $HighlightLine
+ proc = await session.process.start("cat /home/user/code/hello.txt")
+ await proc
+ print(proc.output.stdout)
+ # output: "Welcome to E2B!"
+
+ await session.filesystem.write(
+ "../hello.txt", "We hope you have a great day!"
+ ) # $HighlightLine
+ proc2 = await session.process.start("cat /home/user/hello.txt")
+ await proc2
+ print(proc2.output.stdout)
+ # output: "We hope you have a great day!"
+
+ await session.close()
+
+asyncio.run(main())
diff --git a/apps/docs/src/code/python/cwd/process.py b/apps/docs/src/code/python/cwd/process.py
new file mode 100644
index 000000000..eed7d7e14
--- /dev/null
+++ b/apps/docs/src/code/python/cwd/process.py
@@ -0,0 +1,21 @@
+import asyncio
+from os import getenv
+from e2b import Session
+
+E2B_API_KEY = getenv("E2B_API_KEY")
+
+async def main():
+ session = await Session.create(id="Python3", cwd="/code") # $HighlightLine
+ session_cwd = await session.process.start("pwd") # $HighlightLine
+ await session_cwd
+ print(session_cwd.output.stdout)
+ # output: "/code"
+
+ process_cwd = await session.process.start("pwd", cwd="/home") # $HighlightLine
+ await process_cwd
+ print(process_cwd.output.stdout)
+ # output: "/home"
+
+ await session.close()
+
+asyncio.run(main())
diff --git a/apps/docs/src/code/python/cwd/session.py b/apps/docs/src/code/python/cwd/session.py
new file mode 100644
index 000000000..8beb3e419
--- /dev/null
+++ b/apps/docs/src/code/python/cwd/session.py
@@ -0,0 +1,18 @@
+import asyncio
+from os import getenv
+from e2b import Session
+
+E2B_API_KEY = getenv("E2B_API_KEY")
+
+async def main():
+ session = await Session.create(
+ id="Python3",
+ cwd="/code", # $HighlightLine
+ )
+
+ # You can also change the cwd of an existing session
+ session.cwd = "/home" # $HighlightLine
+
+ await session.close()
+
+asyncio.run(main())
diff --git a/apps/docs/src/components/Navigation.tsx b/apps/docs/src/components/Navigation.tsx
index e127008e1..eee50c003 100644
--- a/apps/docs/src/components/Navigation.tsx
+++ b/apps/docs/src/components/Navigation.tsx
@@ -13,14 +13,15 @@ import { remToPx } from '@/lib/remToPx'
import { Auth } from '@/components/Auth'
import { Feedback } from '@/components/Feedback'
import {
+ Binary,
Bug,
- Timer,
ChevronRightSquare,
+ Folder,
FolderTree,
- ShieldAlert,
KeyRound,
Settings,
- Binary,
+ ShieldAlert,
+ Timer,
} from 'lucide-react'
interface NavGroup {
@@ -363,6 +364,16 @@ export const navigation = [
// title: 'Download Files',
// href: '/playgrounds/download',
// },
+ {
+ icon: (
+ <Folder
+ strokeWidth={1}
+ size={20}
+ />
+ ),
+ title: 'Working Directory',
+ href: '/playgrounds/cwd',
+ },
{
icon: (
<Bug
diff --git a/packages/js-sdk/src/session/index.ts b/packages/js-sdk/src/session/index.ts
index 0c9f701e5..3f20896c0 100644
--- a/packages/js-sdk/src/session/index.ts
+++ b/packages/js-sdk/src/session/index.ts
@@ -25,12 +25,14 @@ import {
TerminalOutput,
terminalService,
} from './terminal'
+import { resolvePath } from '../utils/filesystem'
export type Environment = components['schemas']['Template']
export interface SessionOpts extends SessionConnectionOpts {
onScanPorts?: ScanOpenPortsHandler
timeout?: number
+ cwd?: string // Current working directory. Used to resolve relative paths.
}
export class Session extends SessionConnection {
@@ -54,7 +56,12 @@ export class Session extends SessionConnection {
* @returns Array of files in a directory
*/
list: async (path, opts?: CallOpts) => {
- return (await this.call(filesystemService, 'list', [path], opts)) as FileInfo[]
+ return (await this.call(
+ filesystemService,
+ 'list',
+ [_resolvePath(path)],
+ opts,
+ )) as FileInfo[]
},
/**
* Reads the whole content of a file.
@@ -64,7 +71,12 @@ export class Session extends SessionConnection {
* @returns Content of a file
*/
read: async (path, opts?: CallOpts) => {
- return (await this.call(filesystemService, 'read', [path], opts)) as string
+ return (await this.call(
+ filesystemService,
+ 'read',
+ [_resolvePath(path)],
+ opts,
+ )) as string
},
/**
* Removes a file or a directory.
@@ -73,7 +85,7 @@ export class Session extends SessionConnection {
* @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)
*/
remove: async (path, opts?: CallOpts) => {
- await this.call(filesystemService, 'remove', [path], opts)
+ await this.call(filesystemService, 'remove', [_resolvePath(path)], opts)
},
/**
* Writes content to a new file on path.
@@ -83,7 +95,7 @@ export class Session extends SessionConnection {
* @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)
*/
write: async (path, content, opts?: CallOpts) => {
- await this.call(filesystemService, 'write', [path, content], opts)
+ await this.call(filesystemService, 'write', [_resolvePath(path), content], opts)
},
/**
* Write array of bytes to a file.
@@ -96,7 +108,10 @@ export class Session extends SessionConnection {
// We need to convert the byte array to base64 string without using browser or node specific APIs.
// This should be achieved by the node polyfills.
const base64Content = Buffer.from(content).toString('base64')
- await this.call(filesystemService, 'writeBase64', [path, base64Content])
+ await this.call(filesystemService, 'writeBase64', [
+ _resolvePath(path),
+ base64Content,
+ ])
},
/**
* Reads the whole content of a file as an array of bytes.
@@ -105,7 +120,7 @@ export class Session extends SessionConnection {
*/
readBytes: async (path: string) => {
const base64Content = (await this.call(filesystemService, 'readBase64', [
- path,
+ _resolvePath(path),
])) as string
// We need to convert the byte array to base64 string without using browser or node specific APIs.
// This should be achieved by the node polyfills.
@@ -118,7 +133,7 @@ export class Session extends SessionConnection {
* @param {timeout} [opts.timeout] Timeout in milliseconds (default is 60 seconds)
*/
makeDir: async (path, opts?: CallOpts) => {
- await this.call(filesystemService, 'makeDir', [path], opts)
+ await this.call(filesystemService, 'makeDir', [_resolvePath(path)], opts)
},
/**
* Watches directory for filesystem events.
@@ -127,7 +142,7 @@ export class Session extends SessionConnection {
*/
watchDir: (path: string) => {
this.logger.debug?.(`Watching directory "${path}"`)
- const npath = normalizePath(path)
+ const npath = normalizePath(_resolvePath(path))
return new FilesystemWatcher(this, npath)
},
}
@@ -159,8 +174,8 @@ export class Session extends SessionConnection {
this.logger.warn?.('The rootDir parameter is deprecated, use cwd instead.')
cwd = rootDir
}
- if (!cwd && this.opts.cwd) {
- cwd = this.opts.cwd
+ if (!cwd && this.cwd) {
+ cwd = this.cwd
}
const { promise: terminalExited, resolve: triggerExit } =
createDeferredPromise()
@@ -244,8 +259,8 @@ export class Session extends SessionConnection {
this.logger.warn?.('The rootDir parameter is deprecated, use cwd instead.')
cwd = rootDir
}
- if (!cwd && this.opts.cwd) {
- cwd = this.opts.cwd
+ if (!cwd && this.cwd) {
+ cwd = this.cwd
}
if (!cmd) throw new Error('cmd is required')
this.logger.debug?.(`Starting process "${processID}", cmd: "${cmd}"`)
@@ -307,6 +322,9 @@ export class Session extends SessionConnection {
return await withTimeout(start, timeout)(opts)
},
}
+
+ const _resolvePath = (path: string): string =>
+ resolvePath(path, this.cwd, this.logger)
}
static async create(opts: SessionOpts) {
diff --git a/packages/js-sdk/src/session/sessionConnection.ts b/packages/js-sdk/src/session/sessionConnection.ts
index d7a7dee77..4366eab1a 100644
--- a/packages/js-sdk/src/session/sessionConnection.ts
+++ b/packages/js-sdk/src/session/sessionConnection.ts
@@ -31,7 +31,7 @@ interface Subscriber {
handler: SubscriptionHandler
}
-interface Logger {
+export interface Logger {
debug?: (message: string, ...args: unknown[]) => void
info?: (message: string, ...args: unknown[]) => void
warn?: (message: string, ...args: unknown[]) => void
@@ -59,6 +59,8 @@ const refreshSession = api
.create({ api_key: true })
export class SessionConnection {
+ cwd: string | undefined
+
protected readonly logger: Logger
protected session?: components['schemas']['Session']
protected isOpen = false
@@ -76,6 +78,12 @@ export class SessionConnection {
)
}
this.apiKey = apiKey
+
+ this.cwd = opts.cwd
+ if (this.cwd && this.cwd.startsWith('~')) {
+ this.cwd = this.cwd.replace('~', '/home/user')
+ }
+
this.logger = opts.logger ?? {
// by default, we log to the console
// we don't log debug messages by default
diff --git a/packages/js-sdk/src/utils/filesystem.ts b/packages/js-sdk/src/utils/filesystem.ts
new file mode 100644
index 000000000..9e05a4286
--- /dev/null
+++ b/packages/js-sdk/src/utils/filesystem.ts
@@ -0,0 +1,44 @@
+import path from 'path'
+import { Logger } from '../session/sessionConnection'
+
+export const resolvePath = (
+ inputPath: string,
+ cwd: string | undefined,
+ logger: Logger,
+): string => {
+ let result: string
+ if (inputPath.startsWith('./')) {
+ result = path.join(cwd || '/home/user', inputPath)
+ if (!cwd) {
+ logger.warn?.(
+ `Path starts with './' and cwd isn't set. The path '${inputPath}' will evaluate to '${result}', which may not be what you want.`,
+ )
+ }
+ return result
+ }
+
+ if (inputPath.startsWith('../')) {
+ result = path.join(cwd || '/home/user', inputPath)
+ if (!cwd) {
+ logger.warn?.(
+ `Path starts with '../' and cwd isn't set. The path '${inputPath}' will evaluate to '${result}', which may not be what you want.`,
+ )
+ }
+ return result
+ }
+ if (inputPath.startsWith('~/')) {
+ result = path.join(cwd || '/home/user', inputPath.substring(2))
+ if (!cwd) {
+ logger.warn?.(
+ `Path starts with '~/' and cwd isn't set. The path '${inputPath}' will evaluate to '${result}', which may not be what you want.`,
+ )
+ }
+ return result
+ }
+
+ if (!inputPath.startsWith('/') && cwd) {
+ return path.join(cwd, inputPath)
+ }
+
+ return inputPath
+}
diff --git a/packages/js-sdk/test/cwd.test.mjs b/packages/js-sdk/test/cwd.test.mjs
new file mode 100644
index 000000000..6368f2161
--- /dev/null
+++ b/packages/js-sdk/test/cwd.test.mjs
@@ -0,0 +1,105 @@
+import { Session } from '../src'
+import { expect, test, vi } from 'vitest'
+
+test(
+ 'custom cwd',
+ async () => {
+ const session = await Session.create({
+ id: 'Nodejs',
+ cwd: '/code/app',
+ })
+
+ // change dir to /home/user
+ session.cwd = '/home/user'
+
+ // process respects cwd
+ {
+ const proc = await session.process.start({ cmd: 'pwd' })
+ await proc.finished
+ const out = proc.output.stdout
+ expect(out).toEqual('/home/user')
+ }
+
+ // filesystem respects cwd
+ {
+ await session.filesystem.write('hello.txt', `Hello VM!`)
+ const proc = await session.process.start({ cmd: 'cat /home/user/hello.txt' })
+ await proc.finished
+ const out = proc.output.stdout
+ expect(out).toEqual('Hello VM!')
+ }
+
+ // call cd in process
+ {
+ const proc = await session.process.start({ cmd: 'cd /code' })
+ await proc.finished
+ }
+
+ // process doesn't respect cd
+ {
+ const proc = await session.process.start({ cmd: 'pwd' })
+ await proc.finished
+ const out = proc.output.stdout
+ expect(out).toEqual('/home/user')
+ }
+ await session.close()
+ },
+ { timeout: 10_000 },
+)
+
+test('test_process_cwd', async () => {
+ const session = await Session.create({ id: 'Nodejs', cwd: '/code/app' })
+ const proc = await session.process.start({ cmd: 'pwd' })
+ await proc.finished
+ expect(proc.output.stdout).toEqual('/code/app')
+ await session.close()
+})
+
+test('test_filesystem_cwd', async () => {
+ const session = await Session.create({ id: 'Nodejs', cwd: '/code/app' })
+
+ await session.filesystem.write('hello.txt', 'Hello VM!')
+ const proc = await session.process.start({ cmd: 'cat /code/app/hello.txt' })
+
+ await proc.finished
+ expect(proc.output.stdout).toEqual('Hello VM!')
+ await session.close()
+})
+
+test('test_initial_cwd_with_tilde', async () => {
+ const session = await Session.create({ id: 'Nodejs', cwd: '~/code/' })
+ const proc = await session.process.start({ cmd: 'pwd' })
+ await proc.finished
+ expect(proc.output.stdout).toEqual('/home/user/code')
+ await session.close()
+})
+
+test('test_relative_paths', async () => {
+ const session = await Session.create({ id: 'Nodejs', cwd: '/home/user' })
+ await session.filesystem.makeDir('./code')
+ await session.filesystem.write('./code/hello.txt', 'Hello Vasek!')
+ const proc = await session.process.start({ cmd: 'cat /home/user/code/hello.txt' })
+ await proc.finished
+ expect(proc.output.stdout).toEqual('Hello Vasek!')
+
+ await session.filesystem.write('../../hello.txt', 'Hello Tom!')
+ const proc2 = await session.process.start({ cmd: 'cat /hello.txt' })
+ await proc2.finished
+ expect(proc2.output.stdout).toEqual('Hello Tom!')
+
+ await session.close()
+})
+
+test('test_warnings', async () => {
+ const session = await Session.create({
+ id: 'Nodejs',
+ logger: { warn: vi.spyOn(console, 'warn') },
+ })
+ await session.filesystem.write('./hello.txt', 'Hello Vasek!')
+ expect(console.warn).toHaveBeenCalledTimes(1)
+ await session.filesystem.write('../hello.txt', 'Hello Vasek!')
+ expect(console.warn).toHaveBeenCalledTimes(2)
+ await session.filesystem.write('~/hello.txt', 'Hello Vasek!')
+ expect(console.warn).toHaveBeenCalledTimes(3)
+ await session.close()
+})
diff --git a/packages/js-sdk/test/runCode.test.mjs b/packages/js-sdk/test/runCode.test.mjs
index fb606f0c9..831b4fedf 100644
--- a/packages/js-sdk/test/runCode.test.mjs
+++ b/packages/js-sdk/test/runCode.test.mjs
@@ -8,7 +8,7 @@ test="test\\n"
print(10*test)
raise Exception("err")
`
- const {stdout, stderr} = await runCode('PPSrlH5TIvFx', code)
+ const {stdout, stderr} = await runCode('Python3', code)
console.log('stdout', stdout)
console.log('stderr', stderr)
expect(stdout.length).toEqual(50)
diff --git a/packages/js-sdk/test/session.test.mjs b/packages/js-sdk/test/session.test.mjs
index 18c45bfe1..bc62f3b4b 100644
--- a/packages/js-sdk/test/session.test.mjs
+++ b/packages/js-sdk/test/session.test.mjs
@@ -1,5 +1,5 @@
-import { Session } from '../src'
-import { test, expect } from 'vitest'
+import {Session} from '../src'
+import {test} from 'vitest'
test('create session', async () => {
@@ -14,45 +14,3 @@ test('create multiple sessions', async () => {
await session.close()
await session2.close()
}, 10000)
-
-test(
- 'custom cwd',
- async () => {
- const session = await Session.create({
- id: 'Nodejs',
- cwd: '/code/app',
- })
-
- {
- const proc = await session.process.start({ cmd: 'pwd' })
- await proc.finished
- const out = proc.output.stdout
- expect(out).toEqual('/code/app')
- }
-
- // filesystem ops does not respect the cwd yet
- {
- await session.filesystem.write('hello.txt', `Hello VM!`)
- const proc = await session.process.start({ cmd: 'cat /hello.txt' })
- await proc.finished
- const out = proc.output.stdout
- expect(out).toEqual('Hello VM!')
- }
-
- // change dir to /home/user
- {
- const proc = await session.process.start({ cmd: 'cd /home/user' })
- await proc.finished
- }
-
- // create another file, it should still be in root
- {
- await session.filesystem.write('hello2.txt', `Hello VM 2!`)
- const proc = await session.process.start({ cmd: 'cat /hello2.txt' })
- await proc.finished
- const out = proc.output.stdout
- expect(out).toEqual('Hello VM 2!')
- }
- },
- { timeout: 10_000 },
-)
diff --git a/packages/python-sdk/e2b/session/exception.py b/packages/python-sdk/e2b/session/exception.py
index 6af521e96..400d047c6 100644
--- a/packages/python-sdk/e2b/session/exception.py
+++ b/packages/python-sdk/e2b/session/exception.py
@@ -7,11 +7,11 @@ class SessionException(Exception):
class RpcException(SessionException):
def __init__(
- self,
- message: str,
- code: int,
- id: str,
- data: Optional[Dict] = None,
+ self,
+ message: str,
+ code: int,
+ id: str,
+ data: Optional[Dict] = None,
):
super().__init__(message)
self.data = data
diff --git a/packages/python-sdk/e2b/session/filesystem.py b/packages/python-sdk/e2b/session/filesystem.py
index 921f30455..79d5aa628 100644
--- a/packages/python-sdk/e2b/session/filesystem.py
+++ b/packages/python-sdk/e2b/session/filesystem.py
@@ -1,12 +1,14 @@
-import logging
import base64
+import logging
from typing import Any, List, Optional
+from pydantic import BaseModel
+
from e2b.constants import TIMEOUT
from e2b.session.exception import FilesystemException, RpcException
from e2b.session.filesystem_watcher import FilesystemWatcher
from e2b.session.session_connection import SessionConnection
-from pydantic import BaseModel
+from e2b.utils.filesystem import resolve_path
logger = logging.getLogger(__name__)
@@ -30,7 +32,11 @@ class FilesystemManager:
def __init__(self, session: SessionConnection):
self._session = session
- async def read_bytes(self, path: str) -> bytearray:
+ @property
+ def cwd(self) -> str:
+ return self._session.cwd
+
+ async def read_bytes(self, path: str) -> bytes:
"""
Reads 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.
@@ -38,13 +44,13 @@ class FilesystemManager:
:param path: path to a file
:return: byte array representing the content of a file
"""
+ path = resolve_path(path, self.cwd)
result: str = await self._session._call(
self._service_name, "readBase64", [path]
)
return base64.b64decode(result)
- # return bytearray(result, "base64")
- async def write_bytes(self, path: str, content: bytearray) -> None:
+ async def write_bytes(self, path: str, content: bytes) -> None:
"""
Writes content to a file as a byte array.
This can be used when you cannot represent the data as an UTF-8 string.
@@ -52,6 +58,7 @@ class FilesystemManager:
:param path: path to a file
:param content: byte array representing the content to write
"""
+ path = resolve_path(path, self.cwd)
base64_content = base64.b64encode(content).decode("utf-8")
await self._session._call(
self._service_name, "writeBase64", [path, base64_content]
@@ -66,6 +73,8 @@ class FilesystemManager:
:return: Content of a file
"""
logger.debug(f"Reading file {path}")
+
+ path = resolve_path(path, self.cwd)
try:
result: str = await self._session._call(
self._service_name, "read", [path], timeout=timeout
@@ -86,6 +95,8 @@ class FilesystemManager:
: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:
await self._session._call(
self._service_name, "write", [path, content], timeout=timeout
@@ -102,6 +113,8 @@ class FilesystemManager:
: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:
await self._session._call(
self._service_name, "remove", [path], timeout=timeout
@@ -122,6 +135,8 @@ class FilesystemManager:
:return: Array of files in a directory
"""
logger.debug(f"Listing files in {path}")
+
+ path = resolve_path(path, self.cwd)
try:
result: List[Any] = await self._session._call(
self._service_name, "list", [path], timeout=timeout
@@ -142,6 +157,8 @@ class FilesystemManager:
: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:
await self._session._call(
self._service_name, "makeDir", [path], timeout=timeout
@@ -159,6 +176,8 @@ class FilesystemManager:
:return: New watcher
"""
logger.debug(f"Watching directory {path}")
+
+ path = resolve_path(path, self.cwd)
return FilesystemWatcher(
connection=self._session,
path=path,
diff --git a/packages/python-sdk/e2b/session/main.py b/packages/python-sdk/e2b/session/main.py
index 6b8948a13..ab764df41 100644
--- a/packages/python-sdk/e2b/session/main.py
+++ b/packages/python-sdk/e2b/session/main.py
@@ -60,14 +60,14 @@ class Session(SessionConnection):
return self._filesystem
def __init__(
- self,
- id: Union[Environment, str],
- api_key: Optional[str],
- cwd: Optional[str] = None,
- on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
- _debug_hostname: Optional[str] = None,
- _debug_port: Optional[int] = None,
- _debug_dev_env: Optional[Literal["remote", "local"]] = None,
+ self,
+ id: Union[Environment, str],
+ api_key: Optional[str],
+ cwd: Optional[str] = None,
+ on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
+ _debug_hostname: Optional[str] = None,
+ _debug_port: Optional[int] = None,
+ _debug_dev_env: Optional[Literal["remote", "local"]] = None,
):
"""
Creates a new cloud environment session.
@@ -90,6 +90,9 @@ class Session(SessionConnection):
"""
logger.info(f"Creating session {id if isinstance(id, str) else type(id)}")
+ if cwd and cwd.startswith("~"):
+ cwd = cwd.replace("~", "/home/user")
+
super().__init__(
id=id,
api_key=api_key,
@@ -118,6 +121,8 @@ class Session(SessionConnection):
await super().open()
await self._code_snippet._subscribe()
logger.info(f"Session {self._id} opened")
+ if self.cwd:
+ await self.filesystem.make_dir(self.cwd)
def _close_services(self):
self._terminal._close()
@@ -136,15 +141,15 @@ class Session(SessionConnection):
@classmethod
async def create(
- cls,
- id: Union[Environment, str],
- api_key: Optional[str] = None,
- cwd: Optional[str] = None,
- on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
- timeout: Optional[float] = TIMEOUT,
- _debug_hostname: Optional[str] = None,
- _debug_port: Optional[int] = None,
- _debug_dev_env: Optional[Literal["remote", "local"]] = None,
+ cls,
+ id: Union[Environment, str],
+ api_key: Optional[str] = None,
+ cwd: Optional[str] = None,
+ on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
+ timeout: Optional[float] = TIMEOUT,
+ _debug_hostname: Optional[str] = None,
+ _debug_port: Optional[int] = None,
+ _debug_dev_env: Optional[Literal["remote", "local"]] = None,
):
"""
Creates a new cloud environment session.
@@ -176,7 +181,5 @@ class Session(SessionConnection):
_debug_dev_env=_debug_dev_env,
)
await session.open(timeout=timeout)
- if cwd:
- await session.filesystem.make_dir(cwd)
return session
diff --git a/packages/python-sdk/e2b/session/process.py b/packages/python-sdk/e2b/session/process.py
index cf7828d05..90b00fbb2 100644
--- a/packages/python-sdk/e2b/session/process.py
+++ b/packages/python-sdk/e2b/session/process.py
@@ -4,6 +4,8 @@ from asyncio.exceptions import TimeoutError
from typing import Any, Awaitable, Callable, ClassVar, Coroutine, Dict, List, Optional
import async_timeout
+from pydantic import BaseModel
+
from e2b.constants import TIMEOUT
from e2b.session.env_vars import EnvVars
from e2b.session.exception import MultipleExceptions, ProcessException, RpcException
@@ -11,7 +13,6 @@ from e2b.session.out import OutStderrResponse, OutStdoutResponse
from e2b.session.session_connection import SessionConnection
from e2b.utils.future import DeferredFuture
from e2b.utils.id import create_id
-from pydantic import BaseModel
logger = logging.getLogger(__name__)
diff --git a/packages/python-sdk/e2b/session/run_code.py b/packages/python-sdk/e2b/session/run_code.py
index a2e675507..e7956388d 100644
--- a/packages/python-sdk/e2b/session/run_code.py
+++ b/packages/python-sdk/e2b/session/run_code.py
@@ -11,9 +11,9 @@ CodeRuntime = Literal[
async def run_code(
- runtime: Union[CodeRuntime, str],
- code: str,
- api_key: Optional[str] = None,
+ runtime: Union[CodeRuntime, str],
+ code: str,
+ api_key: Optional[str] = None,
):
"""
Runs code in a sandboxed cloud playground and return the stdout and stderr
diff --git a/packages/python-sdk/e2b/session/session_connection.py b/packages/python-sdk/e2b/session/session_connection.py
index 519dd215a..ecc8498db 100644
--- a/packages/python-sdk/e2b/session/session_connection.py
+++ b/packages/python-sdk/e2b/session/session_connection.py
@@ -42,10 +42,6 @@ class Subscription(BaseModel):
class SessionConnection:
_refresh_retries = 4
- @property
- def cwd(self):
- return self._cwd
-
@property
def finished(self):
"""
@@ -64,14 +60,14 @@ class SessionConnection:
return self._finished.__await__()
def __init__(
- self,
- id: str,
- api_key: Optional[str],
- cwd: Optional[str] = None,
- _debug_hostname: Optional[str] = None,
- _debug_port: Optional[int] = None,
- _debug_dev_env: Optional[Literal["remote", "local"]] = None,
- on_close: Optional[Callable[[], Any]] = None,
+ self,
+ id: str,
+ api_key: Optional[str],
+ cwd: Optional[str] = None,
+ _debug_hostname: Optional[str] = None,
+ _debug_port: Optional[int] = None,
+ _debug_dev_env: Optional[Literal["remote", "local"]] = None,
+ on_close: Optional[Callable[[], Any]] = None,
):
api_key = api_key or getenv("E2B_API_KEY")
@@ -80,9 +76,9 @@ class SessionConnection:
"API key is required, please visit https://e2b.dev/docs to get your API key",
)
+ self.cwd = cwd
self._id = id
self._api_key = api_key
- self._cwd = cwd
self._debug_hostname = _debug_hostname
self._debug_port = _debug_port
self._debug_dev_env = _debug_dev_env
@@ -224,11 +220,11 @@ class SessionConnection:
raise e
async def _call(
- self,
- service: str,
- method: str,
- params: List[Any] = None,
- timeout: Optional[float] = TIMEOUT,
+ self,
+ service: str,
+ method: str,
+ params: List[Any] = None,
+ timeout: Optional[float] = TIMEOUT,
):
if not params:
params = []
@@ -240,8 +236,8 @@ class SessionConnection:
return await self._rpc.send_message(f"{service}_{method}", params)
async def _handle_subscriptions(
- self,
- *subs: Optional[Awaitable[Callable[[], Awaitable[None]]]],
+ self,
+ *subs: Optional[Awaitable[Callable[[], Awaitable[None]]]],
):
results: List[
Union[Callable[[], Awaitable[None]], None, Exception]
@@ -289,12 +285,12 @@ class SessionConnection:
logger.debug(f"Unsubscribed (sub_id: {sub_id})")
async def _subscribe(
- self,
- service: str,
- handler: Callable[[Any], Any],
- method: str,
- *params,
- timeout: Optional[float] = TIMEOUT,
+ self,
+ service: str,
+ handler: Callable[[Any], Any],
+ method: str,
+ *params,
+ timeout: Optional[float] = TIMEOUT,
):
sub_id = await self._call(
service, "subscribe", [method, *params], timeout=timeout
diff --git a/packages/python-sdk/e2b/session/session_rpc.py b/packages/python-sdk/e2b/session/session_rpc.py
index ef13cc7f8..ca80ea4a7 100644
--- a/packages/python-sdk/e2b/session/session_rpc.py
+++ b/packages/python-sdk/e2b/session/session_rpc.py
@@ -123,15 +123,15 @@ class SessionRpc(BaseModel):
)
if isinstance(message, Ok):
if (
- message.id in self._waiting_for_replies
- and self._waiting_for_replies[message.id]
+ 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]
+ message.id in self._waiting_for_replies
+ and self._waiting_for_replies[message.id]
):
self._waiting_for_replies[message.id].reject(
RpcException(
diff --git a/packages/python-sdk/e2b/utils/filesystem.py b/packages/python-sdk/e2b/utils/filesystem.py
new file mode 100644
index 000000000..a6ded651b
--- /dev/null
+++ b/packages/python-sdk/e2b/utils/filesystem.py
@@ -0,0 +1,28 @@
+import os
+import warnings
+from typing import Optional
+
+
+def resolve_path(path: str, cwd: Optional[str] = None) -> str:
+ warning = f"Path starts with %()s and cwd isn't set. The path {path} will evaluate to `%()s`, which may not be what you want."
+ if path.startswith("./"):
+ result = os.path.join(cwd or "/home/user", path)
+ if not cwd:
+ warnings.warn(warning.format("./", result))
+ return result
+
+ if path.startswith("../"):
+ result = os.path.join(cwd or "/home/user", path)
+ if not cwd:
+ warnings.warn(warning.format("../", result))
+ return result
+
+ if path.startswith("~/"):
+ result = os.path.join("/home/user", path[2:])
+ warnings.warn(warning.format("~/", result))
+ return result
+
+ if not path.startswith("/") and cwd:
+ return os.path.join(cwd, path)
+
+ return path
diff --git a/packages/python-sdk/pyproject.toml b/packages/python-sdk/pyproject.toml
index 55c8b1053..ccb7d437b 100644
--- a/packages/python-sdk/pyproject.toml
+++ b/packages/python-sdk/pyproject.toml
@@ -39,3 +39,4 @@ build-backend = "poetry.core.masonry.api"
[tool.pytest.ini_options]
asyncio_mode = "auto"
+addopts = "-n auto"
diff --git a/packages/python-sdk/tests/test_cwd.py b/packages/python-sdk/tests/test_cwd.py
new file mode 100644
index 000000000..2d390cae9
--- /dev/null
+++ b/packages/python-sdk/tests/test_cwd.py
@@ -0,0 +1,85 @@
+import pytest
+
+from e2b import Session
+
+
+async def test_process_cwd():
+ session = await Session.create("Nodejs", cwd="/code/app")
+
+ proc = await session.process.start("pwd")
+ output = await proc
+ assert output.stdout == "/code/app"
+ await session.close()
+
+
+async def test_filesystem_cwd():
+ session = await Session.create("Nodejs", cwd="/code/app")
+
+ await session.filesystem.write("hello.txt", "Hello VM!")
+ proc = await session.process.start("cat /code/app/hello.txt")
+ output = await proc
+ assert output.stdout == "Hello VM!"
+
+ await session.close()
+
+
+async def test_change_cwd():
+ session = await Session.create("Nodejs", cwd="/code/app")
+
+ # change dir to /home/user
+ session.cwd = "/home/user"
+
+ # process respects cwd
+ proc = await session.process.start("pwd")
+ output = await proc
+ assert output.stdout == "/home/user"
+
+ # filesystem respects cwd
+ await session.filesystem.write("hello.txt", "Hello VM!")
+ proc = await session.process.start("cat /home/user/hello.txt")
+ output = await proc
+ assert output.stdout == "Hello VM!"
+
+ await session.close()
+
+
+async def test_initial_cwd_with_tilde():
+ session = await Session.create("Nodejs", cwd="~/code/")
+
+ proc = await session.process.start("pwd")
+ output = await proc
+ assert output.stdout == "/home/user/code"
+
+ await session.close()
+
+
+async def test_relative_paths():
+ session = await Session.create("Nodejs", cwd="/home/user")
+
+ await session.filesystem.make_dir("./code")
+ await session.filesystem.write("./code/hello.txt", "Hello Vasek!")
+ proc = await session.process.start("cat /home/user/code/hello.txt")
+ output = await proc
+ assert output.stdout == "Hello Vasek!"
+
+ await session.filesystem.write("../../hello.txt", "Hello Tom!")
+ proc = await session.process.start("cat /hello.txt")
+ output = await proc
+ assert output.stdout == "Hello Tom!"
+
+ await session.close()
+
+
+async def test_warnings():
+ session = await Session.create("Nodejs")
+
+ with pytest.warns(Warning):
+ await session.filesystem.write("./hello.txt", "Hello Vasek!")
+
+ with pytest.warns(Warning):
+ await session.filesystem.write("../hello.txt", "Hello Vasek!")
+
+ with pytest.warns(Warning):
+ await session.filesystem.write("~/hello.txt", "Hello Vasek!")
+
+ await session.close()
diff --git a/packages/python-sdk/tests/test_filesystem.py b/packages/python-sdk/tests/test_filesystem.py
index 46a8328db..de638ca82 100644
--- a/packages/python-sdk/tests/test_filesystem.py
+++ b/packages/python-sdk/tests/test_filesystem.py
@@ -116,7 +116,7 @@ async def test_read_bytes():
# Upload the file first
with open(local_path, "rb") as f:
content = f.read()
- await session.filesystem.write_bytes(remote_path, bytearray(content))
+ await session.filesystem.write_bytes(remote_path, content)
# Download the file
content = await session.filesystem.read_bytes(remote_path)
diff --git a/packages/python-sdk/tests/test_session.py b/packages/python-sdk/tests/test_session.py
index 29f06786a..433b57f8a 100644
--- a/packages/python-sdk/tests/test_session.py
+++ b/packages/python-sdk/tests/test_session.py
@@ -11,27 +11,3 @@ async def test_create_multiple_sessions():
session2 = await Session.create("Nodejs")
await session.close()
await session2.close()
-
-
-async def test_custom_cwd():
- session = await Session.create("Nodejs", cwd="/code/app")
-
- proc = await session.process.start("pwd")
- output = await proc
- assert output.stdout == "/code/app"
-
- # filesystem ops does not respect the cwd yet
- await session.filesystem.write("hello.txt", "Hello VM!")
- proc = await session.process.start("cat /hello.txt") # notice the file is in root
- output = await proc
- assert output.stdout == "Hello VM!"
-
- # change dir to /home/user
- proc = await session.process.start("cd /home/user")
- await proc
-
- # create another file, it should still be in root
- await session.filesystem.write("hello2.txt", "Hello VM 2!")
- proc = await session.process.start("cat /hello2.txt")
- output = await proc
- assert output.stdout == "Hello VM 2!"