This commit is contained in:
Timothy Jaeryang Baek committed 2026-08-05 05:12:14 -05:00
1 parent 288223204d
commit 22b29c6358
34 files changed
+2325 -1360

No files matched your search

+85 -82
View File
@@ -21,7 +21,7 @@ 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
from cptr.utils.runtime import Runtime, FileError
logger = logging.getLogger(__name__)
@@ -69,19 +69,21 @@ def _get_user(request: Request) -> str:
return auth.user_id
def _workspace_audio_cache_dir(workspace: str | None, kind: str) -> Path | None:
async def _workspace_audio_cache_dir(
request: Request, 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. By default,
# ensure_cptr_gitignored keeps them out of git.
if not workspace:
return None
ws = Path(workspace).expanduser().resolve()
if not ws.is_dir():
try:
listing = await Runtime.list_directory(request, workspace)
except FileError:
return None
ws = Path(listing["path"])
cache_dir = ws / ".cptr" / "cache" / "audio" / kind
cache_dir.mkdir(parents=True, exist_ok=True)
ensure_cptr_gitignored(ws)
return cache_dir
@@ -97,17 +99,8 @@ def _cache_key(payload: dict, data: bytes | None = None) -> str:
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 _cache_json(data: dict) -> str:
return json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
def _audio_extension(filename: str, content_type: str, fallback: str = ".webm") -> str:
@@ -246,8 +239,8 @@ async def _transcribe_chunk(
@router.post("/transcribe")
async def transcribe(
file: UploadFile,
request: Request,
file: UploadFile,
workspace: str | None = Form(None),
text: str | None = Form(None),
source: str | None = Form(None),
@@ -263,7 +256,7 @@ async def transcribe(
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_dir = await _workspace_audio_cache_dir(request, workspace, "stt")
cache_json_path: Path | None = None
cache_audio_path: Path | None = None
provided_text = (text or "").strip()
@@ -290,10 +283,11 @@ async def transcribe(
)
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,
await Runtime.write_file(request, str(cache_audio_path), raw_data)
await Runtime.write_file(
request,
str(cache_json_path),
_cache_json(
{
"type": "stt",
"source": source or "browser_speech_recognition",
@@ -303,8 +297,9 @@ async def transcribe(
"filename": filename,
"content_type": content_type,
"language": language,
},
)
}
),
)
return {"text": provided_text, "cached": True}
api_key_encrypted = await Config.get("audio.stt_api_key")
@@ -336,12 +331,12 @@ async def transcribe(
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
try:
cached_file = await Runtime.read_file(request, str(cache_json_path))
cached = json.loads(str(cached_file.get("content") or ""))
return {"text": str(cached.get("text") or ""), "cached": True}
except (FileError, json.JSONDecodeError):
pass
# Small file: send directly, no temp files needed
if len(raw_data) <= MAX_FILE_SIZE or not HAS_PYDUB:
@@ -350,18 +345,21 @@ async def transcribe(
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,
},
await Runtime.write_file(request, str(cache_audio_path), raw_data)
await Runtime.write_file(
request,
str(cache_json_path),
_cache_json(
{
"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:
@@ -402,18 +400,21 @@ async def transcribe(
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,
},
await Runtime.write_file(request, str(cache_audio_path), raw_data)
await Runtime.write_file(
request,
str(cache_json_path),
_cache_json(
{
"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}
@@ -491,7 +492,7 @@ async def speech(request: Request, body: SpeechRequest):
"voice": voice,
"response_format": fmt,
}
cache_dir = _workspace_audio_cache_dir(body.workspace, "tts")
cache_dir = await _workspace_audio_cache_dir(request, body.workspace, "tts")
cache_audio_path: Path | None = None
cache_json_path: Path | None = None
if cache_dir:
@@ -511,19 +512,18 @@ async def speech(request: Request, body: SpeechRequest):
)
cache_audio_path = cache_dir / f"{key}.{fmt}"
cache_json_path = cache_dir / f"{key}.json"
if cache_audio_path.exists():
try:
if cache_audio_path.stat().st_size <= 0:
cache_audio_path.unlink(missing_ok=True)
cache_json_path.unlink(missing_ok=True)
else:
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:
cached_audio = await Runtime.read_bytes(request, str(cache_audio_path))
if cached_audio["data"]:
return Response(
content=cached_audio["data"],
media_type=_audio_media_type(str(fmt)),
headers={"X-CPTR-Audio-Cache": "hit"},
)
await Runtime.delete_item(request, str(cache_audio_path))
await Runtime.delete_item(request, str(cache_json_path))
except FileError:
pass
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(120)) as client:
@@ -548,19 +548,22 @@ async def speech(request: Request, body: SpeechRequest):
cache_state = "disabled"
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)),
},
await Runtime.write_file(request, str(cache_audio_path), resp.content)
await Runtime.write_file(
request,
str(cache_json_path),
_cache_json(
{
"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)),
}
),
)
cache_state = "write"
+5 -1
View File
@@ -151,7 +151,11 @@ async def login(request: Request, body: LoginRequest):
user_id = await get_or_create_user(body.username)
user = await User.get_by_id(user_id)
if user and user.role == "pending":
return JSONResponse({"error": "account pending approval"}, 403)
role = (
"admin" if not any(u["role"] == "admin" for u in await User.list_all()) else "user"
)
await User.update_role(user_id, role)
user.role = role
return _ok_with_cookie(
create_token(user_id, body.username, role=user.role if user else "user"),
{"ok": True, "username": body.username},
+39 -19
View File
@@ -18,8 +18,8 @@ from cptr.models import Chat, ChatMessage, Config, is_internal_chat
from cptr.utils.config import check_access, now_ms, _get_jwt_secret
from cptr.utils.crypto import decrypt_key
from cptr.utils.db import get_db
from cptr.utils.workspace import ensure_cptr_gitignored
from cptr.utils.chat_export import chat_directory
from cptr.utils.runtime import Runtime, FileError
log = logging.getLogger(__name__)
@@ -797,7 +797,7 @@ class UpdateChatSettingsRequest(BaseModel):
@router.patch("/{chat_id}")
async def update_chat(chat_id: str, body: UpdateChatRequest, request: Request):
async def update_chat(request: Request, chat_id: str, body: UpdateChatRequest):
"""Rename a chat."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
@@ -831,7 +831,7 @@ async def update_chat(chat_id: str, body: UpdateChatRequest, request: Request):
@router.patch("/{chat_id}/settings")
async def update_chat_settings(chat_id: str, body: UpdateChatSettingsRequest, request: Request):
async def update_chat_settings(request: Request, chat_id: str, body: UpdateChatSettingsRequest):
"""Save composer settings for one chat."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
@@ -846,7 +846,7 @@ async def update_chat_settings(chat_id: str, body: UpdateChatSettingsRequest, re
@router.delete("/{chat_id}")
async def delete_chat(chat_id: str, request: Request):
async def delete_chat(request: Request, chat_id: str):
"""Delete a chat and all its messages."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
@@ -856,11 +856,23 @@ async def delete_chat(chat_id: str, request: Request):
# Remove the workspace chat file and durable internal children.
workspace = chat.meta.get("workspace") if chat.meta else None
chat_file = chat_directory(workspace) / f"{chat_id}.json"
await asyncio.to_thread(chat_file.unlink, True) # missing_ok=True
if workspace:
try:
await Runtime.delete_item(request, str(chat_file))
except FileError:
pass
else:
await asyncio.to_thread(chat_file.unlink, True) # missing_ok=True
for child in await Chat.get_internal_descendants(chat_id):
child_workspace = (child.meta or {}).get("workspace")
child_file = chat_directory(child_workspace) / f"{child.id}.json"
await asyncio.to_thread(child_file.unlink, True)
if child_workspace:
try:
await Runtime.delete_item(request, str(child_file))
except FileError:
pass
else:
await asyncio.to_thread(child_file.unlink, True)
await Chat.delete(chat_id)
from cptr.socket.main import emit_to_user
@@ -885,7 +897,7 @@ class ForkChatRequest(BaseModel):
@router.post("/{chat_id}/fork")
async def fork_chat(chat_id: str, request: Request, body: ForkChatRequest | None = None):
async def fork_chat(request: Request, chat_id: str, body: ForkChatRequest | None = None):
"""Clone a completed chat branch through the selected message."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
@@ -974,7 +986,7 @@ class CompactRequest(BaseModel):
@router.post("")
async def send_message(body: SendMessageRequest, request: Request):
async def send_message(request: Request, body: SendMessageRequest):
"""Send a message. Omit chat_id to create a new chat.
Returns: { chat_id, message_id, queued? }
"""
@@ -1012,11 +1024,15 @@ async def send_message(body: SendMessageRequest, request: Request):
meta=meta,
created_at=now_ms(),
)
chats_dir = chat_directory(workspace)
await asyncio.to_thread(lambda: chats_dir.mkdir(parents=True, exist_ok=True))
if workspace:
await asyncio.to_thread(ensure_cptr_gitignored, workspace)
await Runtime.write_file(
request,
str(chat_directory(workspace) / f"{chat.id}.json"),
"{}",
)
else:
chats_dir = chat_directory(workspace)
await asyncio.to_thread(lambda: chats_dir.mkdir(parents=True, exist_ok=True))
from cptr.utils.chat_task import (
get_pending_input_lock,
@@ -1098,6 +1114,7 @@ async def send_message(body: SendMessageRequest, request: Request):
await export_chat_to_file(chat.id)
start_task(
request,
message_id=assistant_msg.id,
chat_id=chat.id,
user_id=user_id,
@@ -1122,7 +1139,7 @@ async def send_message(body: SendMessageRequest, request: Request):
@router.post("/{chat_id}/compact")
async def compact_chat(chat_id: str, body: CompactRequest, request: Request):
async def compact_chat(request: Request, chat_id: str, body: CompactRequest):
"""Summarize older active-branch messages and store a compaction checkpoint."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
@@ -1251,6 +1268,7 @@ async def resolve_ask_user(
)
target = await resolve_model_target(msg.model or "", app.state)
start_task(
None,
message_id=message_id,
chat_id=chat_id,
user_id=chat.user_id,
@@ -1281,7 +1299,7 @@ async def answer_ask_user(
@router.post("/{chat_id}/messages/{message_id}/approve")
async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, request: Request):
async def approve_tool(request: Request, chat_id: str, message_id: str, body: ApproveRequest):
"""Execute or reject a pending tool call, then continue."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
@@ -1340,6 +1358,7 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ
from cptr.utils.chat_task import start_task
start_task(
request,
message_id=message_id,
chat_id=chat_id,
user_id=user_id,
@@ -1354,7 +1373,7 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ
@router.post("/{chat_id}/messages/{message_id}/cancel")
async def cancel_task_endpoint(chat_id: str, message_id: str, request: Request):
async def cancel_task_endpoint(request: Request, chat_id: str, message_id: str):
"""Cancel running task, preserve partial output."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
@@ -1393,7 +1412,7 @@ class UpdateCurrentRequest(BaseModel):
@router.post("/{chat_id}/current")
async def update_current(chat_id: str, body: UpdateCurrentRequest, request: Request):
async def update_current(request: Request, chat_id: str, body: UpdateCurrentRequest):
"""Set current_message_id (the active branch leaf)."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
@@ -1442,7 +1461,7 @@ class CreateMessageRequest(BaseModel):
@router.post("/{chat_id}/messages")
async def create_message_endpoint(chat_id: str, body: CreateMessageRequest, request: Request):
async def create_message_endpoint(request: Request, chat_id: str, body: CreateMessageRequest):
"""Create a message without starting a task (for Save As Copy)."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
@@ -1476,7 +1495,7 @@ def _should_queue_for_parent(parent_msg: ChatMessage | None) -> bool:
@router.post("/{chat_id}/queue/{message_id}/send")
async def queue_send_now(chat_id: str, message_id: str, request: Request):
async def queue_send_now(request: Request, chat_id: str, message_id: str):
"""Dequeue one message and send it immediately on its stored branch."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
@@ -1529,6 +1548,7 @@ async def queue_send_now(chat_id: str, message_id: str, request: Request):
await Chat.update_current_message(chat_id, assistant_msg.id, now_ms())
start_task(
request,
message_id=assistant_msg.id,
chat_id=chat_id,
user_id=user_id,
@@ -1539,7 +1559,7 @@ async def queue_send_now(chat_id: str, message_id: str, request: Request):
@router.delete("/{chat_id}/queue/{message_id}")
async def queue_delete(chat_id: str, message_id: str, request: Request):
async def queue_delete(request: Request, chat_id: str, message_id: str):
"""Remove a queued message."""
user_id = _get_user(request)
chat = await Chat.get_by_id(chat_id)
+52 -34
View File
@@ -29,10 +29,11 @@ from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from cptr.models import Chat, ChatMessage, Config
from cptr.models import Auth, Chat, ChatMessage, Config
from cptr.models.workspaces import Workspace
from cptr.utils.agents.prompts import message_text
from cptr.utils.config import now_ms
from cptr.utils.config import AuthResult, now_ms
from cptr.utils.runtime import Runtime, FileError
logger = logging.getLogger(__name__)
@@ -90,6 +91,11 @@ async def _authenticate(request: Request) -> str:
user_id = key.get("user_id")
if not user_id:
raise HTTPException(500, "API key has no user_id")
auth_row = await Auth.get_by_user_id(user_id)
request.state.auth = AuthResult(
user_id=user_id,
username=auth_row.username if auth_row else None,
)
return user_id
raise HTTPException(401, "Invalid API key")
@@ -168,7 +174,7 @@ async def create_chat_completion(request: Request, body: ChatCompletionRequest):
workspace = await _resolve_workspace(user_id, body.model)
# 2. Resolve the selected model target for this workspace.
target, model_id = await _resolve_model(workspace, request.app.state)
target, model_id = await _resolve_model(request, workspace, request.app.state)
# Intercept OWUI utility tasks (follow-ups, title gen, tags gen).
# These should go directly to the LLM, not through the agentic loop.
@@ -179,7 +185,7 @@ async def create_chat_completion(request: Request, body: ChatCompletionRequest):
# 3. Session mapping: find or create a cptr chat
client_chat_id = request.headers.get(CHAT_ID_HEADER) or request.headers.get(OWUI_CHAT_ID_HEADER)
chat_id = await _ensure_chat(
user_id, workspace, client_chat_id, body.messages, model_id
request, user_id, workspace, client_chat_id, body.messages, model_id
)
# 4. Resolve message tree — map OWUI message IDs to cptr message IDs
@@ -195,13 +201,16 @@ async def create_chat_completion(request: Request, body: ChatCompletionRequest):
# Export JSON so cptr sidebar sees it immediately
from cptr.utils.chat_export import export_chat_to_file
await export_chat_to_file(chat_id)
# 5. Create output queue and start the agentic loop
output_queue: asyncio.Queue = asyncio.Queue()
from cptr.utils.chat_task import start_task
start_task(
request,
message_id=assistant_msg.id,
chat_id=chat_id,
user_id=user_id,
@@ -232,11 +241,13 @@ async def create_chat_completion(request: Request, body: ChatCompletionRequest):
"object": "chat.completion",
"created": created,
"model": body.model,
"choices": [{
"index": 0,
"message": {"role": "assistant", "content": full_text},
"finish_reason": "stop",
}],
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": full_text},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": 0,
"completion_tokens": 0,
@@ -514,10 +525,8 @@ async def _intercept_task(
task_header = request.headers.get(OWUI_TASK_HEADER, "").strip()
if task_header:
logger.info("[gateway] Detected utility task via header: %s", task_header)
utility_target = await _resolve_utility_model(workspace, request.app.state)
return await _proxy_to_llm(
body, utility_target.connection, utility_target.runtime_model
)
utility_target = await _resolve_utility_model(request, workspace, request.app.state)
return await _proxy_to_llm(body, utility_target.connection, utility_target.runtime_model)
# 2. Message content pattern matching (fallback)
if not body.messages:
@@ -533,10 +542,8 @@ async def _intercept_task(
return None
logger.info("[gateway] Detected utility task via content matching")
utility_target = await _resolve_utility_model(workspace, request.app.state)
return await _proxy_to_llm(
body, utility_target.connection, utility_target.runtime_model
)
utility_target = await _resolve_utility_model(request, workspace, request.app.state)
return await _proxy_to_llm(body, utility_target.connection, utility_target.runtime_model)
async def _proxy_to_llm(
@@ -572,11 +579,13 @@ async def _proxy_to_llm(
"object": "chat.completion",
"created": int(time.time()),
"model": body.model,
"choices": [{
"index": 0,
"message": {"role": "assistant", "content": result or ""},
"finish_reason": "stop",
}],
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": result or ""},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": 0,
"completion_tokens": 0,
@@ -618,7 +627,7 @@ async def _resolve_workspace(user_id: str, model_id: str) -> str:
# ── Model connection resolution ──────────────────────────────
async def _resolve_model(workspace: str, app_state=None):
async def _resolve_model(request: Request, workspace: str, app_state=None):
"""Find a model target to use for the agentic loop.
Priority:
@@ -643,10 +652,12 @@ async def _resolve_model(workspace: str, app_state=None):
)
# Check for workspace-specific model override
model_file = Path(workspace) / ".cptr" / "model"
model_override = None
if model_file.is_file():
model_override = model_file.read_text().strip()
try:
model = await Runtime.read_file(request, str(Path(workspace) / ".cptr" / "model"))
model_override = str(model.get("content") or "").strip()
except FileError:
model_override = None
if model_override:
try:
@@ -674,20 +685,26 @@ async def _resolve_model(workspace: str, app_state=None):
return target, target.full_model_id
async def _resolve_utility_model(workspace: str, app_state=None):
async def _resolve_utility_model(request: Request, workspace: str, app_state=None):
"""Resolve an API model for gateway utility tasks."""
from cptr.utils.model_targets import ApiModelTarget, first_api_model_target, resolve_model_target
from cptr.utils.model_targets import (
ApiModelTarget,
first_api_model_target,
resolve_model_target,
)
candidates: list[str] = []
gateway_model = await Config.get("gateway.model")
if isinstance(gateway_model, str) and gateway_model.strip():
candidates.append(gateway_model.strip())
model_file = Path(workspace) / ".cptr" / "model"
if model_file.is_file():
override = model_file.read_text().strip()
try:
model = await Runtime.read_file(request, str(Path(workspace) / ".cptr" / "model"))
override = str(model.get("content") or "").strip()
if override:
candidates.append(override)
except FileError:
pass
default_model = await Config.get("chat.default_model")
if isinstance(default_model, str) and default_model.strip():
@@ -708,6 +725,7 @@ async def _resolve_utility_model(workspace: str, app_state=None):
async def _ensure_chat(
request: Request,
user_id: str,
workspace: str,
client_chat_id: str | None,
@@ -757,9 +775,9 @@ async def _ensure_chat(
)
# Ensure .cptr/chats/ dir exists and create marker file
chats_dir = Path(workspace) / ".cptr" / "chats"
chats_dir.mkdir(parents=True, exist_ok=True)
(chats_dir / f"{chat.id}.json").write_text("{}")
await Runtime.write_file(
request, str(Path(workspace) / ".cptr" / "chats" / f"{chat.id}.json"), "{}"
)
return chat.id
+9 -9
View File
@@ -3,13 +3,13 @@
from __future__ import annotations
import asyncio
from pathlib import Path
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Query, Request
from cptr.models import Chat, is_internal_chat
from cptr.routers.workspace import walk_and_rank_files
from cptr.utils.runtime import Runtime
from cptr.utils.runtime import FileError
router = APIRouter(prefix="/api/search", tags=["search"])
@@ -57,16 +57,16 @@ async def unified_search(
per_ws_limit = max(3, file_limit // max(len(ws_paths), 1))
for ws in ws_paths:
root = Path(ws).resolve()
if not root.exists() or not root.is_dir():
try:
results = await Runtime.search_files(request, q, ws, per_ws_limit)
except FileError:
continue
results = await asyncio.to_thread(walk_and_rank_files, root, q, per_ws_limit)
for r in results:
for r in results["results"]:
all_results.append(
{
"path": r.path,
"name": r.name,
"type": r.type,
"path": r["path"],
"name": r["name"],
"type": r["type"],
"workspace": ws,
}
)
+42 -21
View File
@@ -15,6 +15,7 @@ from fastapi import APIRouter, HTTPException, Request, Query
from cptr.env import DATA_DIR
from cptr.models import Chat, UserStates, Workspace
from cptr.utils.config import get_or_create_user
from cptr.utils.identity import IdentityUnavailable, identity_for_request
router = APIRouter(prefix="/api/state", tags=["state"])
@@ -30,17 +31,30 @@ async def _get_user_id(request: Request) -> str | None:
return await get_or_create_user(auth.username)
def _resolve_workspace_path(path: str) -> str:
def _resolve_workspace_path(path: str, home: str | None = None) -> str:
"""Return the absolute, normalized workspace path."""
raw = (path or "").strip()
if not raw:
raise HTTPException(status_code=400, detail="workspace path is required")
expanded = Path(raw).expanduser()
if home and raw == "~":
expanded = Path(home)
elif home and raw.startswith("~/"):
expanded = Path(home) / raw[2:]
else:
expanded = Path(raw).expanduser()
if not expanded.is_absolute():
raise HTTPException(status_code=400, detail="workspace path must be absolute")
return str(expanded.resolve())
async def _resolve_request_workspace_path(request: Request, path: str) -> str:
try:
identity = await identity_for_request(request)
return _resolve_workspace_path(path, identity.home)
except IdentityUnavailable as exc:
raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc
def _try_resolve_workspace_path(path: str) -> str | None:
try:
return _resolve_workspace_path(path)
@@ -147,7 +161,7 @@ async def get_workspace(request: Request, path: str = Query(...)):
user_id = await _get_user_id(request)
if not user_id:
return {}
workspace_path = _resolve_workspace_path(path)
workspace_path = await _resolve_request_workspace_path(request, path)
workspace = _newest_workspace(await _workspaces_at_path(user_id, workspace_path))
if not workspace:
return {
@@ -172,7 +186,7 @@ async def put_workspace(request: Request, path: str = Query(...)):
user_id = await _get_user_id(request)
if not user_id:
return {"status": "skipped"}
workspace_path = _resolve_workspace_path(path)
workspace_path = await _resolve_request_workspace_path(request, path)
workspace_data = await request.json()
existing_workspace = _newest_workspace(await _workspaces_at_path(user_id, workspace_path))
if "name" in workspace_data:
@@ -203,7 +217,7 @@ async def delete_workspace(request: Request, path: str = Query(...)):
user_id = await _get_user_id(request)
if not user_id:
return {"status": "skipped"}
workspace_path = _resolve_workspace_path(path)
workspace_path = await _resolve_request_workspace_path(request, path)
paths = [workspace.path for workspace in await _workspaces_at_path(user_id, workspace_path)]
if workspace_path not in paths:
paths.append(workspace_path)
@@ -219,7 +233,13 @@ async def get_welcome(request: Request):
"""Return data for the welcome/landing page."""
import asyncio
system_info = await asyncio.to_thread(_collect_system_info)
try:
identity = await identity_for_request(request)
user_home = Path(identity.home)
except Exception:
user_home = Path.home()
system_info = await asyncio.to_thread(_collect_system_info, user_home)
# Recent workspaces from DB (most recently used first)
user_id = await _get_user_id(request)
@@ -242,7 +262,7 @@ async def get_welcome(request: Request):
return system_info
def _collect_system_info() -> dict:
def _collect_system_info(user_home: Path) -> dict:
"""Gather all system info synchronously. Called via asyncio.to_thread()."""
import platform
import socket
@@ -326,7 +346,7 @@ def _collect_system_info() -> dict:
# Disk
try:
disk = shutil.disk_usage(str(Path.home()))
disk = shutil.disk_usage(str(user_home))
system["disk_total"] = disk.total
system["disk_used"] = disk.used
system["disk_free"] = disk.free
@@ -522,25 +542,26 @@ def _collect_system_info() -> dict:
pass
# Suggested directories
home = str(Path.home())
home_path = user_home
home = str(home_path)
candidates = [
home,
str(Path.home() / "Documents"),
str(Path.home() / "Desktop"),
str(Path.home() / "Downloads"),
str(Path.home() / "Projects"),
str(Path.home() / "projects"),
str(Path.home() / "code"),
str(Path.home() / "Code"),
str(Path.home() / "dev"),
str(Path.home() / "workspace"),
str(Path.home() / "src"),
str(home_path / "Documents"),
str(home_path / "Desktop"),
str(home_path / "Downloads"),
str(home_path / "Projects"),
str(home_path / "projects"),
str(home_path / "code"),
str(home_path / "Code"),
str(home_path / "dev"),
str(home_path / "workspace"),
str(home_path / "src"),
]
if platform.system() == "Windows":
candidates.extend(
[
str(Path.home() / "source" / "repos"),
str(Path.home() / "OneDrive" / "Documents"),
str(home_path / "source" / "repos"),
str(home_path / "OneDrive" / "Documents"),
]
)
candidates.append(tempfile.gettempdir())
+25 -17
View File
@@ -6,10 +6,11 @@ import asyncio
import logging
from typing import List, Optional
from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
from fastapi import APIRouter, HTTPException, Request, WebSocket, WebSocketDisconnect
from pydantic import BaseModel
from cptr.utils.config import check_access
from cptr.utils.identity import IdentityUnavailable, identity_for_request
from cptr.utils.terminal import TerminalUnavailable, manager, IS_WINDOWS
from cptr.utils.tools import (
command_session_bytes_since,
@@ -54,13 +55,16 @@ class CommandSessionInfo(BaseModel):
@router.post("", response_model=SessionInfo)
async def create_session(req: CreateSessionRequest):
async def create_session(request: Request, req: CreateSessionRequest):
"""Create a new terminal session."""
logger.info(f"Creating terminal session: cwd={req.cwd}, rows={req.rows}, cols={req.cols}")
try:
session = manager.create(rows=req.rows, cols=req.cols, cwd=req.cwd)
identity = await identity_for_request(request)
session = manager.create(identity=identity, rows=req.rows, cols=req.cols, cwd=req.cwd)
except TerminalUnavailable as exc:
raise HTTPException(status_code=503, detail=str(exc)) from exc
except IdentityUnavailable as exc:
raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc
logger.info(
f"Created session {session.session_id} at {session.cwd}, fd={session._fd}, alive={session.is_alive()}"
)
@@ -68,24 +72,26 @@ async def create_session(req: CreateSessionRequest):
@router.get("", response_model=List[SessionInfo])
async def list_sessions():
async def list_sessions(request: Request):
"""List active terminal sessions."""
sessions = manager.list_sessions()
sessions = manager.list_sessions(request)
logger.debug(f"Listing sessions: {len(sessions)} active")
return [SessionInfo(**s) for s in sessions]
@router.get("/sessions", response_model=List[CommandSessionInfo])
async def list_command_session_endpoint(workspace: str | None = None, chat_id: str | None = None):
async def list_command_session_endpoint(
request: Request, workspace: str | None = None, chat_id: str | None = None
):
"""List live command sessions created by run_command."""
return [CommandSessionInfo(**s) for s in list_command_sessions(workspace, chat_id)]
return [CommandSessionInfo(**s) for s in list_command_sessions(request, workspace, chat_id)]
@router.delete("/{session_id}")
async def delete_session(session_id: str):
async def delete_session(request: Request, session_id: str):
"""Kill a terminal session."""
logger.info(f"Deleting session {session_id}")
if not manager.close(session_id):
if not manager.close(request, session_id):
raise HTTPException(status_code=404, detail="Session not found")
return {"status": "closed"}
@@ -106,8 +112,9 @@ async def command_session_ws(websocket: WebSocket, command_session_id: str):
if auth is None:
await websocket.close(code=4001, reason="unauthorized")
return
websocket.state.auth = auth
session = get_command_session(command_session_id)
session = get_command_session(websocket, command_session_id)
if not session:
await websocket.close(code=4004, reason="Command session not found")
return
@@ -128,7 +135,7 @@ async def command_session_ws(websocket: WebSocket, command_session_id: str):
offset = initial_offset
try:
while True:
session = get_command_session(command_session_id)
session = get_command_session(websocket, command_session_id)
if not session:
break
raw, offset = command_session_bytes_since(session, offset)
@@ -160,12 +167,12 @@ async def command_session_ws(websocket: WebSocket, command_session_id: str):
payload = raw[1:]
if msg_type == MSG_INPUT:
error = send_command_session_input(command_session_id, payload)
error = send_command_session_input(websocket, command_session_id, payload)
if error:
logger.debug(
"command session input ignored for %s: %s", command_session_id, error
)
await drain_command_session_input(command_session_id)
await drain_command_session_input(websocket, command_session_id)
elif msg_type == MSG_RESIZE:
try:
if len(payload) == 4:
@@ -177,15 +184,15 @@ async def command_session_ws(websocket: WebSocket, command_session_id: str):
resize_data = _json.loads(payload)
cols = resize_data.get("cols", 80)
rows = resize_data.get("rows", 24)
resize_command_session(command_session_id, rows, cols)
resize_command_session(websocket, command_session_id, rows, cols)
except (ValueError, KeyError) as e:
logger.warning(
"Invalid command-session resize payload for %s: %s", command_session_id, e
)
elif msg_type == MSG_STOP:
stop_command_session(command_session_id)
stop_command_session(websocket, command_session_id)
elif msg_type == MSG_FORCE_STOP:
stop_command_session(command_session_id, force=True)
stop_command_session(websocket, command_session_id, force=True)
except WebSocketDisconnect:
logger.info("WebSocket disconnected for command session %s", command_session_id)
except Exception as e:
@@ -216,8 +223,9 @@ async def terminal_ws(websocket: WebSocket, session_id: str):
if auth is None:
await websocket.close(code=4001, reason="unauthorized")
return
websocket.state.auth = auth
session = manager.get(session_id)
session = manager.get(websocket, session_id)
if not session:
logger.warning(f"WebSocket: session {session_id} not found")
await websocket.close(code=4004, reason="Session not found")
+156 -837
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -21,6 +21,7 @@ class AcpClient:
client_capabilities: dict[str, Any] | None = None,
resume_session_id: str | None = None,
auto_approve_permissions: bool = False,
preexec_fn=None,
) -> None:
self.command = command
self.args = args
@@ -30,6 +31,7 @@ class AcpClient:
self.client_capabilities = client_capabilities or {}
self.resume_session_id = resume_session_id
self.auto_approve_permissions = auto_approve_permissions
self.preexec_fn = preexec_fn
self.proc: asyncio.subprocess.Process | None = None
self.reader_task: asyncio.Task | None = None
self.stderr_task: asyncio.Task | None = None
@@ -50,6 +52,7 @@ class AcpClient:
stderr=asyncio.subprocess.PIPE,
cwd=self.cwd or os.getcwd(),
env=self.env,
preexec_fn=self.preexec_fn,
)
self.reader_task = asyncio.create_task(self._reader_loop())
self.stderr_task = asyncio.create_task(self._stderr_loop())
+9 -2
View File
@@ -8,6 +8,8 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any
from cptr.utils.identity import identity_for_user_id
from cptr.utils.runtime import Runtime
from cptr.utils.storage import get_storage
@@ -40,6 +42,7 @@ def _is_image(file_meta: dict[str, Any]) -> bool:
async def prepare_agent_attachments(
*,
workspace: str,
user_id: str | None,
chat_id: str,
message_id: str,
files: list[dict[str, Any]] | None,
@@ -54,11 +57,11 @@ async def prepare_agent_attachments(
/ _safe_segment(chat_id)
/ _safe_segment(message_id)
)
root.mkdir(parents=True, exist_ok=True)
images: list[AgentAttachment] = []
staged_files: list[AgentAttachment] = []
storage = get_storage()
identity = await identity_for_user_id(user_id) if user_id else None
for file_meta in files:
if not isinstance(file_meta, dict):
continue
@@ -73,7 +76,11 @@ async def prepare_agent_attachments(
name = _safe_segment(str(file_meta.get("name") or file_id))
path = root / f"{_safe_segment(file_id)}-{name}"
path.write_bytes(data)
if identity:
await Runtime.write_file(identity, str(path), data)
else:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
mime_type = str(
file_meta.get("content_type")
or file_meta.get("mime_type")
+3 -1
View File
@@ -19,6 +19,7 @@ from cptr.utils.agents.events import (
AgentToolUpdate,
)
from cptr.utils.agents.prompts import session_turn_prompt_text
from cptr.utils.identity import env_for
_claude_clients: dict[str, tuple[Any, tuple[Any, ...]]] = {}
@@ -119,6 +120,7 @@ async def run_claude_code_agent(
chat_params: dict[str, Any],
resume_state: dict[str, Any] | None,
attachments: PreparedAgentAttachments,
identity=None,
) -> AsyncIterator[AgentEvent]:
try:
import claude_agent_sdk as sdk
@@ -126,7 +128,7 @@ async def run_claude_code_agent(
yield AgentError("Claude Code support requires the claude-agent-sdk Python package")
return
env = os.environ.copy()
env = env_for(identity, workspace) if identity and identity.is_pam else os.environ.copy()
home = os.path.expanduser(str(profile["home"])) if profile.get("home") else None
if home:
env["HOME"] = home
+4 -1
View File
@@ -22,6 +22,7 @@ from cptr.utils.agents.events import (
AgentToolUpdate,
)
from cptr.utils.agents.prompts import turn_prompt_text
from cptr.utils.identity import env_for, preexec_for
def _auto_approve(chat_params: dict[str, Any]) -> bool:
@@ -40,8 +41,9 @@ async def run_cline_agent(
chat_params: dict[str, Any],
resume_state: dict[str, Any] | None,
attachments: PreparedAgentAttachments,
identity=None,
) -> AsyncIterator[AgentEvent]:
env = os.environ.copy()
env = env_for(identity, workspace) if identity and identity.is_pam else os.environ.copy()
if profile.get("home"):
env["HOME"] = os.path.expanduser(str(profile["home"]))
@@ -57,6 +59,7 @@ async def run_cline_agent(
auth_method_id=None,
resume_session_id=session_id,
auto_approve_permissions=_auto_approve(chat_params),
preexec_fn=preexec_for(identity) if identity and identity.is_pam else None,
)
try:
await client.start()
+12 -3
View File
@@ -22,16 +22,18 @@ from cptr.utils.agents.events import (
AgentToolUpdate,
)
from cptr.utils.agents.prompts import session_turn_prompt_text
from cptr.utils.identity import env_for, preexec_for
CODEX_STDOUT_CHUNK_SIZE = 64 * 1024
CODEX_MAX_WIRE_MESSAGE_CHARS = 16 * 1024 * 1024
class CodexAppServer:
def __init__(self, command: str, cwd: str, env: dict[str, str]) -> None:
def __init__(self, command: str, cwd: str, env: dict[str, str], preexec_fn=None) -> None:
self.command = command
self.cwd = cwd
self.env = env
self.preexec_fn = preexec_fn
self.proc: asyncio.subprocess.Process | None = None
self.reader_task: asyncio.Task | None = None
self.stderr_task: asyncio.Task | None = None
@@ -50,6 +52,7 @@ class CodexAppServer:
stderr=asyncio.subprocess.PIPE,
cwd=self.cwd or os.getcwd(),
env=self.env,
preexec_fn=self.preexec_fn,
)
self.reader_task = asyncio.create_task(self._reader_loop())
self.stderr_task = asyncio.create_task(self._stderr_loop())
@@ -359,12 +362,18 @@ async def run_codex_agent(
chat_params: dict[str, Any],
resume_state: dict[str, Any] | None,
attachments: PreparedAgentAttachments,
identity=None,
) -> AsyncIterator[AgentEvent]:
env = os.environ.copy()
env = env_for(identity, workspace) if identity and identity.is_pam else os.environ.copy()
if profile.get("home"):
env["CODEX_HOME"] = os.path.expanduser(str(profile["home"]))
client = CodexAppServer(str(profile["command"]), workspace, env)
client = CodexAppServer(
str(profile["command"]),
workspace,
env,
preexec_for(identity) if identity and identity.is_pam else None,
)
thread_id: str | None = None
turn_id: str | None = None
try:
+4 -1
View File
@@ -22,6 +22,7 @@ from cptr.utils.agents.events import (
AgentToolUpdate,
)
from cptr.utils.agents.prompts import turn_prompt_text
from cptr.utils.identity import env_for, preexec_for
CURSOR_CAPABILITIES = {"_meta": {"parameterizedModelPicker": True}}
@@ -43,8 +44,9 @@ async def run_cursor_agent(
chat_params: dict[str, Any],
resume_state: dict[str, Any] | None,
attachments: PreparedAgentAttachments,
identity=None,
) -> AsyncIterator[AgentEvent]:
env = os.environ.copy()
env = env_for(identity, workspace) if identity and identity.is_pam else os.environ.copy()
if profile.get("home"):
env["HOME"] = os.path.expanduser(str(profile["home"]))
@@ -67,6 +69,7 @@ async def run_cursor_agent(
client_capabilities=CURSOR_CAPABILITIES,
resume_session_id=session_id,
auto_approve_permissions=_auto_approve(chat_params),
preexec_fn=preexec_for(identity) if identity and identity.is_pam else None,
)
try:
await client.start()
+4 -1
View File
@@ -22,6 +22,7 @@ from cptr.utils.agents.events import (
AgentToolUpdate,
)
from cptr.utils.agents.prompts import turn_prompt_text
from cptr.utils.identity import env_for, preexec_for
def _auto_approve(chat_params: dict[str, Any]) -> bool:
@@ -40,8 +41,9 @@ async def run_gemini_agent(
chat_params: dict[str, Any],
resume_state: dict[str, Any] | None,
attachments: PreparedAgentAttachments,
identity=None,
) -> AsyncIterator[AgentEvent]:
env = os.environ.copy()
env = env_for(identity, workspace) if identity and identity.is_pam else os.environ.copy()
if profile.get("home"):
env["HOME"] = os.path.expanduser(str(profile["home"]))
@@ -57,6 +59,7 @@ async def run_gemini_agent(
auth_method_id="oauth-personal",
resume_session_id=session_id,
auto_approve_permissions=_auto_approve(chat_params),
preexec_fn=preexec_for(identity) if identity and identity.is_pam else None,
)
try:
await client.start()
+4 -1
View File
@@ -22,6 +22,7 @@ from cptr.utils.agents.events import (
AgentToolUpdate,
)
from cptr.utils.agents.prompts import turn_prompt_text
from cptr.utils.identity import env_for, preexec_for
def _auth_method(env: dict[str, str]) -> str:
@@ -44,8 +45,9 @@ async def run_grok_agent(
chat_params: dict[str, Any],
resume_state: dict[str, Any] | None,
attachments: PreparedAgentAttachments,
identity=None,
) -> AsyncIterator[AgentEvent]:
env = os.environ.copy()
env = env_for(identity, workspace) if identity and identity.is_pam else os.environ.copy()
if profile.get("home"):
env["HOME"] = os.path.expanduser(str(profile["home"]))
env["GROK_OAUTH2_REFERRER"] = "cptr"
@@ -62,6 +64,7 @@ async def run_grok_agent(
auth_method_id=_auth_method(env),
resume_session_id=session_id,
auto_approve_permissions=_auto_approve(chat_params),
preexec_fn=preexec_for(identity) if identity and identity.is_pam else None,
)
try:
await client.start()
+14 -4
View File
@@ -24,6 +24,7 @@ from cptr.utils.agents.events import (
AgentToolUpdate,
)
from cptr.utils.agents.prompts import turn_prompt_text
from cptr.utils.identity import env_for, preexec_for
_LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
@@ -71,13 +72,17 @@ async def _server_url_from_stdout(proc: asyncio.subprocess.Process, port: int) -
@asynccontextmanager
async def _opencode_server(profile: dict[str, Any], workspace: str):
async def _opencode_server(profile: dict[str, Any], workspace: str, identity=None):
server_url = str(profile.get("server_url") or "").strip()
if server_url:
yield server_url, None
return
env = os.environ.copy()
env = (
env_for(identity, workspace or os.getcwd())
if identity and identity.is_pam
else os.environ.copy()
)
if profile.get("home"):
env["HOME"] = os.path.expanduser(str(profile["home"]))
port = _free_port()
@@ -90,6 +95,7 @@ async def _opencode_server(profile: dict[str, Any], workspace: str):
stderr=asyncio.subprocess.PIPE,
cwd=workspace or os.getcwd(),
env={**env, "OPENCODE_CONFIG_CONTENT": "{}"},
preexec_fn=preexec_for(identity) if identity and identity.is_pam else None,
)
stderr_task = asyncio.create_task(_drain_stderr(proc))
try:
@@ -330,10 +336,11 @@ async def run_opencode_agent(
chat_params: dict[str, Any],
resume_state: dict[str, Any] | None,
attachments: PreparedAgentAttachments,
identity=None,
) -> AsyncIterator[AgentEvent]:
del chat_params
try:
async with _opencode_server(profile, workspace) as (server_url, _proc):
async with _opencode_server(profile, workspace, identity) as (server_url, _proc):
headers = _headers(profile)
urls = opencode_server_url_candidates(server_url)
last_connect_error: Exception | None = None
@@ -391,7 +398,10 @@ async def run_opencode_agent(
timeout=5,
)
status = _session_data(payload).get(session_id)
if not isinstance(status, dict) or status.get("type") == "idle":
if (
not isinstance(status, dict)
or status.get("type") == "idle"
):
break
if asyncio.get_running_loop().time() - last_activity >= 600:
raise RuntimeError(
+15 -3
View File
@@ -20,6 +20,7 @@ from cptr.utils.agents.events import (
AgentToolOutputDelta,
AgentToolUpdate,
)
from cptr.utils.identity import env_for, preexec_for
def _content_text(value: Any) -> str:
@@ -118,11 +119,14 @@ def tool_output_delta(event: dict[str, Any], sent: dict[str, str]) -> AgentToolO
class PiRpcClient:
"""Small stdio client for ``pi --mode rpc``."""
def __init__(self, command: str, cwd: str, env: dict[str, str], model: str = "") -> None:
def __init__(
self, command: str, cwd: str, env: dict[str, str], model: str = "", preexec_fn=None
) -> None:
self.command = command
self.cwd = cwd
self.env = env
self.model = model
self.preexec_fn = preexec_fn
self.proc: asyncio.subprocess.Process | None = None
self.reader_task: asyncio.Task[None] | None = None
self.stderr_task: asyncio.Task[None] | None = None
@@ -143,6 +147,7 @@ class PiRpcClient:
stderr=asyncio.subprocess.PIPE,
cwd=self.cwd or os.getcwd(),
env=self.env,
preexec_fn=self.preexec_fn,
)
self.reader_task = asyncio.create_task(self._read_stdout())
self.stderr_task = asyncio.create_task(self._read_stderr())
@@ -261,11 +266,18 @@ async def run_pi_agent(
chat_params: dict[str, Any],
resume_state: dict[str, Any] | None,
attachments: PreparedAgentAttachments,
identity=None,
) -> AsyncIterator[AgentEvent]:
env = os.environ.copy()
env = env_for(identity, workspace) if identity and identity.is_pam else os.environ.copy()
if profile.get("home"):
env["HOME"] = os.path.expanduser(str(profile["home"]))
client = PiRpcClient(str(profile.get("command") or "pi"), workspace, env, model)
client = PiRpcClient(
str(profile.get("command") or "pi"),
workspace,
env,
model,
preexec_for(identity) if identity and identity.is_pam else None,
)
session_file = (resume_state or {}).get("session_file")
resumed = isinstance(session_file, str) and bool(session_file)
+2 -2
View File
@@ -232,7 +232,7 @@ async def chat_completion(
async def generate_text(
request=None,
request,
*,
model_id: str | None,
messages: list[dict],
@@ -304,7 +304,7 @@ async def generate_text(
async def generate_json(
request=None,
request,
*,
model_id: str | None,
messages: list[dict],
+1
View File
@@ -280,6 +280,7 @@ async def _inject_completion(record: dict[str, Any]) -> None:
)
start_task(
None,
message_id=assistant_msg.id,
chat_id=parent_chat_id,
user_id=user_id,
+7 -5
View File
@@ -15,6 +15,7 @@ import logging
import random
import time
from datetime import datetime
from pathlib import Path
from typing import Optional
from dateutil.rrule import rrulestr
@@ -166,12 +167,12 @@ async def execute_automation(automation, webhook_payload: str | None = None) ->
await Chat.update_current_message(chat.id, assistant_msg.id, now_ms())
# Write .cptr/chats/{id}.json marker so list_chats discovers it
from pathlib import Path
marker = Path(workspace) / ".cptr" / "chats" / f"{chat.id}.json"
from cptr.utils.identity import identity_for_user_id
from cptr.utils.runtime import Runtime
chats_dir = Path(workspace) / ".cptr" / "chats"
chats_dir.mkdir(parents=True, exist_ok=True)
(chats_dir / f"{chat.id}.json").write_text("{}")
identity = await identity_for_user_id(automation.user_id)
await Runtime.write_file(identity, str(marker), "{}")
from cptr.utils.model_targets import resolve_model_target
@@ -181,6 +182,7 @@ async def execute_automation(automation, webhook_payload: str | None = None) ->
from cptr.utils.chat_task import start_task
start_task(
None,
message_id=assistant_msg.id,
chat_id=chat.id,
user_id=automation.user_id,
+87 -32
View File
@@ -16,6 +16,7 @@ import logging
import uuid
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from pathlib import Path
from typing import Awaitable, Callable, Optional
logger = logging.getLogger(__name__)
@@ -91,13 +92,17 @@ class BaseAdapter(ABC):
"""Show a typing indicator in the chat."""
...
async def send_photo(self, chat_id: str, data: bytes, filename: str, caption: str = "") -> str | None:
async def send_photo(
self, chat_id: str, data: bytes, filename: str, caption: str = ""
) -> str | None:
"""Send a photo. Default: falls back to send() with caption only."""
if caption:
return await self.send(chat_id, caption)
return None
async def send_document(self, chat_id: str, data: bytes, filename: str, caption: str = "") -> str | None:
async def send_document(
self, chat_id: str, data: bytes, filename: str, caption: str = ""
) -> str | None:
"""Send a file. Default: falls back to send() with caption only."""
if caption:
return await self.send(chat_id, caption)
@@ -123,20 +128,20 @@ def chunk_message(text: str, max_len: int = 4096) -> list[str]:
cut = remaining.rfind("\n\n", 0, max_len)
if cut > max_len // 4:
chunks.append(remaining[:cut])
remaining = remaining[cut + 2:]
remaining = remaining[cut + 2 :]
continue
cut = remaining.rfind("\n", 0, max_len)
if cut > max_len // 4:
chunks.append(remaining[:cut])
remaining = remaining[cut + 1:]
remaining = remaining[cut + 1 :]
continue
for sep in (". ", "! ", "? "):
cut = remaining.rfind(sep, 0, max_len)
if cut > max_len // 4:
chunks.append(remaining[: cut + 1])
remaining = remaining[cut + 2:]
remaining = remaining[cut + 2 :]
break
else:
chunks.append(remaining[:max_len])
@@ -214,9 +219,7 @@ async def find_chat_for_thread(bot_id: str, external_thread_id: str) -> str | No
best_ts = -1
async with await get_db() as db:
result = await db.execute(
select(Chat).where(Chat.user_id.isnot(None))
)
result = await db.execute(select(Chat).where(Chat.user_id.isnot(None)))
for chat in result.scalars():
meta = chat.meta or {}
if (
@@ -344,22 +347,27 @@ class BotManager:
if bot["platform"] == "telegram":
from cptr.utils.adapters.telegram import TelegramAdapter
return TelegramAdapter(token=token)
if bot["platform"] == "discord":
from cptr.utils.adapters.discord import DiscordAdapter
return DiscordAdapter(token=token)
if bot["platform"] == "slack":
from cptr.utils.adapters.slack import SlackAdapter
return SlackAdapter(token=token)
if bot["platform"] == "whatsapp":
from cptr.utils.adapters.whatsapp import WhatsAppAdapter
return WhatsAppAdapter(token=token, bot_id=bot["id"])
if bot["platform"] == "signal":
from cptr.utils.adapters.signal import SignalAdapter
return SignalAdapter(token=token)
return None
@@ -371,7 +379,9 @@ class BotManager:
# 1. Auth check
allowed = bot.get("allowed_senders") or []
if allowed and event.sender_id not in allowed:
logger.debug("Ignoring unauthorized sender %s on bot %s", event.sender_id, bot["id"][:8])
logger.debug(
"Ignoring unauthorized sender %s on bot %s", event.sender_id, bot["id"][:8]
)
return
adapter = self._adapters.get(bot["id"])
@@ -380,6 +390,7 @@ class BotManager:
# Normalize: strip Discord bot mention prefix (<@123456>)
# and Telegram command suffix (/cmd@BotName → /cmd)
import re
clean = re.sub(r"<@!?\d+>\s*", "", text).strip()
cmd = clean.split("@")[0].lower() if clean.startswith("/") else ""
@@ -398,6 +409,7 @@ class BotManager:
cancelled = False
if chat_id:
from cptr.utils.chat_task import _tasks, _task_chat, cancel_task
for mid, cid in list(_task_chat.items()):
if cid == chat_id and mid in _tasks and not _tasks[mid].done():
await cancel_task(mid)
@@ -413,20 +425,26 @@ class BotManager:
if cmd == "/retry":
from cptr.models import ChatMessage
chat_id = await find_chat_for_thread(bot["id"], event.chat_id)
if not chat_id:
if adapter:
try:
await adapter.send(event.chat_id, "No active conversation. Send a message first.")
await adapter.send(
event.chat_id, "No active conversation. Send a message first."
)
except Exception:
pass
return
# Check if a task is already running
from cptr.utils.chat_task import get_active_chat_ids
if chat_id in get_active_chat_ids():
if adapter:
try:
await adapter.send(event.chat_id, "⏳ A task is already running. Use /stop first.")
await adapter.send(
event.chat_id, "⏳ A task is already running. Use /stop first."
)
except Exception:
pass
return
@@ -461,6 +479,7 @@ class BotManager:
return
# Update bot config
from cptr.models import Config
bots_raw = await Config.get("bots") or []
for b in bots_raw:
if b.get("id") == bot["id"]:
@@ -494,6 +513,7 @@ class BotManager:
if cmd == "/workspaces":
from cptr.models import Workspace
workspaces = await Workspace.get_by_user(bot["user_id"])
if not workspaces:
if adapter:
@@ -521,6 +541,7 @@ class BotManager:
return
from cptr.models import Workspace
workspaces = await Workspace.get_by_user(bot["user_id"])
match = None
ws_lower = ws_name.lower()
@@ -537,11 +558,14 @@ class BotManager:
if not match:
if adapter:
await adapter.send(event.chat_id, f"Workspace '{ws_name}' not found. Use /workspaces to list.")
await adapter.send(
event.chat_id, f"Workspace '{ws_name}' not found. Use /workspaces to list."
)
return
# Update bot config with new workspace
from cptr.models import Config
bots_raw = await Config.get("bots") or []
for b in bots_raw:
if b.get("id") == bot["id"]:
@@ -554,7 +578,9 @@ class BotManager:
await self._create_chat(event, bot)
if adapter:
try:
await adapter.send(event.chat_id, f"✨ Switched to {match.name}\nNew conversation started.")
await adapter.send(
event.chat_id, f"✨ Switched to {match.name}\nNew conversation started."
)
except Exception:
pass
return
@@ -592,10 +618,12 @@ class BotManager:
created_at=now_ms(),
)
from pathlib import Path
chats_dir = Path(bot["workspace"]) / ".cptr" / "chats"
chats_dir.mkdir(parents=True, exist_ok=True)
(chats_dir / f"{chat.id}.json").write_text("{}")
marker = Path(bot["workspace"]) / ".cptr" / "chats" / f"{chat.id}.json"
from cptr.utils.identity import identity_for_user_id
from cptr.utils.runtime import Runtime
identity = await identity_for_user_id(bot["user_id"])
await Runtime.write_file(identity, str(marker), "{}")
return chat.id
@@ -643,7 +671,9 @@ class BotManager:
entry["type"] = "file"
file_entries.append(entry)
logger.info("[bridge] Saved attachment %s (%s, %d bytes)", att.filename, att.type, len(att.data))
logger.info(
"[bridge] Saved attachment %s (%s, %d bytes)", att.filename, att.type, len(att.data)
)
return file_entries, "\n".join(text_parts)
@@ -702,7 +732,11 @@ class BotManager:
return ""
async def _dispatch_task(
self, chat_id: str, event: MessageEvent, bot: dict, adapter: BaseAdapter | None,
self,
chat_id: str,
event: MessageEvent,
bot: dict,
adapter: BaseAdapter | None,
) -> None:
from cptr.models import Chat, ChatMessage
from cptr.utils.chat_task import start_task, _task_chat
@@ -712,7 +746,9 @@ class BotManager:
user_meta: dict | None = None
if event.attachments:
file_entries, text_prepend = await self._process_attachments(
event.attachments, adapter, event.chat_id,
event.attachments,
adapter,
event.chat_id,
)
if file_entries:
user_meta = {"files": file_entries}
@@ -727,17 +763,24 @@ class BotManager:
active_chat_ids = set(_task_chat.values())
if chat_id in active_chat_ids:
await ChatMessage.create(
chat_id=chat_id, role="user", content=event.text,
chat_id=chat_id,
role="user",
content=event.text,
parent_id=parent_id,
meta={"queued": True, **(user_meta or {})}, created_at=now_ms(),
meta={"queued": True, **(user_meta or {})},
created_at=now_ms(),
)
logger.info("[bridge] Queued message for busy chat %s", chat_id[:8])
return
# Create user message — parent_id chains to previous assistant reply
user_msg = await ChatMessage.create(
chat_id=chat_id, role="user", content=event.text,
parent_id=parent_id, meta=user_meta, created_at=now_ms(),
chat_id=chat_id,
role="user",
content=event.text,
parent_id=parent_id,
meta=user_meta,
created_at=now_ms(),
)
# Resolve model target
@@ -753,13 +796,19 @@ class BotManager:
# Create assistant placeholder
assistant_msg = await ChatMessage.create(
chat_id=chat_id, role="assistant", content="", parent_id=user_msg.id,
model=bot["model_id"], done=False, created_at=now_ms(),
chat_id=chat_id,
role="assistant",
content="",
parent_id=user_msg.id,
model=bot["model_id"],
done=False,
created_at=now_ms(),
)
await Chat.update_current_message(chat_id, assistant_msg.id, now_ms())
# Export JSON so the web UI can see the chat immediately
from cptr.utils.chat_export import export_chat_to_file
await export_chat_to_file(chat_id)
# Send initial "thinking" message for non-draft platforms (Discord)
@@ -775,13 +824,17 @@ class BotManager:
stream_key = f"{bot['id']}:{event.chat_id}"
self._stream_tasks[stream_key] = asyncio.create_task(
self._stream_loop(
adapter, event.chat_id, platform_msg_id,
assistant_msg.id, bot,
adapter,
event.chat_id,
platform_msg_id,
assistant_msg.id,
bot,
)
)
# Start the agentic loop
start_task(
None,
message_id=assistant_msg.id,
chat_id=chat_id,
user_id=bot["user_id"],
@@ -820,6 +873,7 @@ class BotManager:
if use_draft:
try:
from cptr.utils.adapters.telegram import TelegramAdapter
if isinstance(adapter, TelegramAdapter):
# Start with empty draft → shows "Thinking..." placeholder
draft_id = await adapter.send_draft(platform_chat_id, "", None)
@@ -861,9 +915,7 @@ class BotManager:
if use_draft:
try:
draft_id = await adapter.send_draft(
platform_chat_id, display, draft_id
)
draft_id = await adapter.send_draft(platform_chat_id, display, draft_id)
last_sent = display
except Exception:
use_draft = False
@@ -890,6 +942,7 @@ class BotManager:
# ── Task complete — send final response ──
from cptr.models import ChatMessage
msg = await ChatMessage.get_by_id(task_message_id)
final_content = (msg.content if msg else content).strip()
@@ -897,7 +950,9 @@ class BotManager:
if use_draft:
await adapter.send(platform_chat_id, "✅ Done (no text output)")
elif platform_msg_id:
await adapter.edit(platform_chat_id, platform_msg_id, "✅ Done (no text output)")
await adapter.edit(
platform_chat_id, platform_msg_id, "✅ Done (no text output)"
)
return
final_display = final_content
+10 -8
View File
@@ -6,13 +6,14 @@ This function rebuilds the file from DB state.
from __future__ import annotations
import asyncio
import json
import logging
from pathlib import Path
from cptr.env import DATA_DIR
from cptr.models import Chat, ChatMessage
from cptr.utils.identity import identity_for_user_id
from cptr.utils.runtime import Runtime
logger = logging.getLogger(__name__)
@@ -73,13 +74,14 @@ async def export_chat_to_file(chat_id: str) -> None:
},
}
def _write():
chats_dir = chat_directory(workspace)
chats_dir.mkdir(parents=True, exist_ok=True)
target = chats_dir / f"{chat_id}.json"
target.write_text(json.dumps(chat_data, indent=2, ensure_ascii=False))
try:
await asyncio.to_thread(_write)
content = json.dumps(chat_data, indent=2, ensure_ascii=False)
target = chat_directory(workspace) / f"{chat_id}.json"
if workspace:
identity = await identity_for_user_id(chat.user_id)
await Runtime.write_file(identity, str(target), content)
else:
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content, encoding="utf-8")
except Exception:
logger.exception(f"Failed to export chat {chat_id}")
+20 -7
View File
@@ -72,6 +72,7 @@ from cptr.utils.agents.events import (
)
from cptr.utils.agents.attachments import prepare_agent_attachments
from cptr.utils.model_targets import AgentModelTarget, ApiModelTarget, ModelTarget
from cptr.utils.identity import identity_for_context
logger = logging.getLogger(__name__)
@@ -364,6 +365,8 @@ def get_pending_input_lock(chat_id: str) -> asyncio.Lock:
def start_task(
request,
*,
message_id: str,
chat_id: str,
user_id: str,
@@ -386,13 +389,14 @@ def start_task(
)
task = asyncio.create_task(
run_chat_task(
message_id,
chat_id,
user_id,
target,
workspace,
regeneration_prompt,
output_queue,
request,
message_id=message_id,
chat_id=chat_id,
user_id=user_id,
target=target,
workspace=workspace,
regeneration_prompt=regeneration_prompt,
output_queue=output_queue,
)
)
_tasks[message_id] = task
@@ -641,6 +645,7 @@ async def process_pending_chat_inputs(chat_id: str, user_id: str, workspace: str
# Start new task and continue draining other ready branch batches.
start_task(
None,
message_id=assistant_msg.id,
chat_id=chat_id,
user_id=user_id,
@@ -765,6 +770,7 @@ async def review_tool_approval(
args_text[:1000],
)
parsed = await generate_json(
None,
model_id=configured_model,
active_connection=connection,
active_model=model,
@@ -820,6 +826,7 @@ async def generate_chat_title(
try:
parsed = await generate_json(
None,
model_id=await Config.get("chat.title_generation.model"),
active_connection=connection,
active_model=model,
@@ -1382,6 +1389,8 @@ def _default_base_url(provider: str) -> str:
async def run_chat_task(
request,
*,
message_id: str,
chat_id: str,
user_id: str,
@@ -1545,6 +1554,7 @@ async def run_chat_task(
from cptr.utils.agents.pi import run_pi_agent
chat_obj = await Chat.get_by_id(chat_id)
identity = await identity_for_context({"request": request, "user_id": user_id})
chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
agent_workspace = workspace or str(Path.home())
messages, loaded_summary = await _load_message_history(chat_id, message_id)
@@ -1576,6 +1586,7 @@ async def run_chat_task(
current_user_files = meta_files
agent_attachments = await prepare_agent_attachments(
workspace=agent_workspace,
user_id=user_id,
chat_id=chat_id,
message_id=(msg.parent_id if msg and msg.parent_id else message_id),
files=current_user_files,
@@ -1637,6 +1648,7 @@ async def run_chat_task(
chat_params=chat_params,
resume_state=resume_state,
attachments=agent_attachments,
identity=identity,
):
if isinstance(event, AgentTextDelta):
await _finish_reasoning_item()
@@ -2085,6 +2097,7 @@ async def run_chat_task(
tool_ctx = {
"workspace": workspace,
"user_id": user_id,
"request": request,
"model_id": model,
"full_model_id": ((chat_obj.meta or {}).get("last_model") if chat_obj else None)
or model,
+164
View File
@@ -0,0 +1,164 @@
"""Execution identity for OS-facing work.
PAM mode means terminals, command execution, and user files should run as the
authenticated Unix user. Password mode remains server-process scoped.
"""
from __future__ import annotations
import os
import platform
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
from cptr.models import Auth
from cptr.utils.config import AuthMode, AuthResult, get_auth_mode
IS_WINDOWS = platform.system() == "Windows"
class IdentityUnavailable(RuntimeError):
"""Raised when an authenticated request cannot be mapped to an OS identity."""
def __init__(self, message: str, status_code: int = 403) -> None:
super().__init__(message)
self.status_code = status_code
@dataclass(frozen=True)
class ExecutionIdentity:
app_user_id: str | None
username: str
uid: int | None
gid: int | None
groups: tuple[int, ...]
home: str
shell: str
is_pam: bool
def _current_identity(auth: AuthResult | None = None) -> ExecutionIdentity:
username = os.environ.get("USER") or os.environ.get("USERNAME") or "user"
uid = None if IS_WINDOWS else os.getuid()
gid = None if IS_WINDOWS else os.getgid()
groups = () if IS_WINDOWS else tuple(os.getgroups())
return ExecutionIdentity(
app_user_id=auth.user_id if auth else None,
username=username,
uid=uid,
gid=gid,
groups=groups,
home=str(Path.home()),
shell=os.environ.get("SHELL") or os.environ.get("COMSPEC") or "/bin/sh",
is_pam=False,
)
def _pam_identity(auth: AuthResult) -> ExecutionIdentity:
if IS_WINDOWS:
raise IdentityUnavailable("PAM impersonation is not available on Windows")
if not auth.username:
raise IdentityUnavailable("PAM request is missing a username", status_code=401)
try:
import pwd
pw = pwd.getpwnam(auth.username)
except KeyError as exc:
raise IdentityUnavailable(f"Unix user not found: {auth.username}") from exc
try:
groups = tuple(os.getgrouplist(auth.username, pw.pw_gid))
except AttributeError:
groups = (pw.pw_gid,)
return ExecutionIdentity(
app_user_id=auth.user_id,
username=auth.username,
uid=pw.pw_uid,
gid=pw.pw_gid,
groups=groups,
home=pw.pw_dir,
shell=pw.pw_shell or "/bin/sh",
is_pam=True,
)
def _identity_from_auth(auth: AuthResult | None) -> ExecutionIdentity:
if get_auth_mode() != AuthMode.PAM:
return _current_identity(auth)
if auth is None:
raise IdentityUnavailable("not authenticated", status_code=401)
return _pam_identity(auth)
async def identity_for_request(request) -> ExecutionIdentity:
return _identity_from_auth(getattr(request.state, "auth", None))
async def identity_for_user_id(user_id: str | None) -> ExecutionIdentity:
if get_auth_mode() != AuthMode.PAM:
return _current_identity(AuthResult(user_id=user_id))
if not user_id:
raise IdentityUnavailable("missing user id", status_code=401)
auth = await Auth.get_by_user_id(user_id)
if auth is None:
raise IdentityUnavailable("user auth identity not found", status_code=401)
return _identity_from_auth(AuthResult(user_id=user_id, username=auth.username))
async def identity_for_context(context: dict) -> ExecutionIdentity:
request = context.get("request")
if request is not None:
return await identity_for_request(request)
return await identity_for_user_id(context.get("user_id"))
def env_for(
identity: ExecutionIdentity,
cwd: str | Path,
extra: dict[str, str] | None = None,
) -> dict[str, str]:
env = os.environ.copy()
env.update(
{
"HOME": identity.home,
"USER": identity.username,
"LOGNAME": identity.username,
"SHELL": identity.shell,
"PWD": str(cwd),
"PATH": env.get("PATH") or "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
"TERM": env.get("TERM") or "xterm-256color",
}
)
if extra:
env.update(extra)
return env
def preexec_for(identity: ExecutionIdentity) -> Callable[[], None] | None:
if IS_WINDOWS or not identity.is_pam or identity.uid is None or identity.gid is None:
return None
if os.geteuid() == identity.uid:
return None
if os.geteuid() != 0:
raise IdentityUnavailable(
f"Cannot run OS work as {identity.username}; server must run as root or that user"
)
def _drop_privileges() -> None:
os.setgroups(list(identity.groups))
os.setgid(identity.gid)
os.setuid(identity.uid)
return _drop_privileges
def expand_user_path(path: str | Path, identity: ExecutionIdentity) -> Path:
raw = str(path)
if raw == "~":
return Path(identity.home)
if raw.startswith("~/"):
return Path(identity.home) / raw[2:]
return Path(raw)
+6 -4
View File
@@ -16,6 +16,8 @@ import httpx
from cptr.models import Config, File
from cptr.utils.config import _get_jwt_secret, now_ms
from cptr.utils.crypto import decrypt_key
from cptr.utils.identity import identity_for_user_id
from cptr.utils.runtime import Runtime
from cptr.utils.storage import get_storage
@@ -134,13 +136,13 @@ async def _store_image(
if workspace:
workspace_path = _unique_workspace_image_path(workspace, source, content_type)
def _write() -> None:
if user_id:
identity = await identity_for_user_id(user_id)
await Runtime.write_file(identity, str(workspace_path), data)
else:
workspace_path.parent.mkdir(parents=True, exist_ok=True)
workspace_path.write_bytes(data)
await asyncio.to_thread(_write)
filename = workspace_path.name if workspace_path else f"{source}{ext}"
meta = {
"content_type": content_type,
+64 -9
View File
@@ -16,6 +16,8 @@ from typing import Any
from cptr.env import DATA_DIR
from cptr.models import Config
from cptr.utils.identity import identity_for_user_id
from cptr.utils.runtime import Runtime, FileError
from cptr.utils.workspace import ensure_cptr_gitignored
MEMORY_DIR_NAME = "memory"
@@ -1161,12 +1163,13 @@ async def write_memory(
operations: list[dict[str, Any]],
) -> dict[str, Any]:
memory_file = await resolve_memory_file(user_id, workspace, scope)
if scope == "workspace":
await asyncio.to_thread(ensure_cptr_gitignored, workspace)
identity = await identity_for_user_id(user_id) if scope == "workspace" else None
uses_markdown = any(
isinstance(operation, dict) and _operation_uses_markdown(operation)
for operation in operations
)
if scope == "workspace" and uses_markdown:
await asyncio.to_thread(ensure_cptr_gitignored, workspace)
lock_path = memory_file.path.parent if uses_markdown else memory_file.path
async with _memory_file_lock(lock_path):
if uses_markdown:
@@ -1182,7 +1185,18 @@ async def write_memory(
result = await asyncio.to_thread(apply_markdown_memory_batch, root, operations)
result.update({"scope": scope, "path": str(root.root)})
return result
entries = await asyncio.to_thread(read_memory_entries, memory_file.path)
if identity:
try:
file_data = await Runtime.read_file(identity, str(memory_file.path))
entries = [
line[2:].strip()
for line in str(file_data.get("content") or "").splitlines()
if line.strip().startswith("- ") and line[2:].strip()
]
except FileError:
entries = []
else:
entries = await asyncio.to_thread(read_memory_entries, memory_file.path)
success, message, next_entries, usage = apply_memory_batch(
entries, operations, memory_file.character_limit
)
@@ -1195,7 +1209,12 @@ async def write_memory(
"scope": scope,
"path": str(memory_file.path),
}
await asyncio.to_thread(write_memory_entries, memory_file.path, next_entries)
if identity:
await Runtime.write_file(
identity, str(memory_file.path), format_memory_entries(next_entries)
)
else:
await asyncio.to_thread(write_memory_entries, memory_file.path, next_entries)
return {
"success": True,
"message": message,
@@ -1227,7 +1246,17 @@ async def read_memory_state(user_id: str, workspace: str) -> dict[str, Any]:
workspace_path_value = ""
if workspace:
workspace_memory = await resolve_memory_file(user_id, workspace, "workspace")
workspace_entries = await asyncio.to_thread(read_memory_entries, workspace_memory.path)
try:
file_data = await Runtime.read_file(
await identity_for_user_id(user_id), str(workspace_memory.path)
)
workspace_entries = [
line[2:].strip()
for line in str(file_data.get("content") or "").splitlines()
if line.strip().startswith("- ") and line[2:].strip()
]
except FileError:
workspace_entries = []
workspace_usage = (
f"{measure_memory_entries(workspace_entries)}/{workspace_memory.character_limit}"
)
@@ -1267,9 +1296,20 @@ async def recall_memory_context(
snippets_by_scope: dict[str, list[MemorySnippet]] = {"user": [], "workspace": []}
for root in roots:
baseline_text = (
root.baseline_path.read_text(errors="replace") if root.baseline_path.is_file() else ""
)
if root.scope == "workspace":
try:
file_data = await Runtime.read_file(
await identity_for_user_id(user_id), str(root.baseline_path)
)
baseline_text = str(file_data.get("content") or "")
except FileError:
baseline_text = ""
else:
baseline_text = (
root.baseline_path.read_text(errors="replace")
if root.baseline_path.is_file()
else ""
)
contextual_query = query
if baseline_text:
baseline_links = _extract_baseline_links(baseline_text)
@@ -1343,7 +1383,21 @@ async def build_memory_prompt(
)
for root, title, budget, snippets in render_roots:
baseline = _read_baseline_block(root.baseline_path, budget)
if root.scope == "workspace":
try:
file_data = await Runtime.read_file(
await identity_for_user_id(user_id), str(root.baseline_path)
)
text = str(file_data.get("content") or "").strip()
baseline = (
_trim_prompt_text(_prompt_safe_text(text, root.baseline_path.name), budget)
if text
else ""
)
except FileError:
baseline = ""
else:
baseline = _read_baseline_block(root.baseline_path, budget)
remaining = max(0, budget - len(baseline))
contextual = _render_context_snippets(snippets, remaining)
content = "\n".join(part for part in (baseline, contextual) if part.strip()).strip()
@@ -1599,6 +1653,7 @@ async def run_memory_review(
transcript = summarize_recent_conversation(conversation_messages, assistant_reply)
prompt = build_memory_review_prompt(memory_state, workspace, transcript)
parsed = await generate_json(
None,
model_id=await Config.get("memory.background_review.model"),
active_connection=model_connection,
active_model=model,
+35 -8
View File
@@ -12,6 +12,8 @@ from importlib.metadata import version as pkg_version
from pathlib import Path
from cptr.models import Config
from cptr.utils.identity import identity_for_user_id
from cptr.utils.runtime import Runtime, FileError
from cptr.utils.skills import build_catalog_xml, discover_skills
logger = logging.getLogger(__name__)
@@ -138,11 +140,14 @@ def _safe_version() -> str:
return "dev"
def _format_cptr_context(workspace: str, model: str = "") -> str:
def _format_cptr_context(
workspace: str, model: str = "", home: str | None = None, shell: str | None = None
) -> str:
"""Return the default cptr runtime context block for the system prompt."""
ws_path = Path(workspace)
runtime = _runtime_label()
shell = os.environ.get("SHELL") or os.environ.get("COMSPEC") or ""
shell = shell or os.environ.get("SHELL") or os.environ.get("COMSPEC") or ""
home = home or str(Path.home())
host_control = (
"Commands run in the cptr backend environment. Because this appears to be a "
"container, commands affect the container and mounted paths; host-level controls "
@@ -161,7 +166,7 @@ def _format_cptr_context(workspace: str, model: str = "") -> str:
f"- OS: {platform.system().replace('Darwin', 'macOS')} {platform.release()}",
f"- Architecture: {platform.machine() or 'unknown'}",
f"- Shell: {shell or 'unknown'}",
f"- Home: {Path.home()}",
f"- Home: {home}",
f"- cptr version: {_safe_version()}",
]
if model:
@@ -221,11 +226,14 @@ def _build_template_variables(
model: str = "",
memory: str = "",
skills_enabled: bool = True,
home: str | None = None,
shell: str | None = None,
) -> dict[str, str]:
"""Build the dict of template variable values for the current context."""
ws_path = Path(workspace) if workspace else None
os_name = platform.system().replace("Darwin", "macOS")
shell = os.environ.get("SHELL") or os.environ.get("COMSPEC") or ""
shell = shell or os.environ.get("SHELL") or os.environ.get("COMSPEC") or ""
home = home or str(Path.home())
instructions = _load_instruction_files(workspace) if workspace else ""
if instructions:
@@ -247,14 +255,14 @@ def _build_template_variables(
"INSTRUCTIONS": instructions_block,
"MEMORY": memory,
"SKILLS": skills_block,
"CPTR_CONTEXT": _format_cptr_context(workspace, model) if workspace else "",
"CPTR_CONTEXT": _format_cptr_context(workspace, model, home, shell) if workspace else "",
"RUNTIME_ENV": _runtime_label(),
"HOSTNAME": _safe_hostname(),
"OS": os_name,
"PLATFORM": platform.platform(),
"ARCH": platform.machine(),
"SHELL": shell,
"HOME": str(Path.home()),
"HOME": home,
"CPTR_VERSION": _safe_version(),
"DATE": date.today().isoformat(),
"MODEL": model,
@@ -281,7 +289,16 @@ async def load_system_prompt(
if workspace:
ws_prompt = Path(workspace) / ".cptr" / "system.md"
if ws_prompt.is_file():
if user_id:
try:
file_data = await Runtime.read_file(
await identity_for_user_id(user_id), str(ws_prompt)
)
if not file_data.get("binary"):
template = str(file_data.get("content") or "").strip()
except FileError:
pass
elif ws_prompt.is_file():
template = ws_prompt.read_text(errors="replace").strip()
if template is None:
@@ -328,5 +345,15 @@ async def load_system_prompt(
except Exception:
skills_enabled = True
variables = _build_template_variables(workspace, model, memory, skills_enabled)
home = None
shell = None
if user_id:
try:
identity = await identity_for_user_id(user_id)
home = identity.home
shell = identity.shell
except Exception:
logger.debug("[system_prompt] Failed to resolve user identity", exc_info=True)
variables = _build_template_variables(workspace, model, memory, skills_enabled, home, shell)
return _render_system_template(template, variables)
+952
View File
@@ -0,0 +1,952 @@
from __future__ import annotations
import asyncio
import base64
import io
import json
import mimetypes
import os
import shutil
import subprocess
import sys
import zipfile
from datetime import datetime, timezone
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable
from cptr.utils.gitignore import is_gitignored, load_gitignore
from cptr.utils.identity import (
ExecutionIdentity,
IdentityUnavailable,
env_for,
identity_for_request,
preexec_for,
)
if TYPE_CHECKING:
from fastapi import Request
MAX_FILE_SIZE = 100 * 1024 * 1024
MATCH_PAGE_SIZE = 100
MAX_CONTENT_MATCHES_PER_FILE = 3
MAX_CONTENT_SEARCH_FILE_SIZE = 1 * 1024 * 1024
TEXT_EXTENSIONS = {
".bash",
".c",
".cc",
".cfg",
".clj",
".cmake",
".conf",
".cpp",
".css",
".csv",
".cxx",
".diff",
".dockerignore",
".editorconfig",
".el",
".env",
".erl",
".ex",
".exs",
".fish",
".gitignore",
".go",
".gradle",
".h",
".hcl",
".hh",
".hpp",
".hs",
".htm",
".html",
".hxx",
".ini",
".java",
".js",
".json",
".jsx",
".kt",
".lisp",
".lock",
".log",
".lua",
".makefile",
".md",
".ml",
".nix",
".patch",
".php",
".pl",
".py",
".r",
".rb",
".rs",
".sbt",
".scala",
".sh",
".sql",
".svg",
".svelte",
".swift",
".tf",
".toml",
".ts",
".tsv",
".tsx",
".vim",
".xml",
".yaml",
".yml",
".zsh",
}
SEARCH_IGNORE_DIRS = {
".cptr",
".git",
".DS_Store",
".eggs",
".mypy_cache",
".next",
".pytest_cache",
".svelte-kit",
".tox",
".venv",
"__pycache__",
"*.egg-info",
"build",
"dist",
"node_modules",
"venv",
}
class FileError(RuntimeError):
def __init__(self, message: str, status_code: int = 400) -> None:
super().__init__(message)
self.status_code = status_code
class Runtime:
@staticmethod
async def stat(request: Request | ExecutionIdentity, path: str) -> dict[str, Any]:
return await _file(await _identity(request), _stat, path)
@staticmethod
async def list_directory(request: Request | ExecutionIdentity, path: str) -> dict[str, Any]:
return await _file(await _identity(request), _list_directory, path)
@staticmethod
async def list_tree(
request: Request | ExecutionIdentity, path: str, recursive: bool = False
) -> dict[str, Any]:
return await _file(await _identity(request), _list_tree, path, recursive)
@staticmethod
async def read_file(request: Request | ExecutionIdentity, path: str) -> dict[str, Any]:
return await _file(await _identity(request), _read_file, path)
@staticmethod
async def extract_text(request: Request | ExecutionIdentity, path: str) -> dict[str, Any]:
return await _file(await _identity(request), _extract_text, path)
@staticmethod
async def write_file(
request: Request | ExecutionIdentity, path: str, content: str | bytes
) -> dict[str, Any]:
return await _file(await _identity(request), _write_file, path, content)
@staticmethod
async def file_matches(
request: Request | ExecutionIdentity,
query: str,
path: str,
show_hidden: bool = False,
offset: int = 0,
limit: int = MATCH_PAGE_SIZE,
) -> dict[str, Any]:
return await _file(
await _identity(request),
_file_matches,
path,
query,
show_hidden,
offset,
limit,
)
@staticmethod
async def search_files(
request: Request | ExecutionIdentity, query: str, path: str, limit: int = 20
) -> dict[str, Any]:
return await _file(await _identity(request), _search_files, path, query, limit)
@staticmethod
async def create_item(
request: Request | ExecutionIdentity, path: str, type: str = "file"
) -> dict[str, Any]:
return await _file(await _identity(request), _create_item, path, type)
@staticmethod
async def move_item(
request: Request | ExecutionIdentity, source: str, destination: str
) -> dict[str, Any]:
return await _file(await _identity(request), _move_item, source, destination)
@staticmethod
async def delete_item(request: Request | ExecutionIdentity, path: str) -> dict[str, Any]:
return await _file(await _identity(request), _delete_item, path)
@staticmethod
async def upload_file(
request: Request | ExecutionIdentity, directory: str, filename: str, content: bytes
) -> dict[str, Any]:
return await _file(await _identity(request), _upload_file, directory, filename, content)
@staticmethod
async def read_bytes(request: Request | ExecutionIdentity, path: str) -> dict[str, Any]:
return await _file(await _identity(request), _read_bytes, path)
@staticmethod
async def archive_files(
request: Request | ExecutionIdentity, paths: list[str]
) -> dict[str, Any]:
return await _file(await _identity(request), _archive_files, paths)
async def _identity(request: Request | ExecutionIdentity) -> ExecutionIdentity:
if isinstance(request, ExecutionIdentity):
return request
try:
return await identity_for_request(request)
except IdentityUnavailable as exc:
raise FileError(str(exc), exc.status_code) from exc
async def _file(
identity: ExecutionIdentity,
fn: Callable[..., dict[str, Any]],
*args: Any,
) -> dict[str, Any]:
if identity.is_pam and identity.uid is not None and identity.uid != os.geteuid():
return await _subprocess(identity, fn, *args)
return await _same_process(fn, *args)
async def _same_process(fn: Callable[..., dict[str, Any]], *args: Any) -> dict[str, Any]:
try:
return await asyncio.to_thread(fn, *args)
except FileError:
raise
except PermissionError as exc:
raise FileError(str(exc), 403) from exc
except OSError as exc:
raise FileError(str(exc), 400) from exc
async def _subprocess(
identity: ExecutionIdentity,
fn: Callable[..., dict[str, Any]],
*args: Any,
) -> dict[str, Any]:
try:
preexec = preexec_for(identity)
except IdentityUnavailable as exc:
raise FileError(str(exc), exc.status_code) from exc
proc = await asyncio.create_subprocess_exec(
sys.executable,
"-m",
"cptr.utils.runtime",
"--stdio",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=identity.home,
env=env_for(identity, identity.home),
preexec_fn=preexec,
)
stdout, stderr = await proc.communicate(
json.dumps({"function": fn.__name__, "args": _pack(args)}).encode()
)
try:
message = json.loads(stdout.decode())
except json.JSONDecodeError as exc:
detail = stderr.decode(errors="replace").strip() or "file operation failed"
raise FileError(detail, 500) from exc
if not message.get("ok"):
raise FileError(
message.get("error") or "file operation failed",
int(message.get("status") or 400),
)
return _unpack(message.get("result") or {})
def _pack(value: Any) -> Any:
if isinstance(value, bytes):
return {"__bytes__": base64.b64encode(value).decode("ascii")}
if isinstance(value, list):
return [_pack(item) for item in value]
if isinstance(value, dict):
return {key: _pack(item) for key, item in value.items()}
return value
def _unpack(value: Any) -> Any:
if isinstance(value, dict) and set(value) == {"__bytes__"}:
return base64.b64decode(value["__bytes__"])
if isinstance(value, list):
return [_unpack(item) for item in value]
if isinstance(value, dict):
return {key: _unpack(item) for key, item in value.items()}
return value
def _path(value: str) -> Path:
return Path(value).expanduser().resolve()
def _missing(path: str, kind: str = "Path") -> FileError:
return FileError(f"{kind} not found: {path}", 404)
def _detect_language(name: str) -> str | None:
ext = Path(name).suffix.lower()
return {
".bash": "bash",
".c": "c",
".cc": "cpp",
".cpp": "cpp",
".css": "css",
".cxx": "cpp",
".dockerfile": "dockerfile",
".go": "go",
".h": "c",
".hcl": "hcl",
".hh": "cpp",
".hpp": "cpp",
".html": "html",
".hxx": "cpp",
".java": "java",
".js": "javascript",
".json": "json",
".jsx": "jsx",
".kt": "kotlin",
".lua": "lua",
".makefile": "makefile",
".md": "markdown",
".nix": "nix",
".php": "php",
".py": "python",
".r": "r",
".rb": "ruby",
".rs": "rust",
".sh": "bash",
".sql": "sql",
".svelte": "svelte",
".swift": "swift",
".tf": "hcl",
".toml": "toml",
".ts": "typescript",
".tsx": "tsx",
".xml": "xml",
".yaml": "yaml",
".yml": "yaml",
".zsh": "bash",
}.get(ext)
def _human_size(size: int) -> str:
for unit in ["B", "KB", "MB", "GB"]:
if size < 1024:
return f"{size:.1f}{unit}" if unit != "B" else f"{size}B"
size /= 1024
return f"{size:.1f}TB"
def _is_text_file(path: Path) -> bool:
if path.suffix.lower() in TEXT_EXTENSIONS:
return True
if path.name.lower() in {
"changelog",
"dockerfile",
"gemfile",
"license",
"makefile",
"procfile",
"rakefile",
"readme",
}:
return True
try:
with path.open("rb") as source:
return b"\0" not in source.read(8192)
except OSError:
return False
def _list_directory(path: str) -> dict[str, Any]:
target = _path(path)
if not target.exists():
raise _missing(path)
if not target.is_dir():
raise FileError(f"Not a directory: {path}")
entries = []
for item in target.iterdir():
try:
st = item.stat()
kind = "symlink" if item.is_symlink() else "directory" if item.is_dir() else "file"
entries.append(
{
"name": item.name,
"type": kind,
"size": st.st_size if kind == "file" else None,
"modified": datetime.fromtimestamp(st.st_mtime, tz=timezone.utc).isoformat(),
}
)
except OSError:
entries.append({"name": item.name, "type": "file", "size": None, "modified": None})
order = {"directory": 0, "symlink": 1, "file": 2}
entries.sort(key=lambda entry: (order.get(entry["type"], 2), entry["name"].lower()))
return {"path": str(target), "entries": entries}
def _list_tree(path: str, recursive: bool = False) -> dict[str, Any]:
target = _path(path)
if not target.is_dir():
raise FileError(f"not a directory: {path}")
ignore = {
".git",
"node_modules",
"__pycache__",
".venv",
"venv",
".next",
"build",
"dist",
".cptr",
".svelte-kit",
}
lines = []
if recursive:
for root, dirs, files in os.walk(target):
dirs[:] = sorted(d for d in dirs if d not in ignore)
rel = Path(root).relative_to(target)
for filename in sorted(files):
item = Path(root) / filename
try:
size = item.stat().st_size
except OSError:
size = 0
lines.append(f"{rel / filename} ({_human_size(size)})")
else:
for item in sorted(target.iterdir()):
if item.name in ignore:
continue
if item.is_dir():
try:
count = sum(1 for child in item.rglob("*") if child.is_file())
except (PermissionError, OSError):
count = 0
lines.append(f"{item.name}/ ({count} files)")
else:
try:
size = item.stat().st_size
except OSError:
size = 0
lines.append(f"{item.name} ({_human_size(size)})")
return {"text": "\n".join(lines) if lines else "(empty directory)"}
def _stat(path: str) -> dict[str, Any]:
target = _path(path)
if not target.exists():
raise _missing(path)
st = target.stat()
kind = "symlink" if target.is_symlink() else "directory" if target.is_dir() else "file"
media_type, _ = mimetypes.guess_type(str(target))
return {
"path": str(target),
"name": target.name,
"type": kind,
"size": st.st_size if kind == "file" else None,
"modified": datetime.fromtimestamp(st.st_mtime, tz=timezone.utc).isoformat(),
"mode": st.st_mode,
"media_type": media_type or "application/octet-stream",
}
def _read_file(path: str) -> dict[str, Any]:
target = _path(path)
if not target.exists():
raise _missing(path, "File")
if not target.is_file():
raise FileError(f"Not a file: {path}")
size = target.stat().st_size
if size > MAX_FILE_SIZE:
raise FileError(f"File too large ({size} bytes). Max is {MAX_FILE_SIZE} bytes.", 413)
is_text = _is_text_file(target)
return {
"path": str(target),
"name": target.name,
"size": size,
"binary": not is_text,
"content": target.read_text(encoding="utf-8", errors="replace") if is_text else None,
"language": _detect_language(target.name) if is_text else None,
}
def _extract_text(path: str) -> dict[str, Any]:
target = _path(path)
if not target.exists():
raise _missing(path, "File")
if not target.is_file():
raise FileError(f"Not a file: {path}")
try:
from cptr.utils.documents import extract_by_path
except ImportError as exc:
raise FileError(f"reading {target.suffix} files requires: {exc}") from exc
try:
return {"text": extract_by_path(str(target)) or ""}
except Exception as exc:
raise FileError(f"failed to extract text from {target}: {exc}") from exc
def _write_file(path: str, content: str | bytes) -> dict[str, Any]:
target = _path(path)
if target.exists() and not target.is_file():
raise FileError(f"Not a file: {path}")
target.parent.mkdir(parents=True, exist_ok=True)
_ensure_cptr_gitignored_for(target)
if isinstance(content, bytes):
target.write_bytes(content)
else:
target.write_text(content, encoding="utf-8")
return {"status": "saved", "path": str(target), "size": target.stat().st_size}
def _ensure_cptr_gitignored_for(path: Path) -> None:
parts = path.parts
if ".cptr" not in parts:
return
root = Path(*parts[: parts.index(".cptr")])
if not (root / ".git").exists():
return
gitignore = root / ".gitignore"
entry = ".cptr"
content = gitignore.read_text(encoding="utf-8", errors="replace") if gitignore.exists() else ""
if any(line.strip() in {entry, entry + "/"} for line in content.splitlines()):
return
if content and not content.endswith("\n"):
content += "\n"
gitignore.write_text(content + f"{entry}\n", encoding="utf-8")
def _create_item(path: str, type: str = "file") -> dict[str, Any]:
target = _path(path)
if target.exists():
raise FileError(f"Already exists: {path}", 409)
if type == "directory":
target.mkdir(parents=True, exist_ok=True)
else:
target.parent.mkdir(parents=True, exist_ok=True)
target.touch()
return {"status": "created", "path": str(target), "type": type}
def _move_item(source: str, destination: str) -> dict[str, Any]:
src = _path(source)
dst = _path(destination)
if not src.exists():
raise _missing(source, "Source")
if dst.is_dir():
dst = dst / src.name
if dst.exists():
raise FileError(f"Destination exists: {dst}", 409)
src.rename(dst)
return {"status": "moved", "source": str(src), "destination": str(dst)}
def _delete_item(path: str) -> dict[str, Any]:
target = _path(path)
if not target.exists():
raise _missing(path)
shutil.rmtree(target) if target.is_dir() else target.unlink()
return {"status": "deleted", "path": str(target)}
def _unique_child_path(directory: Path, filename: str) -> Path:
safe_name = Path(filename).name or "file"
target = directory / safe_name
if not target.exists():
return target
stem = target.stem
suffix = target.suffix
for index in range(2, 10_000):
candidate = directory / f"{stem}-{index}{suffix}"
if not candidate.exists():
return candidate
raise FileError(f"Could not find available name for: {filename}", 409)
def _upload_file(directory: str, filename: str, content: bytes) -> dict[str, Any]:
target_dir = _path(directory)
if not target_dir.is_dir():
raise FileError(f"Not a directory: {directory}")
target = _unique_child_path(target_dir, filename)
target.write_bytes(content)
return {"status": "uploaded", "path": str(target), "size": len(content)}
def _read_bytes(path: str) -> dict[str, Any]:
target = _path(path)
if not target.exists():
raise _missing(path, "File")
if not target.is_file():
raise FileError(f"Not a file: {path}")
media_type, _ = mimetypes.guess_type(str(target))
return {
"path": str(target),
"name": target.name,
"media_type": media_type or "application/octet-stream",
"data": target.read_bytes(),
}
def _archive_files(paths: list[str]) -> dict[str, Any]:
if not paths:
raise FileError("No paths provided")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as archive:
for raw_path in paths:
target = _path(raw_path)
if target.is_file():
archive.write(target, target.name)
elif target.is_dir():
for child in target.rglob("*"):
if child.is_file():
archive.write(child, str(child.relative_to(target.parent)))
name = Path(paths[0]).name + ".zip" if len(paths) == 1 else "archive.zip"
return {"name": name, "data": buf.getvalue()}
def _is_search_ignored(name: str) -> bool:
return name in SEARCH_IGNORE_DIRS or name.endswith(".egg-info")
def _walk_match_entries(root: Path, show_hidden: bool, gitignore: tuple[Path, tuple] | None = None):
if gitignore is None:
gitignore = load_gitignore(root)
ignore_base, ignore_patterns = gitignore
try:
entries = sorted(root.iterdir(), key=lambda item: item.name.lower())
except OSError:
return
for item in entries:
try:
item_is_dir = item.is_dir()
if (
_is_search_ignored(item.name)
or (not show_hidden and item.name.startswith("."))
or is_gitignored(item, ignore_base, ignore_patterns, is_dir=item_is_dir)
):
continue
if item.is_symlink():
yield item, "file"
elif item_is_dir:
yield item, "directory"
yield from _walk_match_entries(item, show_hidden, gitignore)
elif item.is_file():
yield item, "file"
except OSError:
continue
def _match_column(text: str, query_lower: str) -> int | None:
index = text.lower().find(query_lower)
if index < 0:
return None
return len(text[:index].encode("utf-16-le")) // 2 + 1
def _content_match(text: str, line: int, query_lower: str) -> dict[str, Any] | None:
text = text.rstrip("\r\n")
column = _match_column(text, query_lower)
return {"line": line, "column": column, "text": text} if column is not None else None
def _content_matches_with_rg(
root: Path, query: str, query_lower: str, show_hidden: bool, files: set[Path]
) -> dict[Path, list[dict[str, Any]]] | None:
rg = shutil.which("rg")
if not rg:
return None
args = [
rg,
"--json",
"--no-messages",
"--fixed-strings",
"--ignore-case",
"--line-number",
"--column",
"--max-count",
str(MAX_CONTENT_MATCHES_PER_FILE + 1),
]
if show_hidden:
args.append("--hidden")
for ignored in SEARCH_IGNORE_DIRS:
pattern = f"!{ignored}" if ignored == ".DS_Store" else f"!{ignored}/**"
args.extend(("--glob", pattern))
args.extend(("--", query, str(root)))
try:
completed = subprocess.run(args, capture_output=True, text=True, check=False)
except OSError:
return None
if completed.returncode not in (0, 1):
return None
matches: dict[Path, list[dict[str, Any]]] = {}
for raw in completed.stdout.splitlines():
try:
message = json.loads(raw)
except json.JSONDecodeError:
continue
if message.get("type") != "match":
continue
data = message["data"]
path = Path(data["path"]["text"]).resolve()
if path not in files:
continue
line_matches = matches.setdefault(path, [])
if len(line_matches) >= MAX_CONTENT_MATCHES_PER_FILE:
continue
match = _content_match(data["lines"]["text"], data["line_number"], query_lower)
if match:
line_matches.append(match)
return matches
def _content_matches_with_python(
files: set[Path], query_lower: str
) -> dict[Path, list[dict[str, Any]]]:
matches: dict[Path, list[dict[str, Any]]] = {}
for path in files:
try:
if path.stat().st_size > MAX_CONTENT_SEARCH_FILE_SIZE:
continue
with path.open("rb") as source:
if b"\0" in source.read(8192):
continue
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
except OSError:
continue
for number, text in enumerate(lines, start=1):
match = _content_match(text, number, query_lower)
if not match:
continue
file_matches = matches.setdefault(path, [])
if len(file_matches) >= MAX_CONTENT_MATCHES_PER_FILE:
break
file_matches.append(match)
return matches
def _file_matches(
path: str,
query: str,
show_hidden: bool = False,
offset: int = 0,
limit: int = MATCH_PAGE_SIZE,
) -> dict[str, Any]:
root = _path(path)
if not root.exists() or not root.is_dir():
raise _missing(path)
query = query.strip()
query_lower = query.lower()
entries = list(_walk_match_entries(root, show_hidden))
files = {
entry.resolve() for entry, kind in entries if kind == "file" and not entry.is_symlink()
}
content_matches = _content_matches_with_rg(root, query, query_lower, show_hidden, files)
if content_matches is None:
content_matches = _content_matches_with_python(files, query_lower)
matches: list[tuple[int, int, dict[str, Any]]] = []
for entry, kind in entries:
relative_path = entry.relative_to(root).as_posix()
name_lower = entry.name.lower()
relative_lower = relative_path.lower()
if name_lower == query_lower:
score = 0
elif name_lower.startswith(query_lower):
score = 1
elif query_lower in name_lower:
score = 2
elif query_lower in relative_lower:
score = 3
else:
score = 4
entry_content_matches = content_matches.get(entry.resolve(), []) if kind == "file" else []
name_match = score < 4
if not name_match and not entry_content_matches:
continue
matches.append(
(
score,
len(relative_path),
{
"path": str(entry),
"relative_path": relative_path,
"name": entry.name,
"type": kind,
"name_match": name_match,
"content_matches": entry_content_matches,
},
)
)
matches.sort(key=lambda item: (item[0], item[1], item[2]["relative_path"].lower()))
next_offset = offset + limit if offset + limit < len(matches) else None
return {
"results": [item[2] for item in matches[offset : offset + limit]],
"next_offset": next_offset,
}
def walk_and_rank_files(root: str | Path, query: str, limit: int = 20) -> list[dict[str, Any]]:
root = _path(str(root))
if not root.exists() or not root.is_dir():
raise _missing(str(root))
query_lower = query.strip().lower().replace("\\", "/")
matches: list[tuple[int, int, dict[str, Any]]] = []
max_collect = limit * 10
ignore_base, ignore_patterns = load_gitignore(root)
def walk(directory: Path, depth: int = 0) -> None:
if depth > 8 or len(matches) >= max_collect:
return
try:
entries = sorted(directory.iterdir(), key=lambda item: item.name.lower())
except OSError:
return
for item in entries:
item_is_dir = item.is_dir()
if (
item.name in SEARCH_IGNORE_DIRS
or item.name.startswith(".")
or is_gitignored(item, ignore_base, ignore_patterns, is_dir=item_is_dir)
):
continue
if len(matches) >= max_collect:
return
name_lower = item.name.lower()
if query_lower and query_lower in name_lower:
score = (
0
if name_lower == query_lower
else 1
if name_lower.startswith(query_lower)
else 2
)
elif not query_lower:
score = 2
else:
score = None
if score is not None:
matches.append(
(
score,
len(item.name),
{
"path": str(item),
"name": item.name,
"type": "directory" if item_is_dir else "file",
},
)
)
if item_is_dir:
walk(item, depth + 1)
walk(root)
matches.sort(key=lambda match: (match[0], match[1]))
return [match[2] for match in matches[:limit]]
def _search_files(path: str, query: str, limit: int = 20) -> dict[str, Any]:
return {"results": walk_and_rank_files(path, query, limit)}
CALLS = {
fn.__name__: fn
for fn in (
_archive_files,
_create_item,
_delete_item,
_extract_text,
_file_matches,
_list_directory,
_list_tree,
_move_item,
_read_bytes,
_read_file,
_search_files,
_stat,
_upload_file,
_write_file,
)
}
def _main() -> int:
try:
message = json.loads(sys.stdin.read())
name = message.get("function")
if name not in CALLS:
raise FileError(f"Unsupported file operation: {name}")
result = CALLS[name](*_unpack(message.get("args") or []))
print(json.dumps({"ok": True, "result": _pack(result)}, ensure_ascii=False))
return 0
except FileError as exc:
status = exc.status_code
error = str(exc)
except FileNotFoundError as exc:
status = 404
error = str(exc)
except FileExistsError as exc:
status = 409
error = str(exc)
except PermissionError as exc:
status = 403
error = str(exc)
except OSError as exc:
status = 400
error = str(exc)
except Exception as exc:
status = 400
error = str(exc)
print(json.dumps({"ok": False, "status": status, "error": error}))
return 1
if __name__ == "__main__" and "--stdio" in sys.argv:
raise SystemExit(_main())
+1
View File
@@ -843,6 +843,7 @@ async def run_skill_review(
f"Conversation:\n{transcript}"
)
parsed = await generate_json(
None,
model_id=await Config.get("skills.background_review.model"),
active_connection=model_connection,
active_model=model,
+1
View File
@@ -67,6 +67,7 @@ async def summarize_messages(
from cptr.utils.ai import generate_text
result = await generate_text(
None,
model_id=await Config.get("chat.context_compaction.model"),
active_connection=connection,
active_model=model,
+93 -17
View File
@@ -14,6 +14,8 @@ import uuid
from dataclasses import dataclass, field
from typing import Dict, List, Optional
from cptr.utils.identity import ExecutionIdentity, env_for, expand_user_path, preexec_for
SCROLLBACK_SIZE = 64 * 1024 # 64 KB
IS_WINDOWS = platform.system() == "Windows"
@@ -28,6 +30,8 @@ class TerminalSession:
session_id: str
cwd: str
user_id: str | None = None
identity: ExecutionIdentity | None = field(default=None, repr=False)
rows: int = 24
cols: int = 80
_scrollback: bytearray = field(default_factory=bytearray, repr=False)
@@ -108,8 +112,21 @@ class TerminalSession:
pass
def _make_readable(path: str) -> None:
try:
os.chmod(path, 0o644)
except OSError:
pass
def _create_unix(
session_id: str, shell: str, work_dir: str, env: dict, rows: int, cols: int
session_id: str,
identity: ExecutionIdentity,
shell: str,
work_dir: str,
env: dict,
rows: int,
cols: int,
) -> TerminalSession:
"""Create a terminal session on Unix using stdlib pty."""
import fcntl
@@ -124,13 +141,18 @@ def _create_unix(
shell_name = os.path.basename(shell)
shell_args = [shell]
home = os.path.expanduser("~")
home = identity.home
preexec = preexec_for(identity) if identity.is_pam else None
# Create a temp init script that sources the user's real config then cd's.
# This guarantees cwd is set AFTER all init files run. No timing hacks.
if shell_name in ("zsh",):
# For zsh: use ZDOTDIR to inject our .zshrc
zdotdir = tempfile.mkdtemp(prefix="cptr_zsh_")
try:
os.chmod(zdotdir, 0o755)
except OSError:
pass
init_content = (
f'ZDOTDIR="{home}"\n'
f'[[ -f "{home}/.zshenv" ]] && source "{home}/.zshenv"\n'
@@ -140,9 +162,11 @@ def _create_unix(
)
with open(os.path.join(zdotdir, ".zshrc"), "w") as f:
f.write(init_content)
_make_readable(os.path.join(zdotdir, ".zshrc"))
# Also create .zshenv to prevent system zshenv from interfering
with open(os.path.join(zdotdir, ".zshenv"), "w") as f:
f.write("")
_make_readable(os.path.join(zdotdir, ".zshenv"))
env["ZDOTDIR"] = zdotdir
shell_args = [shell, "-i"]
elif shell_name in ("bash",):
@@ -154,12 +178,14 @@ def _create_unix(
f'[[ -f "{home}/.bashrc" ]] && source "{home}/.bashrc"\ncd {shlex.quote(work_dir)}\n'
)
tmpf.close()
_make_readable(tmpf.name)
shell_args = [shell, "--rcfile", tmpf.name, "-i"]
else:
# Generic POSIX: use ENV variable
tmpf = tempfile.NamedTemporaryFile(mode="w", prefix="cptr_sh_", suffix=".sh", delete=False)
tmpf.write(f'[ -f "$HOME/.profile" ] && . "$HOME/.profile"\ncd {shlex.quote(work_dir)}\n')
tmpf.close()
_make_readable(tmpf.name)
env["ENV"] = tmpf.name
shell_args = [shell, "-i"]
@@ -176,6 +202,8 @@ def _create_unix(
if slave_fd > 2:
os.close(slave_fd)
if preexec:
preexec()
os.chdir(work_dir)
os.execvpe(shell, shell_args, env)
else:
@@ -187,6 +215,8 @@ def _create_unix(
return TerminalSession(
session_id=session_id,
cwd=work_dir,
user_id=identity.app_user_id,
identity=identity,
rows=rows,
cols=cols,
_fd=master_fd,
@@ -195,7 +225,13 @@ def _create_unix(
def _create_windows(
session_id: str, shell: str, work_dir: str, env: dict, rows: int, cols: int
session_id: str,
identity: ExecutionIdentity,
shell: str,
work_dir: str,
env: dict,
rows: int,
cols: int,
) -> TerminalSession:
"""Create a terminal session on Windows using pywinpty."""
try:
@@ -217,6 +253,8 @@ def _create_windows(
return TerminalSession(
session_id=session_id,
cwd=work_dir,
user_id=identity.app_user_id,
identity=identity,
rows=rows,
cols=cols,
_process=proc,
@@ -229,42 +267,74 @@ class SessionManager:
def __init__(self) -> None:
self._sessions: Dict[str, TerminalSession] = {}
def create(self, rows: int = 24, cols: int = 80, cwd: Optional[str] = None) -> TerminalSession:
def create(
self,
identity: ExecutionIdentity,
rows: int = 24,
cols: int = 80,
cwd: Optional[str] = None,
) -> TerminalSession:
session_id = uuid.uuid4().hex[:12]
work_dir = cwd or os.path.expanduser("~")
work_dir = (
str(expand_user_path(cwd, identity).resolve())
if identity.is_pam and cwd
else cwd or identity.home
)
if IS_WINDOWS:
shell = os.environ.get("COMSPEC", "cmd.exe")
else:
shell = os.environ.get("SHELL", "/bin/sh")
shell = identity.shell if identity.is_pam else os.environ.get("SHELL", "/bin/sh")
env = os.environ.copy()
env["TERM"] = "xterm-256color"
env["COLORTERM"] = "truecolor"
env["COLUMNS"] = str(cols)
env["LINES"] = str(rows)
env["PWD"] = work_dir
if identity.is_pam:
env = env_for(
identity,
work_dir,
{
"TERM": "xterm-256color",
"COLORTERM": "truecolor",
"COLUMNS": str(cols),
"LINES": str(rows),
},
)
else:
env = os.environ.copy()
env["TERM"] = "xterm-256color"
env["COLORTERM"] = "truecolor"
env["COLUMNS"] = str(cols)
env["LINES"] = str(rows)
env["PWD"] = work_dir
if IS_WINDOWS:
session = _create_windows(session_id, shell, work_dir, env, rows, cols)
session = _create_windows(session_id, identity, shell, work_dir, env, rows, cols)
else:
session = _create_unix(session_id, shell, work_dir, env, rows, cols)
session = _create_unix(session_id, identity, shell, work_dir, env, rows, cols)
self._sessions[session_id] = session
return session
def get(self, session_id: str) -> Optional[TerminalSession]:
def get(self, request, session_id: str, auth=None) -> Optional[TerminalSession]:
session = self._sessions.get(session_id)
if request is not None:
auth = getattr(getattr(request, "state", None), "auth", None)
user_id = getattr(auth, "user_id", None)
if session and user_id is not None and session.user_id != user_id:
return None
if session and not session.is_alive():
session.close()
del self._sessions[session_id]
return None
return session
def list_sessions(self) -> List[dict]:
def list_sessions(self, request, auth=None) -> List[dict]:
result = []
dead = []
if request is not None:
auth = getattr(getattr(request, "state", None), "auth", None)
user_id = getattr(auth, "user_id", None)
for sid, session in self._sessions.items():
if user_id is not None and session.user_id != user_id:
continue
if session.is_alive():
result.append({"session_id": sid, "cwd": session.cwd})
else:
@@ -274,7 +344,13 @@ class SessionManager:
del self._sessions[sid]
return result
def close(self, session_id: str) -> bool:
def close(self, request, session_id: str, auth=None) -> bool:
session = self._sessions.get(session_id)
if request is not None:
auth = getattr(getattr(request, "state", None), "auth", None)
user_id = getattr(auth, "user_id", None)
if user_id is not None and session and session.user_id != user_id:
return False
session = self._sessions.pop(session_id, None)
if session:
session.close()
+1
View File
@@ -184,6 +184,7 @@ async def _launch_timer(timer, app) -> None:
},
)
start_task(
None,
message_id=assistant_msg.id,
chat_id=parent.id,
user_id=timer.user_id,
+396 -231
View File
File diff suppressed because it is too large. Load diff