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,947 @@
|
|
|
1
|
+
"""Single FastAPI entry point for all HTTP routes."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import fcntl
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import pty
|
|
9
|
+
import signal
|
|
10
|
+
import struct
|
|
11
|
+
import subprocess
|
|
12
|
+
import termios
|
|
13
|
+
from contextlib import asynccontextmanager
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Annotated, Dict, List, Optional, cast
|
|
16
|
+
|
|
17
|
+
from fastapi import FastAPI, HTTPException, Query, Request, WebSocket, WebSocketDisconnect, status
|
|
18
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
19
|
+
from fastapi.middleware.trustedhost import TrustedHostMiddleware
|
|
20
|
+
from pydantic import BaseModel, Field, field_validator
|
|
21
|
+
from watchdog.observers.polling import PollingObserver
|
|
22
|
+
|
|
23
|
+
from cli_agent_orchestrator.clients.database import (
|
|
24
|
+
create_inbox_message,
|
|
25
|
+
get_inbox_messages,
|
|
26
|
+
get_terminal_metadata,
|
|
27
|
+
init_db,
|
|
28
|
+
)
|
|
29
|
+
from cli_agent_orchestrator.constants import (
|
|
30
|
+
ALLOWED_HOSTS,
|
|
31
|
+
CAO_HOME_DIR,
|
|
32
|
+
CORS_ORIGINS,
|
|
33
|
+
INBOX_POLLING_INTERVAL,
|
|
34
|
+
SERVER_HOST,
|
|
35
|
+
SERVER_PORT,
|
|
36
|
+
SERVER_VERSION,
|
|
37
|
+
TERMINAL_LOG_DIR,
|
|
38
|
+
)
|
|
39
|
+
from cli_agent_orchestrator.models.flow import Flow
|
|
40
|
+
from cli_agent_orchestrator.models.inbox import MessageStatus, OrchestrationType
|
|
41
|
+
from cli_agent_orchestrator.models.terminal import Terminal, TerminalId
|
|
42
|
+
from cli_agent_orchestrator.plugins import PluginRegistry
|
|
43
|
+
from cli_agent_orchestrator.providers.manager import provider_manager
|
|
44
|
+
from cli_agent_orchestrator.services import (
|
|
45
|
+
flow_service,
|
|
46
|
+
inbox_service,
|
|
47
|
+
session_service,
|
|
48
|
+
terminal_service,
|
|
49
|
+
)
|
|
50
|
+
from cli_agent_orchestrator.services.cleanup_service import cleanup_old_data
|
|
51
|
+
from cli_agent_orchestrator.services.inbox_service import LogFileHandler
|
|
52
|
+
from cli_agent_orchestrator.services.terminal_service import OutputMode
|
|
53
|
+
from cli_agent_orchestrator.utils.agent_profiles import resolve_provider
|
|
54
|
+
from cli_agent_orchestrator.utils.logging import setup_logging
|
|
55
|
+
from cli_agent_orchestrator.utils.skills import (
|
|
56
|
+
SkillNameError,
|
|
57
|
+
load_skill_content,
|
|
58
|
+
validate_skill_name,
|
|
59
|
+
)
|
|
60
|
+
from cli_agent_orchestrator.utils.terminal import generate_session_name
|
|
61
|
+
|
|
62
|
+
logger = logging.getLogger(__name__)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
async def flow_daemon():
|
|
66
|
+
"""Background task to check and execute flows."""
|
|
67
|
+
logger.info("Flow daemon started")
|
|
68
|
+
while True:
|
|
69
|
+
try:
|
|
70
|
+
flows = flow_service.get_flows_to_run()
|
|
71
|
+
for flow in flows:
|
|
72
|
+
try:
|
|
73
|
+
executed = flow_service.execute_flow(flow.name)
|
|
74
|
+
if executed:
|
|
75
|
+
logger.info(f"Flow '{flow.name}' executed successfully")
|
|
76
|
+
else:
|
|
77
|
+
logger.info(f"Flow '{flow.name}' skipped (execute=false)")
|
|
78
|
+
except Exception as e:
|
|
79
|
+
logger.error(f"Flow '{flow.name}' failed: {e}")
|
|
80
|
+
except Exception as e:
|
|
81
|
+
logger.error(f"Flow daemon error: {e}")
|
|
82
|
+
|
|
83
|
+
await asyncio.sleep(60)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# Response Models
|
|
87
|
+
class TerminalOutputResponse(BaseModel):
|
|
88
|
+
output: str
|
|
89
|
+
mode: str
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class SkillContentResponse(BaseModel):
|
|
93
|
+
"""Response model for a skill content lookup."""
|
|
94
|
+
|
|
95
|
+
name: str
|
|
96
|
+
content: str
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class WorkingDirectoryResponse(BaseModel):
|
|
100
|
+
"""Response model for terminal working directory."""
|
|
101
|
+
|
|
102
|
+
working_directory: Optional[str] = Field(
|
|
103
|
+
description="Current working directory of the terminal, or None if unavailable"
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class CreateFlowRequest(BaseModel):
|
|
108
|
+
"""Request model for creating a flow."""
|
|
109
|
+
|
|
110
|
+
name: str
|
|
111
|
+
schedule: str
|
|
112
|
+
agent_profile: str
|
|
113
|
+
provider: str = "kiro_cli"
|
|
114
|
+
prompt_template: str
|
|
115
|
+
|
|
116
|
+
@field_validator("name")
|
|
117
|
+
@classmethod
|
|
118
|
+
def validate_name(cls, v: str) -> str:
|
|
119
|
+
"""Prevent path traversal — flow name becomes a filename."""
|
|
120
|
+
if "/" in v or "\\" in v or ".." in v:
|
|
121
|
+
raise ValueError("Flow name must not contain '/', '\\', or '..'")
|
|
122
|
+
return v
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@asynccontextmanager
|
|
126
|
+
async def lifespan(app: FastAPI):
|
|
127
|
+
"""Application lifespan events."""
|
|
128
|
+
logger.info("Starting CLI Agent Orchestrator server...")
|
|
129
|
+
setup_logging()
|
|
130
|
+
init_db()
|
|
131
|
+
registry = PluginRegistry()
|
|
132
|
+
await registry.load()
|
|
133
|
+
app.state.plugin_registry = registry
|
|
134
|
+
|
|
135
|
+
# Run cleanup in background
|
|
136
|
+
asyncio.create_task(asyncio.to_thread(cleanup_old_data))
|
|
137
|
+
|
|
138
|
+
# Start flow daemon as background task
|
|
139
|
+
daemon_task = asyncio.create_task(flow_daemon())
|
|
140
|
+
|
|
141
|
+
# Start inbox watcher
|
|
142
|
+
inbox_observer = PollingObserver(timeout=INBOX_POLLING_INTERVAL)
|
|
143
|
+
inbox_observer.schedule(LogFileHandler(registry), str(TERMINAL_LOG_DIR), recursive=False)
|
|
144
|
+
inbox_observer.start()
|
|
145
|
+
logger.info("Inbox watcher started (PollingObserver)")
|
|
146
|
+
|
|
147
|
+
yield
|
|
148
|
+
|
|
149
|
+
# Stop inbox observer
|
|
150
|
+
inbox_observer.stop()
|
|
151
|
+
inbox_observer.join()
|
|
152
|
+
logger.info("Inbox watcher stopped")
|
|
153
|
+
|
|
154
|
+
# Cancel daemon on shutdown
|
|
155
|
+
daemon_task.cancel()
|
|
156
|
+
try:
|
|
157
|
+
await daemon_task
|
|
158
|
+
except asyncio.CancelledError:
|
|
159
|
+
pass
|
|
160
|
+
|
|
161
|
+
await registry.teardown()
|
|
162
|
+
logger.info("Shutting down CLI Agent Orchestrator server...")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def get_plugin_registry(request: Request) -> PluginRegistry:
|
|
166
|
+
"""Return the plugin registry stored on the FastAPI application state."""
|
|
167
|
+
|
|
168
|
+
return cast(PluginRegistry, request.app.state.plugin_registry)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
app = FastAPI(
|
|
172
|
+
title="CLI Agent Orchestrator",
|
|
173
|
+
description="Simplified CLI Agent Orchestrator API",
|
|
174
|
+
version=SERVER_VERSION,
|
|
175
|
+
lifespan=lifespan,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
# Security: DNS Rebinding Protection
|
|
179
|
+
# Validate Host header to prevent DNS rebinding attacks (CVE mitigation)
|
|
180
|
+
# Only allow requests with localhost Host headers
|
|
181
|
+
app.add_middleware(
|
|
182
|
+
TrustedHostMiddleware,
|
|
183
|
+
allowed_hosts=ALLOWED_HOSTS,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
app.add_middleware(
|
|
187
|
+
CORSMiddleware,
|
|
188
|
+
allow_origins=CORS_ORIGINS,
|
|
189
|
+
allow_credentials=True,
|
|
190
|
+
allow_methods=["*"],
|
|
191
|
+
allow_headers=["*"],
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@app.get("/health")
|
|
196
|
+
async def health_check():
|
|
197
|
+
return {"status": "ok", "service": "cli-agent-orchestrator"}
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@app.get("/agents/profiles")
|
|
201
|
+
async def list_agent_profiles_endpoint() -> List[Dict]:
|
|
202
|
+
"""List all available agent profiles from all configured directories."""
|
|
203
|
+
try:
|
|
204
|
+
from cli_agent_orchestrator.utils.agent_profiles import list_agent_profiles
|
|
205
|
+
|
|
206
|
+
return list_agent_profiles()
|
|
207
|
+
except Exception as e:
|
|
208
|
+
raise HTTPException(
|
|
209
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
210
|
+
detail=f"Failed to list agent profiles: {str(e)}",
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@app.get("/agents/providers")
|
|
215
|
+
async def list_providers_endpoint() -> List[Dict]:
|
|
216
|
+
"""List available providers with installation status."""
|
|
217
|
+
import shutil
|
|
218
|
+
|
|
219
|
+
provider_binaries = {
|
|
220
|
+
"kiro_cli": "kiro-cli",
|
|
221
|
+
"claude_code": "claude",
|
|
222
|
+
"q_cli": "q",
|
|
223
|
+
"codex": "codex",
|
|
224
|
+
"gemini_cli": "gemini",
|
|
225
|
+
"kimi_cli": "kimi",
|
|
226
|
+
"copilot_cli": "copilot",
|
|
227
|
+
}
|
|
228
|
+
result = []
|
|
229
|
+
for provider, binary in provider_binaries.items():
|
|
230
|
+
installed = shutil.which(binary) is not None
|
|
231
|
+
result.append({"name": provider, "binary": binary, "installed": installed})
|
|
232
|
+
return result
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@app.get("/settings/agent-dirs")
|
|
236
|
+
async def get_agent_dirs_endpoint() -> Dict:
|
|
237
|
+
"""Get configured agent directories per provider."""
|
|
238
|
+
from cli_agent_orchestrator.services.settings_service import (
|
|
239
|
+
get_agent_dirs,
|
|
240
|
+
get_extra_agent_dirs,
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
return {"agent_dirs": get_agent_dirs(), "extra_dirs": get_extra_agent_dirs()}
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class AgentDirsUpdate(BaseModel):
|
|
247
|
+
agent_dirs: Optional[Dict[str, str]] = None
|
|
248
|
+
extra_dirs: Optional[List[str]] = None
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
@app.post("/settings/agent-dirs")
|
|
252
|
+
async def set_agent_dirs_endpoint(body: AgentDirsUpdate) -> Dict:
|
|
253
|
+
"""Update agent directories per provider."""
|
|
254
|
+
from cli_agent_orchestrator.services.settings_service import (
|
|
255
|
+
get_extra_agent_dirs,
|
|
256
|
+
set_agent_dirs,
|
|
257
|
+
set_extra_agent_dirs,
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
result_dirs = {}
|
|
261
|
+
result_extra = []
|
|
262
|
+
if body.agent_dirs:
|
|
263
|
+
result_dirs = set_agent_dirs(body.agent_dirs)
|
|
264
|
+
if body.extra_dirs is not None:
|
|
265
|
+
result_extra = set_extra_agent_dirs(body.extra_dirs)
|
|
266
|
+
return {
|
|
267
|
+
"agent_dirs": result_dirs or {},
|
|
268
|
+
"extra_dirs": result_extra or get_extra_agent_dirs(),
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
@app.get("/skills/{name}", response_model=SkillContentResponse)
|
|
273
|
+
async def get_skill_content(name: str) -> SkillContentResponse:
|
|
274
|
+
"""Return the full Markdown body for an installed skill."""
|
|
275
|
+
try:
|
|
276
|
+
skill_name = validate_skill_name(name)
|
|
277
|
+
content = load_skill_content(skill_name)
|
|
278
|
+
return SkillContentResponse(name=name, content=content)
|
|
279
|
+
except SkillNameError:
|
|
280
|
+
raise HTTPException(
|
|
281
|
+
status_code=status.HTTP_400_BAD_REQUEST,
|
|
282
|
+
detail=f"Invalid skill name: {name}",
|
|
283
|
+
)
|
|
284
|
+
except ValueError as e:
|
|
285
|
+
raise HTTPException(
|
|
286
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
287
|
+
detail=f"Failed to load skill: {str(e)}",
|
|
288
|
+
)
|
|
289
|
+
except FileNotFoundError:
|
|
290
|
+
raise HTTPException(
|
|
291
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
292
|
+
detail=f"Skill not found: {name}",
|
|
293
|
+
)
|
|
294
|
+
except Exception as e:
|
|
295
|
+
raise HTTPException(
|
|
296
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
297
|
+
detail=f"Failed to load skill: {str(e)}",
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
@app.post("/sessions", response_model=Terminal, status_code=status.HTTP_201_CREATED)
|
|
302
|
+
async def create_session(
|
|
303
|
+
request: Request,
|
|
304
|
+
provider: str,
|
|
305
|
+
agent_profile: str,
|
|
306
|
+
session_name: Optional[str] = None,
|
|
307
|
+
working_directory: Optional[str] = None,
|
|
308
|
+
allowed_tools: Optional[str] = None,
|
|
309
|
+
) -> Terminal:
|
|
310
|
+
"""Create a new session with exactly one terminal."""
|
|
311
|
+
try:
|
|
312
|
+
# Parse comma-separated allowed_tools string into list
|
|
313
|
+
allowed_tools_list = allowed_tools.split(",") if allowed_tools else None
|
|
314
|
+
|
|
315
|
+
result = session_service.create_session(
|
|
316
|
+
provider=provider,
|
|
317
|
+
agent_profile=agent_profile,
|
|
318
|
+
session_name=session_name,
|
|
319
|
+
working_directory=working_directory,
|
|
320
|
+
allowed_tools=allowed_tools_list,
|
|
321
|
+
registry=get_plugin_registry(request),
|
|
322
|
+
)
|
|
323
|
+
return result
|
|
324
|
+
|
|
325
|
+
except ValueError as e:
|
|
326
|
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
|
327
|
+
except Exception as e:
|
|
328
|
+
raise HTTPException(
|
|
329
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
330
|
+
detail=f"Failed to create session: {str(e)}",
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
@app.get("/sessions")
|
|
335
|
+
async def list_sessions() -> List[Dict]:
|
|
336
|
+
try:
|
|
337
|
+
return session_service.list_sessions()
|
|
338
|
+
except Exception as e:
|
|
339
|
+
raise HTTPException(
|
|
340
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
341
|
+
detail=f"Failed to list sessions: {str(e)}",
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
@app.get("/sessions/{session_name}")
|
|
346
|
+
async def get_session(session_name: str) -> Dict:
|
|
347
|
+
try:
|
|
348
|
+
return session_service.get_session(session_name)
|
|
349
|
+
except ValueError as e:
|
|
350
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
351
|
+
except Exception as e:
|
|
352
|
+
raise HTTPException(
|
|
353
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
354
|
+
detail=f"Failed to get session: {str(e)}",
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
@app.delete("/sessions/{session_name}")
|
|
359
|
+
async def delete_session(request: Request, session_name: str) -> Dict:
|
|
360
|
+
try:
|
|
361
|
+
result = session_service.delete_session(session_name, registry=get_plugin_registry(request))
|
|
362
|
+
return {"success": True, **result}
|
|
363
|
+
except ValueError as e:
|
|
364
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
365
|
+
except Exception as e:
|
|
366
|
+
raise HTTPException(
|
|
367
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
368
|
+
detail=f"Failed to delete session: {str(e)}",
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
@app.post(
|
|
373
|
+
"/sessions/{session_name}/terminals",
|
|
374
|
+
response_model=Terminal,
|
|
375
|
+
status_code=status.HTTP_201_CREATED,
|
|
376
|
+
)
|
|
377
|
+
async def create_terminal_in_session(
|
|
378
|
+
request: Request,
|
|
379
|
+
session_name: str,
|
|
380
|
+
provider: str,
|
|
381
|
+
agent_profile: str,
|
|
382
|
+
working_directory: Optional[str] = None,
|
|
383
|
+
allowed_tools: Optional[str] = None,
|
|
384
|
+
) -> Terminal:
|
|
385
|
+
"""Create additional terminal in existing session."""
|
|
386
|
+
try:
|
|
387
|
+
resolved_provider = resolve_provider(agent_profile, fallback_provider=provider)
|
|
388
|
+
|
|
389
|
+
# Parse comma-separated allowed_tools string into list
|
|
390
|
+
allowed_tools_list = allowed_tools.split(",") if allowed_tools else None
|
|
391
|
+
|
|
392
|
+
result = terminal_service.create_terminal(
|
|
393
|
+
provider=resolved_provider,
|
|
394
|
+
agent_profile=agent_profile,
|
|
395
|
+
session_name=session_name,
|
|
396
|
+
new_session=False,
|
|
397
|
+
working_directory=working_directory,
|
|
398
|
+
allowed_tools=allowed_tools_list,
|
|
399
|
+
registry=get_plugin_registry(request),
|
|
400
|
+
)
|
|
401
|
+
return result
|
|
402
|
+
except ValueError as e:
|
|
403
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
404
|
+
except Exception as e:
|
|
405
|
+
raise HTTPException(
|
|
406
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
407
|
+
detail=f"Failed to create terminal: {str(e)}",
|
|
408
|
+
)
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
@app.get("/sessions/{session_name}/terminals")
|
|
412
|
+
async def list_terminals_in_session(session_name: str) -> List[Dict]:
|
|
413
|
+
"""List all terminals in a session."""
|
|
414
|
+
try:
|
|
415
|
+
from cli_agent_orchestrator.clients.database import list_terminals_by_session
|
|
416
|
+
|
|
417
|
+
return list_terminals_by_session(session_name)
|
|
418
|
+
except Exception as e:
|
|
419
|
+
raise HTTPException(
|
|
420
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
421
|
+
detail=f"Failed to list terminals: {str(e)}",
|
|
422
|
+
)
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
@app.get("/terminals/{terminal_id}", response_model=Terminal)
|
|
426
|
+
async def get_terminal(terminal_id: TerminalId) -> Terminal:
|
|
427
|
+
try:
|
|
428
|
+
terminal = terminal_service.get_terminal(terminal_id)
|
|
429
|
+
return Terminal(**terminal)
|
|
430
|
+
except ValueError as e:
|
|
431
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
432
|
+
except Exception as e:
|
|
433
|
+
raise HTTPException(
|
|
434
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
435
|
+
detail=f"Failed to get terminal: {str(e)}",
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
@app.get("/terminals/{terminal_id}/working-directory", response_model=WorkingDirectoryResponse)
|
|
440
|
+
async def get_terminal_working_directory(terminal_id: TerminalId) -> WorkingDirectoryResponse:
|
|
441
|
+
"""Get the current working directory of a terminal's pane."""
|
|
442
|
+
try:
|
|
443
|
+
working_directory = terminal_service.get_working_directory(terminal_id)
|
|
444
|
+
return WorkingDirectoryResponse(working_directory=working_directory)
|
|
445
|
+
except ValueError as e:
|
|
446
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
447
|
+
except Exception as e:
|
|
448
|
+
raise HTTPException(
|
|
449
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
450
|
+
detail=f"Failed to get working directory: {str(e)}",
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
@app.post("/terminals/{terminal_id}/input")
|
|
455
|
+
async def send_terminal_input(
|
|
456
|
+
request: Request,
|
|
457
|
+
terminal_id: TerminalId,
|
|
458
|
+
message: str,
|
|
459
|
+
sender_id: Optional[str] = None,
|
|
460
|
+
orchestration_type: Optional[OrchestrationType] = None,
|
|
461
|
+
) -> Dict:
|
|
462
|
+
try:
|
|
463
|
+
success = terminal_service.send_input(
|
|
464
|
+
terminal_id,
|
|
465
|
+
message,
|
|
466
|
+
registry=get_plugin_registry(request),
|
|
467
|
+
sender_id=sender_id,
|
|
468
|
+
orchestration_type=orchestration_type,
|
|
469
|
+
)
|
|
470
|
+
return {"success": success}
|
|
471
|
+
except ValueError as e:
|
|
472
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
473
|
+
except Exception as e:
|
|
474
|
+
raise HTTPException(
|
|
475
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
476
|
+
detail=f"Failed to send input: {str(e)}",
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
@app.get("/terminals/{terminal_id}/output", response_model=TerminalOutputResponse)
|
|
481
|
+
async def get_terminal_output(
|
|
482
|
+
terminal_id: TerminalId, mode: OutputMode = OutputMode.FULL
|
|
483
|
+
) -> TerminalOutputResponse:
|
|
484
|
+
try:
|
|
485
|
+
output = terminal_service.get_output(terminal_id, mode)
|
|
486
|
+
return TerminalOutputResponse(output=output, mode=mode)
|
|
487
|
+
except ValueError as e:
|
|
488
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
489
|
+
except Exception as e:
|
|
490
|
+
raise HTTPException(
|
|
491
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
492
|
+
detail=f"Failed to get output: {str(e)}",
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
@app.post("/terminals/{terminal_id}/exit")
|
|
497
|
+
async def exit_terminal(terminal_id: TerminalId) -> Dict:
|
|
498
|
+
"""Send provider-specific exit command to terminal."""
|
|
499
|
+
try:
|
|
500
|
+
provider = provider_manager.get_provider(terminal_id)
|
|
501
|
+
if provider is None:
|
|
502
|
+
raise ValueError(f"Provider not found for terminal {terminal_id}")
|
|
503
|
+
exit_command = provider.exit_cli()
|
|
504
|
+
# Some providers use tmux key sequences (e.g., "C-d" for Ctrl+D) instead
|
|
505
|
+
# of text commands (e.g., "/exit"). Key sequences must be sent via
|
|
506
|
+
# send_special_key() to be interpreted by tmux, not as literal text.
|
|
507
|
+
if exit_command.startswith(("C-", "M-")):
|
|
508
|
+
terminal_service.send_special_key(terminal_id, exit_command)
|
|
509
|
+
else:
|
|
510
|
+
terminal_service.send_input(terminal_id, exit_command)
|
|
511
|
+
return {"success": True}
|
|
512
|
+
except ValueError as e:
|
|
513
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
514
|
+
except Exception as e:
|
|
515
|
+
raise HTTPException(
|
|
516
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
517
|
+
detail=f"Failed to exit terminal: {str(e)}",
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
@app.delete("/terminals/{terminal_id}")
|
|
522
|
+
async def delete_terminal(request: Request, terminal_id: TerminalId) -> Dict:
|
|
523
|
+
"""Delete a terminal."""
|
|
524
|
+
try:
|
|
525
|
+
success = terminal_service.delete_terminal(
|
|
526
|
+
terminal_id, registry=get_plugin_registry(request)
|
|
527
|
+
)
|
|
528
|
+
return {"success": success}
|
|
529
|
+
except ValueError as e:
|
|
530
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
531
|
+
except Exception as e:
|
|
532
|
+
raise HTTPException(
|
|
533
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
534
|
+
detail=f"Failed to delete terminal: {str(e)}",
|
|
535
|
+
)
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
@app.post("/terminals/{receiver_id}/inbox/messages")
|
|
539
|
+
async def create_inbox_message_endpoint(
|
|
540
|
+
request: Request,
|
|
541
|
+
receiver_id: TerminalId,
|
|
542
|
+
sender_id: str,
|
|
543
|
+
message: str,
|
|
544
|
+
) -> Dict:
|
|
545
|
+
"""Create inbox message and attempt immediate delivery."""
|
|
546
|
+
try:
|
|
547
|
+
inbox_msg = create_inbox_message(
|
|
548
|
+
sender_id,
|
|
549
|
+
receiver_id,
|
|
550
|
+
message,
|
|
551
|
+
)
|
|
552
|
+
except ValueError as e:
|
|
553
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
554
|
+
except Exception as e:
|
|
555
|
+
raise HTTPException(
|
|
556
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
557
|
+
detail=f"Failed to create inbox message: {str(e)}",
|
|
558
|
+
)
|
|
559
|
+
|
|
560
|
+
# Best-effort immediate delivery. If the receiver terminal is idle, the
|
|
561
|
+
# message is delivered now; otherwise the watchdog will deliver it when
|
|
562
|
+
# the terminal becomes idle. Delivery failures must not cause the API
|
|
563
|
+
# to report an error — the message was already persisted above.
|
|
564
|
+
try:
|
|
565
|
+
inbox_service.check_and_send_pending_messages(
|
|
566
|
+
receiver_id, registry=get_plugin_registry(request)
|
|
567
|
+
)
|
|
568
|
+
except Exception as e:
|
|
569
|
+
logger.warning(f"Immediate delivery attempt failed for {receiver_id}: {e}")
|
|
570
|
+
|
|
571
|
+
return {
|
|
572
|
+
"success": True,
|
|
573
|
+
"message_id": inbox_msg.id,
|
|
574
|
+
"sender_id": inbox_msg.sender_id,
|
|
575
|
+
"receiver_id": inbox_msg.receiver_id,
|
|
576
|
+
"created_at": inbox_msg.created_at.isoformat(),
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
@app.get("/terminals/{terminal_id}/inbox/messages")
|
|
581
|
+
async def get_inbox_messages_endpoint(
|
|
582
|
+
terminal_id: TerminalId,
|
|
583
|
+
limit: int = Query(default=10, le=100, description="Maximum number of messages to retrieve"),
|
|
584
|
+
status_param: Optional[str] = Query(
|
|
585
|
+
default=None, alias="status", description="Filter by message status"
|
|
586
|
+
),
|
|
587
|
+
) -> List[Dict]:
|
|
588
|
+
"""Get inbox messages for a terminal.
|
|
589
|
+
|
|
590
|
+
Args:
|
|
591
|
+
terminal_id: Terminal ID to get messages for
|
|
592
|
+
limit: Maximum number of messages to return (default: 10, max: 100)
|
|
593
|
+
status_param: Optional filter by message status ('pending', 'delivered', 'failed')
|
|
594
|
+
|
|
595
|
+
Returns:
|
|
596
|
+
List of inbox messages with sender_id, message, created_at, status
|
|
597
|
+
"""
|
|
598
|
+
try:
|
|
599
|
+
# Convert status filter if provided
|
|
600
|
+
status_filter = None
|
|
601
|
+
if status_param:
|
|
602
|
+
try:
|
|
603
|
+
status_filter = MessageStatus(status_param)
|
|
604
|
+
except ValueError:
|
|
605
|
+
raise HTTPException(
|
|
606
|
+
status_code=status.HTTP_400_BAD_REQUEST,
|
|
607
|
+
detail=f"Invalid status: {status_param}. Valid values: pending, delivered, failed",
|
|
608
|
+
)
|
|
609
|
+
|
|
610
|
+
# Get messages using existing database function
|
|
611
|
+
messages = get_inbox_messages(terminal_id, limit=limit, status=status_filter)
|
|
612
|
+
|
|
613
|
+
# Convert to response format
|
|
614
|
+
result = []
|
|
615
|
+
for msg in messages:
|
|
616
|
+
result.append(
|
|
617
|
+
{
|
|
618
|
+
"id": msg.id,
|
|
619
|
+
"sender_id": msg.sender_id,
|
|
620
|
+
"receiver_id": msg.receiver_id,
|
|
621
|
+
"message": msg.message,
|
|
622
|
+
"status": msg.status.value,
|
|
623
|
+
"created_at": msg.created_at.isoformat() if msg.created_at else None,
|
|
624
|
+
}
|
|
625
|
+
)
|
|
626
|
+
|
|
627
|
+
return result
|
|
628
|
+
|
|
629
|
+
except HTTPException:
|
|
630
|
+
# Re-raise HTTPException (validation errors)
|
|
631
|
+
raise
|
|
632
|
+
except ValueError as e:
|
|
633
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
634
|
+
except Exception as e:
|
|
635
|
+
raise HTTPException(
|
|
636
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
637
|
+
detail=f"Failed to retrieve inbox messages: {str(e)}",
|
|
638
|
+
)
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
@app.websocket("/terminals/{terminal_id}/ws")
|
|
642
|
+
async def terminal_ws(websocket: WebSocket, terminal_id: str):
|
|
643
|
+
"""WebSocket endpoint for live terminal streaming via tmux attach.
|
|
644
|
+
|
|
645
|
+
Security: This endpoint provides full PTY access with no authentication.
|
|
646
|
+
It is intended for localhost-only use. Do NOT expose the server to
|
|
647
|
+
untrusted networks (e.g. --host 0.0.0.0) without adding authentication.
|
|
648
|
+
"""
|
|
649
|
+
# Reject connections from non-loopback clients
|
|
650
|
+
client_host = websocket.client.host if websocket.client else None
|
|
651
|
+
if client_host not in (None, "127.0.0.1", "::1", "localhost"):
|
|
652
|
+
await websocket.close(code=4003, reason="WebSocket access is restricted to localhost")
|
|
653
|
+
return
|
|
654
|
+
|
|
655
|
+
await websocket.accept()
|
|
656
|
+
|
|
657
|
+
metadata = get_terminal_metadata(terminal_id)
|
|
658
|
+
if not metadata:
|
|
659
|
+
await websocket.close(code=4004, reason="Terminal not found")
|
|
660
|
+
return
|
|
661
|
+
|
|
662
|
+
session_name = metadata["tmux_session"]
|
|
663
|
+
window_name = metadata["tmux_window"]
|
|
664
|
+
|
|
665
|
+
# Create PTY pair for tmux attach
|
|
666
|
+
master_fd, slave_fd = pty.openpty()
|
|
667
|
+
|
|
668
|
+
# Set initial terminal size
|
|
669
|
+
winsize = struct.pack("HHHH", 24, 80, 0, 0)
|
|
670
|
+
fcntl.ioctl(slave_fd, termios.TIOCSWINSZ, winsize)
|
|
671
|
+
|
|
672
|
+
# Start tmux attach inside the PTY
|
|
673
|
+
proc = subprocess.Popen(
|
|
674
|
+
["tmux", "-u", "attach-session", "-t", f"{session_name}:{window_name}"],
|
|
675
|
+
stdin=slave_fd,
|
|
676
|
+
stdout=slave_fd,
|
|
677
|
+
stderr=slave_fd,
|
|
678
|
+
close_fds=True,
|
|
679
|
+
preexec_fn=os.setsid,
|
|
680
|
+
)
|
|
681
|
+
os.close(slave_fd)
|
|
682
|
+
|
|
683
|
+
# Make master_fd non-blocking for event-driven reads
|
|
684
|
+
flag = fcntl.fcntl(master_fd, fcntl.F_GETFL)
|
|
685
|
+
fcntl.fcntl(master_fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)
|
|
686
|
+
|
|
687
|
+
loop = asyncio.get_event_loop()
|
|
688
|
+
output_queue: asyncio.Queue[bytes] = asyncio.Queue()
|
|
689
|
+
done = asyncio.Event()
|
|
690
|
+
|
|
691
|
+
def _on_pty_data():
|
|
692
|
+
"""Callback when PTY has data available."""
|
|
693
|
+
try:
|
|
694
|
+
data = os.read(master_fd, 65536)
|
|
695
|
+
if data:
|
|
696
|
+
output_queue.put_nowait(data)
|
|
697
|
+
else:
|
|
698
|
+
done.set()
|
|
699
|
+
except BlockingIOError:
|
|
700
|
+
pass
|
|
701
|
+
except OSError:
|
|
702
|
+
done.set()
|
|
703
|
+
|
|
704
|
+
loop.add_reader(master_fd, _on_pty_data)
|
|
705
|
+
|
|
706
|
+
async def _forward_output():
|
|
707
|
+
"""Read from PTY queue and send to WebSocket."""
|
|
708
|
+
while not done.is_set():
|
|
709
|
+
try:
|
|
710
|
+
data = await asyncio.wait_for(output_queue.get(), timeout=1.0)
|
|
711
|
+
# Drain any additional pending data for batching
|
|
712
|
+
while not output_queue.empty():
|
|
713
|
+
try:
|
|
714
|
+
data += output_queue.get_nowait()
|
|
715
|
+
except asyncio.QueueEmpty:
|
|
716
|
+
break
|
|
717
|
+
await websocket.send_bytes(data)
|
|
718
|
+
except asyncio.TimeoutError:
|
|
719
|
+
if proc.poll() is not None:
|
|
720
|
+
break
|
|
721
|
+
except (Exception, asyncio.CancelledError):
|
|
722
|
+
break
|
|
723
|
+
|
|
724
|
+
async def _forward_input():
|
|
725
|
+
"""Receive from WebSocket and write to PTY."""
|
|
726
|
+
try:
|
|
727
|
+
while not done.is_set():
|
|
728
|
+
msg = await websocket.receive_text()
|
|
729
|
+
payload = json.loads(msg)
|
|
730
|
+
if payload.get("type") == "input":
|
|
731
|
+
raw = payload["data"].encode()
|
|
732
|
+
# Write in chunks to avoid overflowing the PTY buffer
|
|
733
|
+
chunk_size = 1024
|
|
734
|
+
for i in range(0, len(raw), chunk_size):
|
|
735
|
+
os.write(master_fd, raw[i : i + chunk_size])
|
|
736
|
+
if i + chunk_size < len(raw):
|
|
737
|
+
await asyncio.sleep(0.01)
|
|
738
|
+
elif payload.get("type") == "resize":
|
|
739
|
+
rows = payload.get("rows", 24)
|
|
740
|
+
cols = payload.get("cols", 80)
|
|
741
|
+
winsize_data = struct.pack("HHHH", rows, cols, 0, 0)
|
|
742
|
+
fcntl.ioctl(master_fd, termios.TIOCSWINSZ, winsize_data)
|
|
743
|
+
# Explicitly notify tmux of the size change —
|
|
744
|
+
# TIOCSWINSZ on the master doesn't always deliver
|
|
745
|
+
# SIGWINCH to the child process group.
|
|
746
|
+
try:
|
|
747
|
+
os.kill(proc.pid, signal.SIGWINCH)
|
|
748
|
+
except OSError:
|
|
749
|
+
pass
|
|
750
|
+
except WebSocketDisconnect:
|
|
751
|
+
pass
|
|
752
|
+
except (Exception, asyncio.CancelledError):
|
|
753
|
+
pass
|
|
754
|
+
finally:
|
|
755
|
+
done.set()
|
|
756
|
+
|
|
757
|
+
try:
|
|
758
|
+
await asyncio.gather(_forward_output(), _forward_input())
|
|
759
|
+
except (Exception, asyncio.CancelledError):
|
|
760
|
+
pass
|
|
761
|
+
finally:
|
|
762
|
+
done.set()
|
|
763
|
+
try:
|
|
764
|
+
loop.remove_reader(master_fd)
|
|
765
|
+
except Exception:
|
|
766
|
+
pass
|
|
767
|
+
try:
|
|
768
|
+
os.close(master_fd)
|
|
769
|
+
except OSError:
|
|
770
|
+
pass
|
|
771
|
+
# Terminate tmux attach (just detaches, doesn't kill the session)
|
|
772
|
+
proc.terminate()
|
|
773
|
+
try:
|
|
774
|
+
await asyncio.wait_for(asyncio.to_thread(proc.wait), timeout=3.0)
|
|
775
|
+
except asyncio.TimeoutError:
|
|
776
|
+
proc.kill()
|
|
777
|
+
await asyncio.to_thread(proc.wait)
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
# ── Flow management endpoints ────────────────────────────────────────
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
@app.get("/flows", response_model=List[Flow])
|
|
784
|
+
async def list_flows() -> List[Flow]:
|
|
785
|
+
"""List all flows."""
|
|
786
|
+
try:
|
|
787
|
+
return flow_service.list_flows()
|
|
788
|
+
except Exception as e:
|
|
789
|
+
raise HTTPException(
|
|
790
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
791
|
+
detail=f"Failed to list flows: {str(e)}",
|
|
792
|
+
)
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
@app.get("/flows/{name}", response_model=Flow)
|
|
796
|
+
async def get_flow(name: str) -> Flow:
|
|
797
|
+
"""Get a specific flow by name."""
|
|
798
|
+
try:
|
|
799
|
+
return flow_service.get_flow(name)
|
|
800
|
+
except ValueError as e:
|
|
801
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
802
|
+
except Exception as e:
|
|
803
|
+
raise HTTPException(
|
|
804
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
805
|
+
detail=f"Failed to get flow: {str(e)}",
|
|
806
|
+
)
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
@app.post("/flows", response_model=Flow, status_code=status.HTTP_201_CREATED)
|
|
810
|
+
async def create_flow(body: CreateFlowRequest) -> Flow:
|
|
811
|
+
"""Create a new flow.
|
|
812
|
+
|
|
813
|
+
Writes a .flow.md file with YAML frontmatter and prompt body, then
|
|
814
|
+
registers it via flow_service.add_flow().
|
|
815
|
+
"""
|
|
816
|
+
try:
|
|
817
|
+
flows_dir = CAO_HOME_DIR / "flows"
|
|
818
|
+
flows_dir.mkdir(parents=True, exist_ok=True)
|
|
819
|
+
|
|
820
|
+
file_path = flows_dir / f"{body.name}.flow.md"
|
|
821
|
+
|
|
822
|
+
# Build YAML frontmatter content
|
|
823
|
+
frontmatter_lines = [
|
|
824
|
+
"---",
|
|
825
|
+
f"name: {body.name}",
|
|
826
|
+
f'schedule: "{body.schedule}"',
|
|
827
|
+
f"agent_profile: {body.agent_profile}",
|
|
828
|
+
f"provider: {body.provider}",
|
|
829
|
+
"---",
|
|
830
|
+
]
|
|
831
|
+
file_content = "\n".join(frontmatter_lines) + "\n" + body.prompt_template
|
|
832
|
+
|
|
833
|
+
file_path.write_text(file_content)
|
|
834
|
+
|
|
835
|
+
return flow_service.add_flow(str(file_path))
|
|
836
|
+
except ValueError as e:
|
|
837
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
838
|
+
except Exception as e:
|
|
839
|
+
raise HTTPException(
|
|
840
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
841
|
+
detail=f"Failed to create flow: {str(e)}",
|
|
842
|
+
)
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
@app.delete("/flows/{name}")
|
|
846
|
+
async def remove_flow(name: str) -> Dict:
|
|
847
|
+
"""Remove a flow."""
|
|
848
|
+
try:
|
|
849
|
+
flow_service.remove_flow(name)
|
|
850
|
+
return {"success": True}
|
|
851
|
+
except ValueError as e:
|
|
852
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
853
|
+
except Exception as e:
|
|
854
|
+
raise HTTPException(
|
|
855
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
856
|
+
detail=f"Failed to remove flow: {str(e)}",
|
|
857
|
+
)
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
@app.post("/flows/{name}/enable")
|
|
861
|
+
async def enable_flow(name: str) -> Dict:
|
|
862
|
+
"""Enable a flow."""
|
|
863
|
+
try:
|
|
864
|
+
flow_service.enable_flow(name)
|
|
865
|
+
return {"success": True}
|
|
866
|
+
except ValueError as e:
|
|
867
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
868
|
+
except Exception as e:
|
|
869
|
+
raise HTTPException(
|
|
870
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
871
|
+
detail=f"Failed to enable flow: {str(e)}",
|
|
872
|
+
)
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
@app.post("/flows/{name}/disable")
|
|
876
|
+
async def disable_flow(name: str) -> Dict:
|
|
877
|
+
"""Disable a flow."""
|
|
878
|
+
try:
|
|
879
|
+
flow_service.disable_flow(name)
|
|
880
|
+
return {"success": True}
|
|
881
|
+
except ValueError as e:
|
|
882
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
883
|
+
except Exception as e:
|
|
884
|
+
raise HTTPException(
|
|
885
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
886
|
+
detail=f"Failed to disable flow: {str(e)}",
|
|
887
|
+
)
|
|
888
|
+
|
|
889
|
+
|
|
890
|
+
@app.post("/flows/{name}/run")
|
|
891
|
+
async def run_flow(name: str) -> Dict:
|
|
892
|
+
"""Manually execute a flow."""
|
|
893
|
+
try:
|
|
894
|
+
executed = flow_service.execute_flow(name)
|
|
895
|
+
return {"executed": executed}
|
|
896
|
+
except ValueError as e:
|
|
897
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
|
898
|
+
except Exception as e:
|
|
899
|
+
raise HTTPException(
|
|
900
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
901
|
+
detail=f"Failed to execute flow: {str(e)}",
|
|
902
|
+
)
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
# Static file serving for built web UI.
|
|
906
|
+
# Anchored to the package via importlib.resources so it works for both
|
|
907
|
+
# editable installs (uv sync) and wheel installs (uv tool install, pip install).
|
|
908
|
+
from importlib.resources import files as _pkg_files
|
|
909
|
+
|
|
910
|
+
WEB_DIST = Path(str(_pkg_files("cli_agent_orchestrator") / "web_ui"))
|
|
911
|
+
if (WEB_DIST / "index.html").exists():
|
|
912
|
+
from starlette.staticfiles import StaticFiles
|
|
913
|
+
|
|
914
|
+
app.mount("/", StaticFiles(directory=str(WEB_DIST), html=True), name="web")
|
|
915
|
+
|
|
916
|
+
|
|
917
|
+
def main():
|
|
918
|
+
"""Entry point for cao-server command."""
|
|
919
|
+
import argparse
|
|
920
|
+
|
|
921
|
+
import uvicorn
|
|
922
|
+
|
|
923
|
+
parser = argparse.ArgumentParser(description="CLI Agent Orchestrator Server")
|
|
924
|
+
parser.add_argument(
|
|
925
|
+
"--agents-dir",
|
|
926
|
+
type=str,
|
|
927
|
+
default=None,
|
|
928
|
+
help="Path to agents directory (overrides CAO_AGENTS_DIR env var)",
|
|
929
|
+
)
|
|
930
|
+
parser.add_argument("--host", type=str, default=None, help="Server host")
|
|
931
|
+
parser.add_argument("--port", type=int, default=None, help="Server port")
|
|
932
|
+
args = parser.parse_args()
|
|
933
|
+
|
|
934
|
+
if args.agents_dir:
|
|
935
|
+
os.environ["CAO_AGENTS_DIR"] = args.agents_dir
|
|
936
|
+
import cli_agent_orchestrator.constants as constants
|
|
937
|
+
|
|
938
|
+
constants.KIRO_AGENTS_DIR = Path(args.agents_dir)
|
|
939
|
+
logger.info(f"Using agents directory: {args.agents_dir}")
|
|
940
|
+
|
|
941
|
+
host = args.host or SERVER_HOST
|
|
942
|
+
port = args.port or SERVER_PORT
|
|
943
|
+
uvicorn.run(app, host=host, port=port)
|
|
944
|
+
|
|
945
|
+
|
|
946
|
+
if __name__ == "__main__":
|
|
947
|
+
main()
|