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.
Files changed (84) hide show
  1. cli_agent_orchestrator/__init__.py +0 -0
  2. cli_agent_orchestrator/agent_store/code_supervisor.md +66 -0
  3. cli_agent_orchestrator/agent_store/developer.md +55 -0
  4. cli_agent_orchestrator/agent_store/reviewer.md +60 -0
  5. cli_agent_orchestrator/api/__init__.py +1 -0
  6. cli_agent_orchestrator/api/main.py +947 -0
  7. cli_agent_orchestrator/cli/__init__.py +1 -0
  8. cli_agent_orchestrator/cli/commands/__init__.py +1 -0
  9. cli_agent_orchestrator/cli/commands/env.py +60 -0
  10. cli_agent_orchestrator/cli/commands/flow.py +102 -0
  11. cli_agent_orchestrator/cli/commands/info.py +57 -0
  12. cli_agent_orchestrator/cli/commands/init.py +45 -0
  13. cli_agent_orchestrator/cli/commands/install.py +317 -0
  14. cli_agent_orchestrator/cli/commands/launch.py +243 -0
  15. cli_agent_orchestrator/cli/commands/mcp_server.py +12 -0
  16. cli_agent_orchestrator/cli/commands/session.py +260 -0
  17. cli_agent_orchestrator/cli/commands/shutdown.py +59 -0
  18. cli_agent_orchestrator/cli/commands/skills.py +99 -0
  19. cli_agent_orchestrator/cli/main.py +36 -0
  20. cli_agent_orchestrator/clients/database.py +415 -0
  21. cli_agent_orchestrator/clients/tmux.py +516 -0
  22. cli_agent_orchestrator/constants.py +145 -0
  23. cli_agent_orchestrator/mcp_server/__init__.py +1 -0
  24. cli_agent_orchestrator/mcp_server/models.py +14 -0
  25. cli_agent_orchestrator/mcp_server/server.py +653 -0
  26. cli_agent_orchestrator/mcp_server/utils.py +15 -0
  27. cli_agent_orchestrator/models/__init__.py +1 -0
  28. cli_agent_orchestrator/models/agent_profile.py +37 -0
  29. cli_agent_orchestrator/models/copilot_agent.py +15 -0
  30. cli_agent_orchestrator/models/flow.py +23 -0
  31. cli_agent_orchestrator/models/inbox.py +33 -0
  32. cli_agent_orchestrator/models/kiro_agent.py +28 -0
  33. cli_agent_orchestrator/models/opencode_agent.py +23 -0
  34. cli_agent_orchestrator/models/provider.py +14 -0
  35. cli_agent_orchestrator/models/q_agent.py +28 -0
  36. cli_agent_orchestrator/models/session.py +21 -0
  37. cli_agent_orchestrator/models/skill.py +19 -0
  38. cli_agent_orchestrator/models/terminal.py +37 -0
  39. cli_agent_orchestrator/plugins/__init__.py +24 -0
  40. cli_agent_orchestrator/plugins/base.py +52 -0
  41. cli_agent_orchestrator/plugins/events.py +75 -0
  42. cli_agent_orchestrator/plugins/registry.py +87 -0
  43. cli_agent_orchestrator/providers/__init__.py +0 -0
  44. cli_agent_orchestrator/providers/base.py +186 -0
  45. cli_agent_orchestrator/providers/claude_code.py +434 -0
  46. cli_agent_orchestrator/providers/codex.py +497 -0
  47. cli_agent_orchestrator/providers/copilot_cli.py +502 -0
  48. cli_agent_orchestrator/providers/gemini_cli.py +764 -0
  49. cli_agent_orchestrator/providers/kimi_cli.py +649 -0
  50. cli_agent_orchestrator/providers/kiro_cli.py +548 -0
  51. cli_agent_orchestrator/providers/manager.py +181 -0
  52. cli_agent_orchestrator/providers/opencode_cli.py +369 -0
  53. cli_agent_orchestrator/providers/q_cli.py +176 -0
  54. cli_agent_orchestrator/services/cleanup_service.py +58 -0
  55. cli_agent_orchestrator/services/flow_service.py +235 -0
  56. cli_agent_orchestrator/services/inbox_service.py +172 -0
  57. cli_agent_orchestrator/services/plugin_dispatch.py +42 -0
  58. cli_agent_orchestrator/services/session_service.py +141 -0
  59. cli_agent_orchestrator/services/settings_service.py +78 -0
  60. cli_agent_orchestrator/services/terminal_service.py +475 -0
  61. cli_agent_orchestrator/skills/__init__.py +1 -0
  62. cli_agent_orchestrator/skills/cao-session-management/SKILL.md +106 -0
  63. cli_agent_orchestrator/skills/cao-supervisor-protocols/SKILL.md +84 -0
  64. cli_agent_orchestrator/skills/cao-worker-protocols/SKILL.md +60 -0
  65. cli_agent_orchestrator/utils/__init__.py +1 -0
  66. cli_agent_orchestrator/utils/agent_profiles.py +241 -0
  67. cli_agent_orchestrator/utils/env.py +41 -0
  68. cli_agent_orchestrator/utils/logging.py +25 -0
  69. cli_agent_orchestrator/utils/opencode_config.py +169 -0
  70. cli_agent_orchestrator/utils/opencode_permissions.py +109 -0
  71. cli_agent_orchestrator/utils/skill_injection.py +240 -0
  72. cli_agent_orchestrator/utils/skills.py +129 -0
  73. cli_agent_orchestrator/utils/template.py +30 -0
  74. cli_agent_orchestrator/utils/terminal.py +145 -0
  75. cli_agent_orchestrator/utils/tool_mapping.py +158 -0
  76. cli_agent_orchestrator/web_ui/assets/index-BXMLhBau.css +32 -0
  77. cli_agent_orchestrator/web_ui/assets/index-BpPHwanT.js +275 -0
  78. cli_agent_orchestrator/web_ui/index.html +13 -0
  79. cli_agent_orchestrator-2.1.1.dist-info/METADATA +681 -0
  80. cli_agent_orchestrator-2.1.1.dist-info/RECORD +84 -0
  81. cli_agent_orchestrator-2.1.1.dist-info/WHEEL +4 -0
  82. cli_agent_orchestrator-2.1.1.dist-info/entry_points.txt +4 -0
  83. cli_agent_orchestrator-2.1.1.dist-info/licenses/LICENSE +175 -0
  84. cli_agent_orchestrator-2.1.1.dist-info/licenses/NOTICE +1 -0
@@ -0,0 +1,243 @@
1
+ """Launch command for CLI Agent Orchestrator CLI."""
2
+
3
+ import os
4
+ import subprocess
5
+ import time
6
+
7
+ import click
8
+ import requests
9
+
10
+ from cli_agent_orchestrator.constants import (
11
+ API_BASE_URL,
12
+ DEFAULT_PROVIDER,
13
+ PROVIDERS,
14
+ SERVER_HOST,
15
+ SERVER_PORT,
16
+ )
17
+ from cli_agent_orchestrator.models.terminal import TerminalStatus
18
+ from cli_agent_orchestrator.utils.terminal import poll_until_done, wait_until_terminal_status
19
+
20
+ # Providers that require workspace folder access
21
+ PROVIDERS_REQUIRING_WORKSPACE_ACCESS = {
22
+ "claude_code",
23
+ "codex",
24
+ "copilot_cli",
25
+ "gemini_cli",
26
+ "kimi_cli",
27
+ "kiro_cli",
28
+ "opencode_cli",
29
+ }
30
+
31
+
32
+ @click.command()
33
+ @click.argument("message", required=False, default=None)
34
+ @click.option("--agents", required=True, help="Agent profile to launch")
35
+ @click.option("--session-name", help="Name of the session (default: auto-generated)")
36
+ @click.option("--headless", is_flag=True, help="Launch in detached mode")
37
+ @click.option(
38
+ "--provider",
39
+ default=None,
40
+ help=f"Provider to use (default: profile provider or {DEFAULT_PROVIDER})",
41
+ )
42
+ @click.option(
43
+ "--allowed-tools",
44
+ multiple=True,
45
+ help="Override allowedTools (CAO format: execute_bash, fs_read, @cao-mcp-server). Repeatable.",
46
+ )
47
+ @click.option(
48
+ "--async",
49
+ "is_async",
50
+ is_flag=True,
51
+ help="Send message and return immediately without waiting for completion",
52
+ )
53
+ @click.option(
54
+ "--auto-approve",
55
+ is_flag=True,
56
+ help="Skip confirmation prompt (restrictions still enforced).",
57
+ )
58
+ @click.option(
59
+ "--yolo",
60
+ is_flag=True,
61
+ help="[DANGEROUS] Unrestricted tool access AND skip confirmation prompts. "
62
+ "Agent can execute ANY command including aws, rm, curl.",
63
+ )
64
+ @click.option(
65
+ "--working-directory",
66
+ default=None,
67
+ help="Working directory for the session (default: current directory)",
68
+ )
69
+ def launch(
70
+ message,
71
+ agents,
72
+ session_name,
73
+ headless,
74
+ is_async,
75
+ provider,
76
+ allowed_tools,
77
+ auto_approve,
78
+ yolo,
79
+ working_directory,
80
+ ):
81
+ """Launch cao session with specified agent profile."""
82
+ try:
83
+ display_dir = working_directory or os.path.realpath(os.getcwd())
84
+
85
+ # Resolve allowedTools: --yolo > --allowed-tools CLI > profile/role defaults
86
+ from cli_agent_orchestrator.utils.agent_profiles import load_agent_profile
87
+ from cli_agent_orchestrator.utils.tool_mapping import (
88
+ format_tool_summary,
89
+ get_disallowed_tools,
90
+ resolve_allowed_tools,
91
+ )
92
+
93
+ resolved_allowed_tools = None
94
+ no_role_set = False
95
+ if yolo:
96
+ resolved_allowed_tools = ["*"]
97
+ elif allowed_tools:
98
+ resolved_allowed_tools = list(allowed_tools)
99
+ else:
100
+ # Load profile to get role-based defaults
101
+ try:
102
+ profile = load_agent_profile(agents)
103
+ mcp_server_names = list(profile.mcpServers.keys()) if profile.mcpServers else None
104
+ no_role_set = not profile.role and not profile.allowedTools
105
+ resolved_allowed_tools = resolve_allowed_tools(
106
+ profile.allowedTools, profile.role, mcp_server_names
107
+ )
108
+ # Honour profile.provider when --provider not explicitly passed
109
+ if provider is None:
110
+ from cli_agent_orchestrator.utils.agent_profiles import resolve_provider
111
+
112
+ provider = resolve_provider(agents, DEFAULT_PROVIDER)
113
+ except (FileNotFoundError, RuntimeError):
114
+ # Profile not found — use developer defaults (backward compatible)
115
+ no_role_set = True
116
+ resolved_allowed_tools = resolve_allowed_tools(None, None, None)
117
+
118
+ # Fall back to DEFAULT_PROVIDER when --provider was not given and
119
+ # profile resolution didn't set it (yolo, --allowed-tools, or missing profile)
120
+ if provider is None:
121
+ provider = DEFAULT_PROVIDER
122
+
123
+ # Validate provider
124
+ if provider not in PROVIDERS:
125
+ raise click.ClickException(
126
+ f"Invalid provider '{provider}'. Available providers: {', '.join(PROVIDERS)}"
127
+ )
128
+ # Confirmation / warning prompts
129
+ if provider in PROVIDERS_REQUIRING_WORKSPACE_ACCESS:
130
+ if yolo:
131
+ # --yolo: warn but don't block
132
+ click.echo(click.style("\n[WARNING] --yolo mode enabled", fg="yellow", bold=True))
133
+ click.echo(
134
+ f" Agent '{agents}' launching UNRESTRICTED on {provider}.\n"
135
+ f" Agent can execute ANY command (aws, rm, curl, read credentials).\n"
136
+ f" Directory: {display_dir}\n"
137
+ )
138
+ if provider == "kiro_cli":
139
+ # kiro-cli 2.0.1 TUI blocks on an interactive "Yes, I accept"
140
+ # consent dialog when --trust-all-tools is set. CAO cannot
141
+ # answer it headlessly, so yolo launches use --legacy-ui.
142
+ click.echo(
143
+ " Note: kiro_cli will launch in --legacy-ui mode so "
144
+ "--trust-all-tools can be applied non-interactively.\n"
145
+ )
146
+ elif provider == "opencode_cli":
147
+ # opencode's TUI has no runtime skip-permissions flag
148
+ # (tracked upstream in sst/opencode#8463). Permissions are
149
+ # install-time only, so --yolo cannot loosen them here.
150
+ click.echo(
151
+ click.style(
152
+ " Note: --yolo has no runtime effect on opencode_cli.\n"
153
+ " Permissions are set at cao install time. To get unrestricted\n"
154
+ " access, set 'allowedTools: [\"*\"]' in the profile and re-run\n"
155
+ " 'cao install'. See docs/opencode-cli.md for details.\n",
156
+ fg="yellow",
157
+ )
158
+ )
159
+ else:
160
+ # Normal launch: show tool summary and confirm
161
+ tool_summary = format_tool_summary(resolved_allowed_tools)
162
+ blocked = get_disallowed_tools(provider, resolved_allowed_tools)
163
+ blocked_summary = ", ".join(blocked) if blocked else "(none)"
164
+
165
+ click.echo(
166
+ f"\nAgent '{agents}' launching on {provider}:\n"
167
+ f" Allowed: {tool_summary}\n"
168
+ f" Blocked: {blocked_summary}\n"
169
+ f" Directory: {display_dir}\n"
170
+ )
171
+ if no_role_set:
172
+ click.echo(
173
+ " Note: No role or allowedTools set — defaulting to 'developer'.\n"
174
+ " Add 'role' or 'allowedTools' to your agent profile to control tool access.\n"
175
+ " Docs: https://github.com/awslabs/cli-agent-orchestrator/blob/main/docs/tool-restrictions.md\n"
176
+ )
177
+ click.echo(
178
+ " To skip this prompt next time, relaunch with --auto-approve\n"
179
+ " To remove all restrictions, relaunch with --yolo\n"
180
+ )
181
+ if not auto_approve and not click.confirm("Proceed?", default=True):
182
+ raise click.ClickException("Launch cancelled by user")
183
+
184
+ # Call API to create session — pass working_directory only if explicitly
185
+ # provided. When omitted, the server defaults to its own CWD.
186
+ url = f"http://{SERVER_HOST}:{SERVER_PORT}/sessions"
187
+ params = {
188
+ "provider": provider,
189
+ "agent_profile": agents,
190
+ "working_directory": working_directory or os.getcwd(),
191
+ }
192
+ if session_name:
193
+ params["session_name"] = session_name
194
+ if resolved_allowed_tools:
195
+ # Pass as comma-separated string for query param
196
+ params["allowed_tools"] = ",".join(resolved_allowed_tools)
197
+
198
+ response = requests.post(url, params=params)
199
+ response.raise_for_status()
200
+
201
+ terminal = response.json()
202
+
203
+ click.echo(f"Session created: {terminal['session_name']}")
204
+ click.echo(f"Terminal created: {terminal['name']}")
205
+
206
+ # Attach to tmux session unless headless
207
+ if not headless:
208
+ subprocess.run(["tmux", "attach-session", "-t", terminal["session_name"]])
209
+ elif message:
210
+ ready = wait_until_terminal_status(
211
+ terminal["id"],
212
+ {TerminalStatus.IDLE, TerminalStatus.COMPLETED},
213
+ timeout=120,
214
+ )
215
+ if not ready:
216
+ raise click.ClickException(
217
+ f"Conductor {terminal['id']} did not become ready within 120s"
218
+ )
219
+ response = requests.post(
220
+ f"{API_BASE_URL}/terminals/{terminal['id']}/input",
221
+ params={"message": message},
222
+ )
223
+ response.raise_for_status()
224
+ time.sleep(3)
225
+ if is_async:
226
+ click.echo(f"Message sent to {terminal['name']}. Running in background.")
227
+ return
228
+ poll_until_done(terminal["id"], timeout=300)
229
+ output_resp = requests.get(
230
+ f"{API_BASE_URL}/terminals/{terminal['id']}/output",
231
+ params={"mode": "last"},
232
+ )
233
+ output_resp.raise_for_status()
234
+ output = output_resp.json().get("output", "")
235
+ if output:
236
+ click.echo(output)
237
+
238
+ except requests.exceptions.RequestException as e:
239
+ raise click.ClickException(f"Failed to connect to cao-server: {str(e)}")
240
+ except click.ClickException:
241
+ raise
242
+ except Exception as e:
243
+ raise click.ClickException(str(e))
@@ -0,0 +1,12 @@
1
+ """MCP server command for CLI Agent Orchestrator CLI."""
2
+
3
+ import click
4
+
5
+ from cli_agent_orchestrator.mcp_server.server import main as run_mcp_server
6
+
7
+
8
+ @click.command(name="mcp-server")
9
+ def mcp_server():
10
+ """Start the CAO MCP server."""
11
+ click.echo("Starting CAO MCP server...")
12
+ run_mcp_server()
@@ -0,0 +1,260 @@
1
+ """Session commands for CLI Agent Orchestrator."""
2
+
3
+ import json
4
+ import sys
5
+ import time
6
+ from urllib.parse import quote
7
+
8
+ import click
9
+ import requests
10
+
11
+ from cli_agent_orchestrator.constants import API_BASE_URL
12
+ from cli_agent_orchestrator.models.terminal import TerminalStatus
13
+ from cli_agent_orchestrator.utils.terminal import poll_until_done
14
+
15
+ # Default poll timeout for sync send (seconds). Pass --timeout to override.
16
+ _DEFAULT_SEND_TIMEOUT = 300
17
+
18
+
19
+ def _get_sessions():
20
+ response = requests.get(f"{API_BASE_URL}/sessions")
21
+ response.raise_for_status()
22
+ return response.json()
23
+
24
+
25
+ def _get_terminals(session_name):
26
+ response = requests.get(f"{API_BASE_URL}/sessions/{quote(session_name, safe='')}/terminals")
27
+ response.raise_for_status()
28
+ return response.json()
29
+
30
+
31
+ def _get_terminal(terminal_id):
32
+ response = requests.get(f"{API_BASE_URL}/terminals/{terminal_id}")
33
+ response.raise_for_status()
34
+ return response.json()
35
+
36
+
37
+ def _get_terminal_output(terminal_id):
38
+ response = requests.get(
39
+ f"{API_BASE_URL}/terminals/{terminal_id}/output", params={"mode": "last"}
40
+ )
41
+ response.raise_for_status()
42
+ return response.json()
43
+
44
+
45
+ def _resolve_conductor(session_name):
46
+ terminals = _get_terminals(session_name)
47
+ if not terminals:
48
+ raise click.ClickException(f"No terminals found for session '{session_name}'")
49
+ return terminals[0], terminals
50
+
51
+
52
+ @click.group()
53
+ def session():
54
+ """Manage CAO sessions."""
55
+
56
+
57
+ @session.command("list")
58
+ @click.option("--json", "as_json", is_flag=True, help="Output as JSON")
59
+ def list_sessions(as_json):
60
+ """List all active CAO sessions."""
61
+ try:
62
+ sessions = _get_sessions()
63
+ except requests.exceptions.RequestException as e:
64
+ raise click.ClickException(f"Failed to connect to cao-server: {e}")
65
+
66
+ if not sessions:
67
+ if as_json:
68
+ click.echo("[]")
69
+ else:
70
+ click.echo("No active sessions")
71
+ return
72
+
73
+ rows = []
74
+ for s in sessions:
75
+ try:
76
+ terminals = _get_terminals(s["name"])
77
+ conductor = terminals[0] if terminals else None
78
+ if conductor:
79
+ conductor = _get_terminal(conductor["id"])
80
+ rows.append((s["name"], conductor, len(terminals)))
81
+ except requests.exceptions.RequestException:
82
+ continue
83
+
84
+ if as_json:
85
+ result = []
86
+ for name, conductor, terminal_count in rows:
87
+ result.append(
88
+ {
89
+ "session": name,
90
+ "conductor": (
91
+ {
92
+ "id": conductor["id"],
93
+ "agent_profile": conductor.get("agent_profile"),
94
+ "provider": conductor.get("provider"),
95
+ "status": conductor.get("status"),
96
+ }
97
+ if conductor
98
+ else None
99
+ ),
100
+ "terminal_count": terminal_count,
101
+ }
102
+ )
103
+ click.echo(json.dumps(result, indent=2))
104
+ else:
105
+ click.echo(f"{'SESSION':<25} {'CONDUCTOR':<12} {'STATUS':<15} {'TERMINALS':<10}")
106
+ click.echo("-" * 65)
107
+ for name, conductor, terminal_count in rows:
108
+ conductor_id = conductor["id"] if conductor else "N/A"
109
+ status = conductor.get("status", "N/A") if conductor else "N/A"
110
+ click.echo(f"{name:<25} {conductor_id:<12} {status:<15} {terminal_count:<10}")
111
+
112
+
113
+ @session.command()
114
+ @click.argument("session_name")
115
+ @click.option("--terminal", "terminal_id", help="Target a specific terminal ID")
116
+ @click.option(
117
+ "--workers",
118
+ is_flag=True,
119
+ help="Show all non-conductor terminals (ignored when --terminal is set)",
120
+ )
121
+ @click.option("--json", "as_json", is_flag=True, help="Output as JSON")
122
+ def status(session_name, terminal_id, workers, as_json):
123
+ """Show status of a session's conductor (or specific terminal)."""
124
+ try:
125
+ if terminal_id:
126
+ target = _get_terminal(terminal_id)
127
+ all_terminals = []
128
+ else:
129
+ conductor_raw, all_terminals = _resolve_conductor(session_name)
130
+ target = _get_terminal(conductor_raw["id"])
131
+ except requests.exceptions.RequestException as e:
132
+ raise click.ClickException(f"Failed to connect to cao-server: {e}")
133
+
134
+ try:
135
+ output_data = _get_terminal_output(target["id"])
136
+ last_output = output_data.get("output")
137
+ except requests.exceptions.RequestException:
138
+ last_output = None
139
+
140
+ if as_json:
141
+ result = {
142
+ "session": session_name,
143
+ "conductor": {
144
+ "id": target["id"],
145
+ "agent_profile": target.get("agent_profile"),
146
+ "provider": target.get("provider"),
147
+ "status": target.get("status"),
148
+ "last_output": last_output,
149
+ },
150
+ }
151
+ if workers and not terminal_id:
152
+ result["workers"] = [
153
+ {
154
+ "id": t["id"],
155
+ "agent_profile": t.get("agent_profile"),
156
+ "provider": t.get("provider"),
157
+ "status": t.get("status"),
158
+ }
159
+ for t in all_terminals[1:]
160
+ ]
161
+ click.echo(json.dumps(result, indent=2))
162
+ return
163
+
164
+ click.echo(f"Session: {session_name}")
165
+ click.echo(f"Terminal: {target['id']}")
166
+ click.echo(f"Agent: {target.get('agent_profile', 'N/A')}")
167
+ click.echo(f"Provider: {target.get('provider', 'N/A')}")
168
+ click.echo(f"Status: {target.get('status', 'N/A')}")
169
+
170
+ if last_output:
171
+ lines = last_output.splitlines()
172
+ truncated = lines[:20]
173
+ click.echo("\nLast response:")
174
+ click.echo("\n".join(truncated))
175
+ if len(lines) > 20:
176
+ click.echo(f"... ({len(lines) - 20} more lines)")
177
+ else:
178
+ click.echo("\nNo last response available")
179
+
180
+ if workers and not terminal_id:
181
+ worker_terminals = all_terminals[1:]
182
+ if worker_terminals:
183
+ click.echo(f"\n{'ID':<12} {'AGENT':<20} {'PROVIDER':<15} {'STATUS':<15}")
184
+ click.echo("-" * 65)
185
+ for t in worker_terminals:
186
+ click.echo(
187
+ f"{t['id']:<12} {t.get('agent_profile', 'N/A'):<20} "
188
+ f"{t.get('provider', 'N/A'):<15} {t.get('status', 'N/A'):<15}"
189
+ )
190
+ else:
191
+ click.echo("\nNo worker terminals")
192
+
193
+
194
+ @session.command()
195
+ @click.argument("session_name")
196
+ @click.argument("message")
197
+ @click.option("--terminal", "terminal_id", help="Send to a specific terminal ID")
198
+ @click.option(
199
+ "--async", "is_async", is_flag=True, help="Send and return immediately without waiting"
200
+ )
201
+ @click.option(
202
+ "--timeout",
203
+ "timeout",
204
+ type=int,
205
+ default=None,
206
+ help=f"Timeout in seconds (default: {_DEFAULT_SEND_TIMEOUT}s; ignored with --async)",
207
+ )
208
+ def send(session_name, message, terminal_id, is_async, timeout):
209
+ """Send a message to a session's conductor (or specific terminal)."""
210
+ try:
211
+ if terminal_id:
212
+ target_id = terminal_id
213
+ else:
214
+ conductor, _ = _resolve_conductor(session_name)
215
+ target_id = conductor["id"]
216
+
217
+ status_resp = requests.get(f"{API_BASE_URL}/terminals/{target_id}")
218
+ status_resp.raise_for_status()
219
+ current_status = status_resp.json().get("status")
220
+ # "completed" is a valid pre-send state: the terminal has finished its
221
+ # previous task and is ready to accept a new message.
222
+ if current_status not in (TerminalStatus.IDLE, TerminalStatus.COMPLETED):
223
+ raise click.ClickException(
224
+ f"Terminal {target_id} is currently {current_status}. Wait for it to finish before sending."
225
+ )
226
+
227
+ response = requests.post(
228
+ f"{API_BASE_URL}/terminals/{target_id}/input",
229
+ params={"message": message},
230
+ )
231
+ response.raise_for_status()
232
+ except requests.exceptions.RequestException as e:
233
+ raise click.ClickException(f"Failed to connect to cao-server: {e}")
234
+
235
+ if is_async:
236
+ click.echo(f"Message sent to terminal {target_id}")
237
+ return
238
+
239
+ time.sleep(3)
240
+ effective_timeout = timeout if timeout is not None else _DEFAULT_SEND_TIMEOUT
241
+ interrupted = False
242
+ try:
243
+ poll_until_done(target_id, effective_timeout)
244
+ except KeyboardInterrupt:
245
+ interrupted = True
246
+
247
+ try:
248
+ output_resp = requests.get(
249
+ f"{API_BASE_URL}/terminals/{target_id}/output",
250
+ params={"mode": "last"},
251
+ )
252
+ output_resp.raise_for_status()
253
+ output = output_resp.json().get("output", "")
254
+ if output:
255
+ click.echo(output)
256
+ except requests.exceptions.RequestException:
257
+ pass
258
+
259
+ if interrupted:
260
+ sys.exit(130)
@@ -0,0 +1,59 @@
1
+ """Shutdown command for CLI Agent Orchestrator."""
2
+
3
+ import click
4
+ import requests
5
+
6
+ from cli_agent_orchestrator.constants import API_BASE_URL
7
+
8
+
9
+ def _list_sessions():
10
+ try:
11
+ response = requests.get(f"{API_BASE_URL}/sessions")
12
+ response.raise_for_status()
13
+ return response.json()
14
+ except requests.exceptions.RequestException as e:
15
+ raise click.ClickException(f"Failed to connect to cao-server: {e}")
16
+
17
+
18
+ def _delete_session(name):
19
+ try:
20
+ response = requests.delete(f"{API_BASE_URL}/sessions/{name}")
21
+ if response.status_code == 404:
22
+ click.echo(f"Session '{name}' already removed", err=True)
23
+ return False
24
+ response.raise_for_status()
25
+ return True
26
+ except requests.exceptions.RequestException as e:
27
+ raise click.ClickException(f"Failed to connect to cao-server: {e}")
28
+
29
+
30
+ @click.command()
31
+ @click.option("--all", "shutdown_all", is_flag=True, help="Shutdown all cao sessions")
32
+ @click.option("--session", help="Shutdown specific session")
33
+ def shutdown(shutdown_all, session):
34
+ """Shutdown tmux sessions and cleanup terminal records."""
35
+
36
+ if not shutdown_all and not session:
37
+ raise click.ClickException("Must specify either --all or --session")
38
+
39
+ if shutdown_all and session:
40
+ raise click.ClickException("Cannot use --all and --session together")
41
+
42
+ if shutdown_all:
43
+ sessions = _list_sessions()
44
+ sessions_to_shutdown = [s["name"] for s in sessions]
45
+ else:
46
+ sessions_to_shutdown = [session]
47
+
48
+ if not sessions_to_shutdown:
49
+ click.echo("No cao sessions found to shutdown")
50
+ return
51
+
52
+ for session_name in sessions_to_shutdown:
53
+ try:
54
+ if _delete_session(session_name):
55
+ click.echo(f"✓ Shutdown session '{session_name}'")
56
+ except click.ClickException as e:
57
+ if not shutdown_all:
58
+ raise
59
+ click.echo(f"Error: {e.format_message()}", err=True)
@@ -0,0 +1,99 @@
1
+ """Skill management commands for CLI Agent Orchestrator."""
2
+
3
+ import shutil
4
+ from pathlib import Path
5
+
6
+ import click
7
+
8
+ from cli_agent_orchestrator.constants import SKILLS_DIR
9
+ from cli_agent_orchestrator.utils.skill_injection import refresh_all_cao_managed_agents
10
+ from cli_agent_orchestrator.utils.skills import (
11
+ list_skills,
12
+ validate_skill_folder,
13
+ validate_skill_name,
14
+ )
15
+
16
+
17
+ def _install_skill_folder(source_dir: Path, force: bool = False) -> Path:
18
+ """Validate and copy a skill folder into the local skill store."""
19
+ metadata = validate_skill_folder(source_dir)
20
+ skill_name = validate_skill_name(metadata.name)
21
+
22
+ SKILLS_DIR.mkdir(parents=True, exist_ok=True)
23
+ destination_dir = SKILLS_DIR / skill_name
24
+
25
+ if destination_dir.exists():
26
+ if not force:
27
+ raise FileExistsError(
28
+ f"Skill '{skill_name}' already exists. Use --force to overwrite it."
29
+ )
30
+ shutil.rmtree(destination_dir)
31
+
32
+ shutil.copytree(source_dir, destination_dir)
33
+ return destination_dir
34
+
35
+
36
+ def _refresh_installed_agents() -> None:
37
+ """Refresh baked prompts for installed CAO-managed Q/Copilot agents."""
38
+ try:
39
+ refreshed = refresh_all_cao_managed_agents()
40
+ except Exception as exc:
41
+ click.echo(f"Warning: failed to refresh installed agent prompts: {exc}", err=True)
42
+ return
43
+
44
+ if refreshed:
45
+ click.echo(f"Refreshed {len(refreshed)} installed agent(s)")
46
+
47
+
48
+ @click.group()
49
+ def skills():
50
+ """Manage installed skills."""
51
+
52
+
53
+ @skills.command("add")
54
+ @click.argument("folder_path", type=click.Path(exists=True, path_type=Path))
55
+ @click.option("--force", is_flag=True, help="Overwrite an existing installed skill.")
56
+ def add(folder_path: Path, force: bool) -> None:
57
+ """Install a skill from a local folder path."""
58
+ try:
59
+ destination_dir = _install_skill_folder(folder_path, force=force)
60
+ click.echo(f"Skill '{destination_dir.name}' installed successfully")
61
+ _refresh_installed_agents()
62
+ except Exception as exc:
63
+ raise click.ClickException(str(exc)) from exc
64
+
65
+
66
+ @skills.command("remove")
67
+ @click.argument("name")
68
+ def remove(name: str) -> None:
69
+ """Remove an installed skill."""
70
+ try:
71
+ skill_name = validate_skill_name(name)
72
+ skill_dir = SKILLS_DIR / skill_name
73
+ if not skill_dir.exists():
74
+ raise FileNotFoundError(f"Skill '{skill_name}' does not exist.")
75
+ if not skill_dir.is_dir():
76
+ raise ValueError(f"Skill path is not a directory: {skill_dir}")
77
+
78
+ shutil.rmtree(skill_dir)
79
+ click.echo(f"Skill '{skill_name}' removed successfully")
80
+ _refresh_installed_agents()
81
+ except Exception as exc:
82
+ raise click.ClickException(str(exc)) from exc
83
+
84
+
85
+ @skills.command("list")
86
+ def list_command() -> None:
87
+ """List installed skills."""
88
+ try:
89
+ installed_skills = list_skills()
90
+ if not installed_skills:
91
+ click.echo("No skills found")
92
+ return
93
+
94
+ click.echo(f"{'Name':<32} {'Description'}")
95
+ click.echo("-" * 100)
96
+ for skill in installed_skills:
97
+ click.echo(f"{skill.name:<32} {skill.description}")
98
+ except Exception as exc:
99
+ raise click.ClickException(str(exc)) from exc