Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion scripts/gen_signature.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import sys
import types
import typing as t
from collections import defaultdict
from pathlib import Path

from pydantic import AnyUrl, BaseModel
Expand Down Expand Up @@ -42,6 +43,17 @@ def __init__(self, schema_module: t.Any = None) -> None:
self._literals = {
name: value for name, value in self._schema.__dict__.items() if t.get_origin(value) is t.Literal
}
union_aliases: dict[frozenset[t.Any], list[str]] = defaultdict(list)
for name, value in self._schema.__dict__.items():
if name.startswith("_"):
continue
while t.get_origin(value) is t.Annotated:
value = t.get_args(value)[0]
if t.get_origin(value) in (t.Union, types.UnionType):
members = frozenset(t.get_args(value))
if type(None) not in members:
union_aliases[members].append(name)
self._unions = {members: names[0] for members, names in union_aliases.items() if len(names) == 1}
self._current_model_name: str | None = None
self._type_aliases: dict[str, ast.expr] = {}
self._schema_names: dict[str, str] = {}
Expand Down Expand Up @@ -201,7 +213,16 @@ def _format_annotation(self, annotation: t.Any) -> ast.expr:
if origin is t.Annotated:
return self._format_annotation(t.get_args(annotation)[0])
if origin in (t.Union, types.UnionType):
first, *rest = t.get_args(annotation)
args = t.get_args(annotation)
has_none = type(None) in args
members = tuple(arg for arg in args if arg is not type(None))
if alias_name := self._unions.get(frozenset(members)):
self._add_schema_import(alias_name)
reference = self._schema_reference(alias_name)
if has_none:
return ast.BinOp(left=reference, op=ast.BitOr(), right=ast.Constant(value=None))
return reference
first, *rest = args
formatted = self._format_annotation(first)
for argument in rest:
formatted = ast.BinOp(left=formatted, op=ast.BitOr(), right=self._format_annotation(argument))
Expand Down
37 changes: 1 addition & 36 deletions src/acp/experimental/v2/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,42 +112,7 @@ async def request_permission(
)

@param_model(schema.UpdateSessionNotification)
async def session_update(
self,
session_id: str,
update: schema.UserMessageChunk
| schema.UserMessageUpdate
| schema.AgentMessageChunk
| schema.AgentMessageUpdate
| schema.AgentThoughtChunk
| schema.AgentThoughtUpdate
| schema.ToolCallContentChunkUpdate
| schema.SessionToolCallUpdate
| schema.SessionTerminalUpdate
| schema.SessionTerminalOutputChunk
| schema.SessionPlanUpdate
| schema.SessionPlanRemovedUpdate
| schema.AvailableCommandsUpdate
| schema.ConfigOptionUpdate
| schema.SessionInfoUpdate
| schema.UsageUpdate
| schema.SessionNotice
| schema.SessionCompactionUpdate
| schema.SessionCompactionSummaryChunk
| schema.SessionReplayComplete
| schema.SessionPromptSuggestionsUpdate
| schema.SessionCursorUpdate
| schema.SessionSubagentUpdate
| schema.SessionMessageUpdate
| schema.SessionMessageChunkUpdate
| schema.OtherSessionUpdate
| schema.RunningSessionStateUpdate
| schema.IdleSessionStateUpdate
| schema.RequiresActionSessionStateUpdate
| schema.UnknownSessionStateUpdate
| schema.OtherSessionStateUpdate,
**kwargs: Any,
) -> None:
async def session_update(self, session_id: str, update: schema.SessionUpdate, **kwargs: Any) -> None:
await self._notify(
CLIENT_METHODS["session_update"],
build_request(schema.UpdateSessionNotification, {"session_id": session_id, "update": update}, kwargs),
Expand Down
14 changes: 1 addition & 13 deletions src/acp/experimental/v2/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,19 +253,7 @@ async def set_config_option(

@param_model(schema.PromptRequest)
async def prompt(
self,
session_id: str,
prompt: list[
schema.TextContentBlock
| schema.ImageContentBlock
| schema.AudioContentBlock
| schema.ResourceContentBlock
| schema.EmbeddedResourceContentBlock
| schema.SkillContentBlock
| schema.OtherContentBlock
],
idempotency_key: str | None = None,
**kwargs: Any,
self, session_id: str, prompt: list[schema.ContentBlock], idempotency_key: str | None = None, **kwargs: Any
) -> schema.PromptResponse:
return await self._request(
AGENT_METHODS["session_prompt"],
Expand Down
51 changes: 2 additions & 49 deletions src/acp/experimental/v2/interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,19 +132,7 @@ async def set_config_option(

@param_model(schema.PromptRequest, method=AGENT_METHODS["session_prompt"])
async def prompt(
self,
session_id: str,
prompt: list[
schema.TextContentBlock
| schema.ImageContentBlock
| schema.AudioContentBlock
| schema.ResourceContentBlock
| schema.EmbeddedResourceContentBlock
| schema.SkillContentBlock
| schema.OtherContentBlock
],
idempotency_key: str | None = None,
**kwargs: Any,
self, session_id: str, prompt: list[schema.ContentBlock], idempotency_key: str | None = None, **kwargs: Any
) -> schema.PromptResponse: ...

@param_model(schema.CancelSessionNotification, method=AGENT_METHODS["session_cancel"], kind="notification")
Expand Down Expand Up @@ -204,42 +192,7 @@ async def request_permission(
) -> schema.RequestPermissionResponse: ...

@param_model(schema.UpdateSessionNotification, method=CLIENT_METHODS["session_update"], kind="notification")
async def session_update(
self,
session_id: str,
update: schema.UserMessageChunk
| schema.UserMessageUpdate
| schema.AgentMessageChunk
| schema.AgentMessageUpdate
| schema.AgentThoughtChunk
| schema.AgentThoughtUpdate
| schema.ToolCallContentChunkUpdate
| schema.SessionToolCallUpdate
| schema.SessionTerminalUpdate
| schema.SessionTerminalOutputChunk
| schema.SessionPlanUpdate
| schema.SessionPlanRemovedUpdate
| schema.AvailableCommandsUpdate
| schema.ConfigOptionUpdate
| schema.SessionInfoUpdate
| schema.UsageUpdate
| schema.SessionNotice
| schema.SessionCompactionUpdate
| schema.SessionCompactionSummaryChunk
| schema.SessionReplayComplete
| schema.SessionPromptSuggestionsUpdate
| schema.SessionCursorUpdate
| schema.SessionSubagentUpdate
| schema.SessionMessageUpdate
| schema.SessionMessageChunkUpdate
| schema.OtherSessionUpdate
| schema.RunningSessionStateUpdate
| schema.IdleSessionStateUpdate
| schema.RequiresActionSessionStateUpdate
| schema.UnknownSessionStateUpdate
| schema.OtherSessionStateUpdate,
**kwargs: Any,
) -> None: ...
async def session_update(self, session_id: str, update: schema.SessionUpdate, **kwargs: Any) -> None: ...

@param_model(
schema.MessageMcpRequest,
Expand Down
25 changes: 25 additions & 0 deletions tests/test_gen_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,31 @@ def test_signature_generation_preserves_union_signatures(expression) -> None:
assert ast.dump(tree) == before


def test_signature_generation_reuses_named_union_aliases() -> None:
import ast
from types import SimpleNamespace
from typing import Annotated

from pydantic import BaseModel

from scripts.gen_signature import NodeTransformer

class Request(BaseModel):
value: int | str
optional_value: str | int | None = None

schema = SimpleNamespace(Request=Request, Value=Annotated[str | int, "value"])
tree = ast.parse("from .schema import Request\n@param_model(Request)\nasync def request(self): ...\n")
NodeTransformer(schema).visit(tree)
ast.fix_missing_locations(tree)
assert ast.unparse(tree) == (
"from .schema import Request, Value\n\n"
"@param_model(Request)\n"
"async def request(self, value: Value, optional_value: Value | None=None):\n"
" ..."
)


@pytest.mark.parametrize(
"expression",
[
Expand Down
Loading