diff --git a/MANIFEST.in b/MANIFEST.in index e372b70a..c82fe6b1 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -4,3 +4,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 c83d0ef8..756a97b5 100644 --- a/dashscope/applications/agentstudio/client.py +++ b/dashscope/applications/agentstudio/client.py @@ -151,6 +151,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. @@ -223,9 +231,30 @@ 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), + # Share the parent HTTP pool without transferring ownership. + # pylint: disable-next=protected-access + 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 @@ -307,9 +336,30 @@ 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), + # Share the parent HTTP pool without transferring ownership. + # pylint: disable-next=protected-access + 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..43842197 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/_bootstrap.py @@ -0,0 +1,582 @@ +# -*- 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 """ + r""""$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}" """ + r""" /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 """ + 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" """ + r""""/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 """ + 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 """ + 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" """ + r""" > "$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" + # 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 + 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=") + + +# 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 = [] + 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"] + # 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 + 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: + # 管控台可能已初始化普通凭据文件;仍拒绝符号链接,且不覆盖已有预览 patch。 + bootstrap.command( + [ + "/bin/sh", + "-ec", + '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, + ], + ) + 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..25e04f5e --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/_validation.py @@ -0,0 +1,136 @@ +# -*- 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, identifier: str, status: str) -> float: + result = end - time.monotonic() + if result <= 0: + raise SandboxWaitTimeoutError(identifier, 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 + # 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 + 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 (0 <= size < count): + 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..38b401f1 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/agents.py @@ -0,0 +1,988 @@ +# -*- 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( + f"Operation {info.id} ended with {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) + # 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 + 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 launch 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( + f"Instance {instance_id} is not ready", + 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: + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access + handle = self._agents._connect( + 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 + 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 returned CANCELLED confirms it.""" + 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( + f"Instance {instance_id} is not ready", + 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: + # Internal SDK coordination preserves transport/resource ownership. + # pylint: disable-next=protected-access + handle = await self._agents._connect( + 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 + 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: + # Finish the running read before closing its owned stream. + 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 returned CANCELLED confirms it.""" + 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..6512d057 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/client.py @@ -0,0 +1,87 @@ +# -*- 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..39463c56 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/models.py @@ -0,0 +1,676 @@ +# -*- 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..91da2f65 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/sandboxes.py @@ -0,0 +1,314 @@ +# -*- 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 f"SandboxHandle(id={self.id!r})" + + +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 f"AsyncSandboxHandle(id={self.id!r})" diff --git a/dashscope/applications/agentstudio/sandbox/streaming.py b/dashscope/applications/agentstudio/sandbox/streaming.py new file mode 100644 index 00000000..5bfac86c --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/streaming.py @@ -0,0 +1,412 @@ +# -*- 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, cast + +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 + + # 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: + 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 != f"{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"] = f"{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: 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, + ) + 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(): + cast(Callable[[dict], Any], 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: 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(), + ) + 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 = cast(Callable[[dict], Any], 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..5c5e573c --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/template_files.py @@ -0,0 +1,305 @@ +# -*- 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..f9984691 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/templates.py @@ -0,0 +1,308 @@ +# -*- 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 + # 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) + 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..7a5d75e0 --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/transport.py @@ -0,0 +1,525 @@ +# -*- 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 as json_module +import threading +import uuid +from contextlib import asynccontextmanager, contextmanager +from pathlib import Path +from typing import Any, 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_module.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..e0ef3c0b --- /dev/null +++ b/dashscope/applications/agentstudio/sandbox/web_ui.py @@ -0,0 +1,514 @@ +# -*- 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`` defaults to True and 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 = True + + +# Keep public option validation in protocol order. +# pylint: disable-next=too-many-branches +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) + # 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 + 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) + # 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, + 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: + # 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): + pass + if not self._closed: + proxy.stdin.write(result) + proxy.stdin.flush() + except (OSError, ValueError): + pass + finally: + 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: + 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 ( + f"SandboxWebUi(sandbox_id={self.sandbox_id!r}, " + f"template_id={self.template_id!r}, preview_url=)" + ) + + 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, 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=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 + 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 + + # 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(), + ) + _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, + ) + 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 + + +# 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. + + Cancellation waits for setup and resource cleanup. The asynchronous SDK's + HTTP client is never used from the worker thread. + """ + 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(), + ) + 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, + # 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 + 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/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/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 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",