mirror of
https://github.com/open-webui/computer.git
synced 2026-11-22 21:50:43 -05:00
refac
This commit is contained in:
1 parent
988582f548
commit
bbe3912e79
8 files changed
+106
-123
No files matched your search
@@ -581,13 +581,18 @@ class ChatMessage(Base):
|
||||
role: str,
|
||||
content: str,
|
||||
parent_id: str | None = None,
|
||||
model: str | None = None,
|
||||
model: object = None,
|
||||
done: bool = True,
|
||||
output: dict | list | None = None,
|
||||
usage: dict | None = None,
|
||||
meta: dict | None = None,
|
||||
created_at: int = 0,
|
||||
) -> ChatMessage:
|
||||
if isinstance(model, (list, tuple)):
|
||||
model = next((item.strip() for item in model if isinstance(item, str) and item.strip()), None)
|
||||
elif model is not None and not isinstance(model, str):
|
||||
model = str(model)
|
||||
|
||||
async with await get_db() as db:
|
||||
msg = ChatMessage(
|
||||
chat_id=chat_id,
|
||||
|
||||
@@ -17,22 +17,7 @@ from cptr.utils.agents.events import (
|
||||
AgentTextDelta,
|
||||
AgentToolUpdate,
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
from cptr.utils.agents.prompts import latest_user_text
|
||||
|
||||
|
||||
def _claude_query_input(
|
||||
@@ -124,7 +109,7 @@ async def run_claude_code_agent(
|
||||
yield AgentError("Claude Code support requires the claude-agent-sdk Python package")
|
||||
return
|
||||
|
||||
prompt = _prompt_from_messages(messages)
|
||||
prompt = latest_user_text(messages)
|
||||
env = os.environ.copy()
|
||||
if profile.get("home"):
|
||||
env["HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
@@ -134,6 +119,11 @@ async def run_claude_code_agent(
|
||||
extra_args = shlex.split(launch_args) if launch_args else []
|
||||
|
||||
try:
|
||||
session_id = None
|
||||
if resume_state:
|
||||
value = resume_state.get("session_id")
|
||||
session_id = value if isinstance(value, str) and value else None
|
||||
|
||||
options_kwargs: dict[str, Any] = {
|
||||
"system_prompt": system_prompt or None,
|
||||
"permission_mode": permission_mode,
|
||||
@@ -141,6 +131,8 @@ async def run_claude_code_agent(
|
||||
"include_partial_messages": True,
|
||||
"max_buffer_size": CLAUDE_CODE_MAX_BUFFER_SIZE,
|
||||
}
|
||||
if session_id:
|
||||
options_kwargs["resume"] = session_id
|
||||
if workspace:
|
||||
options_kwargs["cwd"] = workspace
|
||||
if extra_args:
|
||||
@@ -153,10 +145,6 @@ async def run_claude_code_agent(
|
||||
|
||||
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_input = _claude_query_input(prompt, attachments)
|
||||
|
||||
@@ -21,22 +21,7 @@ from cptr.utils.agents.events import (
|
||||
AgentTextDelta,
|
||||
AgentToolUpdate,
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
from cptr.utils.agents.prompts import latest_user_text
|
||||
|
||||
|
||||
def _auto_approve(chat_params: dict[str, Any]) -> bool:
|
||||
@@ -78,7 +63,7 @@ async def run_cline_agent(
|
||||
if model != "default":
|
||||
await client.set_model(model)
|
||||
|
||||
prompt = _prompt_from_messages(messages)
|
||||
prompt = latest_user_text(messages)
|
||||
if system_prompt:
|
||||
prompt = f"{system_prompt}\n\n{prompt}" if prompt else system_prompt
|
||||
|
||||
|
||||
+31
-20
@@ -21,6 +21,7 @@ from cptr.utils.agents.events import (
|
||||
AgentToolOutputDelta,
|
||||
AgentToolUpdate,
|
||||
)
|
||||
from cptr.utils.agents.prompts import latest_user_text
|
||||
|
||||
CODEX_STDOUT_CHUNK_SIZE = 64 * 1024
|
||||
CODEX_MAX_WIRE_MESSAGE_CHARS = 16 * 1024 * 1024
|
||||
@@ -209,22 +210,6 @@ class CodexAppServer:
|
||||
return "Codex app-server exited."
|
||||
|
||||
|
||||
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")
|
||||
|
||||
@@ -254,6 +239,34 @@ def _codex_turn_options(chat_params: dict[str, Any]) -> dict[str, str]:
|
||||
return options
|
||||
|
||||
|
||||
def _resume_thread_id(resume_state: dict[str, Any] | None) -> str | None:
|
||||
if not resume_state:
|
||||
return None
|
||||
value = resume_state.get("thread_id")
|
||||
return value if isinstance(value, str) and value.strip() else None
|
||||
|
||||
|
||||
async def _open_thread(
|
||||
client: CodexAppServer,
|
||||
thread_params: dict[str, Any],
|
||||
resume_state: dict[str, Any] | None,
|
||||
) -> str | None:
|
||||
thread_id = _resume_thread_id(resume_state)
|
||||
if thread_id:
|
||||
try:
|
||||
response = await client.request(
|
||||
"thread/resume", {"threadId": thread_id, **thread_params}
|
||||
)
|
||||
except RuntimeError:
|
||||
response = await client.request("thread/start", thread_params)
|
||||
else:
|
||||
response = await client.request("thread/start", thread_params)
|
||||
|
||||
thread = response.get("result", {}).get("thread", {})
|
||||
value = thread.get("id") if isinstance(thread, dict) else None
|
||||
return value if isinstance(value, str) and value else None
|
||||
|
||||
|
||||
def _tool_from_item_event(method: str, params: dict[str, Any]) -> AgentToolUpdate | None:
|
||||
if method not in {"item/started", "item/completed"}:
|
||||
return None
|
||||
@@ -357,14 +370,12 @@ async def run_codex_agent(
|
||||
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
|
||||
thread_id = await _open_thread(client, thread_params, resume_state)
|
||||
if not thread_id:
|
||||
yield AgentError("Codex did not return a thread id")
|
||||
return
|
||||
|
||||
prompt = _messages_to_prompt(messages)
|
||||
prompt = latest_user_text(messages)
|
||||
turn_input: list[dict[str, Any]] = []
|
||||
if prompt:
|
||||
turn_input.append({"type": "text", "text": prompt})
|
||||
|
||||
@@ -21,27 +21,12 @@ from cptr.utils.agents.events import (
|
||||
AgentTextDelta,
|
||||
AgentToolUpdate,
|
||||
)
|
||||
from cptr.utils.agents.prompts import latest_user_text
|
||||
|
||||
|
||||
CURSOR_CAPABILITIES = {"_meta": {"parameterizedModelPicker": True}}
|
||||
|
||||
|
||||
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 _auto_approve(chat_params: dict[str, Any]) -> bool:
|
||||
if chat_params.get("tool_approval_mode") == "full":
|
||||
return True
|
||||
@@ -88,7 +73,7 @@ async def run_cursor_agent(
|
||||
if model != "default":
|
||||
await client.set_model(model)
|
||||
|
||||
prompt = _prompt_from_messages(messages)
|
||||
prompt = latest_user_text(messages)
|
||||
if system_prompt:
|
||||
prompt = f"{system_prompt}\n\n{prompt}" if prompt else system_prompt
|
||||
|
||||
|
||||
@@ -21,22 +21,7 @@ from cptr.utils.agents.events import (
|
||||
AgentTextDelta,
|
||||
AgentToolUpdate,
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
from cptr.utils.agents.prompts import latest_user_text
|
||||
|
||||
|
||||
def _auth_method(env: dict[str, str]) -> str:
|
||||
@@ -83,7 +68,7 @@ async def run_grok_agent(
|
||||
if model != "default":
|
||||
await client.set_model(model)
|
||||
|
||||
prompt = _prompt_from_messages(messages)
|
||||
prompt = latest_user_text(messages)
|
||||
if system_prompt:
|
||||
prompt = f"{system_prompt}\n\n{prompt}" if prompt else system_prompt
|
||||
|
||||
|
||||
@@ -22,22 +22,7 @@ from cptr.utils.agents.events import (
|
||||
AgentTextDelta,
|
||||
AgentToolUpdate,
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
from cptr.utils.agents.prompts import latest_user_text
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
@@ -161,6 +146,31 @@ def _opencode_parts(prompt: str, attachments: PreparedAgentAttachments) -> list[
|
||||
return parts
|
||||
|
||||
|
||||
def _resume_session_id(resume_state: dict[str, Any] | None) -> str | None:
|
||||
if not resume_state:
|
||||
return None
|
||||
value = resume_state.get("session_id")
|
||||
return value if isinstance(value, str) and value.strip() else None
|
||||
|
||||
|
||||
async def _create_opencode_session(
|
||||
client: httpx.AsyncClient,
|
||||
headers: dict[str, str],
|
||||
) -> str:
|
||||
session_payload = await _request(
|
||||
client,
|
||||
"POST",
|
||||
["session.create", "session/create", "session"],
|
||||
headers=headers,
|
||||
json_body={"title": "cptr", "permission": []},
|
||||
)
|
||||
session = _session_data(session_payload)
|
||||
session_id = session.get("id")
|
||||
if not isinstance(session_id, str) or not session_id:
|
||||
raise RuntimeError("OpenCode did not return a session id")
|
||||
return session_id
|
||||
|
||||
|
||||
def _text_from_event(event: dict[str, Any], emitted: dict[str, str]) -> str | None:
|
||||
event_type = event.get("type")
|
||||
props = event.get("properties") if isinstance(event.get("properties"), dict) else {}
|
||||
@@ -239,23 +249,14 @@ async def run_opencode_agent(
|
||||
resume_state: dict[str, Any] | None,
|
||||
attachments: PreparedAgentAttachments,
|
||||
) -> AsyncIterator[AgentEvent]:
|
||||
del chat_params, resume_state
|
||||
del chat_params
|
||||
try:
|
||||
async with _opencode_server(profile, workspace) as (server_url, _proc):
|
||||
headers = _headers(profile)
|
||||
async with httpx.AsyncClient(base_url=server_url, timeout=None) as client:
|
||||
session_id: str | None = None
|
||||
session_payload = await _request(
|
||||
client,
|
||||
"POST",
|
||||
["session.create", "session/create", "session"],
|
||||
headers=headers,
|
||||
json_body={"title": "cptr", "permission": []},
|
||||
)
|
||||
session = _session_data(session_payload)
|
||||
session_id = session.get("id")
|
||||
if not isinstance(session_id, str) or not session_id:
|
||||
raise RuntimeError("OpenCode did not return a session id")
|
||||
session_id = _resume_session_id(resume_state)
|
||||
if not session_id:
|
||||
session_id = await _create_opencode_session(client, headers)
|
||||
|
||||
emitted: dict[str, str] = {}
|
||||
event_queue: asyncio.Queue[AgentEvent | None] = asyncio.Queue()
|
||||
@@ -263,7 +264,7 @@ async def run_opencode_agent(
|
||||
_collect_opencode_events(client, headers, session_id, emitted, event_queue)
|
||||
)
|
||||
|
||||
prompt = _prompt_from_messages(messages)
|
||||
prompt = latest_user_text(messages)
|
||||
if system_prompt:
|
||||
prompt = f"{system_prompt}\n\n{prompt}" if prompt else system_prompt
|
||||
parsed_model = _parse_model(model)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Prompt helpers shared by coding agent adapters."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def message_text(message: dict[str, Any]) -> str:
|
||||
content = message.get("content", "")
|
||||
if isinstance(content, list):
|
||||
return "\n".join(
|
||||
str(block.get("text", "")) for block in content if isinstance(block, dict)
|
||||
)
|
||||
return str(content or "")
|
||||
|
||||
|
||||
def latest_user_text(messages: list[dict[str, Any]]) -> str:
|
||||
"""Return only the current user turn for native-session agents."""
|
||||
|
||||
for message in reversed(messages):
|
||||
if message.get("role") == "user":
|
||||
return message_text(message).strip()
|
||||
return ""
|
||||
Reference in new issue
Block a user