cli-agent-orchestrator 2.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cli_agent_orchestrator/__init__.py +0 -0
- cli_agent_orchestrator/agent_store/code_supervisor.md +66 -0
- cli_agent_orchestrator/agent_store/developer.md +55 -0
- cli_agent_orchestrator/agent_store/reviewer.md +60 -0
- cli_agent_orchestrator/api/__init__.py +1 -0
- cli_agent_orchestrator/api/main.py +947 -0
- cli_agent_orchestrator/cli/__init__.py +1 -0
- cli_agent_orchestrator/cli/commands/__init__.py +1 -0
- cli_agent_orchestrator/cli/commands/env.py +60 -0
- cli_agent_orchestrator/cli/commands/flow.py +102 -0
- cli_agent_orchestrator/cli/commands/info.py +57 -0
- cli_agent_orchestrator/cli/commands/init.py +45 -0
- cli_agent_orchestrator/cli/commands/install.py +317 -0
- cli_agent_orchestrator/cli/commands/launch.py +243 -0
- cli_agent_orchestrator/cli/commands/mcp_server.py +12 -0
- cli_agent_orchestrator/cli/commands/session.py +260 -0
- cli_agent_orchestrator/cli/commands/shutdown.py +59 -0
- cli_agent_orchestrator/cli/commands/skills.py +99 -0
- cli_agent_orchestrator/cli/main.py +36 -0
- cli_agent_orchestrator/clients/database.py +415 -0
- cli_agent_orchestrator/clients/tmux.py +516 -0
- cli_agent_orchestrator/constants.py +145 -0
- cli_agent_orchestrator/mcp_server/__init__.py +1 -0
- cli_agent_orchestrator/mcp_server/models.py +14 -0
- cli_agent_orchestrator/mcp_server/server.py +653 -0
- cli_agent_orchestrator/mcp_server/utils.py +15 -0
- cli_agent_orchestrator/models/__init__.py +1 -0
- cli_agent_orchestrator/models/agent_profile.py +37 -0
- cli_agent_orchestrator/models/copilot_agent.py +15 -0
- cli_agent_orchestrator/models/flow.py +23 -0
- cli_agent_orchestrator/models/inbox.py +33 -0
- cli_agent_orchestrator/models/kiro_agent.py +28 -0
- cli_agent_orchestrator/models/opencode_agent.py +23 -0
- cli_agent_orchestrator/models/provider.py +14 -0
- cli_agent_orchestrator/models/q_agent.py +28 -0
- cli_agent_orchestrator/models/session.py +21 -0
- cli_agent_orchestrator/models/skill.py +19 -0
- cli_agent_orchestrator/models/terminal.py +37 -0
- cli_agent_orchestrator/plugins/__init__.py +24 -0
- cli_agent_orchestrator/plugins/base.py +52 -0
- cli_agent_orchestrator/plugins/events.py +75 -0
- cli_agent_orchestrator/plugins/registry.py +87 -0
- cli_agent_orchestrator/providers/__init__.py +0 -0
- cli_agent_orchestrator/providers/base.py +186 -0
- cli_agent_orchestrator/providers/claude_code.py +434 -0
- cli_agent_orchestrator/providers/codex.py +497 -0
- cli_agent_orchestrator/providers/copilot_cli.py +502 -0
- cli_agent_orchestrator/providers/gemini_cli.py +764 -0
- cli_agent_orchestrator/providers/kimi_cli.py +649 -0
- cli_agent_orchestrator/providers/kiro_cli.py +548 -0
- cli_agent_orchestrator/providers/manager.py +181 -0
- cli_agent_orchestrator/providers/opencode_cli.py +369 -0
- cli_agent_orchestrator/providers/q_cli.py +176 -0
- cli_agent_orchestrator/services/cleanup_service.py +58 -0
- cli_agent_orchestrator/services/flow_service.py +235 -0
- cli_agent_orchestrator/services/inbox_service.py +172 -0
- cli_agent_orchestrator/services/plugin_dispatch.py +42 -0
- cli_agent_orchestrator/services/session_service.py +141 -0
- cli_agent_orchestrator/services/settings_service.py +78 -0
- cli_agent_orchestrator/services/terminal_service.py +475 -0
- cli_agent_orchestrator/skills/__init__.py +1 -0
- cli_agent_orchestrator/skills/cao-session-management/SKILL.md +106 -0
- cli_agent_orchestrator/skills/cao-supervisor-protocols/SKILL.md +84 -0
- cli_agent_orchestrator/skills/cao-worker-protocols/SKILL.md +60 -0
- cli_agent_orchestrator/utils/__init__.py +1 -0
- cli_agent_orchestrator/utils/agent_profiles.py +241 -0
- cli_agent_orchestrator/utils/env.py +41 -0
- cli_agent_orchestrator/utils/logging.py +25 -0
- cli_agent_orchestrator/utils/opencode_config.py +169 -0
- cli_agent_orchestrator/utils/opencode_permissions.py +109 -0
- cli_agent_orchestrator/utils/skill_injection.py +240 -0
- cli_agent_orchestrator/utils/skills.py +129 -0
- cli_agent_orchestrator/utils/template.py +30 -0
- cli_agent_orchestrator/utils/terminal.py +145 -0
- cli_agent_orchestrator/utils/tool_mapping.py +158 -0
- cli_agent_orchestrator/web_ui/assets/index-BXMLhBau.css +32 -0
- cli_agent_orchestrator/web_ui/assets/index-BpPHwanT.js +275 -0
- cli_agent_orchestrator/web_ui/index.html +13 -0
- cli_agent_orchestrator-2.1.1.dist-info/METADATA +681 -0
- cli_agent_orchestrator-2.1.1.dist-info/RECORD +84 -0
- cli_agent_orchestrator-2.1.1.dist-info/WHEEL +4 -0
- cli_agent_orchestrator-2.1.1.dist-info/entry_points.txt +4 -0
- cli_agent_orchestrator-2.1.1.dist-info/licenses/LICENSE +175 -0
- cli_agent_orchestrator-2.1.1.dist-info/licenses/NOTICE +1 -0
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
"""CLI Agent Orchestrator MCP Server implementation."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any, Dict, Optional, Tuple, Union
|
|
8
|
+
|
|
9
|
+
import requests
|
|
10
|
+
from fastmcp import FastMCP
|
|
11
|
+
from pydantic import Field
|
|
12
|
+
|
|
13
|
+
from cli_agent_orchestrator.constants import API_BASE_URL, DEFAULT_PROVIDER
|
|
14
|
+
from cli_agent_orchestrator.mcp_server.models import HandoffResult
|
|
15
|
+
from cli_agent_orchestrator.models.inbox import OrchestrationType
|
|
16
|
+
from cli_agent_orchestrator.models.terminal import TerminalStatus
|
|
17
|
+
from cli_agent_orchestrator.utils.terminal import generate_session_name, wait_until_terminal_status
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
# Environment variable to enable/disable working_directory parameter
|
|
22
|
+
ENABLE_WORKING_DIRECTORY = os.getenv("CAO_ENABLE_WORKING_DIRECTORY", "false").lower() == "true"
|
|
23
|
+
|
|
24
|
+
# Environment variable to enable/disable automatic sender terminal ID injection
|
|
25
|
+
ENABLE_SENDER_ID_INJECTION = os.getenv("CAO_ENABLE_SENDER_ID_INJECTION", "false").lower() == "true"
|
|
26
|
+
|
|
27
|
+
# Create MCP server
|
|
28
|
+
mcp = FastMCP(
|
|
29
|
+
"cao-mcp-server",
|
|
30
|
+
instructions="""
|
|
31
|
+
# CLI Agent Orchestrator MCP Server
|
|
32
|
+
|
|
33
|
+
This server provides tools to facilitate terminal delegation within CLI Agent Orchestrator sessions.
|
|
34
|
+
|
|
35
|
+
## Best Practices
|
|
36
|
+
|
|
37
|
+
- Use specific agent profiles and providers
|
|
38
|
+
- Provide clear and concise messages
|
|
39
|
+
- Ensure you're running within a CAO terminal (CAO_TERMINAL_ID must be set)
|
|
40
|
+
""",
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
LOAD_SKILL_TOOL_DESCRIPTION = """Retrieve the full Markdown body of an available skill from cao-server.
|
|
44
|
+
|
|
45
|
+
Use this tool when your prompt lists a CAO skill and you need its full instructions at runtime.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
name: Name of the skill to retrieve
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
The skill content on success, or a dict with success=False and an error message on failure
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _resolve_child_allowed_tools(
|
|
56
|
+
parent_allowed_tools: Optional[list], child_profile_name: str
|
|
57
|
+
) -> Optional[str]:
|
|
58
|
+
"""Resolve allowed_tools for a child terminal via intersection.
|
|
59
|
+
|
|
60
|
+
The child gets at most the union of: what the parent allows + what the
|
|
61
|
+
child profile specifies. If the parent is unrestricted ("*"), the child
|
|
62
|
+
profile's allowedTools are used as-is.
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
Comma-separated string of allowed tools, or None for unrestricted.
|
|
66
|
+
"""
|
|
67
|
+
from cli_agent_orchestrator.utils.agent_profiles import load_agent_profile
|
|
68
|
+
from cli_agent_orchestrator.utils.tool_mapping import resolve_allowed_tools
|
|
69
|
+
|
|
70
|
+
try:
|
|
71
|
+
child_profile = load_agent_profile(child_profile_name)
|
|
72
|
+
mcp_server_names = (
|
|
73
|
+
list(child_profile.mcpServers.keys()) if child_profile.mcpServers else None
|
|
74
|
+
)
|
|
75
|
+
child_allowed = resolve_allowed_tools(
|
|
76
|
+
child_profile.allowedTools, child_profile.role, mcp_server_names
|
|
77
|
+
)
|
|
78
|
+
except FileNotFoundError:
|
|
79
|
+
child_allowed = None
|
|
80
|
+
|
|
81
|
+
# If parent is unrestricted or has no restrictions, use child's tools
|
|
82
|
+
if parent_allowed_tools is None or "*" in parent_allowed_tools:
|
|
83
|
+
if child_allowed:
|
|
84
|
+
return ",".join(child_allowed)
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
# If child has no opinion (None), inherit parent's restrictions
|
|
88
|
+
if child_allowed is None:
|
|
89
|
+
return ",".join(parent_allowed_tools)
|
|
90
|
+
|
|
91
|
+
# If child explicitly requests unrestricted ("*"), honor it
|
|
92
|
+
if "*" in child_allowed:
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
# Both have restrictions: child gets its own profile tools
|
|
96
|
+
# (the child profile defines what it needs; parent's restrictions
|
|
97
|
+
# are enforced by the parent not delegating unauthorized work)
|
|
98
|
+
return ",".join(child_allowed)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _create_terminal(
|
|
102
|
+
agent_profile: str, working_directory: Optional[str] = None
|
|
103
|
+
) -> Tuple[str, str]:
|
|
104
|
+
"""Create a new terminal with the specified agent profile.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
agent_profile: Agent profile for the terminal
|
|
108
|
+
working_directory: Optional working directory for the terminal
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
Tuple of (terminal_id, provider)
|
|
112
|
+
|
|
113
|
+
Raises:
|
|
114
|
+
Exception: If terminal creation fails
|
|
115
|
+
"""
|
|
116
|
+
provider = DEFAULT_PROVIDER
|
|
117
|
+
parent_allowed_tools = None
|
|
118
|
+
|
|
119
|
+
# Get current terminal ID from environment
|
|
120
|
+
current_terminal_id = os.environ.get("CAO_TERMINAL_ID")
|
|
121
|
+
if current_terminal_id:
|
|
122
|
+
# Get terminal metadata via API
|
|
123
|
+
response = requests.get(f"{API_BASE_URL}/terminals/{current_terminal_id}")
|
|
124
|
+
response.raise_for_status()
|
|
125
|
+
terminal_metadata = response.json()
|
|
126
|
+
|
|
127
|
+
provider = terminal_metadata["provider"]
|
|
128
|
+
session_name = terminal_metadata["session_name"]
|
|
129
|
+
parent_allowed_tools = terminal_metadata.get("allowed_tools")
|
|
130
|
+
|
|
131
|
+
# If no working_directory specified, get conductor's current directory
|
|
132
|
+
if working_directory is None:
|
|
133
|
+
try:
|
|
134
|
+
response = requests.get(
|
|
135
|
+
f"{API_BASE_URL}/terminals/{current_terminal_id}/working-directory"
|
|
136
|
+
)
|
|
137
|
+
if response.status_code == 200:
|
|
138
|
+
working_directory = response.json().get("working_directory")
|
|
139
|
+
logger.info(f"Inherited working directory from conductor: {working_directory}")
|
|
140
|
+
else:
|
|
141
|
+
logger.warning(
|
|
142
|
+
f"Failed to get conductor's working directory (status {response.status_code}), "
|
|
143
|
+
"will use server default"
|
|
144
|
+
)
|
|
145
|
+
except Exception as e:
|
|
146
|
+
logger.warning(
|
|
147
|
+
f"Error fetching conductor's working directory: {e}, will use server default"
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
# Resolve child's allowed_tools via inheritance
|
|
151
|
+
child_allowed_tools = _resolve_child_allowed_tools(parent_allowed_tools, agent_profile)
|
|
152
|
+
|
|
153
|
+
# Create new terminal in existing session - always pass working_directory
|
|
154
|
+
params = {"provider": provider, "agent_profile": agent_profile}
|
|
155
|
+
if working_directory:
|
|
156
|
+
params["working_directory"] = working_directory
|
|
157
|
+
if child_allowed_tools:
|
|
158
|
+
params["allowed_tools"] = child_allowed_tools
|
|
159
|
+
|
|
160
|
+
response = requests.post(f"{API_BASE_URL}/sessions/{session_name}/terminals", params=params)
|
|
161
|
+
response.raise_for_status()
|
|
162
|
+
terminal = response.json()
|
|
163
|
+
else:
|
|
164
|
+
# Create new session with terminal
|
|
165
|
+
session_name = generate_session_name()
|
|
166
|
+
params = {
|
|
167
|
+
"provider": provider,
|
|
168
|
+
"agent_profile": agent_profile,
|
|
169
|
+
"session_name": session_name,
|
|
170
|
+
}
|
|
171
|
+
if working_directory:
|
|
172
|
+
params["working_directory"] = working_directory
|
|
173
|
+
|
|
174
|
+
response = requests.post(f"{API_BASE_URL}/sessions", params=params)
|
|
175
|
+
response.raise_for_status()
|
|
176
|
+
terminal = response.json()
|
|
177
|
+
|
|
178
|
+
return terminal["id"], provider
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _send_direct_input(
|
|
182
|
+
terminal_id: str, message: str, orchestration_type: OrchestrationType
|
|
183
|
+
) -> None:
|
|
184
|
+
"""Send input directly to a terminal (bypasses inbox).
|
|
185
|
+
|
|
186
|
+
Args:
|
|
187
|
+
terminal_id: Terminal ID
|
|
188
|
+
message: Message to send
|
|
189
|
+
orchestration_type: Orchestration mode for plugin event emission
|
|
190
|
+
|
|
191
|
+
Raises:
|
|
192
|
+
Exception: If sending fails
|
|
193
|
+
"""
|
|
194
|
+
response = requests.post(
|
|
195
|
+
f"{API_BASE_URL}/terminals/{terminal_id}/input",
|
|
196
|
+
params={
|
|
197
|
+
"message": message,
|
|
198
|
+
"sender_id": os.environ.get("CAO_TERMINAL_ID", "supervisor"),
|
|
199
|
+
"orchestration_type": orchestration_type,
|
|
200
|
+
},
|
|
201
|
+
)
|
|
202
|
+
response.raise_for_status()
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _send_direct_input_handoff(terminal_id: str, provider: str, message: str) -> None:
|
|
206
|
+
"""Send handoff payload to an agent, prepending orchestrator instructions if needed."""
|
|
207
|
+
# For Codex provider: prepend handoff context so the worker agent knows
|
|
208
|
+
# this is a blocking handoff and should simply output results rather than
|
|
209
|
+
# attempting to call send_message back to the supervisor.
|
|
210
|
+
if provider == "codex":
|
|
211
|
+
supervisor_id = os.environ.get("CAO_TERMINAL_ID", "unknown")
|
|
212
|
+
handoff_message = (
|
|
213
|
+
f"[CAO Handoff] Supervisor terminal ID: {supervisor_id}. "
|
|
214
|
+
"This is a blocking handoff — the orchestrator will automatically "
|
|
215
|
+
"capture your response when you finish. Complete the task and output "
|
|
216
|
+
"your results directly. Do NOT use send_message to notify the supervisor "
|
|
217
|
+
"unless explicitly needed — just do the work and present your deliverables.\n\n"
|
|
218
|
+
f"{message}"
|
|
219
|
+
)
|
|
220
|
+
else:
|
|
221
|
+
handoff_message = message
|
|
222
|
+
|
|
223
|
+
_send_direct_input(terminal_id, handoff_message, OrchestrationType.HANDOFF)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _send_direct_input_assign(terminal_id: str, message: str) -> None:
|
|
227
|
+
"""Send assign payload to a worker agent, appending callback instructions."""
|
|
228
|
+
# Auto-inject sender terminal ID suffix when enabled
|
|
229
|
+
if ENABLE_SENDER_ID_INJECTION:
|
|
230
|
+
sender_id = os.environ.get("CAO_TERMINAL_ID", "unknown")
|
|
231
|
+
message += (
|
|
232
|
+
f"\n\n[Assigned by terminal {sender_id}. "
|
|
233
|
+
f"When done, send results back to terminal {sender_id} using send_message]"
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
_send_direct_input(terminal_id, message, OrchestrationType.ASSIGN)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _send_to_inbox(receiver_id: str, message: str) -> Dict[str, Any]:
|
|
240
|
+
"""Send message to another terminal's inbox (queued delivery when IDLE).
|
|
241
|
+
|
|
242
|
+
Args:
|
|
243
|
+
receiver_id: Target terminal ID
|
|
244
|
+
message: Message content
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
Dict with message details
|
|
248
|
+
|
|
249
|
+
Raises:
|
|
250
|
+
ValueError: If CAO_TERMINAL_ID not set
|
|
251
|
+
Exception: If API call fails
|
|
252
|
+
"""
|
|
253
|
+
sender_id = os.getenv("CAO_TERMINAL_ID")
|
|
254
|
+
if not sender_id:
|
|
255
|
+
raise ValueError("CAO_TERMINAL_ID not set - cannot determine sender")
|
|
256
|
+
|
|
257
|
+
response = requests.post(
|
|
258
|
+
f"{API_BASE_URL}/terminals/{receiver_id}/inbox/messages",
|
|
259
|
+
params={
|
|
260
|
+
"sender_id": sender_id,
|
|
261
|
+
"message": message,
|
|
262
|
+
},
|
|
263
|
+
)
|
|
264
|
+
response.raise_for_status()
|
|
265
|
+
return response.json()
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _extract_error_detail(response: requests.Response, fallback: str) -> str:
|
|
269
|
+
"""Extract a human-readable error detail from an API response."""
|
|
270
|
+
try:
|
|
271
|
+
payload = response.json()
|
|
272
|
+
except ValueError:
|
|
273
|
+
return fallback
|
|
274
|
+
|
|
275
|
+
detail = payload.get("detail")
|
|
276
|
+
if isinstance(detail, str) and detail:
|
|
277
|
+
return detail
|
|
278
|
+
return fallback
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _load_skill_impl(name: str) -> Union[str, Dict[str, Any]]:
|
|
282
|
+
"""Fetch a skill body from cao-server and return content or a structured error."""
|
|
283
|
+
try:
|
|
284
|
+
response = requests.get(f"{API_BASE_URL}/skills/{name}")
|
|
285
|
+
response.raise_for_status()
|
|
286
|
+
return response.json()["content"]
|
|
287
|
+
except requests.HTTPError as exc:
|
|
288
|
+
detail = str(exc)
|
|
289
|
+
if exc.response is not None:
|
|
290
|
+
detail = _extract_error_detail(exc.response, detail)
|
|
291
|
+
return {"success": False, "error": detail}
|
|
292
|
+
except requests.ConnectionError:
|
|
293
|
+
return {
|
|
294
|
+
"success": False,
|
|
295
|
+
"error": "Failed to connect to cao-server. The server may not be running.",
|
|
296
|
+
}
|
|
297
|
+
except Exception as exc:
|
|
298
|
+
return {"success": False, "error": f"Failed to retrieve skill: {str(exc)}"}
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
# Implementation functions
|
|
302
|
+
async def _handoff_impl(
|
|
303
|
+
agent_profile: str, message: str, timeout: int = 600, working_directory: Optional[str] = None
|
|
304
|
+
) -> HandoffResult:
|
|
305
|
+
"""Implementation of handoff logic."""
|
|
306
|
+
start_time = time.time()
|
|
307
|
+
|
|
308
|
+
try:
|
|
309
|
+
# Create terminal
|
|
310
|
+
terminal_id, provider = _create_terminal(agent_profile, working_directory)
|
|
311
|
+
|
|
312
|
+
# Wait for terminal to be ready (IDLE or COMPLETED) before sending
|
|
313
|
+
# the handoff message. Accept COMPLETED in addition to IDLE because
|
|
314
|
+
# providers that use an initial prompt flag process the system prompt
|
|
315
|
+
# as the first user message and produce a response, reaching COMPLETED
|
|
316
|
+
# without ever showing a bare IDLE state.
|
|
317
|
+
# Both states indicate the provider is ready to accept input.
|
|
318
|
+
#
|
|
319
|
+
# Use a generous timeout (120s) because provider initialization can be
|
|
320
|
+
# slow: shell warm-up (~5s), CLI startup with MCP server registration
|
|
321
|
+
# (~10-30s), and API authentication (~5-10s). If the provider's own
|
|
322
|
+
# initialize() timed out (60-90s), this acts as a fallback to catch
|
|
323
|
+
# cases where the CLI starts slightly after the provider timeout.
|
|
324
|
+
# Provider initialization can be slow (~15-45s depending on provider).
|
|
325
|
+
if not wait_until_terminal_status(
|
|
326
|
+
terminal_id,
|
|
327
|
+
{TerminalStatus.IDLE, TerminalStatus.COMPLETED},
|
|
328
|
+
timeout=120.0,
|
|
329
|
+
):
|
|
330
|
+
return HandoffResult(
|
|
331
|
+
success=False,
|
|
332
|
+
message=f"Terminal {terminal_id} did not reach ready status within 120 seconds",
|
|
333
|
+
output=None,
|
|
334
|
+
terminal_id=terminal_id,
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
await asyncio.sleep(2) # wait another 2s
|
|
338
|
+
|
|
339
|
+
# Send message to terminal (injects handoff instructions for codex if needed)
|
|
340
|
+
_send_direct_input_handoff(terminal_id, provider, message)
|
|
341
|
+
|
|
342
|
+
# Monitor until completion with timeout
|
|
343
|
+
if not wait_until_terminal_status(
|
|
344
|
+
terminal_id, TerminalStatus.COMPLETED, timeout=timeout, polling_interval=1.0
|
|
345
|
+
):
|
|
346
|
+
return HandoffResult(
|
|
347
|
+
success=False,
|
|
348
|
+
message=f"Handoff timed out after {timeout} seconds",
|
|
349
|
+
output=None,
|
|
350
|
+
terminal_id=terminal_id,
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
# Get the response
|
|
354
|
+
response = requests.get(
|
|
355
|
+
f"{API_BASE_URL}/terminals/{terminal_id}/output", params={"mode": "last"}
|
|
356
|
+
)
|
|
357
|
+
response.raise_for_status()
|
|
358
|
+
output_data = response.json()
|
|
359
|
+
output = output_data["output"]
|
|
360
|
+
|
|
361
|
+
# Send provider-specific exit command to cleanup terminal
|
|
362
|
+
response = requests.post(f"{API_BASE_URL}/terminals/{terminal_id}/exit")
|
|
363
|
+
response.raise_for_status()
|
|
364
|
+
|
|
365
|
+
execution_time = time.time() - start_time
|
|
366
|
+
|
|
367
|
+
return HandoffResult(
|
|
368
|
+
success=True,
|
|
369
|
+
message=f"Successfully handed off to {agent_profile} ({provider}) in {execution_time:.2f}s",
|
|
370
|
+
output=output,
|
|
371
|
+
terminal_id=terminal_id,
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
except Exception as e:
|
|
375
|
+
return HandoffResult(
|
|
376
|
+
success=False, message=f"Handoff failed: {str(e)}", output=None, terminal_id=None
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
# Conditional tool registration based on environment variable
|
|
381
|
+
if ENABLE_WORKING_DIRECTORY:
|
|
382
|
+
|
|
383
|
+
@mcp.tool()
|
|
384
|
+
async def handoff(
|
|
385
|
+
agent_profile: str = Field(
|
|
386
|
+
description='The agent profile to hand off to (e.g., "developer", "analyst")'
|
|
387
|
+
),
|
|
388
|
+
message: str = Field(description="The message/task to send to the target agent"),
|
|
389
|
+
timeout: int = Field(
|
|
390
|
+
default=600,
|
|
391
|
+
description="Maximum time to wait for the agent to complete the task (in seconds)",
|
|
392
|
+
ge=1,
|
|
393
|
+
le=3600,
|
|
394
|
+
),
|
|
395
|
+
working_directory: Optional[str] = Field(
|
|
396
|
+
default=None,
|
|
397
|
+
description='Optional working directory where the agent should execute (e.g., "/path/to/workspace/src/Package")',
|
|
398
|
+
),
|
|
399
|
+
) -> HandoffResult:
|
|
400
|
+
"""Hand off a task to another agent via CAO terminal and wait for completion.
|
|
401
|
+
|
|
402
|
+
This tool allows handing off tasks to other agents by creating a new terminal
|
|
403
|
+
in the same session. It sends the message, waits for completion, and captures the output.
|
|
404
|
+
|
|
405
|
+
## Usage
|
|
406
|
+
|
|
407
|
+
Use this tool to hand off tasks to another agent and wait for the results.
|
|
408
|
+
The tool will:
|
|
409
|
+
1. Create a new terminal with the specified agent profile and provider
|
|
410
|
+
2. Set the working directory for the terminal (defaults to supervisor's cwd)
|
|
411
|
+
3. Send the message to the terminal
|
|
412
|
+
4. Monitor until completion
|
|
413
|
+
5. Return the agent's response
|
|
414
|
+
6. Clean up the terminal with /exit
|
|
415
|
+
|
|
416
|
+
## Working Directory
|
|
417
|
+
|
|
418
|
+
- By default, agents start in the supervisor's current working directory
|
|
419
|
+
- You can specify a custom directory via working_directory parameter
|
|
420
|
+
- Directory must exist and be accessible
|
|
421
|
+
|
|
422
|
+
## Requirements
|
|
423
|
+
|
|
424
|
+
- Must be called from within a CAO terminal (CAO_TERMINAL_ID environment variable)
|
|
425
|
+
- Target session must exist and be accessible
|
|
426
|
+
- If working_directory is provided, it must exist and be accessible
|
|
427
|
+
|
|
428
|
+
Args:
|
|
429
|
+
agent_profile: The agent profile for the new terminal
|
|
430
|
+
message: The task/message to send
|
|
431
|
+
timeout: Maximum wait time in seconds
|
|
432
|
+
working_directory: Optional directory path where agent should execute
|
|
433
|
+
|
|
434
|
+
Returns:
|
|
435
|
+
HandoffResult with success status, message, and agent output
|
|
436
|
+
"""
|
|
437
|
+
return await _handoff_impl(agent_profile, message, timeout, working_directory)
|
|
438
|
+
|
|
439
|
+
else:
|
|
440
|
+
|
|
441
|
+
@mcp.tool()
|
|
442
|
+
async def handoff(
|
|
443
|
+
agent_profile: str = Field(
|
|
444
|
+
description='The agent profile to hand off to (e.g., "developer", "analyst")'
|
|
445
|
+
),
|
|
446
|
+
message: str = Field(description="The message/task to send to the target agent"),
|
|
447
|
+
timeout: int = Field(
|
|
448
|
+
default=600,
|
|
449
|
+
description="Maximum time to wait for the agent to complete the task (in seconds)",
|
|
450
|
+
ge=1,
|
|
451
|
+
le=3600,
|
|
452
|
+
),
|
|
453
|
+
) -> HandoffResult:
|
|
454
|
+
"""Hand off a task to another agent via CAO terminal and wait for completion.
|
|
455
|
+
|
|
456
|
+
This tool allows handing off tasks to other agents by creating a new terminal
|
|
457
|
+
in the same session. It sends the message, waits for completion, and captures the output.
|
|
458
|
+
|
|
459
|
+
## Usage
|
|
460
|
+
|
|
461
|
+
Use this tool to hand off tasks to another agent and wait for the results.
|
|
462
|
+
The tool will:
|
|
463
|
+
1. Create a new terminal with the specified agent profile and provider
|
|
464
|
+
2. Send the message to the terminal (starts in supervisor's current directory)
|
|
465
|
+
3. Monitor until completion
|
|
466
|
+
4. Return the agent's response
|
|
467
|
+
5. Clean up the terminal with /exit
|
|
468
|
+
|
|
469
|
+
## Requirements
|
|
470
|
+
|
|
471
|
+
- Must be called from within a CAO terminal (CAO_TERMINAL_ID environment variable)
|
|
472
|
+
- Target session must exist and be accessible
|
|
473
|
+
|
|
474
|
+
Args:
|
|
475
|
+
agent_profile: The agent profile for the new terminal
|
|
476
|
+
message: The task/message to send
|
|
477
|
+
timeout: Maximum wait time in seconds
|
|
478
|
+
|
|
479
|
+
Returns:
|
|
480
|
+
HandoffResult with success status, message, and agent output
|
|
481
|
+
"""
|
|
482
|
+
return await _handoff_impl(agent_profile, message, timeout, None)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
# Implementation function for assign
|
|
486
|
+
def _assign_impl(
|
|
487
|
+
agent_profile: str, message: str, working_directory: Optional[str] = None
|
|
488
|
+
) -> Dict[str, Any]:
|
|
489
|
+
"""Implementation of assign logic."""
|
|
490
|
+
try:
|
|
491
|
+
# Create terminal
|
|
492
|
+
terminal_id, _ = _create_terminal(agent_profile, working_directory)
|
|
493
|
+
|
|
494
|
+
# Guard: wait for the terminal to be genuinely ready before sending
|
|
495
|
+
# the task message. create_terminal() calls provider.initialize() which
|
|
496
|
+
# already waits 30 s for IDLE, but that check can return a false-positive
|
|
497
|
+
# on the pre-existing shell ❯ prompt (zsh/bash) before claude starts.
|
|
498
|
+
# A secondary API-level wait (same as handoff uses) catches that race.
|
|
499
|
+
if not wait_until_terminal_status(
|
|
500
|
+
terminal_id,
|
|
501
|
+
{TerminalStatus.IDLE, TerminalStatus.COMPLETED},
|
|
502
|
+
timeout=60.0,
|
|
503
|
+
):
|
|
504
|
+
return {
|
|
505
|
+
"success": False,
|
|
506
|
+
"terminal_id": terminal_id,
|
|
507
|
+
"message": f"Terminal {terminal_id} did not reach ready status within 60 seconds — agent may not have started",
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
# Send message (auto-injects sender terminal ID suffix when enabled)
|
|
511
|
+
_send_direct_input_assign(terminal_id, message)
|
|
512
|
+
|
|
513
|
+
return {
|
|
514
|
+
"success": True,
|
|
515
|
+
"terminal_id": terminal_id,
|
|
516
|
+
"message": f"Task assigned to {agent_profile} (terminal: {terminal_id})",
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
except Exception as e:
|
|
520
|
+
return {"success": False, "terminal_id": None, "message": f"Assignment failed: {str(e)}"}
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _build_assign_description(enable_sender_id: bool, enable_workdir: bool) -> str:
|
|
524
|
+
"""Build the assign tool description based on feature flags."""
|
|
525
|
+
# Build tool description overview.
|
|
526
|
+
if enable_sender_id:
|
|
527
|
+
desc = """\
|
|
528
|
+
Assigns a task to another agent without blocking.
|
|
529
|
+
|
|
530
|
+
The sender's terminal ID and callback instructions will automatically be appended to the message."""
|
|
531
|
+
else:
|
|
532
|
+
desc = """\
|
|
533
|
+
Assigns a task to another agent without blocking.
|
|
534
|
+
|
|
535
|
+
In the message to the worker agent include instruction to send results back via send_message tool.
|
|
536
|
+
**IMPORTANT**: The terminal id of each agent is available in environment variable CAO_TERMINAL_ID.
|
|
537
|
+
When assigning, first find out your own CAO_TERMINAL_ID value, then include the terminal_id value in the message to the worker agent to allow callback.
|
|
538
|
+
Example message: "Analyze the logs. When done, send results back to terminal ee3f93b3 using send_message tool.\""""
|
|
539
|
+
|
|
540
|
+
if enable_workdir:
|
|
541
|
+
desc += """
|
|
542
|
+
|
|
543
|
+
## Working Directory
|
|
544
|
+
|
|
545
|
+
- By default, agents start in the supervisor's current working directory
|
|
546
|
+
- You can specify a custom directory via working_directory parameter
|
|
547
|
+
- Directory must exist and be accessible"""
|
|
548
|
+
|
|
549
|
+
desc += """
|
|
550
|
+
|
|
551
|
+
Args:
|
|
552
|
+
agent_profile: Agent profile for the worker terminal
|
|
553
|
+
message: Task message (include callback instructions)"""
|
|
554
|
+
|
|
555
|
+
if enable_workdir:
|
|
556
|
+
desc += """
|
|
557
|
+
working_directory: Optional working directory where the agent should execute"""
|
|
558
|
+
|
|
559
|
+
desc += """
|
|
560
|
+
|
|
561
|
+
Returns:
|
|
562
|
+
Dict with success status, worker terminal_id, and message"""
|
|
563
|
+
|
|
564
|
+
return desc
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
_assign_description = _build_assign_description(
|
|
568
|
+
ENABLE_SENDER_ID_INJECTION, ENABLE_WORKING_DIRECTORY
|
|
569
|
+
)
|
|
570
|
+
_assign_message_field_desc = (
|
|
571
|
+
"The task message to send to the worker agent."
|
|
572
|
+
if ENABLE_SENDER_ID_INJECTION
|
|
573
|
+
else "The task message to send. Include callback instructions for the worker to send results back."
|
|
574
|
+
)
|
|
575
|
+
|
|
576
|
+
if ENABLE_WORKING_DIRECTORY:
|
|
577
|
+
|
|
578
|
+
@mcp.tool(description=_assign_description)
|
|
579
|
+
async def assign(
|
|
580
|
+
agent_profile: str = Field(
|
|
581
|
+
description='The agent profile for the worker agent (e.g., "developer", "analyst")'
|
|
582
|
+
),
|
|
583
|
+
message: str = Field(description=_assign_message_field_desc),
|
|
584
|
+
working_directory: Optional[str] = Field(
|
|
585
|
+
default=None, description="Optional working directory where the agent should execute"
|
|
586
|
+
),
|
|
587
|
+
) -> Dict[str, Any]:
|
|
588
|
+
return _assign_impl(agent_profile, message, working_directory)
|
|
589
|
+
|
|
590
|
+
else:
|
|
591
|
+
|
|
592
|
+
@mcp.tool(description=_assign_description)
|
|
593
|
+
async def assign(
|
|
594
|
+
agent_profile: str = Field(
|
|
595
|
+
description='The agent profile for the worker agent (e.g., "developer", "analyst")'
|
|
596
|
+
),
|
|
597
|
+
message: str = Field(description=_assign_message_field_desc),
|
|
598
|
+
) -> Dict[str, Any]:
|
|
599
|
+
return _assign_impl(agent_profile, message, None)
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
# Implementation function for send_message
|
|
603
|
+
def _send_message_impl(receiver_id: str, message: str) -> Dict[str, Any]:
|
|
604
|
+
"""Implementation of send_message logic."""
|
|
605
|
+
try:
|
|
606
|
+
# Auto-inject sender terminal ID suffix when enabled
|
|
607
|
+
if ENABLE_SENDER_ID_INJECTION:
|
|
608
|
+
sender_id = os.environ.get("CAO_TERMINAL_ID", "unknown")
|
|
609
|
+
message += (
|
|
610
|
+
f"\n\n[Message from terminal {sender_id}. "
|
|
611
|
+
"Use send_message MCP tool for any follow-up work.]"
|
|
612
|
+
)
|
|
613
|
+
|
|
614
|
+
return _send_to_inbox(receiver_id, message)
|
|
615
|
+
except Exception as e:
|
|
616
|
+
return {"success": False, "error": str(e)}
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
@mcp.tool()
|
|
620
|
+
async def send_message(
|
|
621
|
+
receiver_id: str = Field(description="Target terminal ID to send message to"),
|
|
622
|
+
message: str = Field(description="Message content to send"),
|
|
623
|
+
) -> Dict[str, Any]:
|
|
624
|
+
"""Send a message to another terminal's inbox.
|
|
625
|
+
|
|
626
|
+
The message will be delivered when the destination terminal is IDLE.
|
|
627
|
+
Messages are delivered in order (oldest first).
|
|
628
|
+
|
|
629
|
+
Args:
|
|
630
|
+
receiver_id: Terminal ID of the receiver
|
|
631
|
+
message: Message content to send
|
|
632
|
+
|
|
633
|
+
Returns:
|
|
634
|
+
Dict with success status and message details
|
|
635
|
+
"""
|
|
636
|
+
return _send_message_impl(receiver_id, message)
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
@mcp.tool(description=LOAD_SKILL_TOOL_DESCRIPTION)
|
|
640
|
+
async def load_skill(
|
|
641
|
+
name: str = Field(description="Name of the skill to retrieve"),
|
|
642
|
+
) -> Any:
|
|
643
|
+
"""Retrieve skill content from cao-server."""
|
|
644
|
+
return _load_skill_impl(name)
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def main():
|
|
648
|
+
"""Main entry point for the MCP server."""
|
|
649
|
+
mcp.run()
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
if __name__ == "__main__":
|
|
653
|
+
main()
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""MCP server utilities."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from cli_agent_orchestrator.clients.database import SessionLocal, TerminalModel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def get_terminal_record(terminal_id: str) -> Optional[TerminalModel]:
|
|
9
|
+
"""Get full terminal record for a given terminal_id from database."""
|
|
10
|
+
db = SessionLocal()
|
|
11
|
+
try:
|
|
12
|
+
terminal_record = db.query(TerminalModel).filter(TerminalModel.id == terminal_id).first()
|
|
13
|
+
return terminal_record
|
|
14
|
+
finally:
|
|
15
|
+
db.close()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|