autohelix 0.0.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.
- autohelix/__init__.py +11 -0
- autohelix/agents/__init__.py +153 -0
- autohelix/agents/claudecode.py +303 -0
- autohelix/agents/codex.py +207 -0
- autohelix/agents/mock.py +116 -0
- autohelix/agents/opencode.py +144 -0
- autohelix/agents/runner.py +146 -0
- autohelix/bin/check_notes.sh +85 -0
- autohelix/bin/claude_hook_time_left.sh +52 -0
- autohelix/bin/opencode_timer_pertool.js +70 -0
- autohelix/bin/time_left.sh +50 -0
- autohelix/checks.py +354 -0
- autohelix/cli.py +707 -0
- autohelix/config.py +448 -0
- autohelix/dashboard.py +532 -0
- autohelix/display.py +224 -0
- autohelix/formatting.py +32 -0
- autohelix/harness.py +1240 -0
- autohelix/history.py +173 -0
- autohelix/iteration_time.py +91 -0
- autohelix/parallel/__init__.py +14 -0
- autohelix/parallel/core.py +340 -0
- autohelix/parallel/display.py +134 -0
- autohelix/prompt_template.py +128 -0
- autohelix/run_log.py +40 -0
- autohelix/sandbox.py +467 -0
- autohelix/state.py +153 -0
- autohelix/templates/__init__.py +2 -0
- autohelix/templates/config_template.yaml +41 -0
- autohelix/templates/default_prompt.md +63 -0
- autohelix-0.0.1.dist-info/METADATA +345 -0
- autohelix-0.0.1.dist-info/RECORD +36 -0
- autohelix-0.0.1.dist-info/WHEEL +4 -0
- autohelix-0.0.1.dist-info/entry_points.txt +2 -0
- autohelix-0.0.1.dist-info/licenses/LICENSE +176 -0
- autohelix-0.0.1.dist-info/licenses/NOTICE +2 -0
autohelix/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""AutoHelix - Minimal harness for autonomous code improvement agents."""
|
|
5
|
+
|
|
6
|
+
from autohelix.config import Config, ConfigIssue, load_config
|
|
7
|
+
from autohelix.harness import Harness
|
|
8
|
+
from autohelix.history import History
|
|
9
|
+
|
|
10
|
+
__version__ = "0.1.0"
|
|
11
|
+
__all__ = ["Config", "ConfigIssue", "load_config", "Harness", "History"]
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Agent backends for AutoHelix."""
|
|
5
|
+
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from enum import StrEnum
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Callable, Protocol
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AgentEventKind(StrEnum):
|
|
13
|
+
"""Normalized event kinds emitted by agent backends."""
|
|
14
|
+
|
|
15
|
+
STATUS = "status"
|
|
16
|
+
THINKING = "thinking"
|
|
17
|
+
ASSISTANT_TEXT = "assistant_text"
|
|
18
|
+
TOOL_USE = "tool_use"
|
|
19
|
+
TOOL_INPUT = "tool_input"
|
|
20
|
+
TOOL_RESULT = "tool_result"
|
|
21
|
+
WARNING = "warning"
|
|
22
|
+
ERROR = "error"
|
|
23
|
+
RAW = "raw"
|
|
24
|
+
RESULT = "result"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class RequireNotesConfig:
|
|
29
|
+
"""Enforce that the agent writes iteration notes before finishing (claude only).
|
|
30
|
+
|
|
31
|
+
Implemented via a Stop hook that blocks the agent from ending its turn until
|
|
32
|
+
the iteration's notes file has at least `min_chars` non-whitespace characters,
|
|
33
|
+
re-prompting up to `max_retries` times before giving up.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
min_chars: int = 50
|
|
37
|
+
max_retries: int = 3
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class AgentConfig:
|
|
42
|
+
"""Configuration for an agent backend."""
|
|
43
|
+
|
|
44
|
+
type: str = "claude"
|
|
45
|
+
command: str | None = None
|
|
46
|
+
model: str | None = None
|
|
47
|
+
reasoning_effort: str | None = None
|
|
48
|
+
timeout_seconds: int | None = None
|
|
49
|
+
settings: dict[str, Any] = field(default_factory=dict)
|
|
50
|
+
extra_args: list[str] = field(default_factory=list)
|
|
51
|
+
auto_memory: bool = False # Disabled by default; set true to enable Claude Code's built-in memory
|
|
52
|
+
require_notes: RequireNotesConfig | None = None
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def from_dict(cls, data: dict[str, Any] | None) -> "AgentConfig":
|
|
56
|
+
"""Build an agent config from YAML data."""
|
|
57
|
+
data = data or {}
|
|
58
|
+
|
|
59
|
+
settings = data.get("settings", {})
|
|
60
|
+
if not isinstance(settings, dict):
|
|
61
|
+
settings = {}
|
|
62
|
+
|
|
63
|
+
extra_args = data.get("extra_args", [])
|
|
64
|
+
if isinstance(extra_args, str):
|
|
65
|
+
extra_args = [extra_args]
|
|
66
|
+
elif not isinstance(extra_args, list):
|
|
67
|
+
extra_args = []
|
|
68
|
+
|
|
69
|
+
auto_memory = bool(data.get("auto_memory", False))
|
|
70
|
+
|
|
71
|
+
# require_notes: bare True -> defaults; dict -> overrides; falsey/absent -> off
|
|
72
|
+
require_notes: RequireNotesConfig | None = None
|
|
73
|
+
raw_require_notes = data.get("require_notes")
|
|
74
|
+
if isinstance(raw_require_notes, dict):
|
|
75
|
+
require_notes = RequireNotesConfig(
|
|
76
|
+
min_chars=int(raw_require_notes.get("min_chars", 50)),
|
|
77
|
+
max_retries=int(raw_require_notes.get("max_retries", 3)),
|
|
78
|
+
)
|
|
79
|
+
elif raw_require_notes: # True (or any truthy scalar)
|
|
80
|
+
require_notes = RequireNotesConfig()
|
|
81
|
+
|
|
82
|
+
return cls(
|
|
83
|
+
type=str(data.get("type", "claude")),
|
|
84
|
+
command=data.get("command"),
|
|
85
|
+
model=data.get("model"),
|
|
86
|
+
reasoning_effort=data.get("reasoning_effort"),
|
|
87
|
+
timeout_seconds=data.get("timeout_seconds"),
|
|
88
|
+
settings=settings,
|
|
89
|
+
extra_args=[str(arg) for arg in extra_args],
|
|
90
|
+
auto_memory=auto_memory,
|
|
91
|
+
require_notes=require_notes,
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass
|
|
96
|
+
class AgentEvent:
|
|
97
|
+
"""A normalized backend event suitable for display."""
|
|
98
|
+
|
|
99
|
+
kind: AgentEventKind | str
|
|
100
|
+
text: str = ""
|
|
101
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass
|
|
105
|
+
class AgentRunResult:
|
|
106
|
+
"""Result from running an agent backend."""
|
|
107
|
+
|
|
108
|
+
success: bool
|
|
109
|
+
exit_code: int | None = None
|
|
110
|
+
error: str | None = None
|
|
111
|
+
usage: dict[str, Any] = field(default_factory=dict)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
EventCallback = Callable[[AgentEvent], None]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class AgentBackend(Protocol):
|
|
118
|
+
"""Runtime interface implemented by each backend."""
|
|
119
|
+
|
|
120
|
+
display_name: str
|
|
121
|
+
|
|
122
|
+
def run(
|
|
123
|
+
self,
|
|
124
|
+
worktree_path: Path,
|
|
125
|
+
prompt: str,
|
|
126
|
+
iteration: int,
|
|
127
|
+
log_path: Path,
|
|
128
|
+
event_callback: EventCallback,
|
|
129
|
+
project_path: Path | None = None,
|
|
130
|
+
) -> AgentRunResult:
|
|
131
|
+
"""Execute the agent inside the given worktree."""
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def create_agent(config: AgentConfig, heartbeat_seconds: int = 30) -> AgentBackend:
|
|
135
|
+
"""Create an agent backend from configuration."""
|
|
136
|
+
agent_type = config.type.lower()
|
|
137
|
+
if agent_type == "claude":
|
|
138
|
+
from autohelix.agents.claudecode import ClaudeCodeAgent
|
|
139
|
+
|
|
140
|
+
return ClaudeCodeAgent(config=config, heartbeat_seconds=heartbeat_seconds)
|
|
141
|
+
if agent_type == "codex":
|
|
142
|
+
from autohelix.agents.codex import CodexAgent
|
|
143
|
+
|
|
144
|
+
return CodexAgent(config=config, heartbeat_seconds=heartbeat_seconds)
|
|
145
|
+
if agent_type == "opencode":
|
|
146
|
+
from autohelix.agents.opencode import OpenCodeAgent
|
|
147
|
+
|
|
148
|
+
return OpenCodeAgent(config=config, heartbeat_seconds=heartbeat_seconds)
|
|
149
|
+
if agent_type == "mock":
|
|
150
|
+
from autohelix.agents.mock import MockAgent
|
|
151
|
+
|
|
152
|
+
return MockAgent(config=config, heartbeat_seconds=heartbeat_seconds)
|
|
153
|
+
raise ValueError(f"Unsupported agent type: {config.type}")
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Claude Code backend."""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from autohelix.agents import AgentConfig, AgentEvent, AgentEventKind, AgentRunResult, EventCallback
|
|
12
|
+
from autohelix.agents.runner import format_timeout_seconds, run_process
|
|
13
|
+
from autohelix.sandbox import build_worktree_env
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ClaudeCodeAgent:
|
|
17
|
+
"""Run Claude Code as the AutoHelix agent backend."""
|
|
18
|
+
|
|
19
|
+
display_name = "Claude Code"
|
|
20
|
+
|
|
21
|
+
def __init__(self, config: AgentConfig, heartbeat_seconds: int = 30):
|
|
22
|
+
self.config = config
|
|
23
|
+
self.heartbeat_seconds = heartbeat_seconds
|
|
24
|
+
self._tool_names: dict[int, str] = {}
|
|
25
|
+
self._tool_inputs: dict[int, str] = {}
|
|
26
|
+
self._active_kind: AgentEventKind | None = None
|
|
27
|
+
self._active_text = ""
|
|
28
|
+
self._active_metadata: dict[str, object] = {}
|
|
29
|
+
self._usage: dict[str, object] = {}
|
|
30
|
+
self._incremental_input: int = 0
|
|
31
|
+
self._incremental_output: int = 0
|
|
32
|
+
|
|
33
|
+
def _command_path(self) -> str:
|
|
34
|
+
if self.config.command:
|
|
35
|
+
return self.config.command
|
|
36
|
+
|
|
37
|
+
env_command = os.environ.get("AUTOHELIX_CLAUDE_CMD")
|
|
38
|
+
if env_command:
|
|
39
|
+
return env_command
|
|
40
|
+
|
|
41
|
+
resolved_claude = shutil.which("claude")
|
|
42
|
+
if resolved_claude:
|
|
43
|
+
return resolved_claude
|
|
44
|
+
|
|
45
|
+
return "claude"
|
|
46
|
+
|
|
47
|
+
def _build_command(self, prompt: str) -> list[str]:
|
|
48
|
+
cmd = [
|
|
49
|
+
self._command_path(),
|
|
50
|
+
"--print",
|
|
51
|
+
"--verbose",
|
|
52
|
+
"--output-format",
|
|
53
|
+
"stream-json",
|
|
54
|
+
"--include-partial-messages",
|
|
55
|
+
"--dangerously-skip-permissions",
|
|
56
|
+
]
|
|
57
|
+
if self.config.model:
|
|
58
|
+
cmd.extend(["--model", self.config.model])
|
|
59
|
+
if self.config.reasoning_effort:
|
|
60
|
+
cmd.extend(["--effort", self.config.reasoning_effort])
|
|
61
|
+
# If autohelix has prepared a settings file with our hooks (e.g. the
|
|
62
|
+
# time_left injector), load it via --settings without touching the user
|
|
63
|
+
# ~/.claude/settings.json.
|
|
64
|
+
autohelix_settings = os.environ.get("AUTOHELIX_CLAUDE_SETTINGS")
|
|
65
|
+
if autohelix_settings and os.path.exists(autohelix_settings):
|
|
66
|
+
cmd.extend(["--settings", autohelix_settings])
|
|
67
|
+
cmd.extend(self.config.extra_args)
|
|
68
|
+
cmd.append(prompt)
|
|
69
|
+
return cmd
|
|
70
|
+
|
|
71
|
+
def _emit_stream(
|
|
72
|
+
self,
|
|
73
|
+
event_callback: EventCallback,
|
|
74
|
+
kind: AgentEventKind,
|
|
75
|
+
text: str,
|
|
76
|
+
**metadata: object,
|
|
77
|
+
) -> None:
|
|
78
|
+
self._active_kind = kind
|
|
79
|
+
self._active_text = text
|
|
80
|
+
self._active_metadata = dict(metadata)
|
|
81
|
+
stream_metadata = {"stream": True, **metadata}
|
|
82
|
+
event_callback(AgentEvent(kind=kind, text=text, metadata=stream_metadata))
|
|
83
|
+
|
|
84
|
+
def _flush_stream(self, event_callback: EventCallback) -> None:
|
|
85
|
+
if self._active_kind is None or not self._active_text:
|
|
86
|
+
self._active_kind = None
|
|
87
|
+
self._active_text = ""
|
|
88
|
+
self._active_metadata = {}
|
|
89
|
+
return
|
|
90
|
+
final_metadata = {"final": True, **self._active_metadata}
|
|
91
|
+
event_callback(AgentEvent(kind=self._active_kind, text=self._active_text, metadata=final_metadata))
|
|
92
|
+
self._active_kind = None
|
|
93
|
+
self._active_text = ""
|
|
94
|
+
self._active_metadata = {}
|
|
95
|
+
|
|
96
|
+
def _emit(self, event_callback: EventCallback, kind: AgentEventKind, text: str, **metadata: object) -> None:
|
|
97
|
+
if text:
|
|
98
|
+
event_callback(AgentEvent(kind=kind, text=text, metadata=metadata))
|
|
99
|
+
|
|
100
|
+
def _handle_line(self, line: str, event_callback: EventCallback) -> None:
|
|
101
|
+
try:
|
|
102
|
+
payload = json.loads(line)
|
|
103
|
+
except json.JSONDecodeError:
|
|
104
|
+
self._emit(event_callback, AgentEventKind.RAW, line)
|
|
105
|
+
return
|
|
106
|
+
|
|
107
|
+
event_type = payload.get("type")
|
|
108
|
+
|
|
109
|
+
if event_type == "system":
|
|
110
|
+
subtype = payload.get("subtype", "event")
|
|
111
|
+
model = payload.get("model")
|
|
112
|
+
detail = f" model={model}" if model else ""
|
|
113
|
+
self._emit(event_callback, AgentEventKind.STATUS, f"{subtype}{detail}")
|
|
114
|
+
return
|
|
115
|
+
|
|
116
|
+
if event_type == "stream_event":
|
|
117
|
+
event = payload.get("event", {})
|
|
118
|
+
stream_type = event.get("type")
|
|
119
|
+
if stream_type == "content_block_start":
|
|
120
|
+
content_block = event.get("content_block", {})
|
|
121
|
+
block_type = content_block.get("type")
|
|
122
|
+
if block_type == "tool_use":
|
|
123
|
+
tool_name = content_block.get("name", "Tool")
|
|
124
|
+
index = event.get("index")
|
|
125
|
+
if isinstance(index, int):
|
|
126
|
+
self._tool_names[index] = tool_name
|
|
127
|
+
self._tool_inputs[index] = ""
|
|
128
|
+
self._emit(event_callback, AgentEventKind.TOOL_USE, tool_name)
|
|
129
|
+
elif stream_type == "content_block_delta":
|
|
130
|
+
delta = event.get("delta", {})
|
|
131
|
+
delta_type = delta.get("type")
|
|
132
|
+
if delta_type == "text_delta":
|
|
133
|
+
text = delta.get("text", "")
|
|
134
|
+
if text:
|
|
135
|
+
current = self._active_text + text if self._active_kind == AgentEventKind.ASSISTANT_TEXT else text
|
|
136
|
+
self._emit_stream(event_callback, AgentEventKind.ASSISTANT_TEXT, current)
|
|
137
|
+
elif delta_type == "thinking_delta":
|
|
138
|
+
text = delta.get("thinking", "")
|
|
139
|
+
if text:
|
|
140
|
+
current = self._active_text + text if self._active_kind == AgentEventKind.THINKING else text
|
|
141
|
+
self._emit_stream(event_callback, AgentEventKind.THINKING, current)
|
|
142
|
+
elif delta_type == "input_json_delta":
|
|
143
|
+
index = event.get("index")
|
|
144
|
+
if isinstance(index, int):
|
|
145
|
+
tool_name = self._tool_names.get(index, "tool")
|
|
146
|
+
current = self._tool_inputs.get(index, "") + str(delta.get("partial_json", ""))
|
|
147
|
+
self._tool_inputs[index] = current
|
|
148
|
+
self._emit_stream(event_callback, AgentEventKind.TOOL_INPUT, current, tool_name=tool_name)
|
|
149
|
+
elif delta_type == "signature_delta":
|
|
150
|
+
signature = delta.get("signature", "")
|
|
151
|
+
if signature:
|
|
152
|
+
self._emit(event_callback, AgentEventKind.STATUS, f"signature {len(signature)} chars")
|
|
153
|
+
elif stream_type in {"content_block_stop", "message_stop"}:
|
|
154
|
+
self._flush_stream(event_callback)
|
|
155
|
+
elif stream_type == "message_start":
|
|
156
|
+
message = event.get("message", {})
|
|
157
|
+
msg_usage = message.get("usage", {})
|
|
158
|
+
input_tokens = msg_usage.get("input_tokens", 0)
|
|
159
|
+
if input_tokens:
|
|
160
|
+
self._incremental_input += input_tokens
|
|
161
|
+
elif stream_type == "message_delta":
|
|
162
|
+
self._flush_stream(event_callback)
|
|
163
|
+
event_usage = event.get("usage", {})
|
|
164
|
+
output_tokens = event_usage.get("output_tokens", 0)
|
|
165
|
+
if output_tokens:
|
|
166
|
+
self._incremental_output += output_tokens
|
|
167
|
+
delta = event.get("delta", {})
|
|
168
|
+
stop_reason = delta.get("stop_reason")
|
|
169
|
+
if stop_reason:
|
|
170
|
+
self._emit(event_callback, AgentEventKind.STATUS, f"stop_reason={stop_reason}")
|
|
171
|
+
return
|
|
172
|
+
|
|
173
|
+
if event_type == "assistant":
|
|
174
|
+
message = payload.get("message", {})
|
|
175
|
+
if isinstance(message, dict):
|
|
176
|
+
for block in message.get("content", []):
|
|
177
|
+
if not isinstance(block, dict):
|
|
178
|
+
continue
|
|
179
|
+
if block.get("type") == "tool_use":
|
|
180
|
+
name = block.get("name", "Tool")
|
|
181
|
+
tool_input = block.get("input", {})
|
|
182
|
+
text = json.dumps(tool_input, ensure_ascii=False, sort_keys=True)
|
|
183
|
+
self._emit(event_callback, AgentEventKind.TOOL_INPUT, text, tool_name=name)
|
|
184
|
+
return
|
|
185
|
+
|
|
186
|
+
if event_type == "user":
|
|
187
|
+
message = payload.get("message", {})
|
|
188
|
+
if isinstance(message, dict):
|
|
189
|
+
for block in message.get("content", []):
|
|
190
|
+
if not isinstance(block, dict) or block.get("type") != "tool_result":
|
|
191
|
+
continue
|
|
192
|
+
text = str(block.get("content") or "").strip()
|
|
193
|
+
if text:
|
|
194
|
+
self._emit(
|
|
195
|
+
event_callback,
|
|
196
|
+
AgentEventKind.TOOL_RESULT,
|
|
197
|
+
text,
|
|
198
|
+
is_error=bool(block.get("is_error")),
|
|
199
|
+
)
|
|
200
|
+
return
|
|
201
|
+
|
|
202
|
+
tool_result = payload.get("tool_use_result")
|
|
203
|
+
if isinstance(tool_result, str):
|
|
204
|
+
self._emit(event_callback, AgentEventKind.TOOL_RESULT, tool_result.strip())
|
|
205
|
+
return
|
|
206
|
+
if isinstance(tool_result, dict):
|
|
207
|
+
summary = self._summarize_tool_result(tool_result)
|
|
208
|
+
self._emit(event_callback, AgentEventKind.TOOL_RESULT, summary)
|
|
209
|
+
return
|
|
210
|
+
|
|
211
|
+
if event_type == "result":
|
|
212
|
+
subtype = payload.get("subtype", "unknown")
|
|
213
|
+
duration_ms = payload.get("duration_ms")
|
|
214
|
+
duration_text = f" in {duration_ms}ms" if duration_ms is not None else ""
|
|
215
|
+
# Extract usage/cost data
|
|
216
|
+
cost_usd = payload.get("total_cost_usd")
|
|
217
|
+
usage = payload.get("usage", {})
|
|
218
|
+
if isinstance(usage, dict):
|
|
219
|
+
if usage.get("input_tokens"):
|
|
220
|
+
self._usage["input_tokens"] = usage["input_tokens"]
|
|
221
|
+
if usage.get("output_tokens"):
|
|
222
|
+
self._usage["output_tokens"] = usage["output_tokens"]
|
|
223
|
+
if cost_usd is not None:
|
|
224
|
+
self._usage["cost_usd"] = cost_usd
|
|
225
|
+
if duration_ms is not None:
|
|
226
|
+
self._usage["duration_ms"] = duration_ms
|
|
227
|
+
cost_text = f" ${cost_usd:.4f}" if cost_usd is not None else ""
|
|
228
|
+
self._emit(event_callback, AgentEventKind.RESULT, f"{subtype}{duration_text}{cost_text}")
|
|
229
|
+
|
|
230
|
+
def _summarize_tool_result(self, tool_result: dict) -> str:
|
|
231
|
+
stdout = str(tool_result.get("stdout") or "").strip()
|
|
232
|
+
stderr = str(tool_result.get("stderr") or "").strip()
|
|
233
|
+
if stdout:
|
|
234
|
+
return stdout
|
|
235
|
+
if stderr:
|
|
236
|
+
return stderr
|
|
237
|
+
file_path = tool_result.get("filePath")
|
|
238
|
+
if file_path:
|
|
239
|
+
return f"updated {file_path}"
|
|
240
|
+
file_obj = tool_result.get("file")
|
|
241
|
+
if isinstance(file_obj, dict):
|
|
242
|
+
nested_path = file_obj.get("filePath", "file")
|
|
243
|
+
total_lines = file_obj.get("totalLines")
|
|
244
|
+
suffix = f" ({total_lines} lines)" if total_lines else ""
|
|
245
|
+
return f"read {nested_path}{suffix}"
|
|
246
|
+
return json.dumps(tool_result, ensure_ascii=False, sort_keys=True)
|
|
247
|
+
|
|
248
|
+
def run(
|
|
249
|
+
self,
|
|
250
|
+
worktree_path: Path,
|
|
251
|
+
prompt: str,
|
|
252
|
+
iteration: int,
|
|
253
|
+
log_path: Path,
|
|
254
|
+
event_callback: EventCallback,
|
|
255
|
+
project_path: Path | None = None,
|
|
256
|
+
) -> AgentRunResult:
|
|
257
|
+
self._tool_names.clear()
|
|
258
|
+
self._tool_inputs.clear()
|
|
259
|
+
self._active_kind = None
|
|
260
|
+
self._active_text = ""
|
|
261
|
+
self._active_metadata = {}
|
|
262
|
+
self._usage = {}
|
|
263
|
+
self._incremental_input = 0
|
|
264
|
+
self._incremental_output = 0
|
|
265
|
+
|
|
266
|
+
# Build env with remapped PYTHONPATH for worktree
|
|
267
|
+
env = build_worktree_env(project_path, worktree_path) if project_path else None
|
|
268
|
+
if not self.config.auto_memory:
|
|
269
|
+
env = env or os.environ.copy()
|
|
270
|
+
env["CLAUDE_CODE_DISABLE_AUTO_MEMORY"] = "1"
|
|
271
|
+
|
|
272
|
+
try:
|
|
273
|
+
result = run_process(
|
|
274
|
+
cmd=self._build_command(prompt),
|
|
275
|
+
cwd=worktree_path,
|
|
276
|
+
log_path=log_path,
|
|
277
|
+
line_callback=lambda line: self._handle_line(line, event_callback),
|
|
278
|
+
heartbeat_seconds=self.heartbeat_seconds,
|
|
279
|
+
timeout_seconds=self.config.timeout_seconds,
|
|
280
|
+
env=env,
|
|
281
|
+
)
|
|
282
|
+
except FileNotFoundError:
|
|
283
|
+
command = self._command_path()
|
|
284
|
+
return AgentRunResult(
|
|
285
|
+
success=False,
|
|
286
|
+
exit_code=None,
|
|
287
|
+
error=f"'{command}' not found. Set AUTOHELIX_CLAUDE_CMD or agent.command.",
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
if result.timed_out:
|
|
291
|
+
event_callback(
|
|
292
|
+
AgentEvent(
|
|
293
|
+
kind=AgentEventKind.WARNING,
|
|
294
|
+
text=f"Agent {format_timeout_seconds(self.config.timeout_seconds)}",
|
|
295
|
+
)
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
if not self._usage.get("input_tokens") and self._incremental_input:
|
|
299
|
+
self._usage["input_tokens"] = self._incremental_input
|
|
300
|
+
if not self._usage.get("output_tokens") and self._incremental_output:
|
|
301
|
+
self._usage["output_tokens"] = self._incremental_output
|
|
302
|
+
|
|
303
|
+
return AgentRunResult(success=result.exit_code == 0, exit_code=result.exit_code, usage=self._usage)
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Codex CLI backend."""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import subprocess
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from autohelix.agents import AgentConfig, AgentEvent, AgentEventKind, AgentRunResult, EventCallback
|
|
13
|
+
from autohelix.agents.runner import format_timeout_seconds, run_process
|
|
14
|
+
from autohelix.sandbox import build_worktree_env
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CodexAgent:
|
|
18
|
+
"""Run Codex CLI as the AutoHelix agent backend."""
|
|
19
|
+
|
|
20
|
+
display_name = "Codex"
|
|
21
|
+
_MIN_HOOK_VERSION = (0, 141, 0)
|
|
22
|
+
|
|
23
|
+
def __init__(self, config: AgentConfig, heartbeat_seconds: int = 30):
|
|
24
|
+
self.config = config
|
|
25
|
+
self.heartbeat_seconds = heartbeat_seconds
|
|
26
|
+
self._usage: dict[str, object] = {}
|
|
27
|
+
|
|
28
|
+
def _command_path(self) -> str:
|
|
29
|
+
return self.config.command or os.environ.get("AUTOHELIX_CODEX_CMD") or "codex"
|
|
30
|
+
|
|
31
|
+
@staticmethod
|
|
32
|
+
def _parse_version(text: str) -> tuple[int, int, int] | None:
|
|
33
|
+
match = re.search(r"codex(?:-cli)?\s+(\d+)\.(\d+)\.(\d+)", text, re.IGNORECASE)
|
|
34
|
+
if not match:
|
|
35
|
+
match = re.search(r"(\d+)\.(\d+)\.(\d+)", text)
|
|
36
|
+
if not match:
|
|
37
|
+
return None
|
|
38
|
+
return tuple(int(part) for part in match.groups())
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def _format_version(cls, version: tuple[int, int, int]) -> str:
|
|
42
|
+
return ".".join(str(part) for part in version)
|
|
43
|
+
|
|
44
|
+
def _time_left_hook_path(self) -> str | None:
|
|
45
|
+
return os.environ.get("AUTOHELIX_CODEX_TIME_LEFT_HOOK") or None
|
|
46
|
+
|
|
47
|
+
def _time_left_hook_args(self, hook_path: str) -> list[str]:
|
|
48
|
+
command = json.dumps(hook_path)
|
|
49
|
+
hook = f'{{type="command",command={command},timeout=5}}'
|
|
50
|
+
return [
|
|
51
|
+
"--dangerously-bypass-hook-trust",
|
|
52
|
+
"-c",
|
|
53
|
+
f'hooks.PostToolUse=[{{matcher="",hooks=[{hook}]}}]',
|
|
54
|
+
"-c",
|
|
55
|
+
f"hooks.UserPromptSubmit=[{{hooks=[{hook}]}}]",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
def _validate_time_left_hook_support(self, hook_path: str) -> str | None:
|
|
59
|
+
if not Path(hook_path).exists():
|
|
60
|
+
return f"Codex time-left hook not found: {hook_path}"
|
|
61
|
+
|
|
62
|
+
command = self._command_path()
|
|
63
|
+
try:
|
|
64
|
+
result = subprocess.run(
|
|
65
|
+
[command, "--version"],
|
|
66
|
+
capture_output=True,
|
|
67
|
+
text=True,
|
|
68
|
+
timeout=5,
|
|
69
|
+
)
|
|
70
|
+
except FileNotFoundError:
|
|
71
|
+
return f"'{command}' not found. Set AUTOHELIX_CODEX_CMD or agent.command."
|
|
72
|
+
except subprocess.TimeoutExpired:
|
|
73
|
+
return f"Could not verify Codex CLI version: '{command} --version' timed out."
|
|
74
|
+
|
|
75
|
+
output = f"{result.stdout}\n{result.stderr}".strip()
|
|
76
|
+
version = self._parse_version(output)
|
|
77
|
+
required = self._format_version(self._MIN_HOOK_VERSION)
|
|
78
|
+
if version is None:
|
|
79
|
+
return (
|
|
80
|
+
"budget.iteration_time for Codex requires codex-cli "
|
|
81
|
+
f">= {required}; could not parse version from: {output or '<empty>'}"
|
|
82
|
+
)
|
|
83
|
+
if version < self._MIN_HOOK_VERSION:
|
|
84
|
+
found = self._format_version(version)
|
|
85
|
+
return (
|
|
86
|
+
"budget.iteration_time for Codex requires codex-cli "
|
|
87
|
+
f">= {required}; found {found}. Upgrade Codex or remove budget.iteration_time."
|
|
88
|
+
)
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
def _build_command(self, prompt: str) -> list[str]:
|
|
92
|
+
cmd = [
|
|
93
|
+
self._command_path(),
|
|
94
|
+
"exec",
|
|
95
|
+
"--json",
|
|
96
|
+
"--dangerously-bypass-approvals-and-sandbox",
|
|
97
|
+
]
|
|
98
|
+
if self.config.model:
|
|
99
|
+
cmd.extend(["--model", self.config.model])
|
|
100
|
+
if self.config.reasoning_effort:
|
|
101
|
+
cmd.extend(["-c", f'model_reasoning_effort="{self.config.reasoning_effort}"'])
|
|
102
|
+
for key, value in self.config.settings.items():
|
|
103
|
+
cmd.extend(["-c", f"{key}={json.dumps(value)}"])
|
|
104
|
+
time_left_hook = self._time_left_hook_path()
|
|
105
|
+
if time_left_hook:
|
|
106
|
+
cmd.extend(self._time_left_hook_args(time_left_hook))
|
|
107
|
+
cmd.extend(self.config.extra_args)
|
|
108
|
+
cmd.append(prompt)
|
|
109
|
+
return cmd
|
|
110
|
+
|
|
111
|
+
def _emit(self, event_callback: EventCallback, kind: AgentEventKind, text: str, **metadata: object) -> None:
|
|
112
|
+
if text:
|
|
113
|
+
event_callback(AgentEvent(kind=kind, text=text, metadata=metadata))
|
|
114
|
+
|
|
115
|
+
def _handle_line(self, line: str, event_callback: EventCallback) -> None:
|
|
116
|
+
try:
|
|
117
|
+
payload = json.loads(line)
|
|
118
|
+
except json.JSONDecodeError:
|
|
119
|
+
self._emit(event_callback, AgentEventKind.RAW, line)
|
|
120
|
+
return
|
|
121
|
+
|
|
122
|
+
event_type = payload.get("type")
|
|
123
|
+
if event_type in {"thread.started", "turn.started"}:
|
|
124
|
+
self._emit(event_callback, AgentEventKind.STATUS, event_type)
|
|
125
|
+
return
|
|
126
|
+
if event_type == "turn.completed":
|
|
127
|
+
usage = payload.get("usage", {})
|
|
128
|
+
if isinstance(usage, dict):
|
|
129
|
+
if usage.get("input_tokens"):
|
|
130
|
+
self._usage["input_tokens"] = usage["input_tokens"]
|
|
131
|
+
if usage.get("output_tokens"):
|
|
132
|
+
self._usage["output_tokens"] = usage["output_tokens"]
|
|
133
|
+
if usage:
|
|
134
|
+
self._emit(event_callback, AgentEventKind.RESULT, json.dumps(usage, sort_keys=True))
|
|
135
|
+
else:
|
|
136
|
+
self._emit(event_callback, AgentEventKind.RESULT, "turn.completed")
|
|
137
|
+
return
|
|
138
|
+
if event_type in {"item.started", "item.completed"}:
|
|
139
|
+
item = payload.get("item", {})
|
|
140
|
+
if not isinstance(item, dict):
|
|
141
|
+
return
|
|
142
|
+
item_type = item.get("type")
|
|
143
|
+
if item_type == "agent_message":
|
|
144
|
+
self._emit(event_callback, AgentEventKind.ASSISTANT_TEXT, str(item.get("text", "")).strip())
|
|
145
|
+
return
|
|
146
|
+
if item_type == "command_execution":
|
|
147
|
+
command = str(item.get("command", "")).strip()
|
|
148
|
+
if event_type == "item.started":
|
|
149
|
+
self._emit(event_callback, AgentEventKind.TOOL_USE, command)
|
|
150
|
+
return
|
|
151
|
+
output = str(item.get("aggregated_output", "")).strip()
|
|
152
|
+
status = str(item.get("status", "")).strip()
|
|
153
|
+
exit_code = item.get("exit_code")
|
|
154
|
+
if output:
|
|
155
|
+
self._emit(event_callback, AgentEventKind.TOOL_RESULT, output, exit_code=exit_code, status=status)
|
|
156
|
+
else:
|
|
157
|
+
self._emit(
|
|
158
|
+
event_callback,
|
|
159
|
+
AgentEventKind.TOOL_RESULT,
|
|
160
|
+
f"{command} exited with status={status} exit_code={exit_code}",
|
|
161
|
+
)
|
|
162
|
+
return
|
|
163
|
+
self._emit(event_callback, AgentEventKind.STATUS, f"{event_type}:{item_type}")
|
|
164
|
+
return
|
|
165
|
+
|
|
166
|
+
self._emit(event_callback, AgentEventKind.STATUS, event_type or "event")
|
|
167
|
+
|
|
168
|
+
def run(
|
|
169
|
+
self,
|
|
170
|
+
worktree_path: Path,
|
|
171
|
+
prompt: str,
|
|
172
|
+
iteration: int,
|
|
173
|
+
log_path: Path,
|
|
174
|
+
event_callback: EventCallback,
|
|
175
|
+
project_path: Path | None = None,
|
|
176
|
+
) -> AgentRunResult:
|
|
177
|
+
self._usage = {}
|
|
178
|
+
|
|
179
|
+
# Build env with remapped PYTHONPATH for worktree
|
|
180
|
+
env = build_worktree_env(project_path, worktree_path) if project_path else None
|
|
181
|
+
|
|
182
|
+
try:
|
|
183
|
+
result = run_process(
|
|
184
|
+
cmd=self._build_command(prompt),
|
|
185
|
+
cwd=worktree_path,
|
|
186
|
+
log_path=log_path,
|
|
187
|
+
line_callback=lambda line: self._handle_line(line, event_callback),
|
|
188
|
+
heartbeat_seconds=self.heartbeat_seconds,
|
|
189
|
+
timeout_seconds=self.config.timeout_seconds,
|
|
190
|
+
env=env,
|
|
191
|
+
)
|
|
192
|
+
except FileNotFoundError:
|
|
193
|
+
command = self._command_path()
|
|
194
|
+
return AgentRunResult(
|
|
195
|
+
success=False,
|
|
196
|
+
exit_code=None,
|
|
197
|
+
error=f"'{command}' not found. Set AUTOHELIX_CODEX_CMD or agent.command.",
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
if result.timed_out:
|
|
201
|
+
event_callback(
|
|
202
|
+
AgentEvent(
|
|
203
|
+
kind=AgentEventKind.WARNING,
|
|
204
|
+
text=f"Agent {format_timeout_seconds(self.config.timeout_seconds)}",
|
|
205
|
+
)
|
|
206
|
+
)
|
|
207
|
+
return AgentRunResult(success=result.exit_code == 0, exit_code=result.exit_code, usage=self._usage)
|