This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-25 16:53:57 -04:00
1 parent 14cfd98a67
commit 89ff737dfd
21 files changed
+1875 -90

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Coding agent support for Codex and Claude Code."""
+152
View File
@@ -0,0 +1,152 @@
"""Claude Code SDK adapter."""
from __future__ import annotations
import asyncio
import os
import shlex
from typing import Any, AsyncIterator
from cptr.utils.agents.events import AgentDone, AgentError, AgentEvent, AgentReasoningDelta, AgentTextDelta
def _prompt_from_messages(messages: list[dict[str, Any]]) -> str:
parts: list[str] = []
for message in messages:
role = message.get("role", "user")
content = message.get("content", "")
if isinstance(content, list):
text = "\n".join(
str(block.get("text", "")) for block in content if isinstance(block, dict)
)
else:
text = str(content or "")
if text:
parts.append(f"[{role}]\n{text}")
return "\n\n".join(parts)
def _chat_approval_mode(chat_params: dict[str, Any]) -> str:
if "tool_approval_mode" in chat_params:
return str(chat_params.get("tool_approval_mode") or "auto")
if "auto_approve_tools" in chat_params:
return "full" if chat_params.get("auto_approve_tools") else "auto"
return "auto"
def _permission_mode(chat_approval_mode: str) -> str:
if chat_approval_mode == "full":
return "bypassPermissions"
if chat_approval_mode == "auto":
return "acceptEdits"
return "default"
async def run_claude_code_agent(
*,
profile: dict[str, Any],
model: str,
workspace: str,
messages: list[dict[str, Any]],
system_prompt: str,
chat_params: dict[str, Any],
resume_state: dict[str, Any] | None,
) -> AsyncIterator[AgentEvent]:
try:
import claude_agent_sdk as sdk
except ImportError:
yield AgentError("Claude Code support requires the claude-agent-sdk Python package")
return
prompt = _prompt_from_messages(messages)
env = os.environ.copy()
if profile.get("home"):
env["HOME"] = os.path.expanduser(str(profile["home"]))
permission_mode = _permission_mode(_chat_approval_mode(chat_params))
launch_args = str(profile.get("launch_args") or "").strip()
extra_args = shlex.split(launch_args) if launch_args else []
try:
options_kwargs: dict[str, Any] = {
"system_prompt": system_prompt or None,
"permission_mode": permission_mode,
"env": env,
"include_partial_messages": True,
}
if workspace:
options_kwargs["cwd"] = workspace
if extra_args:
options_kwargs["extra_args"] = {arg: None for arg in extra_args}
options = sdk.ClaudeAgentOptions(**options_kwargs)
options.cli_path = str(profile["command"])
if model != "default":
options.model = model
client = sdk.ClaudeSDKClient(options)
await client.connect()
session_id = None
if resume_state:
value = resume_state.get("session_id")
session_id = value if isinstance(value, str) and value else None
try:
query = client.query(prompt, session_id=session_id) if session_id else client.query(prompt)
await asyncio.wait_for(query, timeout=20)
stream = client.receive_response()
usage: dict[str, Any] | None = None
observed_session_id = session_id
async for message in stream:
event = getattr(message, "event", None)
if isinstance(event, dict):
event_type = event.get("type")
if event_type == "content_block_delta":
delta = event.get("delta", {})
if isinstance(delta, dict):
if delta.get("type") == "text_delta" and isinstance(delta.get("text"), str):
yield AgentTextDelta(delta["text"])
elif delta.get("type") == "thinking_delta" and isinstance(
delta.get("thinking"), str
):
yield AgentReasoningDelta(delta["thinking"])
continue
class_name = message.__class__.__name__
if class_name == "AssistantMessage":
for block in getattr(message, "content", []) or []:
if block.__class__.__name__ == "TextBlock":
text = getattr(block, "text", "")
if text:
yield AgentTextDelta(text)
elif block.__class__.__name__ == "ThinkingBlock":
text = getattr(block, "thinking", "")
if text:
yield AgentReasoningDelta(text)
elif class_name == "ResultMessage":
observed_session_id = getattr(message, "session_id", None) or observed_session_id
raw_usage = getattr(message, "usage", None)
if isinstance(raw_usage, dict):
usage = {
**raw_usage,
"total_tokens": (raw_usage.get("input_tokens") or 0)
+ (raw_usage.get("output_tokens") or 0),
}
break
yield AgentDone(
usage=usage,
resume_state={
"profile_id": profile["id"],
"session_id": observed_session_id,
"workspace": workspace,
"model": model,
},
)
finally:
await client.disconnect()
except asyncio.CancelledError:
raise
except Exception as exc: # noqa: BLE001 - surfaced in the chat.
yield AgentError(str(exc))
+242
View File
@@ -0,0 +1,242 @@
"""Codex app-server adapter."""
from __future__ import annotations
import asyncio
import json
import os
from contextlib import suppress
from typing import Any, AsyncIterator
from cptr.utils.agents.events import (
AgentDone,
AgentError,
AgentEvent,
AgentReasoningDelta,
AgentTextDelta,
)
class CodexAppServer:
def __init__(self, command: str, cwd: str, env: dict[str, str]) -> None:
self.command = command
self.cwd = cwd
self.env = env
self.proc: asyncio.subprocess.Process | None = None
self.reader_task: asyncio.Task | None = None
self.stderr_task: asyncio.Task | None = None
self.pending: dict[int, asyncio.Future[dict[str, Any]]] = {}
self.events: asyncio.Queue[dict[str, Any]] = asyncio.Queue()
self.next_id = 1
async def start(self) -> None:
self.proc = await asyncio.create_subprocess_exec(
self.command,
"app-server",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=self.cwd or os.getcwd(),
env=self.env,
)
self.reader_task = asyncio.create_task(self._reader_loop())
self.stderr_task = asyncio.create_task(self._stderr_loop())
await self.request(
"initialize",
{
"clientInfo": {"name": "cptr", "version": "0"},
"capabilities": {"experimentalApi": True},
},
)
await self.notify("initialized")
async def close(self) -> None:
if self.proc and self.proc.returncode is None:
self.proc.terminate()
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(self.proc.wait(), timeout=3)
if self.proc.returncode is None:
self.proc.kill()
await self.proc.wait()
for task in (self.reader_task, self.stderr_task):
if task:
task.cancel()
with suppress(asyncio.CancelledError):
await task
for future in self.pending.values():
if not future.done():
future.cancel()
self.pending.clear()
async def request(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
request_id = self.next_id
self.next_id += 1
loop = asyncio.get_running_loop()
future: asyncio.Future[dict[str, Any]] = loop.create_future()
self.pending[request_id] = future
await self._send({"id": request_id, "method": method, "params": params})
response = await future
if response.get("error"):
raise RuntimeError(str(response["error"]))
return response
async def notify(self, method: str, params: dict[str, Any] | None = None) -> None:
payload: dict[str, Any] = {"method": method}
if params is not None:
payload["params"] = params
await self._send(payload)
async def _send(self, payload: dict[str, Any]) -> None:
assert self.proc is not None and self.proc.stdin is not None
self.proc.stdin.write((json.dumps(payload) + "\n").encode())
await self.proc.stdin.drain()
async def _reader_loop(self) -> None:
assert self.proc is not None and self.proc.stdout is not None
while True:
line = await self.proc.stdout.readline()
if not line:
break
try:
message = json.loads(line.decode())
except Exception:
continue
if "id" in message and "method" not in message and (
"result" in message or "error" in message
):
future = self.pending.pop(int(message["id"]), None)
if future and not future.done():
future.set_result(message)
else:
await self.events.put(message)
async def _stderr_loop(self) -> None:
assert self.proc is not None and self.proc.stderr is not None
while await self.proc.stderr.readline():
pass
def _messages_to_prompt(messages: list[dict[str, Any]]) -> str:
parts: list[str] = []
for message in messages:
role = message.get("role", "user")
content = message.get("content", "")
if isinstance(content, list):
text = "\n".join(
str(block.get("text", "")) for block in content if isinstance(block, dict)
)
else:
text = str(content or "")
if text:
parts.append(f"[{role}]\n{text}")
return "\n\n".join(parts)
def _approval_policy(value: str) -> str:
return {"ask": "on-request", "auto": "on-failure", "full": "never"}.get(value, "on-failure")
def _chat_approval_mode(chat_params: dict[str, Any]) -> str:
if "tool_approval_mode" in chat_params:
return str(chat_params.get("tool_approval_mode") or "auto")
if "auto_approve_tools" in chat_params:
return "full" if chat_params.get("auto_approve_tools") else "auto"
return "auto"
def _sandbox_for_approval(value: str) -> str:
if value == "ask":
return "read-only"
return "workspace-write"
async def run_codex_agent(
*,
profile: dict[str, Any],
model: str,
workspace: str,
messages: list[dict[str, Any]],
system_prompt: str,
chat_params: dict[str, Any],
resume_state: dict[str, Any] | None,
) -> AsyncIterator[AgentEvent]:
env = os.environ.copy()
if profile.get("home"):
env["CODEX_HOME"] = os.path.expanduser(str(profile["home"]))
client = CodexAppServer(str(profile["command"]), workspace, env)
thread_id: str | None = None
turn_id: str | None = None
try:
await client.start()
approval_mode = _chat_approval_mode(chat_params)
thread_params: dict[str, Any] = {
"cwd": workspace,
"approvalPolicy": _approval_policy(approval_mode),
"sandbox": _sandbox_for_approval(approval_mode),
}
if model != "default":
thread_params["model"] = model
if system_prompt:
thread_params["developerInstructions"] = system_prompt
response = await client.request("thread/start", thread_params)
thread = response.get("result", {}).get("thread", {})
thread_id = thread.get("id") if isinstance(thread, dict) else None
if not thread_id:
yield AgentError("Codex did not return a thread id")
return
prompt = _messages_to_prompt(messages)
turn_response = await client.request(
"turn/start",
{
"threadId": thread_id,
"input": [{"type": "text", "text": prompt}],
},
)
turn = turn_response.get("result", {}).get("turn", {})
turn_id = turn.get("id") if isinstance(turn, dict) else None
while True:
event = await client.events.get()
method = event.get("method")
params = event.get("params") if isinstance(event.get("params"), dict) else {}
event_turn_id = params.get("turnId")
if event_turn_id and turn_id and event_turn_id != turn_id:
continue
if method == "item/agentMessage/delta":
delta = params.get("delta")
if isinstance(delta, str) and delta:
yield AgentTextDelta(delta)
elif method in ("item/reasoning/textDelta", "item/reasoning/summaryTextDelta"):
delta = params.get("delta")
if isinstance(delta, str) and delta:
yield AgentReasoningDelta(delta)
elif method == "turn/completed":
yield AgentDone(
resume_state={
"profile_id": profile["id"],
"thread_id": thread_id,
"turn_id": turn_id,
"workspace": workspace,
"model": model,
}
)
return
elif method == "turn/failed":
detail = params.get("message") or params.get("error") or "Codex turn failed"
yield AgentError(str(detail))
return
elif method == "error":
yield AgentError(str(params or "Codex app-server error"))
return
except asyncio.CancelledError:
if thread_id and turn_id:
with suppress(Exception):
await client.request("turn/interrupt", {"threadId": thread_id, "turnId": turn_id})
raise
except Exception as exc: # noqa: BLE001 - surfaced in the chat.
yield AgentError(str(exc))
finally:
await client.close()
+238
View File
@@ -0,0 +1,238 @@
"""Detection helpers for coding agent profiles."""
from __future__ import annotations
import asyncio
import importlib.util
import os
import re
import shutil
from dataclasses import dataclass, asdict
from typing import Any
from cptr.utils.agents.models import (
default_agent_profiles,
get_raw_agent_profiles,
model_id_for_profile,
normalize_agent_profiles,
)
DETECTION_TTL_SECONDS = 30
CLAUDE_MODELS = [
"claude-fable-5",
"claude-opus-4-8",
"claude-opus-4-7",
"claude-opus-4-6",
"claude-opus-4-5",
"claude-sonnet-4-6",
"claude-haiku-4-5",
]
MIN_CLAUDE_FABLE_5 = (2, 1, 169)
MIN_CLAUDE_OPUS_4_8 = (2, 1, 154)
MIN_CLAUDE_OPUS_4_7 = (2, 1, 111)
@dataclass
class AgentDetection:
status: str
command: str | None = None
version: str | None = None
message: str | None = None
models: list[str] | None = None
def to_dict(self) -> dict[str, Any]:
return asdict(self)
def _resolve_command(command: str) -> str | None:
command = command.strip()
if not command:
return None
expanded = os.path.expanduser(command)
if os.path.isabs(expanded):
return expanded if os.access(expanded, os.X_OK) else None
return shutil.which(command)
async def _run_probe(argv: list[str], timeout: float = 3.0) -> tuple[int, str]:
try:
proc = await asyncio.create_subprocess_exec(
*argv,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
except asyncio.TimeoutError:
return 124, "probe timed out"
except Exception as exc: # noqa: BLE001 - surfaced as detection status.
return 1, str(exc)
text = (stdout or stderr).decode(errors="replace").strip()
return proc.returncode or 0, text
async def detect_profile(profile: dict[str, Any]) -> AgentDetection:
command = _resolve_command(str(profile.get("command") or ""))
if command is None:
return AgentDetection("not_found", None, None, "Command not found")
code, version_text = await _run_probe([command, "--version"])
version = version_text.splitlines()[0] if code == 0 and version_text else None
if profile.get("agent") == "claude_code":
models = _claude_models_for_version(version)
if importlib.util.find_spec("claude_agent_sdk") is None:
return AgentDetection(
"missing_dependency",
command,
version,
"Python package claude-agent-sdk is not installed",
models,
)
return AgentDetection("ready", command, version, None, models)
if profile.get("agent") == "codex":
help_code, help_text = await _run_probe([command, "app-server", "--help"])
if help_code != 0:
return AgentDetection(
"error",
command,
version,
help_text or "codex app-server is unavailable",
)
models = await _probe_codex_models(command, profile)
return AgentDetection("ready", command, version, None, models)
return AgentDetection("error", command, version, "Unknown agent")
def _parse_version_tuple(version: str | None) -> tuple[int, int, int] | None:
if not version:
return None
match = re.search(r"(\d+)\.(\d+)\.(\d+)", version)
if not match:
return None
return tuple(int(part) for part in match.groups())
def _version_at_least(version: tuple[int, int, int] | None, minimum: tuple[int, int, int]) -> bool:
return version is not None and version >= minimum
def _claude_models_for_version(version: str | None) -> list[str]:
parsed = _parse_version_tuple(version)
models = []
for model in CLAUDE_MODELS:
if model == "claude-fable-5" and not _version_at_least(parsed, MIN_CLAUDE_FABLE_5):
continue
if model == "claude-opus-4-8" and not _version_at_least(parsed, MIN_CLAUDE_OPUS_4_8):
continue
if model == "claude-opus-4-7" and not _version_at_least(parsed, MIN_CLAUDE_OPUS_4_7):
continue
models.append(model)
return models
async def _probe_codex_models(command: str, profile: dict[str, Any]) -> list[str] | None:
from cptr.utils.agents.codex import CodexAppServer
env = os.environ.copy()
if profile.get("home"):
env["CODEX_HOME"] = os.path.expanduser(str(profile["home"]))
client = CodexAppServer(command, os.getcwd(), env)
try:
await asyncio.wait_for(client.start(), timeout=5)
models: list[str] = []
cursor: str | None = None
while True:
response = await asyncio.wait_for(
client.request("model/list", {"cursor": cursor} if cursor else {}),
timeout=5,
)
result = response.get("result") if isinstance(response.get("result"), dict) else {}
data = result.get("data") if isinstance(result, dict) else None
if not isinstance(data, list):
break
for item in data:
if isinstance(item, dict) and isinstance(item.get("model"), str):
models.append(item["model"])
next_cursor = result.get("nextCursor") if isinstance(result, dict) else None
cursor = next_cursor if isinstance(next_cursor, str) and next_cursor else None
if not cursor:
break
return models or None
except Exception:
return None
finally:
await client.close()
async def get_agent_status(app_state=None, refresh: bool = False) -> dict[str, Any]:
now = asyncio.get_running_loop().time()
cache = getattr(app_state, "AGENTS", None) if app_state is not None else None
if not refresh and isinstance(cache, dict):
cached_at = cache.get("cached_at")
if isinstance(cached_at, (int, float)) and now - cached_at < DETECTION_TTL_SECONDS:
return cache["payload"]
raw_profiles = await get_raw_agent_profiles()
implicit_defaults = raw_profiles is None
profiles = [] if implicit_defaults else normalize_agent_profiles(raw_profiles)
entries = []
candidates = profiles if not implicit_defaults else default_agent_profiles()
for profile in candidates:
detected = await detect_profile(profile)
if implicit_defaults and detected.status == "not_found":
continue
mode = profile.get("mode", "auto")
available = mode != "disabled" and (mode != "auto" or detected.status == "ready")
models = detected.models or profile.get("models") or ["default"]
effective_profile = dict(profile)
effective_profile["models"] = models
if effective_profile.get("default_model") not in models:
effective_profile["default_model"] = models[0]
entries.append(
{
"id": effective_profile["id"],
"agent": effective_profile["agent"],
"name": effective_profile["name"],
"config": effective_profile,
"detected": detected.to_dict(),
"available": available,
"implicit": implicit_defaults,
"model_ids": [model_id_for_profile(effective_profile, model) for model in models],
}
)
payload = {"profiles": entries}
if app_state is not None:
app_state.AGENTS = {"cached_at": now, "payload": payload}
return payload
def invalidate_agent_detection_cache(app_state) -> None:
if app_state is not None and hasattr(app_state, "AGENTS"):
delattr(app_state, "AGENTS")
async def get_available_agent_model_entries(app_state=None) -> list[dict[str, str]]:
status = await get_agent_status(app_state)
entries: list[dict[str, str]] = []
for profile in status["profiles"]:
if not profile["available"]:
continue
config = profile["config"]
for model in config.get("models") or ["default"]:
model_id = model_id_for_profile(config, model)
entries.append(
{
"id": model_id,
"name": model_id,
"provider": "agent",
"connection_id": f"agent:{config['id']}",
"agent_id": config["agent"],
"profile_id": config["id"],
}
)
return entries
+29
View File
@@ -0,0 +1,29 @@
"""Normalized event types emitted by coding agent adapters."""
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class AgentTextDelta:
text: str
@dataclass
class AgentReasoningDelta:
text: str
@dataclass
class AgentDone:
usage: dict[str, Any] | None = None
resume_state: dict[str, Any] | None = None
@dataclass
class AgentError:
message: str
AgentEvent = AgentTextDelta | AgentReasoningDelta | AgentDone | AgentError
+189
View File
@@ -0,0 +1,189 @@
"""Configuration model helpers for coding agents."""
from __future__ import annotations
import re
from copy import deepcopy
from typing import Any
from fastapi import HTTPException
from cptr.models import Config
CONFIG_KEY_AGENT_PROFILES = "agents.profiles"
DEFAULT_AGENT_PROFILES: list[dict[str, Any]] = [
{
"id": "codex",
"agent": "codex",
"name": "Codex",
"mode": "auto",
"command": "codex",
"home": None,
"models": ["gpt-5.4"],
"default_model": "gpt-5.4",
"approval_mode": "auto",
"sandbox_mode": "workspace-write",
},
{
"id": "claude-code",
"agent": "claude_code",
"name": "Claude Code",
"mode": "auto",
"command": "claude",
"home": None,
"models": ["claude-sonnet-4-6"],
"default_model": "claude-sonnet-4-6",
"permission_mode": "default",
"launch_args": "",
},
]
_PROFILE_ID_RE = re.compile(r"^[a-z][a-z0-9_-]{0,63}$")
_VALID_AGENTS = {"codex", "claude_code"}
_VALID_MODES = {"auto", "enabled", "disabled"}
_VALID_CODEX_APPROVAL = {"ask", "auto", "full"}
_VALID_CODEX_SANDBOX = {"read-only", "workspace-write", "danger-full-access"}
_VALID_CLAUDE_PERMISSION = {"default", "accept_edits", "bypass_permissions"}
def default_agent_profiles() -> list[dict[str, Any]]:
return deepcopy(DEFAULT_AGENT_PROFILES)
def normalize_agent_profile(raw: dict[str, Any]) -> dict[str, Any]:
profile = dict(raw)
profile_id = str(profile.get("id") or "").strip()
if not _PROFILE_ID_RE.fullmatch(profile_id):
raise HTTPException(400, "agent profile id must be a slug up to 64 characters")
agent = str(profile.get("agent") or "").strip()
if agent not in _VALID_AGENTS:
raise HTTPException(400, "agent must be codex or claude_code")
fallback_model = "gpt-5.4" if agent == "codex" else "claude-sonnet-4-6"
mode = str(profile.get("mode") or "auto").strip()
if mode not in _VALID_MODES:
raise HTTPException(400, "agent mode must be auto, enabled, or disabled")
command = str(profile.get("command") or "").strip()
if not command:
command = "codex" if agent == "codex" else "claude"
name = str(profile.get("name") or "").strip() or (
"Codex" if agent == "codex" else "Claude Code"
)
home = profile.get("home")
if isinstance(home, str):
home = home.strip() or None
elif home is not None:
raise HTTPException(400, "agent home must be a string or null")
models = profile.get("models")
if not isinstance(models, list):
models = ["default"]
normalized_models = []
for model in models:
if isinstance(model, str) and model.strip():
model_id = model.strip()
if model_id == "default":
continue
if "/" in model_id:
raise HTTPException(400, "agent model ids cannot contain '/'")
normalized_models.append(model_id)
if not normalized_models:
normalized_models = [fallback_model]
default_model = str(profile.get("default_model") or normalized_models[0]).strip()
if default_model == "default":
default_model = fallback_model
if default_model not in normalized_models:
raise HTTPException(400, "agent default_model must be present in models")
normalized: dict[str, Any] = {
"id": profile_id,
"agent": agent,
"name": name,
"mode": mode,
"command": command,
"home": home,
"models": normalized_models,
"default_model": default_model,
}
if agent == "codex":
approval_mode = str(profile.get("approval_mode") or "auto").strip()
sandbox_mode = str(profile.get("sandbox_mode") or "workspace-write").strip()
if approval_mode not in _VALID_CODEX_APPROVAL:
raise HTTPException(400, "codex approval_mode must be ask, auto, or full")
if sandbox_mode not in _VALID_CODEX_SANDBOX:
raise HTTPException(
400, "codex sandbox_mode must be read-only, workspace-write, or danger-full-access"
)
normalized.update(
{
"approval_mode": approval_mode,
"sandbox_mode": sandbox_mode,
}
)
else:
permission_mode = str(profile.get("permission_mode") or "default").strip()
if permission_mode not in _VALID_CLAUDE_PERMISSION:
raise HTTPException(
400, "claude permission_mode must be default, accept_edits, or bypass_permissions"
)
normalized.update(
{
"permission_mode": permission_mode,
"launch_args": str(profile.get("launch_args") or "").strip(),
}
)
return normalized
def normalize_agent_profiles(raw_profiles: Any) -> list[dict[str, Any]]:
if raw_profiles is None:
raw_profiles = []
if not isinstance(raw_profiles, list):
raise HTTPException(400, "agents.profiles must be a list")
profiles = []
for profile in raw_profiles:
if not isinstance(profile, dict):
raise HTTPException(400, "agent profiles must be objects")
profiles.append(normalize_agent_profile(profile))
seen: set[str] = set()
for profile in profiles:
profile_id = profile["id"]
if profile_id in seen:
raise HTTPException(400, f"duplicate agent profile id: {profile_id}")
seen.add(profile_id)
return profiles
async def get_raw_agent_profiles() -> Any:
return await Config.get(CONFIG_KEY_AGENT_PROFILES)
async def save_agent_profiles(profiles: list[dict[str, Any]]) -> list[dict[str, Any]]:
normalized = normalize_agent_profiles(profiles)
await Config.upsert({CONFIG_KEY_AGENT_PROFILES: normalized})
return normalized
def model_id_for_profile(profile: dict[str, Any], model: str) -> str:
return f"agent:{profile['id']}/{model}"
def parse_agent_model_id(model_id: str) -> tuple[str, str] | None:
if not model_id.startswith("agent:"):
return None
rest = model_id[len("agent:") :]
if "/" not in rest:
return None
profile_id, model = rest.split("/", 1)
if not profile_id or not model:
return None
return profile_id, model
+3 -5
View File
@@ -173,10 +173,9 @@ async def execute_automation(automation, webhook_payload: str | None = None) ->
chats_dir.mkdir(parents=True, exist_ok=True)
(chats_dir / f"{chat.id}.json").write_text("{}")
# Resolve connection for model
from cptr.routers.chat import _resolve_connection
from cptr.utils.model_targets import resolve_model_target
connection, bare_model = await _resolve_connection(model_id)
target = await resolve_model_target(model_id)
# Start the agentic loop (same as interactive chat)
from cptr.utils.chat_task import start_task
@@ -185,9 +184,8 @@ async def execute_automation(automation, webhook_payload: str | None = None) ->
message_id=assistant_msg.id,
chat_id=chat.id,
user_id=automation.user_id,
connection=connection,
workspace=workspace,
model=bare_model,
target=target,
)
# Notify frontend (standard chat event so sidebar updates)
+6 -8
View File
@@ -690,8 +690,7 @@ class BotManager:
async def _dispatch_task(
self, chat_id: str, event: MessageEvent, bot: dict, adapter: BaseAdapter | None,
) -> None:
from cptr.models import Chat, ChatMessage, Config
from cptr.routers.chat import _resolve_connection
from cptr.models import Chat, ChatMessage
from cptr.utils.chat_task import start_task, _task_chat
from cptr.utils.config import now_ms
@@ -727,9 +726,11 @@ class BotManager:
parent_id=parent_id, meta=user_meta, created_at=now_ms(),
)
# Resolve model connection
# Resolve model target
try:
connection, bare_model = await _resolve_connection(bot["model_id"])
from cptr.utils.model_targets import resolve_model_target
target = await resolve_model_target(bot["model_id"])
except Exception:
logger.exception("[bridge] Failed to resolve model %s", bot["model_id"])
if adapter:
@@ -770,9 +771,8 @@ class BotManager:
message_id=assistant_msg.id,
chat_id=chat_id,
user_id=bot["user_id"],
connection=connection,
workspace=bot["workspace"],
model=bare_model,
target=target,
)
logger.info("[bridge] Started task for bot %s, chat %s", bot["id"][:8], chat_id[:8])
@@ -1024,5 +1024,3 @@ def _tool_label(name: str, args: dict) -> str:
return query[:40] if query else name
return name
+147 -12
View File
@@ -30,6 +30,13 @@ from cptr.utils.tools import ALL_TOOLS, execute_tool, get_tool_list, _fn_to_sche
from cptr.utils.chat_export import export_chat_to_file
from cptr.utils.json_parser import extract_json
from cptr.utils.prompt_templates import load_system_prompt as _load_system_prompt
from cptr.utils.agents.events import (
AgentDone,
AgentError,
AgentReasoningDelta,
AgentTextDelta,
)
from cptr.utils.model_targets import AgentModelTarget, ApiModelTarget, ModelTarget
logger = logging.getLogger(__name__)
@@ -55,21 +62,30 @@ def start_task(
message_id: str,
chat_id: str,
user_id: str,
connection: dict,
workspace: str,
model: str,
model: str = "",
connection: dict | None = None,
regeneration_prompt: str | None = None,
output_queue: asyncio.Queue | None = None,
target: ModelTarget | None = None,
):
"""Launch the agentic loop as a background asyncio.Task."""
if target is None:
if connection is None:
raise ValueError("start_task requires either target or connection")
target = ApiModelTarget(
kind="api",
connection=connection,
runtime_model=model,
full_model_id=model,
)
task = asyncio.create_task(
run_chat_task(
message_id,
chat_id,
user_id,
connection,
target,
workspace,
model,
regeneration_prompt,
output_queue,
)
@@ -270,13 +286,13 @@ async def process_pending_chat_inputs(chat_id: str, user_id: str, workspace: str
)
return
# Resolve connection
# Resolve model target
try:
from cptr.routers.chat import _resolve_connection
from cptr.utils.model_targets import resolve_model_target
connection, bare_model = await _resolve_connection(model_id)
target = await resolve_model_target(model_id)
except Exception:
logger.exception("[chat-input] Failed to resolve connection for model %s", model_id)
logger.exception("[chat-input] Failed to resolve model target for %s", model_id)
return
# Create assistant placeholder
@@ -306,9 +322,8 @@ async def process_pending_chat_inputs(chat_id: str, user_id: str, workspace: str
message_id=assistant_msg.id,
chat_id=chat_id,
user_id=user_id,
connection=connection,
workspace=workspace,
model=bare_model,
target=target,
)
logger.info(
"[chat-input] Processed %d pending input message(s) for chat %s",
@@ -1060,9 +1075,8 @@ async def run_chat_task(
message_id: str,
chat_id: str,
user_id: str,
connection: dict,
target: ModelTarget,
workspace: str,
model: str,
regeneration_prompt: str | None = None,
output_queue: asyncio.Queue | None = None,
):
@@ -1171,7 +1185,128 @@ async def run_chat_task(
log("[task %s] db save (%s) result: updated=%s", message_id[:8], save_reason, saved)
return saved
async def save_session(agent_target: AgentModelTarget, resume_state: dict | None):
if not resume_state:
return
chat = await Chat.get_by_id(chat_id)
if not chat:
return
meta = dict(chat.meta or {})
sessions = dict(meta.get("agent_sessions") or {})
sessions[agent_target.profile_id] = {
**resume_state,
"profile_id": agent_target.profile_id,
"agent": agent_target.agent,
"model": agent_target.model,
"workspace": workspace,
"updated_at": now_ms(),
}
meta["agent_sessions"] = sessions
await Chat.update_meta(chat_id, meta, now_ms())
async def _run_agent_target(agent_target: AgentModelTarget):
nonlocal content, text_buffer
from cptr.utils.agents.claude_code import run_claude_code_agent
from cptr.utils.agents.codex import run_codex_agent
chat_obj = await Chat.get_by_id(chat_id)
chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
messages, loaded_summary = await _load_message_history(chat_id, message_id)
memory_message, memory_files = _memory_recall_inputs(messages, regeneration_prompt)
system = await _load_system_prompt(
workspace,
agent_target.full_model_id,
user_id=user_id,
current_message=memory_message,
recent_messages=messages,
mentioned_files=memory_files,
)
if loaded_summary:
system += f"\n\n[CONVERSATION SUMMARY]\n{loaded_summary}"
if regeneration_prompt:
messages.append({"role": "user", "content": regeneration_prompt})
if chat_params.get("plan_mode", False):
messages.append({"role": "user", "content": PLAN_MODE_PROMPT})
system = await _apply_voice_mode_system_prompt(system, chat_params)
resume_state = None
if chat_obj:
sessions = (chat_obj.meta or {}).get("agent_sessions") or {}
if isinstance(sessions, dict):
candidate = sessions.get(agent_target.profile_id)
if isinstance(candidate, dict):
resume_state = candidate
runner = run_codex_agent if agent_target.agent == "codex" else run_claude_code_agent
reasoning_buffer = ""
async for event in runner(
profile=agent_target.config,
model=agent_target.model,
workspace=workspace,
messages=messages,
system_prompt=system,
chat_params=chat_params,
resume_state=resume_state,
):
if isinstance(event, AgentTextDelta):
content += event.text
text_buffer += event.text
await emit(delta=event.text)
_sync_state()
elif isinstance(event, AgentReasoningDelta):
reasoning_buffer += event.text
item = {
"type": "reasoning",
"id": f"reasoning-{message_id}",
"status": "in_progress",
"content": [{"type": "reasoning_text", "text": reasoning_buffer}],
}
_upsert_output_item(output_items, item)
await emit(output=item)
_sync_state()
elif isinstance(event, AgentError):
raise RuntimeError(event.message)
elif isinstance(event, AgentDone):
if reasoning_buffer:
_upsert_output_item(
output_items,
{
"type": "reasoning",
"id": f"reasoning-{message_id}",
"status": "completed",
"content": [{"type": "reasoning_text", "text": reasoning_buffer}],
},
)
flushed_item = _flush_text()
if flushed_item:
await emit(output=flushed_item)
await save_session(agent_target, event.resume_state)
await _save_message(
"agent done",
content=content,
output=output_items,
usage=event.usage,
done=True,
)
_task_state.pop(message_id, None)
await _emit_done()
return
flushed_item = _flush_text()
if flushed_item:
await emit(output=flushed_item)
await _save_message("agent stream ended", content=content, output=output_items, done=True)
_task_state.pop(message_id, None)
await _emit_done()
return
try:
if isinstance(target, AgentModelTarget):
await _run_agent_target(target)
return
connection = target.connection
model = target.runtime_model
provider = connection["provider"]
api_key = decrypt_key(connection.get("api_key", ""), _get_jwt_secret())
base_url = connection.get("base_url") or _default_base_url(provider)
+108
View File
@@ -0,0 +1,108 @@
"""Resolve selected model ids to API connections or agent profiles."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Literal, Union
from fastapi import HTTPException
from cptr.models import Config
from cptr.utils.agents.detection import get_agent_status
from cptr.utils.agents.models import parse_agent_model_id
@dataclass(frozen=True)
class ApiModelTarget:
kind: Literal["api"]
connection: dict[str, Any]
runtime_model: str
full_model_id: str
@dataclass(frozen=True)
class AgentModelTarget:
kind: Literal["agent"]
profile_id: str
agent: Literal["codex", "claude_code"]
model: str
full_model_id: str
config: dict[str, Any]
ModelTarget = Union[ApiModelTarget, AgentModelTarget]
async def resolve_agent_model_target(model_id: str, app_state=None) -> AgentModelTarget:
parsed = parse_agent_model_id(model_id)
if parsed is None:
raise HTTPException(400, f"not an agent model: {model_id}")
profile_id, model = parsed
status = await get_agent_status(app_state)
entry = next((p for p in status["profiles"] if p["id"] == profile_id), None)
if entry is None:
raise HTTPException(400, f"agent profile not found: {profile_id}")
profile = entry["config"]
if model not in (profile.get("models") or []):
raise HTTPException(400, f"model '{model}' is not configured for agent profile {profile_id}")
if not entry["available"]:
detection = entry.get("detected") or {}
raise HTTPException(
400,
f"agent profile {profile_id} is not available: "
f"{detection.get('message') or detection.get('status')}",
)
return AgentModelTarget(
kind="agent",
profile_id=profile["id"],
agent=profile["agent"],
model=model,
full_model_id=model_id,
config=profile,
)
async def resolve_api_model_target(model_id: str, app_state=None) -> ApiModelTarget:
"""Resolve an API-backed model id using the existing connection rules."""
from cptr.routers.chat import _resolve_connection
connection, runtime_model = await _resolve_connection(model_id, app_state)
return ApiModelTarget(
kind="api",
connection=connection,
runtime_model=runtime_model,
full_model_id=model_id,
)
async def resolve_model_target(model_id: str, app_state=None) -> ModelTarget:
if parse_agent_model_id(model_id) is not None:
return await resolve_agent_model_target(model_id, app_state)
return await resolve_api_model_target(model_id, app_state)
async def first_api_model_target(app_state=None) -> ApiModelTarget:
from cptr.routers.chat import _fetch_provider_models
connections = await Config.get("chat.connections") or []
for conn in connections:
if not conn.get("enabled", True):
continue
model_ids = conn.get("data", {}).get("models")
if not model_ids:
model_ids = await _fetch_provider_models(conn)
if model_ids:
prefix = (conn.get("prefix_id") or "").strip()
runtime_model = model_ids[0]
full = f"{prefix}/{runtime_model}" if prefix else runtime_model
return ApiModelTarget(
kind="api",
connection=conn,
runtime_model=runtime_model,
full_model_id=full,
)
raise HTTPException(503, "No API model connections configured.")
+7 -2
View File
@@ -2034,14 +2034,19 @@ async def _run_existing_subagent_chat(
"""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
from cptr.utils.model_targets import ApiModelTarget
await run_chat_task(
message_id=assistant_msg_id,
chat_id=chat_id,
user_id=user_id,
connection=connection,
target=ApiModelTarget(
kind="api",
connection=connection,
runtime_model=model,
full_model_id=model,
),
workspace=workspace,
model=model,
)
result_msg = await ChatMessage.get_by_id(assistant_msg_id)