diff --git a/cptr/app.py b/cptr/app.py index a0421af..16e3883 100644 --- a/cptr/app.py +++ b/cptr/app.py @@ -71,6 +71,11 @@ async def lifespan(app: FastAPI): app.state.scheduler_task = asyncio.create_task(scheduler_worker_loop(app)) + from cptr.utils.timers import recover_timers, timer_worker_loop + + await recover_timers() + app.state.timer_task = asyncio.create_task(timer_worker_loop(app)) + # Start messaging bots from cptr.utils.bridge import BotManager @@ -80,6 +85,12 @@ async def lifespan(app: FastAPI): try: yield finally: + timer_task = getattr(app.state, "timer_task", None) + if timer_task: + timer_task.cancel() + with suppress(asyncio.CancelledError): + await timer_task + scheduler_task = getattr(app.state, "scheduler_task", None) if scheduler_task: scheduler_task.cancel() diff --git a/cptr/env.py b/cptr/env.py index fd9f47a..4cc3335 100644 --- a/cptr/env.py +++ b/cptr/env.py @@ -82,6 +82,7 @@ STREAM_WRITE_TIMEOUT_SECONDS = float(os.environ.get("CPTR_STREAM_WRITE_TIMEOUT", # ── Automation scheduler ──────────────────────────────────── AUTOMATION_POLL_INTERVAL = int(os.environ.get("AUTOMATION_POLL_INTERVAL", "10")) +TIMER_POLL_INTERVAL = int(os.environ.get("TIMER_POLL_INTERVAL", "10")) # ── CORS ──────────────────────────────────────────────────── # Socket.IO CORS allowed origins. diff --git a/cptr/events.py b/cptr/events.py index d871b95..a211371 100644 --- a/cptr/events.py +++ b/cptr/events.py @@ -26,6 +26,16 @@ class EventDefinition: class EventDefinitions: + CHAT_READ = EventDefinition( + "chat.read", + "The user explicitly marked a chat as read.", + "Chat read", + ) + CHAT_USER_MESSAGE = EventDefinition( + "chat.user_message", + "A user message was added to a chat.", + "User message", + ) CHAT_FINISHED = EventDefinition( "chat.finished", "A chat run finished successfully.", @@ -191,7 +201,16 @@ class NotificationEventSink: await dispatch_notification_event(event) -EVENT_SINKS = [NotificationEventSink()] +class TimerEventSink: + async def handle_event(self, event: Event) -> None: + if event.event not in {EVENTS.CHAT_READ.name, EVENTS.CHAT_USER_MESSAGE.name}: + return + from cptr.utils.timers import cancel_timers_for_event + + await cancel_timers_for_event(event) + + +EVENT_SINKS = [TimerEventSink(), NotificationEventSink()] async def publish_event( diff --git a/cptr/models/__init__.py b/cptr/models/__init__.py index 3727577..b6a0a85 100644 --- a/cptr/models/__init__.py +++ b/cptr/models/__init__.py @@ -5,7 +5,7 @@ from cptr.models.users import User, Auth, UserStates from cptr.models.workspaces import Workspace from cptr.models.config import Config from cptr.models.files import File -from cptr.models.chats import Chat, ChatMessage +from cptr.models.chats import Chat, ChatMessage, is_internal_chat from cptr.models.automations import Automation, AutomationRun __all__ = [ @@ -18,7 +18,7 @@ __all__ = [ "File", "Chat", "ChatMessage", + "is_internal_chat", "Automation", "AutomationRun", ] - diff --git a/cptr/models/chats.py b/cptr/models/chats.py index a59266a..a954cd4 100644 --- a/cptr/models/chats.py +++ b/cptr/models/chats.py @@ -27,6 +27,12 @@ def _uuid() -> str: return str(uuid.uuid4()) +def is_internal_chat(meta: dict | None) -> bool: + """Whether a chat is harness-owned and should stay out of normal chat surfaces.""" + meta = meta or {} + return bool(meta.get("internal") or meta.get("subagent")) + + class Chat(Base): """A chat conversation. Workspace association lives in the filesystem.""" @@ -59,6 +65,71 @@ class Chat(Base): result = await db.execute(select(Chat).where(Chat.id.in_(chat_ids))) return list(result.scalars().all()) + @staticmethod + async def get_due_timers(now_ns: int, limit: int = 10) -> list[Chat]: + """Return pending internal timer chats whose due time has arrived.""" + async with await get_db() as db: + result = await db.execute(select(Chat).where(Chat.meta.is_not(None))) + timers = [ + chat + for chat in result.scalars().all() + if (chat.meta or {}).get("internal") is True + and (chat.meta or {}).get("type") == "timer" + and (chat.meta or {}).get("timer_status") == "pending" + and int((chat.meta or {}).get("timer_at") or 0) <= now_ns + ] + timers.sort(key=lambda chat: int((chat.meta or {}).get("timer_at") or 0)) + return timers[:limit] + + @staticmethod + async def get_pending_timers(parent_chat_id: str) -> list[Chat]: + """Return pending timer children for a parent chat.""" + async with await get_db() as db: + result = await db.execute(select(Chat).where(Chat.meta.is_not(None))) + return [ + chat + for chat in result.scalars().all() + if (chat.meta or {}).get("internal") is True + and (chat.meta or {}).get("type") == "timer" + and (chat.meta or {}).get("parent_chat_id") == parent_chat_id + and (chat.meta or {}).get("timer_status") == "pending" + ] + + @staticmethod + async def get_timers(status: str | None = None) -> list[Chat]: + """Return internal timer chats, optionally in one lifecycle state.""" + async with await get_db() as db: + result = await db.execute(select(Chat).where(Chat.meta.is_not(None))) + return [ + chat + for chat in result.scalars().all() + if (chat.meta or {}).get("internal") is True + and (chat.meta or {}).get("type") == "timer" + and (status is None or (chat.meta or {}).get("timer_status") == status) + ] + + @staticmethod + async def get_internal_descendants(parent_chat_id: str) -> list[Chat]: + """Return every internal child below a chat, including nested timers.""" + async with await get_db() as db: + result = await db.execute(select(Chat).where(Chat.meta.is_not(None))) + candidates = list(result.scalars().all()) + children: list[Chat] = [] + parent_ids = {parent_chat_id} + while parent_ids: + found = [ + chat + for chat in candidates + if is_internal_chat(chat.meta) + and (chat.meta or {}).get("parent_chat_id") in parent_ids + ] + if not found: + break + children.extend(found) + parent_ids = {chat.id for chat in found} + candidates = [chat for chat in candidates if chat not in found] + return children + @staticmethod async def create( user_id: str, @@ -173,9 +244,21 @@ class Chat(Base): @staticmethod async def delete(chat_id: str) -> bool: async with await get_db() as db: + result = await db.execute(select(Chat).where(Chat.meta.is_not(None))) + candidates = list(result.scalars().all()) + delete_ids = {chat_id} + frontier = {chat_id} + while frontier: + frontier = { + chat.id + for chat in candidates + if is_internal_chat(chat.meta) + and (chat.meta or {}).get("parent_chat_id") in frontier + } + delete_ids.update(frontier) # Messages cascade via FK, but be explicit - await db.execute(delete(ChatMessage).where(ChatMessage.chat_id == chat_id)) - result = await db.execute(delete(Chat).where(Chat.id == chat_id)) + await db.execute(delete(ChatMessage).where(ChatMessage.chat_id.in_(delete_ids))) + result = await db.execute(delete(Chat).where(Chat.id.in_(delete_ids))) await db.commit() return result.rowcount > 0 @@ -237,7 +320,7 @@ class Chat(Base): def allowed(chat: Chat) -> bool: meta = chat.meta or {} - if not include_subagents and meta.get("subagent"): + if not include_subagents and is_internal_chat(meta): return False if workspace and meta.get("workspace") != workspace: return False diff --git a/cptr/routers/chat.py b/cptr/routers/chat.py index f671210..d336437 100644 --- a/cptr/routers/chat.py +++ b/cptr/routers/chat.py @@ -11,7 +11,7 @@ from typing import List, Optional from fastapi import APIRouter, HTTPException, Query, Request from pydantic import BaseModel -from cptr.models import Chat, ChatMessage, Config +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.workspace import ensure_cptr_gitignored @@ -97,6 +97,8 @@ async def list_chats( continue chat_meta = chat.meta if isinstance(chat.meta, dict) else {} + if is_internal_chat(chat_meta): + continue if chat.meta is not None and not isinstance(chat.meta, dict): log.warning( "chat.list.bad_meta workspace=%r chat_id=%s title=%r meta_type=%s", @@ -581,10 +583,14 @@ async def delete_chat(chat_id: str, request: Request): if not chat or chat.user_id != user_id: raise HTTPException(404, "chat not found") - # Remove the workspace chat file. + # 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 + 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) await Chat.delete(chat_id) from cptr.socket.main import emit_to_user @@ -801,6 +807,18 @@ async def send_message(body: SendMessageRequest, request: Request): # Update chat pointer to new leaf while still holding the input lock. await Chat.update_current_message(chat.id, assistant_msg.id, now_ms()) + submitted_message = queued_msg or user_msg + if submitted_message: + from cptr.events import EVENTS, publish_event + + await publish_event( + EVENTS.CHAT_USER_MESSAGE, + actor={"id": user_id}, + subject_id=chat.id, + subject_type="chat", + source="chat", + ) + if queued_msg: await process_pending_chat_inputs(chat.id, user_id, workspace or "") return {"chat_id": chat.id, "message_id": queued_msg.id, "queued": True} diff --git a/cptr/socket/main.py b/cptr/socket/main.py index d0c2787..c9ca6b7 100644 --- a/cptr/socket/main.py +++ b/cptr/socket/main.py @@ -89,6 +89,15 @@ async def on_chat_read(sid, data): last_read_at = now_ms() if await Chat.update_last_read_at(chat_id, user_id, last_read_at): + from cptr.events import EVENTS, publish_event + + await publish_event( + EVENTS.CHAT_READ, + actor={"id": user_id}, + subject_id=chat_id, + subject_type="chat", + source="socket", + ) chat = await Chat.get_by_id(chat_id) workspace = (chat.meta or {}).get("workspace", "") if chat else "" from cptr.utils.chat_task import get_active_chat_ids diff --git a/cptr/utils/async_subagents.py b/cptr/utils/async_subagents.py index f1eb0f4..c1988e2 100644 --- a/cptr/utils/async_subagents.py +++ b/cptr/utils/async_subagents.py @@ -160,6 +160,14 @@ async def _finalize( snapshot = {k: v for k, v in record.items() if k != "task"} _prune_completed_locked() + if snapshot.get("timer_chat_id"): + from cptr.utils.timers import set_timer_completion + + try: + await set_timer_completion(snapshot, status, error) + except Exception: + logger.exception("Failed to record timer completion %s", delegation_id) + injector = _completion_injector_override or _inject_completion try: await injector(snapshot) diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 738722c..ece9122 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -23,7 +23,7 @@ from cptr.utils.skills import ( load_skill, ) from cptr.utils.summarize import summarize_messages -from cptr.models import Chat, ChatMessage, Config +from cptr.models import Chat, ChatMessage, Config, is_internal_chat from cptr.socket.main import emit_to_user from cptr.utils.ai import ( ChatCompletionForm, @@ -1936,7 +1936,7 @@ async def run_chat_task( tools = [t for t in tools if t["name"] != "view_skill"] # Strip delegate_task from sub-agent chats (depth limit = 1) - if chat_obj and (chat_obj.meta or {}).get("subagent"): + if chat_obj and is_internal_chat(chat_obj.meta): tools = [t for t in tools if t["name"] not in {"delegate_task", "update_memory"}] # Parse $skill-name mentions from the user message to auto-activate skills diff --git a/cptr/utils/timers.py b/cptr/utils/timers.py new file mode 100644 index 0000000..6fc3183 --- /dev/null +++ b/cptr/utils/timers.py @@ -0,0 +1,287 @@ +"""Durable one-shot timers backed by dormant internal child chats.""" + +from __future__ import annotations + +import asyncio +import logging +import re +import time +from datetime import datetime + +from cptr.env import TIMER_POLL_INTERVAL + +logger = logging.getLogger(__name__) + +_RELATIVE_TIME = re.compile(r"^\+(\d+)([smhd])$") +_RFC3339_TIME = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$") +_TIME_UNITS_NS = { + "s": 1_000_000_000, + "m": 60 * 1_000_000_000, + "h": 60 * 60 * 1_000_000_000, + "d": 24 * 60 * 60 * 1_000_000_000, +} +_manager_lock = asyncio.Lock() + + +def parse_timer_at(value: str) -> int: + """Normalize a relative offset or timezone-aware RFC 3339 timestamp.""" + raw = value.strip() + now = time.time_ns() + relative = _RELATIVE_TIME.fullmatch(raw) + if relative: + count = int(relative.group(1)) + if count <= 0: + raise ValueError("at must be in the future.") + return now + count * _TIME_UNITS_NS[relative.group(2)] + + if not _RFC3339_TIME.fullmatch(raw): + raise ValueError("at must be +5s, +5m, +1h, +2d, or an RFC 3339 timestamp with a timezone.") + try: + parsed = datetime.fromisoformat(raw.replace("Z", "+00:00")) + except ValueError as exc: + raise ValueError( + "at must be +5s, +5m, +1h, +2d, or an RFC 3339 timestamp with a timezone." + ) from exc + if parsed.tzinfo is None or parsed.utcoffset() is None: + raise ValueError("absolute at values must include an explicit timezone.") + + due_at = int(parsed.timestamp() * 1_000_000_000) + if due_at <= now: + raise ValueError("at must be in the future.") + return due_at + + +async def cancel_timers_for_event(event) -> None: + """Cancel matching dormant children after a committed parent-chat event.""" + subject = event.subject or {} + if subject.get("type") != "chat" or not subject.get("id"): + return + + from cptr.models import Chat + from cptr.utils.config import now_ms + + async with _manager_lock: + timers = await Chat.get_pending_timers(str(subject["id"])) + for timer in timers: + meta = dict(timer.meta or {}) + if event.event not in (meta.get("cancel_on") or []): + continue + meta.update( + { + "timer_status": "cancelled", + "timer_cancelled_at": time.time_ns(), + "timer_cancelled_by": event.event, + } + ) + await Chat.update_meta(timer.id, meta, now_ms()) + + +def _pack_parent_context(parent, messages, checkpoint_id: str | None) -> str: + """Build a small launch-time view of the parent without changing its history.""" + message_by_id = {message.id: message for message in messages} + branch = [] + current = message_by_id.get(parent.current_message_id) + while current: + branch.append(current) + current = message_by_id.get(current.parent_id) + branch.reverse() + + checkpoint_index = next( + (index for index, message in enumerate(branch) if message.id == checkpoint_id), -1 + ) + changes = branch[checkpoint_index + 1 :] if checkpoint_index >= 0 else branch[-12:] + changes = changes[-12:] + + parts = [] + summary = next( + (message.chat_summary for message in reversed(branch) if message.chat_summary), None + ) + if summary: + parts.append(f"## Parent summary\n{summary[-4_000:]}") + if changes: + lines = [] + remaining = 6_000 + for message in changes: + content = (message.content or "").strip() + if not content: + continue + content = content[: min(len(content), remaining)] + lines.append(f"{message.role}: {content}") + remaining -= len(content) + if remaining <= 0: + break + if lines: + parts.append("## Changes since timer was set\n" + "\n\n".join(lines)) + return "\n\n".join(parts) + + +async def _set_timer_status(chat_id: str, status: str, **fields) -> None: + from cptr.models import Chat + from cptr.utils.config import now_ms + + chat = await Chat.get_by_id(chat_id) + if not chat: + return + meta = dict(chat.meta or {}) + meta["timer_status"] = status + meta.update(fields) + await Chat.update_meta(chat_id, meta, now_ms()) + + +async def set_timer_completion(record: dict, status: str, error: str | None) -> None: + """Persist completion before the normal async-subagent result reaches the parent.""" + timer_chat_id = record.get("timer_chat_id") + if not timer_chat_id: + return + final_status = "completed" if status == "completed" else "error" + await _set_timer_status( + timer_chat_id, + final_status, + timer_completed_at=time.time_ns(), + timer_error=error, + ) + + +async def _launch_timer(timer, app) -> None: + from cptr.models import Chat, ChatMessage + from cptr.utils.async_subagents import ( + attach_subagent_chat, + reserve_async_subagent, + start_async_subagent, + ) + from cptr.utils.chat_export import export_chat_to_file + from cptr.utils.config import now_ms + from cptr.utils.model_targets import ApiModelTarget, resolve_model_target + from cptr.utils.tools import _get_subagent_config, _run_existing_subagent_chat + + async with _manager_lock: + timer = await Chat.get_by_id(timer.id) + if not timer: + return + meta = dict(timer.meta or {}) + if meta.get("timer_status") != "pending" or int(meta.get("timer_at") or 0) > time.time_ns(): + return + + parent = await Chat.get_by_id(meta.get("parent_chat_id", "")) + if not parent: + await _set_timer_status(timer.id, "error", timer_error="parent chat no longer exists") + return + + config = await _get_subagent_config() + if not config["background_enabled"]: + return + + try: + target = await resolve_model_target(meta["timer_model_id"], app.state) + except Exception as exc: # model configuration can change while a timer waits + await _set_timer_status(timer.id, "error", timer_error=f"model unavailable: {exc}") + return + if not isinstance(target, ApiModelTarget): + await _set_timer_status( + timer.id, "error", timer_error="background timers require an API model" + ) + return + + task_message = await ChatMessage.get_by_id(timer.current_message_id) + if not task_message: + await _set_timer_status(timer.id, "error", timer_error="timer task message is missing") + return + + reserve = await reserve_async_subagent( + config["max_async"], + task=task_message.content, + context="", + workspace=meta.get("workspace", ""), + user_id=timer.user_id, + parent_chat_id=parent.id, + parent_message_id=meta.get("timer_parent_message_id"), + connection=target.connection, + model=target.runtime_model, + model_id=target.full_model_id, + timer_chat_id=timer.id, + ) + if reserve.get("status") == "rejected": + return + + parent_messages = await ChatMessage.get_all_by_chat(parent.id) + parent_context = _pack_parent_context( + parent, parent_messages, meta.get("timer_parent_message_id") + ) + content = task_message.content + if parent_context: + content = f"{content}\n\n## Parent context at launch\n{parent_context}" + await ChatMessage.update(task_message.id, content=content) + + assistant_msg = await ChatMessage.create( + chat_id=timer.id, + role="assistant", + content="", + parent_id=task_message.id, + model=target.full_model_id, + done=False, + created_at=now_ms(), + ) + meta.update( + { + "timer_status": "running", + "timer_started_at": time.time_ns(), + "timer_assistant_message_id": assistant_msg.id, + "delegation_id": reserve["delegation_id"], + } + ) + await Chat.update_meta(timer.id, meta, now_ms()) + await Chat.update_current_message(timer.id, assistant_msg.id, now_ms()) + await export_chat_to_file(timer.id) + await attach_subagent_chat( + reserve["delegation_id"], + subagent_chat_id=timer.id, + subagent_message_id=assistant_msg.id, + ) + + async def runner() -> str: + return await _run_existing_subagent_chat( + assistant_msg_id=assistant_msg.id, + chat_id=timer.id, + workspace=meta.get("workspace", ""), + connection=target.connection, + model=target.runtime_model, + user_id=timer.user_id, + config=config, + ) + + await start_async_subagent(reserve["delegation_id"], runner) + + +async def timer_worker_loop(app) -> None: + """Poll durable pending timers; a capacity miss simply waits for the next pass.""" + from cptr.models import Chat + + logger.info("Timer worker started (poll interval: %ds)", TIMER_POLL_INTERVAL) + while True: + try: + due = await Chat.get_due_timers(time.time_ns()) + for timer in due: + await _launch_timer(timer, app) + except Exception: + logger.exception("Timer worker error") + await asyncio.sleep(TIMER_POLL_INTERVAL) + + +async def recover_timers() -> None: + """Do not replay work that was already launched before a process restart.""" + from cptr.models import Chat, ChatMessage + from cptr.utils.config import now_ms + + for timer in await Chat.get_timers("pending"): + current = await ChatMessage.get_by_id(timer.current_message_id) + if current and current.role == "assistant": + await ChatMessage.delete(current.id) + await Chat.update_current_message(timer.id, current.parent_id, now_ms()) + + for timer in await Chat.get_timers("running"): + await _set_timer_status( + timer.id, + "error", + timer_completed_at=time.time_ns(), + timer_error="interrupted by restart", + ) diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index 076d337..bd8e11f 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -1997,7 +1997,7 @@ async def search_chats( """ from sqlalchemy import select - from cptr.models import Chat, ChatMessage + from cptr.models import Chat, ChatMessage, is_internal_chat from cptr.utils.db import get_db user_id = __context__.get("user_id") @@ -2022,8 +2022,8 @@ async def search_chats( if not chat or chat.user_id != user_id: return None, "chat not found" meta = chat.meta or {} - if not include_subagents and meta.get("subagent"): - return None, "chat is a sub-agent chat" + if not include_subagents and is_internal_chat(meta): + return None, "chat is an internal chat" if workspace and meta.get("workspace") != workspace: return None, "chat is outside the current workspace" return chat, None @@ -2124,7 +2124,7 @@ async def search_chats( meta = chat.meta or {} if chat.id == current_chat_id: continue - if not include_subagents and meta.get("subagent"): + if not include_subagents and is_internal_chat(meta): continue if workspace and meta.get("workspace") != workspace: continue @@ -2299,7 +2299,7 @@ async def delegate_task( delegation_id = reserve["delegation_id"] try: - chat, assistant_msg = await _create_subagent_chat( + chat, _, assistant_msg = await _create_subagent_chat( task=task, context=context, workspace=__context__["workspace"], @@ -2369,6 +2369,76 @@ async def delegate_task( ) +async def timer( + prompt: str, + at: str, + cancel_on: list[Literal["chat.read", "chat.user_message"]] | None = None, + *, + __context__: dict, +) -> str: + """Set a one-shot timer for this chat. + + Use it when time is the missing input: wait for a deployment, retry after + backoff, revisit work after a deadline, or follow up after silence. At + `at`, the agent receives `prompt` and the latest thread context; it may + act, set another timer, or finish silently. + + `cancel_on` prevents launch when `chat.read` or `chat.user_message` + happens first in this chat. Omit it when timed work must run regardless. + """ + from cptr.utils.timers import parse_timer_at + + if not prompt.strip(): + return "Error: prompt must not be empty." + + try: + due_at = parse_timer_at(at) + except ValueError as exc: + return f"Error: {exc}" + + selected_events = cancel_on or [] + allowed_events = {"chat.read", "chat.user_message"} + if any(event not in allowed_events for event in selected_events): + return "Error: cancel_on accepts only chat.read and chat.user_message." + selected_events = list(dict.fromkeys(selected_events)) + + config = await _get_subagent_config() + if not config["background_enabled"]: + return "Error: background sub-agents are disabled in settings." + + full_model_id = __context__.get("full_model_id") or __context__["model_id"] + chat, _, _ = await _create_subagent_chat( + task=prompt, + context="", + workspace=__context__["workspace"], + model=full_model_id, + user_id=__context__["user_id"], + parent_chat_id=__context__["chat_id"], + config=config, + child_type="timer", + deferred=True, + extra_meta={ + "timer_at": due_at, + "cancel_on": selected_events, + "timer_status": "pending", + "timer_parent_message_id": __context__.get("message_id"), + "timer_model_id": full_model_id, + }, + ) + + from datetime import datetime, timezone + + return json.dumps( + { + "status": "set", + "at": datetime.fromtimestamp(due_at / 1_000_000_000, timezone.utc) + .isoformat() + .replace("+00:00", "Z"), + "cancel_on": selected_events, + } + ) + + async def _create_subagent_chat( task: str, context: str, @@ -2378,6 +2448,10 @@ async def _create_subagent_chat( parent_chat_id: str, config: dict, delegation_id: str | None = None, + *, + child_type: str = "subagent", + deferred: bool = False, + extra_meta: dict | None = None, ): """Create the real chat/messages used by a sub-agent.""" from cptr.models import Chat, ChatMessage @@ -2387,7 +2461,8 @@ async def _create_subagent_chat( user_content = f"{task}\n\n## Context\n{context}" if context else task meta = { "workspace": workspace, - "subagent": True, + "internal": True, + "type": child_type, "parent_chat_id": parent_chat_id, "params": { "tool_approval_mode": "full", # auto-approve all tools @@ -2395,10 +2470,12 @@ async def _create_subagent_chat( } if delegation_id: meta["delegation_id"] = delegation_id + if extra_meta: + meta.update(extra_meta) chat = await Chat.create( user_id=user_id, - title=f"Sub-agent: {task[:60]}", + title=f"{child_type.title()}: {task[:60]}", meta=meta, created_at=now_ms(), ) @@ -2410,19 +2487,22 @@ async def _create_subagent_chat( created_at=now_ms(), ) - assistant_msg = await ChatMessage.create( - chat_id=chat.id, - role="assistant", - content="", - parent_id=user_msg.id, - model=model, - done=False, - created_at=now_ms(), - ) - - await Chat.update_current_message(chat.id, assistant_msg.id, now_ms()) + assistant_msg = None + if deferred: + await Chat.update_current_message(chat.id, user_msg.id, now_ms()) + else: + assistant_msg = await ChatMessage.create( + chat_id=chat.id, + role="assistant", + content="", + parent_id=user_msg.id, + model=model, + done=False, + created_at=now_ms(), + ) + await Chat.update_current_message(chat.id, assistant_msg.id, now_ms()) await export_chat_to_file(chat.id) - return chat, assistant_msg + return chat, user_msg, assistant_msg async def _run_existing_subagent_chat( @@ -2469,7 +2549,7 @@ async def _run_subagent_chat( config: dict, ) -> str: """Create a real chat and run the agent loop on it.""" - chat, assistant_msg = await _create_subagent_chat( + chat, _, assistant_msg = await _create_subagent_chat( task=task, context=context, workspace=workspace, @@ -2491,6 +2571,7 @@ async def _run_subagent_chat( SUBAGENT_TOOLS: dict[str, dict] = { "delegate_task": {"fn": delegate_task, "auto": True}, + "timer": {"fn": timer, "auto": False}, } # Combined lookup for execution and approval (always available regardless of config) @@ -2811,7 +2892,7 @@ def _parse_param_descriptions(docstring: str) -> dict[str, str]: def _fn_to_schema(name: str, fn) -> dict: """Introspect function → {name, description, parameters} for LLM.""" doc = inspect.getdoc(fn) or "" - description = doc.split("\n")[0] + description = doc if name == "timer" else doc.split("\n")[0] param_descs = _parse_param_descriptions(doc) hints = get_type_hints(fn) sig = inspect.signature(fn) @@ -2895,6 +2976,8 @@ async def get_tool_list(builtin_tools: dict | None = None, workspace: str = "") "true", "1", ) + if not background_subagents_enabled: + tools.pop("timer", None) images_generation_enabled = (await Config.get("images.generation_enabled")) in ( True, "true",