diff --git a/.agents/README.md b/.agents/README.md index 356724d..01eae03 100644 --- a/.agents/README.md +++ b/.agents/README.md @@ -1,5 +1,9 @@ # `.agents/` — engineering record of the python-sdk repository +## Alibaba Cloud Container Edition Python Provider + +[Design](notes/proposed/architecture/2026-11-24-alicloud-container-native-provider.md) · [Initial verification](evidence/verify/2026-11-24-alicloud-container-native-provider.md) · [Follow-up review and verification](evidence/verify/2026-11-24-alicloud-container-native-provider-recheck.md). + ## Recent changes — 2026-11-10 - [Owner change index](notes/proposed/process/2026-11-10-recent-change-index.md) · [records verification](evidence/verify/2026-11-10-recent-change-index.md). diff --git a/.agents/evidence/verify/2026-11-24-alicloud-container-native-provider-recheck.md b/.agents/evidence/verify/2026-11-24-alicloud-container-native-provider-recheck.md new file mode 100644 index 0000000..eb1621c --- /dev/null +++ b/.agents/evidence/verify/2026-11-24-alicloud-container-native-provider-recheck.md @@ -0,0 +1,44 @@ +# Verification: Container Edition Python Provider follow-up review + +- Date: 2026-11-24 +- Change: [PR #168](https://github.com/Alibaba-Agent-Sandbox/python-sdk/pull/168), reviewed starting revision `ab789cc27b77160aa1e9cc7f6419461fb5e0ccfc` and its follow-up patch +- Result: BLOCKED for live ACS/ACK acceptance +- Package under test: Client and Server SDK 0.4.0a7 from source, and locally built distributions +- Environment: Debian 13, Python 3.12.15 + +## What was verified + +Two independent reviews checked the Container Edition routes and SDK behavior, and checked the user guides and acceptance prerequisites. The review traced the E2B interpreter's [HTTP route](https://github.com/e2b-dev/code-interpreter/blob/db9fdb1cfe6552455d58b1690971bdd3052538c6/template/server/main.py#L81-L129) into its [response wrapper](https://github.com/e2b-dev/code-interpreter/blob/db9fdb1cfe6552455d58b1690971bdd3052538c6/template/server/stream.py#L34-L40). The wrapper emits the public `end_of_execution` event even though the inner iterator consumes its own completion message. Executing the original parser on a well-formed result-only response returned exit code zero. The follow-up rejects responses without completion, with regressions for both gateway layouts. + +## Commands run + +- From `client-sdk`: `pytest -q tests/test_providers/test_alicloud_container.py tests/test_providers/test_bound_client.py tests/test_providers/test_registry_scoping.py tests/test_providers/test_engine_alicloud_container.py` +- From the repository root: `python -m pytest e2e/test_alicloud_container_native.py e2e/test_08_providers.py -k 'alicloud_container_native or container_refuses_without' -ra` +- `make lint format-check typecheck` and `make build dist-check` +- Installed only the built Client SDK wheel in a fresh environment. Used a private-route HTTP fixture in an isolated loopback namespace with an empty executable search path. The fixture returned a completed and an incomplete interpreter response, then accepted deletion and returned 404 for the owned ID. +- `make ci` through the server test stage and `pytest -q -m "not integration"` in `client-sdk` with isolated loopback. Repeated the two failed client cases against `ab789cc` and in an isolated PID namespace on the patched revision. +- `bash scripts/check-repo-health.sh`, `make hygiene` and `git diff --check` + +## Results + +| Scenario | Result | Notes | +| --- | --- | --- | +| Provider, bound client and registry tests | PASS | 47 passed, 4 external-engine cases skipped. The new result-only NDJSON regression rejects incomplete responses. | +| Provider credential refusal | PASS | One case passed without a configured Container Edition cluster. | +| Live lifecycle and interpreter cases | BLOCKED | Two cases skipped before I/O. No Container Edition manager endpoint or Key was available from the workspace configuration or process environment. | +| Lint, formatting, types and distributions | PASS | Both packages checked. Wheel-only imports and a local HTTP packaging probe passed. | +| Installed client wheel and private HTTP route | PASS | Verified both credential audiences, completion and truncation rejection, and deletion by ID. Fixture backend. | +| Local Server unit suite | PASS | 875 passed and one skipped with isolated loopback. | +| Local Client unit suite | PARTIAL | 2,459 passed, 36 skipped, 10 deselected, and two Managed Agents timing or process-domain assertions failed with a shared PID namespace. Both reproduced at `ab789cc` and passed with isolated PIDs on the patched revision. | + +## Cleanup + +The targeted tests used controlled transports or locally owned test processes. The live cases made no requests. No cloud resources were created. + +## Problems found + +The previous interpreter fixture used HTTP EOF as a success signal. The review also found that the initial guide required Jupyter for basic use and that the provider E2E credential-refusal check assumed the container provider was an external plugin. The guides now show basic and interpreter usage separately. The live test distinguishes an ordinary SandboxSet from an interpreter SandboxSet, uses cluster-specific credential masking, and verifies absence of returned IDs against that cluster. Its cleanup does not prove absence for a create that returned no ID. + +## Not verified + +Live ACS/ACK acceptance requires an existing cluster manager endpoint, its cluster Key and a SandboxSet for each selected case. The prerequisite [PR #167](https://github.com/Alibaba-Agent-Sandbox/python-sdk/pull/167) also remains a draft. No artifacts were released. diff --git a/.agents/evidence/verify/2026-11-24-alicloud-container-native-provider.md b/.agents/evidence/verify/2026-11-24-alicloud-container-native-provider.md new file mode 100644 index 0000000..154d897 --- /dev/null +++ b/.agents/evidence/verify/2026-11-24-alicloud-container-native-provider.md @@ -0,0 +1,47 @@ +# Verification: native Python Provider for Alibaba Cloud Container Edition + +- Date: 2026-11-24 +- PR: [#168](https://github.com/Alibaba-Agent-Sandbox/python-sdk/pull/168) +- Change: `2026-11-24-alicloud-container-native-provider`; stacked on [PR #167](https://github.com/Alibaba-Agent-Sandbox/python-sdk/pull/167) at `0f229aa8b28c45f1c2998947acbff9857e411310` +- Result: BLOCKED for ACS/ACK acceptance +- Package under test: editable Client SDK and Server SDK 0.4.0a7 development checkout +- Environment: Python 3.12 on Linux; no Container Edition cluster key or target was available in the existing workspace and SDK configuration + +## What was verified + +The native Provider is reached by both Python entry points. Contract tests run lifecycle calls, two gateway layouts, separate credentials, versioned connect and timeout, terminal-aware process execution, file I/O and default-context Jupyter. They exercise the SDK HTTP client with a test transport. + +## Commands run + +- `pytest -q tests/test_providers/test_alicloud_container.py tests/test_providers/test_bound_client.py tests/test_providers/test_registry_scoping.py` from `client-sdk` +- `make lint`, `make format-check`, `make typecheck`, `make build`, and `make dist-check` +- `bash scripts/check-repo-health.sh` and `make hygiene` +- `make test` in an isolated loopback network; ran the Client suite separately after the Server failure +- `pytest -q --tb=short -m "not integration"` from `client-sdk` with isolated loopback +- Re-ran the failing Server package probe with pip installed and compared the failing Client SSE test against the PR #167 base with isolated loopback and PID namespace +- `pytest -q test_alicloud_container_native.py` from `e2e` + +## Results + +| Scenario | Result | Notes | +| --- | --- | --- | +| Native and private routing, auth, write uncertainty, teardown | PASS | 47 targeted tests including bound and registry regressions. Controlled HTTP backend. | +| Installed Client wheel over loopback HTTP | PASS | Created one fixture sandbox, streamed a framed command, wrote and read a file, executed Jupyter and verified the deletion. The isolated process had no binaries on its PATH and installed the client wheel only. | +| Lint, format, mypy, distribution and records | PASS | Both package wheels and source archives build and pass distribution checks. | +| Full Server unit suite | PARTIAL | 879 passed; the package-list probe initially failed in a uv environment without pip. Installing pip and repeating the probe passed. | +| Full Client unit suite | PARTIAL | 2,467 passed, 35 skipped, 10 deselected, one Managed Agents SSE test timed out. The timeout reproduced against the PR #167 baseline. | +| Review round 1 | PASS | Reviewed lifecycle, framing, credential audiences and direct wheel integration against the pinned providers. | +| Review round 2 | PASS | Corrected legacy connect timeout, signaled exits, public Jupyter NDJSON ending, refresh omission semantics and plugin install validation. | +| ACS/ACK E2E | BLOCKED | One targeted test skipped. A cluster endpoint and its sandbox-manager key are required. | + +## Cleanup + +The local HTTP contract owned no remote resources. The isolated wheel probe shut down its loopback server after checking deletion. The live test skipped before making requests. + +## Problems found + +The Kruise manager reports a fixed envd version. Framing follows its actual Connect implementation. Older connect routes require an explicit timeout. The Jupyter HTTP response suppresses its internal completion message; the reader processes complete HTTP responses, and errors or malformed JSON are surfaced. A second audit found the bundled selection could shadow install verification of the Node plugin and corrected it. + +## Not verified + +Real ACS or ACK lifecycle, cluster-specific admission and internet/private ingress, and deployment-side SandboxSet operations. No package publication occurred. diff --git a/.agents/notes/proposed/architecture/2026-11-24-alicloud-container-native-provider.md b/.agents/notes/proposed/architecture/2026-11-24-alicloud-container-native-provider.md new file mode 100644 index 0000000..0dccd6a --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-24-alicloud-container-native-provider.md @@ -0,0 +1,44 @@ +# Decision: Bundle the Alibaba Cloud Container Edition Python Provider + +Status: proposed + +## Problem + +Python applications using an ACS or ACK sandbox-manager currently use the Node plugin through the local abx engine. The cluster offers a direct HTTP control plane and E2B-shaped data plane. The client should be able to operate existing SandboxSets without installing a second local runtime. + +## Decision + +Ship `alicloud-container` in the Client SDK wheel and select it by ID. Bound preparation resolves the shipped Provider directly and matches the lock version before selecting other approved artifacts. Keep the default Express target. The abx catalog plugin continues to own its Node execution and SandboxSet preparation. The Python plugin installation verifier checks the artifact it was asked to install, even where an SDK Provider also has that ID. + +Reuse the existing HTTP, Connect process and file implementations. Keep account configuration, routing, lifecycle request shapes and the Jupyter endpoint in the Container Edition adapter. Scope the management key to the control plane. Derive all data URLs from the configured cluster gateway. An existing SandboxSet supplies the base compute configuration. + +## API Design + +- `ProviderSandbox.create(provider="alicloud-container", template="code-interpreter")` reads provider-scoped settings from the usual Client SDK configuration sources. +- `ProviderClient.prepare(lock, TransportConfig(...))` binds the shipped version using explicit provider options. +- Methods cover lifecycle, timeout, process and file operations, port resolution and the Jupyter default context. `connect` may resume or extend a lease. List returns one page. +- Jupyter execution checks the completion event emitted by the public `/execute` response wrapper. A response without that event raises a protocol error. +- Sandbox creation can be inconclusive after an upstream transport failure or gateway 5xx. `on_created` records IDs from valid receipts. Reconcile uncertain creation in the cluster before a new request. + +## Alternatives considered + +- Keep the Node bridge for Python. It preserves one host implementation but adds a separate process and runtime for a backend already within the SDK's HTTP capabilities. +- Add the Container gateway to the standard Express client. The management credentials, private data routing, connect and code contracts differ. +- Use a declarative REST preset. The preset cannot express the versioned connect behavior, path routing and Jupyter protocol. + +## Dependencies + +[Alibaba Cloud Container Edition guide](https://help.aliyun.com/zh/agent-sandbox/quick-start1/), [OpenKruise lifecycle](https://github.com/openkruise/agents/blob/25106aaaf6a73770b1ae1ee2cc0a06d6610cf279/pkg/servers/e2b/pause_resume.go), [OpenKruise v0.6.0 route table](https://github.com/openkruise/agents/blob/a1e0811323b71fd9a54efe26b0f4baf19106c84e/pkg/servers/e2b/routes.go), [OpenKruise listing](https://github.com/openkruise/agents/blob/25106aaaf6a73770b1ae1ee2cc0a06d6610cf279/pkg/servers/e2b/list.go) and [Jupyter response producer](https://github.com/e2b-dev/code-interpreter/blob/db9fdb1cfe6552455d58b1690971bdd3052538c6/template/server/messaging.py). Shares bound-client infrastructure with [PR #167](https://github.com/Alibaba-Agent-Sandbox/python-sdk/pull/167). + +## Test Strategy + +Validate both gateway layouts using the real SDK HTTP client with a controlled HTTP contract. Exercise management and data-plane authentication, v2 and v1 connect, list state, file transfers, Jupyter NDJSON, process exits, identity checks and ambiguous creates. Run the basic live case against a maintainer-provided ACS or ACK cluster and confirm deletion by ID. Run the separate interpreter case with a SandboxSet that exposes the Jupyter service. + +## Acceptance criteria + +The client wheel contains the Provider and requires no Node runtime. Both public Python entry points use it without starting the engine. The cluster test proves real commands, files, interpreter results and owned sandbox cleanup. Keep live acceptance open until a cluster with a suitable SandboxSet and credential is available. + +## Evidence + +- [Implementation and two-round review evidence](../../../evidence/verify/2026-11-24-alicloud-container-native-provider.md) +- [Follow-up review and verification evidence](../../../evidence/verify/2026-11-24-alicloud-container-native-provider-recheck.md) diff --git a/.env.example b/.env.example index 424903a..f385234 100644 --- a/.env.example +++ b/.env.example @@ -1,7 +1,7 @@ # Agent Sandbox environment variables. # Copy to .env and fill in real values. Each key has one name. -# Required: sandbox API key +# Required for Express: sandbox API key ABX_SANDBOX_API_KEY=your_api_key_here # Optional: platform URL and data-plane domain @@ -11,6 +11,12 @@ ABX_SANDBOX_API_KEY=your_api_key_here # Optional: provider (default alicloud-express) # ABX_PROVIDER=alicloud-express +# Container Edition: specify the cluster manager key and a domain or management URL. +# ABX_ALICLOUD_CONTAINER_API_KEY= +# ABX_ALICLOUD_CONTAINER_DOMAIN=sandbox.example.com +# ABX_ALICLOUD_CONTAINER_BASE_URL=https://sandbox.example.com/kruise/api +# ABX_ALICLOUD_CONTAINER_PROTOCOL=private + # Optional: Alibaba Cloud official names # ALIBABA_CLOUD_REGION_ID=cn-hangzhou # ALICLOUD_ACCESS_KEY_ID=your_ak diff --git a/CHANGELOG.md b/CHANGELOG.md index f373443..d2ac7e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +### Added + +- Bundle a native Python Provider for Alibaba Cloud Agent Sandbox Container Edition. + `ProviderSandbox` selects it by ID, and `ProviderClient` can bind the matching bundled version. + / 内置阿里云智能体沙箱容器版 Python Provider,支持按 ID 选择和显式绑定。 + +### Fixed + +- Report incomplete Container Edition interpreter responses as protocol errors. / 容器版解释器响应缺少执行完成事件时报告协议错误。 + ### Documentation - Synchronize CLI-dependent SDK documentation, HTTP MCP template deployment and source-acquisition error guidance. / 同步 SDK 文档中的 CLI 用法、HTTP MCP 模板部署与源码获取错误指引。 diff --git a/README.md b/README.md index eabecd2..4335738 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Use `await` with `AsyncSandbox` and `ProviderSandbox`. Provider operations and i ## Other providers and application templates -Express is built in. Installable [provider plugins](https://github.com/Alibaba-Agent-Sandbox/awesome-providers) connect `ProviderSandbox` to other backends. Follow [provider setup](docs/en/guide/providers.md) before using one. +Express is built in. The SDK source also includes a native [Container Edition provider](docs/en/design/provider-alicloud-container.md). Installable [provider plugins](https://github.com/Alibaba-Agent-Sandbox/awesome-providers) connect `ProviderSandbox` to other backends. Follow [provider setup](docs/en/guide/providers.md) before using one. Application templates package browser tools, coding agents and other services. Launch a template with the [abx CLI](https://github.com/Alibaba-Agent-Sandbox/agent-sandbox), then use its returned sandbox ID and the [template startup guide](docs/en/guide/template-workflows.md) to connect from Python. Named application commands require that service to be running. diff --git a/README.zh-CN.md b/README.zh-CN.md index ca4b1d6..0d17395 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -51,7 +51,7 @@ finally: ## 其他提供方与应用模板 -极速版为内置后端。[提供方插件](https://github.com/Alibaba-Agent-Sandbox/awesome-providers)可让 `ProviderSandbox` 连接其他后端,使用前按[提供方指南](docs/zh/guide/providers.md)完成安装与配置。 +SDK 内置极速版,源码版也可直接调用[容器版](docs/zh/design/provider-alicloud-container.md)。其他后端参见[提供方设置](docs/zh/guide/providers.md)。 应用模板封装浏览器工具、编码 Agent 等服务。先用 [abx CLI](https://github.com/Alibaba-Agent-Sandbox/agent-sandbox)启动模板,再根据返回的沙箱 ID 和[模板启动指南](docs/zh/guide/template-workflows.md)从 Python 连接。调用命名应用命令前,需要先启动对应服务。 diff --git a/agent-sandbox-provider/SKILL.md b/agent-sandbox-provider/SKILL.md index 12517ac..df6977b 100644 --- a/agent-sandbox-provider/SKILL.md +++ b/agent-sandbox-provider/SKILL.md @@ -21,12 +21,13 @@ python -m pip check The image needs only `agent-sandbox-server==0.4.0a6`. Installing that package on the host does not update an existing image. Development source installations must use a matching client/server revision. Do not install `agent-sandbox`; that PyPI project is unrelated. -Only `alicloud-express` is built in. Do not reinstall it and do not reuse -its id. `opensandbox`, `cubesandbox`, `e2b`, and `alicloud-container` are -official catalog ids in `awesome-providers`. Install those with -`registry:`. Do not reuse them for a new backend. A new id matches -`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, length 2-40, and must not start with -`abx-`, `alicloud-`, or `shortcuts`. +The Python SDK source bundles `alicloud-express` and `alicloud-container`. Use +the Container Edition ID for the same backend, with its own cluster credentials. +The published 0.4.0a6 and 0.4.0a7 packages predate the built-in Container Edition adapter. +`opensandbox`, `cubesandbox`, `e2b`, and `alicloud-container` also have official +Node catalog artifacts in `awesome-providers`. A new backend needs a separate +ID matching `^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, length 2-40, outside the reserved +`abx-`, `alicloud-`, and `shortcuts` prefixes. The CLI loads `alicloud-express` plus installed `rest`, `exec` and `node` plugins. It rejects `kind = "python"`. An in-code `Provider` subclass still @@ -35,8 +36,8 @@ works from the Python SDK. Catalog providers (`opensandbox`, `e2b`, `provider.mjs`): install with `abx provider install alibaba-agent-sandbox/awesome-providers// --allow-unpinned --yes` (or `python -m agent_sandbox.providers install registry: --yes`), then -`abx --provider ` or `ProviderSandbox.create(provider="")`. The Python SDK -reaches `node` plugins through the local engine (`abx provider engine serve`, +`abx --provider ` or `ProviderSandbox.create(provider="")`. The Python SDK selects the built-in Container Edition by ID. For Node plugins +it uses the local engine (`abx provider engine serve`, started on demand; `abx` must be on `PATH` or in `ABX_BIN`) using `EngineProvider`. Python `exec` and `rest` manifests still run in the Python process. The catalog guide is diff --git a/client-sdk/README.md b/client-sdk/README.md index 21cf7e1..13529e5 100644 --- a/client-sdk/README.md +++ b/client-sdk/README.md @@ -2,6 +2,8 @@ Provider extensions use [whole-template startup](https://github.com/Alibaba-Agent-Sandbox/python-sdk/blob/main/docs/en/guide/template-workflows.md) ([中文](https://github.com/Alibaba-Agent-Sandbox/python-sdk/blob/main/docs/zh/guide/template-workflows.md)); application HTTP, stateless execution and context operations are independent. +The SDK source includes the native [Alibaba Cloud Agent Sandbox Container Edition provider](https://github.com/Alibaba-Agent-Sandbox/python-sdk/blob/main/docs/en/design/provider-alicloud-container.md). + Install the current alpha with `--pre`; use the [installation guide](https://github.com/Alibaba-Agent-Sandbox/python-sdk/blob/main/docs/en/guide/install-python.md) for a pinned version and environment setup. **Client SDK.** The product is Agent Sandbox. The import path is `agent_sandbox`. This package runs on your machine: create a sandbox, use it, and kill it. The HTTP service inside the image is [`agent-sandbox-server`](https://github.com/Alibaba-Agent-Sandbox/python-sdk/blob/main/server-sdk/README.md). Guide: [Client SDK](https://github.com/Alibaba-Agent-Sandbox/python-sdk/blob/main/docs/en/guide/client-sdk.md). diff --git a/client-sdk/src/agent_sandbox/models/sandbox.py b/client-sdk/src/agent_sandbox/models/sandbox.py index ee90c80..4fa3c39 100644 --- a/client-sdk/src/agent_sandbox/models/sandbox.py +++ b/client-sdk/src/agent_sandbox/models/sandbox.py @@ -152,7 +152,7 @@ class SandboxInfo(BaseModel): status: SandboxStatus = Field(default=SandboxStatus.RUNNING, alias="state") # 认证与版本信息(已实测验证) - envd_access_token: str | None = Field(default=None, alias="envdAccessToken") + envd_access_token: str | None = Field(default=None, alias="envdAccessToken", repr=False) traffic_access_token: str | None = Field( default=None, alias="trafficAccessToken", repr=False, exclude=True ) diff --git a/client-sdk/src/agent_sandbox/providers/alicloud_container/__init__.py b/client-sdk/src/agent_sandbox/providers/alicloud_container/__init__.py new file mode 100644 index 0000000..b4ab2c3 --- /dev/null +++ b/client-sdk/src/agent_sandbox/providers/alicloud_container/__init__.py @@ -0,0 +1 @@ +"""Native Python adapter for Alibaba Cloud Agent Sandbox Container Edition.""" diff --git a/client-sdk/src/agent_sandbox/providers/alicloud_container/interpreter.py b/client-sdk/src/agent_sandbox/providers/alicloud_container/interpreter.py new file mode 100644 index 0000000..7e73e95 --- /dev/null +++ b/client-sdk/src/agent_sandbox/providers/alicloud_container/interpreter.py @@ -0,0 +1,110 @@ +"""Default-context interpreter for SandboxSets that expose Jupyter on port 49999.""" + +from __future__ import annotations + +import asyncio +import json +from typing import TYPE_CHECKING, Any + +from agent_sandbox.models.errors import ProviderFeatureNotSupportedError, ProviderProtocolError +from agent_sandbox.providers.shared.e2b.code_interpreter import UnsupportedCodeProtocol + +from .sandbox import PROVIDER_ID, Gateway + +if TYPE_CHECKING: + from agent_sandbox.providers.shared.e2b.auth import EnvdTokenManager + from agent_sandbox.transport.http import HttpClient + +_CODE_PORT = 49999 + + +def _result(body: str) -> dict[str, Any]: + stdout: list[str] = [] + stderr: list[str] = [] + text = "" + exit_code = 0 + completed = False + for line in body.splitlines(): + if not line.strip(): + continue + if completed: + raise ProviderProtocolError( + "Container Edition returned output after interpreter completion." + ) + try: + event = json.loads(line) + except ValueError: + raise ProviderProtocolError( + "Container Edition returned malformed interpreter output." + ) from None + if not isinstance(event, dict) or not isinstance(event.get("type"), str): + raise ProviderProtocolError("Container Edition returned invalid interpreter events.") + kind = event["type"] + if kind == "end_of_execution": + completed = True + elif kind == "stdout": + stdout.append(str(event.get("text") or "")) + elif kind == "stderr": + stderr.append(str(event.get("text") or "")) + elif kind == "result" and (event.get("is_main_result") or not text): + text = str(event.get("text") or text) + elif kind in {"error", "unexpected_end_of_execution"}: + exit_code = 1 + stderr.append(str(event.get("text") or event.get("value") or event.get("name") or "")) + if not completed: + raise ProviderProtocolError( + "Container Edition interpreter output ended without completion." + ) + output = "".join(stdout) + return { + "stdout": output, + "stderr": "".join(stderr), + "text": text or output, + "exitCode": exit_code, + } + + +class JupyterProtocol: + def __init__(self, http: HttpClient, gateway: Gateway) -> None: + self._unsupported = UnsupportedCodeProtocol(PROVIDER_ID) + self._http = http + self._gateway = gateway + + def __getattr__(self, name: str) -> Any: + return getattr(self._unsupported, name) + + async def run_code( + self, + sandbox_id: str, + envd_url: str, + envd_token: EnvdTokenManager, + *, + code: str, + language: str = "python", + mode: str = "stateless", + timeout: int = 30, + envs: dict[str, str] | None = None, + **options: Any, + ) -> dict[str, Any]: + if mode != "default-context" or options.get("context_id") is not None: + return await self._unsupported.run_code(mode=mode, **options) + if any(options.get(name) is not None for name in ("on_stdout", "on_stderr", "on_result")): + raise ProviderFeatureNotSupportedError(PROVIDER_ID, "code.stream") + if timeout <= 0: + raise ValueError("Interpreter timeout must be positive.") + payload: dict[str, Any] = {"code": code, "language": language} + if envs: + payload["env_vars"] = envs + response = await asyncio.wait_for( + self._http.envd_http_request( + self._gateway.url(sandbox_id, _CODE_PORT), + "POST", + "/execute", + envd_token=envd_token, + headers={"Content-Type": "application/json", "E2b-Sandbox-Port": str(_CODE_PORT)}, + content=json.dumps(payload).encode(), + request_timeout=timeout, + ), + timeout=timeout, + ) + return _result(response.text) diff --git a/client-sdk/src/agent_sandbox/providers/alicloud_container/provider.py b/client-sdk/src/agent_sandbox/providers/alicloud_container/provider.py new file mode 100644 index 0000000..b698527 --- /dev/null +++ b/client-sdk/src/agent_sandbox/providers/alicloud_container/provider.py @@ -0,0 +1,195 @@ +"""Built-in Python implementation for a configured ACS/ACK sandbox-manager.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any +from urllib.parse import SplitResult, urlsplit + +from agent_sandbox._version import __version__ +from agent_sandbox.models.errors import InvalidCredentialsError, ProviderConfigError +from agent_sandbox.providers.base import ConfigField, Provider, ProviderInfra +from agent_sandbox.providers.feature_gate import gate_operation_protocols +from agent_sandbox.providers.rest_provider import HeaderKeyAuth +from agent_sandbox.providers.shared.e2b.filesystem import FilesystemProtocol +from agent_sandbox.providers.shared.e2b.process import ProcessProtocol +from agent_sandbox.transport.http import HttpClient + +from .interpreter import JupyterProtocol +from .sandbox import PROVIDER_ID, ContainerSandboxProtocol, Gateway + +if TYPE_CHECKING: + from agent_sandbox.protocol.port_contract import PortContext + from agent_sandbox.transport.config import TransportConfig + + +def _url(value: str, field: str) -> SplitResult: + try: + parts = urlsplit(value) + if ( + parts.scheme in {"http", "https"} + and parts.hostname + and parts.username is None + and parts.password is None + and parts.port != 0 + and not parts.query + and not parts.fragment + and "\\" not in value + and not any(c.isspace() for c in value) + ): + return parts + except ValueError: + pass + raise ProviderConfigError(f"Provide a valid HTTP(S) Container Edition {field}.") + + +def _option(config: TransportConfig, name: str) -> str: + value = config.provider_options.get(name, "") + if not isinstance(value, str): + raise ProviderConfigError(f"Container Edition option '{name}' must be a string.") + return value.strip() + + +def _gateway(config: TransportConfig) -> Gateway: + protocol = _option(config, "protocol").lower() or "native" + if protocol not in {"native", "private"}: + raise ProviderConfigError("Container Edition protocol must be native or private.") + domain = _option(config, "domain") + base = _option(config, "base_url") + if not domain and not base: + raise ProviderConfigError("Container Edition needs a domain or a base URL.") + if domain: + parts = _url(domain if "://" in domain else f"https://{domain}", "domain") + if parts.path not in ("", "/"): + raise ProviderConfigError("Container Edition domain must be a host without a path.") + domain = parts.netloc + if not base: + base = f"https://{domain}/kruise/api" if protocol == "private" else f"https://api.{domain}" + parts = _url(base, "base URL") + base = base.rstrip("/") + if not domain: + domain = parts.netloc.removeprefix("api.") if protocol == "native" else parts.netloc + if protocol == "private": + if not base.endswith("/kruise/api"): + raise ProviderConfigError("Container Edition private base URL must end in /kruise/api.") + return Gateway(base, domain, base.removesuffix("/kruise/api")) + if ":" in (urlsplit(f"https://{domain}").hostname or ""): + raise ProviderConfigError("Container Edition native routing requires a DNS domain.") + return Gateway(base, domain) + + +class AlicloudContainerProvider(Provider): + """Operate existing SandboxSets through the cluster's E2B-compatible gateway.""" + + id = PROVIDER_ID + display_name = "Alibaba Cloud Agent Sandbox Container Edition" + display_name_zh = "阿里云 Agent Sandbox 容器版" + version = __version__ + kind = "builtin" + config_fields = ( + ConfigField("domain", description="Cluster sandbox-manager gateway domain."), + ConfigField("base_url", type="url", description="Cluster sandbox-manager management URL."), + ConfigField( + "api_key", + required=True, + secret=True, + credential=True, + description="Cluster sandbox-manager API key.", + ), + ConfigField( + "protocol", + default="native", + choices=("native", "private"), + description="Wildcard-domain or private-prefix gateway routing.", + ), + ) + features = frozenset( + { + "sandbox.lifecycle", + "sandbox.timeout", + "sandbox.pause", + "exec.run", + "exec.stream", + "process.manage", + "files.rw", + "ports.url", + } + ) + operations = frozenset( + { + "sandbox.create", + "sandbox.get", + "sandbox.list", + "sandbox.delete", + "sandbox.timeout", + "sandbox.pause", + "sandbox.resume", + "exec.run", + "exec.stream", + "files.read", + "files.write", + "files.list", + "files.stat", + "files.remove", + "files.move", + "ports.resolve", + "code.default-context.execute", + } + ) + create_options = frozenset({"auto_pause"}) + workflow_inputs = frozenset({"managed"}) + startup_modes = frozenset({"exec", "entrypoint", "none"}) + + def validate_config(self, config: TransportConfig) -> None: + unknown = set(config.provider_options) - {field.key for field in self.config_fields} + if unknown: + raise ProviderConfigError( + "Unknown Container Edition options: " + ", ".join(sorted(unknown)) + ) + if not _option(config, "api_key"): + raise InvalidCredentialsError( + "Container Edition needs an API key. Set ABX_ALICLOUD_CONTAINER_API_KEY." + ) + _gateway(config) + + async def build_infra(self, config: TransportConfig) -> ProviderInfra: + self.validate_config(config) + gateway = _gateway(config) + config = config.model_copy( + update={ + "sandbox_base_url": gateway.api, + "sandbox_domain": gateway.domain, + "sandbox_api_key": None, + "access_key_id": None, + "access_key_secret": None, + "security_token": None, + } + ) + auth = HeaderKeyAuth(_option(config, "api_key"), "header") + http = HttpClient(config, auth) + return gate_operation_protocols( + ProviderInfra( + config=config, + auth=auth, + http_client=http, + sandbox_protocol=ContainerSandboxProtocol(http, gateway), + process_protocol=ProcessProtocol(http, require_exit=True), + filesystem_protocol=FilesystemProtocol(http), + code_interpreter_protocol=JupyterProtocol(http, gateway), + ), + self.id, + self.operations, + ) + + async def application_endpoint( + self, context: PortContext, port: int, protocol: Any = None + ) -> dict[str, Any]: + access = self.create_port_access(context, protocol) + return { + "provider_id": self.id, + "sandbox_id": context.sandbox_id, + "port": port, + "url": access.get_url(port), + "headers": access.get_server_headers(), + "authentication_audience": "gateway", + "path_mode": "prefix", + } diff --git a/client-sdk/src/agent_sandbox/providers/alicloud_container/sandbox.py b/client-sdk/src/agent_sandbox/providers/alicloud_container/sandbox.py new file mode 100644 index 0000000..c0ba10e --- /dev/null +++ b/client-sdk/src/agent_sandbox/providers/alicloud_container/sandbox.py @@ -0,0 +1,241 @@ +"""Sandbox-manager lifecycle and gateway routing.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any +from urllib.parse import urlsplit + +import httpx +from pydantic import ValidationError + +from agent_sandbox.models.errors import ( + NetworkError, + ProviderConfigError, + ProviderFeatureNotSupportedError, + ProviderProtocolError, + QuotaExceededError, + SandboxCreationError, + SandboxNotFoundError, + TemplateNotFoundError, +) +from agent_sandbox.models.sandbox import SandboxInfo, SandboxStatus +from agent_sandbox.providers.shared.e2b.auth import EnvdTokenManager +from agent_sandbox.providers.shared.e2b.sandbox import SandboxProtocol +from agent_sandbox.providers.shared.e2b.url import ENVD_PORT + +if TYPE_CHECKING: + from agent_sandbox.models.sandbox import SandboxConfig + from agent_sandbox.protocol.port_contract import PortContext + from agent_sandbox.transport.http import HttpClient + +PROVIDER_ID = "alicloud-container" +_TRAFFIC_HEADER = "e2b-traffic-access-token" +_ID = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?") + + +def _valid_id(value: str) -> str: + if _ID.fullmatch(value) is None: + raise ProviderConfigError("Container Edition requires a DNS-label sandbox ID.") + return value + + +@dataclass(frozen=True) +class Gateway: + api: str + domain: str + private_root: str | None = None + + def url(self, sandbox_id: str, port: int) -> str: + _valid_id(sandbox_id) + if type(port) is not int or not 1 <= port <= 65535: + raise ValueError("Port must be an integer from 1 through 65535.") + if self.private_root is not None: + return f"{self.private_root}/kruise/{sandbox_id}/{port}" + return f"https://{port}-{sandbox_id}.{self.domain}" + + +@dataclass(frozen=True) +class PortAccess: + gateway: Gateway + context: PortContext + + def get_host(self, port: int) -> str: + return urlsplit(self.get_url(port)).netloc + + def get_url(self, port: int) -> str: + return self.gateway.url(self.context.sandbox_id, port) + + def get_access_headers(self) -> dict[str, str]: + if self.context.traffic_access_token: + return {_TRAFFIC_HEADER: self.context.traffic_access_token} + if self.context.access_token: + return {"X-Access-Token": self.context.access_token} + return {} + + get_server_headers = get_access_headers + + +class ContainerToken(EnvdTokenManager): + """Keep gateway and runtime credentials scoped to one sandbox handle.""" + + def __init__(self, info: SandboxInfo) -> None: + super().__init__(info.envd_access_token, info.sandbox_id, allow_missing=True) + self.traffic_token = info.traffic_access_token + self._routing_id = info.sandbox_id + + def get_headers(self) -> dict[str, str]: + headers = super().get_headers() + headers["E2b-Sandbox-Id"] = self._routing_id + if self.traffic_token: + headers[_TRAFFIC_HEADER] = self.traffic_token + return headers + + +class ContainerSandboxProtocol(SandboxProtocol): + def __init__(self, http: HttpClient, gateway: Gateway) -> None: + super().__init__(http, unknown_if_absent=True) + self.gateway = gateway + self._token: ContainerToken | None = None + + def _info(self, data: Any) -> SandboxInfo: + if not isinstance(data, dict): + raise ProviderProtocolError("Container Edition returned an invalid sandbox object.") + data = dict(data) + for field in ("startedAt", "endAt"): + if data.get(field) in ("", ""): + data[field] = None + if "metadata" in data and data["metadata"] is None: + data["metadata"] = {} + data["envdUrl"] = None + try: + info = super()._info(data) + info.model_fields_set.difference_update({"region", "timeout"} - data.keys()) + # Use the bound gateway even if a response advertises another data-plane URL. + info.envd_url = self.gateway.url(info.sandbox_id, ENVD_PORT) + except (ValidationError, ProviderConfigError): + raise ProviderProtocolError( + "Container Edition returned invalid sandbox data." + ) from None + return info + + @staticmethod + def _json(response: httpx.Response) -> Any: + try: + return response.json() + except ValueError: + raise ProviderProtocolError("Container Edition returned invalid JSON.") from None + + async def prepare_session(self, info: SandboxInfo) -> dict[str, Any]: + self._token = ContainerToken(info) + return {"envd_token": self._token} + + def create_port_access(self, context: PortContext) -> PortAccess: + return PortAccess(self.gateway, context) + + async def create( + self, config: SandboxConfig, *, request_timeout: float | None = None + ) -> SandboxInfo: + for key in ("cpu", "memory", "disk", "gpu", "secure", "network", "allow_internet_access"): + if getattr(config, key) is not None: + raise ProviderFeatureNotSupportedError(PROVIDER_ID, f"sandbox.create.{key}") + if config.volume_mounts: + raise ProviderFeatureNotSupportedError(PROVIDER_ID, "storage.mount") + if not config.template.strip(): + raise ProviderConfigError("Specify the name of an existing SandboxSet.") + try: + response = await self._http.platform_request( + "POST", + "/sandboxes", + json=config.to_create_payload(), + request_timeout=request_timeout, + ) + return self._info(self._json(response)) + except httpx.HTTPStatusError as exc: + status = exc.response.status_code + if status == 404: + raise TemplateNotFoundError("Container Edition SandboxSet was not found.") from None + if status == 429: + raise QuotaExceededError( + "Container Edition creation reached a quota limit." + ) from None + if status < 500: + raise SandboxCreationError( + f"Container Edition creation was rejected (HTTP {status})." + ) from None + except (httpx.TransportError, NetworkError, ProviderProtocolError): + pass + error = ProviderProtocolError( + "Container Edition creation did not return a valid receipt. " + "Check the cluster before retrying." + ) + error.outcome = "unknown_outcome" # type: ignore[attr-defined] + raise error + + async def _sandbox_request( + self, method: str, sandbox_id: str, suffix: str = "", **kwargs: Any + ) -> httpx.Response: + return await super()._sandbox_request(method, _valid_id(sandbox_id), suffix, **kwargs) + + async def kill(self, sandbox_id: str) -> None: + await super().kill(_valid_id(sandbox_id)) + + def _matching_info(self, data: Any, sandbox_id: str) -> SandboxInfo: + info = self._info(data) + if info.sandbox_id != sandbox_id: + raise ProviderProtocolError("Container Edition returned a different sandbox identity.") + if self._token is not None and "traffic_access_token" in info.model_fields_set: + self._token.traffic_token = info.traffic_access_token + return info + + async def get_info(self, sandbox_id: str) -> SandboxInfo: + response = await self._sandbox_request("GET", sandbox_id) + return self._matching_info(self._json(response), sandbox_id) + + async def connect(self, sandbox_id: str) -> SandboxInfo: + path = f"/sandboxes/{_valid_id(sandbox_id)}/connect" + try: + response = await self._http.platform_request("POST", f"/v2{path}", json={}) + except httpx.HTTPStatusError as exc: + status = exc.response.status_code + # Go's mux returns a plain 404 for an absent route. A sandbox-level + # 404 returns a structured error; do not replay there. + if status == 405 or ( + status == 404 and exc.response.text.strip() == "404 page not found" + ): + response = await self._sandbox_request( + "POST", sandbox_id, "/connect", json={"timeout": 300} + ) + elif status == 404: + raise SandboxNotFoundError("Container Edition sandbox was not found.") from None + else: + raise + if response.status_code == 204: + return await self.get_info(sandbox_id) + return self._matching_info(self._json(response), sandbox_id) + + async def resume(self, sandbox_id: str) -> SandboxInfo: + return await self.connect(sandbox_id) + + async def list( + self, *, status: SandboxStatus | None = None, limit: int = 100, offset: int = 0 + ) -> list[SandboxInfo]: + if offset: + raise ProviderFeatureNotSupportedError(PROVIDER_ID, "sandbox.list.offset") + if not 1 <= limit <= 100: + raise ValueError("Container Edition list limit must be from 1 through 100.") + params: dict[str, Any] = {"limit": limit} + if status is not None: + if status not in (SandboxStatus.RUNNING, SandboxStatus.PAUSED): + raise ValueError("Container Edition sandbox state must be running or paused.") + params["state"] = status.value + response = await self._http.platform_request("GET", "/v2/sandboxes", params=params) + data = self._json(response) + if isinstance(data, dict): + data = data.get("sandboxes", data.get("data")) + if not isinstance(data, list): + raise ProviderProtocolError("Container Edition returned an invalid sandbox list.") + return [self._info(item) for item in data] + + list_v2 = list diff --git a/client-sdk/src/agent_sandbox/providers/client.py b/client-sdk/src/agent_sandbox/providers/client.py index 493a931..c3e4761 100644 --- a/client-sdk/src/agent_sandbox/providers/client.py +++ b/client-sdk/src/agent_sandbox/providers/client.py @@ -29,6 +29,7 @@ from agent_sandbox.providers.exec_provider import ExecProvider from agent_sandbox.providers.manifest import check_requires, load_manifest from agent_sandbox.providers.runtime_assets import ProviderArtifact, member_path, unpack +from agent_sandbox.utils.config_keys import BUILTIN_PROVIDER_ID if TYPE_CHECKING: from collections.abc import AsyncIterator, Awaitable, Callable, Collection, Sequence @@ -242,7 +243,7 @@ async def prepare( ) -> ProviderClient: """Bind an installed Python provider or a locked standalone implementation. - An explicitly supplied compatible native provider wins before downloading. + An explicit native provider or a matching SDK-bundled version wins before downloading. The cache is offline by default. Neither path discovers global plugins. """ if config.provider != lock.provider: @@ -256,8 +257,14 @@ async def prepare( or native.kind not in {"builtin", "python"} ): raise ProviderVersionError("Native Provider identity or kind differs from the lock.") + if native is None: + from agent_sandbox.providers.registry import bundled_provider + + candidate = bundled_provider(lock.provider) + if candidate is not None and candidate.version == lock.version: + native = candidate if native is not None and features <= native.features: - if native.kind == "builtin" and ( + if native.id == BUILTIN_PROVIDER_ID and ( not (config.sandbox_api_key or "").strip() or config.access_key_id or config.access_key_secret diff --git a/client-sdk/src/agent_sandbox/providers/doctor.py b/client-sdk/src/agent_sandbox/providers/doctor.py index 0218706..710b056 100644 --- a/client-sdk/src/agent_sandbox/providers/doctor.py +++ b/client-sdk/src/agent_sandbox/providers/doctor.py @@ -14,7 +14,6 @@ ) from agent_sandbox.providers import registry, store from agent_sandbox.providers.engine_provider import EngineProvider -from agent_sandbox.utils.config_keys import BUILTIN_PROVIDER_ID def _check(name: str, ok: bool, detail: str = "") -> dict[str, Any]: @@ -32,7 +31,9 @@ async def _close_infra(infra: Any) -> None: await http_client.close() -async def doctor_async(provider_id: str, *, handshake: bool = True) -> dict[str, Any]: +async def doctor_async( + provider_id: str, *, handshake: bool = True, installed_plugin: bool = False +) -> dict[str, Any]: """Run every check for *provider_id*; never raises for provider failures. Returns ``{"id", "ok", "checks": [{"name", "ok", "detail"}...]}``. Plugin processes are started @@ -46,13 +47,19 @@ def finish() -> dict[str, Any]: return {"id": provider_id, "ok": all(c["ok"] for c in checks), "checks": checks} try: - provider = registry.get_provider(provider_id) + provider = ( + registry.load_installed(provider_id) + if installed_plugin + else registry.get_provider(provider_id) + ) checks.append(_check("installed", True, f"{provider.display_name} {provider.version}")) except SandboxError as exc: checks.append(_check("installed", False, exc.message)) return finish() - receipt = store.read_receipt(provider_id) if provider_id != BUILTIN_PROVIDER_ID else None + receipt = ( + store.read_receipt(provider_id) if provider.kind not in {"builtin", "python"} else None + ) if receipt is not None and receipt.get("trust") != "link": try: store.verify_integrity(provider_id) @@ -69,7 +76,7 @@ def finish() -> dict[str, Any]: checks.append(_check("config", False, exc.message)) return finish() - if handshake and provider_id != BUILTIN_PROVIDER_ID: + if handshake and provider.kind != "builtin": try: if isinstance(provider, EngineProvider): await provider.verify_handshake(config) @@ -90,16 +97,22 @@ def finish() -> dict[str, Any]: return finish() -def doctor(provider_id: str, *, handshake: bool = True) -> dict[str, Any]: +def doctor( + provider_id: str, *, handshake: bool = True, installed_plugin: bool = False +) -> dict[str, Any]: """Synchronous wrapper around :func:`doctor_async` (safe inside a running event loop).""" + + async def check() -> dict[str, Any]: + return await doctor_async( + provider_id, handshake=handshake, installed_plugin=installed_plugin + ) + try: asyncio.get_running_loop() except RuntimeError: - return asyncio.run(doctor_async(provider_id, handshake=handshake)) + return asyncio.run(check()) with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: - return pool.submit( - lambda: asyncio.run(doctor_async(provider_id, handshake=handshake)) - ).result() + return pool.submit(lambda: asyncio.run(check())).result() def verify_handshake(provider_id: str) -> None: @@ -107,7 +120,7 @@ def verify_handshake(provider_id: str) -> None: from agent_sandbox.models.errors import ProviderInstallError registry.forget(provider_id) - report = doctor(provider_id) + report = doctor(provider_id, installed_plugin=True) for check in report["checks"]: if check["name"] in ("installed", "integrity", "handshake") and not check["ok"]: raise ProviderInstallError( diff --git a/client-sdk/src/agent_sandbox/providers/registry.py b/client-sdk/src/agent_sandbox/providers/registry.py index 6b4bb29..2344a3a 100644 --- a/client-sdk/src/agent_sandbox/providers/registry.py +++ b/client-sdk/src/agent_sandbox/providers/registry.py @@ -24,6 +24,7 @@ logger = get_logger("providers.registry") ENTRY_POINT_GROUP = "agent_sandbox.providers" +_CONTAINER_PROVIDER_ID = "alicloud-container" _lock = threading.Lock() _registered: dict[str, Provider] = {} @@ -39,6 +40,17 @@ def builtin_provider() -> AlicloudExpressProvider: return _builtin +def bundled_provider(provider_id: str) -> Provider | None: + """Load only SDK-shipped implementations, without discovering plugins.""" + if provider_id == BUILTIN_PROVIDER_ID: + return builtin_provider() + if provider_id == _CONTAINER_PROVIDER_ID: + from agent_sandbox.providers.alicloud_container.provider import AlicloudContainerProvider + + return AlicloudContainerProvider() + return None + + def register_provider(provider: Provider, *, replace: bool = False) -> Provider: """Register an SDK-side (Python) provider object under ``provider.id``.""" problem = validate_provider_id(provider.id) @@ -135,6 +147,9 @@ def get_provider(provider_id: str | None = None) -> Provider: with _lock: if provider_id in _registered: return _registered[provider_id] + bundled = bundled_provider(provider_id) + if bundled is not None: + return bundled _load_entry_points() if provider_id in _entry_point_providers: return _entry_point_providers[provider_id] @@ -170,8 +185,10 @@ def list_providers() -> list[dict[str, Any]]: from agent_sandbox.providers.catalog import schedule_update_check schedule_update_check() - builtins = [builtin_provider()] - out: list[dict[str, Any]] = [_summary(prov, trust="builtin") for prov in builtins] + builtins = [builtin_provider(), get_provider(_CONTAINER_PROVIDER_ID)] + out: list[dict[str, Any]] = [ + _summary(prov, trust="builtin" if prov.kind == "builtin" else "python") for prov in builtins + ] seen = {prov.id for prov in builtins} others: list[dict[str, Any]] = [] with _lock: diff --git a/client-sdk/src/agent_sandbox/providers/shared/e2b/process.py b/client-sdk/src/agent_sandbox/providers/shared/e2b/process.py index 6436657..f90e3a6 100644 --- a/client-sdk/src/agent_sandbox/providers/shared/e2b/process.py +++ b/client-sdk/src/agent_sandbox/providers/shared/e2b/process.py @@ -21,7 +21,7 @@ import httpx -from agent_sandbox.models.errors import CommandTimeoutError +from agent_sandbox.models.errors import CommandTimeoutError, ProviderProtocolError from agent_sandbox.models.process import ( ProcessChunk, ProcessChunkType, @@ -141,8 +141,9 @@ class ProcessProtocol: 已实测验证的方法: Start, List, Connect, Update, SendInput, SendSignal """ - def __init__(self, http_client: HttpClient) -> None: + def __init__(self, http_client: HttpClient, *, require_exit: bool = False) -> None: self._http = http_client + self._require_exit = require_exit async def start( self, @@ -217,6 +218,7 @@ async def _guard_command_timeout( """Bound total execution even while output continues, then stop the owned PID.""" pid: int | None = None deadline = time.monotonic() + timeout + exited = False try: while True: remaining = deadline - time.monotonic() @@ -226,10 +228,25 @@ async def _guard_command_timeout( frame = await asyncio.wait_for(anext(raw_stream), timeout=remaining) except StopAsyncIteration: break - started = (frame.get("event") or {}).get("start") + event = frame.get("event") or {} + started = event.get("start") if isinstance(started, dict) and isinstance(started.get("pid"), int): pid = started["pid"] + if self._require_exit and "end" in event: + end = event["end"] + code = end.get("exitCode") if isinstance(end, dict) else None + clean_exit = isinstance(end, dict) and end.get("exited") is True + if (type(code) is not int and (code is not None or not clean_exit)) or ( + code == 0 and not clean_exit + ): + raise ProviderProtocolError( + "Process stream returned an invalid exit event." + ) + # Protobuf JSON omits a zero-valued exit code. + exited = True yield frame + if self._require_exit and not exited: + raise ProviderProtocolError("Process stream ended without an exit event.") except (asyncio.TimeoutError, httpx.ReadTimeout) as exc: if pid is not None: try: diff --git a/client-sdk/src/agent_sandbox/transport/config.py b/client-sdk/src/agent_sandbox/transport/config.py index e563d2e..07563db 100644 --- a/client-sdk/src/agent_sandbox/transport/config.py +++ b/client-sdk/src/agent_sandbox/transport/config.py @@ -92,7 +92,7 @@ class TransportConfig(BaseModel): ) # Provider-scoped values of non-built-in providers (and extra built-in keys such as ``acr_*``) - provider_options: dict[str, Any] = Field(default_factory=dict) + provider_options: dict[str, Any] = Field(default_factory=dict, repr=False) # HTTP settings http_timeout: float = Field(default=30.0, ge=1.0, description="HTTP request timeout in seconds") diff --git a/client-sdk/src/agent_sandbox/transport/http.py b/client-sdk/src/agent_sandbox/transport/http.py index c602aff..5746735 100644 --- a/client-sdk/src/agent_sandbox/transport/http.py +++ b/client-sdk/src/agent_sandbox/transport/http.py @@ -583,6 +583,7 @@ async def envd_http_request( content: bytes | None = None, files: dict[str, Any] | None = None, max_response_bytes: int | None = None, + request_timeout: float | None = None, ) -> httpx.Response: """Send a plain HTTP request (not Connect RPC) to the envd API. @@ -600,6 +601,10 @@ async def envd_http_request( if headers: all_headers.update(headers) + options: dict[str, Any] = {} + if request_timeout is not None: + options["timeout"] = httpx.Timeout(request_timeout) + logger.debug("envd HTTP %s %s%s", method, envd_url, path) try: if max_response_bytes is not None: @@ -618,6 +623,7 @@ async def envd_http_request( headers=all_headers, content=content, files=files, + **options, ) as streamed: # Error details are intentionally not read: a hostile error # body can also be infinite. Preserve the status for mapping. @@ -654,6 +660,7 @@ async def envd_http_request( headers=all_headers, content=content, files=files, + **options, ) response.raise_for_status() return response diff --git a/client-sdk/tests/test_providers/test_alicloud_container.py b/client-sdk/tests/test_providers/test_alicloud_container.py new file mode 100644 index 0000000..4e86fe2 --- /dev/null +++ b/client-sdk/tests/test_providers/test_alicloud_container.py @@ -0,0 +1,359 @@ +"""Public Client SDK paths against the Container Edition HTTP contract.""" + +from __future__ import annotations + +import json +import struct +from typing import TYPE_CHECKING, Any + +import httpx +import pytest + +from agent_sandbox import ProviderSandbox +from agent_sandbox._version import __version__ +from agent_sandbox.models.errors import ( + InvalidAPIKeyError, + InvalidCredentialsError, + ProviderConfigError, + ProviderFeatureNotSupportedError, + ProviderInstallError, + ProviderProtocolError, + SandboxNotFoundError, +) +from agent_sandbox.models.sandbox import SandboxConfig, SandboxStatus +from agent_sandbox.providers import ProviderClient, ProviderLock, doctor, registry +from agent_sandbox.transport.config import TransportConfig + +if TYPE_CHECKING: + from collections.abc import Callable + +_ID = "alicloud-container" +_LOCK = ProviderLock(provider=_ID, version=__version__) + + +def _frame(event: dict[str, Any]) -> bytes: + payload = json.dumps({"event": event}).encode() + return struct.pack(">BI", 0, len(payload)) + payload + + +def _mock( + monkeypatch: pytest.MonkeyPatch, handler: Callable[[httpx.Request], httpx.Response] +) -> None: + original = httpx.AsyncClient + + def use_mock(**kwargs: Any) -> httpx.AsyncClient: + return original(**kwargs, transport=httpx.MockTransport(handler)) + + monkeypatch.setattr(httpx, "AsyncClient", use_mock) + + +def _config(**options: Any) -> TransportConfig: + return TransportConfig( + provider=_ID, + sandbox_api_key="different-express-test-key", + provider_options={ + "domain": "sandbox.example.test", + "api_key": "manager-test-key", + **options, + }, + ) + + +@pytest.mark.parametrize("private", [False, True]) +async def test_builtin_lifecycle_execution_files_and_ports(monkeypatch, private): + root = "https://private.example.test/proxy" if private else "" + prefix = "/proxy/kruise" if private else "" + api_path = f"{prefix}/api" if private else "" + asset_path = f"{prefix}/sbx-one" if private else "" + data_port = f"{asset_path}/49983" if private else "" + interpreter_port = f"{asset_path}/49999" if private else "" + requests = [] + state = "running" + deleted = False + missing_end = False + incomplete_code = False + end: dict[str, Any] = {"exited": True} + token = "runtime-test-token" + traffic = "traffic-test-token" + info = { + "sandboxID": "sbx-one", + "templateID": "code-interpreter", + "startedAt": "", + "envdVersion": "0.2.10", + "envdUrl": "https://unexpected.example.test/steal", + } + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal state, deleted, token, traffic + requests.append(request) + path = request.url.path + control = path.startswith(f"{api_path}/sandboxes") or path.startswith(f"{api_path}/v2/") + if control: + assert request.headers["x-api-key"] == "manager-test-key" + assert "authorization" not in request.headers + assert "x-access-token" not in request.headers + assert "e2b-traffic-access-token" not in request.headers + else: + assert "x-api-key" not in request.headers + assert request.headers["x-access-token"] == token + assert request.headers["e2b-traffic-access-token"] == traffic + assert request.headers["e2b-sandbox-id"] == "sbx-one" + assert request.url.host == ( + "private.example.test" + if private + else "49999-sbx-one.sandbox.example.test" + if path.endswith("/execute") + else "49983-sbx-one.sandbox.example.test" + ) + if path == f"{api_path}/sandboxes" and request.method == "POST": + assert json.loads(request.content) == { + "templateID": "code-interpreter", + "timeout": 300, + "autoPause": True, + "metadata": {"purpose": "test"}, + "envVars": {"WORKSPACE": "/tmp"}, + } + return httpx.Response( + 201, + json={ + **info, + "envdAccessToken": token, + "trafficAccessToken": traffic, + }, + ) + if path == f"{api_path}/v2/sandboxes": + assert dict(request.url.params) == {"limit": "5", "state": "running"} + return httpx.Response(200, json=[info]) + if path.endswith("/timeout"): + assert json.loads(request.content) == {"timeout": 120} + return httpx.Response(204) + if path.endswith("/pause"): + state = "paused" + return httpx.Response(204) + if path.endswith("/connect"): + if private and path.startswith(f"{api_path}/v2"): + return httpx.Response(404, text="404 page not found\n") + assert json.loads(request.content) == ({"timeout": 300} if private else {}) + state = "running" + token, traffic = "new-runtime-test-token", "new-traffic-test-token" + return httpx.Response( + 200, + json={ + **info, + "state": state, + "envdAccessToken": token, + "trafficAccessToken": traffic, + }, + ) + if path == f"{api_path}/sandboxes/sbx-one": + if request.method == "DELETE": + deleted = True + return httpx.Response(204) + if deleted: + return httpx.Response(404, json={"message": "sandbox was not found"}) + return httpx.Response(200, json={**info, "state": state}) + if path == f"{data_port}/process.Process/Start": + assert request.headers["content-type"] == "application/connect+json" + (size,) = struct.unpack(">I", request.content[1:5]) + assert len(request.content[5:]) == size + assert json.loads(request.content[5:])["stdin"] is False + frames = _frame({"start": {"pid": 1}}) + _frame({"data": {"stdout": "aGk="}}) + if not missing_end: + frames += _frame({"end": end}) + return httpx.Response(200, content=frames) + if path == f"{data_port}/files": + assert request.url.params["path"] == "/tmp/demo" + if request.method == "POST": + assert b"hello" in request.content + return httpx.Response(201) + return httpx.Response(200, content=b"hello") + if path == f"{data_port}/filesystem.Filesystem/Remove": + return httpx.Response(200, json={}) + if path == f"{interpreter_port}/execute": + assert request.headers["e2b-sandbox-port"] == "49999" + assert json.loads(request.content) == {"code": "2 + 2", "language": "python"} + events = [{"type": "result", "text": "4", "is_main_result": True}] + if missing_end: + return httpx.Response(200, text='{"type":"result"') + if not incomplete_code: + events.append({"type": "end_of_execution"}) + return httpx.Response(200, text="\n".join(map(json.dumps, events))) + pytest.fail(f"Unexpected route: {request.method} {path}") + + _mock(monkeypatch, handler) + opts = {"base_url": f"{root}/kruise/api", "protocol": "private"} if private else {} + async with await ProviderClient.prepare(_LOCK, _config(**opts), download=True) as client: + assert client.implementation == "python-native" + assert client.features >= {"exec.stream", "files.rw"} + sandbox = await client.create( + SandboxConfig( + template="code-interpreter", + auto_pause=True, + metadata={"purpose": "test"}, + env_vars={"WORKSPACE": "/tmp"}, + ) + ) + result = await sandbox.commands.run("printf hi") + assert result.exit_code == 0 and result.stdout == "hi" + chunks = [event async for event in sandbox.commands.stream("printf hi")] + assert chunks[-1].exit_code == 0 + await sandbox.files.write("/tmp/demo", "hello") + assert await sandbox.files.read("/tmp/demo") == "hello" + await sandbox.files.remove("/tmp/demo") + code = await sandbox.run_code("2 + 2", mode="default-context") + assert code.exit_code == 0 and code.text == "4" + end = {"exited": False, "exitCode": -1, "status": "signal: killed"} + assert (await sandbox.commands.run("printf hi")).exit_code == -1 + end = {} + with pytest.raises(ProviderProtocolError, match="invalid exit event"): + await sandbox.commands.run("printf hi") + missing_end = True + with pytest.raises(ProviderProtocolError, match="without an exit event"): + await sandbox.commands.run("printf hi") + with pytest.raises(ProviderProtocolError, match="malformed interpreter output"): + await sandbox.run_code("2 + 2", mode="default-context") + + missing_end = False + incomplete_code = True + with pytest.raises(ProviderProtocolError, match="ended without completion"): + await sandbox.run_code("2 + 2", mode="default-context") + + listed = await client.list(status=SandboxStatus.RUNNING, limit=5) + assert listed[0].started_at is None and listed[0].region == "" + with pytest.raises(ProviderFeatureNotSupportedError, match="sandbox.list.offset"): + await client.list(offset=1) + await client.set_timeout(sandbox.id, 120) + await sandbox.pause() + assert not await sandbox.is_running() + await sandbox.resume() + end = {"exited": True} + assert (await sandbox.commands.run("printf hi")).stdout == "hi" + assert await sandbox.files.read("/tmp/demo") == "hello" + info_after = await sandbox.refresh_info() + assert info_after.status is SandboxStatus.RUNNING + assert info_after.envd_access_token == token + expected = ( + f"{root}/kruise/sbx-one/9000" + if private + else "https://9000-sbx-one.sandbox.example.test" + ) + assert await sandbox.network.resolve(9000) == ( + expected, + {"e2b-traffic-access-token": traffic}, + ) + async with await sandbox.application_client(9000) as application: + assert application.base_url == expected + with pytest.raises(ProviderFeatureNotSupportedError, match="code.execute"): + await sandbox.run_code("2 + 2") + with pytest.raises(ProviderFeatureNotSupportedError, match="pty"): + await sandbox.get_terminal() + await sandbox.close() + assert not deleted + async with await client.connect(f"{_ID}:sbx-one") as attached: + assert attached.id == "sbx-one" + await client.delete(sandbox.id) + with pytest.raises(SandboxNotFoundError): + await client.get(sandbox.id) + assert requests and deleted + + +@pytest.mark.parametrize("status", [401, 403, 404, 500]) +async def test_connect_does_not_retry_failed_operations(monkeypatch, status): + requests = [] + + def handler(request): + requests.append(request) + return httpx.Response(status, json={"message": "cloud API rejection"}) + + _mock(monkeypatch, handler) + async with await ProviderClient.prepare(_LOCK, _config()) as client: + expected = {401: InvalidAPIKeyError, 404: SandboxNotFoundError}.get( + status, httpx.HTTPStatusError + ) + with pytest.raises(expected): + await client.connect("sbx-one") + assert [(r.method, r.url.path) for r in requests] == [("POST", "/v2/sandboxes/sbx-one/connect")] + + +async def test_public_provider_sandbox_selects_builtin_without_discovery(monkeypatch): + def fail_discovery(*args, **kwargs): + pytest.fail("The built-in implementation should skip plugin discovery.") + + monkeypatch.setattr(registry, "_load_entry_points", fail_discovery) + monkeypatch.setattr(registry, "load_installed", fail_discovery) + monkeypatch.setenv("ABX_ALICLOUD_CONTAINER_API_KEY", "manager-test-key") + monkeypatch.setenv("ABX_ALICLOUD_CONTAINER_DOMAIN", "sandbox.example.test") + monkeypatch.setenv("ABX_SANDBOX_API_KEY", "different-express-test-key") + + def handler(request): + assert request.url.host == "api.sandbox.example.test" + assert request.headers["x-api-key"] == "manager-test-key" + if request.method == "POST": + return httpx.Response( + 201, json={"sandboxID": "sbx-one", "envdAccessToken": "envd-token"} + ) + return httpx.Response(204) + + _mock(monkeypatch, handler) + assert registry.get_provider(_ID).kind == "builtin" + sandbox = await ProviderSandbox.create(provider=_ID, template="code-interpreter") + try: + assert await sandbox.network.resolve(9000) == ( + "https://9000-sbx-one.sandbox.example.test", + {"X-Access-Token": "envd-token"}, + ) + finally: + await sandbox.kill() + + +async def test_container_credentials_and_unsupported_create_are_checked_before_io(monkeypatch): + def no_request(_: httpx.Request) -> httpx.Response: + pytest.fail("Invalid or unsupported configuration must fail before network I/O.") + + _mock(monkeypatch, no_request) + with pytest.raises(InvalidCredentialsError, match="ABX_ALICLOUD_CONTAINER_API_KEY"): + await ProviderClient.prepare( + _LOCK, + TransportConfig( + provider=_ID, + sandbox_api_key="different-express-test-key", + provider_options={"domain": "example.test"}, + ), + ) + with pytest.raises(InvalidCredentialsError, match="ABX_ALICLOUD_CONTAINER_API_KEY"): + await ProviderClient.prepare(_LOCK, _config(api_key=" ")) + with pytest.raises(ProviderConfigError, match="must end in /kruise/api"): + await ProviderClient.prepare( + _LOCK, _config(base_url="https://example.test", protocol="private") + ) + async with await ProviderClient.prepare(_LOCK, _config()) as client: + with pytest.raises(ProviderFeatureNotSupportedError, match="sandbox.create.cpu"): + await client.create(SandboxConfig(template="code-interpreter", cpu=2)) + with pytest.raises(ProviderConfigError, match="DNS-label sandbox ID"): + await client.get("invalid/id") + + +async def test_ambiguous_create_is_never_replayed(monkeypatch): + calls = [] + + def handler(request): + calls.append(request) + return httpx.Response(502, json={"message": "lost upstream response"}) + + _mock(monkeypatch, handler) + async with await ProviderClient.prepare(_LOCK, _config()) as client: + with pytest.raises(ProviderProtocolError) as captured: + await client.create(SandboxConfig(template="code-interpreter")) + assert captured.value.outcome == "unknown_outcome" + assert len(calls) == 1 + + +def test_install_verification_checks_the_installed_artifact(monkeypatch): + def invalid_install(provider_id): + assert provider_id == _ID + raise SandboxNotFoundError("invalid installed artifact") + + monkeypatch.setattr(registry, "load_installed", invalid_install) + assert registry.get_provider(_ID).kind == "builtin" + with pytest.raises(ProviderInstallError, match="failed installed"): + doctor.verify_handshake(_ID) diff --git a/client-sdk/tests/test_providers/test_engine_alicloud_container.py b/client-sdk/tests/test_providers/test_engine_alicloud_container.py index 16af156..a82b262 100644 --- a/client-sdk/tests/test_providers/test_engine_alicloud_container.py +++ b/client-sdk/tests/test_providers/test_engine_alicloud_container.py @@ -102,6 +102,7 @@ def engine_env(iso: Any, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]: # def _install() -> None: installer.install(str(PLUGIN), yes=True) registry.reset_registry() + registry.register_provider(registry.load_installed("alicloud-container")) def _seen(path: Path) -> list[dict[str, Any]]: diff --git a/client-sdk/tests/test_providers/test_registry_scoping.py b/client-sdk/tests/test_providers/test_registry_scoping.py index cdc75e6..bec8075 100644 --- a/client-sdk/tests/test_providers/test_registry_scoping.py +++ b/client-sdk/tests/test_providers/test_registry_scoping.py @@ -69,11 +69,13 @@ def test_list_order_and_trust(self, iso, tmp_path): # noqa: F811 rows = list_providers() assert [r["id"] for r in rows] == [ "alicloud-express", + "alicloud-container", "local-process", "py-prov", ] assert {r["id"]: r["trust"] for r in rows} == { "alicloud-express": "builtin", + "alicloud-container": "builtin", "local-process": "local", "py-prov": "python", } diff --git a/docs/en/design/provider-alicloud-container.md b/docs/en/design/provider-alicloud-container.md index 5c9dc6e..1390e57 100644 --- a/docs/en/design/provider-alicloud-container.md +++ b/docs/en/design/provider-alicloud-container.md @@ -1,48 +1,62 @@ # Alibaba Cloud Agent Sandbox, container edition -Container edition is the OpenKruise Agents sandbox-manager on ACS or ACK. It is a separate provider from Express, with its own domain, credentials and runtime setup. The CLI and Python `ProviderSandbox` use the [catalog adapter](https://github.com/Alibaba-Agent-Sandbox/awesome-providers/tree/main/alicloud-container) through the local engine. The Node.js server HTTP client does not manage this provider. [中文](../../zh/design/provider-alicloud-container.md). +Container Edition runs sandbox-manager on an ACS or ACK cluster. Use the Python Client SDK source version that includes the built-in `alicloud-container` Provider. Python calls the cluster directly. The CLI uses its own [Node Provider](https://github.com/Alibaba-Agent-Sandbox/awesome-providers/tree/main/alicloud-container) for operations such as SandboxSet preparation. [中文](../../zh/design/provider-alicloud-container.md) -Install with `abx provider install alibaba-agent-sandbox/awesome-providers//alicloud-container --allow-unpinned --yes`, or `python -m agent_sandbox.providers install registry:alicloud-container --yes`. Pin a reviewed complete commit for reproducible use. +## Install the Client SDK -## Exact interpreter boundary +From a checkout containing the built-in Container Edition Provider, run `python -m pip install ./client-sdk`. PyPI `0.4.0a7` predates this Provider. -The adapter implements only persistent `code.default-context.execute`, using Jupyter `POST /execute` on port 49999 with `code`, `language` and optional `env_vars`, then reading buffered NDJSON. This is an explicit adapter path, not the removed inferred envd Connect interpreter RPC. Select `mode="default-context"` explicitly. +## Connect to the cluster -Stateless execution, public context management, realtime callbacks and structured-result support are not declared. Context IDs and callbacks fail before code is sent. The adapter never falls back to shell when a runtime or route is missing. A template's Python service does not require this interpreter operation unless the selected workflow actually uses it. - -## Configure and create +Set the cluster's sandbox-manager key and at least one of the domain or management URL. Use an existing SandboxSet from the same cluster. | Setting | Environment | | --- | --- | -| Domain | `ABX_ALICLOUD_CONTAINER_DOMAIN` | -| Optional API origin | `ABX_ALICLOUD_CONTAINER_BASE_URL` | -| Provider key, header `X-API-Key` | `ABX_ALICLOUD_CONTAINER_API_KEY` | -| `native` or `private` | `ABX_ALICLOUD_CONTAINER_PROTOCOL`, default `native` | +| Cluster gateway domain | `ABX_ALICLOUD_CONTAINER_DOMAIN` | +| Explicit management API URL | `ABX_ALICLOUD_CONTAINER_BASE_URL` | +| Cluster sandbox-manager API key | `ABX_ALICLOUD_CONTAINER_API_KEY` | +| Gateway routing | `ABX_ALICLOUD_CONTAINER_PROTOCOL`, defaults to `native`, or `private` | -Native API addressing is `https://api.{domain}` with port hosts `https://{port}-{id}.{domain}`. Private API addressing is `https://{domain}/kruise/api`; the envd binding uses `https://{domain}/kruise/{id}/49983` and the Jupyter handler selects port 49999. Express keys are not inherited. +With `native` routing, the default management URL is `https://api.{domain}` and sandbox ports use `https://{port}-{id}.{domain}`. With `private` routing, the default management URL is `https://{domain}/kruise/api` and sandbox ports use the `/kruise/{id}/{port}` path. An explicit private management URL must end in `/kruise/api`. Its origin and any preceding path prefix also apply to the data plane. The management key goes to the cluster API. The session supplies credentials for the sandbox gateway and envd. ```python +import asyncio + from agent_sandbox import ProviderSandbox -sandbox = await ProviderSandbox.create( - provider="alicloud-container", - template="YOUR_NATIVE_SANDBOXSET", - provider_options={ - "domain": "sbx.example.com", - "api_key": "REPLACE_ME", - "protocol": "native", - }, -) -try: - result = await sandbox.run_code("print(42)", mode="default-context") -finally: - await sandbox.kill() + +async def main(): + sandbox = await ProviderSandbox.create( + provider="alicloud-container", + template="base", # Use an existing SandboxSet name from the cluster. + ) + try: + result = await sandbox.commands.run("printf container") + print(result.stdout) + await sandbox.files.write("/tmp/container-demo.txt", result.stdout) + print(await sandbox.files.read("/tmp/container-demo.txt")) + finally: + await sandbox.kill() + + +asyncio.run(main()) ``` -The manifest declares lifecycle/timeout/pause/resume, exec, process management, files and ports independently. The exact operation lists determine workflow support. PTY, file watch/transfer, template inventory, storage mounts, VPC and named-command service availability are not inferred from these groups. Named-command application workflows require an actual matching HTTP service and binding. +## Run Python in an existing interpreter context + +For a SandboxSet with the Jupyter service on port `49999`, use this call inside the sandbox's `try` block. The default context persists across calls. `run_code` buffers the service output and returns an execution result. + +```python +result = await sandbox.run_code("print(42)", mode="default-context") +print(result.stdout) +``` + +## Bind an explicit cluster target + +Use [`ProviderClient`](../guide/provider-runtime.md) when a service should supply its own cluster configuration. Set `ProviderLock(provider="alicloud-container", version=...)` to the installed `agent-sandbox-client` version. Pass `api_key`, `domain` or `base_url`, and, if needed, `protocol` in `TransportConfig.provider_options`. A matching built-in Provider is selected by that lock. -## Source preparation and evidence +## Capabilities -CLI preparation builds and pushes an explicit compatible source/profile, then clones a configured base SandboxSet's runtime injection, volumes and probes into an owned zero-pool resource. It does not modify the base object or rewrite Dockerfile instructions. This requires Docker/registry access and Kubernetes permissions; an ordinary sandbox-manager key alone cannot register SandboxSets. Python consumes prepared references and does not declare `template.prepare`. +The client operates existing SandboxSets. It supports lifecycle, lease updates, commands and streaming, process operations, file operations, and gateway port addresses. Pause and resume depend on the cluster. `connect()` can resume a sandbox or extend its lease. `close()` releases local connections, and `kill()` deletes the sandbox. Listing returns one page of 1–100 entries and accepts the `running` and `paused` filters. -Container edition remains Beta. Local fake-API tests exercise adapter mapping and refusal behavior. A real create requires an ACS/ACK deployment, a valid native SandboxSet, domain/key and runtime services. No native acceptance was completed in this environment. Source registration, application HTTP and interpreter evidence have different scopes; successful mocks or historical receipts do not certify the current workflow. +The adapter has no support for separate interpreter contexts, real-time interpreter callbacks, PTY, file watching, per-instance compute overrides, or volume and network configuration. See the [Alibaba Cloud setup guide](https://help.aliyun.com/zh/agent-sandbox/quick-start1/) for creating or modifying a SandboxSet. The built-in Python Provider is in preview. diff --git a/docs/en/guide/provider-runtime.md b/docs/en/guide/provider-runtime.md index 3e7cd08..490dd01 100644 --- a/docs/en/guide/provider-runtime.md +++ b/docs/en/guide/provider-runtime.md @@ -1,6 +1,6 @@ # Prepare a Provider runtime in Python -Use `agent_sandbox.providers.ProviderClient` from the Python SDK source to bind a Provider and a target at application startup. A compatible Python implementation supplied by the application takes priority. Otherwise the client can fetch an approved standalone EPP implementation and its runtime. The SDK import and direct HTTP clients require no runtime preparation. +Use `agent_sandbox.providers.ProviderClient` from the Python SDK source to bind a Provider and a target at application startup. A compatible Python implementation supplied by the application or shipped with the SDK takes priority. Otherwise the client can fetch an approved standalone EPP implementation and its runtime. The SDK import and direct HTTP clients require no runtime preparation. ## OpenSandbox on Linux x86-64 with glibc @@ -20,7 +20,7 @@ In an application, call `await ProviderClient.prepare(lock, config, cache_dir=pa ## Use an installed Python Provider -Pass a trusted `Provider` instance as `native=`. Its ID and version must match `ProviderLock`. Declare the features you need using `required_features`. The SDK uses the compatible native implementation or selects an approved standalone entry for the host and feature set. Among standalone entries, Python is preferred, then the smallest numeric priority. You can supply a native-only lock without runtime entries. Install the Python implementation using your normal environment management. +Pass a trusted `Provider` instance as `native=`, or omit it to select a matching SDK-bundled implementation. For [Container Edition](../design/provider-alicloud-container.md), use `alicloud-container` and the installed SDK version in the lock, and pass the cluster options in `TransportConfig.provider_options`. Its ID and version must match `ProviderLock`. Declare the features you need using `required_features`. The SDK uses the compatible native implementation or selects an approved standalone entry for the host and feature set. Among standalone entries, Python is preferred, then the smallest numeric priority. You can supply a native-only lock without runtime entries. Install the Python implementation using your normal environment management. `ProviderClient` provides `create(SandboxConfig(...))`, `connect`, `list`, `get`, `set_timeout` and `delete`. A client belongs to the event loop that prepared it. Close individual sandbox handles and close the client when finished. Call `delete` for owned sandboxes to release remote resources. `ProviderClient.close()` releases local resources. diff --git a/docs/en/guide/providers.md b/docs/en/guide/providers.md index 178484d..23ca7ad 100644 --- a/docs/en/guide/providers.md +++ b/docs/en/guide/providers.md @@ -8,22 +8,22 @@ This guide describes asynchronous `ProviderSandbox` provider extensions. Root `S > **Note:** The `abx provider ...` commands come from the separate [abx CLI](https://github.com/Alibaba-Agent-Sandbox/agent-sandbox). Python users can manage providers with `python -m agent_sandbox.providers ...`; Node providers still need the local `abx` engine. Both management entries share the install directory, receipts and tree digest. -A **provider** is a sandbox backend. The SDK and the CLI ship only `alicloud-express`. The others install with `python -m agent_sandbox.providers install registry: --yes` from `https://registry.agent-sandbox.cn/providers/index.json`. A background check compares recorded archive digests and writes content-change notices to `~/.abx/providers/updates.json`. `ABX_PROVIDER_UPDATE_CHECK=0` turns the check off. `ABX_PROVIDER_REGISTRY` changes the index URL. The official site is . The registry website is . +A **provider** is a sandbox backend. The Python SDK source ships `alicloud-express` and `alicloud-container`. The CLI ships Express. Catalog plugins install with `python -m agent_sandbox.providers install registry: --yes` from `https://registry.agent-sandbox.cn/providers/index.json`. A background check compares recorded archive digests and writes content-change notices to `~/.abx/providers/updates.json`. `ABX_PROVIDER_UPDATE_CHECK=0` turns the check off. `ABX_PROVIDER_REGISTRY` changes the index URL. The official site is . The registry website is . | Id | Name | Kind | Default | |---|---|---|---| | `alicloud-express` | Alibaba Cloud Express Edition (阿里云极速版) | built-in | yes | -| `alicloud-container` | Alibaba Cloud Agent Sandbox, container edition | catalog plugin, `node`; CLI and Python ProviderSandbox after install | no | +| `alicloud-container` | Alibaba Cloud Agent Sandbox, container edition | built into the Python source version, Node plugin for the CLI | no | | `cubesandbox` | CubeSandbox | catalog plugin, `node`; CLI and Python ProviderSandbox after install | no | | `e2b` | E2B | catalog plugin, `node`; CLI and Python ProviderSandbox after install | no | | `opensandbox` | OpenSandbox | catalog plugin, `node` (ES module, EPP methods run in the host process); CLI and Python ProviderSandbox after install | no | -The four non-default ids live in `awesome-providers`. Install with `abx provider install alibaba-agent-sandbox/awesome-providers// --allow-unpinned --yes` or `python -m agent_sandbox.providers install registry: --yes` (the `abx` CLI has no `registry:` form), then select with `ProviderSandbox.create(provider="…")` or `abx --provider `. All four are `runtime.kind = "node"` (an ES module, `provider.mjs`), written once in Node.js. The CLI loads them in-process. The Python SDK reaches them through the local Node engine (`abx provider engine serve`, started on demand, so `abx` must be on `PATH` or in `ABX_BIN`) using `EngineProvider` (`engine:///`). A third-party `rest` provider uses Python HTTP transport; an `exec` provider starts the executable declared in its manifest through the Python adapter. The built-in `alicloud-express` is the Python builtin provider. There is no installable `python` kind. See the CLI's [Engine HTTP API](https://github.com/alibaba-agent-sandbox/agent-sandbox/blob/main/docs/en/reference/engine-api.md). +The CLI's four catalog plugins run as Node.js modules. The Python SDK loads the built-in Container Edition directly. For the other catalog IDs, use `python -m agent_sandbox.providers install registry: --yes` and configure the local engine. A third-party `rest` provider uses Python HTTP transport. An `exec` provider starts its declared executable. See the [Engine HTTP API](https://github.com/alibaba-agent-sandbox/agent-sandbox/blob/main/docs/en/reference/engine-api.md). | Id | How to use it | |---|---| | `opensandbox` | [OpenSandbox provider](../design/provider-opensandbox-mapping.md). HTTP is made from the Node host process that loads `provider.mjs`. `ABX_OPENSANDBOX_BASE_URL` defaults to `http://127.0.0.1:8080`. | -| `alicloud-container` | [Container edition](../design/provider-alicloud-container.md). Needs `ABX_ALICLOUD_CONTAINER_DOMAIN`. Does not read `ABX_SANDBOX_API_KEY`. | +| `alicloud-container` | [Container edition](../design/provider-alicloud-container.md). Set the cluster API key and domain or private management URL. | | `cubesandbox` | [CubeSandbox provider](../design/provider-cubesandbox.md). Default origin `http://127.0.0.1:3000`. | | `e2b` | [E2B provider](../design/provider-e2b.md). Key is `ABX_E2B_API_KEY`. Does not read `ABX_SANDBOX_API_KEY`. | @@ -74,7 +74,7 @@ Python ProviderSandbox -> provider backend ``` -The SDK discovers a running engine or starts one on demand, including during installation verification. It reuses the engine across calls; it does not start Node for every command or file operation. `close()` closes the local SDK client, not the shared engine. The CLI can load the same provider in its own Node process. Ordinary standard Express SDK calls use their native Python path and do not require this Node-provider bridge. +The SDK discovers a running engine or starts one on demand, including during installation verification. It reuses the engine across calls; it does not start Node for every command or file operation. `close()` closes the local SDK client, not the shared engine. The CLI can load the same provider in its own Node process. The Python SDK calls Express and Container Edition directly. Compared with a Python provider that accesses the same backend directly, the bridge adds local communication, encoding/decoding, dispatch and a Node process's memory. An engine that is not running also adds startup and plugin-loading time. These costs depend on payload size, operation, machine and concurrency: diff --git a/docs/zh/design/provider-alicloud-container.md b/docs/zh/design/provider-alicloud-container.md index 19306a7..f28bf17 100644 --- a/docs/zh/design/provider-alicloud-container.md +++ b/docs/zh/design/provider-alicloud-container.md @@ -1,48 +1,62 @@ # 阿里云智能体沙箱容器版 -容器版是 ACS 或 ACK 上的 OpenKruise Agents sandbox-manager,与 Express 分属不同 Provider,使用各自的域名、凭证和运行时条件。CLI 与 Python `ProviderSandbox` 经本机引擎使用[目录适配器](https://github.com/Alibaba-Agent-Sandbox/awesome-providers/tree/main/alicloud-container)。Node.js 服务 HTTP 客户端不管理此 Provider。[English](../../en/design/provider-alicloud-container.md)。 +容器版的 sandbox-manager 运行在 ACS 或 ACK 集群中。使用包含内置 `alicloud-container` 的 Python Client SDK 源码版,可以直接访问集群。CLI 通过自己的 [Node Provider](https://github.com/Alibaba-Agent-Sandbox/awesome-providers/tree/main/alicloud-container) 准备 SandboxSet 等资源。[English](../../en/design/provider-alicloud-container.md) -使用 `abx provider install alibaba-agent-sandbox/awesome-providers//alicloud-container --allow-unpinned --yes` 或 `python -m agent_sandbox.providers install registry:alicloud-container --yes` 安装。可复现使用应固定经审查的完整提交。 +## 安装 Client SDK -## 精确解释器边界 +在包含容器版内置 Provider 的源码目录运行 `python -m pip install ./client-sdk`。PyPI 上的 `0.4.0a7` 尚未包含这个 Provider。 -适配器仅实现持久的 `code.default-context.execute`:向 49999 端口的 Jupyter `POST /execute` 发送 `code`、`language` 与可选 `env_vars`,读取缓冲的 NDJSON。它是明确的独立适配路径,不是已删除的猜测 envd Connect 解释器 RPC。调用时显式选择 `mode="default-context"`。 +## 连接集群 -未声明无状态执行、公共上下文管理、实时回调或结构化结果支持。传入 context ID 或回调时,代码发送前即拒绝。缺少运行时或路由时不会降级为 shell。模板提供 Python 服务,不代表所选工作流必须使用这项解释器操作。 +配置集群 sandbox-manager 的 API Key,并至少提供域名或管理 API 地址之一。运行示例前,准备同一集群中已注册的 SandboxSet。 -## 配置与创建 - -| 设置 | 环境变量 | +| 配置 | 环境变量 | | --- | --- | -| 域名 | `ABX_ALICLOUD_CONTAINER_DOMAIN` | -| 可选 API 源站 | `ABX_ALICLOUD_CONTAINER_BASE_URL` | -| Provider 密钥,请求头 `X-API-Key` | `ABX_ALICLOUD_CONTAINER_API_KEY` | -| `native` 或 `private` | `ABX_ALICLOUD_CONTAINER_PROTOCOL`,默认 `native` | +| 集群网关域名 | `ABX_ALICLOUD_CONTAINER_DOMAIN` | +| 显式管理 API 地址 | `ABX_ALICLOUD_CONTAINER_BASE_URL` | +| 集群 sandbox-manager API Key | `ABX_ALICLOUD_CONTAINER_API_KEY` | +| 网关路由方式 | `ABX_ALICLOUD_CONTAINER_PROTOCOL`,默认为 `native`,也可填 `private` | -Native API 为 `https://api.{domain}`,端口地址为 `https://{port}-{id}.{domain}`。Private API 为 `https://{domain}/kruise/api`;envd 绑定使用 `https://{domain}/kruise/{id}/49983`,Jupyter handler 选择 49999 端口。不继承 Express 密钥。 +`native` 的默认管理地址为 `https://api.{domain}`,沙箱端口地址为 `https://{port}-{id}.{domain}`。`private` 的默认管理地址为 `https://{domain}/kruise/api`,沙箱端口使用 `/kruise/{id}/{port}` 路径。显式私有管理地址必须以 `/kruise/api` 结尾,源站及该路径前的前缀也用于数据面。管理 Key 用于集群 API,沙箱网关及 envd 使用会话返回的令牌。 ```python +import asyncio + from agent_sandbox import ProviderSandbox -sandbox = await ProviderSandbox.create( - provider="alicloud-container", - template="YOUR_NATIVE_SANDBOXSET", - provider_options={ - "domain": "sbx.example.com", - "api_key": "REPLACE_ME", - "protocol": "native", - }, -) -try: - result = await sandbox.run_code("print(42)", mode="default-context") -finally: - await sandbox.kill() + +async def main(): + sandbox = await ProviderSandbox.create( + provider="alicloud-container", + template="base", # 替换为集群中已有的 SandboxSet 名称 + ) + try: + result = await sandbox.commands.run("printf container") + print(result.stdout) + await sandbox.files.write("/tmp/container-demo.txt", result.stdout) + print(await sandbox.files.read("/tmp/container-demo.txt")) + finally: + await sandbox.kill() + + +asyncio.run(main()) ``` -Manifest 分别声明生命周期、超时、暂停/恢复、exec、进程管理、文件与端口。具体 operation 列表决定工作流支持情况,不能推导 PTY、文件监听/传输、模板查询、存储挂载、VPC 或命名命令服务可用。命名命令应用工作流需要真实匹配的 HTTP 服务与绑定。 +## 在已有解释器上下文中运行 Python + +如果 SandboxSet 在 `49999` 端口提供 Jupyter 服务,可以在示例的 `try` 块内调用以下接口。默认上下文在多次调用间保留,`run_code` 收集服务输出后返回执行结果。 + +```python +result = await sandbox.run_code("print(42)", mode="default-context") +print(result.stdout) +``` + +## 显式绑定集群 + +服务需要自行传入集群配置时,可使用 [`ProviderClient`](../guide/provider-runtime.md)。将 `ProviderLock(provider="alicloud-container", version=...)` 中的版本设为已安装的 `agent-sandbox-client` 版本,通过 `TransportConfig.provider_options` 传入 `api_key`、`domain` 或 `base_url`,需要时添加 `protocol`。锁与 SDK 内置实现匹配时会直接加载该实现。 -## 源码准备与证据 +## 支持范围 -CLI 准备流程构建、推送显式兼容的源码/构建方案,再将配置的基础 SandboxSet 中运行时注入、卷、探针复制到本轮自有的零预热池资源。它不修改基础对象,也不改写 Dockerfile 指令。该流程需要 Docker/镜像仓库访问及 Kubernetes 权限,普通 sandbox-manager 密钥本身不能登记 SandboxSet。Python 只消费已准备的引用,不声明 `template.prepare`。 +客户端使用已注册的 SandboxSet,支持实例生命周期、租期调整、命令及流式输出、进程、文件和网关端口访问。暂停和恢复取决于集群配置。`connect()` 可能恢复实例或延长租期。`close()` 释放本机连接,`kill()` 删除实例。列表每次返回一页,支持 1–100 条及 `running`、`paused` 过滤。 -容器版保持 Beta。本地假 API 测试验证映射与拒绝行为;真实创建需要 ACS/ACK 部署、有效的原生 SandboxSet、域名/密钥与运行时服务。本环境尚未完成原生验收。源码注册、应用 HTTP 与解释器证据范围不同,成功的 mock 或历史回执不能证明当前工作流。 +独立解释器上下文、解释器实时回调、PTY、文件监视、实例规格覆盖以及卷和网络配置暂未接入。创建或修改 SandboxSet 的步骤见[阿里云集群配置指南](https://help.aliyun.com/zh/agent-sandbox/quick-start1/)。内置 Python Provider 仍处于预览阶段。 diff --git a/docs/zh/guide/provider-runtime.md b/docs/zh/guide/provider-runtime.md index 1664e0b..19a77d7 100644 --- a/docs/zh/guide/provider-runtime.md +++ b/docs/zh/guide/provider-runtime.md @@ -1,5 +1,7 @@ # 在 Python 中准备 Provider 运行时 +锁指定的 ID 和版本与 SDK 内置实现匹配时,可省略 `native=`。使用[容器版](../design/provider-alicloud-container.md)时,锁中填写 `alicloud-container` 和 SDK 版本,通过 `TransportConfig.provider_options` 提供集群配置。 + 使用 Python SDK 源码中的 `agent_sandbox.providers.ProviderClient`,在应用启动阶段绑定 Provider 和服务目标。应用传入兼容的 Python 实现时优先使用它,否则可以获取已确认的独立 EPP 实现及其运行时。导入 SDK 和直接调用业务 HTTP API 均无需准备 Provider 运行时。 ## 在 Linux x86-64 glibc 上使用 OpenSandbox diff --git a/docs/zh/guide/providers.md b/docs/zh/guide/providers.md index 5540564..577461d 100644 --- a/docs/zh/guide/providers.md +++ b/docs/zh/guide/providers.md @@ -8,22 +8,22 @@ > **说明:** `abx provider ...` 命令来自独立的 [abx CLI](https://github.com/Alibaba-Agent-Sandbox/agent-sandbox)。Python 用户可用 `python -m agent_sandbox.providers ...` 管理提供方;Node 提供方仍需本机 `abx` 引擎。两个管理入口共用安装目录、回执和目录树摘要。 -**提供方**就是一个沙箱后端。SDK 和 CLI 只内置 `alicloud-express`。其余提供方用 `python -m agent_sandbox.providers install registry: --yes` 安装,索引是 `https://registry.agent-sandbox.cn/providers/index.json`。启动时会在后台对照这份索引检查更新,结果写到 `~/.abx/providers/updates.json`。`ABX_PROVIDER_UPDATE_CHECK=0` 关掉检查。`ABX_PROVIDER_REGISTRY` 可以改索引地址。官网是 。提供方注册站是 。 +**提供方**就是一个沙箱后端。Python SDK 源码版内置 `alicloud-express` 和 `alicloud-container`,CLI 内置极速版。其余提供方用 `python -m agent_sandbox.providers install registry: --yes` 安装,索引是 `https://registry.agent-sandbox.cn/providers/index.json`。启动时会在后台对照这份索引检查更新,结果写到 `~/.abx/providers/updates.json`。`ABX_PROVIDER_UPDATE_CHECK=0` 关掉检查。`ABX_PROVIDER_REGISTRY` 可以改索引地址。官网是 。提供方注册站是 。 | Id | 名称 | 类型 | 默认 | |---|---|---|---| | `alicloud-express` | 阿里云极速版(Alibaba Cloud Express Edition) | 内置 | 是 | -| `alicloud-container` | 阿里云智能体沙箱容器版 | 目录插件,`node`;安装后 CLI 和 Python ProviderSandbox 可用 | 否 | +| `alicloud-container` | 阿里云智能体沙箱容器版 | Python 源码版内置,CLI 使用 Node 插件 | 否 | | `cubesandbox` | CubeSandbox | 目录插件,`node`;安装后 CLI 和 Python ProviderSandbox 可用 | 否 | | `e2b` | E2B | 目录插件,`node`;安装后 CLI 和 Python ProviderSandbox 可用 | 否 | | `opensandbox` | OpenSandbox | 目录插件,`node`(ES 模块,EPP 方法在宿主进程内);安装后 CLI 和 Python ProviderSandbox 可用 | 否 | -除默认项以外的四个 id 在 `awesome-providers`,用 `abx provider install alibaba-agent-sandbox/awesome-providers// --allow-unpinned --yes` 安装;也可用 `python -m agent_sandbox.providers install registry: --yes`(`abx` 没有 `registry:` 写法)。装好之后用 `ProviderSandbox.create(provider="…")` 或 `abx --provider ` 选择。四个都是 `runtime.kind = "node"`(ES 模块 `provider.mjs`),只用 Node.js 写一次。CLI 在进程内加载它们。Python SDK 通过本机 Node 引擎(`abx provider engine serve`,按需启动,所以 `abx` 要在 `PATH` 里或用 `ABX_BIN` 指定)用 `EngineProvider` 访问(`engine:///`)。第三方 `rest` 提供方使用 Python HTTP 传输;`exec` 提供方由 Python 适配器启动清单中声明的可执行程序。内置的 `alicloud-express` 是 Python 内置提供方。没有可安装的 `python` 类型。见 CLI 的[引擎 HTTP API](https://github.com/alibaba-agent-sandbox/agent-sandbox/blob/main/docs/zh/reference/engine-api.md)。 +CLI 直接加载目录中的四个 Node.js 插件。Python SDK 直接访问容器版。其他目录提供方通过 `python -m agent_sandbox.providers install registry: --yes` 安装并配置本机引擎。`rest` 提供方使用 Python HTTP 传输,`exec` 提供方启动声明的可执行文件。参见[引擎 HTTP API](https://github.com/alibaba-agent-sandbox/agent-sandbox/blob/main/docs/zh/reference/engine-api.md)。 | Id | 怎么用 | |---|---| | `opensandbox` | [OpenSandbox 提供方](../design/provider-opensandbox-mapping.md)。HTTP 由加载 `provider.mjs` 的 Node 宿主进程发出。`ABX_OPENSANDBOX_BASE_URL` 默认 `http://127.0.0.1:8080`。 | -| `alicloud-container` | [容器版](../design/provider-alicloud-container.md)。需要 `ABX_ALICLOUD_CONTAINER_DOMAIN`。不读取 `ABX_SANDBOX_API_KEY`。 | +| `alicloud-container` | [容器版](../design/provider-alicloud-container.md)。使用集群 API Key 及域名或私有管理地址。 | | `cubesandbox` | [CubeSandbox 提供方](../design/provider-cubesandbox.md)。默认地址 `http://127.0.0.1:3000`。 | | `e2b` | [E2B 提供方](../design/provider-e2b.md)。密钥是 `ABX_E2B_API_KEY`。不读取 `ABX_SANDBOX_API_KEY`。 | diff --git a/e2e/README.md b/e2e/README.md index 28097a2..24ebd03 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -51,6 +51,16 @@ Without credentials every test is **skipped** with the message Third-party providers are not part of this suite's cloud run. They follow the same six tiers as the CLI, from plugin unit tests (T0) to a local OpenSandbox server (T4) and the Alibaba Cloud platform (T5). The table is [cli/e2e/providers/PLAN.md](https://github.com/alibaba-agent-sandbox/agent-sandbox/blob/main/e2e/providers/PLAN.md) ([中文](https://github.com/alibaba-agent-sandbox/agent-sandbox/blob/main/e2e/providers/PLAN.zh-CN.md)). OpenSandbox helpers for T4 live in [opensandbox/README.md](opensandbox/README.md). +## Native Container Edition Provider + +With [cluster configuration](../docs/en/design/provider-alicloud-container.md) loaded, set `E2E_CONTAINER_SANDBOX_SET` to an existing SandboxSet for the command, file and lifecycle case. Set `E2E_CONTAINER_JUPYTER_SANDBOX_SET` to an existing SandboxSet that serves Jupyter on port `49999` to also verify the interpreter. Each case skips if its own prerequisites are absent. + +```bash +python -m pytest e2e/test_alicloud_container_native.py -ra +``` + +The test deletes each sandbox ID returned at creation and verifies its absence with the same cluster. The Express janitor does not query Container Edition. If a creation request fails without returning an ID, check the cluster for the run's `e2e` metadata before repeating it. + ## What is covered | File | Scope | diff --git a/e2e/README.zh-CN.md b/e2e/README.zh-CN.md index c627cae..59675ff 100644 --- a/e2e/README.zh-CN.md +++ b/e2e/README.zh-CN.md @@ -43,6 +43,16 @@ cd e2e && python -m pytest -m "not e2e_slow" -ra # 等同 `make e2 缺少凭据时所有测试都会**跳过**,并给出 `E2E skipped: missing credentials [...]`。单元 CI 不会收集本套件 (`client-sdk` / `server-sdk` 在各自目录运行 `pytest tests/`)。 +## 容器版原生 Provider + +加载[集群配置](../docs/zh/design/provider-alicloud-container.md)后,将 `E2E_CONTAINER_SANDBOX_SET` 设为已有 SandboxSet 名称,验证命令、文件和实例生命周期。要额外验证解释器,将 `E2E_CONTAINER_JUPYTER_SANDBOX_SET` 设为在 `49999` 端口提供 Jupyter 的已有 SandboxSet。缺少对应条件时,该用例会跳过。 + +```bash +python -m pytest e2e/test_alicloud_container_native.py -ra +``` + +测试删除创建时返回的每个实例 ID,并通过同一集群复查。极速版 janitor 不查询容器版。如果创建请求失败且没有返回 ID,重试前先在集群中检查带有本轮 `e2e` 元数据的实例。 + ## 覆盖范围 | 文件 | 范围 | diff --git a/e2e/e2e_helpers.py b/e2e/e2e_helpers.py index d32a154..50ac583 100644 --- a/e2e/e2e_helpers.py +++ b/e2e/e2e_helpers.py @@ -24,6 +24,7 @@ REQUIRED_ENV = ("ABX_SANDBOX_API_KEY",) SECRET_ENV = ( + "ABX_ALICLOUD_CONTAINER_API_KEY", "ABX_SANDBOX_API_KEY", "OPENAI_API_KEY", ) @@ -63,8 +64,13 @@ def mask(text: str) -> str: value = (os.environ.get(name) or "").strip() if len(value) >= 6: out = out.replace(value, f"<{name}:masked>") - out = re.sub(r"(?i)(x-access-token|authorization|envdAccessToken)(['\"]?\s*[:=]\s*['\"]?)[^\s'\",}]+", - r"\1\2", out) + out = re.sub( + r"(?i)(x-access-token|authorization|envdAccessToken|" + r"e2b-traffic-access-token|trafficAccessToken)" + r"(['\"]?\s*[:=]\s*['\"]?)[^\s'\",}]+", + r"\1\2", + out, + ) return out diff --git a/e2e/test_08_providers.py b/e2e/test_08_providers.py index ce0aaf3..eda8124 100644 --- a/e2e/test_08_providers.py +++ b/e2e/test_08_providers.py @@ -215,16 +215,7 @@ def test_e2b_refuses_without_its_own_key() -> None: def test_container_refuses_without_its_own_endpoint() -> None: if live.container_ready() == "": pytest.skip("container endpoint is set; the live test covers this provider") - from agent_sandbox.models.errors import ( - InvalidAPIKeyError, - InvalidCredentialsError, - ProviderConfigError, - ProviderNotFoundError, - ) + from agent_sandbox.models.errors import InvalidCredentialsError, ProviderConfigError - if live._installed("alicloud-container"): - with pytest.raises(ProviderNotFoundError): - live.run(live._create_only("alicloud-container")) - return - with pytest.raises((InvalidAPIKeyError, InvalidCredentialsError, ProviderConfigError)): + with pytest.raises((InvalidCredentialsError, ProviderConfigError)): live.run(live._create_only("alicloud-container")) diff --git a/e2e/test_alicloud_container_native.py b/e2e/test_alicloud_container_native.py new file mode 100644 index 0000000..4ab69d6 --- /dev/null +++ b/e2e/test_alicloud_container_native.py @@ -0,0 +1,95 @@ +"""Native Client SDK verification against an existing Container Edition cluster.""" + +from __future__ import annotations + +import os +from typing import TYPE_CHECKING + +import e2e_helpers as H # noqa: N812 +import pytest + +from agent_sandbox._version import __version__ +from agent_sandbox.models.errors import SandboxNotFoundError +from agent_sandbox.models.sandbox import SandboxConfig +from agent_sandbox.providers import ProviderClient, ProviderLock +from agent_sandbox.transport.config import TransportConfig + +if TYPE_CHECKING: + from collections.abc import Callable, Coroutine + from typing import Any + +pytestmark = pytest.mark.provider_live + + +@pytest.mark.parametrize("interpreter", [False, True], ids=["basic", "jupyter"]) +def test_alicloud_container_native( + run: Callable[[Coroutine[Any, Any, None]], None], interpreter: bool +) -> None: + provider = "alicloud-container" + base = os.environ.get("ABX_ALICLOUD_CONTAINER_BASE_URL", "").strip() + domain = os.environ.get("ABX_ALICLOUD_CONTAINER_DOMAIN", "").strip() + key = os.environ.get("ABX_ALICLOUD_CONTAINER_API_KEY", "").strip() + if not key or not (base or domain): + pytest.skip( + "Set Container Edition API key and domain or private API URL for a live cluster." + ) + env_name = "E2E_CONTAINER_JUPYTER_SANDBOX_SET" if interpreter else "E2E_CONTAINER_SANDBOX_SET" + template = os.environ.get(env_name, "").strip() + if not template: + pytest.skip(f"Set {env_name} to an existing SandboxSet name.") + options = { + "api_key": key, + "protocol": os.environ.get("ABX_ALICLOUD_CONTAINER_PROTOCOL", "native"), + } + if base: + options["base_url"] = base + if domain: + options["domain"] = domain + run( + _exercise( + ProviderLock(provider=provider, version=__version__), + TransportConfig(provider=provider, provider_options=options), + template=template, + interpreter=interpreter, + ) + ) + + +async def _exercise( + lock: ProviderLock, config: TransportConfig, *, template: str, interpreter: bool +) -> None: + owned: list[str] = [] + async with await ProviderClient.prepare(lock, config) as client: + assert client.implementation == "python-native" + try: + sandbox = await client.create( + SandboxConfig(template=template, timeout=300, metadata=H.tag_metadata("container")), + on_created=owned.append, + ) + try: + result = await sandbox.commands.run("printf container-native") + assert result.exit_code == 0 and result.stdout == "container-native" + path = "/tmp/container-native-roundtrip.txt" + await sandbox.files.write(path, "roundtrip") + assert await sandbox.files.read(path) == "roundtrip" + await sandbox.files.remove(path) + if interpreter: + code = await sandbox.run_code("print(42)", mode="default-context") + assert code.exit_code == 0 and code.stdout.strip() == "42" + assert (await client.get(sandbox.id)).sandbox_id == sandbox.id + await client.set_timeout(sandbox.id, 300) + port = 49999 if interpreter else 49983 + url, _ = await sandbox.network.resolve(port) + assert str(port) in url + finally: + await sandbox.close() + attached = await client.connect(sandbox.id) + try: + assert attached.id == sandbox.id + finally: + await attached.close() + finally: + for sandbox_id in owned: + await client.delete(sandbox_id) + with pytest.raises(SandboxNotFoundError): + await client.get(sandbox_id)