This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-19 23:14:20 +02:00
1 parent 82acf9f107
commit fbed1b49fd
10 files changed
+799 -156

No files matched your search

+6
View File
@@ -75,6 +75,12 @@ async def shutdown():
bot_manager = getattr(app.state, "bot_manager", None)
if bot_manager:
await bot_manager.stop_all()
try:
from cptr.utils.async_subagents import cancel_all_async_subagents
await cancel_all_async_subagents(reason="shutdown")
except Exception:
pass
# Clean up browser sessions and launched Chrome
try:
from cptr.utils.browser.session import session_manager
@@ -10,7 +10,9 @@
let saving = $state(false);
let enabled = $state(false);
let backgroundEnabled = $state(false);
let maxConcurrent = $state(3);
let maxAsync = $state(3);
let maxIterations = $state(30);
let maxOutput = $state(30000);
let systemPrompt = $state('');
@@ -19,7 +21,9 @@
try {
const config = await getAdminConfig();
enabled = config['subagents.enabled'] === true || config['subagents.enabled'] === 'true';
backgroundEnabled = config['subagents.background_enabled'] === true || config['subagents.background_enabled'] === 'true';
maxConcurrent = Number(config['subagents.max_concurrent']) || 3;
maxAsync = Number(config['subagents.max_async']) || 3;
maxIterations = Number(config['subagents.max_iterations']) || 30;
maxOutput = Number(config['subagents.max_output']) || 30000;
systemPrompt = (config['subagents.system_prompt'] as string) || '';
@@ -34,7 +38,9 @@
try {
await updateConfig({
'subagents.enabled': enabled,
'subagents.background_enabled': backgroundEnabled,
'subagents.max_concurrent': maxConcurrent,
'subagents.max_async': maxAsync,
'subagents.max_iterations': maxIterations,
'subagents.max_output': maxOutput,
'subagents.system_prompt': systemPrompt
@@ -73,6 +79,27 @@
</div>
</div>
<div>
<label class="flex items-center justify-between cursor-pointer">
<span class="text-xs text-gray-600 dark:text-gray-400">{$t('admin.subagentsBackgroundEnabled')}</span>
<ToggleSwitch value={backgroundEnabled} onchange={(v) => { backgroundEnabled = v; }} />
</label>
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-1">
{$t('admin.subagentsBackgroundHint')}
</p>
</div>
{#if backgroundEnabled}
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="sa-async">{$t('admin.subagentsMaxAsync')}</label>
<div class="flex items-center gap-1.5 mt-1">
<input id="sa-async" type="number" bind:value={maxAsync} min="1" max="10"
class="w-16 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors" />
<span class="text-[11px] text-gray-400 dark:text-gray-600">{$t('admin.subagentsMaxAsyncHint')}</span>
</div>
</div>
{/if}
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="sa-iterations">{$t('admin.subagentsMaxIterations')}</label>
<div class="flex items-center gap-1.5 mt-1">
@@ -188,7 +188,8 @@
}
case 'delegate_task': {
const t = args.task || '?';
return `Sub-agent: "${t.length > 60 ? t.slice(0, 60) + '…' : t}"`;
const label = args.background ? 'Background sub-agent' : 'Sub-agent';
return `${label}: "${t.length > 60 ? t.slice(0, 60) + '…' : t}"`;
}
default: {
// External tool: {server_id}_{tool_name} → "tool_name (server_id)"
@@ -161,8 +161,10 @@
const activePath = $derived.by((): PathEntry[] => {
if (!allMessages.length) return [];
// Exclude queued messages from the display path — they only appear in the queue UI
const displayMessages = allMessages.filter((m) => !m.meta?.queued);
// Exclude pending internal inputs until the parent has processed them.
const displayMessages = allMessages.filter(
(m) => !m.meta?.queued && !m.meta?.async_subagent_pending
);
if (!displayMessages.length) return [];
const msgMap = new Map(displayMessages.map((m) => [m.id, m]));
@@ -259,7 +261,7 @@
const isLanding = $derived(allMessages.length === 0 && !chatId);
const workspaceName = $derived(workspace.split('/').pop() || 'workspace');
// Queued messages: user messages with meta.queued flag (server-side queue)
// Queued messages: user-authored messages waiting behind an active response.
const queuedMessages = $derived(
allMessages
.filter((m) => m.role === 'user' && m.meta?.queued)
@@ -368,7 +370,8 @@
output?: any;
done?: boolean;
error?: string;
queue_processed?: boolean;
pending_inputs_processed?: boolean;
async_subagent_pending?: boolean;
title?: string;
}) {
// On the landing page, update the chat list in place from socket events
@@ -402,8 +405,8 @@
updateTab(tabId, data.chat_id, data.title);
}
// Queue was processed server-side: reload to see combined message + new generation
if (data.queue_processed) {
// Follow-up state changed server-side: reload to see new transcript/generation state.
if (data.pending_inputs_processed || data.async_subagent_pending) {
loadChat(data.chat_id);
return;
}
@@ -42,6 +42,21 @@
let editedContent = $state('');
let copied = $state(false);
let textareaEl: HTMLTextAreaElement;
let asyncExpanded = $state(false);
const isAsyncSubagentResult = $derived(meta?.async_subagent_result === true);
const delegationId = $derived(meta?.delegation_id || '');
const delegationIds = $derived(Array.isArray(meta?.delegation_ids) ? meta.delegation_ids : []);
const delegationLabel = $derived(
delegationId || (delegationIds.length > 1 ? `${delegationIds.length} tasks` : '')
);
const asyncSummary = $derived.by(() => {
const line = content
.split('\n')
.map((s) => s.trim())
.find((s) => s && !s.startsWith('['));
if (!line) return delegationLabel || '';
return line.length > 96 ? `${line.slice(0, 96)}...` : line;
});
async function startEdit() {
edit = true;
@@ -95,7 +110,37 @@
</script>
<div class="group">
{#if edit}
{#if isAsyncSubagentResult}
<div class="w-full min-w-0">
<button
type="button"
class="w-full min-w-0 flex items-center gap-2 text-left text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors"
aria-expanded={asyncExpanded}
onclick={() => (asyncExpanded = !asyncExpanded)}
>
<span class="w-1.5 h-1.5 rounded-full bg-gray-300 dark:bg-gray-600 shrink-0"></span>
<span class="text-[12px] font-medium shrink-0">{$t('chat.asyncSubagentComplete')}</span>
{#if asyncSummary}
<span class="text-[12px] truncate min-w-0 flex-1">{asyncSummary}</span>
{/if}
{#if delegationLabel}
<span class="hidden sm:inline text-[11px] font-mono text-gray-400 dark:text-gray-600 shrink-0">{delegationLabel}</span>
{/if}
<Icon
name="chevron-down"
size={12}
class="text-gray-400 dark:text-gray-600 shrink-0 transition-transform duration-150 {asyncExpanded ? 'rotate-180' : ''}"
/>
</button>
{#if asyncExpanded}
<div
class="mt-2 ml-3 border-l border-gray-100 dark:border-white/8 pl-3 text-[12.5px] leading-relaxed text-gray-600 dark:text-gray-400 whitespace-pre-wrap break-words"
>
{content}
</div>
{/if}
</div>
{:else if edit}
<!-- Edit mode: full width -->
<div class="w-full">
<div
@@ -541,6 +541,7 @@
"chat.tool.backgroundCommand": "Background: {{command}}",
"chat.tool.checkTask": "Check task {{id}}",
"chat.tool.killTask": "Kill task {{id}}",
"chat.asyncSubagentComplete": "Background sub-agent finished",
"chat.tool.webSearch": "Search web: \"{{query}}\"",
"chat.tool.fetchUrl": "Fetch {{hostname}}",
"chat.tool.fetchUrlFallback": "Fetch URL",
@@ -807,6 +808,10 @@
"admin.subagentsHint": "Allow the AI to delegate tasks to sub-agents. Each sub-agent creates a real chat with full tool access. Uses additional LLM calls.",
"admin.subagentsMaxConcurrent": "Max concurrent",
"admin.subagentsMaxConcurrentHint": "simultaneous sub-agents",
"admin.subagentsBackgroundEnabled": "Enable background sub-agents",
"admin.subagentsBackgroundHint": "Allow delegated sub-agents to keep running while the parent chat continues.",
"admin.subagentsMaxAsync": "Max background",
"admin.subagentsMaxAsyncHint": "background sub-agents",
"admin.subagentsMaxIterations": "Max iterations",
"admin.subagentsMaxIterationsHint": "tool loops per sub-agent",
"admin.subagentsMaxOutput": "Max output",
+112 -97
View File
@@ -428,15 +428,23 @@ async def send_message(body: SendMessageRequest, request: Request):
# Sync params into chat meta
if chat.meta is None:
chat.meta = {}
if chat.meta.get("params") != body.params:
if (
chat.meta.get("params") != body.params
or chat.meta.get("last_model") != body.model_id
):
chat.meta["params"] = body.params
chat.meta["last_model"] = body.model_id
await Chat.update_meta(chat.id, chat.meta)
else:
title = body.content[:50].strip() or "New Chat"
chat = await Chat.create(
user_id=user_id,
title=title,
meta={"workspace": body.workspace, "params": body.params},
meta={
"workspace": body.workspace,
"params": body.params,
"last_model": body.model_id,
},
created_at=now_ms(),
)
# Ensure .cptr/chats/ dir exists
@@ -446,70 +454,73 @@ async def send_message(body: SendMessageRequest, request: Request):
# Auto-add .cptr to .gitignore if this is a git repo
await asyncio.to_thread(ensure_cptr_gitignored, body.workspace)
# Check if the chat has an in-progress assistant message.
# If so, queue this message instead of starting a new task.
if body.chat_id and await _chat_has_active_generation(chat.id):
user_msg = await ChatMessage.create(
chat_id=chat.id,
role="user",
content=body.content,
parent_id=body.parent_id,
meta={"queued": True},
created_at=now_ms(),
)
# Double-check: if generation finished during our create,
# process queue now to close the race window.
if not await _chat_has_active_generation(chat.id):
from cptr.utils.chat_task import _process_queue
workspace = (chat.meta or {}).get("workspace", body.workspace)
await _process_queue(chat.id, user_id, workspace)
return {"chat_id": chat.id, "message_id": user_msg.id, "queued": True}
# Resolve connection for model
connection, bare_model = await _resolve_connection(body.model_id, request.app.state)
# Detect regeneration by checking parent message role
parent_msg = await ChatMessage.get_by_id(body.parent_id) if body.parent_id else None
if parent_msg and parent_msg.role == "user":
# Regeneration: create assistant as sibling of existing response
assistant_parent = body.parent_id
else:
# Normal send: create user message first
user_meta = {"files": body.files} if body.files else None
user_msg = await ChatMessage.create(
chat_id=chat.id,
role="user",
content=body.content,
parent_id=body.parent_id,
meta=user_meta,
created_at=now_ms(),
)
assistant_parent = user_msg.id
# Create empty assistant message
assistant_msg = await ChatMessage.create(
chat_id=chat.id,
role="assistant",
content="",
parent_id=assistant_parent,
model=body.model_id,
done=False,
created_at=now_ms(),
from cptr.utils.chat_task import (
get_pending_input_lock,
process_pending_chat_inputs,
start_task,
)
# Update chat pointer to new leaf
await Chat.update_current_message(chat.id, assistant_msg.id, now_ms())
queued_msg = None
user_msg = None
assistant_msg = None
async with get_pending_input_lock(chat.id):
if body.chat_id and await _chat_has_active_generation(chat.id):
queued_msg = await ChatMessage.create(
chat_id=chat.id,
role="user",
content=body.content,
parent_id=body.parent_id,
meta={"queued": True},
created_at=now_ms(),
)
else:
if parent_msg and parent_msg.role == "user":
# Regeneration: create assistant as sibling of existing response.
assistant_parent = body.parent_id
else:
user_meta = {"files": body.files} if body.files else None
user_msg = await ChatMessage.create(
chat_id=chat.id,
role="user",
content=body.content,
parent_id=body.parent_id,
meta=user_meta,
created_at=now_ms(),
)
assistant_parent = user_msg.id
assistant_msg = await ChatMessage.create(
chat_id=chat.id,
role="assistant",
content="",
parent_id=assistant_parent,
model=body.model_id,
done=False,
created_at=now_ms(),
)
# Update chat pointer to new leaf while still holding the input lock.
await Chat.update_current_message(chat.id, assistant_msg.id, now_ms())
if queued_msg:
workspace = (chat.meta or {}).get("workspace", body.workspace)
await process_pending_chat_inputs(chat.id, user_id, workspace)
return {"chat_id": chat.id, "message_id": queued_msg.id, "queued": True}
if not assistant_msg:
raise HTTPException(500, "failed to create assistant message")
# 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)
# Start background task (export_chat_to_file also runs after task completes)
from cptr.utils.chat_task import start_task
start_task(
message_id=assistant_msg.id,
chat_id=chat.id,
@@ -680,11 +691,11 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ
else:
call["status"] = "rejected"
await ChatMessage.update(message_id, output=output, done=True)
# Process queued messages since this chat is now idle
from cptr.utils.chat_task import _process_queue
# Process pending inputs since this chat is now idle.
from cptr.utils.chat_task import process_pending_chat_inputs
workspace = chat.meta.get("workspace", "") if chat.meta else ""
await _process_queue(chat_id, user_id, workspace)
await process_pending_chat_inputs(chat_id, user_id, workspace)
return {"ok": True}
@@ -715,11 +726,11 @@ async def cancel_task_endpoint(chat_id: str, message_id: str, request: Request):
item["status"] = "rejected"
await ChatMessage.update(message_id, output=output, done=True)
# Process queued messages since this chat may now be idle
from cptr.utils.chat_task import _process_queue
# Process pending inputs since this chat may now be idle.
from cptr.utils.chat_task import process_pending_chat_inputs
workspace = chat.meta.get("workspace", "") if chat.meta else ""
await _process_queue(chat_id, user_id, workspace)
await process_pending_chat_inputs(chat_id, user_id, workspace)
return {"ok": True}
@@ -824,53 +835,57 @@ async def queue_send_now(chat_id: str, message_id: str, request: Request):
if not (msg.meta and msg.meta.get("queued")):
raise HTTPException(400, "message is not queued")
# Cancel any active task
all_msgs = await ChatMessage.get_all_by_chat(chat_id)
for m in all_msgs:
if m.role == "assistant" and not m.done:
from cptr.utils.chat_task import cancel_task
from cptr.utils.chat_task import cancel_task, get_pending_input_lock, start_task
await cancel_task(m.id)
await ChatMessage.update(m.id, done=True)
async with get_pending_input_lock(chat_id):
# Cancel any active task
all_msgs = await ChatMessage.get_all_by_chat(chat_id)
for m in all_msgs:
if m.role == "assistant" and not m.done:
await cancel_task(m.id)
await ChatMessage.update(m.id, done=True)
# Delete all OTHER queued messages, keep this one
for m in all_msgs:
if m.role == "user" and m.meta and m.meta.get("queued") and m.id != message_id:
# Delete all OTHER queued user prompts, keep this one.
for m in all_msgs:
if not (m.role == "user" and m.meta and m.meta.get("queued") and m.id != message_id):
continue
await ChatMessage.delete(m.id)
# Clear queued flag on this message
meta = dict(msg.meta or {})
meta.pop("queued", None)
await ChatMessage.update(message_id, meta=meta or None)
# Clear queued flag on this message
meta = dict(msg.meta or {})
meta.pop("queued", None)
await ChatMessage.update(message_id, meta=meta or None)
# Find parent: latest done assistant message, or the queued message's parent
done_assistants = [m for m in all_msgs if m.role == "assistant" and m.done]
parent_id = done_assistants[-1].id if done_assistants else msg.parent_id
# Find parent: latest done assistant message, or the queued message's parent
done_assistants = [m for m in all_msgs if m.role == "assistant" and m.done]
parent_id = done_assistants[-1].id if done_assistants else msg.parent_id
# Re-parent the user message to the correct leaf
if msg.parent_id != parent_id:
await ChatMessage.update(message_id, parent_id=parent_id)
# Re-parent the user message to the correct leaf
if msg.parent_id != parent_id:
await ChatMessage.update(message_id, parent_id=parent_id)
# Resolve connection and start task
model_id = msg.model or (all_msgs[-1].model if all_msgs else "")
if not model_id:
# Fall back to last used model from chat meta
model_id = (chat.meta or {}).get("last_model", "")
connection, bare_model = await _resolve_connection(model_id, request.app.state)
workspace = (chat.meta or {}).get("workspace", "")
# Resolve connection and start task
model_id = msg.model or (all_msgs[-1].model if all_msgs else "")
if not model_id:
# Fall back to last used model from chat meta
model_id = (chat.meta or {}).get("last_model", "")
connection, bare_model = await _resolve_connection(model_id, request.app.state)
workspace = (chat.meta or {}).get("workspace", "")
meta_for_model = dict(chat.meta or {})
if meta_for_model.get("last_model") != model_id:
meta_for_model["last_model"] = model_id
await Chat.update_meta(chat.id, meta_for_model, now_ms())
assistant_msg = await ChatMessage.create(
chat_id=chat_id,
role="assistant",
content="",
parent_id=message_id,
model=model_id,
done=False,
created_at=now_ms(),
)
await Chat.update_current_message(chat_id, assistant_msg.id, now_ms())
from cptr.utils.chat_task import start_task
assistant_msg = await ChatMessage.create(
chat_id=chat_id,
role="assistant",
content="",
parent_id=message_id,
model=model_id,
done=False,
created_at=now_ms(),
)
await Chat.update_current_message(chat_id, assistant_msg.id, now_ms())
start_task(
message_id=assistant_msg.id,
+325
View File
@@ -0,0 +1,325 @@
"""Session-scoped async subagent registry.
Background subagents are deliberately not durable jobs. They run in the
current server process, keep a small in-memory status record, and inject their
final summary back into the parent chat when they finish.
"""
from __future__ import annotations
import asyncio
import logging
import time
import uuid
from collections.abc import Awaitable, Callable
from typing import Any
from cptr.models import Chat, ChatMessage
from cptr.socket.main import emit_to_user
from cptr.utils.chat_export import export_chat_to_file
from cptr.utils.config import now_ms
logger = logging.getLogger(__name__)
_records: dict[str, dict[str, Any]] = {}
_lock = asyncio.Lock()
_MAX_RETAINED_COMPLETED = 50
_completion_injector_override: Callable[[dict[str, Any]], Awaitable[None]] | None = None
def _new_delegation_id() -> str:
return f"deleg_{uuid.uuid4().hex[:8]}"
async def active_count() -> int:
"""Return the number of running background subagents."""
async with _lock:
return sum(1 for r in _records.values() if r.get("status") in {"starting", "running"})
async def reserve_async_subagent(max_async: int, **record: Any) -> dict[str, Any]:
"""Reserve capacity for a background subagent before creating its chat."""
max_async = max(1, int(max_async or 3))
async with _lock:
running = sum(
1 for r in _records.values() if r.get("status") in {"starting", "running"}
)
if running >= max_async:
return {
"status": "rejected",
"error": (
f"Async subagent capacity reached ({max_async} running). "
"Wait for one to finish or increase subagents.max_async."
),
}
delegation_id = _new_delegation_id()
now = time.time()
_records[delegation_id] = {
**record,
"delegation_id": delegation_id,
"status": "starting",
"dispatched_at": now,
"completed_at": None,
"task": None,
"error": None,
"summary": None,
}
return {"status": "reserved", "delegation_id": delegation_id}
async def attach_subagent_chat(
delegation_id: str,
*,
subagent_chat_id: str,
subagent_message_id: str,
) -> None:
async with _lock:
record = _records.get(delegation_id)
if record:
record["subagent_chat_id"] = subagent_chat_id
record["subagent_message_id"] = subagent_message_id
record["status"] = "running"
async def start_async_subagent(
delegation_id: str,
runner: Callable[[], Awaitable[str]],
) -> None:
"""Start a reserved subagent runner and return immediately."""
async def _run() -> None:
status = "completed"
summary = ""
error = None
try:
summary = await runner()
except asyncio.CancelledError:
status = "interrupted"
error = "cancelled"
raise
except Exception as exc: # noqa: BLE001 - completion must still be recorded
logger.exception("Async subagent %s failed", delegation_id)
status = "error"
error = f"{type(exc).__name__}: {exc}"
finally:
await _finalize(delegation_id, status=status, summary=summary, error=error)
task = asyncio.create_task(_run())
async with _lock:
record = _records.get(delegation_id)
if record:
record["task"] = task
async def fail_reserved_subagent(delegation_id: str, error: str) -> None:
await _finalize(delegation_id, status="error", summary="", error=error)
async def cancel_all_async_subagents(reason: str = "shutdown") -> int:
"""Cancel all running background subagents."""
async with _lock:
tasks = [
r.get("task")
for r in _records.values()
if r.get("status") in {"starting", "running"} and r.get("task")
]
count = 0
for task in tasks:
if task and not task.done():
task.cancel()
count += 1
if count:
logger.info("Cancelled %d async subagent(s) (%s)", count, reason)
return count
def list_async_subagents() -> list[dict[str, Any]]:
"""Return a serializable snapshot of records."""
snapshot = []
for record in _records.values():
snapshot.append({k: v for k, v in record.items() if k != "task"})
return snapshot
async def _finalize(
delegation_id: str,
*,
status: str,
summary: str,
error: str | None,
) -> None:
async with _lock:
record = _records.get(delegation_id)
if not record:
return
record["status"] = status
record["summary"] = summary
record["error"] = error
record["completed_at"] = time.time()
snapshot = {k: v for k, v in record.items() if k != "task"}
_prune_completed_locked()
injector = _completion_injector_override or _inject_completion
try:
await injector(snapshot)
except Exception:
logger.exception("Failed to inject async subagent completion %s", delegation_id)
def _prune_completed_locked() -> None:
completed = [
(rid, r)
for rid, r in _records.items()
if r.get("status") not in {"starting", "running"}
]
if len(completed) <= _MAX_RETAINED_COMPLETED:
return
completed.sort(key=lambda kv: kv[1].get("completed_at") or kv[1].get("dispatched_at") or 0)
for rid, _ in completed[: len(completed) - _MAX_RETAINED_COMPLETED]:
_records.pop(rid, None)
async def _inject_completion(record: dict[str, Any]) -> None:
parent_chat_id = record.get("parent_chat_id")
user_id = record.get("user_id")
if not parent_chat_id or not user_id:
return
chat = await Chat.get_by_id(parent_chat_id)
if not chat:
return
model_id = _parent_model_id(chat, record)
content = _format_completion(record)
from cptr.utils.chat_task import get_pending_input_lock, start_task
assistant_msg = None
async with get_pending_input_lock(parent_chat_id):
all_msgs = await ChatMessage.get_all_by_chat(parent_chat_id)
active = any(m.role == "assistant" and not m.done for m in all_msgs)
done_assistants = [m for m in all_msgs if m.role == "assistant" and m.done]
parent_id = done_assistants[-1].id if done_assistants else record.get("parent_message_id")
meta = {
"async_subagent_result": True,
"delegation_id": record.get("delegation_id"),
"subagent_chat_id": record.get("subagent_chat_id"),
}
if active:
meta["async_subagent_pending"] = True
user_msg = await ChatMessage.create(
chat_id=parent_chat_id,
role="user",
content=content,
parent_id=parent_id,
model=model_id,
meta=meta,
created_at=now_ms(),
)
if not active:
assistant_msg = await ChatMessage.create(
chat_id=parent_chat_id,
role="assistant",
content="",
parent_id=user_msg.id,
model=model_id,
done=False,
created_at=now_ms(),
)
await Chat.update_current_message(parent_chat_id, assistant_msg.id, now_ms())
await export_chat_to_file(parent_chat_id)
if not assistant_msg:
await emit_to_user(
user_id,
{
"chat_id": parent_chat_id,
"message_id": user_msg.id,
"async_subagent_pending": True,
},
)
return
await emit_to_user(
user_id,
{
"chat_id": parent_chat_id,
"message_id": assistant_msg.id,
"pending_inputs_processed": True,
},
)
start_task(
message_id=assistant_msg.id,
chat_id=parent_chat_id,
user_id=user_id,
connection=record["connection"],
workspace=record["workspace"],
model=record["model"],
)
def _parent_model_id(chat: Chat, record: dict[str, Any]) -> str:
meta = chat.meta or {}
return str(meta.get("last_model") or record.get("model_id") or record.get("model") or "")
def _format_completion(record: dict[str, Any]) -> str:
status = record.get("status") or "completed"
summary = record.get("summary") or ""
error = record.get("error")
dispatched_at = record.get("dispatched_at")
completed_at = record.get("completed_at") or time.time()
duration = ""
if isinstance(dispatched_at, (int, float)):
duration = f"{completed_at - dispatched_at:.1f}s"
lines = [
f"[ASYNC SUBAGENT COMPLETE - {record.get('delegation_id', 'unknown')}]",
(
"A background subagent you dispatched earlier has finished. "
"The original task source is included so you can decide whether "
"to use the result or continue without it."
),
"",
f"Original task: {record.get('task', '')}",
]
if record.get("context"):
lines.append(f"Context provided: {record['context']}")
if record.get("subagent_chat_id"):
lines.append(f"Subagent chat: {record['subagent_chat_id']}")
if duration:
lines.append(f"Status: {status} Duration: {duration}")
else:
lines.append(f"Status: {status}")
lines.append("--- RESULT ---")
if status == "completed":
lines.append(summary or "Subagent completed without a final summary.")
elif status == "interrupted":
lines.append("The subagent was interrupted before completing.")
if summary:
lines.extend(["Partial output:", summary])
else:
detail = f" {error}" if error else ""
lines.append(f"The subagent did not complete successfully.{detail}")
if summary:
lines.extend(["Partial output:", summary])
return "\n".join(lines)
def _set_completion_injector_for_tests(
injector: Callable[[dict[str, Any]], Awaitable[None]] | None,
) -> None:
global _completion_injector_override
_completion_injector_override = injector
async def _reset_for_tests() -> None:
await cancel_all_async_subagents(reason="test reset")
async with _lock:
_records.clear()
_set_completion_injector_for_tests(None)
+98 -28
View File
@@ -43,7 +43,11 @@ PLAN_MODE_PROMPT = (
_tasks: dict[str, asyncio.Task] = {} # message_id → asyncio.Task
_task_state: dict[str, dict] = {} # message_id → {content, output}
_task_chat: dict[str, str] = {} # message_id → chat_id
_queue_locks: dict[str, asyncio.Lock] = {} # chat_id → Lock
_pending_input_locks: dict[str, asyncio.Lock] = {} # chat_id → Lock
def get_pending_input_lock(chat_id: str) -> asyncio.Lock:
return _pending_input_locks.setdefault(chat_id, asyncio.Lock())
def start_task(
@@ -98,37 +102,89 @@ def get_active_chat_ids() -> set[str]:
return {cid for mid, cid in _task_chat.items() if mid in _tasks and not _tasks[mid].done()}
# ── Queue processing ────────────────────────────────────────
# ── Pending input processing ────────────────────────────────
async def _process_queue(chat_id: str, user_id: str, workspace: str):
"""Check for queued user messages and start the next task.
def _merge_async_subagent_result_meta(messages: list[ChatMessage]) -> dict | None:
if not messages:
return None
if all((m.meta or {}).get("async_subagent_result") for m in messages):
delegation_ids = [
m.meta.get("delegation_id")
for m in messages
if m.meta and m.meta.get("delegation_id")
]
subagent_chat_ids = [
m.meta.get("subagent_chat_id")
for m in messages
if m.meta and m.meta.get("subagent_chat_id")
]
meta = {"async_subagent_result": True}
if len(delegation_ids) == 1:
meta["delegation_id"] = delegation_ids[0]
elif delegation_ids:
meta["delegation_ids"] = delegation_ids
if len(subagent_chat_ids) == 1:
meta["subagent_chat_id"] = subagent_chat_ids[0]
elif subagent_chat_ids:
meta["subagent_chat_ids"] = subagent_chat_ids
return meta
return None
def _is_pending_internal_subagent_result(message: ChatMessage) -> bool:
return bool((message.meta or {}).get("async_subagent_pending"))
def _is_pending_chat_input(message: ChatMessage) -> bool:
meta = message.meta or {}
return bool(meta.get("queued") or meta.get("async_subagent_pending"))
def _first_pending_input_batch(messages: list[ChatMessage]) -> list[ChatMessage]:
if not messages:
return []
first_is_internal_subagent_result = _is_pending_internal_subagent_result(messages[0])
batch = []
for message in messages:
if _is_pending_internal_subagent_result(message) != first_is_internal_subagent_result:
break
batch.append(message)
return batch
async def process_pending_chat_inputs(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
both the task's finally block and the API double-check.
"""
lock = _queue_locks.setdefault(chat_id, asyncio.Lock())
lock = get_pending_input_lock(chat_id)
async with lock:
all_msgs = await ChatMessage.get_all_by_chat(chat_id)
# Don't process queue if there's still an active generation
# Wait until the parent assistant turn is idle.
if any(m.role == "assistant" and not m.done for m in all_msgs):
return
# Find queued messages (ordered by created_at)
queued = [m for m in all_msgs if m.role == "user" and m.meta and m.meta.get("queued")]
if not queued:
pending_inputs = [
m for m in all_msgs if m.role == "user" and _is_pending_chat_input(m)
]
if not pending_inputs:
return
input_batch = _first_pending_input_batch(pending_inputs)
# Combine all queued prompts into one user message
combined_content = "\n\n".join(m.content for m in queued if m.content)
combined_content = "\n\n".join(m.content for m in input_batch if m.content)
combined_meta = _merge_async_subagent_result_meta(input_batch)
# Find the current leaf (latest done assistant message)
done_assistants = [m for m in all_msgs if m.role == "assistant" and m.done]
parent_id = done_assistants[-1].id if done_assistants else queued[0].parent_id
parent_id = done_assistants[-1].id if done_assistants else input_batch[0].parent_id
# Delete individual queued messages, create one combined message
for m in queued:
for m in input_batch:
await ChatMessage.delete(m.id)
combined_msg = await ChatMessage.create(
@@ -136,6 +192,7 @@ async def _process_queue(chat_id: str, user_id: str, workspace: str):
role="user",
content=combined_content,
parent_id=parent_id,
meta=combined_meta,
created_at=now_ms(),
)
@@ -149,7 +206,10 @@ async def _process_queue(chat_id: str, user_id: str, workspace: str):
last_asst = done_assistants[-1] if done_assistants else None
model_id = (last_asst.model if last_asst else "") or ""
if not model_id:
logger.error("[queue] No model found for chat %s, cannot process queue", chat_id)
logger.error(
"[chat-input] No model found for chat %s, cannot process pending input",
chat_id,
)
return
# Resolve connection
@@ -158,7 +218,7 @@ async def _process_queue(chat_id: str, user_id: str, workspace: str):
connection, bare_model = await _resolve_connection(model_id)
except Exception:
logger.exception("[queue] Failed to resolve connection for model %s", model_id)
logger.exception("[chat-input] Failed to resolve connection for model %s", model_id)
return
# Create assistant placeholder
@@ -173,10 +233,14 @@ async def _process_queue(chat_id: str, user_id: str, workspace: str):
)
await Chat.update_current_message(chat_id, assistant_msg.id, now_ms())
# Notify frontend that queue was processed (new messages appeared)
# Notify frontend that pending inputs became transcript messages.
await emit_to_user(
user_id,
{"chat_id": chat_id, "message_id": assistant_msg.id, "queue_processed": True},
{
"chat_id": chat_id,
"message_id": assistant_msg.id,
"pending_inputs_processed": True,
},
)
# Start new task
@@ -189,19 +253,19 @@ async def _process_queue(chat_id: str, user_id: str, workspace: str):
model=bare_model,
)
logger.info(
"[queue] Processed %d queued message(s) for chat %s",
len(queued),
"[chat-input] Processed %d pending input message(s) for chat %s",
len(input_batch),
chat_id[:8],
)
async def reconcile_chat_state():
"""Recover from server crash: fix stuck messages, process orphaned queues.
"""Recover from server crash: fix stuck messages and resume pending inputs.
Called once on startup when ENABLE_CHAT_RECONCILE_ON_STARTUP=true (default).
Finds:
1. Assistant messages with done=False that have no running task → mark done
2. Chats with queued user messages → process them
2. Chats with pending user prompts or subagent results → process them
"""
from sqlalchemy import select, and_
from cptr.utils.db import get_db
@@ -226,15 +290,15 @@ async def reconcile_chat_state():
await ChatMessage.update(msg.id, done=True, meta=meta)
healed_chats.add(msg.chat_id)
# Process orphaned queues for healed chats
# Resume pending inputs for healed chats.
for cid in healed_chats:
chat = await Chat.get_by_id(cid)
if chat:
workspace = (chat.meta or {}).get("workspace", "")
try:
await _process_queue(cid, chat.user_id, workspace)
await process_pending_chat_inputs(cid, chat.user_id, workspace)
except Exception:
logger.exception("[reconcile] Failed to process queue for chat %s", cid)
logger.exception("[reconcile] Failed to process pending inputs for chat %s", cid)
if healed_chats:
logger.info("[reconcile] Recovered %d chat(s) on startup", len(healed_chats))
@@ -1026,6 +1090,7 @@ async def run_chat_task(
plan_mode = chat_params.get("plan_mode", False)
if plan_mode:
tools = [t for t in tools if ALL_TOOLS.get(t["name"], {}).get("auto")]
tools = [t for t in tools if t["name"] != "delegate_task"]
# Inject create_artifact (only available in plan mode)
tools.append(_fn_to_schema("create_artifact", create_artifact))
messages.append({"role": "user", "content": PLAN_MODE_PROMPT})
@@ -1265,7 +1330,12 @@ async def run_chat_task(
"workspace": workspace,
"user_id": user_id,
"model_id": model,
"full_model_id": (
(chat_obj.meta or {}).get("last_model") if chat_obj else None
)
or model,
"chat_id": chat_id,
"message_id": message_id,
"connection": connection,
}
@@ -1555,8 +1625,8 @@ async def run_chat_task(
await post_webhook(webhook_url, title, preview)
except Exception:
logger.debug("[webhook] Error sending webhook for chat %s", chat_id[:8], exc_info=True)
# Process any queued follow-up messages
# Process any pending user prompts or internal subagent results.
try:
await _process_queue(chat_id, user_id, workspace)
await process_pending_chat_inputs(chat_id, user_id, workspace)
except Exception:
logger.exception(f"Failed to process queue for chat {chat_id}")
logger.exception(f"Failed to process pending inputs for chat {chat_id}")
+169 -23
View File
@@ -1498,6 +1498,9 @@ async def _get_subagent_config() -> dict:
return {
"max_concurrent": int(await Config.get("subagents.max_concurrent") or 3),
"background_enabled": (await Config.get("subagents.background_enabled"))
in (True, "true", "1"),
"max_async": int(await Config.get("subagents.max_async") or 3),
"max_iterations": int(await Config.get("subagents.max_iterations") or 30),
"max_output": int(await Config.get("subagents.max_output") or 30_000),
"system_prompt": (await Config.get("subagents.system_prompt"))
@@ -1515,16 +1518,89 @@ def _truncate_output(text: str, max_chars: int) -> str:
async def delegate_task(
task: str,
context: str = "",
background: bool = False,
*,
__context__: dict,
) -> str:
"""Delegate a task to a sub-agent. The sub-agent has full access to read, write, edit files, and run commands. Use for parallel work — call multiple times in one response to run tasks concurrently.
"""Delegate a task to a sub-agent. Use background=true for long-running independent work.
:param task: What the sub-agent should do.
:param context: Optional context (e.g. relevant file paths, decisions made so far).
:param background: Return a handle immediately and inject the final result into this chat when done.
"""
global _subagent_semaphore
config = await _get_subagent_config()
if background:
if not config["background_enabled"]:
return "Error: background sub-agents are disabled in settings."
from cptr.utils.async_subagents import (
attach_subagent_chat,
fail_reserved_subagent,
reserve_async_subagent,
start_async_subagent,
)
reserve = await reserve_async_subagent(
config["max_async"],
task=task,
context=context,
workspace=__context__["workspace"],
user_id=__context__["user_id"],
parent_chat_id=__context__["chat_id"],
parent_message_id=__context__.get("message_id"),
connection=__context__["connection"],
model=__context__["model_id"],
model_id=__context__.get("full_model_id") or __context__["model_id"],
)
if reserve.get("status") == "rejected":
return f"Error: {reserve['error']}"
delegation_id = reserve["delegation_id"]
try:
chat, assistant_msg = await _create_subagent_chat(
task=task,
context=context,
workspace=__context__["workspace"],
model=__context__["model_id"],
user_id=__context__["user_id"],
parent_chat_id=__context__["chat_id"],
config=config,
delegation_id=delegation_id,
)
except Exception as e:
await fail_reserved_subagent(delegation_id, str(e))
return f"Error: failed to create background sub-agent: {e}"
await attach_subagent_chat(
delegation_id,
subagent_chat_id=chat.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=chat.id,
workspace=__context__["workspace"],
connection=__context__["connection"],
model=__context__["model_id"],
user_id=__context__["user_id"],
config=config,
)
await start_async_subagent(delegation_id, _runner)
return json.dumps(
{
"status": "dispatched",
"delegation_id": delegation_id,
"subagent_chat_id": chat.id,
"mode": "background",
"task": task,
}
)
if _subagent_semaphore is None:
_subagent_semaphore = asyncio.Semaphore(config["max_concurrent"])
@@ -1541,40 +1617,40 @@ async def delegate_task(
)
async def _run_subagent_chat(
async def _create_subagent_chat(
task: str,
context: str,
workspace: str,
connection: dict,
model: str,
user_id: str,
parent_chat_id: str,
config: dict,
) -> str:
"""Create a real chat and run the agent loop on it."""
delegation_id: str | None = None,
):
"""Create the real chat/messages used by a sub-agent."""
from cptr.models import Chat, ChatMessage
from cptr.utils.chat_task import run_chat_task
from cptr.utils.chat_export import export_chat_to_file
from cptr.utils.config import now_ms
# Build the user message content
user_content = f"{task}\n\n## Context\n{context}" if context else task
meta = {
"workspace": workspace,
"subagent": True,
"parent_chat_id": parent_chat_id,
"params": {
"tool_approval_mode": "full", # auto-approve all tools
},
}
if delegation_id:
meta["delegation_id"] = delegation_id
# Create a real chat, marked as a sub-agent
chat = await Chat.create(
user_id=user_id,
title=f"Sub-agent: {task[:60]}",
meta={
"workspace": workspace,
"subagent": True,
"parent_chat_id": parent_chat_id,
"params": {
"tool_approval_mode": "full", # auto-approve all tools
},
},
meta=meta,
created_at=now_ms(),
)
# Create user message
user_msg = await ChatMessage.create(
chat_id=chat.id,
role="user",
@@ -1582,7 +1658,6 @@ async def _run_subagent_chat(
created_at=now_ms(),
)
# Create empty assistant message
assistant_msg = await ChatMessage.create(
chat_id=chat.id,
role="assistant",
@@ -1594,24 +1669,69 @@ async def _run_subagent_chat(
)
await Chat.update_current_message(chat.id, assistant_msg.id, now_ms())
await export_chat_to_file(chat.id)
return chat, assistant_msg
async def _run_existing_subagent_chat(
assistant_msg_id: str,
chat_id: str,
workspace: str,
connection: dict,
model: str,
user_id: str,
config: dict,
) -> str:
"""Run the agent loop for an already-created sub-agent chat."""
from cptr.models import ChatMessage
from cptr.utils.chat_task import run_chat_task
# Run the SAME agent loop as a normal chat — no special code
await run_chat_task(
message_id=assistant_msg.id,
chat_id=chat.id,
message_id=assistant_msg_id,
chat_id=chat_id,
user_id=user_id,
connection=connection,
workspace=workspace,
model=model,
)
# Read back the completed message
result_msg = await ChatMessage.get_by_id(assistant_msg.id)
result_msg = await ChatMessage.get_by_id(assistant_msg_id)
output = result_msg.content if result_msg else "Sub-agent produced no output."
return _truncate_output(output, config["max_output"])
async def _run_subagent_chat(
task: str,
context: str,
workspace: str,
connection: dict,
model: str,
user_id: str,
parent_chat_id: str,
config: dict,
) -> str:
"""Create a real chat and run the agent loop on it."""
chat, assistant_msg = await _create_subagent_chat(
task=task,
context=context,
workspace=workspace,
model=model,
user_id=user_id,
parent_chat_id=parent_chat_id,
config=config,
)
return await _run_existing_subagent_chat(
assistant_msg_id=assistant_msg.id,
chat_id=chat.id,
workspace=workspace,
connection=connection,
model=model,
user_id=user_id,
config=config,
)
SUBAGENT_TOOLS: dict[str, dict] = {
"delegate_task": {"fn": delegate_task, "auto": True},
}
@@ -1891,6 +2011,24 @@ def _fn_to_schema(name: str, fn) -> dict:
}
def _without_background_param(schema: dict) -> dict:
"""Return a delegate_task schema copy without the background option."""
if schema.get("name") != "delegate_task":
return schema
schema = {
**schema,
"parameters": {
**schema.get("parameters", {}),
"properties": dict(schema.get("parameters", {}).get("properties", {})),
},
}
schema["parameters"]["properties"].pop("background", None)
required = schema["parameters"].get("required")
if isinstance(required, list):
schema["parameters"]["required"] = [r for r in required if r != "background"]
return schema
async def get_tool_list() -> list[dict]:
"""Return tool schemas for the LLM.
@@ -1898,6 +2036,7 @@ async def get_tool_list() -> list[dict]:
and external tool server tools when configured.
"""
tools = dict(TOOLS)
background_subagents_enabled = False
try:
from cptr.models import Config
@@ -1905,10 +2044,17 @@ async def get_tool_list() -> list[dict]:
tools.update(BROWSER_TOOLS)
if (await Config.get("subagents.enabled")) in (True, "true", "1"):
tools.update(SUBAGENT_TOOLS)
background_subagents_enabled = (await Config.get("subagents.background_enabled")) in (
True,
"true",
"1",
)
except Exception:
pass
schemas = [_fn_to_schema(name, t["fn"]) for name, t in tools.items()]
if not background_subagents_enabled:
schemas = [_without_background_param(s) for s in schemas]
# Add external tool server schemas
try: