Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

fixed tool parser and added signal handlers

Alishahryar1bd1e097d74e3
diff --git a/api/app.py b/api/app.py
index 702b7f4d..9734d9e0 100644
--- a/api/app.py
+++ b/api/app.py
@@ -2,6 +2,7 @@
import asyncio
import os
+import signal
# Opt-in to future behavior for python-telegram-bot
os.environ["PTB_TIMEDELTA"] = "1"
@@ -16,6 +17,8 @@ from .dependencies import cleanup_provider
from providers.exceptions import ProviderError
from config.settings import get_settings
+from utils.signal_handlers import install_chained_signal_handlers
+
# Configure logging (atomic - only on true fresh start)
_settings = get_settings()
LOG_FILE = _settings.log_file
@@ -47,6 +50,9 @@ async def _best_effort(
"""Run a shutdown step with timeout; never raise to callers."""
try:
await asyncio.wait_for(awaitable, timeout=timeout_s)
+ except asyncio.CancelledError:
+ # Shutdown tasks may be cancelled; treat as a successful "best effort".
+ return
except asyncio.TimeoutError:
logger.warning(f"Shutdown step timed out: {name} ({timeout_s}s)")
except Exception as e:
@@ -64,6 +70,87 @@ async def lifespan(app: FastAPI):
message_handler = None
cli_manager = None
+ # Ctrl+C shutdown assist: chain SIGINT/SIGTERM to trigger early cleanup.
+ shutdown_event = asyncio.Event()
+ # Keep a plain counter because asyncio.Event state may lag behind
+ # call_soon_threadsafe when signals arrive back-to-back.
+ signal_count = {"n": 0}
+ loop = asyncio.get_running_loop()
+
+ def _on_signal(signum: int, _frame) -> None:
+ signal_count["n"] += 1
+ logger.warning(
+ f"Signal received: {signum} (count={signal_count['n']}); requesting shutdown"
+ )
+ # On Windows + uvicorn, shutdown can hang indefinitely when
+ # timeout_graceful_shutdown is None and there are stuck connections/tasks.
+ # A second signal should always force termination.
+ if signal_count["n"] >= 2:
+ logger.error("Second shutdown signal; forcing exit")
+ try:
+ from cli.process_registry import kill_all_best_effort
+
+ kill_all_best_effort()
+ finally:
+ os._exit(130)
+ try:
+ loop.call_soon_threadsafe(shutdown_event.set)
+ except Exception:
+ # Best-effort fallback; should still be safe if we're already on-loop.
+ shutdown_event.set()
+
+ signals = [signal.SIGINT, signal.SIGTERM]
+ if hasattr(signal, "SIGBREAK"):
+ # Windows Ctrl+Break.
+ signals.append(signal.SIGBREAK)
+
+ restore_signal_handlers = install_chained_signal_handlers(
+ signals=signals,
+ handler=_on_signal,
+ )
+ logger.info(f"Installed shutdown signal handlers: {[int(s) for s in signals]}")
+
+ async def _early_shutdown_worker() -> None:
+ await shutdown_event.wait()
+ logger.warning("Early shutdown: running best-effort cleanup steps")
+ try:
+ from cli.process_registry import kill_all_best_effort
+
+ kill_all_best_effort()
+ except Exception:
+ pass
+
+ # Try to stop the Telegram poller quickly; lifespan cleanup will also run.
+ mp = getattr(app.state, "messaging_platform", None)
+ cm = getattr(app.state, "cli_manager", None)
+ mh = getattr(app.state, "message_handler", None)
+ if mp:
+ await _best_effort(
+ "early.messaging_platform.stop", mp.stop(), timeout_s=2.0
+ )
+ if mh:
+ await _best_effort(
+ "early.message_handler.stop_all_tasks",
+ mh.stop_all_tasks(),
+ timeout_s=2.0,
+ )
+ if cm:
+ await _best_effort(
+ "early.cli_manager.stop_all", cm.stop_all(), timeout_s=2.0
+ )
+ try:
+ from messaging.limiter import MessagingRateLimiter
+
+ await _best_effort(
+ "early.MessagingRateLimiter.shutdown_instance",
+ MessagingRateLimiter.shutdown_instance(),
+ timeout_s=2.0,
+ )
+ except Exception:
+ pass
+
+ early_shutdown_task = asyncio.create_task(_early_shutdown_worker())
+
try:
# Use the messaging factory to create the right platform
from messaging.factory import create_messaging_platform
@@ -179,6 +266,17 @@ async def lifespan(app: FastAPI):
# Limiter may never have been imported/initialized.
pass
+ # Stop the early-shutdown worker and restore signal handlers.
+ try:
+ early_shutdown_task.cancel()
+ await _best_effort("early_shutdown_task", early_shutdown_task, timeout_s=1.0)
+ except Exception:
+ pass
+ try:
+ restore_signal_handlers()
+ except Exception:
+ pass
+
logger.info("Server shut down cleanly")
diff --git a/messaging/event_parser.py b/messaging/event_parser.py
index 3198d720..630928ba 100644
--- a/messaging/event_parser.py
+++ b/messaging/event_parser.py
@@ -68,7 +68,7 @@ def parse_cli_event(event: Any) -> List[Dict]:
results.append(
{
"type": "tool_use",
- "id": c.get("id", ""),
+ "id": str(c.get("id", "") or "").strip(),
"name": c.get("name", ""),
"input": c.get("input"),
}
@@ -77,7 +77,7 @@ def parse_cli_event(event: Any) -> List[Dict]:
results.append(
{
"type": "tool_result",
- "tool_use_id": c.get("tool_use_id", ""),
+ "tool_use_id": str(c.get("tool_use_id", "") or "").strip(),
"content": c.get("content"),
"is_error": bool(c.get("is_error", False)),
}
@@ -129,7 +129,7 @@ def parse_cli_event(event: Any) -> List[Dict]:
{
"type": "tool_use_start",
"index": event.get("index", -1),
- "id": block.get("id", ""),
+ "id": str(block.get("id", "") or "").strip(),
"name": block.get("name", ""),
"input": block.get("input"),
}
diff --git a/messaging/transcript.py b/messaging/transcript.py
index 3a8896c5..1a78ede7 100644
--- a/messaging/transcript.py
+++ b/messaging/transcript.py
@@ -9,10 +9,15 @@ the transcript grows over time and older content must be truncated.
from __future__ import annotations
import json
+import logging
+import os
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional
+logger = logging.getLogger(__name__)
+
+
def _safe_json_dumps(obj: Any) -> str:
try:
return json.dumps(obj, indent=2, ensure_ascii=False, sort_keys=True)
@@ -249,6 +254,7 @@ class TranscriptBuffer:
self._subagent_stack: List[str] = []
# Parallel stack of segments for rendering nested subagents.
self._subagent_segments: List[SubagentSegment] = []
+ self._debug_subagent_stack = os.getenv("DEBUG_SUBAGENT_STACK") == "1"
def _in_subagent(self) -> bool:
return bool(self._subagent_stack)
@@ -280,6 +286,13 @@ class TranscriptBuffer:
)
self._subagent_stack.append(tool_id)
self._subagent_segments.append(seg)
+ if self._debug_subagent_stack:
+ logger.debug(
+ "SUBAGENT_STACK: push id=%r depth=%d heading=%r",
+ tool_id,
+ len(self._subagent_stack),
+ getattr(seg, "description", None),
+ )
def _subagent_pop(self, tool_id: str) -> None:
tool_id = str(tool_id or "").strip()
@@ -296,16 +309,29 @@ class TranscriptBuffer:
except ValueError:
return
while len(self._subagent_stack) > idx:
- self._subagent_stack.pop()
+ popped = self._subagent_stack.pop()
if self._subagent_segments:
self._subagent_segments.pop()
+ if self._debug_subagent_stack:
+ logger.debug(
+ "SUBAGENT_STACK: pop id=%r depth=%d (matched=%r)",
+ popped,
+ len(self._subagent_stack),
+ tool_id,
+ )
return
# No id in result; only close if we have a synthetic top marker.
if self._subagent_stack and self._subagent_stack[-1].startswith("__task_"):
- self._subagent_stack.pop()
+ popped = self._subagent_stack.pop()
if self._subagent_segments:
self._subagent_segments.pop()
+ if self._debug_subagent_stack:
+ logger.debug(
+ "SUBAGENT_STACK: pop id=%r depth=%d (synthetic)",
+ popped,
+ len(self._subagent_stack),
+ )
def _ensure_thinking(self) -> ThinkingSegment:
seg = ThinkingSegment()
@@ -384,7 +410,7 @@ class TranscriptBuffer:
idx = int(ev.get("index", -1))
if idx >= 0:
self.apply({"type": "block_stop", "index": idx})
- tool_id = str(ev.get("id", "") or "")
+ tool_id = str(ev.get("id", "") or "").strip()
name = str(ev.get("name", "") or "tool")
if tool_id:
self._tool_name_by_id[tool_id] = name
@@ -447,7 +473,7 @@ class TranscriptBuffer:
return
if et == "tool_use":
- tool_id = str(ev.get("id", "") or "")
+ tool_id = str(ev.get("id", "") or "").strip()
name = str(ev.get("name", "") or "tool")
if tool_id:
self._tool_name_by_id[tool_id] = name
@@ -479,7 +505,7 @@ class TranscriptBuffer:
return
if et == "tool_result":
- tool_id = str(ev.get("tool_use_id", "") or "")
+ tool_id = str(ev.get("tool_use_id", "") or "").strip()
name = self._tool_name_by_id.get(tool_id)
# If this was the Task tool result, close subagent context.
diff --git a/server.py b/server.py
index 244e703c..1f0b17f7 100644
--- a/server.py
+++ b/server.py
@@ -2,7 +2,7 @@
Claude Code Proxy - Entry Point
Minimal entry point that imports the app from the api module.
-Run with: uv run uvicorn server:app --host 0.0.0.0 --port 8082
+Run with: uv run uvicorn server:app --host 0.0.0.0 --port 8082 --timeout-graceful-shutdown 5
"""
from api.app import app, create_app
@@ -16,7 +16,14 @@ if __name__ == "__main__":
settings = get_settings()
try:
- uvicorn.run(app, host=settings.host, port=settings.port, log_level="debug")
+ # Avoid hanging forever on Ctrl+C when there are stuck connections/tasks.
+ uvicorn.run(
+ app,
+ host=settings.host,
+ port=settings.port,
+ log_level="debug",
+ timeout_graceful_shutdown=5,
+ )
finally:
# Safety net for Ctrl+C cases where lifespan shutdown doesn't fully run.
kill_all_best_effort()
diff --git a/tests/test_signal_handlers.py b/tests/test_signal_handlers.py
new file mode 100644
index 00000000..d8b6c248
--- /dev/null
+++ b/tests/test_signal_handlers.py
@@ -0,0 +1,33 @@
+import signal
+
+from utils.signal_handlers import install_chained_signal_handlers
+
+
+def test_install_chained_signal_handlers_calls_prev_and_new_handler():
+ calls = []
+
+ def prev(signum, frame):
+ calls.append(("prev", signum))
+
+ old = signal.getsignal(signal.SIGINT)
+ signal.signal(signal.SIGINT, prev)
+
+ try:
+
+ def ours(signum, frame):
+ calls.append(("ours", signum))
+
+ restore = install_chained_signal_handlers(signals=[signal.SIGINT], handler=ours)
+
+ try:
+ h = signal.getsignal(signal.SIGINT)
+ assert callable(h)
+ # Call the installed handler directly (don't actually raise SIGINT).
+ h(signal.SIGINT, None) # type: ignore[misc]
+ finally:
+ restore()
+
+ finally:
+ signal.signal(signal.SIGINT, old)
+
+ assert calls == [("ours", signal.SIGINT), ("prev", signal.SIGINT)]
diff --git a/tests/test_transcript.py b/tests/test_transcript.py
index f1655c84..ff376b03 100644
--- a/tests/test_transcript.py
+++ b/tests/test_transcript.py
@@ -72,6 +72,40 @@ def test_transcript_subagent_suppresses_thinking_and_text_inside():
assert "after" in out
+def test_transcript_subagent_closes_on_whitespace_tool_ids():
+ t = TranscriptBuffer()
+
+ # Provider emitted a Task tool_use id with leading whitespace.
+ t.apply(
+ {
+ "type": "tool_use",
+ "id": " functions.Task:0",
+ "name": "Task",
+ "input": {"description": "Outer"},
+ }
+ )
+
+ # Task completes, but tool_result references a trimmed id (or vice versa).
+ t.apply(
+ {"type": "tool_result", "tool_use_id": "functions.Task:0", "content": "done"}
+ )
+
+ # Next Task should be top-level, not nested under the previous subagent.
+ t.apply(
+ {
+ "type": "tool_use",
+ "id": "functions.Task:1",
+ "name": "Task",
+ "input": {"description": "Next"},
+ }
+ )
+
+ out = t.render(_ctx(), limit_chars=3900, status=None)
+ assert out.count("Subagent:") == 2
+ # If nesting is incorrect, the second subagent line will be indented under the first.
+ assert "\n 🤖 *Subagent:* `Next`" not in out
+
+
def test_transcript_truncates_by_dropping_oldest_segments():
t = TranscriptBuffer()
diff --git a/utils/signal_handlers.py b/utils/signal_handlers.py
new file mode 100644
index 00000000..f9d9ac4c
--- /dev/null
+++ b/utils/signal_handlers.py
@@ -0,0 +1,57 @@
+"""Signal handler helpers.
+
+We run under asyncio + uvicorn on Windows. Ctrl+C (SIGINT) is normally handled by
+uvicorn, but some background tasks (Telegram polling, subprocesses) may keep the
+process alive longer than expected. These helpers let us *chain* our own handler
+without breaking any existing handler already installed by uvicorn.
+"""
+
+from __future__ import annotations
+
+import signal
+import threading
+from types import FrameType
+from typing import Any, Callable, Dict, Iterable, Optional
+
+
+def _call_prev(prev: Any, signum: int, frame: Optional[FrameType]) -> None:
+ if not callable(prev):
+ return
+ try:
+ prev(signum, frame)
+ except TypeError:
+ # Some handlers only accept (signum).
+ prev(signum) # type: ignore[misc]
+
+
+def install_chained_signal_handlers(
+ *,
+ signals: Iterable[int],
+ handler: Callable[[int, Optional[FrameType]], None],
+) -> Callable[[], None]:
+ """Install `handler` for each signal, while preserving any existing handler.
+
+ Returns a restore() function that puts the previous handlers back.
+ """
+ # `signal.signal(...)` only works in the main thread. During tests (FastAPI
+ # TestClient), lifespan runs in a worker thread, so we must no-op.
+ if threading.current_thread() is not threading.main_thread():
+ return lambda: None
+
+ previous: Dict[int, Any] = {}
+
+ for sig in signals:
+ prev = signal.getsignal(sig)
+ previous[sig] = prev
+
+ def _wrapped(signum: int, frame: Optional[FrameType], _prev=prev) -> None:
+ handler(signum, frame)
+ _call_prev(_prev, signum, frame)
+
+ signal.signal(sig, _wrapped)
+
+ def restore() -> None:
+ for sig, prev in previous.items():
+ signal.signal(sig, prev) # type: ignore[arg-type]
+
+ return restore