newcode 0.1.1__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 (289) hide show
  1. code_puppy/__init__.py +10 -0
  2. code_puppy/__main__.py +10 -0
  3. code_puppy/agents/__init__.py +31 -0
  4. code_puppy/agents/agent_c_reviewer.py +155 -0
  5. code_puppy/agents/agent_code_puppy.py +147 -0
  6. code_puppy/agents/agent_code_reviewer.py +90 -0
  7. code_puppy/agents/agent_cpp_reviewer.py +132 -0
  8. code_puppy/agents/agent_creator_agent.py +630 -0
  9. code_puppy/agents/agent_golang_reviewer.py +151 -0
  10. code_puppy/agents/agent_helios.py +122 -0
  11. code_puppy/agents/agent_javascript_reviewer.py +160 -0
  12. code_puppy/agents/agent_manager.py +742 -0
  13. code_puppy/agents/agent_pack_leader.py +380 -0
  14. code_puppy/agents/agent_planning.py +165 -0
  15. code_puppy/agents/agent_python_programmer.py +167 -0
  16. code_puppy/agents/agent_python_reviewer.py +90 -0
  17. code_puppy/agents/agent_qa_expert.py +163 -0
  18. code_puppy/agents/agent_qa_kitten.py +208 -0
  19. code_puppy/agents/agent_scheduler.py +121 -0
  20. code_puppy/agents/agent_security_auditor.py +181 -0
  21. code_puppy/agents/agent_terminal_qa.py +323 -0
  22. code_puppy/agents/agent_typescript_reviewer.py +166 -0
  23. code_puppy/agents/base_agent.py +2145 -0
  24. code_puppy/agents/event_stream_handler.py +348 -0
  25. code_puppy/agents/json_agent.py +202 -0
  26. code_puppy/agents/pack/__init__.py +34 -0
  27. code_puppy/agents/pack/bloodhound.py +296 -0
  28. code_puppy/agents/pack/husky.py +307 -0
  29. code_puppy/agents/pack/retriever.py +380 -0
  30. code_puppy/agents/pack/shepherd.py +327 -0
  31. code_puppy/agents/pack/terrier.py +281 -0
  32. code_puppy/agents/pack/watchdog.py +357 -0
  33. code_puppy/agents/prompt_reviewer.py +145 -0
  34. code_puppy/agents/subagent_stream_handler.py +276 -0
  35. code_puppy/api/__init__.py +13 -0
  36. code_puppy/api/app.py +169 -0
  37. code_puppy/api/main.py +21 -0
  38. code_puppy/api/pty_manager.py +453 -0
  39. code_puppy/api/routers/__init__.py +12 -0
  40. code_puppy/api/routers/agents.py +36 -0
  41. code_puppy/api/routers/commands.py +217 -0
  42. code_puppy/api/routers/config.py +75 -0
  43. code_puppy/api/routers/sessions.py +234 -0
  44. code_puppy/api/templates/terminal.html +361 -0
  45. code_puppy/api/websocket.py +154 -0
  46. code_puppy/callbacks.py +674 -0
  47. code_puppy/chatgpt_codex_client.py +338 -0
  48. code_puppy/claude_cache_client.py +664 -0
  49. code_puppy/cli_runner.py +1038 -0
  50. code_puppy/command_line/__init__.py +1 -0
  51. code_puppy/command_line/add_model_menu.py +1092 -0
  52. code_puppy/command_line/agent_menu.py +662 -0
  53. code_puppy/command_line/attachments.py +395 -0
  54. code_puppy/command_line/autosave_menu.py +704 -0
  55. code_puppy/command_line/clipboard.py +527 -0
  56. code_puppy/command_line/colors_menu.py +526 -0
  57. code_puppy/command_line/command_handler.py +283 -0
  58. code_puppy/command_line/command_registry.py +150 -0
  59. code_puppy/command_line/config_commands.py +719 -0
  60. code_puppy/command_line/core_commands.py +853 -0
  61. code_puppy/command_line/diff_menu.py +865 -0
  62. code_puppy/command_line/file_path_completion.py +73 -0
  63. code_puppy/command_line/load_context_completion.py +52 -0
  64. code_puppy/command_line/mcp/__init__.py +10 -0
  65. code_puppy/command_line/mcp/base.py +32 -0
  66. code_puppy/command_line/mcp/catalog_server_installer.py +175 -0
  67. code_puppy/command_line/mcp/custom_server_form.py +688 -0
  68. code_puppy/command_line/mcp/custom_server_installer.py +195 -0
  69. code_puppy/command_line/mcp/edit_command.py +148 -0
  70. code_puppy/command_line/mcp/handler.py +138 -0
  71. code_puppy/command_line/mcp/help_command.py +147 -0
  72. code_puppy/command_line/mcp/install_command.py +214 -0
  73. code_puppy/command_line/mcp/install_menu.py +705 -0
  74. code_puppy/command_line/mcp/list_command.py +94 -0
  75. code_puppy/command_line/mcp/logs_command.py +235 -0
  76. code_puppy/command_line/mcp/remove_command.py +82 -0
  77. code_puppy/command_line/mcp/restart_command.py +100 -0
  78. code_puppy/command_line/mcp/search_command.py +123 -0
  79. code_puppy/command_line/mcp/start_all_command.py +135 -0
  80. code_puppy/command_line/mcp/start_command.py +117 -0
  81. code_puppy/command_line/mcp/status_command.py +184 -0
  82. code_puppy/command_line/mcp/stop_all_command.py +112 -0
  83. code_puppy/command_line/mcp/stop_command.py +80 -0
  84. code_puppy/command_line/mcp/test_command.py +107 -0
  85. code_puppy/command_line/mcp/utils.py +129 -0
  86. code_puppy/command_line/mcp/wizard_utils.py +334 -0
  87. code_puppy/command_line/mcp_completion.py +174 -0
  88. code_puppy/command_line/model_picker_completion.py +197 -0
  89. code_puppy/command_line/model_settings_menu.py +932 -0
  90. code_puppy/command_line/motd.py +91 -0
  91. code_puppy/command_line/onboarding_slides.py +179 -0
  92. code_puppy/command_line/onboarding_wizard.py +342 -0
  93. code_puppy/command_line/pin_command_completion.py +329 -0
  94. code_puppy/command_line/prompt_toolkit_completion.py +846 -0
  95. code_puppy/command_line/session_commands.py +302 -0
  96. code_puppy/command_line/skills_completion.py +160 -0
  97. code_puppy/command_line/uc_menu.py +893 -0
  98. code_puppy/command_line/utils.py +93 -0
  99. code_puppy/command_line/wiggum_state.py +78 -0
  100. code_puppy/config.py +1787 -0
  101. code_puppy/error_logging.py +133 -0
  102. code_puppy/gemini_code_assist.py +385 -0
  103. code_puppy/gemini_model.py +754 -0
  104. code_puppy/hook_engine/README.md +105 -0
  105. code_puppy/hook_engine/__init__.py +15 -0
  106. code_puppy/hook_engine/aliases.py +155 -0
  107. code_puppy/hook_engine/engine.py +195 -0
  108. code_puppy/hook_engine/executor.py +293 -0
  109. code_puppy/hook_engine/matcher.py +145 -0
  110. code_puppy/hook_engine/models.py +222 -0
  111. code_puppy/hook_engine/registry.py +106 -0
  112. code_puppy/hook_engine/validator.py +141 -0
  113. code_puppy/http_utils.py +361 -0
  114. code_puppy/keymap.py +128 -0
  115. code_puppy/main.py +10 -0
  116. code_puppy/mcp_/__init__.py +66 -0
  117. code_puppy/mcp_/async_lifecycle.py +286 -0
  118. code_puppy/mcp_/blocking_startup.py +469 -0
  119. code_puppy/mcp_/captured_stdio_server.py +275 -0
  120. code_puppy/mcp_/circuit_breaker.py +290 -0
  121. code_puppy/mcp_/config_wizard.py +507 -0
  122. code_puppy/mcp_/dashboard.py +308 -0
  123. code_puppy/mcp_/error_isolation.py +407 -0
  124. code_puppy/mcp_/examples/retry_example.py +226 -0
  125. code_puppy/mcp_/health_monitor.py +589 -0
  126. code_puppy/mcp_/managed_server.py +428 -0
  127. code_puppy/mcp_/manager.py +807 -0
  128. code_puppy/mcp_/mcp_logs.py +224 -0
  129. code_puppy/mcp_/registry.py +451 -0
  130. code_puppy/mcp_/retry_manager.py +337 -0
  131. code_puppy/mcp_/server_registry_catalog.py +1126 -0
  132. code_puppy/mcp_/status_tracker.py +355 -0
  133. code_puppy/mcp_/system_tools.py +209 -0
  134. code_puppy/mcp_prompts/__init__.py +1 -0
  135. code_puppy/mcp_prompts/hook_creator.py +103 -0
  136. code_puppy/messaging/__init__.py +255 -0
  137. code_puppy/messaging/bus.py +613 -0
  138. code_puppy/messaging/commands.py +167 -0
  139. code_puppy/messaging/markdown_patches.py +57 -0
  140. code_puppy/messaging/message_queue.py +361 -0
  141. code_puppy/messaging/messages.py +569 -0
  142. code_puppy/messaging/queue_console.py +271 -0
  143. code_puppy/messaging/renderers.py +311 -0
  144. code_puppy/messaging/rich_renderer.py +1153 -0
  145. code_puppy/messaging/spinner/__init__.py +83 -0
  146. code_puppy/messaging/spinner/console_spinner.py +240 -0
  147. code_puppy/messaging/spinner/spinner_base.py +96 -0
  148. code_puppy/messaging/subagent_console.py +460 -0
  149. code_puppy/model_factory.py +848 -0
  150. code_puppy/model_switching.py +63 -0
  151. code_puppy/model_utils.py +168 -0
  152. code_puppy/models.json +130 -0
  153. code_puppy/models_dev_api.json +1 -0
  154. code_puppy/models_dev_parser.py +592 -0
  155. code_puppy/plugins/__init__.py +186 -0
  156. code_puppy/plugins/agent_skills/__init__.py +22 -0
  157. code_puppy/plugins/agent_skills/config.py +175 -0
  158. code_puppy/plugins/agent_skills/discovery.py +136 -0
  159. code_puppy/plugins/agent_skills/downloader.py +392 -0
  160. code_puppy/plugins/agent_skills/installer.py +22 -0
  161. code_puppy/plugins/agent_skills/metadata.py +219 -0
  162. code_puppy/plugins/agent_skills/prompt_builder.py +100 -0
  163. code_puppy/plugins/agent_skills/register_callbacks.py +241 -0
  164. code_puppy/plugins/agent_skills/remote_catalog.py +322 -0
  165. code_puppy/plugins/agent_skills/skill_catalog.py +257 -0
  166. code_puppy/plugins/agent_skills/skills_install_menu.py +664 -0
  167. code_puppy/plugins/agent_skills/skills_menu.py +781 -0
  168. code_puppy/plugins/antigravity_oauth/__init__.py +10 -0
  169. code_puppy/plugins/antigravity_oauth/accounts.py +406 -0
  170. code_puppy/plugins/antigravity_oauth/antigravity_model.py +706 -0
  171. code_puppy/plugins/antigravity_oauth/config.py +42 -0
  172. code_puppy/plugins/antigravity_oauth/constants.py +133 -0
  173. code_puppy/plugins/antigravity_oauth/oauth.py +478 -0
  174. code_puppy/plugins/antigravity_oauth/register_callbacks.py +518 -0
  175. code_puppy/plugins/antigravity_oauth/storage.py +288 -0
  176. code_puppy/plugins/antigravity_oauth/test_plugin.py +319 -0
  177. code_puppy/plugins/antigravity_oauth/token.py +167 -0
  178. code_puppy/plugins/antigravity_oauth/transport.py +863 -0
  179. code_puppy/plugins/antigravity_oauth/utils.py +168 -0
  180. code_puppy/plugins/chatgpt_oauth/__init__.py +8 -0
  181. code_puppy/plugins/chatgpt_oauth/config.py +52 -0
  182. code_puppy/plugins/chatgpt_oauth/oauth_flow.py +328 -0
  183. code_puppy/plugins/chatgpt_oauth/register_callbacks.py +176 -0
  184. code_puppy/plugins/chatgpt_oauth/test_plugin.py +295 -0
  185. code_puppy/plugins/chatgpt_oauth/utils.py +499 -0
  186. code_puppy/plugins/claude_code_hooks/__init__.py +1 -0
  187. code_puppy/plugins/claude_code_hooks/config.py +131 -0
  188. code_puppy/plugins/claude_code_hooks/register_callbacks.py +163 -0
  189. code_puppy/plugins/claude_code_oauth/README.md +167 -0
  190. code_puppy/plugins/claude_code_oauth/SETUP.md +93 -0
  191. code_puppy/plugins/claude_code_oauth/__init__.py +25 -0
  192. code_puppy/plugins/claude_code_oauth/config.py +52 -0
  193. code_puppy/plugins/claude_code_oauth/register_callbacks.py +453 -0
  194. code_puppy/plugins/claude_code_oauth/test_plugin.py +283 -0
  195. code_puppy/plugins/claude_code_oauth/token_refresh_heartbeat.py +241 -0
  196. code_puppy/plugins/claude_code_oauth/utils.py +601 -0
  197. code_puppy/plugins/customizable_commands/__init__.py +0 -0
  198. code_puppy/plugins/customizable_commands/register_callbacks.py +152 -0
  199. code_puppy/plugins/example_custom_command/README.md +280 -0
  200. code_puppy/plugins/example_custom_command/register_callbacks.py +48 -0
  201. code_puppy/plugins/file_permission_handler/__init__.py +4 -0
  202. code_puppy/plugins/file_permission_handler/register_callbacks.py +528 -0
  203. code_puppy/plugins/frontend_emitter/__init__.py +25 -0
  204. code_puppy/plugins/frontend_emitter/emitter.py +121 -0
  205. code_puppy/plugins/frontend_emitter/register_callbacks.py +261 -0
  206. code_puppy/plugins/hook_creator/__init__.py +1 -0
  207. code_puppy/plugins/hook_creator/register_callbacks.py +33 -0
  208. code_puppy/plugins/hook_manager/__init__.py +1 -0
  209. code_puppy/plugins/hook_manager/config.py +277 -0
  210. code_puppy/plugins/hook_manager/hooks_menu.py +551 -0
  211. code_puppy/plugins/hook_manager/register_callbacks.py +205 -0
  212. code_puppy/plugins/oauth_puppy_html.py +224 -0
  213. code_puppy/plugins/scheduler/__init__.py +1 -0
  214. code_puppy/plugins/scheduler/register_callbacks.py +88 -0
  215. code_puppy/plugins/scheduler/scheduler_menu.py +522 -0
  216. code_puppy/plugins/scheduler/scheduler_wizard.py +341 -0
  217. code_puppy/plugins/shell_safety/__init__.py +6 -0
  218. code_puppy/plugins/shell_safety/agent_shell_safety.py +69 -0
  219. code_puppy/plugins/shell_safety/command_cache.py +156 -0
  220. code_puppy/plugins/shell_safety/register_callbacks.py +202 -0
  221. code_puppy/plugins/synthetic_status/__init__.py +1 -0
  222. code_puppy/plugins/synthetic_status/register_callbacks.py +132 -0
  223. code_puppy/plugins/synthetic_status/status_api.py +147 -0
  224. code_puppy/plugins/universal_constructor/__init__.py +13 -0
  225. code_puppy/plugins/universal_constructor/models.py +138 -0
  226. code_puppy/plugins/universal_constructor/register_callbacks.py +47 -0
  227. code_puppy/plugins/universal_constructor/registry.py +302 -0
  228. code_puppy/plugins/universal_constructor/sandbox.py +584 -0
  229. code_puppy/prompts/antigravity_system_prompt.md +1 -0
  230. code_puppy/pydantic_patches.py +317 -0
  231. code_puppy/reopenable_async_client.py +232 -0
  232. code_puppy/round_robin_model.py +150 -0
  233. code_puppy/scheduler/__init__.py +41 -0
  234. code_puppy/scheduler/__main__.py +9 -0
  235. code_puppy/scheduler/cli.py +118 -0
  236. code_puppy/scheduler/config.py +126 -0
  237. code_puppy/scheduler/daemon.py +280 -0
  238. code_puppy/scheduler/executor.py +155 -0
  239. code_puppy/scheduler/platform.py +19 -0
  240. code_puppy/scheduler/platform_unix.py +22 -0
  241. code_puppy/scheduler/platform_win.py +32 -0
  242. code_puppy/session_storage.py +338 -0
  243. code_puppy/status_display.py +257 -0
  244. code_puppy/summarization_agent.py +176 -0
  245. code_puppy/terminal_utils.py +418 -0
  246. code_puppy/tools/__init__.py +470 -0
  247. code_puppy/tools/agent_tools.py +616 -0
  248. code_puppy/tools/ask_user_question/__init__.py +26 -0
  249. code_puppy/tools/ask_user_question/constants.py +73 -0
  250. code_puppy/tools/ask_user_question/demo_tui.py +55 -0
  251. code_puppy/tools/ask_user_question/handler.py +232 -0
  252. code_puppy/tools/ask_user_question/models.py +304 -0
  253. code_puppy/tools/ask_user_question/registration.py +36 -0
  254. code_puppy/tools/ask_user_question/renderers.py +309 -0
  255. code_puppy/tools/ask_user_question/terminal_ui.py +329 -0
  256. code_puppy/tools/ask_user_question/theme.py +155 -0
  257. code_puppy/tools/ask_user_question/tui_loop.py +423 -0
  258. code_puppy/tools/browser/__init__.py +37 -0
  259. code_puppy/tools/browser/browser_control.py +289 -0
  260. code_puppy/tools/browser/browser_interactions.py +545 -0
  261. code_puppy/tools/browser/browser_locators.py +640 -0
  262. code_puppy/tools/browser/browser_manager.py +378 -0
  263. code_puppy/tools/browser/browser_navigation.py +251 -0
  264. code_puppy/tools/browser/browser_screenshot.py +179 -0
  265. code_puppy/tools/browser/browser_scripts.py +462 -0
  266. code_puppy/tools/browser/browser_workflows.py +221 -0
  267. code_puppy/tools/browser/chromium_terminal_manager.py +259 -0
  268. code_puppy/tools/browser/terminal_command_tools.py +534 -0
  269. code_puppy/tools/browser/terminal_screenshot_tools.py +552 -0
  270. code_puppy/tools/browser/terminal_tools.py +525 -0
  271. code_puppy/tools/command_runner.py +1346 -0
  272. code_puppy/tools/common.py +1409 -0
  273. code_puppy/tools/display.py +84 -0
  274. code_puppy/tools/file_modifications.py +739 -0
  275. code_puppy/tools/file_operations.py +802 -0
  276. code_puppy/tools/scheduler_tools.py +412 -0
  277. code_puppy/tools/skills_tools.py +251 -0
  278. code_puppy/tools/subagent_context.py +158 -0
  279. code_puppy/tools/tools_content.py +51 -0
  280. code_puppy/tools/universal_constructor.py +889 -0
  281. code_puppy/uvx_detection.py +242 -0
  282. code_puppy/version_checker.py +82 -0
  283. newcode-0.1.1.data/data/code_puppy/models.json +130 -0
  284. newcode-0.1.1.data/data/code_puppy/models_dev_api.json +1 -0
  285. newcode-0.1.1.dist-info/METADATA +154 -0
  286. newcode-0.1.1.dist-info/RECORD +289 -0
  287. newcode-0.1.1.dist-info/WHEEL +4 -0
  288. newcode-0.1.1.dist-info/entry_points.txt +3 -0
  289. newcode-0.1.1.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,202 @@
1
+ """Callback registration for shell command safety checking.
2
+
3
+ This module registers a callback that intercepts shell commands in yolo_mode
4
+ and assesses their safety risk before execution.
5
+ """
6
+
7
+ from typing import Any, Dict, Optional
8
+
9
+ from code_puppy.callbacks import register_callback
10
+ from code_puppy.config import (
11
+ get_global_model_name,
12
+ get_safety_permission_level,
13
+ get_yolo_mode,
14
+ )
15
+ from code_puppy.messaging import emit_info
16
+ from code_puppy.plugins.shell_safety.command_cache import (
17
+ cache_assessment,
18
+ get_cached_assessment,
19
+ )
20
+ from code_puppy.tools.command_runner import ShellSafetyAssessment
21
+
22
+ # OAuth model prefixes - these models have their own safety mechanisms
23
+ OAUTH_MODEL_PREFIXES = (
24
+ "claude-code-", # Anthropic OAuth
25
+ "chatgpt-", # OpenAI OAuth
26
+ "gemini-oauth", # Google OAuth
27
+ )
28
+
29
+
30
+ def is_oauth_model(model_name: str | None) -> bool:
31
+ """Check if the model is an OAuth model that should skip safety checks.
32
+
33
+ OAuth models have their own built-in safety mechanisms, so we skip
34
+ the shell safety callback to avoid redundant checks and potential bugs.
35
+
36
+ Args:
37
+ model_name: The name of the current model
38
+
39
+ Returns:
40
+ True if the model is an OAuth model, False otherwise
41
+ """
42
+ if not model_name:
43
+ return False
44
+ return model_name.startswith(OAUTH_MODEL_PREFIXES)
45
+
46
+
47
+ # Risk level hierarchy for numeric comparison
48
+ # Lower numbers = safer commands, higher numbers = more dangerous
49
+ # This mapping allows us to compare risk levels as integers
50
+ RISK_LEVELS: Dict[str, int] = {
51
+ "none": 0,
52
+ "low": 1,
53
+ "medium": 2,
54
+ "high": 3,
55
+ "critical": 4,
56
+ }
57
+
58
+
59
+ def compare_risk_levels(assessed_risk: Optional[str], threshold: str) -> bool:
60
+ """Compare assessed risk against threshold.
61
+
62
+ Args:
63
+ assessed_risk: The risk level from the agent (can be None)
64
+ threshold: The configured risk threshold
65
+
66
+ Returns:
67
+ True if the command should be blocked (risk exceeds threshold)
68
+ False if the command is acceptable
69
+ """
70
+ # If assessment failed (None), treat as high risk (fail-safe behavior)
71
+ if assessed_risk is None:
72
+ assessed_risk = "high"
73
+
74
+ # Convert risk levels to numeric values for comparison
75
+ assessed_level = RISK_LEVELS.get(assessed_risk, 4) # Default to critical if unknown
76
+ threshold_level = RISK_LEVELS.get(threshold, 2) # Default to medium if unknown
77
+
78
+ # Block if assessed risk is GREATER than threshold
79
+ # Note: Commands AT the threshold level are allowed (>, not >=)
80
+ return assessed_level > threshold_level
81
+
82
+
83
+ async def shell_safety_callback(
84
+ context: Any, command: str, cwd: Optional[str] = None, timeout: int = 60
85
+ ) -> Optional[Dict[str, Any]]:
86
+ """Callback to assess shell command safety before execution.
87
+
88
+ This callback is only active when yolo_mode is True. When yolo_mode is False,
89
+ the user manually reviews every command, so we don't need the agent.
90
+
91
+ Args:
92
+ context: The execution context
93
+ command: The shell command to execute
94
+ cwd: Optional working directory
95
+ timeout: Command timeout (unused here)
96
+
97
+ Returns:
98
+ None if command is safe to proceed
99
+ Dict with rejection info if command should be blocked
100
+ """
101
+ # Skip safety checks for OAuth models - they have their own safety mechanisms
102
+ current_model = get_global_model_name()
103
+ if is_oauth_model(current_model):
104
+ return None
105
+
106
+ # Only check safety in yolo_mode - otherwise user is reviewing manually
107
+ yolo_mode = get_yolo_mode()
108
+ if not yolo_mode:
109
+ return None
110
+
111
+ # Get configured risk threshold
112
+ threshold = get_safety_permission_level()
113
+
114
+ try:
115
+ # Check cache first (fast path - no LLM call)
116
+ cached = get_cached_assessment(command, cwd)
117
+
118
+ if cached:
119
+ # Got a cached result - check against threshold
120
+ if compare_risk_levels(cached.risk, threshold):
121
+ # Cached result says it's too risky
122
+ risk_display = cached.risk or "unknown"
123
+ concise_reason = cached.reasoning or "No reasoning provided"
124
+ error_msg = (
125
+ f"🛑 Command blocked (risk {risk_display.upper()} > permission {threshold.upper()}).\n"
126
+ f"Reason: {concise_reason}\n"
127
+ f"Override: /set yolo_mode true or /set safety_permission_level {risk_display}"
128
+ )
129
+ emit_info(error_msg)
130
+ return {
131
+ "blocked": True,
132
+ "risk": cached.risk,
133
+ "reasoning": cached.reasoning,
134
+ "error_message": error_msg,
135
+ }
136
+ # Cached result is within threshold - allow silently
137
+ return None
138
+
139
+ # Cache miss - need LLM assessment
140
+ # Import here to avoid circular imports
141
+ from code_puppy.plugins.shell_safety.agent_shell_safety import ShellSafetyAgent
142
+
143
+ # Create agent and assess command
144
+ agent = ShellSafetyAgent()
145
+
146
+ # Build the assessment prompt with optional cwd context
147
+ prompt = f"Assess this shell command:\n\nCommand: {command}"
148
+ if cwd:
149
+ prompt += f"\nWorking directory: {cwd}"
150
+
151
+ # Run async assessment with structured output type
152
+ result = await agent.run_with_mcp(prompt, output_type=ShellSafetyAssessment)
153
+ assessment = result.output
154
+
155
+ # Cache the result for future use, but only if it's not a fallback assessment
156
+ if not getattr(assessment, "is_fallback", False):
157
+ cache_assessment(command, cwd, assessment.risk, assessment.reasoning)
158
+
159
+ # Check if risk exceeds threshold (commands at threshold are allowed)
160
+ if compare_risk_levels(assessment.risk, threshold):
161
+ risk_display = assessment.risk or "unknown"
162
+ concise_reason = assessment.reasoning or "No reasoning provided"
163
+ error_msg = (
164
+ f"🛑 Command blocked (risk {risk_display.upper()} > permission {threshold.upper()}).\n"
165
+ f"Reason: {concise_reason}\n"
166
+ f"Override: /set yolo_mode true or /set safety_permission_level {risk_display}"
167
+ )
168
+ emit_info(error_msg)
169
+
170
+ # Return rejection info for the command runner
171
+ return {
172
+ "blocked": True,
173
+ "risk": assessment.risk,
174
+ "reasoning": assessment.reasoning,
175
+ "error_message": error_msg,
176
+ }
177
+
178
+ # Command is within acceptable risk threshold - remain silent
179
+ return None # Allow command to proceed
180
+
181
+ except Exception as e:
182
+ # On any error, fail safe by blocking the command
183
+ error_msg = (
184
+ f"🛑 Command blocked (risk HIGH > permission {threshold.upper()}).\n"
185
+ f"Reason: Safety assessment error: {str(e)}\n"
186
+ f"Override: /set yolo_mode true or /set safety_permission_level high"
187
+ )
188
+ return {
189
+ "blocked": True,
190
+ "risk": "high",
191
+ "reasoning": f"Safety assessment error: {str(e)}",
192
+ "error_message": error_msg,
193
+ }
194
+
195
+
196
+ def register():
197
+ """Register the shell safety callback."""
198
+ register_callback("run_shell_command", shell_safety_callback)
199
+
200
+
201
+ # Auto-register the callback when this module is imported
202
+ register()
@@ -0,0 +1 @@
1
+ """Synthetic provider status plugin."""
@@ -0,0 +1,132 @@
1
+ """Slash commands for Synthetic provider subscription status."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import List, Optional, Tuple
6
+
7
+ from rich.panel import Panel
8
+
9
+ from code_puppy.callbacks import register_callback
10
+ from code_puppy.messaging import emit_error, emit_info, emit_warning
11
+ from code_puppy.model_factory import get_api_key
12
+
13
+ from .status_api import fetch_synthetic_quota, resolve_syn_api_key
14
+
15
+ _PROVIDER_ENV_KEYS = {
16
+ "synthetic": "SYN_API_KEY",
17
+ "openai": "OPENAI_API_KEY",
18
+ "anthropic": "ANTHROPIC_API_KEY",
19
+ "gemini": "GEMINI_API_KEY",
20
+ "cerebras": "CEREBRAS_API_KEY",
21
+ "openrouter": "OPENROUTER_API_KEY",
22
+ "zai": "ZAI_API_KEY",
23
+ "azure_openai": "AZURE_OPENAI_API_KEY",
24
+ }
25
+
26
+
27
+ def _custom_help() -> List[Tuple[str, str]]:
28
+ return [
29
+ ("synthetic-status", "Check Synthetic subscription quota and renewal time"),
30
+ ("provider", "Provider utilities (usage: /provider synthetic status)"),
31
+ (
32
+ "status",
33
+ "Show provider status when only Synthetic appears configured",
34
+ ),
35
+ ]
36
+
37
+
38
+ def _format_amount(value: float) -> str:
39
+ rounded = round(value)
40
+ if abs(value - rounded) < 1e-9:
41
+ return str(int(rounded))
42
+ return f"{value:.2f}".rstrip("0").rstrip(".")
43
+
44
+
45
+ def _render_synthetic_status_panel(
46
+ limit: float,
47
+ used: float,
48
+ renews_at_utc: str,
49
+ ) -> Panel:
50
+ remaining = max(limit - used, 0.0)
51
+ body = "\n".join(
52
+ [
53
+ "Provider : Synthetic",
54
+ f"Requests used : {_format_amount(used)} / {_format_amount(limit)}",
55
+ f"Requests left : {_format_amount(remaining)}",
56
+ f"Renews at : {renews_at_utc}",
57
+ ]
58
+ )
59
+ return Panel(body, border_style="cyan")
60
+
61
+
62
+ def _handle_synthetic_status() -> None:
63
+ api_key = resolve_syn_api_key()
64
+ if not api_key:
65
+ emit_error("SYN_API_KEY is not configured. Set it with /set syn_api_key <key>.")
66
+ return
67
+
68
+ result = fetch_synthetic_quota(api_key=api_key)
69
+ if not result.ok or not result.quota:
70
+ emit_warning(result.error or "Failed to fetch Synthetic quota status.")
71
+ return
72
+
73
+ renews_at_str = result.quota.renews_at_utc.strftime("%Y-%m-%d %H:%M UTC")
74
+ panel = _render_synthetic_status_panel(
75
+ limit=result.quota.limit,
76
+ used=result.quota.requests_used,
77
+ renews_at_utc=renews_at_str,
78
+ )
79
+ emit_info(panel)
80
+
81
+
82
+ def _is_synthetic_only_provider_configured() -> bool:
83
+ configured = {
84
+ provider
85
+ for provider, env_name in _PROVIDER_ENV_KEYS.items()
86
+ if get_api_key(env_name)
87
+ }
88
+ return configured == {"synthetic"}
89
+
90
+
91
+ def _handle_provider_command(command: str) -> Optional[bool]:
92
+ tokens = command.strip().split()
93
+ if len(tokens) < 2:
94
+ return None
95
+
96
+ provider = tokens[1].lower()
97
+ if provider != "synthetic":
98
+ return None
99
+
100
+ if len(tokens) == 3 and tokens[2].lower() == "status":
101
+ _handle_synthetic_status()
102
+ return True
103
+
104
+ emit_info("Usage: /provider synthetic status")
105
+ return True
106
+
107
+
108
+ def _handle_custom_command(command: str, name: str) -> Optional[bool]:
109
+ if not name:
110
+ return None
111
+
112
+ if name == "synthetic-status":
113
+ _handle_synthetic_status()
114
+ return True
115
+
116
+ if name == "provider":
117
+ return _handle_provider_command(command)
118
+
119
+ if name == "status":
120
+ if _is_synthetic_only_provider_configured():
121
+ _handle_synthetic_status()
122
+ else:
123
+ emit_warning(
124
+ "Multiple providers appear configured. Use /provider synthetic status."
125
+ )
126
+ return True
127
+
128
+ return None
129
+
130
+
131
+ register_callback("custom_command_help", _custom_help)
132
+ register_callback("custom_command", _handle_custom_command)
@@ -0,0 +1,147 @@
1
+ """HTTP helpers for Synthetic quota status."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from datetime import datetime, timezone
7
+
8
+ import requests
9
+
10
+ from code_puppy.model_factory import get_api_key
11
+
12
+ SYNTHETIC_QUOTAS_URL = "https://api.synthetic.new/v2/quotas"
13
+
14
+
15
+ @dataclass
16
+ class SyntheticQuota:
17
+ """Parsed Synthetic subscription quota values."""
18
+
19
+ limit: float
20
+ requests_used: float
21
+ renews_at_utc: datetime
22
+
23
+
24
+ @dataclass
25
+ class SyntheticQuotaResult:
26
+ """Result wrapper for Synthetic quota fetches."""
27
+
28
+ quota: SyntheticQuota | None = None
29
+ error: str | None = None
30
+
31
+ @property
32
+ def ok(self) -> bool:
33
+ return self.quota is not None and self.error is None
34
+
35
+
36
+ def resolve_syn_api_key() -> str | None:
37
+ """Resolve SYN_API_KEY from config/environment."""
38
+ value = get_api_key("SYN_API_KEY")
39
+ if not value:
40
+ return None
41
+ value = value.strip()
42
+ return value or None
43
+
44
+
45
+ def _parse_renews_at(value: object) -> datetime | None:
46
+ if not isinstance(value, str) or not value.strip():
47
+ return None
48
+
49
+ normalized = value.strip().replace("Z", "+00:00")
50
+ try:
51
+ parsed = datetime.fromisoformat(normalized)
52
+ except ValueError:
53
+ return None
54
+
55
+ if parsed.tzinfo is None:
56
+ parsed = parsed.replace(tzinfo=timezone.utc)
57
+ return parsed.astimezone(timezone.utc)
58
+
59
+
60
+ def fetch_synthetic_quota(
61
+ api_key: str,
62
+ timeout_seconds: float = 15.0,
63
+ ) -> SyntheticQuotaResult:
64
+ """Fetch and validate Synthetic subscription quota status."""
65
+ if not api_key:
66
+ return SyntheticQuotaResult(error="SYN_API_KEY is not configured.")
67
+
68
+ headers = {
69
+ "Authorization": f"Bearer {api_key}",
70
+ "Accept": "application/json",
71
+ }
72
+
73
+ try:
74
+ response = requests.get(
75
+ SYNTHETIC_QUOTAS_URL,
76
+ headers=headers,
77
+ timeout=timeout_seconds,
78
+ )
79
+ except requests.Timeout:
80
+ return SyntheticQuotaResult(error="Synthetic API request timed out.")
81
+ except requests.ConnectionError:
82
+ return SyntheticQuotaResult(
83
+ error="Could not connect to the Synthetic API endpoint."
84
+ )
85
+ except requests.RequestException as exc:
86
+ return SyntheticQuotaResult(error=f"Synthetic API request failed: {exc}")
87
+
88
+ if response.status_code in (401, 403):
89
+ return SyntheticQuotaResult(
90
+ error="Synthetic API authentication failed. Check SYN_API_KEY."
91
+ )
92
+ if response.status_code == 429:
93
+ return SyntheticQuotaResult(
94
+ error="Synthetic API rate limited this request (HTTP 429)."
95
+ )
96
+ if response.status_code >= 500:
97
+ return SyntheticQuotaResult(
98
+ error=f"Synthetic API server error (HTTP {response.status_code})."
99
+ )
100
+ if response.status_code != 200:
101
+ detail = response.text.strip()
102
+ if len(detail) > 200:
103
+ detail = f"{detail[:200]}..."
104
+ suffix = f": {detail}" if detail else ""
105
+ return SyntheticQuotaResult(
106
+ error=f"Synthetic API returned HTTP {response.status_code}{suffix}"
107
+ )
108
+
109
+ try:
110
+ payload = response.json()
111
+ except ValueError:
112
+ return SyntheticQuotaResult(
113
+ error="Synthetic API returned invalid JSON for /v2/quotas."
114
+ )
115
+
116
+ if not isinstance(payload, dict):
117
+ return SyntheticQuotaResult(
118
+ error="Synthetic API response payload is not an object."
119
+ )
120
+
121
+ subscription = payload.get("subscription")
122
+ if not isinstance(subscription, dict):
123
+ return SyntheticQuotaResult(
124
+ error="Synthetic API response is missing 'subscription'."
125
+ )
126
+
127
+ try:
128
+ limit = float(subscription.get("limit"))
129
+ requests_used = float(subscription.get("requests"))
130
+ except (TypeError, ValueError):
131
+ return SyntheticQuotaResult(
132
+ error="Synthetic API response has invalid numeric quota values."
133
+ )
134
+
135
+ renews_at = _parse_renews_at(subscription.get("renewsAt"))
136
+ if renews_at is None:
137
+ return SyntheticQuotaResult(
138
+ error="Synthetic API response has an invalid 'renewsAt' timestamp."
139
+ )
140
+
141
+ return SyntheticQuotaResult(
142
+ quota=SyntheticQuota(
143
+ limit=limit,
144
+ requests_used=requests_used,
145
+ renews_at_utc=renews_at,
146
+ )
147
+ )
@@ -0,0 +1,13 @@
1
+ """Universal Constructor - Dynamic tool creation and management plugin.
2
+
3
+ This plugin enables users to create, manage, and deploy custom tools
4
+ that extend the agent's capabilities. Tools are stored in the user's
5
+ config directory and can be organized into namespaces via subdirectories.
6
+ """
7
+
8
+ from pathlib import Path
9
+
10
+ # User tools directory - where user-created UC tools live
11
+ USER_UC_DIR = Path.home() / ".code_puppy" / "plugins" / "universal_constructor"
12
+
13
+ __all__ = ["USER_UC_DIR"]
@@ -0,0 +1,138 @@
1
+ """Pydantic models for Universal Constructor tools and responses.
2
+
3
+ This module defines the data structures used throughout the UC plugin
4
+ for representing tool metadata, tool information, and operation responses.
5
+ """
6
+
7
+ from typing import Any, List, Optional
8
+
9
+ from pydantic import BaseModel, Field
10
+
11
+
12
+ class ToolMeta(BaseModel):
13
+ """Metadata for a UC tool.
14
+
15
+ This is the structure expected in the TOOL_META dictionary
16
+ at the top of each tool file.
17
+ """
18
+
19
+ name: str = Field(..., description="Human-readable tool name")
20
+ namespace: str = Field(
21
+ default="", description="Namespace for the tool (from subdirectory path)"
22
+ )
23
+ description: str = Field(..., description="What the tool does")
24
+ enabled: bool = Field(default=True, description="Whether the tool is active")
25
+ version: str = Field(default="1.0.0", description="Semantic version of the tool")
26
+ author: str = Field(default="", description="Tool author or creator")
27
+ created_at: Optional[str] = Field(
28
+ default=None, description="When the tool was created (ISO format string)"
29
+ )
30
+
31
+ model_config = {"extra": "allow"} # Allow additional metadata fields
32
+
33
+
34
+ class UCToolInfo(BaseModel):
35
+ """Full information about a UC tool.
36
+
37
+ Combines metadata with runtime information like function signature
38
+ and source file location.
39
+ """
40
+
41
+ meta: ToolMeta = Field(..., description="Tool metadata")
42
+ signature: str = Field(..., description="Function signature string")
43
+ source_path: str = Field(..., description="Path to the tool source file")
44
+ function_name: str = Field(default="", description="Name of the callable function")
45
+ docstring: Optional[str] = Field(default=None, description="Function docstring")
46
+
47
+ model_config = {"arbitrary_types_allowed": True}
48
+
49
+ @property
50
+ def full_name(self) -> str:
51
+ """Get the fully qualified tool name including namespace."""
52
+ if self.meta.namespace:
53
+ return f"{self.meta.namespace}.{self.meta.name}"
54
+ return self.meta.name
55
+
56
+
57
+ # Response models for UC operations
58
+
59
+
60
+ class UCListOutput(BaseModel):
61
+ """Response model for listing UC tools."""
62
+
63
+ tools: List[UCToolInfo] = Field(
64
+ default_factory=list, description="List of available tools"
65
+ )
66
+ total_count: int = Field(default=0, description="Total number of tools")
67
+ enabled_count: int = Field(default=0, description="Number of enabled tools")
68
+ error: Optional[str] = Field(default=None, description="Error message if any")
69
+
70
+ model_config = {"arbitrary_types_allowed": True}
71
+
72
+
73
+ class UCCallOutput(BaseModel):
74
+ """Response model for calling a UC tool."""
75
+
76
+ success: bool = Field(..., description="Whether the call succeeded")
77
+ tool_name: str = Field(..., description="Name of the tool that was called")
78
+ result: Any = Field(default=None, description="Return value from the tool")
79
+ error: Optional[str] = Field(default=None, description="Error message if failed")
80
+ execution_time: Optional[float] = Field(
81
+ default=None, description="Execution time in seconds"
82
+ )
83
+ source_preview: Optional[str] = Field(
84
+ default=None, description="Preview of the tool's source code that was executed"
85
+ )
86
+
87
+
88
+ class UCCreateOutput(BaseModel):
89
+ """Response model for creating a UC tool."""
90
+
91
+ success: bool = Field(..., description="Whether creation succeeded")
92
+ tool_name: str = Field(default="", description="Name of the created tool")
93
+ source_path: Optional[str] = Field(
94
+ default=None, description="Path where tool was saved"
95
+ )
96
+ preview: Optional[str] = Field(
97
+ default=None, description="Preview of the first 10 lines of source code"
98
+ )
99
+ error: Optional[str] = Field(default=None, description="Error message if failed")
100
+ validation_warnings: List[str] = Field(
101
+ default_factory=list, description="Non-fatal validation warnings"
102
+ )
103
+
104
+ model_config = {"arbitrary_types_allowed": True}
105
+
106
+
107
+ class UCUpdateOutput(BaseModel):
108
+ """Response model for updating a UC tool."""
109
+
110
+ success: bool = Field(..., description="Whether update succeeded")
111
+ tool_name: str = Field(default="", description="Name of the updated tool")
112
+ source_path: Optional[str] = Field(
113
+ default=None, description="Path to the updated tool"
114
+ )
115
+ preview: Optional[str] = Field(
116
+ default=None, description="Preview of the first 10 lines of updated source code"
117
+ )
118
+ error: Optional[str] = Field(default=None, description="Error message if failed")
119
+ changes_applied: List[str] = Field(
120
+ default_factory=list, description="List of changes that were applied"
121
+ )
122
+
123
+ model_config = {"arbitrary_types_allowed": True}
124
+
125
+
126
+ class UCInfoOutput(BaseModel):
127
+ """Response model for getting info about a specific UC tool."""
128
+
129
+ success: bool = Field(..., description="Whether lookup succeeded")
130
+ tool: Optional[UCToolInfo] = Field(
131
+ default=None, description="Tool information if found"
132
+ )
133
+ source_code: Optional[str] = Field(
134
+ default=None, description="Source code of the tool"
135
+ )
136
+ error: Optional[str] = Field(default=None, description="Error message if failed")
137
+
138
+ model_config = {"arbitrary_types_allowed": True}
@@ -0,0 +1,47 @@
1
+ """Callback registration for the Universal Constructor plugin.
2
+
3
+ This module registers callbacks to integrate UC with the rest of
4
+ the application. It ensures the plugin is properly loaded and initialized.
5
+ """
6
+
7
+ import logging
8
+
9
+ from code_puppy.callbacks import register_callback
10
+
11
+ from . import USER_UC_DIR
12
+ from .registry import get_registry
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def _on_startup() -> None:
18
+ """Initialize UC plugin on application startup."""
19
+ from code_puppy.config import get_universal_constructor_enabled
20
+
21
+ # Skip initialization if UC is disabled
22
+ if not get_universal_constructor_enabled():
23
+ logger.debug("Universal Constructor is disabled, skipping initialization")
24
+ return
25
+
26
+ logger.debug("Universal Constructor plugin initializing...")
27
+
28
+ # Ensure the user tools directory exists
29
+ USER_UC_DIR.mkdir(parents=True, exist_ok=True)
30
+
31
+ # Do an initial scan of tools (lazy - will happen on first access)
32
+ registry = get_registry()
33
+ logger.debug(f"UC registry initialized, tools dir: {registry._tools_dir}")
34
+
35
+ # Log plugin info at startup
36
+ tools = registry.list_tools(include_disabled=True)
37
+ enabled = [t for t in tools if t.meta.enabled]
38
+ logger.debug(
39
+ f"UC plugin loaded: {len(enabled)}/{len(tools)} tools enabled "
40
+ f"from {USER_UC_DIR}"
41
+ )
42
+
43
+
44
+ # Register startup callback
45
+ register_callback("startup", _on_startup)
46
+
47
+ logger.debug("Universal Constructor plugin callbacks registered")