code-puppy 0.0.332__py3-none-any.whl → 0.0.334__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.
@@ -75,8 +75,6 @@ from code_puppy.model_factory import ModelFactory, make_model_settings
75
75
  from code_puppy.summarization_agent import run_summarization_sync
76
76
  from code_puppy.tools.agent_tools import _active_subagent_tasks
77
77
  from code_puppy.tools.command_runner import (
78
- _add_windows_ctrl_handler,
79
- _remove_windows_ctrl_handler,
80
78
  is_awaiting_user_input,
81
79
  )
82
80
 
@@ -1384,15 +1382,14 @@ class BaseAgent(ABC):
1384
1382
  def _print_thinking_banner() -> None:
1385
1383
  """Print the THINKING banner with spinner pause and line clear."""
1386
1384
  nonlocal did_stream_anything
1387
- import sys
1388
1385
  import time
1389
1386
 
1390
1387
  from code_puppy.config import get_banner_color
1391
1388
 
1392
1389
  pause_all_spinners()
1393
1390
  time.sleep(0.1) # Delay to let spinner fully clear
1394
- sys.stdout.write("\r\x1b[K") # Clear line
1395
- sys.stdout.flush()
1391
+ # Clear line and print newline before banner
1392
+ console.print(" " * 50, end="\r")
1396
1393
  console.print() # Newline before banner
1397
1394
  # Bold banner with configurable color and lightning bolt
1398
1395
  thinking_color = get_banner_color("thinking")
@@ -1402,21 +1399,19 @@ class BaseAgent(ABC):
1402
1399
  ),
1403
1400
  end="",
1404
1401
  )
1405
- sys.stdout.flush()
1406
1402
  did_stream_anything = True
1407
1403
 
1408
1404
  def _print_response_banner() -> None:
1409
1405
  """Print the AGENT RESPONSE banner with spinner pause and line clear."""
1410
1406
  nonlocal did_stream_anything
1411
- import sys
1412
1407
  import time
1413
1408
 
1414
1409
  from code_puppy.config import get_banner_color
1415
1410
 
1416
1411
  pause_all_spinners()
1417
1412
  time.sleep(0.1) # Delay to let spinner fully clear
1418
- sys.stdout.write("\r\x1b[K") # Clear line
1419
- sys.stdout.flush()
1413
+ # Clear line and print newline before banner
1414
+ console.print(" " * 50, end="\r")
1420
1415
  console.print() # Newline before banner
1421
1416
  response_color = get_banner_color("agent_response")
1422
1417
  console.print(
@@ -1424,7 +1419,6 @@ class BaseAgent(ABC):
1424
1419
  f"[bold white on {response_color}] AGENT RESPONSE [/bold white on {response_color}]"
1425
1420
  )
1426
1421
  )
1427
- sys.stdout.flush()
1428
1422
  did_stream_anything = True
1429
1423
 
1430
1424
  async for event in events:
@@ -1448,8 +1442,8 @@ class BaseAgent(ABC):
1448
1442
  # Buffer initial content if present
1449
1443
  if part.content and part.content.strip():
1450
1444
  text_buffer[event.index].append(part.content)
1451
- # Use len(content) / 3 for token estimation (more accurate than chunk counting)
1452
- token_count[event.index] += len(part.content) // 3
1445
+ # Count chunks (each part counts as 1)
1446
+ token_count[event.index] += 1
1453
1447
  elif isinstance(part, ToolCallPart):
1454
1448
  streaming_parts.add(event.index)
1455
1449
  tool_parts.add(event.index)
@@ -1467,24 +1461,20 @@ class BaseAgent(ABC):
1467
1461
  if delta.content_delta:
1468
1462
  # For text parts, show token counter then render at end
1469
1463
  if event.index in text_parts:
1470
- import sys
1471
-
1472
1464
  # Print banner on first content
1473
1465
  if event.index not in banner_printed:
1474
1466
  _print_response_banner()
1475
1467
  banner_printed.add(event.index)
1476
1468
  # Accumulate text for final markdown render
1477
1469
  text_buffer[event.index].append(delta.content_delta)
1478
- # Use len(content) / 3 for token estimation
1479
- token_count[event.index] += (
1480
- len(delta.content_delta) // 3
1481
- )
1482
- # Update token counter in place (single line)
1470
+ # Count chunks received
1471
+ token_count[event.index] += 1
1472
+ # Update chunk counter in place (single line)
1483
1473
  count = token_count[event.index]
1484
- sys.stdout.write(
1485
- f"\r\x1b[K ⏳ Receiving... {count} tokens"
1474
+ console.print(
1475
+ f" ⏳ Receiving... {count} chunks ",
1476
+ end="\r",
1486
1477
  )
1487
- sys.stdout.flush()
1488
1478
  else:
1489
1479
  # For thinking parts, stream immediately (dim)
1490
1480
  if event.index not in banner_printed:
@@ -1493,34 +1483,30 @@ class BaseAgent(ABC):
1493
1483
  escaped = escape(delta.content_delta)
1494
1484
  console.print(f"[dim]{escaped}[/dim]", end="")
1495
1485
  elif isinstance(delta, ToolCallPartDelta):
1496
- import sys
1497
-
1498
- # For tool calls, show token counter (use string repr for estimation)
1499
- token_count[event.index] += len(str(delta)) // 3
1486
+ # For tool calls, count chunks received
1487
+ token_count[event.index] += 1
1500
1488
  # Get tool name if available
1501
1489
  tool_name = getattr(delta, "tool_name_delta", "")
1502
1490
  count = token_count[event.index]
1503
1491
  # Display with tool wrench icon and tool name
1504
1492
  if tool_name:
1505
- sys.stdout.write(
1506
- f"\r\x1b[K 🔧 Calling {tool_name}... {count} tokens"
1493
+ console.print(
1494
+ f" 🔧 Calling {tool_name}... {count} chunks ",
1495
+ end="\r",
1507
1496
  )
1508
1497
  else:
1509
- sys.stdout.write(
1510
- f"\r\x1b[K 🔧 Calling tool... {count} tokens"
1498
+ console.print(
1499
+ f" 🔧 Calling tool... {count} chunks ",
1500
+ end="\r",
1511
1501
  )
1512
- sys.stdout.flush()
1513
1502
 
1514
1503
  # PartEndEvent - finish the streaming with a newline
1515
1504
  elif isinstance(event, PartEndEvent):
1516
1505
  if event.index in streaming_parts:
1517
- import sys
1518
-
1519
1506
  # For text parts, clear counter line and render markdown
1520
1507
  if event.index in text_parts:
1521
- # Clear the token counter line
1522
- sys.stdout.write("\r\x1b[K")
1523
- sys.stdout.flush()
1508
+ # Clear the chunk counter line by printing spaces and returning
1509
+ console.print(" " * 50, end="\r")
1524
1510
  # Render the final markdown nicely
1525
1511
  if event.index in text_buffer:
1526
1512
  try:
@@ -1530,11 +1516,10 @@ class BaseAgent(ABC):
1530
1516
  except Exception:
1531
1517
  pass
1532
1518
  del text_buffer[event.index]
1533
- # For tool parts, clear the token counter line
1519
+ # For tool parts, clear the chunk counter line
1534
1520
  elif event.index in tool_parts:
1535
- # Clear the token counter line
1536
- sys.stdout.write("\r\x1b[K")
1537
- sys.stdout.flush()
1521
+ # Clear the chunk counter line by printing spaces and returning
1522
+ console.print(" " * 50, end="\r")
1538
1523
  # For thinking parts, just print newline
1539
1524
  elif event.index in banner_printed:
1540
1525
  console.print() # Final newline after streaming
@@ -1953,7 +1938,12 @@ class BaseAgent(ABC):
1953
1938
  def graceful_sigint_handler(_sig, _frame):
1954
1939
  # When using keyboard-based cancel, SIGINT should be a no-op
1955
1940
  # (just show a hint to user about the configured cancel key)
1941
+ # Also reset terminal to prevent bricking on Windows+uvx
1956
1942
  from code_puppy.keymap import get_cancel_agent_display_name
1943
+ from code_puppy.terminal_utils import reset_windows_terminal_full
1944
+
1945
+ # Reset terminal state first to prevent bricking
1946
+ reset_windows_terminal_full()
1957
1947
 
1958
1948
  cancel_key = get_cancel_agent_display_name()
1959
1949
  emit_info(f"Use {cancel_key} to cancel the agent task.")
@@ -1961,12 +1951,6 @@ class BaseAgent(ABC):
1961
1951
  original_handler = None
1962
1952
  key_listener_stop_event = None
1963
1953
  _key_listener_thread = None
1964
- windows_ctrl_handler = None
1965
-
1966
- # Check if we're on Windows
1967
- import sys
1968
-
1969
- is_windows = sys.platform.startswith("win")
1970
1954
 
1971
1955
  try:
1972
1956
  if cancel_agent_uses_signal():
@@ -1974,27 +1958,10 @@ class BaseAgent(ABC):
1974
1958
  original_handler = signal.signal(
1975
1959
  signal.SIGINT, keyboard_interrupt_handler
1976
1960
  )
1977
- # On Windows, also use SetConsoleCtrlHandler for reliable Ctrl+C with uvx
1978
- if is_windows:
1979
- windows_ctrl_handler = _add_windows_ctrl_handler(
1980
- schedule_agent_cancel
1981
- )
1982
1961
  else:
1983
1962
  # Use keyboard listener for agent cancellation
1984
1963
  # Set a graceful SIGINT handler that shows a hint
1985
1964
  original_handler = signal.signal(signal.SIGINT, graceful_sigint_handler)
1986
- # On Windows, SetConsoleCtrlHandler should also show the hint
1987
- if is_windows:
1988
-
1989
- def graceful_ctrl_handler():
1990
- from code_puppy.keymap import get_cancel_agent_display_name
1991
-
1992
- cancel_key = get_cancel_agent_display_name()
1993
- emit_info(f"Use {cancel_key} to cancel the agent task.")
1994
-
1995
- windows_ctrl_handler = _add_windows_ctrl_handler(
1996
- graceful_ctrl_handler
1997
- )
1998
1965
  # Spawn keyboard listener with the cancel agent callback
1999
1966
  key_listener_stop_event = threading.Event()
2000
1967
  _key_listener_thread = self._spawn_ctrl_x_key_listener(
@@ -2024,17 +1991,8 @@ class BaseAgent(ABC):
2024
1991
  # Stop keyboard listener if it was started
2025
1992
  if key_listener_stop_event is not None:
2026
1993
  key_listener_stop_event.set()
2027
- # Remove Windows console handler
2028
- if windows_ctrl_handler is not None:
2029
- _remove_windows_ctrl_handler(windows_ctrl_handler)
2030
1994
  # Restore original signal handler
2031
1995
  if (
2032
1996
  original_handler is not None
2033
1997
  ): # Explicit None check - SIG_DFL can be 0/falsy!
2034
1998
  signal.signal(signal.SIGINT, original_handler)
2035
- # Windows-specific: Reset terminal after Ctrl+C to prevent corruption
2036
- # This fixes the issue where Enter key shows as 'm' after interrupting with uvx
2037
- if is_windows:
2038
- from code_puppy.terminal_utils import reset_windows_terminal_full
2039
-
2040
- reset_windows_terminal_full()
code_puppy/cli_runner.py CHANGED
@@ -171,6 +171,45 @@ async def main():
171
171
  emit_error(str(e))
172
172
  sys.exit(1)
173
173
 
174
+ # Show uvx detection notice if we're on Windows + uvx
175
+ # Also disable Ctrl+C at the console level to prevent terminal bricking
176
+ try:
177
+ from code_puppy.uvx_detection import should_use_alternate_cancel_key
178
+
179
+ if should_use_alternate_cancel_key():
180
+ from code_puppy.terminal_utils import (
181
+ disable_windows_ctrl_c,
182
+ set_keep_ctrl_c_disabled,
183
+ )
184
+
185
+ # Disable Ctrl+C at the console input level
186
+ # This prevents Ctrl+C from being processed as a signal at all
187
+ disable_windows_ctrl_c()
188
+
189
+ # Set flag to keep it disabled (prompt_toolkit may re-enable it)
190
+ set_keep_ctrl_c_disabled(True)
191
+
192
+ # Use print directly - emit_system_message can get cleared by ANSI codes
193
+ print(
194
+ "🔧 Detected uvx launch on Windows - using Ctrl+K for cancellation "
195
+ "(Ctrl+C is disabled to prevent terminal issues)"
196
+ )
197
+
198
+ # Also install a SIGINT handler as backup
199
+ import signal
200
+
201
+ from code_puppy.terminal_utils import reset_windows_terminal_full
202
+
203
+ def _uvx_protective_sigint_handler(_sig, _frame):
204
+ """Protective SIGINT handler for Windows+uvx."""
205
+ reset_windows_terminal_full()
206
+ # Re-disable Ctrl+C in case something re-enabled it
207
+ disable_windows_ctrl_c()
208
+
209
+ signal.signal(signal.SIGINT, _uvx_protective_sigint_handler)
210
+ except ImportError:
211
+ pass # uvx_detection module not available, ignore
212
+
174
213
  # Load API keys from puppy.cfg into environment variables
175
214
  from code_puppy.config import load_api_keys_to_environment
176
215
 
@@ -325,6 +364,7 @@ async def interactive_mode(message_renderer, initial_command: str = None) -> Non
325
364
  emit_system_message(
326
365
  "Use /diff to configure diff highlighting colors for file changes."
327
366
  )
367
+ emit_system_message("To re-run the tutorial, use /tutorial.")
328
368
  try:
329
369
  from code_puppy.command_line.motd import print_motd
330
370
 
@@ -421,10 +461,6 @@ async def interactive_mode(message_renderer, initial_command: str = None) -> Non
421
461
  current_agent_task = None
422
462
 
423
463
  while True:
424
- # Windows-specific: Aggressively reset terminal at the start of every loop
425
- # This fixes terminal corruption after Ctrl+C, especially when running via uvx
426
- reset_windows_terminal_full()
427
-
428
464
  from code_puppy.agents.agent_manager import get_current_agent
429
465
  from code_puppy.messaging import emit_info
430
466
 
@@ -444,6 +480,15 @@ async def interactive_mode(message_renderer, initial_command: str = None) -> Non
444
480
  task = await get_input_with_combined_completion(
445
481
  get_prompt_with_active_model(), history_file=COMMAND_HISTORY_FILE
446
482
  )
483
+
484
+ # Windows+uvx: Re-disable Ctrl+C after prompt_toolkit
485
+ # (prompt_toolkit restores console mode which re-enables Ctrl+C)
486
+ try:
487
+ from code_puppy.terminal_utils import ensure_ctrl_c_disabled
488
+
489
+ ensure_ctrl_c_disabled()
490
+ except ImportError:
491
+ pass
447
492
  except ImportError:
448
493
  # Fall back to basic input if prompt_toolkit is not available
449
494
  task = input(">>> ")
@@ -608,8 +653,14 @@ async def interactive_mode(message_renderer, initial_command: str = None) -> Non
608
653
  # Check if the task was cancelled (but don't show message if we just killed processes)
609
654
  if result is None:
610
655
  # Windows-specific: Reset terminal state after cancellation
611
- # Use full reset (ANSI + console mode) to fix stdin after Ctrl+C
612
- reset_windows_terminal_full()
656
+ reset_windows_terminal_ansi()
657
+ # Re-disable Ctrl+C if needed (uvx mode)
658
+ try:
659
+ from code_puppy.terminal_utils import ensure_ctrl_c_disabled
660
+
661
+ ensure_ctrl_c_disabled()
662
+ except ImportError:
663
+ pass
613
664
  continue
614
665
  # Get the structured response
615
666
  agent_response = result.output
@@ -650,6 +701,15 @@ async def interactive_mode(message_renderer, initial_command: str = None) -> Non
650
701
 
651
702
  auto_save_session_if_enabled()
652
703
 
704
+ # Re-disable Ctrl+C if needed (uvx mode) - must be done after
705
+ # each iteration as various operations may restore console mode
706
+ try:
707
+ from code_puppy.terminal_utils import ensure_ctrl_c_disabled
708
+
709
+ ensure_ctrl_c_disabled()
710
+ except ImportError:
711
+ pass
712
+
653
713
 
654
714
  def prettier_code_blocks():
655
715
  """Configure Rich to use prettier code block rendering."""
@@ -46,7 +46,7 @@ def handle_show_command(command: str) -> bool:
46
46
  get_use_dbos,
47
47
  get_yolo_mode,
48
48
  )
49
- from code_puppy.keymap import get_cancel_agent_key, get_cancel_agent_display_name
49
+ from code_puppy.keymap import get_cancel_agent_display_name
50
50
  from code_puppy.messaging import emit_info
51
51
 
52
52
  puppy_name = get_puppy_name()
@@ -115,6 +115,57 @@ def handle_motd_command(command: str) -> bool:
115
115
  return True
116
116
 
117
117
 
118
+ @register_command(
119
+ name="tutorial",
120
+ description="Run the interactive tutorial wizard",
121
+ usage="/tutorial",
122
+ category="core",
123
+ )
124
+ def handle_tutorial_command(command: str) -> bool:
125
+ """Run the interactive tutorial wizard.
126
+
127
+ Usage:
128
+ /tutorial - Run the tutorial (can be run anytime)
129
+ """
130
+ import asyncio
131
+ import concurrent.futures
132
+
133
+ from code_puppy.command_line.onboarding_wizard import (
134
+ reset_onboarding,
135
+ run_onboarding_wizard,
136
+ )
137
+ from code_puppy.config import set_model_name
138
+
139
+ # Always reset so user can re-run the tutorial anytime
140
+ reset_onboarding()
141
+
142
+ # Run the async wizard in a thread pool (same pattern as agent picker)
143
+ with concurrent.futures.ThreadPoolExecutor() as executor:
144
+ future = executor.submit(lambda: asyncio.run(run_onboarding_wizard()))
145
+ result = future.result(timeout=300) # 5 min timeout
146
+
147
+ if result == "chatgpt":
148
+ emit_info("🔐 Starting ChatGPT OAuth flow...")
149
+ from code_puppy.plugins.chatgpt_oauth.oauth_flow import run_oauth_flow
150
+
151
+ run_oauth_flow()
152
+ set_model_name("chatgpt-gpt-5.2-codex")
153
+ elif result == "claude":
154
+ emit_info("🔐 Starting Claude Code OAuth flow...")
155
+ from code_puppy.plugins.claude_code_oauth.register_callbacks import (
156
+ _perform_authentication,
157
+ )
158
+
159
+ _perform_authentication()
160
+ set_model_name("claude-code-claude-opus-4-5-20251101")
161
+ elif result == "completed":
162
+ emit_info("🎉 Tutorial complete! Happy coding!")
163
+ elif result == "skipped":
164
+ emit_info("⏭️ Tutorial skipped. Run /tutorial anytime!")
165
+
166
+ return True
167
+
168
+
118
169
  @register_command(
119
170
  name="exit",
120
171
  description="Exit interactive mode",