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 @@
1
+
@@ -0,0 +1,60 @@
1
+ """Environment variable management commands for CLI Agent Orchestrator."""
2
+
3
+ import click
4
+
5
+ from cli_agent_orchestrator.constants import CAO_ENV_FILE
6
+ from cli_agent_orchestrator.utils.env import (
7
+ list_env_vars,
8
+ load_env_vars,
9
+ set_env_var,
10
+ unset_env_var,
11
+ )
12
+
13
+
14
+ @click.group(name="env", invoke_without_command=True)
15
+ @click.pass_context
16
+ def env(ctx: click.Context) -> None:
17
+ """Manage CAO environment variables."""
18
+ if ctx.invoked_subcommand is None:
19
+ click.echo(ctx.get_help())
20
+
21
+
22
+ @env.command("set")
23
+ @click.argument("key")
24
+ @click.argument("value")
25
+ def env_set(key: str, value: str) -> None:
26
+ """Set a managed environment variable."""
27
+ set_env_var(key, value)
28
+ click.echo(f"✓ Set {key} in {CAO_ENV_FILE}")
29
+
30
+
31
+ @env.command("get")
32
+ @click.argument("key")
33
+ def env_get(key: str) -> None:
34
+ """Get a managed environment variable."""
35
+ value = load_env_vars().get(key)
36
+ if value is None:
37
+ click.echo(f"Error: Environment variable '{key}' not found.", err=True)
38
+ raise click.exceptions.Exit(1)
39
+
40
+ click.echo(value)
41
+
42
+
43
+ @env.command("list")
44
+ def env_list() -> None:
45
+ """List managed environment variables."""
46
+ env_vars = list_env_vars()
47
+ if not env_vars:
48
+ click.echo(f"No env vars set in {CAO_ENV_FILE}")
49
+ return
50
+
51
+ for key, value in env_vars.items():
52
+ click.echo(f"{key}={value}")
53
+
54
+
55
+ @env.command("unset")
56
+ @click.argument("key")
57
+ def env_unset(key: str) -> None:
58
+ """Unset a managed environment variable."""
59
+ unset_env_var(key)
60
+ click.echo(f"✓ Unset {key} in {CAO_ENV_FILE}")
@@ -0,0 +1,102 @@
1
+ """Flow commands for CLI Agent Orchestrator."""
2
+
3
+ from datetime import datetime
4
+
5
+ import click
6
+
7
+ from cli_agent_orchestrator.clients.database import init_db
8
+ from cli_agent_orchestrator.services import flow_service
9
+
10
+
11
+ @click.group()
12
+ def flow():
13
+ """Manage scheduled agent flows."""
14
+ # Ensure database is initialized
15
+ init_db()
16
+
17
+
18
+ @flow.command()
19
+ @click.argument("file_path", type=click.Path(exists=True))
20
+ def add(file_path):
21
+ """Add a flow from file."""
22
+ try:
23
+ flow = flow_service.add_flow(file_path)
24
+ click.echo(f"Flow '{flow.name}' added successfully")
25
+ click.echo(f" Schedule: {flow.schedule}")
26
+ click.echo(f" Agent: {flow.agent_profile}")
27
+ click.echo(f" Next run: {flow.next_run}")
28
+ except Exception as e:
29
+ raise click.ClickException(str(e))
30
+
31
+
32
+ @flow.command()
33
+ def list():
34
+ """List all flows."""
35
+ try:
36
+ flows = flow_service.list_flows()
37
+ if not flows:
38
+ click.echo("No flows found")
39
+ return
40
+
41
+ click.echo(
42
+ f"{'Name':<20} {'Schedule':<15} {'Agent':<15} {'Last Run':<20} {'Next Run':<20} {'Enabled':<8}"
43
+ )
44
+ click.echo("-" * 110)
45
+
46
+ for f in flows:
47
+ last_run = f.last_run.strftime("%Y-%m-%d %H:%M") if f.last_run else "Never"
48
+ next_run = f.next_run.strftime("%Y-%m-%d %H:%M") if f.next_run else "N/A"
49
+ enabled = "Yes" if f.enabled else "No"
50
+
51
+ click.echo(
52
+ f"{f.name:<20} {f.schedule:<15} {f.agent_profile:<15} {last_run:<20} {next_run:<20} {enabled:<8}"
53
+ )
54
+ except Exception as e:
55
+ raise click.ClickException(str(e))
56
+
57
+
58
+ @flow.command()
59
+ @click.argument("name")
60
+ def remove(name):
61
+ """Remove a flow."""
62
+ try:
63
+ flow_service.remove_flow(name)
64
+ click.echo(f"Flow '{name}' removed successfully")
65
+ except Exception as e:
66
+ raise click.ClickException(str(e))
67
+
68
+
69
+ @flow.command()
70
+ @click.argument("name")
71
+ def disable(name):
72
+ """Disable a flow."""
73
+ try:
74
+ flow_service.disable_flow(name)
75
+ click.echo(f"Flow '{name}' disabled")
76
+ except Exception as e:
77
+ raise click.ClickException(str(e))
78
+
79
+
80
+ @flow.command()
81
+ @click.argument("name")
82
+ def enable(name):
83
+ """Enable a flow."""
84
+ try:
85
+ flow_service.enable_flow(name)
86
+ click.echo(f"Flow '{name}' enabled")
87
+ except Exception as e:
88
+ raise click.ClickException(str(e))
89
+
90
+
91
+ @flow.command()
92
+ @click.argument("name")
93
+ def run(name):
94
+ """Manually run a flow."""
95
+ try:
96
+ executed = flow_service.execute_flow(name)
97
+ if executed:
98
+ click.echo(f"Flow '{name}' executed successfully")
99
+ else:
100
+ click.echo(f"Flow '{name}' skipped (execute=false)")
101
+ except Exception as e:
102
+ raise click.ClickException(str(e))
@@ -0,0 +1,57 @@
1
+ """Info command for CLI Agent Orchestrator CLI."""
2
+
3
+ import subprocess
4
+
5
+ import click
6
+ import requests
7
+
8
+ from cli_agent_orchestrator.constants import (
9
+ DATABASE_FILE,
10
+ SERVER_HOST,
11
+ SERVER_PORT,
12
+ SESSION_PREFIX,
13
+ )
14
+
15
+
16
+ @click.command()
17
+ def info():
18
+ """Display information about the current session."""
19
+ try:
20
+ # Display database path
21
+ click.echo(f"Database path: {DATABASE_FILE}")
22
+
23
+ # Try to get current session name from tmux
24
+ session_name = None
25
+ try:
26
+ result = subprocess.run(
27
+ ["tmux", "display-message", "-p", "#S"],
28
+ capture_output=True,
29
+ text=True,
30
+ check=True,
31
+ )
32
+ session_name = result.stdout.strip()
33
+ except (subprocess.CalledProcessError, FileNotFoundError):
34
+ pass
35
+
36
+ if session_name and session_name.startswith(SESSION_PREFIX):
37
+ try:
38
+ # Call API to get session details
39
+ url = f"http://{SERVER_HOST}:{SERVER_PORT}/sessions/{session_name}"
40
+ response = requests.get(url)
41
+
42
+ if response.status_code == 200:
43
+ data = response.json()
44
+ terminals = data.get("terminals", [])
45
+ click.echo(f"Session ID: {session_name}")
46
+ click.echo(f"Active terminals: {len(terminals)}")
47
+ else:
48
+ click.echo(
49
+ f"Session ID: {session_name} (Warning: Session not found in CAO server)"
50
+ )
51
+ except requests.exceptions.RequestException:
52
+ click.echo(f"Session ID: {session_name} (Warning: Could not connect to CAO server)")
53
+ else:
54
+ click.echo("Not currently in a CAO session.")
55
+
56
+ except Exception as e:
57
+ raise click.ClickException(str(e))
@@ -0,0 +1,45 @@
1
+ """Init command for CLI Agent Orchestrator CLI."""
2
+
3
+ import shutil
4
+ from importlib import resources
5
+ from pathlib import Path
6
+
7
+ import click
8
+
9
+ from cli_agent_orchestrator.clients.database import init_db
10
+ from cli_agent_orchestrator.constants import SKILLS_DIR
11
+
12
+
13
+ def seed_default_skills() -> int:
14
+ """Seed builtin skills (cao-supervisor-protocols, cao-worker-protocols) into the local skill store."""
15
+ SKILLS_DIR.mkdir(parents=True, exist_ok=True)
16
+ bundled_skills = resources.files("cli_agent_orchestrator.skills")
17
+ seeded_count = 0
18
+
19
+ for skill_dir in bundled_skills.iterdir():
20
+ if not skill_dir.is_dir() or not (skill_dir / "SKILL.md").is_file():
21
+ continue
22
+
23
+ destination_dir = SKILLS_DIR / skill_dir.name
24
+ if destination_dir.exists():
25
+ continue
26
+
27
+ with resources.as_file(skill_dir) as source_dir:
28
+ shutil.copytree(Path(source_dir), destination_dir)
29
+ seeded_count += 1
30
+
31
+ return seeded_count
32
+
33
+
34
+ @click.command()
35
+ def init():
36
+ """Initialize CLI Agent Orchestrator database."""
37
+ try:
38
+ init_db()
39
+ seeded_count = seed_default_skills()
40
+ click.echo(
41
+ f"CLI Agent Orchestrator initialized successfully. "
42
+ f"Seeded {seeded_count} builtin skills."
43
+ )
44
+ except Exception as e:
45
+ raise click.ClickException(str(e))
@@ -0,0 +1,317 @@
1
+ """Install command for CLI Agent Orchestrator."""
2
+
3
+ import re
4
+ from importlib import resources
5
+ from pathlib import Path
6
+
7
+ import click
8
+ import frontmatter
9
+ import requests # type: ignore[import-untyped]
10
+
11
+ from cli_agent_orchestrator.constants import (
12
+ AGENT_CONTEXT_DIR,
13
+ CAO_ENV_FILE,
14
+ COPILOT_AGENTS_DIR,
15
+ DEFAULT_PROVIDER,
16
+ KIRO_AGENTS_DIR,
17
+ LOCAL_AGENT_STORE_DIR,
18
+ OPENCODE_AGENTS_DIR,
19
+ PROVIDERS,
20
+ Q_AGENTS_DIR,
21
+ SKILLS_DIR,
22
+ )
23
+ from cli_agent_orchestrator.models.copilot_agent import CopilotAgentConfig
24
+ from cli_agent_orchestrator.models.kiro_agent import KiroAgentConfig
25
+ from cli_agent_orchestrator.models.opencode_agent import OpenCodeAgentConfig
26
+ from cli_agent_orchestrator.models.provider import ProviderType
27
+ from cli_agent_orchestrator.models.q_agent import QAgentConfig
28
+ from cli_agent_orchestrator.utils.agent_profiles import parse_agent_profile_text
29
+ from cli_agent_orchestrator.utils.env import resolve_env_vars, set_env_var
30
+ from cli_agent_orchestrator.utils.opencode_config import (
31
+ ensure_skills_symlink,
32
+ remove_agent_tools,
33
+ to_opencode_agent_id,
34
+ translate_mcp_server_config,
35
+ upsert_agent_tools,
36
+ upsert_mcp_server,
37
+ )
38
+ from cli_agent_orchestrator.utils.opencode_permissions import cao_tools_to_opencode_permission
39
+ from cli_agent_orchestrator.utils.skill_injection import compose_agent_prompt
40
+
41
+
42
+ def _download_agent(source: str) -> str:
43
+ """Download or copy agent file to local store. Returns agent name."""
44
+ LOCAL_AGENT_STORE_DIR.mkdir(parents=True, exist_ok=True)
45
+
46
+ # Handle URL
47
+ if source.startswith("http://") or source.startswith("https://"):
48
+ response = requests.get(source)
49
+ response.raise_for_status()
50
+ content = response.text
51
+
52
+ # Extract filename from URL
53
+ filename = Path(source).name
54
+ if not filename.endswith(".md"):
55
+ raise ValueError("URL must point to a .md file")
56
+
57
+ dest_file = LOCAL_AGENT_STORE_DIR / filename
58
+ dest_file.write_text(content)
59
+
60
+ # Return agent name (filename without .md)
61
+ return dest_file.stem
62
+
63
+ # Handle file path
64
+ source_path = Path(source)
65
+ if source_path.exists():
66
+ if not source_path.suffix == ".md":
67
+ raise ValueError("File must be a .md file")
68
+
69
+ dest_file = LOCAL_AGENT_STORE_DIR / source_path.name
70
+ dest_file.write_text(source_path.read_text())
71
+
72
+ # Return agent name (filename without .md)
73
+ return dest_file.stem
74
+
75
+ raise FileNotFoundError(f"Source not found: {source}")
76
+
77
+
78
+ def _parse_env_assignment(env_assignment: str) -> tuple[str, str]:
79
+ """Parse a ``KEY=VALUE`` env assignment for install-time injection."""
80
+ if "=" not in env_assignment:
81
+ raise click.BadParameter(
82
+ f"Invalid env var '{env_assignment}'. Expected format KEY=VALUE.", param_hint="--env"
83
+ )
84
+
85
+ key, value = env_assignment.split("=", 1)
86
+ if not key:
87
+ raise click.BadParameter(
88
+ f"Invalid env var '{env_assignment}'. Key must not be empty.", param_hint="--env"
89
+ )
90
+ return key, value
91
+
92
+
93
+ @click.command()
94
+ @click.argument("agent_source")
95
+ @click.option(
96
+ "--provider",
97
+ type=click.Choice(PROVIDERS),
98
+ default=DEFAULT_PROVIDER,
99
+ help=f"Provider to use (default: {DEFAULT_PROVIDER})",
100
+ )
101
+ @click.option(
102
+ "--env",
103
+ "env_vars",
104
+ multiple=True,
105
+ help=(
106
+ "Set env vars before installing the agent. Values are stored in "
107
+ "~/.aws/cli-agent-orchestrator/.env and can be referenced in profiles as ${VAR}. "
108
+ "Repeatable: --env KEY=VALUE. Example: --env API_TOKEN=my-secret-token."
109
+ ),
110
+ )
111
+ def install(agent_source: str, provider: str, env_vars: tuple[str, ...]):
112
+ """
113
+ Install an agent from local store, built-in store, URL, or file path.
114
+
115
+ AGENT_SOURCE can be:
116
+ - Agent name (e.g., 'developer', 'code_supervisor')
117
+ - File path (e.g., './my-agent.md', '/path/to/agent.md')
118
+ - URL (e.g., 'https://example.com/agent.md')
119
+
120
+ Profiles can reference values from ~/.aws/cli-agent-orchestrator/.env using ${VAR}
121
+ placeholders in frontmatter or markdown content. Use `cao env set KEY VALUE` to
122
+ manage those values separately, or pass `--env KEY=VALUE` during install to write
123
+ them before the profile is loaded.
124
+
125
+ Example:
126
+ \b
127
+ cao install ./service-agent.md --provider claude_code \
128
+ --env API_TOKEN=my-secret-token \
129
+ --env SERVICE_URL=http://127.0.0.1:27124
130
+ """
131
+ try:
132
+ # Detect source type and handle accordingly
133
+ if agent_source.startswith("http://") or agent_source.startswith("https://"):
134
+ # Download from URL
135
+ agent_name = _download_agent(agent_source)
136
+ click.echo(f"✓ Downloaded agent from URL to local store")
137
+ elif Path(agent_source).exists():
138
+ # Copy from file path
139
+ agent_name = _download_agent(agent_source)
140
+ click.echo(f"✓ Copied agent from file to local store")
141
+ else:
142
+ # Treat as agent name
143
+ agent_name = agent_source
144
+
145
+ for env_assignment in env_vars:
146
+ key, value = _parse_env_assignment(env_assignment)
147
+ set_env_var(key, value)
148
+
149
+ # Determine source file for the agent profile
150
+ local_profile = LOCAL_AGENT_STORE_DIR / f"{agent_name}.md"
151
+ if local_profile.exists():
152
+ source_file = local_profile
153
+ else:
154
+ agent_store = resources.files("cli_agent_orchestrator.agent_store")
155
+ source_file = agent_store / f"{agent_name}.md"
156
+
157
+ # Read source once; resolve for in-memory profile, keep raw for context file
158
+ raw_content = source_file.read_text()
159
+ resolved_content = resolve_env_vars(raw_content)
160
+ profile = parse_agent_profile_text(resolved_content, agent_name)
161
+
162
+ # Warn about unresolved placeholders that will leak into provider configs
163
+ unresolved = set(re.findall(r"\$\{(\w+)\}", resolved_content))
164
+ if unresolved:
165
+ names = ", ".join(sorted(unresolved))
166
+ click.echo(
167
+ f"⚠ Unresolved env var(s) in profile: {names}. "
168
+ f"Set them with `cao env set` or pass --env KEY=VALUE.",
169
+ err=True,
170
+ )
171
+
172
+ # Write unresolved source to agent-context (secrets stay in .env)
173
+ AGENT_CONTEXT_DIR.mkdir(parents=True, exist_ok=True)
174
+ dest_file = AGENT_CONTEXT_DIR / f"{profile.name}.md"
175
+ dest_file.write_text(raw_content)
176
+
177
+ # Resolve allowedTools from profile → role defaults → developer defaults
178
+ from cli_agent_orchestrator.utils.tool_mapping import resolve_allowed_tools
179
+
180
+ mcp_server_names = list(profile.mcpServers.keys()) if profile.mcpServers else None
181
+ allowed_tools = resolve_allowed_tools(profile.allowedTools, profile.role, mcp_server_names)
182
+
183
+ # Create agent config based on provider
184
+ agent_file = None
185
+ if provider == ProviderType.Q_CLI.value:
186
+ Q_AGENTS_DIR.mkdir(parents=True, exist_ok=True)
187
+ agent_config = QAgentConfig(
188
+ name=profile.name,
189
+ description=profile.description,
190
+ tools=profile.tools if profile.tools is not None else ["*"],
191
+ allowedTools=allowed_tools,
192
+ resources=[f"file://{dest_file.absolute()}"],
193
+ prompt=compose_agent_prompt(profile),
194
+ mcpServers=profile.mcpServers,
195
+ toolAliases=profile.toolAliases,
196
+ toolsSettings=profile.toolsSettings,
197
+ hooks=profile.hooks,
198
+ model=profile.model,
199
+ )
200
+ safe_filename = profile.name.replace("/", "__")
201
+ agent_file = Q_AGENTS_DIR / f"{safe_filename}.json"
202
+ agent_file.write_text(
203
+ agent_config.model_dump_json(indent=2, exclude_none=True), encoding="utf-8"
204
+ )
205
+
206
+ elif provider == ProviderType.KIRO_CLI.value:
207
+ KIRO_AGENTS_DIR.mkdir(parents=True, exist_ok=True)
208
+ # Kiro natively supports skill:// resources with progressive loading
209
+ # (metadata at startup, full content on demand).
210
+ kiro_resources = [
211
+ f"file://{dest_file.absolute()}",
212
+ f"skill://{SKILLS_DIR}/**/SKILL.md",
213
+ ]
214
+ raw_prompt = (
215
+ profile.prompt.strip() if profile.prompt and profile.prompt.strip() else None
216
+ )
217
+ agent_config = KiroAgentConfig(
218
+ name=profile.name,
219
+ description=profile.description,
220
+ tools=profile.tools if profile.tools is not None else ["*"],
221
+ allowedTools=allowed_tools,
222
+ resources=kiro_resources,
223
+ prompt=raw_prompt,
224
+ mcpServers=profile.mcpServers,
225
+ toolAliases=profile.toolAliases,
226
+ toolsSettings=profile.toolsSettings,
227
+ hooks=profile.hooks,
228
+ model=profile.model,
229
+ )
230
+ safe_filename = profile.name.replace("/", "__")
231
+ agent_file = KIRO_AGENTS_DIR / f"{safe_filename}.json"
232
+ agent_file.write_text(
233
+ agent_config.model_dump_json(indent=2, exclude_none=True), encoding="utf-8"
234
+ )
235
+
236
+ elif provider == ProviderType.COPILOT_CLI.value:
237
+ COPILOT_AGENTS_DIR.mkdir(parents=True, exist_ok=True)
238
+ system_prompt = profile.system_prompt.strip() if profile.system_prompt else ""
239
+ fallback_prompt = profile.prompt.strip() if profile.prompt else ""
240
+ base_prompt = system_prompt or fallback_prompt
241
+ if not base_prompt:
242
+ raise ValueError(
243
+ f"Agent '{profile.name}' has no usable prompt content for Copilot "
244
+ "(both system_prompt and prompt are empty or whitespace)"
245
+ )
246
+
247
+ # Bake skill catalog into the agent prompt body (same as Kiro/Q)
248
+ prompt = compose_agent_prompt(profile, base_prompt=base_prompt) or base_prompt
249
+
250
+ safe_filename = profile.name.replace("/", "__")
251
+ agent_file = COPILOT_AGENTS_DIR / f"{safe_filename}.agent.md"
252
+ agent_config = CopilotAgentConfig(
253
+ name=profile.name,
254
+ description=profile.description,
255
+ prompt=prompt,
256
+ )
257
+ agent_post = frontmatter.Post(
258
+ prompt.rstrip(),
259
+ name=agent_config.name,
260
+ description=agent_config.description,
261
+ )
262
+ agent_file.write_text(frontmatter.dumps(agent_post), encoding="utf-8")
263
+
264
+ elif provider == ProviderType.OPENCODE_CLI.value:
265
+ OPENCODE_AGENTS_DIR.mkdir(parents=True, exist_ok=True)
266
+ ensure_skills_symlink()
267
+ # Use the raw profile prompt as the body — skills are delivered natively
268
+ # via OpenCode's skill tool through the OPENCODE_CONFIG_DIR/skills symlink.
269
+ # compose_agent_prompt is NOT called here so the skill catalog stays out
270
+ # of the system prompt.
271
+ body = profile.system_prompt or profile.prompt or ""
272
+ agent_config = OpenCodeAgentConfig(
273
+ description=profile.description,
274
+ mode="all",
275
+ permission=cao_tools_to_opencode_permission(allowed_tools),
276
+ )
277
+ agent_id = to_opencode_agent_id(profile.name)
278
+ agent_file = OPENCODE_AGENTS_DIR / f"{agent_id}.md"
279
+ agent_post = frontmatter.Post(
280
+ body.rstrip() if body else "",
281
+ **agent_config.model_dump(exclude_none=True),
282
+ )
283
+ agent_file.write_text(frontmatter.dumps(agent_post), encoding="utf-8")
284
+
285
+ # Upsert MCP server declarations and per-agent tool gating into opencode.json.
286
+ # When a profile no longer declares MCP servers, explicitly strip any stale
287
+ # agent.<id>.tools entry from a previous install so revoked grants do not
288
+ # survive a reinstall.
289
+ if profile.mcpServers:
290
+ mcp_names = list(profile.mcpServers.keys())
291
+ for mcp_name, mcp_cfg in profile.mcpServers.items():
292
+ # Translate CAO's mcpServer format to OpenCode's opencode.json format
293
+ # before writing (type:stdio+command str+args → type:local+command list).
294
+ opencode_mcp_cfg = translate_mcp_server_config(dict(mcp_cfg))
295
+ upsert_mcp_server(mcp_name, opencode_mcp_cfg)
296
+ upsert_agent_tools(agent_id, mcp_names)
297
+ else:
298
+ remove_agent_tools(agent_id)
299
+
300
+ click.echo(f"✓ Agent '{profile.name}' installed successfully")
301
+ if env_vars:
302
+ click.echo(f"✓ Set {len(env_vars)} env var(s) in {CAO_ENV_FILE}")
303
+ click.echo(f"✓ Context file: {dest_file}")
304
+ if agent_file:
305
+ click.echo(f"✓ {provider} agent: {agent_file}")
306
+
307
+ except click.BadParameter:
308
+ raise
309
+ except FileNotFoundError as e:
310
+ click.echo(f"Error: {e}", err=True)
311
+ return
312
+ except requests.RequestException as e:
313
+ click.echo(f"Error: Failed to download agent: {e}", err=True)
314
+ return
315
+ except Exception as e:
316
+ click.echo(f"Error: Failed to install agent: {e}", err=True)
317
+ return