68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340 | class ACPAdapter(ACPAgent):
"""Adapts an ant-ai Agent + Workflow to the ACP Agent stdio protocol.
Explicitly implements :class:`acp.interfaces.Agent` so type checkers
verify the full protocol surface is covered.
Can be used directly with :func:`acp.run_agent` for stdio mode, or
wrapped in an :class:`ACPServer` for WebSocket/ASGI mode.
"""
def __init__(
self,
agent: Agent,
workflow: Workflow,
*,
commands: list[ACPCommand] | None = None,
context_class: type[InvocationContext] = InvocationContext,
) -> None:
self._agent: Agent = agent
self._workflow: Workflow[State] = workflow
self._context_class: type[InvocationContext] = context_class
self._commands: dict[str, ACPCommand] = {c.name: c for c in (commands or [])}
self._available_commands: list[AvailableCommand] = [
c.to_available_command() for c in (commands or [])
]
self._client: Client | None = None
self._client_capabilities: ClientCapabilities | None = None
self._sessions: dict[str, list[Message]] = {}
self._session_agents: dict[str, Agent] = {}
self._session_cwds: dict[str, str] = {}
self._session_commands_sent: set[str] = set()
self._translator = HVEventToACP()
def on_connect(self, conn: Client) -> None:
self._client: Client = conn
def _set_session_agent(self, session_id: str, agent: Agent) -> None:
self._session_agents[session_id] = agent
async def initialize(
self,
protocol_version: int,
client_capabilities: ClientCapabilities | None = None,
client_info: Implementation | None = None,
**kwargs: Any,
) -> InitializeResponse:
self._client_capabilities: ClientCapabilities | None = client_capabilities
return InitializeResponse(
protocol_version=protocol_version,
agent_info=Implementation(name=self._agent.name, version="1.0.0"),
agent_capabilities=AgentCapabilities(
load_session=True,
mcp_capabilities=McpCapabilities(http=True, sse=True),
),
)
async def new_session(
self,
cwd: str,
additional_directories: list[str] | None = None,
mcp_servers: _McpServers = None,
**kwargs: Any,
) -> NewSessionResponse:
session_id = str(uuid.uuid4())
self._sessions[session_id] = []
self._session_cwds[session_id] = cwd
logger.debug("acp: new_session cwd='{}'", cwd)
session_agent: Agent = self._agent
if mcp_servers:
extra_tools: list[Tool] = []
for srv in mcp_servers:
if isinstance(srv, HttpMcpServer):
extra_tools.extend(await mcp_tools_from_url(srv.url))
elif isinstance(srv, SseMcpServer):
headers: dict[str, str] = {
h.name: h.value for h in (srv.headers or [])
}
extra_tools.extend(
await mcp_tools_from_url(
srv.url, headers=headers, transport="sse"
)
)
# McpServerStdio: subprocess management out of scope
if extra_tools:
session_agent: Agent = self._agent.model_copy(
update={"tools": [*self._agent.tools, *extra_tools]}
)
self._session_agents[session_id] = session_agent
return NewSessionResponse(session_id=session_id)
async def load_session(
self,
cwd: str,
session_id: str,
mcp_servers: _McpServers = None,
additional_directories: list[str] | None = None,
**kwargs: Any,
) -> LoadSessionResponse | None:
if session_id not in self._sessions:
return None
return LoadSessionResponse()
async def list_sessions(
self,
cwd: str | None = None,
cursor: str | None = None,
**kwargs: Any,
) -> ListSessionsResponse:
sessions: list[SessionInfo] = [
SessionInfo(session_id=sid, cwd="") for sid in self._sessions
]
return ListSessionsResponse(sessions=sessions)
async def prompt(
self,
session_id: str,
prompt: list[Any],
message_id: str | None = None,
**kwargs: Any,
) -> PromptResponse:
_acp_client.set(self._client)
_acp_session_id.set(session_id)
_acp_capabilities.set(self._client_capabilities)
cwd: str | None = self._session_cwds.get(session_id)
_acp_cwd.set(cwd)
caps: ClientCapabilities | None = self._client_capabilities
logger.debug(
"acp: prompt session={} cwd='{}' fs_read={} fs_write={} terminal={}",
session_id[:8],
cwd,
bool(caps and caps.fs and caps.fs.read_text_file),
bool(caps and caps.fs and caps.fs.write_text_file),
bool(caps and caps.terminal),
)
text: str = _extract_prompt_text(prompt)
if (
self._available_commands
and self._client
and session_id not in self._session_commands_sent
):
await self._client.session_update(
session_id=session_id,
update=AvailableCommandsUpdate(
session_update="available_commands_update",
available_commands=self._available_commands,
),
)
self._session_commands_sent.add(session_id)
name, args = parse_slash_command(text)
command = self._commands.get(name) if name else None
if command is not None and command.kind == "code":
return await self._run_code_command(command, args, session_id)
if command is not None and command.kind == "prompt":
text = command.expand(args)
history: list[Message] = list(self._sessions.get(session_id, []))
history.append(Message(role="user", content=text))
ctx: InvocationContext = self._context_class.from_metadata(
session_id=session_id
)
agent: Agent = self._session_agents.get(session_id, self._agent)
state: State = self._workflow.create_state(messages=history)
final_content = ""
async for event in self._workflow.stream(agent=agent, ctx=ctx, state=state):
if self._client:
await self._translator.apply(event, self._client, session_id)
if isinstance(event, FinalAnswerEvent):
final_content = event.content
if session_id in self._sessions:
self._sessions[session_id].append(Message(role="user", content=text))
if final_content:
self._sessions[session_id].append(
Message(role="assistant", content=final_content)
)
return PromptResponse(stop_reason="end_turn")
async def _run_code_command(
self, command: ACPCommand, args: str, session_id: str
) -> PromptResponse:
"""Dispatch a ``kind="code"`` command -- no model turn."""
assert command.handler is not None # guaranteed by ACPCommand.__post_init__
ctx = ACPCommandContext(
args=args,
session_id=session_id,
client=self._client,
capabilities=self._client_capabilities,
cwd=self._session_cwds.get(session_id),
history=self._sessions.setdefault(session_id, []),
agent=self._session_agents.get(session_id, self._agent),
replace_agent=lambda a: self._set_session_agent(session_id, a),
)
try:
reply = await command.handler(ctx)
except Exception:
# Detail stays in the server log; the client gets a generic message so
# handler internals (paths, config) are not disclosed over the wire.
logger.exception("acp: /{} failed", command.name)
reply = f"/{command.name} failed - see server logs."
if reply and self._client:
await self._client.session_update(
session_id=session_id,
update=AgentMessageChunk(
session_update="agent_message_chunk",
content=TextContentBlock(type="text", text=reply),
),
)
return PromptResponse(stop_reason="end_turn")
async def fork_session(
self,
session_id: str,
cwd: str,
additional_directories: list[str] | None = None,
mcp_servers: _McpServers = None,
**kwargs: Any,
) -> ForkSessionResponse:
new_id = str(uuid.uuid4())
self._sessions[new_id] = list(self._sessions.get(session_id, []))
self._session_agents[new_id] = self._session_agents.get(session_id, self._agent)
return ForkSessionResponse(session_id=new_id)
async def resume_session(
self,
session_id: str,
cwd: str,
additional_directories: list[str] | None = None,
mcp_servers: _McpServers = None,
**kwargs: Any,
) -> ResumeSessionResponse:
return ResumeSessionResponse()
async def close_session(
self, session_id: str, **kwargs: Any
) -> CloseSessionResponse | None:
self._sessions.pop(session_id, None)
self._session_agents.pop(session_id, None)
self._session_cwds.pop(session_id, None)
self._session_commands_sent.discard(session_id)
return None
async def authenticate(
self, method_id: str, **kwargs: Any
) -> AuthenticateResponse | None:
return None
async def set_session_mode(
self, session_id: str, mode_id: str, **kwargs: Any
) -> SetSessionModeResponse | None:
return None
async def set_config_option(
self, config_id: str, session_id: str, value: str | bool, **kwargs: Any
) -> SetSessionConfigOptionResponse | None:
return None
async def cancel(self, session_id: str, **kwargs: Any) -> None:
pass
async def ext_method(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
return {}
async def ext_notification(self, method: str, params: dict[str, Any]) -> None:
pass
|