nietzschian-debugger 0.2.0__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.
- nietzschian_debugger/__init__.py +7 -0
- nietzschian_debugger/cli.py +46 -0
- nietzschian_debugger/commands/__init__.py +0 -0
- nietzschian_debugger/commands/debug.py +84 -0
- nietzschian_debugger/core/__init__.py +0 -0
- nietzschian_debugger/core/context_manager.py +126 -0
- nietzschian_debugger/core/session.py +84 -0
- nietzschian_debugger/core/session_loop.py +247 -0
- nietzschian_debugger/llm/__init__.py +0 -0
- nietzschian_debugger/llm/client.py +126 -0
- nietzschian_debugger/llm/prompts.py +135 -0
- nietzschian_debugger/llm/validator.py +106 -0
- nietzschian_debugger/quotes/__init__.py +0 -0
- nietzschian_debugger/quotes/corpus.py +51 -0
- nietzschian_debugger/quotes/selector.py +75 -0
- nietzschian_debugger/scoring/__init__.py +0 -0
- nietzschian_debugger/scoring/behavior_tagger.py +74 -0
- nietzschian_debugger/scoring/growth_profile.py +99 -0
- nietzschian_debugger/scoring/skill_scorer.py +49 -0
- nietzschian_debugger/storage/__init__.py +0 -0
- nietzschian_debugger/storage/file_reader.py +71 -0
- nietzschian_debugger/storage/session_store.py +208 -0
- nietzschian_debugger/types.py +78 -0
- nietzschian_debugger/ui/__init__.py +0 -0
- nietzschian_debugger/ui/growth_display.py +96 -0
- nietzschian_debugger/ui/renderer.py +83 -0
- nietzschian_debugger-0.2.0.dist-info/METADATA +208 -0
- nietzschian_debugger-0.2.0.dist-info/RECORD +32 -0
- nietzschian_debugger-0.2.0.dist-info/WHEEL +5 -0
- nietzschian_debugger-0.2.0.dist-info/entry_points.txt +2 -0
- nietzschian_debugger-0.2.0.dist-info/licenses/LICENSE +21 -0
- nietzschian_debugger-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""CLI entry point for the Nietzschian Debugger."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
import click
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .commands.debug import debug_command
|
|
12
|
+
|
|
13
|
+
VALID_INTENSITIES = ("socrates", "nietzsche", "zarathustra")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@click.group()
|
|
17
|
+
@click.version_option(version=__version__, prog_name="nietzschian")
|
|
18
|
+
def cli() -> None:
|
|
19
|
+
"""The anti-AI debugger. What doesn't kill your code makes it stronger."""
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@cli.command()
|
|
24
|
+
@click.argument("problem")
|
|
25
|
+
@click.option(
|
|
26
|
+
"-i",
|
|
27
|
+
"--intensity",
|
|
28
|
+
type=click.Choice(VALID_INTENSITIES, case_sensitive=False),
|
|
29
|
+
default="nietzsche",
|
|
30
|
+
help="Questioning intensity: socrates, nietzsche, zarathustra",
|
|
31
|
+
)
|
|
32
|
+
def debug(problem: str, intensity: str) -> None:
|
|
33
|
+
"""Start an interactive debugging session.
|
|
34
|
+
|
|
35
|
+
PROBLEM is the description of the bug or problem to debug.
|
|
36
|
+
"""
|
|
37
|
+
asyncio.run(debug_command(problem, intensity)) # type: ignore[arg-type]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def main() -> None:
|
|
41
|
+
"""Main entry point."""
|
|
42
|
+
cli()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Debug command - starts an interactive debugging session."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
import anthropic
|
|
9
|
+
|
|
10
|
+
from ..types import Intensity
|
|
11
|
+
from ..llm.client import get_client, MissingApiKeyError
|
|
12
|
+
from ..core.session import create_session, finalize_session
|
|
13
|
+
from ..core.session_loop import run_session_loop
|
|
14
|
+
from ..storage.session_store import save_session
|
|
15
|
+
from ..scoring.behavior_tagger import tag_session_behaviors
|
|
16
|
+
from ..scoring.skill_scorer import compute_skill_scores
|
|
17
|
+
from ..scoring.growth_profile import compute_growth_profile
|
|
18
|
+
from ..quotes.selector import select_closing_quote
|
|
19
|
+
from ..ui.growth_display import render_growth_score
|
|
20
|
+
from ..ui.renderer import display_error, display_api_key_help
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def debug_command(problem_description: str, intensity: Intensity) -> None:
|
|
24
|
+
"""Run a full debugging session."""
|
|
25
|
+
# Validate API key
|
|
26
|
+
try:
|
|
27
|
+
get_client()
|
|
28
|
+
except MissingApiKeyError:
|
|
29
|
+
display_api_key_help()
|
|
30
|
+
sys.exit(1)
|
|
31
|
+
|
|
32
|
+
# Validate problem description
|
|
33
|
+
if not problem_description or not problem_description.strip():
|
|
34
|
+
display_error("Please provide a problem description.")
|
|
35
|
+
print('\nUsage: nietzschian debug "Your problem description here"')
|
|
36
|
+
sys.exit(2)
|
|
37
|
+
|
|
38
|
+
# Create session
|
|
39
|
+
session = create_session(problem_description.strip(), intensity)
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
# Run interactive session
|
|
43
|
+
result = await run_session_loop(session)
|
|
44
|
+
|
|
45
|
+
# Finalize session
|
|
46
|
+
behavior_tags = session.behavior_tags
|
|
47
|
+
skill_scores = session.skill_scores
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
behavior_tags = await tag_session_behaviors(session.transcript)
|
|
51
|
+
skill_scores = compute_skill_scores(behavior_tags)
|
|
52
|
+
except Exception:
|
|
53
|
+
# Scoring is best-effort
|
|
54
|
+
pass
|
|
55
|
+
|
|
56
|
+
finalize_session(session, result.outcome, skill_scores, behavior_tags)
|
|
57
|
+
|
|
58
|
+
# Save session
|
|
59
|
+
try:
|
|
60
|
+
await save_session(session)
|
|
61
|
+
except Exception:
|
|
62
|
+
# Persistence is best-effort
|
|
63
|
+
pass
|
|
64
|
+
|
|
65
|
+
# Display growth score
|
|
66
|
+
growth_profile = await compute_growth_profile()
|
|
67
|
+
closing_quote = select_closing_quote(result.outcome)
|
|
68
|
+
display = render_growth_score(session, growth_profile, closing_quote)
|
|
69
|
+
print(display)
|
|
70
|
+
|
|
71
|
+
sys.exit(0)
|
|
72
|
+
|
|
73
|
+
except anthropic.AuthenticationError:
|
|
74
|
+
display_error("Invalid API key. Check your ANTHROPIC_API_KEY.")
|
|
75
|
+
sys.exit(1)
|
|
76
|
+
except anthropic.RateLimitError:
|
|
77
|
+
display_error("Rate limit reached. Try again in a moment.")
|
|
78
|
+
sys.exit(3)
|
|
79
|
+
except anthropic.APIConnectionError:
|
|
80
|
+
display_error("Cannot reach Claude API. Check your connection.")
|
|
81
|
+
sys.exit(3)
|
|
82
|
+
except anthropic.APIError as e:
|
|
83
|
+
display_error(f"API error: {e.message}")
|
|
84
|
+
sys.exit(3)
|
|
File without changes
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Context window management for long debugging sessions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
from ..types import Turn
|
|
10
|
+
from ..llm.client import call_llm, get_conversation_model, count_tokens
|
|
11
|
+
|
|
12
|
+
TOKEN_THRESHOLD_RATIO = 0.8
|
|
13
|
+
MAX_CONTEXT_TOKENS = 200_000
|
|
14
|
+
TOKEN_THRESHOLD = int(MAX_CONTEXT_TOKENS * TOKEN_THRESHOLD_RATIO) # 160K
|
|
15
|
+
CHARS_PER_TOKEN = 4
|
|
16
|
+
PRESERVE_RECENT_TURNS = 8
|
|
17
|
+
|
|
18
|
+
SUMMARY_SYSTEM_PROMPT = """You are a precise conversation summarizer. Compress the following debug session turns into a single paragraph that preserves:
|
|
19
|
+
- The developer's key hypotheses (stated and rejected)
|
|
20
|
+
- Observable behaviors (guessing without evidence, checking assumptions, etc.)
|
|
21
|
+
- The current state of understanding at the end of these turns
|
|
22
|
+
- Any files or code elements mentioned
|
|
23
|
+
|
|
24
|
+
Do not editorialize. Do not add new information. Output only the summary paragraph."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class MessageArray:
|
|
29
|
+
messages: list[dict[str, str]]
|
|
30
|
+
rolling_summary: Optional[str] = None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def build_message_array(
|
|
34
|
+
turns: list[Turn],
|
|
35
|
+
rolling_summary: Optional[str] = None,
|
|
36
|
+
) -> MessageArray:
|
|
37
|
+
"""Build a message array from turns for LLM input."""
|
|
38
|
+
messages: list[dict[str, str]] = []
|
|
39
|
+
|
|
40
|
+
for turn in turns:
|
|
41
|
+
if turn.question:
|
|
42
|
+
messages.append({"role": "assistant", "content": turn.question})
|
|
43
|
+
if turn.response:
|
|
44
|
+
messages.append({"role": "user", "content": turn.response})
|
|
45
|
+
|
|
46
|
+
return MessageArray(messages=messages, rolling_summary=rolling_summary)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def estimate_tokens(
|
|
50
|
+
system_prompt: str,
|
|
51
|
+
messages: list[dict[str, str]],
|
|
52
|
+
) -> int:
|
|
53
|
+
"""Estimate token count from character count (~4 chars per token)."""
|
|
54
|
+
total_chars = len(system_prompt)
|
|
55
|
+
for msg in messages:
|
|
56
|
+
total_chars += len(msg["content"])
|
|
57
|
+
return math.ceil(total_chars / CHARS_PER_TOKEN)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def should_summarize(estimated_tokens: int) -> bool:
|
|
61
|
+
"""Determine if the context should be summarized."""
|
|
62
|
+
return estimated_tokens > TOKEN_THRESHOLD
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
async def summarize_old_turns(
|
|
66
|
+
turns: list[Turn],
|
|
67
|
+
existing_summary: Optional[str] = None,
|
|
68
|
+
) -> tuple[str, list[Turn]]:
|
|
69
|
+
"""Summarize older turns, preserving recent ones.
|
|
70
|
+
|
|
71
|
+
Returns (summary, recent_turns).
|
|
72
|
+
"""
|
|
73
|
+
if len(turns) <= PRESERVE_RECENT_TURNS:
|
|
74
|
+
return (existing_summary or "", turns)
|
|
75
|
+
|
|
76
|
+
old_turns = turns[:-PRESERVE_RECENT_TURNS]
|
|
77
|
+
recent_turns = turns[-PRESERVE_RECENT_TURNS:]
|
|
78
|
+
|
|
79
|
+
turns_text = "\n\n".join(
|
|
80
|
+
f"Turn {t.turn_number}:\nQuestion: {t.question}\nDeveloper: {t.response}"
|
|
81
|
+
for t in old_turns
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
if existing_summary:
|
|
85
|
+
to_summarize = (
|
|
86
|
+
f"Previous summary: {existing_summary}\n\n"
|
|
87
|
+
f"New turns to incorporate:\n{turns_text}"
|
|
88
|
+
)
|
|
89
|
+
else:
|
|
90
|
+
to_summarize = turns_text
|
|
91
|
+
|
|
92
|
+
summary = call_llm(
|
|
93
|
+
SUMMARY_SYSTEM_PROMPT,
|
|
94
|
+
[{"role": "user", "content": to_summarize}],
|
|
95
|
+
get_conversation_model(),
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
return (summary, recent_turns)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
async def check_and_summarize(
|
|
102
|
+
system_prompt: str,
|
|
103
|
+
turns: list[Turn],
|
|
104
|
+
existing_summary: Optional[str] = None,
|
|
105
|
+
) -> tuple[list[Turn], Optional[str]]:
|
|
106
|
+
"""Check context size and summarize if needed.
|
|
107
|
+
|
|
108
|
+
Returns (turns, summary).
|
|
109
|
+
"""
|
|
110
|
+
msg_array = build_message_array(turns, existing_summary)
|
|
111
|
+
estimated = estimate_tokens(system_prompt, msg_array.messages)
|
|
112
|
+
|
|
113
|
+
if not should_summarize(estimated):
|
|
114
|
+
return (turns, existing_summary)
|
|
115
|
+
|
|
116
|
+
# Verify with exact count
|
|
117
|
+
try:
|
|
118
|
+
exact = count_tokens(system_prompt, msg_array.messages, get_conversation_model())
|
|
119
|
+
if exact <= TOKEN_THRESHOLD:
|
|
120
|
+
return (turns, existing_summary)
|
|
121
|
+
except Exception:
|
|
122
|
+
# If count_tokens fails, proceed with summarization based on estimate
|
|
123
|
+
pass
|
|
124
|
+
|
|
125
|
+
summary, recent_turns = await summarize_old_turns(turns, existing_summary)
|
|
126
|
+
return (recent_turns, summary)
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Session creation and management."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
from ..types import (
|
|
10
|
+
BehaviorTag,
|
|
11
|
+
Intensity,
|
|
12
|
+
Quote,
|
|
13
|
+
SCHEMA_VERSION,
|
|
14
|
+
Session,
|
|
15
|
+
SessionOutcome,
|
|
16
|
+
SkillScores,
|
|
17
|
+
Turn,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def create_session(problem_description: str, intensity: Intensity) -> Session:
|
|
22
|
+
"""Create a new debugging session."""
|
|
23
|
+
return Session(
|
|
24
|
+
schema_version=SCHEMA_VERSION,
|
|
25
|
+
id=str(uuid.uuid4()),
|
|
26
|
+
timestamp=datetime.now(timezone.utc).isoformat(),
|
|
27
|
+
end_timestamp="",
|
|
28
|
+
problem_description=problem_description,
|
|
29
|
+
intensity=intensity,
|
|
30
|
+
outcome="abandoned",
|
|
31
|
+
questions_to_root_cause=0,
|
|
32
|
+
code_files=[],
|
|
33
|
+
transcript=[],
|
|
34
|
+
skill_scores=SkillScores(
|
|
35
|
+
assumption_checking=5,
|
|
36
|
+
evidence_gathering=5,
|
|
37
|
+
root_cause_speed=5,
|
|
38
|
+
),
|
|
39
|
+
behavior_tags=[],
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def add_turn(
|
|
44
|
+
session: Session,
|
|
45
|
+
question: str,
|
|
46
|
+
response: str,
|
|
47
|
+
model: str,
|
|
48
|
+
behavior_tags: Optional[list[str]] = None,
|
|
49
|
+
quote_used: Optional[Quote] = None,
|
|
50
|
+
) -> Turn:
|
|
51
|
+
"""Add a turn to the session transcript."""
|
|
52
|
+
turn = Turn(
|
|
53
|
+
turn_number=len(session.transcript) + 1,
|
|
54
|
+
question=question,
|
|
55
|
+
response=response,
|
|
56
|
+
model=model,
|
|
57
|
+
quote_used=quote_used,
|
|
58
|
+
behavior_tags=behavior_tags or [],
|
|
59
|
+
timestamp=datetime.now(timezone.utc).isoformat(),
|
|
60
|
+
)
|
|
61
|
+
session.transcript.append(turn)
|
|
62
|
+
session.questions_to_root_cause = len(session.transcript)
|
|
63
|
+
return turn
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def finalize_session(
|
|
67
|
+
session: Session,
|
|
68
|
+
outcome: SessionOutcome,
|
|
69
|
+
skill_scores: Optional[SkillScores] = None,
|
|
70
|
+
behavior_tags: Optional[list[BehaviorTag]] = None,
|
|
71
|
+
) -> None:
|
|
72
|
+
"""Finalize a session with outcome and scores."""
|
|
73
|
+
session.end_timestamp = datetime.now(timezone.utc).isoformat()
|
|
74
|
+
session.outcome = outcome
|
|
75
|
+
if skill_scores is not None:
|
|
76
|
+
session.skill_scores = skill_scores
|
|
77
|
+
if behavior_tags is not None:
|
|
78
|
+
session.behavior_tags = behavior_tags
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def add_code_file(session: Session, file_path: str) -> None:
|
|
82
|
+
"""Add a code file to the session if not already present."""
|
|
83
|
+
if file_path not in session.code_files:
|
|
84
|
+
session.code_files.append(file_path)
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Interactive session loop for the debugging session."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
from ..types import Session, SessionOutcome
|
|
9
|
+
from ..llm.client import stream_question, get_conversation_model, get_model_for_file, StreamCallbacks
|
|
10
|
+
from ..llm.prompts import get_system_prompt
|
|
11
|
+
from ..llm.validator import validate_response, reprompt_if_invalid, get_fallback_question
|
|
12
|
+
from ..storage.file_reader import detect_file_paths, read_code_file, format_code_context
|
|
13
|
+
from .session import add_turn, add_code_file
|
|
14
|
+
from .context_manager import check_and_summarize, build_message_array
|
|
15
|
+
from ..quotes.selector import select_quote
|
|
16
|
+
from ..ui.renderer import (
|
|
17
|
+
new_line,
|
|
18
|
+
display_session_header,
|
|
19
|
+
display_dim,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
EXIT_COMMANDS = {"exit", "quit"}
|
|
23
|
+
SOLVE_COMMANDS = {"solved", "found it"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class SessionLoopResult:
|
|
28
|
+
outcome: SessionOutcome
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def run_session_loop(session: Session) -> SessionLoopResult:
|
|
32
|
+
"""Run the interactive debugging session loop."""
|
|
33
|
+
code_files: dict[str, str] = {}
|
|
34
|
+
rolling_summary: Optional[str] = None
|
|
35
|
+
lifeline_offered = False
|
|
36
|
+
|
|
37
|
+
display_session_header(session.intensity)
|
|
38
|
+
|
|
39
|
+
# Read initial code files from problem description
|
|
40
|
+
initial_paths = detect_file_paths(session.problem_description)
|
|
41
|
+
for file_path in initial_paths:
|
|
42
|
+
content = await read_code_file(file_path)
|
|
43
|
+
if content:
|
|
44
|
+
code_files[file_path] = content
|
|
45
|
+
add_code_file(session, file_path)
|
|
46
|
+
|
|
47
|
+
# Generate opening question
|
|
48
|
+
model = get_model_for_file(initial_paths[0]) if initial_paths else get_conversation_model()
|
|
49
|
+
code_context = format_code_context(code_files)
|
|
50
|
+
system_prompt = get_system_prompt(
|
|
51
|
+
session.intensity,
|
|
52
|
+
session.problem_description,
|
|
53
|
+
code_context or None,
|
|
54
|
+
rolling_summary,
|
|
55
|
+
1,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
opening_question = _generate_valid_question(
|
|
59
|
+
system_prompt,
|
|
60
|
+
[{"role": "user", "content": session.problem_description}],
|
|
61
|
+
model,
|
|
62
|
+
session.intensity,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
new_line()
|
|
66
|
+
display_dim("[Turn 1]")
|
|
67
|
+
print(opening_question)
|
|
68
|
+
new_line()
|
|
69
|
+
|
|
70
|
+
current_question = opening_question
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
while True:
|
|
74
|
+
try:
|
|
75
|
+
raw_input = input("> ")
|
|
76
|
+
except EOFError:
|
|
77
|
+
return SessionLoopResult(outcome="abandoned")
|
|
78
|
+
|
|
79
|
+
trimmed = raw_input.strip()
|
|
80
|
+
if not trimmed:
|
|
81
|
+
continue
|
|
82
|
+
|
|
83
|
+
lower = trimmed.lower()
|
|
84
|
+
|
|
85
|
+
# Check exit commands
|
|
86
|
+
if lower in EXIT_COMMANDS:
|
|
87
|
+
add_turn(session, current_question, "[exited]", model)
|
|
88
|
+
return SessionLoopResult(outcome="abandoned")
|
|
89
|
+
|
|
90
|
+
# Check solve commands
|
|
91
|
+
if lower in SOLVE_COMMANDS:
|
|
92
|
+
add_turn(session, current_question, "[solved]", model)
|
|
93
|
+
return SessionLoopResult(outcome="solved")
|
|
94
|
+
|
|
95
|
+
# Check "I give up"
|
|
96
|
+
if lower == "i give up":
|
|
97
|
+
if not lifeline_offered:
|
|
98
|
+
lifeline_offered = True
|
|
99
|
+
add_turn(session, current_question, trimmed, model)
|
|
100
|
+
|
|
101
|
+
# Generate one lifeline question
|
|
102
|
+
lifeline_prompt = get_system_prompt(
|
|
103
|
+
session.intensity,
|
|
104
|
+
session.problem_description,
|
|
105
|
+
code_context or None,
|
|
106
|
+
rolling_summary,
|
|
107
|
+
len(session.transcript) + 1,
|
|
108
|
+
)
|
|
109
|
+
messages = _build_conversation_messages(session, trimmed)
|
|
110
|
+
lifeline_q = _generate_valid_question(
|
|
111
|
+
lifeline_prompt,
|
|
112
|
+
[*messages, {"role": "user", "content": "I give up. I cannot figure this out."}],
|
|
113
|
+
get_conversation_model(),
|
|
114
|
+
session.intensity,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
new_line()
|
|
118
|
+
display_dim("[Lifeline -- one more question before you go]")
|
|
119
|
+
print(lifeline_q)
|
|
120
|
+
new_line()
|
|
121
|
+
current_question = lifeline_q
|
|
122
|
+
continue
|
|
123
|
+
else:
|
|
124
|
+
add_turn(session, current_question, "[gave up]", model)
|
|
125
|
+
return SessionLoopResult(outcome="abandoned")
|
|
126
|
+
|
|
127
|
+
# Normal response
|
|
128
|
+
add_turn(session, current_question, trimmed, model)
|
|
129
|
+
|
|
130
|
+
# Check for new file paths in response
|
|
131
|
+
new_paths = detect_file_paths(trimmed)
|
|
132
|
+
for file_path in new_paths:
|
|
133
|
+
if file_path not in code_files:
|
|
134
|
+
content = await read_code_file(file_path)
|
|
135
|
+
if content:
|
|
136
|
+
code_files[file_path] = content
|
|
137
|
+
add_code_file(session, file_path)
|
|
138
|
+
|
|
139
|
+
# Check context window
|
|
140
|
+
context_turns, context_summary = await check_and_summarize(
|
|
141
|
+
system_prompt,
|
|
142
|
+
session.transcript,
|
|
143
|
+
rolling_summary,
|
|
144
|
+
)
|
|
145
|
+
rolling_summary = context_summary
|
|
146
|
+
|
|
147
|
+
# Select contextual quote
|
|
148
|
+
quote = select_quote(trimmed)
|
|
149
|
+
suggested_quote_text = quote.text if quote else None
|
|
150
|
+
|
|
151
|
+
# Build next turn
|
|
152
|
+
turn_number = len(session.transcript) + 1
|
|
153
|
+
updated_code_context = format_code_context(code_files)
|
|
154
|
+
system_prompt = get_system_prompt(
|
|
155
|
+
session.intensity,
|
|
156
|
+
session.problem_description,
|
|
157
|
+
updated_code_context or None,
|
|
158
|
+
rolling_summary,
|
|
159
|
+
turn_number,
|
|
160
|
+
suggested_quote_text,
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
# Determine model
|
|
164
|
+
model = get_model_for_file(new_paths[0]) if new_paths else get_conversation_model()
|
|
165
|
+
|
|
166
|
+
messages = _build_conversation_messages(session)
|
|
167
|
+
next_question = _generate_valid_question(
|
|
168
|
+
system_prompt,
|
|
169
|
+
messages,
|
|
170
|
+
model,
|
|
171
|
+
session.intensity,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
new_line()
|
|
175
|
+
display_dim(f"[Turn {turn_number}]")
|
|
176
|
+
print(next_question)
|
|
177
|
+
new_line()
|
|
178
|
+
current_question = next_question
|
|
179
|
+
|
|
180
|
+
except KeyboardInterrupt:
|
|
181
|
+
return SessionLoopResult(outcome="abandoned")
|
|
182
|
+
except Exception:
|
|
183
|
+
return SessionLoopResult(outcome="abandoned")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _generate_valid_question(
|
|
187
|
+
system_prompt: str,
|
|
188
|
+
messages: list[dict[str, str]],
|
|
189
|
+
model: str,
|
|
190
|
+
intensity: str,
|
|
191
|
+
) -> str:
|
|
192
|
+
"""Generate a valid question, with reprompt and fallback."""
|
|
193
|
+
full_text = ""
|
|
194
|
+
|
|
195
|
+
def on_text(text: str) -> None:
|
|
196
|
+
# Buffer silently. The validated question is printed exactly once by the
|
|
197
|
+
# caller under the [Turn N] header. Streaming it live here printed it a
|
|
198
|
+
# second time (the single-line \r\033[K clear could not erase a
|
|
199
|
+
# multi-line response), and could flash text that validation then
|
|
200
|
+
# replaced via reprompt/fallback.
|
|
201
|
+
pass
|
|
202
|
+
|
|
203
|
+
def on_complete(text: str) -> None:
|
|
204
|
+
nonlocal full_text
|
|
205
|
+
full_text = text
|
|
206
|
+
|
|
207
|
+
def on_error(error: Exception) -> None:
|
|
208
|
+
pass
|
|
209
|
+
|
|
210
|
+
stream_question(
|
|
211
|
+
system_prompt,
|
|
212
|
+
messages,
|
|
213
|
+
model,
|
|
214
|
+
StreamCallbacks(on_text=on_text, on_complete=on_complete, on_error=on_error),
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
validation = validate_response(full_text)
|
|
218
|
+
if validation.valid:
|
|
219
|
+
return full_text
|
|
220
|
+
|
|
221
|
+
# Try reprompt
|
|
222
|
+
reprompted = reprompt_if_invalid(system_prompt, messages, full_text)
|
|
223
|
+
if reprompted:
|
|
224
|
+
return reprompted
|
|
225
|
+
|
|
226
|
+
# Fallback
|
|
227
|
+
return get_fallback_question(intensity) # type: ignore[arg-type]
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _build_conversation_messages(
|
|
231
|
+
session: Session,
|
|
232
|
+
current_response: Optional[str] = None,
|
|
233
|
+
) -> list[dict[str, str]]:
|
|
234
|
+
"""Build the conversation message history for the LLM."""
|
|
235
|
+
messages: list[dict[str, str]] = [
|
|
236
|
+
{"role": "user", "content": session.problem_description},
|
|
237
|
+
]
|
|
238
|
+
|
|
239
|
+
for turn in session.transcript:
|
|
240
|
+
messages.append({"role": "assistant", "content": turn.question})
|
|
241
|
+
if turn.response and not turn.response.startswith("["):
|
|
242
|
+
messages.append({"role": "user", "content": turn.response})
|
|
243
|
+
|
|
244
|
+
if current_response:
|
|
245
|
+
messages.append({"role": "user", "content": current_response})
|
|
246
|
+
|
|
247
|
+
return messages
|
|
File without changes
|