Skip to content

cloudflare_provider

Class info

Re-exported classes

Class Module Description
CloudflareExecutionEnvironment exxec.cloudflare_provider.provider Executes code in a Cloudflare Worker sandbox via HTTP API.

🛈 DocStrings

Cloudflare sandbox execution environment using Cloudflare Workers.

CloudflareExecutionEnvironment

Bases: ExecutionEnvironment

Executes code in a Cloudflare Worker sandbox via HTTP API.

Requires a deployed Cloudflare Sandbox Worker that exposes the standard sandbox HTTP API (session/create, execute, file/write, etc.).

Source code in src/exxec/cloudflare_provider/provider.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
class CloudflareExecutionEnvironment(ExecutionEnvironment):
    """Executes code in a Cloudflare Worker sandbox via HTTP API.

    Requires a deployed Cloudflare Sandbox Worker that exposes the
    standard sandbox HTTP API (session/create, execute, file/write, etc.).
    """

    def __init__(
        self,
        lifespan_handler: AbstractAsyncContextManager[ServerInfo] | None = None,
        dependencies: list[str] | None = None,
        base_url: str = "",
        api_token: str | None = None,
        account_id: str | None = None,
        session_id: str | None = None,
        timeout: float = 30.0,
        default_command_timeout: float | None = None,
        language: Language = "python",
        cwd: str | None = None,
        env_vars: dict[str, str] | None = None,
        inherit_env: bool = False,
    ) -> None:
        """Initialize Cloudflare sandbox environment.

        Args:
            lifespan_handler: Async context manager for tool server (optional)
            dependencies: List of packages to install via pip / npm
            base_url: Base URL of the Cloudflare Sandbox Worker deployment
            api_token: API token for authentication (optional)
            account_id: Cloudflare account ID (optional)
            session_id: Explicit session ID (auto-generated if None)
            timeout: HTTP request timeout in seconds
            default_command_timeout: Default timeout for command execution in seconds.
                If None, commands run without timeout unless explicitly specified.
            language: Programming language to use
            cwd: Working directory for the sandbox
            env_vars: Environment variables to set for all executions
            inherit_env: If True, inherit environment variables from os.environ
        """
        super().__init__(
            lifespan_handler=lifespan_handler,
            dependencies=dependencies,
            cwd=cwd,
            env_vars=env_vars,
            inherit_env=inherit_env,
            default_command_timeout=default_command_timeout,
        )
        self.base_url = base_url.rstrip("/")
        self.api_token = api_token
        self.account_id = account_id
        self.session_id = session_id or f"exxec-{uuid.uuid4().hex[:12]}"
        self.timeout = timeout
        self.language: Language = language
        self._client: httpx2.AsyncClient | None = None
        # Cloudflare sandboxes run Linux
        self._os_type = "Linux"

    def _get_headers(self) -> dict[str, str]:
        """Build HTTP headers for API requests."""
        headers: dict[str, str] = {"Content-Type": "application/json"}
        if self.api_token:
            headers["Authorization"] = f"Bearer {self.api_token}"
        if self.account_id:
            headers["CF-Account-ID"] = self.account_id
        return headers

    def get_fs(self) -> CloudflareFS:
        """Return a CloudflareFS instance for the sandbox."""
        from upathtools.filesystems import CloudflareFS

        return CloudflareFS(
            base_url=self.base_url,
            session_id=self.session_id,
            api_token=self.api_token,
            account_id=self.account_id,
            working_dir=self.cwd or "/workspace",
        )

    def _ensure_client(self) -> httpx2.AsyncClient:
        """Ensure the HTTP client is initialized."""
        if self._client is None:
            raise NotInitializedError("CloudFlare")
        return self._client

    async def _post(self, path: str, *, payload: dict[str, Any] | None = None) -> dict[str, Any]:
        """Make a POST request to the sandbox API."""
        client = self._ensure_client()
        url = f"{self.base_url}{path}"
        response = await client.post(url, json=payload, headers=self._get_headers())
        if response.status_code >= _HTTP_ERROR_THRESHOLD:
            msg = f"Cloudflare API error ({response.status_code}): {response.text}"
            raise RuntimeError(msg)
        if response.headers.get("content-type", "").startswith("application/json"):
            return response.json()  # type: ignore[no-any-return]
        return {}

    async def _get(self, path: str) -> dict[str, Any]:
        """Make a GET request to the sandbox API."""
        client = self._ensure_client()
        url = f"{self.base_url}{path}"
        response = await client.get(url, headers=self._get_headers())
        if response.status_code >= _HTTP_ERROR_THRESHOLD:
            msg = f"Cloudflare API error ({response.status_code}): {response.text}"
            raise RuntimeError(msg)
        if response.headers.get("content-type", "").startswith("application/json"):
            return response.json()  # type: ignore[no-any-return]
        return {}

    async def __aenter__(self) -> Self:
        """Setup Cloudflare sandbox session."""
        await super().__aenter__()
        import httpx2

        self._client = httpx2.AsyncClient(timeout=httpx2.Timeout(self.timeout))

        # Create the session
        payload: dict[str, Any] = {
            "id": self.session_id,
            "env": self.env_vars or {},
            "cwd": self.cwd or "/workspace",
            "isolation": True,
        }
        await self._post("/api/session/create", payload=payload)

        # Install dependencies
        if self.dependencies:
            deps_str = " ".join(self.dependencies)
            match self.language:
                case "python":
                    await self._execute_raw(f"pip install {deps_str}")
                case "javascript" | "typescript":
                    await self._execute_raw(f"npm install {deps_str}")

        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Cleanup sandbox session."""
        if self._client:
            with contextlib.suppress(Exception):
                # Kill all processes in the session
                url = f"{self.base_url}/api/process/kill-all"
                await self._client.delete(
                    url,
                    params={"session": self.session_id},
                    headers=self._get_headers(),
                )
            with contextlib.suppress(Exception):
                await self._client.aclose()
            self._client = None
        await super().__aexit__(exc_type, exc_val, exc_tb)

    async def _execute_raw(self, command: str) -> dict[str, Any]:
        """Execute a raw command in the sandbox, returning the API response."""
        env = self.get_env()
        command_to_run = _apply_env_vars_to_command(command, env)
        return await self._post(
            "/api/execute",
            payload={"id": self.session_id, "command": command_to_run},
        )

    async def execute(self, code: str) -> ExecutionResult:
        """Execute code in the Cloudflare sandbox."""
        start_time = time.time()
        try:
            wrapped_code = wrap_code(code, language=self.language)
            script_path = get_script_path(self.language)

            # Write the script file
            await self._post(
                "/api/file/write",
                payload={
                    "id": self.session_id,
                    "path": script_path,
                    "content": wrapped_code,
                },
            )

            # Execute the script
            command = _get_execution_command(self.language, script_path)
            data = await self._execute_raw(command)

            stdout = data.get("stdout", "")
            stderr = data.get("stderr", "")
            exit_code = data.get("exitCode", data.get("exit_code", 0))

            execution_result, error_info = parse_output(stdout)
            if exit_code == 0 and error_info is None:
                return ExecutionResult(
                    result=execution_result,
                    duration=time.time() - start_time,
                    success=True,
                    exit_code=exit_code,
                    stdout=stdout,
                    stderr=stderr,
                )

            return ExecutionResult(
                result=None,
                duration=time.time() - start_time,
                success=False,
                exit_code=exit_code,
                error=(error_info or {}).get("error", "Command execution failed"),
                error_type=(error_info or {}).get("type", "ExecutionError"),
                stdout=stdout,
                stderr=stderr,
            )

        except Exception as e:  # noqa: BLE001
            return ExecutionResult.failed(e, start_time)

    async def execute_command(
        self,
        command: str,
        *,
        timeout: float | None = None,
    ) -> ExecutionResult:
        """Execute a terminal command in the Cloudflare sandbox."""
        start_time = time.time()
        try:
            data = await self._execute_raw(command)
            stdout = data.get("stdout", "")
            stderr = data.get("stderr", "")
            exit_code = data.get("exitCode", data.get("exit_code", 0))
            success = exit_code == 0
            return ExecutionResult(
                result=stdout if success else None,
                duration=time.time() - start_time,
                success=success,
                error=stderr if not success else None,
                error_type="CommandError" if not success else None,
                stdout=stdout,
                stderr=stderr,
                exit_code=exit_code,
            )
        except Exception as e:  # noqa: BLE001
            return ExecutionResult.failed(e, start_time)

    async def stream_code(self, code: str) -> AsyncIterator[ExecutionEvent]:
        """Execute code and stream events in the Cloudflare sandbox."""
        import httpx2

        process_id = f"cf_{self.session_id}"
        wrapped_code = wrap_code(code, language=self.language)
        script_path = get_script_path(self.language)

        # Write the script file
        await self._post(
            "/api/file/write",
            payload={
                "id": self.session_id,
                "path": script_path,
                "content": wrapped_code,
            },
        )

        command = _get_execution_command(self.language, script_path)
        yield ProcessStartedEvent(process_id=process_id, command=f"execute({len(code)} chars)")

        try:
            # Try SSE streaming first
            client = self._ensure_client()
            url = f"{self.base_url}/api/execute/stream"
            env = self.get_env()
            command_to_run = _apply_env_vars_to_command(command, env)
            payload = {"id": self.session_id, "command": command_to_run}
            headers = {**self._get_headers(), "Accept": "text/event-stream"}

            async with client.stream(
                "POST",
                url,
                json=payload,
                headers=headers,
            ) as response:
                if response.status_code == _HTTP_NOT_FOUND:
                    # SSE not supported, fall back to regular execution
                    async for event in self._stream_fallback(command, process_id):
                        yield event
                    return

                response.raise_for_status()
                async for line in response.aiter_lines():
                    if not line.startswith("data: "):
                        continue
                    data = line[6:]
                    if data == "[DONE]":
                        break
                    try:
                        event_data = anyenv.load_json(data, return_type=dict)
                        if "stdout" in event_data:
                            yield OutputEvent(
                                process_id=process_id,
                                data=event_data["stdout"],
                                stream="stdout",
                            )
                        if "stderr" in event_data:
                            yield OutputEvent(
                                process_id=process_id,
                                data=event_data["stderr"],
                                stream="stderr",
                            )
                    except anyenv.JsonLoadError:
                        yield OutputEvent(process_id=process_id, data=data, stream="stdout")

                yield ProcessCompletedEvent(process_id=process_id, exit_code=0)

        except httpx2.HTTPError:
            # Fall back to regular execution on HTTP errors
            async for event in self._stream_fallback(command, process_id):
                yield event
        except Exception as e:  # noqa: BLE001
            yield ProcessErrorEvent.failed(e, process_id=process_id)

    async def _stream_fallback(
        self,
        command: str,
        process_id: str,
    ) -> AsyncIterator[ExecutionEvent]:
        """Fallback streaming by running command and splitting output."""
        try:
            data = await self._execute_raw(command)
            stdout = data.get("stdout", "")
            stderr = data.get("stderr", "")
            exit_code = data.get("exitCode", data.get("exit_code", 0))

            if stdout:
                for line in stdout.splitlines():
                    if line:
                        yield OutputEvent(process_id=process_id, data=line, stream="stdout")
            if stderr:
                for line in stderr.splitlines():
                    if line:
                        yield OutputEvent(process_id=process_id, data=line, stream="stderr")

            if exit_code != 0:
                yield ProcessErrorEvent(
                    process_id=process_id,
                    error=stderr or f"Command exited with code {exit_code}",
                    error_type="ExecutionError",
                    exit_code=exit_code,
                )
            else:
                yield ProcessCompletedEvent(process_id=process_id, exit_code=0)
        except Exception as e:  # noqa: BLE001
            yield ProcessErrorEvent.failed(e, process_id=process_id)

    async def stream_command(
        self,
        command: str,
        *,
        timeout: float | None = None,
    ) -> AsyncIterator[ExecutionEvent]:
        """Execute a terminal command and stream events in the Cloudflare sandbox."""
        import httpx2

        process_id = f"cf_cmd_{self.session_id}"
        yield ProcessStartedEvent(process_id=process_id, command=command)

        try:
            # Try SSE streaming first
            client = self._ensure_client()
            url = f"{self.base_url}/api/execute/stream"
            env = self.get_env()
            command_to_run = _apply_env_vars_to_command(command, env)
            payload = {"id": self.session_id, "command": command_to_run}
            headers = {**self._get_headers(), "Accept": "text/event-stream"}

            async with client.stream("POST", url, json=payload, headers=headers) as response:
                if response.status_code == _HTTP_NOT_FOUND:
                    async for event in self._stream_fallback(command, process_id):
                        yield event
                    return

                response.raise_for_status()
                async for line in response.aiter_lines():
                    if not line.startswith("data: "):
                        continue
                    data = line[6:]
                    if data == "[DONE]":
                        break
                    try:
                        event_data = anyenv.load_json(data, return_type=dict)
                        if "stdout" in event_data:
                            yield OutputEvent(
                                process_id=process_id,
                                data=event_data["stdout"],
                                stream="stdout",
                            )
                        if "stderr" in event_data:
                            yield OutputEvent(
                                process_id=process_id,
                                data=event_data["stderr"],
                                stream="stderr",
                            )
                    except anyenv.JsonLoadError:
                        yield OutputEvent(
                            process_id=process_id,
                            data=data,
                            stream="stdout",
                        )

                yield ProcessCompletedEvent(process_id=process_id, exit_code=0)

        except httpx2.HTTPError:
            async for event in self._stream_fallback(command, process_id):
                yield event
        except Exception as e:  # noqa: BLE001
            yield ProcessErrorEvent.failed(e, process_id=process_id)

    async def set_file_content(self, path: str, content: str | bytes) -> None:
        """Set file content in the Cloudflare sandbox."""
        text = content.decode("utf-8") if isinstance(content, bytes) else content
        await self._post(
            "/api/file/write",
            payload={"id": self.session_id, "path": path, "content": text},
        )

    async def get_file_content(self, path: str) -> bytes:
        """Get file content from the Cloudflare sandbox."""
        data = await self._post(
            "/api/file/read",
            payload={"id": self.session_id, "path": path},
        )
        content = data.get("content", "")
        return content.encode("utf-8") if isinstance(content, str) else content

__aenter__ async

__aenter__() -> Self

Setup Cloudflare sandbox session.

Source code in src/exxec/cloudflare_provider/provider.py
async def __aenter__(self) -> Self:
    """Setup Cloudflare sandbox session."""
    await super().__aenter__()
    import httpx2

    self._client = httpx2.AsyncClient(timeout=httpx2.Timeout(self.timeout))

    # Create the session
    payload: dict[str, Any] = {
        "id": self.session_id,
        "env": self.env_vars or {},
        "cwd": self.cwd or "/workspace",
        "isolation": True,
    }
    await self._post("/api/session/create", payload=payload)

    # Install dependencies
    if self.dependencies:
        deps_str = " ".join(self.dependencies)
        match self.language:
            case "python":
                await self._execute_raw(f"pip install {deps_str}")
            case "javascript" | "typescript":
                await self._execute_raw(f"npm install {deps_str}")

    return self

__aexit__ async

__aexit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Cleanup sandbox session.

Source code in src/exxec/cloudflare_provider/provider.py
async def __aexit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None:
    """Cleanup sandbox session."""
    if self._client:
        with contextlib.suppress(Exception):
            # Kill all processes in the session
            url = f"{self.base_url}/api/process/kill-all"
            await self._client.delete(
                url,
                params={"session": self.session_id},
                headers=self._get_headers(),
            )
        with contextlib.suppress(Exception):
            await self._client.aclose()
        self._client = None
    await super().__aexit__(exc_type, exc_val, exc_tb)

__init__

__init__(
    lifespan_handler: AbstractAsyncContextManager[ServerInfo] | None = None,
    dependencies: list[str] | None = None,
    base_url: str = "",
    api_token: str | None = None,
    account_id: str | None = None,
    session_id: str | None = None,
    timeout: float = 30.0,
    default_command_timeout: float | None = None,
    language: Language = "python",
    cwd: str | None = None,
    env_vars: dict[str, str] | None = None,
    inherit_env: bool = False,
) -> None

Initialize Cloudflare sandbox environment.

Parameters:

Name Type Description Default
lifespan_handler AbstractAsyncContextManager[ServerInfo] | None

Async context manager for tool server (optional)

None
dependencies list[str] | None

List of packages to install via pip / npm

None
base_url str

Base URL of the Cloudflare Sandbox Worker deployment

''
api_token str | None

API token for authentication (optional)

None
account_id str | None

Cloudflare account ID (optional)

None
session_id str | None

Explicit session ID (auto-generated if None)

None
timeout float

HTTP request timeout in seconds

30.0
default_command_timeout float | None

Default timeout for command execution in seconds. If None, commands run without timeout unless explicitly specified.

None
language Language

Programming language to use

'python'
cwd str | None

Working directory for the sandbox

None
env_vars dict[str, str] | None

Environment variables to set for all executions

None
inherit_env bool

If True, inherit environment variables from os.environ

False
Source code in src/exxec/cloudflare_provider/provider.py
def __init__(
    self,
    lifespan_handler: AbstractAsyncContextManager[ServerInfo] | None = None,
    dependencies: list[str] | None = None,
    base_url: str = "",
    api_token: str | None = None,
    account_id: str | None = None,
    session_id: str | None = None,
    timeout: float = 30.0,
    default_command_timeout: float | None = None,
    language: Language = "python",
    cwd: str | None = None,
    env_vars: dict[str, str] | None = None,
    inherit_env: bool = False,
) -> None:
    """Initialize Cloudflare sandbox environment.

    Args:
        lifespan_handler: Async context manager for tool server (optional)
        dependencies: List of packages to install via pip / npm
        base_url: Base URL of the Cloudflare Sandbox Worker deployment
        api_token: API token for authentication (optional)
        account_id: Cloudflare account ID (optional)
        session_id: Explicit session ID (auto-generated if None)
        timeout: HTTP request timeout in seconds
        default_command_timeout: Default timeout for command execution in seconds.
            If None, commands run without timeout unless explicitly specified.
        language: Programming language to use
        cwd: Working directory for the sandbox
        env_vars: Environment variables to set for all executions
        inherit_env: If True, inherit environment variables from os.environ
    """
    super().__init__(
        lifespan_handler=lifespan_handler,
        dependencies=dependencies,
        cwd=cwd,
        env_vars=env_vars,
        inherit_env=inherit_env,
        default_command_timeout=default_command_timeout,
    )
    self.base_url = base_url.rstrip("/")
    self.api_token = api_token
    self.account_id = account_id
    self.session_id = session_id or f"exxec-{uuid.uuid4().hex[:12]}"
    self.timeout = timeout
    self.language: Language = language
    self._client: httpx2.AsyncClient | None = None
    # Cloudflare sandboxes run Linux
    self._os_type = "Linux"

execute async

execute(code: str) -> ExecutionResult

Execute code in the Cloudflare sandbox.

Source code in src/exxec/cloudflare_provider/provider.py
async def execute(self, code: str) -> ExecutionResult:
    """Execute code in the Cloudflare sandbox."""
    start_time = time.time()
    try:
        wrapped_code = wrap_code(code, language=self.language)
        script_path = get_script_path(self.language)

        # Write the script file
        await self._post(
            "/api/file/write",
            payload={
                "id": self.session_id,
                "path": script_path,
                "content": wrapped_code,
            },
        )

        # Execute the script
        command = _get_execution_command(self.language, script_path)
        data = await self._execute_raw(command)

        stdout = data.get("stdout", "")
        stderr = data.get("stderr", "")
        exit_code = data.get("exitCode", data.get("exit_code", 0))

        execution_result, error_info = parse_output(stdout)
        if exit_code == 0 and error_info is None:
            return ExecutionResult(
                result=execution_result,
                duration=time.time() - start_time,
                success=True,
                exit_code=exit_code,
                stdout=stdout,
                stderr=stderr,
            )

        return ExecutionResult(
            result=None,
            duration=time.time() - start_time,
            success=False,
            exit_code=exit_code,
            error=(error_info or {}).get("error", "Command execution failed"),
            error_type=(error_info or {}).get("type", "ExecutionError"),
            stdout=stdout,
            stderr=stderr,
        )

    except Exception as e:  # noqa: BLE001
        return ExecutionResult.failed(e, start_time)

execute_command async

execute_command(command: str, *, timeout: float | None = None) -> ExecutionResult

Execute a terminal command in the Cloudflare sandbox.

Source code in src/exxec/cloudflare_provider/provider.py
async def execute_command(
    self,
    command: str,
    *,
    timeout: float | None = None,
) -> ExecutionResult:
    """Execute a terminal command in the Cloudflare sandbox."""
    start_time = time.time()
    try:
        data = await self._execute_raw(command)
        stdout = data.get("stdout", "")
        stderr = data.get("stderr", "")
        exit_code = data.get("exitCode", data.get("exit_code", 0))
        success = exit_code == 0
        return ExecutionResult(
            result=stdout if success else None,
            duration=time.time() - start_time,
            success=success,
            error=stderr if not success else None,
            error_type="CommandError" if not success else None,
            stdout=stdout,
            stderr=stderr,
            exit_code=exit_code,
        )
    except Exception as e:  # noqa: BLE001
        return ExecutionResult.failed(e, start_time)

get_file_content async

get_file_content(path: str) -> bytes

Get file content from the Cloudflare sandbox.

Source code in src/exxec/cloudflare_provider/provider.py
async def get_file_content(self, path: str) -> bytes:
    """Get file content from the Cloudflare sandbox."""
    data = await self._post(
        "/api/file/read",
        payload={"id": self.session_id, "path": path},
    )
    content = data.get("content", "")
    return content.encode("utf-8") if isinstance(content, str) else content

get_fs

get_fs() -> CloudflareFS

Return a CloudflareFS instance for the sandbox.

Source code in src/exxec/cloudflare_provider/provider.py
def get_fs(self) -> CloudflareFS:
    """Return a CloudflareFS instance for the sandbox."""
    from upathtools.filesystems import CloudflareFS

    return CloudflareFS(
        base_url=self.base_url,
        session_id=self.session_id,
        api_token=self.api_token,
        account_id=self.account_id,
        working_dir=self.cwd or "/workspace",
    )

set_file_content async

set_file_content(path: str, content: str | bytes) -> None

Set file content in the Cloudflare sandbox.

Source code in src/exxec/cloudflare_provider/provider.py
async def set_file_content(self, path: str, content: str | bytes) -> None:
    """Set file content in the Cloudflare sandbox."""
    text = content.decode("utf-8") if isinstance(content, bytes) else content
    await self._post(
        "/api/file/write",
        payload={"id": self.session_id, "path": path, "content": text},
    )

stream_code async

stream_code(code: str) -> AsyncIterator[ExecutionEvent]

Execute code and stream events in the Cloudflare sandbox.

Source code in src/exxec/cloudflare_provider/provider.py
async def stream_code(self, code: str) -> AsyncIterator[ExecutionEvent]:
    """Execute code and stream events in the Cloudflare sandbox."""
    import httpx2

    process_id = f"cf_{self.session_id}"
    wrapped_code = wrap_code(code, language=self.language)
    script_path = get_script_path(self.language)

    # Write the script file
    await self._post(
        "/api/file/write",
        payload={
            "id": self.session_id,
            "path": script_path,
            "content": wrapped_code,
        },
    )

    command = _get_execution_command(self.language, script_path)
    yield ProcessStartedEvent(process_id=process_id, command=f"execute({len(code)} chars)")

    try:
        # Try SSE streaming first
        client = self._ensure_client()
        url = f"{self.base_url}/api/execute/stream"
        env = self.get_env()
        command_to_run = _apply_env_vars_to_command(command, env)
        payload = {"id": self.session_id, "command": command_to_run}
        headers = {**self._get_headers(), "Accept": "text/event-stream"}

        async with client.stream(
            "POST",
            url,
            json=payload,
            headers=headers,
        ) as response:
            if response.status_code == _HTTP_NOT_FOUND:
                # SSE not supported, fall back to regular execution
                async for event in self._stream_fallback(command, process_id):
                    yield event
                return

            response.raise_for_status()
            async for line in response.aiter_lines():
                if not line.startswith("data: "):
                    continue
                data = line[6:]
                if data == "[DONE]":
                    break
                try:
                    event_data = anyenv.load_json(data, return_type=dict)
                    if "stdout" in event_data:
                        yield OutputEvent(
                            process_id=process_id,
                            data=event_data["stdout"],
                            stream="stdout",
                        )
                    if "stderr" in event_data:
                        yield OutputEvent(
                            process_id=process_id,
                            data=event_data["stderr"],
                            stream="stderr",
                        )
                except anyenv.JsonLoadError:
                    yield OutputEvent(process_id=process_id, data=data, stream="stdout")

            yield ProcessCompletedEvent(process_id=process_id, exit_code=0)

    except httpx2.HTTPError:
        # Fall back to regular execution on HTTP errors
        async for event in self._stream_fallback(command, process_id):
            yield event
    except Exception as e:  # noqa: BLE001
        yield ProcessErrorEvent.failed(e, process_id=process_id)

stream_command async

stream_command(command: str, *, timeout: float | None = None) -> AsyncIterator[ExecutionEvent]

Execute a terminal command and stream events in the Cloudflare sandbox.

Source code in src/exxec/cloudflare_provider/provider.py
async def stream_command(
    self,
    command: str,
    *,
    timeout: float | None = None,
) -> AsyncIterator[ExecutionEvent]:
    """Execute a terminal command and stream events in the Cloudflare sandbox."""
    import httpx2

    process_id = f"cf_cmd_{self.session_id}"
    yield ProcessStartedEvent(process_id=process_id, command=command)

    try:
        # Try SSE streaming first
        client = self._ensure_client()
        url = f"{self.base_url}/api/execute/stream"
        env = self.get_env()
        command_to_run = _apply_env_vars_to_command(command, env)
        payload = {"id": self.session_id, "command": command_to_run}
        headers = {**self._get_headers(), "Accept": "text/event-stream"}

        async with client.stream("POST", url, json=payload, headers=headers) as response:
            if response.status_code == _HTTP_NOT_FOUND:
                async for event in self._stream_fallback(command, process_id):
                    yield event
                return

            response.raise_for_status()
            async for line in response.aiter_lines():
                if not line.startswith("data: "):
                    continue
                data = line[6:]
                if data == "[DONE]":
                    break
                try:
                    event_data = anyenv.load_json(data, return_type=dict)
                    if "stdout" in event_data:
                        yield OutputEvent(
                            process_id=process_id,
                            data=event_data["stdout"],
                            stream="stdout",
                        )
                    if "stderr" in event_data:
                        yield OutputEvent(
                            process_id=process_id,
                            data=event_data["stderr"],
                            stream="stderr",
                        )
                except anyenv.JsonLoadError:
                    yield OutputEvent(
                        process_id=process_id,
                        data=data,
                        stream="stdout",
                    )

            yield ProcessCompletedEvent(process_id=process_id, exit_code=0)

    except httpx2.HTTPError:
        async for event in self._stream_fallback(command, process_id):
            yield event
    except Exception as e:  # noqa: BLE001
        yield ProcessErrorEvent.failed(e, process_id=process_id)