Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
2139 lines (1806 loc) · 72.9 KB
/
Copy pathmain.py
File metadata and controls
2139 lines (1806 loc) · 72.9 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
"""Interactive agent loop: turn natural-language questions into graph queries."""
from __future__ import annotations
import asyncio
import difflib
import json
import mimetypes
import os
import shlex
import shutil
import subprocess
import sys
import threading
import uuid
from collections import deque
from collections.abc import Callable, Coroutine
from contextlib import contextmanager
from dataclasses import replace
from decimal import Decimal
from functools import lru_cache
from html import escape as html_escape
from pathlib import Path
from typing import TYPE_CHECKING
from loguru import logger
from prompt_toolkit import PromptSession
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.history import History, InMemoryHistory
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.shortcuts import print_formatted_text
from pydantic_ai import (
BinaryContent,
DeferredToolRequests,
DeferredToolResults,
ToolDenied,
)
from pydantic_ai.messages import (
ModelRequest,
ModelResponse,
ToolCallPart,
ToolReturnPart,
UserContent,
)
from rich.console import Group
from rich.live import Live
from rich.panel import Panel
from rich.prompt import Prompt
from rich.spinner import Spinner
from rich.table import Table
from rich.text import Text
from . import constants as cs
from . import exceptions as ex
from . import logs as ls
from .config import ModelConfig, load_ignore_patterns, settings
from .context_pruning import prune_old_tool_results
from .models import AppContext
from .prompts import OPTIMIZATION_PROMPT, OPTIMIZATION_PROMPT_WITH_REFERENCE
from .providers.base import get_provider_from_config
from .services import QueryProtocol
from .services.graph_service import MemgraphIngestor
from .services.llm import (
CypherGenerator,
create_rag_orchestrator,
create_research_agent,
)
from .taint import ReadContentRecord
from .tools.ast_grep_service import AstGrepService
from .tools.code_retrieval import CodeRetriever, create_code_retrieval_tool
from .tools.codebase_query import create_query_tool
from .tools.directory_lister import DirectoryLister, create_directory_lister_tool
from .tools.duplicate_detection import create_find_duplicates_tool
from .tools.file_editor import FileEditor, create_file_editor_tool
from .tools.file_reader import FileReader, create_file_reader_tool
from .tools.file_writer import FileWriter, create_file_writer_tool
from .tools.research import create_research_tool
from .tools.semantic_search import (
create_get_function_source_tool,
create_semantic_search_tool,
)
from .tools.shell_command import ShellCommander, create_shell_command_tool
from .tools.structural_editor import create_structural_editor_tool
from .tools.structural_search import create_structural_search_tool
from .tools.web_search import create_web_search_tool, make_web_searcher
from .types_defs import (
CHAT_LOOP_UI,
OPTIMIZATION_LOOP_UI,
ORANGE_STYLE,
AgentLoopUI,
CancelledResult,
ConfirmationToolNames,
CreateFileArgs,
GraphData,
QueryJsonOutput,
RawToolArgs,
ReplaceCodeArgs,
ShellCommandArgs,
StructuralReplaceArgs,
ToolArgs,
)
from .utils.rich_markdown import LeftAlignedMarkdown
from .utils.token_utils import estimate_message_tokens
if TYPE_CHECKING:
from prompt_toolkit.key_binding import KeyPressEvent
from pydantic_ai import Agent
from pydantic_ai.messages import ModelMessage
from pydantic_ai.models import Model
from pydantic_ai.usage import RunUsage
def style(
text: str, color: cs.Color, modifier: cs.StyleModifier = cs.StyleModifier.BOLD
) -> str:
if modifier == cs.StyleModifier.NONE:
return f"[{color}]{text}[/{color}]"
return f"[{modifier} {color}]{text}[/{modifier} {color}]"
def dim(text: str) -> str:
return f"[{cs.StyleModifier.DIM}]{text}[/{cs.StyleModifier.DIM}]"
app_context = AppContext()
def init_session_log(project_root: Path) -> Path:
log_dir = project_root / cs.TMP_DIR
log_dir.mkdir(exist_ok=True)
app_context.session.log_file = (
log_dir / f"{cs.SESSION_LOG_PREFIX}{uuid.uuid4().hex[:8]}{cs.SESSION_LOG_EXT}"
)
with open(app_context.session.log_file, "w") as f:
f.write(cs.SESSION_LOG_HEADER)
return app_context.session.log_file
def log_session_event(event: str) -> None:
if app_context.session.log_file:
with open(app_context.session.log_file, "a") as f:
f.write(f"{event}\n")
def get_session_context() -> str:
if app_context.session.log_file and app_context.session.log_file.exists():
content = app_context.session.log_file.read_text(encoding="utf-8")
return f"{cs.SESSION_CONTEXT_START}{content}{cs.SESSION_CONTEXT_END}"
return ""
def _autowrap_diff_blocks(text: str) -> str:
if cs.DIFF_GIT_HEADER not in text:
return text
lines = text.split("\n")
out: list[str] = []
in_fence = False
in_diff = False
def is_diff_continuation(line: str) -> bool:
if line == "":
return True
return line.startswith(cs.DIFF_CONTINUATION_PREFIXES)
for line in lines:
if line.startswith(cs.MARKDOWN_FENCE):
if in_diff:
out.append(cs.MARKDOWN_FENCE)
in_diff = False
in_fence = not in_fence
out.append(line)
continue
if in_fence:
out.append(line)
continue
if not in_diff and line.startswith(cs.DIFF_GIT_HEADER):
out.append(cs.MARKDOWN_FENCE_DIFF)
in_diff = True
out.append(line)
continue
if in_diff:
if is_diff_continuation(line):
out.append(line)
else:
out.append(cs.MARKDOWN_FENCE)
in_diff = False
out.append(line)
continue
out.append(line)
if in_diff:
out.append(cs.MARKDOWN_FENCE)
return "\n".join(out)
def _print_unified_diff(target: str, replacement: str, path: str) -> None:
separator = dim(cs.HORIZONTAL_SEPARATOR)
app_context.console.print(f"\n{cs.UI_DIFF_FILE_HEADER.format(path=path)}")
app_context.console.print(separator)
diff = difflib.unified_diff(
target.splitlines(keepends=True),
replacement.splitlines(keepends=True),
fromfile=cs.DIFF_LABEL_BEFORE,
tofile=cs.DIFF_LABEL_AFTER,
lineterm="",
)
for line in diff:
line = line.rstrip("\n")
match line[:1]:
case cs.DiffMarker.ADD | cs.DiffMarker.DEL if line.startswith(
cs.DiffMarker.HEADER_ADD
) or line.startswith(cs.DiffMarker.HEADER_DEL):
app_context.console.print(dim(line))
case cs.DiffMarker.HUNK:
app_context.console.print(
style(line, cs.Color.CYAN, cs.StyleModifier.NONE)
)
case cs.DiffMarker.ADD:
app_context.console.print(
style(line, cs.Color.GREEN, cs.StyleModifier.NONE)
)
case cs.DiffMarker.DEL:
app_context.console.print(
style(line, cs.Color.RED, cs.StyleModifier.NONE)
)
case _:
app_context.console.print(line)
app_context.console.print(separator)
def _print_new_file_content(path: str, content: str) -> None:
separator = dim(cs.HORIZONTAL_SEPARATOR)
app_context.console.print(f"\n{cs.UI_NEW_FILE_HEADER.format(path=path)}")
app_context.console.print(separator)
for line in content.splitlines():
app_context.console.print(
style(f"{cs.DiffMarker.ADD} {line}", cs.Color.GREEN, cs.StyleModifier.NONE)
)
app_context.console.print(separator)
def _to_tool_args(
tool_name: str, raw_args: RawToolArgs, tool_names: ConfirmationToolNames
) -> ToolArgs:
match tool_name:
case tool_names.replace_code:
return ReplaceCodeArgs(
file_path=raw_args.file_path,
target_code=raw_args.target_code,
replacement_code=raw_args.replacement_code,
)
case tool_names.create_file:
return CreateFileArgs(
file_path=raw_args.file_path,
content=raw_args.content,
)
case tool_names.shell_command:
return ShellCommandArgs(command=raw_args.command)
case tool_names.structural_replace:
return StructuralReplaceArgs(
pattern=raw_args.pattern,
rewrite=raw_args.rewrite,
language=raw_args.language,
dry_run=raw_args.dry_run,
)
case _:
return ShellCommandArgs()
def _display_tool_call_diff(
tool_name: str,
tool_args: ToolArgs,
tool_names: ConfirmationToolNames,
file_path: str | None = None,
) -> None:
match tool_name:
case tool_names.replace_code:
target = str(tool_args.get(cs.ARG_TARGET_CODE, ""))
replacement = str(tool_args.get(cs.ARG_REPLACEMENT_CODE, ""))
path = str(
tool_args.get(cs.ARG_FILE_PATH, file_path or cs.DIFF_FALLBACK_PATH)
)
_print_unified_diff(target, replacement, path)
case tool_names.create_file:
path = str(tool_args.get(cs.ARG_FILE_PATH, ""))
content = str(tool_args.get(cs.ARG_CONTENT, ""))
_print_new_file_content(path, content)
case tool_names.shell_command:
command = tool_args.get(cs.ARG_COMMAND, "")
app_context.console.print(f"\n{cs.UI_SHELL_COMMAND_HEADER}")
app_context.console.print(
style(f"$ {command}", cs.Color.YELLOW, cs.StyleModifier.NONE)
)
case tool_names.structural_replace:
pattern = str(tool_args.get(cs.ARG_PATTERN, ""))
rewrite = str(tool_args.get(cs.ARG_REWRITE, ""))
dry_run = tool_args.get(cs.ARG_DRY_RUN, True)
app_context.console.print(f"\n{cs.AST_GREP_APPROVAL_HEADER}")
app_context.console.print(
style(
cs.AST_GREP_APPROVAL_PATTERN.format(pattern=pattern),
cs.Color.YELLOW,
cs.StyleModifier.NONE,
)
)
app_context.console.print(
style(
cs.AST_GREP_APPROVAL_REWRITE.format(rewrite=rewrite),
cs.Color.YELLOW,
cs.StyleModifier.NONE,
)
)
app_context.console.print(
style(
cs.AST_GREP_APPROVAL_DRY_RUN.format(dry_run=dry_run),
cs.Color.YELLOW,
cs.StyleModifier.NONE,
)
)
case _:
app_context.console.print(
cs.UI_TOOL_ARGS_FORMAT.format(
args=json.dumps(tool_args, indent=cs.JSON_INDENT)
)
)
async def _process_tool_approvals(
requests: DeferredToolRequests,
approval_prompt: str,
denial_default: str,
tool_names: ConfirmationToolNames,
) -> DeferredToolResults:
deferred_results = DeferredToolResults()
for call in requests.approvals:
tool_args = _to_tool_args(
call.tool_name, RawToolArgs(**call.args_as_dict()), tool_names
)
will_prompt = (
app_context.session.confirm_edits and not app_context.session.is_yolo()
)
if will_prompt:
app_context.console.print(
f"\n{cs.UI_TOOL_APPROVAL.format(tool_name=call.tool_name)}"
)
_display_tool_call_diff(call.tool_name, tool_args, tool_names)
if not will_prompt:
deferred_results.approvals[call.tool_call_id] = True
continue
if await _confirm_with_toggle(approval_prompt):
deferred_results.approvals[call.tool_call_id] = True
elif app_context.session.is_yolo():
deferred_results.approvals[call.tool_call_id] = True
else:
feedback = await _prompt_with_toggle(cs.UI_FEEDBACK_PROMPT)
denial_msg = feedback.strip() or denial_default
deferred_results.approvals[call.tool_call_id] = ToolDenied(denial_msg)
return deferred_results
def _approval_keybindings() -> KeyBindings:
bindings = KeyBindings()
@bindings.add(cs.KeyBinding.SHIFT_TAB)
def _toggle(event: KeyPressEvent) -> None:
app_context.session.cycle_permission_mode()
if app_context.session.is_yolo():
event.app.exit(result=cs.YES_ANSWER)
else:
event.app.invalidate()
@bindings.add(cs.KeyBinding.CTRL_C)
def _interrupt(event: KeyPressEvent) -> None:
event.app.exit(exception=KeyboardInterrupt)
return bindings
async def _confirm_with_toggle(question: str) -> bool:
bindings = _approval_keybindings()
prompt_text = HTML(
f'<style fg="ansicyan">{html_escape(question)}</style> [y/n] (Y): '
)
session: PromptSession[str] = PromptSession()
while True:
try:
answer = await session.prompt_async(
prompt_text,
key_bindings=bindings,
style=ORANGE_STYLE,
bottom_toolbar=_status_bar_label,
refresh_interval=0.5,
)
except (KeyboardInterrupt, EOFError):
return False
if app_context.session.is_yolo():
return True
normalized = (answer or "").strip().lower()
if normalized in cs.YES_ANSWERS:
return True
if normalized in cs.NO_ANSWERS:
return False
async def _prompt_with_toggle(question: str) -> str:
bindings = _approval_keybindings()
prompt_text = HTML(
f'<style fg="ansiyellow"><b>{html_escape(question)}</b></style>: '
)
session: PromptSession[str] = PromptSession()
try:
answer = await session.prompt_async(
prompt_text,
key_bindings=bindings,
style=ORANGE_STYLE,
bottom_toolbar=_status_bar_label,
refresh_interval=0.5,
)
except (KeyboardInterrupt, EOFError):
return ""
return answer or ""
def _rich_log_sink(message: object) -> None:
app_context.console.print(str(message), end="", markup=False, highlight=False)
def _setup_common_initialization(repo_path: str) -> Path:
logger.remove()
logger.add(_rich_log_sink, format=cs.LOG_FORMAT, colorize=False)
project_root = Path(repo_path).resolve()
tmp_dir = project_root / cs.TMP_DIR
if tmp_dir.exists():
if tmp_dir.is_dir():
shutil.rmtree(tmp_dir)
else:
tmp_dir.unlink()
tmp_dir.mkdir()
app_context.session.target_repo = project_root
return project_root
def _create_configuration_table(
repo_path: str,
title: str = cs.DEFAULT_TABLE_TITLE,
language: str | None = None,
) -> Table:
table = Table(title=style(title, cs.Color.GREEN))
table.add_column(cs.TABLE_COL_CONFIGURATION, style=cs.Color.CYAN)
table.add_column(cs.TABLE_COL_VALUE, style=cs.Color.MAGENTA)
if language:
table.add_row(cs.TABLE_ROW_TARGET_LANGUAGE, language)
orchestrator_config = settings.active_orchestrator_config
table.add_row(
cs.TABLE_ROW_ORCHESTRATOR_MODEL,
f"{orchestrator_config.model_id} ({orchestrator_config.provider})",
)
cypher_config = settings.active_cypher_config
table.add_row(
cs.TABLE_ROW_CYPHER_MODEL,
f"{cypher_config.model_id} ({cypher_config.provider})",
)
orch_endpoint = (
orchestrator_config.endpoint
if orchestrator_config.provider == cs.Provider.OLLAMA
else None
)
cypher_endpoint = (
cypher_config.endpoint if cypher_config.provider == cs.Provider.OLLAMA else None
)
if orch_endpoint and cypher_endpoint and orch_endpoint == cypher_endpoint:
table.add_row(cs.TABLE_ROW_OLLAMA_ENDPOINT, orch_endpoint)
else:
if orch_endpoint:
table.add_row(cs.TABLE_ROW_OLLAMA_ORCHESTRATOR, orch_endpoint)
if cypher_endpoint:
table.add_row(cs.TABLE_ROW_OLLAMA_CYPHER, cypher_endpoint)
confirmation_status = (
cs.CONFIRM_ENABLED if app_context.session.confirm_edits else cs.CONFIRM_DISABLED
)
table.add_row(cs.TABLE_ROW_EDIT_CONFIRMATION, confirmation_status)
table.add_row(cs.TABLE_ROW_TARGET_REPOSITORY, repo_path)
return table
async def run_optimization_loop(
rag_agent: Agent[None, str | DeferredToolRequests],
message_history: list[ModelMessage],
project_root: Path,
language: str,
tool_names: ConfirmationToolNames,
reference_document: str | None = None,
) -> None:
app_context.console.print(cs.UI_OPTIMIZATION_START.format(language=language))
document_info = (
cs.UI_REFERENCE_DOC_INFO.format(reference_document=reference_document)
if reference_document
else ""
)
app_context.console.print(
Panel(
cs.UI_OPTIMIZATION_PANEL.format(document_info=document_info),
border_style=cs.Color.YELLOW,
)
)
initial_question = (
OPTIMIZATION_PROMPT_WITH_REFERENCE.format(
language=language, reference_document=reference_document
)
if reference_document
else OPTIMIZATION_PROMPT.format(language=language)
)
await _run_interactive_loop(
rag_agent,
message_history,
project_root,
OPTIMIZATION_LOOP_UI,
style(cs.PROMPT_YOUR_RESPONSE, cs.Color.CYAN),
tool_names,
initial_question,
)
async def run_with_cancellation[T](
coro: Coroutine[None, None, T], timeout: float | None = None
) -> T | CancelledResult:
task = asyncio.create_task(coro)
try:
return await asyncio.wait_for(task, timeout=timeout) if timeout else await task
except TimeoutError:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
app_context.console.print(
f"\n{style(cs.MSG_TIMEOUT_FORMAT.format(timeout=timeout), cs.Color.YELLOW)}"
)
return CancelledResult(cancelled=True)
except (asyncio.CancelledError, KeyboardInterrupt):
task.cancel()
await asyncio.gather(task, return_exceptions=True)
app_context.console.print(
f"\n{style(cs.MSG_THINKING_CANCELLED, cs.Color.YELLOW)}"
)
return CancelledResult(cancelled=True)
def _cancel_orphaned_tool_calls(message_history: list[ModelMessage]) -> None:
if not message_history:
return
last = message_history[-1]
if not isinstance(last, ModelResponse):
return
tool_calls = [p for p in last.parts if isinstance(p, ToolCallPart)]
if not tool_calls:
return
message_history.append(
ModelRequest(
parts=[
ToolReturnPart(
tool_name=p.tool_name,
content=cs.MSG_TOOL_CALL_CANCELLED,
tool_call_id=p.tool_call_id,
)
for p in tool_calls
]
)
)
def _price_current_run(
usage: RunUsage, model_config: ModelConfig | None
) -> Decimal | None:
"""Price a run's usage, defaulting to the active orchestrator config.
Returns None when pricing is unavailable; pricing is display-only and
never fatal.
"""
if model_config is None:
try:
model_config = settings.active_orchestrator_config
except Exception: # noqa: BLE001 - pricing is display-only, never fatal
return None
from .services.usage_cost import price_run
return price_run(usage, model_config.provider, model_config.model_id)
def _absorb_research_usage(usage: RunUsage) -> None:
"""Fold research sub-agent token usage into the session totals.
Sub-agent runs happen inside a tool call, outside the turn's own
`response.usage` (#1128). The sub-agent reuses the orchestrator model, so
orchestrator pricing holds.
"""
session = app_context.session
session.total_input_tokens += usage.input_tokens
session.total_output_tokens += usage.output_tokens
cost = _price_current_run(usage, None)
if cost is not None:
session.total_cost_usd += cost
else:
session.cost_incomplete = True
def _record_and_print_turn_usage(
turn_input: int, turn_output: int, turn_cost: Decimal, turn_priced: bool
) -> None:
"""Fold one turn's tokens and cost into the session totals and show them."""
session = app_context.session
session.total_input_tokens += turn_input
session.total_output_tokens += turn_output
session.total_cost_usd += turn_cost
if not turn_priced:
session.cost_incomplete = True
line = cs.UI_TURN_USAGE_TOKENS.format(
ti=turn_input,
to=turn_output,
si=session.total_input_tokens,
so=session.total_output_tokens,
)
if turn_priced:
template = (
cs.UI_TURN_USAGE_COST_PARTIAL
if session.cost_incomplete
else cs.UI_TURN_USAGE_COST
)
line += template.format(tc=turn_cost, sc=session.total_cost_usd)
app_context.console.print(dim(line))
async def _run_agent_response_loop(
rag_agent: Agent[None, str | DeferredToolRequests],
message_history: list[ModelMessage],
question_with_context: str | list[UserContent],
config: AgentLoopUI,
tool_names: ConfirmationToolNames,
model_override: Model | None = None,
model_override_config: ModelConfig | None = None,
) -> None:
deferred_results: DeferredToolResults | None = None
pending_prompt: str | list[UserContent] | None = question_with_context
turn_input = turn_output = 0
turn_cost = Decimal(0)
turn_priced = False
while True:
with _thinking_with_status_bar(config.status_message):
response = await run_with_cancellation(
rag_agent.run(
pending_prompt,
message_history=message_history,
deferred_tool_results=deferred_results,
model=model_override,
),
)
pending_prompt = None
if isinstance(response, CancelledResult):
log_session_event(config.cancelled_log)
app_context.session.cancelled = True
_cancel_orphaned_tool_calls(message_history)
break
message_history.extend(response.new_messages())
run_usage = response.usage
turn_input += run_usage.input_tokens
turn_output += run_usage.output_tokens
run_cost = _price_current_run(run_usage, model_override_config)
if run_cost is not None:
turn_cost += run_cost
turn_priced = True
if isinstance(response.output, DeferredToolRequests):
deferred_results = await _process_tool_approvals(
response.output,
config.approval_prompt,
config.denial_default,
tool_names,
)
continue
# Bound the context BEFORE the counter snapshots it. The refresh below
# is handed `list(message_history)` at spawn time, so pruning after it
# would count the pre-prune history and write that total back: the next
# turn would re-trigger on a number this prune already invalidated.
#
# The threshold is `TOKEN_THRESHOLD_CRITICAL`, the level this project
# already calls critical for this exact quantity (it drives the status
# line). Inheriting it means the shipped default is a decision the
# repository made rather than one chosen to satisfy a review.
#
# DELIBERATELY TIMID, and issue #1500 owns the policy.
# `prune_old_tool_results` still refuses below its own recovery floor,
# so a mechanism that discards data stays inert until it would buy
# something real.
#
# It is no longer inert for want of a measurement, though. This used
# to read 0 for every provider whose counter never ran, which meant
# compaction was Anthropic-only without saying so; the counter now
# falls back to a local estimate, so the threshold is reachable
# whatever the session is talking to.
_, _, context_pct = _token_usage()
if context_pct >= cs.TOKEN_THRESHOLD_CRITICAL:
# Assign THROUGH the slice: callers hold this same list and the
# loop mutates it in place, so rebinding would prune a copy and
# leave the conversation untouched -- a call site that satisfies a
# reachability check while doing nothing.
message_history[:] = prune_old_tool_results(message_history)
_spawn_context_refresh(list(message_history))
output_text = response.output
if not isinstance(output_text, str):
continue
markdown_response = LeftAlignedMarkdown(_autowrap_diff_blocks(output_text))
app_context.console.print(
Panel(
markdown_response,
title=config.panel_title,
border_style=cs.Color.GREEN,
)
)
log_session_event(f"{cs.SESSION_PREFIX_ASSISTANT}{output_text}")
_record_and_print_turn_usage(turn_input, turn_output, turn_cost, turn_priced)
break
def _find_multimodal_paths(question: str) -> list[Path]:
try:
if os.name == "nt":
tokens = shlex.split(question, posix=False)
else:
tokens = shlex.split(question)
except ValueError:
tokens = question.split()
paths: list[Path] = []
for token in tokens:
token = token.strip("'\"")
if token.lower().endswith(cs.MULTIMODAL_EXTENSIONS):
p = Path(token)
if p.is_absolute() or token.startswith("/") or token.startswith("\\"):
paths.append(p)
return paths
def _path_variants(path_str: str) -> tuple[str, ...]:
return (
f"'{path_str}'",
f'"{path_str}"',
path_str.replace(" ", r"\ "),
path_str,
)
def _guess_media_type(path: Path) -> str:
mime, _ = mimetypes.guess_type(str(path))
return mime or cs.MIME_TYPE_FALLBACK
def _build_user_prompt(question: str) -> str | list[UserContent]:
paths = _find_multimodal_paths(question)
if not paths:
return question
content: list[UserContent] = []
remaining = question
for path in paths:
if not path.exists() or not path.is_file():
logger.warning(ls.MULTIMODAL_NOT_FOUND.format(path=path))
continue
match_token = next(
(v for v in _path_variants(str(path)) if v in remaining), None
)
if match_token is None:
logger.warning(ls.PATH_NOT_IN_QUESTION.format(path=path))
continue
before, _, after = remaining.partition(match_token)
if before.strip():
content.append(before.strip())
try:
content.append(
BinaryContent(
data=path.read_bytes(), media_type=_guess_media_type(path)
)
)
logger.info(ls.MULTIMODAL_ATTACHED.format(path=path))
except Exception as e:
logger.error(ls.MULTIMODAL_READ_FAILED.format(path=path, error=e))
content.append(match_token)
remaining = after
if remaining.strip():
content.append(remaining.lstrip())
return content or question
def _permission_mode_label() -> str:
return (
cs.PERMISSION_MODE_YOLO_LABEL
if app_context.session.is_yolo()
else cs.PERMISSION_MODE_NORMAL_LABEL
)
def _git_state() -> tuple[str, bool] | None:
repo = app_context.session.target_repo
if repo is None or not repo.exists():
return None
try:
result = subprocess.run(
["git", "status", "--porcelain", "--branch"],
capture_output=True,
text=True,
encoding=cs.ENCODING_UTF8,
timeout=1.0,
check=True,
cwd=repo,
)
except (subprocess.SubprocessError, OSError):
return None
lines = result.stdout.splitlines()
if not lines or not lines[0].startswith("## "):
return None
header = lines[0][3:].split("...", 1)[0].split(" ", 1)[0]
if header in ("HEAD", "No"):
return None
is_dirty = any(line for line in lines[1:])
return header, is_dirty
def _terminal_columns() -> int:
return shutil.get_terminal_size((80, 24)).columns
def _format_tokens(n: int) -> str:
if n >= 1_000_000:
return f"{n / 1_000_000:.1f}M"
if n >= 1_000:
return f"{n / 1_000:.1f}k"
return str(n)
def _token_color(pct: float) -> str:
if pct >= cs.TOKEN_THRESHOLD_CRITICAL:
return cs.TOKEN_COLOR_CRITICAL
if pct >= cs.TOKEN_THRESHOLD_WARNING:
return cs.TOKEN_COLOR_WARNING
return cs.TOKEN_COLOR_OK
def _token_usage() -> tuple[int, int, float]:
try:
used = int(app_context.session.context_tokens)
except (TypeError, ValueError):
used = 0
try:
model_id = settings.active_orchestrator_config.model_id or ""
except Exception:
model_id = ""
bare = model_id.split(":", 1)[-1]
max_ctx = cs.MODEL_CONTEXT_WINDOWS.get(bare, cs.DEFAULT_CONTEXT_WINDOW)
pct = (used / max_ctx * 100) if max_ctx > 0 else 0.0
return used, max_ctx, pct
_background_tasks: set[asyncio.Task[None]] = set()
# The context estimate runs on a DAEMON thread, not on `asyncio.to_thread`'s
# default executor. That executor registers an atexit hook that JOINS its
# threads, so a cancelled refresh still made shutdown wait out an in-flight
# estimate -- seconds on a large history (Greptile, PR #1832). A daemon thread
# is never joined, so an abandoned estimate cannot delay exit.
#
# Safe precisely because the estimate is pure and its result is discarded on
# cancellation: it reads a message list and returns a number, touching no file
# and no connection, so a thread killed at exit leaves nothing half-written.
# Do NOT run anything that writes this way.
_context_refresh_task: asyncio.Task[None] | None = None
def _spawn_context_refresh(messages: list[ModelMessage]) -> None:
"""Start a context refresh, superseding any still in flight.
Only the NEWEST count is wanted -- it is a percentage on a status line and
a compaction trigger, and an older history's total is stale the moment a
turn completes. Without this, several turns in quick succession each
started a full-history tokenisation and they ran CONCURRENTLY: measured at
5 simultaneous estimates from 5 refreshes (Greptile, PR #1832).
Cancelling is safe because the estimate is pure and its result is
discarded: `_settle` already ignores a future nobody holds.
"""
global _context_refresh_task
if _context_refresh_task is not None and not _context_refresh_task.done():
_context_refresh_task.cancel()
task = asyncio.create_task(_refresh_context_tokens(messages))
_context_refresh_task = task
_background_tasks.add(task)
task.add_done_callback(_background_tasks.discard)
def _spawn_background(coro: Coroutine[None, None, None]) -> None:
task = asyncio.create_task(coro)
_background_tasks.add(task)
task.add_done_callback(_background_tasks.discard)
def _settle(
loop: asyncio.AbstractEventLoop,
future: asyncio.Future[int],
*,
value: int | None = None,
error: BaseException | None = None,
) -> None:
"""Resolve `future` from another thread, ignoring an already-settled one.
A cancelled refresh leaves the future done before the daemon thread
finishes, and setting a result on a cancelled future raises.
"""
def apply() -> None:
if future.done():
return
if error is not None:
future.set_exception(error)
else:
future.set_result(value or 0)
try:
loop.call_soon_threadsafe(apply)
except RuntimeError:
# The loop closed while the daemon thread was still estimating, which
# is the normal shape of shutdown: nothing is awaiting this future any
# more, and `call_soon_threadsafe` raises "Event loop is closed" on a
# thread with no handler, surfacing as an uncaught exception at exit
# (Greptile, PR #1832).
#
# Dropping the result is correct rather than merely quiet. The
# estimate is pure and its only consumer is the future nobody holds;
# there is nothing to retry, flush or report. This is the one case
# where "the answer no longer matters" is literally true.
return
# One estimate at a time. Cancelling the awaiting TASK does not stop a daemon
# thread already tokenising, so several turns in quick succession each started
# a full-history walk and they ran concurrently -- measured at 5 simultaneous
# estimates (Greptile, PR #1832). The lock makes a later estimate wait, and the
# generation check below makes it exit instead: only the newest count is wanted.
_estimate_lock = threading.Lock()
_estimate_generation = 0
async def _estimate_off_loop(messages: list[ModelMessage]) -> int:
"""`estimate_message_tokens` on a daemon thread, awaited without blocking."""
global _estimate_generation
loop = asyncio.get_running_loop()
future: asyncio.Future[int] = loop.create_future()
_estimate_generation += 1
mine = _estimate_generation
def run() -> None:
with _estimate_lock:
if mine != _estimate_generation:
# Superseded while queued: a newer history is already the
# answer, so tokenising this one is pure waste. Left unsettled
# on purpose -- the awaiting task was cancelled with it.
return
try: