mirror of
https://github.com/open-webui/computer.git
synced 2026-12-01 01:12:44 -05:00
refac
This commit is contained in:
1 parent
82acf9f107
commit
fbed1b49fd
10 files changed
+799
-156
No files matched your search
@@ -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
@@ -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
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user