shotgun-sh 0.2.11.dev1__py3-none-any.whl → 0.2.11.dev5__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 (70) hide show
  1. shotgun/agents/agent_manager.py +150 -27
  2. shotgun/agents/common.py +14 -8
  3. shotgun/agents/config/manager.py +64 -33
  4. shotgun/agents/config/models.py +25 -1
  5. shotgun/agents/config/provider.py +2 -2
  6. shotgun/agents/context_analyzer/analyzer.py +2 -24
  7. shotgun/agents/conversation_manager.py +35 -19
  8. shotgun/agents/export.py +2 -2
  9. shotgun/agents/history/token_counting/anthropic.py +17 -1
  10. shotgun/agents/history/token_counting/base.py +14 -3
  11. shotgun/agents/history/token_counting/openai.py +8 -0
  12. shotgun/agents/history/token_counting/sentencepiece_counter.py +8 -0
  13. shotgun/agents/history/token_counting/tokenizer_cache.py +3 -1
  14. shotgun/agents/history/token_counting/utils.py +0 -3
  15. shotgun/agents/plan.py +2 -2
  16. shotgun/agents/research.py +3 -3
  17. shotgun/agents/specify.py +2 -2
  18. shotgun/agents/tasks.py +2 -2
  19. shotgun/agents/tools/codebase/file_read.py +5 -2
  20. shotgun/agents/tools/file_management.py +11 -7
  21. shotgun/agents/tools/web_search/__init__.py +8 -8
  22. shotgun/agents/tools/web_search/anthropic.py +2 -2
  23. shotgun/agents/tools/web_search/gemini.py +1 -1
  24. shotgun/agents/tools/web_search/openai.py +1 -1
  25. shotgun/agents/tools/web_search/utils.py +2 -2
  26. shotgun/agents/usage_manager.py +16 -11
  27. shotgun/cli/clear.py +2 -1
  28. shotgun/cli/compact.py +3 -3
  29. shotgun/cli/config.py +8 -5
  30. shotgun/cli/context.py +2 -2
  31. shotgun/cli/export.py +1 -1
  32. shotgun/cli/feedback.py +4 -2
  33. shotgun/cli/plan.py +1 -1
  34. shotgun/cli/research.py +1 -1
  35. shotgun/cli/specify.py +1 -1
  36. shotgun/cli/tasks.py +1 -1
  37. shotgun/codebase/core/change_detector.py +5 -3
  38. shotgun/codebase/core/code_retrieval.py +4 -2
  39. shotgun/codebase/core/ingestor.py +10 -8
  40. shotgun/codebase/core/manager.py +3 -3
  41. shotgun/codebase/core/nl_query.py +1 -1
  42. shotgun/logging_config.py +10 -17
  43. shotgun/main.py +3 -1
  44. shotgun/posthog_telemetry.py +14 -4
  45. shotgun/sentry_telemetry.py +3 -1
  46. shotgun/telemetry.py +3 -1
  47. shotgun/tui/app.py +71 -65
  48. shotgun/tui/components/context_indicator.py +43 -0
  49. shotgun/tui/containers.py +15 -17
  50. shotgun/tui/dependencies.py +2 -2
  51. shotgun/tui/screens/chat/chat_screen.py +110 -18
  52. shotgun/tui/screens/chat/help_text.py +16 -15
  53. shotgun/tui/screens/chat_screen/command_providers.py +10 -0
  54. shotgun/tui/screens/feedback.py +4 -4
  55. shotgun/tui/screens/github_issue.py +102 -0
  56. shotgun/tui/screens/model_picker.py +21 -20
  57. shotgun/tui/screens/onboarding.py +431 -0
  58. shotgun/tui/screens/provider_config.py +50 -27
  59. shotgun/tui/screens/shotgun_auth.py +2 -2
  60. shotgun/tui/screens/welcome.py +14 -11
  61. shotgun/tui/services/conversation_service.py +16 -14
  62. shotgun/tui/utils/mode_progress.py +14 -7
  63. shotgun/tui/widgets/widget_coordinator.py +15 -0
  64. shotgun/utils/file_system_utils.py +19 -0
  65. shotgun/utils/marketing.py +110 -0
  66. {shotgun_sh-0.2.11.dev1.dist-info → shotgun_sh-0.2.11.dev5.dist-info}/METADATA +2 -1
  67. {shotgun_sh-0.2.11.dev1.dist-info → shotgun_sh-0.2.11.dev5.dist-info}/RECORD +70 -67
  68. {shotgun_sh-0.2.11.dev1.dist-info → shotgun_sh-0.2.11.dev5.dist-info}/WHEEL +0 -0
  69. {shotgun_sh-0.2.11.dev1.dist-info → shotgun_sh-0.2.11.dev5.dist-info}/entry_points.txt +0 -0
  70. {shotgun_sh-0.2.11.dev1.dist-info → shotgun_sh-0.2.11.dev5.dist-info}/licenses/LICENSE +0 -0
@@ -169,6 +169,14 @@ class CompactionCompletedMessage(Message):
169
169
  """Event posted when conversation compaction completes."""
170
170
 
171
171
 
172
+ class AgentStreamingStarted(Message):
173
+ """Event posted when agent starts streaming responses."""
174
+
175
+
176
+ class AgentStreamingCompleted(Message):
177
+ """Event posted when agent finishes streaming responses."""
178
+
179
+
172
180
  @dataclass(frozen=True)
173
181
  class ModelConfigUpdated:
174
182
  """Data returned when AI model configuration changes.
@@ -222,7 +230,7 @@ class AgentManager(Widget):
222
230
  self.deps = deps
223
231
 
224
232
  # Create AgentRuntimeOptions from deps for agent creation
225
- agent_runtime_options = AgentRuntimeOptions(
233
+ self._agent_runtime_options = AgentRuntimeOptions(
226
234
  interactive_mode=self.deps.interactive_mode,
227
235
  working_directory=self.deps.working_directory,
228
236
  is_tui_context=self.deps.is_tui_context,
@@ -231,22 +239,18 @@ class AgentManager(Widget):
231
239
  tasks=self.deps.tasks,
232
240
  )
233
241
 
234
- # Initialize all agents and store their specific deps
235
- self.research_agent, self.research_deps = create_research_agent(
236
- agent_runtime_options=agent_runtime_options
237
- )
238
- self.plan_agent, self.plan_deps = create_plan_agent(
239
- agent_runtime_options=agent_runtime_options
240
- )
241
- self.tasks_agent, self.tasks_deps = create_tasks_agent(
242
- agent_runtime_options=agent_runtime_options
243
- )
244
- self.specify_agent, self.specify_deps = create_specify_agent(
245
- agent_runtime_options=agent_runtime_options
246
- )
247
- self.export_agent, self.export_deps = create_export_agent(
248
- agent_runtime_options=agent_runtime_options
249
- )
242
+ # Lazy initialization - agents created on first access
243
+ self._research_agent: Agent[AgentDeps, AgentResponse] | None = None
244
+ self._research_deps: AgentDeps | None = None
245
+ self._plan_agent: Agent[AgentDeps, AgentResponse] | None = None
246
+ self._plan_deps: AgentDeps | None = None
247
+ self._tasks_agent: Agent[AgentDeps, AgentResponse] | None = None
248
+ self._tasks_deps: AgentDeps | None = None
249
+ self._specify_agent: Agent[AgentDeps, AgentResponse] | None = None
250
+ self._specify_deps: AgentDeps | None = None
251
+ self._export_agent: Agent[AgentDeps, AgentResponse] | None = None
252
+ self._export_deps: AgentDeps | None = None
253
+ self._agents_initialized = False
250
254
 
251
255
  # Track current active agent
252
256
  self._current_agent_type: AgentType = initial_type
@@ -261,6 +265,119 @@ class AgentManager(Widget):
261
265
  self._qa_questions: list[str] | None = None
262
266
  self._qa_mode_active: bool = False
263
267
 
268
+ async def _ensure_agents_initialized(self) -> None:
269
+ """Ensure all agents are initialized (lazy initialization)."""
270
+ if self._agents_initialized:
271
+ return
272
+
273
+ # Initialize all agents asynchronously
274
+ self._research_agent, self._research_deps = await create_research_agent(
275
+ agent_runtime_options=self._agent_runtime_options
276
+ )
277
+ self._plan_agent, self._plan_deps = await create_plan_agent(
278
+ agent_runtime_options=self._agent_runtime_options
279
+ )
280
+ self._tasks_agent, self._tasks_deps = await create_tasks_agent(
281
+ agent_runtime_options=self._agent_runtime_options
282
+ )
283
+ self._specify_agent, self._specify_deps = await create_specify_agent(
284
+ agent_runtime_options=self._agent_runtime_options
285
+ )
286
+ self._export_agent, self._export_deps = await create_export_agent(
287
+ agent_runtime_options=self._agent_runtime_options
288
+ )
289
+ self._agents_initialized = True
290
+
291
+ @property
292
+ def research_agent(self) -> Agent[AgentDeps, AgentResponse]:
293
+ """Get research agent (must call _ensure_agents_initialized first)."""
294
+ if self._research_agent is None:
295
+ raise RuntimeError(
296
+ "Agents not initialized. Call _ensure_agents_initialized() first."
297
+ )
298
+ return self._research_agent
299
+
300
+ @property
301
+ def research_deps(self) -> AgentDeps:
302
+ """Get research deps (must call _ensure_agents_initialized first)."""
303
+ if self._research_deps is None:
304
+ raise RuntimeError(
305
+ "Agents not initialized. Call _ensure_agents_initialized() first."
306
+ )
307
+ return self._research_deps
308
+
309
+ @property
310
+ def plan_agent(self) -> Agent[AgentDeps, AgentResponse]:
311
+ """Get plan agent (must call _ensure_agents_initialized first)."""
312
+ if self._plan_agent is None:
313
+ raise RuntimeError(
314
+ "Agents not initialized. Call _ensure_agents_initialized() first."
315
+ )
316
+ return self._plan_agent
317
+
318
+ @property
319
+ def plan_deps(self) -> AgentDeps:
320
+ """Get plan deps (must call _ensure_agents_initialized first)."""
321
+ if self._plan_deps is None:
322
+ raise RuntimeError(
323
+ "Agents not initialized. Call _ensure_agents_initialized() first."
324
+ )
325
+ return self._plan_deps
326
+
327
+ @property
328
+ def tasks_agent(self) -> Agent[AgentDeps, AgentResponse]:
329
+ """Get tasks agent (must call _ensure_agents_initialized first)."""
330
+ if self._tasks_agent is None:
331
+ raise RuntimeError(
332
+ "Agents not initialized. Call _ensure_agents_initialized() first."
333
+ )
334
+ return self._tasks_agent
335
+
336
+ @property
337
+ def tasks_deps(self) -> AgentDeps:
338
+ """Get tasks deps (must call _ensure_agents_initialized first)."""
339
+ if self._tasks_deps is None:
340
+ raise RuntimeError(
341
+ "Agents not initialized. Call _ensure_agents_initialized() first."
342
+ )
343
+ return self._tasks_deps
344
+
345
+ @property
346
+ def specify_agent(self) -> Agent[AgentDeps, AgentResponse]:
347
+ """Get specify agent (must call _ensure_agents_initialized first)."""
348
+ if self._specify_agent is None:
349
+ raise RuntimeError(
350
+ "Agents not initialized. Call _ensure_agents_initialized() first."
351
+ )
352
+ return self._specify_agent
353
+
354
+ @property
355
+ def specify_deps(self) -> AgentDeps:
356
+ """Get specify deps (must call _ensure_agents_initialized first)."""
357
+ if self._specify_deps is None:
358
+ raise RuntimeError(
359
+ "Agents not initialized. Call _ensure_agents_initialized() first."
360
+ )
361
+ return self._specify_deps
362
+
363
+ @property
364
+ def export_agent(self) -> Agent[AgentDeps, AgentResponse]:
365
+ """Get export agent (must call _ensure_agents_initialized first)."""
366
+ if self._export_agent is None:
367
+ raise RuntimeError(
368
+ "Agents not initialized. Call _ensure_agents_initialized() first."
369
+ )
370
+ return self._export_agent
371
+
372
+ @property
373
+ def export_deps(self) -> AgentDeps:
374
+ """Get export deps (must call _ensure_agents_initialized first)."""
375
+ if self._export_deps is None:
376
+ raise RuntimeError(
377
+ "Agents not initialized. Call _ensure_agents_initialized() first."
378
+ )
379
+ return self._export_deps
380
+
264
381
  @property
265
382
  def current_agent(self) -> Agent[AgentDeps, AgentResponse]:
266
383
  """Get the currently active agent.
@@ -412,6 +529,9 @@ class AgentManager(Widget):
412
529
  Returns:
413
530
  The agent run result.
414
531
  """
532
+ # Ensure agents are initialized before running
533
+ await self._ensure_agents_initialized()
534
+
415
535
  logger.info(f"Running agent {self._current_agent_type.value}")
416
536
  # Use merged deps (shared state + agent-specific system prompt) if not provided
417
537
  if deps is None:
@@ -684,11 +804,9 @@ class AgentManager(Widget):
684
804
  )
685
805
  )
686
806
 
687
- # Post UI update with hint messages and file operations
688
- logger.debug(
689
- "Posting UI update for Q&A mode with hint messages and file operations"
690
- )
691
- self._post_messages_updated(file_operations)
807
+ # Post UI update with hint messages (file operations will be posted after compaction)
808
+ logger.debug("Posting UI update for Q&A mode with hint messages")
809
+ self._post_messages_updated([])
692
810
  else:
693
811
  # No clarifying questions - show the response or a default success message
694
812
  if agent_response.response and agent_response.response.strip():
@@ -723,10 +841,9 @@ class AgentManager(Widget):
723
841
  )
724
842
 
725
843
  # Post UI update immediately so user sees the response without delay
726
- logger.debug(
727
- "Posting immediate UI update with hint message and file operations"
728
- )
729
- self._post_messages_updated(file_operations)
844
+ # (file operations will be posted after compaction to avoid duplicates)
845
+ logger.debug("Posting immediate UI update with hint message")
846
+ self._post_messages_updated([])
730
847
 
731
848
  # Apply compaction to persistent message history to prevent cascading growth
732
849
  all_messages = result.all_messages()
@@ -780,7 +897,7 @@ class AgentManager(Widget):
780
897
 
781
898
  usage = result.usage()
782
899
  if hasattr(deps, "llm_model") and deps.llm_model is not None:
783
- deps.usage_manager.add_usage(
900
+ await deps.usage_manager.add_usage(
784
901
  usage, model_name=deps.llm_model.name, provider=deps.llm_model.provider
785
902
  )
786
903
  else:
@@ -806,6 +923,9 @@ class AgentManager(Widget):
806
923
  ) -> None:
807
924
  """Process streamed events and forward partial updates to the UI."""
808
925
 
926
+ # Notify UI that streaming has started
927
+ self.post_message(AgentStreamingStarted())
928
+
809
929
  state = self._stream_state
810
930
  if state is None:
811
931
  state = self._stream_state = _PartialStreamState()
@@ -984,6 +1104,9 @@ class AgentManager(Widget):
984
1104
  self._post_partial_message(True)
985
1105
  state.current_response = None
986
1106
 
1107
+ # Notify UI that streaming has completed
1108
+ self.post_message(AgentStreamingCompleted())
1109
+
987
1110
  def _build_partial_response(
988
1111
  self, parts: list[ModelResponsePart | ToolCallPartDelta]
989
1112
  ) -> ModelResponse | None:
shotgun/agents/common.py CHANGED
@@ -4,6 +4,7 @@ from collections.abc import Callable
4
4
  from pathlib import Path
5
5
  from typing import Any
6
6
 
7
+ import aiofiles
7
8
  from pydantic_ai import (
8
9
  Agent,
9
10
  RunContext,
@@ -68,7 +69,7 @@ async def add_system_status_message(
68
69
  existing_files = get_agent_existing_files(deps.agent_mode)
69
70
 
70
71
  # Extract table of contents from the agent's markdown file
71
- markdown_toc = extract_markdown_toc(deps.agent_mode)
72
+ markdown_toc = await extract_markdown_toc(deps.agent_mode)
72
73
 
73
74
  # Get current datetime with timezone information
74
75
  dt_context = get_datetime_context()
@@ -94,7 +95,7 @@ async def add_system_status_message(
94
95
  return message_history
95
96
 
96
97
 
97
- def create_base_agent(
98
+ async def create_base_agent(
98
99
  system_prompt_fn: Callable[[RunContext[AgentDeps]], str],
99
100
  agent_runtime_options: AgentRuntimeOptions,
100
101
  load_codebase_understanding_tools: bool = True,
@@ -119,7 +120,7 @@ def create_base_agent(
119
120
 
120
121
  # Get configured model or fall back to first available provider
121
122
  try:
122
- model_config = get_provider_model(provider)
123
+ model_config = await get_provider_model(provider)
123
124
  provider_name = model_config.provider
124
125
  logger.debug(
125
126
  "🤖 Creating agent with configured %s model: %s",
@@ -194,7 +195,7 @@ def create_base_agent(
194
195
  return agent, deps
195
196
 
196
197
 
197
- def _extract_file_toc_content(
198
+ async def _extract_file_toc_content(
198
199
  file_path: Path, max_depth: int | None = None, max_chars: int = 500
199
200
  ) -> str | None:
200
201
  """Extract TOC from a single file with depth and character limits.
@@ -211,7 +212,8 @@ def _extract_file_toc_content(
211
212
  return None
212
213
 
213
214
  try:
214
- content = file_path.read_text(encoding="utf-8")
215
+ async with aiofiles.open(file_path, encoding="utf-8") as f:
216
+ content = await f.read()
215
217
  lines = content.split("\n")
216
218
 
217
219
  # Extract headings
@@ -257,7 +259,7 @@ def _extract_file_toc_content(
257
259
  return None
258
260
 
259
261
 
260
- def extract_markdown_toc(agent_mode: AgentType | None) -> str | None:
262
+ async def extract_markdown_toc(agent_mode: AgentType | None) -> str | None:
261
263
  """Extract TOCs from current and prior agents' files in the pipeline.
262
264
 
263
265
  Shows full TOC of agent's own file and high-level summaries of prior agents'
@@ -309,7 +311,9 @@ def extract_markdown_toc(agent_mode: AgentType | None) -> str | None:
309
311
  for prior_file in config.prior_files:
310
312
  file_path = base_path / prior_file
311
313
  # Only show # and ## headings from prior files, max 500 chars each
312
- prior_toc = _extract_file_toc_content(file_path, max_depth=2, max_chars=500)
314
+ prior_toc = await _extract_file_toc_content(
315
+ file_path, max_depth=2, max_chars=500
316
+ )
313
317
  if prior_toc:
314
318
  # Add section with XML tags
315
319
  toc_sections.append(
@@ -321,7 +325,9 @@ def extract_markdown_toc(agent_mode: AgentType | None) -> str | None:
321
325
  # Extract TOC from own file (full detail)
322
326
  if config.own_file:
323
327
  own_path = base_path / config.own_file
324
- own_toc = _extract_file_toc_content(own_path, max_depth=None, max_chars=2000)
328
+ own_toc = await _extract_file_toc_content(
329
+ own_path, max_depth=None, max_chars=2000
330
+ )
325
331
  if own_toc:
326
332
  # Put own file TOC at the beginning with XML tags
327
333
  toc_sections.insert(
@@ -5,6 +5,8 @@ import uuid
5
5
  from pathlib import Path
6
6
  from typing import Any
7
7
 
8
+ import aiofiles
9
+ import aiofiles.os
8
10
  from pydantic import SecretStr
9
11
 
10
12
  from shotgun.logging_config import get_logger
@@ -48,7 +50,7 @@ class ConfigManager:
48
50
 
49
51
  self._config: ShotgunConfig | None = None
50
52
 
51
- def load(self, force_reload: bool = True) -> ShotgunConfig:
53
+ async def load(self, force_reload: bool = True) -> ShotgunConfig:
52
54
  """Load configuration from file.
53
55
 
54
56
  Args:
@@ -60,18 +62,19 @@ class ConfigManager:
60
62
  if self._config is not None and not force_reload:
61
63
  return self._config
62
64
 
63
- if not self.config_path.exists():
65
+ if not await aiofiles.os.path.exists(self.config_path):
64
66
  logger.info(
65
67
  "Configuration file not found, creating new config at: %s",
66
68
  self.config_path,
67
69
  )
68
70
  # Create new config with generated shotgun_instance_id
69
- self._config = self.initialize()
71
+ self._config = await self.initialize()
70
72
  return self._config
71
73
 
72
74
  try:
73
- with open(self.config_path, encoding="utf-8") as f:
74
- data = json.load(f)
75
+ async with aiofiles.open(self.config_path, encoding="utf-8") as f:
76
+ content = await f.read()
77
+ data = json.loads(content)
75
78
 
76
79
  # Migration: Rename user_id to shotgun_instance_id (config v2 -> v3)
77
80
  if "user_id" in data and SHOTGUN_INSTANCE_ID_FIELD not in data:
@@ -101,6 +104,12 @@ class ConfigManager:
101
104
  "Existing BYOK user detected: set shown_welcome_screen=False to show welcome screen"
102
105
  )
103
106
 
107
+ # Migration: Add marketing config for v3 -> v4
108
+ if "marketing" not in data:
109
+ data["marketing"] = {"messages": {}}
110
+ data["config_version"] = 4
111
+ logger.info("Migrated config v3->v4: added marketing configuration")
112
+
104
113
  # Convert plain text secrets to SecretStr objects
105
114
  self._convert_secrets_to_secretstr(data)
106
115
 
@@ -117,7 +126,7 @@ class ConfigManager:
117
126
 
118
127
  if self._config.selected_model in MODEL_SPECS:
119
128
  spec = MODEL_SPECS[self._config.selected_model]
120
- if not self.has_provider_key(spec.provider):
129
+ if not await self.has_provider_key(spec.provider):
121
130
  logger.info(
122
131
  "Selected model %s provider has no API key, finding available model",
123
132
  self._config.selected_model.value,
@@ -135,7 +144,7 @@ class ConfigManager:
135
144
  # If no selected_model or it was invalid, find first available model
136
145
  if not self._config.selected_model:
137
146
  for provider in ProviderType:
138
- if self.has_provider_key(provider):
147
+ if await self.has_provider_key(provider):
139
148
  # Set to that provider's default model
140
149
  from .models import MODEL_SPECS, ModelName
141
150
 
@@ -156,7 +165,7 @@ class ConfigManager:
156
165
  break
157
166
 
158
167
  if should_save:
159
- self.save(self._config)
168
+ await self.save(self._config)
160
169
 
161
170
  return self._config
162
171
 
@@ -165,10 +174,10 @@ class ConfigManager:
165
174
  "Failed to load configuration from %s: %s", self.config_path, e
166
175
  )
167
176
  logger.info("Creating new configuration with generated shotgun_instance_id")
168
- self._config = self.initialize()
177
+ self._config = await self.initialize()
169
178
  return self._config
170
179
 
171
- def save(self, config: ShotgunConfig | None = None) -> None:
180
+ async def save(self, config: ShotgunConfig | None = None) -> None:
172
181
  """Save configuration to file.
173
182
 
174
183
  Args:
@@ -184,15 +193,17 @@ class ConfigManager:
184
193
  )
185
194
 
186
195
  # Ensure directory exists
187
- self.config_path.parent.mkdir(parents=True, exist_ok=True)
196
+ await aiofiles.os.makedirs(self.config_path.parent, exist_ok=True)
188
197
 
189
198
  try:
190
199
  # Convert SecretStr to plain text for JSON serialization
191
200
  data = config.model_dump()
192
201
  self._convert_secretstr_to_plain(data)
202
+ self._convert_datetime_to_isoformat(data)
193
203
 
194
- with open(self.config_path, "w", encoding="utf-8") as f:
195
- json.dump(data, f, indent=2, ensure_ascii=False)
204
+ json_content = json.dumps(data, indent=2, ensure_ascii=False)
205
+ async with aiofiles.open(self.config_path, "w", encoding="utf-8") as f:
206
+ await f.write(json_content)
196
207
 
197
208
  logger.debug("Configuration saved to %s", self.config_path)
198
209
  self._config = config
@@ -201,14 +212,16 @@ class ConfigManager:
201
212
  logger.error("Failed to save configuration to %s: %s", self.config_path, e)
202
213
  raise
203
214
 
204
- def update_provider(self, provider: ProviderType | str, **kwargs: Any) -> None:
215
+ async def update_provider(
216
+ self, provider: ProviderType | str, **kwargs: Any
217
+ ) -> None:
205
218
  """Update provider configuration.
206
219
 
207
220
  Args:
208
221
  provider: Provider to update
209
222
  **kwargs: Configuration fields to update (only api_key supported)
210
223
  """
211
- config = self.load()
224
+ config = await self.load()
212
225
 
213
226
  # Get provider config and check if it's shotgun
214
227
  provider_config, is_shotgun = self._get_provider_config_and_type(
@@ -253,11 +266,11 @@ class ConfigManager:
253
266
  # This prevents the welcome screen from showing again after user has made their choice
254
267
  config.shown_welcome_screen = True
255
268
 
256
- self.save(config)
269
+ await self.save(config)
257
270
 
258
- def clear_provider_key(self, provider: ProviderType | str) -> None:
271
+ async def clear_provider_key(self, provider: ProviderType | str) -> None:
259
272
  """Remove the API key for the given provider (LLM provider or shotgun)."""
260
- config = self.load()
273
+ config = await self.load()
261
274
 
262
275
  # Get provider config (shotgun or LLM provider)
263
276
  provider_config, is_shotgun = self._get_provider_config_and_type(
@@ -270,34 +283,34 @@ class ConfigManager:
270
283
  if is_shotgun and isinstance(provider_config, ShotgunAccountConfig):
271
284
  provider_config.supabase_jwt = None
272
285
 
273
- self.save(config)
286
+ await self.save(config)
274
287
 
275
- def update_selected_model(self, model_name: "ModelName") -> None:
288
+ async def update_selected_model(self, model_name: "ModelName") -> None:
276
289
  """Update the selected model.
277
290
 
278
291
  Args:
279
292
  model_name: Model to select
280
293
  """
281
- config = self.load()
294
+ config = await self.load()
282
295
  config.selected_model = model_name
283
- self.save(config)
296
+ await self.save(config)
284
297
 
285
- def has_provider_key(self, provider: ProviderType | str) -> bool:
298
+ async def has_provider_key(self, provider: ProviderType | str) -> bool:
286
299
  """Check if the given provider has a non-empty API key configured.
287
300
 
288
301
  This checks only the configuration file.
289
302
  """
290
303
  # Use force_reload=False to avoid infinite loop when called from load()
291
- config = self.load(force_reload=False)
304
+ config = await self.load(force_reload=False)
292
305
  provider_enum = self._ensure_provider_enum(provider)
293
306
  provider_config = self._get_provider_config(config, provider_enum)
294
307
 
295
308
  return self._provider_has_api_key(provider_config)
296
309
 
297
- def has_any_provider_key(self) -> bool:
310
+ async def has_any_provider_key(self) -> bool:
298
311
  """Determine whether any provider has a configured API key."""
299
312
  # Use force_reload=False to avoid infinite loop when called from load()
300
- config = self.load(force_reload=False)
313
+ config = await self.load(force_reload=False)
301
314
  # Check LLM provider keys (BYOK)
302
315
  has_llm_key = any(
303
316
  self._provider_has_api_key(self._get_provider_config(config, provider))
@@ -311,7 +324,7 @@ class ConfigManager:
311
324
  has_shotgun_key = self._provider_has_api_key(config.shotgun)
312
325
  return has_llm_key or has_shotgun_key
313
326
 
314
- def initialize(self) -> ShotgunConfig:
327
+ async def initialize(self) -> ShotgunConfig:
315
328
  """Initialize configuration with defaults and save to file.
316
329
 
317
330
  Returns:
@@ -321,7 +334,7 @@ class ConfigManager:
321
334
  config = ShotgunConfig(
322
335
  shotgun_instance_id=str(uuid.uuid4()),
323
336
  )
324
- self.save(config)
337
+ await self.save(config)
325
338
  logger.info(
326
339
  "Configuration initialized at %s with shotgun_instance_id: %s",
327
340
  self.config_path,
@@ -377,6 +390,24 @@ class ConfigManager:
377
390
  SUPABASE_JWT_FIELD
378
391
  ].get_secret_value()
379
392
 
393
+ def _convert_datetime_to_isoformat(self, data: dict[str, Any]) -> None:
394
+ """Convert datetime objects in data to ISO8601 format strings for JSON serialization."""
395
+ from datetime import datetime
396
+
397
+ def convert_dict(d: dict[str, Any]) -> None:
398
+ """Recursively convert datetime objects in a dict."""
399
+ for key, value in d.items():
400
+ if isinstance(value, datetime):
401
+ d[key] = value.isoformat()
402
+ elif isinstance(value, dict):
403
+ convert_dict(value)
404
+ elif isinstance(value, list):
405
+ for item in value:
406
+ if isinstance(item, dict):
407
+ convert_dict(item)
408
+
409
+ convert_dict(data)
410
+
380
411
  def _ensure_provider_enum(self, provider: ProviderType | str) -> ProviderType:
381
412
  """Normalize provider values to ProviderType enum."""
382
413
  return (
@@ -440,16 +471,16 @@ class ConfigManager:
440
471
  provider_enum = self._ensure_provider_enum(provider)
441
472
  return (self._get_provider_config(config, provider_enum), False)
442
473
 
443
- def get_shotgun_instance_id(self) -> str:
474
+ async def get_shotgun_instance_id(self) -> str:
444
475
  """Get the shotgun instance ID from configuration.
445
476
 
446
477
  Returns:
447
478
  The unique shotgun instance ID string
448
479
  """
449
- config = self.load()
480
+ config = await self.load()
450
481
  return config.shotgun_instance_id
451
482
 
452
- def update_shotgun_account(
483
+ async def update_shotgun_account(
453
484
  self, api_key: str | None = None, supabase_jwt: str | None = None
454
485
  ) -> None:
455
486
  """Update Shotgun Account configuration.
@@ -458,7 +489,7 @@ class ConfigManager:
458
489
  api_key: LiteLLM proxy API key (optional)
459
490
  supabase_jwt: Supabase authentication JWT (optional)
460
491
  """
461
- config = self.load()
492
+ config = await self.load()
462
493
 
463
494
  if api_key is not None:
464
495
  config.shotgun.api_key = SecretStr(api_key) if api_key else None
@@ -468,7 +499,7 @@ class ConfigManager:
468
499
  SecretStr(supabase_jwt) if supabase_jwt else None
469
500
  )
470
501
 
471
- self.save(config)
502
+ await self.save(config)
472
503
  logger.info("Updated Shotgun Account configuration")
473
504
 
474
505
 
@@ -1,5 +1,6 @@
1
1
  """Pydantic models for configuration."""
2
2
 
3
+ from datetime import datetime
3
4
  from enum import StrEnum
4
5
 
5
6
  from pydantic import BaseModel, Field, PrivateAttr, SecretStr
@@ -170,6 +171,21 @@ class ShotgunAccountConfig(BaseModel):
170
171
  )
171
172
 
172
173
 
174
+ class MarketingMessageRecord(BaseModel):
175
+ """Record of when a marketing message was shown to the user."""
176
+
177
+ shown_at: datetime = Field(description="Timestamp when the message was shown")
178
+
179
+
180
+ class MarketingConfig(BaseModel):
181
+ """Configuration for marketing messages shown to users."""
182
+
183
+ messages: dict[str, MarketingMessageRecord] = Field(
184
+ default_factory=dict,
185
+ description="Tracking which marketing messages have been shown. Key is message ID (e.g., 'github_star_v1')",
186
+ )
187
+
188
+
173
189
  class ShotgunConfig(BaseModel):
174
190
  """Main configuration for Shotgun CLI."""
175
191
 
@@ -184,8 +200,16 @@ class ShotgunConfig(BaseModel):
184
200
  shotgun_instance_id: str = Field(
185
201
  description="Unique shotgun instance identifier (also used for anonymous telemetry)",
186
202
  )
187
- config_version: int = Field(default=3, description="Configuration schema version")
203
+ config_version: int = Field(default=4, description="Configuration schema version")
188
204
  shown_welcome_screen: bool = Field(
189
205
  default=False,
190
206
  description="Whether the welcome screen has been shown to the user",
191
207
  )
208
+ shown_onboarding_popup: datetime | None = Field(
209
+ default=None,
210
+ description="Timestamp when the onboarding popup was shown to the user (ISO8601 format)",
211
+ )
212
+ marketing: MarketingConfig = Field(
213
+ default_factory=MarketingConfig,
214
+ description="Marketing messages configuration and tracking",
215
+ )
@@ -170,7 +170,7 @@ def get_or_create_model(
170
170
  return _model_cache[cache_key]
171
171
 
172
172
 
173
- def get_provider_model(
173
+ async def get_provider_model(
174
174
  provider_or_model: ProviderType | ModelName | None = None,
175
175
  ) -> ModelConfig:
176
176
  """Get a fully configured ModelConfig with API key and Model instance.
@@ -189,7 +189,7 @@ def get_provider_model(
189
189
  """
190
190
  config_manager = get_config_manager()
191
191
  # Use cached config for read-only access (performance)
192
- config = config_manager.load(force_reload=False)
192
+ config = await config_manager.load(force_reload=False)
193
193
 
194
194
  # Priority 1: Check if Shotgun key exists - if so, use it for ANY model
195
195
  shotgun_api_key = _get_api_key(config.shotgun.api_key)