diff --git a/backend/models/models.py b/backend/models/models.py index 0232eaa..f998f8d 100644 --- a/backend/models/models.py +++ b/backend/models/models.py @@ -409,11 +409,21 @@ def summary_llm(): return _summary_llm["haiku"] -def tool_agent_llm(deep: bool, choice=None): +def coding_thinking_enabled() -> bool: + """Whether a coding turn on Haiku thinks (CODING_THINKING, on unless set to off). See tool_agent_llm.""" + return os.getenv("CODING_THINKING", "on").strip().lower() not in ("0", "off", "false", "no") + + +def tool_agent_llm(deep: bool, choice=None, coding: bool = False): """The model behind the tool agent's reasoning steps (the reply the person reads is written by Gemini either way). `choice` is the person's own setting, "claude" (Haiku), "sonnet" (Claude Sonnet, when it is offered: see sonnet_available) or "gemini"; with none, the server's default applies: Gemini unless TOOL_AGENT_PROVIDER=anthropic. Claude is only ever used with a key present, and carries the Gemini model it replaces as its fallback, so a Claude failure degrades to what - the turn was before, never to an error. A "sonnet" choice that cannot be offered (no price configured) is served by Haiku, the cheaper of the two. See backend/models/claude_llm.py.""" + the turn was before, never to an error. A "sonnet" choice that cannot be offered (no price configured) is served by Haiku, the cheaper of the two. See backend/models/claude_llm.py. + + `coding`: a turn that makes a change (an edit turn, or a plan turn). On Haiku it THINKS, whatever CLAUDE_THINKING says for everything else, with drop_block on: thinking was switched off on + 2026-11-02 because Anthropic refused a request whose earlier messages had changed since a thinking block was written (a 400, then a silent fall back to Gemini), and the loop still changes earlier + messages (a checkpoint's continue, a forced ending asked again, old results shortened after the cache expired). drop_block drops such a block and the request goes through. Probed live 2026-11-27 on + an eight-file task with all three: thinking without drop_block hit the 400 and answered wrong; with it, 3 of 3 clean and right at about the same cost. CODING_THINKING=off turns it off.""" gemini = lite_llm_deep if deep else lite_llm wanted = choice if choice in ("claude", "sonnet", "gpt", "gemini") else ("claude" if os.getenv("TOOL_AGENT_PROVIDER", "").strip().lower() == "anthropic" else "gemini") if wanted == "gemini": @@ -434,6 +444,11 @@ def tool_agent_llm(deep: bool, choice=None): return gemini if wanted == "sonnet" and not sonnet_available(): wanted = "claude" + if wanted == "claude" and coding and coding_thinking_enabled(): + key = ("claude", deep, "thinking") + if key not in _claude_tool_llms: + _claude_tool_llms[key] = claude_llm.ClaudeLLM(fallback=gemini, thinking_off=False, drop_block=True) + return _claude_tool_llms[key] key = (wanted, deep) if key not in _claude_tool_llms: if wanted == "sonnet": diff --git a/backend/services/agent_workflow.py b/backend/services/agent_workflow.py index ec8d41d..7183642 100644 --- a/backend/services/agent_workflow.py +++ b/backend/services/agent_workflow.py @@ -4649,6 +4649,11 @@ async def _announce_step(title, detail, step_id, tool=None, subject=None, last_s # A listing of a long library adds the read steps it needs, once (backend/utils/library_allowance.py); not in low-power mode, where the step cap is the point. library_allowance = LibraryAllowance(enabled=not budget_guard.low_power(budget_state)) if library_scope else None + loop_llm = tool_agent_llm(bool(deep_thinking), tool_model_choice, coding=bool(edit_turn or plan_phase)) # a turn that makes a change thinks on Haiku (models.tool_agent_llm) + if (edit_turn or plan_phase) and isinstance(loop_llm, ClaudeLLM) and not loop_llm.thinking_off: + from backend.utils.self_counters import record_turn_counts + + await asyncio.to_thread(record_turn_counts, {"code_thinking_turns": 1}) try: try: loop_result = await _native_engine( @@ -4662,7 +4667,7 @@ async def _announce_step(title, detail, step_id, tool=None, subject=None, last_s TOOL_AGENT_PLAN_STEPS if plan_phase == code_plan.PLAN_PHASE else 0), budget_state, ), - llm=tool_agent_llm(bool(deep_thinking), tool_model_choice), + llm=loop_llm, capability_denial_watchlist=TOOL_AGENT_CAPABILITY_DENIAL_WATCHLIST, required_action=_PLAN_REQUIRED_ACTION if plan_phase == code_plan.PLAN_PHASE else (_LOCAL_EDIT_REQUIRED_ACTION if edit_turn else None), steering_source=lambda: steering.drain(steering_key), diff --git a/backend/tests/test_claude_llm.py b/backend/tests/test_claude_llm.py index 73a756e..ae6773c 100644 --- a/backend/tests/test_claude_llm.py +++ b/backend/tests/test_claude_llm.py @@ -277,7 +277,7 @@ def test_any_other_provider_value_stays_on_gemini(monkeypatch): def test_the_tool_agent_asks_for_its_model_through_the_switch(): source = open(os.path.join(REPO, "backend", "services", "agent_workflow.py"), encoding="utf-8").read() - assert "llm=tool_agent_llm(bool(deep_thinking), tool_model_choice)," in source # through the switch, with the plan phase's own choice applied first + assert "loop_llm = tool_agent_llm(bool(deep_thinking), tool_model_choice, coding=bool(edit_turn or plan_phase))" in source and "llm=loop_llm," in source # through the switch, with the plan phase's own choice applied first def test_the_packages_are_declared(): diff --git a/backend/tests/test_code_plan_execute_model.py b/backend/tests/test_code_plan_execute_model.py index b61b183..1658e25 100644 --- a/backend/tests/test_code_plan_execute_model.py +++ b/backend/tests/test_code_plan_execute_model.py @@ -83,7 +83,7 @@ def test_a_choice_that_cannot_be_offered_falls_back_as_it_always_did(monkeypatch def test_the_tool_agent_builds_its_model_through_the_phase_choice_and_says_so_in_the_trace(): source = open(os.path.join(REPO, "backend", "services", "agent_workflow.py"), encoding="utf-8").read() assert 'tool_model_choice = code_plan.execute_phase_choice(state.get("tool_model"), plan_phase, state.get("execute_model"))' in source - assert "llm=tool_agent_llm(bool(deep_thinking), tool_model_choice)," in source + assert "loop_llm = tool_agent_llm(bool(deep_thinking), tool_model_choice, coding=bool(edit_turn or plan_phase))" in source and "llm=loop_llm," in source assert "code_plan.EXECUTE_MODEL_NAMES.get(str(tool_model_choice)" in source # the trace names the model that runs the step assert 'if plan_phase == code_plan.EXECUTE_PHASE and tool_model_choice != state.get("tool_model"):' in source diff --git a/backend/tests/test_coding_thinking.py b/backend/tests/test_coding_thinking.py new file mode 100644 index 0000000..9380aaf --- /dev/null +++ b/backend/tests/test_coding_thinking.py @@ -0,0 +1,80 @@ +"""A turn that makes a change thinks on Haiku, with drop_block on (models.tool_agent_llm(coding=True), tool_agent_node). Nothing here calls a model: the loop is faked.""" +import pytest + +from backend.models import claude_llm +from backend.models import models as models_module +from backend.models.claude_llm import ClaudeLLM +from backend.services import local_edit_decisions as led +from backend.tests.test_local_edit_decisions import _drive +from backend.tests.test_local_edits import _connect_folder, run_async +from backend.utils import self_counters + + +@pytest.fixture(autouse=True) +def _claude_key(monkeypatch): + monkeypatch.setenv("CLAUDE_API_KEY", "sk-ant-not-a-real-key") + monkeypatch.delenv("CODING_THINKING", raising=False) + models_module._claude_tool_llms.clear() + yield + models_module._claude_tool_llms.clear() + + +def test_a_coding_turn_on_haiku_thinks_with_drop_block_and_the_gemini_fallback(): + llm = models_module.tool_agent_llm(False, "claude", coding=True) + assert isinstance(llm, ClaudeLLM) and llm.thinking_off is False and llm.drop_block is True + assert llm.model_name != claude_llm.SONNET_MODEL and llm.fallback is models_module.lite_llm + assert models_module.tool_agent_llm(True, "claude", coding=True).fallback is models_module.lite_llm_deep + assert models_module.tool_agent_llm(False, "claude", coding=True) is llm, "one instance per mode, not one per turn" + + +def test_any_other_turn_keeps_the_ordinary_model(monkeypatch): + coding = models_module.tool_agent_llm(False, "claude", coding=True) + ordinary = models_module.tool_agent_llm(False, "claude") + assert ordinary is not coding and ordinary.drop_block is claude_llm.DROP_BLOCK and ordinary.thinking_off is claude_llm.THINKING_OFF + + +def test_the_switch_turns_it_off(): + import os + + os.environ["CODING_THINKING"] = "off" + try: + llm = models_module.tool_agent_llm(False, "claude", coding=True) + assert llm is models_module.tool_agent_llm(False, "claude") and llm.drop_block is claude_llm.DROP_BLOCK + finally: + del os.environ["CODING_THINKING"] + + +def test_sonnet_gemini_and_no_key_are_unchanged(monkeypatch): + monkeypatch.setattr(models_module, "sonnet_available", lambda: True) + assert models_module.tool_agent_llm(False, "sonnet", coding=True) is models_module.tool_agent_llm(False, "sonnet") + assert models_module.tool_agent_llm(False, "gemini", coding=True) is models_module.lite_llm + monkeypatch.delenv("CLAUDE_API_KEY") + monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) + assert models_module.tool_agent_llm(False, "claude", coding=True) is models_module.lite_llm + + +# ---- through the tool agent ---------------------------------------------------------------------------------------------------------------- + +def _counted(monkeypatch): + recorded = [] + monkeypatch.setattr(self_counters, "record_turn_counts", lambda counts, *a, **k: recorded.append(dict(counts))) + return recorded + + +@run_async +async def test_an_edit_turn_runs_the_thinking_model_and_is_counted(monkeypatch): + _connect_folder() + recorded = _counted(monkeypatch) + seen = await _drive(monkeypatch, lambda pid: led.decide("jack", pid, "applied"), state_extra={"tool_model": "claude"}, question="change greet in src/app.py so it says hello instead of hi") + llm = seen["kwargs"]["llm"] + assert isinstance(llm, ClaudeLLM) and llm.thinking_off is False and llm.drop_block is True + assert {"code_thinking_turns": 1} in recorded and "code_thinking_turns" in self_counters._PLAIN_KEYS + + +@run_async +async def test_a_question_that_changes_nothing_does_not_think_and_is_not_counted(monkeypatch): + _connect_folder() + recorded = _counted(monkeypatch) + seen = await _drive(monkeypatch, lambda pid: led.decide("jack", pid, "applied"), state_extra={"tool_model": "claude"}, question="what does greet return?") + assert seen["kwargs"]["llm"] is models_module.tool_agent_llm(False, "claude") + assert {"code_thinking_turns": 1} not in recorded diff --git a/backend/tests/test_tool_model_setting.py b/backend/tests/test_tool_model_setting.py index 55121ed..ed517be 100644 --- a/backend/tests/test_tool_model_setting.py +++ b/backend/tests/test_tool_model_setting.py @@ -167,7 +167,7 @@ def test_the_chat_turn_hands_the_choice_to_the_agent(): app_source = open(os.path.join(REPO, "app.py"), encoding="utf-8").read() assert '"tool_model": effective_tool_model,' in app_source and 'effective_tool_model = _settings.get("tool_model")' in app_source node_source = open(os.path.join(REPO, "backend", "services", "agent_workflow.py"), encoding="utf-8").read() - assert "llm=tool_agent_llm(bool(deep_thinking), tool_model_choice)," in node_source # the person's choice, except while an approved plan is carried out (backend/tests/test_code_plan_execute_model.py) + assert "loop_llm = tool_agent_llm(bool(deep_thinking), tool_model_choice, coding=bool(edit_turn or plan_phase))" in node_source and "llm=loop_llm," in node_source # the person's choice, except while an approved plan is carried out (backend/tests/test_code_plan_execute_model.py) def test_the_model_chip_is_offered_only_when_available_and_changes_the_tool_model(): diff --git a/backend/utils/self_counters.py b/backend/utils/self_counters.py index 22ee0d3..2d327e2 100644 --- a/backend/utils/self_counters.py +++ b/backend/utils/self_counters.py @@ -101,7 +101,7 @@ # How much each turn mattered, whatever model wrote it (backend/utils/reply_tier.py STAKES, plus "none" for a plain turn): sizes the turns a stronger reply voice would be spent on. Counts only. "reply_stakes": ("safety", "emotional", "checkin", "companion", "identity", "frustration", "none"), } -_PLAIN_KEYS = ("turns_total", "self_model_used", "experience_captured", "experience_capture_merged", "experience_capture_invalid", "experience_offered", "experience_cited", "native_runs", "native_calls", "native_cache_expired_shrinks", "native_cache_expired_chars", "native_chars_sent", "native_chars_results", "native_chars_instructions", "native_chars_tools", "native_chars_preferences", "native_chars_architecture", "native_chars_memory", "native_chars_history", "native_chars_leanings", "leaning_turns", "native_chars_environment", "native_chars_request", "code_plan_turns", "code_plan_exec_tool_steps", "code_plan_exec_early", "code_plan_fed_next", "code_plan_turn_cap_hit", "code_plan_submitted", "code_plan_invalid", "code_plan_approved", "code_plan_cancelled", "code_plan_stalled", "code_plan_halted", "code_plan_marked_done", "claim_unproven", "claim_sent_back", "claim_edit_unbacked", "claim_denial_dropped", "edit_turn_correction", "code_plan_exec_turns", "code_plan_exec_cap_hit", "code_plan_exec_edited", "code_plan_steps_done", "code_plan_prefetched", "code_plan_deviation", "code_pushback", "code_frustrated", "code_proposals", "code_proposal_rework", "code_edit_calls", "code_edit_errors", "code_test_runs", "code_edit_applied", "code_edit_declined", "code_edit_undone", "code_edit_applied_small", "code_edit_applied_large", "code_edit_declined_small", "code_edit_declined_large", "code_edit_undone_small", "code_edit_undone_large", "working_notes_updated", "working_notes_item_added", "working_notes_item_dropped", "working_notes_injected", "working_notes_chat_read", "reply_fit_checked", "reward_evaluated", "relatable_offered", "self_mention", "observations_injected", "observations_used", "experience_placed", "relatable_placed", "take_offered", "corrections_carried", "goal_guard_shown", "care_pause_shown", "timeline_shown", "vague_fact_skipped", "hear_you_held", "shared_moment_offered", "shared_moment_used", "moment_capture_asked", "moment_capture_proposed", "moment_capture_refused", "code_plan_step_closed", "code_cross_file_refused", "code_cross_file_overridden", "code_after_edit_check_run", "code_after_edit_check_failed", "code_after_edit_check_suggested", "reply_bans_shown", "notes_standout_held", "notes_second_look", "notes_second_look_kept", "low_move_push_back", "low_move_pattern", "low_move_company", "support_choice_offered", "support_choice_listen", "support_choice_advice", "support_choice_fix", "support_mode_applied", "encouragement_offered", "open_loop_captured", "open_loop_offered", "open_loop_resolved", "callback_offered", "self_history_offered", "initiation_offered", "initiation_fallback", "initiation_answered", "initiation_interest_offered", "initiation_interest_answered", "duration_offered", "curiosity_offered", "curiosity_taken", "shelf_offered", "shelf_taken", "shelf_listed", "finding_selected", "lean_offered", "guardrail_applied", "routines_offered", "followups_offered", "task_results_offered", "meeting_turns", "headsup_offered", "clarify_noted", "clarify_asked", "clarify_answered", "memory_note_dropped", "memory_note_trimmed", "status_offered", "offer_made", "offer_taken", "offer_passed", "offer_held_back", "code_turns", "code_cap_hit", "code_edited", "code_verified", "code_followed", "code_redo") +_PLAIN_KEYS = ("turns_total", "self_model_used", "experience_captured", "experience_capture_merged", "experience_capture_invalid", "experience_offered", "experience_cited", "native_runs", "native_calls", "code_thinking_turns", "native_cache_expired_shrinks", "native_cache_expired_chars", "native_chars_sent", "native_chars_results", "native_chars_instructions", "native_chars_tools", "native_chars_preferences", "native_chars_architecture", "native_chars_memory", "native_chars_history", "native_chars_leanings", "leaning_turns", "native_chars_environment", "native_chars_request", "code_plan_turns", "code_plan_exec_tool_steps", "code_plan_exec_early", "code_plan_fed_next", "code_plan_turn_cap_hit", "code_plan_submitted", "code_plan_invalid", "code_plan_approved", "code_plan_cancelled", "code_plan_stalled", "code_plan_halted", "code_plan_marked_done", "claim_unproven", "claim_sent_back", "claim_edit_unbacked", "claim_denial_dropped", "edit_turn_correction", "code_plan_exec_turns", "code_plan_exec_cap_hit", "code_plan_exec_edited", "code_plan_steps_done", "code_plan_prefetched", "code_plan_deviation", "code_pushback", "code_frustrated", "code_proposals", "code_proposal_rework", "code_edit_calls", "code_edit_errors", "code_test_runs", "code_edit_applied", "code_edit_declined", "code_edit_undone", "code_edit_applied_small", "code_edit_applied_large", "code_edit_declined_small", "code_edit_declined_large", "code_edit_undone_small", "code_edit_undone_large", "working_notes_updated", "working_notes_item_added", "working_notes_item_dropped", "working_notes_injected", "working_notes_chat_read", "reply_fit_checked", "reward_evaluated", "relatable_offered", "self_mention", "observations_injected", "observations_used", "experience_placed", "relatable_placed", "take_offered", "corrections_carried", "goal_guard_shown", "care_pause_shown", "timeline_shown", "vague_fact_skipped", "hear_you_held", "shared_moment_offered", "shared_moment_used", "moment_capture_asked", "moment_capture_proposed", "moment_capture_refused", "code_plan_step_closed", "code_cross_file_refused", "code_cross_file_overridden", "code_after_edit_check_run", "code_after_edit_check_failed", "code_after_edit_check_suggested", "reply_bans_shown", "notes_standout_held", "notes_second_look", "notes_second_look_kept", "low_move_push_back", "low_move_pattern", "low_move_company", "support_choice_offered", "support_choice_listen", "support_choice_advice", "support_choice_fix", "support_mode_applied", "encouragement_offered", "open_loop_captured", "open_loop_offered", "open_loop_resolved", "callback_offered", "self_history_offered", "initiation_offered", "initiation_fallback", "initiation_answered", "initiation_interest_offered", "initiation_interest_answered", "duration_offered", "curiosity_offered", "curiosity_taken", "shelf_offered", "shelf_taken", "shelf_listed", "finding_selected", "lean_offered", "guardrail_applied", "routines_offered", "followups_offered", "task_results_offered", "meeting_turns", "headsup_offered", "clarify_noted", "clarify_asked", "clarify_answered", "memory_note_dropped", "memory_note_trimmed", "status_offered", "offer_made", "offer_taken", "offer_passed", "offer_held_back", "code_turns", "code_cap_hit", "code_edited", "code_verified", "code_followed", "code_redo") # The rhythm of a coding turn (backend/utils/loop_rhythm.py): turns it was followed on, turns that acted at all, reads before the first act (summed), edits applied, applied edits checked in the next # step, and reading-streak notices shown. Counts only. RHYTHM_KEYS = ("code_rhythm_turns", "code_rhythm_acted_turns", "code_rhythm_reads_before_first_act", "code_rhythm_applies", "code_rhythm_applies_checked", "code_rhythm_streak_notices")