From 22b29c6358363e553fef74e4c0d4b78d644637c0 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Wed, 5 Aug 2026 05:12:14 -0500 Subject: [PATCH] refac --- cptr/routers/audio.py | 167 +++--- cptr/routers/auth.py | 6 +- cptr/routers/chat.py | 58 +- cptr/routers/gateway.py | 86 +-- cptr/routers/search.py | 18 +- cptr/routers/state.py | 63 +- cptr/routers/terminal.py | 42 +- cptr/routers/workspace.py | 993 +++++-------------------------- cptr/utils/agents/acp.py | 3 + cptr/utils/agents/attachments.py | 11 +- cptr/utils/agents/claude_code.py | 4 +- cptr/utils/agents/cline.py | 5 +- cptr/utils/agents/codex.py | 15 +- cptr/utils/agents/cursor.py | 5 +- cptr/utils/agents/gemini.py | 5 +- cptr/utils/agents/grok.py | 5 +- cptr/utils/agents/opencode.py | 18 +- cptr/utils/agents/pi.py | 18 +- cptr/utils/ai.py | 4 +- cptr/utils/async_subagents.py | 1 + cptr/utils/automations.py | 12 +- cptr/utils/bridge.py | 119 +++- cptr/utils/chat_export.py | 18 +- cptr/utils/chat_task.py | 27 +- cptr/utils/identity.py | 164 +++++ cptr/utils/images.py | 10 +- cptr/utils/memory.py | 73 ++- cptr/utils/prompt_templates.py | 43 +- cptr/utils/runtime.py | 952 +++++++++++++++++++++++++++++ cptr/utils/skills.py | 1 + cptr/utils/summarize.py | 1 + cptr/utils/terminal.py | 110 +++- cptr/utils/timers.py | 1 + cptr/utils/tools.py | 627 ++++++++++++------- 34 files changed, 2325 insertions(+), 1360 deletions(-) create mode 100644 cptr/utils/identity.py create mode 100644 cptr/utils/runtime.py diff --git a/cptr/routers/audio.py b/cptr/routers/audio.py index 5c7a820..cf88b63 100644 --- a/cptr/routers/audio.py +++ b/cptr/routers/audio.py @@ -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" diff --git a/cptr/routers/auth.py b/cptr/routers/auth.py index 2c51bbe..2b2ff40 100644 --- a/cptr/routers/auth.py +++ b/cptr/routers/auth.py @@ -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}, diff --git a/cptr/routers/chat.py b/cptr/routers/chat.py index e7cbd6f..15805bd 100644 --- a/cptr/routers/chat.py +++ b/cptr/routers/chat.py @@ -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) diff --git a/cptr/routers/gateway.py b/cptr/routers/gateway.py index f8e0907..d3c4919 100644 --- a/cptr/routers/gateway.py +++ b/cptr/routers/gateway.py @@ -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 diff --git a/cptr/routers/search.py b/cptr/routers/search.py index d6b058d..35f0089 100644 --- a/cptr/routers/search.py +++ b/cptr/routers/search.py @@ -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, } ) diff --git a/cptr/routers/state.py b/cptr/routers/state.py index 58ee142..143935e 100644 --- a/cptr/routers/state.py +++ b/cptr/routers/state.py @@ -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()) diff --git a/cptr/routers/terminal.py b/cptr/routers/terminal.py index dc3c8b1..d2d3f15 100644 --- a/cptr/routers/terminal.py +++ b/cptr/routers/terminal.py @@ -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") diff --git a/cptr/routers/workspace.py b/cptr/routers/workspace.py index d2c3bb8..0cd31c5 100644 --- a/cptr/routers/workspace.py +++ b/cptr/routers/workspace.py @@ -7,25 +7,23 @@ single-user model. Not safe for shared or public instances. See README.md. from __future__ import annotations -import asyncio -import json -import shutil -import subprocess -from datetime import datetime, timezone +import io from pathlib import Path from typing import Optional -from fastapi import APIRouter, HTTPException, Query +from fastapi import APIRouter, File as FastAPIFile, Form, HTTPException, Query, Request, UploadFile +from fastapi.responses import StreamingResponse from pydantic import BaseModel -from cptr.utils.gitignore import is_gitignored, load_gitignore +from cptr.utils.runtime import Runtime +from cptr.utils.runtime import MATCH_PAGE_SIZE, FileError router = APIRouter(prefix="/api/workspace/files", tags=["workspace-files"]) class FileEntry(BaseModel): name: str - type: str # "directory" | "file" | "symlink" + type: str size: Optional[int] = None modified: Optional[str] = None @@ -35,133 +33,6 @@ class DirectoryListing(BaseModel): entries: list[FileEntry] -@router.get("", response_model=DirectoryListing) -async def list_directory(path: str = Query(..., description="Absolute path to list")): - """Return the contents of a directory, sorted dirs-first then alphabetical.""" - - target = Path(path).resolve() - - if not target.exists(): - raise HTTPException(status_code=404, detail=f"Path not found: {path}") - if not target.is_dir(): - raise HTTPException(status_code=400, detail=f"Not a directory: {path}") - - def _scan() -> list[FileEntry]: - entries: list[FileEntry] = [] - for item in target.iterdir(): - try: - st = item.stat() - modified = datetime.fromtimestamp(st.st_mtime, tz=timezone.utc).isoformat() - - if item.is_symlink(): - entry_type = "symlink" - elif item.is_dir(): - entry_type = "directory" - else: - entry_type = "file" - - entries.append( - FileEntry( - name=item.name, - type=entry_type, - size=st.st_size if entry_type == "file" else None, - modified=modified, - ) - ) - except (PermissionError, OSError): - entries.append(FileEntry(name=item.name, type="file")) - # Sort: directories first, then files, alphabetical within each group - type_order = {"directory": 0, "symlink": 1, "file": 2} - entries.sort(key=lambda e: (type_order.get(e.type, 2), e.name.lower())) - return entries - - try: - entries = await asyncio.to_thread(_scan) - except PermissionError: - raise HTTPException(status_code=403, detail=f"Permission denied: {path}") - - return DirectoryListing(path=str(target), entries=entries) - - -# ── File content reading ───────────────────────────────────────── - -MAX_FILE_SIZE = 100 * 1024 * 1024 # 100 MB - -# Extensions we know are text -TEXT_EXTENSIONS = { - ".txt", - ".md", - ".py", - ".js", - ".ts", - ".jsx", - ".tsx", - ".svelte", - ".css", - ".html", - ".htm", - ".json", - ".xml", - ".yaml", - ".yml", - ".toml", - ".ini", - ".cfg", - ".conf", - ".sh", - ".bash", - ".zsh", - ".fish", - ".env", - ".gitignore", - ".dockerignore", - ".editorconfig", - ".rs", - ".go", - ".java", - ".c", - ".h", - ".cc", - ".cxx", - ".hh", - ".hxx", - ".cpp", - ".hpp", - ".rb", - ".php", - ".pl", - ".swift", - ".kt", - ".scala", - ".sql", - ".r", - ".lua", - ".vim", - ".el", - ".ex", - ".exs", - ".erl", - ".hs", - ".ml", - ".clj", - ".lisp", - ".csv", - ".tsv", - ".log", - ".diff", - ".patch", - ".makefile", - ".cmake", - ".gradle", - ".sbt", - ".tf", - ".hcl", - ".nix", - ".lock", - ".svg", -} - - class FileContent(BaseModel): path: str name: str @@ -171,176 +42,6 @@ class FileContent(BaseModel): language: Optional[str] = None -def _detect_language(name: str) -> Optional[str]: - """Map file extension to a language identifier for syntax highlighting.""" - ext = Path(name).suffix.lower() - lang_map = { - ".py": "python", - ".js": "javascript", - ".ts": "typescript", - ".jsx": "jsx", - ".tsx": "tsx", - ".svelte": "svelte", - ".css": "css", - ".html": "html", - ".json": "json", - ".xml": "xml", - ".yaml": "yaml", - ".yml": "yaml", - ".toml": "toml", - ".md": "markdown", - ".sh": "bash", - ".bash": "bash", - ".zsh": "bash", - ".rs": "rust", - ".go": "go", - ".java": "java", - ".c": "c", - ".h": "c", - ".cc": "cpp", - ".cxx": "cpp", - ".hh": "cpp", - ".hxx": "cpp", - ".cpp": "cpp", - ".hpp": "cpp", - ".rb": "ruby", - ".php": "php", - ".swift": "swift", - ".kt": "kotlin", - ".sql": "sql", - ".r": "r", - ".lua": "lua", - ".dockerfile": "dockerfile", - ".makefile": "makefile", - ".tf": "hcl", - ".hcl": "hcl", - ".nix": "nix", - } - return lang_map.get(ext) - - -def _is_text_file(filepath: Path) -> bool: - """Check if a file is likely text based on extension or content sniffing.""" - if filepath.suffix.lower() in TEXT_EXTENSIONS: - return True - # Also check common extensionless files - if filepath.name.lower() in { - "makefile", - "dockerfile", - "gemfile", - "rakefile", - "procfile", - "license", - "readme", - "changelog", - }: - return True - # Content sniff: read first 8KB and check for null bytes - try: - with open(filepath, "rb") as f: - chunk = f.read(8192) - return b"\x00" not in chunk - except (OSError, PermissionError): - return False - - -@router.get("/read", response_model=FileContent) -async def read_file(path: str = Query(..., description="Absolute path to file")): - """Read the contents of a file.""" - - target = Path(path).resolve() - - if not target.exists(): - raise HTTPException(status_code=404, detail=f"File not found: {path}") - if not target.is_file(): - raise HTTPException(status_code=400, detail=f"Not a file: {path}") - - def _read() -> FileContent: - size = target.stat().st_size - - if size > MAX_FILE_SIZE: - raise HTTPException( - status_code=413, - detail=f"File too large ({size} bytes). Max is {MAX_FILE_SIZE} bytes.", - ) - - is_text = _is_text_file(target) - - if is_text: - try: - content = target.read_text(encoding="utf-8", errors="replace") - except (OSError, PermissionError) as e: - raise HTTPException(status_code=403, detail=str(e)) - else: - content = None - - return FileContent( - path=str(target), - name=target.name, - size=size, - binary=not is_text, - content=content, - language=_detect_language(target.name) if is_text else None, - ) - - return await asyncio.to_thread(_read) - - -# ── File writing ───────────────────────────────────────────────── - - -class WriteFileRequest(BaseModel): - path: str - content: str - - -@router.post("/write") -async def write_file(req: WriteFileRequest): - """Write content to a file. Creates the file (and parent dirs) if it doesn't exist.""" - - target = Path(req.path).resolve() - - if target.exists() and not target.is_file(): - raise HTTPException(status_code=400, detail=f"Not a file: {req.path}") - - def _write() -> dict: - target.parent.mkdir(parents=True, exist_ok=True) - target.write_text(req.content, encoding="utf-8") - return {"status": "saved", "path": str(target), "size": target.stat().st_size} - - try: - return await asyncio.to_thread(_write) - except (OSError, PermissionError) as e: - raise HTTPException(status_code=403, detail=str(e)) - - -# ── File search ────────────────────────────────────────────────── - - -SEARCH_IGNORE_DIRS = { - ".cptr", - ".git", - "node_modules", - "__pycache__", - ".svelte-kit", - ".next", - "dist", - "build", - ".venv", - "venv", - ".tox", - ".mypy_cache", - ".pytest_cache", - ".eggs", - "*.egg-info", - ".DS_Store", -} - -MATCH_PAGE_SIZE = 100 -MAX_CONTENT_MATCHES_PER_FILE = 3 -MAX_CONTENT_SEARCH_FILE_SIZE = 1 * 1024 * 1024 - - class ContentMatch(BaseModel): line: int column: int @@ -351,7 +52,7 @@ class FileMatch(BaseModel): path: str relative_path: str name: str - type: str # "file" | "directory" + type: str name_match: bool content_matches: list[ContentMatch] @@ -361,350 +62,24 @@ class FileMatches(BaseModel): next_offset: int | None = None -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, -): - """Yield visible files and directories without following symlinks.""" - 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, PermissionError): - 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, PermissionError): - continue - - -def _match_column(text: str, query_lower: str) -> int | None: - index = text.lower().find(query_lower) - if index < 0: - return None - # CodeMirror measures columns in UTF-16 code units. - return len(text[:index].encode("utf-16-le")) // 2 + 1 - - -def _content_match(text: str, line: int, query_lower: str) -> ContentMatch | None: - text = text.rstrip("\r\n") - column = _match_column(text, query_lower) - return ContentMatch(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] -) -> tuple[dict[Path, list[ContentMatch]], bool] | 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[ContentMatch]] = {} - truncated = False - 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: - truncated = True - continue - match = _content_match(data["lines"]["text"], data["line_number"], query_lower) - if match: - line_matches.append(match) - return matches, truncated - - -def _content_matches_with_python( - files: set[Path], query_lower: str -) -> tuple[dict[Path, list[ContentMatch]], bool]: - matches: dict[Path, list[ContentMatch]] = {} - truncated = False - 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, PermissionError): - 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: - truncated = True - break - file_matches.append(match) - return matches, truncated - - -def find_file_matches( - root: Path, - query: str, - show_hidden: bool = False, - offset: int = 0, - limit: int = MATCH_PAGE_SIZE, -) -> FileMatches: - """Find filename/path and literal text matches below a browser directory.""" - query = query.strip() - query_lower = query.lower() - entries = list(_walk_match_entries(root, show_hidden)) - files = {path.resolve() for path, kind in entries if kind == "file" and not path.is_symlink()} - content_result = _content_matches_with_rg(root, query, query_lower, show_hidden, files) - content_matches, _ = ( - content_result - if content_result is not None - else _content_matches_with_python(files, query_lower) - ) - - matches: list[tuple[int, int, FileMatch]] = [] - for path, kind in entries: - relative_path = path.relative_to(root).as_posix() - name_lower = path.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 - - path_content_matches = content_matches.get(path.resolve(), []) if kind == "file" else [] - name_match = score < 4 - if not name_match and not path_content_matches: - continue - matches.append( - ( - score, - len(relative_path), - FileMatch( - path=str(path), - relative_path=relative_path, - name=path.name, - type=kind, - name_match=name_match, - content_matches=path_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 FileMatches( - results=[item[2] for item in matches[offset : offset + limit]], - next_offset=next_offset, - ) - - -@router.get("/matches", response_model=FileMatches) -async def file_matches( - query: str = Query(..., description="Literal text to match"), - path: str = Query(..., description="Root path to search"), - show_hidden: bool = Query(False, description="Include dotfiles and dot-directories"), - offset: int = Query(0, ge=0, description="Result offset"), - limit: int = Query(MATCH_PAGE_SIZE, ge=1, le=MATCH_PAGE_SIZE, description="Page size"), -): - """Return filename/path and content matches below a directory.""" - if not query.strip(): - raise HTTPException(status_code=400, detail="Query must not be blank") - - root = Path(path).resolve() - if not root.exists() or not root.is_dir(): - raise HTTPException(status_code=404, detail=f"Path not found: {path}") - - return await asyncio.to_thread(find_file_matches, root, query, show_hidden, offset, limit) - - class SearchResult(BaseModel): path: str name: str - type: str # "file" | "directory" + type: str class SearchResponse(BaseModel): results: list[SearchResult] -@router.get("/search", response_model=SearchResponse) -async def search_files( - query: str = Query(..., description="Search term"), - path: str = Query(..., description="Root path to search"), - limit: int = Query(20, description="Max results"), -): - """Fuzzy file search. Walks tree, matching basename and relative path case-insensitively. - - Results are ranked by where/how the query matches: exact name > name prefix > - exact path > path prefix > name contains > path contains. Within each tier, - shorter paths rank higher (more specific match). - """ - - root = Path(path).resolve() - if not root.exists() or not root.is_dir(): - raise HTTPException(status_code=404, detail=f"Path not found: {path}") - - results = await asyncio.to_thread(walk_and_rank_files, root, query, limit) - return SearchResponse(results=results) - - -def walk_and_rank_files(root: Path, query: str, limit: int = 20) -> list[SearchResult]: - """Fuzzy file search — walks tree, ranks by name match quality. - - Reusable by both the /search endpoint and the unified /api/search endpoint. - """ - query_lower = query.strip().lower().replace("\\", "/") - matches: list[tuple[int, int, SearchResult]] = [] - max_collect = limit * 10 - ignore_base, ignore_patterns = load_gitignore(root) - - def walk(directory: Path, depth: int = 0): - if depth > 8 or len(matches) >= max_collect: - return - try: - for item in sorted(directory.iterdir(), key=lambda p: p.name.lower()): - 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: - if name_lower == query_lower: - score = 0 - elif name_lower.startswith(query_lower): - score = 1 - else: - score = 2 - matches.append( - ( - score, - len(item.name), - SearchResult( - path=str(item), - name=item.name, - type="directory" if item_is_dir else "file", - ), - ) - ) - elif not query_lower: - matches.append( - ( - 2, - len(item.name), - SearchResult( - path=str(item), - name=item.name, - type="directory" if item_is_dir else "file", - ), - ) - ) - - if item_is_dir: - walk(item, depth + 1) - except (PermissionError, OSError): - pass - - walk(root) - matches.sort(key=lambda m: (m[0], m[1])) - return [m[2] for m in matches[:limit]] - - -# ── File management ────────────────────────────────────────────── +class WriteFileRequest(BaseModel): + path: str + content: str class CreateRequest(BaseModel): path: str - type: str = "file" # "file" | "directory" - - -@router.post("/create") -async def create_item(req: CreateRequest): - """Create a new file or directory.""" - target = Path(req.path).resolve() - - if target.exists(): - raise HTTPException(status_code=409, detail=f"Already exists: {req.path}") - - def _create(): - if req.type == "directory": - target.mkdir(parents=True, exist_ok=True) - else: - target.parent.mkdir(parents=True, exist_ok=True) - target.touch() - - try: - await asyncio.to_thread(_create) - except (OSError, PermissionError) as e: - raise HTTPException(status_code=403, detail=str(e)) - - return {"status": "created", "path": str(target), "type": req.type} + type: str = "file" class MoveRequest(BaseModel): @@ -712,224 +87,168 @@ class MoveRequest(BaseModel): destination: str -@router.post("/move") -async def move_item(req: MoveRequest): - """Move or rename a file/directory.""" - src = Path(req.source).resolve() - dst = Path(req.destination).resolve() - - if not src.exists(): - raise HTTPException(status_code=404, detail=f"Source not found: {req.source}") - - # If destination is a directory, move into it - if dst.is_dir(): - dst = dst / src.name - - if dst.exists(): - raise HTTPException(status_code=409, detail=f"Destination exists: {dst}") - - try: - await asyncio.to_thread(src.rename, dst) - except (OSError, PermissionError) as e: - raise HTTPException(status_code=403, detail=str(e)) - - return {"status": "moved", "source": str(src), "destination": str(dst)} - - class DeleteRequest(BaseModel): path: str -@router.post("/delete") -async def delete_item(req: DeleteRequest): - """Delete a file or directory.""" - import shutil - - target = Path(req.path).resolve() - - if not target.exists(): - raise HTTPException(status_code=404, detail=f"Not found: {req.path}") - - def _delete(): - if target.is_dir(): - shutil.rmtree(target) - else: - target.unlink() - - try: - await asyncio.to_thread(_delete) - except (OSError, PermissionError) as e: - raise HTTPException(status_code=403, detail=str(e)) - - return {"status": "deleted", "path": str(target)} - - -from fastapi import UploadFile, File as FastAPIFile, Form - - -@router.post("/upload") -async def upload_file( - file: UploadFile = FastAPIFile(...), - directory: str = Form(...), -): - """Upload a file to a directory.""" - target_dir = Path(directory).resolve() - - if not target_dir.is_dir(): - raise HTTPException(status_code=400, detail=f"Not a directory: {directory}") - - target = _unique_child_path(target_dir, file.filename or "file") - try: - content = await file.read() - await asyncio.to_thread(target.write_bytes, content) - except (OSError, PermissionError) as e: - raise HTTPException(status_code=403, detail=str(e)) - - return {"status": "uploaded", "path": str(target), "size": len(content)} - - -def _unique_child_path(directory: Path, filename: str) -> Path: - """Return a non-existing child path by appending -2, -3, ... on collisions.""" - safe_name = Path(filename).name or "file" - target = directory / safe_name - if not target.exists(): - return target - stem = target.stem - suffix = target.suffix - for i in range(2, 10_000): - candidate = directory / f"{stem}-{i}{suffix}" - if not candidate.exists(): - return candidate - raise HTTPException(status_code=409, detail=f"Could not find available name for: {filename}") - - -# ── File viewing (inline) ──────────────────────────────────────── - -import mimetypes - -from fastapi.responses import FileResponse - - -@router.get("/view") -async def view_file(path: str = Query(..., description="Absolute path to file")): - """Serve a file with correct Content-Type for inline browser rendering. - - Unlike /download (which forces application/octet-stream to trigger a - save dialog), this endpoint lets the browser render the file inline — - used by the frontend for image, PDF, video, and audio previews. - """ - target = Path(path).resolve() - - if not target.exists(): - raise HTTPException(status_code=404, detail=f"File not found: {path}") - if not target.is_file(): - raise HTTPException(status_code=400, detail=f"Not a file: {path}") - - media_type, _ = mimetypes.guess_type(str(target)) - - return FileResponse( - path=str(target), - media_type=media_type or "application/octet-stream", - # No filename= → browser renders inline instead of downloading - ) - - -# ── File download ──────────────────────────────────────────────── - - -@router.get("/download") -async def download_file(path: str = Query(..., description="Absolute path to file")): - """Download a file.""" - target = Path(path).resolve() - - if not target.exists(): - raise HTTPException(status_code=404, detail=f"File not found: {path}") - if not target.is_file(): - raise HTTPException(status_code=400, detail=f"Not a file: {path}") - - return FileResponse( - path=str(target), - filename=target.name, - media_type="application/octet-stream", - ) - - -# ── Archive (zip) ──────────────────────────────────────────────── - -import io -import zipfile - -from fastapi.responses import StreamingResponse - - class ArchiveRequest(BaseModel): paths: list[str] -@router.post("/archive") -async def archive_files(req: ArchiveRequest): - """Create a zip archive from a list of file/directory paths.""" - if not req.paths: - raise HTTPException(status_code=400, detail="No paths provided") +@router.get("", response_model=DirectoryListing) +async def list_directory( + request: Request, + path: str = Query(..., description="Absolute path to list"), +): + try: + return DirectoryListing(**await Runtime.list_directory(request, path)) + except FileError as exc: + raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc - def _build_archive() -> io.BytesIO: - buf = io.BytesIO() - with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf: - for raw_path in req.paths: - target = Path(raw_path).resolve() - if not target.exists(): - continue - if target.is_file(): - zf.write(target, target.name) - elif target.is_dir(): - for child in target.rglob("*"): - if child.is_file(): - arcname = str(child.relative_to(target.parent)) - zf.write(child, arcname) - buf.seek(0) - return buf +@router.get("/read", response_model=FileContent) +async def read_file( + request: Request, + path: str = Query(..., description="Absolute path to file"), +): + try: + return FileContent(**await Runtime.read_file(request, path)) + except FileError as exc: + raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc - buf = await asyncio.to_thread(_build_archive) - # Derive a sensible filename - if len(req.paths) == 1: - name = Path(req.paths[0]).name + ".zip" - else: - name = "archive.zip" +@router.post("/write") +async def write_file(request: Request, req: WriteFileRequest): + try: + return await Runtime.write_file(request, req.path, req.content) + except FileError as exc: + raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc + +@router.get("/matches", response_model=FileMatches) +async def file_matches( + request: Request, + query: str = Query(..., description="Literal text to match"), + path: str = Query(..., description="Root path to search"), + show_hidden: bool = Query(False, description="Include dotfiles and dot-directories"), + offset: int = Query(0, ge=0, description="Result offset"), + limit: int = Query(MATCH_PAGE_SIZE, ge=1, le=MATCH_PAGE_SIZE, description="Page size"), +): + if not query.strip(): + raise HTTPException(status_code=400, detail="Query must not be blank") + try: + result = await Runtime.file_matches(request, query, path, show_hidden, offset, limit) + return FileMatches(**result) + except FileError as exc: + raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc + + +@router.get("/search", response_model=SearchResponse) +async def search_files( + request: Request, + query: str = Query(..., description="Search term"), + path: str = Query(..., description="Root path to search"), + limit: int = Query(20, description="Max results"), +): + try: + return SearchResponse(**await Runtime.search_files(request, query, path, limit)) + except FileError as exc: + raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc + + +@router.post("/create") +async def create_item(request: Request, req: CreateRequest): + try: + return await Runtime.create_item(request, req.path, req.type) + except FileError as exc: + raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc + + +@router.post("/move") +async def move_item(request: Request, req: MoveRequest): + try: + return await Runtime.move_item(request, req.source, req.destination) + except FileError as exc: + raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc + + +@router.post("/delete") +async def delete_item(request: Request, req: DeleteRequest): + try: + return await Runtime.delete_item(request, req.path) + except FileError as exc: + raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc + + +@router.post("/upload") +async def upload_file( + request: Request, + file: UploadFile = FastAPIFile(...), + directory: str = Form(...), +): + try: + return await Runtime.upload_file( + request, + directory, + file.filename or "file", + await file.read(), + ) + except FileError as exc: + raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc + + +@router.get("/view") +async def view_file( + request: Request, + path: str = Query(..., description="Absolute path to file"), +): + try: + result = await Runtime.read_bytes(request, path) + except FileError as exc: + raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc return StreamingResponse( - buf, - media_type="application/zip", - headers={"Content-Disposition": f'attachment; filename="{name}"'}, + io.BytesIO(result["data"]), + media_type=result.get("media_type") or "application/octet-stream", ) -# ── Static file serving (path-based) ──────────────────────────── +@router.get("/download") +async def download_file( + request: Request, + path: str = Query(..., description="Absolute path to file"), +): + try: + result = await Runtime.read_bytes(request, path) + except FileError as exc: + raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc + return StreamingResponse( + io.BytesIO(result["data"]), + media_type="application/octet-stream", + headers={"Content-Disposition": f'attachment; filename="{result["name"]}"'}, + ) + + +@router.post("/archive") +async def archive_files(request: Request, req: ArchiveRequest): + try: + result = await Runtime.archive_files(request, req.paths) + except FileError as exc: + raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc + return StreamingResponse( + io.BytesIO(result["data"]), + media_type="application/zip", + headers={"Content-Disposition": f'attachment; filename="{result["name"]}"'}, + ) @router.get("/serve/{file_path:path}") -async def serve_static(file_path: str): - """Serve a file using path-based routing with correct MIME type. - - Unlike /view (query-string based), this uses path segments so - HTML files in iframes can resolve relative CSS/JS/image references. - E.g. /api/files/serve/home/user/project/index.html - """ - # Windows paths arrive as "C:/Users/..." - don't prepend / - if len(file_path) >= 2 and file_path[1] == ":": - target = Path(file_path).resolve() - else: - target = Path("/" + file_path).resolve() - - if not target.exists(): - raise HTTPException(status_code=404, detail=f"File not found: {file_path}") - if not target.is_file(): - raise HTTPException(status_code=400, detail=f"Not a file: {file_path}") - - media_type, _ = mimetypes.guess_type(str(target)) - - return FileResponse( - path=str(target), - media_type=media_type or "application/octet-stream", +async def serve_static(request: Request, file_path: str): + path = str(Path(file_path if len(file_path) >= 2 and file_path[1] == ":" else "/" + file_path)) + try: + result = await Runtime.read_bytes(request, path) + except FileError as exc: + raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc + return StreamingResponse( + io.BytesIO(result["data"]), + media_type=result.get("media_type") or "application/octet-stream", ) diff --git a/cptr/utils/agents/acp.py b/cptr/utils/agents/acp.py index 349bc43..5e4a87c 100644 --- a/cptr/utils/agents/acp.py +++ b/cptr/utils/agents/acp.py @@ -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()) diff --git a/cptr/utils/agents/attachments.py b/cptr/utils/agents/attachments.py index ca99847..01daf6b 100644 --- a/cptr/utils/agents/attachments.py +++ b/cptr/utils/agents/attachments.py @@ -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") diff --git a/cptr/utils/agents/claude_code.py b/cptr/utils/agents/claude_code.py index 8c2a72d..b78b709 100644 --- a/cptr/utils/agents/claude_code.py +++ b/cptr/utils/agents/claude_code.py @@ -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 diff --git a/cptr/utils/agents/cline.py b/cptr/utils/agents/cline.py index b4d7345..6bf1ed9 100644 --- a/cptr/utils/agents/cline.py +++ b/cptr/utils/agents/cline.py @@ -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() diff --git a/cptr/utils/agents/codex.py b/cptr/utils/agents/codex.py index 96c3182..5822417 100644 --- a/cptr/utils/agents/codex.py +++ b/cptr/utils/agents/codex.py @@ -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: diff --git a/cptr/utils/agents/cursor.py b/cptr/utils/agents/cursor.py index 7d5918a..4095378 100644 --- a/cptr/utils/agents/cursor.py +++ b/cptr/utils/agents/cursor.py @@ -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() diff --git a/cptr/utils/agents/gemini.py b/cptr/utils/agents/gemini.py index f75a6e5..17e27f3 100644 --- a/cptr/utils/agents/gemini.py +++ b/cptr/utils/agents/gemini.py @@ -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() diff --git a/cptr/utils/agents/grok.py b/cptr/utils/agents/grok.py index 1751fef..fa22cf7 100644 --- a/cptr/utils/agents/grok.py +++ b/cptr/utils/agents/grok.py @@ -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() diff --git a/cptr/utils/agents/opencode.py b/cptr/utils/agents/opencode.py index 1d3d6fe..4efe6ba 100644 --- a/cptr/utils/agents/opencode.py +++ b/cptr/utils/agents/opencode.py @@ -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( diff --git a/cptr/utils/agents/pi.py b/cptr/utils/agents/pi.py index 166e714..14e134d 100644 --- a/cptr/utils/agents/pi.py +++ b/cptr/utils/agents/pi.py @@ -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) diff --git a/cptr/utils/ai.py b/cptr/utils/ai.py index 3d103f5..c1986f7 100644 --- a/cptr/utils/ai.py +++ b/cptr/utils/ai.py @@ -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], diff --git a/cptr/utils/async_subagents.py b/cptr/utils/async_subagents.py index 3511fe1..d24eae3 100644 --- a/cptr/utils/async_subagents.py +++ b/cptr/utils/async_subagents.py @@ -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, diff --git a/cptr/utils/automations.py b/cptr/utils/automations.py index a5a39ef..70f9fa9 100644 --- a/cptr/utils/automations.py +++ b/cptr/utils/automations.py @@ -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, diff --git a/cptr/utils/bridge.py b/cptr/utils/bridge.py index 7181cc4..aae0c2b 100644 --- a/cptr/utils/bridge.py +++ b/cptr/utils/bridge.py @@ -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 diff --git a/cptr/utils/chat_export.py b/cptr/utils/chat_export.py index 39db186..3c7a14d 100644 --- a/cptr/utils/chat_export.py +++ b/cptr/utils/chat_export.py @@ -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}") diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 91923cc..3363db5 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -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, diff --git a/cptr/utils/identity.py b/cptr/utils/identity.py new file mode 100644 index 0000000..c4d13be --- /dev/null +++ b/cptr/utils/identity.py @@ -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) diff --git a/cptr/utils/images.py b/cptr/utils/images.py index 9fff865..17691f4 100644 --- a/cptr/utils/images.py +++ b/cptr/utils/images.py @@ -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, diff --git a/cptr/utils/memory.py b/cptr/utils/memory.py index b95b60d..1e78020 100644 --- a/cptr/utils/memory.py +++ b/cptr/utils/memory.py @@ -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, diff --git a/cptr/utils/prompt_templates.py b/cptr/utils/prompt_templates.py index 8dc4087..373b48d 100644 --- a/cptr/utils/prompt_templates.py +++ b/cptr/utils/prompt_templates.py @@ -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) diff --git a/cptr/utils/runtime.py b/cptr/utils/runtime.py new file mode 100644 index 0000000..e214691 --- /dev/null +++ b/cptr/utils/runtime.py @@ -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()) diff --git a/cptr/utils/skills.py b/cptr/utils/skills.py index 1023819..195b7fd 100644 --- a/cptr/utils/skills.py +++ b/cptr/utils/skills.py @@ -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, diff --git a/cptr/utils/summarize.py b/cptr/utils/summarize.py index e64a471..3ea534d 100644 --- a/cptr/utils/summarize.py +++ b/cptr/utils/summarize.py @@ -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, diff --git a/cptr/utils/terminal.py b/cptr/utils/terminal.py index a36a97f..b15d612 100644 --- a/cptr/utils/terminal.py +++ b/cptr/utils/terminal.py @@ -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() diff --git a/cptr/utils/timers.py b/cptr/utils/timers.py index 30d7a8b..e91791d 100644 --- a/cptr/utils/timers.py +++ b/cptr/utils/timers.py @@ -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, diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index b07bec3..4d175b8 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -24,6 +24,14 @@ from typing import Any, Literal, Optional, get_args, get_origin, get_type_hints from cptr.env import CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS, EXECUTE_TIMEOUT from cptr.utils.gitignore import is_gitignored, load_gitignore +from cptr.utils.identity import ( + IdentityUnavailable, + env_for, + expand_user_path, + identity_for_context, + preexec_for, +) +from cptr.utils.runtime import Runtime, FileError try: import fcntl @@ -62,7 +70,7 @@ MAX_TASK_CONTENT_CHARS = 4000 _TASK_TRUNCATION_MARKER = "... [truncated]" -def _spawn_pty(command: str, cwd: str, env: dict) -> tuple: +def _spawn_pty(command: str, cwd: str, env: dict, preexec_fn=None) -> tuple: """Spawn a command under a PTY (Unix only). Returns (proc, master_fd).""" master_fd, slave_fd = pty.openpty() try: @@ -76,6 +84,7 @@ def _spawn_pty(command: str, cwd: str, env: dict) -> tuple: cwd=cwd, env=env, start_new_session=True, + preexec_fn=preexec_fn, ) except Exception: os.close(slave_fd) @@ -321,9 +330,20 @@ def _command_session_snapshot(command_session_id: str, session: dict) -> dict[st def list_command_sessions( - workspace: str | None = None, chat_id: str | None = None + request, + workspace: str | None = None, + chat_id: str | None = None, + auth=None, + context: dict | None = None, ) -> list[dict[str, Any]]: sessions: list[dict[str, Any]] = [] + if context and context.get("request") is not None: + request = context["request"] + if request is not None: + auth = getattr(getattr(request, "state", None), "auth", None) + user_id = getattr(auth, "user_id", None) if auth is not None else None + if user_id is None and context: + user_id = context.get("user_id") for command_session_id, session in command_sessions.items(): if session.get("done"): continue @@ -331,13 +351,30 @@ def list_command_sessions( continue if chat_id and session.get("chat_id") != chat_id: continue + if user_id is not None and session.get("user_id") != user_id: + continue sessions.append(_command_session_snapshot(command_session_id, session)) sessions.sort(key=lambda item: (item["status"] != "running", -float(item["created_at"] or 0))) return sessions -def get_command_session(command_session_id: str) -> dict | None: - return command_sessions.get(command_session_id) +def get_command_session( + request, + command_session_id: str = "", + auth=None, + context: dict | None = None, +) -> dict | None: + session = command_sessions.get(command_session_id) + if context and context.get("request") is not None: + request = context["request"] + if request is not None: + auth = getattr(getattr(request, "state", None), "auth", None) + user_id = getattr(auth, "user_id", None) if auth is not None else None + if user_id is None and context: + user_id = context.get("user_id") + if not session or (user_id is not None and session.get("user_id") != user_id): + return None + return session def command_session_bytes_since(session: dict, offset: int) -> tuple[bytes, int]: @@ -351,8 +388,10 @@ def command_session_bytes_since(session: dict, offset: int) -> tuple[bytes, int] return raw, total -def send_command_session_input(command_session_id: str, data: bytes) -> str | None: - session = command_sessions.get(command_session_id) +def send_command_session_input( + request, command_session_id: str, data: bytes, **scope +) -> str | None: + session = get_command_session(request, command_session_id, **scope) if not session: return "command session not found" if session.get("done"): @@ -378,16 +417,16 @@ def send_command_session_input(command_session_id: str, data: bytes) -> str | No return None -async def drain_command_session_input(command_session_id: str) -> None: - session = command_sessions.get(command_session_id) +async def drain_command_session_input(request, command_session_id: str, **scope) -> None: + session = get_command_session(request, command_session_id, **scope) proc = session.get("proc") if session else None stdin = getattr(proc, "stdin", None) if stdin is not None and hasattr(stdin, "drain"): await stdin.drain() -def resize_command_session(command_session_id: str, rows: int, cols: int) -> None: - session = command_sessions.get(command_session_id) +def resize_command_session(request, command_session_id: str, rows: int, cols: int, **scope) -> None: + session = get_command_session(request, command_session_id, **scope) if not session or session.get("done"): return master_fd = session.get("master_fd") @@ -400,8 +439,10 @@ def resize_command_session(command_session_id: str, rows: int, cols: int) -> Non pass -def stop_command_session(command_session_id: str, force: bool = False) -> str | None: - session = command_sessions.get(command_session_id) +def stop_command_session( + request, command_session_id: str, force: bool = False, **scope +) -> str | None: + session = get_command_session(request, command_session_id, **scope) if not session: return "command session not found" if session.get("done"): @@ -444,12 +485,15 @@ def _read_image_file(full: Path, path: str) -> str: using Pillow. Falls back to a text error if Pillow is unavailable and the file is too large. """ + return _read_image_data(full.read_bytes(), full.suffix, path) + + +def _read_image_data(data: bytes, suffix: str, path: str) -> str: import base64 - size = full.stat().st_size - ext = full.suffix.lower() + size = len(data) + ext = suffix.lower() media_type = _IMAGE_MIME.get(ext, "image/png") - data = full.read_bytes() if size > _IMAGE_MAX_BYTES: try: @@ -484,7 +528,7 @@ def _read_image_file(full: Path, path: str) -> str: break scale *= 0.7 # more aggressive on each pass else: - return f"Error: image too large ({_human_size(full.stat().st_size)}) and could not be resized below 5MB." + return f"Error: image too large ({_human_size(size)}) and could not be resized below 5MB." except ImportError: return ( f"Error: image file is too large ({_human_size(size)}). " @@ -503,7 +547,7 @@ async def read_file( start_line: int = 0, end_line: int = 0, *, - workspace: str, + __context__: dict, ) -> str: """Read file contents with optional line range. Lines are 1-indexed. Supports relative workspace paths, absolute paths, and ~/ paths. @@ -512,7 +556,13 @@ async def read_file( :param start_line: First line to read (1-indexed, 0 = from beginning). :param end_line: Last line to read (inclusive, 0 = to end of file). """ - p = Path(path).expanduser() + workspace = __context__["workspace"] + try: + identity = await identity_for_context(__context__) + except IdentityUnavailable as e: + return f"Error: {e}" + + p = expand_user_path(path, identity) if p.is_absolute(): full = p.resolve() else: @@ -525,64 +575,54 @@ async def read_file( return _DOTENV_ERROR resolved = full.resolve() - home = Path.home().resolve() + home = Path(identity.home).resolve() home_rel = resolved.relative_to(home).as_posix() if resolved.is_relative_to(home) else "" if home_rel in _SENSITIVE_HOME_FILES or any( home_rel == d or home_rel.startswith(f"{d}/") for d in _SENSITIVE_HOME_DIRS ): return _SENSITIVE_READ_ERROR + request = __context__.get("request") try: - mode = full.stat().st_mode - except OSError: - mode = 0 + file_stat = await Runtime.stat(request or identity, str(full)) + except FileError: + return f"Error: file not found: {path}" + + mode = int(file_stat.get("mode") or 0) if any(check(mode) for check in (stat.S_ISBLK, stat.S_ISCHR, stat.S_ISFIFO, stat.S_ISSOCK)): return f"Error: cannot read special file: {full}" - if not full.is_file(): + if file_stat.get("type") != "file": return f"Error: file not found: {path}" # Image files: return base64 JSON instead of garbled text if full.suffix.lower() in IMAGE_EXTENSIONS: - return await asyncio.to_thread(_read_image_file, full, path) - - def _read(): - size = full.stat().st_size - if size > 500_000: - return f"Error: file too large ({size} bytes, max 500KB)" - - # Try strict text decoding first try: - content = full.read_text(errors="strict") - except (UnicodeDecodeError, ValueError): - # Binary file — try document extraction (PDF, DOCX, XLSX, etc.) - try: - from cptr.utils.documents import extract_by_path + image = await Runtime.read_bytes(request or identity, str(full)) + except FileError as e: + return f"Error: {e}" + return await asyncio.to_thread(_read_image_data, image["data"], full.suffix, path) - text = extract_by_path(str(full)) - if text: - lines = text.splitlines() - total = len(lines) - if start_line > 0 or end_line > 0: - s = max(1, start_line) - 1 - e = min(total, end_line) if end_line > 0 else total - selected = lines[s:e] - numbered = [f"{i + s + 1}: {line}" for i, line in enumerate(selected)] - return f"File: {path} | Lines {s + 1}-{e} of {total}\n" + "\n".join( - numbered - ) - capped = lines[:800] - numbered = [f"{i + 1}: {line}" for i, line in enumerate(capped)] - header = f"File: {path} | Total lines: {total}" - if total > 800: - header += " (showing first 800)" - return header + "\n" + "\n".join(numbered) - except ImportError as e: - return f"Error: reading {full.suffix} files requires: {e}" - except Exception as e: - return f"Error: failed to extract text from {path}: {e}" + size = int(file_stat.get("size") or 0) + if size > 500_000: + return f"Error: file too large ({size} bytes, max 500KB)" + + try: + file_data = await Runtime.read_file(request or identity, str(full)) + except FileError as e: + return f"Error: {e}" + if file_data.get("binary"): + try: + extracted = await Runtime.extract_text(request or identity, str(full)) + except FileError as e: + return f"Error: {e}" + content = str(extracted.get("text") or "") + if not content: return f"Error: binary file ({full.suffix}), cannot read as text" + else: + content = str(file_data.get("content") or "") + def _format_text(): lines = content.splitlines() total = len(lines) @@ -602,69 +642,28 @@ async def read_file( header += " (showing first 800)" return header + "\n" + "\n".join(numbered) - return await asyncio.to_thread(_read) + return await asyncio.to_thread(_format_text) async def list_directory( path: str = ".", recursive: bool = False, *, - workspace: str, + __context__: dict, ) -> str: """List files and directories with metadata (sizes, child counts). :param path: Directory path relative to workspace root. :param recursive: Whether to list recursively. """ - full = _resolve_path(path, workspace) - if not full.is_dir(): - return f"Error: not a directory: {path}" - - def _list(): - ignore = { - ".git", - "node_modules", - "__pycache__", - ".venv", - "venv", - ".next", - "build", - "dist", - ".cptr", - ".svelte-kit", - } - entries = [] - - if recursive: - for root, dirs, files in os.walk(full): - dirs[:] = sorted(d for d in dirs if d not in ignore) - rel = Path(root).relative_to(full) - for f in sorted(files): - fpath = Path(root) / f - try: - sz = fpath.stat().st_size - except OSError: - sz = 0 - entries.append(f"{rel / f} ({_human_size(sz)})") - else: - for item in sorted(full.iterdir()): - if item.name in ignore: - continue - if item.is_dir(): - try: - count = sum(1 for _ in item.rglob("*") if _.is_file()) - except (PermissionError, OSError): - count = 0 - entries.append(f"{item.name}/ ({count} files)") - else: - try: - sz = item.stat().st_size - except OSError: - sz = 0 - entries.append(f"{item.name} ({_human_size(sz)})") - - return "\n".join(entries) if entries else "(empty directory)" - - res = await asyncio.to_thread(_list) + workspace = __context__["workspace"] + request = __context__.get("request") + try: + identity = None if request is not None else await identity_for_context(__context__) + full = _resolve_path(path, workspace) + result = await Runtime.list_tree(request or identity, str(full), recursive) + except (ValueError, FileError, IdentityUnavailable) as e: + return f"Error: {e}" + res = str(result.get("text") or "") return _truncate_output(res, max_chars=CHAT_TOOL_MAX_CHARS) @@ -676,7 +675,7 @@ async def search_files( include: str = "", filenames_only: bool = False, *, - workspace: str, + __context__: dict, ) -> str: """Search files for a pattern using ripgrep. Fast, respects .gitignore. :param query: Search pattern (plain text or regex). @@ -686,22 +685,56 @@ async def search_files( :param include: Glob pattern to filter files (e.g. '*.py', '*.ts'). :param filenames_only: Only return filenames, not matching lines. """ - full = _resolve_path(path, workspace) - if not full.is_dir(): + workspace = __context__["workspace"] + request = __context__.get("request") + try: + identity = None if request is not None else await identity_for_context(__context__) + full = _resolve_path(path, workspace) + directory = await Runtime.stat(request or identity, str(full)) + except (ValueError, FileError, IdentityUnavailable) as e: + return f"Error: {e}" + if directory.get("type") != "directory": return f"Error: not a directory: {path}" # Try ripgrep first try: - res = await _search_rg(query, full, regex, case_insensitive, include, filenames_only) + res = await _search_rg( + query, + full, + regex, + case_insensitive, + include, + filenames_only, + await identity_for_context(__context__), + ) except FileNotFoundError: - # ripgrep not installed, fall back to Python - res = await _search_python(query, full, case_insensitive) + try: + matches = await Runtime.file_matches( + request or identity, query, str(full), False, 0, 50 + ) + except FileError as e: + return f"Error: {e}" + rows = [] + for item in matches.get("results", []): + rel = item.get("relative_path") or item.get("name") or "" + if filenames_only or item.get("name_match"): + rows.append(str(rel)) + else: + for match in item.get("content_matches") or []: + rows.append(f"{rel}:{match.get('line')}: {match.get('text')}") + res = "\n".join(rows) if rows else "No matches found." return _truncate_output(res, max_chars=CHAT_TOOL_MAX_CHARS) async def _search_rg( - query: str, full: Path, regex: bool, case_insensitive: bool, include: str, filenames_only: bool + query: str, + full: Path, + regex: bool, + case_insensitive: bool, + include: str, + filenames_only: bool, + identity, ) -> str: """Search using ripgrep.""" args = ["rg", "--no-heading", "--max-count=50", "--color=never"] @@ -727,6 +760,8 @@ async def _search_rg( *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, + env=env_for(identity, full) if identity.is_pam else None, + preexec_fn=preexec_for(identity) if identity.is_pam else None, ) stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=15) output = stdout.decode(errors="replace").strip() @@ -805,7 +840,7 @@ async def create_file( overwrite: bool = False, artifact_type: str = "", *, - workspace: str, + __context__: dict, ) -> str: """Create a new file, or create an artifact for user review. When artifact_type is set, path is optional. The artifact is saved automatically. @@ -814,6 +849,15 @@ async def create_file( :param overwrite: Set to true to overwrite an existing file. :param artifact_type: Set to 'implementation_plan' to present a plan for user review before coding. """ + workspace = __context__["workspace"] + request = __context__.get("request") + identity = None + if request is None: + try: + identity = await identity_for_context(__context__) + except IdentityUnavailable as e: + return f"Error: {e}" + # Artifact mode: save to .cptr/artifacts/ (same location as create_artifact) # When artifact_type is set, path is ignored. if artifact_type: @@ -821,13 +865,15 @@ async def create_file( ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") artifact_dir = Path(workspace) / ".cptr" / "artifacts" - artifact_dir.mkdir(parents=True, exist_ok=True) artifact_path = artifact_dir / f"{ts}_{artifact_type}.md" - def _write_artifact(): - artifact_path.write_text(content, encoding="utf-8") - - await asyncio.to_thread(_write_artifact) + try: + if request is not None: + await Runtime.write_file(request, str(artifact_path), content) + else: + await Runtime.write_file(identity, str(artifact_path), content) + except FileError as e: + return f"Error: {e}" rel_path = str(artifact_path.relative_to(Path(workspace))) display_title = artifact_type.replace("_", " ").title() @@ -849,11 +895,13 @@ async def create_file( if full.is_file() and not overwrite: return f"Error: file already exists: {path}. Use overwrite=true or edit_file to modify." - def _write(): - full.parent.mkdir(parents=True, exist_ok=True) - full.write_text(content, encoding="utf-8") - - await asyncio.to_thread(_write) + try: + if request is not None: + await Runtime.write_file(request, str(full), content) + else: + await Runtime.write_file(identity, str(full), content) + except FileError as e: + return f"Error: {e}" return f"Created {path} ({len(content)} bytes, {len(content.splitlines())} lines)" @@ -862,7 +910,7 @@ async def create_artifact( artifact_type: str = "implementation_plan", title: str = "", *, - workspace: str, + __context__: dict, ) -> str: """Create an artifact for user review. Use for implementation plans and analysis. :param content: Artifact content as markdown. @@ -871,16 +919,26 @@ async def create_artifact( """ from datetime import datetime, timezone + workspace = __context__["workspace"] + request = __context__.get("request") + identity = None + if request is None: + try: + identity = await identity_for_context(__context__) + except IdentityUnavailable as e: + return f"Error: {e}" artifact_type = artifact_type or "implementation_plan" ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") artifact_dir = Path(workspace) / ".cptr" / "artifacts" - artifact_dir.mkdir(parents=True, exist_ok=True) artifact_path = artifact_dir / f"{ts}_{artifact_type}.md" - def _write(): - artifact_path.write_text(content, encoding="utf-8") - - await asyncio.to_thread(_write) + try: + if request is not None: + await Runtime.write_file(request, str(artifact_path), content) + else: + await Runtime.write_file(identity, str(artifact_path), content) + except FileError as e: + return f"Error: {e}" display_title = title or artifact_type.replace("_", " ").title() rel_path = str(artifact_path.relative_to(Path(workspace))) @@ -1019,30 +1077,46 @@ async def clear_active_tasks( ) -async def write_file(path: str, content: str, *, workspace: str) -> str: +async def write_file(path: str, content: str, *, __context__: dict) -> str: """Write or create a file (full content). Prefer edit_file for modifications. :param path: Path relative to workspace root. :param content: File contents to write. """ + workspace = __context__["workspace"] + request = __context__.get("request") + identity = None + if request is None: + try: + identity = await identity_for_context(__context__) + except IdentityUnavailable as e: + return f"Error: {e}" full = _resolve_path(path, workspace) if _is_dotenv(full): return _DOTENV_ERROR - def _write(): - full.parent.mkdir(parents=True, exist_ok=True) - full.write_text(content, encoding="utf-8") - - await asyncio.to_thread(_write) + try: + if request is not None: + await Runtime.write_file(request, str(full), content) + else: + await Runtime.write_file(identity, str(full), content) + except FileError as e: + return f"Error: {e}" return f"Wrote {len(content)} bytes to {path}" -async def display_file(path: str, *, workspace: str) -> str: +async def display_file(path: str, *, __context__: dict) -> str: """Display a workspace file inline in chat. Use when the user asks to see, preview, render, or display a file you created or found. :param path: Path relative to workspace root. """ if not path: return "Error: path is required." + workspace = __context__["workspace"] + request = __context__.get("request") + try: + identity = None if request is not None else await identity_for_context(__context__) + except IdentityUnavailable as e: + return f"Error: {e}" try: full = _resolve_path(path, workspace) @@ -1051,12 +1125,13 @@ async def display_file(path: str, *, workspace: str) -> str: if _is_dotenv(full): return _DOTENV_ERROR - if not full.exists(): + try: + file_stat = await Runtime.stat(request or identity, str(full)) + except FileError: return f"Error: file not found: {path}" - if not full.is_file(): + if file_stat.get("type") != "file": return f"Error: not a file: {path}" - stat = await asyncio.to_thread(full.stat) mime_type = mimetypes.guess_type(str(full))[0] or "application/octet-stream" ws = Path(workspace).resolve() try: @@ -1070,7 +1145,7 @@ async def display_file(path: str, *, workspace: str) -> str: "full_path": str(full), "workspace": str(ws), "name": full.name, - "size": stat.st_size, + "size": file_stat.get("size") or 0, "mime_type": mime_type, "kind": _file_kind(full, mime_type), }, @@ -1085,7 +1160,7 @@ async def edit_file( start_line: int = 0, end_line: int = 0, *, - workspace: str, + __context__: dict, ) -> str: """Replace a specific text block in a file. Only provide the text that changes. :param path: Path relative to workspace root. @@ -1094,51 +1169,66 @@ async def edit_file( :param start_line: Narrow search to lines starting here (1-indexed, 0 = from start). :param end_line: Narrow search to lines ending here (0 = to end). """ + workspace = __context__["workspace"] + request = __context__.get("request") + identity = None + if request is None: + try: + identity = await identity_for_context(__context__) + except IdentityUnavailable as e: + return f"Error: {e}" full = _resolve_path(path, workspace) if _is_dotenv(full): return _DOTENV_ERROR - if not full.is_file(): - return f"Error: file not found: {path}" - - def _edit(): - content = full.read_text(encoding="utf-8", errors="replace") - - if start_line > 0 or end_line > 0: - lines = content.splitlines(keepends=True) - total = len(lines) - s = max(1, start_line) - 1 - e = min(total, end_line) if end_line > 0 else total - region = "".join(lines[s:e]) - - if target not in region: - return f"Error: target text not found in lines {s + 1}-{e} of {path}" - - count = region.count(target) - if count > 1: - return ( - f"Error: target text found {count} times in lines {s + 1}-{e}. " - f"Narrow the line range or use a more specific target." - ) - - new_region = region.replace(target, replacement, 1) - new_content = "".join(lines[:s]) + new_region + "".join(lines[e:]) + try: + if request is not None: + file_data = await Runtime.read_file(request, str(full)) else: - count = content.count(target) - if count == 0: - return f"Error: target text not found in {path}" - if count > 1: - return ( - f"Error: target text found {count} times in {path}. " - f"Use start_line/end_line to disambiguate." - ) - new_content = content.replace(target, replacement, 1) + file_data = await Runtime.read_file(identity, str(full)) + except FileError: + return f"Error: file not found: {path}" + if file_data.get("binary"): + return f"Error: not a text file: {path}" - full.write_text(new_content, encoding="utf-8") - return None # success sentinel + content = str(file_data.get("content") or "") - result = await asyncio.to_thread(_edit) - if result is not None: - return result + if start_line > 0 or end_line > 0: + lines = content.splitlines(keepends=True) + total = len(lines) + s = max(1, start_line) - 1 + e = min(total, end_line) if end_line > 0 else total + region = "".join(lines[s:e]) + + if target not in region: + return f"Error: target text not found in lines {s + 1}-{e} of {path}" + + count = region.count(target) + if count > 1: + return ( + f"Error: target text found {count} times in lines {s + 1}-{e}. " + f"Narrow the line range or use a more specific target." + ) + + new_region = region.replace(target, replacement, 1) + new_content = "".join(lines[:s]) + new_region + "".join(lines[e:]) + else: + count = content.count(target) + if count == 0: + return f"Error: target text not found in {path}" + if count > 1: + return ( + f"Error: target text found {count} times in {path}. " + f"Use start_line/end_line to disambiguate." + ) + new_content = content.replace(target, replacement, 1) + + try: + if request is not None: + await Runtime.write_file(request, str(full), new_content) + else: + await Runtime.write_file(identity, str(full), new_content) + except FileError as e: + return f"Error: {e}" target_lines = len(target.splitlines()) replacement_lines = len(replacement.splitlines()) @@ -1152,17 +1242,32 @@ async def multi_edit_file( path: str, edits: str, *, - workspace: str, + __context__: dict, ) -> str: """Apply multiple non-contiguous edits to a file in one operation. :param path: Path relative to workspace root. :param edits: JSON array of edit objects, each with 'target' and 'replacement' strings, and optional 'start_line'/'end_line' integers. """ + workspace = __context__["workspace"] + request = __context__.get("request") + identity = None + if request is None: + try: + identity = await identity_for_context(__context__) + except IdentityUnavailable as e: + return f"Error: {e}" full = _resolve_path(path, workspace) if _is_dotenv(full): return _DOTENV_ERROR - if not full.is_file(): + try: + if request is not None: + file_data = await Runtime.read_file(request, str(full)) + else: + file_data = await Runtime.read_file(identity, str(full)) + except FileError: return f"Error: file not found: {path}" + if file_data.get("binary"): + return f"Error: not a text file: {path}" try: edit_list = json.loads(edits) @@ -1172,34 +1277,37 @@ async def multi_edit_file( if not isinstance(edit_list, list) or not edit_list: return "Error: edits must be a non-empty JSON array" - def _apply(): - content = full.read_text(encoding="utf-8", errors="replace") - applied = 0 + content = str(file_data.get("content") or "") + applied = 0 - for i, edit in enumerate(edit_list): - target = edit.get("target", "") - replacement = edit.get("replacement", "") + for i, edit in enumerate(edit_list): + target = edit.get("target", "") + replacement = edit.get("replacement", "") - if not target: - return f"Error: edit {i + 1} missing 'target'" + if not target: + return f"Error: edit {i + 1} missing 'target'" - if target not in content: - return f"Error: target not found for edit {i + 1}: {target[:100]}..." + if target not in content: + return f"Error: target not found for edit {i + 1}: {target[:100]}..." - count = content.count(target) - if count > 1: - return ( - f"Error: edit {i + 1} target found {count} times. " - f"Each target must be unique in the file." - ) + count = content.count(target) + if count > 1: + return ( + f"Error: edit {i + 1} target found {count} times. " + f"Each target must be unique in the file." + ) - content = content.replace(target, replacement, 1) - applied += 1 + content = content.replace(target, replacement, 1) + applied += 1 - full.write_text(content, encoding="utf-8") - return f"Applied {applied} edits to {path}" - - return await asyncio.to_thread(_apply) + try: + if request is not None: + await Runtime.write_file(request, str(full), content) + else: + await Runtime.write_file(identity, str(full), content) + except FileError as e: + return f"Error: {e}" + return f"Applied {applied} edits to {path}" async def run_command( @@ -1215,21 +1323,40 @@ async def run_command( :param wait: Seconds to wait for the command to finish before returning (max 300). Returns early if done sooner. Null returns immediately. Use 30-60 for installs and builds, 5-10 for quick commands, null or 0 for long-lived servers. """ workspace = __context__["workspace"] + try: + identity = await identity_for_context(__context__) + except IdentityUnavailable as e: + return f"Error: {e}" + user_id = identity.app_user_id or __context__.get("user_id") + request = __context__.get("request") + work_dir = _resolve_path(cwd, workspace) if not work_dir.is_dir(): return f"Error: not a directory: {cwd}" - active = sum(1 for t in command_sessions.values() if not t.get("done")) + active = sum( + 1 + for t in command_sessions.values() + if not t.get("done") and (user_id is None or t.get("user_id") == user_id) + ) if active >= MAX_COMMAND_SESSIONS: return f"Error: too many running command sessions ({active}/{MAX_COMMAND_SESSIONS}). Stop one first." - env = {**os.environ, "PAGER": "cat", "GIT_PAGER": "cat"} + if identity.is_pam: + env = env_for(identity, work_dir, {"PAGER": "cat", "GIT_PAGER": "cat"}) + preexec = preexec_for(identity) + else: + env = {**os.environ, "PAGER": "cat", "GIT_PAGER": "cat"} + preexec = None master_fd = None try: if _PTY_AVAILABLE: - proc, master_fd = _spawn_pty(command, str(work_dir), env) + proc, master_fd = _spawn_pty(command, str(work_dir), env, preexec) else: + kwargs = {} + if preexec is not None: + kwargs["preexec_fn"] = preexec proc = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, @@ -1237,14 +1364,24 @@ async def run_command( stdin=asyncio.subprocess.PIPE, cwd=str(work_dir), env=env, + **kwargs, ) except Exception as e: return f"Error: {e}" command_session_id = uuid.uuid4().hex[:8] - log_dir = Path(workspace) / ".cptr" / "task_logs" - log_dir.mkdir(parents=True, exist_ok=True) - log_path = log_dir / f"{command_session_id}.jsonl" + log_path = Path(workspace) / ".cptr" / "task_logs" / f"{command_session_id}.jsonl" + try: + if request is not None: + await Runtime.write_file(request, str(log_path), "") + else: + await Runtime.write_file(identity, str(log_path), "") + except FileError as e: + try: + _kill_process_group(proc.pid) + except Exception: + pass + return f"Error: {e}" command_sessions[command_session_id] = { "command_session_id": command_session_id, @@ -1254,6 +1391,8 @@ async def run_command( "total_bytes": 0, "command": command, "workspace": workspace, + "user_id": user_id, + "identity": identity, "chat_id": __context__.get("chat_id"), "message_id": __context__.get("message_id"), "call_id": __context__.get("call_id"), @@ -1292,16 +1431,22 @@ async def run_command( async def check_task( - task_id: str, offset: int = 0, wait: Optional[int] = None, *, workspace: str + task_id: str, offset: int = 0, wait: Optional[int] = None, *, __context__: dict ) -> str: """Check status and recent output of a background task. :param task_id: The task ID returned by run_command. :param offset: Byte offset from previous check. Pass next_offset from the last response to get only new output. :param wait: Seconds to wait for the task to finish before returning (max 300). Returns early if done sooner. Null returns immediately. """ - task = command_sessions.get(task_id) + request = __context__.get("request") + task = get_command_session(request, task_id, context=__context__) if not task: - available = list(command_sessions.keys()) + user_id = __context__.get("user_id") + available = [ + session_id + for session_id, session in command_sessions.items() + if session.get("user_id") == user_id + ] return f"Error: no task with id '{task_id}'. Active tasks: {available or 'none'}" # Optionally wait for the task to finish @@ -1339,34 +1484,46 @@ async def check_task( return f"Task {task_id}: {status}\nCommand: {task['command']}\nnext_offset: {next_offset}\n---\n{output}" -async def kill_task(task_id: str, force: bool = False, *, workspace: str) -> str: +async def kill_task(task_id: str, force: bool = False, *, __context__: dict) -> str: """Terminate a running task. Sends SIGTERM for graceful shutdown by default. :param task_id: The task ID to kill. :param force: Send SIGKILL instead of SIGTERM for immediate termination. """ - task = command_sessions.get(task_id) + request = __context__.get("request") + task = get_command_session(request, task_id, context=__context__) if not task: - available = list(command_sessions.keys()) + user_id = __context__.get("user_id") + available = [ + session_id + for session_id, session in command_sessions.items() + if session.get("user_id") == user_id + ] return f"Error: no task with id '{task_id}'. Active tasks: {available or 'none'}" if task.get("done", False): exit_code = task.get("exit_code") return f"Task {task_id} already finished (code {exit_code})" - stop_command_session(task_id, force=force) + stop_command_session(request, task_id, force=force, context=__context__) action = "Killed" if force else "Terminated" return f"{action} task {task_id}" -async def send_input(task_id: str, input: str, *, workspace: str) -> str: +async def send_input(task_id: str, input: str, *, __context__: dict) -> str: """Send input to a running task's stdin. Use for interactive prompts, REPLs, or control characters. :param task_id: The task ID returned by run_command. :param input: Text to send. Use \\n for Enter, \\x03 for Ctrl-C, \\x04 for Ctrl-D. """ - task = command_sessions.get(task_id) + request = __context__.get("request") + task = get_command_session(request, task_id, context=__context__) if not task: - available = list(command_sessions.keys()) + user_id = __context__.get("user_id") + available = [ + session_id + for session_id, session in command_sessions.items() + if session.get("user_id") == user_id + ] return f"Error: no task '{task_id}'. Active: {available or 'none'}" if task.get("done", False): @@ -1378,10 +1535,10 @@ async def send_input(task_id: str, input: str, *, workspace: str) -> str: except (UnicodeDecodeError, ValueError): text = input - error = send_command_session_input(task_id, text.encode()) + error = send_command_session_input(request, task_id, text.encode(), context=__context__) if error: return f"Error: {error} for task {task_id}" - await drain_command_session_input(task_id) + await drain_command_session_input(request, task_id, context=__context__) return f"Sent {len(text)} bytes to task {task_id}" @@ -1919,14 +2076,21 @@ async def browser_screenshot( # Save to workspace workspace = __context__.get("workspace", ".") - screenshots_dir = Path(workspace) / ".cptr" / "screenshots" - screenshots_dir.mkdir(parents=True, exist_ok=True) import time filename = f"screenshot_{int(time.time())}.png" - filepath = screenshots_dir / filename - filepath.write_bytes(png_bytes) + filepath = Path(workspace) / ".cptr" / "screenshots" / filename + request = __context__.get("request") + try: + if request is not None: + await Runtime.write_file(request, str(filepath), png_bytes) + else: + await Runtime.write_file( + await identity_for_context(__context__), str(filepath), png_bytes + ) + except FileError as e: + return f"Error: {e}" return f"Screenshot saved: {filepath}" @@ -2627,6 +2791,7 @@ async def _run_existing_subagent_chat( from cptr.utils.model_targets import ApiModelTarget await run_chat_task( + None, message_id=assistant_msg_id, chat_id=chat_id, user_id=user_id,