From 89ff737dfde437045fa6c1aaa8b94c4d5767d6c8 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Thu, 25 Jun 2026 16:53:57 -0400 Subject: [PATCH] refac --- cptr/frontend/src/lib/apis/admin.ts | 63 +++- .../components/Admin/AgentProfileModal.svelte | 192 +++++++++++ .../src/lib/components/Admin/Agents.svelte | 309 ++++++++++++++++++ .../src/lib/components/SettingsModal.svelte | 16 +- cptr/frontend/src/lib/i18n/locales/en.json | 18 + cptr/routers/admin.py | 39 +++ cptr/routers/chat.py | 47 ++- cptr/routers/gateway.py | 94 +++--- cptr/utils/agents/__init__.py | 1 + cptr/utils/agents/claude_code.py | 152 +++++++++ cptr/utils/agents/codex.py | 242 ++++++++++++++ cptr/utils/agents/detection.py | 238 ++++++++++++++ cptr/utils/agents/events.py | 29 ++ cptr/utils/agents/models.py | 189 +++++++++++ cptr/utils/automations.py | 8 +- cptr/utils/bridge.py | 14 +- cptr/utils/chat_task.py | 159 ++++++++- cptr/utils/model_targets.py | 108 ++++++ cptr/utils/tools.py | 9 +- pyproject.toml | 2 + uv.lock | 36 +- 21 files changed, 1875 insertions(+), 90 deletions(-) create mode 100644 cptr/frontend/src/lib/components/Admin/AgentProfileModal.svelte create mode 100644 cptr/frontend/src/lib/components/Admin/Agents.svelte create mode 100644 cptr/utils/agents/__init__.py create mode 100644 cptr/utils/agents/claude_code.py create mode 100644 cptr/utils/agents/codex.py create mode 100644 cptr/utils/agents/detection.py create mode 100644 cptr/utils/agents/events.py create mode 100644 cptr/utils/agents/models.py create mode 100644 cptr/utils/model_targets.py diff --git a/cptr/frontend/src/lib/apis/admin.ts b/cptr/frontend/src/lib/apis/admin.ts index 4b6eec0..c0cc3c9 100644 --- a/cptr/frontend/src/lib/apis/admin.ts +++ b/cptr/frontend/src/lib/apis/admin.ts @@ -58,6 +58,60 @@ export const updateConfig = (config: Record) => method: 'PUT' }); +// ── Agents ───────────────────────────────────────────────── + +export type AgentType = 'codex' | 'claude_code'; +export type AgentMode = 'auto' | 'enabled' | 'disabled'; +export type AgentStatus = 'ready' | 'not_found' | 'missing_dependency' | 'auth_unknown' | 'error'; + +export interface AgentProfile { + id: string; + agent: AgentType; + name: string; + mode: AgentMode; + command: string; + home: string | null; + models: string[]; + default_model: string; + approval_mode?: 'ask' | 'auto' | 'full'; + sandbox_mode?: 'read-only' | 'workspace-write' | 'danger-full-access'; + permission_mode?: 'default' | 'accept_edits' | 'bypass_permissions'; + launch_args?: string; +} + +export interface AgentsResponseProfile { + id: string; + agent: AgentType; + name: string; + config: AgentProfile; + detected: { + status: AgentStatus; + command: string | null; + version: string | null; + message: string | null; + models?: string[] | null; + }; + available: boolean; + implicit: boolean; + model_ids: string[]; +} + +export interface AgentsResponse { + profiles: AgentsResponseProfile[]; +} + +export const getAgents = async (): Promise => + fetchJSON('/api/admin/agents'); + +export const updateAgents = (profiles: AgentProfile[]): Promise => + fetchJSON('/api/admin/agents', { + ...jsonBody({ profiles }), + method: 'PUT' + }); + +export const refreshAgents = async (): Promise => + fetchJSON('/api/admin/agents/refresh', { method: 'POST' }); + // ── Connections ───────────────────────────────────────────── export interface Connection { @@ -118,7 +172,14 @@ export interface ModelConfigEntry { export interface ModelConfigResponse { config: Record; - models: { id: string; name: string; provider: string; connection_id: string }[]; + models: { + id: string; + name: string; + provider: string; + connection_id: string; + agent_id?: string; + profile_id?: string; + }[]; } export const getModelConfig = async (): Promise => diff --git a/cptr/frontend/src/lib/components/Admin/AgentProfileModal.svelte b/cptr/frontend/src/lib/components/Admin/AgentProfileModal.svelte new file mode 100644 index 0000000..3a4e6ba --- /dev/null +++ b/cptr/frontend/src/lib/components/Admin/AgentProfileModal.svelte @@ -0,0 +1,192 @@ + + + + +
{ + if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) onsave(normalizeDraft()); + }} + > +
+

+ {isNew ? $t('admin.agentsAddProfile') : draft.name} +

+ +
+ +
+
+ + +
+
+ + +
+
+ + + + + + + + + (draft.home = e.currentTarget.value || null)} + class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono" + /> + + {#if draft.agent === 'claude_code'} + + + {/if} + +
+
+ {#if !isNew} + + {/if} +
+ +
+
+
diff --git a/cptr/frontend/src/lib/components/Admin/Agents.svelte b/cptr/frontend/src/lib/components/Admin/Agents.svelte new file mode 100644 index 0000000..be98dbf --- /dev/null +++ b/cptr/frontend/src/lib/components/Admin/Agents.svelte @@ -0,0 +1,309 @@ + + +
+
+

{$t('admin.agents')}

+
+ + +
+
+ + {#if loading} +
+ +
+ {:else} +
+ {#each profiles as profile, index (profile.id)} + + {/each} +
+ + {#if profiles.length === 0} +

No agent profiles

+ {/if} + +
+ + {profiles.length} profile{profiles.length === 1 ? '' : 's'} + + +
+ {/if} +
+ +{#if modal} + (modal = null)} + onsave={saveProfile} + ondelete={deleteProfile} + /> +{/if} diff --git a/cptr/frontend/src/lib/components/SettingsModal.svelte b/cptr/frontend/src/lib/components/SettingsModal.svelte index 86939d8..8d6933a 100644 --- a/cptr/frontend/src/lib/components/SettingsModal.svelte +++ b/cptr/frontend/src/lib/components/SettingsModal.svelte @@ -10,6 +10,7 @@ import About from './Settings/About.svelte'; import Users from './Admin/Users.svelte'; import Connections from './Admin/Connections.svelte'; + import Agents from './Admin/Agents.svelte'; import Models from './Admin/Models.svelte'; import Messaging from './Admin/Messaging.svelte'; import Gateway from './Admin/Gateway.svelte'; @@ -30,6 +31,7 @@ | 'about' | 'users' | 'connections' + | 'agents' | 'models' | 'messaging' | 'gateway' @@ -56,6 +58,7 @@ const adminTabIds: Tab[] = [ 'users', 'connections', + 'agents', 'models', 'messaging', 'gateway', @@ -81,6 +84,7 @@ const adminTabs: { id: Tab; label: string; icon: string }[] = $derived([ { id: 'users', label: $t('admin.users'), icon: 'user' }, { id: 'connections', label: $t('admin.connections'), icon: 'plug' }, + { id: 'agents', label: $t('admin.agents'), icon: 'terminal' }, { id: 'models', label: $t('admin.models'), icon: 'cube' }, { id: 'messaging', label: $t('admin.messaging'), icon: 'chat-bubble' }, { id: 'gateway', label: $t('admin.gateway.tab'), icon: 'gateway' }, @@ -168,11 +172,11 @@
- {#if activeTab === 'general'} - - {:else if activeTab === 'memory'} - - {:else if activeTab === 'pwa' && showPwaSettings} + {#if activeTab === 'general'} + + {:else if activeTab === 'memory'} + + {:else if activeTab === 'pwa' && showPwaSettings} {:else if activeTab === 'keyboard'} @@ -184,6 +188,8 @@ {:else if activeTab === 'connections'} + {:else if activeTab === 'agents'} + {:else if activeTab === 'models'} {:else if activeTab === 'messaging'} diff --git a/cptr/frontend/src/lib/i18n/locales/en.json b/cptr/frontend/src/lib/i18n/locales/en.json index ff8815b..18855f8 100644 --- a/cptr/frontend/src/lib/i18n/locales/en.json +++ b/cptr/frontend/src/lib/i18n/locales/en.json @@ -235,6 +235,24 @@ "admin.minCharsPassword": "Min 6 characters", "admin.connections": "Connections", + "admin.agents": "Agents", + "admin.agentsRefresh": "Refresh", + "admin.agentsAddProfile": "Add profile", + "admin.agentsDeleteProfile": "Delete", + "admin.agentsProfileName": "Name", + "admin.agentsProfileId": "Profile ID", + "admin.agentsType": "Agent", + "admin.agentsCommand": "Command", + "admin.agentsHome": "Home path", + "admin.agentsApprovalMode": "Approval mode", + "admin.agentsSandboxMode": "Sandbox", + "admin.agentsPermissionMode": "Permission mode", + "admin.agentsLaunchArgs": "Launch arguments", + "admin.agentsStatusReady": "Ready", + "admin.agentsStatusNotFound": "Not found", + "admin.agentsStatusMissingDependency": "Missing dependency", + "admin.agentsStatusAuthUnknown": "Auth unknown", + "admin.agentsStatusError": "Error", "connections.loadError": "Failed to load connections", "connections.fieldsRequired": "Base URL and API key required", diff --git a/cptr/routers/admin.py b/cptr/routers/admin.py index 0b093a7..c84c55c 100644 --- a/cptr/routers/admin.py +++ b/cptr/routers/admin.py @@ -11,6 +11,8 @@ from cptr.routers.chat import invalidate_model_cache from cptr.models import User, Auth, Config from cptr.utils.config import AuthResult, _get_jwt_secret, check_access, hash_password, now_ms from cptr.utils.crypto import decrypt_key, encrypt_key, mask_key +from cptr.utils.agents.detection import get_agent_status, invalidate_agent_detection_cache +from cptr.utils.agents.models import save_agent_profiles router = APIRouter(prefix="/api/admin", tags=["admin"]) @@ -154,6 +156,39 @@ async def put_config(body: ConfigUpdateRequest, request: Request): return {"ok": True} +# ── Agents ────────────────────────────────────────────────── + + +class AgentsUpdateRequest(BaseModel): + profiles: list[dict] + + +@router.get("/agents") +async def get_agents(request: Request): + """Get configured agent profiles plus live detection status.""" + require_admin(request) + return await get_agent_status(request.app.state) + + +@router.put("/agents") +async def update_agents(body: AgentsUpdateRequest, request: Request): + """Replace configured agent profiles.""" + require_admin(request) + await save_agent_profiles(body.profiles) + invalidate_agent_detection_cache(request.app.state) + invalidate_model_cache(request.app.state) + return await get_agent_status(request.app.state, refresh=True) + + +@router.post("/agents/refresh") +async def refresh_agents(request: Request): + """Refresh agent detection status.""" + require_admin(request) + invalidate_agent_detection_cache(request.app.state) + invalidate_model_cache(request.app.state) + return await get_agent_status(request.app.state, refresh=True) + + # ── Connections ────────────────────────────────────────────── @@ -408,6 +443,10 @@ async def _build_model_config(request: Request): } ) + from cptr.utils.agents.detection import get_available_agent_model_entries + + models.extend(await get_available_agent_model_entries(request.app.state)) + return {"config": config, "models": models} diff --git a/cptr/routers/chat.py b/cptr/routers/chat.py index 0832834..e0af4cf 100644 --- a/cptr/routers/chat.py +++ b/cptr/routers/chat.py @@ -172,6 +172,10 @@ async def get_models(request: Request): } ) + from cptr.utils.agents.detection import get_available_agent_model_entries + + models.extend(await get_available_agent_model_entries(request.app.state)) + default_model = await Config.get("chat.default_model") # Filter out inactive models @@ -457,8 +461,10 @@ 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) - # Resolve connection for model - connection, bare_model = await _resolve_connection(body.model_id, request.app.state) + # Resolve selected model to either an API connection or an agent profile. + from cptr.utils.model_targets import resolve_model_target + + target = await resolve_model_target(body.model_id, request.app.state) from cptr.utils.chat_task import ( get_pending_input_lock, @@ -532,10 +538,9 @@ async def send_message(body: SendMessageRequest, request: Request): message_id=assistant_msg.id, chat_id=chat.id, user_id=user_id, - connection=connection, workspace=body.workspace, - model=bare_model, regeneration_prompt=body.regeneration_prompt, + target=target, ) # Return the created messages so the frontend can append them @@ -571,7 +576,11 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request): usage = await _get_chat_context_usage(chat, body.model_id) return {"ok": True, "compacted": False, "reason": "too_short", "context_usage": usage} - connection, bare_model = await _resolve_connection(body.model_id, request.app.state) + from cptr.utils.model_targets import ApiModelTarget, first_api_model_target, resolve_model_target + + target = await resolve_model_target(body.model_id, request.app.state) + if not isinstance(target, ApiModelTarget): + target = await first_api_model_target(request.app.state) from cptr.utils.chat_task import _load_message_history from cptr.utils.summarize import summarize_messages @@ -581,6 +590,8 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request): usage = await _get_chat_context_usage(chat, body.model_id) return {"ok": True, "compacted": False, "reason": "too_short", "context_usage": usage} + connection = target.connection + runtime_model = target.runtime_model provider = connection["provider"] api_key = decrypt_key(connection.get("api_key", ""), _get_jwt_secret()) from cptr.utils.chat_task import _default_base_url @@ -594,7 +605,7 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request): provider, base_url, api_key, - bare_model, + runtime_model, api_type=api_type, ) await ChatMessage.update(message_id, chat_summary=summary) @@ -692,8 +703,10 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ await ChatMessage.update(message_id, output=output, done=False) - # Resolve connection and continue - connection, bare_model = await _resolve_connection(model_id, request.app.state) + # Resolve model target and continue + from cptr.utils.model_targets import resolve_model_target + + target = await resolve_model_target(model_id, request.app.state) workspace = chat.meta.get("workspace", "") if chat.meta else "" from cptr.utils.chat_task import start_task @@ -702,9 +715,8 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ message_id=message_id, chat_id=chat_id, user_id=user_id, - connection=connection, workspace=workspace, - model=bare_model, + target=target, ) else: call["status"] = "rejected" @@ -872,11 +884,13 @@ async def queue_send_now(chat_id: str, message_id: str, request: Request): meta.pop("queued", None) await ChatMessage.update(message_id, meta=meta or None) - # Resolve connection and start task + # Resolve model target and start task model_id = msg.model or (chat.meta or {}).get("last_model", "") if not model_id: model_id = next((m.model for m in reversed(all_msgs) if m.model), "") - connection, bare_model = await _resolve_connection(model_id, request.app.state) + from cptr.utils.model_targets import resolve_model_target + + target = await resolve_model_target(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: @@ -898,9 +912,8 @@ async def queue_send_now(chat_id: str, message_id: str, request: Request): message_id=assistant_msg.id, chat_id=chat_id, user_id=user_id, - connection=connection, workspace=workspace, - model=bare_model, + target=target, ) return {"ok": True, "chat_id": chat_id, "message_id": assistant_msg.id} @@ -925,7 +938,7 @@ async def queue_delete(chat_id: str, message_id: str, request: Request): async def _resolve_connection(model_id: str, app_state=None) -> tuple[dict, str]: """Find connection for model. - 'openrouter/gpt-4o' → connection with prefix_id='openrouter', bare model='gpt-4o' + 'openrouter/gpt-4o' → connection with prefix_id='openrouter', runtime model='gpt-4o' 'claude-sonnet-4-20250514' → scan all connections for match Raises 400 if not found. """ @@ -935,10 +948,10 @@ async def _resolve_connection(model_id: str, app_state=None) -> tuple[dict, str] # Try prefix match first if "/" in model_id: - prefix, bare = model_id.split("/", 1) + prefix, runtime_model = model_id.split("/", 1) for conn in connections: if (conn.get("prefix_id") or "").strip() == prefix: - return conn, bare + return conn, runtime_model # Scan all connections using cache for conn in connections: diff --git a/cptr/routers/gateway.py b/cptr/routers/gateway.py index b05958a..ea92f5e 100644 --- a/cptr/routers/gateway.py +++ b/cptr/routers/gateway.py @@ -163,14 +163,12 @@ async def create_chat_completion(request: Request, body: ChatCompletionRequest): # 1. Resolve model → workspace path workspace = await _resolve_workspace(user_id, body.model) - # 2. Resolve the underlying LLM connection for this workspace - connection, bare_model, model_id = await _resolve_model(workspace) + # 2. Resolve the selected model target for this workspace. + target, model_id = await _resolve_model(workspace, request.app.state) # Intercept OWUI utility tasks (follow-ups, title gen, tags gen). # These should go directly to the LLM, not through the agentic loop. - utility_result = await _intercept_task( - request, body, connection, bare_model, model_id - ) + utility_result = await _intercept_task(request, body, workspace, model_id) if utility_result is not None: return utility_result @@ -203,10 +201,9 @@ async def create_chat_completion(request: Request, body: ChatCompletionRequest): message_id=assistant_msg.id, chat_id=chat_id, user_id=user_id, - connection=connection, workspace=workspace, - model=bare_model, output_queue=output_queue, + target=target, ) # 6. Stream SSE response @@ -467,8 +464,7 @@ _UTILITY_PATTERNS = [ async def _intercept_task( request: Request, body: ChatCompletionRequest, - connection: dict, - bare_model: str, + workspace: str, model_id: str, ) -> dict | None: """Detect OWUI utility tasks and proxy them directly to the LLM. @@ -484,7 +480,10 @@ async def _intercept_task( task_header = request.headers.get(OWUI_TASK_HEADER, "").strip() if task_header: logger.info("[gateway] Detected utility task via header: %s", task_header) - return await _proxy_to_llm(body, connection, bare_model) + utility_target = await _resolve_utility_model(workspace, request.app.state) + return await _proxy_to_llm( + body, utility_target.connection, utility_target.runtime_model + ) # 2. Message content pattern matching (fallback) if not body.messages: @@ -500,13 +499,16 @@ async def _intercept_task( return None logger.info("[gateway] Detected utility task via content matching") - return await _proxy_to_llm(body, connection, bare_model) + utility_target = await _resolve_utility_model(workspace, request.app.state) + return await _proxy_to_llm( + body, utility_target.connection, utility_target.runtime_model + ) async def _proxy_to_llm( body: ChatCompletionRequest, connection: dict, - bare_model: str, + runtime_model: str, ) -> dict: """Proxy a utility task directly to the underlying LLM.""" from cptr.utils.ai import chat_completion @@ -522,7 +524,7 @@ async def _proxy_to_llm( provider=provider, base_url=base_url, api_key=api_key, - model=bare_model, + model=runtime_model, messages=body.messages, max_tokens=200, ) @@ -582,8 +584,8 @@ async def _resolve_workspace(user_id: str, model_id: str) -> str: # ── Model connection resolution ────────────────────────────── -async def _resolve_model(workspace: str) -> tuple[dict, str, str]: - """Find a model connection to use for the agentic loop. +async def _resolve_model(workspace: str, app_state=None): + """Find a model target to use for the agentic loop. Priority: 1. Gateway model selected in Settings > Gateway @@ -591,15 +593,15 @@ async def _resolve_model(workspace: str) -> tuple[dict, str, str]: 3. Default model from Settings > Models (chat.default_model) 4. First enabled connection's first model (with auto-discovery) - Returns (connection_dict, bare_model, full_model_id). + Returns (target, full_model_id). """ - from cptr.routers.chat import _resolve_connection + from cptr.utils.model_targets import first_api_model_target, resolve_model_target gateway_model = await Config.get("gateway.model") if isinstance(gateway_model, str) and gateway_model.strip(): try: - connection, bare = await _resolve_connection(gateway_model.strip()) - return connection, bare, gateway_model.strip() + target = await resolve_model_target(gateway_model.strip(), app_state) + return target, gateway_model.strip() except Exception: logger.warning( "[openai-compat] Gateway model '%s' not found, falling back", @@ -614,8 +616,8 @@ async def _resolve_model(workspace: str) -> tuple[dict, str, str]: if model_override: try: - connection, bare = await _resolve_connection(model_override) - return connection, bare, model_override + target = await resolve_model_target(model_override, app_state) + return target, model_override except Exception: logger.warning( "[openai-compat] Workspace model override '%s' not found, falling back", @@ -626,32 +628,46 @@ async def _resolve_model(workspace: str) -> tuple[dict, str, str]: default_model = await Config.get("chat.default_model") if isinstance(default_model, str) and default_model.strip(): try: - connection, bare = await _resolve_connection(default_model.strip()) - return connection, bare, default_model.strip() + target = await resolve_model_target(default_model.strip(), app_state) + return target, default_model.strip() except Exception: logger.warning( "[openai-compat] Default model '%s' not found, falling back", default_model, ) - # Fall back to the first enabled connection + its first model - from cptr.routers.chat import _fetch_provider_models + target = await first_api_model_target(app_state) + return target, target.full_model_id - 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: - # Attempt auto-discovery if models aren't pre-stored - model_ids = await _fetch_provider_models(conn) - if model_ids: - prefix = (conn.get("prefix_id") or "").strip() - bare = model_ids[0] - full = f"{prefix}/{bare}" if prefix else bare - return conn, bare, full - raise HTTPException(503, "No model connections configured. Add a connection in cptr settings.") +async def _resolve_utility_model(workspace: str, app_state=None): + """Resolve an API model for gateway utility tasks.""" + from cptr.utils.model_targets import ApiModelTarget, first_api_model_target, resolve_model_target + + candidates: list[str] = [] + gateway_model = await Config.get("gateway.model") + if isinstance(gateway_model, str) and gateway_model.strip(): + candidates.append(gateway_model.strip()) + + model_file = Path(workspace) / ".cptr" / "model" + if model_file.is_file(): + override = model_file.read_text().strip() + if override: + candidates.append(override) + + default_model = await Config.get("chat.default_model") + if isinstance(default_model, str) and default_model.strip(): + candidates.append(default_model.strip()) + + for model_id in candidates: + try: + target = await resolve_model_target(model_id, app_state) + if isinstance(target, ApiModelTarget): + return target + except Exception: + logger.warning("[openai-compat] Utility model '%s' not available", model_id) + + return await first_api_model_target(app_state) # ── Session mapping ────────────────────────────────────────── diff --git a/cptr/utils/agents/__init__.py b/cptr/utils/agents/__init__.py new file mode 100644 index 0000000..60654d6 --- /dev/null +++ b/cptr/utils/agents/__init__.py @@ -0,0 +1 @@ +"""Coding agent support for Codex and Claude Code.""" diff --git a/cptr/utils/agents/claude_code.py b/cptr/utils/agents/claude_code.py new file mode 100644 index 0000000..cab36f3 --- /dev/null +++ b/cptr/utils/agents/claude_code.py @@ -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)) diff --git a/cptr/utils/agents/codex.py b/cptr/utils/agents/codex.py new file mode 100644 index 0000000..d9944ee --- /dev/null +++ b/cptr/utils/agents/codex.py @@ -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() diff --git a/cptr/utils/agents/detection.py b/cptr/utils/agents/detection.py new file mode 100644 index 0000000..cebff8a --- /dev/null +++ b/cptr/utils/agents/detection.py @@ -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 diff --git a/cptr/utils/agents/events.py b/cptr/utils/agents/events.py new file mode 100644 index 0000000..14996cc --- /dev/null +++ b/cptr/utils/agents/events.py @@ -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 diff --git a/cptr/utils/agents/models.py b/cptr/utils/agents/models.py new file mode 100644 index 0000000..d7eea22 --- /dev/null +++ b/cptr/utils/agents/models.py @@ -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 diff --git a/cptr/utils/automations.py b/cptr/utils/automations.py index 979e097..a5a39ef 100644 --- a/cptr/utils/automations.py +++ b/cptr/utils/automations.py @@ -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) diff --git a/cptr/utils/bridge.py b/cptr/utils/bridge.py index a8834cc..1a9f098 100644 --- a/cptr/utils/bridge.py +++ b/cptr/utils/bridge.py @@ -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 - - diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index fc61f6a..0c927a0 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -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) diff --git a/cptr/utils/model_targets.py b/cptr/utils/model_targets.py new file mode 100644 index 0000000..0e87b07 --- /dev/null +++ b/cptr/utils/model_targets.py @@ -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.") diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index a0e1f8f..f20d8df 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -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) diff --git a/pyproject.toml b/pyproject.toml index 915c38e..1e61033 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,12 +27,14 @@ dependencies = [ pam = ["python-pam>=2.0"] mcp = ["mcp>=1.8"] docs = ["pypdf>=4.0", "python-docx>=1.0", "openpyxl>=3.1"] +agents = ["claude-agent-sdk>=0.1.62"] all = [ "mcp>=1.8", "pypdf>=4.0", "python-docx>=1.0", "openpyxl>=3.1", "python-pam>=2.0", + "claude-agent-sdk>=0.1.62", ] [dependency-groups] diff --git a/uv.lock b/uv.lock index 7cb2e84..333ba2a 100644 --- a/uv.lock +++ b/uv.lock @@ -242,6 +242,25 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ae/3a/dbeec9d1ee0844c679f6bb5d6ad4e9f198b1224f4e7a32825f47f6192b0c/cffi-2.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0a1527a803f0a659de1af2e1fd700213caba79377e27e4693648c2923da066f9", size = 184195 }, ] +[[package]] +name = "claude-agent-sdk" +version = "0.2.110" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "mcp" }, + { name = "sniffio" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bb/98/8fdab35ed9e1a36bc7afab4d390cc5002094a4950996c079da9aa4541cc4/claude_agent_sdk-0.2.110.tar.gz", hash = "sha256:538b548bac07a22f65686abab063a902ac76ba35989d0f073c942f96248e9fa3", size = 255632 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/aa/93/29d4fdaa13e69034faf8d3503df915b07c820e2c08e3d6a7515149cde5bb/claude_agent_sdk-0.2.110-py3-none-macosx_11_0_arm64.whl", hash = "sha256:fed0e0f4804d9f9cff80ab7d1b44142ebd1046cdd29ca74caef4c92c35fff8d8", size = 64924533 }, + { url = "https://files.pythonhosted.org/packages/aa/03/b40bb673cd93cdc3928262c1be75fde34a7bed4bf2c2c20e04218e2005ea/claude_agent_sdk-0.2.110-py3-none-macosx_11_0_x86_64.whl", hash = "sha256:62b23869d46cef6f6ff1d00ceaa5e846e2f1d297478421c835efb8fe99369d4f", size = 69704449 }, + { url = "https://files.pythonhosted.org/packages/f9/18/ab67cb5ce641333385bed55ed8e9665c00f7d30d1f6ab12f8463ddb7695f/claude_agent_sdk-0.2.110-py3-none-manylinux_2_17_aarch64.whl", hash = "sha256:324e49553c6303d6b267217dc2912652b97af2bc96503efd12095ae915b46b83", size = 74879555 }, + { url = "https://files.pythonhosted.org/packages/91/88/3627d7d14310cfec66977551263e219365244a906fc7ca1209fb0c3a6cec/claude_agent_sdk-0.2.110-py3-none-manylinux_2_17_x86_64.whl", hash = "sha256:56371dd7a2c66c0bd497dc0b3cab4193a228b196f600676393d69c0ecee37cfb", size = 75924237 }, + { url = "https://files.pythonhosted.org/packages/49/79/c9066c5c387d42c19a4b675ec1ff5219f8920cfda8ff8b527119fd69b774/claude_agent_sdk-0.2.110-py3-none-win_amd64.whl", hash = "sha256:4235d4de6d685a189c12612095ab192b759280ede1f3aed0c3e784d52c3555f9", size = 75448209 }, +] + [[package]] name = "click" version = "8.1.8" @@ -265,7 +284,7 @@ wheels = [ [[package]] name = "cptr" -version = "0.5.2" +version = "0.6.2" source = { editable = "." } dependencies = [ { name = "aiosqlite" }, @@ -286,7 +305,11 @@ dependencies = [ ] [package.optional-dependencies] +agents = [ + { name = "claude-agent-sdk" }, +] all = [ + { name = "claude-agent-sdk" }, { name = "mcp" }, { name = "openpyxl" }, { name = "pypdf" }, @@ -315,6 +338,8 @@ requires-dist = [ { name = "aiosqlite", specifier = ">=0.20" }, { name = "alembic", specifier = ">=1.13" }, { name = "bcrypt", specifier = ">=4.0" }, + { name = "claude-agent-sdk", marker = "extra == 'agents'", specifier = ">=0.1.62" }, + { name = "claude-agent-sdk", marker = "extra == 'all'", specifier = ">=0.1.62" }, { name = "click", specifier = ">=8.1" }, { name = "cryptography", specifier = ">=42.0" }, { name = "fastapi", extras = ["standard"], specifier = ">=0.128.8" }, @@ -2035,6 +2060,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050 }, ] +[[package]] +name = "sniffio" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a2/87/a6771e1546d97e7e041b6ae58d80074f81b7d5121207425c964ddf5cfdbd/sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc", size = 20372 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235 }, +] + [[package]] name = "sqlalchemy" version = "2.0.50"