code-puppy 0.0.302__py3-none-any.whl → 0.0.335__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.
Files changed (87) hide show
  1. code_puppy/agents/base_agent.py +343 -35
  2. code_puppy/chatgpt_codex_client.py +283 -0
  3. code_puppy/cli_runner.py +898 -0
  4. code_puppy/command_line/add_model_menu.py +23 -1
  5. code_puppy/command_line/autosave_menu.py +271 -35
  6. code_puppy/command_line/colors_menu.py +520 -0
  7. code_puppy/command_line/command_handler.py +8 -2
  8. code_puppy/command_line/config_commands.py +82 -10
  9. code_puppy/command_line/core_commands.py +70 -7
  10. code_puppy/command_line/diff_menu.py +5 -0
  11. code_puppy/command_line/mcp/custom_server_form.py +4 -0
  12. code_puppy/command_line/mcp/edit_command.py +3 -1
  13. code_puppy/command_line/mcp/handler.py +7 -2
  14. code_puppy/command_line/mcp/install_command.py +8 -3
  15. code_puppy/command_line/mcp/install_menu.py +5 -1
  16. code_puppy/command_line/mcp/logs_command.py +173 -64
  17. code_puppy/command_line/mcp/restart_command.py +7 -2
  18. code_puppy/command_line/mcp/search_command.py +10 -4
  19. code_puppy/command_line/mcp/start_all_command.py +16 -6
  20. code_puppy/command_line/mcp/start_command.py +3 -1
  21. code_puppy/command_line/mcp/status_command.py +2 -1
  22. code_puppy/command_line/mcp/stop_all_command.py +5 -1
  23. code_puppy/command_line/mcp/stop_command.py +3 -1
  24. code_puppy/command_line/mcp/wizard_utils.py +10 -4
  25. code_puppy/command_line/model_settings_menu.py +58 -7
  26. code_puppy/command_line/motd.py +13 -7
  27. code_puppy/command_line/onboarding_slides.py +180 -0
  28. code_puppy/command_line/onboarding_wizard.py +340 -0
  29. code_puppy/command_line/prompt_toolkit_completion.py +16 -2
  30. code_puppy/command_line/session_commands.py +11 -4
  31. code_puppy/config.py +106 -17
  32. code_puppy/http_utils.py +155 -196
  33. code_puppy/keymap.py +8 -0
  34. code_puppy/main.py +5 -828
  35. code_puppy/mcp_/__init__.py +17 -0
  36. code_puppy/mcp_/blocking_startup.py +61 -32
  37. code_puppy/mcp_/config_wizard.py +5 -1
  38. code_puppy/mcp_/managed_server.py +23 -3
  39. code_puppy/mcp_/manager.py +65 -0
  40. code_puppy/mcp_/mcp_logs.py +224 -0
  41. code_puppy/messaging/__init__.py +20 -4
  42. code_puppy/messaging/bus.py +64 -0
  43. code_puppy/messaging/markdown_patches.py +57 -0
  44. code_puppy/messaging/messages.py +16 -0
  45. code_puppy/messaging/renderers.py +21 -9
  46. code_puppy/messaging/rich_renderer.py +113 -67
  47. code_puppy/messaging/spinner/console_spinner.py +34 -0
  48. code_puppy/model_factory.py +271 -45
  49. code_puppy/model_utils.py +57 -48
  50. code_puppy/models.json +21 -7
  51. code_puppy/plugins/__init__.py +12 -0
  52. code_puppy/plugins/antigravity_oauth/__init__.py +10 -0
  53. code_puppy/plugins/antigravity_oauth/accounts.py +406 -0
  54. code_puppy/plugins/antigravity_oauth/antigravity_model.py +612 -0
  55. code_puppy/plugins/antigravity_oauth/config.py +42 -0
  56. code_puppy/plugins/antigravity_oauth/constants.py +136 -0
  57. code_puppy/plugins/antigravity_oauth/oauth.py +478 -0
  58. code_puppy/plugins/antigravity_oauth/register_callbacks.py +406 -0
  59. code_puppy/plugins/antigravity_oauth/storage.py +271 -0
  60. code_puppy/plugins/antigravity_oauth/test_plugin.py +319 -0
  61. code_puppy/plugins/antigravity_oauth/token.py +167 -0
  62. code_puppy/plugins/antigravity_oauth/transport.py +595 -0
  63. code_puppy/plugins/antigravity_oauth/utils.py +169 -0
  64. code_puppy/plugins/chatgpt_oauth/config.py +5 -1
  65. code_puppy/plugins/chatgpt_oauth/oauth_flow.py +5 -6
  66. code_puppy/plugins/chatgpt_oauth/register_callbacks.py +5 -3
  67. code_puppy/plugins/chatgpt_oauth/test_plugin.py +26 -11
  68. code_puppy/plugins/chatgpt_oauth/utils.py +180 -65
  69. code_puppy/plugins/claude_code_oauth/register_callbacks.py +30 -0
  70. code_puppy/plugins/claude_code_oauth/utils.py +1 -0
  71. code_puppy/plugins/shell_safety/agent_shell_safety.py +1 -118
  72. code_puppy/plugins/shell_safety/register_callbacks.py +44 -3
  73. code_puppy/prompts/codex_system_prompt.md +310 -0
  74. code_puppy/pydantic_patches.py +131 -0
  75. code_puppy/reopenable_async_client.py +8 -8
  76. code_puppy/terminal_utils.py +291 -0
  77. code_puppy/tools/agent_tools.py +34 -9
  78. code_puppy/tools/command_runner.py +344 -27
  79. code_puppy/tools/file_operations.py +33 -45
  80. code_puppy/uvx_detection.py +242 -0
  81. {code_puppy-0.0.302.data → code_puppy-0.0.335.data}/data/code_puppy/models.json +21 -7
  82. {code_puppy-0.0.302.dist-info → code_puppy-0.0.335.dist-info}/METADATA +30 -1
  83. {code_puppy-0.0.302.dist-info → code_puppy-0.0.335.dist-info}/RECORD +87 -64
  84. {code_puppy-0.0.302.data → code_puppy-0.0.335.data}/data/code_puppy/models_dev_api.json +0 -0
  85. {code_puppy-0.0.302.dist-info → code_puppy-0.0.335.dist-info}/WHEEL +0 -0
  86. {code_puppy-0.0.302.dist-info → code_puppy-0.0.335.dist-info}/entry_points.txt +0 -0
  87. {code_puppy-0.0.302.dist-info → code_puppy-0.0.335.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,898 @@
1
+ """CLI runner for Code Puppy.
2
+
3
+ Contains the main application logic, interactive mode, and entry point.
4
+ """
5
+
6
+ # Apply pydantic-ai patches BEFORE any pydantic-ai imports
7
+ from code_puppy.pydantic_patches import apply_all_patches
8
+
9
+ apply_all_patches()
10
+
11
+ import argparse
12
+ import asyncio
13
+ import os
14
+ import sys
15
+ import time
16
+ import traceback
17
+ from pathlib import Path
18
+
19
+ from dbos import DBOS, DBOSConfig
20
+ from rich.console import Console, ConsoleOptions, RenderResult
21
+ from rich.markdown import CodeBlock, Markdown
22
+ from rich.syntax import Syntax
23
+ from rich.text import Text
24
+
25
+ from code_puppy import __version__, callbacks, plugins
26
+ from code_puppy.agents import get_current_agent
27
+ from code_puppy.command_line.attachments import parse_prompt_attachments
28
+ from code_puppy.config import (
29
+ AUTOSAVE_DIR,
30
+ COMMAND_HISTORY_FILE,
31
+ DBOS_DATABASE_URL,
32
+ ensure_config_exists,
33
+ finalize_autosave_session,
34
+ get_use_dbos,
35
+ initialize_command_history_file,
36
+ save_command_to_history,
37
+ )
38
+ from code_puppy.http_utils import find_available_port
39
+ from code_puppy.keymap import (
40
+ KeymapError,
41
+ get_cancel_agent_display_name,
42
+ validate_cancel_agent_key,
43
+ )
44
+ from code_puppy.messaging import emit_info
45
+ from code_puppy.terminal_utils import (
46
+ reset_unix_terminal,
47
+ reset_windows_terminal_ansi,
48
+ reset_windows_terminal_full,
49
+ )
50
+ from code_puppy.tools.common import console
51
+ from code_puppy.version_checker import default_version_mismatch_behavior
52
+
53
+ plugins.load_plugin_callbacks()
54
+
55
+
56
+ async def main():
57
+ """Main async entry point for Code Puppy CLI."""
58
+ parser = argparse.ArgumentParser(description="Code Puppy - A code generation agent")
59
+ parser.add_argument(
60
+ "--version",
61
+ "-v",
62
+ action="version",
63
+ version=f"{__version__}",
64
+ help="Show version and exit",
65
+ )
66
+ parser.add_argument(
67
+ "--interactive",
68
+ "-i",
69
+ action="store_true",
70
+ help="Run in interactive mode",
71
+ )
72
+ parser.add_argument(
73
+ "--prompt",
74
+ "-p",
75
+ type=str,
76
+ help="Execute a single prompt and exit (no interactive mode)",
77
+ )
78
+ parser.add_argument(
79
+ "--agent",
80
+ "-a",
81
+ type=str,
82
+ help="Specify which agent to use (e.g., --agent code-puppy)",
83
+ )
84
+ parser.add_argument(
85
+ "--model",
86
+ "-m",
87
+ type=str,
88
+ help="Specify which model to use (e.g., --model gpt-5)",
89
+ )
90
+ parser.add_argument(
91
+ "command", nargs="*", help="Run a single command (deprecated, use -p instead)"
92
+ )
93
+ args = parser.parse_args()
94
+ from rich.console import Console
95
+
96
+ from code_puppy.messaging import (
97
+ RichConsoleRenderer,
98
+ SynchronousInteractiveRenderer,
99
+ get_global_queue,
100
+ get_message_bus,
101
+ )
102
+
103
+ # Create a shared console for both renderers
104
+ display_console = Console()
105
+
106
+ # Legacy renderer for backward compatibility (emits via get_global_queue)
107
+ message_queue = get_global_queue()
108
+ message_renderer = SynchronousInteractiveRenderer(message_queue, display_console)
109
+ message_renderer.start()
110
+
111
+ # New MessageBus renderer for structured messages (tools emit here)
112
+ message_bus = get_message_bus()
113
+ bus_renderer = RichConsoleRenderer(message_bus, display_console)
114
+ bus_renderer.start()
115
+
116
+ initialize_command_history_file()
117
+ from code_puppy.messaging import emit_error, emit_system_message
118
+
119
+ # Show the awesome Code Puppy logo when entering interactive mode
120
+ # This happens when: no -p flag (prompt-only mode) is used
121
+ # The logo should appear for both `code-puppy` and `code-puppy -i`
122
+ if not args.prompt:
123
+ try:
124
+ import pyfiglet
125
+
126
+ intro_lines = pyfiglet.figlet_format(
127
+ "CODE PUPPY", font="ansi_shadow"
128
+ ).split("\n")
129
+
130
+ # Simple blue to green gradient (top to bottom)
131
+ gradient_colors = ["bright_blue", "bright_cyan", "bright_green"]
132
+ display_console.print("\n")
133
+
134
+ lines = []
135
+ # Apply gradient line by line
136
+ for line_num, line in enumerate(intro_lines):
137
+ if line.strip():
138
+ # Use line position to determine color (top blue, middle cyan, bottom green)
139
+ color_idx = min(line_num // 2, len(gradient_colors) - 1)
140
+ color = gradient_colors[color_idx]
141
+ lines.append(f"[{color}]{line}[/{color}]")
142
+ else:
143
+ lines.append("")
144
+ # Print directly to console to avoid the 'dim' style from emit_system_message
145
+ display_console.print("\n".join(lines))
146
+ except ImportError:
147
+ emit_system_message("🐶 Code Puppy is Loading...")
148
+
149
+ available_port = find_available_port()
150
+ if available_port is None:
151
+ emit_error("No available ports in range 8090-9010!")
152
+ return
153
+
154
+ # Early model setting if specified via command line
155
+ # This happens before ensure_config_exists() to ensure config is set up correctly
156
+ early_model = None
157
+ if args.model:
158
+ early_model = args.model.strip()
159
+ from code_puppy.config import set_model_name
160
+
161
+ set_model_name(early_model)
162
+
163
+ ensure_config_exists()
164
+
165
+ # Validate cancel_agent_key configuration early
166
+ try:
167
+ validate_cancel_agent_key()
168
+ except KeymapError as e:
169
+ from code_puppy.messaging import emit_error
170
+
171
+ emit_error(str(e))
172
+ sys.exit(1)
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
+
213
+ # Load API keys from puppy.cfg into environment variables
214
+ from code_puppy.config import load_api_keys_to_environment
215
+
216
+ load_api_keys_to_environment()
217
+
218
+ # Handle model validation from command line (validation happens here, setting was earlier)
219
+ if args.model:
220
+ from code_puppy.config import _validate_model_exists
221
+
222
+ model_name = args.model.strip()
223
+ try:
224
+ # Validate that the model exists in models.json
225
+ if not _validate_model_exists(model_name):
226
+ from code_puppy.model_factory import ModelFactory
227
+
228
+ models_config = ModelFactory.load_config()
229
+ available_models = list(models_config.keys()) if models_config else []
230
+
231
+ emit_error(f"Model '{model_name}' not found")
232
+ emit_system_message(f"Available models: {', '.join(available_models)}")
233
+ sys.exit(1)
234
+
235
+ # Model is valid, show confirmation (already set earlier)
236
+ emit_system_message(f"🎯 Using model: {model_name}")
237
+ except Exception as e:
238
+ emit_error(f"Error validating model: {str(e)}")
239
+ sys.exit(1)
240
+
241
+ # Handle agent selection from command line
242
+ if args.agent:
243
+ from code_puppy.agents.agent_manager import (
244
+ get_available_agents,
245
+ set_current_agent,
246
+ )
247
+
248
+ agent_name = args.agent.lower()
249
+ try:
250
+ # First check if the agent exists by getting available agents
251
+ available_agents = get_available_agents()
252
+ if agent_name not in available_agents:
253
+ emit_error(f"Agent '{agent_name}' not found")
254
+ emit_system_message(
255
+ f"Available agents: {', '.join(available_agents.keys())}"
256
+ )
257
+ sys.exit(1)
258
+
259
+ # Agent exists, set it
260
+ set_current_agent(agent_name)
261
+ emit_system_message(f"🤖 Using agent: {agent_name}")
262
+ except Exception as e:
263
+ emit_error(f"Error setting agent: {str(e)}")
264
+ sys.exit(1)
265
+
266
+ current_version = __version__
267
+
268
+ no_version_update = os.getenv("NO_VERSION_UPDATE", "").lower() in (
269
+ "1",
270
+ "true",
271
+ "yes",
272
+ "on",
273
+ )
274
+ if no_version_update:
275
+ version_msg = f"Current version: {current_version}"
276
+ update_disabled_msg = (
277
+ "Update phase disabled because NO_VERSION_UPDATE is set to 1 or true"
278
+ )
279
+ emit_system_message(version_msg)
280
+ emit_system_message(update_disabled_msg)
281
+ else:
282
+ if len(callbacks.get_callbacks("version_check")):
283
+ await callbacks.on_version_check(current_version)
284
+ else:
285
+ default_version_mismatch_behavior(current_version)
286
+
287
+ await callbacks.on_startup()
288
+
289
+ # Initialize DBOS if not disabled
290
+ if get_use_dbos():
291
+ # Append a Unix timestamp in ms to the version for uniqueness
292
+ dbos_app_version = os.environ.get(
293
+ "DBOS_APP_VERSION", f"{current_version}-{int(time.time() * 1000)}"
294
+ )
295
+ dbos_config: DBOSConfig = {
296
+ "name": "dbos-code-puppy",
297
+ "system_database_url": DBOS_DATABASE_URL,
298
+ "run_admin_server": False,
299
+ "conductor_key": os.environ.get(
300
+ "DBOS_CONDUCTOR_KEY"
301
+ ), # Optional, if set in env, connect to conductor
302
+ "log_level": os.environ.get(
303
+ "DBOS_LOG_LEVEL", "ERROR"
304
+ ), # Default to ERROR level to suppress verbose logs
305
+ "application_version": dbos_app_version, # Match DBOS app version to Code Puppy version
306
+ }
307
+ try:
308
+ DBOS(config=dbos_config)
309
+ DBOS.launch()
310
+ except Exception as e:
311
+ emit_error(f"Error initializing DBOS: {e}")
312
+ sys.exit(1)
313
+ else:
314
+ pass
315
+
316
+ global shutdown_flag
317
+ shutdown_flag = False
318
+ try:
319
+ initial_command = None
320
+ prompt_only_mode = False
321
+
322
+ if args.prompt:
323
+ initial_command = args.prompt
324
+ prompt_only_mode = True
325
+ elif args.command:
326
+ initial_command = " ".join(args.command)
327
+ prompt_only_mode = False
328
+
329
+ if prompt_only_mode:
330
+ await execute_single_prompt(initial_command, message_renderer)
331
+ else:
332
+ # Default to interactive mode (no args = same as -i)
333
+ await interactive_mode(message_renderer, initial_command=initial_command)
334
+ finally:
335
+ if message_renderer:
336
+ message_renderer.stop()
337
+ if bus_renderer:
338
+ bus_renderer.stop()
339
+ await callbacks.on_shutdown()
340
+ if get_use_dbos():
341
+ DBOS.destroy()
342
+
343
+
344
+ async def interactive_mode(message_renderer, initial_command: str = None) -> None:
345
+ """Run the agent in interactive mode."""
346
+ from code_puppy.command_line.command_handler import handle_command
347
+
348
+ display_console = message_renderer.console
349
+ from code_puppy.messaging import emit_info, emit_system_message
350
+
351
+ emit_system_message("Type '/exit' or '/quit' to exit the interactive mode.")
352
+ emit_system_message("Type 'clear' to reset the conversation history.")
353
+ emit_system_message("Type /help to view all commands")
354
+ emit_system_message(
355
+ "Type @ for path completion, or /model to pick a model. Toggle multiline with Alt+M or F2; newline: Ctrl+J."
356
+ )
357
+ cancel_key = get_cancel_agent_display_name()
358
+ emit_system_message(
359
+ f"Press {cancel_key} during processing to cancel the current task or inference. Use Ctrl+X to interrupt running shell commands."
360
+ )
361
+ emit_system_message(
362
+ "Use /autosave_load to manually load a previous autosave session."
363
+ )
364
+ emit_system_message(
365
+ "Use /diff to configure diff highlighting colors for file changes."
366
+ )
367
+ emit_system_message("To re-run the tutorial, use /tutorial.")
368
+ try:
369
+ from code_puppy.command_line.motd import print_motd
370
+
371
+ print_motd(console, force=False)
372
+ except Exception as e:
373
+ from code_puppy.messaging import emit_warning
374
+
375
+ emit_warning(f"MOTD error: {e}")
376
+
377
+ # Initialize the runtime agent manager
378
+ if initial_command:
379
+ from code_puppy.agents import get_current_agent
380
+ from code_puppy.messaging import emit_info, emit_success, emit_system_message
381
+
382
+ agent = get_current_agent()
383
+ emit_info(f"Processing initial command: {initial_command}")
384
+
385
+ try:
386
+ # Check if any tool is waiting for user input before showing spinner
387
+ try:
388
+ from code_puppy.tools.command_runner import is_awaiting_user_input
389
+
390
+ awaiting_input = is_awaiting_user_input()
391
+ except ImportError:
392
+ awaiting_input = False
393
+
394
+ # Run with or without spinner based on whether we're awaiting input
395
+ response, agent_task = await run_prompt_with_attachments(
396
+ agent,
397
+ initial_command,
398
+ spinner_console=display_console,
399
+ use_spinner=not awaiting_input,
400
+ )
401
+ if response is not None:
402
+ agent_response = response.output
403
+
404
+ # Update the agent's message history with the complete conversation
405
+ # including the final assistant response
406
+ if hasattr(response, "all_messages"):
407
+ agent.set_message_history(list(response.all_messages()))
408
+
409
+ # Emit structured message for proper markdown rendering
410
+ from code_puppy.messaging import get_message_bus
411
+ from code_puppy.messaging.messages import AgentResponseMessage
412
+
413
+ response_msg = AgentResponseMessage(
414
+ content=agent_response,
415
+ is_markdown=True,
416
+ )
417
+ get_message_bus().emit(response_msg)
418
+
419
+ emit_success("🐶 Continuing in Interactive Mode")
420
+ emit_system_message(
421
+ "Your command and response are preserved in the conversation history."
422
+ )
423
+
424
+ except Exception as e:
425
+ from code_puppy.messaging import emit_error
426
+
427
+ emit_error(f"Error processing initial command: {str(e)}")
428
+
429
+ # Check if prompt_toolkit is installed
430
+ try:
431
+ from code_puppy.command_line.prompt_toolkit_completion import (
432
+ get_input_with_combined_completion,
433
+ get_prompt_with_active_model,
434
+ )
435
+ except ImportError:
436
+ from code_puppy.messaging import emit_warning
437
+
438
+ emit_warning("Warning: prompt_toolkit not installed. Installing now...")
439
+ try:
440
+ import subprocess
441
+
442
+ subprocess.check_call(
443
+ [sys.executable, "-m", "pip", "install", "--quiet", "prompt_toolkit"]
444
+ )
445
+ from code_puppy.messaging import emit_success
446
+
447
+ emit_success("Successfully installed prompt_toolkit")
448
+ from code_puppy.command_line.prompt_toolkit_completion import (
449
+ get_input_with_combined_completion,
450
+ get_prompt_with_active_model,
451
+ )
452
+ except Exception as e:
453
+ from code_puppy.messaging import emit_error, emit_warning
454
+
455
+ emit_error(f"Error installing prompt_toolkit: {e}")
456
+ emit_warning("Falling back to basic input without tab completion")
457
+
458
+ # Autosave loading is now manual - use /autosave_load command
459
+
460
+ # Auto-run tutorial on first startup
461
+ try:
462
+ from code_puppy.command_line.onboarding_wizard import should_show_onboarding
463
+
464
+ if should_show_onboarding():
465
+ import asyncio
466
+ import concurrent.futures
467
+
468
+ from code_puppy.command_line.onboarding_wizard import run_onboarding_wizard
469
+ from code_puppy.config import set_model_name
470
+ from code_puppy.messaging import emit_info
471
+
472
+ with concurrent.futures.ThreadPoolExecutor() as executor:
473
+ future = executor.submit(lambda: asyncio.run(run_onboarding_wizard()))
474
+ result = future.result(timeout=300)
475
+
476
+ if result == "chatgpt":
477
+ emit_info("🔐 Starting ChatGPT OAuth flow...")
478
+ from code_puppy.plugins.chatgpt_oauth.oauth_flow import run_oauth_flow
479
+
480
+ run_oauth_flow()
481
+ set_model_name("chatgpt-gpt-5.2-codex")
482
+ elif result == "claude":
483
+ emit_info("🔐 Starting Claude Code OAuth flow...")
484
+ from code_puppy.plugins.claude_code_oauth.register_callbacks import (
485
+ _perform_authentication,
486
+ )
487
+
488
+ _perform_authentication()
489
+ set_model_name("claude-code-claude-opus-4-5-20251101")
490
+ elif result == "completed":
491
+ emit_info("🎉 Tutorial complete! Happy coding!")
492
+ elif result == "skipped":
493
+ emit_info("⏭️ Tutorial skipped. Run /tutorial anytime!")
494
+ except Exception as e:
495
+ from code_puppy.messaging import emit_warning
496
+
497
+ emit_warning(f"Tutorial auto-start failed: {e}")
498
+
499
+ # Track the current agent task for cancellation on quit
500
+ current_agent_task = None
501
+
502
+ while True:
503
+ from code_puppy.agents.agent_manager import get_current_agent
504
+ from code_puppy.messaging import emit_info
505
+
506
+ # Get the custom prompt from the current agent, or use default
507
+ current_agent = get_current_agent()
508
+ user_prompt = current_agent.get_user_prompt() or "Enter your coding task:"
509
+
510
+ emit_info(f"{user_prompt}\n")
511
+
512
+ try:
513
+ # Use prompt_toolkit for enhanced input with path completion
514
+ try:
515
+ # Windows-specific: Reset terminal state before prompting
516
+ reset_windows_terminal_ansi()
517
+
518
+ # Use the async version of get_input_with_combined_completion
519
+ task = await get_input_with_combined_completion(
520
+ get_prompt_with_active_model(), history_file=COMMAND_HISTORY_FILE
521
+ )
522
+
523
+ # Windows+uvx: Re-disable Ctrl+C after prompt_toolkit
524
+ # (prompt_toolkit restores console mode which re-enables Ctrl+C)
525
+ try:
526
+ from code_puppy.terminal_utils import ensure_ctrl_c_disabled
527
+
528
+ ensure_ctrl_c_disabled()
529
+ except ImportError:
530
+ pass
531
+ except ImportError:
532
+ # Fall back to basic input if prompt_toolkit is not available
533
+ task = input(">>> ")
534
+
535
+ except (KeyboardInterrupt, EOFError):
536
+ # Handle Ctrl+C or Ctrl+D
537
+ # Windows-specific: Reset terminal state after interrupt to prevent
538
+ # the terminal from becoming unresponsive (can't type characters)
539
+ reset_windows_terminal_full()
540
+ from code_puppy.messaging import emit_warning
541
+
542
+ emit_warning("\nInput cancelled")
543
+ continue
544
+
545
+ # Check for exit commands (plain text or command form)
546
+ if task.strip().lower() in ["exit", "quit"] or task.strip().lower() in [
547
+ "/exit",
548
+ "/quit",
549
+ ]:
550
+ import asyncio
551
+
552
+ from code_puppy.messaging import emit_success
553
+
554
+ emit_success("Goodbye!")
555
+
556
+ # Cancel any running agent task for clean shutdown
557
+ if current_agent_task and not current_agent_task.done():
558
+ emit_info("Cancelling running agent task...")
559
+ current_agent_task.cancel()
560
+ try:
561
+ await current_agent_task
562
+ except asyncio.CancelledError:
563
+ pass # Expected when cancelling
564
+
565
+ # The renderer is stopped in the finally block of main().
566
+ break
567
+
568
+ # Check for clear command (supports both `clear` and `/clear`)
569
+ if task.strip().lower() in ("clear", "/clear"):
570
+ from code_puppy.messaging import (
571
+ emit_info,
572
+ emit_system_message,
573
+ emit_warning,
574
+ )
575
+
576
+ agent = get_current_agent()
577
+ new_session_id = finalize_autosave_session()
578
+ agent.clear_message_history()
579
+ emit_warning("Conversation history cleared!")
580
+ emit_system_message("The agent will not remember previous interactions.")
581
+ emit_info(f"Auto-save session rotated to: {new_session_id}")
582
+ continue
583
+
584
+ # Parse attachments first so leading paths aren't misread as commands
585
+ processed_for_commands = parse_prompt_attachments(task)
586
+ cleaned_for_commands = (processed_for_commands.prompt or "").strip()
587
+
588
+ # Handle / commands based on cleaned prompt (after stripping attachments)
589
+ if cleaned_for_commands.startswith("/"):
590
+ try:
591
+ command_result = handle_command(cleaned_for_commands)
592
+ except Exception as e:
593
+ from code_puppy.messaging import emit_error
594
+
595
+ emit_error(f"Command error: {e}")
596
+ # Continue interactive loop instead of exiting
597
+ continue
598
+ if command_result is True:
599
+ continue
600
+ elif isinstance(command_result, str):
601
+ if command_result == "__AUTOSAVE_LOAD__":
602
+ # Handle async autosave loading
603
+ try:
604
+ # Check if we're in a real interactive terminal
605
+ # (not pexpect/tests) - interactive picker requires proper TTY
606
+ use_interactive_picker = (
607
+ sys.stdin.isatty() and sys.stdout.isatty()
608
+ )
609
+
610
+ # Allow environment variable override for tests
611
+ if os.getenv("CODE_PUPPY_NO_TUI") == "1":
612
+ use_interactive_picker = False
613
+
614
+ if use_interactive_picker:
615
+ # Use interactive picker for terminal sessions
616
+ from code_puppy.agents.agent_manager import (
617
+ get_current_agent,
618
+ )
619
+ from code_puppy.command_line.autosave_menu import (
620
+ interactive_autosave_picker,
621
+ )
622
+ from code_puppy.config import (
623
+ set_current_autosave_from_session_name,
624
+ )
625
+ from code_puppy.messaging import (
626
+ emit_error,
627
+ emit_success,
628
+ emit_warning,
629
+ )
630
+ from code_puppy.session_storage import (
631
+ load_session,
632
+ restore_autosave_interactively,
633
+ )
634
+
635
+ chosen_session = await interactive_autosave_picker()
636
+
637
+ if not chosen_session:
638
+ emit_warning("Autosave load cancelled")
639
+ continue
640
+
641
+ # Load the session
642
+ base_dir = Path(AUTOSAVE_DIR)
643
+ history = load_session(chosen_session, base_dir)
644
+
645
+ agent = get_current_agent()
646
+ agent.set_message_history(history)
647
+
648
+ # Set current autosave session
649
+ set_current_autosave_from_session_name(chosen_session)
650
+
651
+ total_tokens = sum(
652
+ agent.estimate_tokens_for_message(msg)
653
+ for msg in history
654
+ )
655
+ session_path = base_dir / f"{chosen_session}.pkl"
656
+
657
+ emit_success(
658
+ f"✅ Autosave loaded: {len(history)} messages ({total_tokens} tokens)\n"
659
+ f"📁 From: {session_path}"
660
+ )
661
+ else:
662
+ # Fall back to old text-based picker for tests/non-TTY environments
663
+ await restore_autosave_interactively(Path(AUTOSAVE_DIR))
664
+
665
+ except Exception as e:
666
+ from code_puppy.messaging import emit_error
667
+
668
+ emit_error(f"Failed to load autosave: {e}")
669
+ continue
670
+ else:
671
+ # Command returned a prompt to execute
672
+ task = command_result
673
+ elif command_result is False:
674
+ # Command not recognized, continue with normal processing
675
+ pass
676
+
677
+ if task.strip():
678
+ # Write to the secret file for permanent history with timestamp
679
+ save_command_to_history(task)
680
+
681
+ try:
682
+ prettier_code_blocks()
683
+
684
+ # No need to get agent directly - use manager's run methods
685
+
686
+ # Use our custom helper to enable attachment handling with spinner support
687
+ result, current_agent_task = await run_prompt_with_attachments(
688
+ current_agent,
689
+ task,
690
+ spinner_console=message_renderer.console,
691
+ )
692
+ # Check if the task was cancelled (but don't show message if we just killed processes)
693
+ if result is None:
694
+ # Windows-specific: Reset terminal state after cancellation
695
+ reset_windows_terminal_ansi()
696
+ # Re-disable Ctrl+C if needed (uvx mode)
697
+ try:
698
+ from code_puppy.terminal_utils import ensure_ctrl_c_disabled
699
+
700
+ ensure_ctrl_c_disabled()
701
+ except ImportError:
702
+ pass
703
+ continue
704
+ # Get the structured response
705
+ agent_response = result.output
706
+
707
+ # Emit structured message for proper markdown rendering
708
+ from code_puppy.messaging import get_message_bus
709
+ from code_puppy.messaging.messages import AgentResponseMessage
710
+
711
+ response_msg = AgentResponseMessage(
712
+ content=agent_response,
713
+ is_markdown=True,
714
+ )
715
+ get_message_bus().emit(response_msg)
716
+
717
+ # Update the agent's message history with the complete conversation
718
+ # including the final assistant response. The history_processors callback
719
+ # may not capture the final message, so we use result.all_messages()
720
+ # to ensure the autosave includes the complete conversation.
721
+ if hasattr(result, "all_messages"):
722
+ current_agent.set_message_history(list(result.all_messages()))
723
+
724
+ # Ensure console output is flushed before next prompt
725
+ # This fixes the issue where prompt doesn't appear after agent response
726
+ display_console.file.flush() if hasattr(
727
+ display_console.file, "flush"
728
+ ) else None
729
+ import time
730
+
731
+ time.sleep(0.1) # Brief pause to ensure all messages are rendered
732
+
733
+ except Exception:
734
+ from code_puppy.messaging.queue_console import get_queue_console
735
+
736
+ get_queue_console().print_exception()
737
+
738
+ # Auto-save session if enabled (moved outside the try block to avoid being swallowed)
739
+ from code_puppy.config import auto_save_session_if_enabled
740
+
741
+ auto_save_session_if_enabled()
742
+
743
+ # Re-disable Ctrl+C if needed (uvx mode) - must be done after
744
+ # each iteration as various operations may restore console mode
745
+ try:
746
+ from code_puppy.terminal_utils import ensure_ctrl_c_disabled
747
+
748
+ ensure_ctrl_c_disabled()
749
+ except ImportError:
750
+ pass
751
+
752
+
753
+ def prettier_code_blocks():
754
+ """Configure Rich to use prettier code block rendering."""
755
+
756
+ class SimpleCodeBlock(CodeBlock):
757
+ def __rich_console__(
758
+ self, console: Console, options: ConsoleOptions
759
+ ) -> RenderResult:
760
+ code = str(self.text).rstrip()
761
+ yield Text(self.lexer_name, style="dim")
762
+ syntax = Syntax(
763
+ code,
764
+ self.lexer_name,
765
+ theme=self.theme,
766
+ background_color="default",
767
+ line_numbers=True,
768
+ )
769
+ yield syntax
770
+ yield Text(f"/{self.lexer_name}", style="dim")
771
+
772
+ Markdown.elements["fence"] = SimpleCodeBlock
773
+
774
+
775
+ async def run_prompt_with_attachments(
776
+ agent,
777
+ raw_prompt: str,
778
+ *,
779
+ spinner_console=None,
780
+ use_spinner: bool = True,
781
+ ):
782
+ """Run the agent after parsing CLI attachments for image/document support.
783
+
784
+ Returns:
785
+ tuple: (result, task) where result is the agent response and task is the asyncio task
786
+ """
787
+ import asyncio
788
+
789
+ from code_puppy.messaging import emit_system_message, emit_warning
790
+
791
+ processed_prompt = parse_prompt_attachments(raw_prompt)
792
+
793
+ for warning in processed_prompt.warnings:
794
+ emit_warning(warning)
795
+
796
+ summary_parts = []
797
+ if processed_prompt.attachments:
798
+ summary_parts.append(f"binary files: {len(processed_prompt.attachments)}")
799
+ if processed_prompt.link_attachments:
800
+ summary_parts.append(f"urls: {len(processed_prompt.link_attachments)}")
801
+ if summary_parts:
802
+ emit_system_message("Attachments detected -> " + ", ".join(summary_parts))
803
+
804
+ if not processed_prompt.prompt:
805
+ emit_warning(
806
+ "Prompt is empty after removing attachments; add instructions and retry."
807
+ )
808
+ return None, None
809
+
810
+ attachments = [attachment.content for attachment in processed_prompt.attachments]
811
+ link_attachments = [link.url_part for link in processed_prompt.link_attachments]
812
+
813
+ # IMPORTANT: Set the shared console on the agent so that streaming output
814
+ # uses the same console as the spinner. This prevents Live display conflicts
815
+ # that cause line duplication during markdown streaming.
816
+ if spinner_console is not None:
817
+ agent._console = spinner_console
818
+
819
+ # Create the agent task first so we can track and cancel it
820
+ agent_task = asyncio.create_task(
821
+ agent.run_with_mcp(
822
+ processed_prompt.prompt,
823
+ attachments=attachments,
824
+ link_attachments=link_attachments,
825
+ )
826
+ )
827
+
828
+ if use_spinner and spinner_console is not None:
829
+ from code_puppy.messaging.spinner import ConsoleSpinner
830
+
831
+ with ConsoleSpinner(console=spinner_console):
832
+ try:
833
+ result = await agent_task
834
+ return result, agent_task
835
+ except asyncio.CancelledError:
836
+ emit_info("Agent task cancelled")
837
+ return None, agent_task
838
+ else:
839
+ try:
840
+ result = await agent_task
841
+ return result, agent_task
842
+ except asyncio.CancelledError:
843
+ emit_info("Agent task cancelled")
844
+ return None, agent_task
845
+
846
+
847
+ async def execute_single_prompt(prompt: str, message_renderer) -> None:
848
+ """Execute a single prompt and exit (for -p flag)."""
849
+ from code_puppy.messaging import emit_info
850
+
851
+ emit_info(f"Executing prompt: {prompt}")
852
+
853
+ try:
854
+ # Get agent through runtime manager and use helper for attachments
855
+ agent = get_current_agent()
856
+ response = await run_prompt_with_attachments(
857
+ agent,
858
+ prompt,
859
+ spinner_console=message_renderer.console,
860
+ )
861
+ if response is None:
862
+ return
863
+
864
+ agent_response = response.output
865
+
866
+ # Emit structured message for proper markdown rendering
867
+ from code_puppy.messaging import get_message_bus
868
+ from code_puppy.messaging.messages import AgentResponseMessage
869
+
870
+ response_msg = AgentResponseMessage(
871
+ content=agent_response,
872
+ is_markdown=True,
873
+ )
874
+ get_message_bus().emit(response_msg)
875
+
876
+ except asyncio.CancelledError:
877
+ from code_puppy.messaging import emit_warning
878
+
879
+ emit_warning("Execution cancelled by user")
880
+ except Exception as e:
881
+ from code_puppy.messaging import emit_error
882
+
883
+ emit_error(f"Error executing prompt: {str(e)}")
884
+
885
+
886
+ def main_entry():
887
+ """Entry point for the installed CLI tool."""
888
+ try:
889
+ asyncio.run(main())
890
+ except KeyboardInterrupt:
891
+ # Note: Using sys.stderr for crash output - messaging system may not be available
892
+ sys.stderr.write(traceback.format_exc())
893
+ if get_use_dbos():
894
+ DBOS.destroy()
895
+ return 0
896
+ finally:
897
+ # Reset terminal on Unix-like systems (not Windows)
898
+ reset_unix_terminal()