This commit is contained in:
Timothy Jaeryang Baek
2026-10-31 08:06:23 +09:00
Unverified
parent f9d1d8cdaf
commit b6c46ab00a
5 changed files with 245 additions and 34 deletions
+6 -2
View File
@@ -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:
@@ -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<string, unknown>;
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 @@
/>
</svg>
</div>
{:else if hasRejected}
<div class="text-red-400 dark:text-red-500">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="2.5"
stroke="currentColor"
class="size-4"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
{:else if hasError}
<div class="text-red-500 dark:text-red-400">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="2"
stroke="currentColor"
class="size-4"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M12 9v4m0 4h.01M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
/>
</svg>
</div>
{:else if allDone}
<div class="text-emerald-500 dark:text-emerald-400">
<svg
@@ -149,19 +227,6 @@
/>
</svg>
</div>
{:else if hasRejected}
<div class="text-red-400 dark:text-red-500">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="2.5"
stroke="currentColor"
class="size-4"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
{:else}
<div class="text-gray-400 dark:text-gray-500">
<svg
@@ -16,6 +16,49 @@
let { item, pairedOutput, done, chatId, messageId, toolLabel, 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<string, unknown>;
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 @@
<path stroke-linecap="round" stroke-linejoin="round" d="M13 7h6M13 12h6M13 17h6" />
</svg>
</div>
{:else if isError}
<div class="text-red-500 dark:text-red-400">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="2"
stroke="currentColor"
class="size-4"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M12 9v4m0 4h.01M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
/>
</svg>
</div>
{:else if isDone}
<div class="text-emerald-500 dark:text-emerald-400">
<svg
+78 -11
View File
@@ -76,6 +76,51 @@ from cptr.utils.identity import identity_for_context
logger = logging.getLogger(__name__)
def _is_tool_result_error(value: Any) -> 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,
]
+17 -5
View File
@@ -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()