| null = null;
+let _fetchSeq = 0;
-async function _doFetch(root: string) {
+async function _doFetch(root: string, seq: number) {
if (!root) {
_status = null;
return;
}
_loading = true;
try {
- const data = (await fetchJSON(
- `/api/git/status?root=${encodeURIComponent(root)}`
- )) as GitStatus;
+ const data = (await fetchJSON(`/api/git/status?root=${encodeURIComponent(root)}`)) as GitStatus;
// Only apply if root hasn't changed while we were fetching
- if (root === _currentRoot) {
+ if (root === _currentRoot && seq === _fetchSeq) {
_status = data;
}
} catch {
- if (root === _currentRoot) {
+ if (root === _currentRoot && seq === _fetchSeq) {
_status = null;
}
} finally {
- _loading = false;
- _fetchPromise = null;
+ if (seq === _fetchSeq) {
+ _loading = false;
+ _fetchPromise = null;
+ }
}
}
@@ -71,7 +72,8 @@ export const gitStatusStore = {
if (root === _currentRoot) return;
_currentRoot = root;
_status = null;
- this.refresh();
+ _fetchPromise = null;
+ this.refresh({ force: true });
},
/** Clear all state (no workspace). */
@@ -80,16 +82,18 @@ export const gitStatusStore = {
_status = null;
_loading = false;
_fetchPromise = null;
+ _fetchSeq++;
},
/**
* Refresh git status from the server.
* Concurrent calls are coalesced into a single fetch.
*/
- refresh() {
+ refresh({ force = false }: { force?: boolean } = {}) {
if (!_currentRoot) return;
- if (!_fetchPromise) {
- _fetchPromise = _doFetch(_currentRoot);
+ if (!_fetchPromise || force) {
+ const seq = ++_fetchSeq;
+ _fetchPromise = _doFetch(_currentRoot, seq);
}
return _fetchPromise;
}
diff --git a/cptr/frontend/src/routes/+layout.svelte b/cptr/frontend/src/routes/+layout.svelte
index b7d92b3..72dd8d7 100644
--- a/cptr/frontend/src/routes/+layout.svelte
+++ b/cptr/frontend/src/routes/+layout.svelte
@@ -331,7 +331,7 @@
{#if !$currentWorkspace && $page.url.pathname === '/'}
diff --git a/cptr/frontend/static/apple-touch-icon.png b/cptr/frontend/static/apple-touch-icon.png
new file mode 100644
index 0000000..fd32ab6
Binary files /dev/null and b/cptr/frontend/static/apple-touch-icon.png differ
diff --git a/cptr/frontend/static/icon-192.png b/cptr/frontend/static/icon-192.png
index fbd2eab..f8b206f 100644
Binary files a/cptr/frontend/static/icon-192.png and b/cptr/frontend/static/icon-192.png differ
diff --git a/cptr/frontend/static/icon-512.png b/cptr/frontend/static/icon-512.png
index afebe2c..10c84f4 100644
Binary files a/cptr/frontend/static/icon-512.png and b/cptr/frontend/static/icon-512.png differ
diff --git a/cptr/routers/admin.py b/cptr/routers/admin.py
index a6d7d1d..acc4d4c 100644
--- a/cptr/routers/admin.py
+++ b/cptr/routers/admin.py
@@ -7,8 +7,10 @@ from fastapi.responses import JSONResponse
from pydantic import BaseModel
from typing import Optional
-from cptr.utils.config import AuthResult, check_access, hash_password, now_ms
+from cptr.routers.chat import invalidate_model_cache
from cptr.models import User, Auth, Config
+from cptr.utils.config import AuthResult, _get_jwt_secret, check_access, hash_password, now_ms
+from cptr.utils.crypto import decrypt_key, encrypt_key, mask_key
router = APIRouter(prefix="/api/admin", tags=["admin"])
@@ -128,20 +130,27 @@ async def get_config_namespace(namespace: str, request: Request):
return {"config": await Config.get_namespace(namespace)}
+def _prepare_config_updates(updates: dict) -> dict:
+ """Normalize sensitive config values before persisting them."""
+ prepared = dict(updates)
+ secret = _get_jwt_secret()
+ for key in ("audio.stt_api_key", "audio.tts_api_key"):
+ value = prepared.get(key)
+ if isinstance(value, str) and value and not value.startswith("encrypted:"):
+ prepared[key] = encrypt_key(value, secret)
+ return prepared
+
+
@router.put("/config")
async def put_config(body: ConfigUpdateRequest, request: Request):
"""Update config keys. Upserts each key."""
require_admin(request)
- await Config.upsert(body.config)
+ await Config.upsert(_prepare_config_updates(body.config))
return {"ok": True}
# ── Connections ──────────────────────────────────────────────
-from cptr.utils.crypto import encrypt_key, decrypt_key, mask_key
-from cptr.utils.config import _get_jwt_secret
-from cptr.routers.chat import invalidate_model_cache
-
async def _get_connections() -> list[dict]:
"""Get all connections from config store."""
@@ -367,6 +376,11 @@ CONFIG_KEY_CHAT_MODELS = "chat.models"
async def get_model_config(request: Request):
"""Get per-model config and full model list (including inactive) for the admin Models tab."""
require_admin(request)
+ return await _build_model_config(request)
+
+
+async def _build_model_config(request: Request):
+ """Build model configuration response for the admin Models tab."""
config = await Config.get(CONFIG_KEY_CHAT_MODELS) or {}
# Build full model list from all enabled connections (same as chat.py
@@ -392,6 +406,14 @@ async def get_model_config(request: Request):
return {"config": config, "models": models}
+@router.post("/models/refresh")
+async def refresh_model_list(request: Request):
+ """Clear cached provider-discovered models and return the refreshed model list."""
+ require_admin(request)
+ invalidate_model_cache(request.app.state)
+ return await _build_model_config(request)
+
+
class UpdateModelConfigRequest(BaseModel):
is_active: Optional[bool] = None
params: Optional[dict] = None
diff --git a/cptr/routers/audio.py b/cptr/routers/audio.py
index 7f4e914..70f02aa 100644
--- a/cptr/routers/audio.py
+++ b/cptr/routers/audio.py
@@ -7,17 +7,21 @@ If pydub is not installed, raw audio is sent directly (works for < 25MB files).
from __future__ import annotations
import asyncio
+import hashlib
+import json
import logging
import os
import tempfile
from pathlib import Path
import httpx
-from fastapi import APIRouter, HTTPException, Request, UploadFile
+from fastapi import APIRouter, Form, HTTPException, Request, Response, UploadFile
+from pydantic import BaseModel
from cptr.models import Config
from cptr.utils.config import _get_jwt_secret, check_access
from cptr.utils.crypto import decrypt_key
+from cptr.utils.workspace import ensure_cptr_gitignored
logger = logging.getLogger(__name__)
@@ -35,6 +39,24 @@ COOKIE_NAME = "cptr_session"
MAX_FILE_SIZE = 25 * 1024 * 1024 # 25MB Whisper API limit
+class SpeechRequest(BaseModel):
+ text: str
+ voice: str | None = None
+ workspace: str | None = None
+
+
+class AudioStateResponse(BaseModel):
+ voice_memos_enabled: bool
+ transcribe_enabled: bool
+ stt_configured: bool
+ recording_quality: str
+ tts_enabled: bool
+ tts_configured: bool
+ tts_voice: str
+ tts_format: str
+ voice_mode_stt_mode: str
+
+
def _get_user(request: Request) -> str:
"""Extract user_id from cookie, raise 401 if not authenticated."""
token = request.cookies.get(COOKIE_NAME)
@@ -45,6 +67,65 @@ def _get_user(request: Request) -> str:
return auth.user_id
+def _workspace_audio_cache_dir(workspace: str | None, kind: str) -> Path | None:
+ # Voice samples are project context, so they live under the workspace .cptr
+ # folder and move with the project. That keeps STT and TTS artifacts available
+ # for reuse, debugging, and the local data flywheel while ensure_cptr_gitignored
+ # keeps them out of git.
+ if not workspace:
+ return None
+ ws = Path(workspace).expanduser().resolve()
+ if not ws.is_dir():
+ return None
+ cache_dir = ws / ".cptr" / "cache" / "audio" / kind
+ cache_dir.mkdir(parents=True, exist_ok=True)
+ ensure_cptr_gitignored(ws)
+ return cache_dir
+
+
+def _cache_key(payload: dict, data: bytes | None = None) -> str:
+ # The key includes the provider settings plus the exact audio bytes or text.
+ # Without those inputs, a model, voice, or format change could accidentally reuse
+ # the wrong artifact. The JSON file beside the audio explains what the hash means.
+ h = hashlib.sha256()
+ h.update(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode())
+ if data is not None:
+ h.update(b"\0")
+ h.update(data)
+ return h.hexdigest()
+
+
+def _write_bytes_atomic(path: Path, data: bytes) -> None:
+ tmp = path.with_suffix(path.suffix + ".tmp")
+ tmp.write_bytes(data)
+ tmp.replace(path)
+
+
+def _write_json_atomic(path: Path, data: dict) -> None:
+ _write_bytes_atomic(
+ path,
+ json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True).encode(),
+ )
+
+
+def _audio_extension(filename: str, content_type: str, fallback: str = ".webm") -> str:
+ ext = Path(filename).suffix.lower()
+ if ext and len(ext) <= 10 and ext[1:].replace("-", "").isalnum():
+ return ext
+ return {
+ "audio/mpeg": ".mp3",
+ "audio/mp3": ".mp3",
+ "audio/webm": ".webm",
+ "audio/ogg": ".ogg",
+ "audio/opus": ".opus",
+ "audio/aac": ".aac",
+ "audio/flac": ".flac",
+ "audio/wav": ".wav",
+ "audio/x-wav": ".wav",
+ "audio/mp4": ".m4a",
+ }.get(content_type.split(";")[0].lower(), fallback)
+
+
# ── Audio processing (optional, requires pydub + ffmpeg) ─────────
@@ -109,6 +190,30 @@ def split_audio(file_path: str, max_bytes: int) -> list[str]:
# ── Transcription ────────────────────────────────────────────────
+@router.get("/state", response_model=AudioStateResponse)
+async def audio_state(request: Request):
+ """Return non-sensitive audio feature state for the authenticated UI."""
+ _get_user(request)
+
+ tts_key = await Config.get("audio.tts_api_key")
+ stt_key = await Config.get("audio.stt_api_key")
+ quality = await Config.get("audio.recording_quality")
+ if quality not in ("high", "medium", "low"):
+ quality = "high"
+
+ return AudioStateResponse(
+ voice_memos_enabled=await Config.get("audio.voice_memos_enabled") is True,
+ transcribe_enabled=await Config.get("audio.transcribe_enabled") is not False,
+ stt_configured=bool(stt_key),
+ recording_quality=str(quality),
+ tts_enabled=await Config.get("audio.tts_enabled") is True,
+ tts_configured=bool(tts_key or stt_key),
+ tts_voice=str((await Config.get("audio.tts_voice")) or "alloy"),
+ tts_format=str((await Config.get("audio.tts_format")) or "mp3"),
+ voice_mode_stt_mode=str((await Config.get("audio.voice_mode_stt_mode")) or "browser"),
+ )
+
+
async def _transcribe_chunk(
data: bytes,
filename: str,
@@ -130,7 +235,14 @@ async def _transcribe_chunk(
@router.post("/transcribe")
-async def transcribe(file: UploadFile, request: Request):
+async def transcribe(
+ file: UploadFile,
+ request: Request,
+ workspace: str | None = Form(None),
+ text: str | None = Form(None),
+ source: str | None = Form(None),
+ language: str | None = Form(None),
+):
"""Send audio to a Whisper-compatible STT API, return transcript text.
If pydub + ffmpeg are available and the file is large, it will be
@@ -138,6 +250,53 @@ async def transcribe(file: UploadFile, request: Request):
"""
_get_user(request)
+ raw_data = await file.read()
+ filename = file.filename or "audio.webm"
+ content_type = file.content_type or "audio/webm"
+ cache_dir = _workspace_audio_cache_dir(workspace, "stt")
+ cache_json_path: Path | None = None
+ cache_audio_path: Path | None = None
+ provided_text = (text or "").strip()
+
+ if provided_text:
+ # Browser speech recognition already produced text, so there is no provider
+ # call to cache. We still store the captured audio and transcript in the
+ # normal STT folder so browser mode and provider mode produce the same kind
+ # of data flywheel sample without paying for a second transcription.
+ if not raw_data:
+ raise HTTPException(400, "Speech-to-text capture requires non-empty audio.")
+ if cache_dir:
+ audio_ext = _audio_extension(filename, content_type)
+ key = _cache_key(
+ {
+ "type": "stt",
+ "source": source or "browser_speech_recognition",
+ "text": provided_text,
+ "filename": filename,
+ "content_type": content_type,
+ "language": language or "",
+ },
+ raw_data,
+ )
+ cache_json_path = cache_dir / f"{key}.json"
+ cache_audio_path = cache_dir / f"{key}{audio_ext}"
+ if not cache_json_path.exists() or not cache_audio_path.exists():
+ _write_bytes_atomic(cache_audio_path, raw_data)
+ _write_json_atomic(
+ cache_json_path,
+ {
+ "type": "stt",
+ "source": source or "browser_speech_recognition",
+ "transcription_source": "browser_speech_recognition",
+ "text": provided_text,
+ "audio_file": cache_audio_path.name,
+ "filename": filename,
+ "content_type": content_type,
+ "language": language,
+ },
+ )
+ return {"text": provided_text, "cached": True}
+
api_key_encrypted = await Config.get("audio.stt_api_key")
if not api_key_encrypted:
raise HTTPException(
@@ -149,14 +308,49 @@ async def transcribe(file: UploadFile, request: Request):
base_url = (await Config.get("audio.stt_base_url")) or "https://api.openai.com/v1"
model = (await Config.get("audio.stt_model")) or "whisper-1"
- raw_data = await file.read()
- filename = file.filename or "audio.webm"
- content_type = file.content_type or "audio/webm"
+ if cache_dir:
+ # Provider STT is cacheable because identical audio with the same provider
+ # settings should produce the same transcript. Keeping the original audio
+ # beside the JSON makes the sample reusable for audits, replay, and future
+ # data flywheel work instead of being a one-off API response.
+ key = _cache_key(
+ {
+ "type": "stt",
+ "base_url": str(base_url).rstrip("/"),
+ "model": model,
+ "filename": filename,
+ "content_type": content_type,
+ },
+ raw_data,
+ )
+ audio_ext = _audio_extension(filename, content_type)
+ cache_json_path = cache_dir / f"{key}.json"
+ cache_audio_path = cache_dir / f"{key}{audio_ext}"
+ if cache_json_path.exists():
+ try:
+ cached = json.loads(cache_json_path.read_text(encoding="utf-8"))
+ return {"text": str(cached.get("text") or ""), "cached": True}
+ except (OSError, json.JSONDecodeError):
+ pass
# Small file: send directly, no temp files needed
if len(raw_data) <= MAX_FILE_SIZE or not HAS_PYDUB:
try:
text = await _transcribe_chunk(raw_data, filename, content_type, base_url, api_key, model)
+ if cache_json_path and cache_audio_path:
+ _write_bytes_atomic(cache_audio_path, raw_data)
+ _write_json_atomic(
+ cache_json_path,
+ {
+ "type": "stt",
+ "text": text,
+ "audio_file": cache_audio_path.name,
+ "filename": filename,
+ "content_type": content_type,
+ "base_url": str(base_url).rstrip("/"),
+ "model": model,
+ },
+ )
return {"text": text}
except httpx.HTTPStatusError as exc:
detail = f"STT API error: {exc.response.status_code}"
@@ -190,7 +384,22 @@ async def transcribe(file: UploadFile, request: Request):
# Use gather to preserve order (as_completed doesn't guarantee it)
results = await asyncio.gather(*tasks)
- return {"text": " ".join(r for r in results if r)}
+ text = " ".join(r for r in results if r)
+ if cache_json_path and cache_audio_path:
+ _write_bytes_atomic(cache_audio_path, raw_data)
+ _write_json_atomic(
+ cache_json_path,
+ {
+ "type": "stt",
+ "text": text,
+ "audio_file": cache_audio_path.name,
+ "filename": filename,
+ "content_type": content_type,
+ "base_url": str(base_url).rstrip("/"),
+ "model": model,
+ },
+ )
+ return {"text": text}
except httpx.HTTPStatusError as exc:
logger.warning("[transcribe] STT API error %s: %s", exc.response.status_code, exc.response.text[:500])
@@ -218,3 +427,114 @@ async def transcribe(file: UploadFile, request: Request):
os.rmdir(tmp_dir)
except OSError:
pass
+
+
+def _audio_media_type(fmt: str) -> str:
+ return {
+ "mp3": "audio/mpeg",
+ "opus": "audio/ogg",
+ "aac": "audio/aac",
+ "flac": "audio/flac",
+ "wav": "audio/wav",
+ "pcm": "audio/L16",
+ }.get(fmt, "audio/mpeg")
+
+
+@router.post("/speech")
+async def speech(body: SpeechRequest, request: Request):
+ """Generate speech audio using an OpenAI-compatible TTS API."""
+ _get_user(request)
+
+ text = body.text.strip()
+ if not text:
+ raise HTTPException(400, "Text-to-speech requires non-empty text.")
+
+ if await Config.get("audio.tts_enabled") is not True:
+ raise HTTPException(400, "Text-to-speech is disabled in Settings → Audio.")
+
+ api_key_encrypted = await Config.get("audio.tts_api_key")
+ if not api_key_encrypted:
+ api_key_encrypted = await Config.get("audio.stt_api_key")
+ if not api_key_encrypted:
+ raise HTTPException(
+ 400,
+ "Text-to-speech not configured. Set up a TTS or STT API key in Settings → Audio.",
+ )
+
+ api_key = decrypt_key(api_key_encrypted, _get_jwt_secret())
+ base_url = ((await Config.get("audio.tts_base_url")) or "https://api.openai.com/v1").rstrip("/")
+ model = (await Config.get("audio.tts_model")) or "tts-1"
+ voice = body.voice or (await Config.get("audio.tts_voice")) or "alloy"
+ fmt = str((await Config.get("audio.tts_format")) or "mp3").lower()
+
+ payload = {
+ "model": model,
+ "input": text,
+ "voice": voice,
+ "response_format": fmt,
+ }
+ cache_dir = _workspace_audio_cache_dir(body.workspace, "tts")
+ cache_audio_path: Path | None = None
+ cache_json_path: Path | None = None
+ if cache_dir:
+ # TTS is especially worth caching because short phrases repeat often across
+ # messages and replays. The key uses provider, model, voice, format, and exact
+ # text so a phrase like "Hi." can be reused safely without new spend, while
+ # the neighboring JSON records why that audio file exists.
+ key = _cache_key(
+ {
+ "type": "tts",
+ "base_url": base_url,
+ "model": model,
+ "voice": voice,
+ "format": fmt,
+ "text": text,
+ }
+ )
+ cache_audio_path = cache_dir / f"{key}.{fmt}"
+ cache_json_path = cache_dir / f"{key}.json"
+ if cache_audio_path.exists():
+ try:
+ return Response(
+ content=cache_audio_path.read_bytes(),
+ media_type=_audio_media_type(str(fmt)),
+ headers={"X-CPTR-Audio-Cache": "hit"},
+ )
+ except OSError:
+ pass
+
+ try:
+ async with httpx.AsyncClient(timeout=httpx.Timeout(120)) as client:
+ resp = await client.post(
+ f"{base_url}/audio/speech",
+ headers={"Authorization": f"Bearer {api_key}"},
+ json=payload,
+ )
+ resp.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ logger.warning(
+ "[speech] TTS API error %s: %s",
+ exc.response.status_code,
+ exc.response.text[:500],
+ )
+ raise HTTPException(502, f"TTS API error: {exc.response.status_code}")
+ except httpx.ConnectError:
+ raise HTTPException(502, "Could not connect to TTS API")
+
+ if cache_audio_path and cache_json_path:
+ _write_bytes_atomic(cache_audio_path, resp.content)
+ _write_json_atomic(
+ cache_json_path,
+ {
+ "type": "tts",
+ "text": text,
+ "audio_file": cache_audio_path.name,
+ "base_url": base_url,
+ "model": model,
+ "voice": voice,
+ "format": fmt,
+ "content_type": _audio_media_type(str(fmt)),
+ },
+ )
+
+ return Response(content=resp.content, media_type=_audio_media_type(str(fmt)))
diff --git a/cptr/routers/chat.py b/cptr/routers/chat.py
index d157547..6cb90d8 100644
--- a/cptr/routers/chat.py
+++ b/cptr/routers/chat.py
@@ -8,12 +8,12 @@ from pathlib import Path
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Query, Request
-from fastapi.responses import JSONResponse
from pydantic import BaseModel
from cptr.models import Chat, ChatMessage, Config
from cptr.utils.config import check_access, now_ms, _get_jwt_secret
from cptr.utils.crypto import decrypt_key
+from cptr.utils.workspace import ensure_cptr_gitignored
log = logging.getLogger(__name__)
@@ -22,32 +22,6 @@ router = APIRouter(prefix="/api/chats", tags=["chats"])
COOKIE_NAME = "cptr_session"
-def _ensure_gitignore(workspace: str) -> None:
- """If workspace is a git repo, ensure .cptr is listed in .gitignore."""
- ws = Path(workspace)
- if not (ws / ".git").exists():
- return
-
- gitignore = ws / ".gitignore"
- entry = ".cptr"
-
- # Check if already ignored
- if gitignore.exists():
- content = gitignore.read_text(encoding="utf-8", errors="replace")
- # Match .cptr as a standalone line (not a substring of something else)
- for line in content.splitlines():
- stripped = line.strip()
- if stripped == entry or stripped == entry + "/":
- return
- # Append with a preceding newline if file doesn't end with one
- if content and not content.endswith("\n"):
- content += "\n"
- content += f"{entry}\n"
- gitignore.write_text(content, encoding="utf-8")
- else:
- gitignore.write_text(f"{entry}\n", encoding="utf-8")
-
-
def _get_user(request: Request) -> str:
"""Extract user_id from cookie, raise 401 if not authenticated."""
token = request.cookies.get(COOKIE_NAME)
@@ -389,7 +363,7 @@ async def send_message(body: SendMessageRequest, request: Request):
await asyncio.to_thread(lambda: chats_dir.mkdir(parents=True, exist_ok=True))
# Auto-add .cptr to .gitignore if this is a git repo
- await asyncio.to_thread(_ensure_gitignore, body.workspace)
+ await asyncio.to_thread(ensure_cptr_gitignored, body.workspace)
# Check if the chat has an in-progress assistant message.
# If so, queue this message instead of starting a new task.
diff --git a/cptr/routers/git.py b/cptr/routers/git.py
index 8320686..1cadd09 100644
--- a/cptr/routers/git.py
+++ b/cptr/routers/git.py
@@ -20,6 +20,7 @@ from cptr.utils.git import (
delete_branch,
diff,
discard,
+ fetch,
is_repo,
log,
pull,
@@ -243,6 +244,15 @@ async def git_pull(body: RootRequest):
_handle_git_error(e)
+@router.post("/fetch")
+async def git_fetch(body: RootRequest):
+ """Fetch from remote without merging."""
+ try:
+ return await fetch(body.root)
+ except GitError as e:
+ _handle_git_error(e)
+
+
@router.post("/push")
async def git_push(body: PushRequest):
"""Push to remote."""
diff --git a/cptr/utils/ai.py b/cptr/utils/ai.py
index 08b8156..166fbf6 100644
--- a/cptr/utils/ai.py
+++ b/cptr/utils/ai.py
@@ -1,7 +1,7 @@
"""Provider streaming and completion functions: raw httpx.
Each streaming function takes a ChatCompletionForm + url + key.
-All yield normalized events: text_delta, tool_call, usage, done.
+All yield normalized events: text_delta, output, tool_call, usage, done.
chat_completion() provides a simple non-streaming call for lightweight tasks
(title generation, summarization, etc.).
@@ -10,6 +10,7 @@ chat_completion() provides a simple non-streaming call for lightweight tasks
from __future__ import annotations
import asyncio
+import copy
import json
import logging
import uuid
@@ -24,10 +25,21 @@ from cptr.env import (
STREAM_READ_TIMEOUT_SECONDS,
STREAM_WRITE_TIMEOUT_SECONDS,
)
+from cptr.utils.logger import log_upstream_request
logger = logging.getLogger(__name__)
+def _reasoning_output_item(text: str = "", *, status: str = "in_progress") -> dict:
+ """Create a Responses-style reasoning output item."""
+ return {
+ "type": "reasoning",
+ "id": f"rs_{uuid.uuid4().hex}",
+ "status": status,
+ "content": [{"type": "text", "text": text}],
+ }
+
+
def _openrouter_headers(url: str) -> dict[str, str]:
"""Return OpenRouter app-info headers when the URL is an OpenRouter endpoint."""
if "openrouter.ai" in url:
@@ -93,6 +105,13 @@ async def chat_completion(
body["system"] = system
if request_params:
body.update(request_params)
+ log_upstream_request(
+ provider="anthropic",
+ endpoint=f"{base_url}/messages",
+ model=model,
+ api_type="messages",
+ body=body,
+ )
resp = await client.post(
f"{base_url}/messages",
json=body,
@@ -113,6 +132,13 @@ async def chat_completion(
body_r["instructions"] = system
if request_params:
body_r.update(request_params)
+ log_upstream_request(
+ provider=provider,
+ endpoint=f"{base_url}/responses",
+ model=model,
+ api_type="responses",
+ body=body_r,
+ )
resp = await client.post(
f"{base_url}/responses",
json=body_r,
@@ -130,6 +156,13 @@ async def chat_completion(
}
if request_params:
body_cc.update(request_params)
+ log_upstream_request(
+ provider=provider,
+ endpoint=f"{base_url}/chat/completions",
+ model=model,
+ api_type="chat_completions",
+ body=body_cc,
+ )
resp = await client.post(
f"{base_url}/chat/completions",
json=body_cc,
@@ -169,7 +202,7 @@ def _to_anthropic_messages(messages: list[dict]) -> list[dict]:
role = m["role"]
if role == "system":
continue # system goes in body.system
-
+
content = m.get("content", "")
if isinstance(content, list):
formatted_content = []
@@ -177,14 +210,16 @@ def _to_anthropic_messages(messages: list[dict]) -> list[dict]:
if block.get("type") == "text":
formatted_content.append({"type": "text", "text": block.get("text", "")})
elif block.get("type") == "image":
- formatted_content.append({
- "type": "image",
- "source": {
- "type": "base64",
- "media_type": block.get("media_type", "image/jpeg"),
- "data": block.get("base64", "")
+ formatted_content.append(
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": block.get("media_type", "image/jpeg"),
+ "data": block.get("base64", ""),
+ },
}
- })
+ )
content = formatted_content
if role == "tool":
# tool result → Anthropic tool_result block
@@ -196,14 +231,16 @@ def _to_anthropic_messages(messages: list[dict]) -> list[dict]:
if block.get("type") == "text":
tool_content.append({"type": "text", "text": block.get("text", "")})
elif block.get("type") == "image":
- tool_content.append({
- "type": "image",
- "source": {
- "type": "base64",
- "media_type": block.get("media_type", "image/jpeg"),
- "data": block.get("base64", ""),
+ tool_content.append(
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": block.get("media_type", "image/jpeg"),
+ "data": block.get("base64", ""),
+ },
}
- })
+ )
else:
tool_content = content
result.append(
@@ -262,6 +299,13 @@ async def stream_anthropic(
body.update(request_params)
# Remove None values
body = {k: v for k, v in body.items() if v is not None}
+ log_upstream_request(
+ provider="anthropic",
+ endpoint=f"{url}/messages",
+ model=form_data.model,
+ api_type="messages",
+ body=body,
+ )
headers = {"x-api-key": key, "anthropic-version": "2023-06-01", **_openrouter_headers(url)}
emitted = False
@@ -286,7 +330,10 @@ async def stream_anthropic(
msg_usage = event.get("message", {}).get("usage", {})
if msg_usage:
usage_data["input_tokens"] = msg_usage.get("input_tokens", 0)
- for cache_key in ("cache_read_input_tokens", "cache_creation_input_tokens"):
+ for cache_key in (
+ "cache_read_input_tokens",
+ "cache_creation_input_tokens",
+ ):
if msg_usage.get(cache_key):
usage_data[cache_key] = msg_usage[cache_key]
@@ -342,11 +389,27 @@ async def stream_anthropic(
# ── OpenAI Chat Completions ──────────────────────────────────
+def _reasoning_items_to_content(items: list[dict]) -> str:
+ """Convert Responses API reasoning items to a reasoning_content string.
+
+ Reasoning items may expose text in content or summary blocks. We extract
+ those text blocks and join them for Chat Completions-compatible providers.
+ """
+ texts: list[str] = []
+ for item in items:
+ blocks = item.get("content") or item.get("summary") or []
+ for block in blocks:
+ if isinstance(block, dict) and block.get("type") == "text" and block.get("text"):
+ texts.append(block["text"])
+ return "\n".join(texts)
+
+
def _to_openai_messages(messages: list[dict], instructions: str) -> list[dict]:
"""Canonical messages → OpenAI Chat Completions format.
- Strips non-standard fields (reasoning_items, fc_id in tool_calls)
- that are used internally but would cause 400 errors from OpenAI.
+ Converts reasoning_items (Responses API format) to reasoning_content
+ (Chat Completions format) for providers like Kimi that require it.
+ Strips other non-standard fields (fc_id in tool_calls).
"""
result = []
if instructions:
@@ -366,24 +429,28 @@ def _to_openai_messages(messages: list[dict], instructions: str) -> list[dict]:
formatted_content.append(block)
elif block.get("type") == "image":
data_uri = f"data:{block.get('media_type', 'image/jpeg')};base64,{block.get('base64', '')}"
- formatted_content.append({
- "type": "image_url",
- "image_url": {"url": data_uri}
- })
+ formatted_content.append({"type": "image_url", "image_url": {"url": data_uri}})
new_m = dict(m)
new_m["content"] = formatted_content
- # Strip non-standard fields
- new_m.pop("reasoning_items", None)
+ # Convert reasoning_items → reasoning_content for round-tripping
+ ri = new_m.pop("reasoning_items", None)
+ if ri and new_m.get("role") == "assistant":
+ rc = _reasoning_items_to_content(ri)
+ if rc:
+ new_m["reasoning_content"] = rc
result.append(new_m)
else:
out = dict(m)
- # Strip non-standard fields that are only for Responses API
- out.pop("reasoning_items", None)
+ # Convert reasoning_items → reasoning_content for round-tripping
+ ri = out.pop("reasoning_items", None)
+ if ri and out.get("role") == "assistant":
+ rc = _reasoning_items_to_content(ri)
+ if rc:
+ out["reasoning_content"] = rc
# Clean tool_calls: remove fc_id which is Responses-API-only
if "tool_calls" in out:
out["tool_calls"] = [
- {k: v for k, v in tc.items() if k != "fc_id"}
- for tc in out["tool_calls"]
+ {k: v for k, v in tc.items() if k != "fc_id"} for tc in out["tool_calls"]
]
result.append(out)
return result
@@ -414,6 +481,13 @@ async def stream_openai_completions(
body["tools"] = tools
if request_params:
body.update(request_params)
+ log_upstream_request(
+ provider="openai",
+ endpoint=f"{url}/chat/completions",
+ model=form_data.model,
+ api_type="chat_completions",
+ body=body,
+ )
headers = {"Authorization": f"Bearer {key}", **_openrouter_headers(url)}
emitted = False
@@ -431,9 +505,25 @@ async def stream_openai_completions(
logger.info("[stream] openai completions status=%s", resp.status_code)
if resp.status_code >= 400:
error_body = await resp.aread()
- logger.error("[stream] openai completions error body: %s", error_body.decode(errors="replace"))
+ logger.error(
+ "[stream] openai completions error body: %s",
+ error_body.decode(errors="replace"),
+ )
resp.raise_for_status()
tool_calls: dict[int, dict] = {}
+ reasoning_buffer = "" # Accumulate reasoning_content deltas (Kimi, DeepSeek)
+ reasoning_item: dict | None = None
+
+ def complete_reasoning_item() -> dict | None:
+ nonlocal reasoning_buffer, reasoning_item
+ if reasoning_item is None:
+ return None
+ reasoning_item["status"] = "completed"
+ item = copy.deepcopy(reasoning_item)
+ reasoning_item = None
+ reasoning_buffer = ""
+ return item
+
async for line in resp.aiter_lines():
if not line.startswith("data: ") or line == "data: [DONE]":
continue
@@ -441,10 +531,29 @@ async def stream_openai_completions(
choices = chunk.get("choices", [])
delta = choices[0].get("delta", {}) if choices else {}
+ # Capture reasoning_content from providers like Kimi / DeepSeek
+ if delta.get("reasoning_content"):
+ reasoning_buffer += delta["reasoning_content"]
+ if reasoning_item is None:
+ reasoning_item = _reasoning_output_item()
+ reasoning_item["content"][0]["text"] = reasoning_buffer
+ emitted = True
+ yield {"type": "output", "item": copy.deepcopy(reasoning_item)}
+
if delta.get("content"):
+ item = complete_reasoning_item()
+ if item is not None:
+ emitted = True
+ yield {"type": "output", "item": item}
emitted = True
yield {"type": "text_delta", "content": delta["content"]}
+ if delta.get("tool_calls"):
+ item = complete_reasoning_item()
+ if item is not None:
+ emitted = True
+ yield {"type": "output", "item": item}
+
for tc in delta.get("tool_calls", []):
idx = tc["index"]
if idx not in tool_calls:
@@ -456,6 +565,11 @@ async def stream_openai_completions(
tool_calls[idx]["arguments_json"] += tc["function"].get("arguments", "")
if choices and choices[0].get("finish_reason") == "tool_calls":
+ # Emit accumulated reasoning before tool calls
+ item = complete_reasoning_item()
+ if item is not None:
+ emitted = True
+ yield {"type": "output", "item": item}
for tc in tool_calls.values():
emitted = True
yield {
@@ -466,6 +580,12 @@ async def stream_openai_completions(
}
if chunk.get("usage"):
+ # Emit any remaining reasoning BEFORE usage
+ # (usage triggers immediate save+return in chat_task)
+ item = complete_reasoning_item()
+ if item is not None:
+ emitted = True
+ yield {"type": "output", "item": item}
raw = chunk["usage"]
emitted = True
yield {
@@ -474,6 +594,11 @@ async def stream_openai_completions(
"output_tokens": raw.get("completion_tokens", 0),
}
+ # Emit any remaining reasoning if no usage event was received
+ item = complete_reasoning_item()
+ if item is not None:
+ emitted = True
+ yield {"type": "output", "item": item}
emitted = True
yield {"type": "done"}
return
@@ -497,11 +622,7 @@ def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]:
# Pre-collect all tool result call_ids so we can validate function_calls
# have matching outputs. This prevents orphaned function_calls (from
# crashes, data corruption, etc.) from permanently breaking the chat.
- tool_result_ids = {
- m.get("tool_call_id", "")
- for m in messages
- if m.get("role") == "tool"
- }
+ tool_result_ids = {m.get("tool_call_id", "") for m in messages if m.get("role") == "tool"}
items = []
for m in messages:
@@ -561,13 +682,12 @@ def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]:
formatted_content = []
for block in content:
if block.get("type") == "text":
- formatted_content.append({"type": "input_text", "text": block.get("text", "")})
+ formatted_content.append(
+ {"type": "input_text", "text": block.get("text", "")}
+ )
elif block.get("type") == "image":
data_uri = f"data:{block.get('media_type', 'image/jpeg')};base64,{block.get('base64', '')}"
- formatted_content.append({
- "type": "input_image",
- "image_url": data_uri
- })
+ formatted_content.append({"type": "input_image", "image_url": data_uri})
items.append({"type": "message", "role": role, "content": formatted_content})
else:
items.append({"type": "message", "role": role, "content": content})
@@ -598,6 +718,13 @@ async def stream_openai_responses(
body["tools"] = tools
if request_params:
body.update(request_params)
+ log_upstream_request(
+ provider="openai",
+ endpoint=f"{url}/responses",
+ model=form_data.model,
+ api_type="responses",
+ body=body,
+ )
headers = {"Authorization": f"Bearer {key}", **_openrouter_headers(url)}
emitted = False
@@ -606,7 +733,8 @@ async def stream_openai_responses(
async with httpx.AsyncClient(timeout=_STREAM_TIMEOUT) as client:
logger.info(
"[stream] openai responses POST %s/responses model=%s input_items=%d types=%s",
- url, form_data.model,
+ url,
+ form_data.model,
len(body.get("input", [])),
[i.get("type", i.get("role", "?")) for i in body.get("input", [])],
)
@@ -616,7 +744,10 @@ async def stream_openai_responses(
logger.info("[stream] openai responses status=%s", resp.status_code)
if resp.status_code >= 400:
error_body = await resp.aread()
- logger.error("[stream] openai responses error body: %s", error_body.decode(errors="replace"))
+ logger.error(
+ "[stream] openai responses error body: %s",
+ error_body.decode(errors="replace"),
+ )
resp.raise_for_status()
async for line in resp.aiter_lines():
if not line.startswith("data: "):
@@ -644,8 +775,9 @@ async def stream_openai_responses(
}
elif item["type"] == "reasoning":
# Reasoning items must be round-tripped for reasoning models
+ emitted = True
yield {
- "type": "reasoning",
+ "type": "output",
"item": item,
}
diff --git a/cptr/utils/audit.py b/cptr/utils/audit.py
new file mode 100644
index 0000000..a2d74f8
--- /dev/null
+++ b/cptr/utils/audit.py
@@ -0,0 +1,169 @@
+"""File-based HTTP audit logging middleware."""
+
+from __future__ import annotations
+
+import json
+import re
+import uuid
+from enum import Enum
+from typing import Any, Awaitable, Callable
+
+from starlette.requests import Request
+
+from cptr.env import AUDIT_LOG_LEVEL, AUDIT_MAX_BODY_SIZE
+from cptr.utils.logger import audit_logger
+
+
+class AuditLevel(str, Enum):
+ NONE = "NONE"
+ METADATA = "METADATA"
+ REQUEST = "REQUEST"
+ REQUEST_RESPONSE = "REQUEST_RESPONSE"
+
+
+_SENSITIVE_KEYS = {"password", "api_key", "token", "authorization", "cookie", "secret"}
+
+
+def _redact(value: Any) -> Any:
+ if isinstance(value, dict):
+ return {
+ k: "********" if k.lower() in _SENSITIVE_KEYS else _redact(v)
+ for k, v in value.items()
+ }
+ if isinstance(value, list):
+ return [_redact(v) for v in value]
+ return value
+
+
+def _decode_body(body: bytearray) -> str | None:
+ if not body:
+ return None
+ text = body.decode("utf-8", errors="replace")
+ try:
+ return json.dumps(_redact(json.loads(text)), ensure_ascii=False, default=str)
+ except Exception:
+ for key in _SENSITIVE_KEYS:
+ text = re.sub(
+ rf'("{re.escape(key)}"\s*:\s*")[^"]*(")',
+ r"\1********\2",
+ text,
+ flags=re.IGNORECASE,
+ )
+ return text
+
+
+class AuditContext:
+ def __init__(self, max_body_size: int) -> None:
+ self.request_body = bytearray()
+ self.response_body = bytearray()
+ self.max_body_size = max_body_size
+ self.status_code: int | None = None
+
+ def add_request(self, chunk: bytes) -> None:
+ self._add(self.request_body, chunk)
+
+ def add_response(self, chunk: bytes) -> None:
+ self._add(self.response_body, chunk)
+
+ def _add(self, target: bytearray, chunk: bytes) -> None:
+ if not chunk or len(target) >= self.max_body_size:
+ return
+ target.extend(chunk[: self.max_body_size - len(target)])
+
+
+class AuditLoggingMiddleware:
+ """Capture safe HTTP audit entries to the audit Loguru sink."""
+
+ AUDITED_METHODS = {"POST", "PUT", "PATCH", "DELETE"}
+
+ def __init__(
+ self,
+ app,
+ *,
+ audit_level: AuditLevel,
+ excluded_paths: list[str] | None = None,
+ max_body_size: int = AUDIT_MAX_BODY_SIZE,
+ ) -> None:
+ self.app = app
+ self.audit_level = audit_level
+ self.excluded_paths = excluded_paths or []
+ self.max_body_size = max_body_size
+
+ async def __call__(
+ self,
+ scope: dict[str, Any],
+ receive: Callable[[], Awaitable[dict[str, Any]]],
+ send: Callable[[dict[str, Any]], Awaitable[None]],
+ ) -> None:
+ if scope.get("type") != "http":
+ await self.app(scope, receive, send)
+ return
+
+ request = Request(scope)
+ if self._should_skip(request):
+ await self.app(scope, receive, send)
+ return
+
+ context = AuditContext(self.max_body_size)
+
+ async def receive_wrapper() -> dict[str, Any]:
+ message = await receive()
+ if self.audit_level in (AuditLevel.REQUEST, AuditLevel.REQUEST_RESPONSE):
+ if message.get("type") == "http.request":
+ context.add_request(message.get("body", b""))
+ return message
+
+ async def send_wrapper(message: dict[str, Any]) -> None:
+ if message.get("type") == "http.response.start":
+ context.status_code = message.get("status")
+ elif (
+ self.audit_level == AuditLevel.REQUEST_RESPONSE
+ and message.get("type") == "http.response.body"
+ ):
+ context.add_response(message.get("body", b""))
+ await send(message)
+
+ try:
+ await self.app(scope, receive_wrapper, send_wrapper)
+ finally:
+ self._write_entry(request, context)
+
+ def _should_skip(self, request: Request) -> bool:
+ if AUDIT_LOG_LEVEL == "NONE" or request.method not in self.AUDITED_METHODS:
+ return True
+ path = request.url.path
+ return any(path.startswith(excluded) for excluded in self.excluded_paths)
+
+ def _write_entry(self, request: Request, context: AuditContext) -> None:
+ auth = getattr(request.state, "auth", None)
+ user = {}
+ if auth is not None:
+ user = {
+ "id": getattr(auth, "user_id", None),
+ "username": getattr(auth, "username", None),
+ "role": getattr(auth, "role", None),
+ }
+
+ audit_logger().bind(
+ id=str(uuid.uuid4()),
+ audit_level=self.audit_level.value,
+ user=user,
+ method=request.method,
+ path=request.url.path,
+ status_code=context.status_code,
+ source_ip=request.client.host if request.client else None,
+ user_agent=request.headers.get("user-agent"),
+ request_body=_decode_body(context.request_body)
+ if self.audit_level in (AuditLevel.REQUEST, AuditLevel.REQUEST_RESPONSE)
+ else None,
+ response_body=_decode_body(context.response_body)
+ if self.audit_level == AuditLevel.REQUEST_RESPONSE
+ else None,
+ ).info("")
+
+
+def get_audit_level() -> AuditLevel:
+ try:
+ return AuditLevel(AUDIT_LOG_LEVEL)
+ except ValueError:
+ return AuditLevel.NONE
diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py
index f511f34..a5e112a 100644
--- a/cptr/utils/chat_task.py
+++ b/cptr/utils/chat_task.py
@@ -8,7 +8,10 @@ from __future__ import annotations
import asyncio
import json
import logging
+import platform
+import re
import uuid
+from datetime import date
from pathlib import Path
from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_MAX_CHARS
@@ -34,7 +37,8 @@ logger = logging.getLogger(__name__)
PLAN_MODE_PROMPT = (
"[Plan Mode] Research the codebase with read-only tools, then present your plan "
- "using create_artifact. Wait for approval before coding."
+ "using create_artifact. Then wait for an explicit approval message before using "
+ "tools or implementing."
)
# ── Task registry ───────────────────────────────────────────
@@ -316,10 +320,6 @@ def _load_instruction_files(workspace: str, max_bytes: int = 32_000) -> str:
# ── Template engine ─────────────────────────────────────────
-import platform
-import re
-from datetime import date
-
_TEMPLATE_RE = re.compile(r"\{\{(\w+)\}\}")
DEFAULT_SYSTEM_PROMPT = (
@@ -327,7 +327,8 @@ DEFAULT_SYSTEM_PROMPT = (
"You have access to tools to read, search, and modify files in the workspace. "
"Use them to help the user with their coding tasks.\n\n"
"For complex tasks, create an implementation plan first using "
- "create_artifact, then wait for approval before coding."
+ "create_artifact. Then wait for an explicit approval message before using "
+ "tools or implementing."
"\n\n{{INSTRUCTIONS}}"
"\n\n{{SKILLS}}"
"\n\nWorkspace: {{WORKSPACE_NAME}}"
@@ -436,6 +437,24 @@ async def _load_system_prompt(workspace: str, model: str = "") -> str:
return _render_template(template, variables)
+VOICE_MODE_SYSTEM_PROMPT = (
+ "You are in voice mode. Keep responses brief, conversational, and easy to hear aloud. "
+ "Prefer one or two short paragraphs. Ask at most one focused follow-up question when needed. "
+ "Avoid long lists, code blocks, tables, and verbose explanations unless the user explicitly asks."
+)
+
+
+async def _apply_voice_mode_system_prompt(system: str, chat_params: dict) -> str:
+ if chat_params.get("voice_mode") is not True:
+ return system
+ prompt = str(
+ (await Config.get("audio.voice_mode_system_prompt")) or VOICE_MODE_SYSTEM_PROMPT
+ ).strip()
+ if not prompt:
+ return system
+ return f"{system}\n\n[VOICE MODE]\n{prompt}"
+
+
# ── Title generation ────────────────────────────────────────
@@ -612,9 +631,7 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
# This is needed to filter out orphaned function_calls
# (e.g. from crashes, partial persistence, or data corruption).
output_call_ids = {
- item["call_id"]
- for item in m.output
- if item.get("type") == "function_call_output"
+ item["call_id"] for item in m.output if item.get("type") == "function_call_output"
}
# ── Group output items into per-iteration turns ──
@@ -671,10 +688,7 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
for ti, turn in enumerate(turns):
# Filter calls to only those with matching outputs
turn_output_ids = {o["call_id"] for o in turn["outputs"]}
- matched_calls = [
- tc for tc in turn["calls"]
- if tc["id"] in turn_output_ids
- ]
+ matched_calls = [tc for tc in turn["calls"] if tc["id"] in turn_output_ids]
if matched_calls:
if ti == 0:
# First turn: attach to the existing entry
@@ -721,9 +735,7 @@ def _sanitize_tool_pairs(messages: list[dict]) -> list[dict]:
"""
# Collect all tool-result call_ids in the conversation
tool_result_ids = {
- m["tool_call_id"]
- for m in messages
- if m.get("role") == "tool" and m.get("tool_call_id")
+ m["tool_call_id"] for m in messages if m.get("role") == "tool" and m.get("tool_call_id")
}
# Collect all tool_call ids declared by assistant messages
@@ -788,7 +800,10 @@ def _parse_image_data_uri(result: str) -> tuple[str, str] | None:
def _append_tool_to_messages(
- messages: list[dict], event: dict, result: str, provider: str,
+ messages: list[dict],
+ event: dict,
+ result: str,
+ provider: str,
reasoning_items: list[dict] | None = None,
):
"""Append a tool call + result to the message history for the next API call."""
@@ -942,6 +957,49 @@ def _scrub_incomplete_items(output_items: list[dict]) -> None:
item["status"] = "failed"
+def _reasoning_text_len(item: dict) -> int:
+ """Return displayable reasoning text length for diagnostics."""
+ blocks = item.get("summary") or item.get("content") or []
+ if not isinstance(blocks, list):
+ return 0
+ return sum(len(block.get("text") or "") for block in blocks if isinstance(block, dict))
+
+
+def _output_debug_stats(output_items: list[dict] | None) -> tuple[dict[str, int], int, int]:
+ """Return output type counts plus reasoning count/text length."""
+ counts: dict[str, int] = {}
+ reasoning_count = 0
+ reasoning_chars = 0
+ for item in output_items or []:
+ itype = item.get("type", "?")
+ counts[itype] = counts.get(itype, 0) + 1
+ if itype == "reasoning":
+ reasoning_count += 1
+ reasoning_chars += _reasoning_text_len(item)
+ return counts, reasoning_count, reasoning_chars
+
+
+def _output_item_key(item: dict) -> tuple | None:
+ """Stable key for Responses-style output item updates."""
+ if item.get("id"):
+ return ("id", item["id"])
+ if item.get("type") and item.get("call_id"):
+ return ("call", item["type"], item["call_id"])
+ return None
+
+
+def _upsert_output_item(items: list[dict], item: dict) -> bool:
+ """Insert or replace a Responses-style output item by id/call_id."""
+ key = _output_item_key(item)
+ if key is not None:
+ for idx, existing in enumerate(items):
+ if _output_item_key(existing) == key:
+ items[idx] = item
+ return False
+ items.append(item)
+ return True
+
+
def _find_safe_split(messages: list[dict], target_keep: int) -> int:
"""Find a safe split index that doesn't break tool call pairs.
@@ -1067,6 +1125,9 @@ async def run_chat_task(
nonlocal text_buffer
if not text_buffer:
return None
+ if not text_buffer.strip():
+ text_buffer = ""
+ return None
logger.info(
"[task %s] flush_text: %d chars into message item", message_id[:8], len(text_buffer)
)
@@ -1086,11 +1147,34 @@ async def run_chat_task(
"""Update in-memory state so API can serve it on refresh."""
_task_state[message_id] = {"content": content, "output": output_items}
+ async def _save_message(save_reason: str, **kwargs) -> bool:
+ """Persist a message update and log enough detail to debug skipped saves."""
+ saved_output = kwargs.get("output", output_items)
+ saved_content = kwargs.get("content", content)
+ counts, reasoning_count, reasoning_chars = _output_debug_stats(saved_output)
+ logger.info(
+ "[task %s] db save (%s) begin: done=%s content=%d chars output=%d items reasoning=%d items/%d chars types=%s",
+ message_id[:8],
+ save_reason,
+ kwargs.get("done", ""),
+ len(saved_content or ""),
+ len(saved_output or []),
+ reasoning_count,
+ reasoning_chars,
+ counts,
+ )
+ saved = await ChatMessage.update(message_id, **kwargs)
+ log = logger.info if saved else logger.warning
+ log("[task %s] db save (%s) result: updated=%s", message_id[:8], save_reason, saved)
+ return saved
+
try:
provider = connection["provider"]
api_key = decrypt_key(connection.get("api_key", ""), _get_jwt_secret())
base_url = connection.get("base_url") or _default_base_url(provider)
+ chat_obj = await Chat.get_by_id(chat_id)
+ chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
system = await _load_system_prompt(workspace, model)
messages, loaded_summary = await _load_message_history(chat_id, message_id)
if loaded_summary:
@@ -1105,12 +1189,10 @@ async def run_chat_task(
tools = [t for t in tools if t["name"] != "view_skill"]
# Strip delegate_task from sub-agent chats (depth limit = 1)
- chat_obj = await Chat.get_by_id(chat_id)
if chat_obj and (chat_obj.meta or {}).get("subagent"):
tools = [t for t in tools if t["name"] != "delegate_task"]
# Parse $skill-name mentions from the user message to auto-activate skills
- chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
attached_skill_ids: list[str] = []
if skills and messages:
# Find the last user message
@@ -1135,6 +1217,8 @@ async def run_chat_task(
if skill_blocks:
system += "\n\n" + "\n\n".join(skill_blocks)
+ system = await _apply_voice_mode_system_prompt(system, chat_params)
+
# Plan mode: strip write tools, inject prompt as user message (not system, to preserve cache)
plan_mode = chat_params.get("plan_mode", False)
if plan_mode:
@@ -1206,6 +1290,7 @@ async def run_chat_task(
skill_blocks.append(format_skill_content(skill))
if skill_blocks:
system += "\n\n" + "\n\n".join(skill_blocks)
+ system = await _apply_voice_mode_system_prompt(system, chat_params)
messages = keep_zone
last_usage = None # reset after compaction
new_messages_since = 0
@@ -1272,7 +1357,8 @@ async def run_chat_task(
restart = False
pending_calls: list[dict] = [] # Collect tool calls from this response
- pending_reasoning: list[dict] = [] # Reasoning items for round-tripping
+ response_reasoning_items: list[dict] = [] # Pair with tool outputs on the next request
+ streamed_reasoning_chars = 0
async for event in stream:
if event["type"] == "text_delta":
@@ -1285,9 +1371,30 @@ async def run_chat_task(
# Collect tool call — don't execute yet
pending_calls.append(event)
- elif event["type"] == "reasoning":
- # Collect reasoning items for round-tripping with tool calls
- pending_reasoning.append(event["item"])
+ elif event["type"] in ("output", "reasoning"):
+ # Providers stream normalized Responses-style output items.
+ # "reasoning" is kept temporarily for compatibility with older
+ # provider adapters.
+ item = event["item"]
+ _upsert_output_item(output_items, item)
+ if item.get("type") == "reasoning":
+ streamed_reasoning_chars = max(
+ streamed_reasoning_chars,
+ _reasoning_text_len(item),
+ )
+ if item.get("status") in (None, "completed"):
+ _upsert_output_item(response_reasoning_items, item)
+ logger.info(
+ "[task %s] output item: type=%s status=%s output=%d items reasoning_chars=%d response_reasoning_items=%d",
+ message_id[:8],
+ item.get("type"),
+ item.get("status"),
+ len(output_items),
+ streamed_reasoning_chars,
+ len(response_reasoning_items),
+ )
+ _sync_state()
+ await emit(output=item)
elif event["type"] == "usage":
usage = {k: v for k, v in event.items() if k != "type"}
@@ -1301,15 +1408,14 @@ async def run_chat_task(
if not pending_calls:
# No tool calls — final response, we're done
_flush_text()
- logger.info(
- "[task %s] save (usage): content=%d chars, output=%d items, types=%s",
- message_id[:8],
- len(content),
- len(output_items),
- [i.get("type") for i in output_items],
- )
- await ChatMessage.update(
- message_id,
+ if streamed_reasoning_chars and not response_reasoning_items:
+ logger.warning(
+ "[task %s] reasoning output streamed (%d chars) but no completed reasoning item arrived before usage; DB output may contain only in-progress reasoning",
+ message_id[:8],
+ streamed_reasoning_chars,
+ )
+ await _save_message(
+ "usage",
content=content,
output=output_items,
usage=usage,
@@ -1320,11 +1426,36 @@ async def run_chat_task(
return
elif event["type"] == "done":
- # Stream ended without explicit usage
- pass
+ # Stream ended — if usage already triggered a save+return, we won't
+ # reach here. This is the fallback for providers that don't support
+ # stream_options.include_usage.
+ if not pending_calls:
+ _flush_text()
+ if streamed_reasoning_chars and not response_reasoning_items:
+ logger.warning(
+ "[task %s] reasoning output streamed (%d chars) but no completed reasoning item arrived before done; DB output may contain only in-progress reasoning",
+ message_id[:8],
+ streamed_reasoning_chars,
+ )
+ await _save_message(
+ "done fallback",
+ content=content,
+ output=output_items,
+ usage=last_usage,
+ done=True,
+ )
+ _task_state.pop(message_id, None)
+ await _emit_done()
+ return
# ── Process collected tool calls ────────────────────
if pending_calls:
+ if streamed_reasoning_chars and not response_reasoning_items:
+ logger.warning(
+ "[task %s] reasoning output streamed (%d chars) before tool calls but no completed reasoning item arrived; model continuation will not include reasoning items",
+ message_id[:8],
+ streamed_reasoning_chars,
+ )
flushed_item = _flush_text()
tool_ctx = {
@@ -1350,9 +1481,6 @@ async def run_chat_task(
if needs_approval:
# First non-auto tool stops the loop for approval
tc = needs_approval
- # Store reasoning items before function_call for round-tripping
- for ri in pending_reasoning:
- output_items.append(ri)
item = {
"type": "function_call",
"id": str(uuid.uuid4()),
@@ -1363,8 +1491,8 @@ async def run_chat_task(
"status": "pending",
}
output_items.append(item)
- await ChatMessage.update(
- message_id,
+ await _save_message(
+ "pending approval",
content=content,
output=output_items,
done=False,
@@ -1376,9 +1504,7 @@ async def run_chat_task(
await emit(done=True)
return
- # All calls are auto-approved — store reasoning + build UI items
- for ri in pending_reasoning:
- output_items.append(ri)
+ # All calls are auto-approved — build UI items
call_items: list[tuple[dict, dict]] = [] # (event, ui_item)
for tc in pending_calls:
item = {
@@ -1401,8 +1527,12 @@ async def run_chat_task(
_sync_state()
# Separate delegate_task (concurrent) from others (sequential)
- delegate_indices = [i for i, (tc, _) in enumerate(call_items) if tc["name"] == "delegate_task"]
- other_indices = [i for i, (tc, _) in enumerate(call_items) if tc["name"] != "delegate_task"]
+ delegate_indices = [
+ i for i, (tc, _) in enumerate(call_items) if tc["name"] == "delegate_task"
+ ]
+ other_indices = [
+ i for i, (tc, _) in enumerate(call_items) if tc["name"] != "delegate_task"
+ ]
# Execute non-delegate tools sequentially first
# Collect results for batch message construction
@@ -1441,8 +1571,10 @@ async def run_chat_task(
# with their shared reasoning items (required for reasoning model round-tripping)
if sequential_results:
_append_batch_to_messages(
- messages, sequential_results, provider,
- reasoning_items=pending_reasoning,
+ messages,
+ sequential_results,
+ provider,
+ reasoning_items=response_reasoning_items,
)
new_messages_since += 1 + len(sequential_results)
@@ -1487,30 +1619,25 @@ async def run_chat_task(
# Build combined message for all delegate calls
if delegate_results:
# Only attach reasoning if sequential calls didn't consume it
- ri = pending_reasoning if not other_indices else None
+ ri = response_reasoning_items if not other_indices else None
_append_batch_to_messages(
- messages, delegate_results, provider,
+ messages,
+ delegate_results,
+ provider,
reasoning_items=ri,
)
new_messages_since += 1 + len(delegate_results)
# Persist after all tool calls
- await ChatMessage.update(message_id, content=content, output=output_items)
+ await _save_message("tool calls complete", content=content, output=output_items)
restart = True
if not restart:
flushed_item = _flush_text()
if flushed_item:
await emit(output=flushed_item)
- logger.info(
- "[task %s] save (end): content=%d chars, output=%d items, types=%s",
- message_id[:8],
- len(content),
- len(output_items),
- [i.get("type") for i in output_items],
- )
- await ChatMessage.update(
- message_id,
+ await _save_message(
+ "end",
content=content,
output=output_items,
done=True,
@@ -1520,8 +1647,8 @@ async def run_chat_task(
return
# Max iterations reached
- await ChatMessage.update(
- message_id,
+ await _save_message(
+ "max iterations",
content=content,
output=output_items,
done=True,
@@ -1533,7 +1660,7 @@ async def run_chat_task(
except asyncio.CancelledError:
_flush_text()
_scrub_incomplete_items(output_items)
- await ChatMessage.update(message_id, content=content, output=output_items, done=True)
+ await _save_message("cancelled", content=content, output=output_items, done=True)
_task_state.pop(message_id, None)
await _emit_done()
except Exception as e:
@@ -1561,8 +1688,8 @@ async def run_chat_task(
if flushed_item:
await emit(output=flushed_item)
_scrub_incomplete_items(output_items)
- await ChatMessage.update(
- message_id,
+ await _save_message(
+ "error",
content=content,
output=output_items,
done=True,
diff --git a/cptr/utils/git.py b/cptr/utils/git.py
index 25499ad..d41b4ab 100644
--- a/cptr/utils/git.py
+++ b/cptr/utils/git.py
@@ -55,6 +55,10 @@ async def is_repo(root: str) -> bool:
async def status(root: str) -> dict[str, Any]:
"""Get repo status using porcelain v2 format."""
+ # Refresh Git's cached file metadata first so status catches edits whose
+ # filesystem stat information was stale.
+ await _run("update-index", "-q", "--refresh", cwd=root, check=False)
+
_, out, _ = await _run(
"status", "--porcelain=v2", "--branch", "--untracked-files=all", cwd=root
)
@@ -474,6 +478,12 @@ async def pull(root: str) -> dict[str, Any]:
return {"ok": code == 0, "message": (out + err).strip()}
+async def fetch(root: str) -> dict[str, Any]:
+ """Fetch remote refs without merging."""
+ code, out, err = await _run("fetch", "--prune", cwd=root, check=False)
+ return {"ok": code == 0, "message": (out + err).strip()}
+
+
async def push(
root: str,
force: bool = False,
diff --git a/cptr/utils/logger.py b/cptr/utils/logger.py
new file mode 100644
index 0000000..e1f5485
--- /dev/null
+++ b/cptr/utils/logger.py
@@ -0,0 +1,212 @@
+"""Loguru-based app, audit, and upstream diagnostic logging."""
+
+from __future__ import annotations
+
+import json
+import logging
+import sys
+import traceback
+import uuid
+from typing import Any
+
+from loguru import logger as loguru_logger
+
+from cptr.env import (
+ AUDIT_LOG_LEVEL,
+ AUDIT_LOG_PATH,
+ AUDIT_LOG_ROTATION,
+ LOG_FORMAT,
+ LOG_LEVEL,
+ LOG_UPSTREAM_REQUESTS,
+ UPSTREAM_REQUEST_LOG_PATH,
+ UPSTREAM_REQUEST_LOG_ROTATION,
+)
+
+
+_LEVELS = {
+ "CRITICAL": "critical",
+ "ERROR": "error",
+ "WARNING": "warning",
+ "INFO": "info",
+ "DEBUG": "debug",
+ "TRACE": "trace",
+}
+_AUDIT_LEVELS = {"METADATA", "REQUEST", "REQUEST_RESPONSE"}
+_configured = False
+
+
+class InterceptHandler(logging.Handler):
+ """Route stdlib logging records through Loguru."""
+
+ def emit(self, record: logging.LogRecord) -> None:
+ try:
+ level: str | int = loguru_logger.level(record.levelname).name
+ except ValueError:
+ level = record.levelno
+
+ frame = logging.currentframe()
+ depth = 2
+ while frame and frame.f_code.co_filename == logging.__file__:
+ frame = frame.f_back
+ depth += 1
+
+ loguru_logger.opt(depth=depth, exception=record.exc_info).log(
+ level, record.getMessage()
+ )
+
+
+def _json_stdout_sink(message) -> None:
+ record = message.record
+ entry: dict[str, Any] = {
+ "timestamp": record["time"].isoformat(),
+ "level": _LEVELS.get(record["level"].name, record["level"].name.lower()),
+ "message": record["message"],
+ "module": record["name"],
+ "function": record["function"],
+ "line": record["line"],
+ }
+ if record["extra"]:
+ entry["extra"] = record["extra"]
+ if record["exception"]:
+ exc = record["exception"]
+ entry["error"] = {
+ "type": exc.type.__name__ if exc.type else None,
+ "message": str(exc.value) if exc.value else None,
+ "stacktrace": "".join(
+ traceback.format_exception(exc.type, exc.value, exc.traceback)
+ ).rstrip(),
+ }
+ sys.stdout.write(json.dumps(entry, ensure_ascii=False, default=str) + "\n")
+ sys.stdout.flush()
+
+
+def _text_stdout_format(record) -> str:
+ extra = ""
+ visible_extra = {
+ k: v
+ for k, v in record["extra"].items()
+ if k not in {"auditable", "upstream_diagnostic"}
+ }
+ if visible_extra:
+ extra = " - {extra[extra_json]}"
+ record["extra"]["extra_json"] = json.dumps(visible_extra, ensure_ascii=False, default=str)
+ return (
+ "{time:YYYY-MM-DD HH:mm:ss.SSS} | "
+ "{level: <8} | "
+ "{name}:{function}:{line} - "
+ "{message}"
+ f"{extra}\n{{exception}}"
+ )
+
+
+def _audit_format(record) -> str:
+ extra = record["extra"]
+ entry = {
+ "id": extra.get("id", ""),
+ "timestamp": extra.get("timestamp") or record["time"].isoformat(),
+ "audit_level": extra.get("audit_level", ""),
+ "user": extra.get("user") or {},
+ "method": extra.get("method", ""),
+ "path": extra.get("path", ""),
+ "status_code": extra.get("status_code"),
+ "source_ip": extra.get("source_ip"),
+ "user_agent": extra.get("user_agent"),
+ "request_body": extra.get("request_body"),
+ "response_body": extra.get("response_body"),
+ }
+ record["extra"]["file_json"] = json.dumps(entry, ensure_ascii=False, default=str)
+ return "{extra[file_json]}\n"
+
+
+def _upstream_format(record) -> str:
+ extra = record["extra"]
+ entry = {
+ "id": extra.get("id", ""),
+ "timestamp": extra.get("timestamp") or record["time"].isoformat(),
+ "provider": extra.get("provider", ""),
+ "endpoint": extra.get("endpoint", ""),
+ "model": extra.get("model", ""),
+ "api_type": extra.get("api_type", ""),
+ "body": extra.get("body"),
+ }
+ record["extra"]["file_json"] = json.dumps(entry, ensure_ascii=False, default=str)
+ return "{extra[file_json]}\n"
+
+
+def setup_logging() -> None:
+ """Configure stdout logging and optional file sinks once."""
+ global _configured
+ if _configured:
+ return
+ _configured = True
+
+ loguru_logger.remove()
+
+ def normal_filter(record) -> bool:
+ return not record["extra"].get("auditable") and not record["extra"].get(
+ "upstream_diagnostic"
+ )
+
+ if LOG_FORMAT == "json":
+ loguru_logger.add(_json_stdout_sink, level=LOG_LEVEL, filter=normal_filter)
+ else:
+ loguru_logger.add(
+ sys.stdout,
+ level=LOG_LEVEL,
+ format=_text_stdout_format,
+ filter=normal_filter,
+ )
+
+ if AUDIT_LOG_LEVEL in _AUDIT_LEVELS:
+ AUDIT_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
+ loguru_logger.add(
+ str(AUDIT_LOG_PATH),
+ level="INFO",
+ rotation=AUDIT_LOG_ROTATION,
+ format=_audit_format,
+ filter=lambda record: record["extra"].get("auditable") is True,
+ )
+
+ if LOG_UPSTREAM_REQUESTS:
+ UPSTREAM_REQUEST_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
+ loguru_logger.add(
+ str(UPSTREAM_REQUEST_LOG_PATH),
+ level="INFO",
+ rotation=UPSTREAM_REQUEST_LOG_ROTATION,
+ format=_upstream_format,
+ filter=lambda record: record["extra"].get("upstream_diagnostic") is True,
+ )
+
+ logging.basicConfig(handlers=[InterceptHandler()], level=LOG_LEVEL, force=True)
+ for name in ("uvicorn", "uvicorn.error", "uvicorn.access"):
+ uvicorn_logger = logging.getLogger(name)
+ uvicorn_logger.handlers = [InterceptHandler()]
+ uvicorn_logger.setLevel(LOG_LEVEL)
+
+ loguru_logger.info("logging configured")
+
+
+def audit_logger():
+ return loguru_logger.bind(auditable=True)
+
+
+def log_upstream_request(
+ *,
+ provider: str,
+ endpoint: str,
+ model: str,
+ api_type: str,
+ body: dict,
+) -> None:
+ """Write an exact upstream request body to the diagnostic sink when enabled."""
+ if not LOG_UPSTREAM_REQUESTS:
+ return
+ loguru_logger.bind(
+ upstream_diagnostic=True,
+ id=str(uuid.uuid4()),
+ provider=provider,
+ endpoint=endpoint,
+ model=model,
+ api_type=api_type,
+ body=body,
+ ).info("")
diff --git a/cptr/utils/workspace.py b/cptr/utils/workspace.py
new file mode 100644
index 0000000..c71ae34
--- /dev/null
+++ b/cptr/utils/workspace.py
@@ -0,0 +1,28 @@
+"""Workspace filesystem helpers."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+
+def ensure_cptr_gitignored(workspace: str | Path) -> None:
+ """If workspace is a git repo, ensure .cptr is listed in .gitignore."""
+ ws = Path(workspace)
+ if not (ws / ".git").exists():
+ return
+
+ gitignore = ws / ".gitignore"
+ entry = ".cptr"
+
+ if gitignore.exists():
+ content = gitignore.read_text(encoding="utf-8", errors="replace")
+ for line in content.splitlines():
+ stripped = line.strip()
+ if stripped == entry or stripped == entry + "/":
+ return
+ if content and not content.endswith("\n"):
+ content += "\n"
+ content += f"{entry}\n"
+ gitignore.write_text(content, encoding="utf-8")
+ else:
+ gitignore.write_text(f"{entry}\n", encoding="utf-8")
diff --git a/pyproject.toml b/pyproject.toml
index 2bf891a..7a1b032 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "cptr"
-version = "0.4.10"
+version = "0.5.0"
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
license = {file = "LICENSE"}
readme = "README.md"
@@ -16,6 +16,7 @@ dependencies = [
"alembic>=1.13",
"PyJWT>=2.8",
"cryptography>=42.0",
+ "loguru>=0.7.3",
"python-socketio[asgi]>=5.11",
"python-dateutil>=2.8",
"truststore>=0.10",
diff --git a/uv.lock b/uv.lock
index 4bd3d59..a6fba69 100644
--- a/uv.lock
+++ b/uv.lock
@@ -265,7 +265,7 @@ wheels = [
[[package]]
name = "cptr"
-version = "0.4.3"
+version = "0.4.10"
source = { editable = "." }
dependencies = [
{ name = "aiosqlite" },
@@ -275,6 +275,7 @@ dependencies = [
{ name = "cryptography" },
{ name = "fastapi", extra = ["standard"] },
{ name = "httpx" },
+ { name = "loguru" },
{ name = "pyjwt" },
{ name = "python-dateutil" },
{ name = "python-socketio" },
@@ -311,6 +312,7 @@ requires-dist = [
{ name = "cryptography", specifier = ">=42.0" },
{ name = "fastapi", extras = ["standard"], specifier = ">=0.128.8" },
{ name = "httpx", specifier = ">=0.28.1" },
+ { name = "loguru", specifier = ">=0.7.3" },
{ name = "mcp", marker = "extra == 'mcp'", specifier = ">=1.8" },
{ name = "openpyxl", marker = "extra == 'docs'", specifier = ">=3.1" },
{ name = "pyjwt", specifier = ">=2.8" },
@@ -806,6 +808,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437 },
]
+[[package]]
+name = "loguru"
+version = "0.7.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+ { name = "win32-setctime", marker = "sys_platform == 'win32'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/3a/05/a1dae3dffd1116099471c643b8924f5aa6524411dc6c63fdae648c4f1aca/loguru-0.7.3.tar.gz", hash = "sha256:19480589e77d47b8d85b2c827ad95d49bf31b0dcde16593892eb51dd18706eb6", size = 63559 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0c/29/0348de65b8cc732daa3e33e67806420b2ae89bdce2b04af740289c5c6c8c/loguru-0.7.3-py3-none-any.whl", hash = "sha256:31a33c10c8e1e10422bfd431aeb5d351c7cf7fa671e3c4df004162264b28220c", size = 61595 },
+]
+
[[package]]
name = "lxml"
version = "6.1.1"
@@ -2686,6 +2701,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/6f/28/258ebab549c2bf3e64d2b0217b973467394a9cea8c42f70418ca2c5d0d2e/websockets-16.0-py3-none-any.whl", hash = "sha256:1637db62fad1dc833276dded54215f2c7fa46912301a24bd94d45d46a011ceec", size = 171598 },
]
+[[package]]
+name = "win32-setctime"
+version = "1.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/b3/8f/705086c9d734d3b663af0e9bb3d4de6578d08f46b1b101c2442fd9aecaa2/win32_setctime-1.2.0.tar.gz", hash = "sha256:ae1fdf948f5640aae05c511ade119313fb6a30d7eabe25fef9764dca5873c4c0", size = 4867 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e1/07/c6fe3ad3e685340704d314d765b7912993bcb8dc198f0e7a89382d37974b/win32_setctime-1.2.0-py3-none-any.whl", hash = "sha256:95d644c4e708aba81dc3704a116d8cbc974d70b3bdb8be1d150e36be6e9d1390", size = 4083 },
+]
+
[[package]]
name = "wsproto"
version = "1.2.0"