From b6c46ab00a210a86d7b77d563874877470b03fff Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sat, 31 Oct 2026 08:06:23 +0900 Subject: [PATCH] refac --- README.md | 8 +- .../chat/ConsecutiveActivityGroup.svelte | 95 ++++++++++++++++--- .../chat/ToolCallCollapsible.svelte | 65 ++++++++++++- cptr/utils/chat_task.py | 89 ++++++++++++++--- cptr/utils/openapi.py | 22 ++++- 5 files changed, 245 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 8f7c750..b5730e8 100644 --- a/README.md +++ b/README.md @@ -29,12 +29,16 @@ MCP tool servers require the optional MCP dependencies: `pip install 'cptr[mcp]' To install every optional feature group, use `pip install 'cptr[all]'`. The Docker image includes all optional feature groups. -Or with [uv](https://docs.astral.sh/uv/): `uvx cptr@latest run` - On Windows, if opening a terminal reports a missing `VCRUNTIME140.dll` or Universal CRT DLL, install Microsoft's [Visual C++ Redistributable](https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist) and restart `cptr`. Opens in your browser at `http://localhost:8000`. +### Run with uv + +```bash +uvx cptr@latest run +``` + ### Access from your phone Same Wi-Fi? Bind to all interfaces: diff --git a/cptr/frontend/src/lib/components/chat/ConsecutiveActivityGroup.svelte b/cptr/frontend/src/lib/components/chat/ConsecutiveActivityGroup.svelte index 4f0053f..11ebdfc 100644 --- a/cptr/frontend/src/lib/components/chat/ConsecutiveActivityGroup.svelte +++ b/cptr/frontend/src/lib/components/chat/ConsecutiveActivityGroup.svelte @@ -32,6 +32,49 @@ onapprove }: Props = $props(); + function isToolResultError(value: unknown): boolean { + if (typeof value === 'string') { + const text = value.trim().toLowerCase(); + if ( + text.startsWith('error:') || + text.startsWith('exception:') || + text.startsWith('traceback') || + text.startsWith('http error!') + ) { + return true; + } + } + + let parsed = value; + while (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch { + break; + } + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return false; + + const result = parsed as Record; + const error = result.error; + if ( + (typeof error === 'string' && error.trim().length > 0) || + (typeof error === 'object' && error !== null) + ) { + return true; + } + + const status = typeof result.status === 'string' ? result.status.trim().toLowerCase() : ''; + if (status === 'error' || status === 'failed') return true; + + const message = result.message; + return ( + (result.success === false || result.ok === false) && + ((typeof message === 'string' && message.trim().length > 0) || + (typeof message === 'object' && message !== null)) + ); + } + let expanded = $state($expandToolDetails); $effect(() => { expanded = $expandToolDetails; @@ -41,14 +84,19 @@ reasoning.some((ri: any) => ri.status === 'in_progress' || ri.status === 'running') ); const hasPending = $derived( - (!done && calls.some((c: any) => c.status !== 'completed' && c.status !== 'rejected')) || + (!done && calls.some((c: any) => !['completed', 'failed', 'rejected'].includes(c.status))) || hasReasoningPending ); const allDone = $derived( - (calls.length === 0 || calls.every((c: any) => c.status === 'completed')) && + (calls.length === 0 || calls.every((c: any) => ['completed', 'failed'].includes(c.status))) && !hasReasoningPending ); const hasRejected = $derived(calls.some((c: any) => c.status === 'rejected')); + const hasError = $derived( + calls.some( + (c: any) => c.status === 'failed' || isToolResultError(outputs.get(c.call_id)?.output ?? '') + ) + ); const pendingCalls = $derived(calls.filter((c: any) => c.status === 'pending')); const hasPendingApproval = $derived(pendingCalls.length > 0); const isThoughtOnly = $derived(calls.length === 0); @@ -132,6 +180,36 @@ /> + {:else if hasRejected} +
+ + + +
+ {:else if hasError} +
+ + + +
{:else if allDone}
- {:else if hasRejected} -
- - - -
{:else}
; + const error = result.error; + if ( + (typeof error === 'string' && error.trim().length > 0) || + (typeof error === 'object' && error !== null) + ) { + return true; + } + + const status = typeof result.status === 'string' ? result.status.trim().toLowerCase() : ''; + if (status === 'error' || status === 'failed') return true; + + const message = result.message; + return ( + (result.success === false || result.ok === false) && + ((typeof message === 'string' && message.trim().length > 0) || + (typeof message === 'object' && message !== null)) + ); + } + let expanded = $state($expandToolDetails || item.name === 'ask_user'); $effect(() => { expanded = $expandToolDetails || item.name === 'ask_user'; @@ -27,7 +70,10 @@ const isExecuting = $derived( item.status === 'running' || item.status === 'in_progress' || (!item.status && !done) ); - const isDone = $derived(item.status === 'completed'); + const isError = $derived( + item.status === 'failed' || isToolResultError(pairedOutput?.output ?? '') + ); + const isDone = $derived(item.status === 'completed' || isError); const isRejected = $derived(item.status === 'rejected'); const isPending = $derived(item.status === 'pending'); const isAskUser = $derived(toolName === 'ask_user'); @@ -126,6 +172,23 @@
+ {:else if isError} +
+ + + +
{:else if isDone}
bool: + if isinstance(value, str): + text = value.strip().lower() + if ( + text.startswith("error:") + or text.startswith("exception:") + or text.startswith("traceback") + or text.startswith("http error!") + ): + return True + + parsed = value + while isinstance(parsed, str): + try: + parsed = json.loads(parsed) + except (json.JSONDecodeError, TypeError, ValueError): + break + + if not isinstance(parsed, dict): + return False + + error = parsed.get("error") + if isinstance(error, str): + has_error = bool(error.strip()) + else: + has_error = isinstance(error, (dict, list)) and bool(error) + if has_error: + return True + + status = parsed.get("status") + if isinstance(status, str) and status.strip().lower() in {"error", "failed"}: + return True + + if parsed.get("success") is False or parsed.get("ok") is False: + message = parsed.get("message") + return has_error or ( + bool(message.strip()) + if isinstance(message, str) + else isinstance(message, (dict, list)) and bool(message) + ) + + return False + + ASK_USER_NAME = "ask_user" DEFAULT_AUTO_RESOLUTION_MS = 120_000 ASK_USER_SCHEMA = { @@ -927,7 +972,11 @@ def _output_items_to_messages( ): continue pending_reasoning_items.append(item) - elif itype == "function_call" and item.get("status") in {"completed", "rejected"}: + elif itype == "function_call" and item.get("status") in { + "completed", + "failed", + "rejected", + }: call_id = item.get("call_id") if not call_id or call_id in native_agent_call_ids: continue @@ -2002,12 +2051,21 @@ async def run_chat_task( if item.get("status") in {"completed", "rejected", "failed"}: continue call_id = item.get("call_id") - if call_id and any( - result.get("type") == "function_call_output" - and result.get("call_id") == call_id - for result in output_items - ): - item["status"] = "completed" + existing_result = next( + ( + result + for result in output_items + if result.get("type") == "function_call_output" + and result.get("call_id") == call_id + ), + None, + ) + if call_id and existing_result: + item["status"] = existing_result.get("status") or ( + "failed" + if _is_tool_result_error(existing_result.get("output", "")) + else "completed" + ) continue name = item.get("name", "") @@ -2090,9 +2148,10 @@ async def run_chat_task( "type": "function_call_output", "call_id": item["call_id"], "output": result, + "status": "failed" if _is_tool_result_error(result) else "completed", } output_items.append(result_item) - item["status"] = "completed" + item["status"] = result_item["status"] await emit(output=item) await emit(output=result_item) _sync_state() @@ -2648,9 +2707,10 @@ async def run_chat_task( "type": "function_call_output", "call_id": tc["call_id"], "output": result, + "status": "failed" if _is_tool_result_error(result) else "completed", } output_items.append(result_item) - item["status"] = "completed" + item["status"] = result_item["status"] await emit(output=item) await emit(output=result_item) _sync_state() @@ -2704,9 +2764,12 @@ async def run_chat_task( "type": "function_call_output", "call_id": tc["call_id"], "output": result, + "status": "failed" + if _is_tool_result_error(result) + else "completed", } output_items.append(result_item) - item["status"] = "completed" + item["status"] = result_item["status"] await emit(output=item) await emit(output=result_item) _sync_state() @@ -2716,7 +2779,11 @@ async def run_chat_task( [ *response_reasoning_items, *([flushed_item] if flushed_item else []), - *(item for _, item in call_items if item.get("status") == "completed"), + *( + item + for _, item in call_items + if item.get("status") in {"completed", "failed"} + ), *sequential_result_items, *delegate_result_items, ] diff --git a/cptr/utils/openapi.py b/cptr/utils/openapi.py index faa8725..0adc5a1 100644 --- a/cptr/utils/openapi.py +++ b/cptr/utils/openapi.py @@ -9,7 +9,6 @@ from __future__ import annotations import copy import json import logging -from typing import Any import httpx @@ -66,9 +65,7 @@ async def fetch_openapi_spec( # ── Schema conversion ────────────────────────────────────── -def _resolve_schema( - schema: dict, components: dict, resolved: set | None = None -) -> dict: +def _resolve_schema(schema: dict, components: dict, resolved: set | None = None) -> dict: """Recursively resolve $ref references in a JSON schema.""" if not schema: return {} @@ -168,7 +165,7 @@ def convert_openapi_to_tool_specs(openapi_spec: dict) -> list[dict]: pschema = param.get("schema", {}) desc = pschema.get("description", "") or param.get("description", "") if pschema.get("enum") and isinstance(pschema["enum"], list): - desc += f'. Possible values: {", ".join(str(v) for v in pschema["enum"])}' + desc += f". Possible values: {', '.join(str(v) for v in pschema['enum'])}" prop = { "type": pschema.get("type") or "string", @@ -298,6 +295,21 @@ async def execute_openapi_tool( json=body_params if body_params else None, ) + if resp.status_code >= 400: + body = resp.text.strip() + try: + body = json.dumps(resp.json(), indent=2, ensure_ascii=False) + except Exception: + pass + return json.dumps( + { + "error": f"HTTP {resp.status_code} from tool server", + "status_code": resp.status_code, + "body": body[:4000], + }, + ensure_ascii=False, + ) + # Try to parse as JSON try: data = resp.json()