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,186 @@
|
|
|
1
|
+
"""Base provider interface for CLI tool abstraction.
|
|
2
|
+
|
|
3
|
+
This module defines the abstract base class that all CLI providers must implement.
|
|
4
|
+
A "provider" is an adapter that enables CAO to interact with a specific CLI-based
|
|
5
|
+
AI agent (e.g., Kiro CLI, Claude Code, Codex, Q CLI).
|
|
6
|
+
|
|
7
|
+
Provider Responsibilities:
|
|
8
|
+
- Initialize the CLI tool in a tmux window (run startup commands)
|
|
9
|
+
- Detect terminal state by parsing terminal output (IDLE, PROCESSING, COMPLETED, etc.)
|
|
10
|
+
- Extract agent responses from terminal output
|
|
11
|
+
- Provide cleanup logic when terminal is deleted
|
|
12
|
+
|
|
13
|
+
Implemented Providers:
|
|
14
|
+
- KiroCliProvider: For Kiro CLI (kiro-cli chat)
|
|
15
|
+
- ClaudeCodeProvider: For Claude Code (claude)
|
|
16
|
+
- CodexProvider: For Codex CLI (codex)
|
|
17
|
+
- QCliProvider: For Amazon Q Developer CLI (q chat)
|
|
18
|
+
|
|
19
|
+
Each provider must implement pattern matching for its specific CLI's prompt
|
|
20
|
+
and output format to reliably detect status changes.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from abc import ABC, abstractmethod
|
|
24
|
+
from typing import List, Optional
|
|
25
|
+
|
|
26
|
+
from cli_agent_orchestrator.models.terminal import TerminalStatus
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class BaseProvider(ABC):
|
|
30
|
+
"""Abstract base class for CLI tool providers.
|
|
31
|
+
|
|
32
|
+
All CLI providers must inherit from this class and implement the abstract methods.
|
|
33
|
+
The provider abstraction allows CAO to work with different CLI-based AI agents
|
|
34
|
+
through a unified interface.
|
|
35
|
+
|
|
36
|
+
Attributes:
|
|
37
|
+
terminal_id: Unique identifier for the terminal this provider manages
|
|
38
|
+
session_name: Name of the tmux session containing the terminal
|
|
39
|
+
window_name: Name of the tmux window containing the terminal
|
|
40
|
+
_status: Internal status cache (use get_status() for current status)
|
|
41
|
+
_allowed_tools: CAO-vocabulary tool names this agent is allowed to use
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
terminal_id: str,
|
|
47
|
+
session_name: str,
|
|
48
|
+
window_name: str,
|
|
49
|
+
allowed_tools: Optional[List[str]] = None,
|
|
50
|
+
skill_prompt: Optional[str] = None,
|
|
51
|
+
):
|
|
52
|
+
"""Initialize provider with terminal context.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
terminal_id: Unique identifier for this terminal instance
|
|
56
|
+
session_name: Name of the tmux session
|
|
57
|
+
window_name: Name of the tmux window
|
|
58
|
+
allowed_tools: Optional list of CAO tool names the agent is allowed to use
|
|
59
|
+
skill_prompt: Optional skill catalog text built by the service layer.
|
|
60
|
+
Providers append this to the system prompt when building their CLI command.
|
|
61
|
+
"""
|
|
62
|
+
self.terminal_id = terminal_id
|
|
63
|
+
self.session_name = session_name
|
|
64
|
+
self.window_name = window_name
|
|
65
|
+
self._status = TerminalStatus.IDLE
|
|
66
|
+
self._allowed_tools: Optional[List[str]] = allowed_tools
|
|
67
|
+
self._skill_prompt: Optional[str] = skill_prompt
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def status(self) -> TerminalStatus:
|
|
71
|
+
"""Get current provider status."""
|
|
72
|
+
return self._status
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def paste_enter_count(self) -> int:
|
|
76
|
+
"""Number of Enter keys to send after pasting user input.
|
|
77
|
+
|
|
78
|
+
After bracketed paste (``paste-buffer -p``), many TUIs (e.g.
|
|
79
|
+
Claude Code) enter multi-line mode. The first Enter adds a
|
|
80
|
+
newline; the second Enter on the empty line triggers submission.
|
|
81
|
+
|
|
82
|
+
Default is 2 (double-Enter). Override to 1 for TUIs where single
|
|
83
|
+
Enter submits after bracketed paste.
|
|
84
|
+
"""
|
|
85
|
+
return 2
|
|
86
|
+
|
|
87
|
+
@abstractmethod
|
|
88
|
+
def initialize(self) -> bool:
|
|
89
|
+
"""Initialize the provider (e.g., start CLI tool, send setup commands).
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
bool: True if initialization successful, False otherwise
|
|
93
|
+
"""
|
|
94
|
+
pass
|
|
95
|
+
|
|
96
|
+
@abstractmethod
|
|
97
|
+
def get_status(self, tail_lines: Optional[int] = None) -> TerminalStatus:
|
|
98
|
+
"""Get current provider status by analyzing terminal output.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
tail_lines: Number of lines to capture from terminal (default: provider-specific)
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
TerminalStatus: Current status of the provider
|
|
105
|
+
"""
|
|
106
|
+
pass
|
|
107
|
+
|
|
108
|
+
@abstractmethod
|
|
109
|
+
def get_idle_pattern_for_log(self) -> str:
|
|
110
|
+
"""Get pattern that indicates IDLE state in log file output.
|
|
111
|
+
|
|
112
|
+
Used for quick detection in file watcher before calling full get_status().
|
|
113
|
+
Should return a simple pattern that appears in the IDLE prompt.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
str: Pattern to search for in log file tail
|
|
117
|
+
"""
|
|
118
|
+
pass
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def extraction_retries(self) -> int:
|
|
122
|
+
"""Number of extraction retries for transient TUI rendering issues.
|
|
123
|
+
|
|
124
|
+
TUI-based providers (e.g. Gemini CLI's Ink renderer) may show
|
|
125
|
+
notification spinners that temporarily obscure response text in
|
|
126
|
+
the tmux capture buffer. Override this to enable automatic retries
|
|
127
|
+
with re-capture between attempts. Default is 0 (no retries).
|
|
128
|
+
"""
|
|
129
|
+
return 0
|
|
130
|
+
|
|
131
|
+
@abstractmethod
|
|
132
|
+
def extract_last_message_from_script(self, script_output: str) -> str:
|
|
133
|
+
"""Extract the last message from terminal script output.
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
script_output: Raw terminal output/script content
|
|
137
|
+
|
|
138
|
+
Returns:
|
|
139
|
+
str: Extracted last message from the provider
|
|
140
|
+
"""
|
|
141
|
+
pass
|
|
142
|
+
|
|
143
|
+
@abstractmethod
|
|
144
|
+
def exit_cli(self) -> str:
|
|
145
|
+
"""Get the command to exit the provider CLI.
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
Command string to send to terminal for exiting
|
|
149
|
+
"""
|
|
150
|
+
pass
|
|
151
|
+
|
|
152
|
+
@abstractmethod
|
|
153
|
+
def cleanup(self) -> None:
|
|
154
|
+
"""Clean up provider resources."""
|
|
155
|
+
pass
|
|
156
|
+
|
|
157
|
+
def mark_input_received(self) -> None:
|
|
158
|
+
"""Notify the provider that external input was sent to the terminal.
|
|
159
|
+
|
|
160
|
+
Called by the terminal service after send_input() delivers a message.
|
|
161
|
+
Providers can override this to adjust status detection behavior.
|
|
162
|
+
For example, providers with initial prompts can use this to
|
|
163
|
+
distinguish post-init idle (ready for first input) from
|
|
164
|
+
post-task completed.
|
|
165
|
+
"""
|
|
166
|
+
pass
|
|
167
|
+
|
|
168
|
+
def _apply_skill_prompt(self, system_prompt: str) -> str:
|
|
169
|
+
"""Append skill catalog text to a system prompt if available.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
system_prompt: The base system prompt string.
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
The system prompt with skill catalog appended, or unchanged if
|
|
176
|
+
no skill_prompt was provided.
|
|
177
|
+
"""
|
|
178
|
+
if not self._skill_prompt:
|
|
179
|
+
return system_prompt
|
|
180
|
+
if system_prompt:
|
|
181
|
+
return f"{system_prompt}\n\n{self._skill_prompt}"
|
|
182
|
+
return self._skill_prompt
|
|
183
|
+
|
|
184
|
+
def _update_status(self, status: TerminalStatus) -> None:
|
|
185
|
+
"""Update internal status."""
|
|
186
|
+
self._status = status
|
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
"""Claude Code provider implementation."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import re
|
|
6
|
+
import shlex
|
|
7
|
+
import subprocess
|
|
8
|
+
import time
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
from cli_agent_orchestrator.clients.tmux import tmux_client
|
|
13
|
+
from cli_agent_orchestrator.models.terminal import TerminalStatus
|
|
14
|
+
from cli_agent_orchestrator.providers.base import BaseProvider
|
|
15
|
+
from cli_agent_orchestrator.utils.agent_profiles import load_agent_profile
|
|
16
|
+
from cli_agent_orchestrator.utils.terminal import wait_for_shell, wait_until_status
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# Custom exception for provider errors
|
|
22
|
+
class ProviderError(Exception):
|
|
23
|
+
"""Exception raised for provider-specific errors."""
|
|
24
|
+
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# Regex patterns for Claude Code output analysis
|
|
29
|
+
ANSI_CODE_PATTERN = r"\x1b\[[0-9;]*m"
|
|
30
|
+
RESPONSE_PATTERN = r"⏺(?:\x1b\[[0-9;]*m)*\s+" # Handle any ANSI codes between marker and text
|
|
31
|
+
# Match Claude Code processing spinners:
|
|
32
|
+
# - Old format: "✽ Cooking… (esc to interrupt)" / "✶ Thinking… (esc to interrupt)"
|
|
33
|
+
# - New format: "✽ Cooking… (6s · ↓ 174 tokens · thinking)"
|
|
34
|
+
# - Minimal format: "✻ Orbiting…" (no parenthesized status)
|
|
35
|
+
# Common: spinner char + text + ellipsis, optionally followed by parenthesized status
|
|
36
|
+
PROCESSING_PATTERN = r"[✶✢✽✻✳·].*\u2026"
|
|
37
|
+
# Structural PROCESSING indicator (reference pattern — get_status uses an
|
|
38
|
+
# inline last-separator-anchored version to avoid false positives from
|
|
39
|
+
# mid-conversation compaction events like "✢ Compacting conversation…"):
|
|
40
|
+
# a spinner line (spinner char + … ) immediately before the ────────
|
|
41
|
+
# separator, allowing 0–2 blank lines between them.
|
|
42
|
+
THINKING_BEFORE_SEPARATOR_PATTERN = re.compile(
|
|
43
|
+
r"[^\n]*[✶✢✽✻✳·][^\n]*\u2026[^\n]*\n(?:[^\n]*\n){0,2}(?:\x1b\[[0-9;]*m)*\u2500{20,}",
|
|
44
|
+
re.MULTILINE,
|
|
45
|
+
)
|
|
46
|
+
IDLE_PROMPT_PATTERN = r"[>❯][\s\xa0]" # Handle both old ">" and new "❯" prompt styles
|
|
47
|
+
WAITING_USER_ANSWER_PATTERN = (
|
|
48
|
+
r"↑/↓ to navigate" # Ink TUI footer shown only while a selection widget is active
|
|
49
|
+
)
|
|
50
|
+
TRUST_PROMPT_PATTERN = r"Yes, I trust this folder" # Workspace trust dialog
|
|
51
|
+
BYPASS_PROMPT_PATTERN = r"Yes, I accept" # Bypass permissions confirmation dialog
|
|
52
|
+
IDLE_PROMPT_PATTERN_LOG = r"[>❯][\s\xa0]" # Same pattern for log files
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ClaudeCodeProvider(BaseProvider):
|
|
56
|
+
"""Provider for Claude Code CLI tool integration."""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
terminal_id: str,
|
|
61
|
+
session_name: str,
|
|
62
|
+
window_name: str,
|
|
63
|
+
agent_profile: Optional[str] = None,
|
|
64
|
+
allowed_tools: Optional[list] = None,
|
|
65
|
+
skill_prompt: Optional[str] = None,
|
|
66
|
+
):
|
|
67
|
+
"""Initialize provider state."""
|
|
68
|
+
super().__init__(terminal_id, session_name, window_name, allowed_tools, skill_prompt)
|
|
69
|
+
self._initialized = False
|
|
70
|
+
self._agent_profile = agent_profile
|
|
71
|
+
|
|
72
|
+
def _build_claude_command(self) -> str:
|
|
73
|
+
"""Build Claude Code command with agent profile if provided.
|
|
74
|
+
|
|
75
|
+
Returns properly escaped shell command string that can be safely sent via tmux.
|
|
76
|
+
Uses shlex.join() to handle multiline strings and special characters correctly.
|
|
77
|
+
"""
|
|
78
|
+
# --dangerously-skip-permissions: bypass the workspace trust dialog and
|
|
79
|
+
# tool permission prompts. CAO already confirms workspace access during
|
|
80
|
+
# `cao launch` (or `--yolo`), so re-prompting each spawned agent
|
|
81
|
+
# (supervisor and worker) is redundant and blocks handoff/assign flows.
|
|
82
|
+
command_parts = ["claude", "--dangerously-skip-permissions"]
|
|
83
|
+
|
|
84
|
+
if self._agent_profile is not None:
|
|
85
|
+
try:
|
|
86
|
+
profile = load_agent_profile(self._agent_profile)
|
|
87
|
+
|
|
88
|
+
if profile.model:
|
|
89
|
+
command_parts.extend(["--model", profile.model])
|
|
90
|
+
|
|
91
|
+
# Add system prompt - escape newlines to prevent tmux chunking issues
|
|
92
|
+
system_prompt = profile.system_prompt if profile.system_prompt is not None else ""
|
|
93
|
+
system_prompt = self._apply_skill_prompt(system_prompt)
|
|
94
|
+
if system_prompt:
|
|
95
|
+
# Replace actual newlines with \n escape sequences
|
|
96
|
+
# This prevents tmux send_keys chunking from breaking the command
|
|
97
|
+
escaped_prompt = system_prompt.replace("\\", "\\\\").replace("\n", "\\n")
|
|
98
|
+
command_parts.extend(["--append-system-prompt", escaped_prompt])
|
|
99
|
+
|
|
100
|
+
# Add MCP config if present.
|
|
101
|
+
# Forward CAO_TERMINAL_ID so MCP servers (e.g. cao-mcp-server)
|
|
102
|
+
# can identify the current terminal for handoff/assign operations.
|
|
103
|
+
# Claude Code does not automatically forward parent shell env vars
|
|
104
|
+
# to MCP subprocesses, so we inject it explicitly via the env field.
|
|
105
|
+
if profile.mcpServers:
|
|
106
|
+
mcp_config = {}
|
|
107
|
+
for server_name, server_config in profile.mcpServers.items():
|
|
108
|
+
if isinstance(server_config, dict):
|
|
109
|
+
mcp_config[server_name] = dict(server_config)
|
|
110
|
+
else:
|
|
111
|
+
mcp_config[server_name] = server_config.model_dump(exclude_none=True)
|
|
112
|
+
|
|
113
|
+
env = mcp_config[server_name].get("env", {})
|
|
114
|
+
if "CAO_TERMINAL_ID" not in env:
|
|
115
|
+
env["CAO_TERMINAL_ID"] = self.terminal_id
|
|
116
|
+
mcp_config[server_name]["env"] = env
|
|
117
|
+
|
|
118
|
+
mcp_json = json.dumps({"mcpServers": mcp_config})
|
|
119
|
+
command_parts.extend(["--mcp-config", mcp_json])
|
|
120
|
+
|
|
121
|
+
except Exception as e:
|
|
122
|
+
raise ProviderError(f"Failed to load agent profile '{self._agent_profile}': {e}")
|
|
123
|
+
|
|
124
|
+
# Apply tool restrictions via --disallowedTools flags.
|
|
125
|
+
# --dangerously-skip-permissions bypasses prompts but --disallowedTools
|
|
126
|
+
# still prevents the agent from using the blocked tools entirely.
|
|
127
|
+
if self._allowed_tools and "*" not in self._allowed_tools:
|
|
128
|
+
from cli_agent_orchestrator.utils.tool_mapping import get_disallowed_tools
|
|
129
|
+
|
|
130
|
+
disallowed = get_disallowed_tools("claude_code", self._allowed_tools)
|
|
131
|
+
for tool in disallowed:
|
|
132
|
+
command_parts.extend(["--disallowedTools", tool])
|
|
133
|
+
|
|
134
|
+
# Use shlex.join() for proper shell escaping of all arguments
|
|
135
|
+
# This correctly handles multiline strings, quotes, and special characters
|
|
136
|
+
claude_cmd = shlex.join(command_parts)
|
|
137
|
+
|
|
138
|
+
# When cao-server runs inside a Claude Code session, CLAUDE* env vars
|
|
139
|
+
# leak into spawned tmux panes (via the tmux server's global env).
|
|
140
|
+
# Claude Code detects these and refuses to start ("nested session").
|
|
141
|
+
# Unset all matching vars except CLAUDE_CODE_USE_* and
|
|
142
|
+
# CLAUDE_CODE_SKIP_*_AUTH (needed for provider authentication:
|
|
143
|
+
# Bedrock, Vertex AI, Foundry).
|
|
144
|
+
unset_cmd = (
|
|
145
|
+
"unset $(env | sed -n 's/^\\(CLAUDE[A-Z_]*\\)=.*/\\1/p'"
|
|
146
|
+
" | grep -v -E 'CLAUDE_CODE_USE_(BEDROCK|VERTEX|FOUNDRY)"
|
|
147
|
+
"|CLAUDE_CODE_SKIP_(BEDROCK|VERTEX|FOUNDRY)_AUTH'"
|
|
148
|
+
") 2>/dev/null"
|
|
149
|
+
)
|
|
150
|
+
return f"{unset_cmd}; {claude_cmd}"
|
|
151
|
+
|
|
152
|
+
@staticmethod
|
|
153
|
+
def _ensure_skip_bypass_prompt_setting() -> None:
|
|
154
|
+
"""Ensure ``skipDangerousModePermissionPrompt`` is set in settings.
|
|
155
|
+
|
|
156
|
+
Claude Code (v2.1.41+) shows a bypass permissions confirmation dialog
|
|
157
|
+
on every launch with ``--dangerously-skip-permissions`` unless
|
|
158
|
+
``skipDangerousModePermissionPrompt: true`` is persisted in
|
|
159
|
+
``~/.claude/settings.json``. CAO already uses the flag intentionally,
|
|
160
|
+
so the confirmation is redundant and blocks initialization.
|
|
161
|
+
"""
|
|
162
|
+
settings_path = Path.home() / ".claude" / "settings.json"
|
|
163
|
+
settings: dict = {}
|
|
164
|
+
if settings_path.exists():
|
|
165
|
+
try:
|
|
166
|
+
with open(settings_path) as f:
|
|
167
|
+
settings = json.load(f)
|
|
168
|
+
except (json.JSONDecodeError, OSError):
|
|
169
|
+
pass
|
|
170
|
+
|
|
171
|
+
if settings.get("skipDangerousModePermissionPrompt") is True:
|
|
172
|
+
return
|
|
173
|
+
|
|
174
|
+
settings["skipDangerousModePermissionPrompt"] = True
|
|
175
|
+
settings_path.parent.mkdir(parents=True, exist_ok=True)
|
|
176
|
+
with open(settings_path, "w") as f:
|
|
177
|
+
json.dump(settings, f, indent=2)
|
|
178
|
+
logger.info("Set skipDangerousModePermissionPrompt in ~/.claude/settings.json")
|
|
179
|
+
|
|
180
|
+
def _handle_startup_prompts(self, timeout: float = 20.0) -> None:
|
|
181
|
+
"""Auto-accept startup prompts that may appear before the REPL is ready.
|
|
182
|
+
|
|
183
|
+
Claude Code may show up to two prompts during startup:
|
|
184
|
+
|
|
185
|
+
1. **Bypass permissions confirmation** (``--dangerously-skip-permissions``)
|
|
186
|
+
– shows "Yes, I accept" as option 2; requires ``Down`` + ``Enter``.
|
|
187
|
+
The settings-based fix (``_ensure_skip_bypass_prompt_setting``) prevents
|
|
188
|
+
this in most cases; this handler is a defensive fallback.
|
|
189
|
+
2. **Workspace trust dialog** – shows "Yes, I trust this folder";
|
|
190
|
+
requires ``Enter``.
|
|
191
|
+
"""
|
|
192
|
+
start_time = time.time()
|
|
193
|
+
bypass_accepted = False
|
|
194
|
+
while time.time() - start_time < timeout:
|
|
195
|
+
output = tmux_client.get_history(self.session_name, self.window_name)
|
|
196
|
+
if not output:
|
|
197
|
+
time.sleep(1.0)
|
|
198
|
+
continue
|
|
199
|
+
|
|
200
|
+
clean_output = re.sub(ANSI_CODE_PATTERN, "", output)
|
|
201
|
+
|
|
202
|
+
# 1) Handle bypass permissions prompt (appears before trust prompt).
|
|
203
|
+
# Only act once — the text stays in the buffer after dismissal.
|
|
204
|
+
if not bypass_accepted and re.search(BYPASS_PROMPT_PATTERN, clean_output):
|
|
205
|
+
logger.info("Bypass permissions prompt detected, auto-accepting")
|
|
206
|
+
target = f"{self.session_name}:{self.window_name}"
|
|
207
|
+
# Send raw Down arrow escape sequence (-l for literal) to move
|
|
208
|
+
# cursor to "Yes, I accept", then Enter to confirm.
|
|
209
|
+
# tmux send-keys "Down" doesn't work with Claude's Ink TUI.
|
|
210
|
+
subprocess.run(["tmux", "send-keys", "-t", target, "-l", "\x1b[B"], check=False)
|
|
211
|
+
time.sleep(0.5)
|
|
212
|
+
subprocess.run(["tmux", "send-keys", "-t", target, "Enter"], check=False)
|
|
213
|
+
bypass_accepted = True
|
|
214
|
+
time.sleep(1.0)
|
|
215
|
+
continue # Trust prompt may follow
|
|
216
|
+
|
|
217
|
+
# 2) Handle workspace trust prompt
|
|
218
|
+
if re.search(TRUST_PROMPT_PATTERN, clean_output):
|
|
219
|
+
logger.info("Workspace trust prompt detected, auto-accepting")
|
|
220
|
+
session = tmux_client.server.sessions.get(session_name=self.session_name)
|
|
221
|
+
window = session.windows.get(window_name=self.window_name)
|
|
222
|
+
pane = window.active_pane
|
|
223
|
+
if pane:
|
|
224
|
+
pane.send_keys("", enter=True)
|
|
225
|
+
return
|
|
226
|
+
|
|
227
|
+
# 3) Claude Code fully started — no prompts needed
|
|
228
|
+
if re.search(r"Welcome to|Claude Code v\d+", clean_output):
|
|
229
|
+
logger.info("Claude Code started without prompts")
|
|
230
|
+
return
|
|
231
|
+
if re.search(IDLE_PROMPT_PATTERN, clean_output):
|
|
232
|
+
logger.info("Claude Code idle prompt detected, no prompts needed")
|
|
233
|
+
return
|
|
234
|
+
|
|
235
|
+
time.sleep(1.0)
|
|
236
|
+
logger.warning("Startup prompt handler timed out")
|
|
237
|
+
|
|
238
|
+
def initialize(self) -> bool:
|
|
239
|
+
"""Initialize Claude Code provider by starting claude command."""
|
|
240
|
+
# Wait for shell prompt to appear in the tmux window
|
|
241
|
+
if not wait_for_shell(tmux_client, self.session_name, self.window_name, timeout=10.0):
|
|
242
|
+
raise TimeoutError("Shell initialization timed out after 10 seconds")
|
|
243
|
+
|
|
244
|
+
# Prevent bypass permissions dialog from appearing (settings-based fix).
|
|
245
|
+
self._ensure_skip_bypass_prompt_setting()
|
|
246
|
+
|
|
247
|
+
# Build properly escaped command string
|
|
248
|
+
command = self._build_claude_command()
|
|
249
|
+
|
|
250
|
+
# Snapshot current pane content before sending the command.
|
|
251
|
+
# We use this to distinguish the pre-existing shell ❯ prompt (zsh/bash)
|
|
252
|
+
# from Claude Code's own ❯ REPL prompt — they are visually identical
|
|
253
|
+
# after ANSI stripping, so without a snapshot, status detection can
|
|
254
|
+
# falsely return IDLE on the old shell prompt before claude even starts.
|
|
255
|
+
pre_launch_snapshot = tmux_client.get_history(self.session_name, self.window_name) or ""
|
|
256
|
+
|
|
257
|
+
# Send Claude Code command using tmux client
|
|
258
|
+
tmux_client.send_keys(self.session_name, self.window_name, command)
|
|
259
|
+
|
|
260
|
+
# Handle startup prompts (bypass permissions + workspace trust)
|
|
261
|
+
self._handle_startup_prompts(timeout=20.0)
|
|
262
|
+
|
|
263
|
+
# Wait for Claude Code prompt to be ready.
|
|
264
|
+
# Accept both IDLE and COMPLETED — some CLI versions show a startup
|
|
265
|
+
# message that get_status() interprets as a completed response.
|
|
266
|
+
#
|
|
267
|
+
# We require that new content appeared beyond the pre-launch snapshot
|
|
268
|
+
# before accepting IDLE, to avoid the false-positive where the old zsh
|
|
269
|
+
# ❯ prompt triggers an immediate IDLE return before claude starts.
|
|
270
|
+
deadline = time.time() + 30.0
|
|
271
|
+
while time.time() < deadline:
|
|
272
|
+
current_output = tmux_client.get_history(self.session_name, self.window_name) or ""
|
|
273
|
+
new_content = current_output[len(pre_launch_snapshot) :]
|
|
274
|
+
# Claude-specific startup markers that cannot come from the shell:
|
|
275
|
+
# the ──────── separator, bypass/trust prompt text, or "Claude Code"
|
|
276
|
+
claude_started = bool(
|
|
277
|
+
re.search(r"\u2500{20,}", new_content)
|
|
278
|
+
or re.search(
|
|
279
|
+
r"bypass permissions|trust this folder|Claude Code", new_content, re.IGNORECASE
|
|
280
|
+
)
|
|
281
|
+
)
|
|
282
|
+
if claude_started:
|
|
283
|
+
status = self.get_status()
|
|
284
|
+
if status in {TerminalStatus.IDLE, TerminalStatus.COMPLETED}:
|
|
285
|
+
break
|
|
286
|
+
time.sleep(1.0)
|
|
287
|
+
else:
|
|
288
|
+
raise TimeoutError("Claude Code initialization timed out after 30 seconds")
|
|
289
|
+
|
|
290
|
+
self._initialized = True
|
|
291
|
+
return True
|
|
292
|
+
|
|
293
|
+
def get_status(self, tail_lines: Optional[int] = None) -> TerminalStatus:
|
|
294
|
+
"""Get Claude Code status by analyzing terminal output.
|
|
295
|
+
|
|
296
|
+
Uses a structural "thinking-before-separator" check as the primary
|
|
297
|
+
PROCESSING indicator, plus position-based fallbacks for edge cases.
|
|
298
|
+
|
|
299
|
+
Bug history:
|
|
300
|
+
1. Stale-spinner bug (#104): Old spinner lines persist in the tmux
|
|
301
|
+
scrollback after the agent returns to idle (Claude Code renders
|
|
302
|
+
inline, not alt-screen, inside a tmux pane). Position comparison
|
|
303
|
+
of last spinner vs last idle prompt catches this.
|
|
304
|
+
|
|
305
|
+
2. Mid-tool-execution race (this issue): The ❯ input prompt is ALWAYS
|
|
306
|
+
rendered at the bottom of the tmux pane (last position in the
|
|
307
|
+
scrollback buffer). Position-based comparisons against ❯ are
|
|
308
|
+
therefore unreliable — last_idle.start() is always greater than
|
|
309
|
+
any other marker when anything has been typed/executed.
|
|
310
|
+
|
|
311
|
+
V3 fix (structural): Check whether any line containing … (U+2026,
|
|
312
|
+
the ellipsis used in all Claude Code thinking/spinner text) appears
|
|
313
|
+
immediately before the ──────── separator line. Claude Code draws
|
|
314
|
+
this separator between the active-execution area and the input prompt.
|
|
315
|
+
When the agent is thinking/processing:
|
|
316
|
+
"· Swirling… (thinking)\n\n──────────────────────\n❯ "
|
|
317
|
+
When idle or completed:
|
|
318
|
+
"some response text\n──────────────────────\n❯ "
|
|
319
|
+
A stale old spinner line far back in scrollback will NOT be
|
|
320
|
+
immediately before the separator, so the structural check is immune
|
|
321
|
+
to the stale-spinner false-positive.
|
|
322
|
+
|
|
323
|
+
See: https://github.com/awslabs/cli-agent-orchestrator/issues/104
|
|
324
|
+
"""
|
|
325
|
+
|
|
326
|
+
output = tmux_client.get_history(self.session_name, self.window_name, tail_lines=tail_lines)
|
|
327
|
+
|
|
328
|
+
if not output:
|
|
329
|
+
return TerminalStatus.ERROR
|
|
330
|
+
|
|
331
|
+
# PRIMARY PROCESSING check: walk backwards from the *last* separator.
|
|
332
|
+
# If we encounter a spinner line (spinner char + …) before we encounter
|
|
333
|
+
# another separator, the agent is actively processing.
|
|
334
|
+
# If we hit another separator first, the spinner belongs to a previously
|
|
335
|
+
# completed task — covers two distinct false-positive patterns:
|
|
336
|
+
# 1. Mid-conversation compaction: "✢ Compacting…" → sep → more output → last sep
|
|
337
|
+
# 2. Post-exit: live spinner → sep (task done) → ❯ /exit → last sep (exit menu)
|
|
338
|
+
_sep_re = re.compile(r"(?:\x1b\[[0-9;]*m)*\u2500{20,}")
|
|
339
|
+
_sep_positions = [m.start() for m in _sep_re.finditer(output)]
|
|
340
|
+
if _sep_positions:
|
|
341
|
+
pre_sep_lines = output[: _sep_positions[-1]].rstrip("\n").split("\n")
|
|
342
|
+
for line in reversed(pre_sep_lines):
|
|
343
|
+
if re.search(r"[✶✢✽✻✳·][^\n]*\u2026", line):
|
|
344
|
+
return TerminalStatus.PROCESSING # spinner before another separator
|
|
345
|
+
if _sep_re.search(line):
|
|
346
|
+
break # hit another separator first — spinner is from a completed task
|
|
347
|
+
|
|
348
|
+
# Find the LAST occurrence of each marker for fallback position checks.
|
|
349
|
+
last_processing = None
|
|
350
|
+
for m in re.finditer(PROCESSING_PATTERN, output):
|
|
351
|
+
last_processing = m
|
|
352
|
+
|
|
353
|
+
last_idle = None
|
|
354
|
+
for m in re.finditer(IDLE_PROMPT_PATTERN, output):
|
|
355
|
+
last_idle = m
|
|
356
|
+
|
|
357
|
+
last_response = None
|
|
358
|
+
for m in re.finditer(RESPONSE_PATTERN, output):
|
|
359
|
+
last_response = m
|
|
360
|
+
|
|
361
|
+
# FALLBACK PROCESSING: spinner visible AND no separator follows it yet
|
|
362
|
+
# (early in execution before the separator appears). Position comparison
|
|
363
|
+
# is used here only when no separator is present (safe case).
|
|
364
|
+
if last_processing and not re.search(r"\u2500{20,}", output):
|
|
365
|
+
if last_idle is None or last_processing.start() > last_idle.start():
|
|
366
|
+
return TerminalStatus.PROCESSING
|
|
367
|
+
|
|
368
|
+
# Check for waiting user answer via the active Ink selection footer.
|
|
369
|
+
# Exclude startup prompts (trust + bypass), which also render the footer.
|
|
370
|
+
if (
|
|
371
|
+
re.search(WAITING_USER_ANSWER_PATTERN, output)
|
|
372
|
+
and not re.search(TRUST_PROMPT_PATTERN, output)
|
|
373
|
+
and not re.search(BYPASS_PROMPT_PATTERN, output)
|
|
374
|
+
):
|
|
375
|
+
return TerminalStatus.WAITING_USER_ANSWER
|
|
376
|
+
|
|
377
|
+
# COMPLETED: ⏺ response exists AND ❯ prompt is visible (agent finished).
|
|
378
|
+
if last_response and last_idle:
|
|
379
|
+
return TerminalStatus.COMPLETED
|
|
380
|
+
|
|
381
|
+
# IDLE: shell prompt visible but no response yet (e.g. just initialized).
|
|
382
|
+
if last_idle:
|
|
383
|
+
return TerminalStatus.IDLE
|
|
384
|
+
|
|
385
|
+
return TerminalStatus.ERROR
|
|
386
|
+
|
|
387
|
+
def get_idle_pattern_for_log(self) -> str:
|
|
388
|
+
"""Return Claude Code IDLE prompt pattern for log files."""
|
|
389
|
+
return IDLE_PROMPT_PATTERN_LOG
|
|
390
|
+
|
|
391
|
+
def extract_last_message_from_script(self, script_output: str) -> str:
|
|
392
|
+
"""Extract Claude's final response message using ⏺ indicator."""
|
|
393
|
+
# Find all matches of response pattern
|
|
394
|
+
matches = list(re.finditer(RESPONSE_PATTERN, script_output))
|
|
395
|
+
|
|
396
|
+
if not matches:
|
|
397
|
+
raise ValueError("No Claude Code response found - no ⏺ pattern detected")
|
|
398
|
+
|
|
399
|
+
# Get the last match (final answer)
|
|
400
|
+
last_match = matches[-1]
|
|
401
|
+
start_pos = last_match.end()
|
|
402
|
+
|
|
403
|
+
# Extract everything after the last ⏺ until next prompt or separator
|
|
404
|
+
remaining_text = script_output[start_pos:]
|
|
405
|
+
|
|
406
|
+
# Split by lines and extract response
|
|
407
|
+
lines = remaining_text.split("\n")
|
|
408
|
+
response_lines = []
|
|
409
|
+
|
|
410
|
+
for line in lines:
|
|
411
|
+
# Stop at next > prompt or separator line
|
|
412
|
+
if re.match(r">\s", line) or "────────" in line:
|
|
413
|
+
break
|
|
414
|
+
|
|
415
|
+
# Clean the line
|
|
416
|
+
clean_line = line.strip()
|
|
417
|
+
response_lines.append(clean_line)
|
|
418
|
+
|
|
419
|
+
if not response_lines or not any(line.strip() for line in response_lines):
|
|
420
|
+
raise ValueError("Empty Claude Code response - no content found after ⏺")
|
|
421
|
+
|
|
422
|
+
# Join lines and clean up
|
|
423
|
+
final_answer = "\n".join(response_lines).strip()
|
|
424
|
+
# Remove ANSI codes from the final message
|
|
425
|
+
final_answer = re.sub(ANSI_CODE_PATTERN, "", final_answer)
|
|
426
|
+
return final_answer.strip()
|
|
427
|
+
|
|
428
|
+
def exit_cli(self) -> str:
|
|
429
|
+
"""Get the command to exit Claude Code."""
|
|
430
|
+
return "/exit"
|
|
431
|
+
|
|
432
|
+
def cleanup(self) -> None:
|
|
433
|
+
"""Clean up Claude Code provider."""
|
|
434
|
+
self._initialized = False
|