diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c226f9..dd10490 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,28 @@ existing `0.1.0` release; earlier development prereleases are not listed. ## [Unreleased] +## [0.17.0] + +### Added + +- Add optional Managed `sessions.events.send(busy_mode="reject" | "steer")` in synchronous and asynchronous clients. Omit it for the service's `reject` default (HTTP 409 during an active Turn); `steer` (Beta) appends a user message without cancelling the Turn. Respond to pending tool confirmation or custom tool results first. +- Add Forward Template `managed_tool_config.schedule` request/response types with `access_scope="identity" | "template"`. Omit or clear `schedule` for the identity default; template scope limits management to Schedules created by that Template and cannot be expanded by Identity overrides. +- Add Managed Session Agent patch `name` and `description`. Pass `betas=["session-agent-patch-2026-07-21"]`; patches change the embedded snapshot, not its Agent ID/version or coordinator roster. Wait for idle when a clean Turn boundary is required. + +### Fixed + +- Make Forward `ManagedToolConfigParam.enabled_tools` optional so the documented empty-object clearing form is typed correctly. Template updates replace the whole baseline; `None`, `{}`, or `enabled_tools=[]` clears the managed capabilities. +- Document Managed SA Key direct access with the existing `auth_mode="sa", access_token=sa_key` configuration. Add synchronous/asynchronous `--managed-direct` SA Key examples; the default still exchanges and caches a shared SAT for Forward and Managed. Forward business APIs require PAT or SAT. + +### Breaking changes + +- Narrow Managed `UserMessageEventParams.content` to text and image blocks, matching the public user-message contract. Document and redacted blocks are no longer accepted by that request type; historical response parsing and tool-result document input remain unchanged. + +### Migration + +- Send user messages as non-empty text/image arrays; use image Base64, HTTPS URL or uploaded File sources. Put document results in supported `user.tool_result` or `user.custom_tool_result` events instead of user messages. This is a typing correction, not new client-side runtime validation. +- Existing `extra_body={"busy_mode": "steer"}` calls remain supported; use the explicit `busy_mode="steer"` argument for typed access. No new Beta header is added automatically. + ## [0.16.0] ### Added diff --git a/README.md b/README.md index aa86fa7..ca43b26 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,23 @@ clients accept the same configuration). `QODER_ACCESS_TOKEN` supplies the select mode's token; only PAT mode falls back to `QODER_PAT`. Ordinary clients do not read `QODER_SA_KEY` or implicitly exchange it. +Managed also accepts the complete SA Key directly, without exchanging a SAT: + +```python +import os +from qca import Managed + +with Managed(auth_mode="sa", access_token=os.environ["QODER_SA_KEY"]) as managed: + agents = managed.agents.list(limit=1) +``` + +`AsyncManaged` accepts the same static configuration. Forward business APIs +require PAT or SAT, not a raw SA Key. Use the credential below to exchange and +cache a SAT shared by Forward and Managed. The runnable SA Key example preserves +that shared-SAT default; select `python -m examples.auth.sa_key --managed-direct` +(or add `--async`) for Managed-only direct access. Configure the matching CN base +URL explicitly when using a CN key. + ```python from qca import Forward, Managed, ServiceAccountCredential diff --git a/docs/api/reference.md b/docs/api/reference.md index e5502ff..b8e7c2c 100644 --- a/docs/api/reference.md +++ b/docs/api/reference.md @@ -15308,6 +15308,22 @@ class ManagedCapabilityOverride(BaseModel) # qca.forward.types.managed\_tool\_config + + +## ManagedScheduleConfig + +```python +class ManagedScheduleConfig(BaseModel) +``` + +[[view_source]](https://github.com/QoderAI/qoder-cloud-agents-sdk-python/blob/main/src/qca/forward/types/managed_tool_config.py) + +Template Schedule scope; template confines management to its Schedules. + + + +#### access\_scope + ## ManagedToolConfig @@ -15324,10 +15340,30 @@ Forward-managed tools, distinct from tools[].enabled_tools. #### enabled\_tools + + +#### schedule + # qca.forward.types.managed\_tool\_config\_param + + +## ManagedScheduleConfigParam + +```python +class ManagedScheduleConfigParam(TypedDict) +``` + +[[view_source]](https://github.com/QoderAI/qoder-cloud-agents-sdk-python/blob/main/src/qca/forward/types/managed_tool_config_param.py) + +Schedule management scope; omission defaults to identity. + + + +#### access\_scope + ## ManagedToolConfigParam @@ -15338,12 +15374,16 @@ class ManagedToolConfigParam(TypedDict) [[view_source]](https://github.com/QoderAI/qoder-cloud-agents-sdk-python/blob/main/src/qca/forward/types/managed_tool_config_param.py) -Replaces the complete enabled list; [] disables all managed tools. +Replaces the entire Template baseline; {} or enabled_tools=[] clears it. #### enabled\_tools + + +#### schedule + # qca.forward.types.mcp\_server @@ -24989,6 +25029,7 @@ def send( UserToolResultEventParams, SystemMessageEventParams, ]], + busy_mode: Union[Literal["reject", "steer"], NotGiven] = NOT_GIVEN, workspace_id: Union[str, None, NotGiven] = NOT_GIVEN, betas: Union[List[str], None, NotGiven] = NOT_GIVEN, extra_headers: Dict[str, str] | None = None, @@ -25002,6 +25043,10 @@ def send( POST /sessions/{session_id}/events. +Omit busy_mode for the server's reject default (409 during an active Turn). +Use steer (Beta) to append user.message without cancelling the current Turn. +Respond to pending tool confirmation or custom tool results first. + #### stream @@ -25108,6 +25153,7 @@ async def send( UserToolResultEventParams, SystemMessageEventParams, ]], + busy_mode: Union[Literal["reject", "steer"], NotGiven] = NOT_GIVEN, workspace_id: Union[str, None, NotGiven] = NOT_GIVEN, betas: Union[List[str], None, NotGiven] = NOT_GIVEN, extra_headers: Dict[str, str] | None = None, @@ -25121,6 +25167,10 @@ async def send( POST /sessions/{session_id}/events. +Omit busy_mode for the server's reject default (409 during an active Turn). +Use steer (Beta) to append user.message without cancelling the current Turn. +Respond to pending tool confirmation or custom tool results first. + #### stream @@ -35321,6 +35371,19 @@ class SessionAgentUpdateParam(TypedDict) [[view_source]](https://github.com/QoderAI/qoder-cloud-agents-sdk-python/blob/main/src/qca/managed/types/session_agent_update_param.py) +Patch the embedded snapshot, not its ID/version or coordinator roster. + +model, system, skills, name and description require session-agent-patch-2026-07-21. +Lists are complete replacements; wait for idle for a clean Turn boundary. + + + +#### name + + + +#### description + #### model @@ -35823,6 +35886,10 @@ class SessionEventSendParams(TypedDict) #### events + + +#### busy\_mode + #### workspace\_id @@ -38943,6 +39010,8 @@ class UserMessageEventParams(TypedDict) [[view_source]](https://github.com/QoderAI/qoder-cloud-agents-sdk-python/blob/main/src/qca/managed/types/user_message_event_params.py) +User input accepts a non-empty array of text or image blocks. + #### content diff --git a/examples/auth/sa_key.py b/examples/auth/sa_key.py index 1e07664..484566f 100644 --- a/examples/auth/sa_key.py +++ b/examples/auth/sa_key.py @@ -1,7 +1,7 @@ -"""Exchange an SA Key automatically; list Forward templates and Managed agents. +"""Use an SA Key directly for Managed or exchange a shared SAT for both APIs. Set QODER_SA_KEY and QODER_SA_REGION=cn|global in the process environment. -Run: python -m examples.auth.sa_key [--async] +Run: python -m examples.auth.sa_key [--async] [--managed-direct] """ import argparse @@ -28,8 +28,14 @@ def config(): return dict(sa_key=os.environ["QODER_SA_KEY"], region=region, scopes=["qca.access", "forward.access"]), host -def main(): +def main(*, managed_direct=False): options, host = config() + if managed_direct: + with Managed( + auth_mode="sa", access_token=options["sa_key"], base_url=f"{host}/api/v1/cloud", max_retries=0 + ) as managed: + print("Managed agents:", len(managed.agents.list(limit=1).data)) + return with ServiceAccountCredential(**options) as credential: with ( Forward(credential=credential, base_url=f"{host}/api/v1/forward", max_retries=0) as forward, @@ -39,8 +45,14 @@ def main(): print("Managed agents:", len(managed.agents.list(limit=1).data)) -async def async_main(): +async def async_main(*, managed_direct=False): options, host = config() + if managed_direct: + async with AsyncManaged( + auth_mode="sa", access_token=options["sa_key"], base_url=f"{host}/api/v1/cloud", max_retries=0 + ) as managed: + print("Managed agents:", len((await managed.agents.list(limit=1)).data)) + return async with AsyncServiceAccountCredential(**options) as credential: async with ( AsyncForward(credential=credential, base_url=f"{host}/api/v1/forward", max_retries=0) as forward, @@ -53,9 +65,15 @@ async def async_main(): if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--async", dest="use_async", action="store_true") + parser.add_argument( + "--managed-direct", action="store_true", help="Use the SA Key without SAT exchange (Managed only)" + ) args = parser.parse_args() try: - asyncio.run(async_main()) if args.use_async else main() + if args.use_async: + asyncio.run(async_main(managed_direct=args.managed_direct)) + else: + main(managed_direct=args.managed_direct) except Exception as error: # Avoid dumping authentication headers from an HTTP error traceback. print(f"SA Key example failed: {type(error).__name__}") diff --git a/pyproject.toml b/pyproject.toml index a62144d..a463ef4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "qca-sdk" -version = "0.16.0" +version = "0.17.0" description = "Typed synchronous and asynchronous clients for Qoder Cloud Agents" authors = [{name = "Qoder"}] license = "MIT" diff --git a/src/qca/forward/types/__init__.py b/src/qca/forward/types/__init__.py index 2c67710..c773d92 100644 --- a/src/qca/forward/types/__init__.py +++ b/src/qca/forward/types/__init__.py @@ -143,7 +143,9 @@ from .image_source_param import ImageSourceParam as ImageSourceParam from .managed_capability_override import ManagedCapabilityOverride as ManagedCapabilityOverride from .managed_capability_override import ManagedCapabilityOverrideParam as ManagedCapabilityOverrideParam +from .managed_tool_config import ManagedScheduleConfig as ManagedScheduleConfig from .managed_tool_config import ManagedToolConfig as ManagedToolConfig +from .managed_tool_config_param import ManagedScheduleConfigParam as ManagedScheduleConfigParam from .managed_tool_config_param import ManagedToolConfigParam as ManagedToolConfigParam from .mcp_server import MCPServer as MCPServer from .mcp_server_override import MCPServerOverride as MCPServerOverride diff --git a/src/qca/forward/types/managed_tool_config.py b/src/qca/forward/types/managed_tool_config.py index d673cdc..77ecd92 100644 --- a/src/qca/forward/types/managed_tool_config.py +++ b/src/qca/forward/types/managed_tool_config.py @@ -1,7 +1,16 @@ +from typing import Literal + from qca.common._models import BaseModel +class ManagedScheduleConfig(BaseModel): + """Template Schedule scope; template confines management to its Schedules.""" + + access_scope: Literal["identity", "template"] + + class ManagedToolConfig(BaseModel): """Forward-managed tools, distinct from tools[].enabled_tools.""" enabled_tools: list[str] + schedule: ManagedScheduleConfig | None = None diff --git a/src/qca/forward/types/managed_tool_config_param.py b/src/qca/forward/types/managed_tool_config_param.py index 8e6ffdd..6bce30e 100644 --- a/src/qca/forward/types/managed_tool_config_param.py +++ b/src/qca/forward/types/managed_tool_config_param.py @@ -1,7 +1,16 @@ +from typing import Literal + from typing_extensions import TypedDict -class ManagedToolConfigParam(TypedDict): - """Replaces the complete enabled list; [] disables all managed tools.""" +class ManagedScheduleConfigParam(TypedDict, total=False): + """Schedule management scope; omission defaults to identity.""" + + access_scope: Literal["identity", "template"] + + +class ManagedToolConfigParam(TypedDict, total=False): + """Replaces the entire Template baseline; {} or enabled_tools=[] clears it.""" enabled_tools: list[str] + schedule: ManagedScheduleConfigParam | None diff --git a/src/qca/managed/resources/sessions/events.py b/src/qca/managed/resources/sessions/events.py index 7827f3d..827debb 100644 --- a/src/qca/managed/resources/sessions/events.py +++ b/src/qca/managed/resources/sessions/events.py @@ -86,6 +86,7 @@ def send( SystemMessageEventParams, ] ], + busy_mode: Union[Literal["reject", "steer"], NotGiven] = NOT_GIVEN, workspace_id: Union[str, None, NotGiven] = NOT_GIVEN, betas: Union[List[str], None, NotGiven] = NOT_GIVEN, extra_headers: Dict[str, str] | None = None, @@ -93,10 +94,15 @@ def send( extra_body: Dict[str, Any] | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SendSessionEvents: - """POST /sessions/{session_id}/events.""" + """POST /sessions/{session_id}/events. + + Omit busy_mode for the server's reject default (409 during an active Turn). + Use steer (Beta) to append user.message without cancelling the current Turn. + Respond to pending tool confirmation or custom tool results first. + """ _path = path_template("/sessions/{session_id}/events", session_id=session_id) options = make_request_options( - body={"events": events}, + body={"events": events, "busy_mode": busy_mode}, query={}, headers={"qoder-workspace-id": workspace_id, "x-qoder-beta": betas}, extra_headers=extra_headers, @@ -231,6 +237,7 @@ async def send( SystemMessageEventParams, ] ], + busy_mode: Union[Literal["reject", "steer"], NotGiven] = NOT_GIVEN, workspace_id: Union[str, None, NotGiven] = NOT_GIVEN, betas: Union[List[str], None, NotGiven] = NOT_GIVEN, extra_headers: Dict[str, str] | None = None, @@ -238,10 +245,15 @@ async def send( extra_body: Dict[str, Any] | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SendSessionEvents: - """POST /sessions/{session_id}/events.""" + """POST /sessions/{session_id}/events. + + Omit busy_mode for the server's reject default (409 during an active Turn). + Use steer (Beta) to append user.message without cancelling the current Turn. + Respond to pending tool confirmation or custom tool results first. + """ _path = path_template("/sessions/{session_id}/events", session_id=session_id) options = make_request_options( - body={"events": events}, + body={"events": events, "busy_mode": busy_mode}, query={}, headers={"qoder-workspace-id": workspace_id, "x-qoder-beta": betas}, extra_headers=extra_headers, diff --git a/src/qca/managed/types/session_agent_update_param.py b/src/qca/managed/types/session_agent_update_param.py index 29a158a..6d4df85 100644 --- a/src/qca/managed/types/session_agent_update_param.py +++ b/src/qca/managed/types/session_agent_update_param.py @@ -18,6 +18,14 @@ class SessionAgentUpdateParam(TypedDict, total=False): + """Patch the embedded snapshot, not its ID/version or coordinator roster. + + model, system, skills, name and description require session-agent-patch-2026-07-21. + Lists are complete replacements; wait for idle for a clean Turn boundary. + """ + + name: str + description: str model: Union[str, ModelConfigParams] system: Optional[str] skills: List[Union[QoderSkillParams, CustomSkillParams]] diff --git a/src/qca/managed/types/session_event_send_params.py b/src/qca/managed/types/session_event_send_params.py index ede1b34..82f2db2 100644 --- a/src/qca/managed/types/session_event_send_params.py +++ b/src/qca/managed/types/session_event_send_params.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Optional, Union +from typing import TYPE_CHECKING, List, Literal, Optional, Union from typing_extensions import Required, TypedDict @@ -30,5 +30,6 @@ class SessionEventSendParams(TypedDict, total=False): ] ] ] + busy_mode: Literal["reject", "steer"] workspace_id: Optional[str] betas: List[str] diff --git a/src/qca/managed/types/user_message_event_params.py b/src/qca/managed/types/user_message_event_params.py index 22c6bf8..fe8ddcd 100644 --- a/src/qca/managed/types/user_message_event_params.py +++ b/src/qca/managed/types/user_message_event_params.py @@ -5,14 +5,14 @@ from typing_extensions import Required, TypedDict if TYPE_CHECKING: - from .document_block_param import DocumentBlockParam from .image_block_param import ImageBlockParam - from .redacted_block_param import RedactedBlockParam from .text_block_param import TextBlockParam __all__ = ["UserMessageEventParams"] class UserMessageEventParams(TypedDict, total=False): - content: Required[List[Union[TextBlockParam, ImageBlockParam, DocumentBlockParam, RedactedBlockParam]]] + """User input accepts a non-empty array of text or image blocks.""" + + content: Required[List[Union[TextBlockParam, ImageBlockParam]]] type: Required[Literal["user.message"]] diff --git a/tests/test_capability_parity.py b/tests/test_capability_parity.py index a6c9e28..bf6c383 100644 --- a/tests/test_capability_parity.py +++ b/tests/test_capability_parity.py @@ -19,7 +19,16 @@ import pytest from pydantic import TypeAdapter, ValidationError -from qca import APIResponseValidationError, AsyncForward, AsyncManaged, BadRequestError, Forward, Managed, __version__ +from qca import ( + APIResponseValidationError, + AsyncForward, + AsyncManaged, + BadRequestError, + ConflictError, + Forward, + Managed, + __version__, +) from qca.common._types import NOT_GIVEN from qca.forward import types as ft from qca.managed import types as mt @@ -835,3 +844,208 @@ def test_mcp_top_level_policy_request_and_response_types(policy): assert snapshot.to_dict() == tool with pytest.raises(ValidationError): adapter(mt.MCPToolsetParams, mt).validate_python({**tool, "permission_policy": {"type": "deny"}}) + + +@pytest.mark.parametrize("busy_mode", [NOT_GIVEN, "reject", "steer"]) +async def test_managed_send_busy_mode_contract(async_, busy_mode): + """Official /api/sessions/events/send: optional body field, checked 2026-12-03.""" + events = [{"type": "user.message", "content": [{"type": "text", "text": "Check login first"}]}] + expected = {"events": events} + if busy_mode is not NOT_GIVEN: + expected["busy_mode"] = busy_mode + + def handle(request): + assert request.method == "POST" + assert request.url.raw_path == f"/api/v1/managed/sessions/{ESCAPED}/events?custom=kept".encode() + assert json.loads(request.content) == expected + assert request.headers["qoder-workspace-id"] == "workspace_test" + assert request.headers["x-test"] == "kept" + assert "x-qoder-beta" not in request.headers + assert request.extensions["timeout"]["read"] == 12.5 + return reply({"data": [{"id": "evt_one", **events[0]}]}) + + async with client_for(async_, "managed", handle) as client: + result = await resolve( + client.sessions.events.send( + SEGMENT, + events=events, + busy_mode=busy_mode, + workspace_id="workspace_test", + extra_headers={"X-Test": "kept"}, + extra_query={"custom": "kept"}, + timeout=12.5, + ) + ) + assert result.data[0].id == "evt_one" + assert result.data[0].content[0].text == "Check login first" + + +async def test_managed_busy_mode_extra_body_override_and_conflict(async_): + calls = [] + + def handle(request): + calls.append(request) + assert json.loads(request.content) == {"events": [], "busy_mode": "steer"} + return reply({"error": {"type": "invalid_request_error", "message": "Pending action"}}, 409) + + async with client_for(async_, "managed", handle) as client: + with pytest.raises(ConflictError): + await resolve( + client.sessions.events.send( + "sess_one", events=[], busy_mode="reject", extra_body={"busy_mode": "steer"} + ) + ) + assert len(calls) == 1 + + +def test_managed_busy_mode_request_type(): + request_type = adapter(mt.SessionEventSendParams, mt) + assert request_type.validate_python({"events": []}) == {"events": []} + for value in ["reject", "steer"]: + payload = {"events": [], "busy_mode": value} + assert request_type.validate_python(payload) == payload + for value in [None, "cancel", True]: + with pytest.raises(ValidationError): + request_type.validate_python({"events": [], "busy_mode": value}) + + +@pytest.mark.parametrize("method", ["create", "update"]) +@pytest.mark.parametrize( + "config", + [ + NOT_GIVEN, + None, + {}, + {"enabled_tools": []}, + {"enabled_tools": ["schedule"], "schedule": None}, + {"enabled_tools": ["schedule"], "schedule": {"access_scope": "identity"}}, + {"enabled_tools": ["schedule"], "schedule": {"access_scope": "template"}}, + ], +) +async def test_template_schedule_scope_contract(async_, method, config): + """Official Forward templates create/update and schedule-management contracts.""" + expected = {"name": "scheduler", "model": "auto", "environment_id": "env_one"} if method == "create" else {} + if config is not NOT_GIVEN: + expected["managed_tool_config"] = config + response = {"id": "tmpl_one"} + if config is not NOT_GIVEN: + response["managed_tool_config"] = config if config else {"enabled_tools": []} + + def handle(request): + assert request.method == "POST" + suffix = "/templates" + ("/tmpl_one" if method == "update" else "") + assert request.url.path == "/api/v1/forward" + suffix + assert json.loads(request.content) == expected + return reply(response) + + async with client_for(async_, "forward", handle) as client: + options = {"managed_tool_config": config} + template = await resolve( + client.templates.create(name="scheduler", model="auto", environment_id="env_one", **options) + if method == "create" + else client.templates.update("tmpl_one", **options) + ) + assert template.to_dict() == response + if isinstance(config, dict) and config.get("schedule"): + assert isinstance(template.managed_tool_config.schedule, ft.ManagedScheduleConfig) + assert template.managed_tool_config.schedule.access_scope == config["schedule"]["access_scope"] + + +def test_template_schedule_scope_public_types(): + request_type = adapter(ft.ManagedToolConfigParam, ft) + for payload in [ + {}, + {"schedule": None}, + {"schedule": {}}, + {"enabled_tools": []}, + {"enabled_tools": ["future_selector"], "schedule": {"access_scope": "template"}}, + ]: + assert request_type.validate_python(payload) == payload + for payload in [ + {"enabled_tools": None}, + {"schedule": {"access_scope": None}}, + {"schedule": {"access_scope": "workspace"}}, + ]: + with pytest.raises(ValidationError): + request_type.validate_python(payload) + assert adapter(ft.ManagedScheduleConfigParam, ft).validate_python({}) == {} + parsed = ft.ManagedToolConfig.model_validate( + {"enabled_tools": ["schedule"], "schedule": {"access_scope": "template", "future": True}} + ) + assert parsed.schedule.future is True + assert ft.ManagedToolConfig.model_validate({"enabled_tools": []}).schedule is None + with pytest.raises(ValidationError): + ft.ManagedToolConfig.model_validate({"enabled_tools": [], "schedule": {"access_scope": "workspace"}}) + + +async def test_managed_session_patch_name_description(async_): + """Official /api/sessions/update: strings and the existing patch Beta header.""" + patch = {"name": "Login reviewer", "description": "", "tools": [{"type": "browser_toolset_20260714"}]} + snapshot = {"id": "agent_one", "version": 7, **patch} + + def handle(request): + assert request.method == "POST" and request.url.path == "/api/v1/managed/sessions/sess_one" + assert json.loads(request.content) == {"agent": patch} + assert request.headers["x-qoder-beta"] == "session-agent-patch-2026-07-21,browser-use-2026-07-14" + return reply({"id": "sess_one", "agent": snapshot}) + + async with client_for(async_, "managed", handle) as client: + session = await resolve( + client.sessions.update( + "sess_one", agent=patch, betas=["session-agent-patch-2026-07-21", "browser-use-2026-07-14"] + ) + ) + assert session.agent.name == "Login reviewer" and session.agent.description == "" + assert session.agent.version == 7 + assert session.agent.to_dict() == snapshot + + +def test_managed_session_patch_public_fields(): + fields = get_type_hints(mt.SessionAgentUpdateParam, vars(mt), vars(mt)) + assert set(fields) == {"name", "description", "model", "system", "skills", "mcp_servers", "tools"} + request_type = adapter(mt.SessionAgentUpdateParam, mt) + for payload in [{"name": "Reviewer"}, {"description": ""}]: + assert request_type.validate_python(payload) == payload + for field in ["name", "description"]: + with pytest.raises(ValidationError): + request_type.validate_python({field: None}) + + +@pytest.mark.parametrize( + "source", + [ + {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}, + {"type": "url", "url": "https://example.test/image.png"}, + {"type": "file", "file_id": "file_image"}, + ], +) +def test_managed_user_message_text_image_contract(source): + payload = { + "type": "user.message", + "content": [{"type": "text", "text": "Describe"}, {"type": "image", "source": source}], + } + assert adapter(mt.UserMessageEventParams, mt).validate_python(payload) == payload + + +@pytest.mark.parametrize( + "block", + [ + {"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "report"}}, + {"type": "redacted", "data": "hidden"}, + ], +) +def test_managed_user_message_excludes_document_redacted(block): + """Official event-schemas#message-content-blocks; not runtime SDK validation.""" + with pytest.raises(ValidationError): + adapter(mt.UserMessageEventParams, mt).validate_python({"type": "user.message", "content": [block]}) + if block["type"] == "document": + for request_type, identifier in [ + (mt.UserToolResultEventParams, "tool_use_id"), + (mt.UserCustomToolResultEventParams, "custom_tool_use_id"), + ]: + payload = { + "type": "user.tool_result" if identifier == "tool_use_id" else "user.custom_tool_result", + identifier: "tool_one", + "content": [block], + } + assert adapter(request_type, mt).validate_python(payload) == payload diff --git a/tests/test_example_auth.py b/tests/test_example_auth.py index df37b49..54ea873 100644 --- a/tests/test_example_auth.py +++ b/tests/test_example_auth.py @@ -104,3 +104,78 @@ def respond(request): credential.get_token() assert [r.headers["Authorization"] for r in requests] == ["Bearer test-key", "Bearer exchanged-sat"] assert [r.url.host for r in requests] == ["openapi.qoder.sh", "api.qoder.com"] + + +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("direct", [False, True], ids=["shared-sat", "managed-direct"]) +@pytest.mark.parametrize("region", ["cn", "global"]) +async def test_sa_key_example_direct_or_shared_sat(is_async, direct, region, monkeypatch, capsys): + from examples.auth import sa_key + + monkeypatch.setenv("QODER_SA_KEY", "test-direct-key") + monkeypatch.setenv("QODER_SA_REGION", region) + requests = [] + clients = [] + exchange_clients = [] + + def respond(request): + requests.append(request) + if request.url.path.endswith("/exchange"): + assert not direct + return httpx.Response( + 200, json={"access_token": "test-shared-sat", "token_type": "Bearer", "expires_in": 3600} + ) + return httpx.Response(200, json={"data": []}) + + def client_factory(client_type, **options): + http = (httpx.AsyncClient if is_async else httpx.Client)(transport=httpx.MockTransport(respond)) + client = client_type(http_client=http, **options) + clients.append(client) + return client + + def credential_factory(**options): + assert not direct + http = (httpx.AsyncClient if is_async else httpx.Client)(transport=httpx.MockTransport(respond)) + exchange_clients.append(http) + return (AsyncServiceAccountCredential if is_async else ServiceAccountCredential)(http_client=http, **options) + + monkeypatch.setattr( + sa_key, + "AsyncManaged" if is_async else "Managed", + partial(client_factory, AsyncManaged if is_async else Managed), + ) + monkeypatch.setattr( + sa_key, + "AsyncForward" if is_async else "Forward", + partial(client_factory, AsyncForward if is_async else Forward), + ) + monkeypatch.setattr( + sa_key, "AsyncServiceAccountCredential" if is_async else "ServiceAccountCredential", credential_factory + ) + try: + if is_async: + await sa_key.async_main(managed_direct=direct) + else: + sa_key.main(managed_direct=direct) + assert all(client.is_closed() for client in clients) + finally: + for http in exchange_clients: + await http.aclose() if is_async else http.close() + host = "api.qoder.com.cn" if region == "cn" else "api.qoder.com" + if direct: + assert [(request.method, request.url.host, request.url.path) for request in requests] == [ + ("GET", host, "/api/v1/cloud/agents") + ] + assert requests[0].headers["authorization"] == "Bearer test-direct-key" + else: + exchange_host = "openapi.qoder.com.cn" if region == "cn" else "openapi.qoder.sh" + assert [request.url.host for request in requests] == [exchange_host, host, host] + assert [request.headers["authorization"] for request in requests] == [ + "Bearer test-direct-key", + "Bearer test-shared-sat", + "Bearer test-shared-sat", + ] + assert [request.url.path for request in requests[1:]] == ["/api/v1/forward/templates", "/api/v1/cloud/agents"] + output = capsys.readouterr() + assert "test-direct-key" not in output.out + output.err + assert "test-shared-sat" not in output.out + output.err diff --git a/uv.lock b/uv.lock index 7fbf66c..14629b4 100644 --- a/uv.lock +++ b/uv.lock @@ -1418,7 +1418,7 @@ wheels = [ [[package]] name = "qca-sdk" -version = "0.16.0" +version = "0.17.0" source = { editable = "." } dependencies = [ { name = "anyio" },