shotgun-sh 0.2.3.dev2__py3-none-any.whl → 0.2.11.dev1__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 (107) hide show
  1. shotgun/agents/agent_manager.py +524 -58
  2. shotgun/agents/common.py +62 -62
  3. shotgun/agents/config/constants.py +0 -6
  4. shotgun/agents/config/manager.py +14 -3
  5. shotgun/agents/config/models.py +16 -0
  6. shotgun/agents/config/provider.py +68 -13
  7. shotgun/agents/context_analyzer/__init__.py +28 -0
  8. shotgun/agents/context_analyzer/analyzer.py +493 -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 +24 -2
  14. shotgun/agents/export.py +4 -5
  15. shotgun/agents/history/compaction.py +9 -4
  16. shotgun/agents/history/context_extraction.py +93 -6
  17. shotgun/agents/history/history_processors.py +14 -2
  18. shotgun/agents/history/token_counting/anthropic.py +32 -10
  19. shotgun/agents/models.py +50 -2
  20. shotgun/agents/plan.py +4 -5
  21. shotgun/agents/research.py +4 -5
  22. shotgun/agents/specify.py +4 -5
  23. shotgun/agents/tasks.py +4 -5
  24. shotgun/agents/tools/__init__.py +0 -2
  25. shotgun/agents/tools/codebase/codebase_shell.py +6 -0
  26. shotgun/agents/tools/codebase/directory_lister.py +6 -0
  27. shotgun/agents/tools/codebase/file_read.py +6 -0
  28. shotgun/agents/tools/codebase/query_graph.py +6 -0
  29. shotgun/agents/tools/codebase/retrieve_code.py +6 -0
  30. shotgun/agents/tools/file_management.py +71 -9
  31. shotgun/agents/tools/registry.py +217 -0
  32. shotgun/agents/tools/web_search/__init__.py +24 -12
  33. shotgun/agents/tools/web_search/anthropic.py +24 -3
  34. shotgun/agents/tools/web_search/gemini.py +22 -10
  35. shotgun/agents/tools/web_search/openai.py +21 -12
  36. shotgun/api_endpoints.py +7 -3
  37. shotgun/build_constants.py +1 -1
  38. shotgun/cli/clear.py +52 -0
  39. shotgun/cli/compact.py +186 -0
  40. shotgun/cli/context.py +111 -0
  41. shotgun/cli/models.py +1 -0
  42. shotgun/cli/update.py +16 -2
  43. shotgun/codebase/core/manager.py +10 -1
  44. shotgun/llm_proxy/__init__.py +5 -2
  45. shotgun/llm_proxy/clients.py +12 -7
  46. shotgun/logging_config.py +8 -10
  47. shotgun/main.py +70 -10
  48. shotgun/posthog_telemetry.py +9 -3
  49. shotgun/prompts/agents/export.j2 +18 -1
  50. shotgun/prompts/agents/partials/common_agent_system_prompt.j2 +5 -1
  51. shotgun/prompts/agents/partials/interactive_mode.j2 +24 -7
  52. shotgun/prompts/agents/plan.j2 +1 -1
  53. shotgun/prompts/agents/research.j2 +1 -1
  54. shotgun/prompts/agents/specify.j2 +270 -3
  55. shotgun/prompts/agents/state/system_state.j2 +4 -0
  56. shotgun/prompts/agents/tasks.j2 +1 -1
  57. shotgun/prompts/loader.py +2 -2
  58. shotgun/prompts/tools/web_search.j2 +14 -0
  59. shotgun/sentry_telemetry.py +4 -15
  60. shotgun/settings.py +238 -0
  61. shotgun/telemetry.py +15 -32
  62. shotgun/tui/app.py +203 -9
  63. shotgun/tui/commands/__init__.py +1 -1
  64. shotgun/tui/components/context_indicator.py +136 -0
  65. shotgun/tui/components/mode_indicator.py +70 -0
  66. shotgun/tui/components/status_bar.py +48 -0
  67. shotgun/tui/containers.py +93 -0
  68. shotgun/tui/dependencies.py +39 -0
  69. shotgun/tui/protocols.py +45 -0
  70. shotgun/tui/screens/chat/__init__.py +5 -0
  71. shotgun/tui/screens/chat/chat.tcss +54 -0
  72. shotgun/tui/screens/chat/chat_screen.py +1110 -0
  73. shotgun/tui/screens/chat/codebase_index_prompt_screen.py +64 -0
  74. shotgun/tui/screens/chat/codebase_index_selection.py +12 -0
  75. shotgun/tui/screens/chat/help_text.py +39 -0
  76. shotgun/tui/screens/chat/prompt_history.py +48 -0
  77. shotgun/tui/screens/chat.tcss +11 -0
  78. shotgun/tui/screens/chat_screen/command_providers.py +68 -2
  79. shotgun/tui/screens/chat_screen/history/__init__.py +22 -0
  80. shotgun/tui/screens/chat_screen/history/agent_response.py +66 -0
  81. shotgun/tui/screens/chat_screen/history/chat_history.py +116 -0
  82. shotgun/tui/screens/chat_screen/history/formatters.py +115 -0
  83. shotgun/tui/screens/chat_screen/history/partial_response.py +43 -0
  84. shotgun/tui/screens/chat_screen/history/user_question.py +42 -0
  85. shotgun/tui/screens/confirmation_dialog.py +151 -0
  86. shotgun/tui/screens/model_picker.py +30 -6
  87. shotgun/tui/screens/pipx_migration.py +153 -0
  88. shotgun/tui/screens/welcome.py +24 -5
  89. shotgun/tui/services/__init__.py +5 -0
  90. shotgun/tui/services/conversation_service.py +182 -0
  91. shotgun/tui/state/__init__.py +7 -0
  92. shotgun/tui/state/processing_state.py +185 -0
  93. shotgun/tui/widgets/__init__.py +5 -0
  94. shotgun/tui/widgets/widget_coordinator.py +247 -0
  95. shotgun/utils/datetime_utils.py +77 -0
  96. shotgun/utils/file_system_utils.py +3 -2
  97. shotgun/utils/update_checker.py +69 -14
  98. shotgun_sh-0.2.11.dev1.dist-info/METADATA +129 -0
  99. shotgun_sh-0.2.11.dev1.dist-info/RECORD +190 -0
  100. {shotgun_sh-0.2.3.dev2.dist-info → shotgun_sh-0.2.11.dev1.dist-info}/entry_points.txt +1 -0
  101. {shotgun_sh-0.2.3.dev2.dist-info → shotgun_sh-0.2.11.dev1.dist-info}/licenses/LICENSE +1 -1
  102. shotgun/agents/tools/user_interaction.py +0 -37
  103. shotgun/tui/screens/chat.py +0 -804
  104. shotgun/tui/screens/chat_screen/history.py +0 -352
  105. shotgun_sh-0.2.3.dev2.dist-info/METADATA +0 -467
  106. shotgun_sh-0.2.3.dev2.dist-info/RECORD +0 -154
  107. {shotgun_sh-0.2.3.dev2.dist-info → shotgun_sh-0.2.11.dev1.dist-info}/WHEEL +0 -0
@@ -0,0 +1,493 @@
1
+ """Core context analysis logic."""
2
+
3
+ import json
4
+ from collections.abc import Sequence
5
+
6
+ from pydantic_ai.messages import (
7
+ ModelMessage,
8
+ ModelRequest,
9
+ ModelResponse,
10
+ SystemPromptPart,
11
+ TextPart,
12
+ ToolCallPart,
13
+ ToolReturnPart,
14
+ UserPromptPart,
15
+ )
16
+
17
+ from shotgun.agents.config.models import ModelConfig
18
+ from shotgun.agents.history.token_counting.utils import count_tokens_from_messages
19
+ from shotgun.agents.history.token_estimation import estimate_tokens_from_messages
20
+ from shotgun.agents.messages import AgentSystemPrompt, SystemStatusPrompt
21
+ from shotgun.logging_config import get_logger
22
+ from shotgun.tui.screens.chat_screen.hint_message import HintMessage
23
+
24
+ from .constants import ToolCategory, get_tool_category
25
+ from .models import ContextAnalysis, MessageTypeStats, TokenAllocation
26
+
27
+ logger = get_logger(__name__)
28
+
29
+
30
+ class ContextAnalyzer:
31
+ """Analyzes conversation message history for context composition."""
32
+
33
+ def __init__(self, model_config: ModelConfig):
34
+ """Initialize the analyzer with model configuration for token counting.
35
+
36
+ Args:
37
+ model_config: Model configuration for accurate token counting
38
+ """
39
+ self.model_config = model_config
40
+
41
+ async def _allocate_tokens_from_usage(
42
+ self,
43
+ message_history: list[ModelMessage],
44
+ ) -> TokenAllocation:
45
+ """Allocate tokens from actual API usage data proportionally to parts.
46
+
47
+ This uses the ground truth token counts from ModelResponse.usage instead of
48
+ creating synthetic messages, which avoids inflating counts with message framing overhead.
49
+
50
+ IMPORTANT: usage.input_tokens is cumulative (includes all conversation history), so we:
51
+ 1. Use the LAST response's input_tokens as the ground truth total
52
+ 2. Calculate proportions based on content size across ALL requests
53
+ 3. Allocate the ground truth total proportionally
54
+
55
+ If usage data is missing or zero (e.g., after compaction), falls back to token estimation.
56
+
57
+ Args:
58
+ message_history: List of actual messages from conversation
59
+
60
+ Returns:
61
+ TokenAllocation with token counts by message/tool type
62
+ """
63
+ # Step 1: Find the last response's usage data (ground truth for input tokens)
64
+ last_input_tokens = 0
65
+ total_output_tokens = 0
66
+
67
+ for msg in reversed(message_history):
68
+ if isinstance(msg, ModelResponse) and msg.usage:
69
+ last_input_tokens = msg.usage.input_tokens + msg.usage.cache_read_tokens
70
+ logger.debug(
71
+ f"[ANALYZER] Found last response with usage - "
72
+ f"input_tokens={msg.usage.input_tokens}, "
73
+ f"cache_read_tokens={msg.usage.cache_read_tokens}, "
74
+ f"total={last_input_tokens}"
75
+ )
76
+ break
77
+
78
+ if last_input_tokens == 0:
79
+ logger.warning(
80
+ f"[ANALYZER] No usage data found in message history! "
81
+ f"message_count={len(message_history)}, "
82
+ f"response_count={sum(1 for m in message_history if isinstance(m, ModelResponse))}"
83
+ )
84
+ # Fallback to token estimation
85
+ logger.info("[ANALYZER] Falling back to token estimation")
86
+ last_input_tokens = await estimate_tokens_from_messages(
87
+ message_history, self.model_config
88
+ )
89
+ logger.debug(f"[ANALYZER] Estimated tokens: {last_input_tokens}")
90
+
91
+ # Step 2: Calculate total output tokens (sum across all responses)
92
+ for msg in message_history:
93
+ if isinstance(msg, ModelResponse) and msg.usage:
94
+ total_output_tokens += msg.usage.output_tokens
95
+
96
+ # Step 3: Calculate content size proportions for each part type across ALL requests
97
+ # Initialize size accumulators
98
+ user_size = 0
99
+ system_prompts_size = 0
100
+ system_status_size = 0
101
+ codebase_understanding_input_size = 0
102
+ artifact_management_input_size = 0
103
+ web_research_input_size = 0
104
+ unknown_input_size = 0
105
+
106
+ for msg in message_history:
107
+ if isinstance(msg, ModelRequest):
108
+ for part in msg.parts:
109
+ if isinstance(part, (SystemPromptPart, UserPromptPart)):
110
+ size = len(part.content)
111
+ elif isinstance(part, ToolReturnPart):
112
+ # ToolReturnPart.content can be Any type
113
+ try:
114
+ content_str = (
115
+ json.dumps(part.content)
116
+ if part.content is not None
117
+ else ""
118
+ )
119
+ except (TypeError, ValueError):
120
+ content_str = (
121
+ str(part.content) if part.content is not None else ""
122
+ )
123
+ size = len(content_str)
124
+ else:
125
+ size = 0
126
+
127
+ # Categorize by part type
128
+ # Note: Check subclasses first (AgentSystemPrompt, SystemStatusPrompt)
129
+ # before checking base class (SystemPromptPart)
130
+ if isinstance(part, SystemStatusPrompt):
131
+ system_status_size += size
132
+ elif isinstance(part, AgentSystemPrompt):
133
+ system_prompts_size += size
134
+ elif isinstance(part, SystemPromptPart):
135
+ # Generic system prompt (not AgentSystemPrompt or SystemStatusPrompt)
136
+ system_prompts_size += size
137
+ elif isinstance(part, UserPromptPart):
138
+ user_size += size
139
+ elif isinstance(part, ToolReturnPart):
140
+ # Categorize tool results by tool category
141
+ category = get_tool_category(part.tool_name)
142
+ if category == ToolCategory.CODEBASE_UNDERSTANDING:
143
+ codebase_understanding_input_size += size
144
+ elif category == ToolCategory.ARTIFACT_MANAGEMENT:
145
+ artifact_management_input_size += size
146
+ elif category == ToolCategory.WEB_RESEARCH:
147
+ web_research_input_size += size
148
+ elif category == ToolCategory.UNKNOWN:
149
+ unknown_input_size += size
150
+
151
+ # Step 4: Calculate output proportions by tool category
152
+ codebase_understanding_size = 0
153
+ artifact_management_size = 0
154
+ web_research_size = 0
155
+ unknown_size = 0
156
+ agent_response_size = 0
157
+
158
+ for msg in message_history:
159
+ if isinstance(msg, ModelResponse):
160
+ for part in msg.parts: # type: ignore[assignment]
161
+ if isinstance(part, ToolCallPart):
162
+ category = get_tool_category(part.tool_name)
163
+ size = len(str(part.args))
164
+
165
+ if category == ToolCategory.AGENT_RESPONSE:
166
+ agent_response_size += size
167
+ elif category == ToolCategory.CODEBASE_UNDERSTANDING:
168
+ codebase_understanding_size += size
169
+ elif category == ToolCategory.ARTIFACT_MANAGEMENT:
170
+ artifact_management_size += size
171
+ elif category == ToolCategory.WEB_RESEARCH:
172
+ web_research_size += size
173
+ elif category == ToolCategory.UNKNOWN:
174
+ unknown_size += size
175
+ elif isinstance(part, TextPart):
176
+ agent_response_size += len(part.content)
177
+
178
+ # Step 5: Allocate input tokens proportionally
179
+ # Initialize TokenAllocation fields
180
+ user_tokens = 0
181
+ agent_response_tokens = 0
182
+ system_prompt_tokens = 0
183
+ system_status_tokens = 0
184
+ codebase_understanding_tokens = 0
185
+ artifact_management_tokens = 0
186
+ web_research_tokens = 0
187
+ unknown_tokens = 0
188
+
189
+ total_input_size = (
190
+ user_size
191
+ + system_prompts_size
192
+ + system_status_size
193
+ + codebase_understanding_input_size
194
+ + artifact_management_input_size
195
+ + web_research_input_size
196
+ + unknown_input_size
197
+ )
198
+
199
+ if total_input_size > 0 and last_input_tokens > 0:
200
+ user_tokens = int(last_input_tokens * (user_size / total_input_size))
201
+ system_prompt_tokens = int(
202
+ last_input_tokens * (system_prompts_size / total_input_size)
203
+ )
204
+ system_status_tokens = int(
205
+ last_input_tokens * (system_status_size / total_input_size)
206
+ )
207
+ codebase_understanding_tokens = int(
208
+ last_input_tokens
209
+ * (codebase_understanding_input_size / total_input_size)
210
+ )
211
+ artifact_management_tokens = int(
212
+ last_input_tokens * (artifact_management_input_size / total_input_size)
213
+ )
214
+ web_research_tokens = int(
215
+ last_input_tokens * (web_research_input_size / total_input_size)
216
+ )
217
+ unknown_tokens = int(
218
+ last_input_tokens * (unknown_input_size / total_input_size)
219
+ )
220
+
221
+ # Step 6: Allocate output tokens proportionally
222
+ total_output_size = (
223
+ codebase_understanding_size
224
+ + artifact_management_size
225
+ + web_research_size
226
+ + unknown_size
227
+ + agent_response_size
228
+ )
229
+
230
+ if total_output_size > 0 and total_output_tokens > 0:
231
+ codebase_understanding_tokens += int(
232
+ total_output_tokens * (codebase_understanding_size / total_output_size)
233
+ )
234
+ artifact_management_tokens += int(
235
+ total_output_tokens * (artifact_management_size / total_output_size)
236
+ )
237
+ web_research_tokens += int(
238
+ total_output_tokens * (web_research_size / total_output_size)
239
+ )
240
+ unknown_tokens += int(
241
+ total_output_tokens * (unknown_size / total_output_size)
242
+ )
243
+ agent_response_tokens += int(
244
+ total_output_tokens * (agent_response_size / total_output_size)
245
+ )
246
+ elif total_output_tokens > 0:
247
+ # If no content, put all in agent responses
248
+ agent_response_tokens = total_output_tokens
249
+
250
+ logger.debug(
251
+ f"Token allocation complete: user={user_tokens}, agent_responses={agent_response_tokens}, "
252
+ f"system_prompts={system_prompt_tokens}, system_status={system_status_tokens}, "
253
+ f"codebase_understanding={codebase_understanding_tokens}, "
254
+ f"artifact_management={artifact_management_tokens}, web_research={web_research_tokens}, "
255
+ f"unknown={unknown_tokens}"
256
+ )
257
+ logger.debug(
258
+ f"Input tokens (from last response): {last_input_tokens}, Output tokens (sum): {total_output_tokens}"
259
+ )
260
+
261
+ # Create TokenAllocation model
262
+ return TokenAllocation(
263
+ user=user_tokens,
264
+ agent_responses=agent_response_tokens,
265
+ system_prompts=system_prompt_tokens,
266
+ system_status=system_status_tokens,
267
+ codebase_understanding=codebase_understanding_tokens,
268
+ artifact_management=artifact_management_tokens,
269
+ web_research=web_research_tokens,
270
+ unknown=unknown_tokens,
271
+ )
272
+
273
+ async def analyze_conversation(
274
+ self,
275
+ message_history: list[ModelMessage],
276
+ ui_message_history: list[ModelMessage | HintMessage],
277
+ ) -> ContextAnalysis:
278
+ """Analyze the conversation to determine message type composition.
279
+
280
+ Args:
281
+ message_history: The agent message history (for token counting)
282
+ ui_message_history: The UI message history (includes hints)
283
+
284
+ Returns:
285
+ ContextAnalysis with statistics for each message type
286
+ """
287
+ # Track counts for each message type
288
+ user_count = 0
289
+ agent_responses_count = 0
290
+ system_prompts_count = 0
291
+ system_status_count = 0
292
+ codebase_understanding_count = 0
293
+ artifact_management_count = 0
294
+ web_research_count = 0
295
+ unknown_count = 0
296
+
297
+ # Analyze message_history to count message types
298
+ for msg in message_history:
299
+ if isinstance(msg, ModelRequest):
300
+ # Track what types are in this message for counting
301
+ has_user_prompt = False
302
+ has_system_prompt = False
303
+ has_system_status = False
304
+
305
+ # Check what part types this message contains
306
+ for part in msg.parts:
307
+ if isinstance(part, AgentSystemPrompt):
308
+ has_system_prompt = True
309
+ elif isinstance(part, SystemStatusPrompt):
310
+ has_system_status = True
311
+ elif isinstance(part, SystemPromptPart):
312
+ # Generic system prompt
313
+ has_system_prompt = True
314
+ elif isinstance(part, UserPromptPart):
315
+ has_user_prompt = True
316
+ elif isinstance(part, ToolReturnPart):
317
+ # Categorize tool results by category
318
+ category = get_tool_category(part.tool_name)
319
+ if category == ToolCategory.CODEBASE_UNDERSTANDING:
320
+ codebase_understanding_count += 1
321
+ elif category == ToolCategory.ARTIFACT_MANAGEMENT:
322
+ artifact_management_count += 1
323
+ elif category == ToolCategory.WEB_RESEARCH:
324
+ web_research_count += 1
325
+ elif category == ToolCategory.UNKNOWN:
326
+ unknown_count += 1
327
+
328
+ # Count the message types (only count once per message)
329
+ if has_system_prompt:
330
+ system_prompts_count += 1
331
+ if has_system_status:
332
+ system_status_count += 1
333
+ if has_user_prompt:
334
+ user_count += 1
335
+
336
+ elif isinstance(msg, ModelResponse):
337
+ # Agent responses - count entire response as one
338
+ agent_responses_count += 1
339
+
340
+ # Check for tool calls in the response
341
+ for part in msg.parts: # type: ignore[assignment]
342
+ if isinstance(part, ToolCallPart):
343
+ category = get_tool_category(part.tool_name)
344
+ if category == ToolCategory.CODEBASE_UNDERSTANDING:
345
+ codebase_understanding_count += 1
346
+ elif category == ToolCategory.ARTIFACT_MANAGEMENT:
347
+ artifact_management_count += 1
348
+ elif category == ToolCategory.WEB_RESEARCH:
349
+ web_research_count += 1
350
+ elif category == ToolCategory.UNKNOWN:
351
+ unknown_count += 1
352
+
353
+ # Count hints from ui_message_history
354
+ hint_count = sum(
355
+ 1 for msg in ui_message_history if isinstance(msg, HintMessage)
356
+ )
357
+
358
+ # Use actual API usage data for accurate token counting (avoids synthetic message overhead)
359
+ usage_tokens = await self._allocate_tokens_from_usage(message_history)
360
+
361
+ user_tokens = usage_tokens.user
362
+ agent_response_tokens = usage_tokens.agent_responses
363
+ system_prompt_tokens = usage_tokens.system_prompts
364
+ system_status_tokens = usage_tokens.system_status
365
+ codebase_understanding_tokens = usage_tokens.codebase_understanding
366
+ artifact_management_tokens = usage_tokens.artifact_management
367
+ web_research_tokens = usage_tokens.web_research
368
+ unknown_tokens = usage_tokens.unknown
369
+
370
+ # Estimate hint tokens (rough estimate based on character count)
371
+ hint_tokens = 0
372
+ for msg in ui_message_history: # type: ignore[assignment]
373
+ if isinstance(msg, HintMessage):
374
+ # Rough estimate: ~4 chars per token
375
+ hint_tokens += len(msg.message) // 4
376
+
377
+ # Calculate agent context tokens (excluding UI-only hints)
378
+ agent_context_tokens = (
379
+ user_tokens
380
+ + agent_response_tokens
381
+ + system_prompt_tokens
382
+ + system_status_tokens
383
+ + codebase_understanding_tokens
384
+ + artifact_management_tokens
385
+ + web_research_tokens
386
+ + unknown_tokens
387
+ )
388
+
389
+ # Total tokens includes hints for display purposes, but agent_context_tokens does not
390
+ total_tokens = agent_context_tokens + hint_tokens
391
+ total_messages = (
392
+ user_count
393
+ + agent_responses_count
394
+ + system_prompts_count
395
+ + system_status_count
396
+ + codebase_understanding_count
397
+ + artifact_management_count
398
+ + web_research_count
399
+ + unknown_count
400
+ + hint_count
401
+ )
402
+
403
+ # Calculate usable context limit (80% of max_input_tokens) and free space
404
+ # This matches the TOKEN_LIMIT_RATIO = 0.8 from history/constants.py
405
+ max_usable_tokens = int(self.model_config.max_input_tokens * 0.8)
406
+ free_space_tokens = max_usable_tokens - agent_context_tokens
407
+
408
+ return ContextAnalysis(
409
+ user_messages=MessageTypeStats(count=user_count, tokens=user_tokens),
410
+ agent_responses=MessageTypeStats(
411
+ count=agent_responses_count, tokens=agent_response_tokens
412
+ ),
413
+ system_prompts=MessageTypeStats(
414
+ count=system_prompts_count, tokens=system_prompt_tokens
415
+ ),
416
+ system_status=MessageTypeStats(
417
+ count=system_status_count, tokens=system_status_tokens
418
+ ),
419
+ codebase_understanding=MessageTypeStats(
420
+ count=codebase_understanding_count,
421
+ tokens=codebase_understanding_tokens,
422
+ ),
423
+ artifact_management=MessageTypeStats(
424
+ count=artifact_management_count, tokens=artifact_management_tokens
425
+ ),
426
+ web_research=MessageTypeStats(
427
+ count=web_research_count, tokens=web_research_tokens
428
+ ),
429
+ unknown=MessageTypeStats(count=unknown_count, tokens=unknown_tokens),
430
+ hint_messages=MessageTypeStats(count=hint_count, tokens=hint_tokens),
431
+ total_tokens=total_tokens,
432
+ total_messages=total_messages,
433
+ context_window=self.model_config.max_input_tokens,
434
+ agent_context_tokens=agent_context_tokens,
435
+ model_name=self.model_config.name.value,
436
+ max_usable_tokens=max_usable_tokens,
437
+ free_space_tokens=free_space_tokens,
438
+ )
439
+
440
+ async def _count_tokens_for_parts(
441
+ self,
442
+ parts: Sequence[
443
+ UserPromptPart | SystemPromptPart | ToolReturnPart | ToolCallPart
444
+ ],
445
+ part_type: str,
446
+ ) -> int:
447
+ """Count tokens for a list of parts by creating synthetic single-part messages.
448
+
449
+ This avoids double-counting when a message contains multiple part types.
450
+
451
+ Args:
452
+ parts: List of parts to count tokens for
453
+ part_type: Type of parts ("user", "system", "tool_return", "tool_call")
454
+
455
+ Returns:
456
+ Total token count for all parts
457
+ """
458
+ if not parts:
459
+ return 0
460
+
461
+ # Create synthetic messages with single parts for accurate token counting
462
+ synthetic_messages: list[ModelMessage] = []
463
+
464
+ for part in parts:
465
+ if part_type in ("user", "system", "tool_return"):
466
+ # These are request parts - wrap in ModelRequest
467
+ synthetic_messages.append(ModelRequest(parts=[part])) # type: ignore[list-item]
468
+ elif part_type == "tool_call":
469
+ # Tool calls are in responses - wrap in ModelResponse
470
+ synthetic_messages.append(ModelResponse(parts=[part])) # type: ignore[list-item]
471
+
472
+ # Count tokens for the synthetic messages
473
+ return await self._count_tokens_safe(synthetic_messages)
474
+
475
+ async def _count_tokens_safe(self, messages: Sequence[ModelMessage]) -> int:
476
+ """Count tokens for a list of messages, returning 0 on error.
477
+
478
+ Args:
479
+ messages: List of messages to count tokens for
480
+
481
+ Returns:
482
+ Token count or 0 if counting fails
483
+ """
484
+ if not messages:
485
+ return 0
486
+
487
+ try:
488
+ return await count_tokens_from_messages(list(messages), self.model_config)
489
+ except Exception as e:
490
+ logger.warning(f"Failed to count tokens: {e}")
491
+ # Fallback to rough estimate
492
+ total_chars = sum(len(str(msg)) for msg in messages)
493
+ return total_chars // 4 # Rough estimate: 4 chars per token
@@ -0,0 +1,9 @@
1
+ """Tool category registry for context analysis.
2
+
3
+ This module re-exports the tool registry functionality for backward compatibility.
4
+ The actual implementation is in shotgun.agents.tools.registry.
5
+ """
6
+
7
+ from shotgun.agents.tools.registry import ToolCategory, get_tool_category
8
+
9
+ __all__ = ["ToolCategory", "get_tool_category"]
@@ -0,0 +1,115 @@
1
+ """Format context analysis for various output types."""
2
+
3
+ from typing import Any
4
+
5
+ from .models import ContextAnalysis
6
+
7
+
8
+ class ContextFormatter:
9
+ """Formats context analysis for various output types."""
10
+
11
+ @staticmethod
12
+ def format_markdown(analysis: ContextAnalysis) -> str:
13
+ """Format the analysis as markdown for display.
14
+
15
+ Args:
16
+ analysis: Context analysis to format
17
+
18
+ Returns:
19
+ Markdown-formatted string
20
+ """
21
+ lines = ["# Conversation Context Analysis", ""]
22
+
23
+ # Top-level summary with model and usage info
24
+ usage_percent = (
25
+ (analysis.agent_context_tokens / analysis.max_usable_tokens * 100)
26
+ if analysis.max_usable_tokens > 0
27
+ else 0
28
+ )
29
+ free_percent = (
30
+ (analysis.free_space_tokens / analysis.max_usable_tokens * 100)
31
+ if analysis.max_usable_tokens > 0
32
+ else 0
33
+ )
34
+
35
+ lines.extend(
36
+ [
37
+ f"Model: {analysis.model_name}",
38
+ "",
39
+ f"Total Context: {analysis.agent_context_tokens:,} / {analysis.max_usable_tokens:,} tokens ({usage_percent:.1f}%)",
40
+ "",
41
+ f"Free Space: {analysis.free_space_tokens:,} tokens ({free_percent:.1f}%)",
42
+ "",
43
+ "Autocompact Buffer: 500 tokens",
44
+ "",
45
+ ]
46
+ )
47
+
48
+ # Create 25-character visual bar showing proportional usage
49
+ # Each character represents 4% of total context
50
+ filled_chars = int(usage_percent / 4)
51
+ empty_chars = 25 - filled_chars
52
+ visual_bar = "●" * filled_chars + "○" * empty_chars
53
+
54
+ lines.extend(
55
+ [
56
+ "## Context Composition",
57
+ visual_bar,
58
+ "",
59
+ ]
60
+ )
61
+
62
+ # Add agent context categories only (hints are not part of agent context)
63
+ agent_categories = [
64
+ ("🧑 User Messages", analysis.user_messages),
65
+ ("🤖 Agent Responses", analysis.agent_responses),
66
+ ("📋 System Prompts", analysis.system_prompts),
67
+ ("📊 System Status", analysis.system_status),
68
+ ("🔍 Codebase Understanding", analysis.codebase_understanding),
69
+ ("📦 Artifact Management", analysis.artifact_management),
70
+ ("🌐 Web Research", analysis.web_research),
71
+ ]
72
+
73
+ # Only add unknown if it has content
74
+ if analysis.unknown.count > 0:
75
+ agent_categories.append(("⚠️ Unknown Tools", analysis.unknown))
76
+
77
+ for label, stats in agent_categories:
78
+ if stats.count > 0:
79
+ percentage = analysis.get_percentage(stats)
80
+ # Align labels to 30 characters for clean visual layout
81
+ lines.append(
82
+ f"{label:<30} {percentage:>5.1f}% ({stats.count} messages, ~{stats.tokens:,} tokens)"
83
+ )
84
+ # Add blank line to prevent Textual's Markdown widget from reflowing
85
+ lines.append("")
86
+
87
+ return "\n".join(lines)
88
+
89
+ @staticmethod
90
+ def format_json(analysis: ContextAnalysis) -> dict[str, Any]:
91
+ """Format the analysis as a JSON-serializable dictionary.
92
+
93
+ Args:
94
+ analysis: Context analysis to format
95
+
96
+ Returns:
97
+ Dictionary with context analysis data
98
+ """
99
+ # Use Pydantic's model_dump() to serialize the model
100
+ data = analysis.model_dump()
101
+
102
+ # Add computed summary field
103
+ data["summary"] = {
104
+ "total_messages": analysis.total_messages - analysis.hint_messages.count,
105
+ "agent_context_tokens": analysis.agent_context_tokens,
106
+ "context_window": analysis.context_window,
107
+ "usage_percentage": round(
108
+ (analysis.agent_context_tokens / analysis.context_window * 100)
109
+ if analysis.context_window > 0
110
+ else 0,
111
+ 1,
112
+ ),
113
+ }
114
+
115
+ return data