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.
- api/__init__.py +17 -0
- api/admin_config.py +1303 -0
- api/admin_routes.py +287 -0
- api/admin_static/admin.css +459 -0
- api/admin_static/admin.js +497 -0
- api/admin_static/index.html +77 -0
- api/admin_urls.py +34 -0
- api/app.py +194 -0
- api/command_utils.py +164 -0
- api/dependencies.py +144 -0
- api/detection.py +152 -0
- api/gateway_model_ids.py +54 -0
- api/model_catalog.py +133 -0
- api/model_router.py +125 -0
- api/models/__init__.py +45 -0
- api/models/anthropic.py +234 -0
- api/models/openai_responses.py +28 -0
- api/models/responses.py +60 -0
- api/optimization_handlers.py +154 -0
- api/request_pipeline.py +424 -0
- api/routes.py +156 -0
- api/runtime.py +334 -0
- api/validation_log.py +48 -0
- api/web_server_tools.py +22 -0
- api/web_tools/__init__.py +17 -0
- api/web_tools/constants.py +15 -0
- api/web_tools/egress.py +99 -0
- api/web_tools/outbound.py +278 -0
- api/web_tools/parsers.py +104 -0
- api/web_tools/request.py +87 -0
- api/web_tools/streaming.py +206 -0
- cli/__init__.py +5 -0
- cli/claude_env.py +12 -0
- cli/entrypoints.py +166 -0
- cli/env.example +209 -0
- cli/launchers/__init__.py +1 -0
- cli/launchers/claude.py +84 -0
- cli/launchers/codex.py +204 -0
- cli/launchers/codex_model_catalog.py +186 -0
- cli/launchers/common.py +93 -0
- cli/managed/__init__.py +6 -0
- cli/managed/claude.py +215 -0
- cli/managed/manager.py +157 -0
- cli/managed/session.py +260 -0
- cli/process_registry.py +78 -0
- config/__init__.py +5 -0
- config/constants.py +13 -0
- config/logging_config.py +159 -0
- config/nim.py +118 -0
- config/paths.py +91 -0
- config/provider_catalog.py +259 -0
- config/provider_ids.py +7 -0
- config/settings.py +538 -0
- core/__init__.py +1 -0
- core/anthropic/__init__.py +46 -0
- core/anthropic/content.py +31 -0
- core/anthropic/conversion.py +587 -0
- core/anthropic/emitted_sse_tracker.py +346 -0
- core/anthropic/errors.py +70 -0
- core/anthropic/native_messages_request.py +280 -0
- core/anthropic/native_sse_block_policy.py +313 -0
- core/anthropic/provider_stream_error.py +34 -0
- core/anthropic/server_tool_sse.py +14 -0
- core/anthropic/sse.py +440 -0
- core/anthropic/stream_contracts.py +205 -0
- core/anthropic/stream_recovery.py +346 -0
- core/anthropic/stream_recovery_session.py +133 -0
- core/anthropic/thinking.py +140 -0
- core/anthropic/tokens.py +117 -0
- core/anthropic/tools.py +212 -0
- core/anthropic/utils.py +9 -0
- core/openai_responses/__init__.py +5 -0
- core/openai_responses/adapter.py +31 -0
- core/openai_responses/anthropic_sse.py +59 -0
- core/openai_responses/errors.py +22 -0
- core/openai_responses/events.py +19 -0
- core/openai_responses/ids.py +21 -0
- core/openai_responses/input.py +258 -0
- core/openai_responses/items.py +37 -0
- core/openai_responses/reasoning.py +52 -0
- core/openai_responses/stream.py +25 -0
- core/openai_responses/stream_state.py +654 -0
- core/openai_responses/tools.py +374 -0
- core/openai_responses/usage.py +37 -0
- core/rate_limit.py +60 -0
- core/trace.py +216 -0
- devcopilot-0.2.0.dist-info/METADATA +687 -0
- devcopilot-0.2.0.dist-info/RECORD +189 -0
- devcopilot-0.2.0.dist-info/WHEEL +4 -0
- devcopilot-0.2.0.dist-info/entry_points.txt +6 -0
- devcopilot-0.2.0.dist-info/licenses/LICENSE +21 -0
- messaging/__init__.py +26 -0
- messaging/cli_event_constants.py +67 -0
- messaging/command_context.py +66 -0
- messaging/command_dispatcher.py +37 -0
- messaging/commands.py +275 -0
- messaging/event_parser.py +181 -0
- messaging/limiter.py +300 -0
- messaging/models.py +36 -0
- messaging/node_event_pipeline.py +127 -0
- messaging/node_runner.py +342 -0
- messaging/platforms/__init__.py +15 -0
- messaging/platforms/base.py +228 -0
- messaging/platforms/discord.py +567 -0
- messaging/platforms/factory.py +103 -0
- messaging/platforms/outbox.py +144 -0
- messaging/platforms/telegram.py +688 -0
- messaging/platforms/voice_flow.py +295 -0
- messaging/rendering/__init__.py +3 -0
- messaging/rendering/discord_markdown.py +318 -0
- messaging/rendering/markdown_tables.py +49 -0
- messaging/rendering/profiles.py +55 -0
- messaging/rendering/telegram_markdown.py +327 -0
- messaging/safe_diagnostics.py +17 -0
- messaging/session.py +334 -0
- messaging/transcript.py +581 -0
- messaging/transcription.py +164 -0
- messaging/trees/__init__.py +15 -0
- messaging/trees/data.py +482 -0
- messaging/trees/manager.py +433 -0
- messaging/trees/processor.py +179 -0
- messaging/trees/repository.py +177 -0
- messaging/turn_intake.py +235 -0
- messaging/ui_updates.py +101 -0
- messaging/voice.py +76 -0
- messaging/workflow.py +200 -0
- providers/__init__.py +31 -0
- providers/base.py +152 -0
- providers/cerebras/__init__.py +7 -0
- providers/cerebras/client.py +31 -0
- providers/cerebras/request.py +55 -0
- providers/codestral/__init__.py +7 -0
- providers/codestral/client.py +34 -0
- providers/deepseek/__init__.py +11 -0
- providers/deepseek/client.py +51 -0
- providers/deepseek/request.py +475 -0
- providers/defaults.py +41 -0
- providers/error_mapping.py +309 -0
- providers/exceptions.py +113 -0
- providers/fireworks/__init__.py +5 -0
- providers/fireworks/client.py +45 -0
- providers/fireworks/request.py +48 -0
- providers/gemini/__init__.py +7 -0
- providers/gemini/client.py +49 -0
- providers/gemini/request.py +199 -0
- providers/groq/__init__.py +7 -0
- providers/groq/client.py +31 -0
- providers/groq/request.py +83 -0
- providers/kimi/__init__.py +10 -0
- providers/kimi/client.py +53 -0
- providers/kimi/request.py +42 -0
- providers/llamacpp/__init__.py +3 -0
- providers/llamacpp/client.py +16 -0
- providers/lmstudio/__init__.py +5 -0
- providers/lmstudio/client.py +16 -0
- providers/mistral/__init__.py +7 -0
- providers/mistral/client.py +31 -0
- providers/mistral/request.py +37 -0
- providers/model_listing.py +133 -0
- providers/nvidia_nim/__init__.py +7 -0
- providers/nvidia_nim/client.py +91 -0
- providers/nvidia_nim/request.py +430 -0
- providers/nvidia_nim/voice.py +95 -0
- providers/ollama/__init__.py +7 -0
- providers/ollama/client.py +39 -0
- providers/open_router/__init__.py +7 -0
- providers/open_router/client.py +124 -0
- providers/open_router/request.py +42 -0
- providers/opencode/__init__.py +11 -0
- providers/opencode/client.py +31 -0
- providers/opencode/request.py +35 -0
- providers/rate_limit.py +300 -0
- providers/registry.py +527 -0
- providers/transports/__init__.py +1 -0
- providers/transports/anthropic_messages/__init__.py +5 -0
- providers/transports/anthropic_messages/http.py +118 -0
- providers/transports/anthropic_messages/recovery.py +206 -0
- providers/transports/anthropic_messages/stream.py +295 -0
- providers/transports/anthropic_messages/transport.py +236 -0
- providers/transports/openai_chat/__init__.py +5 -0
- providers/transports/openai_chat/recovery.py +217 -0
- providers/transports/openai_chat/stream.py +384 -0
- providers/transports/openai_chat/tool_calls.py +293 -0
- providers/transports/openai_chat/transport.py +156 -0
- providers/wafer/__init__.py +10 -0
- providers/wafer/client.py +50 -0
- providers/zai/__init__.py +10 -0
- providers/zai/client.py +46 -0
- providers/zai/request.py +42 -0
messaging/limiter.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Global Rate Limiter for Messaging Platforms.
|
|
3
|
+
|
|
4
|
+
Centralizes outgoing message requests and ensures compliance with rate limits
|
|
5
|
+
using a strict sliding window algorithm and a task queue.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
from collections import deque
|
|
10
|
+
from collections.abc import Awaitable, Callable
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from loguru import logger
|
|
14
|
+
|
|
15
|
+
from config.settings import get_settings
|
|
16
|
+
from core.rate_limit import StrictSlidingWindowLimiter as SlidingWindowLimiter
|
|
17
|
+
|
|
18
|
+
from .safe_diagnostics import format_exception_for_log
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class MessagingRateLimiter:
|
|
22
|
+
"""
|
|
23
|
+
A thread-safe global rate limiter for messaging.
|
|
24
|
+
|
|
25
|
+
Uses a custom queue with task compaction (deduplication) to ensure
|
|
26
|
+
only the latest version of a message update is processed.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
_instance: MessagingRateLimiter | None = None
|
|
30
|
+
_lock = asyncio.Lock()
|
|
31
|
+
|
|
32
|
+
def __new__(cls, *args, **kwargs):
|
|
33
|
+
return super().__new__(cls)
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
async def get_instance(
|
|
37
|
+
cls,
|
|
38
|
+
*,
|
|
39
|
+
rate_limit: int = 1,
|
|
40
|
+
rate_window: float = 1.0,
|
|
41
|
+
) -> MessagingRateLimiter:
|
|
42
|
+
"""Get the singleton instance of the limiter.
|
|
43
|
+
|
|
44
|
+
``rate_limit`` and ``rate_window`` apply only when the singleton is first
|
|
45
|
+
created. Call :meth:`shutdown_instance` before changing parameters.
|
|
46
|
+
"""
|
|
47
|
+
async with cls._lock:
|
|
48
|
+
if cls._instance is None:
|
|
49
|
+
cls._instance = cls(rate_limit=rate_limit, rate_window=rate_window)
|
|
50
|
+
# Start the background worker (tracked for graceful shutdown).
|
|
51
|
+
cls._instance._start_worker()
|
|
52
|
+
return cls._instance
|
|
53
|
+
|
|
54
|
+
def __init__(self, *, rate_limit: int, rate_window: float) -> None:
|
|
55
|
+
# Prevent double initialization in singleton
|
|
56
|
+
if hasattr(self, "_initialized"):
|
|
57
|
+
return
|
|
58
|
+
|
|
59
|
+
self.limiter = SlidingWindowLimiter(rate_limit, rate_window)
|
|
60
|
+
# Custom queue state - using deque for O(1) popleft
|
|
61
|
+
self._queue_list: deque[str] = deque() # Deque of dedup_keys in order
|
|
62
|
+
self._queue_map: dict[
|
|
63
|
+
str, tuple[Callable[[], Awaitable[Any]], list[asyncio.Future]]
|
|
64
|
+
] = {}
|
|
65
|
+
self._condition = asyncio.Condition()
|
|
66
|
+
self._shutdown = asyncio.Event()
|
|
67
|
+
self._worker_task: asyncio.Task | None = None
|
|
68
|
+
|
|
69
|
+
self._initialized = True
|
|
70
|
+
self._paused_until = 0
|
|
71
|
+
|
|
72
|
+
logger.info(
|
|
73
|
+
f"MessagingRateLimiter initialized ({rate_limit} req / {rate_window}s with Task Compaction)"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
def _start_worker(self) -> None:
|
|
77
|
+
"""Ensure the worker task exists."""
|
|
78
|
+
if self._worker_task and not self._worker_task.done():
|
|
79
|
+
return
|
|
80
|
+
# Named task helps debugging shutdown hangs.
|
|
81
|
+
self._worker_task = asyncio.create_task(
|
|
82
|
+
self._worker(), name="msg-limiter-worker"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
async def _worker(self):
|
|
86
|
+
"""Background worker that processes queued messaging tasks."""
|
|
87
|
+
logger.info("MessagingRateLimiter worker started")
|
|
88
|
+
while not self._shutdown.is_set():
|
|
89
|
+
try:
|
|
90
|
+
# Get a task from the queue
|
|
91
|
+
async with self._condition:
|
|
92
|
+
while not self._queue_list and not self._shutdown.is_set():
|
|
93
|
+
await self._condition.wait()
|
|
94
|
+
|
|
95
|
+
if self._shutdown.is_set():
|
|
96
|
+
break
|
|
97
|
+
|
|
98
|
+
dedup_key = self._queue_list.popleft()
|
|
99
|
+
func, futures = self._queue_map.pop(dedup_key)
|
|
100
|
+
|
|
101
|
+
# Check for manual pause (FloodWait)
|
|
102
|
+
now = asyncio.get_event_loop().time()
|
|
103
|
+
if self._paused_until > now:
|
|
104
|
+
wait_time = self._paused_until - now
|
|
105
|
+
logger.warning(
|
|
106
|
+
f"Limiter worker paused, waiting {wait_time:.1f}s more..."
|
|
107
|
+
)
|
|
108
|
+
await asyncio.sleep(wait_time)
|
|
109
|
+
|
|
110
|
+
# Wait for rate limit capacity
|
|
111
|
+
async with self.limiter:
|
|
112
|
+
try:
|
|
113
|
+
result = await func()
|
|
114
|
+
for f in futures:
|
|
115
|
+
if not f.done():
|
|
116
|
+
f.set_result(result)
|
|
117
|
+
except Exception as e:
|
|
118
|
+
# Report error to all futures and log it
|
|
119
|
+
for f in futures:
|
|
120
|
+
if not f.done():
|
|
121
|
+
f.set_exception(e)
|
|
122
|
+
|
|
123
|
+
error_msg = str(e).lower()
|
|
124
|
+
if "flood" in error_msg or "wait" in error_msg:
|
|
125
|
+
seconds = 30
|
|
126
|
+
try:
|
|
127
|
+
if hasattr(e, "seconds"):
|
|
128
|
+
seconds = e.seconds
|
|
129
|
+
elif "after " in error_msg:
|
|
130
|
+
# Try to parse "retry after X"
|
|
131
|
+
parts = error_msg.split("after ")
|
|
132
|
+
if len(parts) > 1:
|
|
133
|
+
seconds = int(parts[1].split()[0])
|
|
134
|
+
except Exception:
|
|
135
|
+
pass
|
|
136
|
+
|
|
137
|
+
logger.error(
|
|
138
|
+
f"FloodWait detected! Pausing worker for {seconds}s"
|
|
139
|
+
)
|
|
140
|
+
wait_secs = (
|
|
141
|
+
float(seconds)
|
|
142
|
+
if isinstance(seconds, (int, float, str))
|
|
143
|
+
else 30.0
|
|
144
|
+
)
|
|
145
|
+
self._paused_until = (
|
|
146
|
+
asyncio.get_event_loop().time() + wait_secs
|
|
147
|
+
)
|
|
148
|
+
else:
|
|
149
|
+
d = get_settings().log_messaging_error_details
|
|
150
|
+
logger.error(
|
|
151
|
+
"Error in limiter worker for key {}: {}",
|
|
152
|
+
dedup_key,
|
|
153
|
+
format_exception_for_log(e, log_full_message=d),
|
|
154
|
+
)
|
|
155
|
+
except asyncio.CancelledError:
|
|
156
|
+
break
|
|
157
|
+
except Exception as e:
|
|
158
|
+
d = get_settings().log_messaging_error_details
|
|
159
|
+
if d:
|
|
160
|
+
logger.error(
|
|
161
|
+
"MessagingRateLimiter worker critical error: {}",
|
|
162
|
+
e,
|
|
163
|
+
exc_info=True,
|
|
164
|
+
)
|
|
165
|
+
else:
|
|
166
|
+
logger.error(
|
|
167
|
+
"MessagingRateLimiter worker critical error: exc_type={}",
|
|
168
|
+
type(e).__name__,
|
|
169
|
+
)
|
|
170
|
+
await asyncio.sleep(1)
|
|
171
|
+
|
|
172
|
+
async def shutdown(self, timeout: float = 2.0) -> None:
|
|
173
|
+
"""Stop the background worker so process shutdown doesn't hang."""
|
|
174
|
+
self._shutdown.set()
|
|
175
|
+
try:
|
|
176
|
+
async with self._condition:
|
|
177
|
+
self._condition.notify_all()
|
|
178
|
+
except Exception:
|
|
179
|
+
# Best-effort: condition may be bound to a closing loop.
|
|
180
|
+
pass
|
|
181
|
+
|
|
182
|
+
task = self._worker_task
|
|
183
|
+
if not task or task.done():
|
|
184
|
+
self._worker_task = None
|
|
185
|
+
return
|
|
186
|
+
|
|
187
|
+
task.cancel()
|
|
188
|
+
try:
|
|
189
|
+
await asyncio.wait_for(task, timeout=timeout)
|
|
190
|
+
except TimeoutError:
|
|
191
|
+
logger.warning("MessagingRateLimiter worker did not stop before timeout")
|
|
192
|
+
except asyncio.CancelledError:
|
|
193
|
+
pass
|
|
194
|
+
except Exception as e:
|
|
195
|
+
d = get_settings().log_messaging_error_details
|
|
196
|
+
logger.debug(
|
|
197
|
+
"MessagingRateLimiter worker shutdown error: {}",
|
|
198
|
+
format_exception_for_log(e, log_full_message=d),
|
|
199
|
+
)
|
|
200
|
+
finally:
|
|
201
|
+
self._worker_task = None
|
|
202
|
+
|
|
203
|
+
@classmethod
|
|
204
|
+
async def shutdown_instance(cls, timeout: float = 2.0) -> None:
|
|
205
|
+
"""Shutdown and clear the singleton instance (safe to call multiple times)."""
|
|
206
|
+
inst = cls._instance
|
|
207
|
+
if not inst:
|
|
208
|
+
return
|
|
209
|
+
try:
|
|
210
|
+
await inst.shutdown(timeout=timeout)
|
|
211
|
+
finally:
|
|
212
|
+
cls._instance = None
|
|
213
|
+
|
|
214
|
+
async def _enqueue_internal(self, func, future, dedup_key, front=False):
|
|
215
|
+
await self._enqueue_internal_multi(func, [future], dedup_key, front)
|
|
216
|
+
|
|
217
|
+
async def _enqueue_internal_multi(self, func, futures, dedup_key, front=False):
|
|
218
|
+
async with self._condition:
|
|
219
|
+
if dedup_key in self._queue_map:
|
|
220
|
+
# Compaction: Update existing task with new func, append new futures
|
|
221
|
+
_old_func, old_futures = self._queue_map[dedup_key]
|
|
222
|
+
old_futures.extend(futures)
|
|
223
|
+
self._queue_map[dedup_key] = (func, old_futures)
|
|
224
|
+
logger.debug(
|
|
225
|
+
f"Compacted task for key: {dedup_key} (now {len(old_futures)} futures)"
|
|
226
|
+
)
|
|
227
|
+
else:
|
|
228
|
+
self._queue_map[dedup_key] = (func, futures)
|
|
229
|
+
if front:
|
|
230
|
+
self._queue_list.appendleft(dedup_key)
|
|
231
|
+
else:
|
|
232
|
+
self._queue_list.append(dedup_key)
|
|
233
|
+
self._condition.notify_all()
|
|
234
|
+
|
|
235
|
+
async def enqueue(
|
|
236
|
+
self, func: Callable[[], Awaitable[Any]], dedup_key: str | None = None
|
|
237
|
+
) -> Any:
|
|
238
|
+
"""
|
|
239
|
+
Enqueue a messaging task and return its future result.
|
|
240
|
+
If dedup_key is provided, subsequent tasks with the same key will replace this one.
|
|
241
|
+
"""
|
|
242
|
+
if dedup_key is None:
|
|
243
|
+
# Unique key to avoid deduplication
|
|
244
|
+
dedup_key = f"task_{id(func)}_{asyncio.get_event_loop().time()}"
|
|
245
|
+
|
|
246
|
+
future = asyncio.get_event_loop().create_future()
|
|
247
|
+
await self._enqueue_internal(func, future, dedup_key)
|
|
248
|
+
return await future
|
|
249
|
+
|
|
250
|
+
def fire_and_forget(
|
|
251
|
+
self, func: Callable[[], Awaitable[Any]], dedup_key: str | None = None
|
|
252
|
+
):
|
|
253
|
+
"""Enqueue a task without waiting for the result."""
|
|
254
|
+
if dedup_key is None:
|
|
255
|
+
dedup_key = f"task_{id(func)}_{asyncio.get_event_loop().time()}"
|
|
256
|
+
|
|
257
|
+
future = asyncio.get_event_loop().create_future()
|
|
258
|
+
|
|
259
|
+
async def _wrapped():
|
|
260
|
+
max_retries = 2
|
|
261
|
+
for attempt in range(max_retries + 1):
|
|
262
|
+
try:
|
|
263
|
+
return await self.enqueue(func, dedup_key)
|
|
264
|
+
except Exception as e:
|
|
265
|
+
error_msg = str(e).lower()
|
|
266
|
+
# Only retry transient connectivity issues that might have slipped through
|
|
267
|
+
# or occurred between platform checks.
|
|
268
|
+
if attempt < max_retries and any(
|
|
269
|
+
x in error_msg for x in ["connect", "timeout", "broken"]
|
|
270
|
+
):
|
|
271
|
+
wait = 2**attempt
|
|
272
|
+
d = get_settings().log_messaging_error_details
|
|
273
|
+
if d:
|
|
274
|
+
logger.warning(
|
|
275
|
+
"Limiter fire_and_forget transient error (attempt {}): {}. Retrying in {}s...",
|
|
276
|
+
attempt + 1,
|
|
277
|
+
e,
|
|
278
|
+
wait,
|
|
279
|
+
)
|
|
280
|
+
else:
|
|
281
|
+
logger.warning(
|
|
282
|
+
"Limiter fire_and_forget transient error (attempt {}): exc_type={}. Retrying in {}s...",
|
|
283
|
+
attempt + 1,
|
|
284
|
+
type(e).__name__,
|
|
285
|
+
wait,
|
|
286
|
+
)
|
|
287
|
+
await asyncio.sleep(wait)
|
|
288
|
+
continue
|
|
289
|
+
|
|
290
|
+
d = get_settings().log_messaging_error_details
|
|
291
|
+
logger.error(
|
|
292
|
+
"Final error in fire_and_forget for key {}: {}",
|
|
293
|
+
dedup_key,
|
|
294
|
+
format_exception_for_log(e, log_full_message=d),
|
|
295
|
+
)
|
|
296
|
+
if not future.done():
|
|
297
|
+
future.set_exception(e)
|
|
298
|
+
break
|
|
299
|
+
|
|
300
|
+
_ = asyncio.create_task(_wrapped())
|
messaging/models.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Platform-agnostic message models."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import UTC, datetime
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass
|
|
9
|
+
class IncomingMessage:
|
|
10
|
+
"""
|
|
11
|
+
Platform-agnostic incoming message.
|
|
12
|
+
|
|
13
|
+
Adapters convert platform-specific events to this format.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
text: str
|
|
17
|
+
chat_id: str
|
|
18
|
+
user_id: str
|
|
19
|
+
message_id: str
|
|
20
|
+
platform: str # "telegram", "discord", "slack", etc.
|
|
21
|
+
|
|
22
|
+
# Optional fields
|
|
23
|
+
reply_to_message_id: str | None = None
|
|
24
|
+
# Forum topic ID (Telegram); required when replying in forum supergroups
|
|
25
|
+
message_thread_id: str | None = None
|
|
26
|
+
username: str | None = None
|
|
27
|
+
# Pre-sent status message ID (e.g. "Transcribing voice note..."); handler edits in place
|
|
28
|
+
status_message_id: str | None = None
|
|
29
|
+
timestamp: datetime = field(default_factory=lambda: datetime.now(UTC))
|
|
30
|
+
|
|
31
|
+
# Platform-specific raw event for edge cases
|
|
32
|
+
raw_event: Any = None
|
|
33
|
+
|
|
34
|
+
def is_reply(self) -> bool:
|
|
35
|
+
"""Check if this message is a reply to another message."""
|
|
36
|
+
return self.reply_to_message_id is not None
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""CLI event handling for a single queued node (transcript + session + errors)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from loguru import logger
|
|
9
|
+
|
|
10
|
+
from core.trace import trace_event
|
|
11
|
+
|
|
12
|
+
from .cli_event_constants import TRANSCRIPT_EVENT_TYPES, get_status_for_event
|
|
13
|
+
from .platforms.base import ManagedClaudeSessionManagerProtocol
|
|
14
|
+
from .safe_diagnostics import text_len_hint
|
|
15
|
+
from .session import SessionStore
|
|
16
|
+
from .transcript import TranscriptBuffer
|
|
17
|
+
from .trees import MessageState, MessageTree
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def handle_session_info_event(
|
|
21
|
+
event_data: dict[str, Any],
|
|
22
|
+
tree: MessageTree | None,
|
|
23
|
+
node_id: str,
|
|
24
|
+
captured_session_id: str | None,
|
|
25
|
+
temp_session_id: str | None,
|
|
26
|
+
*,
|
|
27
|
+
cli_manager: ManagedClaudeSessionManagerProtocol,
|
|
28
|
+
session_store: SessionStore,
|
|
29
|
+
) -> tuple[str | None, str | None]:
|
|
30
|
+
"""Handle session_info event; return updated (captured_session_id, temp_session_id)."""
|
|
31
|
+
if event_data.get("type") != "session_info":
|
|
32
|
+
return captured_session_id, temp_session_id
|
|
33
|
+
|
|
34
|
+
real_session_id = event_data.get("session_id")
|
|
35
|
+
if not real_session_id or not temp_session_id:
|
|
36
|
+
return captured_session_id, temp_session_id
|
|
37
|
+
|
|
38
|
+
await cli_manager.register_real_session_id(temp_session_id, real_session_id)
|
|
39
|
+
trace_event(
|
|
40
|
+
stage="claude_cli",
|
|
41
|
+
event="claude_cli.session.registered",
|
|
42
|
+
source="claude_cli",
|
|
43
|
+
node_id=node_id,
|
|
44
|
+
temp_session_id=temp_session_id,
|
|
45
|
+
real_session_id=real_session_id,
|
|
46
|
+
tree_root_id=tree.root_id if tree else None,
|
|
47
|
+
)
|
|
48
|
+
if tree and real_session_id:
|
|
49
|
+
await tree.update_state(
|
|
50
|
+
node_id,
|
|
51
|
+
MessageState.IN_PROGRESS,
|
|
52
|
+
session_id=real_session_id,
|
|
53
|
+
)
|
|
54
|
+
session_store.save_tree(tree.root_id, tree.to_dict())
|
|
55
|
+
|
|
56
|
+
return real_session_id, None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
async def process_parsed_cli_event(
|
|
60
|
+
parsed: dict[str, Any],
|
|
61
|
+
transcript: TranscriptBuffer,
|
|
62
|
+
update_ui: Callable[..., Awaitable[None]],
|
|
63
|
+
last_status: str | None,
|
|
64
|
+
had_transcript_events: bool,
|
|
65
|
+
tree: MessageTree | None,
|
|
66
|
+
node_id: str,
|
|
67
|
+
captured_session_id: str | None,
|
|
68
|
+
*,
|
|
69
|
+
session_store: SessionStore,
|
|
70
|
+
format_status: Callable[..., str],
|
|
71
|
+
propagate_error_to_children: Callable[[str, str, str], Awaitable[None]],
|
|
72
|
+
log_messaging_error_details: bool = False,
|
|
73
|
+
) -> tuple[str | None, bool]:
|
|
74
|
+
"""Process a single parsed CLI event. Returns (last_status, had_transcript_events)."""
|
|
75
|
+
ptype = parsed.get("type") or ""
|
|
76
|
+
|
|
77
|
+
if ptype in TRANSCRIPT_EVENT_TYPES:
|
|
78
|
+
transcript.apply(parsed)
|
|
79
|
+
had_transcript_events = True
|
|
80
|
+
|
|
81
|
+
status = get_status_for_event(ptype, parsed, format_status)
|
|
82
|
+
if status is not None:
|
|
83
|
+
await update_ui(status)
|
|
84
|
+
last_status = status
|
|
85
|
+
elif ptype == "block_stop":
|
|
86
|
+
await update_ui(last_status, force=True)
|
|
87
|
+
elif ptype == "complete":
|
|
88
|
+
if not had_transcript_events:
|
|
89
|
+
transcript.apply({"type": "text_chunk", "text": "Done."})
|
|
90
|
+
trace_event(
|
|
91
|
+
stage="claude_cli",
|
|
92
|
+
event="turn.completed",
|
|
93
|
+
source="cli_event",
|
|
94
|
+
node_id=node_id,
|
|
95
|
+
claude_session_id=captured_session_id,
|
|
96
|
+
)
|
|
97
|
+
await update_ui(format_status("✅", "Complete"), force=True)
|
|
98
|
+
if tree and captured_session_id:
|
|
99
|
+
await tree.update_state(
|
|
100
|
+
node_id,
|
|
101
|
+
MessageState.COMPLETED,
|
|
102
|
+
session_id=captured_session_id,
|
|
103
|
+
)
|
|
104
|
+
session_store.save_tree(tree.root_id, tree.to_dict())
|
|
105
|
+
elif ptype == "error":
|
|
106
|
+
error_msg = parsed.get("message", "Unknown error")
|
|
107
|
+
em = error_msg if isinstance(error_msg, str) else str(error_msg)
|
|
108
|
+
trace_event(
|
|
109
|
+
stage="claude_cli",
|
|
110
|
+
event="turn.failed",
|
|
111
|
+
source="cli_event",
|
|
112
|
+
node_id=node_id,
|
|
113
|
+
claude_session_id=captured_session_id,
|
|
114
|
+
cli_error_message=em,
|
|
115
|
+
)
|
|
116
|
+
if log_messaging_error_details:
|
|
117
|
+
logger.error("HANDLER: Error event received: {}", error_msg)
|
|
118
|
+
else:
|
|
119
|
+
logger.error(
|
|
120
|
+
"HANDLER: Error event received: message_chars={}",
|
|
121
|
+
text_len_hint(em),
|
|
122
|
+
)
|
|
123
|
+
await update_ui(format_status("❌", "Error"), force=True)
|
|
124
|
+
if tree:
|
|
125
|
+
await propagate_error_to_children(node_id, error_msg, "Parent task failed")
|
|
126
|
+
|
|
127
|
+
return last_status, had_transcript_events
|