diff --git a/cptr/app.py b/cptr/app.py index 16e3883..94af51a 100644 --- a/cptr/app.py +++ b/cptr/app.py @@ -79,7 +79,7 @@ async def lifespan(app: FastAPI): # Start messaging bots from cptr.utils.bridge import BotManager - app.state.bot_manager = BotManager() + app.state.bot_manager = BotManager(app) await app.state.bot_manager.start_all() try: diff --git a/cptr/routers/automations.py b/cptr/routers/automations.py index 0168089..3b33d25 100644 --- a/cptr/routers/automations.py +++ b/cptr/routers/automations.py @@ -270,7 +270,7 @@ async def run_automation_now( from cptr.utils.automations import execute_automation - asyncio.create_task(execute_automation(automation, webhook_payload=webhook_payload)) + asyncio.create_task(execute_automation(request.app, automation, webhook_payload=webhook_payload)) return _automation_dict(automation) diff --git a/cptr/routers/chat.py b/cptr/routers/chat.py index 15805bd..0b92138 100644 --- a/cptr/routers/chat.py +++ b/cptr/routers/chat.py @@ -662,7 +662,7 @@ async def get_chat( raise HTTPException(404, "chat not found") messages = await ChatMessage.get_all_by_chat(chat_id) - context_usage = await _get_chat_context_usage(chat, model_id) + context_usage = await _get_chat_context_usage(request, chat, model_id) from cptr.utils.chat_task import get_active_chat_ids from cptr.utils.tools import _normalize_tasks @@ -716,7 +716,9 @@ async def _get_context_leaf_message_id(chat) -> str | None: return messages[-1].id if messages else None -async def _get_chat_context_usage(chat, model_id: str | None = None) -> dict | None: +async def _get_chat_context_usage( + request: Request, chat, model_id: str | None = None +) -> dict | None: message_id = await _get_context_leaf_message_id(chat) if not message_id: return None @@ -734,7 +736,7 @@ async def _get_chat_context_usage(chat, model_id: str | None = None) -> dict | N workspace = (chat.meta or {}).get("workspace", "") model = model_id or await _infer_chat_model(chat.id) compact_token_threshold = await load_compact_token_threshold(model) - system = await _load_system_prompt(workspace, model or "", user_id=chat.user_id) + system = await _load_system_prompt(request, workspace, model or "", user_id=chat.user_id) if existing_summary: system += f"\n\n[CONVERSATION SUMMARY]\n{existing_summary}" @@ -963,7 +965,7 @@ async def fork_chat(request: Request, chat_id: str, body: ForkChatRequest | None from cptr.utils.chat_export import export_chat_to_file - await export_chat_to_file(fork.id) + await export_chat_to_file(request, fork.id) return {"ok": True, "chat_id": fork.id} @@ -1102,7 +1104,7 @@ async def send_message(request: Request, body: SendMessageRequest): ) if queued_msg: - await process_pending_chat_inputs(chat.id, user_id, workspace or "") + await process_pending_chat_inputs(request, chat.id, user_id, workspace or "") return {"chat_id": chat.id, "message_id": queued_msg.id, "queued": True} if not assistant_msg: @@ -1111,7 +1113,7 @@ async def send_message(request: Request, body: SendMessageRequest): # Export JSON immediately so list_chats discovers it right away from cptr.utils.chat_export import export_chat_to_file - await export_chat_to_file(chat.id) + await export_chat_to_file(request, chat.id) start_task( request, @@ -1156,7 +1158,7 @@ async def compact_chat(request: Request, chat_id: str, body: CompactRequest): return {"ok": True, "compacted": False, "reason": "empty", "context_usage": None} current_msg = await ChatMessage.get_by_id(message_id) if not current_msg or not current_msg.parent_id: - usage = await _get_chat_context_usage(chat, model_id) + usage = await _get_chat_context_usage(request, chat, model_id) return {"ok": True, "compacted": False, "reason": "too_short", "context_usage": usage} from cptr.utils.model_targets import ( @@ -1176,7 +1178,7 @@ async def compact_chat(request: Request, chat_id: str, body: CompactRequest): compacted_messages = messages[:-1] keep_zone = messages[-1:] if not compacted_messages or not keep_zone: - usage = await _get_chat_context_usage(chat, model_id) + usage = await _get_chat_context_usage(request, chat, model_id) return {"ok": True, "compacted": False, "reason": "too_short", "context_usage": usage} summary = await summarize_messages( @@ -1190,8 +1192,8 @@ async def compact_chat(request: Request, chat_id: str, body: CompactRequest): from cptr.utils.chat_export import export_chat_to_file - await export_chat_to_file(chat_id) - usage = await _get_chat_context_usage(chat, model_id) + await export_chat_to_file(request, chat_id) + usage = await _get_chat_context_usage(request, chat, model_id) return { "ok": True, "compacted": True, @@ -1399,7 +1401,7 @@ async def cancel_task_endpoint(request: Request, chat_id: str, message_id: str): from cptr.utils.chat_task import process_pending_chat_inputs workspace = chat.meta.get("workspace", "") if chat.meta else "" - await process_pending_chat_inputs(chat_id, user_id, workspace) + await process_pending_chat_inputs(request, chat_id, user_id, workspace) return {"ok": True} diff --git a/cptr/routers/gateway.py b/cptr/routers/gateway.py index d3c4919..0ea05c6 100644 --- a/cptr/routers/gateway.py +++ b/cptr/routers/gateway.py @@ -202,7 +202,7 @@ 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) + await export_chat_to_file(request, chat_id) # 5. Create output queue and start the agentic loop output_queue: asyncio.Queue = asyncio.Queue() diff --git a/cptr/routers/images.py b/cptr/routers/images.py index b172920..d053094 100644 --- a/cptr/routers/images.py +++ b/cptr/routers/images.py @@ -64,6 +64,7 @@ async def create_image_generation(request: Request, body: GenerateImageRequest): user_id = _get_user(request) try: images = await generate_images( + request, body.prompt, user_id=user_id, model=body.model, @@ -81,6 +82,7 @@ async def create_image_edit(request: Request, body: EditImageRequest): user_id = _get_user(request) try: images = await edit_images( + request, body.prompt, body.image_ids, user_id=user_id, diff --git a/cptr/routers/memory.py b/cptr/routers/memory.py index ecdc530..649513b 100644 --- a/cptr/routers/memory.py +++ b/cptr/routers/memory.py @@ -70,7 +70,7 @@ class MemoryReviewRequest(BaseModel): @router.get("") async def get_memory(request: Request, workspace: str = Query("")): user_id = _get_user(request) - return await read_memory_state(user_id, workspace) + return await read_memory_state(request, user_id, workspace) @router.put("/config") @@ -83,6 +83,7 @@ async def put_memory_settings(request: Request, body: MemorySettingsRequest): async def update_memory(request: Request, body: MemoryUpdateRequest): user_id = _get_user(request) return await remember( + request, user_id=user_id, workspace=body.workspace, scope=body.scope, @@ -136,6 +137,7 @@ async def get_memory_file( user_id = _get_user(request) try: return await read_memory_file_state( + request, user_id=user_id, workspace=workspace, scope=scope, @@ -148,4 +150,4 @@ async def get_memory_file( @router.post("/review") async def review_memory(request: Request, body: MemoryReviewRequest): user_id = _get_user(request) - return await review_memory_vault(user_id, body.workspace) + return await review_memory_vault(request, user_id, body.workspace) diff --git a/cptr/routers/workspace.py b/cptr/routers/workspace.py index 357a40e..5f05c92 100644 --- a/cptr/routers/workspace.py +++ b/cptr/routers/workspace.py @@ -118,7 +118,7 @@ async def send_file(request: Request, path: str, *, download: bool = False): ) try: - result = await Runtime.stream_file(identity, path) + result = await Runtime.stream_file(request, path) except FileError as exc: raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc headers = {"Content-Length": str(result["size"])} diff --git a/cptr/utils/agents/attachments.py b/cptr/utils/agents/attachments.py index 01daf6b..4e64467 100644 --- a/cptr/utils/agents/attachments.py +++ b/cptr/utils/agents/attachments.py @@ -8,7 +8,7 @@ from dataclasses import dataclass from pathlib import Path from typing import Any -from cptr.utils.identity import identity_for_user_id +from fastapi import Request from cptr.utils.runtime import Runtime from cptr.utils.storage import get_storage @@ -40,6 +40,7 @@ def _is_image(file_meta: dict[str, Any]) -> bool: async def prepare_agent_attachments( + request: Request, *, workspace: str, user_id: str | None, @@ -61,7 +62,6 @@ async def prepare_agent_attachments( 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 @@ -76,11 +76,7 @@ async def prepare_agent_attachments( name = _safe_segment(str(file_meta.get("name") or file_id)) path = root / f"{_safe_segment(file_id)}-{name}" - if identity: - await Runtime.write_file(identity, str(path), data) - else: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(data) + await Runtime.write_file(request, str(path), data) mime_type = str( file_meta.get("content_type") or file_meta.get("mime_type") diff --git a/cptr/utils/async_subagents.py b/cptr/utils/async_subagents.py index d24eae3..9ddbd74 100644 --- a/cptr/utils/async_subagents.py +++ b/cptr/utils/async_subagents.py @@ -247,7 +247,9 @@ async def _inject_completion(record: dict[str, Any]) -> None: ) await Chat.update_current_message(parent_chat_id, assistant_msg.id, now_ms()) - await export_chat_to_file(parent_chat_id) + request = record["request"] + await export_chat_to_file(request, parent_chat_id) + if direct_timer_completion: await emit_to_user( user_id, @@ -280,7 +282,7 @@ async def _inject_completion(record: dict[str, Any]) -> None: ) start_task( - None, + request, 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 70f9fa9..5225677 100644 --- a/cptr/utils/automations.py +++ b/cptr/utils/automations.py @@ -100,7 +100,7 @@ async def scheduler_worker_loop(app) -> None: if batch: logger.info("Claimed %d due automation(s)", len(batch)) for automation in batch: - asyncio.create_task(execute_automation(automation)) + asyncio.create_task(execute_automation(app, automation)) except Exception: logger.exception("Scheduler worker error") @@ -112,7 +112,7 @@ async def scheduler_worker_loop(app) -> None: #################### -async def execute_automation(automation, webhook_payload: str | None = None) -> None: +async def execute_automation(app, automation, webhook_payload: str | None = None) -> None: """Execute an automation by creating a chat and calling start_task(). Creates a real chat + messages, then uses the same agentic loop @@ -124,10 +124,12 @@ async def execute_automation(automation, webhook_payload: str | None = None) -> from cptr.models import Chat, ChatMessage from cptr.models.automations import AutomationRun from cptr.utils.config import now_ms + from cptr.utils.identity import internal_request_for_user from cptr.socket.main import emit_to_user try: workspace = automation.workspace + request = await internal_request_for_user(app, automation.user_id) model_id = automation.model_id prompt = automation.prompt @@ -168,11 +170,10 @@ async def execute_automation(automation, webhook_payload: str | None = None) -> await Chat.update_current_message(chat.id, assistant_msg.id, now_ms()) marker = Path(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(automation.user_id) - await Runtime.write_file(identity, str(marker), "{}") + await Runtime.write_file(request, str(marker), "{}") from cptr.utils.model_targets import resolve_model_target @@ -182,7 +183,7 @@ async def execute_automation(automation, webhook_payload: str | None = None) -> from cptr.utils.chat_task import start_task start_task( - None, + request, 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 aae0c2b..4179364 100644 --- a/cptr/utils/bridge.py +++ b/cptr/utils/bridge.py @@ -244,8 +244,9 @@ class BotManager: asyncio tasks. """ - def __init__(self) -> None: + def __init__(self, app=None) -> None: global _current_bot_manager + self.app = app self._adapters: dict[str, BaseAdapter] = {} # bot_id → adapter self._tasks: dict[str, asyncio.Task] = {} # bot_id → polling task self._stream_tasks: dict[str, asyncio.Task] = {} # key → streaming task @@ -619,11 +620,11 @@ class BotManager: ) marker = Path(bot["workspace"]) / ".cptr" / "chats" / f"{chat.id}.json" - from cptr.utils.identity import identity_for_user_id + from cptr.utils.identity import internal_request_for_user from cptr.utils.runtime import Runtime - identity = await identity_for_user_id(bot["user_id"]) - await Runtime.write_file(identity, str(marker), "{}") + request = await internal_request_for_user(self.app, bot["user_id"]) + await Runtime.write_file(request, str(marker), "{}") return chat.id @@ -806,10 +807,11 @@ class BotManager: ) 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 + from cptr.utils.identity import internal_request_for_user - await export_chat_to_file(chat_id) + request = await internal_request_for_user(self.app, bot["user_id"]) + await export_chat_to_file(request, chat_id) # Send initial "thinking" message for non-draft platforms (Discord) # Telegram uses sendMessageDraft which handles this natively @@ -834,7 +836,7 @@ class BotManager: # Start the agentic loop start_task( - None, + request, message_id=assistant_msg.id, chat_id=chat_id, user_id=bot["user_id"], diff --git a/cptr/utils/chat_export.py b/cptr/utils/chat_export.py index 3c7a14d..9ffa825 100644 --- a/cptr/utils/chat_export.py +++ b/cptr/utils/chat_export.py @@ -10,9 +10,9 @@ import json import logging from pathlib import Path +from fastapi import Request 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__) @@ -23,7 +23,7 @@ def chat_directory(workspace: str | None) -> Path: return Path(workspace) / ".cptr" / "chats" if workspace else DATA_DIR / "chats" -async def export_chat_to_file(chat_id: str) -> None: +async def export_chat_to_file(request: Request, chat_id: str) -> None: """Regenerate .cptr/chats/{id}.json from the DB.""" chat = await Chat.get_by_id(chat_id) if not chat: @@ -78,8 +78,7 @@ async def export_chat_to_file(chat_id: str) -> None: 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) + await Runtime.write_file(request, str(target), content) else: target.parent.mkdir(parents=True, exist_ok=True) target.write_text(content, encoding="utf-8") diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 3363db5..eecda2e 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -562,7 +562,7 @@ def _first_ready_pending_input_batch(messages: list[ChatMessage]) -> list[ChatMe return batch -async def process_pending_chat_inputs(chat_id: str, user_id: str, workspace: str): +async def process_pending_chat_inputs(request, chat_id: str, user_id: str, workspace: str): """Start the next task from user-queued prompts or internal subagent results. Uses a per-chat lock to prevent concurrent processing from @@ -645,7 +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, + request, message_id=assistant_msg.id, chat_id=chat_id, user_id=user_id, @@ -696,7 +696,10 @@ async def reconcile_chat_state(): if chat: workspace = (chat.meta or {}).get("workspace", "") try: - await process_pending_chat_inputs(cid, chat.user_id, workspace) + from cptr.utils.identity import internal_request_for_user + + request = await internal_request_for_user(None, chat.user_id) + await process_pending_chat_inputs(request, cid, chat.user_id, workspace) except Exception: logger.exception("[reconcile] Failed to process pending inputs for chat %s", cid) @@ -1569,6 +1572,7 @@ async def run_chat_task( ) memory_message, memory_files = _memory_recall_inputs(messages, regeneration_prompt) system = await _load_system_prompt( + request, agent_workspace, agent_target.full_model_id, user_id=user_id, @@ -1585,6 +1589,7 @@ async def run_chat_task( if isinstance(meta_files, list): current_user_files = meta_files agent_attachments = await prepare_agent_attachments( + request, workspace=agent_workspace, user_id=user_id, chat_id=chat_id, @@ -1885,6 +1890,7 @@ async def run_chat_task( ) memory_message, memory_files = _memory_recall_inputs(messages, regeneration_prompt) system = await _load_system_prompt( + request, workspace, model, user_id=user_id, @@ -2166,6 +2172,7 @@ async def run_chat_task( # Append summary to system prompt (works for all providers) memory_message, memory_files = _memory_recall_inputs(keep_zone, regeneration_prompt) system = await _load_system_prompt( + request, workspace, model, user_id=user_id, @@ -2820,7 +2827,7 @@ async def run_chat_task( except Exception: logger.debug("[task %s] active-state emit failed", message_id[:8], exc_info=True) try: - await export_chat_to_file(chat_id) + await export_chat_to_file(request, chat_id) except Exception: logger.exception(f"Failed to export chat {chat_id}") # Generate a proper title if the chat still has the auto-truncated fallback @@ -2858,6 +2865,7 @@ async def run_chat_task( from cptr.utils.memory import review_memory_after_turn await review_memory_after_turn( + request, user_id=user_id, message_id=message_id, workspace=workspace, @@ -2890,6 +2898,6 @@ async def run_chat_task( logger.debug("[skills] Failed to review conversation", exc_info=True) # Process any pending user prompts or internal subagent results. try: - await process_pending_chat_inputs(chat_id, user_id, workspace) + await process_pending_chat_inputs(request, chat_id, user_id, workspace) except Exception: logger.exception(f"Failed to process pending inputs for chat {chat_id}") diff --git a/cptr/utils/identity.py b/cptr/utils/identity.py index c4d13be..baa8ec9 100644 --- a/cptr/utils/identity.py +++ b/cptr/utils/identity.py @@ -12,7 +12,8 @@ from dataclasses import dataclass from pathlib import Path from typing import Callable -from cptr.models import Auth +from fastapi import Request +from cptr.models import Auth, User from cptr.utils.config import AuthMode, AuthResult, get_auth_mode IS_WINDOWS = platform.system() == "Windows" @@ -115,6 +116,35 @@ async def identity_for_context(context: dict) -> ExecutionIdentity: return await identity_for_user_id(context.get("user_id")) +async def internal_request_for_user(app, user_id: str | None) -> Request: + if not user_id: + raise IdentityUnavailable("missing user id", status_code=401) + user = await User.get_by_id(user_id) + if user is None: + raise IdentityUnavailable("user not found", status_code=401) + auth = await Auth.get_by_user_id(user_id) + request = Request( + { + "type": "http", + "method": "GET", + "path": "/__internal__", + "headers": [], + "client": ("127.0.0.1", 0), + "server": ("internal", 0), + "scheme": "http", + "app": app, + "state": {}, + } + ) + request.state.auth = AuthResult( + user_id=user_id, + username=auth.username if auth else None, + role=user.role, + ) + request.state.internal = True + return request + + def env_for( identity: ExecutionIdentity, cwd: str | Path, diff --git a/cptr/utils/images.py b/cptr/utils/images.py index 17691f4..1b2777b 100644 --- a/cptr/utils/images.py +++ b/cptr/utils/images.py @@ -3,7 +3,6 @@ from __future__ import annotations import base64 -import asyncio import hashlib import mimetypes import os @@ -11,12 +10,12 @@ from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path +from fastapi import Request 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 @@ -123,6 +122,7 @@ def _unique_workspace_image_path(workspace: str, source: str, content_type: str) async def _store_image( + request: Request, data: bytes, content_type: str, user_id: str | None, @@ -136,12 +136,7 @@ async def _store_image( if workspace: workspace_path = _unique_workspace_image_path(workspace, source, content_type) - 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 Runtime.write_file(request, str(workspace_path), data) filename = workspace_path.name if workspace_path else f"{source}{ext}" meta = { @@ -191,6 +186,7 @@ async def _decode_image_response_item( async def generate_images( + request: Request, prompt: str, *, user_id: str | None, @@ -228,6 +224,7 @@ async def generate_images( data, content_type = await _decode_image_response_item(client, item, headers) results.append( await _store_image( + request, data, content_type, user_id, @@ -261,13 +258,16 @@ def _resolve_workspace_image_path(value: str, workspace: str | None) -> Path | N return path.resolve() -async def _load_image_file(image_ref: str, workspace: str | None = None) -> tuple[str, bytes, str]: +async def _load_image_file( + request: Request, image_ref: str, workspace: str | None = None +) -> tuple[str, bytes, str]: path = _resolve_workspace_image_path(image_ref, workspace) if path and path.is_file(): content_type = mimetypes.guess_type(str(path))[0] or "application/octet-stream" if not content_type.lower().startswith("image/"): raise ValueError(f"File is not an image: {image_ref}") - data = await asyncio.to_thread(path.read_bytes) + file_data = await Runtime.read_bytes(request, str(path)) + data = file_data["data"] return path.name, data, content_type clean_id = clean_file_id(image_ref) @@ -284,6 +284,7 @@ async def _load_image_file(image_ref: str, workspace: str | None = None) -> tupl async def edit_images( + request: Request, prompt: str, image_ids: list[str], *, @@ -313,7 +314,7 @@ async def edit_images( if background: payload["background"] = background - loaded_files = [await _load_image_file(image_id, workspace) for image_id in image_ids] + loaded_files = [await _load_image_file(request, image_id, workspace) for image_id in image_ids] files = [] multi = len(loaded_files) > 1 for filename, data, content_type in loaded_files: @@ -336,6 +337,7 @@ async def edit_images( data, content_type = await _decode_image_response_item(client, item, headers) results.append( await _store_image( + request, data, content_type, user_id, diff --git a/cptr/utils/memory.py b/cptr/utils/memory.py index 1e78020..a665c4a 100644 --- a/cptr/utils/memory.py +++ b/cptr/utils/memory.py @@ -14,10 +14,10 @@ from dataclasses import dataclass from pathlib import Path from typing import Any +from fastapi import Request 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.runtime import FileError, Runtime from cptr.utils.workspace import ensure_cptr_gitignored MEMORY_DIR_NAME = "memory" @@ -1157,13 +1157,13 @@ def apply_memory_batch( async def write_memory( + request: Request, user_id: str, workspace: str, scope: str, operations: list[dict[str, Any]], ) -> dict[str, Any]: memory_file = await resolve_memory_file(user_id, workspace, scope) - 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 @@ -1185,9 +1185,9 @@ 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 - if identity: + if scope == "workspace": try: - file_data = await Runtime.read_file(identity, str(memory_file.path)) + file_data = await Runtime.read_file(request, str(memory_file.path)) entries = [ line[2:].strip() for line in str(file_data.get("content") or "").splitlines() @@ -1209,10 +1209,8 @@ async def write_memory( "scope": scope, "path": str(memory_file.path), } - if identity: - await Runtime.write_file( - identity, str(memory_file.path), format_memory_entries(next_entries) - ) + if scope == "workspace": + await Runtime.write_file(request, str(memory_file.path), format_memory_entries(next_entries)) else: await asyncio.to_thread(write_memory_entries, memory_file.path, next_entries) return { @@ -1226,6 +1224,7 @@ async def write_memory( async def remember( + request: Request, user_id: str, workspace: str, scope: str, @@ -1234,10 +1233,10 @@ async def remember( settings = await get_memory_settings() if not settings["enabled"]: return {"success": False, "error": "memory writes are disabled"} - return await write_memory(user_id, workspace, scope, operations) + return await write_memory(request, user_id, workspace, scope, operations) -async def read_memory_state(user_id: str, workspace: str) -> dict[str, Any]: +async def read_memory_state(request: Request, user_id: str, workspace: str) -> dict[str, Any]: settings = await get_memory_settings() user_memory = await resolve_memory_file(user_id, workspace, "user") user_entries = await asyncio.to_thread(read_memory_entries, user_memory.path) @@ -1247,9 +1246,7 @@ async def read_memory_state(user_id: str, workspace: str) -> dict[str, Any]: if workspace: workspace_memory = await resolve_memory_file(user_id, workspace, "workspace") try: - file_data = await Runtime.read_file( - await identity_for_user_id(user_id), str(workspace_memory.path) - ) + file_data = await Runtime.read_file(request, str(workspace_memory.path)) workspace_entries = [ line[2:].strip() for line in str(file_data.get("content") or "").splitlines() @@ -1279,6 +1276,7 @@ async def read_memory_state(user_id: str, workspace: str) -> dict[str, Any]: async def recall_memory_context( + request: Request, *, user_id: str, workspace: str, @@ -1298,9 +1296,7 @@ async def recall_memory_context( for root in roots: if root.scope == "workspace": try: - file_data = await Runtime.read_file( - await identity_for_user_id(user_id), str(root.baseline_path) - ) + file_data = await Runtime.read_file(request, str(root.baseline_path)) baseline_text = str(file_data.get("content") or "") except FileError: baseline_text = "" @@ -1336,6 +1332,7 @@ async def recall_memory_context( async def build_memory_prompt( + request: Request, user_id: str | None, workspace: str, *, @@ -1351,6 +1348,7 @@ async def build_memory_prompt( blocks: list[str] = [] context = await recall_memory_context( + request, user_id=user_id, workspace=workspace, current_message=current_message, @@ -1385,9 +1383,7 @@ async def build_memory_prompt( for root, title, budget, snippets in render_roots: if root.scope == "workspace": try: - file_data = await Runtime.read_file( - await identity_for_user_id(user_id), str(root.baseline_path) - ) + file_data = await Runtime.read_file(request, 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) @@ -1482,6 +1478,7 @@ async def list_memory_files_state( async def read_memory_file_state( + request: Request, user_id: str, workspace: str, *, @@ -1495,7 +1492,11 @@ async def read_memory_file_state( target = _safe_relative_path(root.root, path) if not target.is_file() or target.suffix.lower() != ".md": raise ValueError("memory file not found") - content = await asyncio.to_thread(target.read_text, errors="replace") + if scope == "workspace": + file_data = await Runtime.read_file(request, str(target)) + content = str(file_data.get("content") or "") + else: + content = await asyncio.to_thread(target.read_text, errors="replace") sections = _split_markdown_sections(content, target.stem) return { "scope": scope, @@ -1512,7 +1513,7 @@ async def read_memory_file_state( } -async def review_memory_vault(user_id: str, workspace: str) -> dict[str, Any]: +async def review_memory_vault(request: Request, user_id: str, workspace: str) -> dict[str, Any]: """Deterministic vault review for the UI/API; LLM learning still runs after turns.""" roots = resolve_memory_roots(user_id, workspace) @@ -1602,6 +1603,7 @@ def build_memory_review_prompt( async def review_memory_after_turn( + request: Request, *, user_id: str, message_id: str, @@ -1627,6 +1629,7 @@ async def review_memory_after_turn( _reviewed_messages.add(message_id) asyncio.create_task( run_memory_review( + request, user_id=user_id, workspace=workspace, conversation_messages=list(conversation_messages), @@ -1638,6 +1641,7 @@ async def review_memory_after_turn( async def run_memory_review( + request: Request, *, user_id: str, workspace: str, @@ -1649,7 +1653,7 @@ async def run_memory_review( try: from cptr.utils.ai import generate_json - memory_state = await read_memory_state(user_id, workspace) + memory_state = await read_memory_state(request, user_id, workspace) transcript = summarize_recent_conversation(conversation_messages, assistant_reply) prompt = build_memory_review_prompt(memory_state, workspace, transcript) parsed = await generate_json( @@ -1668,6 +1672,7 @@ async def run_memory_review( if not isinstance(operations, list) or not operations: continue await remember( + request, user_id=user_id, workspace=workspace, scope=scope, diff --git a/cptr/utils/prompt_templates.py b/cptr/utils/prompt_templates.py index 373b48d..4322b1d 100644 --- a/cptr/utils/prompt_templates.py +++ b/cptr/utils/prompt_templates.py @@ -11,6 +11,7 @@ from datetime import date from importlib.metadata import version as pkg_version from pathlib import Path +from fastapi import Request from cptr.models import Config from cptr.utils.identity import identity_for_user_id from cptr.utils.runtime import Runtime, FileError @@ -270,6 +271,7 @@ def _build_template_variables( async def load_system_prompt( + request: Request, workspace: str, model: str = "", user_id: str | None = None, @@ -291,9 +293,7 @@ async def load_system_prompt( ws_prompt = Path(workspace) / ".cptr" / "system.md" if user_id: try: - file_data = await Runtime.read_file( - await identity_for_user_id(user_id), str(ws_prompt) - ) + file_data = await Runtime.read_file(request, str(ws_prompt)) if not file_data.get("binary"): template = str(file_data.get("content") or "").strip() except FileError: @@ -328,6 +328,7 @@ async def load_system_prompt( from cptr.utils.memory import build_memory_prompt memory = await build_memory_prompt( + request, user_id, workspace, current_message=current_message, diff --git a/cptr/utils/runtime.py b/cptr/utils/runtime.py index d5cfbd7..869430c 100644 --- a/cptr/utils/runtime.py +++ b/cptr/utils/runtime.py @@ -13,8 +13,9 @@ import sys import zipfile from datetime import datetime, timezone from pathlib import Path -from typing import TYPE_CHECKING, Any, Callable +from typing import Any, Callable +from fastapi import Request from cptr.utils.gitignore import is_gitignored, load_gitignore from cptr.utils.identity import ( ExecutionIdentity, @@ -24,9 +25,6 @@ from cptr.utils.identity import ( 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 @@ -132,36 +130,32 @@ class FileError(RuntimeError): class Runtime: @staticmethod - async def stat(request: Request | ExecutionIdentity, path: str) -> dict[str, Any]: - return await _file(await _identity(request), _stat, path) + async def stat(request: Request, path: str) -> dict[str, Any]: + return await _file(await _request_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) + async def list_directory(request: Request, path: str) -> dict[str, Any]: + return await _file(await _request_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) + async def list_tree(request: Request, path: str, recursive: bool = False) -> dict[str, Any]: + return await _file(await _request_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) + async def read_file(request: Request, path: str) -> dict[str, Any]: + return await _file(await _request_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) + async def extract_text(request: Request, path: str) -> dict[str, Any]: + return await _file(await _request_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) + async def write_file(request: Request, path: str, content: str | bytes) -> dict[str, Any]: + return await _file(await _request_identity(request), _write_file, path, content) @staticmethod async def file_matches( - request: Request | ExecutionIdentity, + request: Request, query: str, path: str, show_hidden: bool = False, @@ -169,7 +163,7 @@ class Runtime: limit: int = MATCH_PAGE_SIZE, ) -> dict[str, Any]: return await _file( - await _identity(request), + await _request_identity(request), _file_matches, path, query, @@ -179,40 +173,34 @@ class Runtime: ) @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) + async def search_files(request: Request, query: str, path: str, limit: int = 20) -> dict[str, Any]: + return await _file(await _request_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) + async def create_item(request: Request, path: str, type: str = "file") -> dict[str, Any]: + return await _file(await _request_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) + async def move_item(request: Request, source: str, destination: str) -> dict[str, Any]: + return await _file(await _request_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) + async def delete_item(request: Request, path: str) -> dict[str, Any]: + return await _file(await _request_identity(request), _delete_item, path) @staticmethod async def upload_file( - request: Request | ExecutionIdentity, directory: str, filename: str, content: bytes + request: Request, directory: str, filename: str, content: bytes ) -> dict[str, Any]: - return await _file(await _identity(request), _upload_file, directory, filename, content) + return await _file(await _request_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) + async def read_bytes(request: Request, path: str) -> dict[str, Any]: + return await _file(await _request_identity(request), _read_bytes, path) @staticmethod - async def stream_file(request: Request | ExecutionIdentity, path: str) -> dict[str, Any]: - identity = await _identity(request) + async def stream_file(request: Request, path: str) -> dict[str, Any]: + identity = await _request_identity(request) file_stat = await _file(identity, _stat, path) if file_stat.get("type") != "file": raise FileError(f"Not a file: {path}") @@ -272,15 +260,11 @@ class Runtime: } @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 archive_files(request: Request, paths: list[str]) -> dict[str, Any]: + return await _file(await _request_identity(request), _archive_files, paths) -async def _identity(request: Request | ExecutionIdentity) -> ExecutionIdentity: - if isinstance(request, ExecutionIdentity): - return request +async def _request_identity(request: Request) -> ExecutionIdentity: try: return await identity_for_request(request) except IdentityUnavailable as exc: diff --git a/cptr/utils/timers.py b/cptr/utils/timers.py index e91791d..a250e27 100644 --- a/cptr/utils/timers.py +++ b/cptr/utils/timers.py @@ -101,6 +101,7 @@ async def _launch_timer(timer, app) -> None: from cptr.utils.chat_export import export_chat_to_file from cptr.utils.chat_task import get_pending_input_lock, start_task from cptr.utils.config import now_ms + from cptr.utils.identity import internal_request_for_user from cptr.utils.model_targets import resolve_model_target async with _manager_lock: @@ -111,6 +112,7 @@ async def _launch_timer(timer, app) -> None: status = meta.get("status") or meta.get("timer_status") if status != "pending" or int(meta.get("timer_at") or 0) > time.time_ns(): return + request = await internal_request_for_user(app, timer.user_id) parent = await Chat.get_by_id(meta.get("parent_chat_id", "")) if not parent: @@ -172,8 +174,8 @@ async def _launch_timer(timer, app) -> None: ) await Chat.update_meta(timer.id, meta, now_ms()) - await export_chat_to_file(timer.id) - await export_chat_to_file(parent.id) + await export_chat_to_file(request, timer.id) + await export_chat_to_file(request, parent.id) await emit_to_user( timer.user_id, @@ -184,7 +186,7 @@ async def _launch_timer(timer, app) -> None: }, ) start_task( - None, + request, 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 4d175b8..3ead57e 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -22,6 +22,7 @@ import uuid from pathlib import Path, PureWindowsPath from typing import Any, Literal, Optional, get_args, get_origin, get_type_hints +from fastapi import Request 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 ( @@ -584,7 +585,9 @@ async def read_file( request = __context__.get("request") try: - file_stat = await Runtime.stat(request or identity, str(full)) + if request is None: + return "Error: request context unavailable" + file_stat = await Runtime.stat(request, str(full)) except FileError: return f"Error: file not found: {path}" @@ -598,7 +601,7 @@ async def read_file( # Image files: return base64 JSON instead of garbled text if full.suffix.lower() in IMAGE_EXTENSIONS: try: - image = await Runtime.read_bytes(request or identity, str(full)) + image = await Runtime.read_bytes(request, str(full)) except FileError as e: return f"Error: {e}" return await asyncio.to_thread(_read_image_data, image["data"], full.suffix, path) @@ -608,12 +611,12 @@ async def read_file( return f"Error: file too large ({size} bytes, max 500KB)" try: - file_data = await Runtime.read_file(request or identity, str(full)) + file_data = await Runtime.read_file(request, 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)) + extracted = await Runtime.extract_text(request, str(full)) except FileError as e: return f"Error: {e}" content = str(extracted.get("text") or "") @@ -658,9 +661,10 @@ async def list_directory( 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) + if request is None: + return "Error: request context unavailable" + result = await Runtime.list_tree(request, str(full), recursive) except (ValueError, FileError, IdentityUnavailable) as e: return f"Error: {e}" res = str(result.get("text") or "") @@ -688,9 +692,10 @@ async def search_files( 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)) + if request is None: + return "Error: request context unavailable" + directory = await Runtime.stat(request, str(full)) except (ValueError, FileError, IdentityUnavailable) as e: return f"Error: {e}" if directory.get("type") != "directory": @@ -709,9 +714,7 @@ async def search_files( ) except FileNotFoundError: try: - matches = await Runtime.file_matches( - request or identity, query, str(full), False, 0, 50 - ) + matches = await Runtime.file_matches(request, query, str(full), False, 0, 50) except FileError as e: return f"Error: {e}" rows = [] @@ -851,12 +854,8 @@ async def create_file( """ 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}" + return "Error: request context unavailable" # Artifact mode: save to .cptr/artifacts/ (same location as create_artifact) # When artifact_type is set, path is ignored. @@ -868,10 +867,9 @@ async def create_file( artifact_path = artifact_dir / f"{ts}_{artifact_type}.md" 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) + if request is None: + return "Error: request context unavailable" + await Runtime.write_file(request, str(artifact_path), content) except FileError as e: return f"Error: {e}" @@ -896,10 +894,9 @@ async def create_file( return f"Error: file already exists: {path}. Use overwrite=true or edit_file to modify." try: - if request is not None: - await Runtime.write_file(request, str(full), content) - else: - await Runtime.write_file(identity, str(full), content) + if request is None: + return "Error: request context unavailable" + await Runtime.write_file(request, str(full), content) except FileError as e: return f"Error: {e}" return f"Created {path} ({len(content)} bytes, {len(content.splitlines())} lines)" @@ -921,22 +918,15 @@ async def create_artifact( 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}" + return "Error: request context unavailable" 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_path = artifact_dir / f"{ts}_{artifact_type}.md" 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) + await Runtime.write_file(request, str(artifact_path), content) except FileError as e: return f"Error: {e}" @@ -1084,21 +1074,16 @@ async def write_file(path: str, content: str, *, __context__: dict) -> str: """ 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}" + return "Error: request context unavailable" full = _resolve_path(path, workspace) if _is_dotenv(full): return _DOTENV_ERROR try: - if request is not None: - await Runtime.write_file(request, str(full), content) - else: - await Runtime.write_file(identity, str(full), content) + if request is None: + return "Error: request context unavailable" + await Runtime.write_file(request, str(full), content) except FileError as e: return f"Error: {e}" return f"Wrote {len(content)} bytes to {path}" @@ -1113,10 +1098,8 @@ async def display_file(path: str, *, __context__: dict) -> str: 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}" + if request is None: + return "Error: request context unavailable" try: full = _resolve_path(path, workspace) @@ -1126,7 +1109,7 @@ async def display_file(path: str, *, __context__: dict) -> str: if _is_dotenv(full): return _DOTENV_ERROR try: - file_stat = await Runtime.stat(request or identity, str(full)) + file_stat = await Runtime.stat(request, str(full)) except FileError: return f"Error: file not found: {path}" if file_stat.get("type") != "file": @@ -1171,20 +1154,13 @@ async def edit_file( """ 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}" + return "Error: request context unavailable" full = _resolve_path(path, workspace) if _is_dotenv(full): return _DOTENV_ERROR 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)) + file_data = await Runtime.read_file(request, str(full)) except FileError: return f"Error: file not found: {path}" if file_data.get("binary"): @@ -1223,10 +1199,7 @@ async def edit_file( 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) + await Runtime.write_file(request, str(full), new_content) except FileError as e: return f"Error: {e}" @@ -1250,20 +1223,13 @@ async def multi_edit_file( """ 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}" + return "Error: request context unavailable" full = _resolve_path(path, workspace) if _is_dotenv(full): return _DOTENV_ERROR 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)) + file_data = await Runtime.read_file(request, str(full)) except FileError: return f"Error: file not found: {path}" if file_data.get("binary"): @@ -1301,10 +1267,7 @@ async def multi_edit_file( applied += 1 try: - if request is not None: - await Runtime.write_file(request, str(full), content) - else: - await Runtime.write_file(identity, str(full), content) + await Runtime.write_file(request, str(full), content) except FileError as e: return f"Error: {e}" return f"Applied {applied} edits to {path}" @@ -1372,10 +1335,9 @@ async def run_command( command_session_id = uuid.uuid4().hex[:8] 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), "") + if request is None: + return "Error: request context unavailable" + await Runtime.write_file(request, str(log_path), "") except FileError as e: try: _kill_process_group(proc.pid) @@ -2083,12 +2045,9 @@ async def browser_screenshot( 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 - ) + if request is None: + return "Error: request context unavailable" + await Runtime.write_file(request, str(filepath), png_bytes) except FileError as e: return f"Error: {e}" @@ -2137,7 +2096,11 @@ async def image_generate( if image_refs: from cptr.utils.images import edit_images + request = __context__.get("request") + if request is None: + return "Error: request context unavailable" results = await edit_images( + request, prompt, image_refs, user_id=__context__.get("user_id"), @@ -2150,7 +2113,11 @@ async def image_generate( else: from cptr.utils.images import generate_images + request = __context__.get("request") + if request is None: + return "Error: request context unavailable" results = await generate_images( + request, prompt, user_id=__context__.get("user_id"), size=size, @@ -2195,11 +2162,15 @@ async def update_memory( return json.dumps({"success": False, "error": "user_id missing from tool context"}) if not isinstance(operations, list): return json.dumps({"success": False, "error": "operations must be a list"}) + request = __context__.get("request") + if request is None: + return json.dumps({"success": False, "error": "request context unavailable"}) settings = await get_memory_settings() if not settings.get("tool_enabled", True): return json.dumps({"success": False, "error": "memory tool is disabled"}) result = await remember( + request, user_id=user_id, workspace=workspace, scope=scope, @@ -2558,6 +2529,7 @@ async def delegate_task( reserve = await reserve_async_subagent( config["max_async"], + request=__context__["request"], task=task, context=context, workspace=__context__["workspace"], @@ -2574,6 +2546,7 @@ async def delegate_task( delegation_id = reserve["delegation_id"] try: chat, _, assistant_msg = await _create_subagent_chat( + __context__["request"], task=task, context=context, workspace=__context__["workspace"], @@ -2616,6 +2589,7 @@ async def delegate_task( if config["max_concurrent"] == -1: return await _run_subagent_chat( + __context__["request"], task=task, context=context, workspace=__context__["workspace"], @@ -2631,6 +2605,7 @@ async def delegate_task( async with _subagent_semaphore: return await _run_subagent_chat( + __context__["request"], task=task, context=context, workspace=__context__["workspace"], @@ -2681,6 +2656,7 @@ async def timer( full_model_id = __context__.get("full_model_id") or __context__["model_id"] chat, _, _ = await _create_subagent_chat( + __context__["request"], task=prompt, context="", workspace=__context__["workspace"], @@ -2712,6 +2688,7 @@ async def timer( async def _create_subagent_chat( + request: Request, task: str, context: str, workspace: str, @@ -2772,7 +2749,7 @@ async def _create_subagent_chat( created_at=now_ms(), ) await Chat.update_current_message(chat.id, assistant_msg.id, now_ms()) - await export_chat_to_file(chat.id) + await export_chat_to_file(request, chat.id) return chat, user_msg, assistant_msg @@ -2811,6 +2788,7 @@ async def _run_existing_subagent_chat( async def _run_subagent_chat( + request: Request, task: str, context: str, workspace: str, @@ -2822,6 +2800,7 @@ async def _run_subagent_chat( ) -> str: """Create a real chat and run the agent loop on it.""" chat, _, assistant_msg = await _create_subagent_chat( + request, task=task, context=context, workspace=workspace,