This commit is contained in:
Timothy Jaeryang Baek committed 2026-07-12 00:57:58 -05:00
1 parent f031c479ba
commit e7afb6cba3
11 files changed
+550 -31

No files matched your search

+8
View File
@@ -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)
+2 -2
View File
@@ -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
+287
View File
@@ -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",
)
+104 -21
View File
@@ -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",