Skip to content

Commit f0f546e

Browse files
authored
refactor(codegen): reuse named schema union aliases in generated signatures (#214)
1 parent 034ccbc commit f0f546e

5 files changed

Lines changed: 51 additions & 99 deletions

File tree

‎scripts/gen_signature.py‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import sys
55
import types
66
import typing as t
7+
from collections import defaultdict
78
from pathlib import Path
89

910
from pydantic import AnyUrl, BaseModel
@@ -42,6 +43,17 @@ def __init__(self, schema_module: t.Any = None) -> None:
4243
self._literals = {
4344
name: value for name, value in self._schema.__dict__.items() if t.get_origin(value) is t.Literal
4445
}
46+
union_aliases: dict[frozenset[t.Any], list[str]] = defaultdict(list)
47+
for name, value in self._schema.__dict__.items():
48+
if name.startswith("_"):
49+
continue
50+
while t.get_origin(value) is t.Annotated:
51+
value = t.get_args(value)[0]
52+
if t.get_origin(value) in (t.Union, types.UnionType):
53+
members = frozenset(t.get_args(value))
54+
if type(None) not in members:
55+
union_aliases[members].append(name)
56+
self._unions = {members: names[0] for members, names in union_aliases.items() if len(names) == 1}
4557
self._current_model_name: str | None = None
4658
self._type_aliases: dict[str, ast.expr] = {}
4759
self._schema_names: dict[str, str] = {}
@@ -201,7 +213,16 @@ def _format_annotation(self, annotation: t.Any) -> ast.expr:
201213
if origin is t.Annotated:
202214
return self._format_annotation(t.get_args(annotation)[0])
203215
if origin in (t.Union, types.UnionType):
204-
first, *rest = t.get_args(annotation)
216+
args = t.get_args(annotation)
217+
has_none = type(None) in args
218+
members = tuple(arg for arg in args if arg is not type(None))
219+
if alias_name := self._unions.get(frozenset(members)):
220+
self._add_schema_import(alias_name)
221+
reference = self._schema_reference(alias_name)
222+
if has_none:
223+
return ast.BinOp(left=reference, op=ast.BitOr(), right=ast.Constant(value=None))
224+
return reference
225+
first, *rest = args
205226
formatted = self._format_annotation(first)
206227
for argument in rest:
207228
formatted = ast.BinOp(left=formatted, op=ast.BitOr(), right=self._format_annotation(argument))

‎src/acp/experimental/v2/agent.py‎

Lines changed: 1 addition & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -112,42 +112,7 @@ async def request_permission(
112112
)
113113

114114
@param_model(schema.UpdateSessionNotification)
115-
async def session_update(
116-
self,
117-
session_id: str,
118-
update: schema.UserMessageChunk
119-
| schema.UserMessageUpdate
120-
| schema.AgentMessageChunk
121-
| schema.AgentMessageUpdate
122-
| schema.AgentThoughtChunk
123-
| schema.AgentThoughtUpdate
124-
| schema.ToolCallContentChunkUpdate
125-
| schema.SessionToolCallUpdate
126-
| schema.SessionTerminalUpdate
127-
| schema.SessionTerminalOutputChunk
128-
| schema.SessionPlanUpdate
129-
| schema.SessionPlanRemovedUpdate
130-
| schema.AvailableCommandsUpdate
131-
| schema.ConfigOptionUpdate
132-
| schema.SessionInfoUpdate
133-
| schema.UsageUpdate
134-
| schema.SessionNotice
135-
| schema.SessionCompactionUpdate
136-
| schema.SessionCompactionSummaryChunk
137-
| schema.SessionReplayComplete
138-
| schema.SessionPromptSuggestionsUpdate
139-
| schema.SessionCursorUpdate
140-
| schema.SessionSubagentUpdate
141-
| schema.SessionMessageUpdate
142-
| schema.SessionMessageChunkUpdate
143-
| schema.OtherSessionUpdate
144-
| schema.RunningSessionStateUpdate
145-
| schema.IdleSessionStateUpdate
146-
| schema.RequiresActionSessionStateUpdate
147-
| schema.UnknownSessionStateUpdate
148-
| schema.OtherSessionStateUpdate,
149-
**kwargs: Any,
150-
) -> None:
115+
async def session_update(self, session_id: str, update: schema.SessionUpdate, **kwargs: Any) -> None:
151116
await self._notify(
152117
CLIENT_METHODS["session_update"],
153118
build_request(schema.UpdateSessionNotification, {"session_id": session_id, "update": update}, kwargs),

‎src/acp/experimental/v2/client.py‎

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -253,19 +253,7 @@ async def set_config_option(
253253

254254
@param_model(schema.PromptRequest)
255255
async def prompt(
256-
self,
257-
session_id: str,
258-
prompt: list[
259-
schema.TextContentBlock
260-
| schema.ImageContentBlock
261-
| schema.AudioContentBlock
262-
| schema.ResourceContentBlock
263-
| schema.EmbeddedResourceContentBlock
264-
| schema.SkillContentBlock
265-
| schema.OtherContentBlock
266-
],
267-
idempotency_key: str | None = None,
268-
**kwargs: Any,
256+
self, session_id: str, prompt: list[schema.ContentBlock], idempotency_key: str | None = None, **kwargs: Any
269257
) -> schema.PromptResponse:
270258
return await self._request(
271259
AGENT_METHODS["session_prompt"],

‎src/acp/experimental/v2/interfaces.py‎

Lines changed: 2 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -132,19 +132,7 @@ async def set_config_option(
132132

133133
@param_model(schema.PromptRequest, method=AGENT_METHODS["session_prompt"])
134134
async def prompt(
135-
self,
136-
session_id: str,
137-
prompt: list[
138-
schema.TextContentBlock
139-
| schema.ImageContentBlock
140-
| schema.AudioContentBlock
141-
| schema.ResourceContentBlock
142-
| schema.EmbeddedResourceContentBlock
143-
| schema.SkillContentBlock
144-
| schema.OtherContentBlock
145-
],
146-
idempotency_key: str | None = None,
147-
**kwargs: Any,
135+
self, session_id: str, prompt: list[schema.ContentBlock], idempotency_key: str | None = None, **kwargs: Any
148136
) -> schema.PromptResponse: ...
149137

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

206194
@param_model(schema.UpdateSessionNotification, method=CLIENT_METHODS["session_update"], kind="notification")
207-
async def session_update(
208-
self,
209-
session_id: str,
210-
update: schema.UserMessageChunk
211-
| schema.UserMessageUpdate
212-
| schema.AgentMessageChunk
213-
| schema.AgentMessageUpdate
214-
| schema.AgentThoughtChunk
215-
| schema.AgentThoughtUpdate
216-
| schema.ToolCallContentChunkUpdate
217-
| schema.SessionToolCallUpdate
218-
| schema.SessionTerminalUpdate
219-
| schema.SessionTerminalOutputChunk
220-
| schema.SessionPlanUpdate
221-
| schema.SessionPlanRemovedUpdate
222-
| schema.AvailableCommandsUpdate
223-
| schema.ConfigOptionUpdate
224-
| schema.SessionInfoUpdate
225-
| schema.UsageUpdate
226-
| schema.SessionNotice
227-
| schema.SessionCompactionUpdate
228-
| schema.SessionCompactionSummaryChunk
229-
| schema.SessionReplayComplete
230-
| schema.SessionPromptSuggestionsUpdate
231-
| schema.SessionCursorUpdate
232-
| schema.SessionSubagentUpdate
233-
| schema.SessionMessageUpdate
234-
| schema.SessionMessageChunkUpdate
235-
| schema.OtherSessionUpdate
236-
| schema.RunningSessionStateUpdate
237-
| schema.IdleSessionStateUpdate
238-
| schema.RequiresActionSessionStateUpdate
239-
| schema.UnknownSessionStateUpdate
240-
| schema.OtherSessionStateUpdate,
241-
**kwargs: Any,
242-
) -> None: ...
195+
async def session_update(self, session_id: str, update: schema.SessionUpdate, **kwargs: Any) -> None: ...
243196

244197
@param_model(
245198
schema.MessageMcpRequest,

‎tests/test_gen_all.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,31 @@ def test_signature_generation_preserves_union_signatures(expression) -> None:
149149
assert ast.dump(tree) == before
150150

151151

152+
def test_signature_generation_reuses_named_union_aliases() -> None:
153+
import ast
154+
from types import SimpleNamespace
155+
from typing import Annotated
156+
157+
from pydantic import BaseModel
158+
159+
from scripts.gen_signature import NodeTransformer
160+
161+
class Request(BaseModel):
162+
value: int | str
163+
optional_value: str | int | None = None
164+
165+
schema = SimpleNamespace(Request=Request, Value=Annotated[str | int, "value"])
166+
tree = ast.parse("from .schema import Request\n@param_model(Request)\nasync def request(self): ...\n")
167+
NodeTransformer(schema).visit(tree)
168+
ast.fix_missing_locations(tree)
169+
assert ast.unparse(tree) == (
170+
"from .schema import Request, Value\n\n"
171+
"@param_model(Request)\n"
172+
"async def request(self, value: Value, optional_value: Value | None=None):\n"
173+
" ..."
174+
)
175+
176+
152177
@pytest.mark.parametrize(
153178
"expression",
154179
[

0 commit comments

Comments
 (0)