-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent_night_shift.py
More file actions
1478 lines (1216 loc) · 66.5 KB
/
agent_night_shift.py
File metadata and controls
1478 lines (1216 loc) · 66.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
🌙 Night Shift Agent v3.6 - Autonomous Coding Assistant
========================================================
Refactored Architecture:
- NightShiftAgent (Main Controller)
- LLMClient (Provider Abstraction with Failover)
- Toolbox (File & Shell Operations)
- BuildState (Context & Verification)
"""
import os
import subprocess
import sys
import re
import time
import json
import urllib.request
import logging
import argparse
import difflib
from datetime import datetime
from pathlib import Path
from dotenv import load_dotenv
# =============================================================================
# CONFIGURATION & CONSTANTS
# =============================================================================
load_dotenv()
# Defaults
# Gemini CLI models (gemini-cli-core config/models.js, v0.25.1)
# - gemini-2.5-pro
# - gemini-2.5-flash
# - gemini-2.5-flash-lite
# - gemini-3-pro-preview
# - gemini-3-flash-preview
# Aliases: auto, auto-gemini-2.5, auto-gemini-3, pro, flash, flash-lite
# Embedding: gemini-embedding-001
DEFAULT_PROVIDER = "gemini"
DEFAULT_MODEL_GEMINI = "gemini-3-flash-preview"
DEFAULT_MODEL_OPENROUTER = "google/gemini-2.0-flash-exp:free"
DEFAULT_MODEL_CLAUDE = "claude-3-5-sonnet-20241022"
DEFAULT_MODEL_OLLAMA = "deepseek-r1:32b"
OLLAMA_BASE_URL = "http://localhost:11434/api/generate"
MAX_ITERATIONS = 80
MAX_RETRIES = 2
MAX_CI_FIX_ATTEMPTS = 5
RETRY_BASE_DELAY = 5
MAX_FILES_IN_CONTEXT = 50
MAX_CONTEXT_CHARS = 80000
MAX_TOOL_OUTPUT_CHARS = 50000 # 50KB max per tool output to prevent context explosion
REPLACE_STALL_THRESHOLD = 3
REQUIRE_BUILD_VERIFICATION = True
BRANCH_PREFIX = "nightshift"
PROTECTED_FILES = {
"build.gradle.kts", "settings.gradle.kts", "gradle.properties",
"libs.versions.toml", "gradle-wrapper.properties", "tasks.txt"
}
CI_POLL_INTERVAL = 60 # Seconds
MAX_CI_WAIT_POLLS = 30 # 30 * 60s = 30 minutes
# Logger Setup - Console + file handlers
SESSION_TIMESTAMP = datetime.now().strftime('%Y%m%d_%H%M%S')
logger = logging.getLogger("NightShiftAgent")
logger.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s', '%Y-%m-%d %H:%M:%S'))
logger.addHandler(console_handler)
# Prompt logger - file handler added later in project directory
prompt_logger = logging.getLogger("PromptLogger")
prompt_logger.setLevel(logging.DEBUG)
prompt_logger.propagate = False # Don't duplicate to main logger
# =============================================================================
# EXCEPTIONS
# =============================================================================
class QuotaExceededError(Exception):
"""Exception raised when an LLM provider hits a rate limit or quota."""
pass
# =============================================================================
# HELPER CLASSES
# =============================================================================
class BuildState:
"""Tracks the state of the build and file changes for verification/rolling back."""
def __init__(self):
self.build_attempted = False
self.build_passed = False
self.last_error = None
self.last_successful_files = {} # path -> content snapshot
self.files_changed_since_success = []
def reset(self):
self.build_attempted = False
self.build_passed = False
self.last_error = None
def checkpoint(self, files_written: list):
"""Snapshot file contents after successful build."""
for path in files_written:
try:
with open(path, 'r') as f:
self.last_successful_files[path] = f.read()
except: pass
self.files_changed_since_success = []
logger.info(f"📸 Checkpoint saved: {len(self.last_successful_files)} files known-good")
def is_verified(self):
return self.build_passed
class RateLimiter:
"""Prevents command spam loops."""
def __init__(self, window_seconds=30, max_identical=3):
self.recent_commands = []
self.window = window_seconds
self.max_identical = max_identical
def should_allow(self, command: str) -> tuple[bool, str]:
current_time = time.time()
self.recent_commands = [(t, c) for t, c in self.recent_commands if current_time - t < self.window]
identical_count = sum(1 for _, c in self.recent_commands if c == command)
if identical_count >= self.max_identical:
return False, f"Rate limited: same command executed {identical_count} times in {self.window}s"
self.recent_commands.append((current_time, command))
return True, ""
# =============================================================================
# LLM CLIENT (FAILOVER LOGIC)
# =============================================================================
# =============================================================================
# LLM PROVIDER ABSTRACTION
# =============================================================================
from abc import ABC, abstractmethod
from typing import List, Optional
class LLMProvider(ABC):
"""Abstract base class for LLM providers (CLI or API)."""
@abstractmethod
def ask(self, prompt_or_messages) -> Optional[str]:
"""Sends prompt (str) or messages (list of dicts) to the model and returns text response."""
pass
@property
@abstractmethod
def name(self) -> str:
"""Friendly name for logging."""
pass
def messages_to_string(self, messages: list) -> str:
"""Converts a list of message dicts to a single string for CLI providers."""
parts = []
for msg in messages:
role = msg.get("role", "user").upper()
content = msg.get("content", "")
if role == "SYSTEM":
parts.append(content) # System prompt goes first, no prefix
elif role == "USER":
parts.append(f"\n\nUSER: {content}")
elif role == "ASSISTANT":
parts.append(f"\n\nASSISTANT: {content}")
return "".join(parts).strip()
def strip_markdown_code_blocks(self, text: str) -> str:
text = text.strip()
if text.startswith("```"):
lines = text.split('\n')
if lines[0].startswith("```"): lines = lines[1:]
if lines and lines[-1].strip() == "```": lines = lines[:-1]
return '\n'.join(lines).strip()
return text
class GeminiCLIProvider(LLMProvider):
def __init__(self, model=DEFAULT_MODEL_GEMINI):
self.model = model
@property
def name(self): return f"Gemini CLI ({self.model})"
def ask(self, prompt_or_messages) -> Optional[str]:
# Flatten messages list to string for CLI
if isinstance(prompt_or_messages, list):
prompt = self.messages_to_string(prompt_or_messages)
else:
prompt = prompt_or_messages
prompt_logger.debug(
f"{'='*80}\n>>> PROMPT TO {self.name}\n{'='*80}\n{prompt}\n{'='*80}\n"
)
for attempt in range(MAX_RETRIES):
try:
# Use positional argument for prompt (stdin/--prompt is deprecated)
result = subprocess.run(
["gemini", "--model", self.model, "--sandbox", "false", "--output-format", "json", prompt],
capture_output=True, text=True, timeout=300
)
self._log_raw_response(attempt, result)
self._check_quota(result.stderr)
if result.returncode == 0 and result.stdout.strip():
return self._parse_json_response(result.stdout)
if result.returncode != 0:
logger.warning(f"⚠️ {self.name} Error ({attempt+1}/{MAX_RETRIES}): {result.stderr}")
self._backoff(attempt)
except QuotaExceededError:
raise
except Exception as e:
logger.warning(f"⚠️ {self.name} Exception ({attempt+1}/{MAX_RETRIES}): {e}")
self._backoff(attempt)
return None
def _log_raw_response(self, attempt, result):
prompt_logger.debug(
f"{'='*80}\n<<< RAW RESPONSE ({attempt+1}) RC:{result.returncode}\n{'='*80}\n"
f"STDOUT:\n{result.stdout}\n{'~'*40}\nSTDERR:\n{result.stderr}\n{'='*80}\n"
)
def _check_quota(self, stderr):
lower_err = stderr.lower()
if any(x in lower_err for x in ["quota exceeded", "resource exhausted", "rate limit"]):
logger.error(f"🚨 {self.name} Quota Exceeded!")
raise QuotaExceededError(f"{self.name} Quota Exceeded")
if "429" in lower_err and ("error" in lower_err or "too many" in lower_err):
logger.error(f"🚨 {self.name} Rate Limited (429)!")
raise QuotaExceededError(f"{self.name} Rate Limited")
def _parse_json_response(self, stdout):
try:
data = json.loads(stdout.strip())
if isinstance(data, list): data = data[0]
# Extract content from various potential CLI JSON schemas
response_text = data.get("response") or data.get("content") or json.dumps(data)
parsed = self.strip_markdown_code_blocks(response_text)
prompt_logger.debug(f"{'='*80}\n<<< PARSED RESPONSE\n{'='*80}\n{parsed}\n{'='*80}\n")
return parsed
except json.JSONDecodeError:
logger.warning(f"⚠️ Failed to parse JSON: {stdout[:200]}")
return None
def _backoff(self, attempt):
if attempt < MAX_RETRIES - 1:
time.sleep(RETRY_BASE_DELAY * (2 ** attempt))
class ClaudeCLIProvider(LLMProvider):
def __init__(self, model=""):
self.model = model
@property
def name(self): return f"Claude CLI ({self.model or 'default'})"
def ask(self, prompt_or_messages) -> Optional[str]:
# Flatten messages list to string for CLI
if isinstance(prompt_or_messages, list):
prompt = self.messages_to_string(prompt_or_messages)
else:
prompt = prompt_or_messages
prompt_logger.debug(
f"{'='*80}\n>>> PROMPT TO {self.name}\n{'='*80}\n{prompt}\n{'='*80}\n"
)
for attempt in range(MAX_RETRIES):
try:
import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as f:
f.write(prompt)
temp_path = f.name
try:
# Use --print for non-interactive mode, --tools "" to disable native tools
# This forces text-only output using <agent_action> tags
model_arg = f"--model {self.model}" if self.model else ""
cmd = f"cat {temp_path} | claude --print {model_arg} --tools \"\""
result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=300, stdin=subprocess.DEVNULL)
self._log_raw_response(attempt, result)
self._check_quota(result.stdout + result.stderr)
if result.returncode != 0:
logger.warning(f"⚠️ {self.name} Error ({attempt+1}/{MAX_RETRIES}): {result.stderr}")
self._backoff(attempt)
continue
parsed = self.strip_markdown_code_blocks(result.stdout.strip())
prompt_logger.debug(f"{'='*80}\n<<< PARSED RESPONSE\n{'='*80}\n{parsed}\n{'='*80}\n")
return parsed
finally:
if os.path.exists(temp_path): os.unlink(temp_path)
except QuotaExceededError:
raise
except Exception as e:
logger.warning(f"⚠️ {self.name} Exception ({attempt+1}/{MAX_RETRIES}): {e}")
self._backoff(attempt)
return None
def _log_raw_response(self, attempt, result):
prompt_logger.debug(
f"{'='*80}\n<<< RAW RESPONSE ({attempt+1}) RC:{result.returncode}\n{'='*80}\n"
f"STDOUT:\n{result.stdout}\n{'~'*40}\nSTDERR:\n{result.stderr}\n{'='*80}\n"
)
def _check_quota(self, combined_output):
lower = combined_output.lower()
if any(x in lower for x in ["hit your limit", "rate limit", "quota exceeded"]):
logger.error(f"🚨 {self.name} Quota Exceeded!")
raise QuotaExceededError(f"{self.name} Quota Exceeded")
def _backoff(self, attempt):
if attempt < MAX_RETRIES - 1:
time.sleep(RETRY_BASE_DELAY * (2 ** attempt))
class OllamaProvider(LLMProvider):
"""Ollama provider with KV cache optimization.
Ollama's /api/chat endpoint automatically caches previous tokens in the KV cache
as long as the model stays loaded. By setting keep_alive=-1, we keep the model
loaded indefinitely, so the system prompt is only fully processed on the first call.
Subsequent calls only process the new/delta tokens.
"""
def __init__(self, model=DEFAULT_MODEL_OLLAMA):
self.model = model
self.base_url = "http://localhost:11434/api/chat" # Chat API endpoint
self.keep_alive = -1 # Keep model loaded indefinitely for KV cache persistence
@property
def name(self): return f"Ollama ({self.model})"
def ask(self, prompt_or_messages) -> Optional[str]:
# Convert string prompt to messages list if needed
if isinstance(prompt_or_messages, str):
messages = [{"role": "user", "content": prompt_or_messages}]
else:
messages = prompt_or_messages
prompt_logger.debug(
f"{'='*80}\n>>> PROMPT TO {self.name}\n{'='*80}\n{json.dumps(messages, indent=2)}\n{'='*80}\n"
)
for attempt in range(MAX_RETRIES):
try:
# Prepare JSON payload for Ollama /api/chat
# keep_alive=-1 keeps the model loaded indefinitely, preserving KV cache
# This means the system prompt is only fully tokenized on first call;
# subsequent calls reuse cached KV states for the prefix
data = {
"model": self.model,
"messages": messages,
"stream": False,
"keep_alive": self.keep_alive,
"options": {
"temperature": 0.6, # R1 models need non-zero temp
"num_ctx": 32768 # Large context for DeepSeek-R1
}
}
req = urllib.request.Request(
self.base_url,
data=json.dumps(data).encode('utf-8'),
headers={'Content-Type': 'application/json'}
)
with urllib.request.urlopen(req, timeout=900) as response:
resp_body = response.read().decode('utf-8')
result = json.loads(resp_body)
self._log_raw_response(attempt, resp_body)
# Chat API returns message.content
raw_text = result.get("message", {}).get("content", "")
parsed = self.strip_markdown_code_blocks(raw_text.strip())
prompt_logger.debug(f"{'='*80}\n<<< PARSED RESPONSE\n{'='*80}\n{parsed}\n{'='*80}\n")
return parsed
except Exception as e:
logger.warning(f"⚠️ {self.name} Exception ({attempt+1}/{MAX_RETRIES}): {e}")
self._backoff(attempt)
return None
def _log_raw_response(self, attempt, body):
prompt_logger.debug(
f"{'='*80}\n<<< RAW RESPONSE ({attempt+1})\n{'='*80}\n"
f"{body}\n{'='*80}\n"
)
def _backoff(self, attempt):
if attempt < MAX_RETRIES - 1:
time.sleep(RETRY_BASE_DELAY * (2 ** attempt))
class OpenRouterAPIProvider(LLMProvider):
def __init__(self):
pass # Model and key read fresh on each request to allow runtime changes
@property
def name(self):
model = os.getenv("OPENROUTER_MODEL", DEFAULT_MODEL_OPENROUTER)
return f"OpenRouter API ({model})"
def ask(self, prompt_or_messages) -> Optional[str]:
api_key = os.getenv("OPENROUTER_API_KEY")
model = os.getenv("OPENROUTER_MODEL", DEFAULT_MODEL_OPENROUTER)
if not api_key:
logger.info(f"⏭️ Skipping {self.name}: OPENROUTER_API_KEY not set")
raise QuotaExceededError("OpenRouter Key Missing") # Treat as unavailable
import urllib.request
import json
# Convert string to messages list if needed
if isinstance(prompt_or_messages, list):
messages = prompt_or_messages
else:
messages = [{"role": "user", "content": prompt_or_messages}]
prompt_logger.debug(
f"{'='*80}\n>>> PROMPT TO {self.name}\n{'='*80}\n{json.dumps(messages, indent=2)}\n{'='*80}\n"
)
# We need generic requests, but trying to avoid external deps if possible.
# But for OpenRouter, curl/requests is needed. Let's use standard lib urllib to avoid forcing 'requests' install.
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"HTTP-Referer": "https://github.com/chrishonson/night-shift-agent",
}
data = {
"model": model,
"messages": messages
}
for attempt in range(MAX_RETRIES):
try:
req = urllib.request.Request(
"https://openrouter.ai/api/v1/chat/completions",
headers=headers,
data=json.dumps(data).encode('utf-8')
)
with urllib.request.urlopen(req, timeout=60) as response:
resp_body = response.read().decode('utf-8')
# Log raw
self._log_raw_response(attempt, 200, resp_body)
data = json.loads(resp_body)
if "error" in data:
# Check for rate limits in API error
err_msg = json.dumps(data['error']).lower()
if "rate limit" in err_msg or "quota" in err_msg or "insufficient" in err_msg:
raise QuotaExceededError(err_msg)
raise Exception(f"OpenRouter Error: {err_msg}")
content = data['choices'][0]['message']['content']
parsed = self.strip_markdown_code_blocks(content)
prompt_logger.debug(f"{'='*80}\n<<< PARSED RESPONSE\n{'='*80}\n{parsed}\n{'='*80}\n")
return parsed
except urllib.error.HTTPError as e:
err_text = e.read().decode('utf-8')
self._log_raw_response(attempt, e.code, err_text)
if e.code == 429:
raise QuotaExceededError("OpenRouter 429")
logger.warning(f"⚠️ {self.name} HTTP Error {e.code}: {err_text}")
self._backoff(attempt)
except Exception as e:
logger.warning(f"⚠️ {self.name} Exception: {e}")
self._backoff(attempt)
return None
def _log_raw_response(self, attempt, status, text):
prompt_logger.debug(
f"{'='*80}\n<<< RAW RESPONSE ({attempt+1}) Status:{status}\n{'='*80}\n"
f"{text}\n{'='*80}\n"
)
def _backoff(self, attempt):
if attempt < MAX_RETRIES - 1:
time.sleep(RETRY_BASE_DELAY * (2 ** attempt))
class ProviderManager:
"""Manages a list of providers and handles failover."""
def __init__(self):
self.providers: List[LLMProvider] = []
self.current_index = 0 # Persist which provider is working
self._init_providers()
def _init_providers(self):
# Determine order based on env preference
gemini_model = os.getenv("PREFERRED_AGENT_MODEL", DEFAULT_MODEL_GEMINI)
ollama_model = os.getenv("OLLAMA_MODEL", DEFAULT_MODEL_OLLAMA)
# Define all providers
ollama_p = OllamaProvider(model=ollama_model) # Primary: Local & Free
gemini_p = GeminiCLIProvider(model=gemini_model)
claude_p = ClaudeCLIProvider() # Default claude model
openrouter_p = OpenRouterAPIProvider() # Fallback to openrouter
# User preferred order: Gemini -> Claude -> OpenRouter -> Ollama
force_provider = os.getenv("FORCE_PROVIDER", "").lower()
if force_provider == "ollama":
self.providers = [ollama_p]
logger.info(f"🔌 FORCE_PROVIDER=ollama: Limited to Ollama only.")
else:
self.providers = [gemini_p, claude_p, openrouter_p, ollama_p]
logger.info(f"🔌 Provider Chain: {[p.name for p in self.providers]}")
def ask(self, prompt: str) -> Optional[str]:
# Start from the last working provider, not always from 0
start_index = self.current_index
for offset in range(len(self.providers)):
i = (start_index + offset) % len(self.providers)
provider = self.providers[i]
try:
result = provider.ask(prompt)
# Success! Remember this provider for next time
self.current_index = i
return result
except QuotaExceededError:
logger.warning(f"🛑 {provider.name} Quota/Key Limit. Switching...")
next_i = (i + 1) % len(self.providers)
if next_i != start_index: # Haven't looped back yet
logger.info(f"🔄 Switching to: {self.providers[next_i].name}...")
continue
else:
logger.error("❌ All providers exhausted!")
return None
except Exception as e:
logger.error(f"❌ Critical error in {provider.name}: {e}")
# Failover on crash too
next_i = (i + 1) % len(self.providers)
if next_i != start_index: continue
return None
return None
def strip_markdown_code_blocks(self, text: str) -> str:
text = text.strip()
if text.startswith("```"):
lines = text.split('\n')
if lines[0].startswith("```"): lines = lines[1:]
if lines and lines[-1].strip() == "```": lines = lines[:-1]
return '\n'.join(lines).strip()
return text
# =============================================================================
# TOOLBOX
# =============================================================================
class Toolbox:
def __init__(self, build_state: BuildState):
self.build_state = build_state
self.rate_limiter = RateLimiter()
def exec_command(self, command: str, env: dict = None, timeout: int = 600) -> subprocess.CompletedProcess:
"""Centralized helper for safe subprocess execution."""
if env is None: env = os.environ.copy()
# Ensure /opt/homebrew/bin is in PATH for Mac
path = env.get("PATH", "")
if "/opt/homebrew/bin" not in path:
env["PATH"] = f"/opt/homebrew/bin:{path}"
try:
return subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=timeout,
env=env,
stdin=subprocess.DEVNULL
)
except Exception as e:
# Create a fake failed result if execution blows up (e.g. OOM)
logger.error(f"FATAL subprocess error: {e}")
raise e
def read_file(self, path: str = None, file_path: str = None) -> str:
target = path or file_path
if not target: return "Error: No path"
try:
with open(target, "r") as f: content = f.read()
logger.info(f"📖 Read file: {target}")
return content
except Exception as e: return f"Error reading {target}: {e}"
def write_file(self, path: str = None, content: str = None, **kwargs) -> str:
target = path or kwargs.get('file_path')
content = content or kwargs.get('code') or kwargs.get('file_content') or ""
if not target: return "Error: No path"
if os.path.basename(target) in PROTECTED_FILES:
return f"ERROR: {target} is protected."
try:
os.makedirs(os.path.dirname(target) if os.path.dirname(target) else ".", exist_ok=True)
with open(target, "w") as f: f.write(content)
logger.info(f"✍️ Wrote file: {target}")
self.build_state.files_changed_since_success.append(target)
self.build_state.build_passed = False
self.build_state.build_attempted = False
return f"Successfully wrote to {target}"
except Exception as e: return f"Error writing {target}: {e}"
def run_shell(self, command: str) -> str:
allowed, reason = self.rate_limiter.should_allow(command)
if not allowed: return f"Error: {reason}"
# Auto-add exclusions for grep commands to avoid matching build artifacts
cmd_stripped = command.strip()
if cmd_stripped.startswith("grep ") and "--exclude-dir" not in command:
# Add common exclusions for build directories
exclusions = "--exclude-dir=.git --exclude-dir=.gradle --exclude-dir=build --exclude-dir=node_modules --exclude-dir=.idea"
# Insert exclusions after 'grep'
command = command.replace("grep ", f"grep {exclusions} ", 1)
logger.info(f"🔧 Auto-excluded build dirs: {command}")
logger.info(f"🤖 Executing: {command}")
env = os.environ.copy()
if os.getenv("GH_BOT_TOKEN") and cmd_stripped.startswith("gh "):
env["GITHUB_TOKEN"] = os.getenv("GH_BOT_TOKEN")
try:
result = self.exec_command(command, env=env)
output = result.stdout + result.stderr
# Truncate large outputs to prevent context overflow
if len(output) > MAX_TOOL_OUTPUT_CHARS:
truncated_msg = f"\n\n[OUTPUT TRUNCATED - showing last {MAX_TOOL_OUTPUT_CHARS} chars of {len(output)} total]"
output = output[-MAX_TOOL_OUTPUT_CHARS:] + truncated_msg
if result.returncode != 0:
return f"Command failed (exit {result.returncode}):\n{output}"
return output
except Exception as e: return f"Error: {e}"
def replace(self, path: str = None, old_string: str = None, new_string: str = None, **kwargs) -> str:
target = path or kwargs.get('file_path')
if not target or not old_string or new_string is None: return "Error: Missing args"
try:
with open(target, "r") as f: content = f.read()
if new_string in content: return f"Success: Text already present in {target}"
if old_string not in content: return f"Error: Text not found in {target}"
with open(target, "w") as f: f.write(content.replace(old_string, new_string, 1))
logger.info(f"✏️ Replaced text in: {target}")
self.build_state.files_changed_since_success.append(target)
self.build_state.build_passed = False
self.build_state.build_attempted = False
return f"Successfully replaced text in {target}"
except Exception as e: return f"Error: {e}"
def list_files(self, path="."):
files = []
ignore = {".git", ".gradle", ".idea", "build", ".kotlin", "node_modules", ".agent_logs"}
for root, dirs, filenames in os.walk(path):
dirs[:] = [d for d in dirs if d not in ignore and not d.startswith(".")]
for f in filenames:
if not f.startswith(".") and not f.endswith(('.jar','.class','.pyc')):
files.append(os.path.join(root, f))
return "\n".join(files[:MAX_FILES_IN_CONTEXT])
def _parse_and_contextualize_errors(self, output: str) -> str:
"""Parses compiler errors, reads source files, and returns a focused error report."""
# Regex patterns for common Kotlin/Gradle errors
# 1. e: file:///path/to/File.kt:10:20: error: message
# 2. e: /path/to/File.kt: (10, 20): message
error_patterns = [
r"(?P<level>[ew]):\s+(?P<path>file://[^:]+|/[^:]+):\s*\(?(?P<line>\d+)[:,\s]+(?P<col>\d+)\)?:\s*(?P<msg>.*)",
r"(?P<path>[^:\n]+\.kt):\s*(?P<line>\d+):\s*(?P<col>\d+):\s*error:\s*(?P<msg>.*)"
]
extracted_errors = []
files_to_read = set()
for line in output.split('\n'):
for pattern in error_patterns:
match = re.search(pattern, line)
if match:
path_str = match.group("path").strip()
# Fix file:// prefix
if path_str.startswith("file://"):
path_str = path_str[7:]
# Normalize absolute paths
if os.path.exists(path_str):
files_to_read.add(os.path.abspath(path_str))
extracted_errors.append(line)
break # Single match per line
if not extracted_errors:
# Fallback output if no specific errors parsed
if len(output) > MAX_TOOL_OUTPUT_CHARS:
half = MAX_TOOL_OUTPUT_CHARS // 2
return output[:half] + "\n\n... [TRUNCATED] ...\n\n" + output[-half:]
return output
# Read files
file_contexts = []
for file_path in files_to_read:
try:
with open(file_path, 'r') as f:
content = f.read()
file_contexts.append(f"--- FILE: {file_path} ---\n{content}\n")
except Exception as e:
file_contexts.append(f"--- FILE: {file_path} ---\n[Error reading file: {e}]\n")
# Assemble report
report_parts = [
"❌ BUILD FAILED - ERROR REPORT",
"\n=== EXTRACTED ERRORS ==="
]
report_parts.extend(extracted_errors)
report_parts.append("\n=== SOURCE FILES CONTEXT ===")
report_parts.extend(file_contexts)
report_parts.append("\n=== RAW OUTPUT TAIL (Last 2000 chars) ===")
report_parts.append(output[-2000:])
return "\n".join(report_parts)
def run_tests(self) -> str:
"""Run tests only (for TDD red/green phases). Does NOT count as final verification."""
TEST_CMD = "./gradlew testDebugUnitTest"
logger.info(f"🧪 Running tests: {TEST_CMD}")
env = os.environ.copy()
try:
result = self.exec_command(TEST_CMD, env=env, timeout=300)
output = result.stdout + result.stderr
logger.debug(f"Full Test Output:\n{output}")
if result.returncode == 0:
logger.info("✅ Tests PASSED")
if len(output) > MAX_TOOL_OUTPUT_CHARS:
half = MAX_TOOL_OUTPUT_CHARS // 2
output = output[:half] + "\n\n... [TRUNCATED] ...\n\n" + output[-half:]
return f"✅ TESTS PASSED\n\n{output}"
else:
logger.info("🔴 Tests FAILED (expected in TDD red phase)")
return f"🔴 TESTS FAILED (exit {result.returncode}):\n\n{self._parse_and_contextualize_errors(output)}"
except Exception as e:
logger.error(f"❌ Test error: {e}")
return f"Error running tests: {e}"
def verify_build(self) -> str:
"""Run the official verification build with coverage. This is the ONLY way to pass verification."""
VERIFICATION_CMD = "./gradlew assembleDebug :composeApp:linkDebugFrameworkIosSimulatorArm64 detekt testDebugUnitTest koverVerify"
logger.info(f"🔍 Running verification build: {VERIFICATION_CMD}")
env = os.environ.copy()
try:
result = self.exec_command(VERIFICATION_CMD, env=env)
self.build_state.build_attempted = True
self.build_state.build_passed = (result.returncode == 0)
output = result.stdout + result.stderr
logger.debug(f"Full Verification Output:\n{output}")
if result.returncode == 0:
# Success - truncate if needed
if len(output) > MAX_TOOL_OUTPUT_CHARS:
output = output[-MAX_TOOL_OUTPUT_CHARS:]
logger.info("✅ Verification PASSED")
if self.build_state.files_changed_since_success:
self.build_state.checkpoint(self.build_state.files_changed_since_success)
return f"✅ VERIFICATION PASSED (build + tests + coverage)\n\n{output}"
else:
# Failure - use smart parsing
logger.warning(f"❌ Verification FAILED (Exit {result.returncode})")
return f"❌ VERIFICATION FAILED (exit {result.returncode}):\n\n{self._parse_and_contextualize_errors(output)}"
except Exception as e:
logger.error(f"❌ Verification error: {e}")
return f"Error running verification: {e}"
def dispatch(self, tool_name, args):
mapping = {
"read_file": self.read_file, "write_file": self.write_file,
"run_shell": self.run_shell, "run_shell_command": self.run_shell,
"replace": self.replace, "list_files": self.list_files,
"run_tests": self.run_tests, "test": self.run_tests, # TDD tool
"verify_build": self.verify_build, "verify": self.verify_build # Alias
}
# Arg Normalization
if tool_name in ["run_shell", "run_shell_command"]:
# Extensive alias mapping for creative models
cmd = (args.get("command") or args.get("cmd") or args.get("code") or
args.get("script") or args.get("command_line") or
args.get("cli") or args.get("exec") or args.get("input") or args.get("bash"))
if cmd: args["command"] = cmd
if tool_name == "replace":
old = args.get("search") or args.get("old") or args.get("original") or args.get("pattern")
new = args.get("replace") or args.get("new") or args.get("content") or args.get("replacement")
if old: args["old_string"] = old
if new: args["new_string"] = new
# Normalize path arguments across all file-related tools
if "dir_path" in args: args["path"] = args.pop("dir_path")
if "directory" in args: args["path"] = args.pop("directory")
if "file_path" in args: args["path"] = args.pop("file_path")
# Handle search_file_content by mapping to grep
if tool_name == "search_file_content":
pattern = args.get("pattern", "")
include = args.get("include", "*.kt")
# Convert to grep command and clear other args
command = f"grep -rn '{pattern}' --include='{include}' ."
args = {"command": command} # Clear all other args, only keep command
tool_name = "run_shell"
logger.info(f"Arguments for {tool_name}: {args}")
func = mapping.get(tool_name)
if func: return func(**args)
return f"Unknown tool: {tool_name}. Available tools: {', '.join(mapping.keys())}"
# =============================================================================
# MAIN AGENT CONTROLLER
# =============================================================================
class NightShiftAgent:
def __init__(self, project_dir):
self.project_dir = Path(project_dir).resolve()
if not self.project_dir.exists():
raise ValueError(f"Project dir not found: {project_dir}")
os.chdir(self.project_dir)
# Set up file logging in the project directory
self._setup_logging()
self.build_state = BuildState()
self.toolbox = Toolbox(self.build_state)
self.llm = ProviderManager()
self.bot_username = os.getenv("BOT_USERNAME", "agentnightshift")
self.gh_token = os.getenv("GH_BOT_TOKEN")
def _setup_logging(self):
"""Set up file handlers in the project directory."""
log_dir = self.project_dir / ".agent_logs"
log_dir.mkdir(exist_ok=True)
log_file = log_dir / f"session_{SESSION_TIMESTAMP}.log"
prompt_log_file = log_dir / f"prompts_{SESSION_TIMESTAMP}.log"
# Add file handler to main logger
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s', '%Y-%m-%d %H:%M:%S'))
logger.addHandler(file_handler)
# Add file handler to prompt logger
prompt_handler = logging.FileHandler(prompt_log_file)
prompt_handler.setFormatter(logging.Formatter('%(asctime)s\n%(message)s\n'))
prompt_logger.addHandler(prompt_handler)
logger.info(f"📁 Logging to: {log_dir}")
def run_cmd_quiet(self, cmd):
env = os.environ.copy()
# Ensure /opt/homebrew/bin is in PATH for Mac
path = env.get("PATH", "")
if "/opt/homebrew/bin" not in path:
env["PATH"] = f"/opt/homebrew/bin:{path}"
if self.gh_token: env["GITHUB_TOKEN"] = self.gh_token
return subprocess.run(cmd, shell=True, capture_output=True, text=True, env=env, stdin=subprocess.DEVNULL)
def configure_git(self):
logger.info("🔧 Configuring git...")
repo = self.run_cmd_quiet("gh repo view --json nameWithOwner --jq .nameWithOwner").stdout.strip()
if self.gh_token and repo:
url = f"https://{self.bot_username}:{self.gh_token}@github.com/{repo}.git"
self.run_cmd_quiet(f'git remote set-url origin "{url}"')
self.run_cmd_quiet(f'git config user.name "{self.bot_username}"')
self.run_cmd_quiet(f'git config user.email "{self.bot_username}@users.noreply.github.com"')
logger.info(f"✅ Authenticated for {repo}")
def create_branch(self):
# Check current branch
current = self.run_cmd_quiet("git branch --show-current").stdout.strip()
# If already on a nightshift branch, reuse it
if current.startswith(BRANCH_PREFIX + "/"):
logger.info(f"🌿 Reusing existing branch: {current}")
return current
# If on a feature branch (not main), stay on it and work there
if current and current != "main":
logger.info(f"🌿 Working on existing feature branch: {current}")
# Pull latest changes for this branch if it has a remote
pull_result = self.run_cmd_quiet(f"git pull origin {current} 2>/dev/null || true")
return current
# Only create new nightshift branch when on main
ts = datetime.now().strftime('%Y%m%d-%H%M%S')
branch = f"{BRANCH_PREFIX}/{ts}"
self.run_cmd_quiet("git checkout main")
self.run_cmd_quiet("git pull origin main")
self.run_cmd_quiet(f"git checkout -b {branch}")
logger.info(f"🌿 Created branch: {branch}")
return branch
def commit_changes(self, task: str):
logger.info("📝 Committing changes...")
self.toolbox.run_shell("git add .")
# Escape quotes in task name
safe_task = task.replace('"', '\\"')
commit_msg = f"Night Shift: {safe_task}"
# Check if anything to commit
status = self.toolbox.run_shell("git status --porcelain")
if not status.strip():
logger.warning("⚠️ No changes to commit")
return False
result = self.toolbox.run_shell(f'git commit -m "{commit_msg}"')
if "Command failed" in result:
logger.error(f"❌ Failed to commit: {result}")
return False
logger.info("✅ Changes committed")
return True
def push_and_create_pr(self, completed: list, branch: str) -> bool:
"""Push branch and create PR. Returns True if PR was created/exists, False if no commits."""
logger.info(f"🚀 Pushing branch {branch}...")
push_result = self.toolbox.run_shell(f"git push -u origin {branch}")
# Build nice PR title and body
tasks_succeeded = len(completed)
pr_title = f"🌙 Night Shift: {tasks_succeeded} task(s)"
task_list = "\n".join([f"- [x] {t}" for t in completed])
pr_body = f"## 🌙 Night Shift Agent Report\\n\\n**Tasks**: {tasks_succeeded}\\n\\n{task_list}"
# Create PR
pr_result = self.toolbox.run_shell(f'gh pr create --title "{pr_title}" --body "{pr_body}" --head {branch} --base main')
logger.info("Compare URL: " + pr_result)
# Check for "no commits" error - this means there's nothing to PR
if "No commits between" in pr_result:
logger.warning("⚠️ No new commits to create PR. All tasks may have been completed in previous runs.")
return False
# Check if PR already exists (not an error)
if "already exists" in pr_result.lower():
logger.info("✅ PR already exists, will monitor existing PR.")
return True
# Check for other errors
if "Command failed" in pr_result and "No commits between" not in pr_result:
logger.warning(f"⚠️ PR creation may have issues: {pr_result}")
# Still return True to attempt monitoring - the PR might already exist
return True
return True
def monitor_pr(self, branch: str):
logger.info("\n" + "="*60)
logger.info(f"🔍 Monitoring CI Status for branch: {branch}")
logger.info("="*60)