Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
fix(sdk): select stack-trace frames by SDK boundary instead of fixed depth (#1599)
Mish Ushakov3f46d560260a
diff --git a/.changeset/boundary-stack-traces.md b/.changeset/boundary-stack-traces.mdnew file mode 100644index 000000000..4f080813a--- /dev/null+++ b/.changeset/boundary-stack-traces.md@@ -0,0 +1,6 @@+---+'e2b': patch+'@e2b/python-sdk': patch+---++Select template build-step stack-trace frames by SDK boundary instead of fixed depth. The caller's frame is now the first one whose file lies outside the SDK package, so traces stay correct when transpilers inject extra frames (e.g. TS class-field initializers) or runtimes elide delegating frames (e.g. Bun's tail-call elision). The suppress/override stack-trace collection machinery this made redundant (`runInNewStackTraceContext`, `runInStackTraceOverrideContext` and their Python equivalents) is removed.diff --git a/packages/js-sdk/package.json b/packages/js-sdk/package.jsonindex 18c9f1e90..d6b7561e2 100644--- a/packages/js-sdk/package.json+++ b/packages/js-sdk/package.json@@ -56,6 +56,7 @@"@vitest/browser": "^4.1.10","@vitest/browser-playwright": "^4.1.10","dotenv": "^16.4.5",+ "error-stack-parser-es": "^2.0.1","json-schema-to-typescript": "^15.0.4","knip": "^5.43.6","msw": "^2.12.10",diff --git a/packages/js-sdk/src/template/consts.ts b/packages/js-sdk/src/template/consts.tsindex a36e8eb8a..e29932103 100644--- a/packages/js-sdk/src/template/consts.ts+++ b/packages/js-sdk/src/template/consts.ts@@ -12,20 +12,6 @@ export const FINALIZE_STEP_NAME = 'finalize'*/export const BASE_STEP_NAME = 'base'-/**- * Stack trace depth for capturing caller information.- *- * Depth levels:- * 1. Template function- * 2. TemplateBase class- * 3. Caller method (e.g., copy(), fromImage(), etc.)- *- * This depth is used to determine the original caller's location- * for stack traces.- * @internal- */-export const STACK_TRACE_DEPTH = 3-/*** Default setting for whether to resolve symbolic links when copying files.* When false, symlinks are copied as symlinks rather than following them.diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.tsindex 5d1176f52..48ed679c2 100644--- a/packages/js-sdk/src/template/index.ts+++ b/packages/js-sdk/src/template/index.ts@@ -16,7 +16,7 @@ import {uploadFile,waitForBuildFinish,} from './buildApi'-import { GZIP, RESOLVE_SYMLINKS, STACK_TRACE_DEPTH } from './consts'+import { GZIP, RESOLVE_SYMLINKS } from './consts'import { parseDockerfile } from './dockerfileParser'import { LogEntry, LogEntryEnd, LogEntryStart } from './logger'import { ReadyCmd, waitForFile } from './readycmd'@@ -70,15 +70,11 @@ export class TemplateBaseprivate fileIgnorePatterns: string[] = []private logsRefreshFrequency: number = 200private stackTraces: (string | undefined)[] = []- private stackTracesEnabled: boolean = true- private stackTracesOverride: string | undefined = undefinedconstructor(options?: TemplateOptions) {this.fileContextPath =options?.fileContextPath ??- (runtime === 'browser'- ? '.'- : (getCallerDirectory(STACK_TRACE_DEPTH) ?? '.'))+ (runtime === 'browser' ? '.' : (getCallerDirectory() ?? '.'))this.fileIgnorePatterns =options?.fileIgnorePatterns ?? this.fileIgnorePatterns}@@ -454,7 +450,7 @@ export class TemplateBaseif (credentials && (!credentials.username || !credentials.password)) {throw new InvalidArgumentError('Both username and password are required when providing registry credentials',- getCallerFrame(STACK_TRACE_DEPTH - 1)+ getCallerFrame())}@@ -493,11 +489,9 @@ export class TemplateBase}fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder {- const { baseImage } = this.runInStackTraceOverrideContext(- () => parseDockerfile(dockerfileContentOrPath, this),- // -1 as we're going up the call stack from the parseDockerfile function- getCallerFrame(STACK_TRACE_DEPTH - 1)- )+ // Each instruction parsed from the Dockerfile collects its own stack+ // trace, which resolves to this method's call site+ const { baseImage } = parseDockerfile(dockerfileContentOrPath, this)this.baseImage = baseImagethis.baseTemplate = undefined@@ -581,7 +575,7 @@ export class TemplateBase}const srcs = Array.isArray(src) ? src : [src]- const stackTrace = getCallerFrame(STACK_TRACE_DEPTH - 1)+ const stackTrace = getCallerFrame()for (const src of srcs) {const srcString = src.toString()@@ -619,27 +613,23 @@ export class TemplateBase}// Stack trace that will be used to re-throw the error with- const stackTrace = getCallerFrame(STACK_TRACE_DEPTH - 1)-- // 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, {- forceUpload: item.forceUpload,- user: item.user,- mode: item.mode,- resolveSymlinks: item.resolveSymlinks,- gzip: item.gzip,- })- } catch (error) {- const copyError = error as Error- copyError.stack = stackTrace- throw copyError- }+ const stackTrace = getCallerFrame()++ for (const item of items) {+ try {+ this.copy(item.src, item.dest, {+ forceUpload: item.forceUpload,+ user: item.user,+ mode: item.mode,+ resolveSymlinks: item.resolveSymlinks,+ gzip: item.gzip,+ })+ } catch (error) {+ const copyError = error as Error+ copyError.stack = stackTrace+ throw copyError}- }, stackTrace)+ }return this}@@ -657,9 +647,7 @@ export class TemplateBaseargs.push('-f')}args.push(...paths.map((p) => shellQuote(p.toString())))- return this.runInNewStackTraceContext(() =>- this.runCmd(args.join(' '), { user: options?.user })- )+ return this.runCmd(args.join(' '), { user: options?.user })}rename(@@ -671,9 +659,7 @@ export class TemplateBaseif (options?.force) {args.push('-f')}- return this.runInNewStackTraceContext(() =>- this.runCmd(args.join(' '), { user: options?.user })- )+ return this.runCmd(args.join(' '), { user: options?.user })}makeDir(@@ -686,9 +672,7 @@ export class TemplateBaseargs.push(`-m ${padOctal(options.mode)}`)}args.push(...paths.map((p) => shellQuote(p.toString())))- return this.runInNewStackTraceContext(() =>- this.runCmd(args.join(' '), { user: options?.user })- )+ return this.runCmd(args.join(' '), { user: options?.user })}makeSymlink(@@ -701,9 +685,7 @@ export class TemplateBaseargs.push('-f')}args.push(shellQuote(src.toString()), shellQuote(dest.toString()))- return this.runInNewStackTraceContext(() =>- this.runCmd(args.join(' '), { user: options?.user })- )+ return this.runCmd(args.join(' '), { user: options?.user })}runCmd(command: string, options?: { user?: string }): TemplateBuilder@@ -774,11 +756,9 @@ export class TemplateBaseargs.push('.')}- return this.runInNewStackTraceContext(() =>- this.runCmd(args.join(' '), {- user: g ? 'root' : undefined,- })- )+ return this.runCmd(args.join(' '), {+ user: g ? 'root' : undefined,+ })}npmInstall(@@ -801,11 +781,9 @@ export class TemplateBaseargs.push(...packageList)}- return this.runInNewStackTraceContext(() =>- this.runCmd(args.join(' '), {- user: options?.g ? 'root' : undefined,- })- )+ return this.runCmd(args.join(' '), {+ user: options?.g ? 'root' : undefined,+ })}bunInstall(@@ -828,11 +806,9 @@ export class TemplateBaseargs.push(...packageList)}- return this.runInNewStackTraceContext(() =>- this.runCmd(args.join(' '), {- user: options?.g ? 'root' : undefined,- })- )+ return this.runCmd(args.join(' '), {+ user: options?.g ? 'root' : undefined,+ })}aptInstall(@@ -840,16 +816,14 @@ export class TemplateBaseoptions?: { noInstallRecommends?: boolean; fixMissing?: boolean }): TemplateBuilder {const packageList = Array.isArray(packages) ? packages : [packages]- return this.runInNewStackTraceContext(() =>- this.runCmd(- [- 'apt-get update',- `DEBIAN_FRONTEND=noninteractive DEBCONF_NOWARNINGS=yes apt-get install -y ${options?.noInstallRecommends ? '--no-install-recommends ' : ''}${options?.fixMissing ? '--fix-missing ' : ''}${packageList.join(- ' '- )}`,- ],- { user: 'root' }- )+ return this.runCmd(+ [+ 'apt-get update',+ `DEBIAN_FRONTEND=noninteractive DEBCONF_NOWARNINGS=yes apt-get install -y ${options?.noInstallRecommends ? '--no-install-recommends ' : ''}${options?.fixMissing ? '--fix-missing ' : ''}${packageList.join(+ ' '+ )}`,+ ],+ { user: 'root' })}@@ -857,16 +831,14 @@ export class TemplateBaseif (this.baseTemplate !== 'mcp-gateway') {throw new BuildError('MCP servers can only be added to mcp-gateway template',- getCallerFrame(STACK_TRACE_DEPTH - 1)+ getCallerFrame())}const serverList = Array.isArray(servers) ? servers : [servers]- return this.runInNewStackTraceContext(() =>- this.runCmd(`mcp-gateway pull ${serverList.join(' ')}`, {- user: 'root',- })- )+ return this.runCmd(`mcp-gateway pull ${serverList.join(' ')}`, {+ user: 'root',+ })}gitClone(@@ -886,9 +858,7 @@ export class TemplateBaseargs.push(shellQuote(path.toString()))}- return this.runInNewStackTraceContext(() =>- this.runCmd(args.join(' '), { user: options?.user })- )+ return this.runCmd(args.join(' '), { user: options?.user })}setStartCmd(@@ -941,105 +911,45 @@ export class TemplateBaseif (this.baseTemplate !== 'devcontainer') {throw new BuildError('Devcontainers can only used in the devcontainer template',- getCallerFrame(STACK_TRACE_DEPTH - 1)+ getCallerFrame())}- return this.runInNewStackTraceContext(() => {- return this.runCmd(- `devcontainer build --workspace-folder ${shellQuote(devcontainerDirectory)}`,- { user: 'root' }- )- })+ return this.runCmd(+ `devcontainer build --workspace-folder ${shellQuote(devcontainerDirectory)}`,+ { user: 'root' }+ )}betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal {if (this.baseTemplate !== 'devcontainer') {throw new BuildError('Devcontainers can only used in the devcontainer template',- getCallerFrame(STACK_TRACE_DEPTH - 1)+ getCallerFrame())}- return this.runInNewStackTraceContext(() => {- const dir = shellQuote(devcontainerDirectory)- return this.setStartCmd(- `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')- )- })+ const dir = shellQuote(devcontainerDirectory)+ return this.setStartCmd(+ `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')+ )}/*** Collect the current stack trace for debugging purposes.*- * @param stackTracesDepth Depth to traverse in the call stack- * @returns this for method chaining- */- private collectStackTrace(stackTracesDepth: number = STACK_TRACE_DEPTH) {- if (!this.stackTracesEnabled) {- return this- }-- if (this.stackTracesOverride) {- this.stackTraces.push(this.stackTracesOverride)- return this- }-- this.stackTraces.push(getCallerFrame(stackTracesDepth))- return this- }-- /**- * Temporarily disable stack trace collection.+ * The trace resolves to the first frame outside the SDK, so methods that+ * delegate to other builder methods (e.g. `remove()` → `runCmd()`) collect+ * the user's call site without any bookkeeping.** @returns this for method chaining*/- private disableStackTrace() {- this.stackTracesEnabled = false+ private collectStackTrace() {+ this.stackTraces.push(getCallerFrame())return this}- /**- * Re-enable stack trace collection.- *- * @returns this for method chaining- */- private enableStackTrace() {- this.stackTracesEnabled = true- return this- }-- /**- * Execute a function in a clean stack trace context.- *- * @param fn Function to execute- * @returns The result of the function- */- private runInNewStackTraceContext<T>(fn: () => T): T {- this.disableStackTrace()- let result: T- try {- result = fn()- } finally {- this.enableStackTrace()- }- this.collectStackTrace(STACK_TRACE_DEPTH + 1)- return result- }-- private runInStackTraceOverrideContext<T>(- fn: () => T,- stackTraceOverride: string | undefined- ): T {- this.stackTracesOverride = stackTraceOverride- try {- return fn()- } finally {- this.stackTracesOverride = undefined- }- }-/*** Convert the template to JSON representation.*diff --git a/packages/js-sdk/src/template/utils.ts b/packages/js-sdk/src/template/utils.tsindex 5eccbc5d6..868c38949 100644--- a/packages/js-sdk/src/template/utils.ts+++ b/packages/js-sdk/src/template/utils.ts@@ -3,6 +3,7 @@ import fs from 'node:fs'import os from 'node:os'import path from 'node:path'import url from 'node:url'+import { parse, type StackFrame } from 'error-stack-parser-es'import { dynamicImport } from '../utils'import { TemplateError } from '../errors'import { BASE_STEP_NAME, FINALIZE_STEP_NAME } from './consts'@@ -269,70 +270,100 @@ export async function calculateFilesHash(}/**- * Get the caller's stack trace frame at a specific depth.- *- * @param depth The depth of the stack trace to retrieve- * - Levels: caller (e.g., TemplateBase.fromImage) > original caller (e.g., user's template file)- * @returns The caller frame as a string, or undefined if not available+ * Convert a stack-trace file name to a filesystem path.+ * In ESM modules, stack frames report file:// URLs.*/-export function getCallerFrame(depth: number): string | undefined {- const stackTrace = new Error().stack- if (!stackTrace) {- return+function frameFileToPath(fileName: string): string {+ return fileName.startsWith('file:') ? url.fileURLToPath(fileName) : fileName+}++/**+ * Check whether a stack-trace file name refers to user code, i.e. a file+ * outside the SDK's own directory. Node internals (`node:*`) and native+ * frames are never user code.+ */+function isUserFile(fileName: string, sdkDir: string): boolean {+ if (fileName.startsWith('node:') || fileName === 'native') {+ return false+ }+ try {+ const relative = path.relative(+ sdkDir,+ path.dirname(frameFileToPath(fileName))+ )+ return (+ relative !== '' &&+ (relative.startsWith('..') || path.isAbsolute(relative))+ )+ } catch {+ return false}+}- const lines = stackTrace.split('\n').slice(1) // Skip the this function (getCallerFrame)- if (lines.length < depth + 1) {- return+/**+ * Capture the current stack and locate the first frame in user code.+ *+ * Frames are selected by boundary rather than by fixed depth: the SDK's own+ * directory is derived from the top frame (which is always SDK code — this+ * module), and the first frame whose file lies outside it is the user's call+ * site. This keeps the result stable when transpilers inject extra frames+ * (e.g. TS class-field initializers) or runtimes elide delegating frames+ * (e.g. Bun's tail-call elision).+ *+ * @returns Parsed frames and the index of the user's frame, -1 when no user+ * frame is identifiable (e.g. the SDK is bundled into the caller's file)+ */+function captureUserFrames(): {+ frames: StackFrame[]+ userFrameIndex: number+} {+ const frames = parse(new Error(), { allowEmpty: true })+ const ownFile = frames[0]?.fileName+ if (!ownFile) {+ return { frames, userFrameIndex: -1 }}+ const sdkDir = path.dirname(frameFileToPath(ownFile))- return lines.slice(depth).join('\n')+ const userFrameIndex = frames.findIndex(+ (frame) =>+ frame.fileName !== undefined && isUserFile(frame.fileName, sdkDir)+ )+ return { frames, userFrameIndex }}-// adopted from https://github.com/sindresorhus/callsites-export function callsites(depth: number): NodeJS.CallSite[] {- const _originalPrepareStackTrace = Error.prepareStackTrace- try {- let result: NodeJS.CallSite[] = []- Error.prepareStackTrace = (_, callSites) => {- const callSitesWithoutCurrent = callSites.slice(depth)- result = callSitesWithoutCurrent- return callSitesWithoutCurrent- }-- // Accessing `.stack` triggers `Error.prepareStackTrace` for its side effect.- // oxlint-disable-next-line no-unused-expressions- new Error().stack- return result- } finally {- Error.prepareStackTrace = _originalPrepareStackTrace+/**+ * Get the stack trace starting at the caller's frame in user code.+ *+ * @returns The stack trace starting at the user's frame, or undefined when no+ * user frame is identifiable+ */+export function getCallerFrame(): string | undefined {+ const { frames, userFrameIndex } = captureUserFrames()+ if (userFrameIndex === -1) {+ return}++ return frames+ .slice(userFrameIndex)+ .map((frame) => frame.source)+ .filter((source): source is string => source !== undefined)+ .join('\n')}/**- * Get the directory of the caller at a specific stack depth.+ * Get the directory of the caller in user code.*- * @param depth The depth of the stack trace* @returns The caller's directory path, or undefined if not available*/-export function getCallerDirectory(depth: number): string | undefined {- // +1 depth to skip this function (getCallerDirectory)- const callSites = callsites(depth + 1)- if (callSites.length === 0) {- return undefined- }-- let fileName = callSites[0].getFileName()+export function getCallerDirectory(): string | undefined {+ const { frames, userFrameIndex } = captureUserFrames()+ const fileName =+ userFrameIndex === -1 ? undefined : frames[userFrameIndex].fileNameif (!fileName) {return undefined}- // Handle file:// URLs returned by getFileName() in ESM modules- if (fileName.startsWith('file:')) {- fileName = url.fileURLToPath(fileName)- }-- return path.dirname(fileName)+ return path.dirname(frameFileToPath(fileName))}/**diff --git a/packages/js-sdk/tests/template/stacktrace.test.ts b/packages/js-sdk/tests/template/stacktrace.test.tsindex 69bab8b8c..08cf0d193 100644--- a/packages/js-sdk/tests/template/stacktrace.test.ts+++ b/packages/js-sdk/tests/template/stacktrace.test.ts@@ -36,6 +36,7 @@ const failureMap: Record<string, number | undefined> = {setUser: 1,pipInstall: 1,npmInstall: 1,+ bunInstall: 1,aptInstall: 1,gitClone: 1,setStartCmd: 1,@@ -368,6 +369,14 @@ buildTemplateTest('traces on npmInstall', async ({ buildTemplate }) => {}, 'npmInstall')})+buildTemplateTest('traces on bunInstall', async ({ buildTemplate }) => {+ let template = Template().fromBaseImage()+ template = template.skipCache().bunInstall('nonexistent-package')+ await expectToThrowAndCheckTrace(async () => {+ await buildTemplate(template, { name: 'bunInstall' })+ }, 'bunInstall')+})+buildTemplateTest('traces on aptInstall', async ({ buildTemplate }) => {let template = Template().fromBaseImage()template = template.skipCache().aptInstall('nonexistent-package')diff --git a/packages/js-sdk/tests/template/utils/getCallerDirectory.test.ts b/packages/js-sdk/tests/template/utils/getCallerDirectory.test.tsindex 8bbfdda34..e9de0910d 100644--- a/packages/js-sdk/tests/template/utils/getCallerDirectory.test.ts+++ b/packages/js-sdk/tests/template/utils/getCallerDirectory.test.ts@@ -2,16 +2,25 @@ import { expect, test } from 'vitest'import os from 'node:os'import path from 'node:path'import { fileURLToPath, pathToFileURL } from 'node:url'-import { getCallerDirectory } from '../../../src/template/utils'+import { getCallerDirectory, getCallerFrame } from '../../../src/template/utils'test('getCallerDirectory', () => {- // getCallerDirectory(1) should return the directory of the current file- // __dirname is the directory of the current file.+ // getCallerDirectory should return the directory of the first frame outside+ // the SDK — here, the current file.// Normalize before comparing: on Windows the stack-trace file name reported// by vite/vitest uses forward slashes (e.g. "D:/a/...") whereas __dirname// uses native backslashes — the directory is the same, only the separators// differ.- expect(path.normalize(getCallerDirectory(1)!)).toBe(path.normalize(__dirname))+ expect(path.normalize(getCallerDirectory()!)).toBe(path.normalize(__dirname))+})++test('getCallerFrame starts at the first frame outside the SDK', () => {+ const stackTrace = getCallerFrame()+ expect(stackTrace).toBeDefined()+ // The first returned frame must be this test file, no matter how many+ // SDK-internal (or transpiler-injected) frames sit above it.+ const firstFrame = stackTrace!.split('\n')[0]+ expect(firstFrame).toContain(path.basename(__filename))})test('getCallerDirectory handles file:// URLs from ESM modules', () => {diff --git a/packages/js-sdk/tsdown.config.ts b/packages/js-sdk/tsdown.config.tsindex 115365e95..a17d0aed4 100644--- a/packages/js-sdk/tsdown.config.ts+++ b/packages/js-sdk/tsdown.config.ts@@ -4,6 +4,9 @@ export default defineConfig({entry: { index: './src/index.ts' },target: 'es2017',format: ['esm', 'cjs'],+ // ESM-only package inlined into both output formats — our engines range+ // includes Node versions that cannot require() ESM from the CJS build.+ noExternal: ['error-stack-parser-es'],fixedExtension: false,sourcemap: true,dts: true,diff --git a/packages/python-sdk/e2b/template/consts.py b/packages/python-sdk/e2b/template/consts.pyindex f40d8382c..4f8f1f3ec 100644--- a/packages/python-sdk/e2b/template/consts.py+++ b/packages/python-sdk/e2b/template/consts.py@@ -11,18 +11,6 @@ This is the first step that sets up the base image."""BASE_STEP_NAME = "base"-"""-Stack trace depth for capturing caller information.--Depth levels:-1. TemplateClass-2. Caller method (e.g., copy(), from_image(), etc.)--This depth is used to determine the original caller's location-for stack traces.-"""-STACK_TRACE_DEPTH = 2-"""Default setting for whether to resolve symbolic links when copying files.When False, symlinks are copied as symlinks rather than following them.diff --git a/packages/python-sdk/e2b/template/main.py b/packages/python-sdk/e2b/template/main.pyindex c92e07638..d2549f05d 100644--- a/packages/python-sdk/e2b/template/main.py+++ b/packages/python-sdk/e2b/template/main.py@@ -5,7 +5,7 @@ from pathlib import Pathfrom e2b.exceptions import BuildException, InvalidArgumentException-from e2b.template.consts import STACK_TRACE_DEPTH, RESOLVE_SYMLINKS+from e2b.template.consts import RESOLVE_SYMLINKSfrom e2b.template.dockerfile_parser import parse_dockerfilefrom e2b.template.readycmd import ReadyCmd, wait_for_filefrom e2b.template.types import (@@ -70,7 +70,7 @@ class TemplateBuilder:srcs = [src] if isinstance(src, (str, Path)) else src# Get the caller frame for stack trace in validation errors- caller_frame = get_caller_frame(STACK_TRACE_DEPTH - 1)+ caller_frame = get_caller_frame()stack_trace = make_traceback(caller_frame)for src_item in srcs:@@ -121,7 +121,7 @@ class TemplateBuilder:```"""# Get the stack trace at the copy_items call site- caller_frame = get_caller_frame(STACK_TRACE_DEPTH - 1)+ caller_frame = get_caller_frame()stack_trace = make_traceback(caller_frame)def _copy_items():@@ -142,9 +142,7 @@ class TemplateBuilder:raise error.with_traceback(stack_trace)raise- # 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)+ _copy_items()return selfdef remove(@@ -178,9 +176,7 @@ class TemplateBuilder:args.append("-f")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)- )+ return self.run_cmd(" ".join(args), user=user)def rename(self,@@ -209,9 +205,7 @@ class TemplateBuilder:if force:args.append("-f")- return self._template._run_in_new_stack_trace_context(- lambda: self.run_cmd(" ".join(args), user=user)- )+ return self.run_cmd(" ".join(args), user=user)def make_dir(self,@@ -241,9 +235,7 @@ class TemplateBuilder:args.append(f"-m {pad_octal(mode)}")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)- )+ return self.run_cmd(" ".join(args), user=user)def make_symlink(self,@@ -273,9 +265,7 @@ class TemplateBuilder:if force:args.append("-f")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)- )+ return self.run_cmd(" ".join(args), user=user)def run_cmd(self, command: Union[str, List[str]], user: Optional[str] = None@@ -387,9 +377,7 @@ class TemplateBuilder:else:args.append(".")- return self._template._run_in_new_stack_trace_context(- lambda: self.run_cmd(" ".join(args), user="root" if g else None)- )+ return self.run_cmd(" ".join(args), user="root" if g else None)def npm_install(self,@@ -425,9 +413,7 @@ class TemplateBuilder:if packages:args.extend(packages)- return self._template._run_in_new_stack_trace_context(- lambda: self.run_cmd(" ".join(args), user="root" if g else None)- )+ return self.run_cmd(" ".join(args), user="root" if g else None)def bun_install(self,@@ -450,7 +436,7 @@ class TemplateBuilder:template.bun_install(['lodash', 'axios'])template.bun_install('tsx', g=True)template.bun_install('typescript', dev=True)- template.bun_install() // Installs from package.json+ template.bun_install() # Installs from package.json```"""if isinstance(packages, str):@@ -464,9 +450,7 @@ class TemplateBuilder:if packages:args.extend(packages)- return self._template._run_in_new_stack_trace_context(- lambda: self.run_cmd(" ".join(args), user="root" if g else None)- )+ return self.run_cmd(" ".join(args), user="root" if g else None)def apt_install(self,@@ -493,14 +477,12 @@ class TemplateBuilder:if isinstance(packages, str):packages = [packages]- return self._template._run_in_new_stack_trace_context(- lambda: self.run_cmd(- [- "apt-get update",- f"DEBIAN_FRONTEND=noninteractive DEBCONF_NOWARNINGS=yes apt-get install -y {'--no-install-recommends ' if no_install_recommends else ''}{'--fix-missing ' if fix_missing else ''}{' '.join(packages)}",- ],- user="root",- )+ return self.run_cmd(+ [+ "apt-get update",+ f"DEBIAN_FRONTEND=noninteractive DEBCONF_NOWARNINGS=yes apt-get install -y {'--no-install-recommends ' if no_install_recommends else ''}{'--fix-missing ' if fix_missing else ''}{' '.join(packages)}",+ ],+ user="root",)def add_mcp_server(self, servers: Union[str, List[str]]) -> "TemplateBuilder":@@ -520,7 +502,7 @@ class TemplateBuilder:```"""if self._template._base_template != "mcp-gateway":- caller_frame = get_caller_frame(STACK_TRACE_DEPTH - 1)+ caller_frame = get_caller_frame()stack_trace = make_traceback(caller_frame)raise BuildException("MCP servers can only be added to mcp-gateway template"@@ -529,9 +511,7 @@ class TemplateBuilder:if isinstance(servers, str):servers = [servers]- return self._template._run_in_new_stack_trace_context(- lambda: self.run_cmd(f"mcp-gateway pull {' '.join(servers)}", user="root")- )+ return self.run_cmd(f"mcp-gateway pull {' '.join(servers)}", user="root")def git_clone(self,@@ -567,9 +547,7 @@ class TemplateBuilder:args.append(f"--depth {depth}")if path:args.append(shlex.quote(str(path)))- return self._template._run_in_new_stack_trace_context(- lambda: self.run_cmd(" ".join(args), user=user)- )+ return self.run_cmd(" ".join(args), user=user)def beta_dev_container_prebuild(self,@@ -589,17 +567,15 @@ class TemplateBuilder:```"""if self._template._base_template != "devcontainer":- caller_frame = get_caller_frame(STACK_TRACE_DEPTH - 1)+ caller_frame = get_caller_frame()stack_trace = make_traceback(caller_frame)raise BuildException("Devcontainers can only used in the devcontainer template").with_traceback(stack_trace)- return self._template._run_in_new_stack_trace_context(- lambda: self.run_cmd(- f"devcontainer build --workspace-folder {shlex.quote(str(devcontainer_directory))}",- user="root",- )+ return self.run_cmd(+ f"devcontainer build --workspace-folder {shlex.quote(str(devcontainer_directory))}",+ user="root",)def beta_set_dev_container_start(@@ -628,7 +604,7 @@ class TemplateBuilder:```"""if self._template._base_template != "devcontainer":- caller_frame = get_caller_frame(STACK_TRACE_DEPTH - 1)+ caller_frame = get_caller_frame()stack_trace = make_traceback(caller_frame)raise BuildException("Devcontainers can only used in the devcontainer template"@@ -645,7 +621,7 @@ class TemplateBuilder:wait_for_file("/devcontainer.up"),)- return self._template._run_in_new_stack_trace_context(_set_start)+ return _set_start()def set_envs(self, envs: Dict[str, str]) -> "TemplateBuilder":"""@@ -806,12 +782,10 @@ class TemplateBase:self._file_context_path = (file_context_path.as_posix()if isinstance(file_context_path, Path)- else (file_context_path or get_caller_directory(STACK_TRACE_DEPTH) or ".")+ else (file_context_path or get_caller_directory() or "."))self._file_ignore_patterns: List[str] = file_ignore_patterns or []self._stack_traces: List[Union[TracebackType, None]] = []- self._stack_traces_enabled: bool = True- self._stack_traces_override: Optional[Union[TracebackType, None]] = Nonedef skip_cache(self) -> "TemplateBase":"""@@ -827,79 +801,20 @@ class TemplateBase:self._force_next_layer = Truereturn self- def _collect_stack_trace(- self, stack_traces_depth: int = STACK_TRACE_DEPTH- ) -> "TemplateBase":+ def _collect_stack_trace(self) -> "TemplateBase":"""Collect the current stack trace for debugging purposes.- :param stack_traces_depth: Depth to traverse in the call stack+ The trace resolves to the first frame outside the SDK, so methods that+ delegate to other builder methods (e.g. ``remove()`` -> ``run_cmd()``)+ collect the user's call site without any bookkeeping.:return: `TemplateBase` class"""- if not self._stack_traces_enabled:- return self-- # Use the override if set, otherwise get the caller frame- if self._stack_traces_override is not None:- self._stack_traces.append(self._stack_traces_override)- return self-- stack = get_caller_frame(stack_traces_depth)+ stack = get_caller_frame()self._stack_traces.append(make_traceback(stack))return self- def _disable_stack_trace(self) -> "TemplateBase":- """- Temporarily disable stack trace collection.-- :return: `TemplateBase` class- """- self._stack_traces_enabled = False- return self-- def _enable_stack_trace(self) -> "TemplateBase":- """- Re-enable stack trace collection.-- :return: `TemplateBase` class- """- self._stack_traces_enabled = True- return self-- def _run_in_new_stack_trace_context(self, fn):- """- Execute a function in a clean stack trace context.-- :param fn: Function to execute-- :return: The result of the function- """- self._disable_stack_trace()- try:- result = fn()- finally:- self._enable_stack_trace()- self._collect_stack_trace(STACK_TRACE_DEPTH + 1)- return result-- def _run_in_stack_trace_override_context(- self, fn, stack_trace_override: Optional[Union[TracebackType, None]]- ):- """- Execute a function with a manual stack trace override.-- :param fn: Function to execute- :param stack_trace_override: Stack trace to use instead of auto-collecting-- :return: The result of the function- """- self._stack_traces_override = stack_trace_override- try:- return fn()- finally:- self._stack_traces_override = None-# Built-in image mixinsdef from_debian_image(self, variant: str = "stable") -> TemplateBuilder:"""@@ -914,9 +829,7 @@ class TemplateBase:Template().from_debian_image('bookworm')```"""- return self._run_in_new_stack_trace_context(- lambda: self.from_image(f"debian:{variant}")- )+ return self.from_image(f"debian:{variant}")def from_ubuntu_image(self, variant: str = "latest") -> TemplateBuilder:"""@@ -931,9 +844,7 @@ class TemplateBase:Template().from_ubuntu_image('24.04')```"""- return self._run_in_new_stack_trace_context(- lambda: self.from_image(f"ubuntu:{variant}")- )+ return self.from_image(f"ubuntu:{variant}")def from_python_image(self, version: str = "3") -> TemplateBuilder:"""@@ -948,9 +859,7 @@ class TemplateBase:Template().from_python_image('3')```"""- return self._run_in_new_stack_trace_context(- lambda: self.from_image(f"python:{version}")- )+ return self.from_image(f"python:{version}")def from_node_image(self, variant: str = "lts") -> TemplateBuilder:"""@@ -965,9 +874,7 @@ class TemplateBase:Template().from_node_image('24')```"""- return self._run_in_new_stack_trace_context(- lambda: self.from_image(f"node:{variant}")- )+ return self.from_image(f"node:{variant}")def from_bun_image(self, variant: str = "latest") -> TemplateBuilder:"""@@ -977,9 +884,7 @@ class TemplateBase::return: `TemplateBuilder` class"""- return self._run_in_new_stack_trace_context(- lambda: self.from_image(f"oven/bun:{variant}")- )+ return self.from_image(f"oven/bun:{variant}")def from_base_image(self) -> TemplateBuilder:"""@@ -992,9 +897,7 @@ class TemplateBase:Template().from_base_image()```"""- return self._run_in_new_stack_trace_context(- lambda: self.from_image(self._default_base_image)- )+ return self.from_image(self._default_base_image)def from_image(self,@@ -1022,7 +925,7 @@ class TemplateBase:# Validate (and resolve the registry config) before mutating the builder.if username is not None or password is not None:if not username or not password:- caller_frame = get_caller_frame(STACK_TRACE_DEPTH - 1)+ caller_frame = get_caller_frame()stack_trace = make_traceback(caller_frame)raise InvalidArgumentException("Both username and password are required when providing registry credentials"@@ -1084,16 +987,10 @@ class TemplateBase:# Create a TemplateBuilder first to use its methodsbuilder = TemplateBuilder(self)- # Get the caller frame to use for stack trace override- # -1 as we're going up the call stack from the parse_dockerfile function- caller_frame = get_caller_frame(STACK_TRACE_DEPTH - 1)- stack_trace_override = make_traceback(caller_frame)-- # Parse the dockerfile using the builder as the interface- base_image = self._run_in_stack_trace_override_context(- lambda: parse_dockerfile(dockerfile_content_or_path, builder),- stack_trace_override,- )+ # Parse the dockerfile using the builder as the interface. Each parsed+ # instruction collects its own stack trace, which resolves to this+ # method's call site+ base_image = parse_dockerfile(dockerfile_content_or_path, builder)self._base_image = base_image# If we should force the next layer and it's a FROM command, invalidate whole templatediff --git a/packages/python-sdk/e2b/template/utils.py b/packages/python-sdk/e2b/template/utils.pyindex fc54936b1..8a1d4a165 100644--- a/packages/python-sdk/e2b/template/utils.py+++ b/packages/python-sdk/e2b/template/utils.py@@ -324,37 +324,55 @@ def strip_ansi_escape_codes(text: str) -> str:return ansi_escape.sub("", text)-def get_caller_frame(depth: int) -> Optional[FrameType]:+# Root directory of the e2b package, used as the boundary between SDK frames+# and user frames when capturing stack traces.+_SDK_ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+++def _is_user_file(filename: str) -> bool:+ """Check whether a frame's file lies outside the SDK package."""+ try:+ return (+ os.path.commonpath([_SDK_ROOT_DIR, os.path.abspath(filename)])+ != _SDK_ROOT_DIR+ )+ except ValueError:+ # Different drives on Windows — outside the SDK+ return True+++def get_caller_frame() -> Optional[FrameType]:"""- Get the caller's stack frame at a specific depth.+ Get the caller's stack frame in user code.This is used to provide better error messages and debugging informationby tracking where template methods were called from in user code.- :param depth: The depth of the stack trace to retrieve+ The caller is the first frame whose file lies outside the SDK package.+ Selecting frames by boundary rather than by fixed depth keeps the result+ stable no matter how many SDK-internal frames sit in between.:return: The caller frame, or None if not available"""- stack = inspect.stack()[1:]- if len(stack) < depth + 1:- return None- return stack[depth].frame+ frame = inspect.currentframe()+ while frame is not None:+ if _is_user_file(frame.f_code.co_filename):+ return frame+ frame = frame.f_back+ return None-def get_caller_directory(depth: int) -> Optional[str]:+def get_caller_directory() -> Optional[str]:"""- Get the directory of the caller at a specific stack depth.+ Get the directory of the caller in user code.This is used to determine the file_context_path when creating a template,so file paths are resolved relative to the user's template file location.- :param depth: The depth of the stack trace-:return: The caller's directory path, or None if not available"""try:- # Get the stack trace- caller_frame = get_caller_frame(depth)+ caller_frame = get_caller_frame()if caller_frame is None:return Nonediff --git a/packages/python-sdk/tests/async/template_async/test_stacktrace.py b/packages/python-sdk/tests/async/template_async/test_stacktrace.pyindex 47cef087b..63c3e5e7a 100644--- a/packages/python-sdk/tests/async/template_async/test_stacktrace.py+++ b/packages/python-sdk/tests/async/template_async/test_stacktrace.py@@ -38,6 +38,7 @@ failure_map: dict[str, Optional[int]] = {"set_user": 1,"pip_install": 1,"npm_install": 1,+ "bun_install": 1,"apt_install": 1,"git_clone": 1,"set_start_cmd": 1,@@ -363,6 +364,16 @@ async def test_traces_on_npm_install(async_build):)[email protected]_debug()+async def test_traces_on_bun_install(async_build):+ template = AsyncTemplate()+ template = template.from_base_image()+ template = template.skip_cache().bun_install("nonexistent-package")+ await _expect_to_throw_and_check_trace(+ lambda: async_build(template, name="bun_install"), "bun_install"+ )++@pytest.mark.skip_debug()async def test_traces_on_apt_install(async_build):template = AsyncTemplate()diff --git a/packages/python-sdk/tests/shared/template/utils/test_get_caller_directory.py b/packages/python-sdk/tests/shared/template/utils/test_get_caller_directory.pyindex ba3141393..f384ec1ea 100644--- a/packages/python-sdk/tests/shared/template/utils/test_get_caller_directory.py+++ b/packages/python-sdk/tests/shared/template/utils/test_get_caller_directory.py@@ -1,6 +1,14 @@import os-from e2b.template.utils import get_caller_directory+from e2b.template.utils import get_caller_directory, get_caller_framedef test_get_caller_directory():- assert get_caller_directory(1) == os.path.dirname(__file__)+ assert get_caller_directory() == os.path.dirname(os.path.abspath(__file__))+++def test_get_caller_frame_returns_first_frame_outside_sdk():+ frame = get_caller_frame()+ assert frame is not None+ # The returned frame must be this test file, no matter how many+ # SDK-internal frames sit above it.+ assert frame.f_code.co_filename == os.path.abspath(__file__)diff --git a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.pyindex 8d1fa7120..f416c84ee 100644--- a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py+++ b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py@@ -38,6 +38,7 @@ failure_map: dict[str, Optional[int]] = {"set_user": 1,"pip_install": 1,"npm_install": 1,+ "bun_install": 1,"apt_install": 1,"git_clone": 1,"set_start_cmd": 1,@@ -359,6 +360,16 @@ def test_traces_on_npm_install(build):)[email protected]_debug()+def test_traces_on_bun_install(build):+ template = Template()+ template = template.from_base_image()+ template = template.skip_cache().bun_install("nonexistent-package")+ _expect_to_throw_and_check_trace(+ lambda: build(template, name="bun_install"), "bun_install"+ )++@pytest.mark.skip_debug()def test_traces_on_apt_install(build):template = Template()diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4324066af..7dd335ea8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -204,6 +204,9 @@ importers:dotenv:specifier: ^16.4.5version: 16.4.5+ error-stack-parser-es:+ specifier: ^2.0.1+ version: 2.0.1json-schema-to-typescript:specifier: ^15.0.4version: 15.0.4@@ -2324,6 +2327,9 @@ packages:resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==}+ resolution: {integrity: sha512-J36ntO+rMQVRuR/umlmxmfLi4TpWwtmTnHoJoXTiC2xDNazs0VDPKcX6pbhZMDd2HFtH9isMBJXMdbki+A++Pg==}+resolution: {integrity: sha512-WSzPgsdLtTcQwm4CROfS5ju2Wa1QQcVeT37jFjYzdFz1r9ahadC8B8/a4qxJxM+09F18iumCdRmlr96ZYkQvEg==}engines: {node: '>= 0.4'}@@ -5786,6 +5792,8 @@ snapshots:+ [email protected]: {}+dependencies:array-buffer-byte-length: 1.0.2