From 350deeb65180317e3da96faf40154a77922d573d Mon Sep 17 00:00:00 2001 From: "guning.lt" Date: Thu, 26 Nov 2026 11:37:43 +0800 Subject: [PATCH 1/7] sandbox api --- MANIFEST.in | 1 + dashscope/applications/agentstudio/client.py | 50 +- .../agentstudio/sandbox/__init__.py | 113 ++ .../agentstudio/sandbox/_bootstrap.py | 523 +++++++ .../agentstudio/sandbox/_validation.py | 124 ++ .../agentstudio/sandbox/agents.py | 778 +++++++++++ .../agentstudio/sandbox/client.py | 79 ++ .../agentstudio/sandbox/exceptions.py | 42 + .../agentstudio/sandbox/models.py | 575 ++++++++ .../agentstudio/sandbox/sandboxes.py | 280 ++++ .../agentstudio/sandbox/streaming.py | 394 ++++++ .../agentstudio/sandbox/template_files.py | 239 ++++ .../agentstudio/sandbox/templates.py | 233 ++++ .../agentstudio/sandbox/transport.py | 475 +++++++ .../sandbox/web-preview/preview.mjs | 313 +++++ .../agentstudio/sandbox/web_ui.py | 451 ++++++ dashscope/client.py | 20 +- dashscope/version.py | 2 +- tests/agentstudio_sandbox/test_agents.py | 590 ++++++++ tests/agentstudio_sandbox/test_client.py | 532 +++++++ tests/agentstudio_sandbox/test_resources.py | 1028 ++++++++++++++ tests/agentstudio_sandbox/test_stream.py | 487 +++++++ tests/agentstudio_sandbox/test_web_ui.py | 1233 +++++++++++++++++ 23 files changed, 8551 insertions(+), 11 deletions(-) create mode 100644 dashscope/applications/agentstudio/sandbox/__init__.py create mode 100644 dashscope/applications/agentstudio/sandbox/_bootstrap.py create mode 100644 dashscope/applications/agentstudio/sandbox/_validation.py create mode 100644 dashscope/applications/agentstudio/sandbox/agents.py create mode 100644 dashscope/applications/agentstudio/sandbox/client.py create mode 100644 dashscope/applications/agentstudio/sandbox/exceptions.py create mode 100644 dashscope/applications/agentstudio/sandbox/models.py create mode 100644 dashscope/applications/agentstudio/sandbox/sandboxes.py create mode 100644 dashscope/applications/agentstudio/sandbox/streaming.py create mode 100644 dashscope/applications/agentstudio/sandbox/template_files.py create mode 100644 dashscope/applications/agentstudio/sandbox/templates.py create mode 100644 dashscope/applications/agentstudio/sandbox/transport.py create mode 100644 dashscope/applications/agentstudio/sandbox/web-preview/preview.mjs create mode 100644 dashscope/applications/agentstudio/sandbox/web_ui.py create mode 100644 tests/agentstudio_sandbox/test_agents.py create mode 100644 tests/agentstudio_sandbox/test_client.py create mode 100644 tests/agentstudio_sandbox/test_resources.py create mode 100644 tests/agentstudio_sandbox/test_stream.py create mode 100644 tests/agentstudio_sandbox/test_web_ui.py diff --git a/MANIFEST.in b/MANIFEST.in index 3d855be6..2a11a285 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -5,3 +5,4 @@ include NOTICE include LICENSE.certifi recursive-include examples *.md *.py include requirements.txt +include dashscope/applications/agentstudio/sandbox/web-preview/preview.mjs diff --git a/dashscope/applications/agentstudio/client.py b/dashscope/applications/agentstudio/client.py index 90dd9b32..1bd8bfb2 100644 --- a/dashscope/applications/agentstudio/client.py +++ b/dashscope/applications/agentstudio/client.py @@ -147,6 +147,14 @@ def _user_agent(base_url: str) -> str: return f"dashscope-agentstudio-python/{__version__} (+{base_url})" +def _sandbox_timeout(value) -> float: + if isinstance(value, httpx.Timeout): + value = value.read + elif isinstance(value, tuple): + value = value[1] + return 30.0 if value is None else float(value) + + class Client: """Synchronous AgentStudio client. @@ -218,9 +226,28 @@ def __init__( self.webhook_endpoints = WebhookEndpoints(self) self.security = Security(self) self.usage = Usage(self) + self._sandbox = None + + @property + def sandbox(self): + """Sandbox lifecycle and Harness Agent APIs, mounted on first use.""" + if self._sandbox is None: + from .sandbox import SandboxClient + + self._sandbox = SandboxClient( + base_url=self.transport.base_url, + api_key=self.transport.api_key, + timeout=_sandbox_timeout(self.transport.timeout), + http_client=self.transport._client, + ) + return self._sandbox def close(self) -> None: - self.transport.close() + try: + if self._sandbox is not None: + self._sandbox.close() + finally: + self.transport.close() def __enter__(self) -> "Client": return self @@ -301,9 +328,28 @@ def __init__( self.webhook_endpoints = AsyncWebhookEndpoints(self) self.security = AsyncSecurity(self) self.usage = AsyncUsage(self) + self._sandbox = None + + @property + def sandbox(self): + """Asynchronous Sandbox sub-client, sharing this client's HTTP pool.""" + if self._sandbox is None: + from .sandbox import AsyncSandboxClient + + self._sandbox = AsyncSandboxClient( + base_url=self.transport.base_url, + api_key=self.transport.api_key, + timeout=_sandbox_timeout(self.transport.timeout), + http_client=self.transport._client, + ) + return self._sandbox async def aclose(self) -> None: - await self.transport.aclose() + try: + if self._sandbox is not None: + await self._sandbox.aclose() + finally: + await self.transport.aclose() async def __aenter__(self) -> "AsyncClient": return self diff --git a/dashscope/applications/agentstudio/sandbox/__init__.py b/dashscope/applications/agentstudio/sandbox/__init__.py new file mode 100644 index 00000000..532ceeef --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/__init__.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Sandbox lifecycle, Harness Agents, files and local native Web UI.""" + +from .agents import ( + AgentHandle, + AgentsClient, + AsyncAgentHandle, + AsyncAgentsClient, + AsyncLaunchOperation, + AsyncOperationHandle, + AsyncSessionHandle, + AsyncTurnHandle, + LaunchOperation, + OperationHandle, + SessionHandle, + TurnHandle, +) +from .client import AsyncSandboxClient, SandboxClient +from .exceptions import SandboxAPIError, SandboxWaitTimeoutError +from .models import ( + AgentInstanceInfo, + AgentOperationInfo, + AgentPage, + AgentSessionInfo, + AgentTemplateConfig, + AgentTurnInfo, + BuildStatus, + Compute, + ConnectionOptions, + FileMount, + LaunchRequest, + ModelConfig, + OfficialImage, + SandboxConnection, + SandboxCreateRequest, + SandboxInfo, + TemplateCreateRequest, + TemplateFile, + TemplateInfo, + TemplateMount, + TemplateUpdateRequest, + TurnResult, + UploadedFile, + UploadRequest, + UploadTicket, +) +from .sandboxes import ( + AsyncSandboxHandle, + AsyncSandboxesClient, + SandboxHandle, + SandboxesClient, +) +from .streaming import AsyncEventSubscription, EventSubscription +from .template_files import AsyncTemplateFilesClient, TemplateFilesClient +from .templates import AsyncTemplatesClient, TemplatesClient +from .web_ui import SandboxWebUi, WebUiOptions + +__all__ = [ + "SandboxClient", + "AsyncSandboxClient", + "SandboxAPIError", + "SandboxWaitTimeoutError", + "OfficialImage", + "ModelConfig", + "LaunchRequest", + "Compute", + "FileMount", + "TemplateCreateRequest", + "TemplateUpdateRequest", + "SandboxCreateRequest", + "ConnectionOptions", + "SandboxConnection", + "SandboxInfo", + "TemplateInfo", + "TemplateMount", + "BuildStatus", + "AgentInstanceInfo", + "AgentOperationInfo", + "AgentPage", + "AgentSessionInfo", + "AgentTurnInfo", + "AgentTemplateConfig", + "TurnResult", + "UploadedFile", + "TemplateFile", + "UploadTicket", + "UploadRequest", + "AgentsClient", + "AsyncAgentsClient", + "AgentHandle", + "AsyncAgentHandle", + "SessionHandle", + "AsyncSessionHandle", + "TurnHandle", + "AsyncTurnHandle", + "OperationHandle", + "AsyncOperationHandle", + "LaunchOperation", + "AsyncLaunchOperation", + "EventSubscription", + "AsyncEventSubscription", + "SandboxesClient", + "AsyncSandboxesClient", + "SandboxHandle", + "AsyncSandboxHandle", + "TemplatesClient", + "AsyncTemplatesClient", + "TemplateFilesClient", + "AsyncTemplateFilesClient", + "SandboxWebUi", + "WebUiOptions", +] diff --git a/dashscope/applications/agentstudio/sandbox/_bootstrap.py b/dashscope/applications/agentstudio/sandbox/_bootstrap.py new file mode 100644 index 00000000..17840fd7 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/_bootstrap.py @@ -0,0 +1,523 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Private, bounded envd bootstrap for image-native Web UIs.""" + +import base64 +import binascii +import json +import re +import shlex +import struct +import uuid +from dataclasses import dataclass, field +from urllib.parse import urljoin, urlsplit + +import httpx + +from .exceptions import SandboxAPIError + +_MAX_RESPONSE = 2 * 1024 * 1024 +_DSH_PATCH = "/home/user/.dsh/native-web-preview.json" +_DSH_CREDENTIALS = "/home/user/.dsh/.credentials.yaml" +_OPENCLAW_DIR = "/home/user/.openclaw/sdk-web-preview" +_OPENCLAW_KEY = _OPENCLAW_DIR + "/model.key" + +_DSH_START = r"""umask 077 +wrapper=$(mktemp -d) +trap 'rm -rf -- "$wrapper"' EXIT +cat > "$wrapper/dsh" <<'SH' +#!/bin/bash +if [ "$1" != web ]; then + exec /home/user/.dsh/bin/dsh "$@" +fi +shift +if [ "$DSH_PREVIEW_FRESH" = true ]; then + unset DASHSCOPE_API_KEY DEEPSEEK_API_KEY +fi +if [ "${DEEPSEEK_API_KEY:-}" = "$DSH_PREVIEW_PLACEHOLDER" ]; then + unset DEEPSEEK_API_KEY +fi +unset DSH_PREVIEW_PLACEHOLDER +if [ -f "$DSH_PREVIEW_PATCH" ]; then + exec /home/user/.dsh/bin/dsh --profile web --patch "$DSH_PREVIEW_PATCH" "$@" +fi +exec /home/user/.dsh/bin/dsh web "$@" +SH +chmod 700 "$wrapper/dsh" +export PATH="$wrapper:$PATH" DSH_PREVIEW_PATCH="$1" DSH_PREVIEW_FRESH="$3" +# 仅供镜像脚本启动检查。启动 DSH 进程前移除占位值。 +export DSH_PREVIEW_PLACEHOLDER=unused-preview-placeholder +DEEPSEEK_API_KEY="${DEEPSEEK_API_KEY:-$DSH_PREVIEW_PLACEHOLDER}" /opt/deepseek-harness/start.sh --trusted-host "$2" +""" + +_OPENCLAW_START = r"""umask 077 +dir="$1" +patch="$2" +port="$3" +binary=/home/user/.openclaw/bin/openclaw +node=/home/user/.openclaw/tools/node/bin/node +pid_file="$dir/gateway.pid" +token_file="$dir/gateway.token" +export OPENCLAW_CONFIG_PATH="$dir/openclaw.json" + +exec 9>"$dir/start.lock" +trap 'rm -f -- "$patch"' EXIT +flock -w 15 9 +health() { curl --noproxy '*' -fsS --max-time 1 "http://127.0.0.1:$port/healthz" >/dev/null 2>&1; } +if [ -n "$(ss -H -ltn "sport = :$port")" ]; then + pid=$(cat "$pid_file" 2>/dev/null || true) + if [[ "$pid" =~ ^[1-9][0-9]*$ ]] && [ -s "$token_file" ] && + grep -zFxq "OPENCLAW_CONFIG_PATH=$OPENCLAW_CONFIG_PATH" "/proc/$pid/environ" 2>/dev/null && + health; then + printf 'OPENCLAW_WEB_TOKEN=%s\n' "$(cat "$token_file")" + else + printf 'OPENCLAW_WEB_PORT_IN_USE\n' + fi + exit 0 +fi + +if [ ! -s "$token_file" ]; then + "$node" -e 'process.stdout.write(require("node:crypto").randomBytes(32).toString("hex"))' > "$token_file" +fi +export OPENCLAW_GATEWAY_TOKEN="$(cat "$token_file")" +if [ ! -e "$OPENCLAW_CONFIG_PATH" ] && [ -f /home/user/.openclaw/openclaw.json ]; then + cp /home/user/.openclaw/openclaw.json "$OPENCLAW_CONFIG_PATH" +fi +"$binary" config patch --file "$patch" > "$dir/setup.log" 2>&1 +nohup "$binary" gateway run --bind lan --auth token --port "$port" > "$dir/gateway.log" 2>&1 &- & +pid=$! +trap 'kill "$pid" 2>/dev/null || true; rm -f -- "$patch"' EXIT +deadline=$((SECONDS + 40)) +while (( SECONDS < deadline )); do + kill -0 "$pid" 2>/dev/null || exit 1 + if health; then + printf '%s\n' "$pid" > "$pid_file" + trap 'rm -f -- "$patch"' EXIT + printf 'OPENCLAW_WEB_TOKEN=%s\n' "$OPENCLAW_GATEWAY_TOKEN" + exit 0 + fi + sleep 0.5 +done +exit 1 +""" + +_OPENCLAW_PREPARE = r"""umask 077 +install -d -m 700 "$1" +set -C +: > "$2" +if [ "$3" = true ]; then : > "$4"; fi +""" + +_OPENCLAW_APPROVE = r"""export OPENCLAW_CONFIG_PATH="$1/openclaw.json" +OPENCLAW_GATEWAY_TOKEN=$(cat "$1/gateway.token") +export OPENCLAW_GATEWAY_TOKEN +unset OPENCLAW_GATEWAY_URL +exec /home/user/.openclaw/bin/openclaw devices approve "$2" --json +""" + + +def _endpoint(value): + try: + parsed = urlsplit(value) + local = parsed.scheme == "http" and parsed.hostname == "127.0.0.1" + if ( + not parsed.hostname + or parsed.username is not None + or parsed.password is not None + or parsed.query + or parsed.fragment + or not (parsed.scheme == "https" or local) + or any(ord(char) < 33 for char in value) + ): + raise ValueError() + parsed.port + return value if value.endswith("/") else value + "/" + except (TypeError, ValueError): + raise OSError("Invalid Sandbox endpoint") from None + + +@dataclass(frozen=True) +class _Route: + upstream: str + login_token: str = field(repr=False) + headers: dict = field(repr=False) + openclaw: bool + bootstrap: object = field(repr=False) + + +class _Bootstrap: + def __init__(self, sandbox_id, connection): + self.sandbox_id = sandbox_id + self.connection = connection + self.envd = _endpoint(connection.envd_url) + + def _send(self, path, data, headers=None, params=None): + headers = dict(headers or {}) + headers.update( + { + "Authorization": "Basic dXNlcjo=", + "X-Access-Token": self.connection.envd_access_token, + "E2B-Sandbox-Id": self.sandbox_id, + "E2B-Sandbox-Port": "49983", + "Accept-Encoding": "identity", + } + ) + if self.connection.traffic_access_token: + headers["E2B-Traffic-Access-Token"] = self.connection.traffic_access_token + try: + with httpx.Client(timeout=90.0, follow_redirects=False) as client: + with client.stream( + "POST", + urljoin(self.envd, path), + content=data, + headers=headers, + params=params, + ) as response: + if not 200 <= response.status_code < 300: + raise OSError( + "Sandbox data-plane HTTP " + str(response.status_code) + ) + body = bytearray() + for chunk in response.iter_bytes(): + if len(body) + len(chunk) > _MAX_RESPONSE: + raise OSError("Sandbox response exceeds its size limit") + body.extend(chunk) + return bytes(body) + except httpx.HTTPError: + # envd 地址和临时凭据不进入异常文本。 + raise OSError("Sandbox data-plane request failed") from None + + def command(self, argv): + # 参数只进入引用后的 argv,不拼接用户提供的 shell 片段。 + process = { + "cmd": "/bin/sh", + "cwd": "/home/user", + "args": ["-ec", "exec " + " ".join(shlex.quote(arg) for arg in argv)], + } + message = json.dumps( + {"stdin": False, "process": process}, separators=(",", ":") + ).encode() + payload = b"\0" + struct.pack(">I", len(message)) + message + return _stdout( + self._send( + "process.Process/Start", + payload, + { + "Content-Type": "application/connect+json", + "Connect-Protocol-Version": "1", + "connect-content-encoding": "identity", + }, + ) + ) + + def put_file(self, path, data): + self._send( + "files", + data, + {"Content-Type": "application/octet-stream"}, + {"path": path, "username": "user"}, + ) + + def put_json(self, path, value): + self.put_file(path, json.dumps(value, separators=(",", ":")).encode()) + + def start_dsh(self, host, fresh, model_url, model_id, model_key): + if fresh and model_url: + _configure_dsh_model(self, model_url, model_id, model_key) + output = self.command( + [ + "/bin/bash", + "-ec", + _DSH_START, + "start-dsh-web", + _DSH_PATCH, + host, + str(fresh).lower(), + ] + ) + return _read_token(output, "DSH_WEB_TOKEN=") + + +def _stdout(response): + offset, started, ended, finished = 0, False, False, False + stdout = [] + while offset < len(response): + if len(response) - offset < 5 or finished: + raise OSError("Invalid Sandbox process stream") + flags, size = ( + response[offset], + struct.unpack(">I", response[offset + 1 : offset + 5])[0], + ) + offset += 5 + if flags not in (0, 2) or size > len(response) - offset: + raise OSError("Invalid Sandbox process frame") + try: + value = json.loads(response[offset : offset + size]) + if not isinstance(value, dict): + raise ValueError() + except (UnicodeError, ValueError): + raise OSError("Invalid Sandbox process response") from None + offset += size + if flags == 2: + if not ended or value.get("error") is not None: + raise OSError("Sandbox process stream failed") + finished = True + continue + if ended: + raise OSError("Sandbox process returned data after exit") + event = value.get("event", {}) + if not isinstance(event, dict): + raise OSError("Invalid Sandbox process event") + if "start" in event: + start = event["start"] + pid = start.get("pid") if isinstance(start, dict) else None + if started or type(pid) is not int or pid <= 0: + raise OSError("Invalid Sandbox process start") + started = True + data = event.get("data", {}) + output = data.get("stdout") if isinstance(data, dict) else None + if isinstance(output, str) and started: + try: + stdout.append(base64.b64decode(output, validate=True).decode("utf-8")) + except (ValueError, UnicodeError, binascii.Error): + raise OSError("Invalid Sandbox process output") from None + if "end" in event: + end = event["end"] + if ( + not isinstance(end, dict) + or not started + or end.get("exited") is not True + or type(end.get("exitCode", 0)) is not int + or end.get("exitCode", 0) != 0 + or end.get("error") + ): + raise OSError("Sandbox process failed") + ended = True + if not ended: + raise OSError("Sandbox process did not confirm its exit") + return "".join(stdout) + + +def _read_token(stdout, prefix): + for line in stdout.splitlines(): + if line.startswith(prefix): + token = line[len(prefix) :].strip() + if re.fullmatch(r"[A-Za-z0-9_-]+", token): + return token + raise OSError("Missing native Web UI token") + + +def _configure_dsh_model(bootstrap, url, model, key): + # 未传模型 Key 时,保留镜像自己的凭据文件。 + if key: + bootstrap.command( + [ + "/bin/sh", + "-ec", + 'umask 077; set -C; : > "$1"; : > "$2"', + "model-config", + _DSH_CREDENTIALS, + _DSH_PATCH, + ] + ) + bootstrap.put_json( + _DSH_CREDENTIALS, {"version": 1, "refs": {"DASHSCOPE_API_KEY": key}} + ) + else: + bootstrap.command( + [ + "/bin/sh", + "-ec", + 'umask 077; set -C; : > "$1"', + "model-config", + _DSH_PATCH, + ] + ) + bootstrap.put_json( + _DSH_PATCH, + [ + { + "id": "llm-pi-ai", + "config": { + "providers": { + "bailian-qwen": { + "displayName": "Bailian", + "apiKeyEnv": "DASHSCOPE_API_KEY", + "api": "openai-completions", + "baseURL": url, + "models": [{"id": model, "maxTokens": 8192}], + } + } + }, + }, + { + "id": "agent-default-model", + "config": {"provider": "bailian-qwen", "model": model}, + }, + ], + ) + + +def _openclaw_config(origin, configure_model, model_url, model_id, model_api, has_key): + config = { + "gateway": { + "mode": "local", + "bind": "lan", + "port": 18789, + "tls": {"enabled": False}, + "tailscale": {"mode": "off"}, + "auth": { + "mode": "token", + "allowTailscale": False, + "token": { + "source": "env", + "provider": "default", + "id": "OPENCLAW_GATEWAY_TOKEN", + }, + }, + "controlUi": { + "enabled": True, + "basePath": "", + "allowInsecureAuth": False, + "dangerouslyDisableDeviceAuth": False, + "dangerouslyAllowHostHeaderOriginFallback": False, + "allowedOrigins": [origin], + }, + } + } + if configure_model: + provider = { + "baseUrl": model_url, + "api": model_api or "openai-completions", + "models": [{"id": model_id, "name": model_id}], + } + config["models"] = {"providers": {"bailian-qwen": provider}} + if has_key: + config["secrets"] = { + "providers": { + "sdkwebmodel": { + "source": "file", + "mode": "singleValue", + "path": _OPENCLAW_KEY, + } + } + } + provider["apiKey"] = { + "source": "file", + "provider": "sdkwebmodel", + "id": "value", + } + config["agents"] = { + "defaults": {"model": {"primary": "bailian-qwen/" + model_id}} + } + return config + + +def _start_openclaw( + bootstrap, origin, fresh, model_url, model_id, model_key, model_api +): + patch = _OPENCLAW_DIR + "/patch-" + str(uuid.uuid4()) + ".json" + configure_model = fresh and bool(model_url) + write_key = configure_model and bool(model_key) + bootstrap.command( + [ + "/bin/sh", + "-ec", + _OPENCLAW_PREPARE, + "prepare-openclaw-web", + _OPENCLAW_DIR, + patch, + str(write_key).lower(), + _OPENCLAW_KEY, + ] + ) + if write_key: + bootstrap.put_file(_OPENCLAW_KEY, model_key.encode()) + bootstrap.put_json( + patch, + _openclaw_config( + origin, configure_model, model_url, model_id, model_api, write_key + ), + ) + output = bootstrap.command( + [ + "/bin/bash", + "-ec", + _OPENCLAW_START, + "start-openclaw-web", + _OPENCLAW_DIR, + patch, + "18789", + ] + ) + if "OPENCLAW_WEB_PORT_IN_USE" in output.splitlines(): + raise SandboxAPIError( + "OpenClaw port 18789 is in use by a Gateway this preview did not start", + code="WEB_UI_PORT_IN_USE", + ) + return _read_token(output, "OPENCLAW_WEB_TOKEN=") + + +def _approve_pairing(bootstrap, request_id): + if not re.fullmatch( + r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", request_id + ): + raise OSError("Invalid OpenClaw pairing request ID") + bootstrap.command( + [ + "/bin/sh", + "-ec", + _OPENCLAW_APPROVE, + "approve-openclaw-device", + _OPENCLAW_DIR, + request_id, + ] + ) + + +def prepare( + sandbox_id, + connection, + image, + fresh, + model_url="", + model_id="", + model_key="", + model_api="", +): + from .models import OfficialImage + + if connection is None or not connection.domain or not connection.envd_access_token: + raise OSError("Incomplete Sandbox connection information") + openclaw = image == OfficialImage.OPENCLAW + port = 18789 if openclaw else 8080 + host = str(port) + "-" + sandbox_id + "." + connection.domain + upstream = _endpoint("https://" + host) + if urlsplit(upstream).netloc != host or urlsplit(upstream).hostname != host: + raise OSError("Invalid Sandbox Web endpoint") + bootstrap = _Bootstrap(sandbox_id, connection) + token = ( + _start_openclaw( + bootstrap, + "https://" + host, + fresh, + model_url, + model_id, + model_key, + model_api, + ) + if openclaw + else bootstrap.start_dsh(host, fresh, model_url, model_id, model_key) + ) + headers = {} + if connection.traffic_access_token: + headers["e2b-traffic-access-token"] = connection.traffic_access_token + if openclaw: + headers.update( + { + "x-access-token": connection.envd_access_token, + "e2b-sandbox-id": sandbox_id, + "e2b-sandbox-port": str(port), + } + ) + return _Route(upstream, token, headers, openclaw, bootstrap) diff --git a/dashscope/applications/agentstudio/sandbox/_validation.py b/dashscope/applications/agentstudio/sandbox/_validation.py new file mode 100644 index 00000000..290f19bb --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/_validation.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Validation at public input and protocol boundaries.""" + +from __future__ import annotations + +import math +import time +from datetime import timedelta +from numbers import Real +from typing import BinaryIO, Iterator, Optional +from urllib.parse import quote, urlsplit, urlunsplit + +from .exceptions import SandboxWaitTimeoutError + + +def required(value: str, name: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{name} must be a non-empty string") + return value + + +def resource_id(value: str) -> str: + required(value, "resource_id") + if ( + len(value) > 256 + or value in (".", "..") + or any(ord(c) < 33 or ord(c) == 127 or c in "/\\?#%" for c in value) + ): + raise ValueError("Invalid resource ID") + return quote(value, safe="-._~") + + +def positive(value: Real, name: str) -> float: + if isinstance(value, bool) or not isinstance(value, Real): + raise ValueError(f"{name} must be a positive duration") + result = float(value) + if not math.isfinite(result) or result <= 0: + raise ValueError(f"{name} must be a positive duration") + return result + + +def seconds( + value: Real, + name: str, + minimum: int = 1, + maximum: Optional[int] = None, +) -> int: + if isinstance(value, timedelta): + value = value.total_seconds() + result = positive(value, name) + if not result.is_integer() or result < minimum: + raise ValueError(f"{name} must be whole seconds >= {minimum}") + if maximum is not None and result > maximum: + raise ValueError(f"{name} exceeds the maximum {maximum}") + return int(result) + + +def deadline(wait: Real) -> float: + return time.monotonic() + positive(wait, "timeout") + + +def remaining(end: float, resource_id: str, status: str) -> float: + result = end - time.monotonic() + if result <= 0: + raise SandboxWaitTimeoutError(resource_id, status) + return result + + +def filename(value: str) -> str: + required(value, "filename") + if ( + value in (".", "..") + or "/" in value + or "\\" in value + or any(ord(c) < 32 or ord(c) == 127 for c in value) + ): + raise ValueError("filename must be a file name without path components") + return value + + +def http_url(value: str, name: str = "base_url") -> str: + required(value, name) + try: + parsed = urlsplit(value) + port = parsed.port + except ValueError: + raise ValueError(f"{name} must be a valid HTTP(S) URL") from None + if ( + parsed.scheme not in ("http", "https") + or not parsed.hostname + or parsed.username is not None + or parsed.password is not None + or parsed.query + or parsed.fragment + or any(ord(c) < 33 or ord(c) == 127 for c in value) + or port == 0 + ): + raise ValueError(f"{name} must be an HTTP(S) URL without credentials or query") + return urlunsplit((parsed.scheme, parsed.netloc, parsed.path.rstrip("/"), "", "")) + + +def bounded_stream(stream: BinaryIO, limit: int, size: int = -1) -> Iterator[bytes]: + """Upload in chunks and close the supplied content on every exit path.""" + count = 0 + try: + if isinstance(size, bool) or size < -1: + raise ValueError("size_bytes must be nonnegative or -1") + if size > limit: + raise ValueError("File exceeds the instance upload limit") + while True: + chunk = stream.read(65536) + if not chunk: + break + if not isinstance(chunk, bytes): + raise ValueError("Upload content must be a binary stream") + count += len(chunk) + if count > limit or (size >= 0 and count > size): + raise ValueError("File exceeds the instance upload limit") + yield chunk + if size >= 0 and count != size: + raise ValueError("Upload size does not match the supplied content") + finally: + stream.close() diff --git a/dashscope/applications/agentstudio/sandbox/agents.py b/dashscope/applications/agentstudio/sandbox/agents.py new file mode 100644 index 00000000..c57dfbd8 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/agents.py @@ -0,0 +1,778 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Managed Harness Agent instances, sessions, turns, and operations.""" + +from __future__ import annotations + +import asyncio +import time +from pathlib import Path +from typing import Any, BinaryIO, Optional, Sequence, Union + +from .exceptions import SandboxAPIError, SandboxWaitTimeoutError +from .models import ( + AgentInstanceInfo, + AgentOperationInfo, + AgentPage, + AgentSessionInfo, + AgentTemplateConfig, + AgentTurnInfo, + LaunchRequest, + TurnResult, + UploadedFile, +) +from .streaming import AsyncEventSubscription, EventSubscription +from .transport import AGENT, AsyncTransport, Transport +from ._validation import ( + bounded_stream, + deadline, + filename, + remaining, + required, + resource_id, + seconds, +) + +_DEFAULT_UPLOAD_LIMIT = 16 * 1024 * 1024 +_OPERATION_TERMINAL = frozenset(("SUCCEEDED", "FAILED", "UNKNOWN")) +_TURN_TERMINAL = _OPERATION_TERMINAL | {"CANCELLED"} + + +def _page_params(limit: int, cursor: Optional[str]) -> dict: + if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 100: + raise ValueError("limit must be between 1 and 100") + params: dict[str, Any] = {"limit": limit} + if cursor is not None: + params["cursor"] = required(cursor, "cursor") + return params + + +def _response_id(data: dict, name: str) -> str: + value = data.get(name) + if not isinstance(value, str) or not value.strip(): + raise SandboxAPIError("Missing response identifier", code="INVALID_RESPONSE") + resource_id(value) + return value + + +def _operation_result(info: AgentOperationInfo) -> AgentOperationInfo: + if info.status in ("FAILED", "UNKNOWN"): + error = info.error + code = error.get("code") if isinstance(error, dict) else None + failure = SandboxAPIError( + "Operation {} ended with {}".format(info.id, info.status), + code=code or "OPERATION_" + info.status, + outcome_unknown=info.status == "UNKNOWN", + ) + failure.resource_id = info.id + failure.status = info.status + raise failure + return info + + +def _wait( + transport: Transport, + path: str, + identifier: str, + timeout: float, + terminal: frozenset, +) -> dict: + end = deadline(timeout) + status = "UNKNOWN" + while True: + budget = remaining(end, identifier, status) + try: + data = transport.request( + "GET", path, agent=True, timeout=min(transport.timeout, budget) + ) + except SandboxAPIError as error: + if error.code == "REQUEST_TIMEOUT" and budget <= transport.timeout: + raise SandboxWaitTimeoutError(identifier, status) from error + raise + status = required(data.get("status"), "response status") + remaining(end, identifier, status) + if status in terminal: + return data + time.sleep(min(transport.poll_interval, remaining(end, identifier, status))) + + +async def _await( + transport: AsyncTransport, + path: str, + identifier: str, + timeout: float, + terminal: frozenset, +) -> dict: + end = deadline(timeout) + status = "UNKNOWN" + while True: + budget = remaining(end, identifier, status) + try: + data = await transport.request( + "GET", path, agent=True, timeout=min(transport.timeout, budget) + ) + except SandboxAPIError as error: + if error.code == "REQUEST_TIMEOUT" and budget <= transport.timeout: + raise SandboxWaitTimeoutError(identifier, status) from error + raise + status = required(data.get("status"), "response status") + remaining(end, identifier, status) + if status in terminal: + return data + await asyncio.sleep( + min(transport.poll_interval, remaining(end, identifier, status)) + ) + + +def _prompt( + text: str, + files: Sequence[UploadedFile], + deadline_seconds: int, + instance_id: Optional[str], +) -> dict: + required(text, "text") + if len(text.encode("utf-8")) > 1024 * 1024: + raise ValueError("text must contain at most 1048576 UTF-8 bytes") + duration = seconds(deadline_seconds, "deadline_seconds", maximum=3600) + if len(files) > 16: + raise ValueError("A prompt can reference at most 16 files") + identifiers = [] + owner = instance_id + for file in files: + if not isinstance(file, UploadedFile): + raise ValueError("files must contain uploaded file references") + resource_id(file.id) + if file.id in identifiers: + raise ValueError("files must contain unique uploaded files") + if owner is None: + owner = file.instance_id + if owner != file.instance_id: + raise ValueError("files must belong to this instance") + identifiers.append(file.id) + body: dict[str, Any] = { + "input": [{"type": "text", "text": text}], + "deadline_seconds": duration, + } + if identifiers: + body["attachment_ids"] = identifiers + return body + + +def _upload_source( + name_or_path: Union[str, Path], stream: Optional[BinaryIO], size_bytes: int +) -> tuple[str, BinaryIO, int]: + if stream is None: + path = Path(name_or_path) + if not path.is_file(): + raise ValueError("upload path must be a regular file") + name = filename(path.name) + source = path.open("rb") + try: + return name, source, path.stat().st_size + except BaseException: + source.close() + raise + try: + if ( + isinstance(size_bytes, bool) + or not isinstance(size_bytes, int) + or size_bytes < -1 + ): + raise ValueError("size_bytes must be nonnegative or -1") + return filename(name_or_path), stream, size_bytes + except BaseException: + stream.close() + raise + + +def _uploaded(data: dict, identifier: str, size: int) -> UploadedFile: + uploaded = UploadedFile.from_dict(data) + if uploaded.instance_id != identifier or ( + size >= 0 and uploaded.size_bytes != size + ): + raise SandboxAPIError( + "Uploaded file does not match the instance or size", code="INVALID_RESPONSE" + ) + return uploaded + + +class AgentsClient: + def __init__(self, transport: Transport): + self._transport = transport + + def template_config(self) -> AgentTemplateConfig: + return AgentTemplateConfig.from_dict( + self._transport.request("GET", AGENT + "/template-config", agent=True) + ) + + def launch_async(self, request: LaunchRequest) -> LaunchOperation: + """Accept a launch operation without waiting for the instance to become ready.""" + return self._launch(request) + + def _launch( + self, request: LaunchRequest, timeout: Optional[float] = None + ) -> LaunchOperation: + data = self._transport.request( + "POST", + AGENT + "/instances", + json=request.to_dict(), + agent=True, + timeout=timeout, + ) + return LaunchOperation( + self, _response_id(data, "instance_id"), _response_id(data, "operation_id") + ) + + def launch(self, request: LaunchRequest, timeout: float = 600) -> AgentHandle: + end = deadline(timeout) + operation = self._launch( + request, min(self._transport.timeout, remaining(end, "launch", "PENDING")) + ) + return operation.wait(remaining(end, operation.operation_id, "PENDING")) + + def list_instances( + self, limit: int = 50, cursor: Optional[str] = None + ) -> AgentPage[AgentInstanceInfo]: + data = self._transport.request( + "GET", AGENT + "/instances", params=_page_params(limit, cursor), agent=True + ) + return AgentPage[AgentInstanceInfo].from_dict(data) + + def get_instance(self, instance_id: str) -> AgentInstanceInfo: + return AgentInstanceInfo.from_dict( + self._transport.request( + "GET", AGENT + "/instances/" + resource_id(instance_id), agent=True + ) + ) + + def connect(self, instance_id: str) -> AgentHandle: + return self._connect(instance_id) + + def _connect( + self, instance_id: str, timeout: Optional[float] = None + ) -> AgentHandle: + data = self._transport.request( + "GET", + AGENT + "/instances/" + resource_id(instance_id), + timeout=timeout, + agent=True, + ) + info = AgentInstanceInfo.from_dict(data) + if info.state != "READY": + raise SandboxAPIError( + "Instance {} is not ready".format(instance_id), + code="INSTANCE_NOT_READY", + ) + return AgentHandle( + self._transport, + instance_id, + required(info.default_session_id, "default_session_id"), + info, + ) + + def release(self, instance_id: str) -> OperationHandle: + data = self._transport.request( + "DELETE", AGENT + "/instances/" + resource_id(instance_id), agent=True + ) + return self.operation(_response_id(data, "operation_id")) + + def operation(self, operation_id: str) -> OperationHandle: + return OperationHandle(self._transport, operation_id) + + def session(self, session_id: str) -> SessionHandle: + return SessionHandle(self._transport, session_id) + + def turn(self, turn_id: str) -> TurnHandle: + return TurnHandle(self._transport, turn_id) + + def list_sessions( + self, instance_id: str, limit: int = 50, cursor: Optional[str] = None + ) -> AgentPage[AgentSessionInfo]: + data = self._transport.request( + "GET", + AGENT + "/instances/" + resource_id(instance_id) + "/sessions", + params=_page_params(limit, cursor), + agent=True, + ) + return AgentPage[AgentSessionInfo].from_dict(data) + + +class LaunchOperation: + def __init__(self, agents: AgentsClient, instance_id: str, operation_id: str): + self._agents = agents + self.instance_id = instance_id + self.operation_id = operation_id + + def wait(self, timeout: float = 600) -> AgentHandle: + end = deadline(timeout) + self._agents.operation(self.operation_id).wait( + remaining(end, self.operation_id, "PENDING") + ) + budget = remaining(end, self.operation_id, "SUCCEEDED") + try: + handle = self._agents._connect( + self.instance_id, min(self._agents._transport.timeout, budget) + ) + except SandboxAPIError as error: + if ( + error.code == "REQUEST_TIMEOUT" + and budget <= self._agents._transport.timeout + ): + raise SandboxWaitTimeoutError(self.operation_id, "SUCCEEDED") from error + raise + remaining(end, self.operation_id, "SUCCEEDED") + return handle + + +class AgentHandle: + def __init__( + self, + transport: Transport, + instance_id: str, + default_session_id: str, + info: Optional[AgentInstanceInfo] = None, + ): + resource_id(instance_id) + self.id = instance_id + self._transport = transport + self._info = info + self.default_session = SessionHandle(transport, default_session_id, instance_id) + + def get(self) -> AgentInstanceInfo: + self._info = AgentsClient(self._transport).get_instance(self.id) + return self._info + + def get_info(self) -> AgentInstanceInfo: + return self.get() + + def new_session(self) -> SessionHandle: + data = self._transport.request( + "POST", + AGENT + "/instances/" + resource_id(self.id) + "/sessions", + json={}, + agent=True, + ) + return SessionHandle(self._transport, _response_id(data, "session_id"), self.id) + + def list_sessions( + self, limit: int = 50, cursor: Optional[str] = None + ) -> AgentPage[AgentSessionInfo]: + return AgentsClient(self._transport).list_sessions(self.id, limit, cursor) + + def upload( + self, + name_or_path: Union[str, Path], + stream: Optional[BinaryIO] = None, + size_bytes: int = -1, + ) -> UploadedFile: + """Stream a regular file or owned binary stream; the stream is always closed.""" + name, source, size = _upload_source(name_or_path, stream, size_bytes) + try: + info = self._info if self._info is not None else self.get() + limit = ( + info.max_upload_bytes + if info.max_upload_bytes is not None + else _DEFAULT_UPLOAD_LIMIT + ) + if size > limit: + raise ValueError("upload exceeds the instance upload limit") + headers = {"Content-Type": "application/octet-stream"} + if size >= 0: + headers["Content-Length"] = str(size) + data = self._transport.request( + "POST", + AGENT + "/instances/" + resource_id(self.id) + "/files", + params={"name": name}, + content=bounded_stream(source, limit, size), + headers=headers, + agent=True, + ) + return _uploaded(data, self.id, size) + finally: + source.close() + + def release(self) -> OperationHandle: + return AgentsClient(self._transport).release(self.id) + + +class SessionHandle: + def __init__( + self, transport: Transport, session_id: str, instance_id: Optional[str] = None + ): + self.id = session_id + self._transport = transport + self._instance_id = instance_id + self._path = AGENT + "/sessions/" + resource_id(session_id) + "/turns" + + def submit(self, text: str, deadline_seconds: int = 120) -> TurnHandle: + return self.submit_with_files(text, (), deadline_seconds) + + def submit_with_files( + self, text: str, files: Sequence[UploadedFile], deadline_seconds: int = 120 + ) -> TurnHandle: + body = _prompt(text, files, deadline_seconds, self._instance_id) + data = self._transport.request("POST", self._path, json=body, agent=True) + return TurnHandle(self._transport, _response_id(data, "turn_id")) + + def list_turns( + self, limit: int = 50, cursor: Optional[str] = None + ) -> AgentPage[AgentTurnInfo]: + data = self._transport.request( + "GET", self._path, params=_page_params(limit, cursor), agent=True + ) + return AgentPage[AgentTurnInfo].from_dict(data) + + +class OperationHandle: + def __init__(self, transport: Transport, operation_id: str): + self.id = operation_id + self._transport = transport + self._path = AGENT + "/operations/" + resource_id(operation_id) + + def get(self) -> AgentOperationInfo: + return AgentOperationInfo.from_dict( + self._transport.request("GET", self._path, agent=True) + ) + + def wait(self, timeout: float = 600) -> AgentOperationInfo: + info = AgentOperationInfo.from_dict( + _wait(self._transport, self._path, self.id, timeout, _OPERATION_TERMINAL) + ) + return _operation_result(info) + + +class TurnHandle: + def __init__(self, transport: Transport, turn_id: str): + self.id = turn_id + self._transport = transport + self._path = AGENT + "/turns/" + resource_id(turn_id) + + def get(self) -> TurnResult: + return TurnResult.from_dict( + self._transport.request("GET", self._path, agent=True) + ) + + def wait(self, timeout: float = 180) -> TurnResult: + return TurnResult.from_dict( + _wait(self._transport, self._path, self.id, timeout, _TURN_TERMINAL) + ) + + def cancel(self) -> TurnResult: + """Request cancellation; only a returned CANCELLED status confirms cancellation.""" + return TurnResult.from_dict( + self._transport.request("POST", self._path + "/cancel", agent=True) + ) + + def subscribe(self, callback=None, after_sequence: int = 0) -> EventSubscription: + return EventSubscription( + self._transport, self._path, self.id, after_sequence, callback + ) + + +class AsyncAgentsClient: + def __init__(self, transport: AsyncTransport): + self._transport = transport + + async def template_config(self) -> AgentTemplateConfig: + return AgentTemplateConfig.from_dict( + await self._transport.request("GET", AGENT + "/template-config", agent=True) + ) + + async def launch_async(self, request: LaunchRequest) -> AsyncLaunchOperation: + """Accept a launch operation without waiting for instance readiness.""" + return await self._launch(request) + + async def _launch( + self, request: LaunchRequest, timeout: Optional[float] = None + ) -> AsyncLaunchOperation: + data = await self._transport.request( + "POST", + AGENT + "/instances", + json=request.to_dict(), + agent=True, + timeout=timeout, + ) + return AsyncLaunchOperation( + self, _response_id(data, "instance_id"), _response_id(data, "operation_id") + ) + + async def launch( + self, request: LaunchRequest, timeout: float = 600 + ) -> AsyncAgentHandle: + end = deadline(timeout) + operation = await self._launch( + request, min(self._transport.timeout, remaining(end, "launch", "PENDING")) + ) + return await operation.wait(remaining(end, operation.operation_id, "PENDING")) + + async def list_instances( + self, limit: int = 50, cursor: Optional[str] = None + ) -> AgentPage[AgentInstanceInfo]: + data = await self._transport.request( + "GET", AGENT + "/instances", params=_page_params(limit, cursor), agent=True + ) + return AgentPage[AgentInstanceInfo].from_dict(data) + + async def get_instance(self, instance_id: str) -> AgentInstanceInfo: + return AgentInstanceInfo.from_dict( + await self._transport.request( + "GET", AGENT + "/instances/" + resource_id(instance_id), agent=True + ) + ) + + async def connect(self, instance_id: str) -> AsyncAgentHandle: + return await self._connect(instance_id) + + async def _connect( + self, instance_id: str, timeout: Optional[float] = None + ) -> AsyncAgentHandle: + data = await self._transport.request( + "GET", + AGENT + "/instances/" + resource_id(instance_id), + timeout=timeout, + agent=True, + ) + info = AgentInstanceInfo.from_dict(data) + if info.state != "READY": + raise SandboxAPIError( + "Instance {} is not ready".format(instance_id), + code="INSTANCE_NOT_READY", + ) + return AsyncAgentHandle( + self._transport, + instance_id, + required(info.default_session_id, "default_session_id"), + info, + ) + + async def release(self, instance_id: str) -> AsyncOperationHandle: + data = await self._transport.request( + "DELETE", AGENT + "/instances/" + resource_id(instance_id), agent=True + ) + return self.operation(_response_id(data, "operation_id")) + + def operation(self, operation_id: str) -> AsyncOperationHandle: + return AsyncOperationHandle(self._transport, operation_id) + + def session(self, session_id: str) -> AsyncSessionHandle: + return AsyncSessionHandle(self._transport, session_id) + + def turn(self, turn_id: str) -> AsyncTurnHandle: + return AsyncTurnHandle(self._transport, turn_id) + + async def list_sessions( + self, instance_id: str, limit: int = 50, cursor: Optional[str] = None + ) -> AgentPage[AgentSessionInfo]: + data = await self._transport.request( + "GET", + AGENT + "/instances/" + resource_id(instance_id) + "/sessions", + params=_page_params(limit, cursor), + agent=True, + ) + return AgentPage[AgentSessionInfo].from_dict(data) + + +class AsyncLaunchOperation: + def __init__(self, agents: AsyncAgentsClient, instance_id: str, operation_id: str): + self._agents = agents + self.instance_id = instance_id + self.operation_id = operation_id + + async def wait(self, timeout: float = 600) -> AsyncAgentHandle: + end = deadline(timeout) + await self._agents.operation(self.operation_id).wait( + remaining(end, self.operation_id, "PENDING") + ) + budget = remaining(end, self.operation_id, "SUCCEEDED") + try: + handle = await self._agents._connect( + self.instance_id, min(self._agents._transport.timeout, budget) + ) + except SandboxAPIError as error: + if ( + error.code == "REQUEST_TIMEOUT" + and budget <= self._agents._transport.timeout + ): + raise SandboxWaitTimeoutError(self.operation_id, "SUCCEEDED") from error + raise + remaining(end, self.operation_id, "SUCCEEDED") + return handle + + +class AsyncAgentHandle: + def __init__( + self, + transport: AsyncTransport, + instance_id: str, + default_session_id: str, + info: Optional[AgentInstanceInfo] = None, + ): + resource_id(instance_id) + self.id = instance_id + self._transport = transport + self._info = info + self.default_session = AsyncSessionHandle( + transport, default_session_id, instance_id + ) + + async def get(self) -> AgentInstanceInfo: + self._info = await AsyncAgentsClient(self._transport).get_instance(self.id) + return self._info + + async def get_info(self) -> AgentInstanceInfo: + return await self.get() + + async def new_session(self) -> AsyncSessionHandle: + data = await self._transport.request( + "POST", + AGENT + "/instances/" + resource_id(self.id) + "/sessions", + json={}, + agent=True, + ) + return AsyncSessionHandle( + self._transport, _response_id(data, "session_id"), self.id + ) + + async def list_sessions( + self, limit: int = 50, cursor: Optional[str] = None + ) -> AgentPage[AgentSessionInfo]: + return await AsyncAgentsClient(self._transport).list_sessions( + self.id, limit, cursor + ) + + async def upload( + self, + name_or_path: Union[str, Path], + stream: Optional[BinaryIO] = None, + size_bytes: int = -1, + ) -> UploadedFile: + """Stream a regular file or owned binary stream; the stream is always closed.""" + name, source, size = _upload_source(name_or_path, stream, size_bytes) + chunks = None + try: + info = self._info if self._info is not None else await self.get() + limit = ( + info.max_upload_bytes + if info.max_upload_bytes is not None + else _DEFAULT_UPLOAD_LIMIT + ) + if size > limit: + raise ValueError("upload exceeds the instance upload limit") + headers = {"Content-Type": "application/octet-stream"} + if size >= 0: + headers["Content-Length"] = str(size) + chunks = bounded_stream(source, limit, size) + sentinel = object() + + async def content(): + while True: + read = asyncio.create_task( + asyncio.to_thread(next, chunks, sentinel) + ) + try: + chunk = await asyncio.shield(read) + except asyncio.CancelledError: + # A running file read must finish before its owned stream closes. + await read + raise + if chunk is sentinel: + return + yield chunk + + data = await self._transport.request( + "POST", + AGENT + "/instances/" + resource_id(self.id) + "/files", + params={"name": name}, + content=content(), + headers=headers, + agent=True, + ) + return _uploaded(data, self.id, size) + finally: + if chunks is not None: + chunks.close() + source.close() + + async def release(self) -> AsyncOperationHandle: + return await AsyncAgentsClient(self._transport).release(self.id) + + +class AsyncSessionHandle: + def __init__( + self, + transport: AsyncTransport, + session_id: str, + instance_id: Optional[str] = None, + ): + self.id = session_id + self._transport = transport + self._instance_id = instance_id + self._path = AGENT + "/sessions/" + resource_id(session_id) + "/turns" + + async def submit(self, text: str, deadline_seconds: int = 120) -> AsyncTurnHandle: + return await self.submit_with_files(text, (), deadline_seconds) + + async def submit_with_files( + self, text: str, files: Sequence[UploadedFile], deadline_seconds: int = 120 + ) -> AsyncTurnHandle: + body = _prompt(text, files, deadline_seconds, self._instance_id) + data = await self._transport.request("POST", self._path, json=body, agent=True) + return AsyncTurnHandle(self._transport, _response_id(data, "turn_id")) + + async def list_turns( + self, limit: int = 50, cursor: Optional[str] = None + ) -> AgentPage[AgentTurnInfo]: + data = await self._transport.request( + "GET", self._path, params=_page_params(limit, cursor), agent=True + ) + return AgentPage[AgentTurnInfo].from_dict(data) + + +class AsyncOperationHandle: + def __init__(self, transport: AsyncTransport, operation_id: str): + self.id = operation_id + self._transport = transport + self._path = AGENT + "/operations/" + resource_id(operation_id) + + async def get(self) -> AgentOperationInfo: + return AgentOperationInfo.from_dict( + await self._transport.request("GET", self._path, agent=True) + ) + + async def wait(self, timeout: float = 600) -> AgentOperationInfo: + info = AgentOperationInfo.from_dict( + await _await( + self._transport, self._path, self.id, timeout, _OPERATION_TERMINAL + ) + ) + return _operation_result(info) + + +class AsyncTurnHandle: + def __init__(self, transport: AsyncTransport, turn_id: str): + self.id = turn_id + self._transport = transport + self._path = AGENT + "/turns/" + resource_id(turn_id) + + async def get(self) -> TurnResult: + return TurnResult.from_dict( + await self._transport.request("GET", self._path, agent=True) + ) + + async def wait(self, timeout: float = 180) -> TurnResult: + return TurnResult.from_dict( + await _await(self._transport, self._path, self.id, timeout, _TURN_TERMINAL) + ) + + async def cancel(self) -> TurnResult: + """Request cancellation; only a returned CANCELLED status confirms cancellation.""" + return TurnResult.from_dict( + await self._transport.request("POST", self._path + "/cancel", agent=True) + ) + + def subscribe( + self, callback=None, after_sequence: int = 0 + ) -> AsyncEventSubscription: + return AsyncEventSubscription( + self._transport, self._path, self.id, after_sequence, callback + ) diff --git a/dashscope/applications/agentstudio/sandbox/client.py b/dashscope/applications/agentstudio/sandbox/client.py new file mode 100644 index 00000000..420bc4d1 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/client.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Unified Sandbox client with four independent business facets.""" + +from __future__ import annotations + +from typing import Optional + +import httpx + +from .agents import AgentsClient, AsyncAgentsClient +from .sandboxes import AsyncSandboxesClient, SandboxesClient +from .template_files import AsyncTemplateFilesClient, TemplateFilesClient +from .templates import AsyncTemplatesClient, TemplatesClient +from .transport import AsyncTransport, Transport + + +class SandboxClient: + """Synchronous Sandbox API; model credentials are configured separately. + + ``close()`` closes local subscriptions and owned HTTP connections. Release + remote instances explicitly; close native previews before the client. + """ + + def __init__( + self, + *, + base_url: str, + api_key: str, + timeout: float = 30.0, + poll_interval: float = 0.35, + http_client: Optional[httpx.Client] = None, + ) -> None: + self._transport = Transport( + base_url, api_key, timeout, poll_interval, http_client + ) + self.agents = AgentsClient(self._transport) + self.sandboxes = SandboxesClient(self._transport) + self.templates = TemplatesClient(self._transport) + self.template_files = TemplateFilesClient(self._transport) + + def close(self) -> None: + self._transport.close() + + def __enter__(self) -> SandboxClient: + return self + + def __exit__(self, *exc) -> None: + self.close() + + +class AsyncSandboxClient: + """Asynchronous equivalent of :class:`SandboxClient`.""" + + def __init__( + self, + *, + base_url: str, + api_key: str, + timeout: float = 30.0, + poll_interval: float = 0.35, + http_client: Optional[httpx.AsyncClient] = None, + ) -> None: + self._transport = AsyncTransport( + base_url, api_key, timeout, poll_interval, http_client + ) + self.agents = AsyncAgentsClient(self._transport) + self.sandboxes = AsyncSandboxesClient(self._transport) + self.templates = AsyncTemplatesClient(self._transport) + self.template_files = AsyncTemplateFilesClient(self._transport) + + async def aclose(self) -> None: + await self._transport.aclose() + + async def __aenter__(self) -> AsyncSandboxClient: + return self + + async def __aexit__(self, *exc) -> None: + await self.aclose() diff --git a/dashscope/applications/agentstudio/sandbox/exceptions.py b/dashscope/applications/agentstudio/sandbox/exceptions.py new file mode 100644 index 00000000..ef7bb91d --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/exceptions.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Sandbox protocol errors; compatible with the main SDK error family.""" + +from typing import Any, Optional + +from dashscope.errors import DashScopeError + + +class SandboxAPIError(DashScopeError): + """A platform error, including an unconfirmed mutating request.""" + + def __init__( + self, + message: str, + *, + code: Optional[str] = None, + status_code: Optional[int] = None, + request_id: Optional[str] = None, + body: Any = None, + outcome_unknown: bool = False, + ) -> None: + super().__init__( + message, + code=code, + status_code=status_code, + request_id=request_id, + body=body, + ) + self.outcome_unknown = outcome_unknown + + +class SandboxWaitTimeoutError(SandboxAPIError, TimeoutError): + """Waiting ended; the resource ID remains usable for a later query.""" + + def __init__(self, resource_id: str, status: str) -> None: + super().__init__( + "Sandbox resource wait timed out", + code="WAIT_TIMEOUT", + ) + self.resource_id = resource_id + self.status = status diff --git a/dashscope/applications/agentstudio/sandbox/models.py b/dashscope/applications/agentstudio/sandbox/models.py new file mode 100644 index 00000000..8291f748 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/models.py @@ -0,0 +1,575 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Typed Sandbox inputs and responses, preserving the platform wire names.""" + +from __future__ import annotations + +from enum import Enum +from typing import Any, Dict, Generic, List, Literal, Mapping, Optional, TypeVar + +from pydantic import ( + AliasChoices, + BaseModel, + ConfigDict, + Field, + ValidationError, + field_serializer, + field_validator, + model_validator, +) + +from .exceptions import SandboxAPIError +from ._validation import http_url, required, resource_id, seconds + + +class Record(BaseModel): + model_config = ConfigDict( + populate_by_name=True, extra="allow", hide_input_in_errors=True + ) + + @classmethod + def from_dict(cls, data): + try: + return cls.model_validate(data) + except ValidationError: + raise SandboxAPIError( + "Invalid Sandbox response", code="INVALID_RESPONSE" + ) from None + + def to_dict(self) -> Dict[str, Any]: + return self.model_dump(mode="json", by_alias=True, exclude_none=True) + + def __repr__(self) -> str: + # 默认文本表示只展示资源标识和状态,连接凭据需由调用方显式读取。 + values = [] + for key in ("id", "status", "state"): + value = getattr(self, key, None) + if isinstance(value, str): + values.append(f"{key}={value!r}") + return f"{type(self).__name__}({', '.join(values)})" + + __str__ = __repr__ + + +class Input(Record): + model_config = ConfigDict( + populate_by_name=True, + extra="forbid", + hide_input_in_errors=True, + frozen=True, + ) + + +class OfficialImage(str, Enum): + CODE_INTERPRETER = "code-interpreter-v1" + BROWSER = "browser" + ALL_IN_ONE = "all-in-one" + DEEPSEEK_HARNESS = "deepseek-harness" + OPENCLAW = "openclaw" + + @property + def image_name(self) -> str: + return self.value + + @property + def supports_agent(self) -> bool: + return self in (self.DEEPSEEK_HARNESS, self.OPENCLAW) + + +class ModelConfig(Input): + base_url: Optional[str] = None + model_id: Optional[str] = None + api_key: Optional[str] = Field(default=None, repr=False) + + @field_validator("base_url", "model_id", "api_key", mode="before") + @classmethod + def trim_optional(cls, value): + if isinstance(value, str): + return value.strip() or None + return value + + @model_validator(mode="after") + def validate_model(self): + if not self.base_url and (self.model_id or self.api_key): + raise ValueError("base_url is required when configuring a model") + if self.base_url: + object.__setattr__(self, "base_url", http_url(self.base_url, "base_url")) + object.__setattr__(self, "model_id", self.model_id or "qwen3.7-plus") + return self + + +class Compute(Record): + cpu: int = Field(gt=0, strict=True) + memory_mib: int = Field(gt=0, strict=True) + + +class LaunchRequest(Input): + image: Optional[OfficialImage] = Field(default=None, exclude=True) + harness_type: Optional[str] = None + image_name: Optional[str] = None + image_url: Optional[str] = None + template_id: Optional[str] = None + template_name: Optional[str] = Field(default=None, max_length=128) + compute: Optional[Compute] = None + model: Optional[ModelConfig] = Field(default=None, alias="model_config") + runtime_budget_seconds: Optional[int] = None + + @field_validator("runtime_budget_seconds", mode="before") + @classmethod + def validate_budget(cls, value): + return ( + None + if value is None + else seconds(value, "runtime_budget_seconds", 300, 604800) + ) + + @model_validator(mode="after") + def validate_selection(self): + image = self.image + if image is not None and not image.supports_agent: + raise ValueError("This official image has no Harness Agent") + harness = self.harness_type or (image.value if image else None) + if harness not in ("deepseek-harness", "openclaw"): + raise ValueError("Select DeepSeek Harness or OpenClaw") + if image and harness != image.value: + raise ValueError("image and harness_type must match") + object.__setattr__(self, "harness_type", harness) + if self.template_id: + resource_id(self.template_id) + if any( + value is not None + for value in ( + self.image_name, + self.image_url, + self.template_name, + self.compute, + ) + ): + raise ValueError("template_id conflicts with new-template settings") + elif image is not None and self.image_name is None: + object.__setattr__(self, "image_name", image.value) + return self + + +class FileMount(Input): + origin_file_id: str = Field(alias="originFileId") + mount_path: str = Field(alias="mountPath") + origin_file_name: Optional[str] = Field(default=None, alias="originFileName") + + @model_validator(mode="after") + def validate_mount(self): + resource_id(self.origin_file_id) + path = required(self.mount_path, "mount_path") + if ( + not path.startswith("/home/user/workspace/uploads/") + or path.endswith("/") + or any(part in (".", "..") for part in path.split("/")) + or any(ord(c) < 32 or ord(c) == 127 for c in path) + ): + raise ValueError("mount_path must be a file under workspace/uploads") + return self + + +class TemplateCreateRequest(Input): + name: str + image: Optional[OfficialImage] = Field(default=None, exclude=True) + from_image: Optional[str] = Field(default=None, alias="fromImage") + image_name: Optional[str] = Field(default=None, alias="imageName") + harness_type: Optional[Literal["dsh", "openclaw", "codex", "hermes"]] = Field( + default=None, alias="harnessType" + ) + cpu_count: int = Field(alias="cpuCount", gt=0, strict=True) + memory_mb: int = Field(alias="memoryMB", gt=0, strict=True) + description: Optional[str] = None + model: Optional[ModelConfig] = Field( + default=None, + alias="modelConfig", + validation_alias=AliasChoices("model_config", "modelConfig"), + ) + env_config: Optional[Dict[str, str]] = Field(default=None, alias="envConfig") + network_config: Optional[Dict[str, Any]] = Field( + default=None, alias="networkConfig" + ) + hook_config: Optional[Dict[str, Any]] = Field(default=None, alias="hookConfig") + mounts: Optional[List[FileMount]] = Field(default=None, alias="mntConfig") + auto_pause_time: Optional[int] = Field(default=None, alias="autoPauseTime") + max_running_timeout: Optional[int] = Field(default=None, alias="maxRunningTimeout") + + @field_validator("model") + @classmethod + def omit_empty_model(cls, model): + return model if model is not None and model.base_url else None + + @field_serializer("model", when_used="json") + def serialize_template_model(self, model): + if model is None: + return None + # 模板沿用管控台字段;托管 Agent 的 model_config 协议保持不变。 + values = { + "modelName": model.model_id, + "baseUrl": model.base_url, + "apiKey": model.api_key, + } + return {name: value for name, value in values.items() if value is not None} + + @field_validator("name") + @classmethod + def validate_name(cls, value): + return required(value, "name") + + @model_validator(mode="after") + def validate_harness_selection(self): + if self.image is not None and self.harness_type is not None: + if not self.image.supports_agent: + raise ValueError("harness_type requires a Harness image") + expected = ( + "dsh" if self.image is OfficialImage.DEEPSEEK_HARNESS else "openclaw" + ) + if self.harness_type != expected: + raise ValueError("harness_type must match the selected image") + return self + + @field_validator("auto_pause_time", "max_running_timeout", mode="before") + @classmethod + def validate_lifetime(cls, value, info): + return None if value is None else seconds(value, info.field_name, 300, 604800) + + +class TemplateUpdateRequest(Input): + name: Optional[str] = None + from_image: Optional[str] = Field(default=None, alias="fromImage") + image_name: Optional[str] = Field(default=None, alias="imageName") + harness_type: Optional[Literal["dsh", "openclaw", "codex", "hermes"]] = Field( + default=None, alias="harnessType" + ) + cpu_count: Optional[int] = Field(default=None, alias="cpuCount", gt=0, strict=True) + memory_mb: Optional[int] = Field(default=None, alias="memoryMB", gt=0, strict=True) + description: Optional[str] = None + env_config: Optional[Dict[str, str]] = Field(default=None, alias="envConfig") + network_config: Optional[Dict[str, Any]] = Field( + default=None, alias="networkConfig" + ) + hook_config: Optional[Dict[str, Any]] = Field(default=None, alias="hookConfig") + mounts: Optional[List[FileMount]] = Field(default=None, alias="mntConfig") + auto_pause_time: Optional[int] = Field(default=None, alias="autoPauseTime") + max_running_timeout: Optional[int] = Field(default=None, alias="maxRunningTimeout") + + @field_validator("auto_pause_time", "max_running_timeout", mode="before") + @classmethod + def validate_lifetime(cls, value, info): + return None if value is None else seconds(value, info.field_name, 300, 604800) + + @model_validator(mode="after") + def paired_compute(self): + if (self.cpu_count is None) != (self.memory_mb is None): + raise ValueError("cpu_count and memory_mb must be updated together") + if self.name is not None: + required(self.name, "name") + return self + + +class SandboxCreateRequest(Input): + template_id: str = Field(alias="templateID") + timeout: Optional[int] = None + env_vars: Optional[Dict[str, str]] = Field(default=None, alias="envVars") + metadata: Optional[Dict[str, str]] = None + allow_internet_access: Optional[bool] = Field( + default=None, alias="allowInternetAccess" + ) + secure: Optional[bool] = None + auto_pause: Optional[bool] = Field(default=None, alias="autoPause") + auto_pause_memory: Optional[bool] = Field(default=None, alias="autoPauseMemory") + auto_resume: Optional[bool] = Field(default=None, alias="autoResume") + network: Optional[Dict[str, Any]] = None + volume_mounts: Optional[List[Dict[str, Any]]] = Field( + default=None, alias="volumeMounts" + ) + mcp: Optional[Dict[str, Any]] = None + + @field_validator("template_id") + @classmethod + def validate_id(cls, value): + resource_id(value) + return value + + @field_validator("timeout", mode="before") + @classmethod + def validate_lifetime(cls, value): + return None if value is None else seconds(value, "timeout") + + +class ConnectionOptions(Input): + timeout: Optional[int] = None + + @field_validator("timeout", mode="before") + @classmethod + def validate_lifetime(cls, value): + return None if value is None else seconds(value, "timeout") + + +class BuildStatus(Record): + template_id: Optional[str] = Field(default=None, alias="templateID") + build_id: Optional[str] = Field(default=None, alias="buildID") + status: str + logs: Any = None + log_entries: Any = Field(default=None, alias="logEntries") + reason: Any = None + + @property + def ready(self) -> bool: + return self.status.upper() == "READY" + + +class TemplateMount(Record): + """A stored mount; reading existing templates does not revalidate new mounts.""" + + origin_file_id: Optional[str] = Field(default=None, alias="originFileId") + mount_path: Optional[str] = Field(default=None, alias="mountPath") + origin_file_name: Optional[str] = Field(default=None, alias="originFileName") + + +class TemplateInfo(Record): + id: str = Field( + validation_alias=AliasChoices("templateID", "templateCode", "id"), + serialization_alias="templateID", + ) + name: Optional[str] = Field(default=None, alias="templateName") + cpu_count: Optional[int] = Field(default=None, alias="cpuCount") + memory_mb: Optional[int] = Field(default=None, alias="memoryMB") + build_id: Optional[str] = Field(default=None, alias="buildID") + build_status: Optional[str] = Field(default=None, alias="buildStatus") + version: Optional[int] = None + description: Optional[str] = None + from_image: Optional[str] = Field(default=None, alias="fromImage") + image_name: Optional[str] = Field(default=None, alias="imageName") + image_type: Optional[str] = Field(default=None, alias="imageType") + env_config: Dict[str, str] = Field(default_factory=dict, alias="envConfig") + mounts: List[TemplateMount] = Field(default_factory=list, alias="mntConfig") + builds: List[Dict[str, Any]] = Field(default_factory=list) + + @field_validator("env_config", "mounts", "builds", mode="before") + @classmethod + def optional_collections(cls, value, info): + # 管控台历史模板可能返回 null,读取时与未配置的空集合保持一致。 + if value is None: + return {} if info.field_name == "env_config" else [] + return value + + @model_validator(mode="before") + @classmethod + def build_defaults(cls, data): + if not isinstance(data, Mapping): + return data + data = dict(data) + if not data.get("templateName") and data.get("names"): + data["templateName"] = data["names"][0] + builds = data.get("builds") + if isinstance(builds, list) and builds and isinstance(builds[0], Mapping): + first = builds[0] + data.setdefault("buildID", first.get("buildID")) + data.setdefault("buildStatus", first.get("status")) + return data + + +class SandboxConnection(Record): + domain: Optional[str] = None + envd_url: Optional[str] = Field(default=None, alias="envdUrl", repr=False) + envd_version: Optional[str] = Field(default=None, alias="envdVersion") + envd_access_token: Optional[str] = Field( + default=None, alias="envdAccessToken", repr=False + ) + traffic_access_token: Optional[str] = Field( + default=None, alias="trafficAccessToken", repr=False + ) + + +class SandboxInfo(Record): + id: str = Field( + validation_alias=AliasChoices("sandboxID", "sandbox_id", "id"), + serialization_alias="sandboxID", + ) + template_id: Optional[str] = Field( + default=None, + validation_alias=AliasChoices("templateID", "template_id"), + serialization_alias="templateID", + ) + state: Optional[str] = None + cpu_count: Optional[int] = Field(default=None, alias="cpuCount") + memory_mb: Optional[int] = Field(default=None, alias="memoryMB") + metadata: Dict[str, str] = Field(default_factory=dict) + started_at: Optional[str] = Field(default=None, alias="startedAt") + end_at: Optional[str] = Field(default=None, alias="endAt") + connection: SandboxConnection = Field(default_factory=SandboxConnection, repr=False) + + @field_validator("metadata", mode="before") + @classmethod + def optional_metadata(cls, value): + return {} if value is None else value + + @model_validator(mode="before") + @classmethod + def connection_fields(cls, data): + if isinstance(data, Mapping): + data = dict(data) + data.setdefault( + "connection", + { + key: data[key] + for key in ( + "domain", + "envdUrl", + "envdVersion", + "envdAccessToken", + "trafficAccessToken", + ) + if key in data + }, + ) + return data + + +class AgentInstanceInfo(Record): + instance_id: str + state: str + harness_type: Optional[str] = None + image_name: Optional[str] = None + image_url: Optional[str] = None + template_id: Optional[str] = None + build_id: Optional[str] = None + default_session_id: Optional[str] = None + sandbox_id: Optional[str] = None + model: Optional[Dict[str, Any]] = Field( + default=None, alias="model_config", repr=False + ) + compute: Optional[Compute] = None + capabilities: Dict[str, Any] = Field(default_factory=dict) + max_upload_bytes: Optional[int] = None + created_at: Optional[str] = None + expires_at: Optional[str] = None + template_source: Optional[str] = None + credential_source: Optional[str] = None + + @property + def id(self) -> str: + return self.instance_id + + +class AgentSessionInfo(Record): + session_id: str + instance_id: Optional[str] = None + state: Optional[str] = None + created_at: Optional[str] = None + + @property + def id(self) -> str: + return self.session_id + + +class AgentTurnInfo(Record): + turn_id: str + session_id: Optional[str] = None + instance_id: Optional[str] = None + status: str + created_at: Optional[str] = None + error: Optional[Dict[str, Any]] = None + + @property + def id(self) -> str: + return self.turn_id + + +class AgentOperationInfo(Record): + operation_id: Optional[str] = None + instance_id: Optional[str] = None + status: str + result: Optional[Dict[str, Any]] = None + error: Optional[Dict[str, Any]] = None + + @property + def id(self) -> Optional[str]: + return self.operation_id + + +class TurnResult(Record): + turn_id: str + status: str + session_id: Optional[str] = None + output: List[Dict[str, Any]] = Field(default_factory=list) + stop_reason: Optional[str] = None + output_status: Optional[str] = None + usage: Optional[Dict[str, Any]] = None + error: Optional[Dict[str, Any]] = None + + @property + def id(self) -> str: + return self.turn_id + + @property + def text(self) -> str: + return "".join( + block.get("text", "") + for block in self.output + if block.get("type") == "text" + ) + + +T = TypeVar("T") + + +class AgentPage(Record, Generic[T]): + items: List[T] + next_cursor: Optional[str] = None + + +class UploadedFile(Record): + id: str = Field(alias="file_id") + instance_id: str + name: str + path: str + size_bytes: int + created_at: Optional[str] = None + + +class AgentImage(Record): + name: str + image_url: str + harness_type: str + + +class AgentTemplateConfig(Record): + images: List[AgentImage] + resource_configs: List[Compute] + default_compute: Optional[Compute] = None + + +class TemplateFile(Record): + id: str + type: Optional[str] = None + filename: Optional[str] = None + mime_type: Optional[str] = None + size_bytes: Optional[int] = None + downloadable: Optional[bool] = None + status: Optional[str] = None + created_at: Any = None + request_id: Optional[str] = None + + +class UploadTicket(Record): + id: str + status: Optional[str] = None + upload_url: str = Field(repr=False) + upload_expires_at: Any = None + request_id: Optional[str] = None + + +class UploadRequest(Input): + filename: str + mime_type: Optional[str] = None + size_bytes: Optional[int] = Field(default=None, gt=0, strict=True) + + @field_validator("filename") + @classmethod + def validate_filename(cls, value): + from ._validation import filename + + return filename(value) diff --git a/dashscope/applications/agentstudio/sandbox/sandboxes.py b/dashscope/applications/agentstudio/sandbox/sandboxes.py new file mode 100644 index 00000000..fc0501b4 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/sandboxes.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Ordinary Sandbox operations and resource handles.""" + +from typing import List, Optional + +from .exceptions import SandboxAPIError +from .models import ( + ConnectionOptions, + OfficialImage, + SandboxConnection, + SandboxCreateRequest, + SandboxInfo, +) +from .transport import SANDBOX, AsyncTransport, Transport +from ._validation import required, resource_id, seconds + + +def _path(sandbox_id: str) -> str: + return SANDBOX + "/sandboxes/" + resource_id(sandbox_id) + + +def _query(template_id, sandbox_id, state, limit) -> dict: + params = {"limit": seconds(limit, "limit")} + for name, value in ( + ("templateID", template_id), + ("sandboxID", sandbox_id), + ("state", state), + ): + if value is not None: + params[name] = required(value, name) + return params + + +def _list(data) -> List[SandboxInfo]: + if not isinstance(data, list): + raise SandboxAPIError("Sandbox list must be an array", code="INVALID_RESPONSE") + return [SandboxInfo.from_dict(item) for item in data] + + +class SandboxesClient: + def __init__(self, transport: Transport): + self._http = transport + + def create(self, request: SandboxCreateRequest) -> "SandboxHandle": + return SandboxHandle( + self, + SandboxInfo.from_dict( + self._http.request( + "POST", SANDBOX + "/sandboxes", json=request.to_dict() + ) + ), + ) + + def list( + self, + template_id: Optional[str] = None, + sandbox_id: Optional[str] = None, + state: Optional[str] = None, + limit: int = 100, + ) -> List[SandboxInfo]: + return _list( + self._http.request( + "GET", + SANDBOX + "/v2/sandboxes", + params=_query(template_id, sandbox_id, state, limit), + ) + ) + + def get(self, sandbox_id: str) -> SandboxInfo: + return SandboxInfo.from_dict(self._http.request("GET", _path(sandbox_id))) + + def connect( + self, sandbox_id: str, options: Optional[ConnectionOptions] = None + ) -> "SandboxHandle": + return SandboxHandle( + self, + SandboxInfo.from_dict( + self._http.request( + "POST", + _path(sandbox_id) + "/connect", + json=options.to_dict() if options is not None else {}, + ) + ), + ) + + def pause(self, sandbox_id: str) -> None: + self._http.request("POST", _path(sandbox_id) + "/pause", json={}) + + def resume( + self, sandbox_id: str, options: Optional[ConnectionOptions] = None + ) -> "SandboxHandle": + return SandboxHandle( + self, + SandboxInfo.from_dict( + self._http.request( + "POST", + _path(sandbox_id) + "/resume", + json=options.to_dict() if options is not None else {}, + ) + ), + ) + + def release(self, sandbox_id: str) -> None: + self._http.request("DELETE", _path(sandbox_id)) + + def open_web_ui(self, image: OfficialImage, options=None): + from .web_ui import open_web_ui + + return open_web_ui(self, self._http, image, options) + + +class SandboxHandle: + """A handle holds connection details; release is always explicit.""" + + def __init__(self, client: SandboxesClient, info: SandboxInfo): + self._client = client + self._id = info.id + self._template_id = info.template_id + self._connection = info.connection + + @property + def id(self) -> str: + return self._id + + @property + def sandbox_id(self) -> str: + return self._id + + @property + def template_id(self) -> Optional[str]: + return self._template_id + + @property + def connection(self) -> Optional[SandboxConnection]: + return self._connection + + def get(self) -> SandboxInfo: + info = self._client.get(self.id) + self._connection = info.connection + return info + + def connect(self, options: Optional[ConnectionOptions] = None) -> "SandboxHandle": + self._connection = self._client.connect(self.id, options).connection + return self + + def pause(self) -> None: + self._client.pause(self.id) + + def resume(self, options: Optional[ConnectionOptions] = None) -> "SandboxHandle": + self._connection = self._client.resume(self.id, options).connection + return self + + def release(self) -> None: + self._client.release(self.id) + + def __repr__(self) -> str: + return "SandboxHandle(id={!r})".format(self.id) + + +class AsyncSandboxesClient: + def __init__(self, transport: AsyncTransport): + self._http = transport + + async def create(self, request: SandboxCreateRequest) -> "AsyncSandboxHandle": + return AsyncSandboxHandle( + self, + SandboxInfo.from_dict( + await self._http.request( + "POST", SANDBOX + "/sandboxes", json=request.to_dict() + ) + ), + ) + + async def list( + self, + template_id: Optional[str] = None, + sandbox_id: Optional[str] = None, + state: Optional[str] = None, + limit: int = 100, + ) -> List[SandboxInfo]: + return _list( + await self._http.request( + "GET", + SANDBOX + "/v2/sandboxes", + params=_query(template_id, sandbox_id, state, limit), + ) + ) + + async def get(self, sandbox_id: str) -> SandboxInfo: + return SandboxInfo.from_dict(await self._http.request("GET", _path(sandbox_id))) + + async def connect( + self, sandbox_id: str, options: Optional[ConnectionOptions] = None + ) -> "AsyncSandboxHandle": + return AsyncSandboxHandle( + self, + SandboxInfo.from_dict( + await self._http.request( + "POST", + _path(sandbox_id) + "/connect", + json=options.to_dict() if options is not None else {}, + ) + ), + ) + + async def pause(self, sandbox_id: str) -> None: + await self._http.request("POST", _path(sandbox_id) + "/pause", json={}) + + async def resume( + self, sandbox_id: str, options: Optional[ConnectionOptions] = None + ) -> "AsyncSandboxHandle": + return AsyncSandboxHandle( + self, + SandboxInfo.from_dict( + await self._http.request( + "POST", + _path(sandbox_id) + "/resume", + json=options.to_dict() if options is not None else {}, + ) + ), + ) + + async def release(self, sandbox_id: str) -> None: + await self._http.request("DELETE", _path(sandbox_id)) + + async def open_web_ui(self, image: OfficialImage, options=None): + from .web_ui import async_open_web_ui + + return await async_open_web_ui(self, self._http, image, options) + + +class AsyncSandboxHandle: + def __init__(self, client: AsyncSandboxesClient, info: SandboxInfo): + self._client = client + self._id = info.id + self._template_id = info.template_id + self._connection = info.connection + + @property + def id(self) -> str: + return self._id + + @property + def sandbox_id(self) -> str: + return self._id + + @property + def template_id(self) -> Optional[str]: + return self._template_id + + @property + def connection(self) -> Optional[SandboxConnection]: + return self._connection + + async def get(self) -> SandboxInfo: + info = await self._client.get(self.id) + self._connection = info.connection + return info + + async def connect( + self, options: Optional[ConnectionOptions] = None + ) -> "AsyncSandboxHandle": + self._connection = (await self._client.connect(self.id, options)).connection + return self + + async def pause(self) -> None: + await self._client.pause(self.id) + + async def resume( + self, options: Optional[ConnectionOptions] = None + ) -> "AsyncSandboxHandle": + self._connection = (await self._client.resume(self.id, options)).connection + return self + + async def release(self) -> None: + await self._client.release(self.id) + + def __repr__(self) -> str: + return "AsyncSandboxHandle(id={!r})".format(self.id) diff --git a/dashscope/applications/agentstudio/sandbox/streaming.py b/dashscope/applications/agentstudio/sandbox/streaming.py new file mode 100644 index 00000000..5fa2320d --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/streaming.py @@ -0,0 +1,394 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Bounded SSE subscriptions. Disconnecting never cancels a remote Turn.""" + +from __future__ import annotations + +import asyncio +import inspect +import json +import threading +from typing import Any, AsyncIterator, Callable, Iterator, Optional + +from .exceptions import SandboxAPIError, SandboxWaitTimeoutError +from ._validation import positive + +_TERMINAL = frozenset(("turn.completed", "turn.cancelled", "turn.failed")) +_MAX_EVENT_BYTES = 4 * 1024 * 1024 +_MAX_SEQUENCE = 2**63 - 1 + + +def _invalid(message: str) -> SandboxAPIError: + return SandboxAPIError(message, code="INVALID_RESPONSE") + + +class _EventDecoder: + """SSE framing and contiguous, turn-scoped replay validation.""" + + def __init__(self, turn_id: str, sequence: int): + if ( + isinstance(sequence, bool) + or not isinstance(sequence, int) + or not 0 <= sequence <= _MAX_SEQUENCE + ): + raise ValueError("after_sequence must be a nonnegative 64-bit integer") + self.turn_id = turn_id + self.last_sequence = sequence + self._lines = [] + self._size = 0 + self._event_id: Optional[str] = None + + def feed(self, line: str) -> Optional[dict]: + if line == "": + if not self._lines: + self._event_id = None + return None + try: + event = json.loads("\n".join(self._lines)) + except (ValueError, RecursionError): + raise _invalid("Invalid JSON in Turn event") from None + finally: + self._lines = [] + self._size = 0 + if not isinstance(event, dict) or event.get("turn_id") != self.turn_id: + raise _invalid("Event belongs to an unexpected Turn") + sequence = event.get("sequence") + if ( + isinstance(sequence, bool) + or not isinstance(sequence, int) + or not 1 <= sequence <= _MAX_SEQUENCE + ): + raise _invalid("Invalid Turn event sequence") + if self._event_id is not None and self._event_id != "{}:{}".format( + self.turn_id, sequence + ): + raise _invalid("Inconsistent Turn event identifier") + self._event_id = None + event_type = event.get("type") + if not isinstance(event_type, str) or not event_type: + raise _invalid("Missing Turn event type") + if sequence <= self.last_sequence: + return None + if sequence != self.last_sequence + 1: + raise _invalid("Gap in Turn event sequence") + self.last_sequence = sequence + return event + if line.startswith(":"): + return None + field, separator, value = line.partition(":") + if value.startswith(" "): + value = value[1:] + if field == "data": + self._size += len(value.encode("utf-8")) + 1 + if self._size > _MAX_EVENT_BYTES: + raise _invalid("Turn event exceeds the stream size limit") + self._lines.append(value if separator else "") + elif field == "id": + self._event_id = value + return None + + def eof(self) -> None: + if self._lines: + raise _invalid("Incomplete Turn event at end of stream") + + +def _headers(turn_id: str, sequence: int) -> dict: + headers = {"Accept": "text/event-stream"} + # The protocol rejects Last-Event-ID with sequence zero. + if sequence: + headers["Last-Event-ID"] = "{}:{}".format(turn_id, sequence) + return headers + + +def _check_response(response) -> None: + media_type = ( + response.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + ) + if media_type != "text/event-stream": + raise _invalid("Expected text/event-stream response") + + +class EventSubscription: + """Iterate SSE events, or consume them on one callback reader thread. + + ``wait`` waits for a callback subscription to finish and propagates callback + or stream failures. ``close`` only disconnects this HTTP subscription. + No reconnect or Turn resubmission is performed automatically. + """ + + def __init__( + self, + transport, + path: str, + turn_id: str, + after_sequence: int = 0, + callback: Optional[Callable[[dict], Any]] = None, + ): + if callback is not None and not callable(callback): + raise ValueError("callback must be callable") + self._decoder = _EventDecoder(turn_id, after_sequence) + self._transport = transport + self._path = path + "/events" + self._callback = callback + self._context = None + self._response = None + self._closed = False + self._iterator = None + self._error: Optional[BaseException] = None + self._completion = threading.Event() + self._thread: Optional[threading.Thread] = None + transport.register(self) + if callback is not None: + self._thread = threading.Thread( + target=self._consume, name="dashscope-sandbox-sse", daemon=True + ) + self._thread.start() + + @property + def last_sequence(self) -> int: + return self._decoder.last_sequence + + def _open(self) -> None: + if self._closed or self._response is not None: + return + self._context = self._transport.stream( + "GET", + self._path, + headers=_headers(self._decoder.turn_id, self.last_sequence), + params={"after_seq": self.last_sequence}, + ) + try: + response = self._context.__enter__() + if self._closed: + response.close() + self._context.__exit__(None, None, None) + self._context = None + return + self._response = response + _check_response(response) + except BaseException: + self.close() + raise + + def _events(self) -> Iterator[dict]: + # 建联异常须保留;只有主动关闭引起的后续读取异常可以忽略。 + self._open() + try: + if self._closed: + return + first = True + for line in self._response.iter_lines(): + if self._closed: + return + if first: + line = line.lstrip("\ufeff") + first = False + event = self._decoder.feed(line) + if event is not None: + yield event + if event["type"] in _TERMINAL: + return + if not self._closed: + self._decoder.eof() + except Exception: + if not self._closed: + raise + finally: + self.close() + + def __iter__(self) -> Iterator[dict]: + if self._callback is not None: + raise ValueError("callback subscriptions cannot also be iterated") + if self._iterator is None: + self._iterator = self._events() + return self._iterator + + def _consume(self) -> None: + try: + for event in self._events(): + self._callback(event) + except BaseException as error: + self._error = error + finally: + self.close() + self._completion.set() + + def wait(self, timeout: Optional[float] = None) -> None: + if self._callback is None: + raise ValueError( + "wait requires a callback subscription; iterate events otherwise" + ) + if timeout is not None: + timeout = positive(timeout, "timeout") + if not self._completion.wait(timeout): + raise SandboxWaitTimeoutError(self._decoder.turn_id, "SUBSCRIBED") + if self._error is not None: + raise self._error + + def close(self) -> None: + if self._closed: + return + self._closed = True + try: + if self._response is not None: + self._response.close() + if self._context is not None and self._response is not None: + self._context.__exit__(None, None, None) + self._context = None + finally: + self._transport.unregister(self) + + def __enter__(self) -> EventSubscription: + if self._callback is None: + self._open() + return self + + def __exit__(self, exc_type, exc, traceback) -> None: + self.close() + + +class AsyncEventSubscription: + """Async iteration or one callback task, with local-only cancellation. + + A callback may be synchronous or return an awaitable; callbacks run in event + order on the reader task. Avoid blocking work in synchronous callbacks. + """ + + def __init__( + self, + transport, + path: str, + turn_id: str, + after_sequence: int = 0, + callback: Optional[Callable[[dict], Any]] = None, + ): + if callback is not None and not callable(callback): + raise ValueError("callback must be callable") + self._decoder = _EventDecoder(turn_id, after_sequence) + self._transport = transport + self._path = path + "/events" + self._callback = callback + self._context = None + self._response = None + self._closed = False + self._iterator = None + self._task: Optional[asyncio.Task] = None + transport.register(self) + if callback is not None: + try: + self._task = asyncio.get_running_loop().create_task(self._consume()) + except BaseException: + transport.unregister(self) + raise + + @property + def last_sequence(self) -> int: + return self._decoder.last_sequence + + async def _open(self) -> None: + if self._closed or self._response is not None: + return + self._context = self._transport.stream( + "GET", + self._path, + headers=_headers(self._decoder.turn_id, self.last_sequence), + params={"after_seq": self.last_sequence}, + ) + try: + response = await self._context.__aenter__() + if self._closed: + await response.aclose() + await self._context.__aexit__(None, None, None) + self._context = None + return + self._response = response + _check_response(response) + except BaseException: + await self.aclose() + raise + + async def _events(self) -> AsyncIterator[dict]: + try: + await self._open() + if self._closed: + return + first = True + async for line in self._response.aiter_lines(): + if self._closed: + return + if first: + line = line.lstrip("\ufeff") + first = False + event = self._decoder.feed(line) + if event is not None: + yield event + if event["type"] in _TERMINAL: + return + if not self._closed: + self._decoder.eof() + finally: + await self.aclose() + + def __aiter__(self) -> AsyncIterator[dict]: + if self._callback is not None: + raise ValueError("callback subscriptions cannot also be iterated") + if self._iterator is None: + self._iterator = self._events() + return self._iterator + + async def _consume(self) -> None: + events = self._events() + try: + async for event in events: + result = self._callback(event) + if inspect.isawaitable(result): + await result + finally: + await events.aclose() + await self.aclose() + + async def wait(self, timeout: Optional[float] = None) -> None: + if self._task is None: + raise ValueError( + "wait requires a callback subscription; iterate events otherwise" + ) + if timeout is not None: + timeout = positive(timeout, "timeout") + try: + await asyncio.wait_for(asyncio.shield(self._task), timeout) + except asyncio.TimeoutError: + raise SandboxWaitTimeoutError(self._decoder.turn_id, "SUBSCRIBED") from None + except asyncio.CancelledError: + await self.aclose() + raise + + async def aclose(self) -> None: + if self._closed: + return + self._closed = True + try: + if self._response is not None: + await self._response.aclose() + if self._context is not None and self._response is not None: + await self._context.__aexit__(None, None, None) + self._context = None + finally: + self._transport.unregister(self) + if ( + self._task is not None + and self._task is not asyncio.current_task() + and not self._task.done() + ): + self._task.cancel() + try: + await self._task + except asyncio.CancelledError: + pass + + async def __aenter__(self) -> AsyncEventSubscription: + if self._callback is None: + await self._open() + return self + + async def __aexit__(self, exc_type, exc, traceback) -> None: + await self.aclose() diff --git a/dashscope/applications/agentstudio/sandbox/template_files.py b/dashscope/applications/agentstudio/sandbox/template_files.py new file mode 100644 index 00000000..0e337fb5 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/template_files.py @@ -0,0 +1,239 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Template file storage with streamed uploads and atomic downloads.""" + +import asyncio +import os +import tempfile +import time +from pathlib import Path +from typing import Union + +from .exceptions import SandboxAPIError, SandboxWaitTimeoutError +from .models import TemplateFile, UploadRequest, UploadTicket +from .transport import FILES, AsyncTransport, Transport +from ._validation import deadline, filename, remaining, resource_id + +_SOURCE = "sandbox_template" +_FAILED_FILES = {"rejected", "type_rejected", "failed", "deleted"} +PathLike = Union[str, os.PathLike] + + +def _path(file_id: str) -> str: + return FILES + "/" + resource_id(file_id) + + +def _check_file(file: TemplateFile) -> bool: + if file.status in _FAILED_FILES: + raise SandboxAPIError( + "Template file is " + file.status, + code="FILE_" + file.status.upper(), + body=file.to_dict(), + ) + return file.status == "available" + + +def _upload_path(path: PathLike) -> Path: + result = Path(path) + filename(result.name) + return result + + +class TemplateFilesClient: + def __init__(self, transport: Transport): + self._http = transport + + def upload(self, path: PathLike) -> TemplateFile: + source = _upload_path(path) + try: + with source.open("rb") as input_file: + # 直接将文件句柄交给 multipart 编码器,避免将整个文件读入内存。 + data = self._http.request( + "POST", + FILES, + files=[ + ("source", (None, _SOURCE)), + ("file", (source.name, input_file, "application/octet-stream")), + ], + ) + except OSError as error: + raise SandboxAPIError( + "Cannot read the upload file", code="FILE_IO_ERROR" + ) from error + return TemplateFile.from_dict(data) + + def get(self, file_id: str) -> TemplateFile: + return TemplateFile.from_dict(self._http.request("GET", _path(file_id))) + + def wait_available(self, file_id: str, timeout: float = 600) -> TemplateFile: + path = _path(file_id) + end = deadline(timeout) + last_status = None + while True: + budget = remaining(end, file_id, last_status) + try: + file = TemplateFile.from_dict( + self._http.request( + "GET", path, timeout=min(self._http.timeout, budget) + ) + ) + except SandboxAPIError as error: + if error.code == "REQUEST_TIMEOUT" and budget <= self._http.timeout: + raise SandboxWaitTimeoutError(file_id, last_status) from error + raise + last_status = file.status + remaining(end, file_id, last_status) + if _check_file(file): + return file + time.sleep( + min(self._http.poll_interval, remaining(end, file_id, last_status)) + ) + + def prepare_upload(self, request: UploadRequest) -> UploadTicket: + fields = request.to_dict() + fields["source"] = _SOURCE + return UploadTicket.from_dict(self._http.request("POST", FILES, json=fields)) + + def upload_content(self, ticket: UploadTicket, path: PathLike) -> None: + try: + self._http.put_signed(ticket.upload_url, _upload_path(path)) + except OSError as error: + raise SandboxAPIError( + "Cannot read the upload file", code="FILE_IO_ERROR" + ) from error + + def complete(self, file_id: str) -> TemplateFile: + return TemplateFile.from_dict( + self._http.request("POST", _path(file_id) + "/complete") + ) + + def download(self, file_id: str, target: PathLike) -> Path: + path = _path(file_id) + "/content" + target = Path(target) + temporary = None + try: + descriptor, temporary_name = tempfile.mkstemp( + prefix=".bailian-download-", + suffix=".part", + dir=str(target.absolute().parent), + ) + temporary = Path(temporary_name) + with os.fdopen(descriptor, "wb") as output: + with self._http.stream( + "GET", path, headers={"Accept": "application/octet-stream"} + ) as response: + for chunk in response.iter_bytes(chunk_size=64 * 1024): + output.write(chunk) + # 同目录临时文件保证替换是原子操作,失败时保留原文件。 + os.replace(temporary, target) + return target + except OSError as error: + raise SandboxAPIError( + "Cannot save the downloaded file", code="FILE_IO_ERROR" + ) from error + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + + def delete(self, file_id: str) -> None: + self._http.request("DELETE", _path(file_id)) + + +class AsyncTemplateFilesClient: + def __init__(self, transport: AsyncTransport): + self._http = transport + + async def upload(self, path: PathLike) -> TemplateFile: + source = _upload_path(path) + try: + with source.open("rb") as input_file: + data = await self._http.request( + "POST", + FILES, + files=[ + ("source", (None, _SOURCE)), + ("file", (source.name, input_file, "application/octet-stream")), + ], + ) + except OSError as error: + raise SandboxAPIError( + "Cannot read the upload file", code="FILE_IO_ERROR" + ) from error + return TemplateFile.from_dict(data) + + async def get(self, file_id: str) -> TemplateFile: + return TemplateFile.from_dict(await self._http.request("GET", _path(file_id))) + + async def wait_available(self, file_id: str, timeout: float = 600) -> TemplateFile: + path = _path(file_id) + end = deadline(timeout) + last_status = None + while True: + budget = remaining(end, file_id, last_status) + try: + file = TemplateFile.from_dict( + await self._http.request( + "GET", path, timeout=min(self._http.timeout, budget) + ) + ) + except SandboxAPIError as error: + if error.code == "REQUEST_TIMEOUT" and budget <= self._http.timeout: + raise SandboxWaitTimeoutError(file_id, last_status) from error + raise + last_status = file.status + remaining(end, file_id, last_status) + if _check_file(file): + return file + await asyncio.sleep( + min(self._http.poll_interval, remaining(end, file_id, last_status)) + ) + + async def prepare_upload(self, request: UploadRequest) -> UploadTicket: + fields = request.to_dict() + fields["source"] = _SOURCE + return UploadTicket.from_dict( + await self._http.request("POST", FILES, json=fields) + ) + + async def upload_content(self, ticket: UploadTicket, path: PathLike) -> None: + try: + await self._http.put_signed(ticket.upload_url, _upload_path(path)) + except OSError as error: + raise SandboxAPIError( + "Cannot read the upload file", code="FILE_IO_ERROR" + ) from error + + async def complete(self, file_id: str) -> TemplateFile: + return TemplateFile.from_dict( + await self._http.request("POST", _path(file_id) + "/complete") + ) + + async def download(self, file_id: str, target: PathLike) -> Path: + path = _path(file_id) + "/content" + target = Path(target) + temporary = None + try: + descriptor, temporary_name = tempfile.mkstemp( + prefix=".bailian-download-", + suffix=".part", + dir=str(target.absolute().parent), + ) + temporary = Path(temporary_name) + with os.fdopen(descriptor, "wb") as output: + async with self._http.stream( + "GET", path, headers={"Accept": "application/octet-stream"} + ) as response: + async for chunk in response.aiter_bytes(chunk_size=64 * 1024): + await asyncio.to_thread(output.write, chunk) + os.replace(temporary, target) + return target + except OSError as error: + raise SandboxAPIError( + "Cannot save the downloaded file", code="FILE_IO_ERROR" + ) from error + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + + async def delete(self, file_id: str) -> None: + await self._http.request("DELETE", _path(file_id)) diff --git a/dashscope/applications/agentstudio/sandbox/templates.py b/dashscope/applications/agentstudio/sandbox/templates.py new file mode 100644 index 00000000..b11c24d0 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/templates.py @@ -0,0 +1,233 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Personal sandbox templates and explicit build polling.""" + +import asyncio +import time +from typing import List + +from .exceptions import SandboxAPIError, SandboxWaitTimeoutError +from .models import ( + BuildStatus, + OfficialImage, + TemplateCreateRequest, + TemplateInfo, + TemplateUpdateRequest, +) +from .transport import SANDBOX, AsyncTransport, Transport +from ._validation import deadline, remaining, resource_id, seconds + +_FAILED_BUILDS = {"ERROR", "FAILED", "CANCELLED", "CANCELED"} + + +def _path(template_id: str) -> str: + return SANDBOX + "/templates/" + resource_id(template_id) + + +def _list(data) -> List[TemplateInfo]: + if not isinstance(data, list): + raise SandboxAPIError("Template list must be an array", code="INVALID_RESPONSE") + return [TemplateInfo.from_dict(item) for item in data] + + +def _creation_fields(request: TemplateCreateRequest, resolved) -> dict: + fields = request.to_dict() + if request.image is None: + return fields + image_name = request.image.image_name + exact_url = request.from_image + if ( + not isinstance(resolved, dict) + or resolved.get("imageName") != image_name + or not isinstance(resolved.get("imageUrl"), str) + or not resolved["imageUrl"].strip() + or (exact_url is not None and resolved["imageUrl"] != exact_url) + ): + raise SandboxAPIError( + "Official image resolution did not match the selected image", + code="INVALID_RESPONSE", + ) + if request.image.supports_agent: + fields["harnessType"] = ( + "dsh" if request.image is OfficialImage.DEEPSEEK_HARNESS else "openclaw" + ) + fields["imageType"] = "MANAGED" + fields["fromImage"] = resolved["imageUrl"] + fields.setdefault("imageName", image_name) + return fields + + +def _check_build(status: BuildStatus) -> bool: + normalized = status.status.upper() + if normalized in _FAILED_BUILDS: + raise SandboxAPIError( + "Template build failed", code="TEMPLATE_BUILD_FAILED", body=status.to_dict() + ) + return normalized == "READY" + + +class TemplatesClient: + def __init__(self, transport: Transport): + self._http = transport + + def create(self, request: TemplateCreateRequest) -> TemplateInfo: + resolved = None + if request.image is not None: + # 先解析官方目录,避免在多版本或目录异常时创建错误模板。 + params = ( + {"imageUrl": request.from_image} + if request.from_image is not None + else None + ) + resolved = self._http.request( + "GET", SANDBOX + "/images/" + request.image.image_name, params=params + ) + return TemplateInfo.from_dict( + self._http.request( + "POST", + SANDBOX + "/v3/templates", + json=_creation_fields(request, resolved), + ) + ) + + def list(self, limit: int = 100, page_no: int = 1) -> List[TemplateInfo]: + return _list( + self._http.request( + "GET", + SANDBOX + "/v2/templates", + params={ + "limit": seconds(limit, "limit"), + "pageNo": seconds(page_no, "page_no"), + }, + ) + ) + + def get(self, template_id: str) -> TemplateInfo: + return TemplateInfo.from_dict(self._http.request("GET", _path(template_id))) + + def update(self, template_id: str, request: TemplateUpdateRequest) -> TemplateInfo: + return TemplateInfo.from_dict( + self._http.request("PUT", _path(template_id), json=request.to_dict()) + ) + + def build_status(self, template_id: str, build_id: str) -> BuildStatus: + return BuildStatus.from_dict( + self._http.request( + "GET", + _path(template_id) + "/builds/" + resource_id(build_id) + "/status", + ) + ) + + def wait_ready( + self, template_id: str, build_id: str, timeout: float = 600 + ) -> BuildStatus: + path = _path(template_id) + "/builds/" + resource_id(build_id) + "/status" + end = deadline(timeout) + last_status = None + while True: + budget = remaining(end, template_id, last_status) + try: + status = BuildStatus.from_dict( + self._http.request( + "GET", path, timeout=min(self._http.timeout, budget) + ) + ) + except SandboxAPIError as error: + if error.code == "REQUEST_TIMEOUT" and budget <= self._http.timeout: + raise SandboxWaitTimeoutError(template_id, last_status) from error + raise + last_status = status.status + remaining(end, template_id, last_status) + if _check_build(status): + return status + time.sleep( + min(self._http.poll_interval, remaining(end, template_id, last_status)) + ) + + def delete(self, template_id: str) -> None: + self._http.request("DELETE", _path(template_id)) + + +class AsyncTemplatesClient: + def __init__(self, transport: AsyncTransport): + self._http = transport + + async def create(self, request: TemplateCreateRequest) -> TemplateInfo: + resolved = None + if request.image is not None: + params = ( + {"imageUrl": request.from_image} + if request.from_image is not None + else None + ) + resolved = await self._http.request( + "GET", SANDBOX + "/images/" + request.image.image_name, params=params + ) + return TemplateInfo.from_dict( + await self._http.request( + "POST", + SANDBOX + "/v3/templates", + json=_creation_fields(request, resolved), + ) + ) + + async def list(self, limit: int = 100, page_no: int = 1) -> List[TemplateInfo]: + return _list( + await self._http.request( + "GET", + SANDBOX + "/v2/templates", + params={ + "limit": seconds(limit, "limit"), + "pageNo": seconds(page_no, "page_no"), + }, + ) + ) + + async def get(self, template_id: str) -> TemplateInfo: + return TemplateInfo.from_dict( + await self._http.request("GET", _path(template_id)) + ) + + async def update( + self, template_id: str, request: TemplateUpdateRequest + ) -> TemplateInfo: + return TemplateInfo.from_dict( + await self._http.request("PUT", _path(template_id), json=request.to_dict()) + ) + + async def build_status(self, template_id: str, build_id: str) -> BuildStatus: + return BuildStatus.from_dict( + await self._http.request( + "GET", + _path(template_id) + "/builds/" + resource_id(build_id) + "/status", + ) + ) + + async def wait_ready( + self, template_id: str, build_id: str, timeout: float = 600 + ) -> BuildStatus: + path = _path(template_id) + "/builds/" + resource_id(build_id) + "/status" + end = deadline(timeout) + last_status = None + while True: + budget = remaining(end, template_id, last_status) + try: + status = BuildStatus.from_dict( + await self._http.request( + "GET", path, timeout=min(self._http.timeout, budget) + ) + ) + except SandboxAPIError as error: + if error.code == "REQUEST_TIMEOUT" and budget <= self._http.timeout: + raise SandboxWaitTimeoutError(template_id, last_status) from error + raise + last_status = status.status + remaining(end, template_id, last_status) + if _check_build(status): + return status + await asyncio.sleep( + min(self._http.poll_interval, remaining(end, template_id, last_status)) + ) + + async def delete(self, template_id: str) -> None: + await self._http.request("DELETE", _path(template_id)) diff --git a/dashscope/applications/agentstudio/sandbox/transport.py b/dashscope/applications/agentstudio/sandbox/transport.py new file mode 100644 index 00000000..52dede5e --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/transport.py @@ -0,0 +1,475 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Shared HTTP mechanics for the four Sandbox business facets.""" + +from __future__ import annotations + +import json +import threading +import uuid +from contextlib import asynccontextmanager, contextmanager +from pathlib import Path +from typing import Any, Mapping, Optional +from urllib.parse import urlsplit + +import httpx + +from dashscope._shared._sdk_ident import get_sdk_headers + +from .exceptions import SandboxAPIError +from ._validation import http_url, positive + +AGENT = "/api/v1/agentstudio/agent-runtime" +SANDBOX = "/api/v1/agentstudio/sandbox" +FILES = "/api/v1/agentstudio/files" +_MAX_JSON = 8 * 1024 * 1024 +_SUFFIXES = ( + AGENT, + SANDBOX, + FILES, + "/api/v1/agentstudio", + "/compatible-mode/v1", + "/api/v1", +) + + +def resolve_base_url(value: str) -> str: + base = http_url(value) + # 主 SDK 的 AgentStudio 挂载会追加此后缀;仅去掉一次,保留代理基础路径。 + if base.endswith("/agentstudio"): + base = base[: -len("/agentstudio")] + for suffix in _SUFFIXES: + if base.endswith(suffix): + return base[: -len(suffix)] + return base + + +def _key(value: str) -> str: + if ( + not isinstance(value, str) + or not value + or len(value) > 8192 + or any(ord(c) < 33 or ord(c) > 126 or c == "," for c in value) + ): + raise ValueError("Invalid API key") + return value + + +def _decode(response: httpx.Response, content: bytes) -> Any: + if response.status_code == 204 or not content: + return None + try: + return json.loads(content) + except (ValueError, UnicodeError): + if response.is_success: + raise SandboxAPIError( + "Invalid JSON response", code="INVALID_RESPONSE" + ) from None + return None + + +class _Base: + def __init__(self, base_url, api_key, timeout, poll_interval): + self.base_url = resolve_base_url(base_url) + self.api_key = _key(api_key) + self.timeout = positive(timeout, "timeout") + self.poll_interval = positive(poll_interval, "poll_interval") + self._subscriptions = set() + self._lock = threading.RLock() + self._closed = False + self._closing = False + + def register(self, subscription): + with self._lock: + if self._closed or self._closing: + raise ValueError("Sandbox client is closed") + self._subscriptions.add(subscription) + + def unregister(self, subscription): + with self._lock: + self._subscriptions.discard(subscription) + + def _take_subscriptions(self): + with self._lock: + if self._closed or self._closing: + return None + # 预览清理仍需发出释放请求,资源关闭完成后再关闭HTTP池。 + self._closing = True + result = tuple(self._subscriptions) + self._subscriptions.clear() + return result + + def _request(self, method, path, *, headers=None, timeout=None, **kwargs): + if self._closed: + raise ValueError("Sandbox client is closed") + if not path.startswith("/") or path.startswith("//"): + raise ValueError("A Sandbox API path is required") + configured = dict(get_sdk_headers(module="agentstudio")) + configured.update(headers or {}) + configured["Authorization"] = "Bearer " + self.api_key + configured.setdefault("Accept", "application/json") + configured.setdefault("x-dashscope-client-request-id", str(uuid.uuid4())) + request = self._client.build_request( + method, + self.base_url + path, + headers=configured, + timeout=self.timeout if timeout is None else timeout, + **kwargs, + ) + # 资源归属由网关根据域名和Bearer解析;不带调用方HTTP池的空间选择头。 + for name in ("X-DashScope-WorkSpace", "X-DashScope-Workspace-Id"): + request.headers.pop(name, None) + return request + + def _transport_error(self, request, error): + uncertain = request.method not in ("GET", "HEAD", "OPTIONS") + code = "OUTCOME_UNKNOWN" if uncertain else "REQUEST_FAILED" + if isinstance(error, httpx.TimeoutException) and not uncertain: + code = "REQUEST_TIMEOUT" + return SandboxAPIError( + ( + "Request outcome is unknown; query the resource before retrying" + if uncertain + else "Sandbox request failed" + ), + code=code, + request_id=request.headers.get("x-dashscope-client-request-id"), + outcome_unknown=uncertain, + ) + + def _checked(self, response, payload, agent=False): + obj = payload if isinstance(payload, dict) else {} + error = obj.get("error") + error = error if isinstance(error, dict) else obj + business_error = isinstance(obj.get("error"), dict) or ( + obj.get("code") is not None + and str(obj["code"]) not in ("200", "0", "OK", "SUCCESS") + ) + request_id = ( + obj.get("request_id") + or obj.get("requestId") + or response.headers.get("x-request-id") + or response.headers.get("x-acs-request-id") + ) + if not response.is_success or business_error: + message = str( + error.get("message") + or error.get("errorMsg") + or f"Platform HTTP {response.status_code}" + ) + message = message.replace(self.api_key, "")[:8192] + raise SandboxAPIError( + message, + code=str(error.get("code") or "HTTP_ERROR"), + status_code=response.status_code, + request_id=request_id, + ) + if agent: + if not isinstance(obj.get("data"), dict): + raise SandboxAPIError( + "Missing Agent response data", + code="INVALID_RESPONSE", + request_id=request_id, + ) + return obj["data"] + return payload + + @staticmethod + def _signed_request(url, content, headers, timeout): + try: + parsed = urlsplit(url) + _ = parsed.port + except (ValueError, TypeError): + raise ValueError("Invalid signed upload URL") from None + if ( + parsed.scheme not in ("https", "http") + or not parsed.hostname + or parsed.username is not None + or parsed.password is not None + or parsed.fragment + ): + raise ValueError("Invalid signed upload URL") + safe = { + name: value + for name, value in (headers or {}).items() + if name.lower() + not in ( + "authorization", + "cookie", + "x-dashscope-workspace", + "x-dashscope-workspace-id", + ) + } + return httpx.Request( + "PUT", + url, + content=content, + headers=safe, + extensions={"timeout": httpx.Timeout(timeout).as_dict()}, + ) + + +class Transport(_Base): + def __init__( + self, + base_url, + api_key, + timeout=30.0, + poll_interval=0.35, + http_client: Optional[httpx.Client] = None, + ): + super().__init__(base_url, api_key, timeout, poll_interval) + self._owns_client = http_client is None + self._client = http_client or httpx.Client( + timeout=self.timeout, follow_redirects=False + ) + + def _read(self, response): + content = bytearray() + for chunk in response.iter_bytes(): + content.extend(chunk) + if len(content) > _MAX_JSON: + raise SandboxAPIError("Response is too large", code="INVALID_RESPONSE") + return _decode(response, bytes(content)) + + def request( + self, + method, + path, + *, + json=None, + params=None, + content=None, + files=None, + headers=None, + timeout=None, + agent=False, + ): + request = self._request( + method, + path, + json=json, + params=params, + content=content, + files=files, + headers=headers, + timeout=timeout, + ) + try: + response = self._client.send( + request, stream=True, follow_redirects=False, auth=None + ) + try: + return self._checked(response, self._read(response), agent) + finally: + response.close() + except httpx.TransportError as error: + raise self._transport_error(request, error) from None + + @contextmanager + def stream( + self, + method, + path, + *, + headers=None, + timeout=None, + params=None, + json=None, + ): + request = self._request( + method, path, headers=headers, timeout=timeout, params=params, json=json + ) + try: + response = self._client.send( + request, stream=True, follow_redirects=False, auth=None + ) + try: + if not response.is_success: + self._checked(response, self._read(response)) + yield response + finally: + response.close() + except httpx.TransportError as error: + raise self._transport_error(request, error) from None + + def put_signed(self, url, source, *, headers=None, timeout=None): + with Path(source).open("rb") as content: + request = self._signed_request( + url, content, headers, timeout or self.timeout + ) + try: + response = self._client.send( + request, stream=True, auth=None, follow_redirects=False + ) + try: + if not response.is_success: + raise SandboxAPIError( + "Signed upload failed", + code="SIGNED_UPLOAD_FAILED", + status_code=response.status_code, + ) + finally: + response.close() + except httpx.TransportError: + raise SandboxAPIError( + "Signed upload outcome is unknown", + code="OUTCOME_UNKNOWN", + outcome_unknown=True, + ) from None + + def close(self): + subscriptions = self._take_subscriptions() + if subscriptions is None: + return + first_error = None + try: + for subscription in subscriptions: + try: + subscription.close() + except Exception as error: + if first_error is None: + first_error = error + finally: + self._closed = True + if self._owns_client: + self._client.close() + if first_error is not None: + raise first_error + + +class AsyncTransport(_Base): + def __init__( + self, + base_url, + api_key, + timeout=30.0, + poll_interval=0.35, + http_client: Optional[httpx.AsyncClient] = None, + ): + super().__init__(base_url, api_key, timeout, poll_interval) + self._owns_client = http_client is None + self._client = http_client or httpx.AsyncClient( + timeout=self.timeout, follow_redirects=False + ) + + async def _read(self, response): + content = bytearray() + async for chunk in response.aiter_bytes(): + content.extend(chunk) + if len(content) > _MAX_JSON: + raise SandboxAPIError("Response is too large", code="INVALID_RESPONSE") + return _decode(response, bytes(content)) + + async def request( + self, + method, + path, + *, + json=None, + params=None, + content=None, + files=None, + headers=None, + timeout=None, + agent=False, + ): + request = self._request( + method, + path, + json=json, + params=params, + content=content, + files=files, + headers=headers, + timeout=timeout, + ) + try: + response = await self._client.send( + request, stream=True, follow_redirects=False, auth=None + ) + try: + return self._checked(response, await self._read(response), agent) + finally: + await response.aclose() + except httpx.TransportError as error: + raise self._transport_error(request, error) from None + + @asynccontextmanager + async def stream( + self, + method, + path, + *, + headers=None, + timeout=None, + params=None, + json=None, + ): + request = self._request( + method, path, headers=headers, timeout=timeout, params=params, json=json + ) + try: + response = await self._client.send( + request, stream=True, follow_redirects=False, auth=None + ) + try: + if not response.is_success: + self._checked(response, await self._read(response)) + yield response + finally: + await response.aclose() + except httpx.TransportError as error: + raise self._transport_error(request, error) from None + + async def put_signed(self, url, source, *, headers=None, timeout=None): + with Path(source).open("rb") as content: + + async def chunks(): + while True: + chunk = content.read(65536) + if not chunk: + break + yield chunk + + request = self._signed_request( + url, chunks(), headers, timeout or self.timeout + ) + try: + response = await self._client.send( + request, stream=True, auth=None, follow_redirects=False + ) + try: + if not response.is_success: + raise SandboxAPIError( + "Signed upload failed", + code="SIGNED_UPLOAD_FAILED", + status_code=response.status_code, + ) + finally: + await response.aclose() + except httpx.TransportError: + raise SandboxAPIError( + "Signed upload outcome is unknown", + code="OUTCOME_UNKNOWN", + outcome_unknown=True, + ) from None + + async def aclose(self): + subscriptions = self._take_subscriptions() + if subscriptions is None: + return + first_error = None + try: + for subscription in subscriptions: + try: + await subscription.aclose() + except Exception as error: + if first_error is None: + first_error = error + finally: + self._closed = True + if self._owns_client: + await self._client.aclose() + if first_error is not None: + raise first_error diff --git a/dashscope/applications/agentstudio/sandbox/web-preview/preview.mjs b/dashscope/applications/agentstudio/sandbox/web-preview/preview.mjs new file mode 100644 index 00000000..2e668885 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/web-preview/preview.mjs @@ -0,0 +1,313 @@ +import { randomBytes, timingSafeEqual } from 'node:crypto'; +import { realpathSync } from 'node:fs'; +import http from 'node:http'; +import https from 'node:https'; +import { createInterface } from 'node:readline'; +import { Transform } from 'node:stream'; +import { pathToFileURL } from 'node:url'; + +const privateHeaders = new Set([ + 'authorization', 'proxy-authorization', 'cookie', 'referer', 'forwarded', + 'x-access-token', 'e2b-traffic-access-token', 'e2b-sandbox-id', 'e2b-sandbox-port', +]); + +export function createPreviewServer({ + upstream, upstreamCookie, sandboxHeaders = {}, gatewayAuthorization, entryPath, sessionCookie, entryLocation = '/', approvePairing, +}) { + let entry = entryPath; + const expectedCookie = Buffer.from(sessionCookie); + const transport = upstream.protocol === 'https:' ? https : http; + const server = http.createServer(forwardHttp); + server.on('upgrade', forwardWebSocket); + + function fromPreviewOrigin(request) { + const address = '127.0.0.1:' + server.address().port; + return request.headers.host === address + && (!request.headers.origin || request.headers.origin === 'http://' + address) + && (!request.headers['sec-fetch-site'] || ['same-origin', 'none'].includes(request.headers['sec-fetch-site'])) + && request.url?.startsWith('/') && !request.url.startsWith('//') && !request.url.includes('\\'); + } + + function hasSession(request) { + return (request.headers.cookie ?? '').split(';').some(cookie => { + const candidate = Buffer.from(cookie.trim()); + return candidate.length === expectedCookie.length && timingSafeEqual(candidate, expectedCookie); + }); + } + + function toUpstream(request, { inspectHandshake = false, readAvatar = false } = {}) { + const headers = { ...request.headers, host: upstream.host }; + for (const name of Object.keys(headers)) { + if (privateHeaders.has(name) || name.startsWith('x-forwarded-')) delete headers[name]; + } + if (headers.origin) headers.origin = upstream.origin; + // 配对握手需要读取 Gateway 的文本帧。 + if (inspectHandshake) delete headers['sec-websocket-extensions']; + if (upstreamCookie) headers.cookie = upstreamCookie; + const authorization = request.headers.authorization; + // OpenClaw 的头像请求使用设备凭据,由 Gateway 校验其身份及权限。 + if (gatewayAuthorization && (authorization === gatewayAuthorization + || (readAvatar && /^Bearer +[A-Za-z0-9._~+/-]+=*$/i.test(authorization ?? '')))) { + headers.authorization = authorization; + } + Object.assign(headers, sandboxHeaders); + const proxy = transport.request({ + hostname: upstream.hostname, port: upstream.port, method: request.method, path: request.url, headers, + }); + proxy.setTimeout(60_000, () => proxy.destroy()); + return proxy; + } + + function forwardHttp(request, response) { + if (!fromPreviewOrigin(request)) { + response.writeHead(403).end(); + return; + } + if (request.method === 'GET' && request.url === entry) { + entry = null; + response.writeHead(303, { + location: entryLocation, 'set-cookie': sessionCookie + '; Path=/; HttpOnly; SameSite=Strict', + 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', + }).end(); + return; + } + if (!hasSession(request)) { + response.writeHead(403).end(); + return; + } + + const readAvatar = (request.method === 'GET' || request.method === 'HEAD') + && /^\/avatar\/[A-Za-z0-9_-]+(?:\?|$)/.test(request.url); + const proxy = toUpstream(request, { readAvatar }); + proxy.on('response', remote => { + const headers = { ...remote.headers, 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' }; + delete headers['set-cookie']; + // FC 给页面附加裸 attachment,保留应用返回的带文件名下载。 + if (headers['content-disposition']?.trim().toLowerCase() === 'attachment') { + delete headers['content-disposition']; + } + if (headers.location) { + try { + const redirect = new URL(headers.location, upstream); + if (redirect.origin !== upstream.origin || redirect.pathname.startsWith('//')) throw new Error(); + headers.location = redirect.pathname + redirect.search + redirect.hash; + } catch { + remote.destroy(); + response.writeHead(502).end(); + return; + } + } + remote.on('error', () => response.destroy()); + response.writeHead(remote.statusCode, headers); + remote.pipe(response); + }); + proxy.on('error', () => { + if (response.headersSent) response.destroy(); + else response.writeHead(502).end(); + }); + response.on('close', () => { + if (!response.writableFinished) proxy.destroy(); + }); + request.pipe(proxy); + } + + let pairingRequest; + let pairingApproval; + function approvePreviewDevice(requestId) { + if (pairingRequest) return requestId === pairingRequest ? pairingApproval : undefined; + pairingRequest = requestId; + pairingApproval = approvePairing(requestId).finally(() => { pairingApproval = undefined; }); + return pairingApproval; + } + + function forwardWebSocket(request, socket, head) { + socket.on('error', () => socket.destroy()); + if (!fromPreviewOrigin(request) || !hasSession(request) + || request.headers.upgrade?.toLowerCase() !== 'websocket') { + socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); + return; + } + + const inspectHandshake = approvePairing && (!pairingRequest || pairingApproval) + && request.headers.origin === 'http://' + request.headers.host; + const proxy = toUpstream(request, { inspectHandshake }); + socket.once('close', () => proxy.destroy()); + proxy.on('upgrade', (remote, peer, remoteHead) => { + if (socket.destroyed) { + peer.destroy(); + return; + } + peer.setTimeout(0); + peer.on('error', () => socket.destroy()); + socket.once('close', () => peer.destroy()); + const handshake = ['HTTP/1.1 101 Switching Protocols']; + for (let index = 0; index < remote.rawHeaders.length; index += 2) { + const name = remote.rawHeaders[index]; + if (name.toLowerCase() !== 'set-cookie') { + handshake.push(name + ': ' + remote.rawHeaders[index + 1]); + } + } + socket.write(handshake.concat('', '').join('\r\n')); + if (inspectHandshake) { + const inspection = pairingHandshake(socket, approvePreviewDevice); + inspection.on('error', () => socket.destroy()); + inspection.pipe(socket); + if (remoteHead.length) inspection.write(remoteHead); + peer.once('close', () => inspection.end()); + peer.pipe(inspection); + } else { + peer.once('close', () => socket.destroy()); + if (remoteHead.length) socket.write(remoteHead); + peer.pipe(socket); + } + if (head.length) peer.write(head); + socket.pipe(peer); + }); + proxy.on('response', remote => { + remote.resume(); + socket.end('HTTP/1.1 ' + remote.statusCode + ' Upstream Response\r\nConnection: close\r\n\r\n'); + }); + proxy.on('error', () => socket.destroy()); + proxy.end(); + } + + return server; +} + +// 仅检查来自 Gateway 的握手帧。握手成功或原生拒绝后,按字节转发后续数据。 +function pairingHandshake(socket, approvePairing) { + let buffered = Buffer.alloc(0); + let inspecting = true; + let sawChallenge = false; + + return new Transform({ + transform(chunk, encoding, done) { + if (!inspecting) return done(null, chunk); + buffered = Buffer.concat([buffered, chunk]); + while (buffered.length >= 2) { + const flags = buffered[0]; + const size = buffered[1]; + // 非普通文本帧、压缩帧和大包交由原生 WebSocket 处理。 + if (flags !== 0x81 || size >= 127) break; + const headerSize = size === 126 ? 4 : 2; + if (buffered.length < headerSize) return done(); + const frameSize = headerSize + (size === 126 ? buffered.readUInt16BE(2) : size); + if (buffered.length < frameSize) return done(); + const raw = buffered.subarray(0, frameSize); + const frame = parseFrame(raw.subarray(headerSize)); + + if (frame?.type === 'res') { + const details = frame.error?.details; + if (sawChallenge && !socket.destroyed && frame.ok === false && frame.error?.code === 'NOT_PAIRED' + && details?.code === 'PAIRING_REQUIRED' && details.reason === 'not-paired' + && details.requestedRole === 'operator' + && typeof details.requestId === 'string' + && /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(details.requestId)) { + const approval = approvePairing(details.requestId); + if (approval) { + inspecting = false; + buffered = Buffer.alloc(0); + approval.then(approved => { + if (!socket.destroyed) { + if (!approved) this.push(raw); + this.unpipe(socket); + // 让原生前端重新连接并签名新 challenge。 + const code = approved ? 1012 : 1008; + socket.end(Buffer.from([0x88, 2, code >> 8, code & 255])); + } + done(); + }); + return; + } + } + break; + } + + if (frame?.type !== 'event' || frame.event !== 'connect.challenge') break; + sawChallenge = true; + this.push(raw); + buffered = buffered.subarray(frameSize); + } + + if (buffered.length >= 2) { + inspecting = false; + const remaining = buffered; + buffered = Buffer.alloc(0); + return done(null, remaining); + } + done(); + }, + flush(done) { + done(null, buffered); + }, + }); +} + +function parseFrame(bytes) { + try { + return JSON.parse(bytes.toString('utf8')); + } catch { + return null; + } +} + +async function start() { + const input = createInterface({ input: process.stdin }); + const lines = input[Symbol.asyncIterator](); + const { upstream: address, loginToken, sandboxHeaders, openClaw, autoPairOpenClaw } = + JSON.parse((await lines.next()).value); + const approvePairing = openClaw && autoPairOpenClaw ? requestId => { + console.log(requestId); + const deadline = setTimeout(() => input.close(), 60_000); + return lines.next().then(result => result.value === 'approved', () => false).finally(() => { + clearTimeout(deadline); + input.close(); + }); + } : undefined; + if (!approvePairing) input.close(); + const upstream = new URL(address); + const loginUrl = new URL('/', upstream); + if (!openClaw) loginUrl.searchParams.set('token', loginToken); + const login = await fetch(loginUrl, { + headers: sandboxHeaders, + redirect: 'manual', + signal: AbortSignal.timeout(15_000), + }); + const upstreamCookie = openClaw ? '' + : login.headers.getSetCookie().map(cookie => cookie.split(';', 1)[0]).join('; '); + await login.body?.cancel(); + const ready = openClaw + ? login.ok && login.headers.get('content-type')?.startsWith('text/html') + : login.status === 303 && upstreamCookie; + if (!ready) { + input.close(); + console.error('原生 Web UI 启动检查失败。HTTP ' + login.status); + process.exitCode = 1; + return; + } + + const entryPath = '/__preview/' + randomBytes(24).toString('base64url'); + const sessionCookie = 'sandbox_preview_' + randomBytes(8).toString('hex') + '=' + randomBytes(24).toString('base64url'); + // OpenClaw 在浏览器读取 fragment,并在原生 WebSocket 握手中提交 Gateway Token。 + const entryLocation = openClaw ? '/#token=' + encodeURIComponent(loginToken) : '/'; + const gatewayAuthorization = openClaw ? 'Bearer ' + loginToken : undefined; + const server = createPreviewServer({ + upstream, upstreamCookie, sandboxHeaders, gatewayAuthorization, entryPath, sessionCookie, entryLocation, + approvePairing, + }); + server.on('error', () => { + input.close(); + console.error('无法启动本地 Web UI 代理。'); + process.exitCode = 1; + }); + server.listen(0, '127.0.0.1', () => { + console.log('http://127.0.0.1:' + server.address().port + entryPath); + }); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) { + start().catch(() => { + console.error('无法连接原生 Web UI。请检查沙箱端口、网络和证书。'); + process.exitCode = 1; + }); +} diff --git a/dashscope/applications/agentstudio/sandbox/web_ui.py b/dashscope/applications/agentstudio/sandbox/web_ui.py new file mode 100644 index 00000000..5cf2decf --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/web_ui.py @@ -0,0 +1,451 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Image-native Web UI preview through a local, loopback-only Node proxy.""" + +import asyncio +import json +import os +import queue +import re +import shutil +import subprocess +import tempfile +import threading +import uuid +from dataclasses import dataclass, field, replace +from pathlib import Path +from urllib.parse import urlsplit + +from . import _bootstrap +from .exceptions import SandboxAPIError +from ._validation import resource_id + + +@dataclass(frozen=True) +class WebUiOptions: + """Reuse a Sandbox/template or provision a fresh native Web UI. + + Model settings apply only to a new Sandbox and never inherit the platform + API key. ``auto_pair_openclaw`` approves this preview browser's first + validated operator pairing request. + """ + + sandbox_id: str = None + ready_template_id: str = None + image_url: str = None + model_base_url: str = None + model_id: str = None + model_api_key: str = field(default=None, repr=False) + openclaw_model_api: str = None + auto_pair_openclaw: bool = False + + +def _validate(image, options): + from .models import OfficialImage + + if not isinstance(image, OfficialImage) or image not in ( + OfficialImage.DEEPSEEK_HARNESS, + OfficialImage.OPENCLAW, + ): + raise ValueError("image does not support a native Web UI preview") + if not isinstance(options, WebUiOptions): + raise TypeError("options must be WebUiOptions") + values = {} + for name in ( + "sandbox_id", + "ready_template_id", + "image_url", + "model_base_url", + "model_id", + "model_api_key", + "openclaw_model_api", + ): + value = getattr(options, name) + if value is not None and not isinstance(value, str): + raise ValueError(name + " must be a string") + values[name] = (value.strip() or None) if value is not None else None + validated = replace(options, **values) + if type(validated.auto_pair_openclaw) is not bool: + raise ValueError("auto_pair_openclaw must be a boolean") + if validated.image_url and (validated.sandbox_id or validated.ready_template_id): + raise ValueError("image_url can only be used when creating a template") + if validated.sandbox_id: + resource_id(validated.sandbox_id) + if validated.ready_template_id: + resource_id(validated.ready_template_id) + model_settings = ( + validated.model_base_url, + validated.model_id, + validated.model_api_key, + validated.openclaw_model_api, + ) + if validated.sandbox_id and any(model_settings): + raise ValueError("model settings can only be used when creating a Sandbox") + if validated.openclaw_model_api and ( + image != OfficialImage.OPENCLAW + or validated.openclaw_model_api + not in ("openai-completions", "anthropic-messages") + ): + raise ValueError( + "openclaw_model_api requires OpenClaw and a supported model API" + ) + if validated.model_id and not re.fullmatch( + r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}", validated.model_id + ): + raise ValueError( + "model_id must be a model identifier of at most 128 characters" + ) + if not validated.model_base_url and any(model_settings[1:]): + raise ValueError("model_base_url is required when configuring a model") + if validated.model_base_url: + try: + url = urlsplit(validated.model_base_url) + if ( + url.scheme not in ("http", "https") + or not url.hostname + or url.username is not None + or url.password is not None + or url.query + or url.fragment + or any(ord(char) < 33 for char in validated.model_base_url) + ): + raise ValueError() + url.port + except ValueError: + raise ValueError("model_base_url must be an HTTP(S) base URL") from None + validated = replace(validated, model_id=validated.model_id or "qwen3.7-plus") + return validated + + +def _check_node(): + try: + result = subprocess.run( + ["node", "--use-system-ca", "--version"], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=5, + check=False, + ) + if result.returncode == 0: + return + except (OSError, subprocess.TimeoutExpired): + pass + raise SandboxAPIError( + "Install Node.js with --use-system-ca support and add it to PATH", + code="WEB_UI_NODE_UNAVAILABLE", + ) + + +def _read_line(stream): + line = stream.readline(4097) + if len(line) > 4096 or (line and not line.endswith(b"\n")): + raise OSError("Invalid local preview response") + try: + return line.rstrip(b"\r\n").decode("ascii") if line else None + except UnicodeError: + raise OSError("Invalid local preview response") from None + + +class _Resources: + def __init__(self, templates, transport): + self.templates = templates + self.transport = transport + self.sandbox = None + self.owned_template = None + self.proxy = None + self.script = None + self.preview = None + self.owned_client = None + self.parent_transport = None + self._closed = False + self._lock = threading.Lock() + + def start_proxy(self, route, auto_pair): + descriptor, self.script = tempfile.mkstemp( + prefix="sandbox-web-preview-", suffix=".mjs" + ) + with os.fdopen(descriptor, "wb") as target: + with (Path(__file__).parent / "web-preview" / "preview.mjs").open( + "rb" + ) as source: + shutil.copyfileobj(source, target) + self.proxy = subprocess.Popen( + ["node", "--use-system-ca", self.script], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + ) + settings = { + "upstream": route.upstream, + "loginToken": route.login_token, + "sandboxHeaders": route.headers, + "openClaw": route.openclaw, + "autoPairOpenClaw": auto_pair, + } + # 连接凭据只通过 stdin 传递,临时文件只保存代理源码。 + self.proxy.stdin.write( + json.dumps(settings, separators=(",", ":")).encode() + b"\n" + ) + self.proxy.stdin.flush() + if not auto_pair: + self.proxy.stdin.close() + result = queue.Queue(maxsize=1) + + def read_ready(): + try: + result.put(_read_line(self.proxy.stdout)) + except (OSError, ValueError): + result.put(None) + + threading.Thread( + target=read_ready, name="sandbox-preview-ready", daemon=True + ).start() + try: + address = result.get(timeout=20) + except queue.Empty: + raise OSError("Local preview startup did not complete") from None + if ( + not address + or not re.fullmatch( + r"http://127\.0\.0\.1:[0-9]+/__preview/[A-Za-z0-9_-]+", address + ) + or not 0 < urlsplit(address).port < 65536 + ): + raise OSError("Local preview did not return a loopback URL") + if auto_pair: + threading.Thread( + target=self._approve, + args=(route.bootstrap,), + name="sandbox-preview-pairing", + daemon=True, + ).start() + else: + self.proxy.stdout.close() + return address + + def _approve(self, bootstrap): + proxy = self.proxy + try: + request_id = _read_line(proxy.stdout) + if request_id is None or self._closed: + return + result = b"denied\n" + try: + _bootstrap._approve_pairing(bootstrap, request_id) + result = b"approved\n" + except (OSError, SandboxAPIError): + pass + if not self._closed: + proxy.stdin.write(result) + proxy.stdin.flush() + except (OSError, ValueError): + pass + finally: + proxy.stdout.close() + proxy.stdin.close() + + def close(self): + with self._lock: + if self._closed: + return + self._closed = True + error = None + try: + if self.proxy is not None: + if self.proxy.poll() is None: + self.proxy.kill() + self.proxy.wait(timeout=5) + for stream in (self.proxy.stdin, self.proxy.stdout): + if stream is not None: + stream.close() + except (OSError, ValueError, subprocess.TimeoutExpired) as failure: + error = failure + # 即便一种清理失败,也继续释放本次新建的其余资源。 + try: + if self.sandbox is not None: + self.sandbox.release() + except Exception as failure: + error = error or failure + try: + if self.owned_template is not None: + self.templates.delete(self.owned_template) + except Exception as failure: + error = error or failure + finally: + if self.script is not None: + try: + os.unlink(self.script) + except FileNotFoundError: + pass + except OSError as failure: + error = error or failure + if self.preview is not None: + self.transport.unregister(self.preview) + if self.parent_transport is not None: + self.parent_transport.unregister(self.preview) + if self.owned_client is not None: + self.owned_client.close() + if error is not None: + raise error + + +class SandboxWebUi: + """One-time browser entry. Keep the preview URL private; close after use.""" + + def __init__(self, preview_url, sandbox_id, template_id, resources): + self.preview_url = preview_url + self.sandbox_id = sandbox_id + self.template_id = template_id + self._resources = resources + + def __repr__(self): + return "SandboxWebUi(sandbox_id={!r}, template_id={!r}, preview_url=)".format( + self.sandbox_id, self.template_id + ) + + def close(self): + """Close the local proxy and release only resources created by this preview.""" + self._resources.close() + + async def aclose(self): + await asyncio.to_thread(self.close) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_value, traceback): + await self.aclose() + + +def _create_template(resources, transport, image, image_url): + from .models import TemplateCreateRequest + from .agents import AgentsClient + + compute = AgentsClient(transport).template_config().default_compute + request = TemplateCreateRequest( + name=image.value + "-web-preview-" + uuid.uuid4().hex[:8], + image=image, + from_image=image_url, + cpu_count=compute.cpu, + memory_mb=compute.memory_mib, + ) + template = resources.templates.create(request) + resources.owned_template = template.id + build_id = template.build_id + if build_id is None: + build_id = resources.templates.get(template.id).build_id + resources.templates.wait_ready(template.id, build_id, timeout=480) + return template.id + + +def open_web_ui(sandboxes, transport, image, options=None): + """Provision/start a native Web UI and its credential-isolating local proxy.""" + from .templates import TemplatesClient + from .models import SandboxCreateRequest + + if transport._closed or transport._closing or transport._client.is_closed: + raise ValueError("Sandbox client is closed") + options = _validate(image, options if options is not None else WebUiOptions()) + _check_node() + resources = _Resources(TemplatesClient(transport), transport) + try: + template_id = options.ready_template_id + sandbox_id = options.sandbox_id + fresh = sandbox_id is None + if fresh: + if template_id is None: + template_id = _create_template( + resources, transport, image, options.image_url + ) + resources.sandbox = sandboxes.create( + SandboxCreateRequest( + template_id=template_id, + secure=True, + timeout=3600, + metadata={"purpose": image.value + "-native-web-preview"}, + ) + ) + sandbox_id = resources.sandbox.id + connected = sandboxes.connect(sandbox_id) + if not fresh and template_id and template_id != connected.template_id: + raise ValueError("Sandbox does not belong to ready_template_id") + route = _bootstrap.prepare( + connected.id, + connected.connection, + image, + fresh, + options.model_base_url or "", + options.model_id or "", + options.model_api_key or "", + options.openclaw_model_api or "", + ) + address = resources.start_proxy( + route, route.openclaw and options.auto_pair_openclaw + ) + preview = SandboxWebUi( + address, + connected.id, + template_id if fresh else connected.template_id, + resources, + ) + resources.preview = preview + transport.register(preview) + return preview + except BaseException as failure: + try: + resources.close() + except Exception: + pass + if isinstance(failure, (OSError, subprocess.SubprocessError)): + raise SandboxAPIError( + "Could not prepare the native Web UI or start the local proxy", + code="WEB_UI_UNAVAILABLE", + ) from None + raise + + +async def async_open_web_ui(sandboxes, transport, image, options=None): + """Use a dedicated synchronous HTTP client for blocking native setup. + + Cancellation waits for setup and resource cleanup. The asynchronous SDK's + HTTP client is never used from the worker thread. + """ + from .client import SandboxClient + + if transport._closed or transport._closing or transport._client.is_closed: + raise ValueError("Sandbox client is closed") + options = _validate(image, options if options is not None else WebUiOptions()) + owned = SandboxClient( + base_url=transport.base_url, + api_key=transport.api_key, + timeout=transport.timeout, + poll_interval=transport.poll_interval, + ) + + def start(): + try: + preview = open_web_ui(owned.sandboxes, owned._transport, image, options) + preview._resources.owned_client = owned + preview._resources.parent_transport = transport + transport.register(preview) + return preview + except BaseException: + owned.close() + raise + + task = asyncio.create_task(asyncio.to_thread(start)) + try: + return await asyncio.shield(task) + except asyncio.CancelledError: + try: + preview = await task + await preview.aclose() + finally: + raise diff --git a/dashscope/client.py b/dashscope/client.py index 5f6d342f..85c558b8 100644 --- a/dashscope/client.py +++ b/dashscope/client.py @@ -279,10 +279,12 @@ def with_options( ) def close(self) -> None: - self._transport.close() - if self._agentstudio is not None: - self._agentstudio.close() - self._agentstudio = None + try: + if self._agentstudio is not None: + self._agentstudio.close() + self._agentstudio = None + finally: + self._transport.close() def ws_connection( self, @@ -533,10 +535,12 @@ def with_options( ) async def aclose(self) -> None: - await self._transport.aclose() - if self._agentstudio is not None: - await self._agentstudio.aclose() - self._agentstudio = None + try: + if self._agentstudio is not None: + await self._agentstudio.aclose() + self._agentstudio = None + finally: + await self._transport.aclose() async def __aenter__(self) -> "AsyncClient": return self diff --git a/dashscope/version.py b/dashscope/version.py index 88cef6b2..553343b7 100644 --- a/dashscope/version.py +++ b/dashscope/version.py @@ -1,4 +1,4 @@ # -*- coding: utf-8 -*- # Copyright (c) Alibaba, Inc. and its affiliates. -__version__ = "2.1.0" +__version__ = "2.1.0.1" diff --git a/tests/agentstudio_sandbox/test_agents.py b/tests/agentstudio_sandbox/test_agents.py new file mode 100644 index 00000000..e84ebfd4 --- /dev/null +++ b/tests/agentstudio_sandbox/test_agents.py @@ -0,0 +1,590 @@ +"""Managed Agent protocol tests; all HTTP is local MockTransport traffic.""" + +import asyncio +import io +import json +import threading +import time + +import httpx +import pytest + +from dashscope.applications.agentstudio.sandbox.agents import ( + AgentHandle, + AgentsClient, + AsyncAgentHandle, + AsyncAgentsClient, +) +from dashscope.applications.agentstudio.sandbox.exceptions import ( + SandboxAPIError, + SandboxWaitTimeoutError, +) +from dashscope.applications.agentstudio.sandbox.models import ( + AgentInstanceInfo, + LaunchRequest, + ModelConfig, + OfficialImage, + UploadedFile, +) +from dashscope.applications.agentstudio.sandbox.transport import ( + AGENT, + AsyncTransport, + Transport, +) + + +def response(data, status=200): + return httpx.Response(status, json={"data": data}) + + +def instance(**extra): + return dict( + instance_id="ai_one", + state="READY", + harness_type="deepseek-harness", + image_name="deepseek-harness", + default_session_id="as_default", + **extra + ) + + +def uploaded(identifier="af_one", instance_id="ai_one", size=3): + return UploadedFile.from_dict( + dict( + file_id=identifier, + instance_id=instance_id, + name="hello.txt", + path="/home/user/hello.txt", + size_bytes=size, + ) + ) + + +def sync_client(handler, poll_interval=0.001): + pool = httpx.Client(transport=httpx.MockTransport(handler)) + transport = Transport( + "https://unit.test", + "platform-key", + http_client=pool, + poll_interval=poll_interval, + ) + return AgentsClient(transport), transport, pool + + +def test_launch_accept_wait_typed_handles_and_no_model_credentials_fallback(): + seen = [] + + def handler(request): + seen.append(request) + if request.url.path.startswith(AGENT): + assert request.headers["Authorization"] == "Bearer platform-key" + if request.method == "POST": + body = json.loads(request.content) + assert body["harness_type"] == "deepseek-harness" + assert "model_config" not in body + return response({"instance_id": "ai_one", "operation_id": "ao_launch"}, 202) + if "/operations/" in request.url.path: + return response( + dict(operation_id="ao_launch", instance_id="ai_one", status="SUCCEEDED") + ) + return response(instance()) + + agents, transport, pool = sync_client(handler) + try: + operation = agents.launch_async( + LaunchRequest(image=OfficialImage.DEEPSEEK_HARNESS) + ) + assert operation.instance_id == "ai_one" + assert operation.operation_id == "ao_launch" + agent = operation.wait(timeout=2) + assert agent.id == "ai_one" + assert agent.default_session.id == "as_default" + assert isinstance(agent.get_info(), AgentInstanceInfo) + assert len([r for r in seen if r.method == "POST"]) == 1 + transport.close() + assert pool.get("https://unit.test/borrowed-still-open").status_code == 200 + finally: + transport.close() + pool.close() + + +def test_template_reuse_does_not_send_image_and_explicit_model_key_only(): + seen = [] + + def handler(request): + seen.append(json.loads(request.content)) + return response({"instance_id": "ai_one", "operation_id": "ao_launch"}, 202) + + agents, transport, pool = sync_client(handler) + try: + agents.launch_async( + LaunchRequest( + image=OfficialImage.DEEPSEEK_HARNESS, + template_id="tpl_one", + model_config=ModelConfig(base_url="https://model.test/v1"), + ) + ) + assert seen[0]["template_id"] == "tpl_one" + assert "image_name" not in seen[0] + assert "api_key" not in seen[0]["model_config"] + assert seen[0]["model_config"]["model_id"] == "qwen3.7-plus" + finally: + transport.close() + pool.close() + + +def test_lists_preserve_typed_items_cursor_and_safe_query_encoding(): + seen = [] + + def handler(request): + seen.append(request) + if request.url.path.endswith("/instances"): + return response({"items": [instance()], "next_cursor": "next+ /?="}) + if request.url.path.endswith("/sessions"): + return response( + {"items": [{"session_id": "as_one", "instance_id": "ai_one"}]} + ) + return response( + { + "items": [ + { + "turn_id": "at_one", + "session_id": "as_one", + "instance_id": "ai_one", + "status": "RUNNING", + } + ] + } + ) + + agents, transport, pool = sync_client(handler) + try: + page = agents.list_instances(3, "cursor+ /?=") + assert isinstance(page.items[0], AgentInstanceInfo) + assert page.next_cursor == "next+ /?=" + assert seen[-1].url.params["cursor"] == "cursor+ /?=" + assert agents.list_sessions("ai_one").items[0].id == "as_one" + assert agents.session("as_one").list_turns().items[0].id == "at_one" + for limit in (0, 101, True, 1.5): + with pytest.raises(ValueError): + agents.list_instances(limit) + finally: + transport.close() + pool.close() + + +def test_prompt_files_are_unique_instance_bound_and_text_deadline_bounded(): + seen = [] + + def handler(request): + seen.append(json.loads(request.content)) + return response({"turn_id": "at_one", "status": "PENDING"}, 201) + + agents, transport, pool = sync_client(handler) + agent = AgentHandle( + transport, "ai_one", "as_one", AgentInstanceInfo.from_dict(instance()) + ) + try: + session = agent.default_session + turn = session.submit_with_files("continue", [uploaded()], deadline_seconds=300) + assert turn.id == "at_one" + assert seen == [ + { + "input": [{"type": "text", "text": "continue"}], + "attachment_ids": ["af_one"], + "deadline_seconds": 300, + } + ] + invalid_files = ( + [uploaded(), uploaded()], + [uploaded(instance_id="ai_other")], + [uploaded(str(i)) for i in range(17)], + ) + for files in invalid_files: + with pytest.raises(ValueError): + session.submit_with_files("hello", files) + for duration in (0, 3601, 1.5, True): + with pytest.raises(ValueError): + session.submit("hello", deadline_seconds=duration) + with pytest.raises(ValueError): + session.submit("好" * 350000) + assert len(seen) == 1 + finally: + transport.close() + pool.close() + + +class RecordingInput(io.BytesIO): + def __init__(self, data): + super().__init__(data) + self.read_sizes = [] + + def read(self, size=-1): + self.read_sizes.append(size) + assert size > 0, "upload must not buffer a stream with read()" + return super().read(size) + + +def test_upload_streaming_cap_filename_size_ownership_and_source_closure(tmp_path): + seen = [] + + def handler(request): + seen.append(request) + assert request.headers["Content-Type"] == "application/octet-stream" + return response( + dict( + file_id="af_one", + instance_id="ai_one", + name=request.url.params["name"], + path="/private/hello.txt", + size_bytes=len(request.content), + ) + ) + + agents, transport, pool = sync_client(handler) + agent = AgentHandle( + transport, + "ai_one", + "as_one", + AgentInstanceInfo.from_dict(instance(max_upload_bytes=10)), + ) + try: + source = RecordingInput(b"hello") + file = agent.upload("hello.txt", source) + assert file.id == "af_one" and file.instance_id == agent.id + assert source.closed and all(size > 0 for size in source.read_sizes) + path = tmp_path / "local.txt" + path.write_bytes(b"abc") + assert agent.upload(path).size_bytes == 3 + assert seen[-1].headers["Content-Length"] == "3" + for name, data, size in [ + ("too-big", b"x" * 11, 11), + ("../bad", b"a", 1), + ("too-big-unknown", b"x" * 11, -1), + ("bad-size", b"abc", 2), + ("short-size", b"ab", 3), + ]: + source = RecordingInput(data) + with pytest.raises((ValueError, SandboxAPIError)): + agent.upload(name, source, size) + assert source.closed + source = RecordingInput(b"abc") + with pytest.raises(ValueError): + agent.upload("empty", source, 0) + assert source.closed + finally: + transport.close() + pool.close() + + +def test_failed_unknown_operation_and_turn_cancellation_request_semantics(): + status = ["RUNNING", "CANCELLED"] + + def handler(request): + if "/operations/" in request.url.path: + return response( + { + "operation_id": "ao_one", + "instance_id": "ai_one", + "status": "UNKNOWN", + "error": {"code": "NATIVE_DISCONNECTED", "message": "unconfirmed"}, + } + ) + if request.method == "POST": + return response({"turn_id": "at_one", "status": "CANCELLING"}) + return response({"turn_id": "at_one", "status": status.pop(0), "output": []}) + + agents, transport, pool = sync_client(handler) + try: + with pytest.raises(SandboxAPIError) as error: + agents.operation("ao_one").wait(1) + assert error.value.code == "NATIVE_DISCONNECTED" + assert error.value.outcome_unknown + assert error.value.resource_id == "ao_one" + turn = agents.turn("at_one") + assert turn.cancel().status == "CANCELLING" + assert turn.wait(1).status == "CANCELLED" + finally: + transport.close() + pool.close() + + +def test_polling_budgets_each_request_and_timeout_preserves_resource_id(): + budgets = [] + + def handler(request): + budgets.append(request.extensions["timeout"]["read"]) + time.sleep(0.004) + return response({"operation_id": "ao_slow", "status": "PENDING"}) + + agents, transport, pool = sync_client(handler) + try: + with pytest.raises(SandboxWaitTimeoutError) as error: + agents.operation("ao_slow").wait(0.025) + assert error.value.resource_id == "ao_slow" + assert error.value.status == "PENDING" + assert len(budgets) >= 2 and budgets[-1] < budgets[0] <= 0.025 + finally: + transport.close() + pool.close() + + +def test_async_launch_submit_upload_poll_and_release_parity(): + async def run(): + seen = [] + + async def handler(request): + seen.append(request) + path = request.url.path + if request.method == "POST" and path.endswith("/instances"): + assert "model_config" not in json.loads(request.content) + return response({"instance_id": "ai_one", "operation_id": "ao_launch"}) + if "/operations/" in path: + return response( + { + "operation_id": "ao_launch", + "instance_id": "ai_one", + "status": "SUCCEEDED", + } + ) + if path.endswith("/sessions/as_default/turns"): + if request.method == "POST": + return response({"turn_id": "at_one"}) + return response( + { + "items": [ + { + "turn_id": "at_one", + "session_id": "as_default", + "instance_id": "ai_one", + "status": "RUNNING", + } + ] + } + ) + if path.endswith("/files"): + return response( + dict( + file_id="af_one", + instance_id="ai_one", + name="upload.txt", + path="/private/upload.txt", + size_bytes=len(request.content), + ) + ) + if "/turns/" in path: + return response( + { + "turn_id": "at_one", + "status": "SUCCEEDED", + "output": [{"type": "text", "text": "hello"}], + } + ) + if request.method == "DELETE": + return response({"operation_id": "ao_launch"}) + return response(instance(max_upload_bytes=10)) + + pool = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + transport = AsyncTransport( + "https://unit.test", "platform-key", http_client=pool + ) + agents = AsyncAgentsClient(transport) + try: + launch = await agents.launch_async( + LaunchRequest(image=OfficialImage.DEEPSEEK_HARNESS) + ) + agent = await launch.wait(2) + source = RecordingInput(b"abc") + assert (await agent.upload("upload.txt", source)).size_bytes == 3 + assert source.closed + turn = await agent.default_session.submit_with_files("hello", [uploaded()]) + assert (await turn.wait()).text == "hello" + assert (await agent.default_session.list_turns()).items[0].id == turn.id + assert (await agent.release()).id == "ao_launch" + assert ( + sum( + r.method == "POST" and r.url.path.endswith("/instances") + for r in seen + ) + == 1 + ) + await transport.aclose() + assert (await pool.get("https://unit.test/still-open")).status_code == 200 + finally: + await transport.aclose() + await pool.aclose() + + asyncio.run(run()) + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("source_kind", ["path", "known-stream", "unknown-stream"]) +def test_empty_upload_sources_are_valid_and_streams_close( + tmp_path, asynchronous, source_kind +): + seen = [] + + def handler(request): + seen.append(request) + assert request.content == b"" + if source_kind == "unknown-stream": + assert "Content-Length" not in request.headers + else: + assert request.headers["Content-Length"] == "0" + return response( + dict( + file_id="af_empty", + instance_id="ai_one", + name="empty.txt", + path="/private/empty.txt", + size_bytes=0, + ) + ) + + path = tmp_path / "empty.txt" + path.write_bytes(b"") + source = RecordingInput(b"") + + def upload_arguments(): + if source_kind == "path": + return (path,) + return ("empty.txt", source, 0 if source_kind == "known-stream" else -1) + + if asynchronous: + + async def run(): + async with httpx.AsyncClient( + transport=httpx.MockTransport(handler) + ) as pool: + transport = AsyncTransport( + "https://unit.test", "platform-key", http_client=pool + ) + agent = AsyncAgentHandle( + transport, + "ai_one", + "as_one", + AgentInstanceInfo.from_dict(instance(max_upload_bytes=10)), + ) + try: + return await agent.upload(*upload_arguments()) + finally: + await transport.aclose() + + file = asyncio.run(run()) + else: + _, transport, pool = sync_client(handler) + agent = AgentHandle( + transport, + "ai_one", + "as_one", + AgentInstanceInfo.from_dict(instance(max_upload_bytes=10)), + ) + try: + file = agent.upload(*upload_arguments()) + finally: + transport.close() + pool.close() + assert file.size_bytes == 0 and file.instance_id == "ai_one" + assert len(seen) == 1 + if source_kind != "path": + assert source.closed + + +@pytest.mark.parametrize("contents", [b"", b"x"], ids=["empty", "nonempty"]) +def test_async_zero_length_upload_reads_off_event_loop(contents): + reads = [] + + class ThreadRecordingInput(RecordingInput): + def read(self, size=-1): + reads.append(threading.get_ident()) + return super().read(size) + + source = ThreadRecordingInput(contents) + + async def handler(request): + assert await request.aread() == b"" + assert request.headers["Content-Length"] == "0" + return response( + dict( + file_id="af_empty", + instance_id="ai_one", + name="empty.txt", + path="/private/empty.txt", + size_bytes=0, + ) + ) + + async def run(): + loop_thread = threading.get_ident() + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as pool: + transport = AsyncTransport( + "https://unit.test", "platform-key", http_client=pool + ) + agent = AsyncAgentHandle( + transport, + "ai_one", + "as_one", + AgentInstanceInfo.from_dict(instance(max_upload_bytes=10)), + ) + try: + if contents: + with pytest.raises(ValueError): + await agent.upload("empty.txt", source, 0) + else: + assert (await agent.upload("empty.txt", source, 0)).size_bytes == 0 + finally: + await transport.aclose() + assert reads and all(identifier != loop_thread for identifier in reads) + + asyncio.run(run()) + assert source.closed + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_nonempty_stream_declared_empty_is_rejected_and_closed(asynchronous): + seen = [] + + def handler(request): + seen.append(request) + return response({}) + + source = RecordingInput(b"x") + if asynchronous: + + async def run(): + async with httpx.AsyncClient( + transport=httpx.MockTransport(handler) + ) as pool: + transport = AsyncTransport( + "https://unit.test", "platform-key", http_client=pool + ) + agent = AsyncAgentHandle( + transport, + "ai_one", + "as_one", + AgentInstanceInfo.from_dict(instance(max_upload_bytes=10)), + ) + try: + with pytest.raises(ValueError): + await agent.upload("empty.txt", source, 0) + finally: + await transport.aclose() + + asyncio.run(run()) + else: + _, transport, pool = sync_client(handler) + agent = AgentHandle( + transport, + "ai_one", + "as_one", + AgentInstanceInfo.from_dict(instance(max_upload_bytes=10)), + ) + try: + with pytest.raises(ValueError): + agent.upload("empty.txt", source, 0) + finally: + transport.close() + pool.close() + assert not seen + assert source.read_sizes + assert source.closed diff --git a/tests/agentstudio_sandbox/test_client.py b/tests/agentstudio_sandbox/test_client.py new file mode 100644 index 00000000..33ed70d3 --- /dev/null +++ b/tests/agentstudio_sandbox/test_client.py @@ -0,0 +1,532 @@ +# -*- coding: utf-8 -*- +"""Shared client boundaries and non-invasive AgentStudio integration.""" + +import httpx +import pytest + +from dashscope.applications.agentstudio.sandbox import ( + AsyncSandboxClient, + LaunchRequest, + ModelConfig, + OfficialImage, + SandboxAPIError, + SandboxClient, + SandboxConnection, + SandboxCreateRequest, + TemplateInfo, + TemplateUpdateRequest, +) + + +@pytest.mark.parametrize( + "suffix", + [ + "", + "/compatible-mode/v1", + "/api/v1/agentstudio", + "/api/v1/agentstudio/sandbox", + "/api/v1/agentstudio/agent-runtime", + ], +) +def test_four_facets_share_fixed_bearer_and_proxy_base(suffix): + calls = [] + + def handle(request): + calls.append(request) + if request.url.path.endswith("/instances"): + return httpx.Response(200, json={"data": {"items": []}}) + if request.url.path.endswith("/files/file_a"): + return httpx.Response(200, json={"id": "file_a"}) + return httpx.Response(200, json=[]) + + pool = httpx.Client( + transport=httpx.MockTransport(handle), + headers={"X-DashScope-Workspace": "not-forwarded"}, + ) + with SandboxClient( + base_url="https://unit.test/proxy" + suffix, + api_key="fixed-key", + http_client=pool, + ) as client: + client.templates.list() + client.sandboxes.list() + client.agents.list_instances() + client.template_files.get("file_a") + assert all(r.headers["Authorization"] == "Bearer fixed-key" for r in calls) + assert all(r.url.path.startswith("/proxy/api/v1/agentstudio/") for r in calls) + assert all("X-DashScope-Workspace" not in r.headers for r in calls) + assert not pool.is_closed + pool.close() + + +@pytest.mark.parametrize( + "url", + [ + "https://user:pass@unit.test", + "https://unit.test?token=x", + "https://unit.test/#frag", + "file:///tmp/file", + "https://unit.test:0", + ], +) +def test_invalid_base_urls_rejected(url): + with pytest.raises(ValueError): + SandboxClient(base_url=url, api_key="key") + + +@pytest.mark.parametrize("key", [None, "", " ", "x\nheader", "x,y", "密钥", "x" * 8193]) +def test_invalid_key_error_does_not_reveal_credentials(key): + with pytest.raises(ValueError, match="Invalid API key") as error: + SandboxClient(base_url="https://unit.test", api_key=key) + assert str(error.value) == "Invalid API key" + + +def test_model_credentials_never_fall_back_to_platform_config(): + request = LaunchRequest(image=OfficialImage.DEEPSEEK_HARNESS) + assert "model_config" not in request.to_dict() + configured = LaunchRequest( + image=OfficialImage.OPENCLAW, + model_config=ModelConfig(base_url="https://model.test/v1"), + ) + assert configured.to_dict()["model_config"] == { + "base_url": "https://model.test/v1", + "model_id": "qwen3.7-plus", + } + assert LaunchRequest( + image=OfficialImage.OPENCLAW, template_id="tpl_a" + ).to_dict() == {"harness_type": "openclaw", "template_id": "tpl_a"} + + +def test_model_secrets_hidden_in_repr_and_validation_messages(): + secret = "synthetic-private-model-key" + model = ModelConfig(base_url="https://model.test/v1", api_key=secret) + assert secret not in repr(model) and secret not in str(model) + with pytest.raises(ValueError) as error: + ModelConfig(api_key=secret) + assert secret not in str(error.value) + connection = SandboxConnection(envdAccessToken=secret, trafficAccessToken=secret) + assert secret not in repr(connection) and secret not in str(connection) + + +def test_updates_keep_explicit_empty_collections_but_not_unset_fields(): + assert TemplateUpdateRequest(env_config={}).to_dict() == {"envConfig": {}} + assert SandboxCreateRequest(template_id="tpl_a").to_dict() == { + "templateID": "tpl_a" + } + info = TemplateInfo.from_dict( + { + "templateID": "tpl_a", + "names": ["first"], + "builds": [{"buildID": "b1", "status": "READY"}], + } + ) + assert info.name == "first" and info.build_id == "b1" + + +def test_unknown_write_outcome_is_not_retried(): + attempts = [] + + def handle(request): + attempts.append(request) + raise httpx.ReadTimeout("do not echo credentials", request=request) + + pool = httpx.Client(transport=httpx.MockTransport(handle)) + with SandboxClient( + base_url="https://unit.test", api_key="fixed-key", http_client=pool + ) as client: + with pytest.raises(SandboxAPIError) as error: + client.agents.launch_async(LaunchRequest(image=OfficialImage.OPENCLAW)) + assert error.value.outcome_unknown + assert len(attempts) == 1 + pool.close() + + +def test_main_agentstudio_sandbox_mount_is_lazy_and_shares_pool(): + from dashscope import Client + + pool = httpx.Client( + transport=httpx.MockTransport(lambda r: httpx.Response(200, json=[])) + ) + with Client( + base_url="https://unit.test", api_key="key", http_client=pool + ) as client: + studio = client.agentstudio + sandbox = studio.sandbox + assert sandbox is studio.sandbox + assert sandbox._transport._client is pool + sandbox.templates.list() + assert not pool.is_closed + pool.close() + + +@pytest.mark.asyncio +async def test_async_mount_shares_pool_and_leaves_existing_api_usable(): + from dashscope import AsyncClient + + pool = httpx.AsyncClient( + transport=httpx.MockTransport(lambda r: httpx.Response(200, json=[])) + ) + async with AsyncClient( + base_url="https://unit.test", api_key="key", http_client=pool + ) as client: + sandbox = client.agentstudio.sandbox + assert isinstance(sandbox, AsyncSandboxClient) + assert sandbox._transport._client is pool + await sandbox.templates.list() + assert not pool.is_closed + await pool.aclose() + + +def test_legacy_deep_import_is_the_same_new_module(): + from dashscope.agentstudio.sandbox import SandboxClient as LegacyImport + + assert LegacyImport is SandboxClient + + +def test_template_response_accepts_unconfigured_console_fields_and_old_mounts(): + info = TemplateInfo.from_dict( + { + "templateID": "tpl_old", + "envConfig": None, + "mntConfig": None, + "builds": None, + "version": 1, + } + ) + assert info.env_config == {} and info.mounts == [] and info.builds == [] + info = TemplateInfo.from_dict( + {"templateID": "tpl_old", "mntConfig": [{"mountPath": "/opt/data/a.txt"}]} + ) + assert info.mounts[0].mount_path == "/opt/data/a.txt" + + +def test_sandbox_response_accepts_unconfigured_metadata(): + from dashscope.applications.agentstudio.sandbox import SandboxInfo + + assert ( + SandboxInfo.from_dict({"sandboxID": "sbx_a", "metadata": None}).metadata == {} + ) + + +def test_bad_nested_template_response_is_a_protocol_error(): + with pytest.raises(SandboxAPIError) as error: + TemplateInfo.from_dict({"templateID": "tpl_a", "builds": [1]}) + assert error.value.code == "INVALID_RESPONSE" + + +def test_parent_owned_pool_closes_even_if_preview_cleanup_fails(): + from dashscope.applications.agentstudio.client import Client + + class BrokenPreview: + def close(self): + raise RuntimeError("cleanup failed") + + client = Client(base_url="https://unit.test", api_key="key") + client._sandbox = BrokenPreview() + with pytest.raises(RuntimeError, match="cleanup failed"): + client.close() + assert client.transport._client.is_closed + + +@pytest.mark.asyncio +async def test_async_parent_pool_closes_when_preview_cleanup_fails(): + from dashscope.applications.agentstudio.client import AsyncClient + + class BrokenPreview: + async def aclose(self): + raise RuntimeError("cleanup failed") + + client = AsyncClient(base_url="https://unit.test", api_key="key") + client._sandbox = BrokenPreview() + with pytest.raises(RuntimeError, match="cleanup failed"): + await client.aclose() + assert client.transport._client.is_closed + + +@pytest.fixture +def mounted_preview_platform(monkeypatch): + from types import SimpleNamespace + from dashscope.applications.agentstudio.sandbox import web_ui as _web_ui + + calls = [] + + def reply(request): + calls.append((request.method, request.url.path)) + path = request.url.path + if path.endswith("/template-config"): + value = { + "data": { + "images": [], + "resource_configs": [], + "default_compute": {"cpu": 1, "memory_mib": 2048}, + } + } + elif "/images/" in path: + value = { + "imageName": "deepseek-harness", + "imageUrl": "registry.test/dsh:v1", + } + elif path.endswith("/v3/templates"): + value = {"templateID": "tpl_preview", "buildID": "build_one"} + elif path.endswith("/status"): + value = {"status": "READY"} + elif path.endswith("/sandboxes") or path.endswith("/connect"): + value = {"sandboxID": "sbx_preview", "templateID": "tpl_preview"} + elif request.method == "DELETE": + return httpx.Response(204) + else: + raise AssertionError("Unexpected native preview API") + return httpx.Response(200, json=value) + + sync_type, async_type = httpx.Client, httpx.AsyncClient + + def sync_pool(**kwargs): + return sync_type(transport=httpx.MockTransport(reply), **kwargs) + + def async_pool(**kwargs): + return async_type(transport=httpx.MockTransport(reply), **kwargs) + + monkeypatch.setattr(httpx, "Client", sync_pool) + monkeypatch.setattr(httpx, "AsyncClient", async_pool) + monkeypatch.setattr(_web_ui, "_check_node", lambda: None) + monkeypatch.setattr( + _web_ui._bootstrap, "prepare", lambda *args: SimpleNamespace(openclaw=False) + ) + monkeypatch.setattr( + _web_ui._Resources, + "start_proxy", + lambda *args: "http://127.0.0.1:12345/__preview/entry", + ) + return calls + + +def test_root_owned_pool_remains_open_until_mounted_preview_is_released( + mounted_preview_platform, +): + from dashscope import Client + + client = Client(base_url="https://unit.test/api/v1", api_key="key") + pool = client.transport.http_client + assert client.transport._owns_client + try: + with client: + preview = client.agentstudio.sandbox.sandboxes.open_web_ui( + OfficialImage.DEEPSEEK_HARNESS + ) + assert preview._resources._closed + assert pool.is_closed + assert [ + path for method, path in mounted_preview_platform if method == "DELETE" + ] == [ + "/api/v1/agentstudio/sandbox/sandboxes/sbx_preview", + "/api/v1/agentstudio/sandbox/templates/tpl_preview", + ] + finally: + client.close() + + +@pytest.mark.asyncio +async def test_async_root_keeps_pool_open_during_real_mounted_preview_cleanup( + mounted_preview_platform, + monkeypatch, +): + from dashscope import AsyncClient + + client = AsyncClient(base_url="https://unit.test/api/v1", api_key="key") + pool = client.transport.http_client + assert client.transport._owns_client + preview = None + try: + async with client: + preview = await client.agentstudio.sandbox.sandboxes.open_web_ui( + OfficialImage.DEEPSEEK_HARNESS + ) + close_preview = preview.aclose + + async def cleanup_before_root_pool(): + assert not pool.is_closed, "Root pool closed before mounted resources" + await close_preview() + + monkeypatch.setattr(preview, "aclose", cleanup_before_root_pool) + assert preview._resources._closed + assert pool.is_closed + assert [ + path for method, path in mounted_preview_platform if method == "DELETE" + ] == [ + "/api/v1/agentstudio/sandbox/sandboxes/sbx_preview", + "/api/v1/agentstudio/sandbox/templates/tpl_preview", + ] + finally: + if preview is not None: + await close_preview() + await client.aclose() + + +def test_root_owned_pool_closes_if_mounted_resource_cleanup_raises(): + from dashscope import Client + + class BrokenPreview: + def close(self): + raise RuntimeError("preview cleanup failed") + + client = Client(base_url="https://unit.test/api/v1", api_key="key") + pool = client.transport.http_client + client.agentstudio._sandbox = BrokenPreview() + with pytest.raises(RuntimeError, match="preview cleanup failed"): + client.close() + assert pool.is_closed + + +@pytest.mark.asyncio +async def test_async_root_owned_pool_closes_if_mounted_resource_cleanup_raises(): + from dashscope import AsyncClient + + class BrokenPreview: + async def aclose(self): + raise RuntimeError("preview cleanup failed") + + client = AsyncClient(base_url="https://unit.test/api/v1", api_key="key") + pool = client.transport.http_client + client.agentstudio._sandbox = BrokenPreview() + with pytest.raises(RuntimeError, match="preview cleanup failed"): + await client.aclose() + assert pool.is_closed + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "base_path", + [ + "", + "/api/v1", + "/compatible-mode/v1", + "/api/v1/agentstudio", + "/proxy", + "/proxy/api/v1", + "/proxy/compatible-mode/v1", + "/proxy/api/v1/agentstudio", + ], +) +def test_root_sandbox_mount_derives_exact_api_paths(asynchronous, base_path): + import asyncio + from dashscope import AsyncClient, Client + + calls = [] + + def handle(request): + calls.append(request.url.path) + return httpx.Response( + 200, + json=( + {"data": {"items": []}} + if request.url.path.endswith("/instances") + else [] + ), + ) + + prefix = "/proxy" if base_path.startswith("/proxy") else "" + expected = [ + prefix + "/api/v1/agentstudio/sandbox/v2/templates", + prefix + "/api/v1/agentstudio/agent-runtime/instances", + ] + if not asynchronous: + pool = httpx.Client(transport=httpx.MockTransport(handle)) + try: + with Client( + base_url="https://unit.test" + base_path, + api_key="key", + http_client=pool, + ) as client: + sandbox = client.agentstudio.sandbox + sandbox.templates.list() + sandbox.agents.list_instances() + assert calls == expected + assert not pool.is_closed + finally: + pool.close() + return + + async def run(): + pool = httpx.AsyncClient(transport=httpx.MockTransport(handle)) + try: + async with AsyncClient( + base_url="https://unit.test" + base_path, + api_key="key", + http_client=pool, + ) as client: + sandbox = client.agentstudio.sandbox + await sandbox.templates.list() + await sandbox.agents.list_instances() + assert calls == expected + assert not pool.is_closed + finally: + await pool.aclose() + + asyncio.run(run()) + + +@pytest.mark.parametrize("asynchronous", [False, True]) +def test_real_socket_response_body_read_timeout(asynchronous): + """A stalled response body must time out without issuing another request.""" + import asyncio + import threading + from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + from dashscope.applications.agentstudio.sandbox import AsyncSandboxClient + + requests = [] + release = threading.Event() + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + requests.append(self.path) + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", "2") + self.end_headers() + release.wait(2) + try: + self.wfile.write(b"[]") + except (BrokenPipeError, ConnectionResetError): + pass + + def log_message(self, *args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + server.daemon_threads = True + worker = threading.Thread( + target=lambda: server.serve_forever(poll_interval=0.01), daemon=True + ) + worker.start() + base_url = "http://127.0.0.1:" + str(server.server_port) + try: + if asynchronous: + + async def run(): + async with httpx.AsyncClient(trust_env=False) as pool: + async with AsyncSandboxClient( + base_url=base_url, + api_key="test-key", + timeout=0.1, + http_client=pool, + ) as client: + with pytest.raises(SandboxAPIError) as error: + await client.templates.list() + return error + + error = asyncio.run(run()) + else: + with httpx.Client(trust_env=False) as pool: + with SandboxClient( + base_url=base_url, api_key="test-key", timeout=0.1, http_client=pool + ) as client: + with pytest.raises(SandboxAPIError) as error: + client.templates.list() + assert error.value.code == "REQUEST_TIMEOUT" + assert not error.value.outcome_unknown + assert len(requests) == 1 + finally: + release.set() + server.shutdown() + server.server_close() + worker.join(timeout=2) diff --git a/tests/agentstudio_sandbox/test_resources.py b/tests/agentstudio_sandbox/test_resources.py new file mode 100644 index 00000000..f6ff6b3f --- /dev/null +++ b/tests/agentstudio_sandbox/test_resources.py @@ -0,0 +1,1028 @@ +"""Ordinary sandbox boundaries, template resolution, and file transfer behavior.""" + +import asyncio +import importlib +import json + +import httpx +import pytest + +PREFIX = "/api/v1/agentstudio/sandbox" +FILES = "/api/v1/agentstudio/files" + + +def modules(): + base = "dashscope.applications.agentstudio.sandbox." + return tuple( + importlib.import_module(base + name) + for name in ( + "models", + "transport", + "templates", + "sandboxes", + "template_files", + "exceptions", + ) + ) + + +def sync_transport(handler): + _, transport, *_ = modules() + return transport.Transport( + "https://platform.test", + "platform-key", + poll_interval=0.001, + http_client=httpx.Client(transport=httpx.MockTransport(handler)), + ) + + +def test_official_template_resolves_directory_before_create(): + models, _, templates, *_ = modules() + requests = [] + + def handler(request): + requests.append(request) + if request.method == "GET": + assert request.url.path == PREFIX + "/images/browser" + assert request.url.params["imageUrl"] == "registry/browser:1.2" + return httpx.Response( + 200, json={"imageName": "browser", "imageUrl": "registry/browser:1.2"} + ) + assert request.url.path == PREFIX + "/v3/templates" + assert json.loads(request.content) == { + "name": "browser-template", + "cpuCount": 2, + "memoryMB": 4096, + "fromImage": "registry/browser:1.2", + "imageName": "browser", + } + return httpx.Response( + 200, + json={ + "templateID": "t1", + "templateName": "browser-template", + "buildID": "b1", + }, + ) + + result = templates.TemplatesClient(sync_transport(handler)).create( + models.TemplateCreateRequest( + name="browser-template", + image=models.OfficialImage.BROWSER, + from_image="registry/browser:1.2", + cpu_count=2, + memory_mb=4096, + ) + ) + assert result.id == "t1" + assert len(requests) == 2 + + +def test_ambiguous_directory_failure_never_creates_template(): + models, _, templates, *_, errors = modules() + methods = [] + + def handler(request): + methods.append(request.method) + return httpx.Response( + 409, + json={ + "code": "IMAGE_VERSION_AMBIGUOUS", + "message": "Select exact image URL", + }, + ) + + with pytest.raises(errors.SandboxAPIError): + templates.TemplatesClient(sync_transport(handler)).create( + models.TemplateCreateRequest( + name="browser-template", + image=models.OfficialImage.BROWSER, + cpu_count=2, + memory_mb=4096, + ) + ) + assert methods == ["GET"] + + +def test_mismatched_directory_response_never_creates_template(): + models, _, templates, *_, errors = modules() + methods = [] + + def handler(request): + methods.append(request.method) + return httpx.Response( + 200, json={"imageName": "all-in-one", "imageUrl": "registry/other:1"} + ) + + with pytest.raises(errors.SandboxAPIError) as failure: + templates.TemplatesClient(sync_transport(handler)).create( + models.TemplateCreateRequest( + name="browser-template", + image=models.OfficialImage.BROWSER, + cpu_count=2, + memory_mb=4096, + ) + ) + assert failure.value.code == "INVALID_RESPONSE" + assert methods == ["GET"] + + +def test_template_crud_update_preserves_explicit_empty_fields(): + models, _, templates, *_ = modules() + observed = [] + + def handler(request): + observed.append((request.method, request.url.path, dict(request.url.params))) + if request.method == "PUT": + assert json.loads(request.content) == { + "description": "", + "envConfig": {}, + "mntConfig": [], + } + if request.url.path.endswith("/v2/templates"): + return httpx.Response( + 200, json=[{"templateID": "t1", "templateName": "one"}] + ) + if request.method == "DELETE": + return httpx.Response(204) + return httpx.Response(200, json={"templateID": "t1", "templateName": "one"}) + + client = templates.TemplatesClient(sync_transport(handler)) + assert client.list(limit=7, page_no=2)[0].id == "t1" + assert client.get("t1").id == "t1" + assert ( + client.update( + "t1", models.TemplateUpdateRequest(description="", env_config={}, mounts=[]) + ).id + == "t1" + ) + client.delete("t1") + assert observed == [ + ("GET", PREFIX + "/v2/templates", {"limit": "7", "pageNo": "2"}), + ("GET", PREFIX + "/templates/t1", {}), + ("PUT", PREFIX + "/templates/t1", {}), + ("DELETE", PREFIX + "/templates/t1", {}), + ] + + +@pytest.mark.parametrize("status", ["ERROR", "failed", "CANCELLED", "canceled"]) +def test_build_wait_stops_on_failure_preserving_reason(status): + _, _, templates, *_, errors = modules() + + def handler(request): + assert request.url.path == PREFIX + "/templates/t1/builds/b1/status" + return httpx.Response( + 200, + json={ + "templateID": "t1", + "buildID": "b1", + "status": status, + "reason": {"message": "image failed"}, + "logs": ["line"], + }, + ) + + with pytest.raises(errors.SandboxAPIError) as failure: + templates.TemplatesClient(sync_transport(handler)).wait_ready( + "t1", "b1", timeout=0.1 + ) + assert failure.value.code == "TEMPLATE_BUILD_FAILED" + assert failure.value.body["reason"] == {"message": "image failed"} + + +def test_build_wait_ready_and_total_deadline(): + _, _, templates, *_, errors = modules() + statuses = iter(["BUILDING", "ready"]) + + def handler(request): + return httpx.Response( + 200, json={"templateID": "t1", "buildID": "b1", "status": next(statuses)} + ) + + assert ( + templates.TemplatesClient(sync_transport(handler)) + .wait_ready("t1", "b1", timeout=1) + .status + == "ready" + ) + pending = sync_transport( + lambda request: httpx.Response( + 200, json={"templateID": "t1", "buildID": "b1", "status": "BUILDING"} + ) + ) + with pytest.raises(errors.SandboxWaitTimeoutError) as failure: + templates.TemplatesClient(pending).wait_ready("t1", "b1", timeout=0.005) + assert failure.value.resource_id == "t1" + assert failure.value.status == "BUILDING" + + +def test_sandbox_handles_follow_public_id_and_refresh_connection(): + models, _, _, sandboxes, *_ = modules() + observed = [] + + def handler(request): + body = json.loads(request.content) if request.content else None + observed.append( + (request.method, request.url.path, body, dict(request.url.params)) + ) + if request.url.path.endswith("/v2/sandboxes"): + return httpx.Response( + 200, json=[{"id": "database-id", "sandboxID": "s1", "templateID": "t1"}] + ) + if request.method == "DELETE" or request.url.path.endswith("/pause"): + return httpx.Response(204) + return httpx.Response( + 200, + json={ + "id": "database-id", + "sandboxID": "s1", + "templateID": "t1", + "envdUrl": "https://envd.test", + "envdAccessToken": "private-token", + }, + ) + + client = sandboxes.SandboxesClient(sync_transport(handler)) + handle = client.create(models.SandboxCreateRequest(template_id="t1", timeout=300)) + assert handle.id == "s1" + assert handle.sandbox_id == "s1" + assert handle.template_id == "t1" + assert handle.get().id == "s1" + assert handle.connection.envd_url == "https://envd.test" + assert handle.connect() is handle + handle.pause() + assert handle.resume(models.ConnectionOptions(timeout=600)) is handle + assert client.connect("s1").id == "s1" + assert client.resume("s1").id == "s1" + assert ( + client.list(template_id="t1", sandbox_id="s1", state="running", limit=7)[0].id + == "s1" + ) + handle.release() + assert ( + "POST", + PREFIX + "/sandboxes", + {"templateID": "t1", "timeout": 300}, + {}, + ) in observed + assert ("POST", PREFIX + "/sandboxes/s1/connect", {}, {}) in observed + assert ("POST", PREFIX + "/sandboxes/s1/resume", {"timeout": 600}, {}) in observed + assert ("POST", PREFIX + "/sandboxes/s1/resume", {}, {}) in observed + assert ( + "GET", + PREFIX + "/v2/sandboxes", + None, + {"templateID": "t1", "sandboxID": "s1", "state": "running", "limit": "7"}, + ) in observed + assert observed[-1][:2] == ("DELETE", PREFIX + "/sandboxes/s1") + + +@pytest.mark.parametrize("value", [0, -1, True, 1.25]) +def test_lifetime_requires_positive_whole_seconds(value): + models, *_ = modules() + with pytest.raises(ValueError): + models.ConnectionOptions(timeout=value) + with pytest.raises(ValueError): + models.SandboxCreateRequest(template_id="t1", timeout=value) + + +def test_template_file_upload_streaming_signed_and_complete(tmp_path): + models, _, _, _, files, _ = modules() + source = tmp_path / "100% ready.txt" + source.write_bytes(b"hello file") + observed = [] + + def handler(request): + observed.append(request) + if request.method == "POST" and request.headers.get( + "content-type", "" + ).startswith("multipart/"): + assert b'name="source"\r\n\r\nsandbox_template' in request.content + assert b'filename="100% ready.txt"' in request.content + assert b"hello file" in request.content + return httpx.Response( + 200, json={"id": "f1", "filename": source.name, "status": "checking"} + ) + if request.url.path.endswith("/complete"): + assert not request.content + return httpx.Response(200, json={"id": "f1", "status": "checking"}) + if request.method == "POST": + assert json.loads(request.content) == { + "filename": source.name, + "size_bytes": 10, + "source": "sandbox_template", + } + return httpx.Response( + 200, + json={ + "id": "f1", + "status": "uploading", + "upload_url": "https://storage.test/upload?signature=private", + }, + ) + return httpx.Response(200, json={"id": "f1", "status": "available"}) + + client = files.TemplateFilesClient(sync_transport(handler)) + assert client.upload(source).status == "checking" + ticket = client.prepare_upload( + models.UploadRequest(filename=source.name, size_bytes=10) + ) + assert client.complete(ticket.id).status == "checking" + assert client.get("f1").status == "available" + assert client.wait_available("f1", timeout=1).status == "available" + client.delete("f1") + assert observed[-1].method == "DELETE" + assert observed[-1].url.path == FILES + "/f1" + + +def test_signed_upload_does_not_send_platform_credentials_or_follow_redirects(tmp_path): + models, transport, _, _, files, errors = modules() + source = tmp_path / "file.txt" + source.write_bytes(b"content") + observed = [] + + def handler(request): + observed.append(request) + assert request.headers.get("authorization") is None + assert request.headers.get("cookie") is None + assert request.content == b"content" + return httpx.Response(307, headers={"Location": "https://other.test/leak"}) + + pool = httpx.Client( + transport=httpx.MockTransport(handler), + headers={"Authorization": "Bearer platform-key"}, + cookies={"session": "private"}, + follow_redirects=True, + ) + client = files.TemplateFilesClient( + transport.Transport("https://platform.test", "platform-key", http_client=pool) + ) + with pytest.raises(errors.SandboxAPIError): + client.upload_content( + models.UploadTicket( + id="f1", + status="uploading", + upload_url="https://storage.test/upload?signature=private", + ), + source, + ) + assert len(observed) == 1 + + +def test_download_replaces_atomically_and_preserves_target_on_stream_error(tmp_path): + _, _, _, _, files, _ = modules() + target = tmp_path / "result.bin" + target.write_bytes(b"old") + + class BrokenStream(httpx.SyncByteStream): + def __iter__(self): + yield b"partial" + raise httpx.ReadError("interrupted") + + client = files.TemplateFilesClient( + sync_transport(lambda request: httpx.Response(200, stream=BrokenStream())) + ) + with pytest.raises(Exception): + client.download("f1", target) + assert target.read_bytes() == b"old" + assert list(tmp_path.iterdir()) == [target] + client = files.TemplateFilesClient( + sync_transport(lambda request: httpx.Response(200, content=b"new\x00bytes")) + ) + assert client.download("f1", target) == target + assert target.read_bytes() == b"new\x00bytes" + + +@pytest.mark.parametrize("status", ["rejected", "type_rejected", "failed", "deleted"]) +def test_file_wait_stops_on_terminal_status(status): + _, _, _, _, files, errors = modules() + client = files.TemplateFilesClient( + sync_transport( + lambda request: httpx.Response(200, json={"id": "f1", "status": status}) + ) + ) + with pytest.raises(errors.SandboxAPIError) as failure: + client.wait_available("f1", timeout=0.1) + assert failure.value.code == "FILE_" + status.upper() + + +def test_async_resource_routes_polling_and_streamed_upload_download(tmp_path): + models, transport, templates, sandboxes, files, _ = modules() + source = tmp_path / "source.txt" + source.write_bytes(b"async payload") + target = tmp_path / "target.txt" + observed = [] + + async def handler(request): + observed.append((request.method, request.url.path, await request.aread())) + if request.url.path.endswith("/images/browser"): + return httpx.Response( + 200, json={"imageName": "browser", "imageUrl": "registry/browser:2"} + ) + if request.url.path.endswith("/v3/templates"): + return httpx.Response( + 200, json={"templateID": "t1", "templateName": "one", "buildID": "b1"} + ) + if request.url.path.endswith("/v2/templates"): + return httpx.Response( + 200, json=[{"templateID": "t1", "templateName": "one"}] + ) + if "/builds/" in request.url.path: + return httpx.Response( + 200, json={"templateID": "t1", "buildID": "b1", "status": "READY"} + ) + if "/templates/" in request.url.path: + return httpx.Response(200, json={"templateID": "t1", "templateName": "one"}) + if request.url.path.endswith("/v2/sandboxes"): + return httpx.Response(200, json=[{"sandboxID": "s1", "templateID": "t1"}]) + if "/sandboxes" in request.url.path: + return httpx.Response(200, json={"sandboxID": "s1", "templateID": "t1"}) + if request.url.path.endswith("/content"): + return httpx.Response(200, content=b"download") + if request.method == "POST" and request.headers.get( + "content-type", "" + ).startswith("multipart/"): + assert b"async payload" in await request.aread() + return httpx.Response( + 200, + json={ + "id": "f1", + "status": "available", + "upload_url": "https://storage.test/file", + }, + ) + + async def run(): + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as pool: + http = transport.AsyncTransport( + "https://platform.test", "platform-key", http_client=pool + ) + template_client = templates.AsyncTemplatesClient(http) + assert ( + await template_client.create( + models.TemplateCreateRequest( + name="one", + image=models.OfficialImage.BROWSER, + cpu_count=2, + memory_mb=4096, + ) + ) + ).id == "t1" + assert (await template_client.list())[0].id == "t1" + assert (await template_client.get("t1")).id == "t1" + await template_client.update( + "t1", models.TemplateUpdateRequest(description="") + ) + assert (await template_client.build_status("t1", "b1")).ready + assert (await template_client.wait_ready("t1", "b1", timeout=1)).ready + await template_client.delete("t1") + sandbox_client = sandboxes.AsyncSandboxesClient(http) + handle = await sandbox_client.create( + models.SandboxCreateRequest(template_id="t1") + ) + assert handle.sandbox_id == "s1" + assert (await handle.get()).id == "s1" + assert await handle.connect() is handle + await handle.pause() + assert await handle.resume() is handle + assert (await sandbox_client.list())[0].id == "s1" + await handle.release() + file_client = files.AsyncTemplateFilesClient(http) + assert (await file_client.upload(source)).id == "f1" + assert (await file_client.get("f1")).id == "f1" + assert ( + await file_client.wait_available("f1", timeout=1) + ).status == "available" + ticket = await file_client.prepare_upload( + models.UploadRequest(filename="source.txt") + ) + await file_client.upload_content(ticket, source) + await file_client.complete("f1") + assert await file_client.download("f1", target) == target + await file_client.delete("f1") + assert target.read_bytes() == b"download" + connects = [ + body for method, path, body in observed if path.endswith("/connect") + ] + assert connects == [b"{}"] + + asyncio.run(run()) + + +@pytest.mark.parametrize("facet_name", ["TemplatesClient", "SandboxesClient"]) +def test_list_rejects_malformed_platform_object(facet_name): + _, _, templates, sandboxes, _, errors = modules() + client_type = getattr( + templates if facet_name == "TemplatesClient" else sandboxes, facet_name + ) + client = client_type( + sync_transport(lambda request: httpx.Response(200, json={"items": []})) + ) + with pytest.raises(errors.SandboxAPIError) as failure: + client.list() + assert failure.value.code == "INVALID_RESPONSE" + + +@pytest.mark.parametrize("bad_id", ["", "..", "s/other", "s?query", "s\x00"]) +def test_invalid_resource_id_is_rejected_before_request(bad_id): + _, _, templates, sandboxes, files, _ = modules() + + def handler(request): + raise AssertionError("invalid resource ID reached the network") + + transport = sync_transport(handler) + for client in ( + templates.TemplatesClient(transport), + sandboxes.SandboxesClient(transport), + files.TemplateFilesClient(transport), + ): + with pytest.raises(ValueError): + client.get(bad_id) + + +def test_file_wait_timeout_preserves_last_status_and_missing_file_is_io_error(tmp_path): + _, _, _, _, files, errors = modules() + client = files.TemplateFilesClient( + sync_transport( + lambda request: httpx.Response(200, json={"id": "f1", "status": "checking"}) + ) + ) + with pytest.raises(errors.SandboxWaitTimeoutError) as failure: + client.wait_available("f1", timeout=0.005) + assert failure.value.resource_id == "f1" + assert failure.value.status == "checking" + with pytest.raises(errors.SandboxAPIError) as failure: + client.upload(tmp_path / "missing.txt") + assert failure.value.code == "FILE_IO_ERROR" + + +def test_download_http_failure_preserves_target_and_removes_partial_file(tmp_path): + _, _, _, _, files, errors = modules() + target = tmp_path / "target.txt" + target.write_bytes(b"old contents") + client = files.TemplateFilesClient( + sync_transport( + lambda request: httpx.Response( + 403, json={"code": "AccessDenied", "message": "Denied"} + ) + ) + ) + with pytest.raises(errors.SandboxAPIError): + client.download("f1", target) + assert target.read_bytes() == b"old contents" + assert list(tmp_path.iterdir()) == [target] + + +def test_async_download_cancellation_closes_response_and_preserves_target(tmp_path): + _, transport, _, _, files, _ = modules() + target = tmp_path / "target.txt" + target.write_bytes(b"old") + closed = [] + + class CancelledStream(httpx.AsyncByteStream): + async def __aiter__(self): + yield b"partial" + raise asyncio.CancelledError() + + async def aclose(self): + closed.append(True) + + async def run(): + async with httpx.AsyncClient( + transport=httpx.MockTransport( + lambda request: httpx.Response(200, stream=CancelledStream()) + ) + ) as pool: + client = files.AsyncTemplateFilesClient( + transport.AsyncTransport( + "https://platform.test", "platform-key", http_client=pool + ) + ) + with pytest.raises(asyncio.CancelledError): + await client.download("f1", target) + assert closed == [True] + assert target.read_bytes() == b"old" + assert list(tmp_path.iterdir()) == [target] + + asyncio.run(run()) + + +@pytest.mark.parametrize("kind", ["build", "file"]) +def test_polling_rejects_ready_response_after_total_deadline(kind): + import time + + _, _, templates, _, files, errors = modules() + + def handler(request): + time.sleep(0.02) + if kind == "build": + return httpx.Response( + 200, json={"templateID": "t1", "buildID": "b1", "status": "READY"} + ) + return httpx.Response(200, json={"id": "f1", "status": "available"}) + + http = sync_transport(handler) + with pytest.raises(errors.SandboxWaitTimeoutError): + if kind == "build": + templates.TemplatesClient(http).wait_ready("t1", "b1", timeout=0.005) + else: + files.TemplateFilesClient(http).wait_available("f1", timeout=0.005) + + +@pytest.mark.parametrize("kind", ["build", "file"]) +def test_async_polling_rejects_ready_response_after_total_deadline(kind): + _, transport, templates, _, files, errors = modules() + + async def handler(request): + await asyncio.sleep(0.02) + if kind == "build": + return httpx.Response( + 200, json={"templateID": "t1", "buildID": "b1", "status": "READY"} + ) + return httpx.Response(200, json={"id": "f1", "status": "available"}) + + async def run(): + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as pool: + http = transport.AsyncTransport( + "https://platform.test", "platform-key", http_client=pool + ) + with pytest.raises(errors.SandboxWaitTimeoutError): + if kind == "build": + await templates.AsyncTemplatesClient(http).wait_ready( + "t1", "b1", timeout=0.005 + ) + else: + await files.AsyncTemplateFilesClient(http).wait_available( + "f1", timeout=0.005 + ) + + asyncio.run(run()) + + +def _call_template_resource(handler, asynchronous, method, *args): + _, transport, templates, *_ = modules() + if not asynchronous: + return getattr(templates.TemplatesClient(sync_transport(handler)), method)(*args) + + async def run(): + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as pool: + client = templates.AsyncTemplatesClient( + transport.AsyncTransport( + "https://platform.test", "platform-key", http_client=pool + ) + ) + return await getattr(client, method)(*args) + + return asyncio.run(run()) + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("custom_name", [None, "my-template-image"]) +@pytest.mark.parametrize( + "image_name,harness_type", + [ + ("code-interpreter-v1", None), + ("browser", None), + ("all-in-one", None), + ("deepseek-harness", "dsh"), + ("openclaw", "openclaw"), + ], +) +def test_five_enum_template_bodies_preserve_catalog_and_reusable_request( + asynchronous, custom_name, image_name, harness_type +): + models, *_ = modules() + observed = [] + exact_url = "registry.test/" + image_name + ":version-1" + + def handler(request): + observed.append((request.method, request.url.path)) + if request.method == "GET": + assert request.url.path == PREFIX + "/images/" + image_name + assert request.url.params["imageUrl"] == exact_url + return httpx.Response( + 200, json={"imageName": image_name, "imageUrl": exact_url} + ) + body = json.loads(request.content) + expected = { + "name": "typed-template", + "cpuCount": 2, + "memoryMB": 4096, + "fromImage": exact_url, + "imageName": custom_name or image_name, + } + if harness_type: + expected.update(harnessType=harness_type, imageType="MANAGED") + assert body == expected + return httpx.Response(200, json={"templateID": "t1"}) + + request = models.TemplateCreateRequest( + name="typed-template", + image=models.OfficialImage(image_name), + from_image=exact_url, + image_name=custom_name, + cpu_count=2, + memory_mb=4096, + ) + original = request.to_dict() + for _ in range(2): + assert _call_template_resource(handler, asynchronous, "create", request).id == "t1" + assert request.to_dict() == original + assert observed == [ + ("GET", PREFIX + "/images/" + image_name), + ("POST", PREFIX + "/v3/templates"), + ] * 2 + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "image_name,harness_type", + [ + ("deepseek-harness", "openclaw"), + ("openclaw", "dsh"), + ("deepseek-harness", "codex"), + ("code-interpreter-v1", "dsh"), + ("browser", "openclaw"), + ("all-in-one", "hermes"), + ], +) +def test_template_enum_conflicts_fail_before_any_http( + asynchronous, image_name, harness_type +): + models, *_ = modules() + observed = [] + + def handler(request): + observed.append(request.method) + return httpx.Response(500) + + with pytest.raises(ValueError, match="harness_type.*image"): + request = models.TemplateCreateRequest( + name="conflict", + image=models.OfficialImage(image_name), + harness_type=harness_type, + cpu_count=2, + memory_mb=4096, + ) + _call_template_resource(handler, asynchronous, "create", request) + assert observed == [] + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("harness_type", ["dsh", "openclaw", "codex", "hermes"]) +def test_raw_template_explicit_harness_uses_one_post(asynchronous, harness_type): + models, *_ = modules() + observed = [] + + def handler(request): + observed.append(request.method) + assert request.url.path == PREFIX + "/v3/templates" + assert json.loads(request.content) == { + "name": "raw-template", + "cpuCount": 2, + "memoryMB": 4096, + "fromImage": "registry.test/raw:version-1", + "harnessType": harness_type, + } + return httpx.Response(200, json={"templateID": "t1"}) + + request = models.TemplateCreateRequest( + name="raw-template", + from_image="registry.test/raw:version-1", + harnessType=harness_type, + cpu_count=2, + memory_mb=4096, + ) + assert _call_template_resource(handler, asynchronous, "create", request).id == "t1" + assert observed == ["POST"] + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("harness_type", ["dsh", "openclaw", "codex", "hermes"]) +def test_template_update_harness_is_explicit_single_put(asynchronous, harness_type): + models, *_ = modules() + observed = [] + + def handler(request): + observed.append(request.method) + assert request.url.path == PREFIX + "/templates/t1" + assert json.loads(request.content) == { + "harnessType": harness_type, + "fromImage": "registry.test/raw:version-1", + "description": "", + } + return httpx.Response(200, json={"templateID": "t1", "imageType": "MANAGED"}) + + request = models.TemplateUpdateRequest( + harness_type=harness_type, + from_image="registry.test/raw:version-1", + description="", + ) + result = _call_template_resource(handler, asynchronous, "update", "t1", request) + assert result.image_type == "MANAGED" + assert observed == ["PUT"] + + +@pytest.mark.parametrize("request_type", ["TemplateCreateRequest", "TemplateUpdateRequest"]) +@pytest.mark.parametrize("harness_type", ["deepseek-harness", "unknown"]) +def test_template_harness_rejects_non_template_literal(request_type, harness_type): + from pydantic import ValidationError + + models, *_ = modules() + fields = {"harness_type": harness_type} + if request_type == "TemplateCreateRequest": + fields.update(name="one", cpu_count=2, memory_mb=4096) + with pytest.raises(ValidationError) as failure: + getattr(models, request_type)(**fields) + assert failure.value.errors()[0]["type"] == "literal_error" + + +@pytest.mark.parametrize( + "fields,expected", + [ + ({}, None), + ({"imageType": None}, None), + ({"imageType": "MANAGED"}, "MANAGED"), + ({"imageType": "BASE"}, "BASE"), + ], +) +def test_template_image_type_metadata_accepts_new_and_legacy_responses(fields, expected): + models, *_ = modules() + result = models.TemplateInfo.from_dict(dict(templateID="t1", **fields)) + assert result.image_type == expected + assert "harness_type" not in models.TemplateInfo.model_fields + + +@pytest.mark.parametrize("asynchronous", [False, True]) +def test_harness_enum_keeps_explicit_lifecycle_for_platform_validation(asynchronous): + models, *_ = modules() + observed = [] + + def handler(request): + observed.append(request.method) + if request.method == "GET": + return httpx.Response( + 200, + json={"imageName": "deepseek-harness", "imageUrl": "registry.test/dsh:1"}, + ) + body = json.loads(request.content) + assert body["harnessType"] == "dsh" + assert body["imageType"] == "MANAGED" + assert body["autoPauseTime"] == 300 + assert body["maxRunningTimeout"] == 900 + return httpx.Response(200, json={"templateID": "t1"}) + + request = models.TemplateCreateRequest( + name="explicit-lifecycle", + image=models.OfficialImage.DEEPSEEK_HARNESS, + cpu_count=2, + memory_mb=4096, + auto_pause_time=300, + max_running_timeout=900, + ) + _call_template_resource(handler, asynchronous, "create", request) + assert observed == ["GET", "POST"] + + +@pytest.mark.parametrize("image_name", ["deepseek-harness", "openclaw"]) +def test_agent_launch_keeps_snake_protocol_and_full_runtime_budget(image_name): + models, *_ = modules() + request = models.LaunchRequest( + image=models.OfficialImage(image_name), runtime_budget_seconds=172800 + ) + assert request.to_dict() == { + "harness_type": image_name, + "image_name": image_name, + "runtime_budget_seconds": 172800, + } + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("model_field", ["model_config", "modelConfig"]) +@pytest.mark.parametrize("image_name", ["deepseek-harness", "openclaw"]) +def test_template_model_uses_console_fields_without_changing_agent_protocol( + asynchronous, model_field, image_name +): + models, *_ = modules() + bodies = [] + + def handler(request): + if request.method == "GET": + return httpx.Response( + 200, + json={ + "imageName": image_name, + "imageUrl": "registry.test/" + image_name + ":1", + }, + ) + assert request.headers["Authorization"] == "Bearer platform-key" + assert request.url.path == PREFIX + "/v3/templates" + bodies.append(json.loads(request.content)) + return httpx.Response(202, json={"templateID": "model-template"}) + + model = models.ModelConfig( + base_url="https://models.example/custom/api", + model_id="qwen3.7-plus", + api_key="private-template-model-key", + ) + request = models.TemplateCreateRequest( + name="configured-template", + image=models.OfficialImage(image_name), + cpu_count=2, + memory_mb=4096, + **{model_field: model}, + ) + original = request.to_dict() + result = _call_template_resource(handler, asynchronous, "create", request) + assert result.id == "model-template" + assert bodies[0]["modelConfig"] == { + "modelName": "qwen3.7-plus", + "baseUrl": "https://models.example/custom/api", + "apiKey": "private-template-model-key", + } + assert "model_config" not in bodies[0] + assert "private-template-model-key" not in repr(request) + assert request.to_dict() == original + assert model.to_dict() == { + "base_url": "https://models.example/custom/api", + "model_id": "qwen3.7-plus", + "api_key": "private-template-model-key", + } + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("model_key", [None, "", " "]) +def test_raw_template_model_defaults_id_and_keeps_key_unconfigured( + asynchronous, model_key +): + models, *_ = modules() + bodies = [] + + def handler(request): + assert request.method == "POST" + bodies.append(json.loads(request.content)) + return httpx.Response(202, json={"templateID": "model-template"}) + + request = models.TemplateCreateRequest( + name="keyless-template", + from_image="registry.test/deepseek-harness:1", + harness_type="dsh", + cpu_count=2, + memory_mb=4096, + model_config=models.ModelConfig( + base_url="https://models.example/custom/api", api_key=model_key + ), + ) + result = _call_template_resource(handler, asynchronous, "create", request) + assert result.id == "model-template" + assert bodies[0]["modelConfig"] == { + "modelName": "qwen3.7-plus", + "baseUrl": "https://models.example/custom/api", + } + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("model", ["omitted", "none", "empty"]) +def test_template_without_model_preserves_image_defaults(asynchronous, model): + models, *_ = modules() + bodies = [] + + def handler(request): + bodies.append(json.loads(request.content)) + return httpx.Response(202, json={"templateID": "default-template"}) + + fields = {} + if model != "omitted": + fields["model_config"] = models.ModelConfig() if model == "empty" else None + request = models.TemplateCreateRequest( + name="image-defaults", + from_image="registry.test/deepseek-harness:1", + harness_type="dsh", + cpu_count=2, + memory_mb=4096, + **fields, + ) + result = _call_template_resource(handler, asynchronous, "create", request) + assert result.id == "default-template" + assert bodies == [ + { + "name": "image-defaults", + "fromImage": "registry.test/deepseek-harness:1", + "harnessType": "dsh", + "cpuCount": 2, + "memoryMB": 4096, + } + ] + + +@pytest.mark.parametrize("request_type", ["TemplateCreateRequest", "TemplateUpdateRequest"]) +@pytest.mark.parametrize("field", ["auto_pause_time", "max_running_timeout"]) +def test_template_duration_validation_names_the_supplied_field(request_type, field): + models, *_ = modules() + values = {field: 0} + if request_type == "TemplateCreateRequest": + values.update(name="template", cpu_count=2, memory_mb=4096) + with pytest.raises(ValueError) as failure: + getattr(models, request_type)(**values) + assert field in failure.value.errors()[0]["msg"] + assert "lifetime" not in failure.value.errors()[0]["msg"] diff --git a/tests/agentstudio_sandbox/test_stream.py b/tests/agentstudio_sandbox/test_stream.py new file mode 100644 index 00000000..3c2b9359 --- /dev/null +++ b/tests/agentstudio_sandbox/test_stream.py @@ -0,0 +1,487 @@ +"""SSE framing, replay, lifetime, and callback tests without external traffic.""" + +import asyncio +import json +import threading + +import httpx +import pytest + +from dashscope.applications.agentstudio.sandbox.agents import ( + AgentsClient, + AsyncAgentsClient, +) +from dashscope.applications.agentstudio.sandbox.exceptions import SandboxAPIError +from dashscope.applications.agentstudio.sandbox.transport import ( + AsyncTransport, + Transport, +) + + +def event(sequence, kind="message.delta", turn="at_one", **extra): + return {"turn_id": turn, "sequence": sequence, "type": kind, **extra} + + +def frame(value, with_id=True): + identifier = ( + "id: {}:{}\n".format(value["turn_id"], value["sequence"]) if with_id else "" + ) + return ( + identifier + "event: " + value["type"] + "\ndata: " + json.dumps(value) + "\n\n" + ).encode() + + +class Stream(httpx.SyncByteStream): + def __init__(self, chunks): + self.chunks = chunks + self.closed = False + + def __iter__(self): + yield from self.chunks + + def close(self): + self.closed = True + + +class AsyncStream(httpx.AsyncByteStream): + def __init__(self, chunks): + self.chunks = chunks + self.closed = False + + async def __aiter__(self): + for chunk in self.chunks: + await asyncio.sleep(0) + yield chunk + + async def aclose(self): + self.closed = True + + +def test_sync_iteration_replay_cursor_multiline_terminal_and_borrowed_pool(): + seen = [] + multiline = ( + b'data: {"turn_id":"at_one",\ndata: "sequence":3,"type":"message.delta"}\n\n' + ) + source = Stream( + [ + b": keepalive\n\n", + frame(event(2)), + multiline[:14], + multiline[14:], + frame(event(4, "turn.completed")), + frame(event(5)), + ] + ) + + def handler(request): + seen.append(request) + if request.url.path.endswith("/events"): + return httpx.Response( + 200, + headers={"Content-Type": "text/event-stream; charset=utf-8"}, + stream=source, + ) + return httpx.Response(200, json={"data": {}}) + + pool = httpx.Client(transport=httpx.MockTransport(handler)) + transport = Transport("https://unit.test", "platform-key", http_client=pool) + try: + with AgentsClient(transport).turn("at_one").subscribe( + after_sequence=2 + ) as subscription: + received = list(subscription) + assert [item["sequence"] for item in received] == [3, 4] + assert subscription.last_sequence == 4 + assert seen[0].headers["Last-Event-ID"] == "at_one:2" + assert seen[0].url.params["after_seq"] == "2" + assert source.closed + assert len(seen) == 1 and seen[0].method == "GET" + transport.close() + assert pool.get("https://unit.test/alive").status_code == 200 + finally: + transport.close() + pool.close() + + +@pytest.mark.parametrize( + "chunks", + [ + [frame(event(2))], + [frame(event(1, turn="at_wrong"))], + [b"data: not-json\n\n"], + [b'data: {"turn_id":"at_one","sequence":true,"type":"turn.started"}\n\n'], + [frame(event(1))[:-1]], + [ + b'id: at_one:99\ndata: {"turn_id":"at_one","sequence":1,"type":"turn.started"}\n\n' + ], + ], +) +def test_sync_invalid_events_fail_close_and_do_not_retry(chunks): + seen = [] + source = Stream(chunks) + + def handler(request): + seen.append(request) + return httpx.Response( + 200, headers={"Content-Type": "text/event-stream"}, stream=source + ) + + pool = httpx.Client(transport=httpx.MockTransport(handler)) + transport = Transport("https://unit.test", "platform-key", http_client=pool) + try: + with pytest.raises(SandboxAPIError) as error: + with AgentsClient(transport).turn("at_one").subscribe() as subscription: + list(subscription) + assert error.value.code == "INVALID_RESPONSE" + assert source.closed and len(seen) == 1 + assert "Last-Event-ID" not in seen[0].headers + finally: + transport.close() + pool.close() + + +def test_sync_callback_uses_one_reader_and_propagates_handler_failure(): + source = Stream([frame(event(1)), frame(event(2, "turn.completed"))]) + pool = httpx.Client( + transport=httpx.MockTransport( + lambda request: httpx.Response( + 200, headers={"Content-Type": "text/event-stream"}, stream=source + ) + ) + ) + transport = Transport("https://unit.test", "platform-key", http_client=pool) + threads = [] + received = [] + + def callback(item): + threads.append(threading.current_thread().ident) + received.append(item["sequence"]) + + try: + subscription = AgentsClient(transport).turn("at_one").subscribe(callback) + subscription.wait(2) + assert received == [1, 2] + assert len(set(threads)) == 1 + assert threads[0] != threading.current_thread().ident + assert source.closed and subscription.last_sequence == 2 + finally: + transport.close() + pool.close() + + pool = httpx.Client( + transport=httpx.MockTransport( + lambda request: httpx.Response( + 200, + headers={"Content-Type": "text/event-stream"}, + stream=Stream([frame(event(1))]), + ) + ) + ) + transport = Transport("https://unit.test", "platform-key", http_client=pool) + + def failure(item): + raise RuntimeError("callback failed") + + try: + subscription = AgentsClient(transport).turn("at_one").subscribe(failure) + with pytest.raises(RuntimeError, match="callback failed"): + subscription.wait(2) + assert subscription.last_sequence == 1 + finally: + transport.close() + pool.close() + + +def test_sync_sdk_close_disconnects_without_remote_cancel_and_invalid_media_closes(): + source = Stream([frame(event(1))]) + seen = [] + + def handler(request): + seen.append(request) + return httpx.Response( + 200, headers={"Content-Type": "text/event-stream"}, stream=source + ) + + pool = httpx.Client(transport=httpx.MockTransport(handler)) + transport = Transport("https://unit.test", "platform-key", http_client=pool) + try: + subscription = AgentsClient(transport).turn("at_one").subscribe() + subscription.__enter__() + transport.close() + assert source.closed + assert len(seen) == 1 and seen[0].method == "GET" + finally: + transport.close() + pool.close() + + source = Stream([b"{}"]) + pool = httpx.Client( + transport=httpx.MockTransport( + lambda request: httpx.Response( + 200, headers={"Content-Type": "application/json"}, stream=source + ) + ) + ) + transport = Transport("https://unit.test", "platform-key", http_client=pool) + try: + with pytest.raises(SandboxAPIError, match="text/event-stream"): + with AgentsClient(transport).turn("at_one").subscribe(): + pass + assert source.closed + finally: + transport.close() + pool.close() + + +def test_async_iteration_and_ordered_awaitable_callback(): + async def run(): + sources = [] + seen = [] + + async def handler(request): + seen.append(request) + source = AsyncStream([frame(event(1)), frame(event(2, "turn.completed"))]) + sources.append(source) + return httpx.Response( + 200, headers={"Content-Type": "text/event-stream"}, stream=source + ) + + pool = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + transport = AsyncTransport( + "https://unit.test", "platform-key", http_client=pool + ) + try: + turn = AsyncAgentsClient(transport).turn("at_one") + async with turn.subscribe() as subscription: + received = [item["sequence"] async for item in subscription] + assert received == [1, 2] and subscription.last_sequence == 2 + assert sources[0].closed + callback_items = [] + tasks = [] + + async def callback(item): + await asyncio.sleep(0) + tasks.append(asyncio.current_task()) + callback_items.append(item["sequence"]) + + subscription = turn.subscribe(callback) + await subscription.wait(2) + assert callback_items == [1, 2] and len(set(tasks)) == 1 + assert sources[1].closed + assert all(request.method == "GET" for request in seen) + finally: + await transport.aclose() + await pool.aclose() + + asyncio.run(run()) + + +def test_async_cancelled_reader_closes_http_subscription_only(): + async def run(): + waiting = asyncio.Event() + source_closed = asyncio.Event() + seen = [] + + class BlockingStream(httpx.AsyncByteStream): + async def __aiter__(self): + yield frame(event(1)) + waiting.set() + await asyncio.Event().wait() + + async def aclose(self): + source_closed.set() + + async def handler(request): + seen.append(request) + return httpx.Response( + 200, + headers={"Content-Type": "text/event-stream"}, + stream=BlockingStream(), + ) + + pool = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + transport = AsyncTransport( + "https://unit.test", "platform-key", http_client=pool + ) + try: + subscription = ( + AsyncAgentsClient(transport) + .turn("at_one") + .subscribe(lambda event: None) + ) + await asyncio.wait_for(waiting.wait(), 2) + await subscription.aclose() + assert source_closed.is_set() + assert subscription.last_sequence == 1 + assert len(seen) == 1 and seen[0].method == "GET" + finally: + await transport.aclose() + await pool.aclose() + + asyncio.run(run()) + + +@pytest.mark.parametrize("mode", ["iterator", "callback"]) +@pytest.mark.parametrize("status", [401, 404, 200]) +def test_sync_sse_startup_failure_is_not_reported_as_empty_success(mode, status): + code = "UNAUTHORIZED" if status == 401 else "NOT_FOUND" + source = Stream([json.dumps({"error": {"code": code}}).encode()]) + requests = [] + + def handler(request): + requests.append(request) + return httpx.Response( + status, headers={"Content-Type": "application/json"}, stream=source + ) + + pool = httpx.Client(transport=httpx.MockTransport(handler)) + transport = Transport("https://unit.test", "platform-key", http_client=pool) + try: + subscription = ( + AgentsClient(transport) + .turn("at_one") + .subscribe((lambda item: None) if mode == "callback" else None) + ) + with pytest.raises(SandboxAPIError) as failure: + if mode == "callback": + subscription.wait(2) + else: + list(subscription) + assert failure.value.code == ("INVALID_RESPONSE" if status == 200 else code) + assert source.closed + assert len(requests) == 1 and requests[0].method == "GET" + assert not transport._subscriptions + finally: + transport.close() + pool.close() + + +@pytest.mark.parametrize("mode", ["iterator", "callback"]) +@pytest.mark.parametrize("status", [401, 404, 200]) +def test_async_sse_startup_failure_propagates_and_closes(mode, status): + async def run(): + code = "UNAUTHORIZED" if status == 401 else "NOT_FOUND" + source = AsyncStream([json.dumps({"error": {"code": code}}).encode()]) + requests = [] + + async def handler(request): + requests.append(request) + return httpx.Response( + status, headers={"Content-Type": "application/json"}, stream=source + ) + + pool = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + transport = AsyncTransport( + "https://unit.test", "platform-key", http_client=pool + ) + try: + subscription = ( + AsyncAgentsClient(transport) + .turn("at_one") + .subscribe((lambda item: None) if mode == "callback" else None) + ) + with pytest.raises(SandboxAPIError) as failure: + if mode == "callback": + await subscription.wait(2) + else: + _ = [item async for item in subscription] + assert failure.value.code == ("INVALID_RESPONSE" if status == 200 else code) + assert source.closed + assert len(requests) == 1 and requests[0].method == "GET" + assert not transport._subscriptions + finally: + await transport.aclose() + await pool.aclose() + + asyncio.run(run()) + + +def test_sync_external_close_unblocks_callback_reader_without_reporting_failure(): + reading = threading.Event() + closed = threading.Event() + requests = [] + + class InterruptedStream(httpx.SyncByteStream): + def __iter__(self): + yield frame(event(1)) + reading.set() + closed.wait(2) + raise httpx.ReadError("reader interrupted by local close") + + def close(self): + closed.set() + + def handler(request): + requests.append(request) + return httpx.Response( + 200, + headers={"Content-Type": "text/event-stream"}, + stream=InterruptedStream(), + ) + + pool = httpx.Client(transport=httpx.MockTransport(handler)) + transport = Transport("https://unit.test", "platform-key", http_client=pool) + try: + subscription = ( + AgentsClient(transport).turn("at_one").subscribe(lambda item: None) + ) + assert reading.wait(2) + subscription.close() + subscription.wait(2) + assert closed.is_set() + assert len(requests) == 1 and requests[0].method == "GET" + assert subscription.last_sequence == 1 + finally: + closed.set() + transport.close() + pool.close() + + +@pytest.mark.parametrize("asynchronous", [False, True]) +def test_expired_event_cursor_is_not_retried_or_reset(asynchronous): + """410 must reach the caller; starting from zero could duplicate a Turn.""" + seen = [] + + def reply(request): + seen.append(request) + return httpx.Response( + 410, + headers={"x-request-id": "expired-cursor-request"}, + json={"error": {"code": "EVENTS_EXPIRED", "message": "Events expired"}}, + ) + + if not asynchronous: + with httpx.Client(transport=httpx.MockTransport(reply)) as pool: + transport = Transport("https://unit.test", "platform-key", http_client=pool) + try: + with pytest.raises(SandboxAPIError) as error: + with AgentsClient(transport).turn("at_one").subscribe( + after_sequence=9 + ) as events: + list(events) + finally: + transport.close() + else: + + async def run(): + async with httpx.AsyncClient(transport=httpx.MockTransport(reply)) as pool: + transport = AsyncTransport( + "https://unit.test", "platform-key", http_client=pool + ) + try: + with pytest.raises(SandboxAPIError) as error: + async with AsyncAgentsClient(transport).turn( + "at_one" + ).subscribe(after_sequence=9) as events: + [event async for event in events] + return error + finally: + await transport.aclose() + + error = asyncio.run(run()) + assert error.value.status_code == 410 + assert error.value.code == "EVENTS_EXPIRED" + assert error.value.request_id == "expired-cursor-request" + assert len(seen) == 1 + assert seen[0].url.params["after_seq"] == "9" + assert seen[0].headers["Last-Event-ID"] == "at_one:9" diff --git a/tests/agentstudio_sandbox/test_web_ui.py b/tests/agentstudio_sandbox/test_web_ui.py new file mode 100644 index 00000000..58730e72 --- /dev/null +++ b/tests/agentstudio_sandbox/test_web_ui.py @@ -0,0 +1,1233 @@ +import base64 +import io +import json +import shlex +import struct +from contextlib import contextmanager +from types import SimpleNamespace + +import httpx +import pytest + + +def frame(value, flags=0): + data = json.dumps(value).encode() + return bytes([flags]) + struct.pack(">I", len(data)) + data + + +def process_output(text="DSH_WEB_TOKEN=login_token\n", exit_code=0): + return ( + frame({"event": {"start": {"pid": 42}}}) + + frame( + {"event": {"data": {"stdout": base64.b64encode(text.encode()).decode()}}} + ) + + frame({"event": {"end": {"exited": True, "exitCode": exit_code}}}) + + frame({}, 2) + ) + + +def connection(): + return SimpleNamespace( + domain="sandbox.example", + envd_url="https://envd.example/", + envd_access_token="envd-secret", + traffic_access_token="traffic-secret", + ) + + +def test_envd_command_uses_framed_process_and_private_headers(monkeypatch): + from dashscope.applications.agentstudio.sandbox import _bootstrap + + requests = [] + original = httpx.Client + + def reply(request): + requests.append(request) + return httpx.Response(200, content=process_output()) + + monkeypatch.setattr( + _bootstrap.httpx, + "Client", + lambda **kwargs: original(transport=httpx.MockTransport(reply)), + ) + bootstrap = _bootstrap._Bootstrap("sandbox-1", connection()) + assert ( + bootstrap.command( + ["/bin/sh", "-ec", 'printf "%s" "$1"', "label", "a; echo 'secret'"] + ) + == "DSH_WEB_TOKEN=login_token\n" + ) + request = requests[0] + assert request.url.path == "/process.Process/Start" + assert request.headers["x-access-token"] == "envd-secret" + assert request.headers["authorization"] == "Basic dXNlcjo=" + assert request.headers["e2b-sandbox-id"] == "sandbox-1" + assert request.headers["e2b-sandbox-port"] == "49983" + assert request.headers["e2b-traffic-access-token"] == "traffic-secret" + assert request.content[0] == 0 + assert struct.unpack(">I", request.content[1:5])[0] == len(request.content) - 5 + body = json.loads(request.content[5:]) + assert body["stdin"] is False + assert body["process"]["cwd"] == "/home/user" + assert shlex.split(body["process"]["args"][1])[1:] == [ + "/bin/sh", + "-ec", + 'printf "%s" "$1"', + "label", + "a; echo 'secret'", + ] + + +@pytest.mark.parametrize( + "response", + [ + b"\x00\x00", + frame({"event": {"end": {"exited": True, "exitCode": 0}}}), + process_output(exit_code=1), + process_output() + frame({}), + frame({"event": {"start": {"pid": 42}}}) + + frame({"event": {"data": {"stdout": "not base64"}}}), + b'\x00\x00\x00\x00\x08{"x":1}x', + ], +) +def test_envd_rejects_malformed_or_unconfirmed_process(response): + from dashscope.applications.agentstudio.sandbox._bootstrap import _stdout + + with pytest.raises(OSError): + _stdout(response) + + +def test_envd_bounded_response_and_errors_hide_endpoint(monkeypatch): + from dashscope.applications.agentstudio.sandbox import _bootstrap + + original = httpx.Client + monkeypatch.setattr( + _bootstrap.httpx, + "Client", + lambda **kwargs: original( + transport=httpx.MockTransport( + lambda request: httpx.Response( + 200, content=b"x" * (2 * 1024 * 1024 + 1) + ) + ) + ), + ) + with pytest.raises(OSError, match="size limit"): + _bootstrap._Bootstrap("sandbox-1", connection()).command(["true"]) + monkeypatch.setattr( + _bootstrap.httpx, + "Client", + lambda **kwargs: original( + transport=httpx.MockTransport( + lambda request: httpx.Response(403, content=b"envd-secret") + ) + ), + ) + with pytest.raises(OSError) as error: + _bootstrap._Bootstrap("sandbox-1", connection()).command(["true"]) + assert "envd-secret" not in str(error.value) + assert "envd.example" not in str(error.value) + + +class RecordingBootstrap: + def __init__(self, token): + self.commands, self.files, self.token = [], {}, token + + def command(self, argv): + self.commands.append(argv) + return self.token + + def put_file(self, path, data): + self.files[path] = data + + def put_json(self, path, data): + self.files[path] = json.dumps(data).encode() + + +def test_dsh_model_credentials_are_private_and_missing_key_stays_absent(): + from dashscope.applications.agentstudio.sandbox._bootstrap import _Bootstrap + + recorder = RecordingBootstrap("DSH_WEB_TOKEN=web_token\n") + assert ( + _Bootstrap.start_dsh( + recorder, + "8080-s.example", + True, + "https://model.example/v1", + "qwen3.7-plus", + "", + ) + == "web_token" + ) + assert set(recorder.files) == {"/home/user/.dsh/native-web-preview.json"} + patch = json.loads(recorder.files["/home/user/.dsh/native-web-preview.json"]) + provider = patch[0]["config"]["providers"]["bailian-qwen"] + assert provider["baseURL"] == "https://model.example/v1" + assert provider["apiKeyEnv"] == "DASHSCOPE_API_KEY" + recorder = RecordingBootstrap("DSH_WEB_TOKEN=web_token\n") + _Bootstrap.start_dsh( + recorder, + "8080-s.example", + True, + "https://model.example/v1", + "custom", + "model-secret", + ) + assert json.loads(recorder.files["/home/user/.dsh/.credentials.yaml"]) == { + "version": 1, + "refs": {"DASHSCOPE_API_KEY": "model-secret"}, + } + assert "model-secret" not in json.dumps(recorder.commands) + + +def test_openclaw_config_keeps_device_auth_and_file_secret(): + from dashscope.applications.agentstudio.sandbox._bootstrap import _start_openclaw + + recorder = RecordingBootstrap("OPENCLAW_WEB_TOKEN=gateway_token\n") + assert ( + _start_openclaw( + recorder, + "https://18789-s.example", + True, + "https://model.example/v1", + "custom", + "model-secret", + "anthropic-messages", + ) + == "gateway_token" + ) + patch = json.loads( + next(data for name, data in recorder.files.items() if "/patch-" in name) + ) + assert ( + recorder.files["/home/user/.openclaw/sdk-web-preview/model.key"] + == b"model-secret" + ) + assert patch["models"]["providers"]["bailian-qwen"]["apiKey"] == { + "source": "file", + "provider": "sdkwebmodel", + "id": "value", + } + assert patch["models"]["providers"]["bailian-qwen"]["api"] == "anthropic-messages" + assert patch["gateway"]["controlUi"] == { + "enabled": True, + "basePath": "", + "allowInsecureAuth": False, + "dangerouslyDisableDeviceAuth": False, + "dangerouslyAllowHostHeaderOriginFallback": False, + "allowedOrigins": ["https://18789-s.example"], + } + assert "model-secret" not in json.dumps(patch) + assert "model-secret" not in json.dumps(recorder.commands) + + +def test_borrowed_bootstrap_does_not_write_model_settings(): + from dashscope.applications.agentstudio.sandbox._bootstrap import ( + _Bootstrap, + _start_openclaw, + ) + + recorder = RecordingBootstrap("DSH_WEB_TOKEN=web_token\n") + _Bootstrap.start_dsh(recorder, "host", False, "", "", "") + assert recorder.files == {} + recorder = RecordingBootstrap("OPENCLAW_WEB_TOKEN=web_token\n") + _start_openclaw(recorder, "https://host", False, "", "", "", "") + patch = json.loads(next(iter(recorder.files.values()))) + assert "models" not in patch and "secrets" not in patch + + +def test_pairing_id_validated_before_remote_command(): + from dashscope.applications.agentstudio.sandbox._bootstrap import _approve_pairing + + recorder = RecordingBootstrap("") + with pytest.raises(OSError): + _approve_pairing(recorder, "not-a-uuid; echo token") + assert recorder.commands == [] + _approve_pairing(recorder, "12345678-1234-1234-1234-123456789abc") + assert recorder.commands[-1][-1] == "12345678-1234-1234-1234-123456789abc" + + +def test_options_do_not_reveal_key_or_allow_model_without_endpoint(): + from dashscope.applications.agentstudio.sandbox.models import OfficialImage + from dashscope.applications.agentstudio.sandbox.web_ui import ( + WebUiOptions, + _validate, + ) + + options = WebUiOptions(model_api_key="model-secret") + assert "model-secret" not in repr(options) + with pytest.raises(ValueError, match="model_base_url"): + _validate(OfficialImage.DEEPSEEK_HARNESS, options) + with pytest.raises(ValueError): + _validate( + OfficialImage.DEEPSEEK_HARNESS, + WebUiOptions(sandbox_id="s", model_base_url="https://model.example"), + ) + validated = _validate( + OfficialImage.OPENCLAW, WebUiOptions(model_base_url="https://model.example/v1") + ) + assert validated.model_id == "qwen3.7-plus" + assert validated.model_api_key is None + + +class FakePlatform: + base_url = "https://platform.example" + api_key = "platform-secret" + timeout = 30.0 + poll_interval = 0.01 + + def __init__(self, fail_connect=False, release_fails=False): + self._closed = False + self._closing = False + self._client = SimpleNamespace(is_closed=False) + self.calls, self.subscriptions = [], set() + self.fail_connect, self.release_fails = fail_connect, release_fails + + def request(self, method, path, **kwargs): + self.calls.append((method, path, kwargs.get("json"))) + if path.endswith("/template-config"): + return { + "images": [], + "resource_configs": [], + "default_compute": {"cpu": 2, "memory_mib": 4096}, + } + if "/images/" in path: + return { + "imageName": "deepseek-harness", + "imageUrl": "registry.example/native:v8", + } + if path.endswith("/v3/templates"): + return { + "templateID": "template-new", + "templateName": "preview", + "buildID": "build-1", + } + if path.endswith("/status"): + return { + "templateID": "template-new", + "buildID": "build-1", + "status": "READY", + } + if path.endswith("/connect") and self.fail_connect: + raise OSError("network unavailable") + if path.endswith("/sandboxes") or path.endswith("/connect"): + return { + "sandboxID": "sandbox-1", + "templateID": "template-new", + "domain": "sandbox.example", + "envdUrl": "https://envd.example/", + "envdAccessToken": "envd-secret", + } + if method == "DELETE" and "/sandboxes/" in path and self.release_fails: + raise RuntimeError("release unavailable") + if method == "DELETE": + return None + raise AssertionError((method, path)) + + def register(self, subscription): + self.subscriptions.add(subscription) + + def unregister(self, subscription): + self.subscriptions.discard(subscription) + + +def prepare_local_preview(monkeypatch): + from dashscope.applications.agentstudio.sandbox import web_ui as _web_ui + + monkeypatch.setattr(_web_ui, "_check_node", lambda: None) + monkeypatch.setattr( + _web_ui._bootstrap, "prepare", lambda *args: SimpleNamespace(openclaw=False) + ) + monkeypatch.setattr( + _web_ui._Resources, + "start_proxy", + lambda *args: "http://127.0.0.1:12345/__preview/entry", + ) + return _web_ui + + +def test_fresh_preview_resolves_directory_and_releases_only_owned_resources( + monkeypatch, +): + from dashscope.applications.agentstudio.sandbox.models import OfficialImage + from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient + + web_ui = prepare_local_preview(monkeypatch) + platform = FakePlatform() + preview = web_ui.open_web_ui( + SandboxesClient(platform), platform, OfficialImage.DEEPSEEK_HARNESS + ) + assert preview.sandbox_id == "sandbox-1" + assert preview.template_id == "template-new" + assert preview in platform.subscriptions + create = next( + body for method, path, body in platform.calls if path.endswith("/v3/templates") + ) + assert create["fromImage"] == "registry.example/native:v8" + assert create["cpuCount"] == 2 and create["memoryMB"] == 4096 + sandbox = next( + body + for method, path, body in platform.calls + if method == "POST" and path.endswith("/sandboxes") + ) + assert sandbox == { + "templateID": "template-new", + "timeout": 3600, + "metadata": {"purpose": "deepseek-harness-native-web-preview"}, + "secure": True, + } + preview.close() + preview.close() + deletes = [path for method, path, body in platform.calls if method == "DELETE"] + assert deletes == [ + "/api/v1/agentstudio/sandbox/sandboxes/sandbox-1", + "/api/v1/agentstudio/sandbox/templates/template-new", + ] + assert platform.subscriptions == set() + assert "/__preview/" not in repr(preview) + + +@pytest.mark.parametrize( + "options,deletes", + [ + ({"sandbox_id": "sandbox-1"}, []), + ( + {"ready_template_id": "template-new"}, + ["/api/v1/agentstudio/sandbox/sandboxes/sandbox-1"], + ), + ], +) +def test_reuse_preserves_borrowed_resources(monkeypatch, options, deletes): + from dashscope.applications.agentstudio.sandbox.models import OfficialImage + from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient + + web_ui = prepare_local_preview(monkeypatch) + platform = FakePlatform() + with web_ui.open_web_ui( + SandboxesClient(platform), + platform, + OfficialImage.DEEPSEEK_HARNESS, + web_ui.WebUiOptions(**options), + ): + pass + assert [ + path for method, path, body in platform.calls if method == "DELETE" + ] == deletes + assert not any( + "/template-config" in path or "/images/" in path or "/v3/templates" in path + for method, path, body in platform.calls + ) + + +def test_connect_failure_still_releases_new_sandbox_and_template(monkeypatch): + from dashscope.applications.agentstudio.sandbox.models import OfficialImage + from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient + from dashscope.applications.agentstudio.sandbox.exceptions import SandboxAPIError + + web_ui = prepare_local_preview(monkeypatch) + platform = FakePlatform(fail_connect=True, release_fails=True) + with pytest.raises(SandboxAPIError, match="native Web UI"): + web_ui.open_web_ui( + SandboxesClient(platform), platform, OfficialImage.DEEPSEEK_HARNESS + ) + assert [path for method, path, body in platform.calls if method == "DELETE"] == [ + "/api/v1/agentstudio/sandbox/sandboxes/sandbox-1", + "/api/v1/agentstudio/sandbox/templates/template-new", + ] + + +def test_ready_template_mismatch_preserves_existing_sandbox(monkeypatch): + from dashscope.applications.agentstudio.sandbox.models import OfficialImage + from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient + + web_ui = prepare_local_preview(monkeypatch) + platform = FakePlatform() + with pytest.raises(ValueError, match="ready_template_id"): + web_ui.open_web_ui( + SandboxesClient(platform), + platform, + OfficialImage.DEEPSEEK_HARNESS, + web_ui.WebUiOptions(sandbox_id="sandbox-1", ready_template_id="wrong"), + ) + assert not any(method == "DELETE" for method, path, body in platform.calls) + + +def test_local_proxy_real_node_uses_private_stdin_and_one_time_cookie(): + import shutil + import threading + from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + from dashscope.applications.agentstudio.sandbox._bootstrap import _Route + from dashscope.applications.agentstudio.sandbox.web_ui import ( + _Resources, + _check_node, + ) + + if not shutil.which("node"): + pytest.skip("Node.js is not installed") + try: + _check_node() + except Exception: + pytest.skip("Node.js --use-system-ca support is unavailable") + seen = [] + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + seen.append( + ( + self.path, + self.headers.get("cookie"), + self.headers.get("x-access-token"), + ) + ) + if self.path == "/?token=native-secret": + self.send_response(303) + self.send_header("Set-Cookie", "dsh=native-cookie; HttpOnly") + self.send_header("Location", "/") + self.end_headers() + else: + self.send_response(200) + self.send_header("Content-Type", "text/html") + self.end_headers() + self.wfile.write(b"native preview") + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + resources = _Resources(SimpleNamespace(), FakePlatform()) + try: + address = resources.start_proxy( + _Route( + "http://127.0.0.1:" + str(server.server_port) + "/", + "native-secret", + {"x-access-token": "envd-secret"}, + False, + None, + ), + False, + ) + script = resources.script + proxy = resources.proxy + assert "native-secret" not in open(script).read() + assert "native-secret" not in repr(proxy.args) + origin = address.split("/__preview/")[0] + with httpx.Client(trust_env=False) as browser: + assert browser.get(origin).status_code == 403 + entry = browser.get(address) + assert entry.status_code == 303 + assert "native-secret" not in entry.headers.get("set-cookie", "") + assert browser.get(origin).text == "native preview" + assert browser.get(address).status_code != 303 + assert seen[0] == ("/?token=native-secret", None, "envd-secret") + assert seen[1][1:] == ("dsh=native-cookie", "envd-secret") + finally: + resources.close() + server.shutdown() + server.server_close() + assert proxy.poll() is not None + assert not __import__("os").path.exists(script) + + +def test_client_context_closes_preview_before_pool_and_releases_owned_resources( + monkeypatch, +): + from dashscope.applications.agentstudio.sandbox.client import SandboxClient + from dashscope.applications.agentstudio.sandbox.models import OfficialImage + + prepare_local_preview(monkeypatch) + platform = FakePlatform() + + def reply(request): + body = json.loads(request.content) if request.content else None + result = platform.request(request.method, request.url.path, json=body) + if request.url.path.endswith("/template-config"): + result = {"data": result} + return httpx.Response(200, json=result) + + with httpx.Client(transport=httpx.MockTransport(reply)) as pool: + with SandboxClient( + base_url="https://platform.example", + api_key="platform-secret", + http_client=pool, + ) as client: + preview = client.sandboxes.open_web_ui(OfficialImage.DEEPSEEK_HARNESS) + assert not pool.is_closed + assert preview._resources._closed + assert [path for method, path, body in platform.calls if method == "DELETE"] == [ + "/api/v1/agentstudio/sandbox/sandboxes/sandbox-1", + "/api/v1/agentstudio/sandbox/templates/template-new", + ] + + +def test_proxy_start_failure_kills_child_and_removes_script(monkeypatch): + from dashscope.applications.agentstudio.sandbox import web_ui as _web_ui + from dashscope.applications.agentstudio.sandbox._bootstrap import _Route + from dashscope.applications.agentstudio.sandbox.models import OfficialImage + from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient + from dashscope.applications.agentstudio.sandbox.exceptions import SandboxAPIError + + monkeypatch.setattr(_web_ui, "_check_node", lambda: None) + route = _Route("https://upstream.example/", "login-secret", {}, False, None) + monkeypatch.setattr(_web_ui._bootstrap, "prepare", lambda *args: route) + children = [] + + class Child: + def __init__(self, args, **kwargs): + self.args, self.stdin, self.stdout, self.killed = ( + args, + io.BytesIO(), + io.BytesIO(b"https://outside.example/\n"), + False, + ) + children.append(self) + + def poll(self): + return -9 if self.killed else None + + def kill(self): + self.killed = True + + def wait(self, timeout=None): + return -9 + + monkeypatch.setattr(_web_ui.subprocess, "Popen", Child) + platform = FakePlatform() + with pytest.raises(SandboxAPIError, match="native Web UI"): + _web_ui.open_web_ui( + SandboxesClient(platform), platform, OfficialImage.DEEPSEEK_HARNESS + ) + assert children[0].killed + assert not __import__("os").path.exists(children[0].args[2]) + assert len([1 for method, path, body in platform.calls if method == "DELETE"]) == 2 + + +@pytest.mark.parametrize("cancel", [False, True]) +def test_async_preview_owns_sync_client_and_cleans_after_cancellation( + monkeypatch, cancel +): + import asyncio + import threading + from dashscope.applications.agentstudio.sandbox import client as _client + from dashscope.applications.agentstudio.sandbox.models import OfficialImage + + web_ui = prepare_local_preview(monkeypatch) + platform = FakePlatform() + + def reply(request): + result = platform.request( + request.method, + request.url.path, + json=json.loads(request.content) if request.content else None, + ) + return httpx.Response( + 200, + json=( + {"data": result} + if request.url.path.endswith("/template-config") + else result + ), + ) + + original = _client.SandboxClient + owned = [] + with httpx.Client(transport=httpx.MockTransport(reply)) as pool: + + def create(**kwargs): + client = original(**kwargs, http_client=pool) + owned.append(client) + return client + + monkeypatch.setattr(_client, "SandboxClient", create) + started, proceed = threading.Event(), threading.Event() + + def ready(*args): + started.set() + assert proceed.wait(5) + return "http://127.0.0.1:12345/__preview/entry" + + monkeypatch.setattr(web_ui._Resources, "start_proxy", ready) + + async def exercise(): + async with httpx.AsyncClient( + transport=httpx.MockTransport( + lambda request: pytest.fail( + "Async HTTP pool crossed into native setup" + ) + ) + ) as async_pool: + async with _client.AsyncSandboxClient( + base_url="https://platform.example", + api_key="platform-secret", + http_client=async_pool, + ) as client: + pending = asyncio.create_task( + client.sandboxes.open_web_ui(OfficialImage.DEEPSEEK_HARNESS) + ) + assert await asyncio.to_thread(started.wait, 5) + if cancel: + pending.cancel() + proceed.set() + if cancel: + with pytest.raises(asyncio.CancelledError): + await pending + else: + preview = await pending + assert preview._resources.owned_client is owned[0] + assert not owned[0]._transport._closed + async with preview: + pass + assert owned[0]._transport._closed + assert not client._transport._subscriptions + assert not async_pool.is_closed + + asyncio.run(exercise()) + assert len([1 for method, path, body in platform.calls if method == "DELETE"]) == 2 + + +def test_web_ui_requires_explicit_supported_image_enum(): + from dashscope.applications.agentstudio.sandbox.web_ui import ( + WebUiOptions, + _validate, + ) + + with pytest.raises(ValueError, match="image"): + _validate("deepseek-harness", WebUiOptions()) + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("lifecycle", ["closed", "closing"]) +def test_web_ui_does_not_start_setup_after_client_shutdown( + monkeypatch, asynchronous, lifecycle +): + import asyncio + from dashscope.applications.agentstudio.sandbox import ( + AsyncSandboxClient, + OfficialImage, + SandboxClient, + client as _client, + web_ui as _web_ui, + ) + + requests = [] + + def handle(request): + requests.append(request) + raise AssertionError("Shutdown client must not provision resources") + + def reject_node_check(): + raise AssertionError("Shutdown client must not check Node") + + def reject_owned_client(**kwargs): + raise AssertionError("Shutdown client must not create a worker HTTP pool") + + monkeypatch.setattr(_web_ui, "_check_node", reject_node_check) + if not asynchronous: + pool = httpx.Client(transport=httpx.MockTransport(handle)) + client = SandboxClient( + base_url="https://unit.test", api_key="key", http_client=pool + ) + try: + if lifecycle == "closed": + client.close() + else: + client._transport._take_subscriptions() + with pytest.raises(ValueError, match="Sandbox client is closed"): + client.sandboxes.open_web_ui(OfficialImage.DEEPSEEK_HARNESS) + assert not requests + finally: + client._transport._closing = False + client.close() + pool.close() + return + + async def run(): + pool = httpx.AsyncClient(transport=httpx.MockTransport(handle)) + client = AsyncSandboxClient( + base_url="https://unit.test", api_key="key", http_client=pool + ) + monkeypatch.setattr(_client, "SandboxClient", reject_owned_client) + try: + if lifecycle == "closed": + await client.aclose() + else: + client._transport._take_subscriptions() + with pytest.raises(ValueError, match="Sandbox client is closed"): + await client.sandboxes.open_web_ui(OfficialImage.DEEPSEEK_HARNESS) + assert not requests + finally: + client._transport._closing = False + await client.aclose() + await pool.aclose() + + asyncio.run(run()) + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("entry", ["closed_root", "closed_borrowed_pool"]) +def test_web_ui_rejects_a_closed_underlying_pool_before_native_setup( + monkeypatch, + asynchronous, + entry, +): + import asyncio + from dashscope import AsyncClient, Client + from dashscope.applications.agentstudio.sandbox import ( + AsyncSandboxClient, + OfficialImage, + SandboxClient, + client as _client, + web_ui as _web_ui, + ) + + requests = [] + + def handle(request): + requests.append(request) + raise AssertionError("Closed HTTP pool must not provision remote resources") + + def reject_setup(): + raise AssertionError("Closed HTTP pool must not check Node") + + def reject_worker(**kwargs): + raise AssertionError("Closed HTTP pool must not create a worker HTTP client") + + monkeypatch.setattr(_web_ui, "_check_node", reject_setup) + if not asynchronous: + pool = httpx.Client(transport=httpx.MockTransport(handle)) + if entry == "closed_root": + monkeypatch.setattr(httpx, "Client", lambda **kwargs: pool) + client = Client(base_url="https://unit.test/api/v1", api_key="key") + assert client.transport._owns_client + client.close() + sandbox = client.agentstudio.sandbox + else: + client = SandboxClient( + base_url="https://unit.test", api_key="key", http_client=pool + ) + pool.close() + sandbox = client + try: + with pytest.raises(ValueError, match="Sandbox client is closed"): + sandbox.sandboxes.open_web_ui(OfficialImage.DEEPSEEK_HARNESS) + assert not requests + finally: + client.close() + pool.close() + return + + async def run(): + pool = httpx.AsyncClient(transport=httpx.MockTransport(handle)) + if entry == "closed_root": + monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: pool) + client = AsyncClient(base_url="https://unit.test/api/v1", api_key="key") + assert client.transport._owns_client + await client.aclose() + sandbox = client.agentstudio.sandbox + else: + client = AsyncSandboxClient( + base_url="https://unit.test", api_key="key", http_client=pool + ) + await pool.aclose() + sandbox = client + monkeypatch.setattr(_client, "SandboxClient", reject_worker) + try: + with pytest.raises(ValueError, match="Sandbox client is closed"): + await sandbox.sandboxes.open_web_ui(OfficialImage.DEEPSEEK_HARNESS) + assert not requests + finally: + await client.aclose() + await pool.aclose() + + asyncio.run(run()) + + +@pytest.fixture +def openclaw_preview(): + """Run the bundled proxy against a local Gateway with no cloud credentials.""" + import hashlib + import shutil + import threading + from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + from dashscope.applications.agentstudio.sandbox._bootstrap import _Route + from dashscope.applications.agentstudio.sandbox.web_ui import ( + _Resources, + _check_node, + ) + + if not shutil.which("node"): + pytest.skip("Node.js is not installed") + try: + _check_node() + except Exception: + pytest.skip("Node.js --use-system-ca support is unavailable") + + running = [] + + def start(auto_pair=False, reason="not-paired", approval_succeeds=True): + state = SimpleNamespace(requests=[], approvals=[], connections=0) + + class PairingBootstrap: + def command(self, argv): + state.approvals.append(argv) + if not approval_succeeds: + raise OSError("Pairing denied by the Gateway") + return "" + + class Gateway(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def record(self): + state.requests.append( + ( + self.path, + {key.lower(): value for key, value in self.headers.items()}, + ) + ) + + def do_HEAD(self): + self.do_GET() + + def do_POST(self): + self.do_GET() + + def do_GET(self): + self.record() + if self.headers.get("upgrade", "").lower() == "websocket": + self.websocket() + return + avatar = self.path == "/avatar/main?meta=1" + status = 200 + if avatar and self.headers.get("authorization") not in ( + "Bearer device-secret", + "Bearer gateway-secret", + ): + status = 401 + self.send_response(status) + self.send_header("Content-Type", "text/html") + self.send_header("Content-Disposition", "attachment") + self.send_header("Set-Cookie", "gateway=private-cookie") + self.end_headers() + if self.command != "HEAD": + self.wfile.write(b"
OpenClaw
") + + def websocket(self): + accept = hashlib.sha1( + ( + self.headers["sec-websocket-key"] + + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + ).encode() + ).digest() + self.send_response(101) + self.send_header("Connection", "Upgrade") + self.send_header("Upgrade", "websocket") + self.send_header( + "Sec-WebSocket-Accept", base64.b64encode(accept).decode() + ) + self.end_headers() + self.connection.settimeout(5) + state.connections += 1 + current = state.connections + self.send_text({"type": "event", "event": "connect.challenge"}) + try: + opcode, _ = self.read_packet() + if opcode != 1: + return + if current > 1: + reply = { + "type": "res", + "id": "browser-connect", + "ok": True, + "payload": {"type": "hello-ok"}, + } + else: + reply = { + "type": "res", + "id": "browser-connect", + "ok": False, + "error": { + "code": "NOT_PAIRED", + "details": { + "code": "PAIRING_REQUIRED", + "reason": reason, + "requestedRole": "operator", + "requestId": "12345678-1234-1234-1234-123456789abc", + }, + }, + } + # Gateway messages may span multiple TCP reads. + self.send_text(reply, fragmented=True) + opcode, payload = self.read_packet() + if opcode == 8: + self.connection.sendall(bytes([0x88, len(payload)]) + payload) + except (OSError, EOFError): + pass + + def send_text(self, value, fragmented=False): + data = json.dumps(value).encode() + header = ( + bytes([0x81, len(data)]) + if len(data) < 126 + else b"\x81\x7e" + struct.pack(">H", len(data)) + ) + packet = header + data + if fragmented: + self.connection.sendall(packet[:3]) + self.connection.sendall(packet[3:]) + else: + self.connection.sendall(packet) + + def read_packet(self): + header = self.rfile.read(2) + if len(header) != 2: + raise EOFError() + length = header[1] & 127 + if length == 126: + length = struct.unpack(">H", self.rfile.read(2))[0] + mask = self.rfile.read(4) if header[1] & 128 else None + payload = self.rfile.read(length) + if len(payload) != length: + raise EOFError() + if mask: + payload = bytes( + value ^ mask[index % 4] for index, value in enumerate(payload) + ) + return header[0] & 15, payload + + server = ThreadingHTTPServer(("127.0.0.1", 0), Gateway) + thread = threading.Thread( + target=lambda: server.serve_forever(poll_interval=0.01), daemon=True + ) + thread.start() + resources = _Resources(SimpleNamespace(), FakePlatform()) + running.append((resources, server, thread)) + state.upstream = "http://127.0.0.1:" + str(server.server_port) + address = resources.start_proxy( + _Route( + state.upstream + "/", + "gateway-secret", + { + "x-access-token": "fc-envd-secret", + "e2b-traffic-access-token": "fc-traffic-secret", + "e2b-sandbox-id": "sandbox-test", + "e2b-sandbox-port": "18789", + }, + True, + PairingBootstrap(), + ), + auto_pair, + ) + state.origin = address.split("/__preview/")[0] + state.entry = address + return state + + try: + yield start + finally: + for resources, server, thread in reversed(running): + try: + resources.close() + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + + +@contextmanager +def _open_preview_browser(state): + with httpx.Client(trust_env=False, timeout=3) as browser: + opened = browser.get(state.entry) + assert opened.status_code == 303 + assert opened.headers["location"] == "/#token=gateway-secret" + assert "gateway-secret" not in opened.headers["set-cookie"] + yield browser + + +def _connect_preview_socket(state, browser, origin=None, headers=None): + import websocket + + return websocket.create_connection( + state.origin.replace("https://", "ws://") + "/", + timeout=3, + origin=origin or state.origin, + cookie="; ".join(key + "=" + value for key, value in browser.cookies.items()), + header=headers, + http_no_proxy=["127.0.0.1"], + ) + + +@pytest.mark.parametrize( + "enabled,reason,approval_succeeds", + [ + (True, "not-paired", True), + (True, "not-paired", False), + (False, "not-paired", False), + (True, "scope-upgrade", False), + ], +) +def test_openclaw_pairs_only_the_authorized_browser_request( + openclaw_preview, enabled, reason, approval_succeeds +): + import websocket + + state = openclaw_preview(enabled, reason, approval_succeeds) + with _open_preview_browser(state) as browser: + socket = _connect_preview_socket(state, browser) + try: + assert json.loads(socket.recv())["event"] == "connect.challenge" + socket.send('{"type":"req","id":"browser-connect","method":"connect"}') + if enabled and reason == "not-paired": + if not approval_succeeds: + refusal = json.loads(socket.recv()) + assert refusal["error"]["details"]["reason"] == "not-paired" + opcode, payload = socket.recv_data(control_frame=True) + assert opcode == websocket.ABNF.OPCODE_CLOSE + assert struct.unpack(">H", payload[:2])[0] == ( + 1012 if approval_succeeds else 1008 + ) + assert len(state.approvals) == 1 + assert state.approvals[0][-1] == "12345678-1234-1234-1234-123456789abc" + else: + refusal = json.loads(socket.recv()) + assert refusal["error"]["details"]["reason"] == reason + assert state.approvals == [] + finally: + socket.close() + if approval_succeeds: + reconnected = _connect_preview_socket(state, browser) + try: + assert json.loads(reconnected.recv())["event"] == "connect.challenge" + reconnected.send( + '{"type":"req","id":"browser-connect","method":"connect"}' + ) + assert json.loads(reconnected.recv())["payload"]["type"] == "hello-ok" + assert len(state.approvals) == 1 + finally: + reconnected.close() + + +@pytest.mark.parametrize( + "method,path,authorization,status,forwarded", + [ + ( + "GET", + "/avatar/main?meta=1", + "Bearer device-secret", + 200, + "Bearer device-secret", + ), + ( + "HEAD", + "/avatar/main?meta=1", + "Bearer device-secret", + 200, + "Bearer device-secret", + ), + ( + "GET", + "/avatar/main?meta=1", + "Bearer gateway-secret", + 200, + "Bearer gateway-secret", + ), + ("GET", "/avatar/main?meta=1", "Bearer invalid", 401, "Bearer invalid"), + ("GET", "/avatar/main?meta=1", "Basic device-secret", 401, None), + ("POST", "/avatar/main?meta=1", "Bearer device-secret", 401, None), + ("GET", "/avatar/main/extra", "Bearer device-secret", 200, None), + ("GET", "/", "Bearer device-secret", 200, None), + ("GET", "/", "Bearer gateway-secret", 200, "Bearer gateway-secret"), + ], +) +def test_openclaw_forwards_device_bearer_only_for_avatar_reads( + openclaw_preview, method, path, authorization, status, forwarded +): + state = openclaw_preview() + with _open_preview_browser(state) as browser: + response = browser.request( + method, state.origin + path, headers={"Authorization": authorization} + ) + assert response.status_code == status + assert state.requests[-1][1].get("authorization") == forwarded + assert "set-cookie" not in response.headers + assert "content-disposition" not in response.headers + assert response.headers["cache-control"] == "no-store" + before = len(state.requests) + with httpx.Client(trust_env=False, timeout=3) as unauthenticated: + assert ( + unauthenticated.get( + state.origin + path, headers={"Authorization": authorization} + ).status_code + == 403 + ) + assert len(state.requests) == before + + +def test_openclaw_isolates_browser_origin_and_private_headers(openclaw_preview): + import websocket + + state = openclaw_preview() + spoofed = { + "Origin": state.origin, + "Referer": state.origin + "/?token=browser-secret", + "Forwarded": "for=untrusted", + "X-Forwarded-For": "untrusted", + "X-Forwarded-Host": "untrusted.example", + "X-Access-Token": "browser-envd-secret", + "E2B-Traffic-Access-Token": "browser-traffic-secret", + "E2B-Sandbox-Id": "browser-sandbox", + "E2B-Sandbox-Port": "1", + "Proxy-Authorization": "Bearer browser-proxy-secret", + "Authorization": "Bearer device-secret", + } + with _open_preview_browser(state) as browser: + assert browser.get(state.origin, headers=spoofed).status_code == 200 + path, forwarded = state.requests[-1] + assert path == "/" + assert forwarded["origin"] == state.upstream + assert forwarded["x-access-token"] == "fc-envd-secret" + assert forwarded["e2b-traffic-access-token"] == "fc-traffic-secret" + assert forwarded["e2b-sandbox-id"] == "sandbox-test" + assert forwarded["e2b-sandbox-port"] == "18789" + for name in ( + "cookie", + "authorization", + "proxy-authorization", + "referer", + "forwarded", + ): + assert name not in forwarded + assert not any(name.startswith("x-forwarded-") for name in forwarded) + before = len(state.requests) + for headers in ( + {"Origin": "http://unrelated.example"}, + {"Sec-Fetch-Site": "cross-site"}, + {"Host": "unrelated.example"}, + ): + assert browser.get(state.origin, headers=headers).status_code == 403 + assert len(state.requests) == before + with pytest.raises(websocket.WebSocketBadStatusException) as denied: + _connect_preview_socket(state, browser, origin="http://unrelated.example") + assert denied.value.status_code == 403 + assert len(state.requests) == before + socket = _connect_preview_socket( + state, + browser, + headers={key: value for key, value in spoofed.items() if key != "Origin"}, + ) + try: + assert json.loads(socket.recv())["event"] == "connect.challenge" + forwarded = state.requests[-1][1] + assert forwarded["origin"] == state.upstream + assert forwarded["x-access-token"] == "fc-envd-secret" + assert forwarded["e2b-traffic-access-token"] == "fc-traffic-secret" + assert "cookie" not in forwarded + assert "authorization" not in forwarded + assert "referer" not in forwarded + assert "proxy-authorization" not in forwarded + assert "forwarded" not in forwarded + assert not any(name.startswith("x-forwarded-") for name in forwarded) + finally: + socket.close() From 290d669b108c6c9b623fe541efef82d1765e068d Mon Sep 17 00:00:00 2001 From: "guning.lt" Date: Fri, 27 Nov 2026 10:59:28 +0800 Subject: [PATCH 2/7] sandbox api --- .../agentstudio/sandbox/_bootstrap.py | 5 +- .../agentstudio/sandbox/web_ui.py | 19 +- tests/agentstudio_sandbox/test_web_ui.py | 183 +++++++++++++++++- 3 files changed, 201 insertions(+), 6 deletions(-) diff --git a/dashscope/applications/agentstudio/sandbox/_bootstrap.py b/dashscope/applications/agentstudio/sandbox/_bootstrap.py index 17840fd7..3dd7b28b 100644 --- a/dashscope/applications/agentstudio/sandbox/_bootstrap.py +++ b/dashscope/applications/agentstudio/sandbox/_bootstrap.py @@ -310,11 +310,14 @@ def _read_token(stdout, prefix): def _configure_dsh_model(bootstrap, url, model, key): # 未传模型 Key 时,保留镜像自己的凭据文件。 if key: + # 管控台可能已初始化普通凭据文件;仍拒绝符号链接,且不覆盖已有预览 patch。 bootstrap.command( [ "/bin/sh", "-ec", - 'umask 077; set -C; : > "$1"; : > "$2"', + 'umask 077; set -C; : > "$2"; ' + 'if [ -e "$1" ]; then [ -f "$1" ]; [ ! -L "$1" ]; ' + 'else : > "$1"; fi; chmod 600 "$1"', "model-config", _DSH_CREDENTIALS, _DSH_PATCH, diff --git a/dashscope/applications/agentstudio/sandbox/web_ui.py b/dashscope/applications/agentstudio/sandbox/web_ui.py index 5cf2decf..ad07a846 100644 --- a/dashscope/applications/agentstudio/sandbox/web_ui.py +++ b/dashscope/applications/agentstudio/sandbox/web_ui.py @@ -324,17 +324,28 @@ async def __aexit__(self, exc_type, exc_value, traceback): await self.aclose() -def _create_template(resources, transport, image, image_url): - from .models import TemplateCreateRequest +def _create_template(resources, transport, image, options): + from .models import ModelConfig, TemplateCreateRequest from .agents import AgentsClient compute = AgentsClient(transport).template_config().default_compute + # 模板与实例使用同一份模型配置,避免管控台详情与实际运行不一致。 + model = ( + ModelConfig( + base_url=options.model_base_url, + model_id=options.model_id, + api_key=options.model_api_key, + ) + if options.model_base_url + else None + ) request = TemplateCreateRequest( name=image.value + "-web-preview-" + uuid.uuid4().hex[:8], image=image, - from_image=image_url, + from_image=options.image_url, cpu_count=compute.cpu, memory_mb=compute.memory_mib, + model_config=model, ) template = resources.templates.create(request) resources.owned_template = template.id @@ -362,7 +373,7 @@ def open_web_ui(sandboxes, transport, image, options=None): if fresh: if template_id is None: template_id = _create_template( - resources, transport, image, options.image_url + resources, transport, image, options ) resources.sandbox = sandboxes.create( SandboxCreateRequest( diff --git a/tests/agentstudio_sandbox/test_web_ui.py b/tests/agentstudio_sandbox/test_web_ui.py index 58730e72..0a6f8e2c 100644 --- a/tests/agentstudio_sandbox/test_web_ui.py +++ b/tests/agentstudio_sandbox/test_web_ui.py @@ -3,7 +3,9 @@ import json import shlex import struct +import subprocess from contextlib import contextmanager +from pathlib import Path from types import SimpleNamespace import httpx @@ -180,6 +182,103 @@ def test_dsh_model_credentials_are_private_and_missing_key_stays_absent(): assert "model-secret" not in json.dumps(recorder.commands) +@pytest.fixture +def local_dsh_model_files(tmp_path, monkeypatch): + from dashscope.applications.agentstudio.sandbox import _bootstrap + + credentials = tmp_path / ".credentials.yaml" + patch = tmp_path / "native-web-preview.json" + monkeypatch.setattr(_bootstrap, "_DSH_CREDENTIALS", str(credentials)) + monkeypatch.setattr(_bootstrap, "_DSH_PATCH", str(patch)) + + class LocalFiles(RecordingBootstrap): + def command(self, argv): + self.commands.append(argv) + return subprocess.run( + argv, check=True, capture_output=True, text=True + ).stdout + + def put_json(self, path, data): + super().put_json(path, data) + Path(path).write_bytes(self.files[path]) + + return _bootstrap, credentials, patch, LocalFiles("") + + +@pytest.mark.parametrize("already_exists", [False, True]) +def test_dsh_model_setup_writes_private_regular_credentials( + local_dsh_model_files, already_exists +): + module, credentials, patch, bootstrap = local_dsh_model_files + if already_exists: + credentials.write_text("existing credentials") + credentials.chmod(0o644) + module._configure_dsh_model( + bootstrap, "https://model.example/v1", "qwen3.7-plus", "model-secret" + ) + assert json.loads(credentials.read_text()) == { + "version": 1, + "refs": {"DASHSCOPE_API_KEY": "model-secret"}, + } + assert credentials.stat().st_mode & 0o777 == 0o600 + assert patch.stat().st_mode & 0o777 == 0o600 + assert "model-secret" not in json.dumps(bootstrap.commands) + + +@pytest.mark.parametrize("file_kind", ["symlink", "dangling-symlink", "directory"]) +def test_dsh_model_setup_rejects_non_regular_credentials( + local_dsh_model_files, file_kind +): + module, credentials, patch, bootstrap = local_dsh_model_files + if file_kind in ("symlink", "dangling-symlink"): + target = credentials.with_name("original.credentials") + if file_kind == "symlink": + target.write_text("original credentials") + credentials.symlink_to(target) + else: + credentials.mkdir() + credentials.chmod(0o755) + with pytest.raises(subprocess.CalledProcessError): + module._configure_dsh_model( + bootstrap, "https://model.example/v1", "qwen3.7-plus", "model-secret" + ) + assert bootstrap.files == {} + if file_kind in ("symlink", "dangling-symlink"): + assert credentials.is_symlink() + if file_kind == "symlink": + assert target.read_text() == "original credentials" + else: + assert not target.exists() + else: + assert credentials.is_dir() + assert credentials.stat().st_mode & 0o777 == 0o755 + + +def test_dsh_model_setup_preserves_an_existing_patch(local_dsh_model_files): + module, credentials, patch, bootstrap = local_dsh_model_files + credentials.write_text("existing credentials") + patch.write_text("existing patch") + with pytest.raises(subprocess.CalledProcessError): + module._configure_dsh_model( + bootstrap, "https://model.example/v1", "qwen3.7-plus", "model-secret" + ) + assert credentials.read_text() == "existing credentials" + assert patch.read_text() == "existing patch" + assert bootstrap.files == {} + + +def test_dsh_model_setup_without_key_preserves_credentials(local_dsh_model_files): + module, credentials, patch, bootstrap = local_dsh_model_files + credentials.write_text("existing credentials") + credentials.chmod(0o640) + module._configure_dsh_model( + bootstrap, "https://model.example/v1", "qwen3.7-plus", "" + ) + assert credentials.read_text() == "existing credentials" + assert credentials.stat().st_mode & 0o777 == 0o640 + assert patch.stat().st_mode & 0o777 == 0o600 + + def test_openclaw_config_keeps_device_auth_and_file_secret(): from dashscope.applications.agentstudio.sandbox._bootstrap import _start_openclaw @@ -293,7 +392,7 @@ def request(self, method, path, **kwargs): } if "/images/" in path: return { - "imageName": "deepseek-harness", + "imageName": path.rsplit("/", 1)[-1], "imageUrl": "registry.example/native:v8", } if path.endswith("/v3/templates"): @@ -387,6 +486,76 @@ def test_fresh_preview_resolves_directory_and_releases_only_owned_resources( assert "/__preview/" not in repr(preview) +@pytest.mark.parametrize("image_name", ["deepseek-harness", "openclaw"]) +@pytest.mark.parametrize( + "model_options,expected_model", + [ + ( + { + "model_base_url": "https://model.example/v1", + "model_id": "qwen3.7-plus", + "model_api_key": "model-secret", + }, + { + "baseUrl": "https://model.example/v1", + "modelName": "qwen3.7-plus", + "apiKey": "model-secret", + }, + ), + ( + {"model_base_url": "https://model.example/v1"}, + {"baseUrl": "https://model.example/v1", "modelName": "qwen3.7-plus"}, + ), + ( + { + "model_base_url": "https://model.example/v1", + "model_id": "qwen3.7-plus", + "model_api_key": " ", + }, + {"baseUrl": "https://model.example/v1", "modelName": "qwen3.7-plus"}, + ), + ({}, None), + ], + ids=["explicit-model", "url-only-default", "empty-key", "image-defaults"], +) +def test_fresh_preview_uses_same_model_for_template_and_instance( + monkeypatch, image_name, model_options, expected_model +): + from dashscope.applications.agentstudio.sandbox.models import OfficialImage + from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient + + web_ui = prepare_local_preview(monkeypatch) + prepared = [] + + def prepare(*args): + prepared.append(args) + return SimpleNamespace(openclaw=image_name == "openclaw") + + monkeypatch.setattr(web_ui._bootstrap, "prepare", prepare) + platform = FakePlatform() + with web_ui.open_web_ui( + SandboxesClient(platform), + platform, + OfficialImage(image_name), + web_ui.WebUiOptions(**model_options), + ): + create = next( + body + for method, path, body in platform.calls + if path.endswith("/v3/templates") + ) + if expected_model is None: + assert "modelConfig" not in create + assert prepared[0][4:7] == ("", "", "") + else: + assert create["modelConfig"] == expected_model + assert prepared[0][4:7] == ( + expected_model["baseUrl"], + expected_model["modelName"], + expected_model.get("apiKey", ""), + ) + + @pytest.mark.parametrize( "options,deletes", [ @@ -395,6 +564,14 @@ def test_fresh_preview_resolves_directory_and_releases_only_owned_resources( {"ready_template_id": "template-new"}, ["/api/v1/agentstudio/sandbox/sandboxes/sandbox-1"], ), + ( + { + "ready_template_id": "template-new", + "model_base_url": "https://model.example/v1", + "model_id": "qwen3.7-plus", + }, + ["/api/v1/agentstudio/sandbox/sandboxes/sandbox-1"], + ), ], ) def test_reuse_preserves_borrowed_resources(monkeypatch, options, deletes): @@ -417,6 +594,10 @@ def test_reuse_preserves_borrowed_resources(monkeypatch, options, deletes): "/template-config" in path or "/images/" in path or "/v3/templates" in path for method, path, body in platform.calls ) + assert not any( + method in ("POST", "PUT", "PATCH") and "/templates/" in path + for method, path, body in platform.calls + ) def test_connect_failure_still_releases_new_sandbox_and_template(monkeypatch): From 5a858bf017a3003a91681dcbd943f7e8a642f7ac Mon Sep 17 00:00:00 2001 From: "guning.lt" Date: Wed, 2 Dec 2026 14:01:34 +0800 Subject: [PATCH 3/7] sandbox api --- .../agentstudio/sandbox/web_ui.py | 6 +-- tests/agentstudio_sandbox/test_web_ui.py | 43 +++++++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/dashscope/applications/agentstudio/sandbox/web_ui.py b/dashscope/applications/agentstudio/sandbox/web_ui.py index ad07a846..33233ef4 100644 --- a/dashscope/applications/agentstudio/sandbox/web_ui.py +++ b/dashscope/applications/agentstudio/sandbox/web_ui.py @@ -26,8 +26,8 @@ class WebUiOptions: """Reuse a Sandbox/template or provision a fresh native Web UI. Model settings apply only to a new Sandbox and never inherit the platform - API key. ``auto_pair_openclaw`` approves this preview browser's first - validated operator pairing request. + API key. ``auto_pair_openclaw`` defaults to True and approves this preview + browser's first validated operator pairing request. """ sandbox_id: str = None @@ -37,7 +37,7 @@ class WebUiOptions: model_id: str = None model_api_key: str = field(default=None, repr=False) openclaw_model_api: str = None - auto_pair_openclaw: bool = False + auto_pair_openclaw: bool = True def _validate(image, options): diff --git a/tests/agentstudio_sandbox/test_web_ui.py b/tests/agentstudio_sandbox/test_web_ui.py index 0a6f8e2c..b76680b8 100644 --- a/tests/agentstudio_sandbox/test_web_ui.py +++ b/tests/agentstudio_sandbox/test_web_ui.py @@ -445,6 +445,49 @@ def prepare_local_preview(monkeypatch): return _web_ui +@pytest.mark.parametrize( + "image_name,options,expected", + [ + ("openclaw", None, True), + ("openclaw", {}, True), + ("openclaw", {"auto_pair_openclaw": False}, False), + ("openclaw", {"auto_pair_openclaw": True}, True), + ("deepseek-harness", None, False), + ], + ids=["default", "default-options", "disabled", "enabled", "dsh"], +) +def test_web_ui_pairing_defaults_and_explicit_override( + monkeypatch, image_name, options, expected +): + from dashscope.applications.agentstudio.sandbox.models import OfficialImage + from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient + + web_ui = prepare_local_preview(monkeypatch) + monkeypatch.setattr( + web_ui._bootstrap, + "prepare", + lambda *args: SimpleNamespace(openclaw=image_name == "openclaw"), + ) + approvals = [] + + def start_proxy(self, route, auto_pair): + approvals.append(auto_pair) + return "http://127.0.0.1:12345/__preview/entry" + + monkeypatch.setattr(web_ui._Resources, "start_proxy", start_proxy) + platform = FakePlatform() + preview = web_ui.open_web_ui( + SandboxesClient(platform), + platform, + OfficialImage(image_name), + None if options is None else web_ui.WebUiOptions(**options), + ) + try: + assert approvals == [expected] + finally: + preview.close() + + def test_fresh_preview_resolves_directory_and_releases_only_owned_resources( monkeypatch, ): From bd86d944bc6bd102d38c2eefcd743f9fb38b3b80 Mon Sep 17 00:00:00 2001 From: "guning.lt" Date: Wed, 2 Dec 2026 18:25:06 +0800 Subject: [PATCH 4/7] sandbox api --- dashscope/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dashscope/version.py b/dashscope/version.py index 553343b7..dba31bb2 100644 --- a/dashscope/version.py +++ b/dashscope/version.py @@ -1,4 +1,4 @@ # -*- coding: utf-8 -*- # Copyright (c) Alibaba, Inc. and its affiliates. -__version__ = "2.1.0.1" +__version__ = "2.1.4" From 0f2969e26ec52cf42c7d24b67b1a4f6e280eb362 Mon Sep 17 00:00:00 2001 From: "guning.lt" Date: Wed, 2 Dec 2026 18:28:42 +0800 Subject: [PATCH 5/7] sandbox api --- tests/agentstudio_sandbox/test_agents.py | 590 -------- tests/agentstudio_sandbox/test_client.py | 532 ------- tests/agentstudio_sandbox/test_resources.py | 1028 ------------- tests/agentstudio_sandbox/test_stream.py | 487 ------- tests/agentstudio_sandbox/test_web_ui.py | 1457 ------------------- 5 files changed, 4094 deletions(-) delete mode 100644 tests/agentstudio_sandbox/test_agents.py delete mode 100644 tests/agentstudio_sandbox/test_client.py delete mode 100644 tests/agentstudio_sandbox/test_resources.py delete mode 100644 tests/agentstudio_sandbox/test_stream.py delete mode 100644 tests/agentstudio_sandbox/test_web_ui.py diff --git a/tests/agentstudio_sandbox/test_agents.py b/tests/agentstudio_sandbox/test_agents.py deleted file mode 100644 index e84ebfd4..00000000 --- a/tests/agentstudio_sandbox/test_agents.py +++ /dev/null @@ -1,590 +0,0 @@ -"""Managed Agent protocol tests; all HTTP is local MockTransport traffic.""" - -import asyncio -import io -import json -import threading -import time - -import httpx -import pytest - -from dashscope.applications.agentstudio.sandbox.agents import ( - AgentHandle, - AgentsClient, - AsyncAgentHandle, - AsyncAgentsClient, -) -from dashscope.applications.agentstudio.sandbox.exceptions import ( - SandboxAPIError, - SandboxWaitTimeoutError, -) -from dashscope.applications.agentstudio.sandbox.models import ( - AgentInstanceInfo, - LaunchRequest, - ModelConfig, - OfficialImage, - UploadedFile, -) -from dashscope.applications.agentstudio.sandbox.transport import ( - AGENT, - AsyncTransport, - Transport, -) - - -def response(data, status=200): - return httpx.Response(status, json={"data": data}) - - -def instance(**extra): - return dict( - instance_id="ai_one", - state="READY", - harness_type="deepseek-harness", - image_name="deepseek-harness", - default_session_id="as_default", - **extra - ) - - -def uploaded(identifier="af_one", instance_id="ai_one", size=3): - return UploadedFile.from_dict( - dict( - file_id=identifier, - instance_id=instance_id, - name="hello.txt", - path="/home/user/hello.txt", - size_bytes=size, - ) - ) - - -def sync_client(handler, poll_interval=0.001): - pool = httpx.Client(transport=httpx.MockTransport(handler)) - transport = Transport( - "https://unit.test", - "platform-key", - http_client=pool, - poll_interval=poll_interval, - ) - return AgentsClient(transport), transport, pool - - -def test_launch_accept_wait_typed_handles_and_no_model_credentials_fallback(): - seen = [] - - def handler(request): - seen.append(request) - if request.url.path.startswith(AGENT): - assert request.headers["Authorization"] == "Bearer platform-key" - if request.method == "POST": - body = json.loads(request.content) - assert body["harness_type"] == "deepseek-harness" - assert "model_config" not in body - return response({"instance_id": "ai_one", "operation_id": "ao_launch"}, 202) - if "/operations/" in request.url.path: - return response( - dict(operation_id="ao_launch", instance_id="ai_one", status="SUCCEEDED") - ) - return response(instance()) - - agents, transport, pool = sync_client(handler) - try: - operation = agents.launch_async( - LaunchRequest(image=OfficialImage.DEEPSEEK_HARNESS) - ) - assert operation.instance_id == "ai_one" - assert operation.operation_id == "ao_launch" - agent = operation.wait(timeout=2) - assert agent.id == "ai_one" - assert agent.default_session.id == "as_default" - assert isinstance(agent.get_info(), AgentInstanceInfo) - assert len([r for r in seen if r.method == "POST"]) == 1 - transport.close() - assert pool.get("https://unit.test/borrowed-still-open").status_code == 200 - finally: - transport.close() - pool.close() - - -def test_template_reuse_does_not_send_image_and_explicit_model_key_only(): - seen = [] - - def handler(request): - seen.append(json.loads(request.content)) - return response({"instance_id": "ai_one", "operation_id": "ao_launch"}, 202) - - agents, transport, pool = sync_client(handler) - try: - agents.launch_async( - LaunchRequest( - image=OfficialImage.DEEPSEEK_HARNESS, - template_id="tpl_one", - model_config=ModelConfig(base_url="https://model.test/v1"), - ) - ) - assert seen[0]["template_id"] == "tpl_one" - assert "image_name" not in seen[0] - assert "api_key" not in seen[0]["model_config"] - assert seen[0]["model_config"]["model_id"] == "qwen3.7-plus" - finally: - transport.close() - pool.close() - - -def test_lists_preserve_typed_items_cursor_and_safe_query_encoding(): - seen = [] - - def handler(request): - seen.append(request) - if request.url.path.endswith("/instances"): - return response({"items": [instance()], "next_cursor": "next+ /?="}) - if request.url.path.endswith("/sessions"): - return response( - {"items": [{"session_id": "as_one", "instance_id": "ai_one"}]} - ) - return response( - { - "items": [ - { - "turn_id": "at_one", - "session_id": "as_one", - "instance_id": "ai_one", - "status": "RUNNING", - } - ] - } - ) - - agents, transport, pool = sync_client(handler) - try: - page = agents.list_instances(3, "cursor+ /?=") - assert isinstance(page.items[0], AgentInstanceInfo) - assert page.next_cursor == "next+ /?=" - assert seen[-1].url.params["cursor"] == "cursor+ /?=" - assert agents.list_sessions("ai_one").items[0].id == "as_one" - assert agents.session("as_one").list_turns().items[0].id == "at_one" - for limit in (0, 101, True, 1.5): - with pytest.raises(ValueError): - agents.list_instances(limit) - finally: - transport.close() - pool.close() - - -def test_prompt_files_are_unique_instance_bound_and_text_deadline_bounded(): - seen = [] - - def handler(request): - seen.append(json.loads(request.content)) - return response({"turn_id": "at_one", "status": "PENDING"}, 201) - - agents, transport, pool = sync_client(handler) - agent = AgentHandle( - transport, "ai_one", "as_one", AgentInstanceInfo.from_dict(instance()) - ) - try: - session = agent.default_session - turn = session.submit_with_files("continue", [uploaded()], deadline_seconds=300) - assert turn.id == "at_one" - assert seen == [ - { - "input": [{"type": "text", "text": "continue"}], - "attachment_ids": ["af_one"], - "deadline_seconds": 300, - } - ] - invalid_files = ( - [uploaded(), uploaded()], - [uploaded(instance_id="ai_other")], - [uploaded(str(i)) for i in range(17)], - ) - for files in invalid_files: - with pytest.raises(ValueError): - session.submit_with_files("hello", files) - for duration in (0, 3601, 1.5, True): - with pytest.raises(ValueError): - session.submit("hello", deadline_seconds=duration) - with pytest.raises(ValueError): - session.submit("好" * 350000) - assert len(seen) == 1 - finally: - transport.close() - pool.close() - - -class RecordingInput(io.BytesIO): - def __init__(self, data): - super().__init__(data) - self.read_sizes = [] - - def read(self, size=-1): - self.read_sizes.append(size) - assert size > 0, "upload must not buffer a stream with read()" - return super().read(size) - - -def test_upload_streaming_cap_filename_size_ownership_and_source_closure(tmp_path): - seen = [] - - def handler(request): - seen.append(request) - assert request.headers["Content-Type"] == "application/octet-stream" - return response( - dict( - file_id="af_one", - instance_id="ai_one", - name=request.url.params["name"], - path="/private/hello.txt", - size_bytes=len(request.content), - ) - ) - - agents, transport, pool = sync_client(handler) - agent = AgentHandle( - transport, - "ai_one", - "as_one", - AgentInstanceInfo.from_dict(instance(max_upload_bytes=10)), - ) - try: - source = RecordingInput(b"hello") - file = agent.upload("hello.txt", source) - assert file.id == "af_one" and file.instance_id == agent.id - assert source.closed and all(size > 0 for size in source.read_sizes) - path = tmp_path / "local.txt" - path.write_bytes(b"abc") - assert agent.upload(path).size_bytes == 3 - assert seen[-1].headers["Content-Length"] == "3" - for name, data, size in [ - ("too-big", b"x" * 11, 11), - ("../bad", b"a", 1), - ("too-big-unknown", b"x" * 11, -1), - ("bad-size", b"abc", 2), - ("short-size", b"ab", 3), - ]: - source = RecordingInput(data) - with pytest.raises((ValueError, SandboxAPIError)): - agent.upload(name, source, size) - assert source.closed - source = RecordingInput(b"abc") - with pytest.raises(ValueError): - agent.upload("empty", source, 0) - assert source.closed - finally: - transport.close() - pool.close() - - -def test_failed_unknown_operation_and_turn_cancellation_request_semantics(): - status = ["RUNNING", "CANCELLED"] - - def handler(request): - if "/operations/" in request.url.path: - return response( - { - "operation_id": "ao_one", - "instance_id": "ai_one", - "status": "UNKNOWN", - "error": {"code": "NATIVE_DISCONNECTED", "message": "unconfirmed"}, - } - ) - if request.method == "POST": - return response({"turn_id": "at_one", "status": "CANCELLING"}) - return response({"turn_id": "at_one", "status": status.pop(0), "output": []}) - - agents, transport, pool = sync_client(handler) - try: - with pytest.raises(SandboxAPIError) as error: - agents.operation("ao_one").wait(1) - assert error.value.code == "NATIVE_DISCONNECTED" - assert error.value.outcome_unknown - assert error.value.resource_id == "ao_one" - turn = agents.turn("at_one") - assert turn.cancel().status == "CANCELLING" - assert turn.wait(1).status == "CANCELLED" - finally: - transport.close() - pool.close() - - -def test_polling_budgets_each_request_and_timeout_preserves_resource_id(): - budgets = [] - - def handler(request): - budgets.append(request.extensions["timeout"]["read"]) - time.sleep(0.004) - return response({"operation_id": "ao_slow", "status": "PENDING"}) - - agents, transport, pool = sync_client(handler) - try: - with pytest.raises(SandboxWaitTimeoutError) as error: - agents.operation("ao_slow").wait(0.025) - assert error.value.resource_id == "ao_slow" - assert error.value.status == "PENDING" - assert len(budgets) >= 2 and budgets[-1] < budgets[0] <= 0.025 - finally: - transport.close() - pool.close() - - -def test_async_launch_submit_upload_poll_and_release_parity(): - async def run(): - seen = [] - - async def handler(request): - seen.append(request) - path = request.url.path - if request.method == "POST" and path.endswith("/instances"): - assert "model_config" not in json.loads(request.content) - return response({"instance_id": "ai_one", "operation_id": "ao_launch"}) - if "/operations/" in path: - return response( - { - "operation_id": "ao_launch", - "instance_id": "ai_one", - "status": "SUCCEEDED", - } - ) - if path.endswith("/sessions/as_default/turns"): - if request.method == "POST": - return response({"turn_id": "at_one"}) - return response( - { - "items": [ - { - "turn_id": "at_one", - "session_id": "as_default", - "instance_id": "ai_one", - "status": "RUNNING", - } - ] - } - ) - if path.endswith("/files"): - return response( - dict( - file_id="af_one", - instance_id="ai_one", - name="upload.txt", - path="/private/upload.txt", - size_bytes=len(request.content), - ) - ) - if "/turns/" in path: - return response( - { - "turn_id": "at_one", - "status": "SUCCEEDED", - "output": [{"type": "text", "text": "hello"}], - } - ) - if request.method == "DELETE": - return response({"operation_id": "ao_launch"}) - return response(instance(max_upload_bytes=10)) - - pool = httpx.AsyncClient(transport=httpx.MockTransport(handler)) - transport = AsyncTransport( - "https://unit.test", "platform-key", http_client=pool - ) - agents = AsyncAgentsClient(transport) - try: - launch = await agents.launch_async( - LaunchRequest(image=OfficialImage.DEEPSEEK_HARNESS) - ) - agent = await launch.wait(2) - source = RecordingInput(b"abc") - assert (await agent.upload("upload.txt", source)).size_bytes == 3 - assert source.closed - turn = await agent.default_session.submit_with_files("hello", [uploaded()]) - assert (await turn.wait()).text == "hello" - assert (await agent.default_session.list_turns()).items[0].id == turn.id - assert (await agent.release()).id == "ao_launch" - assert ( - sum( - r.method == "POST" and r.url.path.endswith("/instances") - for r in seen - ) - == 1 - ) - await transport.aclose() - assert (await pool.get("https://unit.test/still-open")).status_code == 200 - finally: - await transport.aclose() - await pool.aclose() - - asyncio.run(run()) - - -@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) -@pytest.mark.parametrize("source_kind", ["path", "known-stream", "unknown-stream"]) -def test_empty_upload_sources_are_valid_and_streams_close( - tmp_path, asynchronous, source_kind -): - seen = [] - - def handler(request): - seen.append(request) - assert request.content == b"" - if source_kind == "unknown-stream": - assert "Content-Length" not in request.headers - else: - assert request.headers["Content-Length"] == "0" - return response( - dict( - file_id="af_empty", - instance_id="ai_one", - name="empty.txt", - path="/private/empty.txt", - size_bytes=0, - ) - ) - - path = tmp_path / "empty.txt" - path.write_bytes(b"") - source = RecordingInput(b"") - - def upload_arguments(): - if source_kind == "path": - return (path,) - return ("empty.txt", source, 0 if source_kind == "known-stream" else -1) - - if asynchronous: - - async def run(): - async with httpx.AsyncClient( - transport=httpx.MockTransport(handler) - ) as pool: - transport = AsyncTransport( - "https://unit.test", "platform-key", http_client=pool - ) - agent = AsyncAgentHandle( - transport, - "ai_one", - "as_one", - AgentInstanceInfo.from_dict(instance(max_upload_bytes=10)), - ) - try: - return await agent.upload(*upload_arguments()) - finally: - await transport.aclose() - - file = asyncio.run(run()) - else: - _, transport, pool = sync_client(handler) - agent = AgentHandle( - transport, - "ai_one", - "as_one", - AgentInstanceInfo.from_dict(instance(max_upload_bytes=10)), - ) - try: - file = agent.upload(*upload_arguments()) - finally: - transport.close() - pool.close() - assert file.size_bytes == 0 and file.instance_id == "ai_one" - assert len(seen) == 1 - if source_kind != "path": - assert source.closed - - -@pytest.mark.parametrize("contents", [b"", b"x"], ids=["empty", "nonempty"]) -def test_async_zero_length_upload_reads_off_event_loop(contents): - reads = [] - - class ThreadRecordingInput(RecordingInput): - def read(self, size=-1): - reads.append(threading.get_ident()) - return super().read(size) - - source = ThreadRecordingInput(contents) - - async def handler(request): - assert await request.aread() == b"" - assert request.headers["Content-Length"] == "0" - return response( - dict( - file_id="af_empty", - instance_id="ai_one", - name="empty.txt", - path="/private/empty.txt", - size_bytes=0, - ) - ) - - async def run(): - loop_thread = threading.get_ident() - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as pool: - transport = AsyncTransport( - "https://unit.test", "platform-key", http_client=pool - ) - agent = AsyncAgentHandle( - transport, - "ai_one", - "as_one", - AgentInstanceInfo.from_dict(instance(max_upload_bytes=10)), - ) - try: - if contents: - with pytest.raises(ValueError): - await agent.upload("empty.txt", source, 0) - else: - assert (await agent.upload("empty.txt", source, 0)).size_bytes == 0 - finally: - await transport.aclose() - assert reads and all(identifier != loop_thread for identifier in reads) - - asyncio.run(run()) - assert source.closed - - -@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) -def test_nonempty_stream_declared_empty_is_rejected_and_closed(asynchronous): - seen = [] - - def handler(request): - seen.append(request) - return response({}) - - source = RecordingInput(b"x") - if asynchronous: - - async def run(): - async with httpx.AsyncClient( - transport=httpx.MockTransport(handler) - ) as pool: - transport = AsyncTransport( - "https://unit.test", "platform-key", http_client=pool - ) - agent = AsyncAgentHandle( - transport, - "ai_one", - "as_one", - AgentInstanceInfo.from_dict(instance(max_upload_bytes=10)), - ) - try: - with pytest.raises(ValueError): - await agent.upload("empty.txt", source, 0) - finally: - await transport.aclose() - - asyncio.run(run()) - else: - _, transport, pool = sync_client(handler) - agent = AgentHandle( - transport, - "ai_one", - "as_one", - AgentInstanceInfo.from_dict(instance(max_upload_bytes=10)), - ) - try: - with pytest.raises(ValueError): - agent.upload("empty.txt", source, 0) - finally: - transport.close() - pool.close() - assert not seen - assert source.read_sizes - assert source.closed diff --git a/tests/agentstudio_sandbox/test_client.py b/tests/agentstudio_sandbox/test_client.py deleted file mode 100644 index 33ed70d3..00000000 --- a/tests/agentstudio_sandbox/test_client.py +++ /dev/null @@ -1,532 +0,0 @@ -# -*- coding: utf-8 -*- -"""Shared client boundaries and non-invasive AgentStudio integration.""" - -import httpx -import pytest - -from dashscope.applications.agentstudio.sandbox import ( - AsyncSandboxClient, - LaunchRequest, - ModelConfig, - OfficialImage, - SandboxAPIError, - SandboxClient, - SandboxConnection, - SandboxCreateRequest, - TemplateInfo, - TemplateUpdateRequest, -) - - -@pytest.mark.parametrize( - "suffix", - [ - "", - "/compatible-mode/v1", - "/api/v1/agentstudio", - "/api/v1/agentstudio/sandbox", - "/api/v1/agentstudio/agent-runtime", - ], -) -def test_four_facets_share_fixed_bearer_and_proxy_base(suffix): - calls = [] - - def handle(request): - calls.append(request) - if request.url.path.endswith("/instances"): - return httpx.Response(200, json={"data": {"items": []}}) - if request.url.path.endswith("/files/file_a"): - return httpx.Response(200, json={"id": "file_a"}) - return httpx.Response(200, json=[]) - - pool = httpx.Client( - transport=httpx.MockTransport(handle), - headers={"X-DashScope-Workspace": "not-forwarded"}, - ) - with SandboxClient( - base_url="https://unit.test/proxy" + suffix, - api_key="fixed-key", - http_client=pool, - ) as client: - client.templates.list() - client.sandboxes.list() - client.agents.list_instances() - client.template_files.get("file_a") - assert all(r.headers["Authorization"] == "Bearer fixed-key" for r in calls) - assert all(r.url.path.startswith("/proxy/api/v1/agentstudio/") for r in calls) - assert all("X-DashScope-Workspace" not in r.headers for r in calls) - assert not pool.is_closed - pool.close() - - -@pytest.mark.parametrize( - "url", - [ - "https://user:pass@unit.test", - "https://unit.test?token=x", - "https://unit.test/#frag", - "file:///tmp/file", - "https://unit.test:0", - ], -) -def test_invalid_base_urls_rejected(url): - with pytest.raises(ValueError): - SandboxClient(base_url=url, api_key="key") - - -@pytest.mark.parametrize("key", [None, "", " ", "x\nheader", "x,y", "密钥", "x" * 8193]) -def test_invalid_key_error_does_not_reveal_credentials(key): - with pytest.raises(ValueError, match="Invalid API key") as error: - SandboxClient(base_url="https://unit.test", api_key=key) - assert str(error.value) == "Invalid API key" - - -def test_model_credentials_never_fall_back_to_platform_config(): - request = LaunchRequest(image=OfficialImage.DEEPSEEK_HARNESS) - assert "model_config" not in request.to_dict() - configured = LaunchRequest( - image=OfficialImage.OPENCLAW, - model_config=ModelConfig(base_url="https://model.test/v1"), - ) - assert configured.to_dict()["model_config"] == { - "base_url": "https://model.test/v1", - "model_id": "qwen3.7-plus", - } - assert LaunchRequest( - image=OfficialImage.OPENCLAW, template_id="tpl_a" - ).to_dict() == {"harness_type": "openclaw", "template_id": "tpl_a"} - - -def test_model_secrets_hidden_in_repr_and_validation_messages(): - secret = "synthetic-private-model-key" - model = ModelConfig(base_url="https://model.test/v1", api_key=secret) - assert secret not in repr(model) and secret not in str(model) - with pytest.raises(ValueError) as error: - ModelConfig(api_key=secret) - assert secret not in str(error.value) - connection = SandboxConnection(envdAccessToken=secret, trafficAccessToken=secret) - assert secret not in repr(connection) and secret not in str(connection) - - -def test_updates_keep_explicit_empty_collections_but_not_unset_fields(): - assert TemplateUpdateRequest(env_config={}).to_dict() == {"envConfig": {}} - assert SandboxCreateRequest(template_id="tpl_a").to_dict() == { - "templateID": "tpl_a" - } - info = TemplateInfo.from_dict( - { - "templateID": "tpl_a", - "names": ["first"], - "builds": [{"buildID": "b1", "status": "READY"}], - } - ) - assert info.name == "first" and info.build_id == "b1" - - -def test_unknown_write_outcome_is_not_retried(): - attempts = [] - - def handle(request): - attempts.append(request) - raise httpx.ReadTimeout("do not echo credentials", request=request) - - pool = httpx.Client(transport=httpx.MockTransport(handle)) - with SandboxClient( - base_url="https://unit.test", api_key="fixed-key", http_client=pool - ) as client: - with pytest.raises(SandboxAPIError) as error: - client.agents.launch_async(LaunchRequest(image=OfficialImage.OPENCLAW)) - assert error.value.outcome_unknown - assert len(attempts) == 1 - pool.close() - - -def test_main_agentstudio_sandbox_mount_is_lazy_and_shares_pool(): - from dashscope import Client - - pool = httpx.Client( - transport=httpx.MockTransport(lambda r: httpx.Response(200, json=[])) - ) - with Client( - base_url="https://unit.test", api_key="key", http_client=pool - ) as client: - studio = client.agentstudio - sandbox = studio.sandbox - assert sandbox is studio.sandbox - assert sandbox._transport._client is pool - sandbox.templates.list() - assert not pool.is_closed - pool.close() - - -@pytest.mark.asyncio -async def test_async_mount_shares_pool_and_leaves_existing_api_usable(): - from dashscope import AsyncClient - - pool = httpx.AsyncClient( - transport=httpx.MockTransport(lambda r: httpx.Response(200, json=[])) - ) - async with AsyncClient( - base_url="https://unit.test", api_key="key", http_client=pool - ) as client: - sandbox = client.agentstudio.sandbox - assert isinstance(sandbox, AsyncSandboxClient) - assert sandbox._transport._client is pool - await sandbox.templates.list() - assert not pool.is_closed - await pool.aclose() - - -def test_legacy_deep_import_is_the_same_new_module(): - from dashscope.agentstudio.sandbox import SandboxClient as LegacyImport - - assert LegacyImport is SandboxClient - - -def test_template_response_accepts_unconfigured_console_fields_and_old_mounts(): - info = TemplateInfo.from_dict( - { - "templateID": "tpl_old", - "envConfig": None, - "mntConfig": None, - "builds": None, - "version": 1, - } - ) - assert info.env_config == {} and info.mounts == [] and info.builds == [] - info = TemplateInfo.from_dict( - {"templateID": "tpl_old", "mntConfig": [{"mountPath": "/opt/data/a.txt"}]} - ) - assert info.mounts[0].mount_path == "/opt/data/a.txt" - - -def test_sandbox_response_accepts_unconfigured_metadata(): - from dashscope.applications.agentstudio.sandbox import SandboxInfo - - assert ( - SandboxInfo.from_dict({"sandboxID": "sbx_a", "metadata": None}).metadata == {} - ) - - -def test_bad_nested_template_response_is_a_protocol_error(): - with pytest.raises(SandboxAPIError) as error: - TemplateInfo.from_dict({"templateID": "tpl_a", "builds": [1]}) - assert error.value.code == "INVALID_RESPONSE" - - -def test_parent_owned_pool_closes_even_if_preview_cleanup_fails(): - from dashscope.applications.agentstudio.client import Client - - class BrokenPreview: - def close(self): - raise RuntimeError("cleanup failed") - - client = Client(base_url="https://unit.test", api_key="key") - client._sandbox = BrokenPreview() - with pytest.raises(RuntimeError, match="cleanup failed"): - client.close() - assert client.transport._client.is_closed - - -@pytest.mark.asyncio -async def test_async_parent_pool_closes_when_preview_cleanup_fails(): - from dashscope.applications.agentstudio.client import AsyncClient - - class BrokenPreview: - async def aclose(self): - raise RuntimeError("cleanup failed") - - client = AsyncClient(base_url="https://unit.test", api_key="key") - client._sandbox = BrokenPreview() - with pytest.raises(RuntimeError, match="cleanup failed"): - await client.aclose() - assert client.transport._client.is_closed - - -@pytest.fixture -def mounted_preview_platform(monkeypatch): - from types import SimpleNamespace - from dashscope.applications.agentstudio.sandbox import web_ui as _web_ui - - calls = [] - - def reply(request): - calls.append((request.method, request.url.path)) - path = request.url.path - if path.endswith("/template-config"): - value = { - "data": { - "images": [], - "resource_configs": [], - "default_compute": {"cpu": 1, "memory_mib": 2048}, - } - } - elif "/images/" in path: - value = { - "imageName": "deepseek-harness", - "imageUrl": "registry.test/dsh:v1", - } - elif path.endswith("/v3/templates"): - value = {"templateID": "tpl_preview", "buildID": "build_one"} - elif path.endswith("/status"): - value = {"status": "READY"} - elif path.endswith("/sandboxes") or path.endswith("/connect"): - value = {"sandboxID": "sbx_preview", "templateID": "tpl_preview"} - elif request.method == "DELETE": - return httpx.Response(204) - else: - raise AssertionError("Unexpected native preview API") - return httpx.Response(200, json=value) - - sync_type, async_type = httpx.Client, httpx.AsyncClient - - def sync_pool(**kwargs): - return sync_type(transport=httpx.MockTransport(reply), **kwargs) - - def async_pool(**kwargs): - return async_type(transport=httpx.MockTransport(reply), **kwargs) - - monkeypatch.setattr(httpx, "Client", sync_pool) - monkeypatch.setattr(httpx, "AsyncClient", async_pool) - monkeypatch.setattr(_web_ui, "_check_node", lambda: None) - monkeypatch.setattr( - _web_ui._bootstrap, "prepare", lambda *args: SimpleNamespace(openclaw=False) - ) - monkeypatch.setattr( - _web_ui._Resources, - "start_proxy", - lambda *args: "http://127.0.0.1:12345/__preview/entry", - ) - return calls - - -def test_root_owned_pool_remains_open_until_mounted_preview_is_released( - mounted_preview_platform, -): - from dashscope import Client - - client = Client(base_url="https://unit.test/api/v1", api_key="key") - pool = client.transport.http_client - assert client.transport._owns_client - try: - with client: - preview = client.agentstudio.sandbox.sandboxes.open_web_ui( - OfficialImage.DEEPSEEK_HARNESS - ) - assert preview._resources._closed - assert pool.is_closed - assert [ - path for method, path in mounted_preview_platform if method == "DELETE" - ] == [ - "/api/v1/agentstudio/sandbox/sandboxes/sbx_preview", - "/api/v1/agentstudio/sandbox/templates/tpl_preview", - ] - finally: - client.close() - - -@pytest.mark.asyncio -async def test_async_root_keeps_pool_open_during_real_mounted_preview_cleanup( - mounted_preview_platform, - monkeypatch, -): - from dashscope import AsyncClient - - client = AsyncClient(base_url="https://unit.test/api/v1", api_key="key") - pool = client.transport.http_client - assert client.transport._owns_client - preview = None - try: - async with client: - preview = await client.agentstudio.sandbox.sandboxes.open_web_ui( - OfficialImage.DEEPSEEK_HARNESS - ) - close_preview = preview.aclose - - async def cleanup_before_root_pool(): - assert not pool.is_closed, "Root pool closed before mounted resources" - await close_preview() - - monkeypatch.setattr(preview, "aclose", cleanup_before_root_pool) - assert preview._resources._closed - assert pool.is_closed - assert [ - path for method, path in mounted_preview_platform if method == "DELETE" - ] == [ - "/api/v1/agentstudio/sandbox/sandboxes/sbx_preview", - "/api/v1/agentstudio/sandbox/templates/tpl_preview", - ] - finally: - if preview is not None: - await close_preview() - await client.aclose() - - -def test_root_owned_pool_closes_if_mounted_resource_cleanup_raises(): - from dashscope import Client - - class BrokenPreview: - def close(self): - raise RuntimeError("preview cleanup failed") - - client = Client(base_url="https://unit.test/api/v1", api_key="key") - pool = client.transport.http_client - client.agentstudio._sandbox = BrokenPreview() - with pytest.raises(RuntimeError, match="preview cleanup failed"): - client.close() - assert pool.is_closed - - -@pytest.mark.asyncio -async def test_async_root_owned_pool_closes_if_mounted_resource_cleanup_raises(): - from dashscope import AsyncClient - - class BrokenPreview: - async def aclose(self): - raise RuntimeError("preview cleanup failed") - - client = AsyncClient(base_url="https://unit.test/api/v1", api_key="key") - pool = client.transport.http_client - client.agentstudio._sandbox = BrokenPreview() - with pytest.raises(RuntimeError, match="preview cleanup failed"): - await client.aclose() - assert pool.is_closed - - -@pytest.mark.parametrize("asynchronous", [False, True]) -@pytest.mark.parametrize( - "base_path", - [ - "", - "/api/v1", - "/compatible-mode/v1", - "/api/v1/agentstudio", - "/proxy", - "/proxy/api/v1", - "/proxy/compatible-mode/v1", - "/proxy/api/v1/agentstudio", - ], -) -def test_root_sandbox_mount_derives_exact_api_paths(asynchronous, base_path): - import asyncio - from dashscope import AsyncClient, Client - - calls = [] - - def handle(request): - calls.append(request.url.path) - return httpx.Response( - 200, - json=( - {"data": {"items": []}} - if request.url.path.endswith("/instances") - else [] - ), - ) - - prefix = "/proxy" if base_path.startswith("/proxy") else "" - expected = [ - prefix + "/api/v1/agentstudio/sandbox/v2/templates", - prefix + "/api/v1/agentstudio/agent-runtime/instances", - ] - if not asynchronous: - pool = httpx.Client(transport=httpx.MockTransport(handle)) - try: - with Client( - base_url="https://unit.test" + base_path, - api_key="key", - http_client=pool, - ) as client: - sandbox = client.agentstudio.sandbox - sandbox.templates.list() - sandbox.agents.list_instances() - assert calls == expected - assert not pool.is_closed - finally: - pool.close() - return - - async def run(): - pool = httpx.AsyncClient(transport=httpx.MockTransport(handle)) - try: - async with AsyncClient( - base_url="https://unit.test" + base_path, - api_key="key", - http_client=pool, - ) as client: - sandbox = client.agentstudio.sandbox - await sandbox.templates.list() - await sandbox.agents.list_instances() - assert calls == expected - assert not pool.is_closed - finally: - await pool.aclose() - - asyncio.run(run()) - - -@pytest.mark.parametrize("asynchronous", [False, True]) -def test_real_socket_response_body_read_timeout(asynchronous): - """A stalled response body must time out without issuing another request.""" - import asyncio - import threading - from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer - from dashscope.applications.agentstudio.sandbox import AsyncSandboxClient - - requests = [] - release = threading.Event() - - class Handler(BaseHTTPRequestHandler): - def do_GET(self): - requests.append(self.path) - self.send_response(200) - self.send_header("Content-Type", "application/json") - self.send_header("Content-Length", "2") - self.end_headers() - release.wait(2) - try: - self.wfile.write(b"[]") - except (BrokenPipeError, ConnectionResetError): - pass - - def log_message(self, *args): - pass - - server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) - server.daemon_threads = True - worker = threading.Thread( - target=lambda: server.serve_forever(poll_interval=0.01), daemon=True - ) - worker.start() - base_url = "http://127.0.0.1:" + str(server.server_port) - try: - if asynchronous: - - async def run(): - async with httpx.AsyncClient(trust_env=False) as pool: - async with AsyncSandboxClient( - base_url=base_url, - api_key="test-key", - timeout=0.1, - http_client=pool, - ) as client: - with pytest.raises(SandboxAPIError) as error: - await client.templates.list() - return error - - error = asyncio.run(run()) - else: - with httpx.Client(trust_env=False) as pool: - with SandboxClient( - base_url=base_url, api_key="test-key", timeout=0.1, http_client=pool - ) as client: - with pytest.raises(SandboxAPIError) as error: - client.templates.list() - assert error.value.code == "REQUEST_TIMEOUT" - assert not error.value.outcome_unknown - assert len(requests) == 1 - finally: - release.set() - server.shutdown() - server.server_close() - worker.join(timeout=2) diff --git a/tests/agentstudio_sandbox/test_resources.py b/tests/agentstudio_sandbox/test_resources.py deleted file mode 100644 index f6ff6b3f..00000000 --- a/tests/agentstudio_sandbox/test_resources.py +++ /dev/null @@ -1,1028 +0,0 @@ -"""Ordinary sandbox boundaries, template resolution, and file transfer behavior.""" - -import asyncio -import importlib -import json - -import httpx -import pytest - -PREFIX = "/api/v1/agentstudio/sandbox" -FILES = "/api/v1/agentstudio/files" - - -def modules(): - base = "dashscope.applications.agentstudio.sandbox." - return tuple( - importlib.import_module(base + name) - for name in ( - "models", - "transport", - "templates", - "sandboxes", - "template_files", - "exceptions", - ) - ) - - -def sync_transport(handler): - _, transport, *_ = modules() - return transport.Transport( - "https://platform.test", - "platform-key", - poll_interval=0.001, - http_client=httpx.Client(transport=httpx.MockTransport(handler)), - ) - - -def test_official_template_resolves_directory_before_create(): - models, _, templates, *_ = modules() - requests = [] - - def handler(request): - requests.append(request) - if request.method == "GET": - assert request.url.path == PREFIX + "/images/browser" - assert request.url.params["imageUrl"] == "registry/browser:1.2" - return httpx.Response( - 200, json={"imageName": "browser", "imageUrl": "registry/browser:1.2"} - ) - assert request.url.path == PREFIX + "/v3/templates" - assert json.loads(request.content) == { - "name": "browser-template", - "cpuCount": 2, - "memoryMB": 4096, - "fromImage": "registry/browser:1.2", - "imageName": "browser", - } - return httpx.Response( - 200, - json={ - "templateID": "t1", - "templateName": "browser-template", - "buildID": "b1", - }, - ) - - result = templates.TemplatesClient(sync_transport(handler)).create( - models.TemplateCreateRequest( - name="browser-template", - image=models.OfficialImage.BROWSER, - from_image="registry/browser:1.2", - cpu_count=2, - memory_mb=4096, - ) - ) - assert result.id == "t1" - assert len(requests) == 2 - - -def test_ambiguous_directory_failure_never_creates_template(): - models, _, templates, *_, errors = modules() - methods = [] - - def handler(request): - methods.append(request.method) - return httpx.Response( - 409, - json={ - "code": "IMAGE_VERSION_AMBIGUOUS", - "message": "Select exact image URL", - }, - ) - - with pytest.raises(errors.SandboxAPIError): - templates.TemplatesClient(sync_transport(handler)).create( - models.TemplateCreateRequest( - name="browser-template", - image=models.OfficialImage.BROWSER, - cpu_count=2, - memory_mb=4096, - ) - ) - assert methods == ["GET"] - - -def test_mismatched_directory_response_never_creates_template(): - models, _, templates, *_, errors = modules() - methods = [] - - def handler(request): - methods.append(request.method) - return httpx.Response( - 200, json={"imageName": "all-in-one", "imageUrl": "registry/other:1"} - ) - - with pytest.raises(errors.SandboxAPIError) as failure: - templates.TemplatesClient(sync_transport(handler)).create( - models.TemplateCreateRequest( - name="browser-template", - image=models.OfficialImage.BROWSER, - cpu_count=2, - memory_mb=4096, - ) - ) - assert failure.value.code == "INVALID_RESPONSE" - assert methods == ["GET"] - - -def test_template_crud_update_preserves_explicit_empty_fields(): - models, _, templates, *_ = modules() - observed = [] - - def handler(request): - observed.append((request.method, request.url.path, dict(request.url.params))) - if request.method == "PUT": - assert json.loads(request.content) == { - "description": "", - "envConfig": {}, - "mntConfig": [], - } - if request.url.path.endswith("/v2/templates"): - return httpx.Response( - 200, json=[{"templateID": "t1", "templateName": "one"}] - ) - if request.method == "DELETE": - return httpx.Response(204) - return httpx.Response(200, json={"templateID": "t1", "templateName": "one"}) - - client = templates.TemplatesClient(sync_transport(handler)) - assert client.list(limit=7, page_no=2)[0].id == "t1" - assert client.get("t1").id == "t1" - assert ( - client.update( - "t1", models.TemplateUpdateRequest(description="", env_config={}, mounts=[]) - ).id - == "t1" - ) - client.delete("t1") - assert observed == [ - ("GET", PREFIX + "/v2/templates", {"limit": "7", "pageNo": "2"}), - ("GET", PREFIX + "/templates/t1", {}), - ("PUT", PREFIX + "/templates/t1", {}), - ("DELETE", PREFIX + "/templates/t1", {}), - ] - - -@pytest.mark.parametrize("status", ["ERROR", "failed", "CANCELLED", "canceled"]) -def test_build_wait_stops_on_failure_preserving_reason(status): - _, _, templates, *_, errors = modules() - - def handler(request): - assert request.url.path == PREFIX + "/templates/t1/builds/b1/status" - return httpx.Response( - 200, - json={ - "templateID": "t1", - "buildID": "b1", - "status": status, - "reason": {"message": "image failed"}, - "logs": ["line"], - }, - ) - - with pytest.raises(errors.SandboxAPIError) as failure: - templates.TemplatesClient(sync_transport(handler)).wait_ready( - "t1", "b1", timeout=0.1 - ) - assert failure.value.code == "TEMPLATE_BUILD_FAILED" - assert failure.value.body["reason"] == {"message": "image failed"} - - -def test_build_wait_ready_and_total_deadline(): - _, _, templates, *_, errors = modules() - statuses = iter(["BUILDING", "ready"]) - - def handler(request): - return httpx.Response( - 200, json={"templateID": "t1", "buildID": "b1", "status": next(statuses)} - ) - - assert ( - templates.TemplatesClient(sync_transport(handler)) - .wait_ready("t1", "b1", timeout=1) - .status - == "ready" - ) - pending = sync_transport( - lambda request: httpx.Response( - 200, json={"templateID": "t1", "buildID": "b1", "status": "BUILDING"} - ) - ) - with pytest.raises(errors.SandboxWaitTimeoutError) as failure: - templates.TemplatesClient(pending).wait_ready("t1", "b1", timeout=0.005) - assert failure.value.resource_id == "t1" - assert failure.value.status == "BUILDING" - - -def test_sandbox_handles_follow_public_id_and_refresh_connection(): - models, _, _, sandboxes, *_ = modules() - observed = [] - - def handler(request): - body = json.loads(request.content) if request.content else None - observed.append( - (request.method, request.url.path, body, dict(request.url.params)) - ) - if request.url.path.endswith("/v2/sandboxes"): - return httpx.Response( - 200, json=[{"id": "database-id", "sandboxID": "s1", "templateID": "t1"}] - ) - if request.method == "DELETE" or request.url.path.endswith("/pause"): - return httpx.Response(204) - return httpx.Response( - 200, - json={ - "id": "database-id", - "sandboxID": "s1", - "templateID": "t1", - "envdUrl": "https://envd.test", - "envdAccessToken": "private-token", - }, - ) - - client = sandboxes.SandboxesClient(sync_transport(handler)) - handle = client.create(models.SandboxCreateRequest(template_id="t1", timeout=300)) - assert handle.id == "s1" - assert handle.sandbox_id == "s1" - assert handle.template_id == "t1" - assert handle.get().id == "s1" - assert handle.connection.envd_url == "https://envd.test" - assert handle.connect() is handle - handle.pause() - assert handle.resume(models.ConnectionOptions(timeout=600)) is handle - assert client.connect("s1").id == "s1" - assert client.resume("s1").id == "s1" - assert ( - client.list(template_id="t1", sandbox_id="s1", state="running", limit=7)[0].id - == "s1" - ) - handle.release() - assert ( - "POST", - PREFIX + "/sandboxes", - {"templateID": "t1", "timeout": 300}, - {}, - ) in observed - assert ("POST", PREFIX + "/sandboxes/s1/connect", {}, {}) in observed - assert ("POST", PREFIX + "/sandboxes/s1/resume", {"timeout": 600}, {}) in observed - assert ("POST", PREFIX + "/sandboxes/s1/resume", {}, {}) in observed - assert ( - "GET", - PREFIX + "/v2/sandboxes", - None, - {"templateID": "t1", "sandboxID": "s1", "state": "running", "limit": "7"}, - ) in observed - assert observed[-1][:2] == ("DELETE", PREFIX + "/sandboxes/s1") - - -@pytest.mark.parametrize("value", [0, -1, True, 1.25]) -def test_lifetime_requires_positive_whole_seconds(value): - models, *_ = modules() - with pytest.raises(ValueError): - models.ConnectionOptions(timeout=value) - with pytest.raises(ValueError): - models.SandboxCreateRequest(template_id="t1", timeout=value) - - -def test_template_file_upload_streaming_signed_and_complete(tmp_path): - models, _, _, _, files, _ = modules() - source = tmp_path / "100% ready.txt" - source.write_bytes(b"hello file") - observed = [] - - def handler(request): - observed.append(request) - if request.method == "POST" and request.headers.get( - "content-type", "" - ).startswith("multipart/"): - assert b'name="source"\r\n\r\nsandbox_template' in request.content - assert b'filename="100% ready.txt"' in request.content - assert b"hello file" in request.content - return httpx.Response( - 200, json={"id": "f1", "filename": source.name, "status": "checking"} - ) - if request.url.path.endswith("/complete"): - assert not request.content - return httpx.Response(200, json={"id": "f1", "status": "checking"}) - if request.method == "POST": - assert json.loads(request.content) == { - "filename": source.name, - "size_bytes": 10, - "source": "sandbox_template", - } - return httpx.Response( - 200, - json={ - "id": "f1", - "status": "uploading", - "upload_url": "https://storage.test/upload?signature=private", - }, - ) - return httpx.Response(200, json={"id": "f1", "status": "available"}) - - client = files.TemplateFilesClient(sync_transport(handler)) - assert client.upload(source).status == "checking" - ticket = client.prepare_upload( - models.UploadRequest(filename=source.name, size_bytes=10) - ) - assert client.complete(ticket.id).status == "checking" - assert client.get("f1").status == "available" - assert client.wait_available("f1", timeout=1).status == "available" - client.delete("f1") - assert observed[-1].method == "DELETE" - assert observed[-1].url.path == FILES + "/f1" - - -def test_signed_upload_does_not_send_platform_credentials_or_follow_redirects(tmp_path): - models, transport, _, _, files, errors = modules() - source = tmp_path / "file.txt" - source.write_bytes(b"content") - observed = [] - - def handler(request): - observed.append(request) - assert request.headers.get("authorization") is None - assert request.headers.get("cookie") is None - assert request.content == b"content" - return httpx.Response(307, headers={"Location": "https://other.test/leak"}) - - pool = httpx.Client( - transport=httpx.MockTransport(handler), - headers={"Authorization": "Bearer platform-key"}, - cookies={"session": "private"}, - follow_redirects=True, - ) - client = files.TemplateFilesClient( - transport.Transport("https://platform.test", "platform-key", http_client=pool) - ) - with pytest.raises(errors.SandboxAPIError): - client.upload_content( - models.UploadTicket( - id="f1", - status="uploading", - upload_url="https://storage.test/upload?signature=private", - ), - source, - ) - assert len(observed) == 1 - - -def test_download_replaces_atomically_and_preserves_target_on_stream_error(tmp_path): - _, _, _, _, files, _ = modules() - target = tmp_path / "result.bin" - target.write_bytes(b"old") - - class BrokenStream(httpx.SyncByteStream): - def __iter__(self): - yield b"partial" - raise httpx.ReadError("interrupted") - - client = files.TemplateFilesClient( - sync_transport(lambda request: httpx.Response(200, stream=BrokenStream())) - ) - with pytest.raises(Exception): - client.download("f1", target) - assert target.read_bytes() == b"old" - assert list(tmp_path.iterdir()) == [target] - client = files.TemplateFilesClient( - sync_transport(lambda request: httpx.Response(200, content=b"new\x00bytes")) - ) - assert client.download("f1", target) == target - assert target.read_bytes() == b"new\x00bytes" - - -@pytest.mark.parametrize("status", ["rejected", "type_rejected", "failed", "deleted"]) -def test_file_wait_stops_on_terminal_status(status): - _, _, _, _, files, errors = modules() - client = files.TemplateFilesClient( - sync_transport( - lambda request: httpx.Response(200, json={"id": "f1", "status": status}) - ) - ) - with pytest.raises(errors.SandboxAPIError) as failure: - client.wait_available("f1", timeout=0.1) - assert failure.value.code == "FILE_" + status.upper() - - -def test_async_resource_routes_polling_and_streamed_upload_download(tmp_path): - models, transport, templates, sandboxes, files, _ = modules() - source = tmp_path / "source.txt" - source.write_bytes(b"async payload") - target = tmp_path / "target.txt" - observed = [] - - async def handler(request): - observed.append((request.method, request.url.path, await request.aread())) - if request.url.path.endswith("/images/browser"): - return httpx.Response( - 200, json={"imageName": "browser", "imageUrl": "registry/browser:2"} - ) - if request.url.path.endswith("/v3/templates"): - return httpx.Response( - 200, json={"templateID": "t1", "templateName": "one", "buildID": "b1"} - ) - if request.url.path.endswith("/v2/templates"): - return httpx.Response( - 200, json=[{"templateID": "t1", "templateName": "one"}] - ) - if "/builds/" in request.url.path: - return httpx.Response( - 200, json={"templateID": "t1", "buildID": "b1", "status": "READY"} - ) - if "/templates/" in request.url.path: - return httpx.Response(200, json={"templateID": "t1", "templateName": "one"}) - if request.url.path.endswith("/v2/sandboxes"): - return httpx.Response(200, json=[{"sandboxID": "s1", "templateID": "t1"}]) - if "/sandboxes" in request.url.path: - return httpx.Response(200, json={"sandboxID": "s1", "templateID": "t1"}) - if request.url.path.endswith("/content"): - return httpx.Response(200, content=b"download") - if request.method == "POST" and request.headers.get( - "content-type", "" - ).startswith("multipart/"): - assert b"async payload" in await request.aread() - return httpx.Response( - 200, - json={ - "id": "f1", - "status": "available", - "upload_url": "https://storage.test/file", - }, - ) - - async def run(): - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as pool: - http = transport.AsyncTransport( - "https://platform.test", "platform-key", http_client=pool - ) - template_client = templates.AsyncTemplatesClient(http) - assert ( - await template_client.create( - models.TemplateCreateRequest( - name="one", - image=models.OfficialImage.BROWSER, - cpu_count=2, - memory_mb=4096, - ) - ) - ).id == "t1" - assert (await template_client.list())[0].id == "t1" - assert (await template_client.get("t1")).id == "t1" - await template_client.update( - "t1", models.TemplateUpdateRequest(description="") - ) - assert (await template_client.build_status("t1", "b1")).ready - assert (await template_client.wait_ready("t1", "b1", timeout=1)).ready - await template_client.delete("t1") - sandbox_client = sandboxes.AsyncSandboxesClient(http) - handle = await sandbox_client.create( - models.SandboxCreateRequest(template_id="t1") - ) - assert handle.sandbox_id == "s1" - assert (await handle.get()).id == "s1" - assert await handle.connect() is handle - await handle.pause() - assert await handle.resume() is handle - assert (await sandbox_client.list())[0].id == "s1" - await handle.release() - file_client = files.AsyncTemplateFilesClient(http) - assert (await file_client.upload(source)).id == "f1" - assert (await file_client.get("f1")).id == "f1" - assert ( - await file_client.wait_available("f1", timeout=1) - ).status == "available" - ticket = await file_client.prepare_upload( - models.UploadRequest(filename="source.txt") - ) - await file_client.upload_content(ticket, source) - await file_client.complete("f1") - assert await file_client.download("f1", target) == target - await file_client.delete("f1") - assert target.read_bytes() == b"download" - connects = [ - body for method, path, body in observed if path.endswith("/connect") - ] - assert connects == [b"{}"] - - asyncio.run(run()) - - -@pytest.mark.parametrize("facet_name", ["TemplatesClient", "SandboxesClient"]) -def test_list_rejects_malformed_platform_object(facet_name): - _, _, templates, sandboxes, _, errors = modules() - client_type = getattr( - templates if facet_name == "TemplatesClient" else sandboxes, facet_name - ) - client = client_type( - sync_transport(lambda request: httpx.Response(200, json={"items": []})) - ) - with pytest.raises(errors.SandboxAPIError) as failure: - client.list() - assert failure.value.code == "INVALID_RESPONSE" - - -@pytest.mark.parametrize("bad_id", ["", "..", "s/other", "s?query", "s\x00"]) -def test_invalid_resource_id_is_rejected_before_request(bad_id): - _, _, templates, sandboxes, files, _ = modules() - - def handler(request): - raise AssertionError("invalid resource ID reached the network") - - transport = sync_transport(handler) - for client in ( - templates.TemplatesClient(transport), - sandboxes.SandboxesClient(transport), - files.TemplateFilesClient(transport), - ): - with pytest.raises(ValueError): - client.get(bad_id) - - -def test_file_wait_timeout_preserves_last_status_and_missing_file_is_io_error(tmp_path): - _, _, _, _, files, errors = modules() - client = files.TemplateFilesClient( - sync_transport( - lambda request: httpx.Response(200, json={"id": "f1", "status": "checking"}) - ) - ) - with pytest.raises(errors.SandboxWaitTimeoutError) as failure: - client.wait_available("f1", timeout=0.005) - assert failure.value.resource_id == "f1" - assert failure.value.status == "checking" - with pytest.raises(errors.SandboxAPIError) as failure: - client.upload(tmp_path / "missing.txt") - assert failure.value.code == "FILE_IO_ERROR" - - -def test_download_http_failure_preserves_target_and_removes_partial_file(tmp_path): - _, _, _, _, files, errors = modules() - target = tmp_path / "target.txt" - target.write_bytes(b"old contents") - client = files.TemplateFilesClient( - sync_transport( - lambda request: httpx.Response( - 403, json={"code": "AccessDenied", "message": "Denied"} - ) - ) - ) - with pytest.raises(errors.SandboxAPIError): - client.download("f1", target) - assert target.read_bytes() == b"old contents" - assert list(tmp_path.iterdir()) == [target] - - -def test_async_download_cancellation_closes_response_and_preserves_target(tmp_path): - _, transport, _, _, files, _ = modules() - target = tmp_path / "target.txt" - target.write_bytes(b"old") - closed = [] - - class CancelledStream(httpx.AsyncByteStream): - async def __aiter__(self): - yield b"partial" - raise asyncio.CancelledError() - - async def aclose(self): - closed.append(True) - - async def run(): - async with httpx.AsyncClient( - transport=httpx.MockTransport( - lambda request: httpx.Response(200, stream=CancelledStream()) - ) - ) as pool: - client = files.AsyncTemplateFilesClient( - transport.AsyncTransport( - "https://platform.test", "platform-key", http_client=pool - ) - ) - with pytest.raises(asyncio.CancelledError): - await client.download("f1", target) - assert closed == [True] - assert target.read_bytes() == b"old" - assert list(tmp_path.iterdir()) == [target] - - asyncio.run(run()) - - -@pytest.mark.parametrize("kind", ["build", "file"]) -def test_polling_rejects_ready_response_after_total_deadline(kind): - import time - - _, _, templates, _, files, errors = modules() - - def handler(request): - time.sleep(0.02) - if kind == "build": - return httpx.Response( - 200, json={"templateID": "t1", "buildID": "b1", "status": "READY"} - ) - return httpx.Response(200, json={"id": "f1", "status": "available"}) - - http = sync_transport(handler) - with pytest.raises(errors.SandboxWaitTimeoutError): - if kind == "build": - templates.TemplatesClient(http).wait_ready("t1", "b1", timeout=0.005) - else: - files.TemplateFilesClient(http).wait_available("f1", timeout=0.005) - - -@pytest.mark.parametrize("kind", ["build", "file"]) -def test_async_polling_rejects_ready_response_after_total_deadline(kind): - _, transport, templates, _, files, errors = modules() - - async def handler(request): - await asyncio.sleep(0.02) - if kind == "build": - return httpx.Response( - 200, json={"templateID": "t1", "buildID": "b1", "status": "READY"} - ) - return httpx.Response(200, json={"id": "f1", "status": "available"}) - - async def run(): - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as pool: - http = transport.AsyncTransport( - "https://platform.test", "platform-key", http_client=pool - ) - with pytest.raises(errors.SandboxWaitTimeoutError): - if kind == "build": - await templates.AsyncTemplatesClient(http).wait_ready( - "t1", "b1", timeout=0.005 - ) - else: - await files.AsyncTemplateFilesClient(http).wait_available( - "f1", timeout=0.005 - ) - - asyncio.run(run()) - - -def _call_template_resource(handler, asynchronous, method, *args): - _, transport, templates, *_ = modules() - if not asynchronous: - return getattr(templates.TemplatesClient(sync_transport(handler)), method)(*args) - - async def run(): - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as pool: - client = templates.AsyncTemplatesClient( - transport.AsyncTransport( - "https://platform.test", "platform-key", http_client=pool - ) - ) - return await getattr(client, method)(*args) - - return asyncio.run(run()) - - -@pytest.mark.parametrize("asynchronous", [False, True]) -@pytest.mark.parametrize("custom_name", [None, "my-template-image"]) -@pytest.mark.parametrize( - "image_name,harness_type", - [ - ("code-interpreter-v1", None), - ("browser", None), - ("all-in-one", None), - ("deepseek-harness", "dsh"), - ("openclaw", "openclaw"), - ], -) -def test_five_enum_template_bodies_preserve_catalog_and_reusable_request( - asynchronous, custom_name, image_name, harness_type -): - models, *_ = modules() - observed = [] - exact_url = "registry.test/" + image_name + ":version-1" - - def handler(request): - observed.append((request.method, request.url.path)) - if request.method == "GET": - assert request.url.path == PREFIX + "/images/" + image_name - assert request.url.params["imageUrl"] == exact_url - return httpx.Response( - 200, json={"imageName": image_name, "imageUrl": exact_url} - ) - body = json.loads(request.content) - expected = { - "name": "typed-template", - "cpuCount": 2, - "memoryMB": 4096, - "fromImage": exact_url, - "imageName": custom_name or image_name, - } - if harness_type: - expected.update(harnessType=harness_type, imageType="MANAGED") - assert body == expected - return httpx.Response(200, json={"templateID": "t1"}) - - request = models.TemplateCreateRequest( - name="typed-template", - image=models.OfficialImage(image_name), - from_image=exact_url, - image_name=custom_name, - cpu_count=2, - memory_mb=4096, - ) - original = request.to_dict() - for _ in range(2): - assert _call_template_resource(handler, asynchronous, "create", request).id == "t1" - assert request.to_dict() == original - assert observed == [ - ("GET", PREFIX + "/images/" + image_name), - ("POST", PREFIX + "/v3/templates"), - ] * 2 - - -@pytest.mark.parametrize("asynchronous", [False, True]) -@pytest.mark.parametrize( - "image_name,harness_type", - [ - ("deepseek-harness", "openclaw"), - ("openclaw", "dsh"), - ("deepseek-harness", "codex"), - ("code-interpreter-v1", "dsh"), - ("browser", "openclaw"), - ("all-in-one", "hermes"), - ], -) -def test_template_enum_conflicts_fail_before_any_http( - asynchronous, image_name, harness_type -): - models, *_ = modules() - observed = [] - - def handler(request): - observed.append(request.method) - return httpx.Response(500) - - with pytest.raises(ValueError, match="harness_type.*image"): - request = models.TemplateCreateRequest( - name="conflict", - image=models.OfficialImage(image_name), - harness_type=harness_type, - cpu_count=2, - memory_mb=4096, - ) - _call_template_resource(handler, asynchronous, "create", request) - assert observed == [] - - -@pytest.mark.parametrize("asynchronous", [False, True]) -@pytest.mark.parametrize("harness_type", ["dsh", "openclaw", "codex", "hermes"]) -def test_raw_template_explicit_harness_uses_one_post(asynchronous, harness_type): - models, *_ = modules() - observed = [] - - def handler(request): - observed.append(request.method) - assert request.url.path == PREFIX + "/v3/templates" - assert json.loads(request.content) == { - "name": "raw-template", - "cpuCount": 2, - "memoryMB": 4096, - "fromImage": "registry.test/raw:version-1", - "harnessType": harness_type, - } - return httpx.Response(200, json={"templateID": "t1"}) - - request = models.TemplateCreateRequest( - name="raw-template", - from_image="registry.test/raw:version-1", - harnessType=harness_type, - cpu_count=2, - memory_mb=4096, - ) - assert _call_template_resource(handler, asynchronous, "create", request).id == "t1" - assert observed == ["POST"] - - -@pytest.mark.parametrize("asynchronous", [False, True]) -@pytest.mark.parametrize("harness_type", ["dsh", "openclaw", "codex", "hermes"]) -def test_template_update_harness_is_explicit_single_put(asynchronous, harness_type): - models, *_ = modules() - observed = [] - - def handler(request): - observed.append(request.method) - assert request.url.path == PREFIX + "/templates/t1" - assert json.loads(request.content) == { - "harnessType": harness_type, - "fromImage": "registry.test/raw:version-1", - "description": "", - } - return httpx.Response(200, json={"templateID": "t1", "imageType": "MANAGED"}) - - request = models.TemplateUpdateRequest( - harness_type=harness_type, - from_image="registry.test/raw:version-1", - description="", - ) - result = _call_template_resource(handler, asynchronous, "update", "t1", request) - assert result.image_type == "MANAGED" - assert observed == ["PUT"] - - -@pytest.mark.parametrize("request_type", ["TemplateCreateRequest", "TemplateUpdateRequest"]) -@pytest.mark.parametrize("harness_type", ["deepseek-harness", "unknown"]) -def test_template_harness_rejects_non_template_literal(request_type, harness_type): - from pydantic import ValidationError - - models, *_ = modules() - fields = {"harness_type": harness_type} - if request_type == "TemplateCreateRequest": - fields.update(name="one", cpu_count=2, memory_mb=4096) - with pytest.raises(ValidationError) as failure: - getattr(models, request_type)(**fields) - assert failure.value.errors()[0]["type"] == "literal_error" - - -@pytest.mark.parametrize( - "fields,expected", - [ - ({}, None), - ({"imageType": None}, None), - ({"imageType": "MANAGED"}, "MANAGED"), - ({"imageType": "BASE"}, "BASE"), - ], -) -def test_template_image_type_metadata_accepts_new_and_legacy_responses(fields, expected): - models, *_ = modules() - result = models.TemplateInfo.from_dict(dict(templateID="t1", **fields)) - assert result.image_type == expected - assert "harness_type" not in models.TemplateInfo.model_fields - - -@pytest.mark.parametrize("asynchronous", [False, True]) -def test_harness_enum_keeps_explicit_lifecycle_for_platform_validation(asynchronous): - models, *_ = modules() - observed = [] - - def handler(request): - observed.append(request.method) - if request.method == "GET": - return httpx.Response( - 200, - json={"imageName": "deepseek-harness", "imageUrl": "registry.test/dsh:1"}, - ) - body = json.loads(request.content) - assert body["harnessType"] == "dsh" - assert body["imageType"] == "MANAGED" - assert body["autoPauseTime"] == 300 - assert body["maxRunningTimeout"] == 900 - return httpx.Response(200, json={"templateID": "t1"}) - - request = models.TemplateCreateRequest( - name="explicit-lifecycle", - image=models.OfficialImage.DEEPSEEK_HARNESS, - cpu_count=2, - memory_mb=4096, - auto_pause_time=300, - max_running_timeout=900, - ) - _call_template_resource(handler, asynchronous, "create", request) - assert observed == ["GET", "POST"] - - -@pytest.mark.parametrize("image_name", ["deepseek-harness", "openclaw"]) -def test_agent_launch_keeps_snake_protocol_and_full_runtime_budget(image_name): - models, *_ = modules() - request = models.LaunchRequest( - image=models.OfficialImage(image_name), runtime_budget_seconds=172800 - ) - assert request.to_dict() == { - "harness_type": image_name, - "image_name": image_name, - "runtime_budget_seconds": 172800, - } - - -@pytest.mark.parametrize("asynchronous", [False, True]) -@pytest.mark.parametrize("model_field", ["model_config", "modelConfig"]) -@pytest.mark.parametrize("image_name", ["deepseek-harness", "openclaw"]) -def test_template_model_uses_console_fields_without_changing_agent_protocol( - asynchronous, model_field, image_name -): - models, *_ = modules() - bodies = [] - - def handler(request): - if request.method == "GET": - return httpx.Response( - 200, - json={ - "imageName": image_name, - "imageUrl": "registry.test/" + image_name + ":1", - }, - ) - assert request.headers["Authorization"] == "Bearer platform-key" - assert request.url.path == PREFIX + "/v3/templates" - bodies.append(json.loads(request.content)) - return httpx.Response(202, json={"templateID": "model-template"}) - - model = models.ModelConfig( - base_url="https://models.example/custom/api", - model_id="qwen3.7-plus", - api_key="private-template-model-key", - ) - request = models.TemplateCreateRequest( - name="configured-template", - image=models.OfficialImage(image_name), - cpu_count=2, - memory_mb=4096, - **{model_field: model}, - ) - original = request.to_dict() - result = _call_template_resource(handler, asynchronous, "create", request) - assert result.id == "model-template" - assert bodies[0]["modelConfig"] == { - "modelName": "qwen3.7-plus", - "baseUrl": "https://models.example/custom/api", - "apiKey": "private-template-model-key", - } - assert "model_config" not in bodies[0] - assert "private-template-model-key" not in repr(request) - assert request.to_dict() == original - assert model.to_dict() == { - "base_url": "https://models.example/custom/api", - "model_id": "qwen3.7-plus", - "api_key": "private-template-model-key", - } - - -@pytest.mark.parametrize("asynchronous", [False, True]) -@pytest.mark.parametrize("model_key", [None, "", " "]) -def test_raw_template_model_defaults_id_and_keeps_key_unconfigured( - asynchronous, model_key -): - models, *_ = modules() - bodies = [] - - def handler(request): - assert request.method == "POST" - bodies.append(json.loads(request.content)) - return httpx.Response(202, json={"templateID": "model-template"}) - - request = models.TemplateCreateRequest( - name="keyless-template", - from_image="registry.test/deepseek-harness:1", - harness_type="dsh", - cpu_count=2, - memory_mb=4096, - model_config=models.ModelConfig( - base_url="https://models.example/custom/api", api_key=model_key - ), - ) - result = _call_template_resource(handler, asynchronous, "create", request) - assert result.id == "model-template" - assert bodies[0]["modelConfig"] == { - "modelName": "qwen3.7-plus", - "baseUrl": "https://models.example/custom/api", - } - - -@pytest.mark.parametrize("asynchronous", [False, True]) -@pytest.mark.parametrize("model", ["omitted", "none", "empty"]) -def test_template_without_model_preserves_image_defaults(asynchronous, model): - models, *_ = modules() - bodies = [] - - def handler(request): - bodies.append(json.loads(request.content)) - return httpx.Response(202, json={"templateID": "default-template"}) - - fields = {} - if model != "omitted": - fields["model_config"] = models.ModelConfig() if model == "empty" else None - request = models.TemplateCreateRequest( - name="image-defaults", - from_image="registry.test/deepseek-harness:1", - harness_type="dsh", - cpu_count=2, - memory_mb=4096, - **fields, - ) - result = _call_template_resource(handler, asynchronous, "create", request) - assert result.id == "default-template" - assert bodies == [ - { - "name": "image-defaults", - "fromImage": "registry.test/deepseek-harness:1", - "harnessType": "dsh", - "cpuCount": 2, - "memoryMB": 4096, - } - ] - - -@pytest.mark.parametrize("request_type", ["TemplateCreateRequest", "TemplateUpdateRequest"]) -@pytest.mark.parametrize("field", ["auto_pause_time", "max_running_timeout"]) -def test_template_duration_validation_names_the_supplied_field(request_type, field): - models, *_ = modules() - values = {field: 0} - if request_type == "TemplateCreateRequest": - values.update(name="template", cpu_count=2, memory_mb=4096) - with pytest.raises(ValueError) as failure: - getattr(models, request_type)(**values) - assert field in failure.value.errors()[0]["msg"] - assert "lifetime" not in failure.value.errors()[0]["msg"] diff --git a/tests/agentstudio_sandbox/test_stream.py b/tests/agentstudio_sandbox/test_stream.py deleted file mode 100644 index 3c2b9359..00000000 --- a/tests/agentstudio_sandbox/test_stream.py +++ /dev/null @@ -1,487 +0,0 @@ -"""SSE framing, replay, lifetime, and callback tests without external traffic.""" - -import asyncio -import json -import threading - -import httpx -import pytest - -from dashscope.applications.agentstudio.sandbox.agents import ( - AgentsClient, - AsyncAgentsClient, -) -from dashscope.applications.agentstudio.sandbox.exceptions import SandboxAPIError -from dashscope.applications.agentstudio.sandbox.transport import ( - AsyncTransport, - Transport, -) - - -def event(sequence, kind="message.delta", turn="at_one", **extra): - return {"turn_id": turn, "sequence": sequence, "type": kind, **extra} - - -def frame(value, with_id=True): - identifier = ( - "id: {}:{}\n".format(value["turn_id"], value["sequence"]) if with_id else "" - ) - return ( - identifier + "event: " + value["type"] + "\ndata: " + json.dumps(value) + "\n\n" - ).encode() - - -class Stream(httpx.SyncByteStream): - def __init__(self, chunks): - self.chunks = chunks - self.closed = False - - def __iter__(self): - yield from self.chunks - - def close(self): - self.closed = True - - -class AsyncStream(httpx.AsyncByteStream): - def __init__(self, chunks): - self.chunks = chunks - self.closed = False - - async def __aiter__(self): - for chunk in self.chunks: - await asyncio.sleep(0) - yield chunk - - async def aclose(self): - self.closed = True - - -def test_sync_iteration_replay_cursor_multiline_terminal_and_borrowed_pool(): - seen = [] - multiline = ( - b'data: {"turn_id":"at_one",\ndata: "sequence":3,"type":"message.delta"}\n\n' - ) - source = Stream( - [ - b": keepalive\n\n", - frame(event(2)), - multiline[:14], - multiline[14:], - frame(event(4, "turn.completed")), - frame(event(5)), - ] - ) - - def handler(request): - seen.append(request) - if request.url.path.endswith("/events"): - return httpx.Response( - 200, - headers={"Content-Type": "text/event-stream; charset=utf-8"}, - stream=source, - ) - return httpx.Response(200, json={"data": {}}) - - pool = httpx.Client(transport=httpx.MockTransport(handler)) - transport = Transport("https://unit.test", "platform-key", http_client=pool) - try: - with AgentsClient(transport).turn("at_one").subscribe( - after_sequence=2 - ) as subscription: - received = list(subscription) - assert [item["sequence"] for item in received] == [3, 4] - assert subscription.last_sequence == 4 - assert seen[0].headers["Last-Event-ID"] == "at_one:2" - assert seen[0].url.params["after_seq"] == "2" - assert source.closed - assert len(seen) == 1 and seen[0].method == "GET" - transport.close() - assert pool.get("https://unit.test/alive").status_code == 200 - finally: - transport.close() - pool.close() - - -@pytest.mark.parametrize( - "chunks", - [ - [frame(event(2))], - [frame(event(1, turn="at_wrong"))], - [b"data: not-json\n\n"], - [b'data: {"turn_id":"at_one","sequence":true,"type":"turn.started"}\n\n'], - [frame(event(1))[:-1]], - [ - b'id: at_one:99\ndata: {"turn_id":"at_one","sequence":1,"type":"turn.started"}\n\n' - ], - ], -) -def test_sync_invalid_events_fail_close_and_do_not_retry(chunks): - seen = [] - source = Stream(chunks) - - def handler(request): - seen.append(request) - return httpx.Response( - 200, headers={"Content-Type": "text/event-stream"}, stream=source - ) - - pool = httpx.Client(transport=httpx.MockTransport(handler)) - transport = Transport("https://unit.test", "platform-key", http_client=pool) - try: - with pytest.raises(SandboxAPIError) as error: - with AgentsClient(transport).turn("at_one").subscribe() as subscription: - list(subscription) - assert error.value.code == "INVALID_RESPONSE" - assert source.closed and len(seen) == 1 - assert "Last-Event-ID" not in seen[0].headers - finally: - transport.close() - pool.close() - - -def test_sync_callback_uses_one_reader_and_propagates_handler_failure(): - source = Stream([frame(event(1)), frame(event(2, "turn.completed"))]) - pool = httpx.Client( - transport=httpx.MockTransport( - lambda request: httpx.Response( - 200, headers={"Content-Type": "text/event-stream"}, stream=source - ) - ) - ) - transport = Transport("https://unit.test", "platform-key", http_client=pool) - threads = [] - received = [] - - def callback(item): - threads.append(threading.current_thread().ident) - received.append(item["sequence"]) - - try: - subscription = AgentsClient(transport).turn("at_one").subscribe(callback) - subscription.wait(2) - assert received == [1, 2] - assert len(set(threads)) == 1 - assert threads[0] != threading.current_thread().ident - assert source.closed and subscription.last_sequence == 2 - finally: - transport.close() - pool.close() - - pool = httpx.Client( - transport=httpx.MockTransport( - lambda request: httpx.Response( - 200, - headers={"Content-Type": "text/event-stream"}, - stream=Stream([frame(event(1))]), - ) - ) - ) - transport = Transport("https://unit.test", "platform-key", http_client=pool) - - def failure(item): - raise RuntimeError("callback failed") - - try: - subscription = AgentsClient(transport).turn("at_one").subscribe(failure) - with pytest.raises(RuntimeError, match="callback failed"): - subscription.wait(2) - assert subscription.last_sequence == 1 - finally: - transport.close() - pool.close() - - -def test_sync_sdk_close_disconnects_without_remote_cancel_and_invalid_media_closes(): - source = Stream([frame(event(1))]) - seen = [] - - def handler(request): - seen.append(request) - return httpx.Response( - 200, headers={"Content-Type": "text/event-stream"}, stream=source - ) - - pool = httpx.Client(transport=httpx.MockTransport(handler)) - transport = Transport("https://unit.test", "platform-key", http_client=pool) - try: - subscription = AgentsClient(transport).turn("at_one").subscribe() - subscription.__enter__() - transport.close() - assert source.closed - assert len(seen) == 1 and seen[0].method == "GET" - finally: - transport.close() - pool.close() - - source = Stream([b"{}"]) - pool = httpx.Client( - transport=httpx.MockTransport( - lambda request: httpx.Response( - 200, headers={"Content-Type": "application/json"}, stream=source - ) - ) - ) - transport = Transport("https://unit.test", "platform-key", http_client=pool) - try: - with pytest.raises(SandboxAPIError, match="text/event-stream"): - with AgentsClient(transport).turn("at_one").subscribe(): - pass - assert source.closed - finally: - transport.close() - pool.close() - - -def test_async_iteration_and_ordered_awaitable_callback(): - async def run(): - sources = [] - seen = [] - - async def handler(request): - seen.append(request) - source = AsyncStream([frame(event(1)), frame(event(2, "turn.completed"))]) - sources.append(source) - return httpx.Response( - 200, headers={"Content-Type": "text/event-stream"}, stream=source - ) - - pool = httpx.AsyncClient(transport=httpx.MockTransport(handler)) - transport = AsyncTransport( - "https://unit.test", "platform-key", http_client=pool - ) - try: - turn = AsyncAgentsClient(transport).turn("at_one") - async with turn.subscribe() as subscription: - received = [item["sequence"] async for item in subscription] - assert received == [1, 2] and subscription.last_sequence == 2 - assert sources[0].closed - callback_items = [] - tasks = [] - - async def callback(item): - await asyncio.sleep(0) - tasks.append(asyncio.current_task()) - callback_items.append(item["sequence"]) - - subscription = turn.subscribe(callback) - await subscription.wait(2) - assert callback_items == [1, 2] and len(set(tasks)) == 1 - assert sources[1].closed - assert all(request.method == "GET" for request in seen) - finally: - await transport.aclose() - await pool.aclose() - - asyncio.run(run()) - - -def test_async_cancelled_reader_closes_http_subscription_only(): - async def run(): - waiting = asyncio.Event() - source_closed = asyncio.Event() - seen = [] - - class BlockingStream(httpx.AsyncByteStream): - async def __aiter__(self): - yield frame(event(1)) - waiting.set() - await asyncio.Event().wait() - - async def aclose(self): - source_closed.set() - - async def handler(request): - seen.append(request) - return httpx.Response( - 200, - headers={"Content-Type": "text/event-stream"}, - stream=BlockingStream(), - ) - - pool = httpx.AsyncClient(transport=httpx.MockTransport(handler)) - transport = AsyncTransport( - "https://unit.test", "platform-key", http_client=pool - ) - try: - subscription = ( - AsyncAgentsClient(transport) - .turn("at_one") - .subscribe(lambda event: None) - ) - await asyncio.wait_for(waiting.wait(), 2) - await subscription.aclose() - assert source_closed.is_set() - assert subscription.last_sequence == 1 - assert len(seen) == 1 and seen[0].method == "GET" - finally: - await transport.aclose() - await pool.aclose() - - asyncio.run(run()) - - -@pytest.mark.parametrize("mode", ["iterator", "callback"]) -@pytest.mark.parametrize("status", [401, 404, 200]) -def test_sync_sse_startup_failure_is_not_reported_as_empty_success(mode, status): - code = "UNAUTHORIZED" if status == 401 else "NOT_FOUND" - source = Stream([json.dumps({"error": {"code": code}}).encode()]) - requests = [] - - def handler(request): - requests.append(request) - return httpx.Response( - status, headers={"Content-Type": "application/json"}, stream=source - ) - - pool = httpx.Client(transport=httpx.MockTransport(handler)) - transport = Transport("https://unit.test", "platform-key", http_client=pool) - try: - subscription = ( - AgentsClient(transport) - .turn("at_one") - .subscribe((lambda item: None) if mode == "callback" else None) - ) - with pytest.raises(SandboxAPIError) as failure: - if mode == "callback": - subscription.wait(2) - else: - list(subscription) - assert failure.value.code == ("INVALID_RESPONSE" if status == 200 else code) - assert source.closed - assert len(requests) == 1 and requests[0].method == "GET" - assert not transport._subscriptions - finally: - transport.close() - pool.close() - - -@pytest.mark.parametrize("mode", ["iterator", "callback"]) -@pytest.mark.parametrize("status", [401, 404, 200]) -def test_async_sse_startup_failure_propagates_and_closes(mode, status): - async def run(): - code = "UNAUTHORIZED" if status == 401 else "NOT_FOUND" - source = AsyncStream([json.dumps({"error": {"code": code}}).encode()]) - requests = [] - - async def handler(request): - requests.append(request) - return httpx.Response( - status, headers={"Content-Type": "application/json"}, stream=source - ) - - pool = httpx.AsyncClient(transport=httpx.MockTransport(handler)) - transport = AsyncTransport( - "https://unit.test", "platform-key", http_client=pool - ) - try: - subscription = ( - AsyncAgentsClient(transport) - .turn("at_one") - .subscribe((lambda item: None) if mode == "callback" else None) - ) - with pytest.raises(SandboxAPIError) as failure: - if mode == "callback": - await subscription.wait(2) - else: - _ = [item async for item in subscription] - assert failure.value.code == ("INVALID_RESPONSE" if status == 200 else code) - assert source.closed - assert len(requests) == 1 and requests[0].method == "GET" - assert not transport._subscriptions - finally: - await transport.aclose() - await pool.aclose() - - asyncio.run(run()) - - -def test_sync_external_close_unblocks_callback_reader_without_reporting_failure(): - reading = threading.Event() - closed = threading.Event() - requests = [] - - class InterruptedStream(httpx.SyncByteStream): - def __iter__(self): - yield frame(event(1)) - reading.set() - closed.wait(2) - raise httpx.ReadError("reader interrupted by local close") - - def close(self): - closed.set() - - def handler(request): - requests.append(request) - return httpx.Response( - 200, - headers={"Content-Type": "text/event-stream"}, - stream=InterruptedStream(), - ) - - pool = httpx.Client(transport=httpx.MockTransport(handler)) - transport = Transport("https://unit.test", "platform-key", http_client=pool) - try: - subscription = ( - AgentsClient(transport).turn("at_one").subscribe(lambda item: None) - ) - assert reading.wait(2) - subscription.close() - subscription.wait(2) - assert closed.is_set() - assert len(requests) == 1 and requests[0].method == "GET" - assert subscription.last_sequence == 1 - finally: - closed.set() - transport.close() - pool.close() - - -@pytest.mark.parametrize("asynchronous", [False, True]) -def test_expired_event_cursor_is_not_retried_or_reset(asynchronous): - """410 must reach the caller; starting from zero could duplicate a Turn.""" - seen = [] - - def reply(request): - seen.append(request) - return httpx.Response( - 410, - headers={"x-request-id": "expired-cursor-request"}, - json={"error": {"code": "EVENTS_EXPIRED", "message": "Events expired"}}, - ) - - if not asynchronous: - with httpx.Client(transport=httpx.MockTransport(reply)) as pool: - transport = Transport("https://unit.test", "platform-key", http_client=pool) - try: - with pytest.raises(SandboxAPIError) as error: - with AgentsClient(transport).turn("at_one").subscribe( - after_sequence=9 - ) as events: - list(events) - finally: - transport.close() - else: - - async def run(): - async with httpx.AsyncClient(transport=httpx.MockTransport(reply)) as pool: - transport = AsyncTransport( - "https://unit.test", "platform-key", http_client=pool - ) - try: - with pytest.raises(SandboxAPIError) as error: - async with AsyncAgentsClient(transport).turn( - "at_one" - ).subscribe(after_sequence=9) as events: - [event async for event in events] - return error - finally: - await transport.aclose() - - error = asyncio.run(run()) - assert error.value.status_code == 410 - assert error.value.code == "EVENTS_EXPIRED" - assert error.value.request_id == "expired-cursor-request" - assert len(seen) == 1 - assert seen[0].url.params["after_seq"] == "9" - assert seen[0].headers["Last-Event-ID"] == "at_one:9" diff --git a/tests/agentstudio_sandbox/test_web_ui.py b/tests/agentstudio_sandbox/test_web_ui.py deleted file mode 100644 index b76680b8..00000000 --- a/tests/agentstudio_sandbox/test_web_ui.py +++ /dev/null @@ -1,1457 +0,0 @@ -import base64 -import io -import json -import shlex -import struct -import subprocess -from contextlib import contextmanager -from pathlib import Path -from types import SimpleNamespace - -import httpx -import pytest - - -def frame(value, flags=0): - data = json.dumps(value).encode() - return bytes([flags]) + struct.pack(">I", len(data)) + data - - -def process_output(text="DSH_WEB_TOKEN=login_token\n", exit_code=0): - return ( - frame({"event": {"start": {"pid": 42}}}) - + frame( - {"event": {"data": {"stdout": base64.b64encode(text.encode()).decode()}}} - ) - + frame({"event": {"end": {"exited": True, "exitCode": exit_code}}}) - + frame({}, 2) - ) - - -def connection(): - return SimpleNamespace( - domain="sandbox.example", - envd_url="https://envd.example/", - envd_access_token="envd-secret", - traffic_access_token="traffic-secret", - ) - - -def test_envd_command_uses_framed_process_and_private_headers(monkeypatch): - from dashscope.applications.agentstudio.sandbox import _bootstrap - - requests = [] - original = httpx.Client - - def reply(request): - requests.append(request) - return httpx.Response(200, content=process_output()) - - monkeypatch.setattr( - _bootstrap.httpx, - "Client", - lambda **kwargs: original(transport=httpx.MockTransport(reply)), - ) - bootstrap = _bootstrap._Bootstrap("sandbox-1", connection()) - assert ( - bootstrap.command( - ["/bin/sh", "-ec", 'printf "%s" "$1"', "label", "a; echo 'secret'"] - ) - == "DSH_WEB_TOKEN=login_token\n" - ) - request = requests[0] - assert request.url.path == "/process.Process/Start" - assert request.headers["x-access-token"] == "envd-secret" - assert request.headers["authorization"] == "Basic dXNlcjo=" - assert request.headers["e2b-sandbox-id"] == "sandbox-1" - assert request.headers["e2b-sandbox-port"] == "49983" - assert request.headers["e2b-traffic-access-token"] == "traffic-secret" - assert request.content[0] == 0 - assert struct.unpack(">I", request.content[1:5])[0] == len(request.content) - 5 - body = json.loads(request.content[5:]) - assert body["stdin"] is False - assert body["process"]["cwd"] == "/home/user" - assert shlex.split(body["process"]["args"][1])[1:] == [ - "/bin/sh", - "-ec", - 'printf "%s" "$1"', - "label", - "a; echo 'secret'", - ] - - -@pytest.mark.parametrize( - "response", - [ - b"\x00\x00", - frame({"event": {"end": {"exited": True, "exitCode": 0}}}), - process_output(exit_code=1), - process_output() + frame({}), - frame({"event": {"start": {"pid": 42}}}) - + frame({"event": {"data": {"stdout": "not base64"}}}), - b'\x00\x00\x00\x00\x08{"x":1}x', - ], -) -def test_envd_rejects_malformed_or_unconfirmed_process(response): - from dashscope.applications.agentstudio.sandbox._bootstrap import _stdout - - with pytest.raises(OSError): - _stdout(response) - - -def test_envd_bounded_response_and_errors_hide_endpoint(monkeypatch): - from dashscope.applications.agentstudio.sandbox import _bootstrap - - original = httpx.Client - monkeypatch.setattr( - _bootstrap.httpx, - "Client", - lambda **kwargs: original( - transport=httpx.MockTransport( - lambda request: httpx.Response( - 200, content=b"x" * (2 * 1024 * 1024 + 1) - ) - ) - ), - ) - with pytest.raises(OSError, match="size limit"): - _bootstrap._Bootstrap("sandbox-1", connection()).command(["true"]) - monkeypatch.setattr( - _bootstrap.httpx, - "Client", - lambda **kwargs: original( - transport=httpx.MockTransport( - lambda request: httpx.Response(403, content=b"envd-secret") - ) - ), - ) - with pytest.raises(OSError) as error: - _bootstrap._Bootstrap("sandbox-1", connection()).command(["true"]) - assert "envd-secret" not in str(error.value) - assert "envd.example" not in str(error.value) - - -class RecordingBootstrap: - def __init__(self, token): - self.commands, self.files, self.token = [], {}, token - - def command(self, argv): - self.commands.append(argv) - return self.token - - def put_file(self, path, data): - self.files[path] = data - - def put_json(self, path, data): - self.files[path] = json.dumps(data).encode() - - -def test_dsh_model_credentials_are_private_and_missing_key_stays_absent(): - from dashscope.applications.agentstudio.sandbox._bootstrap import _Bootstrap - - recorder = RecordingBootstrap("DSH_WEB_TOKEN=web_token\n") - assert ( - _Bootstrap.start_dsh( - recorder, - "8080-s.example", - True, - "https://model.example/v1", - "qwen3.7-plus", - "", - ) - == "web_token" - ) - assert set(recorder.files) == {"/home/user/.dsh/native-web-preview.json"} - patch = json.loads(recorder.files["/home/user/.dsh/native-web-preview.json"]) - provider = patch[0]["config"]["providers"]["bailian-qwen"] - assert provider["baseURL"] == "https://model.example/v1" - assert provider["apiKeyEnv"] == "DASHSCOPE_API_KEY" - recorder = RecordingBootstrap("DSH_WEB_TOKEN=web_token\n") - _Bootstrap.start_dsh( - recorder, - "8080-s.example", - True, - "https://model.example/v1", - "custom", - "model-secret", - ) - assert json.loads(recorder.files["/home/user/.dsh/.credentials.yaml"]) == { - "version": 1, - "refs": {"DASHSCOPE_API_KEY": "model-secret"}, - } - assert "model-secret" not in json.dumps(recorder.commands) - - -@pytest.fixture -def local_dsh_model_files(tmp_path, monkeypatch): - from dashscope.applications.agentstudio.sandbox import _bootstrap - - credentials = tmp_path / ".credentials.yaml" - patch = tmp_path / "native-web-preview.json" - monkeypatch.setattr(_bootstrap, "_DSH_CREDENTIALS", str(credentials)) - monkeypatch.setattr(_bootstrap, "_DSH_PATCH", str(patch)) - - class LocalFiles(RecordingBootstrap): - def command(self, argv): - self.commands.append(argv) - return subprocess.run( - argv, check=True, capture_output=True, text=True - ).stdout - - def put_json(self, path, data): - super().put_json(path, data) - Path(path).write_bytes(self.files[path]) - - return _bootstrap, credentials, patch, LocalFiles("") - - -@pytest.mark.parametrize("already_exists", [False, True]) -def test_dsh_model_setup_writes_private_regular_credentials( - local_dsh_model_files, already_exists -): - module, credentials, patch, bootstrap = local_dsh_model_files - if already_exists: - credentials.write_text("existing credentials") - credentials.chmod(0o644) - module._configure_dsh_model( - bootstrap, "https://model.example/v1", "qwen3.7-plus", "model-secret" - ) - assert json.loads(credentials.read_text()) == { - "version": 1, - "refs": {"DASHSCOPE_API_KEY": "model-secret"}, - } - assert credentials.stat().st_mode & 0o777 == 0o600 - assert patch.stat().st_mode & 0o777 == 0o600 - assert "model-secret" not in json.dumps(bootstrap.commands) - - -@pytest.mark.parametrize("file_kind", ["symlink", "dangling-symlink", "directory"]) -def test_dsh_model_setup_rejects_non_regular_credentials( - local_dsh_model_files, file_kind -): - module, credentials, patch, bootstrap = local_dsh_model_files - if file_kind in ("symlink", "dangling-symlink"): - target = credentials.with_name("original.credentials") - if file_kind == "symlink": - target.write_text("original credentials") - credentials.symlink_to(target) - else: - credentials.mkdir() - credentials.chmod(0o755) - with pytest.raises(subprocess.CalledProcessError): - module._configure_dsh_model( - bootstrap, "https://model.example/v1", "qwen3.7-plus", "model-secret" - ) - assert bootstrap.files == {} - if file_kind in ("symlink", "dangling-symlink"): - assert credentials.is_symlink() - if file_kind == "symlink": - assert target.read_text() == "original credentials" - else: - assert not target.exists() - else: - assert credentials.is_dir() - assert credentials.stat().st_mode & 0o777 == 0o755 - - -def test_dsh_model_setup_preserves_an_existing_patch(local_dsh_model_files): - module, credentials, patch, bootstrap = local_dsh_model_files - credentials.write_text("existing credentials") - patch.write_text("existing patch") - with pytest.raises(subprocess.CalledProcessError): - module._configure_dsh_model( - bootstrap, "https://model.example/v1", "qwen3.7-plus", "model-secret" - ) - assert credentials.read_text() == "existing credentials" - assert patch.read_text() == "existing patch" - assert bootstrap.files == {} - - -def test_dsh_model_setup_without_key_preserves_credentials(local_dsh_model_files): - module, credentials, patch, bootstrap = local_dsh_model_files - credentials.write_text("existing credentials") - credentials.chmod(0o640) - module._configure_dsh_model( - bootstrap, "https://model.example/v1", "qwen3.7-plus", "" - ) - assert credentials.read_text() == "existing credentials" - assert credentials.stat().st_mode & 0o777 == 0o640 - assert patch.stat().st_mode & 0o777 == 0o600 - - -def test_openclaw_config_keeps_device_auth_and_file_secret(): - from dashscope.applications.agentstudio.sandbox._bootstrap import _start_openclaw - - recorder = RecordingBootstrap("OPENCLAW_WEB_TOKEN=gateway_token\n") - assert ( - _start_openclaw( - recorder, - "https://18789-s.example", - True, - "https://model.example/v1", - "custom", - "model-secret", - "anthropic-messages", - ) - == "gateway_token" - ) - patch = json.loads( - next(data for name, data in recorder.files.items() if "/patch-" in name) - ) - assert ( - recorder.files["/home/user/.openclaw/sdk-web-preview/model.key"] - == b"model-secret" - ) - assert patch["models"]["providers"]["bailian-qwen"]["apiKey"] == { - "source": "file", - "provider": "sdkwebmodel", - "id": "value", - } - assert patch["models"]["providers"]["bailian-qwen"]["api"] == "anthropic-messages" - assert patch["gateway"]["controlUi"] == { - "enabled": True, - "basePath": "", - "allowInsecureAuth": False, - "dangerouslyDisableDeviceAuth": False, - "dangerouslyAllowHostHeaderOriginFallback": False, - "allowedOrigins": ["https://18789-s.example"], - } - assert "model-secret" not in json.dumps(patch) - assert "model-secret" not in json.dumps(recorder.commands) - - -def test_borrowed_bootstrap_does_not_write_model_settings(): - from dashscope.applications.agentstudio.sandbox._bootstrap import ( - _Bootstrap, - _start_openclaw, - ) - - recorder = RecordingBootstrap("DSH_WEB_TOKEN=web_token\n") - _Bootstrap.start_dsh(recorder, "host", False, "", "", "") - assert recorder.files == {} - recorder = RecordingBootstrap("OPENCLAW_WEB_TOKEN=web_token\n") - _start_openclaw(recorder, "https://host", False, "", "", "", "") - patch = json.loads(next(iter(recorder.files.values()))) - assert "models" not in patch and "secrets" not in patch - - -def test_pairing_id_validated_before_remote_command(): - from dashscope.applications.agentstudio.sandbox._bootstrap import _approve_pairing - - recorder = RecordingBootstrap("") - with pytest.raises(OSError): - _approve_pairing(recorder, "not-a-uuid; echo token") - assert recorder.commands == [] - _approve_pairing(recorder, "12345678-1234-1234-1234-123456789abc") - assert recorder.commands[-1][-1] == "12345678-1234-1234-1234-123456789abc" - - -def test_options_do_not_reveal_key_or_allow_model_without_endpoint(): - from dashscope.applications.agentstudio.sandbox.models import OfficialImage - from dashscope.applications.agentstudio.sandbox.web_ui import ( - WebUiOptions, - _validate, - ) - - options = WebUiOptions(model_api_key="model-secret") - assert "model-secret" not in repr(options) - with pytest.raises(ValueError, match="model_base_url"): - _validate(OfficialImage.DEEPSEEK_HARNESS, options) - with pytest.raises(ValueError): - _validate( - OfficialImage.DEEPSEEK_HARNESS, - WebUiOptions(sandbox_id="s", model_base_url="https://model.example"), - ) - validated = _validate( - OfficialImage.OPENCLAW, WebUiOptions(model_base_url="https://model.example/v1") - ) - assert validated.model_id == "qwen3.7-plus" - assert validated.model_api_key is None - - -class FakePlatform: - base_url = "https://platform.example" - api_key = "platform-secret" - timeout = 30.0 - poll_interval = 0.01 - - def __init__(self, fail_connect=False, release_fails=False): - self._closed = False - self._closing = False - self._client = SimpleNamespace(is_closed=False) - self.calls, self.subscriptions = [], set() - self.fail_connect, self.release_fails = fail_connect, release_fails - - def request(self, method, path, **kwargs): - self.calls.append((method, path, kwargs.get("json"))) - if path.endswith("/template-config"): - return { - "images": [], - "resource_configs": [], - "default_compute": {"cpu": 2, "memory_mib": 4096}, - } - if "/images/" in path: - return { - "imageName": path.rsplit("/", 1)[-1], - "imageUrl": "registry.example/native:v8", - } - if path.endswith("/v3/templates"): - return { - "templateID": "template-new", - "templateName": "preview", - "buildID": "build-1", - } - if path.endswith("/status"): - return { - "templateID": "template-new", - "buildID": "build-1", - "status": "READY", - } - if path.endswith("/connect") and self.fail_connect: - raise OSError("network unavailable") - if path.endswith("/sandboxes") or path.endswith("/connect"): - return { - "sandboxID": "sandbox-1", - "templateID": "template-new", - "domain": "sandbox.example", - "envdUrl": "https://envd.example/", - "envdAccessToken": "envd-secret", - } - if method == "DELETE" and "/sandboxes/" in path and self.release_fails: - raise RuntimeError("release unavailable") - if method == "DELETE": - return None - raise AssertionError((method, path)) - - def register(self, subscription): - self.subscriptions.add(subscription) - - def unregister(self, subscription): - self.subscriptions.discard(subscription) - - -def prepare_local_preview(monkeypatch): - from dashscope.applications.agentstudio.sandbox import web_ui as _web_ui - - monkeypatch.setattr(_web_ui, "_check_node", lambda: None) - monkeypatch.setattr( - _web_ui._bootstrap, "prepare", lambda *args: SimpleNamespace(openclaw=False) - ) - monkeypatch.setattr( - _web_ui._Resources, - "start_proxy", - lambda *args: "http://127.0.0.1:12345/__preview/entry", - ) - return _web_ui - - -@pytest.mark.parametrize( - "image_name,options,expected", - [ - ("openclaw", None, True), - ("openclaw", {}, True), - ("openclaw", {"auto_pair_openclaw": False}, False), - ("openclaw", {"auto_pair_openclaw": True}, True), - ("deepseek-harness", None, False), - ], - ids=["default", "default-options", "disabled", "enabled", "dsh"], -) -def test_web_ui_pairing_defaults_and_explicit_override( - monkeypatch, image_name, options, expected -): - from dashscope.applications.agentstudio.sandbox.models import OfficialImage - from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient - - web_ui = prepare_local_preview(monkeypatch) - monkeypatch.setattr( - web_ui._bootstrap, - "prepare", - lambda *args: SimpleNamespace(openclaw=image_name == "openclaw"), - ) - approvals = [] - - def start_proxy(self, route, auto_pair): - approvals.append(auto_pair) - return "http://127.0.0.1:12345/__preview/entry" - - monkeypatch.setattr(web_ui._Resources, "start_proxy", start_proxy) - platform = FakePlatform() - preview = web_ui.open_web_ui( - SandboxesClient(platform), - platform, - OfficialImage(image_name), - None if options is None else web_ui.WebUiOptions(**options), - ) - try: - assert approvals == [expected] - finally: - preview.close() - - -def test_fresh_preview_resolves_directory_and_releases_only_owned_resources( - monkeypatch, -): - from dashscope.applications.agentstudio.sandbox.models import OfficialImage - from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient - - web_ui = prepare_local_preview(monkeypatch) - platform = FakePlatform() - preview = web_ui.open_web_ui( - SandboxesClient(platform), platform, OfficialImage.DEEPSEEK_HARNESS - ) - assert preview.sandbox_id == "sandbox-1" - assert preview.template_id == "template-new" - assert preview in platform.subscriptions - create = next( - body for method, path, body in platform.calls if path.endswith("/v3/templates") - ) - assert create["fromImage"] == "registry.example/native:v8" - assert create["cpuCount"] == 2 and create["memoryMB"] == 4096 - sandbox = next( - body - for method, path, body in platform.calls - if method == "POST" and path.endswith("/sandboxes") - ) - assert sandbox == { - "templateID": "template-new", - "timeout": 3600, - "metadata": {"purpose": "deepseek-harness-native-web-preview"}, - "secure": True, - } - preview.close() - preview.close() - deletes = [path for method, path, body in platform.calls if method == "DELETE"] - assert deletes == [ - "/api/v1/agentstudio/sandbox/sandboxes/sandbox-1", - "/api/v1/agentstudio/sandbox/templates/template-new", - ] - assert platform.subscriptions == set() - assert "/__preview/" not in repr(preview) - - -@pytest.mark.parametrize("image_name", ["deepseek-harness", "openclaw"]) -@pytest.mark.parametrize( - "model_options,expected_model", - [ - ( - { - "model_base_url": "https://model.example/v1", - "model_id": "qwen3.7-plus", - "model_api_key": "model-secret", - }, - { - "baseUrl": "https://model.example/v1", - "modelName": "qwen3.7-plus", - "apiKey": "model-secret", - }, - ), - ( - {"model_base_url": "https://model.example/v1"}, - {"baseUrl": "https://model.example/v1", "modelName": "qwen3.7-plus"}, - ), - ( - { - "model_base_url": "https://model.example/v1", - "model_id": "qwen3.7-plus", - "model_api_key": " ", - }, - {"baseUrl": "https://model.example/v1", "modelName": "qwen3.7-plus"}, - ), - ({}, None), - ], - ids=["explicit-model", "url-only-default", "empty-key", "image-defaults"], -) -def test_fresh_preview_uses_same_model_for_template_and_instance( - monkeypatch, image_name, model_options, expected_model -): - from dashscope.applications.agentstudio.sandbox.models import OfficialImage - from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient - - web_ui = prepare_local_preview(monkeypatch) - prepared = [] - - def prepare(*args): - prepared.append(args) - return SimpleNamespace(openclaw=image_name == "openclaw") - - monkeypatch.setattr(web_ui._bootstrap, "prepare", prepare) - platform = FakePlatform() - with web_ui.open_web_ui( - SandboxesClient(platform), - platform, - OfficialImage(image_name), - web_ui.WebUiOptions(**model_options), - ): - create = next( - body - for method, path, body in platform.calls - if path.endswith("/v3/templates") - ) - if expected_model is None: - assert "modelConfig" not in create - assert prepared[0][4:7] == ("", "", "") - else: - assert create["modelConfig"] == expected_model - assert prepared[0][4:7] == ( - expected_model["baseUrl"], - expected_model["modelName"], - expected_model.get("apiKey", ""), - ) - - -@pytest.mark.parametrize( - "options,deletes", - [ - ({"sandbox_id": "sandbox-1"}, []), - ( - {"ready_template_id": "template-new"}, - ["/api/v1/agentstudio/sandbox/sandboxes/sandbox-1"], - ), - ( - { - "ready_template_id": "template-new", - "model_base_url": "https://model.example/v1", - "model_id": "qwen3.7-plus", - }, - ["/api/v1/agentstudio/sandbox/sandboxes/sandbox-1"], - ), - ], -) -def test_reuse_preserves_borrowed_resources(monkeypatch, options, deletes): - from dashscope.applications.agentstudio.sandbox.models import OfficialImage - from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient - - web_ui = prepare_local_preview(monkeypatch) - platform = FakePlatform() - with web_ui.open_web_ui( - SandboxesClient(platform), - platform, - OfficialImage.DEEPSEEK_HARNESS, - web_ui.WebUiOptions(**options), - ): - pass - assert [ - path for method, path, body in platform.calls if method == "DELETE" - ] == deletes - assert not any( - "/template-config" in path or "/images/" in path or "/v3/templates" in path - for method, path, body in platform.calls - ) - assert not any( - method in ("POST", "PUT", "PATCH") and "/templates/" in path - for method, path, body in platform.calls - ) - - -def test_connect_failure_still_releases_new_sandbox_and_template(monkeypatch): - from dashscope.applications.agentstudio.sandbox.models import OfficialImage - from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient - from dashscope.applications.agentstudio.sandbox.exceptions import SandboxAPIError - - web_ui = prepare_local_preview(monkeypatch) - platform = FakePlatform(fail_connect=True, release_fails=True) - with pytest.raises(SandboxAPIError, match="native Web UI"): - web_ui.open_web_ui( - SandboxesClient(platform), platform, OfficialImage.DEEPSEEK_HARNESS - ) - assert [path for method, path, body in platform.calls if method == "DELETE"] == [ - "/api/v1/agentstudio/sandbox/sandboxes/sandbox-1", - "/api/v1/agentstudio/sandbox/templates/template-new", - ] - - -def test_ready_template_mismatch_preserves_existing_sandbox(monkeypatch): - from dashscope.applications.agentstudio.sandbox.models import OfficialImage - from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient - - web_ui = prepare_local_preview(monkeypatch) - platform = FakePlatform() - with pytest.raises(ValueError, match="ready_template_id"): - web_ui.open_web_ui( - SandboxesClient(platform), - platform, - OfficialImage.DEEPSEEK_HARNESS, - web_ui.WebUiOptions(sandbox_id="sandbox-1", ready_template_id="wrong"), - ) - assert not any(method == "DELETE" for method, path, body in platform.calls) - - -def test_local_proxy_real_node_uses_private_stdin_and_one_time_cookie(): - import shutil - import threading - from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer - from dashscope.applications.agentstudio.sandbox._bootstrap import _Route - from dashscope.applications.agentstudio.sandbox.web_ui import ( - _Resources, - _check_node, - ) - - if not shutil.which("node"): - pytest.skip("Node.js is not installed") - try: - _check_node() - except Exception: - pytest.skip("Node.js --use-system-ca support is unavailable") - seen = [] - - class Handler(BaseHTTPRequestHandler): - def log_message(self, *args): - pass - - def do_GET(self): - seen.append( - ( - self.path, - self.headers.get("cookie"), - self.headers.get("x-access-token"), - ) - ) - if self.path == "/?token=native-secret": - self.send_response(303) - self.send_header("Set-Cookie", "dsh=native-cookie; HttpOnly") - self.send_header("Location", "/") - self.end_headers() - else: - self.send_response(200) - self.send_header("Content-Type", "text/html") - self.end_headers() - self.wfile.write(b"native preview") - - server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) - thread = threading.Thread(target=server.serve_forever, daemon=True) - thread.start() - resources = _Resources(SimpleNamespace(), FakePlatform()) - try: - address = resources.start_proxy( - _Route( - "http://127.0.0.1:" + str(server.server_port) + "/", - "native-secret", - {"x-access-token": "envd-secret"}, - False, - None, - ), - False, - ) - script = resources.script - proxy = resources.proxy - assert "native-secret" not in open(script).read() - assert "native-secret" not in repr(proxy.args) - origin = address.split("/__preview/")[0] - with httpx.Client(trust_env=False) as browser: - assert browser.get(origin).status_code == 403 - entry = browser.get(address) - assert entry.status_code == 303 - assert "native-secret" not in entry.headers.get("set-cookie", "") - assert browser.get(origin).text == "native preview" - assert browser.get(address).status_code != 303 - assert seen[0] == ("/?token=native-secret", None, "envd-secret") - assert seen[1][1:] == ("dsh=native-cookie", "envd-secret") - finally: - resources.close() - server.shutdown() - server.server_close() - assert proxy.poll() is not None - assert not __import__("os").path.exists(script) - - -def test_client_context_closes_preview_before_pool_and_releases_owned_resources( - monkeypatch, -): - from dashscope.applications.agentstudio.sandbox.client import SandboxClient - from dashscope.applications.agentstudio.sandbox.models import OfficialImage - - prepare_local_preview(monkeypatch) - platform = FakePlatform() - - def reply(request): - body = json.loads(request.content) if request.content else None - result = platform.request(request.method, request.url.path, json=body) - if request.url.path.endswith("/template-config"): - result = {"data": result} - return httpx.Response(200, json=result) - - with httpx.Client(transport=httpx.MockTransport(reply)) as pool: - with SandboxClient( - base_url="https://platform.example", - api_key="platform-secret", - http_client=pool, - ) as client: - preview = client.sandboxes.open_web_ui(OfficialImage.DEEPSEEK_HARNESS) - assert not pool.is_closed - assert preview._resources._closed - assert [path for method, path, body in platform.calls if method == "DELETE"] == [ - "/api/v1/agentstudio/sandbox/sandboxes/sandbox-1", - "/api/v1/agentstudio/sandbox/templates/template-new", - ] - - -def test_proxy_start_failure_kills_child_and_removes_script(monkeypatch): - from dashscope.applications.agentstudio.sandbox import web_ui as _web_ui - from dashscope.applications.agentstudio.sandbox._bootstrap import _Route - from dashscope.applications.agentstudio.sandbox.models import OfficialImage - from dashscope.applications.agentstudio.sandbox.sandboxes import SandboxesClient - from dashscope.applications.agentstudio.sandbox.exceptions import SandboxAPIError - - monkeypatch.setattr(_web_ui, "_check_node", lambda: None) - route = _Route("https://upstream.example/", "login-secret", {}, False, None) - monkeypatch.setattr(_web_ui._bootstrap, "prepare", lambda *args: route) - children = [] - - class Child: - def __init__(self, args, **kwargs): - self.args, self.stdin, self.stdout, self.killed = ( - args, - io.BytesIO(), - io.BytesIO(b"https://outside.example/\n"), - False, - ) - children.append(self) - - def poll(self): - return -9 if self.killed else None - - def kill(self): - self.killed = True - - def wait(self, timeout=None): - return -9 - - monkeypatch.setattr(_web_ui.subprocess, "Popen", Child) - platform = FakePlatform() - with pytest.raises(SandboxAPIError, match="native Web UI"): - _web_ui.open_web_ui( - SandboxesClient(platform), platform, OfficialImage.DEEPSEEK_HARNESS - ) - assert children[0].killed - assert not __import__("os").path.exists(children[0].args[2]) - assert len([1 for method, path, body in platform.calls if method == "DELETE"]) == 2 - - -@pytest.mark.parametrize("cancel", [False, True]) -def test_async_preview_owns_sync_client_and_cleans_after_cancellation( - monkeypatch, cancel -): - import asyncio - import threading - from dashscope.applications.agentstudio.sandbox import client as _client - from dashscope.applications.agentstudio.sandbox.models import OfficialImage - - web_ui = prepare_local_preview(monkeypatch) - platform = FakePlatform() - - def reply(request): - result = platform.request( - request.method, - request.url.path, - json=json.loads(request.content) if request.content else None, - ) - return httpx.Response( - 200, - json=( - {"data": result} - if request.url.path.endswith("/template-config") - else result - ), - ) - - original = _client.SandboxClient - owned = [] - with httpx.Client(transport=httpx.MockTransport(reply)) as pool: - - def create(**kwargs): - client = original(**kwargs, http_client=pool) - owned.append(client) - return client - - monkeypatch.setattr(_client, "SandboxClient", create) - started, proceed = threading.Event(), threading.Event() - - def ready(*args): - started.set() - assert proceed.wait(5) - return "http://127.0.0.1:12345/__preview/entry" - - monkeypatch.setattr(web_ui._Resources, "start_proxy", ready) - - async def exercise(): - async with httpx.AsyncClient( - transport=httpx.MockTransport( - lambda request: pytest.fail( - "Async HTTP pool crossed into native setup" - ) - ) - ) as async_pool: - async with _client.AsyncSandboxClient( - base_url="https://platform.example", - api_key="platform-secret", - http_client=async_pool, - ) as client: - pending = asyncio.create_task( - client.sandboxes.open_web_ui(OfficialImage.DEEPSEEK_HARNESS) - ) - assert await asyncio.to_thread(started.wait, 5) - if cancel: - pending.cancel() - proceed.set() - if cancel: - with pytest.raises(asyncio.CancelledError): - await pending - else: - preview = await pending - assert preview._resources.owned_client is owned[0] - assert not owned[0]._transport._closed - async with preview: - pass - assert owned[0]._transport._closed - assert not client._transport._subscriptions - assert not async_pool.is_closed - - asyncio.run(exercise()) - assert len([1 for method, path, body in platform.calls if method == "DELETE"]) == 2 - - -def test_web_ui_requires_explicit_supported_image_enum(): - from dashscope.applications.agentstudio.sandbox.web_ui import ( - WebUiOptions, - _validate, - ) - - with pytest.raises(ValueError, match="image"): - _validate("deepseek-harness", WebUiOptions()) - - -@pytest.mark.parametrize("asynchronous", [False, True]) -@pytest.mark.parametrize("lifecycle", ["closed", "closing"]) -def test_web_ui_does_not_start_setup_after_client_shutdown( - monkeypatch, asynchronous, lifecycle -): - import asyncio - from dashscope.applications.agentstudio.sandbox import ( - AsyncSandboxClient, - OfficialImage, - SandboxClient, - client as _client, - web_ui as _web_ui, - ) - - requests = [] - - def handle(request): - requests.append(request) - raise AssertionError("Shutdown client must not provision resources") - - def reject_node_check(): - raise AssertionError("Shutdown client must not check Node") - - def reject_owned_client(**kwargs): - raise AssertionError("Shutdown client must not create a worker HTTP pool") - - monkeypatch.setattr(_web_ui, "_check_node", reject_node_check) - if not asynchronous: - pool = httpx.Client(transport=httpx.MockTransport(handle)) - client = SandboxClient( - base_url="https://unit.test", api_key="key", http_client=pool - ) - try: - if lifecycle == "closed": - client.close() - else: - client._transport._take_subscriptions() - with pytest.raises(ValueError, match="Sandbox client is closed"): - client.sandboxes.open_web_ui(OfficialImage.DEEPSEEK_HARNESS) - assert not requests - finally: - client._transport._closing = False - client.close() - pool.close() - return - - async def run(): - pool = httpx.AsyncClient(transport=httpx.MockTransport(handle)) - client = AsyncSandboxClient( - base_url="https://unit.test", api_key="key", http_client=pool - ) - monkeypatch.setattr(_client, "SandboxClient", reject_owned_client) - try: - if lifecycle == "closed": - await client.aclose() - else: - client._transport._take_subscriptions() - with pytest.raises(ValueError, match="Sandbox client is closed"): - await client.sandboxes.open_web_ui(OfficialImage.DEEPSEEK_HARNESS) - assert not requests - finally: - client._transport._closing = False - await client.aclose() - await pool.aclose() - - asyncio.run(run()) - - -@pytest.mark.parametrize("asynchronous", [False, True]) -@pytest.mark.parametrize("entry", ["closed_root", "closed_borrowed_pool"]) -def test_web_ui_rejects_a_closed_underlying_pool_before_native_setup( - monkeypatch, - asynchronous, - entry, -): - import asyncio - from dashscope import AsyncClient, Client - from dashscope.applications.agentstudio.sandbox import ( - AsyncSandboxClient, - OfficialImage, - SandboxClient, - client as _client, - web_ui as _web_ui, - ) - - requests = [] - - def handle(request): - requests.append(request) - raise AssertionError("Closed HTTP pool must not provision remote resources") - - def reject_setup(): - raise AssertionError("Closed HTTP pool must not check Node") - - def reject_worker(**kwargs): - raise AssertionError("Closed HTTP pool must not create a worker HTTP client") - - monkeypatch.setattr(_web_ui, "_check_node", reject_setup) - if not asynchronous: - pool = httpx.Client(transport=httpx.MockTransport(handle)) - if entry == "closed_root": - monkeypatch.setattr(httpx, "Client", lambda **kwargs: pool) - client = Client(base_url="https://unit.test/api/v1", api_key="key") - assert client.transport._owns_client - client.close() - sandbox = client.agentstudio.sandbox - else: - client = SandboxClient( - base_url="https://unit.test", api_key="key", http_client=pool - ) - pool.close() - sandbox = client - try: - with pytest.raises(ValueError, match="Sandbox client is closed"): - sandbox.sandboxes.open_web_ui(OfficialImage.DEEPSEEK_HARNESS) - assert not requests - finally: - client.close() - pool.close() - return - - async def run(): - pool = httpx.AsyncClient(transport=httpx.MockTransport(handle)) - if entry == "closed_root": - monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: pool) - client = AsyncClient(base_url="https://unit.test/api/v1", api_key="key") - assert client.transport._owns_client - await client.aclose() - sandbox = client.agentstudio.sandbox - else: - client = AsyncSandboxClient( - base_url="https://unit.test", api_key="key", http_client=pool - ) - await pool.aclose() - sandbox = client - monkeypatch.setattr(_client, "SandboxClient", reject_worker) - try: - with pytest.raises(ValueError, match="Sandbox client is closed"): - await sandbox.sandboxes.open_web_ui(OfficialImage.DEEPSEEK_HARNESS) - assert not requests - finally: - await client.aclose() - await pool.aclose() - - asyncio.run(run()) - - -@pytest.fixture -def openclaw_preview(): - """Run the bundled proxy against a local Gateway with no cloud credentials.""" - import hashlib - import shutil - import threading - from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer - - from dashscope.applications.agentstudio.sandbox._bootstrap import _Route - from dashscope.applications.agentstudio.sandbox.web_ui import ( - _Resources, - _check_node, - ) - - if not shutil.which("node"): - pytest.skip("Node.js is not installed") - try: - _check_node() - except Exception: - pytest.skip("Node.js --use-system-ca support is unavailable") - - running = [] - - def start(auto_pair=False, reason="not-paired", approval_succeeds=True): - state = SimpleNamespace(requests=[], approvals=[], connections=0) - - class PairingBootstrap: - def command(self, argv): - state.approvals.append(argv) - if not approval_succeeds: - raise OSError("Pairing denied by the Gateway") - return "" - - class Gateway(BaseHTTPRequestHandler): - def log_message(self, *args): - pass - - def record(self): - state.requests.append( - ( - self.path, - {key.lower(): value for key, value in self.headers.items()}, - ) - ) - - def do_HEAD(self): - self.do_GET() - - def do_POST(self): - self.do_GET() - - def do_GET(self): - self.record() - if self.headers.get("upgrade", "").lower() == "websocket": - self.websocket() - return - avatar = self.path == "/avatar/main?meta=1" - status = 200 - if avatar and self.headers.get("authorization") not in ( - "Bearer device-secret", - "Bearer gateway-secret", - ): - status = 401 - self.send_response(status) - self.send_header("Content-Type", "text/html") - self.send_header("Content-Disposition", "attachment") - self.send_header("Set-Cookie", "gateway=private-cookie") - self.end_headers() - if self.command != "HEAD": - self.wfile.write(b"
OpenClaw
") - - def websocket(self): - accept = hashlib.sha1( - ( - self.headers["sec-websocket-key"] - + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" - ).encode() - ).digest() - self.send_response(101) - self.send_header("Connection", "Upgrade") - self.send_header("Upgrade", "websocket") - self.send_header( - "Sec-WebSocket-Accept", base64.b64encode(accept).decode() - ) - self.end_headers() - self.connection.settimeout(5) - state.connections += 1 - current = state.connections - self.send_text({"type": "event", "event": "connect.challenge"}) - try: - opcode, _ = self.read_packet() - if opcode != 1: - return - if current > 1: - reply = { - "type": "res", - "id": "browser-connect", - "ok": True, - "payload": {"type": "hello-ok"}, - } - else: - reply = { - "type": "res", - "id": "browser-connect", - "ok": False, - "error": { - "code": "NOT_PAIRED", - "details": { - "code": "PAIRING_REQUIRED", - "reason": reason, - "requestedRole": "operator", - "requestId": "12345678-1234-1234-1234-123456789abc", - }, - }, - } - # Gateway messages may span multiple TCP reads. - self.send_text(reply, fragmented=True) - opcode, payload = self.read_packet() - if opcode == 8: - self.connection.sendall(bytes([0x88, len(payload)]) + payload) - except (OSError, EOFError): - pass - - def send_text(self, value, fragmented=False): - data = json.dumps(value).encode() - header = ( - bytes([0x81, len(data)]) - if len(data) < 126 - else b"\x81\x7e" + struct.pack(">H", len(data)) - ) - packet = header + data - if fragmented: - self.connection.sendall(packet[:3]) - self.connection.sendall(packet[3:]) - else: - self.connection.sendall(packet) - - def read_packet(self): - header = self.rfile.read(2) - if len(header) != 2: - raise EOFError() - length = header[1] & 127 - if length == 126: - length = struct.unpack(">H", self.rfile.read(2))[0] - mask = self.rfile.read(4) if header[1] & 128 else None - payload = self.rfile.read(length) - if len(payload) != length: - raise EOFError() - if mask: - payload = bytes( - value ^ mask[index % 4] for index, value in enumerate(payload) - ) - return header[0] & 15, payload - - server = ThreadingHTTPServer(("127.0.0.1", 0), Gateway) - thread = threading.Thread( - target=lambda: server.serve_forever(poll_interval=0.01), daemon=True - ) - thread.start() - resources = _Resources(SimpleNamespace(), FakePlatform()) - running.append((resources, server, thread)) - state.upstream = "http://127.0.0.1:" + str(server.server_port) - address = resources.start_proxy( - _Route( - state.upstream + "/", - "gateway-secret", - { - "x-access-token": "fc-envd-secret", - "e2b-traffic-access-token": "fc-traffic-secret", - "e2b-sandbox-id": "sandbox-test", - "e2b-sandbox-port": "18789", - }, - True, - PairingBootstrap(), - ), - auto_pair, - ) - state.origin = address.split("/__preview/")[0] - state.entry = address - return state - - try: - yield start - finally: - for resources, server, thread in reversed(running): - try: - resources.close() - finally: - server.shutdown() - server.server_close() - thread.join(timeout=5) - - -@contextmanager -def _open_preview_browser(state): - with httpx.Client(trust_env=False, timeout=3) as browser: - opened = browser.get(state.entry) - assert opened.status_code == 303 - assert opened.headers["location"] == "/#token=gateway-secret" - assert "gateway-secret" not in opened.headers["set-cookie"] - yield browser - - -def _connect_preview_socket(state, browser, origin=None, headers=None): - import websocket - - return websocket.create_connection( - state.origin.replace("https://", "ws://") + "/", - timeout=3, - origin=origin or state.origin, - cookie="; ".join(key + "=" + value for key, value in browser.cookies.items()), - header=headers, - http_no_proxy=["127.0.0.1"], - ) - - -@pytest.mark.parametrize( - "enabled,reason,approval_succeeds", - [ - (True, "not-paired", True), - (True, "not-paired", False), - (False, "not-paired", False), - (True, "scope-upgrade", False), - ], -) -def test_openclaw_pairs_only_the_authorized_browser_request( - openclaw_preview, enabled, reason, approval_succeeds -): - import websocket - - state = openclaw_preview(enabled, reason, approval_succeeds) - with _open_preview_browser(state) as browser: - socket = _connect_preview_socket(state, browser) - try: - assert json.loads(socket.recv())["event"] == "connect.challenge" - socket.send('{"type":"req","id":"browser-connect","method":"connect"}') - if enabled and reason == "not-paired": - if not approval_succeeds: - refusal = json.loads(socket.recv()) - assert refusal["error"]["details"]["reason"] == "not-paired" - opcode, payload = socket.recv_data(control_frame=True) - assert opcode == websocket.ABNF.OPCODE_CLOSE - assert struct.unpack(">H", payload[:2])[0] == ( - 1012 if approval_succeeds else 1008 - ) - assert len(state.approvals) == 1 - assert state.approvals[0][-1] == "12345678-1234-1234-1234-123456789abc" - else: - refusal = json.loads(socket.recv()) - assert refusal["error"]["details"]["reason"] == reason - assert state.approvals == [] - finally: - socket.close() - if approval_succeeds: - reconnected = _connect_preview_socket(state, browser) - try: - assert json.loads(reconnected.recv())["event"] == "connect.challenge" - reconnected.send( - '{"type":"req","id":"browser-connect","method":"connect"}' - ) - assert json.loads(reconnected.recv())["payload"]["type"] == "hello-ok" - assert len(state.approvals) == 1 - finally: - reconnected.close() - - -@pytest.mark.parametrize( - "method,path,authorization,status,forwarded", - [ - ( - "GET", - "/avatar/main?meta=1", - "Bearer device-secret", - 200, - "Bearer device-secret", - ), - ( - "HEAD", - "/avatar/main?meta=1", - "Bearer device-secret", - 200, - "Bearer device-secret", - ), - ( - "GET", - "/avatar/main?meta=1", - "Bearer gateway-secret", - 200, - "Bearer gateway-secret", - ), - ("GET", "/avatar/main?meta=1", "Bearer invalid", 401, "Bearer invalid"), - ("GET", "/avatar/main?meta=1", "Basic device-secret", 401, None), - ("POST", "/avatar/main?meta=1", "Bearer device-secret", 401, None), - ("GET", "/avatar/main/extra", "Bearer device-secret", 200, None), - ("GET", "/", "Bearer device-secret", 200, None), - ("GET", "/", "Bearer gateway-secret", 200, "Bearer gateway-secret"), - ], -) -def test_openclaw_forwards_device_bearer_only_for_avatar_reads( - openclaw_preview, method, path, authorization, status, forwarded -): - state = openclaw_preview() - with _open_preview_browser(state) as browser: - response = browser.request( - method, state.origin + path, headers={"Authorization": authorization} - ) - assert response.status_code == status - assert state.requests[-1][1].get("authorization") == forwarded - assert "set-cookie" not in response.headers - assert "content-disposition" not in response.headers - assert response.headers["cache-control"] == "no-store" - before = len(state.requests) - with httpx.Client(trust_env=False, timeout=3) as unauthenticated: - assert ( - unauthenticated.get( - state.origin + path, headers={"Authorization": authorization} - ).status_code - == 403 - ) - assert len(state.requests) == before - - -def test_openclaw_isolates_browser_origin_and_private_headers(openclaw_preview): - import websocket - - state = openclaw_preview() - spoofed = { - "Origin": state.origin, - "Referer": state.origin + "/?token=browser-secret", - "Forwarded": "for=untrusted", - "X-Forwarded-For": "untrusted", - "X-Forwarded-Host": "untrusted.example", - "X-Access-Token": "browser-envd-secret", - "E2B-Traffic-Access-Token": "browser-traffic-secret", - "E2B-Sandbox-Id": "browser-sandbox", - "E2B-Sandbox-Port": "1", - "Proxy-Authorization": "Bearer browser-proxy-secret", - "Authorization": "Bearer device-secret", - } - with _open_preview_browser(state) as browser: - assert browser.get(state.origin, headers=spoofed).status_code == 200 - path, forwarded = state.requests[-1] - assert path == "/" - assert forwarded["origin"] == state.upstream - assert forwarded["x-access-token"] == "fc-envd-secret" - assert forwarded["e2b-traffic-access-token"] == "fc-traffic-secret" - assert forwarded["e2b-sandbox-id"] == "sandbox-test" - assert forwarded["e2b-sandbox-port"] == "18789" - for name in ( - "cookie", - "authorization", - "proxy-authorization", - "referer", - "forwarded", - ): - assert name not in forwarded - assert not any(name.startswith("x-forwarded-") for name in forwarded) - before = len(state.requests) - for headers in ( - {"Origin": "http://unrelated.example"}, - {"Sec-Fetch-Site": "cross-site"}, - {"Host": "unrelated.example"}, - ): - assert browser.get(state.origin, headers=headers).status_code == 403 - assert len(state.requests) == before - with pytest.raises(websocket.WebSocketBadStatusException) as denied: - _connect_preview_socket(state, browser, origin="http://unrelated.example") - assert denied.value.status_code == 403 - assert len(state.requests) == before - socket = _connect_preview_socket( - state, - browser, - headers={key: value for key, value in spoofed.items() if key != "Origin"}, - ) - try: - assert json.loads(socket.recv())["event"] == "connect.challenge" - forwarded = state.requests[-1][1] - assert forwarded["origin"] == state.upstream - assert forwarded["x-access-token"] == "fc-envd-secret" - assert forwarded["e2b-traffic-access-token"] == "fc-traffic-secret" - assert "cookie" not in forwarded - assert "authorization" not in forwarded - assert "referer" not in forwarded - assert "proxy-authorization" not in forwarded - assert "forwarded" not in forwarded - assert not any(name.startswith("x-forwarded-") for name in forwarded) - finally: - socket.close() From 33e3cdee737d3f8ce8c302c11a4d574ed75c0379 Mon Sep 17 00:00:00 2001 From: "guning.lt" Date: Thu, 3 Dec 2026 10:56:16 +0800 Subject: [PATCH 6/7] sandbox api --- dashscope/applications/agentstudio/client.py | 4 + .../agentstudio/sandbox/_bootstrap.py | 132 ++++-- .../agentstudio/sandbox/_validation.py | 30 +- .../agentstudio/sandbox/agents.py | 380 ++++++++++++++---- .../agentstudio/sandbox/client.py | 12 +- .../agentstudio/sandbox/models.py | 175 ++++++-- .../agentstudio/sandbox/sandboxes.py | 86 ++-- .../agentstudio/sandbox/streaming.py | 50 ++- .../agentstudio/sandbox/template_files.py | 126 ++++-- .../agentstudio/sandbox/templates.py | 145 +++++-- .../agentstudio/sandbox/transport.py | 92 ++++- .../agentstudio/sandbox/web_ui.py | 94 ++++- docs/en/reference/agentstudio.md | 144 +++++++ docs/zh/reference/agentstudio.md | 143 +++++++ tools/gen_reference.py | 1 + 15 files changed, 1294 insertions(+), 320 deletions(-) diff --git a/dashscope/applications/agentstudio/client.py b/dashscope/applications/agentstudio/client.py index 0bbb350f..756a97b5 100644 --- a/dashscope/applications/agentstudio/client.py +++ b/dashscope/applications/agentstudio/client.py @@ -243,6 +243,8 @@ def sandbox(self): base_url=self.transport.base_url, api_key=self.transport.api_key, timeout=_sandbox_timeout(self.transport.timeout), + # Share the parent HTTP pool without transferring ownership. + # pylint: disable-next=protected-access http_client=self.transport._client, ) return self._sandbox @@ -346,6 +348,8 @@ def sandbox(self): base_url=self.transport.base_url, api_key=self.transport.api_key, timeout=_sandbox_timeout(self.transport.timeout), + # Share the parent HTTP pool without transferring ownership. + # pylint: disable-next=protected-access http_client=self.transport._client, ) return self._sandbox diff --git a/dashscope/applications/agentstudio/sandbox/_bootstrap.py b/dashscope/applications/agentstudio/sandbox/_bootstrap.py index 3dd7b28b..43842197 100644 --- a/dashscope/applications/agentstudio/sandbox/_bootstrap.py +++ b/dashscope/applications/agentstudio/sandbox/_bootstrap.py @@ -22,7 +22,8 @@ _OPENCLAW_DIR = "/home/user/.openclaw/sdk-web-preview" _OPENCLAW_KEY = _OPENCLAW_DIR + "/model.key" -_DSH_START = r"""umask 077 +_DSH_START = ( + r"""umask 077 wrapper=$(mktemp -d) trap 'rm -rf -- "$wrapper"' EXIT cat > "$wrapper/dsh" <<'SH' @@ -39,7 +40,8 @@ fi unset DSH_PREVIEW_PLACEHOLDER if [ -f "$DSH_PREVIEW_PATCH" ]; then - exec /home/user/.dsh/bin/dsh --profile web --patch "$DSH_PREVIEW_PATCH" "$@" + exec /home/user/.dsh/bin/dsh --profile web --patch """ + r""""$DSH_PREVIEW_PATCH" "$@" fi exec /home/user/.dsh/bin/dsh web "$@" SH @@ -47,10 +49,13 @@ export PATH="$wrapper:$PATH" DSH_PREVIEW_PATCH="$1" DSH_PREVIEW_FRESH="$3" # 仅供镜像脚本启动检查。启动 DSH 进程前移除占位值。 export DSH_PREVIEW_PLACEHOLDER=unused-preview-placeholder -DEEPSEEK_API_KEY="${DEEPSEEK_API_KEY:-$DSH_PREVIEW_PLACEHOLDER}" /opt/deepseek-harness/start.sh --trusted-host "$2" +DEEPSEEK_API_KEY="${DEEPSEEK_API_KEY:-$DSH_PREVIEW_PLACEHOLDER}" """ + r""" /opt/deepseek-harness/start.sh --trusted-host "$2" """ +) -_OPENCLAW_START = r"""umask 077 +_OPENCLAW_START = ( + r"""umask 077 dir="$1" patch="$2" port="$3" @@ -63,11 +68,13 @@ exec 9>"$dir/start.lock" trap 'rm -f -- "$patch"' EXIT flock -w 15 9 -health() { curl --noproxy '*' -fsS --max-time 1 "http://127.0.0.1:$port/healthz" >/dev/null 2>&1; } +health() { curl --noproxy '*' -fsS --max-time 1 """ + r""""http://127.0.0.1:$port/healthz" >/dev/null 2>&1; } if [ -n "$(ss -H -ltn "sport = :$port")" ]; then pid=$(cat "$pid_file" 2>/dev/null || true) if [[ "$pid" =~ ^[1-9][0-9]*$ ]] && [ -s "$token_file" ] && - grep -zFxq "OPENCLAW_CONFIG_PATH=$OPENCLAW_CONFIG_PATH" "/proc/$pid/environ" 2>/dev/null && + grep -zFxq "OPENCLAW_CONFIG_PATH=$OPENCLAW_CONFIG_PATH" """ + r""""/proc/$pid/environ" 2>/dev/null && health; then printf 'OPENCLAW_WEB_TOKEN=%s\n' "$(cat "$token_file")" else @@ -77,14 +84,18 @@ fi if [ ! -s "$token_file" ]; then - "$node" -e 'process.stdout.write(require("node:crypto").randomBytes(32).toString("hex"))' > "$token_file" + "$node" -e """ + r"""'process.stdout.write(require("node:crypto").randomBytes(32).toStrin""" + r"""g("hex"))' > "$token_file" fi export OPENCLAW_GATEWAY_TOKEN="$(cat "$token_file")" -if [ ! -e "$OPENCLAW_CONFIG_PATH" ] && [ -f /home/user/.openclaw/openclaw.json ]; then +if [ ! -e "$OPENCLAW_CONFIG_PATH" ] && [ -f """ + r"""/home/user/.openclaw/openclaw.json ]; then cp /home/user/.openclaw/openclaw.json "$OPENCLAW_CONFIG_PATH" fi "$binary" config patch --file "$patch" > "$dir/setup.log" 2>&1 -nohup "$binary" gateway run --bind lan --auth token --port "$port" > "$dir/gateway.log" 2>&1 &- & +nohup "$binary" gateway run --bind lan --auth token --port "$port" """ + r""" > "$dir/gateway.log" 2>&1 &- & pid=$! trap 'kill "$pid" 2>/dev/null || true; rm -f -- "$patch"' EXIT deadline=$((SECONDS + 40)) @@ -100,6 +111,7 @@ done exit 1 """ +) _OPENCLAW_PREPARE = r"""umask 077 install -d -m 700 "$1" @@ -120,7 +132,9 @@ def _endpoint(value): try: parsed = urlsplit(value) local = parsed.scheme == "http" and parsed.hostname == "127.0.0.1" + # Validate the endpoint as one short-circuiting boundary. if ( + # pylint: disable-next=too-many-boolean-expressions not parsed.hostname or parsed.username is not None or parsed.password is not None @@ -130,7 +144,7 @@ def _endpoint(value): or any(ord(char) < 33 for char in value) ): raise ValueError() - parsed.port + _ = parsed.port return value if value.endswith("/") else value + "/" except (TypeError, ValueError): raise OSError("Invalid Sandbox endpoint") from None @@ -160,10 +174,12 @@ def _send(self, path, data, headers=None, params=None): "E2B-Sandbox-Id": self.sandbox_id, "E2B-Sandbox-Port": "49983", "Accept-Encoding": "identity", - } + }, ) if self.connection.traffic_access_token: - headers["E2B-Traffic-Access-Token"] = self.connection.traffic_access_token + headers[ + "E2B-Traffic-Access-Token" + ] = self.connection.traffic_access_token try: with httpx.Client(timeout=90.0, follow_redirects=False) as client: with client.stream( @@ -175,12 +191,15 @@ def _send(self, path, data, headers=None, params=None): ) as response: if not 200 <= response.status_code < 300: raise OSError( - "Sandbox data-plane HTTP " + str(response.status_code) + "Sandbox data-plane HTTP " + + str(response.status_code), ) body = bytearray() for chunk in response.iter_bytes(): if len(body) + len(chunk) > _MAX_RESPONSE: - raise OSError("Sandbox response exceeds its size limit") + raise OSError( + "Sandbox response exceeds its size limit", + ) body.extend(chunk) return bytes(body) except httpx.HTTPError: @@ -192,10 +211,14 @@ def command(self, argv): process = { "cmd": "/bin/sh", "cwd": "/home/user", - "args": ["-ec", "exec " + " ".join(shlex.quote(arg) for arg in argv)], + "args": [ + "-ec", + "exec " + " ".join(shlex.quote(arg) for arg in argv), + ], } message = json.dumps( - {"stdin": False, "process": process}, separators=(",", ":") + {"stdin": False, "process": process}, + separators=(",", ":"), ).encode() payload = b"\0" + struct.pack(">I", len(message)) + message return _stdout( @@ -207,7 +230,7 @@ def command(self, argv): "Connect-Protocol-Version": "1", "connect-content-encoding": "identity", }, - ) + ), ) def put_file(self, path, data): @@ -233,11 +256,13 @@ def start_dsh(self, host, fresh, model_url, model_id, model_key): _DSH_PATCH, host, str(fresh).lower(), - ] + ], ) return _read_token(output, "DSH_WEB_TOKEN=") +# Keep Connect-RPC lifecycle validation in stream order. +# pylint: disable-next=too-many-branches def _stdout(response): offset, started, ended, finished = 0, False, False, False stdout = [] @@ -278,12 +303,16 @@ def _stdout(response): output = data.get("stdout") if isinstance(data, dict) else None if isinstance(output, str) and started: try: - stdout.append(base64.b64decode(output, validate=True).decode("utf-8")) + stdout.append( + base64.b64decode(output, validate=True).decode("utf-8"), + ) except (ValueError, UnicodeError, binascii.Error): raise OSError("Invalid Sandbox process output") from None if "end" in event: end = event["end"] + # Validate one complete process-end frame before accepting it. if ( + # pylint: disable-next=too-many-boolean-expressions not isinstance(end, dict) or not started or end.get("exited") is not True @@ -321,10 +350,11 @@ def _configure_dsh_model(bootstrap, url, model, key): "model-config", _DSH_CREDENTIALS, _DSH_PATCH, - ] + ], ) bootstrap.put_json( - _DSH_CREDENTIALS, {"version": 1, "refs": {"DASHSCOPE_API_KEY": key}} + _DSH_CREDENTIALS, + {"version": 1, "refs": {"DASHSCOPE_API_KEY": key}}, ) else: bootstrap.command( @@ -334,7 +364,7 @@ def _configure_dsh_model(bootstrap, url, model, key): 'umask 077; set -C; : > "$1"', "model-config", _DSH_PATCH, - ] + ], ) bootstrap.put_json( _DSH_PATCH, @@ -349,8 +379,8 @@ def _configure_dsh_model(bootstrap, url, model, key): "api": "openai-completions", "baseURL": url, "models": [{"id": model, "maxTokens": 8192}], - } - } + }, + }, }, }, { @@ -361,7 +391,14 @@ def _configure_dsh_model(bootstrap, url, model, key): ) -def _openclaw_config(origin, configure_model, model_url, model_id, model_api, has_key): +def _openclaw_config( + origin, + configure_model, + model_url, + model_id, + model_api, + has_key, +): config = { "gateway": { "mode": "local", @@ -386,7 +423,7 @@ def _openclaw_config(origin, configure_model, model_url, model_id, model_api, ha "dangerouslyAllowHostHeaderOriginFallback": False, "allowedOrigins": [origin], }, - } + }, } if configure_model: provider = { @@ -402,8 +439,8 @@ def _openclaw_config(origin, configure_model, model_url, model_id, model_api, ha "source": "file", "mode": "singleValue", "path": _OPENCLAW_KEY, - } - } + }, + }, } provider["apiKey"] = { "source": "file", @@ -411,13 +448,19 @@ def _openclaw_config(origin, configure_model, model_url, model_id, model_api, ha "id": "value", } config["agents"] = { - "defaults": {"model": {"primary": "bailian-qwen/" + model_id}} + "defaults": {"model": {"primary": "bailian-qwen/" + model_id}}, } return config def _start_openclaw( - bootstrap, origin, fresh, model_url, model_id, model_key, model_api + bootstrap, + origin, + fresh, + model_url, + model_id, + model_key, + model_api, ): patch = _OPENCLAW_DIR + "/patch-" + str(uuid.uuid4()) + ".json" configure_model = fresh and bool(model_url) @@ -432,14 +475,19 @@ def _start_openclaw( patch, str(write_key).lower(), _OPENCLAW_KEY, - ] + ], ) if write_key: bootstrap.put_file(_OPENCLAW_KEY, model_key.encode()) bootstrap.put_json( patch, _openclaw_config( - origin, configure_model, model_url, model_id, model_api, write_key + origin, + configure_model, + model_url, + model_id, + model_api, + write_key, ), ) output = bootstrap.command( @@ -451,7 +499,7 @@ def _start_openclaw( _OPENCLAW_DIR, patch, "18789", - ] + ], ) if "OPENCLAW_WEB_PORT_IN_USE" in output.splitlines(): raise SandboxAPIError( @@ -463,7 +511,8 @@ def _start_openclaw( def _approve_pairing(bootstrap, request_id): if not re.fullmatch( - r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", request_id + r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", + request_id, ): raise OSError("Invalid OpenClaw pairing request ID") bootstrap.command( @@ -474,7 +523,7 @@ def _approve_pairing(bootstrap, request_id): "approve-openclaw-device", _OPENCLAW_DIR, request_id, - ] + ], ) @@ -490,13 +539,20 @@ def prepare( ): from .models import OfficialImage - if connection is None or not connection.domain or not connection.envd_access_token: + if ( + connection is None + or not connection.domain + or not connection.envd_access_token + ): raise OSError("Incomplete Sandbox connection information") openclaw = image == OfficialImage.OPENCLAW port = 18789 if openclaw else 8080 host = str(port) + "-" + sandbox_id + "." + connection.domain upstream = _endpoint("https://" + host) - if urlsplit(upstream).netloc != host or urlsplit(upstream).hostname != host: + if ( + urlsplit(upstream).netloc != host + or urlsplit(upstream).hostname != host + ): raise OSError("Invalid Sandbox Web endpoint") bootstrap = _Bootstrap(sandbox_id, connection) token = ( @@ -521,6 +577,6 @@ def prepare( "x-access-token": connection.envd_access_token, "e2b-sandbox-id": sandbox_id, "e2b-sandbox-port": str(port), - } + }, ) return _Route(upstream, token, headers, openclaw, bootstrap) diff --git a/dashscope/applications/agentstudio/sandbox/_validation.py b/dashscope/applications/agentstudio/sandbox/_validation.py index 290f19bb..25e04f5e 100644 --- a/dashscope/applications/agentstudio/sandbox/_validation.py +++ b/dashscope/applications/agentstudio/sandbox/_validation.py @@ -60,10 +60,10 @@ def deadline(wait: Real) -> float: return time.monotonic() + positive(wait, "timeout") -def remaining(end: float, resource_id: str, status: str) -> float: +def remaining(end: float, identifier: str, status: str) -> float: result = end - time.monotonic() if result <= 0: - raise SandboxWaitTimeoutError(resource_id, status) + raise SandboxWaitTimeoutError(identifier, status) return result @@ -75,7 +75,9 @@ def filename(value: str) -> str: or "\\" in value or any(ord(c) < 32 or ord(c) == 127 for c in value) ): - raise ValueError("filename must be a file name without path components") + raise ValueError( + "filename must be a file name without path components", + ) return value @@ -86,7 +88,9 @@ def http_url(value: str, name: str = "base_url") -> str: port = parsed.port except ValueError: raise ValueError(f"{name} must be a valid HTTP(S) URL") from None + # Keep URL credential, host and control-character checks together. if ( + # pylint: disable-next=too-many-boolean-expressions parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.username is not None @@ -96,11 +100,19 @@ def http_url(value: str, name: str = "base_url") -> str: or any(ord(c) < 33 or ord(c) == 127 for c in value) or port == 0 ): - raise ValueError(f"{name} must be an HTTP(S) URL without credentials or query") - return urlunsplit((parsed.scheme, parsed.netloc, parsed.path.rstrip("/"), "", "")) - - -def bounded_stream(stream: BinaryIO, limit: int, size: int = -1) -> Iterator[bytes]: + raise ValueError( + f"{name} must be an HTTP(S) URL without credentials or query", + ) + return urlunsplit( + (parsed.scheme, parsed.netloc, parsed.path.rstrip("/"), "", ""), + ) + + +def bounded_stream( + stream: BinaryIO, + limit: int, + size: int = -1, +) -> Iterator[bytes]: """Upload in chunks and close the supplied content on every exit path.""" count = 0 try: @@ -115,7 +127,7 @@ def bounded_stream(stream: BinaryIO, limit: int, size: int = -1) -> Iterator[byt if not isinstance(chunk, bytes): raise ValueError("Upload content must be a binary stream") count += len(chunk) - if count > limit or (size >= 0 and count > size): + if count > limit or (0 <= size < count): raise ValueError("File exceeds the instance upload limit") yield chunk if size >= 0 and count != size: diff --git a/dashscope/applications/agentstudio/sandbox/agents.py b/dashscope/applications/agentstudio/sandbox/agents.py index c57dfbd8..38b401f1 100644 --- a/dashscope/applications/agentstudio/sandbox/agents.py +++ b/dashscope/applications/agentstudio/sandbox/agents.py @@ -39,7 +39,11 @@ def _page_params(limit: int, cursor: Optional[str]) -> dict: - if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 100: + if ( + isinstance(limit, bool) + or not isinstance(limit, int) + or not 1 <= limit <= 100 + ): raise ValueError("limit must be between 1 and 100") params: dict[str, Any] = {"limit": limit} if cursor is not None: @@ -50,7 +54,10 @@ def _page_params(limit: int, cursor: Optional[str]) -> dict: def _response_id(data: dict, name: str) -> str: value = data.get(name) if not isinstance(value, str) or not value.strip(): - raise SandboxAPIError("Missing response identifier", code="INVALID_RESPONSE") + raise SandboxAPIError( + "Missing response identifier", + code="INVALID_RESPONSE", + ) resource_id(value) return value @@ -60,7 +67,7 @@ def _operation_result(info: AgentOperationInfo) -> AgentOperationInfo: error = info.error code = error.get("code") if isinstance(error, dict) else None failure = SandboxAPIError( - "Operation {} ended with {}".format(info.id, info.status), + f"Operation {info.id} ended with {info.status}", code=code or "OPERATION_" + info.status, outcome_unknown=info.status == "UNKNOWN", ) @@ -83,7 +90,10 @@ def _wait( budget = remaining(end, identifier, status) try: data = transport.request( - "GET", path, agent=True, timeout=min(transport.timeout, budget) + "GET", + path, + agent=True, + timeout=min(transport.timeout, budget), ) except SandboxAPIError as error: if error.code == "REQUEST_TIMEOUT" and budget <= transport.timeout: @@ -93,7 +103,9 @@ def _wait( remaining(end, identifier, status) if status in terminal: return data - time.sleep(min(transport.poll_interval, remaining(end, identifier, status))) + time.sleep( + min(transport.poll_interval, remaining(end, identifier, status)), + ) async def _await( @@ -109,7 +121,10 @@ async def _await( budget = remaining(end, identifier, status) try: data = await transport.request( - "GET", path, agent=True, timeout=min(transport.timeout, budget) + "GET", + path, + agent=True, + timeout=min(transport.timeout, budget), ) except SandboxAPIError as error: if error.code == "REQUEST_TIMEOUT" and budget <= transport.timeout: @@ -120,7 +135,7 @@ async def _await( if status in terminal: return data await asyncio.sleep( - min(transport.poll_interval, remaining(end, identifier, status)) + min(transport.poll_interval, remaining(end, identifier, status)), ) @@ -159,13 +174,17 @@ def _prompt( def _upload_source( - name_or_path: Union[str, Path], stream: Optional[BinaryIO], size_bytes: int + name_or_path: Union[str, Path], + stream: Optional[BinaryIO], + size_bytes: int, ) -> tuple[str, BinaryIO, int]: if stream is None: path = Path(name_or_path) if not path.is_file(): raise ValueError("upload path must be a regular file") name = filename(path.name) + # Upload owns this stream after the metadata read succeeds. + # pylint: disable-next=consider-using-with source = path.open("rb") try: return name, source, path.stat().st_size @@ -191,7 +210,8 @@ def _uploaded(data: dict, identifier: str, size: int) -> UploadedFile: size >= 0 and uploaded.size_bytes != size ): raise SandboxAPIError( - "Uploaded file does not match the instance or size", code="INVALID_RESPONSE" + "Uploaded file does not match the instance or size", + code="INVALID_RESPONSE", ) return uploaded @@ -202,15 +222,21 @@ def __init__(self, transport: Transport): def template_config(self) -> AgentTemplateConfig: return AgentTemplateConfig.from_dict( - self._transport.request("GET", AGENT + "/template-config", agent=True) + self._transport.request( + "GET", + AGENT + "/template-config", + agent=True, + ), ) def launch_async(self, request: LaunchRequest) -> LaunchOperation: - """Accept a launch operation without waiting for the instance to become ready.""" + """Accept launch without waiting for the instance to become ready.""" return self._launch(request) def _launch( - self, request: LaunchRequest, timeout: Optional[float] = None + self, + request: LaunchRequest, + timeout: Optional[float] = None, ) -> LaunchOperation: data = self._transport.request( "POST", @@ -220,36 +246,54 @@ def _launch( timeout=timeout, ) return LaunchOperation( - self, _response_id(data, "instance_id"), _response_id(data, "operation_id") + self, + _response_id(data, "instance_id"), + _response_id(data, "operation_id"), ) - def launch(self, request: LaunchRequest, timeout: float = 600) -> AgentHandle: + def launch( + self, + request: LaunchRequest, + timeout: float = 600, + ) -> AgentHandle: end = deadline(timeout) operation = self._launch( - request, min(self._transport.timeout, remaining(end, "launch", "PENDING")) + request, + min(self._transport.timeout, remaining(end, "launch", "PENDING")), + ) + return operation.wait( + remaining(end, operation.operation_id, "PENDING"), ) - return operation.wait(remaining(end, operation.operation_id, "PENDING")) def list_instances( - self, limit: int = 50, cursor: Optional[str] = None + self, + limit: int = 50, + cursor: Optional[str] = None, ) -> AgentPage[AgentInstanceInfo]: data = self._transport.request( - "GET", AGENT + "/instances", params=_page_params(limit, cursor), agent=True + "GET", + AGENT + "/instances", + params=_page_params(limit, cursor), + agent=True, ) return AgentPage[AgentInstanceInfo].from_dict(data) def get_instance(self, instance_id: str) -> AgentInstanceInfo: return AgentInstanceInfo.from_dict( self._transport.request( - "GET", AGENT + "/instances/" + resource_id(instance_id), agent=True - ) + "GET", + AGENT + "/instances/" + resource_id(instance_id), + agent=True, + ), ) def connect(self, instance_id: str) -> AgentHandle: return self._connect(instance_id) def _connect( - self, instance_id: str, timeout: Optional[float] = None + self, + instance_id: str, + timeout: Optional[float] = None, ) -> AgentHandle: data = self._transport.request( "GET", @@ -260,7 +304,7 @@ def _connect( info = AgentInstanceInfo.from_dict(data) if info.state != "READY": raise SandboxAPIError( - "Instance {} is not ready".format(instance_id), + f"Instance {instance_id} is not ready", code="INSTANCE_NOT_READY", ) return AgentHandle( @@ -272,7 +316,9 @@ def _connect( def release(self, instance_id: str) -> OperationHandle: data = self._transport.request( - "DELETE", AGENT + "/instances/" + resource_id(instance_id), agent=True + "DELETE", + AGENT + "/instances/" + resource_id(instance_id), + agent=True, ) return self.operation(_response_id(data, "operation_id")) @@ -286,7 +332,10 @@ def turn(self, turn_id: str) -> TurnHandle: return TurnHandle(self._transport, turn_id) def list_sessions( - self, instance_id: str, limit: int = 50, cursor: Optional[str] = None + self, + instance_id: str, + limit: int = 50, + cursor: Optional[str] = None, ) -> AgentPage[AgentSessionInfo]: data = self._transport.request( "GET", @@ -298,7 +347,12 @@ def list_sessions( class LaunchOperation: - def __init__(self, agents: AgentsClient, instance_id: str, operation_id: str): + def __init__( + self, + agents: AgentsClient, + instance_id: str, + operation_id: str, + ): self._agents = agents self.instance_id = instance_id self.operation_id = operation_id @@ -306,19 +360,29 @@ def __init__(self, agents: AgentsClient, instance_id: str, operation_id: str): def wait(self, timeout: float = 600) -> AgentHandle: end = deadline(timeout) self._agents.operation(self.operation_id).wait( - remaining(end, self.operation_id, "PENDING") + remaining(end, self.operation_id, "PENDING"), ) budget = remaining(end, self.operation_id, "SUCCEEDED") try: + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access handle = self._agents._connect( - self.instance_id, min(self._agents._transport.timeout, budget) + self.instance_id, + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access + min(self._agents._transport.timeout, budget), ) except SandboxAPIError as error: if ( error.code == "REQUEST_TIMEOUT" + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access and budget <= self._agents._transport.timeout ): - raise SandboxWaitTimeoutError(self.operation_id, "SUCCEEDED") from error + raise SandboxWaitTimeoutError( + self.operation_id, + "SUCCEEDED", + ) from error raise remaining(end, self.operation_id, "SUCCEEDED") return handle @@ -336,7 +400,11 @@ def __init__( self.id = instance_id self._transport = transport self._info = info - self.default_session = SessionHandle(transport, default_session_id, instance_id) + self.default_session = SessionHandle( + transport, + default_session_id, + instance_id, + ) def get(self) -> AgentInstanceInfo: self._info = AgentsClient(self._transport).get_instance(self.id) @@ -352,12 +420,22 @@ def new_session(self) -> SessionHandle: json={}, agent=True, ) - return SessionHandle(self._transport, _response_id(data, "session_id"), self.id) + return SessionHandle( + self._transport, + _response_id(data, "session_id"), + self.id, + ) def list_sessions( - self, limit: int = 50, cursor: Optional[str] = None + self, + limit: int = 50, + cursor: Optional[str] = None, ) -> AgentPage[AgentSessionInfo]: - return AgentsClient(self._transport).list_sessions(self.id, limit, cursor) + return AgentsClient(self._transport).list_sessions( + self.id, + limit, + cursor, + ) def upload( self, @@ -397,7 +475,10 @@ def release(self) -> OperationHandle: class SessionHandle: def __init__( - self, transport: Transport, session_id: str, instance_id: Optional[str] = None + self, + transport: Transport, + session_id: str, + instance_id: Optional[str] = None, ): self.id = session_id self._transport = transport @@ -408,17 +489,30 @@ def submit(self, text: str, deadline_seconds: int = 120) -> TurnHandle: return self.submit_with_files(text, (), deadline_seconds) def submit_with_files( - self, text: str, files: Sequence[UploadedFile], deadline_seconds: int = 120 + self, + text: str, + files: Sequence[UploadedFile], + deadline_seconds: int = 120, ) -> TurnHandle: body = _prompt(text, files, deadline_seconds, self._instance_id) - data = self._transport.request("POST", self._path, json=body, agent=True) + data = self._transport.request( + "POST", + self._path, + json=body, + agent=True, + ) return TurnHandle(self._transport, _response_id(data, "turn_id")) def list_turns( - self, limit: int = 50, cursor: Optional[str] = None + self, + limit: int = 50, + cursor: Optional[str] = None, ) -> AgentPage[AgentTurnInfo]: data = self._transport.request( - "GET", self._path, params=_page_params(limit, cursor), agent=True + "GET", + self._path, + params=_page_params(limit, cursor), + agent=True, ) return AgentPage[AgentTurnInfo].from_dict(data) @@ -431,12 +525,18 @@ def __init__(self, transport: Transport, operation_id: str): def get(self) -> AgentOperationInfo: return AgentOperationInfo.from_dict( - self._transport.request("GET", self._path, agent=True) + self._transport.request("GET", self._path, agent=True), ) def wait(self, timeout: float = 600) -> AgentOperationInfo: info = AgentOperationInfo.from_dict( - _wait(self._transport, self._path, self.id, timeout, _OPERATION_TERMINAL) + _wait( + self._transport, + self._path, + self.id, + timeout, + _OPERATION_TERMINAL, + ), ) return _operation_result(info) @@ -449,23 +549,41 @@ def __init__(self, transport: Transport, turn_id: str): def get(self) -> TurnResult: return TurnResult.from_dict( - self._transport.request("GET", self._path, agent=True) + self._transport.request("GET", self._path, agent=True), ) def wait(self, timeout: float = 180) -> TurnResult: return TurnResult.from_dict( - _wait(self._transport, self._path, self.id, timeout, _TURN_TERMINAL) + _wait( + self._transport, + self._path, + self.id, + timeout, + _TURN_TERMINAL, + ), ) def cancel(self) -> TurnResult: - """Request cancellation; only a returned CANCELLED status confirms cancellation.""" + """Request cancellation; only returned CANCELLED confirms it.""" return TurnResult.from_dict( - self._transport.request("POST", self._path + "/cancel", agent=True) + self._transport.request( + "POST", + self._path + "/cancel", + agent=True, + ), ) - def subscribe(self, callback=None, after_sequence: int = 0) -> EventSubscription: + def subscribe( + self, + callback=None, + after_sequence: int = 0, + ) -> EventSubscription: return EventSubscription( - self._transport, self._path, self.id, after_sequence, callback + self._transport, + self._path, + self.id, + after_sequence, + callback, ) @@ -475,15 +593,24 @@ def __init__(self, transport: AsyncTransport): async def template_config(self) -> AgentTemplateConfig: return AgentTemplateConfig.from_dict( - await self._transport.request("GET", AGENT + "/template-config", agent=True) + await self._transport.request( + "GET", + AGENT + "/template-config", + agent=True, + ), ) - async def launch_async(self, request: LaunchRequest) -> AsyncLaunchOperation: + async def launch_async( + self, + request: LaunchRequest, + ) -> AsyncLaunchOperation: """Accept a launch operation without waiting for instance readiness.""" return await self._launch(request) async def _launch( - self, request: LaunchRequest, timeout: Optional[float] = None + self, + request: LaunchRequest, + timeout: Optional[float] = None, ) -> AsyncLaunchOperation: data = await self._transport.request( "POST", @@ -493,38 +620,54 @@ async def _launch( timeout=timeout, ) return AsyncLaunchOperation( - self, _response_id(data, "instance_id"), _response_id(data, "operation_id") + self, + _response_id(data, "instance_id"), + _response_id(data, "operation_id"), ) async def launch( - self, request: LaunchRequest, timeout: float = 600 + self, + request: LaunchRequest, + timeout: float = 600, ) -> AsyncAgentHandle: end = deadline(timeout) operation = await self._launch( - request, min(self._transport.timeout, remaining(end, "launch", "PENDING")) + request, + min(self._transport.timeout, remaining(end, "launch", "PENDING")), + ) + return await operation.wait( + remaining(end, operation.operation_id, "PENDING"), ) - return await operation.wait(remaining(end, operation.operation_id, "PENDING")) async def list_instances( - self, limit: int = 50, cursor: Optional[str] = None + self, + limit: int = 50, + cursor: Optional[str] = None, ) -> AgentPage[AgentInstanceInfo]: data = await self._transport.request( - "GET", AGENT + "/instances", params=_page_params(limit, cursor), agent=True + "GET", + AGENT + "/instances", + params=_page_params(limit, cursor), + agent=True, ) return AgentPage[AgentInstanceInfo].from_dict(data) async def get_instance(self, instance_id: str) -> AgentInstanceInfo: return AgentInstanceInfo.from_dict( await self._transport.request( - "GET", AGENT + "/instances/" + resource_id(instance_id), agent=True - ) + "GET", + AGENT + "/instances/" + resource_id(instance_id), + agent=True, + ), ) async def connect(self, instance_id: str) -> AsyncAgentHandle: return await self._connect(instance_id) async def _connect( - self, instance_id: str, timeout: Optional[float] = None + self, + instance_id: str, + timeout: Optional[float] = None, ) -> AsyncAgentHandle: data = await self._transport.request( "GET", @@ -535,7 +678,7 @@ async def _connect( info = AgentInstanceInfo.from_dict(data) if info.state != "READY": raise SandboxAPIError( - "Instance {} is not ready".format(instance_id), + f"Instance {instance_id} is not ready", code="INSTANCE_NOT_READY", ) return AsyncAgentHandle( @@ -547,7 +690,9 @@ async def _connect( async def release(self, instance_id: str) -> AsyncOperationHandle: data = await self._transport.request( - "DELETE", AGENT + "/instances/" + resource_id(instance_id), agent=True + "DELETE", + AGENT + "/instances/" + resource_id(instance_id), + agent=True, ) return self.operation(_response_id(data, "operation_id")) @@ -561,7 +706,10 @@ def turn(self, turn_id: str) -> AsyncTurnHandle: return AsyncTurnHandle(self._transport, turn_id) async def list_sessions( - self, instance_id: str, limit: int = 50, cursor: Optional[str] = None + self, + instance_id: str, + limit: int = 50, + cursor: Optional[str] = None, ) -> AgentPage[AgentSessionInfo]: data = await self._transport.request( "GET", @@ -573,7 +721,12 @@ async def list_sessions( class AsyncLaunchOperation: - def __init__(self, agents: AsyncAgentsClient, instance_id: str, operation_id: str): + def __init__( + self, + agents: AsyncAgentsClient, + instance_id: str, + operation_id: str, + ): self._agents = agents self.instance_id = instance_id self.operation_id = operation_id @@ -581,19 +734,29 @@ def __init__(self, agents: AsyncAgentsClient, instance_id: str, operation_id: st async def wait(self, timeout: float = 600) -> AsyncAgentHandle: end = deadline(timeout) await self._agents.operation(self.operation_id).wait( - remaining(end, self.operation_id, "PENDING") + remaining(end, self.operation_id, "PENDING"), ) budget = remaining(end, self.operation_id, "SUCCEEDED") try: + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access handle = await self._agents._connect( - self.instance_id, min(self._agents._transport.timeout, budget) + self.instance_id, + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access + min(self._agents._transport.timeout, budget), ) except SandboxAPIError as error: if ( error.code == "REQUEST_TIMEOUT" + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access and budget <= self._agents._transport.timeout ): - raise SandboxWaitTimeoutError(self.operation_id, "SUCCEEDED") from error + raise SandboxWaitTimeoutError( + self.operation_id, + "SUCCEEDED", + ) from error raise remaining(end, self.operation_id, "SUCCEEDED") return handle @@ -612,11 +775,15 @@ def __init__( self._transport = transport self._info = info self.default_session = AsyncSessionHandle( - transport, default_session_id, instance_id + transport, + default_session_id, + instance_id, ) async def get(self) -> AgentInstanceInfo: - self._info = await AsyncAgentsClient(self._transport).get_instance(self.id) + self._info = await AsyncAgentsClient(self._transport).get_instance( + self.id, + ) return self._info async def get_info(self) -> AgentInstanceInfo: @@ -630,14 +797,20 @@ async def new_session(self) -> AsyncSessionHandle: agent=True, ) return AsyncSessionHandle( - self._transport, _response_id(data, "session_id"), self.id + self._transport, + _response_id(data, "session_id"), + self.id, ) async def list_sessions( - self, limit: int = 50, cursor: Optional[str] = None + self, + limit: int = 50, + cursor: Optional[str] = None, ) -> AgentPage[AgentSessionInfo]: return await AsyncAgentsClient(self._transport).list_sessions( - self.id, limit, cursor + self.id, + limit, + cursor, ) async def upload( @@ -667,12 +840,12 @@ async def upload( async def content(): while True: read = asyncio.create_task( - asyncio.to_thread(next, chunks, sentinel) + asyncio.to_thread(next, chunks, sentinel), ) try: chunk = await asyncio.shield(read) except asyncio.CancelledError: - # A running file read must finish before its owned stream closes. + # Finish the running read before closing its owned stream. await read raise if chunk is sentinel: @@ -709,21 +882,38 @@ def __init__( self._instance_id = instance_id self._path = AGENT + "/sessions/" + resource_id(session_id) + "/turns" - async def submit(self, text: str, deadline_seconds: int = 120) -> AsyncTurnHandle: + async def submit( + self, + text: str, + deadline_seconds: int = 120, + ) -> AsyncTurnHandle: return await self.submit_with_files(text, (), deadline_seconds) async def submit_with_files( - self, text: str, files: Sequence[UploadedFile], deadline_seconds: int = 120 + self, + text: str, + files: Sequence[UploadedFile], + deadline_seconds: int = 120, ) -> AsyncTurnHandle: body = _prompt(text, files, deadline_seconds, self._instance_id) - data = await self._transport.request("POST", self._path, json=body, agent=True) + data = await self._transport.request( + "POST", + self._path, + json=body, + agent=True, + ) return AsyncTurnHandle(self._transport, _response_id(data, "turn_id")) async def list_turns( - self, limit: int = 50, cursor: Optional[str] = None + self, + limit: int = 50, + cursor: Optional[str] = None, ) -> AgentPage[AgentTurnInfo]: data = await self._transport.request( - "GET", self._path, params=_page_params(limit, cursor), agent=True + "GET", + self._path, + params=_page_params(limit, cursor), + agent=True, ) return AgentPage[AgentTurnInfo].from_dict(data) @@ -736,14 +926,18 @@ def __init__(self, transport: AsyncTransport, operation_id: str): async def get(self) -> AgentOperationInfo: return AgentOperationInfo.from_dict( - await self._transport.request("GET", self._path, agent=True) + await self._transport.request("GET", self._path, agent=True), ) async def wait(self, timeout: float = 600) -> AgentOperationInfo: info = AgentOperationInfo.from_dict( await _await( - self._transport, self._path, self.id, timeout, _OPERATION_TERMINAL - ) + self._transport, + self._path, + self.id, + timeout, + _OPERATION_TERMINAL, + ), ) return _operation_result(info) @@ -756,23 +950,39 @@ def __init__(self, transport: AsyncTransport, turn_id: str): async def get(self) -> TurnResult: return TurnResult.from_dict( - await self._transport.request("GET", self._path, agent=True) + await self._transport.request("GET", self._path, agent=True), ) async def wait(self, timeout: float = 180) -> TurnResult: return TurnResult.from_dict( - await _await(self._transport, self._path, self.id, timeout, _TURN_TERMINAL) + await _await( + self._transport, + self._path, + self.id, + timeout, + _TURN_TERMINAL, + ), ) async def cancel(self) -> TurnResult: - """Request cancellation; only a returned CANCELLED status confirms cancellation.""" + """Request cancellation; only returned CANCELLED confirms it.""" return TurnResult.from_dict( - await self._transport.request("POST", self._path + "/cancel", agent=True) + await self._transport.request( + "POST", + self._path + "/cancel", + agent=True, + ), ) def subscribe( - self, callback=None, after_sequence: int = 0 + self, + callback=None, + after_sequence: int = 0, ) -> AsyncEventSubscription: return AsyncEventSubscription( - self._transport, self._path, self.id, after_sequence, callback + self._transport, + self._path, + self.id, + after_sequence, + callback, ) diff --git a/dashscope/applications/agentstudio/sandbox/client.py b/dashscope/applications/agentstudio/sandbox/client.py index 420bc4d1..6512d057 100644 --- a/dashscope/applications/agentstudio/sandbox/client.py +++ b/dashscope/applications/agentstudio/sandbox/client.py @@ -32,7 +32,11 @@ def __init__( http_client: Optional[httpx.Client] = None, ) -> None: self._transport = Transport( - base_url, api_key, timeout, poll_interval, http_client + base_url, + api_key, + timeout, + poll_interval, + http_client, ) self.agents = AgentsClient(self._transport) self.sandboxes = SandboxesClient(self._transport) @@ -62,7 +66,11 @@ def __init__( http_client: Optional[httpx.AsyncClient] = None, ) -> None: self._transport = AsyncTransport( - base_url, api_key, timeout, poll_interval, http_client + base_url, + api_key, + timeout, + poll_interval, + http_client, ) self.agents = AsyncAgentsClient(self._transport) self.sandboxes = AsyncSandboxesClient(self._transport) diff --git a/dashscope/applications/agentstudio/sandbox/models.py b/dashscope/applications/agentstudio/sandbox/models.py index 8291f748..39463c56 100644 --- a/dashscope/applications/agentstudio/sandbox/models.py +++ b/dashscope/applications/agentstudio/sandbox/models.py @@ -5,7 +5,16 @@ from __future__ import annotations from enum import Enum -from typing import Any, Dict, Generic, List, Literal, Mapping, Optional, TypeVar +from typing import ( + Any, + Dict, + Generic, + List, + Literal, + Mapping, + Optional, + TypeVar, +) from pydantic import ( AliasChoices, @@ -24,7 +33,9 @@ class Record(BaseModel): model_config = ConfigDict( - populate_by_name=True, extra="allow", hide_input_in_errors=True + populate_by_name=True, + extra="allow", + hide_input_in_errors=True, ) @classmethod @@ -33,7 +44,8 @@ def from_dict(cls, data): return cls.model_validate(data) except ValidationError: raise SandboxAPIError( - "Invalid Sandbox response", code="INVALID_RESPONSE" + "Invalid Sandbox response", + code="INVALID_RESPONSE", ) from None def to_dict(self) -> Dict[str, Any]: @@ -93,8 +105,16 @@ def validate_model(self): if not self.base_url and (self.model_id or self.api_key): raise ValueError("base_url is required when configuring a model") if self.base_url: - object.__setattr__(self, "base_url", http_url(self.base_url, "base_url")) - object.__setattr__(self, "model_id", self.model_id or "qwen3.7-plus") + object.__setattr__( + self, + "base_url", + http_url(self.base_url, "base_url"), + ) + object.__setattr__( + self, + "model_id", + self.model_id or "qwen3.7-plus", + ) return self @@ -145,7 +165,9 @@ def validate_selection(self): self.compute, ) ): - raise ValueError("template_id conflicts with new-template settings") + raise ValueError( + "template_id conflicts with new-template settings", + ) elif image is not None and self.image_name is None: object.__setattr__(self, "image_name", image.value) return self @@ -154,7 +176,10 @@ def validate_selection(self): class FileMount(Input): origin_file_id: str = Field(alias="originFileId") mount_path: str = Field(alias="mountPath") - origin_file_name: Optional[str] = Field(default=None, alias="originFileName") + origin_file_name: Optional[str] = Field( + default=None, + alias="originFileName", + ) @model_validator(mode="after") def validate_mount(self): @@ -166,7 +191,9 @@ def validate_mount(self): or any(part in (".", "..") for part in path.split("/")) or any(ord(c) < 32 or ord(c) == 127 for c in path) ): - raise ValueError("mount_path must be a file under workspace/uploads") + raise ValueError( + "mount_path must be a file under workspace/uploads", + ) return self @@ -175,8 +202,11 @@ class TemplateCreateRequest(Input): image: Optional[OfficialImage] = Field(default=None, exclude=True) from_image: Optional[str] = Field(default=None, alias="fromImage") image_name: Optional[str] = Field(default=None, alias="imageName") - harness_type: Optional[Literal["dsh", "openclaw", "codex", "hermes"]] = Field( - default=None, alias="harnessType" + harness_type: Optional[ + Literal["dsh", "openclaw", "codex", "hermes"] + ] = Field( + default=None, + alias="harnessType", ) cpu_count: int = Field(alias="cpuCount", gt=0, strict=True) memory_mb: int = Field(alias="memoryMB", gt=0, strict=True) @@ -186,14 +216,24 @@ class TemplateCreateRequest(Input): alias="modelConfig", validation_alias=AliasChoices("model_config", "modelConfig"), ) - env_config: Optional[Dict[str, str]] = Field(default=None, alias="envConfig") + env_config: Optional[Dict[str, str]] = Field( + default=None, + alias="envConfig", + ) network_config: Optional[Dict[str, Any]] = Field( - default=None, alias="networkConfig" + default=None, + alias="networkConfig", + ) + hook_config: Optional[Dict[str, Any]] = Field( + default=None, + alias="hookConfig", ) - hook_config: Optional[Dict[str, Any]] = Field(default=None, alias="hookConfig") mounts: Optional[List[FileMount]] = Field(default=None, alias="mntConfig") auto_pause_time: Optional[int] = Field(default=None, alias="autoPauseTime") - max_running_timeout: Optional[int] = Field(default=None, alias="maxRunningTimeout") + max_running_timeout: Optional[int] = Field( + default=None, + alias="maxRunningTimeout", + ) @field_validator("model") @classmethod @@ -210,7 +250,9 @@ def serialize_template_model(self, model): "baseUrl": model.base_url, "apiKey": model.api_key, } - return {name: value for name, value in values.items() if value is not None} + return { + name: value for name, value in values.items() if value is not None + } @field_validator("name") @classmethod @@ -223,7 +265,9 @@ def validate_harness_selection(self): if not self.image.supports_agent: raise ValueError("harness_type requires a Harness image") expected = ( - "dsh" if self.image is OfficialImage.DEEPSEEK_HARNESS else "openclaw" + "dsh" + if self.image is OfficialImage.DEEPSEEK_HARNESS + else "openclaw" ) if self.harness_type != expected: raise ValueError("harness_type must match the selected image") @@ -232,37 +276,70 @@ def validate_harness_selection(self): @field_validator("auto_pause_time", "max_running_timeout", mode="before") @classmethod def validate_lifetime(cls, value, info): - return None if value is None else seconds(value, info.field_name, 300, 604800) + return ( + None + if value is None + else seconds(value, info.field_name, 300, 604800) + ) class TemplateUpdateRequest(Input): name: Optional[str] = None from_image: Optional[str] = Field(default=None, alias="fromImage") image_name: Optional[str] = Field(default=None, alias="imageName") - harness_type: Optional[Literal["dsh", "openclaw", "codex", "hermes"]] = Field( - default=None, alias="harnessType" + harness_type: Optional[ + Literal["dsh", "openclaw", "codex", "hermes"] + ] = Field( + default=None, + alias="harnessType", + ) + cpu_count: Optional[int] = Field( + default=None, + alias="cpuCount", + gt=0, + strict=True, + ) + memory_mb: Optional[int] = Field( + default=None, + alias="memoryMB", + gt=0, + strict=True, ) - cpu_count: Optional[int] = Field(default=None, alias="cpuCount", gt=0, strict=True) - memory_mb: Optional[int] = Field(default=None, alias="memoryMB", gt=0, strict=True) description: Optional[str] = None - env_config: Optional[Dict[str, str]] = Field(default=None, alias="envConfig") + env_config: Optional[Dict[str, str]] = Field( + default=None, + alias="envConfig", + ) network_config: Optional[Dict[str, Any]] = Field( - default=None, alias="networkConfig" + default=None, + alias="networkConfig", + ) + hook_config: Optional[Dict[str, Any]] = Field( + default=None, + alias="hookConfig", ) - hook_config: Optional[Dict[str, Any]] = Field(default=None, alias="hookConfig") mounts: Optional[List[FileMount]] = Field(default=None, alias="mntConfig") auto_pause_time: Optional[int] = Field(default=None, alias="autoPauseTime") - max_running_timeout: Optional[int] = Field(default=None, alias="maxRunningTimeout") + max_running_timeout: Optional[int] = Field( + default=None, + alias="maxRunningTimeout", + ) @field_validator("auto_pause_time", "max_running_timeout", mode="before") @classmethod def validate_lifetime(cls, value, info): - return None if value is None else seconds(value, info.field_name, 300, 604800) + return ( + None + if value is None + else seconds(value, info.field_name, 300, 604800) + ) @model_validator(mode="after") def paired_compute(self): if (self.cpu_count is None) != (self.memory_mb is None): - raise ValueError("cpu_count and memory_mb must be updated together") + raise ValueError( + "cpu_count and memory_mb must be updated together", + ) if self.name is not None: required(self.name, "name") return self @@ -274,15 +351,20 @@ class SandboxCreateRequest(Input): env_vars: Optional[Dict[str, str]] = Field(default=None, alias="envVars") metadata: Optional[Dict[str, str]] = None allow_internet_access: Optional[bool] = Field( - default=None, alias="allowInternetAccess" + default=None, + alias="allowInternetAccess", ) secure: Optional[bool] = None auto_pause: Optional[bool] = Field(default=None, alias="autoPause") - auto_pause_memory: Optional[bool] = Field(default=None, alias="autoPauseMemory") + auto_pause_memory: Optional[bool] = Field( + default=None, + alias="autoPauseMemory", + ) auto_resume: Optional[bool] = Field(default=None, alias="autoResume") network: Optional[Dict[str, Any]] = None volume_mounts: Optional[List[Dict[str, Any]]] = Field( - default=None, alias="volumeMounts" + default=None, + alias="volumeMounts", ) mcp: Optional[Dict[str, Any]] = None @@ -325,7 +407,10 @@ class TemplateMount(Record): origin_file_id: Optional[str] = Field(default=None, alias="originFileId") mount_path: Optional[str] = Field(default=None, alias="mountPath") - origin_file_name: Optional[str] = Field(default=None, alias="originFileName") + origin_file_name: Optional[str] = Field( + default=None, + alias="originFileName", + ) class TemplateInfo(Record): @@ -344,7 +429,10 @@ class TemplateInfo(Record): image_name: Optional[str] = Field(default=None, alias="imageName") image_type: Optional[str] = Field(default=None, alias="imageType") env_config: Dict[str, str] = Field(default_factory=dict, alias="envConfig") - mounts: List[TemplateMount] = Field(default_factory=list, alias="mntConfig") + mounts: List[TemplateMount] = Field( + default_factory=list, + alias="mntConfig", + ) builds: List[Dict[str, Any]] = Field(default_factory=list) @field_validator("env_config", "mounts", "builds", mode="before") @@ -364,7 +452,11 @@ def build_defaults(cls, data): if not data.get("templateName") and data.get("names"): data["templateName"] = data["names"][0] builds = data.get("builds") - if isinstance(builds, list) and builds and isinstance(builds[0], Mapping): + if ( + isinstance(builds, list) + and builds + and isinstance(builds[0], Mapping) + ): first = builds[0] data.setdefault("buildID", first.get("buildID")) data.setdefault("buildStatus", first.get("status")) @@ -376,10 +468,14 @@ class SandboxConnection(Record): envd_url: Optional[str] = Field(default=None, alias="envdUrl", repr=False) envd_version: Optional[str] = Field(default=None, alias="envdVersion") envd_access_token: Optional[str] = Field( - default=None, alias="envdAccessToken", repr=False + default=None, + alias="envdAccessToken", + repr=False, ) traffic_access_token: Optional[str] = Field( - default=None, alias="trafficAccessToken", repr=False + default=None, + alias="trafficAccessToken", + repr=False, ) @@ -399,7 +495,10 @@ class SandboxInfo(Record): metadata: Dict[str, str] = Field(default_factory=dict) started_at: Optional[str] = Field(default=None, alias="startedAt") end_at: Optional[str] = Field(default=None, alias="endAt") - connection: SandboxConnection = Field(default_factory=SandboxConnection, repr=False) + connection: SandboxConnection = Field( + default_factory=SandboxConnection, + repr=False, + ) @field_validator("metadata", mode="before") @classmethod @@ -439,7 +538,9 @@ class AgentInstanceInfo(Record): default_session_id: Optional[str] = None sandbox_id: Optional[str] = None model: Optional[Dict[str, Any]] = Field( - default=None, alias="model_config", repr=False + default=None, + alias="model_config", + repr=False, ) compute: Optional[Compute] = None capabilities: Dict[str, Any] = Field(default_factory=dict) diff --git a/dashscope/applications/agentstudio/sandbox/sandboxes.py b/dashscope/applications/agentstudio/sandbox/sandboxes.py index fc0501b4..91da2f65 100644 --- a/dashscope/applications/agentstudio/sandbox/sandboxes.py +++ b/dashscope/applications/agentstudio/sandbox/sandboxes.py @@ -34,7 +34,10 @@ def _query(template_id, sandbox_id, state, limit) -> dict: def _list(data) -> List[SandboxInfo]: if not isinstance(data, list): - raise SandboxAPIError("Sandbox list must be an array", code="INVALID_RESPONSE") + raise SandboxAPIError( + "Sandbox list must be an array", + code="INVALID_RESPONSE", + ) return [SandboxInfo.from_dict(item) for item in data] @@ -47,8 +50,10 @@ def create(self, request: SandboxCreateRequest) -> "SandboxHandle": self, SandboxInfo.from_dict( self._http.request( - "POST", SANDBOX + "/sandboxes", json=request.to_dict() - ) + "POST", + SANDBOX + "/sandboxes", + json=request.to_dict(), + ), ), ) @@ -64,14 +69,18 @@ def list( "GET", SANDBOX + "/v2/sandboxes", params=_query(template_id, sandbox_id, state, limit), - ) + ), ) def get(self, sandbox_id: str) -> SandboxInfo: - return SandboxInfo.from_dict(self._http.request("GET", _path(sandbox_id))) + return SandboxInfo.from_dict( + self._http.request("GET", _path(sandbox_id)), + ) def connect( - self, sandbox_id: str, options: Optional[ConnectionOptions] = None + self, + sandbox_id: str, + options: Optional[ConnectionOptions] = None, ) -> "SandboxHandle": return SandboxHandle( self, @@ -80,7 +89,7 @@ def connect( "POST", _path(sandbox_id) + "/connect", json=options.to_dict() if options is not None else {}, - ) + ), ), ) @@ -88,7 +97,9 @@ def pause(self, sandbox_id: str) -> None: self._http.request("POST", _path(sandbox_id) + "/pause", json={}) def resume( - self, sandbox_id: str, options: Optional[ConnectionOptions] = None + self, + sandbox_id: str, + options: Optional[ConnectionOptions] = None, ) -> "SandboxHandle": return SandboxHandle( self, @@ -97,7 +108,7 @@ def resume( "POST", _path(sandbox_id) + "/resume", json=options.to_dict() if options is not None else {}, - ) + ), ), ) @@ -140,14 +151,20 @@ def get(self) -> SandboxInfo: self._connection = info.connection return info - def connect(self, options: Optional[ConnectionOptions] = None) -> "SandboxHandle": + def connect( + self, + options: Optional[ConnectionOptions] = None, + ) -> "SandboxHandle": self._connection = self._client.connect(self.id, options).connection return self def pause(self) -> None: self._client.pause(self.id) - def resume(self, options: Optional[ConnectionOptions] = None) -> "SandboxHandle": + def resume( + self, + options: Optional[ConnectionOptions] = None, + ) -> "SandboxHandle": self._connection = self._client.resume(self.id, options).connection return self @@ -155,20 +172,25 @@ def release(self) -> None: self._client.release(self.id) def __repr__(self) -> str: - return "SandboxHandle(id={!r})".format(self.id) + return f"SandboxHandle(id={self.id!r})" class AsyncSandboxesClient: def __init__(self, transport: AsyncTransport): self._http = transport - async def create(self, request: SandboxCreateRequest) -> "AsyncSandboxHandle": + async def create( + self, + request: SandboxCreateRequest, + ) -> "AsyncSandboxHandle": return AsyncSandboxHandle( self, SandboxInfo.from_dict( await self._http.request( - "POST", SANDBOX + "/sandboxes", json=request.to_dict() - ) + "POST", + SANDBOX + "/sandboxes", + json=request.to_dict(), + ), ), ) @@ -184,14 +206,18 @@ async def list( "GET", SANDBOX + "/v2/sandboxes", params=_query(template_id, sandbox_id, state, limit), - ) + ), ) async def get(self, sandbox_id: str) -> SandboxInfo: - return SandboxInfo.from_dict(await self._http.request("GET", _path(sandbox_id))) + return SandboxInfo.from_dict( + await self._http.request("GET", _path(sandbox_id)), + ) async def connect( - self, sandbox_id: str, options: Optional[ConnectionOptions] = None + self, + sandbox_id: str, + options: Optional[ConnectionOptions] = None, ) -> "AsyncSandboxHandle": return AsyncSandboxHandle( self, @@ -200,7 +226,7 @@ async def connect( "POST", _path(sandbox_id) + "/connect", json=options.to_dict() if options is not None else {}, - ) + ), ), ) @@ -208,7 +234,9 @@ async def pause(self, sandbox_id: str) -> None: await self._http.request("POST", _path(sandbox_id) + "/pause", json={}) async def resume( - self, sandbox_id: str, options: Optional[ConnectionOptions] = None + self, + sandbox_id: str, + options: Optional[ConnectionOptions] = None, ) -> "AsyncSandboxHandle": return AsyncSandboxHandle( self, @@ -217,7 +245,7 @@ async def resume( "POST", _path(sandbox_id) + "/resume", json=options.to_dict() if options is not None else {}, - ) + ), ), ) @@ -259,22 +287,28 @@ async def get(self) -> SandboxInfo: return info async def connect( - self, options: Optional[ConnectionOptions] = None + self, + options: Optional[ConnectionOptions] = None, ) -> "AsyncSandboxHandle": - self._connection = (await self._client.connect(self.id, options)).connection + self._connection = ( + await self._client.connect(self.id, options) + ).connection return self async def pause(self) -> None: await self._client.pause(self.id) async def resume( - self, options: Optional[ConnectionOptions] = None + self, + options: Optional[ConnectionOptions] = None, ) -> "AsyncSandboxHandle": - self._connection = (await self._client.resume(self.id, options)).connection + self._connection = ( + await self._client.resume(self.id, options) + ).connection return self async def release(self) -> None: await self._client.release(self.id) def __repr__(self) -> str: - return "AsyncSandboxHandle(id={!r})".format(self.id) + return f"AsyncSandboxHandle(id={self.id!r})" diff --git a/dashscope/applications/agentstudio/sandbox/streaming.py b/dashscope/applications/agentstudio/sandbox/streaming.py index 5fa2320d..5bfac86c 100644 --- a/dashscope/applications/agentstudio/sandbox/streaming.py +++ b/dashscope/applications/agentstudio/sandbox/streaming.py @@ -8,7 +8,7 @@ import inspect import json import threading -from typing import Any, AsyncIterator, Callable, Iterator, Optional +from typing import Any, AsyncIterator, Callable, Iterator, Optional, cast from .exceptions import SandboxAPIError, SandboxWaitTimeoutError from ._validation import positive @@ -31,13 +31,17 @@ def __init__(self, turn_id: str, sequence: int): or not isinstance(sequence, int) or not 0 <= sequence <= _MAX_SEQUENCE ): - raise ValueError("after_sequence must be a nonnegative 64-bit integer") + raise ValueError( + "after_sequence must be a nonnegative 64-bit integer", + ) self.turn_id = turn_id self.last_sequence = sequence self._lines = [] self._size = 0 self._event_id: Optional[str] = None + # The SSE state machine handles each protocol field explicitly. + # pylint: disable-next=too-many-branches def feed(self, line: str) -> Optional[dict]: if line == "": if not self._lines: @@ -50,7 +54,10 @@ def feed(self, line: str) -> Optional[dict]: finally: self._lines = [] self._size = 0 - if not isinstance(event, dict) or event.get("turn_id") != self.turn_id: + if ( + not isinstance(event, dict) + or event.get("turn_id") != self.turn_id + ): raise _invalid("Event belongs to an unexpected Turn") sequence = event.get("sequence") if ( @@ -59,8 +66,9 @@ def feed(self, line: str) -> Optional[dict]: or not 1 <= sequence <= _MAX_SEQUENCE ): raise _invalid("Invalid Turn event sequence") - if self._event_id is not None and self._event_id != "{}:{}".format( - self.turn_id, sequence + if ( + self._event_id is not None + and self._event_id != f"{self.turn_id}:{sequence}" ): raise _invalid("Inconsistent Turn event identifier") self._event_id = None @@ -96,13 +104,16 @@ def _headers(turn_id: str, sequence: int) -> dict: headers = {"Accept": "text/event-stream"} # The protocol rejects Last-Event-ID with sequence zero. if sequence: - headers["Last-Event-ID"] = "{}:{}".format(turn_id, sequence) + headers["Last-Event-ID"] = f"{turn_id}:{sequence}" return headers def _check_response(response) -> None: media_type = ( - response.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + response.headers.get("Content-Type", "") + .split(";", 1)[0] + .strip() + .lower() ) if media_type != "text/event-stream": raise _invalid("Expected text/event-stream response") @@ -133,14 +144,16 @@ def __init__( self._context = None self._response = None self._closed = False - self._iterator = None + self._iterator: Optional[Iterator[dict]] = None self._error: Optional[BaseException] = None self._completion = threading.Event() self._thread: Optional[threading.Thread] = None transport.register(self) if callback is not None: self._thread = threading.Thread( - target=self._consume, name="dashscope-sandbox-sse", daemon=True + target=self._consume, + name="dashscope-sandbox-sse", + daemon=True, ) self._thread.start() @@ -206,7 +219,7 @@ def __iter__(self) -> Iterator[dict]: def _consume(self) -> None: try: for event in self._events(): - self._callback(event) + cast(Callable[[dict], Any], self._callback)(event) except BaseException as error: self._error = error finally: @@ -216,7 +229,7 @@ def _consume(self) -> None: def wait(self, timeout: Optional[float] = None) -> None: if self._callback is None: raise ValueError( - "wait requires a callback subscription; iterate events otherwise" + "wait requires a callback subscription; iterate events otherwise", ) if timeout is not None: timeout = positive(timeout, "timeout") @@ -271,12 +284,14 @@ def __init__( self._context = None self._response = None self._closed = False - self._iterator = None + self._iterator: Optional[AsyncIterator[dict]] = None self._task: Optional[asyncio.Task] = None transport.register(self) if callback is not None: try: - self._task = asyncio.get_running_loop().create_task(self._consume()) + self._task = asyncio.get_running_loop().create_task( + self._consume(), + ) except BaseException: transport.unregister(self) raise @@ -340,7 +355,7 @@ async def _consume(self) -> None: events = self._events() try: async for event in events: - result = self._callback(event) + result = cast(Callable[[dict], Any], self._callback)(event) if inspect.isawaitable(result): await result finally: @@ -350,14 +365,17 @@ async def _consume(self) -> None: async def wait(self, timeout: Optional[float] = None) -> None: if self._task is None: raise ValueError( - "wait requires a callback subscription; iterate events otherwise" + "wait requires a callback subscription; iterate events otherwise", ) if timeout is not None: timeout = positive(timeout, "timeout") try: await asyncio.wait_for(asyncio.shield(self._task), timeout) except asyncio.TimeoutError: - raise SandboxWaitTimeoutError(self._decoder.turn_id, "SUBSCRIBED") from None + raise SandboxWaitTimeoutError( + self._decoder.turn_id, + "SUBSCRIBED", + ) from None except asyncio.CancelledError: await self.aclose() raise diff --git a/dashscope/applications/agentstudio/sandbox/template_files.py b/dashscope/applications/agentstudio/sandbox/template_files.py index 0e337fb5..5c5e573c 100644 --- a/dashscope/applications/agentstudio/sandbox/template_files.py +++ b/dashscope/applications/agentstudio/sandbox/template_files.py @@ -53,19 +53,33 @@ def upload(self, path: PathLike) -> TemplateFile: FILES, files=[ ("source", (None, _SOURCE)), - ("file", (source.name, input_file, "application/octet-stream")), + ( + "file", + ( + source.name, + input_file, + "application/octet-stream", + ), + ), ], ) except OSError as error: raise SandboxAPIError( - "Cannot read the upload file", code="FILE_IO_ERROR" + "Cannot read the upload file", + code="FILE_IO_ERROR", ) from error return TemplateFile.from_dict(data) def get(self, file_id: str) -> TemplateFile: - return TemplateFile.from_dict(self._http.request("GET", _path(file_id))) + return TemplateFile.from_dict( + self._http.request("GET", _path(file_id)), + ) - def wait_available(self, file_id: str, timeout: float = 600) -> TemplateFile: + def wait_available( + self, + file_id: str, + timeout: float = 600, + ) -> TemplateFile: path = _path(file_id) end = deadline(timeout) last_status = None @@ -74,37 +88,51 @@ def wait_available(self, file_id: str, timeout: float = 600) -> TemplateFile: try: file = TemplateFile.from_dict( self._http.request( - "GET", path, timeout=min(self._http.timeout, budget) - ) + "GET", + path, + timeout=min(self._http.timeout, budget), + ), ) except SandboxAPIError as error: - if error.code == "REQUEST_TIMEOUT" and budget <= self._http.timeout: - raise SandboxWaitTimeoutError(file_id, last_status) from error + if ( + error.code == "REQUEST_TIMEOUT" + and budget <= self._http.timeout + ): + raise SandboxWaitTimeoutError( + file_id, + last_status, + ) from error raise last_status = file.status remaining(end, file_id, last_status) if _check_file(file): return file time.sleep( - min(self._http.poll_interval, remaining(end, file_id, last_status)) + min( + self._http.poll_interval, + remaining(end, file_id, last_status), + ), ) def prepare_upload(self, request: UploadRequest) -> UploadTicket: fields = request.to_dict() fields["source"] = _SOURCE - return UploadTicket.from_dict(self._http.request("POST", FILES, json=fields)) + return UploadTicket.from_dict( + self._http.request("POST", FILES, json=fields), + ) def upload_content(self, ticket: UploadTicket, path: PathLike) -> None: try: self._http.put_signed(ticket.upload_url, _upload_path(path)) except OSError as error: raise SandboxAPIError( - "Cannot read the upload file", code="FILE_IO_ERROR" + "Cannot read the upload file", + code="FILE_IO_ERROR", ) from error def complete(self, file_id: str) -> TemplateFile: return TemplateFile.from_dict( - self._http.request("POST", _path(file_id) + "/complete") + self._http.request("POST", _path(file_id) + "/complete"), ) def download(self, file_id: str, target: PathLike) -> Path: @@ -120,7 +148,9 @@ def download(self, file_id: str, target: PathLike) -> Path: temporary = Path(temporary_name) with os.fdopen(descriptor, "wb") as output: with self._http.stream( - "GET", path, headers={"Accept": "application/octet-stream"} + "GET", + path, + headers={"Accept": "application/octet-stream"}, ) as response: for chunk in response.iter_bytes(chunk_size=64 * 1024): output.write(chunk) @@ -129,7 +159,8 @@ def download(self, file_id: str, target: PathLike) -> Path: return target except OSError as error: raise SandboxAPIError( - "Cannot save the downloaded file", code="FILE_IO_ERROR" + "Cannot save the downloaded file", + code="FILE_IO_ERROR", ) from error finally: if temporary is not None: @@ -152,19 +183,33 @@ async def upload(self, path: PathLike) -> TemplateFile: FILES, files=[ ("source", (None, _SOURCE)), - ("file", (source.name, input_file, "application/octet-stream")), + ( + "file", + ( + source.name, + input_file, + "application/octet-stream", + ), + ), ], ) except OSError as error: raise SandboxAPIError( - "Cannot read the upload file", code="FILE_IO_ERROR" + "Cannot read the upload file", + code="FILE_IO_ERROR", ) from error return TemplateFile.from_dict(data) async def get(self, file_id: str) -> TemplateFile: - return TemplateFile.from_dict(await self._http.request("GET", _path(file_id))) + return TemplateFile.from_dict( + await self._http.request("GET", _path(file_id)), + ) - async def wait_available(self, file_id: str, timeout: float = 600) -> TemplateFile: + async def wait_available( + self, + file_id: str, + timeout: float = 600, + ) -> TemplateFile: path = _path(file_id) end = deadline(timeout) last_status = None @@ -173,39 +218,55 @@ async def wait_available(self, file_id: str, timeout: float = 600) -> TemplateFi try: file = TemplateFile.from_dict( await self._http.request( - "GET", path, timeout=min(self._http.timeout, budget) - ) + "GET", + path, + timeout=min(self._http.timeout, budget), + ), ) except SandboxAPIError as error: - if error.code == "REQUEST_TIMEOUT" and budget <= self._http.timeout: - raise SandboxWaitTimeoutError(file_id, last_status) from error + if ( + error.code == "REQUEST_TIMEOUT" + and budget <= self._http.timeout + ): + raise SandboxWaitTimeoutError( + file_id, + last_status, + ) from error raise last_status = file.status remaining(end, file_id, last_status) if _check_file(file): return file await asyncio.sleep( - min(self._http.poll_interval, remaining(end, file_id, last_status)) + min( + self._http.poll_interval, + remaining(end, file_id, last_status), + ), ) async def prepare_upload(self, request: UploadRequest) -> UploadTicket: fields = request.to_dict() fields["source"] = _SOURCE return UploadTicket.from_dict( - await self._http.request("POST", FILES, json=fields) + await self._http.request("POST", FILES, json=fields), ) - async def upload_content(self, ticket: UploadTicket, path: PathLike) -> None: + async def upload_content( + self, + ticket: UploadTicket, + path: PathLike, + ) -> None: try: await self._http.put_signed(ticket.upload_url, _upload_path(path)) except OSError as error: raise SandboxAPIError( - "Cannot read the upload file", code="FILE_IO_ERROR" + "Cannot read the upload file", + code="FILE_IO_ERROR", ) from error async def complete(self, file_id: str) -> TemplateFile: return TemplateFile.from_dict( - await self._http.request("POST", _path(file_id) + "/complete") + await self._http.request("POST", _path(file_id) + "/complete"), ) async def download(self, file_id: str, target: PathLike) -> Path: @@ -221,15 +282,20 @@ async def download(self, file_id: str, target: PathLike) -> Path: temporary = Path(temporary_name) with os.fdopen(descriptor, "wb") as output: async with self._http.stream( - "GET", path, headers={"Accept": "application/octet-stream"} + "GET", + path, + headers={"Accept": "application/octet-stream"}, ) as response: - async for chunk in response.aiter_bytes(chunk_size=64 * 1024): + async for chunk in response.aiter_bytes( + chunk_size=64 * 1024, + ): await asyncio.to_thread(output.write, chunk) os.replace(temporary, target) return target except OSError as error: raise SandboxAPIError( - "Cannot save the downloaded file", code="FILE_IO_ERROR" + "Cannot save the downloaded file", + code="FILE_IO_ERROR", ) from error finally: if temporary is not None: diff --git a/dashscope/applications/agentstudio/sandbox/templates.py b/dashscope/applications/agentstudio/sandbox/templates.py index b11c24d0..f9984691 100644 --- a/dashscope/applications/agentstudio/sandbox/templates.py +++ b/dashscope/applications/agentstudio/sandbox/templates.py @@ -26,7 +26,10 @@ def _path(template_id: str) -> str: def _list(data) -> List[TemplateInfo]: if not isinstance(data, list): - raise SandboxAPIError("Template list must be an array", code="INVALID_RESPONSE") + raise SandboxAPIError( + "Template list must be an array", + code="INVALID_RESPONSE", + ) return [TemplateInfo.from_dict(item) for item in data] @@ -36,7 +39,9 @@ def _creation_fields(request: TemplateCreateRequest, resolved) -> dict: return fields image_name = request.image.image_name exact_url = request.from_image + # Only accept an exact, internally consistent image resolution. if ( + # pylint: disable-next=too-many-boolean-expressions not isinstance(resolved, dict) or resolved.get("imageName") != image_name or not isinstance(resolved.get("imageUrl"), str) @@ -49,7 +54,9 @@ def _creation_fields(request: TemplateCreateRequest, resolved) -> dict: ) if request.image.supports_agent: fields["harnessType"] = ( - "dsh" if request.image is OfficialImage.DEEPSEEK_HARNESS else "openclaw" + "dsh" + if request.image is OfficialImage.DEEPSEEK_HARNESS + else "openclaw" ) fields["imageType"] = "MANAGED" fields["fromImage"] = resolved["imageUrl"] @@ -61,7 +68,9 @@ def _check_build(status: BuildStatus) -> bool: normalized = status.status.upper() if normalized in _FAILED_BUILDS: raise SandboxAPIError( - "Template build failed", code="TEMPLATE_BUILD_FAILED", body=status.to_dict() + "Template build failed", + code="TEMPLATE_BUILD_FAILED", + body=status.to_dict(), ) return normalized == "READY" @@ -80,14 +89,16 @@ def create(self, request: TemplateCreateRequest) -> TemplateInfo: else None ) resolved = self._http.request( - "GET", SANDBOX + "/images/" + request.image.image_name, params=params + "GET", + SANDBOX + "/images/" + request.image.image_name, + params=params, ) return TemplateInfo.from_dict( self._http.request( "POST", SANDBOX + "/v3/templates", json=_creation_fields(request, resolved), - ) + ), ) def list(self, limit: int = 100, page_no: int = 1) -> List[TemplateInfo]: @@ -99,29 +110,47 @@ def list(self, limit: int = 100, page_no: int = 1) -> List[TemplateInfo]: "limit": seconds(limit, "limit"), "pageNo": seconds(page_no, "page_no"), }, - ) + ), ) def get(self, template_id: str) -> TemplateInfo: - return TemplateInfo.from_dict(self._http.request("GET", _path(template_id))) + return TemplateInfo.from_dict( + self._http.request("GET", _path(template_id)), + ) - def update(self, template_id: str, request: TemplateUpdateRequest) -> TemplateInfo: + def update( + self, + template_id: str, + request: TemplateUpdateRequest, + ) -> TemplateInfo: return TemplateInfo.from_dict( - self._http.request("PUT", _path(template_id), json=request.to_dict()) + self._http.request( + "PUT", + _path(template_id), + json=request.to_dict(), + ), ) def build_status(self, template_id: str, build_id: str) -> BuildStatus: return BuildStatus.from_dict( self._http.request( "GET", - _path(template_id) + "/builds/" + resource_id(build_id) + "/status", - ) + _path(template_id) + + "/builds/" + + resource_id(build_id) + + "/status", + ), ) def wait_ready( - self, template_id: str, build_id: str, timeout: float = 600 + self, + template_id: str, + build_id: str, + timeout: float = 600, ) -> BuildStatus: - path = _path(template_id) + "/builds/" + resource_id(build_id) + "/status" + path = ( + _path(template_id) + "/builds/" + resource_id(build_id) + "/status" + ) end = deadline(timeout) last_status = None while True: @@ -129,19 +158,30 @@ def wait_ready( try: status = BuildStatus.from_dict( self._http.request( - "GET", path, timeout=min(self._http.timeout, budget) - ) + "GET", + path, + timeout=min(self._http.timeout, budget), + ), ) except SandboxAPIError as error: - if error.code == "REQUEST_TIMEOUT" and budget <= self._http.timeout: - raise SandboxWaitTimeoutError(template_id, last_status) from error + if ( + error.code == "REQUEST_TIMEOUT" + and budget <= self._http.timeout + ): + raise SandboxWaitTimeoutError( + template_id, + last_status, + ) from error raise last_status = status.status remaining(end, template_id, last_status) if _check_build(status): return status time.sleep( - min(self._http.poll_interval, remaining(end, template_id, last_status)) + min( + self._http.poll_interval, + remaining(end, template_id, last_status), + ), ) def delete(self, template_id: str) -> None: @@ -161,17 +201,23 @@ async def create(self, request: TemplateCreateRequest) -> TemplateInfo: else None ) resolved = await self._http.request( - "GET", SANDBOX + "/images/" + request.image.image_name, params=params + "GET", + SANDBOX + "/images/" + request.image.image_name, + params=params, ) return TemplateInfo.from_dict( await self._http.request( "POST", SANDBOX + "/v3/templates", json=_creation_fields(request, resolved), - ) + ), ) - async def list(self, limit: int = 100, page_no: int = 1) -> List[TemplateInfo]: + async def list( + self, + limit: int = 100, + page_no: int = 1, + ) -> List[TemplateInfo]: return _list( await self._http.request( "GET", @@ -180,33 +226,51 @@ async def list(self, limit: int = 100, page_no: int = 1) -> List[TemplateInfo]: "limit": seconds(limit, "limit"), "pageNo": seconds(page_no, "page_no"), }, - ) + ), ) async def get(self, template_id: str) -> TemplateInfo: return TemplateInfo.from_dict( - await self._http.request("GET", _path(template_id)) + await self._http.request("GET", _path(template_id)), ) async def update( - self, template_id: str, request: TemplateUpdateRequest + self, + template_id: str, + request: TemplateUpdateRequest, ) -> TemplateInfo: return TemplateInfo.from_dict( - await self._http.request("PUT", _path(template_id), json=request.to_dict()) + await self._http.request( + "PUT", + _path(template_id), + json=request.to_dict(), + ), ) - async def build_status(self, template_id: str, build_id: str) -> BuildStatus: + async def build_status( + self, + template_id: str, + build_id: str, + ) -> BuildStatus: return BuildStatus.from_dict( await self._http.request( "GET", - _path(template_id) + "/builds/" + resource_id(build_id) + "/status", - ) + _path(template_id) + + "/builds/" + + resource_id(build_id) + + "/status", + ), ) async def wait_ready( - self, template_id: str, build_id: str, timeout: float = 600 + self, + template_id: str, + build_id: str, + timeout: float = 600, ) -> BuildStatus: - path = _path(template_id) + "/builds/" + resource_id(build_id) + "/status" + path = ( + _path(template_id) + "/builds/" + resource_id(build_id) + "/status" + ) end = deadline(timeout) last_status = None while True: @@ -214,19 +278,30 @@ async def wait_ready( try: status = BuildStatus.from_dict( await self._http.request( - "GET", path, timeout=min(self._http.timeout, budget) - ) + "GET", + path, + timeout=min(self._http.timeout, budget), + ), ) except SandboxAPIError as error: - if error.code == "REQUEST_TIMEOUT" and budget <= self._http.timeout: - raise SandboxWaitTimeoutError(template_id, last_status) from error + if ( + error.code == "REQUEST_TIMEOUT" + and budget <= self._http.timeout + ): + raise SandboxWaitTimeoutError( + template_id, + last_status, + ) from error raise last_status = status.status remaining(end, template_id, last_status) if _check_build(status): return status await asyncio.sleep( - min(self._http.poll_interval, remaining(end, template_id, last_status)) + min( + self._http.poll_interval, + remaining(end, template_id, last_status), + ), ) async def delete(self, template_id: str) -> None: diff --git a/dashscope/applications/agentstudio/sandbox/transport.py b/dashscope/applications/agentstudio/sandbox/transport.py index 52dede5e..7a5d75e0 100644 --- a/dashscope/applications/agentstudio/sandbox/transport.py +++ b/dashscope/applications/agentstudio/sandbox/transport.py @@ -4,12 +4,12 @@ from __future__ import annotations -import json +import json as json_module import threading import uuid from contextlib import asynccontextmanager, contextmanager from pathlib import Path -from typing import Any, Mapping, Optional +from typing import Any, Optional from urllib.parse import urlsplit import httpx @@ -59,11 +59,12 @@ def _decode(response: httpx.Response, content: bytes) -> Any: if response.status_code == 204 or not content: return None try: - return json.loads(content) + return json_module.loads(content) except (ValueError, UnicodeError): if response.is_success: raise SandboxAPIError( - "Invalid JSON response", code="INVALID_RESPONSE" + "Invalid JSON response", + code="INVALID_RESPONSE", ) from None return None @@ -108,7 +109,10 @@ def _request(self, method, path, *, headers=None, timeout=None, **kwargs): configured.update(headers or {}) configured["Authorization"] = "Bearer " + self.api_key configured.setdefault("Accept", "application/json") - configured.setdefault("x-dashscope-client-request-id", str(uuid.uuid4())) + configured.setdefault( + "x-dashscope-client-request-id", + str(uuid.uuid4()), + ) request = self._client.build_request( method, self.base_url + path, @@ -155,7 +159,7 @@ def _checked(self, response, payload, agent=False): message = str( error.get("message") or error.get("errorMsg") - or f"Platform HTTP {response.status_code}" + or f"Platform HTTP {response.status_code}", ) message = message.replace(self.api_key, "")[:8192] raise SandboxAPIError( @@ -221,7 +225,8 @@ def __init__( super().__init__(base_url, api_key, timeout, poll_interval) self._owns_client = http_client is None self._client = http_client or httpx.Client( - timeout=self.timeout, follow_redirects=False + timeout=self.timeout, + follow_redirects=False, ) def _read(self, response): @@ -229,7 +234,10 @@ def _read(self, response): for chunk in response.iter_bytes(): content.extend(chunk) if len(content) > _MAX_JSON: - raise SandboxAPIError("Response is too large", code="INVALID_RESPONSE") + raise SandboxAPIError( + "Response is too large", + code="INVALID_RESPONSE", + ) return _decode(response, bytes(content)) def request( @@ -257,7 +265,10 @@ def request( ) try: response = self._client.send( - request, stream=True, follow_redirects=False, auth=None + request, + stream=True, + follow_redirects=False, + auth=None, ) try: return self._checked(response, self._read(response), agent) @@ -278,11 +289,19 @@ def stream( json=None, ): request = self._request( - method, path, headers=headers, timeout=timeout, params=params, json=json + method, + path, + headers=headers, + timeout=timeout, + params=params, + json=json, ) try: response = self._client.send( - request, stream=True, follow_redirects=False, auth=None + request, + stream=True, + follow_redirects=False, + auth=None, ) try: if not response.is_success: @@ -296,11 +315,17 @@ def stream( def put_signed(self, url, source, *, headers=None, timeout=None): with Path(source).open("rb") as content: request = self._signed_request( - url, content, headers, timeout or self.timeout + url, + content, + headers, + timeout or self.timeout, ) try: response = self._client.send( - request, stream=True, auth=None, follow_redirects=False + request, + stream=True, + auth=None, + follow_redirects=False, ) try: if not response.is_success: @@ -350,7 +375,8 @@ def __init__( super().__init__(base_url, api_key, timeout, poll_interval) self._owns_client = http_client is None self._client = http_client or httpx.AsyncClient( - timeout=self.timeout, follow_redirects=False + timeout=self.timeout, + follow_redirects=False, ) async def _read(self, response): @@ -358,7 +384,10 @@ async def _read(self, response): async for chunk in response.aiter_bytes(): content.extend(chunk) if len(content) > _MAX_JSON: - raise SandboxAPIError("Response is too large", code="INVALID_RESPONSE") + raise SandboxAPIError( + "Response is too large", + code="INVALID_RESPONSE", + ) return _decode(response, bytes(content)) async def request( @@ -386,10 +415,17 @@ async def request( ) try: response = await self._client.send( - request, stream=True, follow_redirects=False, auth=None + request, + stream=True, + follow_redirects=False, + auth=None, ) try: - return self._checked(response, await self._read(response), agent) + return self._checked( + response, + await self._read(response), + agent, + ) finally: await response.aclose() except httpx.TransportError as error: @@ -407,11 +443,19 @@ async def stream( json=None, ): request = self._request( - method, path, headers=headers, timeout=timeout, params=params, json=json + method, + path, + headers=headers, + timeout=timeout, + params=params, + json=json, ) try: response = await self._client.send( - request, stream=True, follow_redirects=False, auth=None + request, + stream=True, + follow_redirects=False, + auth=None, ) try: if not response.is_success: @@ -433,11 +477,17 @@ async def chunks(): yield chunk request = self._signed_request( - url, chunks(), headers, timeout or self.timeout + url, + chunks(), + headers, + timeout or self.timeout, ) try: response = await self._client.send( - request, stream=True, auth=None, follow_redirects=False + request, + stream=True, + auth=None, + follow_redirects=False, ) try: if not response.is_success: diff --git a/dashscope/applications/agentstudio/sandbox/web_ui.py b/dashscope/applications/agentstudio/sandbox/web_ui.py index 33233ef4..e0ef3c0b 100644 --- a/dashscope/applications/agentstudio/sandbox/web_ui.py +++ b/dashscope/applications/agentstudio/sandbox/web_ui.py @@ -40,6 +40,8 @@ class WebUiOptions: auto_pair_openclaw: bool = True +# Keep public option validation in protocol order. +# pylint: disable-next=too-many-branches def _validate(image, options): from .models import OfficialImage @@ -67,7 +69,9 @@ def _validate(image, options): validated = replace(options, **values) if type(validated.auto_pair_openclaw) is not bool: raise ValueError("auto_pair_openclaw must be a boolean") - if validated.image_url and (validated.sandbox_id or validated.ready_template_id): + if validated.image_url and ( + validated.sandbox_id or validated.ready_template_id + ): raise ValueError("image_url can only be used when creating a template") if validated.sandbox_id: resource_id(validated.sandbox_id) @@ -80,27 +84,32 @@ def _validate(image, options): validated.openclaw_model_api, ) if validated.sandbox_id and any(model_settings): - raise ValueError("model settings can only be used when creating a Sandbox") + raise ValueError( + "model settings can only be used when creating a Sandbox", + ) if validated.openclaw_model_api and ( image != OfficialImage.OPENCLAW or validated.openclaw_model_api not in ("openai-completions", "anthropic-messages") ): raise ValueError( - "openclaw_model_api requires OpenClaw and a supported model API" + "openclaw_model_api requires OpenClaw and a supported model API", ) if validated.model_id and not re.fullmatch( - r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}", validated.model_id + r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}", + validated.model_id, ): raise ValueError( - "model_id must be a model identifier of at most 128 characters" + "model_id must be a model identifier of at most 128 characters", ) if not validated.model_base_url and any(model_settings[1:]): raise ValueError("model_base_url is required when configuring a model") if validated.model_base_url: try: url = urlsplit(validated.model_base_url) + # Validate the model URL before using any connection fields. if ( + # pylint: disable-next=too-many-boolean-expressions url.scheme not in ("http", "https") or not url.hostname or url.username is not None @@ -110,10 +119,15 @@ def _validate(image, options): or any(ord(char) < 33 for char in validated.model_base_url) ): raise ValueError() - url.port + _ = url.port except ValueError: - raise ValueError("model_base_url must be an HTTP(S) base URL") from None - validated = replace(validated, model_id=validated.model_id or "qwen3.7-plus") + raise ValueError( + "model_base_url must be an HTTP(S) base URL", + ) from None + validated = replace( + validated, + model_id=validated.model_id or "qwen3.7-plus", + ) return validated @@ -163,13 +177,16 @@ def __init__(self, templates, transport): def start_proxy(self, route, auto_pair): descriptor, self.script = tempfile.mkstemp( - prefix="sandbox-web-preview-", suffix=".mjs" + prefix="sandbox-web-preview-", + suffix=".mjs", ) with os.fdopen(descriptor, "wb") as target: with (Path(__file__).parent / "web-preview" / "preview.mjs").open( - "rb" + "rb", ) as source: shutil.copyfileobj(source, target) + # The preview retains this process until Resources.close(). + # pylint: disable-next=consider-using-with self.proxy = subprocess.Popen( ["node", "--use-system-ca", self.script], stdin=subprocess.PIPE, @@ -185,7 +202,7 @@ def start_proxy(self, route, auto_pair): } # 连接凭据只通过 stdin 传递,临时文件只保存代理源码。 self.proxy.stdin.write( - json.dumps(settings, separators=(",", ":")).encode() + b"\n" + json.dumps(settings, separators=(",", ":")).encode() + b"\n", ) self.proxy.stdin.flush() if not auto_pair: @@ -199,7 +216,9 @@ def read_ready(): result.put(None) threading.Thread( - target=read_ready, name="sandbox-preview-ready", daemon=True + target=read_ready, + name="sandbox-preview-ready", + daemon=True, ).start() try: address = result.get(timeout=20) @@ -208,7 +227,8 @@ def read_ready(): if ( not address or not re.fullmatch( - r"http://127\.0\.0\.1:[0-9]+/__preview/[A-Za-z0-9_-]+", address + r"http://127\.0\.0\.1:[0-9]+/__preview/[A-Za-z0-9_-]+", + address, ) or not 0 < urlsplit(address).port < 65536 ): @@ -232,6 +252,8 @@ def _approve(self, bootstrap): return result = b"denied\n" try: + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access _bootstrap._approve_pairing(bootstrap, request_id) result = b"approved\n" except (OSError, SandboxAPIError): @@ -245,6 +267,8 @@ def _approve(self, bootstrap): proxy.stdout.close() proxy.stdin.close() + # Attempt all owned cleanup stages, retaining the first failure. + # pylint: disable-next=too-many-branches def close(self): with self._lock: if self._closed: @@ -300,8 +324,9 @@ def __init__(self, preview_url, sandbox_id, template_id, resources): self._resources = resources def __repr__(self): - return "SandboxWebUi(sandbox_id={!r}, template_id={!r}, preview_url=)".format( - self.sandbox_id, self.template_id + return ( + f"SandboxWebUi(sandbox_id={self.sandbox_id!r}, " + f"template_id={self.template_id!r}, preview_url=)" ) def close(self): @@ -361,9 +386,14 @@ def open_web_ui(sandboxes, transport, image, options=None): from .templates import TemplatesClient from .models import SandboxCreateRequest + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access if transport._closed or transport._closing or transport._client.is_closed: raise ValueError("Sandbox client is closed") - options = _validate(image, options if options is not None else WebUiOptions()) + options = _validate( + image, + options if options is not None else WebUiOptions(), + ) _check_node() resources = _Resources(TemplatesClient(transport), transport) try: @@ -373,7 +403,10 @@ def open_web_ui(sandboxes, transport, image, options=None): if fresh: if template_id is None: template_id = _create_template( - resources, transport, image, options + resources, + transport, + image, + options, ) resources.sandbox = sandboxes.create( SandboxCreateRequest( @@ -381,7 +414,7 @@ def open_web_ui(sandboxes, transport, image, options=None): secure=True, timeout=3600, metadata={"purpose": image.value + "-native-web-preview"}, - ) + ), ) sandbox_id = resources.sandbox.id connected = sandboxes.connect(sandbox_id) @@ -398,7 +431,8 @@ def open_web_ui(sandboxes, transport, image, options=None): options.openclaw_model_api or "", ) address = resources.start_proxy( - route, route.openclaw and options.auto_pair_openclaw + route, + route.openclaw and options.auto_pair_openclaw, ) preview = SandboxWebUi( address, @@ -422,6 +456,8 @@ def open_web_ui(sandboxes, transport, image, options=None): raise +# Keep the synchronous/asynchronous entry-point call signature. +# pylint: disable-next=unused-argument async def async_open_web_ui(sandboxes, transport, image, options=None): """Use a dedicated synchronous HTTP client for blocking native setup. @@ -430,9 +466,14 @@ async def async_open_web_ui(sandboxes, transport, image, options=None): """ from .client import SandboxClient + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access if transport._closed or transport._closing or transport._client.is_closed: raise ValueError("Sandbox client is closed") - options = _validate(image, options if options is not None else WebUiOptions()) + options = _validate( + image, + options if options is not None else WebUiOptions(), + ) owned = SandboxClient( base_url=transport.base_url, api_key=transport.api_key, @@ -442,8 +483,19 @@ async def async_open_web_ui(sandboxes, transport, image, options=None): def start(): try: - preview = open_web_ui(owned.sandboxes, owned._transport, image, options) + preview = open_web_ui( + owned.sandboxes, + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access + owned._transport, + image, + options, + ) + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access preview._resources.owned_client = owned + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access preview._resources.parent_transport = transport transport.register(preview) return preview diff --git a/docs/en/reference/agentstudio.md b/docs/en/reference/agentstudio.md index e3d89bb2..e4f03f6e 100644 --- a/docs/en/reference/agentstudio.md +++ b/docs/en/reference/agentstudio.md @@ -290,3 +290,147 @@ for a runnable lifecycle example and an Agent fixed-version binding example. ::: dashscope.applications.agentstudio.StreamError ::: dashscope.applications.agentstudio.StreamClosedError + +## Sandbox + +Use `client.sandbox` on an AgentStudio client, or create `SandboxClient` / +`AsyncSandboxClient` directly, to manage templates, instances, files, managed +Harness Agents and native Web UI previews. + +### Clients + +::: dashscope.applications.agentstudio.sandbox.client.SandboxClient + +::: dashscope.applications.agentstudio.sandbox.client.AsyncSandboxClient + + +### Exceptions + +::: dashscope.applications.agentstudio.sandbox.exceptions.SandboxAPIError + +::: dashscope.applications.agentstudio.sandbox.exceptions.SandboxWaitTimeoutError + + +### Models and requests + +::: dashscope.applications.agentstudio.sandbox.models.OfficialImage + +::: dashscope.applications.agentstudio.sandbox.models.ModelConfig + +::: dashscope.applications.agentstudio.sandbox.models.LaunchRequest + +::: dashscope.applications.agentstudio.sandbox.models.Compute + +::: dashscope.applications.agentstudio.sandbox.models.FileMount + +::: dashscope.applications.agentstudio.sandbox.models.TemplateCreateRequest + +::: dashscope.applications.agentstudio.sandbox.models.TemplateUpdateRequest + +::: dashscope.applications.agentstudio.sandbox.models.SandboxCreateRequest + +::: dashscope.applications.agentstudio.sandbox.models.ConnectionOptions + +::: dashscope.applications.agentstudio.sandbox.models.SandboxConnection + +::: dashscope.applications.agentstudio.sandbox.models.SandboxInfo + +::: dashscope.applications.agentstudio.sandbox.models.TemplateInfo + +::: dashscope.applications.agentstudio.sandbox.models.TemplateMount + +::: dashscope.applications.agentstudio.sandbox.models.BuildStatus + +::: dashscope.applications.agentstudio.sandbox.models.AgentInstanceInfo + +::: dashscope.applications.agentstudio.sandbox.models.AgentOperationInfo + +::: dashscope.applications.agentstudio.sandbox.models.AgentPage + +::: dashscope.applications.agentstudio.sandbox.models.AgentSessionInfo + +::: dashscope.applications.agentstudio.sandbox.models.AgentTurnInfo + +::: dashscope.applications.agentstudio.sandbox.models.AgentTemplateConfig + +::: dashscope.applications.agentstudio.sandbox.models.TurnResult + +::: dashscope.applications.agentstudio.sandbox.models.UploadedFile + +::: dashscope.applications.agentstudio.sandbox.models.TemplateFile + +::: dashscope.applications.agentstudio.sandbox.models.UploadTicket + +::: dashscope.applications.agentstudio.sandbox.models.UploadRequest + +::: dashscope.applications.agentstudio.sandbox.models.Record + +::: dashscope.applications.agentstudio.sandbox.models.Input + +::: dashscope.applications.agentstudio.sandbox.models.AgentImage + + +### Harness Agents + +::: dashscope.applications.agentstudio.sandbox.agents.AgentsClient + +::: dashscope.applications.agentstudio.sandbox.agents.AsyncAgentsClient + +::: dashscope.applications.agentstudio.sandbox.agents.AgentHandle + +::: dashscope.applications.agentstudio.sandbox.agents.AsyncAgentHandle + +::: dashscope.applications.agentstudio.sandbox.agents.SessionHandle + +::: dashscope.applications.agentstudio.sandbox.agents.AsyncSessionHandle + +::: dashscope.applications.agentstudio.sandbox.agents.TurnHandle + +::: dashscope.applications.agentstudio.sandbox.agents.AsyncTurnHandle + +::: dashscope.applications.agentstudio.sandbox.agents.OperationHandle + +::: dashscope.applications.agentstudio.sandbox.agents.AsyncOperationHandle + +::: dashscope.applications.agentstudio.sandbox.agents.LaunchOperation + +::: dashscope.applications.agentstudio.sandbox.agents.AsyncLaunchOperation + + +### Event subscriptions + +::: dashscope.applications.agentstudio.sandbox.streaming.EventSubscription + +::: dashscope.applications.agentstudio.sandbox.streaming.AsyncEventSubscription + + +### Sandbox instances + +::: dashscope.applications.agentstudio.sandbox.sandboxes.SandboxesClient + +::: dashscope.applications.agentstudio.sandbox.sandboxes.AsyncSandboxesClient + +::: dashscope.applications.agentstudio.sandbox.sandboxes.SandboxHandle + +::: dashscope.applications.agentstudio.sandbox.sandboxes.AsyncSandboxHandle + + +### Templates + +::: dashscope.applications.agentstudio.sandbox.templates.TemplatesClient + +::: dashscope.applications.agentstudio.sandbox.templates.AsyncTemplatesClient + + +### Template files + +::: dashscope.applications.agentstudio.sandbox.template_files.TemplateFilesClient + +::: dashscope.applications.agentstudio.sandbox.template_files.AsyncTemplateFilesClient + + +### Native Web UI + +::: dashscope.applications.agentstudio.sandbox.web_ui.SandboxWebUi + +::: dashscope.applications.agentstudio.sandbox.web_ui.WebUiOptions diff --git a/docs/zh/reference/agentstudio.md b/docs/zh/reference/agentstudio.md index 36771a5a..25afd969 100644 --- a/docs/zh/reference/agentstudio.md +++ b/docs/zh/reference/agentstudio.md @@ -307,3 +307,146 @@ agent = client.agents.create( ::: dashscope.applications.agentstudio.StreamError ::: dashscope.applications.agentstudio.StreamClosedError + +## Sandbox + +通过 AgentStudio 客户端的 `client.sandbox`,或直接创建 `SandboxClient` / +`AsyncSandboxClient`,管理模板、实例、文件、托管 Harness Agent 和原生 Web UI。 + +### 客户端 + +::: dashscope.applications.agentstudio.sandbox.client.SandboxClient + +::: dashscope.applications.agentstudio.sandbox.client.AsyncSandboxClient + + +### 异常 + +::: dashscope.applications.agentstudio.sandbox.exceptions.SandboxAPIError + +::: dashscope.applications.agentstudio.sandbox.exceptions.SandboxWaitTimeoutError + + +### 类型与请求 + +::: dashscope.applications.agentstudio.sandbox.models.OfficialImage + +::: dashscope.applications.agentstudio.sandbox.models.ModelConfig + +::: dashscope.applications.agentstudio.sandbox.models.LaunchRequest + +::: dashscope.applications.agentstudio.sandbox.models.Compute + +::: dashscope.applications.agentstudio.sandbox.models.FileMount + +::: dashscope.applications.agentstudio.sandbox.models.TemplateCreateRequest + +::: dashscope.applications.agentstudio.sandbox.models.TemplateUpdateRequest + +::: dashscope.applications.agentstudio.sandbox.models.SandboxCreateRequest + +::: dashscope.applications.agentstudio.sandbox.models.ConnectionOptions + +::: dashscope.applications.agentstudio.sandbox.models.SandboxConnection + +::: dashscope.applications.agentstudio.sandbox.models.SandboxInfo + +::: dashscope.applications.agentstudio.sandbox.models.TemplateInfo + +::: dashscope.applications.agentstudio.sandbox.models.TemplateMount + +::: dashscope.applications.agentstudio.sandbox.models.BuildStatus + +::: dashscope.applications.agentstudio.sandbox.models.AgentInstanceInfo + +::: dashscope.applications.agentstudio.sandbox.models.AgentOperationInfo + +::: dashscope.applications.agentstudio.sandbox.models.AgentPage + +::: dashscope.applications.agentstudio.sandbox.models.AgentSessionInfo + +::: dashscope.applications.agentstudio.sandbox.models.AgentTurnInfo + +::: dashscope.applications.agentstudio.sandbox.models.AgentTemplateConfig + +::: dashscope.applications.agentstudio.sandbox.models.TurnResult + +::: dashscope.applications.agentstudio.sandbox.models.UploadedFile + +::: dashscope.applications.agentstudio.sandbox.models.TemplateFile + +::: dashscope.applications.agentstudio.sandbox.models.UploadTicket + +::: dashscope.applications.agentstudio.sandbox.models.UploadRequest + +::: dashscope.applications.agentstudio.sandbox.models.Record + +::: dashscope.applications.agentstudio.sandbox.models.Input + +::: dashscope.applications.agentstudio.sandbox.models.AgentImage + + +### Harness Agent + +::: dashscope.applications.agentstudio.sandbox.agents.AgentsClient + +::: dashscope.applications.agentstudio.sandbox.agents.AsyncAgentsClient + +::: dashscope.applications.agentstudio.sandbox.agents.AgentHandle + +::: dashscope.applications.agentstudio.sandbox.agents.AsyncAgentHandle + +::: dashscope.applications.agentstudio.sandbox.agents.SessionHandle + +::: dashscope.applications.agentstudio.sandbox.agents.AsyncSessionHandle + +::: dashscope.applications.agentstudio.sandbox.agents.TurnHandle + +::: dashscope.applications.agentstudio.sandbox.agents.AsyncTurnHandle + +::: dashscope.applications.agentstudio.sandbox.agents.OperationHandle + +::: dashscope.applications.agentstudio.sandbox.agents.AsyncOperationHandle + +::: dashscope.applications.agentstudio.sandbox.agents.LaunchOperation + +::: dashscope.applications.agentstudio.sandbox.agents.AsyncLaunchOperation + + +### 事件订阅 + +::: dashscope.applications.agentstudio.sandbox.streaming.EventSubscription + +::: dashscope.applications.agentstudio.sandbox.streaming.AsyncEventSubscription + + +### Sandbox 实例 + +::: dashscope.applications.agentstudio.sandbox.sandboxes.SandboxesClient + +::: dashscope.applications.agentstudio.sandbox.sandboxes.AsyncSandboxesClient + +::: dashscope.applications.agentstudio.sandbox.sandboxes.SandboxHandle + +::: dashscope.applications.agentstudio.sandbox.sandboxes.AsyncSandboxHandle + + +### 模板 + +::: dashscope.applications.agentstudio.sandbox.templates.TemplatesClient + +::: dashscope.applications.agentstudio.sandbox.templates.AsyncTemplatesClient + + +### 模板文件 + +::: dashscope.applications.agentstudio.sandbox.template_files.TemplateFilesClient + +::: dashscope.applications.agentstudio.sandbox.template_files.AsyncTemplateFilesClient + + +### 原生 Web UI + +::: dashscope.applications.agentstudio.sandbox.web_ui.SandboxWebUi + +::: dashscope.applications.agentstudio.sandbox.web_ui.WebUiOptions diff --git a/tools/gen_reference.py b/tools/gen_reference.py index 8f6d4ba4..f375c9ce 100644 --- a/tools/gen_reference.py +++ b/tools/gen_reference.py @@ -93,6 +93,7 @@ # __all__ or be listed here; --check fails on unclassified ones. INTERNAL_MODULES = { "dashscope.applications.finetune", + "dashscope.applications.agentstudio.sandbox.transport", "dashscope.applications.finetune.reinforcement.component.func_decorator", "dashscope.applications.finetune.reinforcement.component.func_manager", "dashscope.resources", From fe796eacac71dadc3f49a21bc1d7c9773f7f9a71 Mon Sep 17 00:00:00 2001 From: "guning.lt" Date: Thu, 3 Dec 2026 13:49:09 +0800 Subject: [PATCH 7/7] sandbox api --- .../03_agent_recipes/agentstudio_sandbox.py | 53 ++ .../agentstudio_sandbox_agent.py | 48 ++ .../agentstudio_sandbox_web_ui.py | 52 ++ examples/README.md | 3 + examples/README_zh.md | 3 + tests/test_agentstudio_sandbox.py | 456 ++++++++++++++++++ 6 files changed, 615 insertions(+) create mode 100644 examples/03_agent_recipes/agentstudio_sandbox.py create mode 100644 examples/03_agent_recipes/agentstudio_sandbox_agent.py create mode 100644 examples/03_agent_recipes/agentstudio_sandbox_web_ui.py create mode 100644 tests/test_agentstudio_sandbox.py diff --git a/examples/03_agent_recipes/agentstudio_sandbox.py b/examples/03_agent_recipes/agentstudio_sandbox.py new file mode 100644 index 00000000..a40c1d64 --- /dev/null +++ b/examples/03_agent_recipes/agentstudio_sandbox.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Create a template and Sandbox, connect, then release both resources. + +Requires DASHSCOPE_AGENTSTUDIO_URL and DASHSCOPE_API_KEY. +""" + +import os + +import dashscope +from dashscope.agentstudio.sandbox import ( + ConnectionOptions, + OfficialImage, + SandboxCreateRequest, + TemplateCreateRequest, +) + + +def main() -> None: + with dashscope.Client( + base_url=os.environ["DASHSCOPE_AGENTSTUDIO_URL"], + ) as client: + sandbox = client.agentstudio.sandbox + template = sandbox.templates.create( + TemplateCreateRequest( + name="python-sandbox-example", + image=OfficialImage.CODE_INTERPRETER, + cpu_count=1, + memory_mb=2048, + ), + ) + try: + build_id = ( + template.build_id + or sandbox.templates.get( + template.id, + ).build_id + ) + sandbox.templates.wait_ready(template.id, build_id) + instance = sandbox.sandboxes.create( + SandboxCreateRequest(template_id=template.id, timeout=600), + ) + try: + instance.connect(ConnectionOptions(timeout=600)) + print(instance.id, instance.get().state) + finally: + instance.release() + finally: + sandbox.templates.delete(template.id) + + +if __name__ == "__main__": + main() diff --git a/examples/03_agent_recipes/agentstudio_sandbox_agent.py b/examples/03_agent_recipes/agentstudio_sandbox_agent.py new file mode 100644 index 00000000..3c389a5a --- /dev/null +++ b/examples/03_agent_recipes/agentstudio_sandbox_agent.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Run a Harness Agent turn and release the instance, keeping its template. + +Requires DASHSCOPE_AGENTSTUDIO_URL, DASHSCOPE_API_KEY and +DASHSCOPE_MODEL_BASE_URL. DASHSCOPE_MODEL_API_KEY supplies the separate model +credential; DASHSCOPE_MODEL selects the model. The platform key is not reused. +""" + +import os + +import dashscope +from dashscope.agentstudio.sandbox import ( + LaunchRequest, + ModelConfig, + OfficialImage, +) + + +def main() -> None: + with dashscope.Client( + base_url=os.environ["DASHSCOPE_AGENTSTUDIO_URL"], + ) as client: + agents = client.agentstudio.sandbox.agents + accepted = agents.launch_async( + LaunchRequest( + image=OfficialImage.DEEPSEEK_HARNESS, + model_config=ModelConfig( + base_url=os.environ["DASHSCOPE_MODEL_BASE_URL"], + model_id=os.environ.get("DASHSCOPE_MODEL"), + api_key=os.environ.get("DASHSCOPE_MODEL_API_KEY"), + ), + ), + ) + try: + agent = accepted.wait() + result = agent.default_session.submit( + "只计算7乘8并返回结果。", + ).wait() + if result.status != "SUCCEEDED": + raise RuntimeError("Turn ended with " + result.status) + print(result.text) + finally: + agents.release(accepted.instance_id).wait() + + +if __name__ == "__main__": + main() diff --git a/examples/03_agent_recipes/agentstudio_sandbox_web_ui.py b/examples/03_agent_recipes/agentstudio_sandbox_web_ui.py new file mode 100644 index 00000000..58f385e0 --- /dev/null +++ b/examples/03_agent_recipes/agentstudio_sandbox_web_ui.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Open a native Harness Web UI and close it on exit. + +Requires DASHSCOPE_AGENTSTUDIO_URL and DASHSCOPE_API_KEY. Select deepseek-harness +or openclaw with DASHSCOPE_SANDBOX_IMAGE. DASHSCOPE_SANDBOX_ID reuses an instance; +DASHSCOPE_SANDBOX_TEMPLATE_ID creates an instance from an existing template. +For a new instance, model settings use DASHSCOPE_MODEL_BASE_URL, +DASHSCOPE_MODEL_API_KEY and optional DASHSCOPE_MODEL, independently of the SDK. +Closing releases newly created resources and preserves borrowed resources. +""" + +import os +import webbrowser + +import dashscope +from dashscope.agentstudio.sandbox import OfficialImage, WebUiOptions + + +def main() -> None: + image = OfficialImage( + os.environ.get("DASHSCOPE_SANDBOX_IMAGE", "deepseek-harness"), + ) + sandbox_id = os.environ.get("DASHSCOPE_SANDBOX_ID") + if sandbox_id: + # Reuse the instance's existing model settings without overriding them. + options = WebUiOptions(sandbox_id=sandbox_id) + else: + options = WebUiOptions( + ready_template_id=os.environ.get("DASHSCOPE_SANDBOX_TEMPLATE_ID"), + model_base_url=os.environ.get("DASHSCOPE_MODEL_BASE_URL"), + model_id=os.environ.get("DASHSCOPE_MODEL"), + model_api_key=os.environ.get("DASHSCOPE_MODEL_API_KEY"), + ) + with dashscope.Client( + base_url=os.environ["DASHSCOPE_AGENTSTUDIO_URL"], + ) as client: + preview = client.agentstudio.sandbox.sandboxes.open_web_ui( + image, + options, + ) + try: + print("Web UI Sandbox:", preview.sandbox_id) + print(preview.preview_url) + webbrowser.open(preview.preview_url) + input("按回车关闭预览。") + finally: + preview.close() + + +if __name__ == "__main__": + main() diff --git a/examples/README.md b/examples/README.md index a45353a3..bb55ffe5 100644 --- a/examples/README.md +++ b/examples/README.md @@ -127,6 +127,9 @@ Uniform style: `client = dashscope.Client()` (reads the key from the `DASHSCOPE_ | `agentstudio.py` | AgentStudio end-to-end quickstart via `client.agentstudio`: environment -> agent -> session -> streamed reply (plus an opt-in memory-store demo); AgentStudio is shared by the 1.x/2.0 generations and mounts on the 2.0 client | Yes | | `agentstudio_deployments.py` | Managed Agent deployments: create a cron-scheduled deployment, trigger a run, list runs | Yes | | `agentstudio_dynamic_workflows.py` | Published Workflow definitions and versions, explicit nulls, Agent bindings and archive cleanup | Yes | +| `agentstudio_sandbox.py` | Sandbox template/build/instance lifecycle with explicit cleanup | Yes | +| `agentstudio_sandbox_agent.py` | Harness Agent conversation with separate model credentials and instance release | Yes | +| `agentstudio_sandbox_web_ui.py` | Native Web UI, instance/template reuse and preview cleanup | Yes | ## 04_real_world_scenarios — Real-world scenarios diff --git a/examples/README_zh.md b/examples/README_zh.md index f5096f5d..f6368b95 100644 --- a/examples/README_zh.md +++ b/examples/README_zh.md @@ -127,6 +127,9 @@ examples/ | `agentstudio.py` | AgentStudio 端到端 quickstart(经 `client.agentstudio`):环境 -> 智能体 -> 会话 -> 流式回复(另附可选的 memory store 演示);AgentStudio 为 1.x/2.0 两代共用模块,挂载在 2.0 客户端上 | 是 | | `agentstudio_deployments.py` | 托管智能体部署:创建 cron 定时部署、触发运行、列出运行记录 | 是 | | `agentstudio_dynamic_workflows.py` | Workflow 定义与发布版本、显式空值、Agent 绑定及归档清理 | 是 | +| `agentstudio_sandbox.py` | Sandbox 模板构建、实例连接与显式清理 | 是 | +| `agentstudio_sandbox_agent.py` | Harness Agent 对话、独立模型凭据与实例释放 | 是 | +| `agentstudio_sandbox_web_ui.py` | 原生 Web UI、实例/模板复用与预览清理 | 是 | ## 04_real_world_scenarios —— 真实场景 diff --git a/tests/test_agentstudio_sandbox.py b/tests/test_agentstudio_sandbox.py new file mode 100644 index 00000000..a3af5901 --- /dev/null +++ b/tests/test_agentstudio_sandbox.py @@ -0,0 +1,456 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Sandbox public HTTP contracts and runnable recipe cleanup, without a cloud.""" + +import json +from contextlib import contextmanager +import runpy +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import httpx +import pytest + +import dashscope +from dashscope import AsyncClient, Client +from dashscope.agentstudio.sandbox import ( + ConnectionOptions, + LaunchRequest, + ModelConfig, + OfficialImage, + SandboxAPIError, + SandboxCreateRequest, + SandboxesClient, + SandboxInfo, + TemplateCreateRequest, + TemplateFile, + TemplateInfo, + TurnResult, +) + +BASE = "https://sandbox.test/api/v1" +PREFIX = "/api/v1/agentstudio" +INSTANCE = {"sandboxID": "sbx-unit", "state": "running"} + + +def _http(handler): + def checked(request): + assert request.headers["Authorization"] == "Bearer platform-key" + return handler(request) + + return httpx.Client(transport=httpx.MockTransport(checked)) + + +@contextmanager +def _client(handler): + with _http(handler) as pool, Client( + api_key="platform-key", + base_url=BASE, + http_client=pool, + ) as client: + yield client + + +def _response(request, routes): + key = (request.method, request.url.path.removeprefix(PREFIX)) + assert key in routes, key + value = routes[key] + if isinstance(value, httpx.Response): + return value + if request.url.path.startswith(PREFIX + "/agent-runtime/"): + value = {"data": value} + return ( + httpx.Response(204) + if value is None + else httpx.Response( + 200, + json=value, + ) + ) + + +@pytest.mark.parametrize("image", list(OfficialImage)) +def test_official_template_resolves_current_catalogue(image): + requests = [] + selected_url = "https://registry.test/" + image.value + ":catalogue-head" + + def handle(request): + requests.append(request) + if request.method == "GET": + assert ( + request.url.path == PREFIX + "/sandbox/images/" + image.value + ) + return httpx.Response( + 200, + json={ + "imageName": image.value, + "imageUrl": selected_url, + }, + ) + assert request.method == "POST" + assert request.url.path == PREFIX + "/sandbox/v3/templates" + return httpx.Response(202, json={"templateID": "tpl-unit"}) + + with _client(handle) as client: + result = client.agentstudio.sandbox.templates.create( + TemplateCreateRequest( + name="test", + image=image, + cpu_count=1, + memory_mb=2048, + ), + ) + assert isinstance(result, TemplateInfo) and result.id == "tpl-unit" + body = json.loads(requests[-1].content) + assert body["imageName"] == image.value + assert body["fromImage"] == selected_url + if image.supports_agent: + assert body["imageType"] == "MANAGED" + assert body["harnessType"] == ( + "dsh" if image is OfficialImage.DEEPSEEK_HARNESS else "openclaw" + ) + + +def test_instance_connection_uses_timeout_and_explicit_release(): + requests = [] + + def handle(request): + requests.append(request) + return httpx.Response(200, json=INSTANCE) + + with _client(handle) as client: + sandbox = client.agentstudio.sandbox.sandboxes + instance = sandbox.create( + SandboxCreateRequest(template_id="tpl-unit", timeout=600), + ) + assert instance.connect() is instance + assert instance.connect(ConnectionOptions(timeout=900)) is instance + assert isinstance(instance.get(), SandboxInfo) + instance.release() + assert json.loads(requests[0].content)["timeout"] == 600 + assert json.loads(requests[1].content) == {} + assert json.loads(requests[2].content) == {"timeout": 900} + assert all( + "lifetime" not in request.content.decode() for request in requests + ) + assert requests[-1].method == "DELETE" + assert requests[-1].url.path == PREFIX + "/sandbox/sandboxes/sbx-unit" + + +@pytest.mark.parametrize( + "model", + [ + None, + ModelConfig(base_url="https://model.test/v1"), + ModelConfig(base_url="https://model.test/v1", api_key="model-key"), + ], +) +def test_launch_keeps_model_credentials_independent_of_platform_key(model): + def handle(request): + assert request.url.path == PREFIX + "/agent-runtime/instances" + body = json.loads(request.content) + assert body["image_name"] == "deepseek-harness" + assert "image_url" not in body + assert "platform-key" not in request.content.decode() + if model is not None and model.api_key: + assert body["model_config"]["api_key"] == "model-key" + else: + assert "api_key" not in body.get("model_config", {}) + return httpx.Response( + 202, + json={ + "data": { + "instance_id": "ai-unit", + "operation_id": "op-unit", + }, + }, + ) + + with _client(handle) as client: + accepted = client.agentstudio.sandbox.agents.launch_async( + LaunchRequest( + image=OfficialImage.DEEPSEEK_HARNESS, + model_config=model, + ), + ) + assert accepted.instance_id == "ai-unit" + + +def test_turn_callback_resumes_sse_and_returns_typed_result(): + events = [ + { + "turn_id": "ar-unit", + "sequence": 2, + "type": "message.delta", + "payload": {"delta": "你好"}, + }, + {"turn_id": "ar-unit", "sequence": 3, "type": "turn.completed"}, + ] + + def handle(request): + path = request.url.path + if request.method == "POST": + assert path == PREFIX + "/agent-runtime/sessions/as-unit/turns" + return httpx.Response(202, json={"data": {"turn_id": "ar-unit"}}) + assert request.method == "GET" + if path.endswith("/events"): + assert request.url.params["after_seq"] == "1" + assert request.headers["Last-Event-ID"] == "ar-unit:1" + data = "".join( + "data: " + json.dumps(event) + "\n\n" for event in events + ) + return httpx.Response( + 200, + text=data, + headers={ + "Content-Type": "text/event-stream", + }, + ) + assert path == PREFIX + "/agent-runtime/turns/ar-unit" + return httpx.Response( + 200, + json={ + "data": { + "turn_id": "ar-unit", + "status": "SUCCEEDED", + "output": [{"type": "text", "text": "56"}], + }, + }, + ) + + with _client(handle) as client: + turn = client.agentstudio.sandbox.agents.session("as-unit").submit( + "7乘8", + ) + received = [] + with turn.subscribe(received.append, after_sequence=1) as stream: + stream.wait(timeout=5) + assert received == events and stream.last_sequence == 3 + assert received[0]["payload"]["delta"] == "你好" + result = turn.wait() + assert isinstance(result, TurnResult) and result.text == "56" + + +def test_template_file_upload_preserves_chinese_filename_and_content(tmp_path): + source = tmp_path / "中文资料.txt" + source.write_text("附件内容", encoding="utf-8") + + def handle(request): + assert request.method == "POST" + assert request.url.path == PREFIX + "/files" + assert "multipart/form-data" in request.headers["Content-Type"] + body = request.read() + assert source.name.encode() in body and source.read_bytes() in body + assert b"sandbox_template" in body + return httpx.Response( + 200, + json={"id": "file-unit", "status": "available"}, + ) + + with _client(handle) as client: + file = client.agentstudio.sandbox.template_files.upload(source) + assert isinstance(file, TemplateFile) and file.id == "file-unit" + + +def test_api_error_preserves_status_code_and_request_id(): + with _http( + lambda request: httpx.Response( + 409, + json={ + "error": { + "code": "TEMPLATE_IN_USE", + "message": "Template is in use", + }, + "request_id": "req-unit", + }, + ), + ) as pool, Client( + api_key="platform-key", + base_url=BASE, + http_client=pool, + ) as client: + with pytest.raises(SandboxAPIError) as error: + client.agentstudio.sandbox.templates.delete("tpl-unit") + assert error.value.status_code == 409 + assert error.value.code == "TEMPLATE_IN_USE" + assert error.value.request_id == "req-unit" + + +def test_sandbox_close_preserves_parent_borrowed_http_pool(): + with _http(lambda request: httpx.Response(200, json={"data": []})) as pool: + with Client( + api_key="platform-key", + base_url=BASE, + http_client=pool, + ) as client: + sandbox = client.agentstudio.sandbox + sandbox.close() + assert not pool.is_closed + assert list(client.agentstudio.agents.list()) == [] + assert not pool.is_closed + assert pool.is_closed + + +@pytest.mark.asyncio +async def test_async_public_facet_and_borrowed_pool_lifecycle(): + def handle(request): + assert request.url.path == PREFIX + "/sandbox/v2/sandboxes" + assert request.headers["Authorization"] == "Bearer platform-key" + return httpx.Response(200, json=[INSTANCE]) + + async with httpx.AsyncClient( + transport=httpx.MockTransport(handle), + ) as pool: + async with AsyncClient( + api_key="platform-key", + base_url=BASE, + http_client=pool, + ) as client: + sandbox = client.agentstudio.sandbox + values = await sandbox.sandboxes.list() + assert isinstance(values[0], SandboxInfo) + await sandbox.aclose() + assert not pool.is_closed + assert not pool.is_closed + assert pool.is_closed + + +def _run_recipe(monkeypatch, name, handler): + monkeypatch.setenv("DASHSCOPE_AGENTSTUDIO_URL", BASE) + monkeypatch.setenv("DASHSCOPE_MODEL_BASE_URL", "https://model.test/v1") + monkeypatch.setenv("DASHSCOPE_MODEL_API_KEY", "model-key") + with _http(handler) as pool: + monkeypatch.setattr( + dashscope, + "Client", + lambda **kwargs: Client( + api_key="platform-key", + http_client=pool, + **kwargs, + ), + ) + path = Path(__file__).parents[1] / "examples/03_agent_recipes" / name + runpy.run_path(str(path))["main"]() + + +@pytest.mark.parametrize("failure", [False, True]) +def test_lifecycle_recipe_releases_instance_before_template( + monkeypatch, + failure, +): + calls = [] + routes = { + ("GET", "/sandbox/images/code-interpreter-v1"): { + "imageName": "code-interpreter-v1", + "imageUrl": "https://registry.test/current", + }, + ("POST", "/sandbox/v3/templates"): { + "id": "tpl-unit", + "buildID": "build-unit", + }, + ("GET", "/sandbox/templates/tpl-unit/builds/build-unit/status"): { + "status": "READY", + }, + ("POST", "/sandbox/sandboxes"): INSTANCE, + ("POST", "/sandbox/sandboxes/sbx-unit/connect"): INSTANCE, + ("GET", "/sandbox/sandboxes/sbx-unit"): httpx.Response(500) + if failure + else INSTANCE, + ("DELETE", "/sandbox/sandboxes/sbx-unit"): None, + ("DELETE", "/sandbox/templates/tpl-unit"): None, + } + + def handle(request): + calls.append((request.method, request.url.path.removeprefix(PREFIX))) + return _response(request, routes) + + if failure: + with pytest.raises(SandboxAPIError): + _run_recipe(monkeypatch, "agentstudio_sandbox.py", handle) + else: + _run_recipe(monkeypatch, "agentstudio_sandbox.py", handle) + assert calls[-2:] == [ + ("DELETE", "/sandbox/sandboxes/sbx-unit"), + ("DELETE", "/sandbox/templates/tpl-unit"), + ] + + +@pytest.mark.parametrize("status", ["SUCCEEDED", "FAILED"]) +def test_agent_recipe_releases_after_success_or_failed_turn( + monkeypatch, + status, +): + calls = [] + routes = { + ("POST", "/agent-runtime/instances"): { + "instance_id": "ai-unit", + "operation_id": "op-start", + }, + ("GET", "/agent-runtime/operations/op-start"): { + "operation_id": "op-start", + "status": "SUCCEEDED", + }, + ("GET", "/agent-runtime/instances/ai-unit"): { + "instance_id": "ai-unit", + "state": "READY", + "default_session_id": "as-unit", + }, + ("POST", "/agent-runtime/sessions/as-unit/turns"): { + "turn_id": "ar-unit", + }, + ("GET", "/agent-runtime/turns/ar-unit"): { + "turn_id": "ar-unit", + "status": status, + "output": [{"type": "text", "text": "56"}], + }, + ("DELETE", "/agent-runtime/instances/ai-unit"): { + "operation_id": "op-release", + }, + ("GET", "/agent-runtime/operations/op-release"): { + "operation_id": "op-release", + "status": "SUCCEEDED", + }, + } + + def handle(request): + calls.append((request.method, request.url.path.removeprefix(PREFIX))) + return _response(request, routes) + + if status == "FAILED": + with pytest.raises(RuntimeError, match="FAILED"): + _run_recipe(monkeypatch, "agentstudio_sandbox_agent.py", handle) + else: + _run_recipe(monkeypatch, "agentstudio_sandbox_agent.py", handle) + assert ("DELETE", "/agent-runtime/instances/ai-unit") in calls + + +@pytest.mark.parametrize("reuse", [False, True]) +def test_web_ui_recipe_closes_and_preserves_reused_model_settings( + monkeypatch, + reuse, + capsys, +): + preview = SimpleNamespace( + sandbox_id="sbx-unit", + preview_url="http://127.0.0.1:8765", + close=Mock(), + ) + opened = Mock(return_value=preview) + browser = Mock() + monkeypatch.setattr(SandboxesClient, "open_web_ui", opened) + monkeypatch.setattr("webbrowser.open", browser) + monkeypatch.setattr("builtins.input", lambda prompt: "") + if reuse: + monkeypatch.setenv("DASHSCOPE_SANDBOX_ID", "sbx-existing") + else: + monkeypatch.delenv("DASHSCOPE_SANDBOX_ID", raising=False) + _run_recipe(monkeypatch, "agentstudio_sandbox_web_ui.py", None) + options = opened.call_args.args[-1] + assert options.sandbox_id == ("sbx-existing" if reuse else None) + assert options.model_api_key == (None if reuse else "model-key") + browser.assert_called_once_with(preview.preview_url) + preview.close.assert_called_once_with() + output = capsys.readouterr().out + assert preview.preview_url in output + assert "platform-key" not in output and "model-key" not in output