mirror of
https://github.com/open-webui/computer.git
synced 2026-11-23 06:00:43 -05:00
refac
This commit is contained in:
1 parent
e92b376036
commit
3610efd5d0
12 files changed
+1321
-62
No files matched your search
@@ -60,7 +60,7 @@ export const updateConfig = (config: Record<string, unknown>) =>
|
||||
|
||||
// ── Agents ─────────────────────────────────────────────────
|
||||
|
||||
export type AgentType = 'codex' | 'claude_code';
|
||||
export type AgentType = 'codex' | 'claude_code' | 'cursor' | 'grok' | 'opencode';
|
||||
export type AgentMode = 'auto' | 'enabled' | 'disabled';
|
||||
export type AgentStatus = 'ready' | 'not_found' | 'missing_dependency' | 'auth_unknown' | 'error';
|
||||
|
||||
@@ -77,6 +77,9 @@ export interface AgentProfile {
|
||||
sandbox_mode?: 'read-only' | 'workspace-write' | 'danger-full-access';
|
||||
permission_mode?: 'default' | 'accept_edits' | 'bypass_permissions';
|
||||
launch_args?: string;
|
||||
api_endpoint?: string;
|
||||
server_url?: string;
|
||||
server_password?: string;
|
||||
}
|
||||
|
||||
export interface AgentsResponseProfile {
|
||||
|
||||
@@ -17,33 +17,49 @@
|
||||
// svelte-ignore state_referenced_locally
|
||||
let draft = $state<AgentProfile>({
|
||||
...profile,
|
||||
models: [...(profile.models?.length ? profile.models : ['default'])]
|
||||
models: [...(profile.models?.length ? profile.models : [])]
|
||||
});
|
||||
|
||||
function normalizeDraft(): AgentProfile {
|
||||
const fallbackModel = draft.agent === 'codex' ? 'gpt-5.4' : 'claude-sonnet-4-6';
|
||||
const currentModels = draft.models?.map((model) => model.trim()).filter(Boolean) || [];
|
||||
const models =
|
||||
currentModels.length === 1 && currentModels[0] === 'default'
|
||||
? [fallbackModel]
|
||||
: currentModels.length
|
||||
? currentModels
|
||||
: [fallbackModel];
|
||||
const defaultModel =
|
||||
draft.default_model !== 'default' && models.includes(draft.default_model)
|
||||
? draft.default_model
|
||||
: models[0];
|
||||
const models = currentModels.filter((model) => model !== 'default');
|
||||
const defaultModel = models.includes(draft.default_model)
|
||||
? draft.default_model
|
||||
: models[0] || '';
|
||||
return {
|
||||
...draft,
|
||||
id: draft.id.trim(),
|
||||
name: draft.name.trim() || draft.id.trim(),
|
||||
command: draft.command.trim() || (draft.agent === 'codex' ? 'codex' : 'claude'),
|
||||
command: draft.command.trim() || defaultCommand(draft.agent),
|
||||
home: draft.home?.trim() || null,
|
||||
models,
|
||||
default_model: defaultModel,
|
||||
launch_args: draft.launch_args?.trim() || ''
|
||||
launch_args: draft.launch_args?.trim() || '',
|
||||
api_endpoint: draft.api_endpoint?.trim() || '',
|
||||
server_url: draft.server_url?.trim() || '',
|
||||
server_password: draft.server_password?.trim() || ''
|
||||
};
|
||||
}
|
||||
|
||||
function defaultCommand(agent: AgentProfile['agent']): string {
|
||||
return {
|
||||
codex: 'codex',
|
||||
claude_code: 'claude',
|
||||
cursor: 'agent',
|
||||
grok: 'grok',
|
||||
opencode: 'opencode'
|
||||
}[agent];
|
||||
}
|
||||
|
||||
function defaultName(agent: AgentProfile['agent']): string {
|
||||
return {
|
||||
codex: 'Codex',
|
||||
claude_code: 'Claude Code',
|
||||
cursor: 'Cursor',
|
||||
grok: 'Grok',
|
||||
opencode: 'OpenCode'
|
||||
}[agent];
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal {onclose} class="w-full max-w-md mx-4">
|
||||
@@ -89,14 +105,14 @@
|
||||
id={`${fieldPrefix}-type`}
|
||||
value={draft.agent}
|
||||
onchange={(e) => {
|
||||
const agent = e.currentTarget.value as 'codex' | 'claude_code';
|
||||
const defaultModel = agent === 'codex' ? 'gpt-5.4' : 'claude-sonnet-4-6';
|
||||
const agent = e.currentTarget.value as AgentProfile['agent'];
|
||||
draft = {
|
||||
...draft,
|
||||
agent,
|
||||
command: agent === 'codex' ? 'codex' : 'claude',
|
||||
models: [defaultModel],
|
||||
default_model: defaultModel,
|
||||
name: defaultName(agent),
|
||||
command: defaultCommand(agent),
|
||||
models: [],
|
||||
default_model: '',
|
||||
approval_mode: draft.approval_mode || 'auto',
|
||||
sandbox_mode: draft.sandbox_mode || 'workspace-write',
|
||||
permission_mode: draft.permission_mode || 'default',
|
||||
@@ -107,6 +123,9 @@
|
||||
>
|
||||
<option value="codex">Codex</option>
|
||||
<option value="claude_code">Claude Code</option>
|
||||
<option value="cursor">Cursor</option>
|
||||
<option value="grok">Grok</option>
|
||||
<option value="opencode">OpenCode</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
@@ -130,7 +149,7 @@
|
||||
id={`${fieldPrefix}-command`}
|
||||
type="text"
|
||||
bind:value={draft.command}
|
||||
placeholder={draft.agent === 'codex' ? 'codex' : 'claude'}
|
||||
placeholder={defaultCommand(draft.agent)}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
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"
|
||||
@@ -167,6 +186,58 @@
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if draft.agent === 'cursor'}
|
||||
<label
|
||||
for={`${fieldPrefix}-api-endpoint`}
|
||||
class="text-[10px] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>
|
||||
{$t('admin.agentsApiEndpoint')}
|
||||
</label>
|
||||
<input
|
||||
id={`${fieldPrefix}-api-endpoint`}
|
||||
type="text"
|
||||
bind:value={draft.api_endpoint}
|
||||
placeholder="Optional"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
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}
|
||||
|
||||
{#if draft.agent === 'opencode'}
|
||||
<label
|
||||
for={`${fieldPrefix}-server-url`}
|
||||
class="text-[10px] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>
|
||||
{$t('admin.agentsServerUrl')}
|
||||
</label>
|
||||
<input
|
||||
id={`${fieldPrefix}-server-url`}
|
||||
type="text"
|
||||
bind:value={draft.server_url}
|
||||
placeholder="Optional"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
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"
|
||||
/>
|
||||
|
||||
<label
|
||||
for={`${fieldPrefix}-server-password`}
|
||||
class="text-[10px] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>
|
||||
{$t('admin.agentsServerPassword')}
|
||||
</label>
|
||||
<input
|
||||
id={`${fieldPrefix}-server-password`}
|
||||
type="password"
|
||||
bind:value={draft.server_password}
|
||||
placeholder="Optional"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
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}
|
||||
|
||||
<div class="flex items-center justify-between mt-3">
|
||||
<div class="flex items-center gap-3">
|
||||
{#if !isNew}
|
||||
|
||||
@@ -37,19 +37,22 @@
|
||||
|
||||
function normalizeProfile(profile: AgentProfile): AgentProfile {
|
||||
const models = profile.models?.map((m) => m.trim()).filter(Boolean);
|
||||
const nextModels = models.length ? models : ['default'];
|
||||
const nextModels = models.length ? models : [];
|
||||
const defaultModel = nextModels.includes(profile.default_model)
|
||||
? profile.default_model
|
||||
: nextModels[0];
|
||||
: nextModels[0] || '';
|
||||
return {
|
||||
...profile,
|
||||
id: profile.id.trim(),
|
||||
name: profile.name.trim() || profile.id.trim(),
|
||||
command: profile.command.trim() || (profile.agent === 'codex' ? 'codex' : 'claude'),
|
||||
command: profile.command.trim() || defaultCommand(profile.agent),
|
||||
home: profile.home?.trim() || null,
|
||||
models: nextModels,
|
||||
default_model: defaultModel,
|
||||
launch_args: profile.launch_args?.trim() || ''
|
||||
launch_args: profile.launch_args?.trim() || '',
|
||||
api_endpoint: profile.api_endpoint?.trim() || '',
|
||||
server_url: profile.server_url?.trim() || '',
|
||||
server_password: profile.server_password?.trim() || ''
|
||||
};
|
||||
}
|
||||
|
||||
@@ -60,9 +63,8 @@
|
||||
saved = Object.fromEntries(data.profiles.map((entry) => [entry.id, !entry.implicit]));
|
||||
}
|
||||
|
||||
function newProfile(agent: 'codex' | 'claude_code' = 'codex'): AgentProfile {
|
||||
const base = agent === 'codex' ? 'codex' : 'claude-code';
|
||||
const defaultModel = agent === 'codex' ? 'gpt-5.4' : 'claude-sonnet-4-6';
|
||||
function newProfile(agent: AgentProfile['agent'] = 'codex'): AgentProfile {
|
||||
const base = defaultProfileId(agent);
|
||||
let suffix = profiles.length + 1;
|
||||
let id = `${base}-${suffix}`;
|
||||
while (profiles.some((p) => p.id === id)) {
|
||||
@@ -72,25 +74,57 @@
|
||||
return {
|
||||
id,
|
||||
agent,
|
||||
name: agent === 'codex' ? 'Codex' : 'Claude Code',
|
||||
name: agentLabel(agent),
|
||||
mode: 'enabled',
|
||||
command: agent === 'codex' ? 'codex' : 'claude',
|
||||
command: defaultCommand(agent),
|
||||
home: null,
|
||||
models: [defaultModel],
|
||||
default_model: defaultModel,
|
||||
models: [],
|
||||
default_model: '',
|
||||
approval_mode: 'auto',
|
||||
sandbox_mode: 'workspace-write',
|
||||
permission_mode: 'default',
|
||||
launch_args: ''
|
||||
launch_args: '',
|
||||
api_endpoint: '',
|
||||
server_url: '',
|
||||
server_password: ''
|
||||
};
|
||||
}
|
||||
|
||||
function profileSubtitle(profile: AgentProfile): string {
|
||||
const modelCount = profile.models?.length || 0;
|
||||
const modelLabel = modelCount === 1 ? profile.default_model : `${modelCount} models`;
|
||||
const modelLabel =
|
||||
modelCount === 0
|
||||
? 'auto-detect'
|
||||
: modelCount === 1
|
||||
? profile.default_model
|
||||
: `${modelCount} models`;
|
||||
return `agent:${profile.id} · ${modelLabel}`;
|
||||
}
|
||||
|
||||
function defaultProfileId(agent: AgentProfile['agent']): string {
|
||||
return agent === 'claude_code' ? 'claude-code' : agent;
|
||||
}
|
||||
|
||||
function defaultCommand(agent: AgentProfile['agent']): string {
|
||||
return {
|
||||
codex: 'codex',
|
||||
claude_code: 'claude',
|
||||
cursor: 'agent',
|
||||
grok: 'grok',
|
||||
opencode: 'opencode'
|
||||
}[agent];
|
||||
}
|
||||
|
||||
function agentLabel(agent: AgentProfile['agent']): string {
|
||||
return {
|
||||
codex: 'Codex',
|
||||
claude_code: 'Claude Code',
|
||||
cursor: 'Cursor',
|
||||
grok: 'Grok',
|
||||
opencode: 'OpenCode'
|
||||
}[agent];
|
||||
}
|
||||
|
||||
function statusKey(profile: AgentProfile): string {
|
||||
return statusLabelKey[detected[profile.id]?.status || 'error'] || statusLabelKey.error;
|
||||
}
|
||||
|
||||
@@ -248,6 +248,9 @@
|
||||
"admin.agentsSandboxMode": "Sandbox",
|
||||
"admin.agentsPermissionMode": "Permission mode",
|
||||
"admin.agentsLaunchArgs": "Launch arguments",
|
||||
"admin.agentsApiEndpoint": "API endpoint",
|
||||
"admin.agentsServerUrl": "Server URL",
|
||||
"admin.agentsServerPassword": "Server password",
|
||||
"admin.agentsStatusReady": "Ready",
|
||||
"admin.agentsStatusNotFound": "Not found",
|
||||
"admin.agentsStatusMissingDependency": "Missing dependency",
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
"""Small ACP JSON-RPC client for Cursor and Grok agents."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from contextlib import suppress
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
|
||||
class AcpClient:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
command: str,
|
||||
args: list[str],
|
||||
cwd: str,
|
||||
env: dict[str, str],
|
||||
auth_method_id: str,
|
||||
client_capabilities: dict[str, Any] | None = None,
|
||||
resume_session_id: str | None = None,
|
||||
auto_approve_permissions: bool = False,
|
||||
) -> None:
|
||||
self.command = command
|
||||
self.args = args
|
||||
self.cwd = cwd
|
||||
self.env = env
|
||||
self.auth_method_id = auth_method_id
|
||||
self.client_capabilities = client_capabilities or {}
|
||||
self.resume_session_id = resume_session_id
|
||||
self.auto_approve_permissions = auto_approve_permissions
|
||||
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
|
||||
self.session_id: str | None = None
|
||||
self.setup_result: dict[str, Any] = {}
|
||||
self.model_config_id: str | None = None
|
||||
|
||||
async def start(self) -> None:
|
||||
self.proc = await asyncio.create_subprocess_exec(
|
||||
self.command,
|
||||
*self.args,
|
||||
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",
|
||||
{
|
||||
"protocolVersion": 1,
|
||||
"clientCapabilities": {
|
||||
"fs": {"readTextFile": False, "writeTextFile": False},
|
||||
"terminal": False,
|
||||
**self.client_capabilities,
|
||||
},
|
||||
"clientInfo": {"name": "cptr", "version": "0"},
|
||||
},
|
||||
)
|
||||
await self.request("authenticate", {"methodId": self.auth_method_id})
|
||||
await self._open_session()
|
||||
|
||||
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({"jsonrpc": "2.0", "id": request_id, "method": method, "params": params})
|
||||
response = await future
|
||||
if "error" in response:
|
||||
raise RuntimeError(str(response["error"]))
|
||||
result = response.get("result")
|
||||
return result if isinstance(result, dict) else {}
|
||||
|
||||
async def notify(self, method: str, params: dict[str, Any]) -> None:
|
||||
await self._send({"jsonrpc": "2.0", "method": method, "params": params})
|
||||
|
||||
async def prompt(self, text: str) -> dict[str, Any]:
|
||||
if not self.session_id:
|
||||
raise RuntimeError("ACP session has not started")
|
||||
return await self.request(
|
||||
"session/prompt",
|
||||
{"sessionId": self.session_id, "prompt": [{"type": "text", "text": text}]},
|
||||
)
|
||||
|
||||
async def cancel(self) -> None:
|
||||
if self.session_id:
|
||||
with suppress(Exception):
|
||||
await self.notify("session/cancel", {"sessionId": self.session_id})
|
||||
|
||||
async def set_model(self, model: str) -> None:
|
||||
if not self.session_id:
|
||||
return
|
||||
if self.model_config_id:
|
||||
with suppress(Exception):
|
||||
await self.request(
|
||||
"session/set_config_option",
|
||||
{"sessionId": self.session_id, "configId": self.model_config_id, "value": model},
|
||||
)
|
||||
return
|
||||
with suppress(Exception):
|
||||
await self.request("session/set_model", {"sessionId": self.session_id, "modelId": model})
|
||||
|
||||
async def _open_session(self) -> None:
|
||||
setup: dict[str, Any] | None = None
|
||||
if self.resume_session_id:
|
||||
with suppress(Exception):
|
||||
setup = await self.request(
|
||||
"session/load",
|
||||
{"sessionId": self.resume_session_id, "cwd": self.cwd, "mcpServers": []},
|
||||
)
|
||||
self.session_id = self.resume_session_id
|
||||
if setup is None:
|
||||
setup = await self.request("session/new", {"cwd": self.cwd, "mcpServers": []})
|
||||
session_id = setup.get("sessionId")
|
||||
self.session_id = session_id if isinstance(session_id, str) else None
|
||||
if not self.session_id:
|
||||
raise RuntimeError("ACP did not return a session id")
|
||||
self.setup_result = setup
|
||||
self.model_config_id = _extract_model_config_id(setup)
|
||||
|
||||
async def _send(self, payload: dict[str, Any]) -> None:
|
||||
assert self.proc is not None and self.proc.stdin is not None
|
||||
data = json.dumps(payload, separators=(",", ":")).encode()
|
||||
framed = b"Content-Length: " + str(len(data)).encode() + b"\r\n\r\n" + data
|
||||
self.proc.stdin.write(framed)
|
||||
await self.proc.stdin.drain()
|
||||
|
||||
async def _reader_loop(self) -> None:
|
||||
assert self.proc is not None and self.proc.stdout is not None
|
||||
buffer = b""
|
||||
while True:
|
||||
chunk = await self.proc.stdout.read(4096)
|
||||
if not chunk:
|
||||
break
|
||||
buffer += chunk
|
||||
while True:
|
||||
extracted = _extract_json_message(buffer)
|
||||
if extracted is None:
|
||||
break
|
||||
message, buffer = extracted
|
||||
await self._handle_message(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
|
||||
|
||||
async def _handle_message(self, message: dict[str, Any]) -> None:
|
||||
if "id" in message and ("result" in message or "error" in message) and "method" not in message:
|
||||
future = self.pending.pop(int(message["id"]), None)
|
||||
if future and not future.done():
|
||||
future.set_result(message)
|
||||
return
|
||||
|
||||
method = message.get("method")
|
||||
params = message.get("params") if isinstance(message.get("params"), dict) else {}
|
||||
if "id" in message and method == "session/request_permission":
|
||||
await self._reply_permission(int(message["id"]), params)
|
||||
return
|
||||
await self.events.put(message)
|
||||
|
||||
async def _reply_permission(self, request_id: int, params: dict[str, Any]) -> None:
|
||||
option_id = None
|
||||
if self.auto_approve_permissions:
|
||||
option_id = _select_permission_option(params, "allow_always") or _select_permission_option(
|
||||
params, "allow_once"
|
||||
)
|
||||
outcome = (
|
||||
{"outcome": {"outcome": "selected", "optionId": option_id}}
|
||||
if option_id
|
||||
else {"outcome": {"outcome": "cancelled"}}
|
||||
)
|
||||
await self._send({"jsonrpc": "2.0", "id": request_id, "result": outcome})
|
||||
|
||||
|
||||
def _extract_json_message(buffer: bytes) -> tuple[dict[str, Any], bytes] | None:
|
||||
stripped = buffer.lstrip()
|
||||
skipped = len(buffer) - len(stripped)
|
||||
if skipped:
|
||||
buffer = stripped
|
||||
|
||||
lower = buffer[:32].lower()
|
||||
if lower.startswith(b"content-length:"):
|
||||
header_end = buffer.find(b"\r\n\r\n")
|
||||
sep_len = 4
|
||||
if header_end < 0:
|
||||
header_end = buffer.find(b"\n\n")
|
||||
sep_len = 2
|
||||
if header_end < 0:
|
||||
return None
|
||||
header = buffer[:header_end].decode(errors="replace")
|
||||
length = None
|
||||
for line in header.splitlines():
|
||||
if line.lower().startswith("content-length:"):
|
||||
with suppress(ValueError):
|
||||
length = int(line.split(":", 1)[1].strip())
|
||||
if length is None:
|
||||
raise RuntimeError("ACP message missing Content-Length")
|
||||
start = header_end + sep_len
|
||||
end = start + length
|
||||
if len(buffer) < end:
|
||||
return None
|
||||
return json.loads(buffer[start:end].decode()), buffer[end:]
|
||||
|
||||
line_end = buffer.find(b"\n")
|
||||
if line_end < 0:
|
||||
return None
|
||||
line = buffer[:line_end].strip()
|
||||
if not line:
|
||||
return {}, buffer[line_end + 1 :]
|
||||
return json.loads(line.decode()), buffer[line_end + 1 :]
|
||||
|
||||
|
||||
def _extract_model_config_id(setup: dict[str, Any]) -> str | None:
|
||||
options = setup.get("configOptions")
|
||||
if not isinstance(options, list):
|
||||
return None
|
||||
for option in options:
|
||||
if isinstance(option, dict) and option.get("category") == "model":
|
||||
option_id = option.get("id")
|
||||
if isinstance(option_id, str) and option_id.strip():
|
||||
return option_id.strip()
|
||||
return None
|
||||
|
||||
|
||||
def _select_permission_option(params: dict[str, Any], kind: str) -> str | None:
|
||||
options = params.get("options")
|
||||
if not isinstance(options, list):
|
||||
return None
|
||||
for option in options:
|
||||
if isinstance(option, dict) and option.get("kind") == kind:
|
||||
option_id = option.get("optionId")
|
||||
if isinstance(option_id, str) and option_id.strip():
|
||||
return option_id.strip()
|
||||
return None
|
||||
|
||||
|
||||
def acp_text_from_update(params: dict[str, Any]) -> str | None:
|
||||
update = params.get("update")
|
||||
if not isinstance(update, dict):
|
||||
return None
|
||||
if update.get("sessionUpdate") != "agent_message_chunk":
|
||||
return None
|
||||
content = update.get("content")
|
||||
if isinstance(content, dict) and content.get("type") == "text":
|
||||
text = content.get("text")
|
||||
return text if isinstance(text, str) and text else None
|
||||
return None
|
||||
|
||||
|
||||
def acp_models_from_setup(setup: dict[str, Any]) -> list[str]:
|
||||
models = setup.get("models")
|
||||
if not isinstance(models, dict):
|
||||
return []
|
||||
available = models.get("availableModels")
|
||||
if not isinstance(available, list):
|
||||
return []
|
||||
result = []
|
||||
for item in available:
|
||||
if isinstance(item, dict):
|
||||
model = item.get("modelId")
|
||||
if isinstance(model, str) and model.strip():
|
||||
result.append(model.strip())
|
||||
return result
|
||||
|
||||
|
||||
async def acp_event_stream(client: AcpClient) -> AsyncIterator[dict[str, Any]]:
|
||||
while True:
|
||||
yield await client.events.get()
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Cursor Agent ACP adapter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from contextlib import suppress
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
from cptr.utils.agents.acp import AcpClient, acp_event_stream, acp_text_from_update
|
||||
from cptr.utils.agents.events import AgentDone, AgentError, AgentEvent, AgentTextDelta
|
||||
|
||||
|
||||
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
|
||||
return bool(chat_params.get("auto_approve_tools"))
|
||||
|
||||
|
||||
async def run_cursor_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["HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
|
||||
args = []
|
||||
api_endpoint = str(profile.get("api_endpoint") or "").strip()
|
||||
if api_endpoint:
|
||||
args.extend(["-e", api_endpoint])
|
||||
args.append("acp")
|
||||
|
||||
session_id = None
|
||||
if resume_state and isinstance(resume_state.get("session_id"), str):
|
||||
session_id = resume_state["session_id"]
|
||||
|
||||
client = AcpClient(
|
||||
command=str(profile["command"]),
|
||||
args=args,
|
||||
cwd=workspace,
|
||||
env=env,
|
||||
auth_method_id="cursor_login",
|
||||
client_capabilities=CURSOR_CAPABILITIES,
|
||||
resume_session_id=session_id,
|
||||
auto_approve_permissions=_auto_approve(chat_params),
|
||||
)
|
||||
try:
|
||||
await client.start()
|
||||
if model != "default":
|
||||
await client.set_model(model)
|
||||
|
||||
prompt = _prompt_from_messages(messages)
|
||||
if system_prompt:
|
||||
prompt = f"{system_prompt}\n\n{prompt}" if prompt else system_prompt
|
||||
|
||||
prompt_task = asyncio.create_task(client.prompt(prompt))
|
||||
try:
|
||||
async for event in acp_event_stream(client):
|
||||
params = event.get("params") if isinstance(event.get("params"), dict) else {}
|
||||
text = acp_text_from_update(params)
|
||||
if text:
|
||||
yield AgentTextDelta(text)
|
||||
if prompt_task.done():
|
||||
try:
|
||||
next_event = await asyncio.wait_for(client.events.get(), timeout=0.25)
|
||||
except asyncio.TimeoutError:
|
||||
break
|
||||
next_params = (
|
||||
next_event.get("params") if isinstance(next_event.get("params"), dict) else {}
|
||||
)
|
||||
next_text = acp_text_from_update(next_params)
|
||||
if next_text:
|
||||
yield AgentTextDelta(next_text)
|
||||
await prompt_task
|
||||
finally:
|
||||
if not prompt_task.done():
|
||||
prompt_task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await prompt_task
|
||||
|
||||
yield AgentDone(
|
||||
resume_state={
|
||||
"profile_id": profile["id"],
|
||||
"session_id": client.session_id,
|
||||
"workspace": workspace,
|
||||
"model": model,
|
||||
}
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
await client.cancel()
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - surfaced in chat.
|
||||
yield AgentError(str(exc))
|
||||
finally:
|
||||
await client.close()
|
||||
@@ -4,12 +4,17 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
from dataclasses import dataclass, asdict
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from cptr.utils.agents.models import (
|
||||
default_agent_profiles,
|
||||
get_raw_agent_profiles,
|
||||
@@ -54,12 +59,17 @@ def _resolve_command(command: str) -> str | None:
|
||||
return shutil.which(command)
|
||||
|
||||
|
||||
async def _run_probe(argv: list[str], timeout: float = 3.0) -> tuple[int, str]:
|
||||
async def _run_probe(
|
||||
argv: list[str],
|
||||
timeout: float = 3.0,
|
||||
env: dict[str, str] | None = None,
|
||||
) -> tuple[int, str]:
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*argv,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
env=env,
|
||||
)
|
||||
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
@@ -103,6 +113,51 @@ async def detect_profile(profile: dict[str, Any]) -> AgentDetection:
|
||||
models = await _probe_codex_models(command, profile)
|
||||
return AgentDetection("ready", command, version, None, models)
|
||||
|
||||
if profile.get("agent") == "cursor":
|
||||
about = await _probe_cursor_about(command, profile)
|
||||
if about["status"] != "ready":
|
||||
return AgentDetection(
|
||||
about["status"],
|
||||
command,
|
||||
about.get("version"),
|
||||
about.get("message"),
|
||||
[],
|
||||
)
|
||||
models = await _probe_cursor_models(command, profile)
|
||||
if not models:
|
||||
return AgentDetection(
|
||||
"auth_unknown",
|
||||
command,
|
||||
about.get("version"),
|
||||
"Could not discover Cursor models. Check Cursor Agent login and CLI setup.",
|
||||
[],
|
||||
)
|
||||
return AgentDetection("ready", command, about.get("version"), None, models)
|
||||
|
||||
if profile.get("agent") == "grok":
|
||||
models = await _probe_grok_models(command, profile)
|
||||
if not models:
|
||||
return AgentDetection(
|
||||
"auth_unknown",
|
||||
command,
|
||||
version,
|
||||
"Could not discover Grok models. Check Grok login or XAI_API_KEY.",
|
||||
[],
|
||||
)
|
||||
return AgentDetection("ready", command, version, None, models)
|
||||
|
||||
if profile.get("agent") == "opencode":
|
||||
models = await _probe_opencode_models(command, profile)
|
||||
if not models:
|
||||
return AgentDetection(
|
||||
"auth_unknown",
|
||||
command,
|
||||
version,
|
||||
"Could not discover OpenCode models. Check connected OpenCode providers.",
|
||||
[],
|
||||
)
|
||||
return AgentDetection("ready", command, version, None, models)
|
||||
|
||||
return AgentDetection("error", command, version, "Unknown agent")
|
||||
|
||||
|
||||
@@ -168,6 +223,212 @@ async def _probe_codex_models(command: str, profile: dict[str, Any]) -> list[str
|
||||
await client.close()
|
||||
|
||||
|
||||
async def _probe_cursor_about(command: str, profile: dict[str, Any]) -> dict[str, Any]:
|
||||
env = os.environ.copy()
|
||||
if profile.get("home"):
|
||||
env["HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
code, text = await _run_probe([command, "about", "--format", "json"], timeout=8, env=env)
|
||||
if code != 0:
|
||||
code, text = await _run_probe([command, "about"], timeout=8, env=env)
|
||||
version = None
|
||||
if text:
|
||||
with suppress(Exception):
|
||||
parsed = json.loads(text)
|
||||
if isinstance(parsed, dict):
|
||||
raw_version = parsed.get("cliVersion")
|
||||
version = raw_version.strip() if isinstance(raw_version, str) else None
|
||||
if parsed.get("userEmail") is None:
|
||||
return {
|
||||
"status": "auth_unknown",
|
||||
"version": version,
|
||||
"message": "Cursor Agent is not authenticated. Run `agent login`.",
|
||||
}
|
||||
email = parsed.get("userEmail")
|
||||
if isinstance(email, str) and email.strip():
|
||||
lower = email.strip().lower()
|
||||
if "not logged in" in lower or "login required" in lower:
|
||||
return {
|
||||
"status": "auth_unknown",
|
||||
"version": version,
|
||||
"message": "Cursor Agent is not authenticated. Run `agent login`.",
|
||||
}
|
||||
return {"status": "ready", "version": version, "message": None}
|
||||
version_match = re.search(r"CLI Version\s+([^\n]+)", text)
|
||||
if version_match:
|
||||
version = version_match.group(1).strip()
|
||||
email_match = re.search(r"User Email\s+([^\n]+)", text)
|
||||
if email_match:
|
||||
email = email_match.group(1).strip().lower()
|
||||
if "not logged in" in email or "login required" in email:
|
||||
return {
|
||||
"status": "auth_unknown",
|
||||
"version": version,
|
||||
"message": "Cursor Agent is not authenticated. Run `agent login`.",
|
||||
}
|
||||
if code != 0:
|
||||
return {
|
||||
"status": "error",
|
||||
"version": version,
|
||||
"message": text or "Failed to run Cursor Agent health check.",
|
||||
}
|
||||
return {"status": "ready", "version": version, "message": None}
|
||||
|
||||
|
||||
async def _probe_cursor_models(command: str, profile: dict[str, Any]) -> list[str] | None:
|
||||
from cptr.utils.agents.acp import AcpClient
|
||||
|
||||
env = os.environ.copy()
|
||||
if profile.get("home"):
|
||||
env["HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
args = []
|
||||
api_endpoint = str(profile.get("api_endpoint") or "").strip()
|
||||
if api_endpoint:
|
||||
args.extend(["-e", api_endpoint])
|
||||
args.append("acp")
|
||||
client = AcpClient(
|
||||
command=command,
|
||||
args=args,
|
||||
cwd=os.getcwd(),
|
||||
env=env,
|
||||
auth_method_id="cursor_login",
|
||||
client_capabilities={"_meta": {"parameterizedModelPicker": True}},
|
||||
)
|
||||
try:
|
||||
await asyncio.wait_for(client.start(), timeout=10)
|
||||
result = await asyncio.wait_for(client.request("cursor/list_available_models", {}), timeout=5)
|
||||
models = []
|
||||
for item in result.get("models") or []:
|
||||
if isinstance(item, dict) and isinstance(item.get("value"), str):
|
||||
models.append(item["value"].strip())
|
||||
return [model for model in models if model] or None
|
||||
except Exception:
|
||||
return None
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
|
||||
async def _probe_grok_models(command: str, profile: dict[str, Any]) -> list[str] | None:
|
||||
from cptr.utils.agents.acp import AcpClient, acp_models_from_setup
|
||||
|
||||
env = os.environ.copy()
|
||||
if profile.get("home"):
|
||||
env["HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
env["GROK_OAUTH2_REFERRER"] = "cptr"
|
||||
auth_method_id = "xai.api_key" if env.get("XAI_API_KEY", "").strip() else "cached_token"
|
||||
client = AcpClient(
|
||||
command=command,
|
||||
args=["agent", "stdio"],
|
||||
cwd=os.getcwd(),
|
||||
env=env,
|
||||
auth_method_id=auth_method_id,
|
||||
)
|
||||
try:
|
||||
await asyncio.wait_for(client.start(), timeout=10)
|
||||
return acp_models_from_setup(client.setup_result) or None
|
||||
except Exception:
|
||||
return None
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
|
||||
async def _probe_opencode_models(command: str, profile: dict[str, Any]) -> list[str] | None:
|
||||
env = os.environ.copy()
|
||||
if profile.get("home"):
|
||||
env["HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
server_url = str(profile.get("server_url") or "").strip()
|
||||
password = str(profile.get("server_password") or "").strip()
|
||||
proc: asyncio.subprocess.Process | None = None
|
||||
try:
|
||||
if not server_url:
|
||||
port = _free_port()
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
command,
|
||||
"serve",
|
||||
"--hostname=127.0.0.1",
|
||||
f"--port={port}",
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
env={**env, "OPENCODE_CONFIG_CONTENT": "{}"},
|
||||
)
|
||||
server_url = await _read_opencode_server_url(proc, port)
|
||||
async with httpx.AsyncClient(base_url=server_url, timeout=5) as client:
|
||||
headers = {}
|
||||
if password:
|
||||
import base64
|
||||
|
||||
token = base64.b64encode(f"opencode:{password}".encode()).decode()
|
||||
headers["Authorization"] = f"Basic {token}"
|
||||
providers = await _opencode_json(client, ["provider.list", "provider/list", "provider"], headers)
|
||||
provider_list = providers.get("data") if isinstance(providers.get("data"), dict) else providers
|
||||
connected = set(provider_list.get("connected") or [])
|
||||
all_providers = provider_list.get("all") or []
|
||||
models: list[str] = []
|
||||
for provider in all_providers:
|
||||
if not isinstance(provider, dict):
|
||||
continue
|
||||
provider_id = provider.get("id")
|
||||
if not isinstance(provider_id, str) or provider_id not in connected:
|
||||
continue
|
||||
raw_models = provider.get("models")
|
||||
if isinstance(raw_models, dict):
|
||||
for model_id in raw_models:
|
||||
if isinstance(model_id, str) and model_id.strip():
|
||||
models.append(f"{provider_id}/{model_id.strip()}")
|
||||
return models or None
|
||||
except Exception:
|
||||
return None
|
||||
finally:
|
||||
if proc and proc.returncode is None:
|
||||
proc.terminate()
|
||||
with suppress(asyncio.TimeoutError):
|
||||
await asyncio.wait_for(proc.wait(), timeout=2)
|
||||
if proc.returncode is None:
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return int(sock.getsockname()[1])
|
||||
|
||||
|
||||
async def _read_opencode_server_url(proc: asyncio.subprocess.Process, port: int) -> str:
|
||||
assert proc.stdout is not None
|
||||
fallback = f"http://127.0.0.1:{port}"
|
||||
deadline = asyncio.get_running_loop().time() + 5
|
||||
while asyncio.get_running_loop().time() < deadline:
|
||||
line = await asyncio.wait_for(proc.stdout.readline(), timeout=1)
|
||||
if not line:
|
||||
break
|
||||
text = line.decode(errors="replace").strip()
|
||||
match = re.search(r"(https?://[^\s]+)", text)
|
||||
if match:
|
||||
return match.group(1)
|
||||
return fallback
|
||||
|
||||
|
||||
async def _opencode_json(
|
||||
client: httpx.AsyncClient,
|
||||
paths: list[str],
|
||||
headers: dict[str, str],
|
||||
) -> dict[str, Any]:
|
||||
last_error = None
|
||||
for path in paths:
|
||||
try:
|
||||
response = await client.get(f"/{path}", headers=headers)
|
||||
if response.status_code == 405:
|
||||
response = await client.post(f"/{path}", headers=headers, json={})
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception as exc: # noqa: BLE001 - try alternate generated route names.
|
||||
last_error = exc
|
||||
if last_error:
|
||||
raise last_error
|
||||
return {}
|
||||
|
||||
|
||||
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
|
||||
@@ -186,11 +447,15 @@ async def get_agent_status(app_state=None, refresh: bool = False) -> dict[str, A
|
||||
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"]
|
||||
models = detected.models or profile.get("models") or []
|
||||
available = (
|
||||
mode != "disabled"
|
||||
and bool(models)
|
||||
and (mode != "auto" or detected.status == "ready")
|
||||
)
|
||||
effective_profile = dict(profile)
|
||||
effective_profile["models"] = models
|
||||
if effective_profile.get("default_model") not in models:
|
||||
if models and effective_profile.get("default_model") not in models:
|
||||
effective_profile["default_model"] = models[0]
|
||||
entries.append(
|
||||
{
|
||||
@@ -223,7 +488,7 @@ async def get_available_agent_model_entries(app_state=None) -> list[dict[str, st
|
||||
if not profile["available"]:
|
||||
continue
|
||||
config = profile["config"]
|
||||
for model in config.get("models") or ["default"]:
|
||||
for model in config.get("models") or []:
|
||||
model_id = model_id_for_profile(config, model)
|
||||
entries.append(
|
||||
{
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Grok ACP adapter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from contextlib import suppress
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
from cptr.utils.agents.acp import AcpClient, acp_event_stream, acp_text_from_update
|
||||
from cptr.utils.agents.events import AgentDone, AgentError, AgentEvent, 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 _auth_method(env: dict[str, str]) -> str:
|
||||
return "xai.api_key" if env.get("XAI_API_KEY", "").strip() else "cached_token"
|
||||
|
||||
|
||||
def _auto_approve(chat_params: dict[str, Any]) -> bool:
|
||||
if chat_params.get("tool_approval_mode") == "full":
|
||||
return True
|
||||
return bool(chat_params.get("auto_approve_tools"))
|
||||
|
||||
|
||||
async def run_grok_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["HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
env["GROK_OAUTH2_REFERRER"] = "cptr"
|
||||
|
||||
session_id = None
|
||||
if resume_state and isinstance(resume_state.get("session_id"), str):
|
||||
session_id = resume_state["session_id"]
|
||||
|
||||
client = AcpClient(
|
||||
command=str(profile["command"]),
|
||||
args=["agent", "stdio"],
|
||||
cwd=workspace,
|
||||
env=env,
|
||||
auth_method_id=_auth_method(env),
|
||||
resume_session_id=session_id,
|
||||
auto_approve_permissions=_auto_approve(chat_params),
|
||||
)
|
||||
try:
|
||||
await client.start()
|
||||
if model != "default":
|
||||
await client.set_model(model)
|
||||
|
||||
prompt = _prompt_from_messages(messages)
|
||||
if system_prompt:
|
||||
prompt = f"{system_prompt}\n\n{prompt}" if prompt else system_prompt
|
||||
|
||||
prompt_task = asyncio.create_task(client.prompt(prompt))
|
||||
try:
|
||||
async for event in acp_event_stream(client):
|
||||
params = event.get("params") if isinstance(event.get("params"), dict) else {}
|
||||
text = acp_text_from_update(params)
|
||||
if text:
|
||||
yield AgentTextDelta(text)
|
||||
if prompt_task.done():
|
||||
try:
|
||||
next_event = await asyncio.wait_for(client.events.get(), timeout=0.25)
|
||||
except asyncio.TimeoutError:
|
||||
break
|
||||
next_params = (
|
||||
next_event.get("params") if isinstance(next_event.get("params"), dict) else {}
|
||||
)
|
||||
next_text = acp_text_from_update(next_params)
|
||||
if next_text:
|
||||
yield AgentTextDelta(next_text)
|
||||
await prompt_task
|
||||
finally:
|
||||
if not prompt_task.done():
|
||||
prompt_task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await prompt_task
|
||||
|
||||
yield AgentDone(
|
||||
resume_state={
|
||||
"profile_id": profile["id"],
|
||||
"session_id": client.session_id,
|
||||
"workspace": workspace,
|
||||
"model": model,
|
||||
}
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
await client.cancel()
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - surfaced in chat.
|
||||
yield AgentError(str(exc))
|
||||
finally:
|
||||
await client.close()
|
||||
+69
-21
@@ -20,8 +20,8 @@ DEFAULT_AGENT_PROFILES: list[dict[str, Any]] = [
|
||||
"mode": "auto",
|
||||
"command": "codex",
|
||||
"home": None,
|
||||
"models": ["gpt-5.4"],
|
||||
"default_model": "gpt-5.4",
|
||||
"models": [],
|
||||
"default_model": "",
|
||||
"approval_mode": "auto",
|
||||
"sandbox_mode": "workspace-write",
|
||||
},
|
||||
@@ -32,19 +32,67 @@ DEFAULT_AGENT_PROFILES: list[dict[str, Any]] = [
|
||||
"mode": "auto",
|
||||
"command": "claude",
|
||||
"home": None,
|
||||
"models": ["claude-sonnet-4-6"],
|
||||
"default_model": "claude-sonnet-4-6",
|
||||
"models": [],
|
||||
"default_model": "",
|
||||
"permission_mode": "default",
|
||||
"launch_args": "",
|
||||
},
|
||||
{
|
||||
"id": "cursor",
|
||||
"agent": "cursor",
|
||||
"name": "Cursor",
|
||||
"mode": "auto",
|
||||
"command": "agent",
|
||||
"home": None,
|
||||
"models": [],
|
||||
"default_model": "",
|
||||
"api_endpoint": "",
|
||||
},
|
||||
{
|
||||
"id": "grok",
|
||||
"agent": "grok",
|
||||
"name": "Grok",
|
||||
"mode": "auto",
|
||||
"command": "grok",
|
||||
"home": None,
|
||||
"models": [],
|
||||
"default_model": "",
|
||||
},
|
||||
{
|
||||
"id": "opencode",
|
||||
"agent": "opencode",
|
||||
"name": "OpenCode",
|
||||
"mode": "auto",
|
||||
"command": "opencode",
|
||||
"home": None,
|
||||
"models": [],
|
||||
"default_model": "",
|
||||
"server_url": "",
|
||||
"server_password": "",
|
||||
},
|
||||
]
|
||||
|
||||
_PROFILE_ID_RE = re.compile(r"^[a-z][a-z0-9_-]{0,63}$")
|
||||
_VALID_AGENTS = {"codex", "claude_code"}
|
||||
_VALID_AGENTS = {"codex", "claude_code", "cursor", "grok", "opencode"}
|
||||
_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"}
|
||||
_AGENT_DEFAULTS: dict[str, dict[str, str]] = {
|
||||
"codex": {"name": "Codex", "command": "codex", "model": ""},
|
||||
"claude_code": {
|
||||
"name": "Claude Code",
|
||||
"command": "claude",
|
||||
"model": "",
|
||||
},
|
||||
"cursor": {
|
||||
"name": "Cursor",
|
||||
"command": "agent",
|
||||
"model": "",
|
||||
},
|
||||
"grok": {"name": "Grok", "command": "grok", "model": ""},
|
||||
"opencode": {"name": "OpenCode", "command": "opencode", "model": ""},
|
||||
}
|
||||
|
||||
|
||||
def default_agent_profiles() -> list[dict[str, Any]]:
|
||||
@@ -59,8 +107,8 @@ def normalize_agent_profile(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
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"
|
||||
raise HTTPException(400, "agent must be codex, claude_code, cursor, grok, or opencode")
|
||||
defaults = _AGENT_DEFAULTS[agent]
|
||||
|
||||
mode = str(profile.get("mode") or "auto").strip()
|
||||
if mode not in _VALID_MODES:
|
||||
@@ -68,11 +116,9 @@ def normalize_agent_profile(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
command = str(profile.get("command") or "").strip()
|
||||
if not command:
|
||||
command = "codex" if agent == "codex" else "claude"
|
||||
command = defaults["command"]
|
||||
|
||||
name = str(profile.get("name") or "").strip() or (
|
||||
"Codex" if agent == "codex" else "Claude Code"
|
||||
)
|
||||
name = str(profile.get("name") or "").strip() or defaults["name"]
|
||||
home = profile.get("home")
|
||||
if isinstance(home, str):
|
||||
home = home.strip() or None
|
||||
@@ -81,23 +127,20 @@ def normalize_agent_profile(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
models = profile.get("models")
|
||||
if not isinstance(models, list):
|
||||
models = ["default"]
|
||||
models = []
|
||||
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()
|
||||
default_model = str(profile.get("default_model") or "").strip()
|
||||
if default_model == "default":
|
||||
default_model = fallback_model
|
||||
if default_model not in normalized_models:
|
||||
default_model = ""
|
||||
if normalized_models and not default_model:
|
||||
default_model = normalized_models[0]
|
||||
if normalized_models and default_model not in normalized_models:
|
||||
raise HTTPException(400, "agent default_model must be present in models")
|
||||
|
||||
normalized: dict[str, Any] = {
|
||||
@@ -126,7 +169,7 @@ def normalize_agent_profile(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"sandbox_mode": sandbox_mode,
|
||||
}
|
||||
)
|
||||
else:
|
||||
elif agent == "claude_code":
|
||||
permission_mode = str(profile.get("permission_mode") or "default").strip()
|
||||
if permission_mode not in _VALID_CLAUDE_PERMISSION:
|
||||
raise HTTPException(
|
||||
@@ -138,6 +181,11 @@ def normalize_agent_profile(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"launch_args": str(profile.get("launch_args") or "").strip(),
|
||||
}
|
||||
)
|
||||
elif agent == "cursor":
|
||||
normalized["api_endpoint"] = str(profile.get("api_endpoint") or "").strip()
|
||||
elif agent == "opencode":
|
||||
normalized["server_url"] = str(profile.get("server_url") or "").strip()
|
||||
normalized["server_password"] = str(profile.get("server_password") or "").strip()
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
"""OpenCode server adapter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
from contextlib import asynccontextmanager, suppress
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
import httpx
|
||||
|
||||
from cptr.utils.agents.events import AgentDone, AgentError, AgentEvent, 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 _free_port() -> int:
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return int(sock.getsockname()[1])
|
||||
|
||||
|
||||
async def _server_url_from_stdout(proc: asyncio.subprocess.Process, port: int) -> str:
|
||||
assert proc.stdout is not None
|
||||
fallback = f"http://127.0.0.1:{port}"
|
||||
deadline = asyncio.get_running_loop().time() + 5
|
||||
while asyncio.get_running_loop().time() < deadline:
|
||||
line = await asyncio.wait_for(proc.stdout.readline(), timeout=1)
|
||||
if not line:
|
||||
break
|
||||
match = re.search(r"(https?://[^\s]+)", line.decode(errors="replace"))
|
||||
if match:
|
||||
return match.group(1)
|
||||
return fallback
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def _opencode_server(profile: dict[str, Any], workspace: str):
|
||||
server_url = str(profile.get("server_url") or "").strip()
|
||||
if server_url:
|
||||
yield server_url, None
|
||||
return
|
||||
|
||||
env = os.environ.copy()
|
||||
if profile.get("home"):
|
||||
env["HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
port = _free_port()
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
str(profile["command"]),
|
||||
"serve",
|
||||
"--hostname=127.0.0.1",
|
||||
f"--port={port}",
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
cwd=workspace or os.getcwd(),
|
||||
env={**env, "OPENCODE_CONFIG_CONTENT": "{}"},
|
||||
)
|
||||
stderr_task = asyncio.create_task(_drain_stderr(proc))
|
||||
try:
|
||||
yield await _server_url_from_stdout(proc, port), proc
|
||||
finally:
|
||||
stderr_task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await stderr_task
|
||||
if proc.returncode is None:
|
||||
proc.terminate()
|
||||
with suppress(asyncio.TimeoutError):
|
||||
await asyncio.wait_for(proc.wait(), timeout=2)
|
||||
if proc.returncode is None:
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
|
||||
|
||||
async def _drain_stderr(proc: asyncio.subprocess.Process) -> None:
|
||||
assert proc.stderr is not None
|
||||
while await proc.stderr.readline():
|
||||
pass
|
||||
|
||||
|
||||
def _headers(profile: dict[str, Any]) -> dict[str, str]:
|
||||
password = str(profile.get("server_password") or "").strip()
|
||||
if not password:
|
||||
return {}
|
||||
token = base64.b64encode(f"opencode:{password}".encode()).decode()
|
||||
return {"Authorization": f"Basic {token}"}
|
||||
|
||||
|
||||
async def _request(
|
||||
client: httpx.AsyncClient,
|
||||
method: str,
|
||||
paths: list[str],
|
||||
*,
|
||||
headers: dict[str, str],
|
||||
json_body: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
last_error: Exception | None = None
|
||||
for path in paths:
|
||||
try:
|
||||
response = await client.request(method, f"/{path}", headers=headers, json=json_body)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception as exc: # noqa: BLE001 - try alternate generated route names.
|
||||
last_error = exc
|
||||
if last_error:
|
||||
raise last_error
|
||||
return {}
|
||||
|
||||
|
||||
def _session_data(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
data = payload.get("data")
|
||||
return data if isinstance(data, dict) else payload
|
||||
|
||||
|
||||
def _parse_model(model: str) -> dict[str, str]:
|
||||
provider_id, _, model_id = model.partition("/")
|
||||
if not provider_id or not model_id:
|
||||
raise RuntimeError("OpenCode models must use provider/model format")
|
||||
return {"providerID": provider_id, "modelID": model_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 {}
|
||||
if event_type == "message.part.delta":
|
||||
delta = props.get("delta")
|
||||
return delta if isinstance(delta, str) and delta else None
|
||||
if event_type == "message.part.updated":
|
||||
part = props.get("part") if isinstance(props.get("part"), dict) else {}
|
||||
if part.get("type") not in ("text", "reasoning"):
|
||||
return None
|
||||
part_id = part.get("id")
|
||||
text = part.get("text")
|
||||
if not isinstance(part_id, str) or not isinstance(text, str):
|
||||
return None
|
||||
previous = emitted.get(part_id, "")
|
||||
if text.startswith(previous):
|
||||
delta = text[len(previous) :]
|
||||
else:
|
||||
delta = text
|
||||
emitted[part_id] = text
|
||||
return delta or None
|
||||
return None
|
||||
|
||||
|
||||
async def run_opencode_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]:
|
||||
del chat_params, resume_state
|
||||
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")
|
||||
|
||||
emitted: dict[str, str] = {}
|
||||
event_queue: asyncio.Queue[str | None] = asyncio.Queue()
|
||||
event_task = asyncio.create_task(
|
||||
_collect_opencode_events(client, headers, session_id, emitted, event_queue)
|
||||
)
|
||||
|
||||
prompt = _prompt_from_messages(messages)
|
||||
if system_prompt:
|
||||
prompt = f"{system_prompt}\n\n{prompt}" if prompt else system_prompt
|
||||
parsed_model = _parse_model(model)
|
||||
try:
|
||||
await _request(
|
||||
client,
|
||||
"POST",
|
||||
["session.promptAsync", "session/promptAsync", "session/prompt"],
|
||||
headers=headers,
|
||||
json_body={
|
||||
"sessionID": session_id,
|
||||
"model": parsed_model,
|
||||
"parts": [{"type": "text", "text": prompt}],
|
||||
},
|
||||
)
|
||||
|
||||
while True:
|
||||
item = await event_queue.get()
|
||||
if item is None:
|
||||
break
|
||||
yield AgentTextDelta(item)
|
||||
except asyncio.CancelledError:
|
||||
with suppress(Exception):
|
||||
await _request(
|
||||
client,
|
||||
"POST",
|
||||
["session.abort", "session/abort"],
|
||||
headers=headers,
|
||||
json_body={"sessionID": session_id},
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
event_task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await event_task
|
||||
|
||||
yield AgentDone(
|
||||
resume_state={
|
||||
"profile_id": profile["id"],
|
||||
"session_id": session_id,
|
||||
"workspace": workspace,
|
||||
"model": model,
|
||||
}
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - surfaced in chat.
|
||||
yield AgentError(str(exc))
|
||||
|
||||
|
||||
async def _collect_opencode_events(
|
||||
client: httpx.AsyncClient,
|
||||
headers: dict[str, str],
|
||||
session_id: str,
|
||||
emitted: dict[str, str],
|
||||
queue: asyncio.Queue[str | None],
|
||||
) -> None:
|
||||
try:
|
||||
for path in ("event.subscribe", "event/subscribe", "event"):
|
||||
try:
|
||||
async with client.stream("GET", f"/{path}", headers=headers) as response:
|
||||
response.raise_for_status()
|
||||
async for line in response.aiter_lines():
|
||||
if not line:
|
||||
continue
|
||||
if line.startswith("data:"):
|
||||
line = line[5:].strip()
|
||||
with suppress(Exception):
|
||||
event = json.loads(line)
|
||||
if not isinstance(event, dict):
|
||||
continue
|
||||
props = (
|
||||
event.get("properties")
|
||||
if isinstance(event.get("properties"), dict)
|
||||
else {}
|
||||
)
|
||||
if props.get("sessionID") != session_id:
|
||||
continue
|
||||
text = _text_from_event(event, emitted)
|
||||
if text:
|
||||
await queue.put(text)
|
||||
status = (
|
||||
props.get("status") if isinstance(props.get("status"), dict) else {}
|
||||
)
|
||||
if event.get("type") == "session.status" and status.get("type") == "idle":
|
||||
await queue.put(None)
|
||||
return
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
await queue.put(None)
|
||||
await queue.put(None)
|
||||
+13
-1
@@ -1208,6 +1208,9 @@ async def run_chat_task(
|
||||
nonlocal content, text_buffer
|
||||
from cptr.utils.agents.claude_code import run_claude_code_agent
|
||||
from cptr.utils.agents.codex import run_codex_agent
|
||||
from cptr.utils.agents.cursor import run_cursor_agent
|
||||
from cptr.utils.agents.grok import run_grok_agent
|
||||
from cptr.utils.agents.opencode import run_opencode_agent
|
||||
|
||||
chat_obj = await Chat.get_by_id(chat_id)
|
||||
chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
|
||||
@@ -1237,7 +1240,16 @@ async def run_chat_task(
|
||||
if isinstance(candidate, dict):
|
||||
resume_state = candidate
|
||||
|
||||
runner = run_codex_agent if agent_target.agent == "codex" else run_claude_code_agent
|
||||
runners = {
|
||||
"codex": run_codex_agent,
|
||||
"claude_code": run_claude_code_agent,
|
||||
"cursor": run_cursor_agent,
|
||||
"grok": run_grok_agent,
|
||||
"opencode": run_opencode_agent,
|
||||
}
|
||||
runner = runners.get(agent_target.agent)
|
||||
if runner is None:
|
||||
raise RuntimeError(f"Unsupported agent type: {agent_target.agent}")
|
||||
reasoning_buffer = ""
|
||||
async for event in runner(
|
||||
profile=agent_target.config,
|
||||
|
||||
@@ -24,7 +24,7 @@ class ApiModelTarget:
|
||||
class AgentModelTarget:
|
||||
kind: Literal["agent"]
|
||||
profile_id: str
|
||||
agent: Literal["codex", "claude_code"]
|
||||
agent: Literal["codex", "claude_code", "cursor", "grok", "opencode"]
|
||||
model: str
|
||||
full_model_id: str
|
||||
config: dict[str, Any]
|
||||
|
||||
Reference in new issue
Block a user