shotgun-sh 0.1.9__py3-none-any.whl → 0.2.11__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.

Potentially problematic release.


This version of shotgun-sh might be problematic. Click here for more details.

Files changed (150) hide show
  1. shotgun/agents/agent_manager.py +761 -52
  2. shotgun/agents/common.py +80 -75
  3. shotgun/agents/config/constants.py +21 -10
  4. shotgun/agents/config/manager.py +322 -97
  5. shotgun/agents/config/models.py +114 -84
  6. shotgun/agents/config/provider.py +232 -88
  7. shotgun/agents/context_analyzer/__init__.py +28 -0
  8. shotgun/agents/context_analyzer/analyzer.py +471 -0
  9. shotgun/agents/context_analyzer/constants.py +9 -0
  10. shotgun/agents/context_analyzer/formatter.py +115 -0
  11. shotgun/agents/context_analyzer/models.py +212 -0
  12. shotgun/agents/conversation_history.py +125 -2
  13. shotgun/agents/conversation_manager.py +57 -19
  14. shotgun/agents/export.py +6 -7
  15. shotgun/agents/history/compaction.py +23 -3
  16. shotgun/agents/history/context_extraction.py +93 -6
  17. shotgun/agents/history/history_processors.py +179 -11
  18. shotgun/agents/history/token_counting/__init__.py +31 -0
  19. shotgun/agents/history/token_counting/anthropic.py +127 -0
  20. shotgun/agents/history/token_counting/base.py +78 -0
  21. shotgun/agents/history/token_counting/openai.py +90 -0
  22. shotgun/agents/history/token_counting/sentencepiece_counter.py +127 -0
  23. shotgun/agents/history/token_counting/tokenizer_cache.py +92 -0
  24. shotgun/agents/history/token_counting/utils.py +144 -0
  25. shotgun/agents/history/token_estimation.py +12 -12
  26. shotgun/agents/llm.py +62 -0
  27. shotgun/agents/models.py +59 -4
  28. shotgun/agents/plan.py +6 -7
  29. shotgun/agents/research.py +7 -8
  30. shotgun/agents/specify.py +6 -7
  31. shotgun/agents/tasks.py +6 -7
  32. shotgun/agents/tools/__init__.py +0 -2
  33. shotgun/agents/tools/codebase/codebase_shell.py +6 -0
  34. shotgun/agents/tools/codebase/directory_lister.py +6 -0
  35. shotgun/agents/tools/codebase/file_read.py +11 -2
  36. shotgun/agents/tools/codebase/query_graph.py +6 -0
  37. shotgun/agents/tools/codebase/retrieve_code.py +6 -0
  38. shotgun/agents/tools/file_management.py +82 -16
  39. shotgun/agents/tools/registry.py +217 -0
  40. shotgun/agents/tools/web_search/__init__.py +55 -16
  41. shotgun/agents/tools/web_search/anthropic.py +76 -51
  42. shotgun/agents/tools/web_search/gemini.py +50 -27
  43. shotgun/agents/tools/web_search/openai.py +26 -17
  44. shotgun/agents/tools/web_search/utils.py +2 -2
  45. shotgun/agents/usage_manager.py +164 -0
  46. shotgun/api_endpoints.py +15 -0
  47. shotgun/cli/clear.py +53 -0
  48. shotgun/cli/codebase/commands.py +71 -2
  49. shotgun/cli/compact.py +186 -0
  50. shotgun/cli/config.py +41 -67
  51. shotgun/cli/context.py +111 -0
  52. shotgun/cli/export.py +1 -1
  53. shotgun/cli/feedback.py +50 -0
  54. shotgun/cli/models.py +3 -2
  55. shotgun/cli/plan.py +1 -1
  56. shotgun/cli/research.py +1 -1
  57. shotgun/cli/specify.py +1 -1
  58. shotgun/cli/tasks.py +1 -1
  59. shotgun/cli/update.py +18 -5
  60. shotgun/codebase/core/change_detector.py +5 -3
  61. shotgun/codebase/core/code_retrieval.py +4 -2
  62. shotgun/codebase/core/ingestor.py +169 -19
  63. shotgun/codebase/core/manager.py +177 -13
  64. shotgun/codebase/core/nl_query.py +1 -1
  65. shotgun/codebase/models.py +28 -3
  66. shotgun/codebase/service.py +14 -2
  67. shotgun/exceptions.py +32 -0
  68. shotgun/llm_proxy/__init__.py +19 -0
  69. shotgun/llm_proxy/clients.py +44 -0
  70. shotgun/llm_proxy/constants.py +15 -0
  71. shotgun/logging_config.py +18 -27
  72. shotgun/main.py +91 -4
  73. shotgun/posthog_telemetry.py +87 -40
  74. shotgun/prompts/agents/export.j2 +18 -1
  75. shotgun/prompts/agents/partials/common_agent_system_prompt.j2 +5 -1
  76. shotgun/prompts/agents/partials/interactive_mode.j2 +24 -7
  77. shotgun/prompts/agents/plan.j2 +1 -1
  78. shotgun/prompts/agents/research.j2 +1 -1
  79. shotgun/prompts/agents/specify.j2 +270 -3
  80. shotgun/prompts/agents/state/system_state.j2 +4 -0
  81. shotgun/prompts/agents/tasks.j2 +1 -1
  82. shotgun/prompts/codebase/partials/cypher_rules.j2 +13 -0
  83. shotgun/prompts/loader.py +2 -2
  84. shotgun/prompts/tools/web_search.j2 +14 -0
  85. shotgun/sdk/codebase.py +60 -2
  86. shotgun/sentry_telemetry.py +28 -21
  87. shotgun/settings.py +238 -0
  88. shotgun/shotgun_web/__init__.py +19 -0
  89. shotgun/shotgun_web/client.py +138 -0
  90. shotgun/shotgun_web/constants.py +21 -0
  91. shotgun/shotgun_web/models.py +47 -0
  92. shotgun/telemetry.py +24 -36
  93. shotgun/tui/app.py +275 -23
  94. shotgun/tui/commands/__init__.py +1 -1
  95. shotgun/tui/components/context_indicator.py +179 -0
  96. shotgun/tui/components/mode_indicator.py +70 -0
  97. shotgun/tui/components/status_bar.py +48 -0
  98. shotgun/tui/components/vertical_tail.py +6 -0
  99. shotgun/tui/containers.py +91 -0
  100. shotgun/tui/dependencies.py +39 -0
  101. shotgun/tui/filtered_codebase_service.py +46 -0
  102. shotgun/tui/protocols.py +45 -0
  103. shotgun/tui/screens/chat/__init__.py +5 -0
  104. shotgun/tui/screens/chat/chat.tcss +54 -0
  105. shotgun/tui/screens/chat/chat_screen.py +1234 -0
  106. shotgun/tui/screens/chat/codebase_index_prompt_screen.py +64 -0
  107. shotgun/tui/screens/chat/codebase_index_selection.py +12 -0
  108. shotgun/tui/screens/chat/help_text.py +40 -0
  109. shotgun/tui/screens/chat/prompt_history.py +48 -0
  110. shotgun/tui/screens/chat.tcss +11 -0
  111. shotgun/tui/screens/chat_screen/command_providers.py +226 -11
  112. shotgun/tui/screens/chat_screen/history/__init__.py +22 -0
  113. shotgun/tui/screens/chat_screen/history/agent_response.py +66 -0
  114. shotgun/tui/screens/chat_screen/history/chat_history.py +116 -0
  115. shotgun/tui/screens/chat_screen/history/formatters.py +115 -0
  116. shotgun/tui/screens/chat_screen/history/partial_response.py +43 -0
  117. shotgun/tui/screens/chat_screen/history/user_question.py +42 -0
  118. shotgun/tui/screens/confirmation_dialog.py +151 -0
  119. shotgun/tui/screens/feedback.py +193 -0
  120. shotgun/tui/screens/github_issue.py +102 -0
  121. shotgun/tui/screens/model_picker.py +352 -0
  122. shotgun/tui/screens/onboarding.py +431 -0
  123. shotgun/tui/screens/pipx_migration.py +153 -0
  124. shotgun/tui/screens/provider_config.py +156 -39
  125. shotgun/tui/screens/shotgun_auth.py +295 -0
  126. shotgun/tui/screens/welcome.py +198 -0
  127. shotgun/tui/services/__init__.py +5 -0
  128. shotgun/tui/services/conversation_service.py +184 -0
  129. shotgun/tui/state/__init__.py +7 -0
  130. shotgun/tui/state/processing_state.py +185 -0
  131. shotgun/tui/utils/mode_progress.py +14 -7
  132. shotgun/tui/widgets/__init__.py +5 -0
  133. shotgun/tui/widgets/widget_coordinator.py +262 -0
  134. shotgun/utils/datetime_utils.py +77 -0
  135. shotgun/utils/env_utils.py +13 -0
  136. shotgun/utils/file_system_utils.py +22 -2
  137. shotgun/utils/marketing.py +110 -0
  138. shotgun/utils/source_detection.py +16 -0
  139. shotgun/utils/update_checker.py +73 -21
  140. shotgun_sh-0.2.11.dist-info/METADATA +130 -0
  141. shotgun_sh-0.2.11.dist-info/RECORD +194 -0
  142. {shotgun_sh-0.1.9.dist-info → shotgun_sh-0.2.11.dist-info}/entry_points.txt +1 -0
  143. {shotgun_sh-0.1.9.dist-info → shotgun_sh-0.2.11.dist-info}/licenses/LICENSE +1 -1
  144. shotgun/agents/history/token_counting.py +0 -429
  145. shotgun/agents/tools/user_interaction.py +0 -37
  146. shotgun/tui/screens/chat.py +0 -818
  147. shotgun/tui/screens/chat_screen/history.py +0 -222
  148. shotgun_sh-0.1.9.dist-info/METADATA +0 -466
  149. shotgun_sh-0.1.9.dist-info/RECORD +0 -131
  150. {shotgun_sh-0.1.9.dist-info → shotgun_sh-0.2.11.dist-info}/WHEEL +0 -0
@@ -0,0 +1,262 @@
1
+ # mypy: disable-error-code="import-not-found"
2
+ """Widget coordinator to centralize widget queries and updates.
3
+
4
+ This module eliminates scattered `query_one()` calls throughout ChatScreen
5
+ by providing a single place for all widget updates. This improves:
6
+ - Testability (can test update logic in isolation)
7
+ - Maintainability (clear update contracts)
8
+ - Performance (can batch updates if needed)
9
+ """
10
+
11
+ import logging
12
+ from typing import TYPE_CHECKING
13
+
14
+ from pydantic_ai.messages import ModelMessage
15
+
16
+ from shotgun.agents.config.models import ModelName
17
+ from shotgun.agents.models import AgentType
18
+ from shotgun.tui.components.context_indicator import ContextIndicator
19
+ from shotgun.tui.components.mode_indicator import ModeIndicator
20
+ from shotgun.tui.components.prompt_input import PromptInput
21
+ from shotgun.tui.components.spinner import Spinner
22
+ from shotgun.tui.components.status_bar import StatusBar
23
+ from shotgun.tui.screens.chat_screen.history.chat_history import ChatHistory
24
+
25
+ if TYPE_CHECKING:
26
+ from shotgun.agents.context_analyzer.models import ContextAnalysis
27
+ from shotgun.agents.conversation_history import HintMessage
28
+ from shotgun.tui.screens.chat import ChatScreen
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ class WidgetCoordinator:
34
+ """Coordinates updates to all widgets in ChatScreen.
35
+
36
+ This class centralizes all `query_one()` calls and widget manipulations,
37
+ providing clear update methods instead of scattered direct queries.
38
+
39
+ Benefits:
40
+ - Single place for all widget updates
41
+ - Testable without full TUI
42
+ - Clear update contracts
43
+ - Can add batching/debouncing easily
44
+ """
45
+
46
+ def __init__(self, screen: "ChatScreen"):
47
+ """Initialize the coordinator with a reference to the screen.
48
+
49
+ Args:
50
+ screen: The ChatScreen instance containing the widgets.
51
+ """
52
+ self.screen = screen
53
+
54
+ def update_for_mode_change(
55
+ self, new_mode: AgentType, placeholder: str | None = None
56
+ ) -> None:
57
+ """Update all widgets when agent mode changes.
58
+
59
+ Args:
60
+ new_mode: The new agent mode.
61
+ placeholder: Optional placeholder text for input. If not provided,
62
+ will use the screen's _placeholder_for_mode method.
63
+ """
64
+ if not self.screen.is_mounted:
65
+ return
66
+
67
+ # Update mode indicator
68
+ try:
69
+ mode_indicator = self.screen.query_one(ModeIndicator)
70
+ mode_indicator.mode = new_mode
71
+ mode_indicator.refresh()
72
+ except Exception as e:
73
+ logger.exception(f"Failed to update mode indicator: {e}")
74
+
75
+ # Update prompt input placeholder
76
+ try:
77
+ prompt_input = self.screen.query_one(PromptInput)
78
+ if placeholder is None:
79
+ placeholder = self.screen._placeholder_for_mode(
80
+ new_mode, force_new=True
81
+ )
82
+ prompt_input.placeholder = placeholder
83
+ prompt_input.refresh()
84
+ except Exception as e:
85
+ logger.exception(f"Failed to update prompt input: {e}")
86
+
87
+ def update_for_processing_state(
88
+ self, is_processing: bool, spinner_text: str | None = None
89
+ ) -> None:
90
+ """Update widgets when processing state changes.
91
+
92
+ Args:
93
+ is_processing: Whether processing is active.
94
+ spinner_text: Optional text to display in spinner.
95
+ """
96
+ if not self.screen.is_mounted:
97
+ return
98
+
99
+ # Update spinner visibility
100
+ try:
101
+ spinner = self.screen.query_one("#spinner", Spinner)
102
+ spinner.set_classes("" if is_processing else "hidden")
103
+ spinner.display = is_processing
104
+ if spinner_text and is_processing:
105
+ spinner.text = spinner_text
106
+ except Exception as e:
107
+ logger.exception(f"Failed to update spinner: {e}")
108
+
109
+ # Update status bar
110
+ try:
111
+ status_bar = self.screen.query_one(StatusBar)
112
+ status_bar.working = is_processing
113
+ status_bar.refresh()
114
+ except Exception as e:
115
+ logger.exception(f"Failed to update status bar: {e}")
116
+
117
+ def update_for_qa_mode(self, qa_mode_active: bool) -> None:
118
+ """Update widgets when Q&A mode changes.
119
+
120
+ Args:
121
+ qa_mode_active: Whether Q&A mode is active.
122
+ """
123
+ if not self.screen.is_mounted:
124
+ return
125
+
126
+ # Update status bar
127
+ try:
128
+ status_bar = self.screen.query_one(StatusBar)
129
+ status_bar.refresh()
130
+ except Exception as e:
131
+ logger.exception(f"Failed to update status bar for Q&A: {e}")
132
+
133
+ # Update mode indicator
134
+ try:
135
+ mode_indicator = self.screen.query_one(ModeIndicator)
136
+ mode_indicator.refresh()
137
+ except Exception as e:
138
+ logger.exception(f"Failed to update mode indicator for Q&A: {e}")
139
+
140
+ def update_messages(self, messages: list[ModelMessage | "HintMessage"]) -> None:
141
+ """Update chat history with new messages.
142
+
143
+ Args:
144
+ messages: The messages to display.
145
+ """
146
+ if not self.screen.is_mounted:
147
+ return
148
+
149
+ try:
150
+ chat_history = self.screen.query_one(ChatHistory)
151
+ chat_history.update_messages(messages)
152
+ except Exception as e:
153
+ logger.exception(f"Failed to update messages: {e}")
154
+
155
+ def set_partial_response(
156
+ self, message: ModelMessage | None, messages: list[ModelMessage | "HintMessage"]
157
+ ) -> None:
158
+ """Update chat history with partial streaming response.
159
+
160
+ Args:
161
+ message: The partial message being streamed.
162
+ messages: The full message history.
163
+ """
164
+ if not self.screen.is_mounted:
165
+ return
166
+
167
+ try:
168
+ chat_history = self.screen.query_one(ChatHistory)
169
+ if message:
170
+ chat_history.partial_response = message
171
+ chat_history.update_messages(messages)
172
+ except Exception as e:
173
+ logger.exception(f"Failed to set partial response: {e}")
174
+
175
+ def update_context_indicator(
176
+ self, analysis: "ContextAnalysis | None", model_name: str
177
+ ) -> None:
178
+ """Update context indicator with new analysis.
179
+
180
+ Args:
181
+ analysis: The context analysis results.
182
+ model_name: The current model name.
183
+ """
184
+ if not self.screen.is_mounted:
185
+ return
186
+
187
+ try:
188
+ context_indicator = self.screen.query_one(ContextIndicator)
189
+ # Cast the string model name to ModelName type
190
+ model = ModelName(model_name) if model_name else None
191
+ context_indicator.update_context(analysis, model)
192
+ except Exception as e:
193
+ logger.exception(f"Failed to update context indicator: {e}")
194
+
195
+ def update_prompt_input(
196
+ self,
197
+ placeholder: str | None = None,
198
+ clear: bool = False,
199
+ focus: bool = False,
200
+ ) -> None:
201
+ """Update prompt input widget.
202
+
203
+ Args:
204
+ placeholder: New placeholder text.
205
+ clear: Whether to clear the input.
206
+ focus: Whether to focus the input.
207
+ """
208
+ if not self.screen.is_mounted:
209
+ return
210
+
211
+ try:
212
+ prompt_input = self.screen.query_one(PromptInput)
213
+ if placeholder is not None:
214
+ prompt_input.placeholder = placeholder
215
+ if clear:
216
+ prompt_input.clear()
217
+ if focus:
218
+ prompt_input.focus()
219
+ except Exception as e:
220
+ logger.exception(f"Failed to update prompt input: {e}")
221
+
222
+ def refresh_mode_indicator(self) -> None:
223
+ """Refresh mode indicator without changing mode."""
224
+ if not self.screen.is_mounted:
225
+ return
226
+
227
+ try:
228
+ mode_indicator = self.screen.query_one(ModeIndicator)
229
+ mode_indicator.refresh()
230
+ except Exception as e:
231
+ logger.exception(f"Failed to refresh mode indicator: {e}")
232
+
233
+ def update_spinner_text(self, text: str) -> None:
234
+ """Update spinner text without changing visibility.
235
+
236
+ Args:
237
+ text: The new spinner text.
238
+ """
239
+ if not self.screen.is_mounted:
240
+ return
241
+
242
+ try:
243
+ spinner = self.screen.query_one("#spinner", Spinner)
244
+ if spinner.display: # Only update if visible
245
+ spinner.text = text
246
+ except Exception as e:
247
+ logger.exception(f"Failed to update spinner text: {e}")
248
+
249
+ def set_context_streaming(self, streaming: bool) -> None:
250
+ """Enable or disable context indicator streaming animation.
251
+
252
+ Args:
253
+ streaming: Whether to show streaming animation.
254
+ """
255
+ if not self.screen.is_mounted:
256
+ return
257
+
258
+ try:
259
+ context_indicator = self.screen.query_one(ContextIndicator)
260
+ context_indicator.set_streaming(streaming)
261
+ except Exception as e:
262
+ logger.exception(f"Failed to set context streaming: {e}")
@@ -0,0 +1,77 @@
1
+ """Datetime utilities for consistent datetime formatting across the application."""
2
+
3
+ from datetime import datetime
4
+
5
+ from pydantic import BaseModel, Field
6
+
7
+
8
+ class DateTimeContext(BaseModel):
9
+ """Structured datetime context with timezone information.
10
+
11
+ This model provides consistently formatted datetime information
12
+ for use in prompts, templates, and UI display.
13
+
14
+ Attributes:
15
+ datetime_formatted: Human-readable datetime string
16
+ timezone_name: Short timezone name (e.g., "PST", "UTC")
17
+ utc_offset: UTC offset formatted with colon (e.g., "UTC-08:00")
18
+
19
+ Example:
20
+ >>> dt_context = get_datetime_context()
21
+ >>> print(dt_context.datetime_formatted)
22
+ 'Monday, January 13, 2025 at 3:45:30 PM'
23
+ >>> print(dt_context.timezone_name)
24
+ 'PST'
25
+ >>> print(dt_context.utc_offset)
26
+ 'UTC-08:00'
27
+ """
28
+
29
+ datetime_formatted: str = Field(
30
+ description="Human-readable datetime string in format: 'Day, Month DD, YYYY at HH:MM:SS AM/PM'"
31
+ )
32
+ timezone_name: str = Field(description="Short timezone name (e.g., PST, EST, UTC)")
33
+ utc_offset: str = Field(
34
+ description="UTC offset formatted with colon (e.g., UTC-08:00, UTC+05:30)"
35
+ )
36
+
37
+
38
+ def get_datetime_context() -> DateTimeContext:
39
+ """Get formatted datetime context with timezone information.
40
+
41
+ Returns a Pydantic model containing consistently formatted datetime
42
+ information suitable for use in prompts and templates.
43
+
44
+ Returns:
45
+ DateTimeContext: Structured datetime context with formatted strings
46
+
47
+ Example:
48
+ >>> dt_context = get_datetime_context()
49
+ >>> dt_context.datetime_formatted
50
+ 'Monday, January 13, 2025 at 3:45:30 PM'
51
+ >>> dt_context.timezone_name
52
+ 'PST'
53
+ >>> dt_context.utc_offset
54
+ 'UTC-08:00'
55
+ """
56
+ # Get current datetime with timezone information
57
+ now = datetime.now().astimezone()
58
+
59
+ # Format datetime in plain English
60
+ # Example: "Monday, January 13, 2025 at 3:45:30 PM"
61
+ datetime_formatted = now.strftime("%A, %B %d, %Y at %I:%M:%S %p")
62
+
63
+ # Get timezone name and UTC offset
64
+ # Example: "PST" and "UTC-08:00"
65
+ timezone_name = now.strftime("%Z")
66
+ utc_offset = now.strftime("%z") # Format: +0800 or -0500
67
+
68
+ # Reformat UTC offset to include colon: +08:00 or -05:00
69
+ utc_offset_formatted = (
70
+ f"UTC{utc_offset[:3]}:{utc_offset[3:]}" if utc_offset else "UTC"
71
+ )
72
+
73
+ return DateTimeContext(
74
+ datetime_formatted=datetime_formatted,
75
+ timezone_name=timezone_name,
76
+ utc_offset=utc_offset_formatted,
77
+ )
@@ -1,6 +1,19 @@
1
1
  """Utilities for working with environment variables."""
2
2
 
3
3
 
4
+ def is_shotgun_account_enabled() -> bool:
5
+ """Check if Shotgun Account feature is enabled via environment variable.
6
+
7
+ Returns:
8
+ True always (Shotgun Account is now live for all users)
9
+
10
+ Note:
11
+ This function is deprecated and always returns True.
12
+ Shotgun Account is now available to all users by default.
13
+ """
14
+ return True
15
+
16
+
4
17
  def is_truthy(value: str | None) -> bool:
5
18
  """Check if a string value represents true.
6
19
 
@@ -1,8 +1,11 @@
1
1
  """File system utility functions."""
2
2
 
3
- import os
4
3
  from pathlib import Path
5
4
 
5
+ import aiofiles
6
+
7
+ from shotgun.settings import settings
8
+
6
9
 
7
10
  def get_shotgun_base_path() -> Path:
8
11
  """Get the absolute path to the .shotgun directory."""
@@ -18,7 +21,7 @@ def get_shotgun_home() -> Path:
18
21
  Path to shotgun home directory (default: ~/.shotgun-sh/)
19
22
  """
20
23
  # Allow override via environment variable (useful for testing)
21
- if custom_home := os.environ.get("SHOTGUN_HOME"):
24
+ if custom_home := settings.dev.home:
22
25
  return Path(custom_home)
23
26
 
24
27
  return Path.home() / ".shotgun-sh"
@@ -34,3 +37,20 @@ def ensure_shotgun_directory_exists() -> Path:
34
37
  shotgun_dir.mkdir(exist_ok=True)
35
38
  # Note: Removed logger to avoid circular dependency with logging_config
36
39
  return shotgun_dir
40
+
41
+
42
+ async def async_copy_file(src: Path, dst: Path) -> None:
43
+ """Asynchronously copy a file from src to dst.
44
+
45
+ Args:
46
+ src: Source file path
47
+ dst: Destination file path
48
+
49
+ Raises:
50
+ FileNotFoundError: If source file doesn't exist
51
+ OSError: If copy operation fails
52
+ """
53
+ async with aiofiles.open(src, "rb") as src_file:
54
+ content = await src_file.read()
55
+ async with aiofiles.open(dst, "wb") as dst_file:
56
+ await dst_file.write(content)
@@ -0,0 +1,110 @@
1
+ """Marketing message management for Shotgun CLI."""
2
+
3
+ from collections.abc import Callable
4
+ from datetime import datetime, timezone
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING
7
+
8
+ from shotgun.agents.config.models import MarketingConfig, MarketingMessageRecord
9
+ from shotgun.agents.models import FileOperation
10
+
11
+ if TYPE_CHECKING:
12
+ from shotgun.agents.config.manager import ConfigManager
13
+
14
+ # Marketing message IDs
15
+ GITHUB_STAR_MESSAGE_ID = "github_star_v1"
16
+
17
+ # Spec files that trigger the GitHub star message
18
+ SPEC_FILES = {"research.md", "specification.md", "plan.md", "tasks.md"}
19
+
20
+
21
+ class MarketingManager:
22
+ """Manages marketing messages shown to users."""
23
+
24
+ @staticmethod
25
+ def should_show_github_star_message(
26
+ marketing_config: MarketingConfig, file_operations: list[FileOperation]
27
+ ) -> bool:
28
+ """
29
+ Check if the GitHub star message should be shown.
30
+
31
+ Args:
32
+ marketing_config: Current marketing configuration
33
+ file_operations: List of file operations from the current agent run
34
+
35
+ Returns:
36
+ True if message should be shown, False otherwise
37
+ """
38
+ # Check if message has already been shown
39
+ if GITHUB_STAR_MESSAGE_ID in marketing_config.messages:
40
+ return False
41
+
42
+ # Check if any spec file was written
43
+ for operation in file_operations:
44
+ # operation.file_path is a string, so we convert to Path to get the filename
45
+ file_name = Path(operation.file_path).name
46
+ if file_name in SPEC_FILES:
47
+ return True
48
+
49
+ return False
50
+
51
+ @staticmethod
52
+ def mark_message_shown(
53
+ marketing_config: MarketingConfig, message_id: str
54
+ ) -> MarketingConfig:
55
+ """
56
+ Mark a marketing message as shown.
57
+
58
+ Args:
59
+ marketing_config: Current marketing configuration
60
+ message_id: ID of the message to mark as shown
61
+
62
+ Returns:
63
+ Updated marketing configuration
64
+ """
65
+ # Create a new record with current timestamp
66
+ record = MarketingMessageRecord(shown_at=datetime.now(timezone.utc))
67
+
68
+ # Update the messages dict
69
+ marketing_config.messages[message_id] = record
70
+
71
+ return marketing_config
72
+
73
+ @staticmethod
74
+ def get_github_star_message() -> str:
75
+ """Get the GitHub star marketing message text."""
76
+ return "⭐ Enjoying Shotgun? Star us on GitHub: https://github.com/shotgun-sh/shotgun"
77
+
78
+ @staticmethod
79
+ async def check_and_display_messages(
80
+ config_manager: "ConfigManager",
81
+ file_operations: list[FileOperation],
82
+ display_callback: Callable[[str], None],
83
+ ) -> None:
84
+ """
85
+ Check if any marketing messages should be shown and display them.
86
+
87
+ This is the main entry point for marketing message handling. It checks
88
+ all configured messages, displays them if appropriate, and updates the
89
+ config to mark them as shown.
90
+
91
+ Args:
92
+ config_manager: Config manager to load/save configuration
93
+ file_operations: List of file operations from the current agent run
94
+ display_callback: Callback function to display messages to the user
95
+ """
96
+ config = await config_manager.load()
97
+
98
+ # Check GitHub star message
99
+ if MarketingManager.should_show_github_star_message(
100
+ config.marketing, file_operations
101
+ ):
102
+ # Display the message
103
+ message = MarketingManager.get_github_star_message()
104
+ display_callback(message)
105
+
106
+ # Mark as shown and save
107
+ MarketingManager.mark_message_shown(
108
+ config.marketing, GITHUB_STAR_MESSAGE_ID
109
+ )
110
+ await config_manager.save(config)
@@ -0,0 +1,16 @@
1
+ """Utility for detecting the source of function calls (CLI vs TUI)."""
2
+
3
+ import inspect
4
+
5
+
6
+ def detect_source() -> str:
7
+ """Detect if the call originated from CLI or TUI by inspecting the call stack.
8
+
9
+ Returns:
10
+ "tui" if any frame in the call stack contains "tui" in the filename,
11
+ "cli" otherwise.
12
+ """
13
+ for frame_info in inspect.stack():
14
+ if "tui" in frame_info.filename.lower():
15
+ return "tui"
16
+ return "cli"
@@ -5,7 +5,12 @@ import sys
5
5
  import threading
6
6
  from pathlib import Path
7
7
 
8
+ import httpx
9
+ from packaging import version
10
+
11
+ from shotgun import __version__
8
12
  from shotgun.logging_config import get_logger
13
+ from shotgun.settings import settings
9
14
 
10
15
  logger = get_logger(__name__)
11
16
 
@@ -14,8 +19,34 @@ def detect_installation_method() -> str:
14
19
  """Detect how shotgun-sh was installed.
15
20
 
16
21
  Returns:
17
- Installation method: 'pipx', 'pip', 'venv', or 'unknown'.
22
+ Installation method: 'uvx', 'uv-tool', 'pipx', 'pip', 'venv', or 'unknown'.
18
23
  """
24
+ # Check for simulation environment variable (for testing)
25
+ if settings.dev.pipx_simulate:
26
+ logger.debug("SHOTGUN_PIPX_SIMULATE enabled, simulating pipx installation")
27
+ return "pipx"
28
+
29
+ # Check for uvx (ephemeral execution) by looking at executable path
30
+ # uvx runs from a temporary cache directory
31
+ executable = Path(sys.executable)
32
+ if ".cache/uv" in str(executable) or "uv/cache" in str(executable):
33
+ logger.debug("Detected uvx (ephemeral) execution")
34
+ return "uvx"
35
+
36
+ # Check for uv tool installation
37
+ try:
38
+ result = subprocess.run(
39
+ ["uv", "tool", "list"], # noqa: S607, S603
40
+ capture_output=True,
41
+ text=True,
42
+ timeout=5,
43
+ )
44
+ if result.returncode == 0 and "shotgun-sh" in result.stdout:
45
+ logger.debug("Detected uv tool installation")
46
+ return "uv-tool"
47
+ except (subprocess.SubprocessError, FileNotFoundError):
48
+ pass
49
+
19
50
  # Check for pipx installation
20
51
  try:
21
52
  result = subprocess.run(
@@ -55,7 +86,7 @@ def detect_installation_method() -> str:
55
86
 
56
87
 
57
88
  def perform_auto_update(no_update_check: bool = False) -> None:
58
- """Perform automatic update if installed via pipx.
89
+ """Perform automatic update if installed via pipx or uv tool.
59
90
 
60
91
  Args:
61
92
  no_update_check: If True, skip the update.
@@ -64,23 +95,40 @@ def perform_auto_update(no_update_check: bool = False) -> None:
64
95
  return
65
96
 
66
97
  try:
67
- # Only auto-update for pipx installations
68
- if detect_installation_method() != "pipx":
69
- logger.debug("Not a pipx installation, skipping auto-update")
98
+ method = detect_installation_method()
99
+
100
+ # Skip auto-update for ephemeral uvx executions
101
+ if method == "uvx":
102
+ logger.debug("uvx (ephemeral) execution, skipping auto-update")
70
103
  return
71
104
 
72
- # Run pipx upgrade quietly
73
- logger.debug("Running pipx upgrade shotgun-sh --quiet")
74
- result = subprocess.run(
75
- ["pipx", "upgrade", "shotgun-sh", "--quiet"], # noqa: S607, S603
105
+ # Only auto-update for pipx and uv-tool installations
106
+ if method not in ["pipx", "uv-tool"]:
107
+ logger.debug(f"Installation method '{method}', skipping auto-update")
108
+ return
109
+
110
+ # Determine the appropriate upgrade command
111
+ if method == "pipx":
112
+ command = ["pipx", "upgrade", "shotgun-sh", "--quiet"]
113
+ logger.debug("Running pipx upgrade shotgun-sh --quiet")
114
+ elif method == "uv-tool":
115
+ command = ["uv", "tool", "upgrade", "shotgun-sh"]
116
+ logger.debug("Running uv tool upgrade shotgun-sh")
117
+ else:
118
+ return
119
+
120
+ # Run upgrade command
121
+ result = subprocess.run( # noqa: S603, S607
122
+ command,
76
123
  capture_output=True,
77
124
  text=True,
78
125
  timeout=30,
79
126
  )
80
127
 
81
128
  if result.returncode == 0:
82
- # Check if there was an actual update (pipx shows output even with --quiet for actual updates)
83
- if result.stdout and "upgraded" in result.stdout.lower():
129
+ # Check if there was an actual update
130
+ output = result.stdout.lower()
131
+ if "upgraded" in output or "updated" in output:
84
132
  logger.info("Shotgun-sh has been updated to the latest version")
85
133
  else:
86
134
  # Only log errors at debug level to not annoy users
@@ -110,13 +158,6 @@ def perform_auto_update_async(no_update_check: bool = False) -> threading.Thread
110
158
  return thread
111
159
 
112
160
 
113
- # Keep these for backward compatibility with the update CLI command
114
- import httpx # noqa: E402
115
- from packaging import version # noqa: E402
116
-
117
- from shotgun import __version__ # noqa: E402
118
-
119
-
120
161
  def is_dev_version(version_str: str | None = None) -> bool:
121
162
  """Check if the current or given version is a development version.
122
163
 
@@ -169,16 +210,18 @@ def compare_versions(current: str, latest: str) -> bool:
169
210
  return False
170
211
 
171
212
 
172
- def get_update_command(method: str) -> list[str]:
213
+ def get_update_command(method: str) -> list[str] | None:
173
214
  """Get the appropriate update command based on installation method.
174
215
 
175
216
  Args:
176
- method: Installation method ('pipx', 'pip', 'venv', or 'unknown').
217
+ method: Installation method ('uvx', 'uv-tool', 'pipx', 'pip', 'venv', or 'unknown').
177
218
 
178
219
  Returns:
179
- Command list to execute for updating.
220
+ Command list to execute for updating, or None for uvx (ephemeral).
180
221
  """
181
222
  commands = {
223
+ "uvx": None, # uvx is ephemeral, no update command
224
+ "uv-tool": ["uv", "tool", "upgrade", "shotgun-sh"],
182
225
  "pipx": ["pipx", "upgrade", "shotgun-sh"],
183
226
  "pip": [sys.executable, "-m", "pip", "install", "--upgrade", "shotgun-sh"],
184
227
  "venv": [sys.executable, "-m", "pip", "install", "--upgrade", "shotgun-sh"],
@@ -213,6 +256,15 @@ def perform_update(force: bool = False) -> tuple[bool, str]:
213
256
  method = detect_installation_method()
214
257
  command = get_update_command(method)
215
258
 
259
+ # Handle uvx (ephemeral) installations
260
+ if method == "uvx" or command is None:
261
+ return (
262
+ False,
263
+ "You're running shotgun-sh via uvx (ephemeral mode). "
264
+ "To get the latest version, simply run 'uvx shotgun-sh' again, "
265
+ "or install permanently with 'uv tool install shotgun-sh'.",
266
+ )
267
+
216
268
  # Perform update
217
269
  try:
218
270
  logger.info(f"Updating shotgun-sh using {method}...")