Skip to content

armgit / E2B

Public Imported from GitHub
0

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

fix(sdks): fix template build bugs and consolidate shell quoting (#1442)

Mish Ushakov706c55329540
diff --git a/.changeset/eighty-jokes-design.md b/.changeset/eighty-jokes-design.md
new file mode 100644
index 000000000..d587e1af8
--- /dev/null
+++ b/.changeset/eighty-jokes-design.md
@@ -0,0 +1,11 @@
+---
+"@e2b/python-sdk": patch
+---
+
+Template SDK fixes:
+
+- Match the exact listening port in `wait_for_port` (via `ss`'s `sport` filter) so e.g. port 80 no longer matches 8080.
+- Shell-quote the URL, filename, and process name in `wait_for_url`, `wait_for_file`, and `wait_for_process`.
+- Shell-quote paths and arguments in `remove`, `rename`, `make_dir`, `make_symlink`, `git_clone` (URL/branch/path), and the devcontainer helpers so values with spaces or shell metacharacters work correctly.
+- Keep fetching build logs after a terminal build status is returned so the tail of the logs (beyond the 100-entries-per-call API limit) is no longer dropped.
+- Collect one stack trace per `COPY` instruction so failed-step stack traces stay aligned after `copy()` with multiple sources or `copy_items()`.
diff --git a/.changeset/great-pandas-listen.md b/.changeset/great-pandas-listen.md
new file mode 100644
index 000000000..e860318f9
--- /dev/null
+++ b/.changeset/great-pandas-listen.md
@@ -0,0 +1,13 @@
+---
+"e2b": patch
+---
+
+Template SDK fixes:
+
+- Sort files by full path in `getAllFilesInPath` so the files hash no longer depends on filesystem traversal order (the previous `sort()` was a no-op on glob `Path` objects).
+- Match the exact listening port in `waitForPort` (via `ss`'s `sport` filter) so e.g. port 80 no longer matches 8080.
+- Shell-quote the URL, filename, and process name in `waitForURL`, `waitForFile`, and `waitForProcess`.
+- Shell-quote paths and arguments in `remove`, `rename`, `makeDir`, `makeSymlink`, `gitClone` (URL/branch/path), and the devcontainer helpers so values with spaces or shell metacharacters work correctly.
+- Keep fetching build logs after a terminal build status is returned so the tail of the logs (beyond the 100-entries-per-call API limit) is no longer dropped.
+- Collect one stack trace per `COPY` instruction so failed-step stack traces stay aligned after `copy()` with multiple sources or `copyItems()`.
+- Strip ANSI escape codes in `LogEntry` messages, matching the Python SDK.
diff --git a/packages/js-sdk/src/sandbox/git/index.ts b/packages/js-sdk/src/sandbox/git/index.ts
index cfa637328..f50a864c9 100644
--- a/packages/js-sdk/src/sandbox/git/index.ts
+++ b/packages/js-sdk/src/sandbox/git/index.ts
@@ -3,6 +3,7 @@ import {
GitUpstreamError,
InvalidArgumentError,
} from '../../errors'
+import { shellQuote } from '../../utils'
import type { CommandStartOpts } from '../commands'
import type { CommandResult } from '../commands/commandHandle'
import { Commands } from '../commands'
@@ -20,7 +21,6 @@ import {
isMissingUpstream,
parseGitBranches,
parseGitStatus,
- shellEscape,
stripCredentials,
deriveRepoDirFromUrl,
withCredentials,
@@ -880,7 +880,7 @@ export class Git {
rest
)
- const approveCmd = `printf %s ${shellEscape(credentialInput)} | ${buildGitCommand(
+ const approveCmd = `printf %s ${shellQuote(credentialInput)} | ${buildGitCommand(
['credential', 'approve']
)}`
diff --git a/packages/js-sdk/src/sandbox/git/utils.ts b/packages/js-sdk/src/sandbox/git/utils.ts
index ad6001894..6df7fbc88 100644
--- a/packages/js-sdk/src/sandbox/git/utils.ts
+++ b/packages/js-sdk/src/sandbox/git/utils.ts
@@ -1,4 +1,5 @@
import { InvalidArgumentError } from '../../errors'
+import { shellQuote } from '../../utils'
import { CommandExitError } from '../commands/commandHandle'
/**
@@ -134,15 +135,6 @@ export interface GitBranches {
currentBranch?: string
}
-/**
- * Escape a string for safe use in a shell command.
- *
- * This uses single-quoted shell escaping and safely handles embedded single quotes.
- */
-export function shellEscape(value: string): string {
- return `'${value.replace(/'/g, "'\"'\"'")}'`
-}
-
/**
* Add HTTP(S) credentials to a Git URL.
*
@@ -249,7 +241,7 @@ export function buildGitCommand(args: string[], repoPath?: string): string {
}
parts.push(...args)
- return parts.map((part) => shellEscape(part)).join(' ')
+ return parts.map((part) => shellQuote(part)).join(' ')
}
type GitPushArgsOptions = {
diff --git a/packages/js-sdk/src/template/buildApi.ts b/packages/js-sdk/src/template/buildApi.ts
index 35b9c5267..819981ad3 100644
--- a/packages/js-sdk/src/template/buildApi.ts
+++ b/packages/js-sdk/src/template/buildApi.ts
@@ -1,6 +1,6 @@
import { ApiClient, handleApiError, components } from '../api'
import { buildRequestSignal } from '../connectionConfig'
-import { dynamicImport, stripAnsi } from '../utils'
+import { dynamicImport } from '../utils'
import { BuildError, FileUploadError, TemplateError } from '../errors'
import { FILE_UPLOAD_TIMEOUT_MS } from './consts'
import { LogEntry } from './logger'
@@ -309,9 +309,7 @@ export async function waitForBuildFinish(
let logsOffset = 0
let status: TemplateBuildStatus = 'building'
- while (status === 'building' || status === 'waiting') {
- signal?.throwIfAborted()
-
+ const pollStatus = async (): Promise<TemplateBuildStatusResponse> => {
const buildStatus = await getBuildStatus(
client,
{
@@ -323,26 +321,33 @@ export async function waitForBuildFinish(
)
logsOffset += buildStatus.logEntries.length
+ buildStatus.logEntries.forEach((logEntry) => onBuildLogs?.(logEntry))
- buildStatus.logEntries.forEach((logEntry) =>
- onBuildLogs?.(
- new LogEntry(
- logEntry.timestamp,
- logEntry.level,
- stripAnsi(logEntry.message)
- )
- )
- )
+ return buildStatus
+ }
+
+ while (status === 'building' || status === 'waiting') {
+ signal?.throwIfAborted()
+
+ const buildStatus = await pollStatus()
status = buildStatus.status
switch (status) {
- case 'ready': {
- return
- }
- case 'waiting': {
- break
- }
+ case 'ready':
case 'error': {
+ // The status endpoint returns at most 100 log entries per call, so
+ // the terminal response may not include the last logs — keep
+ // fetching until they are drained.
+ let tailStatus = buildStatus
+ while (tailStatus.logEntries.length > 0) {
+ signal?.throwIfAborted()
+ tailStatus = await pollStatus()
+ }
+
+ if (status === 'ready') {
+ return
+ }
+
let stackError: string | undefined
if (buildStatus.reason?.step !== undefined) {
const step = getBuildStepIndex(
@@ -357,6 +362,9 @@ export async function waitForBuildFinish(
stackError
)
}
+ case 'waiting': {
+ break
+ }
}
// Wait for a short period before checking the status again. Abort is
diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.ts
index 8c836e199..186e0a312 100644
--- a/packages/js-sdk/src/template/index.ts
+++ b/packages/js-sdk/src/template/index.ts
@@ -2,7 +2,7 @@ import type { PathLike } from 'node:fs'
import { ApiClient } from '../api'
import { ConnectionConfig, ConnectionOpts } from '../connectionConfig'
import { BuildError, InvalidArgumentError } from '../errors'
-import { runtime } from '../utils'
+import { runtime, shellQuote } from '../utils'
import {
assignTags,
checkAliasExists,
@@ -599,9 +599,12 @@ export class TemplateBase
forceUpload: options?.forceUpload,
resolveSymlinks: options?.resolveSymlinks,
})
+
+ // Collect one stack trace per pushed instruction so build steps stay
+ // aligned with their stack traces when copying multiple sources
+ this.collectStackTrace()
}
- this.collectStackTrace()
return this
}
@@ -613,7 +616,9 @@ export class TemplateBase
// Stack trace that will be used to re-throw the error with
const stackTrace = getCallerFrame(STACK_TRACE_DEPTH - 1)
- this.runInNewStackTraceContext(() => {
+ // Use the override so each copied item collects this stack trace,
+ // keeping build steps aligned with their stack traces
+ this.runInStackTraceOverrideContext(() => {
for (const item of items) {
try {
this.copy(item.src, item.dest, {
@@ -628,7 +633,7 @@ export class TemplateBase
throw copyError
}
}
- })
+ }, stackTrace)
return this
}
@@ -645,7 +650,7 @@ export class TemplateBase
if (options?.force) {
args.push('-f')
}
- args.push(...paths.map((p) => p.toString()))
+ args.push(...paths.map((p) => shellQuote(p.toString())))
return this.runInNewStackTraceContext(() =>
this.runCmd(args.join(' '), { user: options?.user })
)
@@ -656,7 +661,7 @@ export class TemplateBase
dest: PathLike,
options?: { force?: boolean; user?: string }
): TemplateBuilder {
- const args = ['mv', src.toString(), dest.toString()]
+ const args = ['mv', shellQuote(src.toString()), shellQuote(dest.toString())]
if (options?.force) {
args.push('-f')
}
@@ -674,7 +679,7 @@ export class TemplateBase
if (options?.mode) {
args.push(`-m ${padOctal(options.mode)}`)
}
- args.push(...paths.map((p) => p.toString()))
+ args.push(...paths.map((p) => shellQuote(p.toString())))
return this.runInNewStackTraceContext(() =>
this.runCmd(args.join(' '), { user: options?.user })
)
@@ -689,7 +694,7 @@ export class TemplateBase
if (options?.force) {
args.push('-f')
}
- args.push(src.toString(), dest.toString())
+ args.push(shellQuote(src.toString()), shellQuote(dest.toString()))
return this.runInNewStackTraceContext(() =>
this.runCmd(args.join(' '), { user: options?.user })
)
@@ -863,16 +868,16 @@ export class TemplateBase
path?: PathLike,
options?: { branch?: string; depth?: number; user?: string }
): TemplateBuilder {
- const args = ['git', 'clone', url]
+ const args = ['git', 'clone', shellQuote(url)]
if (options?.branch) {
- args.push(`--branch ${options.branch}`)
+ args.push(`--branch ${shellQuote(options.branch)}`)
args.push('--single-branch')
}
if (options?.depth) {
args.push(`--depth ${options.depth}`)
}
if (path) {
- args.push(path.toString())
+ args.push(shellQuote(path.toString()))
}
return this.runInNewStackTraceContext(() =>
@@ -936,7 +941,7 @@ export class TemplateBase
return this.runInNewStackTraceContext(() => {
return this.runCmd(
- `devcontainer build --workspace-folder ${devcontainerDirectory}`,
+ `devcontainer build --workspace-folder ${shellQuote(devcontainerDirectory)}`,
{ user: 'root' }
)
})
@@ -951,8 +956,9 @@ export class TemplateBase
}
return this.runInNewStackTraceContext(() => {
+ const dir = shellQuote(devcontainerDirectory)
return this.setStartCmd(
- `sudo devcontainer up --workspace-folder ${devcontainerDirectory} && sudo /prepare-exec.sh ${devcontainerDirectory} | sudo tee /devcontainer.sh > /dev/null && sudo chmod +x /devcontainer.sh && sudo touch /devcontainer.up`,
+ `sudo devcontainer up --workspace-folder ${dir} && sudo /prepare-exec.sh ${dir} | sudo tee /devcontainer.sh > /dev/null && sudo chmod +x /devcontainer.sh && sudo touch /devcontainer.up`,
waitForFile('/devcontainer.up')
)
})
@@ -1006,8 +1012,12 @@ export class TemplateBase
*/
private runInNewStackTraceContext<T>(fn: () => T): T {
this.disableStackTrace()
- const result = fn()
- this.enableStackTrace()
+ let result: T
+ try {
+ result = fn()
+ } finally {
+ this.enableStackTrace()
+ }
this.collectStackTrace(STACK_TRACE_DEPTH + 1)
return result
}
@@ -1017,9 +1027,11 @@ export class TemplateBase
stackTraceOverride: string | undefined
): T {
this.stackTracesOverride = stackTraceOverride
- const result = fn()
- this.stackTracesOverride = undefined
- return result
+ try {
+ return fn()
+ } finally {
+ this.stackTracesOverride = undefined
+ }
}
/**
diff --git a/packages/js-sdk/src/template/logger.ts b/packages/js-sdk/src/template/logger.ts
index 13fdcaa39..d3f30af62 100644
--- a/packages/js-sdk/src/template/logger.ts
+++ b/packages/js-sdk/src/template/logger.ts
@@ -10,16 +10,20 @@ export type LogEntryLevel = 'debug' | 'info' | 'warn' | 'error'
* Represents a single log entry from the template build process.
*/
export class LogEntry {
- constructor(
- public readonly timestamp: Date,
- public readonly level: LogEntryLevel,
- public readonly message: string
- ) {}
+ public readonly timestamp: Date
+ public readonly level: LogEntryLevel
+ public readonly message: string
+
+ constructor(timestamp: Date, level: LogEntryLevel, message: string) {
+ this.timestamp = timestamp
+ this.level = level
+ // Strip ANSI escape codes on construction so messages are consistent
+ // everywhere (matches the Python SDK behavior)
+ this.message = stripAnsi(message)
+ }
toString() {
- return `[${this.timestamp.toISOString()}] [${this.level}] ${stripAnsi(
- this.message
- )}`
+ return `[${this.timestamp.toISOString()}] [${this.level}] ${this.message}`
}
}
diff --git a/packages/js-sdk/src/template/readycmd.ts b/packages/js-sdk/src/template/readycmd.ts
index c08ea4788..d4b67295b 100644
--- a/packages/js-sdk/src/template/readycmd.ts
+++ b/packages/js-sdk/src/template/readycmd.ts
@@ -1,3 +1,5 @@
+import { shellQuote } from '../utils'
+
/**
* Class for ready check commands.
*/
@@ -30,7 +32,10 @@ export class ReadyCmd {
* ```
*/
export function waitForPort(port: number): ReadyCmd {
- const cmd = `ss -tuln | grep :${port}`
+ // Match the exact listening port via ss's source-port filter (so e.g. port
+ // 80 doesn't match 8080). ss exits 0 regardless of matches, so test for
+ // non-empty output to signal readiness.
+ const cmd = `[ -n "$(ss -Htuln sport = :${port})" ]`
return new ReadyCmd(cmd)
}
@@ -52,7 +57,7 @@ export function waitForPort(port: number): ReadyCmd {
* ```
*/
export function waitForURL(url: string, statusCode: number = 200): ReadyCmd {
- const cmd = `curl -s -o /dev/null -w "%{http_code}" ${url} | grep -q "${statusCode}"`
+ const cmd = `curl -s -o /dev/null -w "%{http_code}" ${shellQuote(url)} | grep -q "${statusCode}"`
return new ReadyCmd(cmd)
}
@@ -73,7 +78,7 @@ export function waitForURL(url: string, statusCode: number = 200): ReadyCmd {
* ```
*/
export function waitForProcess(processName: string): ReadyCmd {
- const cmd = `pgrep ${processName} > /dev/null`
+ const cmd = `pgrep ${shellQuote(processName)} > /dev/null`
return new ReadyCmd(cmd)
}
@@ -94,7 +99,7 @@ export function waitForProcess(processName: string): ReadyCmd {
* ```
*/
export function waitForFile(filename: string): ReadyCmd {
- const cmd = `[ -f ${filename} ]`
+ const cmd = `[ -f ${shellQuote(filename)} ]`
return new ReadyCmd(cmd)
}
diff --git a/packages/js-sdk/src/template/utils.ts b/packages/js-sdk/src/template/utils.ts
index 4b9cca2ac..e4e83a37c 100644
--- a/packages/js-sdk/src/template/utils.ts
+++ b/packages/js-sdk/src/template/utils.ts
@@ -175,7 +175,12 @@ export async function getAllFilesInPath(
}
}
- return Array.from(files.values()).sort()
+ // Sort by full path for a deterministic order — the default sort() would
+ // stringify the Path objects to '[object Object]' and keep glob order,
+ // making the files hash dependent on filesystem traversal order.
+ return Array.from(files.values()).sort((a, b) =>
+ a.fullpath() < b.fullpath() ? -1 : a.fullpath() > b.fullpath() ? 1 : 0
+ )
}
/**
diff --git a/packages/js-sdk/src/utils.ts b/packages/js-sdk/src/utils.ts
index 1037ae810..89f45252e 100644
--- a/packages/js-sdk/src/utils.ts
+++ b/packages/js-sdk/src/utils.ts
@@ -121,12 +121,26 @@ export function toBlob(
return new Response(data).blob()
}
+// Characters that are safe to leave unquoted in a POSIX shell, matching the
+// set used by Python's shlex.quote (`[^\w@%+=:,./-]` is considered unsafe).
+const UNSAFE_SHELL_CHAR = /[^\w@%+=:,./-]/
+
/**
- * Escape a string for safe inclusion in a single-quoted shell argument.
- * Equivalent to Python's shlex.quote().
+ * Quote a string for safe interpolation into a POSIX shell command.
+ *
+ * Faithful port of Python's `shlex.quote`: an empty string becomes `''`,
+ * values containing only safe characters are returned unchanged (keeping
+ * generated commands stable and cache-friendly), and anything else is wrapped
+ * in single quotes with embedded single quotes escaped as `'"'"'`.
*/
export function shellQuote(s: string): string {
- return "'" + s.replace(/'/g, "'\\''") + "'"
+ if (s === '') {
+ return "''"
+ }
+ if (!UNSAFE_SHELL_CHAR.test(s)) {
+ return s
+ }
+ return "'" + s.replace(/'/g, "'\"'\"'") + "'"
}
/**
diff --git a/packages/js-sdk/tests/template/stacktrace.test.ts b/packages/js-sdk/tests/template/stacktrace.test.ts
index 3d6fbec0d..69bab8b8c 100644
--- a/packages/js-sdk/tests/template/stacktrace.test.ts
+++ b/packages/js-sdk/tests/template/stacktrace.test.ts
@@ -21,6 +21,12 @@ const failureMap: Record<string, number | undefined> = {
fromGCPRegistry: 0,
copy: undefined,
copyItems: undefined,
+ // multi-source copy produces two COPY instructions (steps 1 and 2),
+ // the runCmd after it is step 3
+ multiSourceCopySecondSource: 2,
+ multiSourceCopyNextStep: 3,
+ copyItemsSecondItem: 2,
+ copyItemsNextStep: 3,
remove: 1,
rename: 1,
makeDir: 1,
@@ -50,6 +56,9 @@ export const restHandlers = [
http.post(apiUrl('/v2/templates/:templateID/builds/:buildID'), () => {
return HttpResponse.json({})
}),
+ http.get(apiUrl('/templates/:templateID/files/:hash'), () => {
+ return HttpResponse.json({ present: true })
+ }),
http.get<{ templateID: string; buildID: string }>(
apiUrl('/templates/:templateID/builds/:buildID/status'),
({ params }) => {
@@ -219,6 +228,60 @@ buildTemplateTest('traces on copyItems', async ({ buildTemplate }) => {
}, 'copyItems')
})
+buildTemplateTest(
+ 'traces on second source of multi-source copy',
+ async ({ buildTemplate }) => {
+ let template = Template().fromBaseImage()
+ template = template.copy(['stacktrace.test.ts', 'tags.test.ts'], '.')
+ await expectToThrowAndCheckTrace(async () => {
+ await buildTemplate(template, { name: 'multiSourceCopySecondSource' })
+ }, 'copy')
+ }
+)
+
+buildTemplateTest(
+ 'traces on step after multi-source copy',
+ async ({ buildTemplate }) => {
+ let template = Template().fromBaseImage()
+ template = template
+ .copy(['stacktrace.test.ts', 'tags.test.ts'], '.')
+ .runCmd(`./${nonExistentPath}`)
+ await expectToThrowAndCheckTrace(async () => {
+ await buildTemplate(template, { name: 'multiSourceCopyNextStep' })
+ }, 'runCmd')
+ }
+)
+
+buildTemplateTest(
+ 'traces on second item of copyItems',
+ async ({ buildTemplate }) => {
+ let template = Template().fromBaseImage()
+ template = template.copyItems([
+ { src: 'stacktrace.test.ts', dest: '.' },
+ { src: 'tags.test.ts', dest: '.' },
+ ])
+ await expectToThrowAndCheckTrace(async () => {
+ await buildTemplate(template, { name: 'copyItemsSecondItem' })
+ }, 'copyItems')
+ }
+)
+
+buildTemplateTest(
+ 'traces on step after copyItems',
+ async ({ buildTemplate }) => {
+ let template = Template().fromBaseImage()
+ template = template
+ .copyItems([
+ { src: 'stacktrace.test.ts', dest: '.' },
+ { src: 'tags.test.ts', dest: '.' },
+ ])
+ .runCmd(`./${nonExistentPath}`)
+ await expectToThrowAndCheckTrace(async () => {
+ await buildTemplate(template, { name: 'copyItemsNextStep' })
+ }, 'runCmd')
+ }
+)
+
buildTemplateTest('traces on copy absolute path', async () => {
await expectToThrowAndCheckTrace(async () => {
Template().fromBaseImage().copy('/absolute/path', '/absolute/path')
diff --git a/packages/js-sdk/tests/template/utils/getAllFilesInPath.test.ts b/packages/js-sdk/tests/template/utils/getAllFilesInPath.test.ts
index c75962904..fefc0e9a2 100644
--- a/packages/js-sdk/tests/template/utils/getAllFilesInPath.test.ts
+++ b/packages/js-sdk/tests/template/utils/getAllFilesInPath.test.ts
@@ -195,11 +195,25 @@ describe('getAllFilesInPath', () => {
const files = await getAllFilesInPath('*.txt', testDir, [])
expect(files).toHaveLength(3)
- // Files are sorted by full path, not just filename
- const fileNames = files.map((f) => basename(f.fullpath())).sort()
+ // Files must be returned sorted by full path so the files hash is
+ // independent of filesystem traversal order
+ const fileNames = files.map((f) => basename(f.fullpath()))
expect(fileNames).toEqual(['apple.txt', 'banana.txt', 'zebra.txt'])
})
+ test('should return nested files sorted by full path', async () => {
+ await mkdir(join(testDir, 'b'), { recursive: true })
+ await mkdir(join(testDir, 'a'), { recursive: true })
+ await writeFile(join(testDir, 'zebra.txt'), 'z content')
+ await writeFile(join(testDir, 'b', 'file.txt'), 'b content')
+ await writeFile(join(testDir, 'a', 'file.txt'), 'a content')
+
+ const files = await getAllFilesInPath('*', testDir, [])
+
+ const paths = files.map((f) => f.fullpath())
+ expect(paths).toEqual([...paths].sort())
+ })
+
test('should handle no matching files', async () => {
await writeFile(join(testDir, 'file.txt'), 'content')
diff --git a/packages/js-sdk/tests/template/utils/readycmd.test.ts b/packages/js-sdk/tests/template/utils/readycmd.test.ts
new file mode 100644
index 000000000..f3da4f1cf
--- /dev/null
+++ b/packages/js-sdk/tests/template/utils/readycmd.test.ts
@@ -0,0 +1,49 @@
+import { expect, test, describe } from 'vitest'
+import {
+ waitForFile,
+ waitForPort,
+ waitForProcess,
+ waitForTimeout,
+ waitForURL,
+} from '../../../src/template/readycmd'
+
+describe('readycmd', () => {
+ test('waitForPort matches the exact listening port', () => {
+ const cmd = waitForPort(80).getCmd()
+ expect(cmd).toBe('[ -n "$(ss -Htuln sport = :80)" ]')
+ })
+
+ test('waitForURL quotes the url', () => {
+ const cmd = waitForURL('http://localhost:3000/health?ready=1&x=y').getCmd()
+ expect(cmd).toBe(
+ 'curl -s -o /dev/null -w "%{http_code}" \'http://localhost:3000/health?ready=1&x=y\' | grep -q "200"'
+ )
+ })
+
+ test('waitForURL keeps simple urls unquoted', () => {
+ const cmd = waitForURL('http://localhost:3000/health').getCmd()
+ expect(cmd).toBe(
+ 'curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/health | grep -q "200"'
+ )
+ })
+
+ test('waitForProcess quotes the process name', () => {
+ const cmd = waitForProcess('my daemon').getCmd()
+ expect(cmd).toBe("pgrep 'my daemon' > /dev/null")
+ })
+
+ test('waitForFile quotes the filename', () => {
+ const cmd = waitForFile('/tmp/ready file').getCmd()
+ expect(cmd).toBe("[ -f '/tmp/ready file' ]")
+ })
+
+ test('waitForFile keeps simple paths unquoted', () => {
+ const cmd = waitForFile('/tmp/ready').getCmd()
+ expect(cmd).toBe('[ -f /tmp/ready ]')
+ })
+
+ test('waitForTimeout converts milliseconds to seconds', () => {
+ expect(waitForTimeout(5000).getCmd()).toBe('sleep 5')
+ expect(waitForTimeout(100).getCmd()).toBe('sleep 1')
+ })
+})
diff --git a/packages/python-sdk/e2b/template/main.py b/packages/python-sdk/e2b/template/main.py
index 5d0c74e40..1928a5918 100644
--- a/packages/python-sdk/e2b/template/main.py
+++ b/packages/python-sdk/e2b/template/main.py
@@ -1,4 +1,5 @@
import json
+import shlex
from typing import Dict, List, Optional, Union, Literal
from pathlib import Path
@@ -93,7 +94,11 @@ class TemplateBuilder:
self._template._instructions.append(instruction)
- self._template._collect_stack_trace()
+ # Collect one stack trace per pushed instruction so build steps
+ # stay aligned with their stack traces when copying multiple
+ # sources
+ self._template._collect_stack_trace()
+
return self
def copy_items(self, items: List[CopyItem]) -> "TemplateBuilder":
@@ -133,7 +138,9 @@ class TemplateBuilder:
raise error.with_traceback(stack_trace)
raise
- self._template._run_in_new_stack_trace_context(_copy_items)
+ # Use the override so each copied item collects this stack trace,
+ # keeping build steps aligned with their stack traces
+ self._template._run_in_stack_trace_override_context(_copy_items, stack_trace)
return self
def remove(
@@ -165,7 +172,7 @@ class TemplateBuilder:
args.append("-r")
if force:
args.append("-f")
- args.extend([str(p) for p in paths])
+ args.extend([shlex.quote(str(p)) for p in paths])
return self._template._run_in_new_stack_trace_context(
lambda: self.run_cmd(" ".join(args), user=user)
@@ -194,7 +201,7 @@ class TemplateBuilder:
template.rename('/tmp/old.txt', '/tmp/new.txt', user='root')
```
"""
- args = ["mv", str(src), str(dest)]
+ args = ["mv", shlex.quote(str(src)), shlex.quote(str(dest))]
if force:
args.append("-f")
@@ -228,7 +235,7 @@ class TemplateBuilder:
args = ["mkdir", "-p"]
if mode:
args.append(f"-m {pad_octal(mode)}")
- args.extend([str(p) for p in path_list])
+ args.extend([shlex.quote(str(p)) for p in path_list])
return self._template._run_in_new_stack_trace_context(
lambda: self.run_cmd(" ".join(args), user=user)
@@ -261,7 +268,7 @@ class TemplateBuilder:
args = ["ln", "-s"]
if force:
args.append("-f")
- args.extend([str(src), str(dest)])
+ args.extend([shlex.quote(str(src)), shlex.quote(str(dest))])
return self._template._run_in_new_stack_trace_context(
lambda: self.run_cmd(" ".join(args), user=user)
)
@@ -548,14 +555,14 @@ class TemplateBuilder:
template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root')
```
"""
- args = ["git", "clone", url]
+ args = ["git", "clone", shlex.quote(url)]
if branch:
- args.append(f"--branch {branch}")
+ args.append(f"--branch {shlex.quote(branch)}")
args.append("--single-branch")
if depth:
args.append(f"--depth {depth}")
if path:
- args.append(str(path))
+ args.append(shlex.quote(str(path)))
return self._template._run_in_new_stack_trace_context(
lambda: self.run_cmd(" ".join(args), user=user)
)
@@ -586,7 +593,7 @@ class TemplateBuilder:
return self._template._run_in_new_stack_trace_context(
lambda: self.run_cmd(
- f"devcontainer build --workspace-folder {devcontainer_directory}",
+ f"devcontainer build --workspace-folder {shlex.quote(str(devcontainer_directory))}",
user="root",
)
)
@@ -624,11 +631,12 @@ class TemplateBuilder:
).with_traceback(stack_trace)
def _set_start():
+ dir_ = shlex.quote(str(devcontainer_directory))
return self.set_start_cmd(
"sudo devcontainer up --workspace-folder "
- + str(devcontainer_directory)
+ + dir_
+ " && sudo /prepare-exec.sh "
- + str(devcontainer_directory)
+ + dir_
+ " | sudo tee /devcontainer.sh > /dev/null && sudo chmod +x /devcontainer.sh && sudo touch /devcontainer.up",
wait_for_file("/devcontainer.up"),
)
@@ -864,8 +872,10 @@ class TemplateBase:
:return: The result of the function
"""
self._disable_stack_trace()
- result = fn()
- self._enable_stack_trace()
+ try:
+ result = fn()
+ finally:
+ self._enable_stack_trace()
self._collect_stack_trace(STACK_TRACE_DEPTH + 1)
return result
@@ -881,9 +891,10 @@ class TemplateBase:
:return: The result of the function
"""
self._stack_traces_override = stack_trace_override
- result = fn()
- self._stack_traces_override = None
- return result
+ try:
+ return fn()
+ finally:
+ self._stack_traces_override = None
# Built-in image mixins
def from_debian_image(self, variant: str = "stable") -> TemplateBuilder:
diff --git a/packages/python-sdk/e2b/template/readycmd.py b/packages/python-sdk/e2b/template/readycmd.py
index 1ec65d822..7ab28d9c0 100644
--- a/packages/python-sdk/e2b/template/readycmd.py
+++ b/packages/python-sdk/e2b/template/readycmd.py
@@ -1,3 +1,6 @@
+import shlex
+
+
class ReadyCmd:
"""
Wrapper class for ready check commands.
@@ -31,7 +34,10 @@ def wait_for_port(port: int):
)
```
"""
- cmd = f"ss -tuln | grep :{port}"
+ # Match the exact listening port via ss's source-port filter (so e.g. port
+ # 80 doesn't match 8080). ss exits 0 regardless of matches, so test for
+ # non-empty output to signal readiness.
+ cmd = f'[ -n "$(ss -Htuln sport = :{port})" ]'
return ReadyCmd(cmd)
@@ -57,7 +63,7 @@ def wait_for_url(url: str, status_code: int = 200):
)
```
"""
- cmd = f'curl -s -o /dev/null -w "%{{http_code}}" {url} | grep -q "{status_code}"'
+ cmd = f'curl -s -o /dev/null -w "%{{http_code}}" {shlex.quote(url)} | grep -q "{status_code}"'
return ReadyCmd(cmd)
@@ -82,7 +88,7 @@ def wait_for_process(process_name: str):
)
```
"""
- cmd = f"pgrep {process_name} > /dev/null"
+ cmd = f"pgrep {shlex.quote(process_name)} > /dev/null"
return ReadyCmd(cmd)
@@ -107,7 +113,7 @@ def wait_for_file(filename: str):
)
```
"""
- cmd = f"[ -f {filename} ]"
+ cmd = f"[ -f {shlex.quote(filename)} ]"
return ReadyCmd(cmd)
diff --git a/packages/python-sdk/e2b/template_async/build_api.py b/packages/python-sdk/e2b/template_async/build_api.py
index 5e6278450..44eada8cc 100644
--- a/packages/python-sdk/e2b/template_async/build_api.py
+++ b/packages/python-sdk/e2b/template_async/build_api.py
@@ -217,7 +217,8 @@ async def wait_for_build_finish(
logs_offset = 0
status = TemplateBuildStatus.BUILDING
- while status in [TemplateBuildStatus.BUILDING, TemplateBuildStatus.WAITING]:
+ async def poll_status() -> TemplateBuildStatusResponse:
+ nonlocal logs_offset
build_status = await get_build_status(
client, template_id, build_id, logs_offset
)
@@ -228,15 +229,24 @@ async def wait_for_build_finish(
if on_build_logs:
on_build_logs(log_entry)
+ return build_status
+
+ while status in [TemplateBuildStatus.BUILDING, TemplateBuildStatus.WAITING]:
+ build_status = await poll_status()
+
status = build_status.status
- if status == TemplateBuildStatus.READY:
- return
+ if status in [TemplateBuildStatus.READY, TemplateBuildStatus.ERROR]:
+ # The status endpoint returns at most 100 log entries per call, so
+ # the terminal response may not include the last logs - keep
+ # fetching until they are drained.
+ tail_status = build_status
+ while len(tail_status.log_entries) > 0:
+ tail_status = await poll_status()
- elif status == TemplateBuildStatus.WAITING:
- pass
+ if status == TemplateBuildStatus.READY:
+ return
- elif status == TemplateBuildStatus.ERROR:
traceback = None
if build_status.reason and build_status.reason.step:
# Find the corresponding stack trace for the failed step
diff --git a/packages/python-sdk/e2b/template_sync/build_api.py b/packages/python-sdk/e2b/template_sync/build_api.py
index 0cba15dfb..257492928 100644
--- a/packages/python-sdk/e2b/template_sync/build_api.py
+++ b/packages/python-sdk/e2b/template_sync/build_api.py
@@ -216,7 +216,8 @@ def wait_for_build_finish(
logs_offset = 0
status = TemplateBuildStatus.BUILDING
- while status in [TemplateBuildStatus.BUILDING, TemplateBuildStatus.WAITING]:
+ def poll_status() -> TemplateBuildStatusResponse:
+ nonlocal logs_offset
build_status = get_build_status(client, template_id, build_id, logs_offset)
logs_offset += len(build_status.log_entries)
@@ -225,15 +226,24 @@ def wait_for_build_finish(
if on_build_logs:
on_build_logs(log_entry)
+ return build_status
+
+ while status in [TemplateBuildStatus.BUILDING, TemplateBuildStatus.WAITING]:
+ build_status = poll_status()
+
status = build_status.status
- if status == TemplateBuildStatus.READY:
- return
+ if status in [TemplateBuildStatus.READY, TemplateBuildStatus.ERROR]:
+ # The status endpoint returns at most 100 log entries per call, so
+ # the terminal response may not include the last logs - keep
+ # fetching until they are drained.
+ tail_status = build_status
+ while len(tail_status.log_entries) > 0:
+ tail_status = poll_status()
- elif status == TemplateBuildStatus.WAITING:
- pass
+ if status == TemplateBuildStatus.READY:
+ return
- elif status == TemplateBuildStatus.ERROR:
traceback = None
if build_status.reason and build_status.reason.step:
# Find the corresponding stack trace for the failed step
diff --git a/packages/python-sdk/tests/async/template_async/test_stacktrace.py b/packages/python-sdk/tests/async/template_async/test_stacktrace.py
index b1e8bcbb7..47cef087b 100644
--- a/packages/python-sdk/tests/async/template_async/test_stacktrace.py
+++ b/packages/python-sdk/tests/async/template_async/test_stacktrace.py
@@ -23,6 +23,12 @@ failure_map: dict[str, Optional[int]] = {
"from_gcp_registry": 0,
"copy": None,
"copy_items": None,
+ # multi-source copy produces two COPY instructions (steps 1 and 2),
+ # the run_cmd after it is step 3
+ "multi_source_copy_second_source": 2,
+ "multi_source_copy_next_step": 3,
+ "copy_items_second_item": 2,
+ "copy_items_next_step": 3,
"remove": 1,
"rename": 1,
"make_dir": 1,
@@ -51,6 +57,11 @@ def mock_template_build(monkeypatch):
async def mock_trigger_build(client, template_id: str, build_id: str, template):
return None
+ async def mock_get_file_upload_link(
+ client, template_id: str, files_hash: str, stack_trace=None
+ ):
+ return SimpleNamespace(present=True, url=None)
+
async def mock_get_build_status(
client, template_id: str, build_id: str, logs_offset: int
):
@@ -68,6 +79,9 @@ def mock_template_build(monkeypatch):
monkeypatch.setattr(template_async_main, "request_build", mock_request_build)
monkeypatch.setattr(template_async_main, "trigger_build", mock_trigger_build)
+ monkeypatch.setattr(
+ template_async_main, "get_file_upload_link", mock_get_file_upload_link
+ )
monkeypatch.setattr(build_api_mod, "get_build_status", mock_get_build_status)
@@ -187,6 +201,58 @@ async def test_traces_on_copyItems(async_build):
)
+async def test_traces_on_second_source_of_multi_source_copy(async_build):
+ template = AsyncTemplate()
+ template = template.from_base_image()
+ template = template.copy(["test_stacktrace.py", "test_tags.py"], ".")
+ await _expect_to_throw_and_check_trace(
+ lambda: async_build(template, name="multi_source_copy_second_source"), "copy"
+ )
+
+
+async def test_traces_on_step_after_multi_source_copy(async_build):
+ template = AsyncTemplate()
+ template = template.from_base_image()
+ template = template.copy(["test_stacktrace.py", "test_tags.py"], ".")
+ template = template.run_cmd(f"cat {non_existent_path}")
+ await _expect_to_throw_and_check_trace(
+ lambda: async_build(template, name="multi_source_copy_next_step"), "run_cmd"
+ )
+
+
+async def test_traces_on_second_item_of_copy_items(async_build):
+ template = AsyncTemplate()
+ template = template.from_base_image()
+ template = template.copy_items(
+ [
+ CopyItem(src="test_stacktrace.py", dest="."),
+ CopyItem(src="test_tags.py", dest="."),
+ ]
+ )
+ await _expect_to_throw_and_check_trace(
+ lambda: async_build(template, name="copy_items_second_item"), "copy_items"
+ )
+
+
+async def test_traces_on_step_after_copy_items(async_build):
+ template = AsyncTemplate()
+ template = template.from_base_image()
+ template = template.copy_items(
+ [
+ CopyItem(src="test_stacktrace.py", dest="."),
+ CopyItem(src="test_tags.py", dest="."),
+ ]
+ )
+ template = template.run_cmd(f"cat {non_existent_path}")
+ await _expect_to_throw_and_check_trace(
+ lambda: async_build(template, name="copy_items_next_step"), "run_cmd"
+ )
+
+
@pytest.mark.skip_debug()
async def test_traces_on_copy_absolute_path():
await _expect_to_throw_and_check_trace(
diff --git a/packages/python-sdk/tests/shared/template/test_readycmd.py b/packages/python-sdk/tests/shared/template/test_readycmd.py
new file mode 100644
index 000000000..daf430445
--- /dev/null
+++ b/packages/python-sdk/tests/shared/template/test_readycmd.py
@@ -0,0 +1,48 @@
+from e2b.template.readycmd import (
+ wait_for_file,
+ wait_for_port,
+ wait_for_process,
+ wait_for_timeout,
+ wait_for_url,
+)
+
+
+def test_wait_for_port_matches_the_exact_listening_port():
+ cmd = wait_for_port(80).get_cmd()
+ assert cmd == '[ -n "$(ss -Htuln sport = :80)" ]'
+
+
+def test_wait_for_url_quotes_the_url():
+ cmd = wait_for_url("http://localhost:3000/health?ready=1&x=y").get_cmd()
+ assert cmd == (
+ 'curl -s -o /dev/null -w "%{http_code}" '
+ "'http://localhost:3000/health?ready=1&x=y' | grep -q \"200\""
+ )
+
+
+def test_wait_for_url_keeps_simple_urls_unquoted():
+ cmd = wait_for_url("http://localhost:3000/health").get_cmd()
+ assert cmd == (
+ 'curl -s -o /dev/null -w "%{http_code}" '
+ 'http://localhost:3000/health | grep -q "200"'
+ )
+
+
+def test_wait_for_process_quotes_the_process_name():
+ cmd = wait_for_process("my daemon").get_cmd()
+ assert cmd == "pgrep 'my daemon' > /dev/null"
+
+
+def test_wait_for_file_quotes_the_filename():
+ cmd = wait_for_file("/tmp/ready file").get_cmd()
+ assert cmd == "[ -f '/tmp/ready file' ]"
+
+
+def test_wait_for_file_keeps_simple_paths_unquoted():
+ cmd = wait_for_file("/tmp/ready").get_cmd()
+ assert cmd == "[ -f /tmp/ready ]"
+
+
+def test_wait_for_timeout_converts_milliseconds_to_seconds():
+ assert wait_for_timeout(5000).get_cmd() == "sleep 5"
+ assert wait_for_timeout(100).get_cmd() == "sleep 1"
diff --git a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
index aed121b3f..8d1fa7120 100644
--- a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
+++ b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
@@ -23,6 +23,12 @@ failure_map: dict[str, Optional[int]] = {
"from_gcp_registry": 0,
"copy": None,
"copy_items": None,
+ # multi-source copy produces two COPY instructions (steps 1 and 2),
+ # the run_cmd after it is step 3
+ "multi_source_copy_second_source": 2,
+ "multi_source_copy_next_step": 3,
+ "copy_items_second_item": 2,
+ "copy_items_next_step": 3,
"remove": 1,
"rename": 1,
"make_dir": 1,
@@ -51,6 +57,11 @@ def mock_template_build(monkeypatch):
def mock_trigger_build(client, template_id: str, build_id: str, template):
return None
+ def mock_get_file_upload_link(
+ client, template_id: str, files_hash: str, stack_trace=None
+ ):
+ return SimpleNamespace(present=True, url=None)
+
def mock_get_build_status(
client, template_id: str, build_id: str, logs_offset: int
):
@@ -68,6 +79,9 @@ def mock_template_build(monkeypatch):
monkeypatch.setattr(template_sync_main, "request_build", mock_request_build)
monkeypatch.setattr(template_sync_main, "trigger_build", mock_trigger_build)
+ monkeypatch.setattr(
+ template_sync_main, "get_file_upload_link", mock_get_file_upload_link
+ )
monkeypatch.setattr(build_api_mod, "get_build_status", mock_get_build_status)
@@ -189,6 +203,58 @@ def test_traces_on_copyItems(build):
)
+def test_traces_on_second_source_of_multi_source_copy(build):
+ template = Template()
+ template = template.from_base_image()
+ template = template.copy(["test_stacktrace.py", "test_tags.py"], ".")
+ _expect_to_throw_and_check_trace(
+ lambda: build(template, name="multi_source_copy_second_source"), "copy"
+ )
+
+
+def test_traces_on_step_after_multi_source_copy(build):
+ template = Template()
+ template = template.from_base_image()
+ template = template.copy(["test_stacktrace.py", "test_tags.py"], ".")
+ template = template.run_cmd(f"cat {non_existent_path}")
+ _expect_to_throw_and_check_trace(
+ lambda: build(template, name="multi_source_copy_next_step"), "run_cmd"
+ )
+
+
+def test_traces_on_second_item_of_copy_items(build):
+ template = Template()
+ template = template.from_base_image()
+ template = template.copy_items(
+ [
+ CopyItem(src="test_stacktrace.py", dest="."),
+ CopyItem(src="test_tags.py", dest="."),
+ ]
+ )
+ _expect_to_throw_and_check_trace(
+ lambda: build(template, name="copy_items_second_item"), "copy_items"
+ )
+
+
+def test_traces_on_step_after_copy_items(build):
+ template = Template()
+ template = template.from_base_image()
+ template = template.copy_items(
+ [
+ CopyItem(src="test_stacktrace.py", dest="."),
+ CopyItem(src="test_tags.py", dest="."),
+ ]
+ )
+ template = template.run_cmd(f"cat {non_existent_path}")
+ _expect_to_throw_and_check_trace(
+ lambda: build(template, name="copy_items_next_step"), "run_cmd"
+ )
+
+
@pytest.mark.skip_debug()
def test_traces_on_copy_absolute_path():
_expect_to_throw_and_check_trace(