Coverage for little_loops / subprocess_utils.py: 19%

99 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-04-02 13:03 -0500

1"""Subprocess utilities for Claude CLI invocation. 

2 

3Provides shared functionality for running Claude CLI commands with 

4real-time output streaming, timeout handling, and context handoff detection. 

5""" 

6 

7from __future__ import annotations 

8 

9import json 

10import logging 

11import os 

12import re 

13import selectors 

14import subprocess 

15import time 

16from collections.abc import Callable 

17from pathlib import Path 

18 

19logger = logging.getLogger(__name__) 

20 

21# Callback type: (line: str, is_stderr: bool) -> None 

22OutputCallback = Callable[[str, bool], None] 

23 

24# Process lifecycle callback: (process: Popen) -> None 

25ProcessCallback = Callable[[subprocess.Popen[str]], None] 

26 

27# Model detection callback: (model: str) -> None 

28ModelCallback = Callable[[str], None] 

29 

30# Context handoff detection pattern 

31CONTEXT_HANDOFF_PATTERN = re.compile(r"CONTEXT_HANDOFF:\s*Ready for fresh session") 

32CONTINUATION_PROMPT_PATH = Path(".ll/ll-continue-prompt.md") 

33 

34 

35def detect_context_handoff(output: str) -> bool: 

36 """Check if output contains a context handoff signal. 

37 

38 Args: 

39 output: Command output to check 

40 

41 Returns: 

42 True if context handoff was signaled 

43 """ 

44 return bool(CONTEXT_HANDOFF_PATTERN.search(output)) 

45 

46 

47def read_continuation_prompt(repo_path: Path | None = None) -> str | None: 

48 """Read the continuation prompt file if it exists. 

49 

50 Args: 

51 repo_path: Optional repository root path 

52 

53 Returns: 

54 Contents of continuation prompt, or None if not found 

55 """ 

56 prompt_path = (repo_path or Path.cwd()) / CONTINUATION_PROMPT_PATH 

57 if prompt_path.exists(): 

58 return prompt_path.read_text() 

59 return None 

60 

61 

62def run_claude_command( 

63 command: str, 

64 timeout: int = 3600, 

65 working_dir: Path | None = None, 

66 stream_callback: OutputCallback | None = None, 

67 on_process_start: ProcessCallback | None = None, 

68 on_process_end: ProcessCallback | None = None, 

69 idle_timeout: int = 0, 

70 on_model_detected: ModelCallback | None = None, 

71) -> subprocess.CompletedProcess[str]: 

72 """Invoke Claude CLI command with real-time output streaming. 

73 

74 Args: 

75 command: Command to pass to Claude CLI 

76 timeout: Timeout in seconds (0 for no timeout) 

77 working_dir: Optional working directory for the command 

78 stream_callback: Optional callback for streaming output lines. 

79 Called with (line, is_stderr) for each line of output. 

80 on_process_start: Optional callback invoked after process starts. 

81 Receives the Popen object for tracking/management. 

82 on_process_end: Optional callback invoked after process completes. 

83 Receives the Popen object. Called in finally block. 

84 idle_timeout: Kill process if no output for this many seconds (0 to disable). 

85 on_model_detected: Optional callback invoked with the model name from the 

86 stream-json system/init event. Called at most once per invocation. 

87 

88 Returns: 

89 CompletedProcess with stdout/stderr captured 

90 

91 Raises: 

92 subprocess.TimeoutExpired: If command exceeds timeout or idle timeout. 

93 When triggered by idle timeout, the output field is set to "idle_timeout". 

94 """ 

95 cmd_args = [ 

96 "claude", 

97 "--dangerously-skip-permissions", 

98 "--verbose", 

99 "--output-format", 

100 "stream-json", 

101 "-p", 

102 command, 

103 ] 

104 

105 # Set environment to keep Claude in the project working directory (BUG-007) 

106 # This helps prevent file writes from leaking to the main repo in worktrees 

107 env = os.environ.copy() 

108 env["CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR"] = "1" 

109 

110 process = subprocess.Popen( 

111 cmd_args, 

112 stdout=subprocess.PIPE, 

113 stderr=subprocess.PIPE, 

114 text=True, 

115 bufsize=1, # Line buffered 

116 cwd=working_dir, 

117 env=env, 

118 ) 

119 

120 if on_process_start: 

121 on_process_start(process) 

122 

123 stdout_lines: list[str] = [] 

124 stderr_lines: list[str] = [] 

125 

126 # Use selectors for non-blocking read from both streams 

127 with selectors.DefaultSelector() as sel: 

128 if process.stdout: 

129 sel.register(process.stdout, selectors.EVENT_READ) 

130 if process.stderr: 

131 sel.register(process.stderr, selectors.EVENT_READ) 

132 

133 start_time = time.time() 

134 last_output_time = start_time 

135 

136 try: 

137 while sel.get_map(): 

138 now = time.time() 

139 if timeout and (now - start_time) > timeout: 

140 process.kill() 

141 try: 

142 process.wait(timeout=10) 

143 except subprocess.TimeoutExpired: 

144 logger.warning( 

145 "Process %s did not terminate within 10s after kill", 

146 process.pid, 

147 ) 

148 raise subprocess.TimeoutExpired(cmd_args, timeout) 

149 

150 if idle_timeout and (now - last_output_time) > idle_timeout: 

151 process.kill() 

152 try: 

153 process.wait(timeout=10) 

154 except subprocess.TimeoutExpired: 

155 logger.warning( 

156 "Process %s did not terminate within 10s after kill", 

157 process.pid, 

158 ) 

159 raise subprocess.TimeoutExpired(cmd_args, idle_timeout, output="idle_timeout") 

160 

161 ready = sel.select(timeout=1.0) 

162 for key, _ in ready: 

163 line = key.fileobj.readline() # type: ignore[union-attr] 

164 if not line: 

165 sel.unregister(key.fileobj) 

166 continue 

167 

168 last_output_time = time.time() 

169 line = line.rstrip("\n") 

170 is_stderr = key.fileobj is process.stderr 

171 

172 if not is_stderr: 

173 try: 

174 event = json.loads(line) 

175 etype = event.get("type") 

176 if etype == "system" and event.get("subtype") == "init": 

177 if on_model_detected and "model" in event: 

178 on_model_detected(event["model"]) 

179 continue # don't add to stdout_lines 

180 elif etype == "assistant": 

181 msg = event.get("message", {}) 

182 text_parts = [ 

183 block["text"] 

184 for block in msg.get("content", []) 

185 if block.get("type") == "text" 

186 ] 

187 line = "".join(text_parts) 

188 if not line: 

189 continue 

190 else: 

191 continue # skip other event types (result, tool_use, etc.) 

192 except (json.JSONDecodeError, KeyError, TypeError): 

193 pass # non-JSON line: pass through as raw text 

194 

195 if is_stderr: 

196 stderr_lines.append(line) 

197 else: 

198 stdout_lines.append(line) 

199 

200 if stream_callback: 

201 stream_callback(line, is_stderr) 

202 

203 try: 

204 process.wait(timeout=30) 

205 except subprocess.TimeoutExpired: 

206 logger.warning( 

207 "Process %s did not exit within 30s after streams closed, killing", 

208 process.pid, 

209 ) 

210 process.kill() 

211 try: 

212 process.wait(timeout=10) 

213 except subprocess.TimeoutExpired: 

214 logger.warning( 

215 "Process %s did not terminate within 10s after kill", 

216 process.pid, 

217 ) 

218 finally: 

219 if on_process_end: 

220 on_process_end(process) 

221 

222 return subprocess.CompletedProcess( 

223 cmd_args, 

224 process.returncode if process.returncode is not None else -9, 

225 stdout="\n".join(stdout_lines), 

226 stderr="\n".join(stderr_lines), 

227 )