devcopilot 0.2.0__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 (189) hide show
  1. api/__init__.py +17 -0
  2. api/admin_config.py +1303 -0
  3. api/admin_routes.py +287 -0
  4. api/admin_static/admin.css +459 -0
  5. api/admin_static/admin.js +497 -0
  6. api/admin_static/index.html +77 -0
  7. api/admin_urls.py +34 -0
  8. api/app.py +194 -0
  9. api/command_utils.py +164 -0
  10. api/dependencies.py +144 -0
  11. api/detection.py +152 -0
  12. api/gateway_model_ids.py +54 -0
  13. api/model_catalog.py +133 -0
  14. api/model_router.py +125 -0
  15. api/models/__init__.py +45 -0
  16. api/models/anthropic.py +234 -0
  17. api/models/openai_responses.py +28 -0
  18. api/models/responses.py +60 -0
  19. api/optimization_handlers.py +154 -0
  20. api/request_pipeline.py +424 -0
  21. api/routes.py +156 -0
  22. api/runtime.py +334 -0
  23. api/validation_log.py +48 -0
  24. api/web_server_tools.py +22 -0
  25. api/web_tools/__init__.py +17 -0
  26. api/web_tools/constants.py +15 -0
  27. api/web_tools/egress.py +99 -0
  28. api/web_tools/outbound.py +278 -0
  29. api/web_tools/parsers.py +104 -0
  30. api/web_tools/request.py +87 -0
  31. api/web_tools/streaming.py +206 -0
  32. cli/__init__.py +5 -0
  33. cli/claude_env.py +12 -0
  34. cli/entrypoints.py +166 -0
  35. cli/env.example +209 -0
  36. cli/launchers/__init__.py +1 -0
  37. cli/launchers/claude.py +84 -0
  38. cli/launchers/codex.py +204 -0
  39. cli/launchers/codex_model_catalog.py +186 -0
  40. cli/launchers/common.py +93 -0
  41. cli/managed/__init__.py +6 -0
  42. cli/managed/claude.py +215 -0
  43. cli/managed/manager.py +157 -0
  44. cli/managed/session.py +260 -0
  45. cli/process_registry.py +78 -0
  46. config/__init__.py +5 -0
  47. config/constants.py +13 -0
  48. config/logging_config.py +159 -0
  49. config/nim.py +118 -0
  50. config/paths.py +91 -0
  51. config/provider_catalog.py +259 -0
  52. config/provider_ids.py +7 -0
  53. config/settings.py +538 -0
  54. core/__init__.py +1 -0
  55. core/anthropic/__init__.py +46 -0
  56. core/anthropic/content.py +31 -0
  57. core/anthropic/conversion.py +587 -0
  58. core/anthropic/emitted_sse_tracker.py +346 -0
  59. core/anthropic/errors.py +70 -0
  60. core/anthropic/native_messages_request.py +280 -0
  61. core/anthropic/native_sse_block_policy.py +313 -0
  62. core/anthropic/provider_stream_error.py +34 -0
  63. core/anthropic/server_tool_sse.py +14 -0
  64. core/anthropic/sse.py +440 -0
  65. core/anthropic/stream_contracts.py +205 -0
  66. core/anthropic/stream_recovery.py +346 -0
  67. core/anthropic/stream_recovery_session.py +133 -0
  68. core/anthropic/thinking.py +140 -0
  69. core/anthropic/tokens.py +117 -0
  70. core/anthropic/tools.py +212 -0
  71. core/anthropic/utils.py +9 -0
  72. core/openai_responses/__init__.py +5 -0
  73. core/openai_responses/adapter.py +31 -0
  74. core/openai_responses/anthropic_sse.py +59 -0
  75. core/openai_responses/errors.py +22 -0
  76. core/openai_responses/events.py +19 -0
  77. core/openai_responses/ids.py +21 -0
  78. core/openai_responses/input.py +258 -0
  79. core/openai_responses/items.py +37 -0
  80. core/openai_responses/reasoning.py +52 -0
  81. core/openai_responses/stream.py +25 -0
  82. core/openai_responses/stream_state.py +654 -0
  83. core/openai_responses/tools.py +374 -0
  84. core/openai_responses/usage.py +37 -0
  85. core/rate_limit.py +60 -0
  86. core/trace.py +216 -0
  87. devcopilot-0.2.0.dist-info/METADATA +687 -0
  88. devcopilot-0.2.0.dist-info/RECORD +189 -0
  89. devcopilot-0.2.0.dist-info/WHEEL +4 -0
  90. devcopilot-0.2.0.dist-info/entry_points.txt +6 -0
  91. devcopilot-0.2.0.dist-info/licenses/LICENSE +21 -0
  92. messaging/__init__.py +26 -0
  93. messaging/cli_event_constants.py +67 -0
  94. messaging/command_context.py +66 -0
  95. messaging/command_dispatcher.py +37 -0
  96. messaging/commands.py +275 -0
  97. messaging/event_parser.py +181 -0
  98. messaging/limiter.py +300 -0
  99. messaging/models.py +36 -0
  100. messaging/node_event_pipeline.py +127 -0
  101. messaging/node_runner.py +342 -0
  102. messaging/platforms/__init__.py +15 -0
  103. messaging/platforms/base.py +228 -0
  104. messaging/platforms/discord.py +567 -0
  105. messaging/platforms/factory.py +103 -0
  106. messaging/platforms/outbox.py +144 -0
  107. messaging/platforms/telegram.py +688 -0
  108. messaging/platforms/voice_flow.py +295 -0
  109. messaging/rendering/__init__.py +3 -0
  110. messaging/rendering/discord_markdown.py +318 -0
  111. messaging/rendering/markdown_tables.py +49 -0
  112. messaging/rendering/profiles.py +55 -0
  113. messaging/rendering/telegram_markdown.py +327 -0
  114. messaging/safe_diagnostics.py +17 -0
  115. messaging/session.py +334 -0
  116. messaging/transcript.py +581 -0
  117. messaging/transcription.py +164 -0
  118. messaging/trees/__init__.py +15 -0
  119. messaging/trees/data.py +482 -0
  120. messaging/trees/manager.py +433 -0
  121. messaging/trees/processor.py +179 -0
  122. messaging/trees/repository.py +177 -0
  123. messaging/turn_intake.py +235 -0
  124. messaging/ui_updates.py +101 -0
  125. messaging/voice.py +76 -0
  126. messaging/workflow.py +200 -0
  127. providers/__init__.py +31 -0
  128. providers/base.py +152 -0
  129. providers/cerebras/__init__.py +7 -0
  130. providers/cerebras/client.py +31 -0
  131. providers/cerebras/request.py +55 -0
  132. providers/codestral/__init__.py +7 -0
  133. providers/codestral/client.py +34 -0
  134. providers/deepseek/__init__.py +11 -0
  135. providers/deepseek/client.py +51 -0
  136. providers/deepseek/request.py +475 -0
  137. providers/defaults.py +41 -0
  138. providers/error_mapping.py +309 -0
  139. providers/exceptions.py +113 -0
  140. providers/fireworks/__init__.py +5 -0
  141. providers/fireworks/client.py +45 -0
  142. providers/fireworks/request.py +48 -0
  143. providers/gemini/__init__.py +7 -0
  144. providers/gemini/client.py +49 -0
  145. providers/gemini/request.py +199 -0
  146. providers/groq/__init__.py +7 -0
  147. providers/groq/client.py +31 -0
  148. providers/groq/request.py +83 -0
  149. providers/kimi/__init__.py +10 -0
  150. providers/kimi/client.py +53 -0
  151. providers/kimi/request.py +42 -0
  152. providers/llamacpp/__init__.py +3 -0
  153. providers/llamacpp/client.py +16 -0
  154. providers/lmstudio/__init__.py +5 -0
  155. providers/lmstudio/client.py +16 -0
  156. providers/mistral/__init__.py +7 -0
  157. providers/mistral/client.py +31 -0
  158. providers/mistral/request.py +37 -0
  159. providers/model_listing.py +133 -0
  160. providers/nvidia_nim/__init__.py +7 -0
  161. providers/nvidia_nim/client.py +91 -0
  162. providers/nvidia_nim/request.py +430 -0
  163. providers/nvidia_nim/voice.py +95 -0
  164. providers/ollama/__init__.py +7 -0
  165. providers/ollama/client.py +39 -0
  166. providers/open_router/__init__.py +7 -0
  167. providers/open_router/client.py +124 -0
  168. providers/open_router/request.py +42 -0
  169. providers/opencode/__init__.py +11 -0
  170. providers/opencode/client.py +31 -0
  171. providers/opencode/request.py +35 -0
  172. providers/rate_limit.py +300 -0
  173. providers/registry.py +527 -0
  174. providers/transports/__init__.py +1 -0
  175. providers/transports/anthropic_messages/__init__.py +5 -0
  176. providers/transports/anthropic_messages/http.py +118 -0
  177. providers/transports/anthropic_messages/recovery.py +206 -0
  178. providers/transports/anthropic_messages/stream.py +295 -0
  179. providers/transports/anthropic_messages/transport.py +236 -0
  180. providers/transports/openai_chat/__init__.py +5 -0
  181. providers/transports/openai_chat/recovery.py +217 -0
  182. providers/transports/openai_chat/stream.py +384 -0
  183. providers/transports/openai_chat/tool_calls.py +293 -0
  184. providers/transports/openai_chat/transport.py +156 -0
  185. providers/wafer/__init__.py +10 -0
  186. providers/wafer/client.py +50 -0
  187. providers/zai/__init__.py +10 -0
  188. providers/zai/client.py +46 -0
  189. providers/zai/request.py +42 -0
config/settings.py ADDED
@@ -0,0 +1,538 @@
1
+ """Centralized configuration using Pydantic Settings."""
2
+
3
+ import os
4
+ from collections.abc import Mapping
5
+ from dataclasses import dataclass
6
+ from functools import lru_cache
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from dotenv import dotenv_values
11
+ from pydantic import Field, field_validator, model_validator
12
+ from pydantic_settings import BaseSettings, SettingsConfigDict
13
+
14
+ from .constants import HTTP_CONNECT_TIMEOUT_DEFAULT
15
+ from .nim import NimSettings
16
+ from .paths import default_claude_workspace_path, managed_env_path
17
+ from .provider_ids import SUPPORTED_PROVIDER_IDS
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class ConfiguredChatModelRef:
22
+ """A unique configured chat model reference and the env keys that set it."""
23
+
24
+ model_ref: str
25
+ provider_id: str
26
+ model_id: str
27
+ sources: tuple[str, ...]
28
+
29
+
30
+ def _env_files() -> tuple[Path, ...]:
31
+ """Return env file paths in priority order (later overrides earlier)."""
32
+ files: list[Path] = [
33
+ Path(".env"),
34
+ managed_env_path(),
35
+ ]
36
+ if explicit := os.environ.get("FCC_ENV_FILE"):
37
+ files.append(Path(explicit))
38
+ return tuple(files)
39
+
40
+
41
+ def _configured_env_files(model_config: Mapping[str, Any]) -> tuple[Path, ...]:
42
+ """Return the currently configured env files for Settings."""
43
+ configured = model_config.get("env_file")
44
+ if configured is None:
45
+ return ()
46
+ if isinstance(configured, (str, Path)):
47
+ return (Path(configured),)
48
+ return tuple(Path(item) for item in configured)
49
+
50
+
51
+ def _env_file_value(path: Path, key: str) -> str | None:
52
+ """Return a dotenv value when the file explicitly defines the key."""
53
+ if not path.is_file():
54
+ return None
55
+
56
+ try:
57
+ values = dotenv_values(path)
58
+ except OSError:
59
+ return None
60
+
61
+ if key not in values:
62
+ return None
63
+ value = values[key]
64
+ return "" if value is None else value
65
+
66
+
67
+ def _env_file_override(model_config: Mapping[str, Any], key: str) -> str | None:
68
+ """Return the last configured dotenv value that explicitly defines a key."""
69
+ configured_value: str | None = None
70
+ for env_file in _configured_env_files(model_config):
71
+ value = _env_file_value(env_file, key)
72
+ if value is not None:
73
+ configured_value = value
74
+ return configured_value
75
+
76
+
77
+ class Settings(BaseSettings):
78
+ """Application settings loaded from environment variables."""
79
+
80
+ # ==================== OpenRouter Config ====================
81
+ open_router_api_key: str = Field(default="", validation_alias="OPENROUTER_API_KEY")
82
+
83
+ # ==================== Mistral La Plateforme ====================
84
+ mistral_api_key: str = Field(default="", validation_alias="MISTRAL_API_KEY")
85
+
86
+ # ==================== Mistral Codestral (codestral.mistral.ai) ====================
87
+ codestral_api_key: str = Field(default="", validation_alias="CODESTRAL_API_KEY")
88
+
89
+ # ==================== DeepSeek Config ====================
90
+ deepseek_api_key: str = Field(default="", validation_alias="DEEPSEEK_API_KEY")
91
+
92
+ # ==================== Kimi Config ====================
93
+ kimi_api_key: str = Field(default="", validation_alias="KIMI_API_KEY")
94
+
95
+ # ==================== Wafer Config ====================
96
+ wafer_api_key: str = Field(default="", validation_alias="WAFER_API_KEY")
97
+
98
+ # ==================== OpenCode Zen / OpenCode Go ====================
99
+ # Same key from opencode.ai/auth; zen uses prefix ``opencode/``, Go uses ``opencode_go/``.
100
+ opencode_api_key: str = Field(default="", validation_alias="OPENCODE_API_KEY")
101
+
102
+ # ==================== Z.ai Config ====================
103
+ zai_api_key: str = Field(default="", validation_alias="ZAI_API_KEY")
104
+
105
+ # ==================== Fireworks AI Config ====================
106
+ fireworks_api_key: str = Field(default="", validation_alias="FIREWORKS_API_KEY")
107
+
108
+ # ==================== Google Gemini (Google AI Studio) ====================
109
+ gemini_api_key: str = Field(default="", validation_alias="GEMINI_API_KEY")
110
+
111
+ # ==================== Groq (OpenAI-compatible) ====================
112
+ groq_api_key: str = Field(default="", validation_alias="GROQ_API_KEY")
113
+
114
+ # ==================== Cerebras Inference (OpenAI-compatible) ====================
115
+ cerebras_api_key: str = Field(default="", validation_alias="CEREBRAS_API_KEY")
116
+
117
+ # ==================== Messaging Platform Selection ====================
118
+ # Valid: "telegram" | "discord" | "none"
119
+ messaging_platform: str = Field(
120
+ default="discord", validation_alias="MESSAGING_PLATFORM"
121
+ )
122
+ messaging_rate_limit: int = Field(
123
+ default=1, validation_alias="MESSAGING_RATE_LIMIT"
124
+ )
125
+ messaging_rate_window: float = Field(
126
+ default=1.0, validation_alias="MESSAGING_RATE_WINDOW"
127
+ )
128
+
129
+ # ==================== NVIDIA NIM Config ====================
130
+ nvidia_nim_api_key: str = ""
131
+
132
+ # ==================== LM Studio Config ====================
133
+ lm_studio_base_url: str = Field(
134
+ default="http://localhost:1234/v1",
135
+ validation_alias="LM_STUDIO_BASE_URL",
136
+ )
137
+
138
+ # ==================== Llama.cpp Config ====================
139
+ llamacpp_base_url: str = Field(
140
+ default="http://localhost:8080/v1",
141
+ validation_alias="LLAMACPP_BASE_URL",
142
+ )
143
+
144
+ # ==================== Ollama Config ====================
145
+ ollama_base_url: str = Field(
146
+ default="http://localhost:11434",
147
+ validation_alias="OLLAMA_BASE_URL",
148
+ )
149
+
150
+ # ==================== Model ====================
151
+ # All Claude model requests are mapped to this single model (fallback)
152
+ # Format: provider_type/model/name
153
+ model: str = "nvidia_nim/nvidia/nemotron-3-super-120b-a12b"
154
+
155
+ # Per-model overrides (optional, falls back to MODEL)
156
+ # Each can use a different provider
157
+ model_opus: str | None = Field(default=None, validation_alias="MODEL_OPUS")
158
+ model_sonnet: str | None = Field(default=None, validation_alias="MODEL_SONNET")
159
+ model_haiku: str | None = Field(default=None, validation_alias="MODEL_HAIKU")
160
+
161
+ # ==================== Per-Provider Proxy ====================
162
+ nvidia_nim_proxy: str = Field(default="", validation_alias="NVIDIA_NIM_PROXY")
163
+ open_router_proxy: str = Field(default="", validation_alias="OPENROUTER_PROXY")
164
+ mistral_proxy: str = Field(default="", validation_alias="MISTRAL_PROXY")
165
+ codestral_proxy: str = Field(default="", validation_alias="CODESTRAL_PROXY")
166
+ lmstudio_proxy: str = Field(default="", validation_alias="LMSTUDIO_PROXY")
167
+ llamacpp_proxy: str = Field(default="", validation_alias="LLAMACPP_PROXY")
168
+ kimi_proxy: str = Field(default="", validation_alias="KIMI_PROXY")
169
+ wafer_proxy: str = Field(default="", validation_alias="WAFER_PROXY")
170
+ opencode_proxy: str = Field(default="", validation_alias="OPENCODE_PROXY")
171
+ opencode_go_proxy: str = Field(default="", validation_alias="OPENCODE_GO_PROXY")
172
+ zai_proxy: str = Field(default="", validation_alias="ZAI_PROXY")
173
+ fireworks_proxy: str = Field(default="", validation_alias="FIREWORKS_PROXY")
174
+ gemini_proxy: str = Field(default="", validation_alias="GEMINI_PROXY")
175
+ groq_proxy: str = Field(default="", validation_alias="GROQ_PROXY")
176
+ cerebras_proxy: str = Field(default="", validation_alias="CEREBRAS_PROXY")
177
+
178
+ # ==================== Provider Rate Limiting ====================
179
+ provider_rate_limit: int = Field(default=40, validation_alias="PROVIDER_RATE_LIMIT")
180
+ provider_rate_window: int = Field(
181
+ default=60, validation_alias="PROVIDER_RATE_WINDOW"
182
+ )
183
+ provider_max_concurrency: int = Field(
184
+ default=5, validation_alias="PROVIDER_MAX_CONCURRENCY"
185
+ )
186
+ enable_model_thinking: bool = Field(
187
+ default=True, validation_alias="ENABLE_MODEL_THINKING"
188
+ )
189
+ enable_opus_thinking: bool | None = Field(
190
+ default=None, validation_alias="ENABLE_OPUS_THINKING"
191
+ )
192
+ enable_sonnet_thinking: bool | None = Field(
193
+ default=None, validation_alias="ENABLE_SONNET_THINKING"
194
+ )
195
+ enable_haiku_thinking: bool | None = Field(
196
+ default=None, validation_alias="ENABLE_HAIKU_THINKING"
197
+ )
198
+
199
+ # ==================== HTTP Client Timeouts ====================
200
+ http_read_timeout: float = Field(
201
+ default=120.0, validation_alias="HTTP_READ_TIMEOUT"
202
+ )
203
+ http_write_timeout: float = Field(
204
+ default=10.0, validation_alias="HTTP_WRITE_TIMEOUT"
205
+ )
206
+ http_connect_timeout: float = Field(
207
+ default=HTTP_CONNECT_TIMEOUT_DEFAULT,
208
+ validation_alias="HTTP_CONNECT_TIMEOUT",
209
+ )
210
+
211
+ # ==================== Fast Prefix Detection ====================
212
+ fast_prefix_detection: bool = True
213
+
214
+ # ==================== Optimizations ====================
215
+ enable_network_probe_mock: bool = True
216
+ enable_title_generation_skip: bool = True
217
+ enable_suggestion_mode_skip: bool = True
218
+ enable_filepath_extraction_mock: bool = True
219
+
220
+ # ==================== Local web server tools (web_search / web_fetch) ====================
221
+ # Off by default: these tools perform outbound HTTP from the proxy (SSRF risk).
222
+ enable_web_server_tools: bool = Field(
223
+ default=False, validation_alias="ENABLE_WEB_SERVER_TOOLS"
224
+ )
225
+ # Comma-separated URL schemes allowed for web_fetch (default: http,https).
226
+ web_fetch_allowed_schemes: str = Field(
227
+ default="http,https", validation_alias="WEB_FETCH_ALLOWED_SCHEMES"
228
+ )
229
+ # When true, skip private/loopback/link-local IP blocking for web_fetch (lab only).
230
+ web_fetch_allow_private_networks: bool = Field(
231
+ default=False, validation_alias="WEB_FETCH_ALLOW_PRIVATE_NETWORKS"
232
+ )
233
+
234
+ # ==================== Debug / diagnostic logging (avoid sensitive content) ====================
235
+ # When false (default), API and SSE helpers log only metadata (counts, lengths, ids).
236
+ log_raw_api_payloads: bool = Field(
237
+ default=False, validation_alias="LOG_RAW_API_PAYLOADS"
238
+ )
239
+ log_raw_sse_events: bool = Field(
240
+ default=False, validation_alias="LOG_RAW_SSE_EVENTS"
241
+ )
242
+ # When false (default), unhandled exceptions log only type + route metadata (no message/traceback).
243
+ log_api_error_tracebacks: bool = Field(
244
+ default=False, validation_alias="LOG_API_ERROR_TRACEBACKS"
245
+ )
246
+ # When false (default), messaging logs omit text/transcription previews (metadata only).
247
+ log_raw_messaging_content: bool = Field(
248
+ default=False, validation_alias="LOG_RAW_MESSAGING_CONTENT"
249
+ )
250
+ # When true, log full Claude CLI stderr, non-JSON lines, and parser error text.
251
+ log_raw_cli_diagnostics: bool = Field(
252
+ default=False, validation_alias="LOG_RAW_CLI_DIAGNOSTICS"
253
+ )
254
+ # When true, log exception text / CLI error strings in messaging (may leak user content).
255
+ log_messaging_error_details: bool = Field(
256
+ default=False, validation_alias="LOG_MESSAGING_ERROR_DETAILS"
257
+ )
258
+ debug_platform_edits: bool = Field(
259
+ default=False, validation_alias="DEBUG_PLATFORM_EDITS"
260
+ )
261
+ debug_subagent_stack: bool = Field(
262
+ default=False, validation_alias="DEBUG_SUBAGENT_STACK"
263
+ )
264
+
265
+ # ==================== NIM Settings ====================
266
+ nim: NimSettings = Field(default_factory=NimSettings)
267
+
268
+ # ==================== Voice Note Transcription ====================
269
+ voice_note_enabled: bool = Field(
270
+ default=True, validation_alias="VOICE_NOTE_ENABLED"
271
+ )
272
+ # Device: "cpu" | "cuda" | "nvidia_nim"
273
+ # - "cpu"/"cuda": local Whisper (requires voice_local extra: uv sync --extra voice_local)
274
+ # - "nvidia_nim": NVIDIA NIM Whisper API (requires voice extra: uv sync --extra voice)
275
+ whisper_device: str = Field(default="cpu", validation_alias="WHISPER_DEVICE")
276
+ # Whisper model ID or short name (for local Whisper) or NVIDIA NIM model (for nvidia_nim)
277
+ # Local Whisper: "tiny", "base", "small", "medium", "large-v2", "large-v3", "large-v3-turbo"
278
+ # NVIDIA NIM: "nvidia/parakeet-ctc-1.1b-asr", "openai/whisper-large-v3", etc.
279
+ whisper_model: str = Field(default="base", validation_alias="WHISPER_MODEL")
280
+ # Hugging Face token for faster model downloads (optional, for local Whisper)
281
+ hf_token: str = Field(default="", validation_alias="HF_TOKEN")
282
+
283
+ # ==================== Bot Wrapper Config ====================
284
+ telegram_bot_token: str | None = None
285
+ allowed_telegram_user_id: str | None = None
286
+ discord_bot_token: str | None = Field(
287
+ default=None, validation_alias="DISCORD_BOT_TOKEN"
288
+ )
289
+ allowed_discord_channels: str | None = Field(
290
+ default=None, validation_alias="ALLOWED_DISCORD_CHANNELS"
291
+ )
292
+ allowed_dir: str = ""
293
+ max_message_log_entries_per_chat: int | None = Field(
294
+ default=None, validation_alias="MAX_MESSAGE_LOG_ENTRIES_PER_CHAT"
295
+ )
296
+
297
+ # ==================== Server ====================
298
+ host: str = "0.0.0.0"
299
+ port: int = 8082
300
+ # Optional server API key to protect endpoints (Anthropic-style)
301
+ # Set via env `ANTHROPIC_AUTH_TOKEN`. When empty, no auth is required.
302
+ anthropic_auth_token: str = Field(
303
+ default="", validation_alias="ANTHROPIC_AUTH_TOKEN"
304
+ )
305
+
306
+ # Handle empty strings for optional string fields
307
+ @field_validator(
308
+ "telegram_bot_token",
309
+ "allowed_telegram_user_id",
310
+ "discord_bot_token",
311
+ "allowed_discord_channels",
312
+ "model_opus",
313
+ "model_sonnet",
314
+ "model_haiku",
315
+ "enable_opus_thinking",
316
+ "enable_sonnet_thinking",
317
+ "enable_haiku_thinking",
318
+ mode="before",
319
+ )
320
+ @classmethod
321
+ def parse_optional_str(cls, v: Any) -> Any:
322
+ if v == "":
323
+ return None
324
+ return v
325
+
326
+ @field_validator("max_message_log_entries_per_chat", mode="before")
327
+ @classmethod
328
+ def parse_optional_log_cap(cls, v: Any) -> Any:
329
+ if v == "" or v is None:
330
+ return None
331
+ return v
332
+
333
+ @property
334
+ def claude_workspace(self) -> str:
335
+ """Return the fixed Claude data workspace path."""
336
+
337
+ return str(default_claude_workspace_path())
338
+
339
+ @property
340
+ def claude_cli_bin(self) -> str:
341
+ """Return the fixed Claude Code binary name."""
342
+
343
+ return "claude"
344
+
345
+ @property
346
+ def codex_cli_bin(self) -> str:
347
+ """Return the fixed Codex CLI binary name."""
348
+
349
+ return "codex"
350
+
351
+ @field_validator("whisper_device")
352
+ @classmethod
353
+ def validate_whisper_device(cls, v: str) -> str:
354
+ if v not in ("cpu", "cuda", "nvidia_nim"):
355
+ raise ValueError(
356
+ f"whisper_device must be 'cpu', 'cuda', or 'nvidia_nim', got {v!r}"
357
+ )
358
+ return v
359
+
360
+ @field_validator("messaging_platform")
361
+ @classmethod
362
+ def validate_messaging_platform(cls, v: str) -> str:
363
+ if v not in ("telegram", "discord", "none"):
364
+ raise ValueError(
365
+ f"messaging_platform must be 'telegram', 'discord', or 'none', got {v!r}"
366
+ )
367
+ return v
368
+
369
+ @field_validator("messaging_rate_limit")
370
+ @classmethod
371
+ def validate_messaging_rate_limit(cls, v: int) -> int:
372
+ if v <= 0:
373
+ raise ValueError("messaging_rate_limit must be > 0")
374
+ return v
375
+
376
+ @field_validator("messaging_rate_window")
377
+ @classmethod
378
+ def validate_messaging_rate_window(cls, v: float) -> float:
379
+ if v <= 0:
380
+ raise ValueError("messaging_rate_window must be > 0")
381
+ return float(v)
382
+
383
+ @field_validator("web_fetch_allowed_schemes")
384
+ @classmethod
385
+ def validate_web_fetch_allowed_schemes(cls, v: str) -> str:
386
+ schemes = [part.strip().lower() for part in v.split(",") if part.strip()]
387
+ if not schemes:
388
+ raise ValueError("web_fetch_allowed_schemes must list at least one scheme")
389
+ for scheme in schemes:
390
+ if not scheme.isascii() or not scheme.isalpha():
391
+ raise ValueError(
392
+ f"Invalid URL scheme in web_fetch_allowed_schemes: {scheme!r}"
393
+ )
394
+ return ",".join(schemes)
395
+
396
+ @field_validator("ollama_base_url")
397
+ @classmethod
398
+ def validate_ollama_base_url(cls, v: str) -> str:
399
+ if v.rstrip("/").endswith("/v1"):
400
+ raise ValueError(
401
+ "OLLAMA_BASE_URL must be the Ollama root URL for native Anthropic "
402
+ "messages, e.g. http://localhost:11434 (without /v1)."
403
+ )
404
+ return v
405
+
406
+ @field_validator("model", "model_opus", "model_sonnet", "model_haiku")
407
+ @classmethod
408
+ def validate_model_format(cls, v: str | None) -> str | None:
409
+ if v is None:
410
+ return None
411
+ if "/" not in v:
412
+ raise ValueError(
413
+ f"Model must be prefixed with provider type. "
414
+ f"Valid providers: {', '.join(SUPPORTED_PROVIDER_IDS)}. "
415
+ f"Format: provider_type/model/name"
416
+ )
417
+ provider = v.split("/", 1)[0]
418
+ if provider not in SUPPORTED_PROVIDER_IDS:
419
+ supported = ", ".join(f"'{p}'" for p in SUPPORTED_PROVIDER_IDS)
420
+ raise ValueError(f"Invalid provider: '{provider}'. Supported: {supported}")
421
+ return v
422
+
423
+ @model_validator(mode="after")
424
+ def check_nvidia_nim_api_key(self) -> Settings:
425
+ if (
426
+ self.voice_note_enabled
427
+ and self.whisper_device == "nvidia_nim"
428
+ and not self.nvidia_nim_api_key.strip()
429
+ ):
430
+ raise ValueError(
431
+ "NVIDIA_NIM_API_KEY is required when WHISPER_DEVICE is 'nvidia_nim'. "
432
+ "Set it in your .env file."
433
+ )
434
+ return self
435
+
436
+ @model_validator(mode="after")
437
+ def prefer_dotenv_anthropic_auth_token(self) -> Settings:
438
+ """Let explicit .env auth config override stale shell/client tokens."""
439
+ dotenv_value = _env_file_override(self.model_config, "ANTHROPIC_AUTH_TOKEN")
440
+ if dotenv_value is not None:
441
+ self.anthropic_auth_token = dotenv_value
442
+ return self
443
+
444
+ def uses_process_anthropic_auth_token(self) -> bool:
445
+ """Return whether proxy auth came from process env, not dotenv config."""
446
+ if _env_file_override(self.model_config, "ANTHROPIC_AUTH_TOKEN") is not None:
447
+ return False
448
+ return bool(os.environ.get("ANTHROPIC_AUTH_TOKEN"))
449
+
450
+ @property
451
+ def provider_type(self) -> str:
452
+ """Extract provider type from the default model string."""
453
+ return Settings.parse_provider_type(self.model)
454
+
455
+ @property
456
+ def model_name(self) -> str:
457
+ """Extract the actual model name from the default model string."""
458
+ return Settings.parse_model_name(self.model)
459
+
460
+ def resolve_model(self, claude_model_name: str) -> str:
461
+ """Resolve a Claude model name to the configured provider/model string.
462
+
463
+ Classifies the incoming Claude model (opus/sonnet/haiku) and
464
+ returns the model-specific override if configured, otherwise the fallback MODEL.
465
+ """
466
+ name_lower = claude_model_name.lower()
467
+ if "opus" in name_lower and self.model_opus is not None:
468
+ return self.model_opus
469
+ if "haiku" in name_lower and self.model_haiku is not None:
470
+ return self.model_haiku
471
+ if "sonnet" in name_lower and self.model_sonnet is not None:
472
+ return self.model_sonnet
473
+ return self.model
474
+
475
+ def configured_chat_model_refs(self) -> tuple[ConfiguredChatModelRef, ...]:
476
+ """Return unique configured chat provider/model refs with source env keys."""
477
+ candidates = (
478
+ ("MODEL", self.model),
479
+ ("MODEL_OPUS", self.model_opus),
480
+ ("MODEL_SONNET", self.model_sonnet),
481
+ ("MODEL_HAIKU", self.model_haiku),
482
+ )
483
+ sources_by_ref: dict[str, list[str]] = {}
484
+ for source, model_ref in candidates:
485
+ if model_ref is None:
486
+ continue
487
+ sources_by_ref.setdefault(model_ref, []).append(source)
488
+
489
+ return tuple(
490
+ ConfiguredChatModelRef(
491
+ model_ref=model_ref,
492
+ provider_id=Settings.parse_provider_type(model_ref),
493
+ model_id=Settings.parse_model_name(model_ref),
494
+ sources=tuple(sources),
495
+ )
496
+ for model_ref, sources in sources_by_ref.items()
497
+ )
498
+
499
+ def resolve_thinking(self, claude_model_name: str) -> bool:
500
+ """Resolve whether thinking is enabled for an incoming Claude model name."""
501
+ name_lower = claude_model_name.lower()
502
+ if "opus" in name_lower and self.enable_opus_thinking is not None:
503
+ return self.enable_opus_thinking
504
+ if "haiku" in name_lower and self.enable_haiku_thinking is not None:
505
+ return self.enable_haiku_thinking
506
+ if "sonnet" in name_lower and self.enable_sonnet_thinking is not None:
507
+ return self.enable_sonnet_thinking
508
+ return self.enable_model_thinking
509
+
510
+ def web_fetch_allowed_scheme_set(self) -> frozenset[str]:
511
+ """Return normalized schemes allowed for web_fetch."""
512
+ return frozenset(
513
+ part.strip().lower()
514
+ for part in self.web_fetch_allowed_schemes.split(",")
515
+ if part.strip()
516
+ )
517
+
518
+ @staticmethod
519
+ def parse_provider_type(model_string: str) -> str:
520
+ """Extract provider type from any 'provider/model' string."""
521
+ return model_string.split("/", 1)[0]
522
+
523
+ @staticmethod
524
+ def parse_model_name(model_string: str) -> str:
525
+ """Extract model name from any 'provider/model' string."""
526
+ return model_string.split("/", 1)[1]
527
+
528
+ model_config = SettingsConfigDict(
529
+ env_file=_env_files(),
530
+ env_file_encoding="utf-8",
531
+ extra="ignore",
532
+ )
533
+
534
+
535
+ @lru_cache
536
+ def get_settings() -> Settings:
537
+ """Get cached settings instance."""
538
+ return Settings()
core/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Neutral shared application core."""
@@ -0,0 +1,46 @@
1
+ """Anthropic protocol helpers shared across API, providers, and integrations."""
2
+
3
+ from .content import extract_text_from_content, get_block_attr, get_block_type
4
+ from .conversion import (
5
+ AnthropicToOpenAIConverter,
6
+ OpenAIConversionError,
7
+ ReasoningReplayMode,
8
+ build_base_request_body,
9
+ )
10
+ from .errors import (
11
+ append_request_id,
12
+ format_user_error_preview,
13
+ get_user_facing_error_message,
14
+ )
15
+ from .native_messages_request import sanitize_native_messages_thinking_policy
16
+ from .provider_stream_error import iter_provider_stream_error_sse_events
17
+ from .sse import ContentBlockManager, SSEBuilder, format_sse_event, map_stop_reason
18
+ from .thinking import ContentChunk, ContentType, ThinkTagParser
19
+ from .tokens import get_token_count
20
+ from .tools import HeuristicToolParser
21
+ from .utils import set_if_not_none
22
+
23
+ __all__ = [
24
+ "AnthropicToOpenAIConverter",
25
+ "ContentBlockManager",
26
+ "ContentChunk",
27
+ "ContentType",
28
+ "HeuristicToolParser",
29
+ "OpenAIConversionError",
30
+ "ReasoningReplayMode",
31
+ "SSEBuilder",
32
+ "ThinkTagParser",
33
+ "append_request_id",
34
+ "build_base_request_body",
35
+ "extract_text_from_content",
36
+ "format_sse_event",
37
+ "format_user_error_preview",
38
+ "get_block_attr",
39
+ "get_block_type",
40
+ "get_token_count",
41
+ "get_user_facing_error_message",
42
+ "iter_provider_stream_error_sse_events",
43
+ "map_stop_reason",
44
+ "sanitize_native_messages_thinking_policy",
45
+ "set_if_not_none",
46
+ ]
@@ -0,0 +1,31 @@
1
+ """Content block helpers for Anthropic-compatible payloads."""
2
+
3
+ from typing import Any
4
+
5
+
6
+ def get_block_attr(block: Any, attr: str, default: Any = None) -> Any:
7
+ """Get an attribute from a Pydantic model, lightweight object, or dict."""
8
+ if hasattr(block, attr):
9
+ return getattr(block, attr)
10
+ if isinstance(block, dict):
11
+ return block.get(attr, default)
12
+ return default
13
+
14
+
15
+ def get_block_type(block: Any) -> str | None:
16
+ """Return a content block type when present."""
17
+ return get_block_attr(block, "type")
18
+
19
+
20
+ def extract_text_from_content(content: Any) -> str:
21
+ """Extract concatenated text from message content."""
22
+ if isinstance(content, str):
23
+ return content
24
+ if isinstance(content, list):
25
+ parts: list[str] = []
26
+ for block in content:
27
+ text = get_block_attr(block, "text", "")
28
+ if isinstance(text, str) and text:
29
+ parts.append(text)
30
+ return "".join(parts)
31
+ return ""