mirror of
https://github.com/open-webui/computer.git
synced 2026-11-22 21:50:43 -05:00
53 files changed
+4244
-199
No files matched your search
@@ -5,6 +5,21 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.7.0] - 2026-06-25
|
||||
|
||||
### Added
|
||||
|
||||
- 🤖 **Coding agents.** You can now connect coding agents as AI backends. Supported agents include Codex, Claude Code, Cursor, Grok, and OpenCode. Configure agent profiles from the new Agents tab in admin settings, and they show up as selectable models in the chat. Each agent runs in your workspace with full tool access, and conversations can be resumed where you left off.
|
||||
- ⚙️ **Agents admin panel.** A new Agents section in Settings lets you add, edit, and remove agent profiles. You can configure the command path, model list, approval and permission modes, and see at a glance whether each agent is installed and ready. Models can be left empty to auto-detect what the agent supports.
|
||||
- 🎙️ **Voice dictation in the terminal.** The mobile shortcut bar now has a microphone button that lets you dictate text directly into the terminal using speech recognition.
|
||||
- ℹ️ **System info modal.** A new "System info" option in the sidebar menu shows your machine's hostname, OS, CPU, memory, disk, and running processes in a dedicated modal instead of on the welcome screen.
|
||||
|
||||
### Changed
|
||||
|
||||
- 🏠 **Redesigned welcome screen.** The home page now highlights a "Continue" section that picks up your most recent workspace with context about what was happening (active tasks, running processes). Recent workspaces also show status signals so you can see which ones have work in progress.
|
||||
- 🏷️ **Renamed to Computer.** All visible references to "cptr" in the UI, notifications, and documentation now read "Computer" for clarity.
|
||||
- 🧹 **Code formatting cleanup.** Whitespace and formatting improvements across frontend components.
|
||||
|
||||
## [0.6.2] - 2026-06-25
|
||||
|
||||
### Added
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# cptr
|
||||
# Computer (cptr)
|
||||
|
||||

|
||||

|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
`cptr` (short for "computer") runs on your machine and serves your whole computer (files, terminal, editor, git) to any browser. It literally is your computer.
|
||||
|
||||
Use it from your phone, tablet, laptop, another computer, or the machine it's running on. Designed to feel native on every screen. Plug in an AI that can actually read, write, and run things on your machine, or bring your favourite terminal agent. Terminal multiplexer, parallel AI agents, full workstation, one tool, your computer, any device.
|
||||
Use it from your phone, tablet, laptop, another computer, or the machine it's running on. Designed to feel native on every screen. Connect your own AI via API key, or plug in a coding agent you already subscribe to and skip the key entirely. Terminal multiplexer, parallel AI agents, full workstation, one tool, your computer, any device.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -69,7 +69,7 @@ Or skip networking entirely and connect a [messaging bot](#messaging-bots) inste
|
||||
|
||||
## AI agent
|
||||
|
||||
Bring your own API key. Works with OpenAI, Anthropic, Ollama, or any OpenAI-compatible endpoint.
|
||||
Bring your own API key (OpenAI, Anthropic, Ollama, or any OpenAI-compatible endpoint), or connect a coding agent you already subscribe to.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
@@ -91,7 +91,15 @@ Bring your own API key. Works with OpenAI, Anthropic, Ollama, or any OpenAI-comp
|
||||
| 🔌 **Tool servers** | Connect external tools via MCP or OpenAPI. |
|
||||
| 🧠 **Context compaction** | Long conversations are automatically summarised to stay fast. |
|
||||
|
||||
Already have a favourite terminal agent? Claude Code, Codex, Gemini CLI, Cursor, Grok, OpenCode, Kilo Code, and Pi all plug straight in. Use the subscription you already pay for.
|
||||
## Coding agents
|
||||
|
||||
Connect a coding agent as a native backend and use the subscription you already pay for. No separate API key needed.
|
||||
|
||||
**Codex** · **Claude Code** · **Cursor** · **Grok** · **OpenCode**
|
||||
|
||||
Add an agent profile from Settings, pick your models, and it shows up in the model selector like any other provider. Conversations run inside your workspace with full tool access and resume where you left off.
|
||||
|
||||
Prefer to run agents yourself? Any terminal agent (Gemini CLI, Kilo Code, Pi, and others) works in the terminal tab the way it always has.
|
||||
|
||||
## Messaging bots
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="apple-mobile-web-app-title" content="cptr" />
|
||||
<meta name="apple-mobile-web-app-title" content="Computer" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<link rel="apple-touch-startup-image" href="/icon-512.png" />
|
||||
%sveltekit.head%
|
||||
|
||||
@@ -58,6 +58,63 @@ export const updateConfig = (config: Record<string, unknown>) =>
|
||||
method: 'PUT'
|
||||
});
|
||||
|
||||
// ── Agents ─────────────────────────────────────────────────
|
||||
|
||||
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';
|
||||
|
||||
export interface AgentProfile {
|
||||
id: string;
|
||||
agent: AgentType;
|
||||
name: string;
|
||||
mode: AgentMode;
|
||||
command: string;
|
||||
home: string | null;
|
||||
models: string[];
|
||||
default_model: string;
|
||||
approval_mode?: 'ask' | 'auto' | 'full';
|
||||
sandbox_mode?: 'read-only' | 'workspace-write' | 'danger-full-access';
|
||||
permission_mode?: 'default' | 'accept_edits' | 'bypass_permissions';
|
||||
launch_args?: string;
|
||||
api_endpoint?: string;
|
||||
server_url?: string;
|
||||
server_password?: string;
|
||||
}
|
||||
|
||||
export interface AgentsResponseProfile {
|
||||
id: string;
|
||||
agent: AgentType;
|
||||
name: string;
|
||||
config: AgentProfile;
|
||||
detected: {
|
||||
status: AgentStatus;
|
||||
command: string | null;
|
||||
version: string | null;
|
||||
message: string | null;
|
||||
models?: string[] | null;
|
||||
};
|
||||
available: boolean;
|
||||
implicit: boolean;
|
||||
model_ids: string[];
|
||||
}
|
||||
|
||||
export interface AgentsResponse {
|
||||
profiles: AgentsResponseProfile[];
|
||||
}
|
||||
|
||||
export const getAgents = async (): Promise<AgentsResponse> =>
|
||||
fetchJSON<AgentsResponse>('/api/admin/agents');
|
||||
|
||||
export const updateAgents = (profiles: AgentProfile[]): Promise<AgentsResponse> =>
|
||||
fetchJSON<AgentsResponse>('/api/admin/agents', {
|
||||
...jsonBody({ profiles }),
|
||||
method: 'PUT'
|
||||
});
|
||||
|
||||
export const refreshAgents = async (): Promise<AgentsResponse> =>
|
||||
fetchJSON<AgentsResponse>('/api/admin/agents/refresh', { method: 'POST' });
|
||||
|
||||
// ── Connections ─────────────────────────────────────────────
|
||||
|
||||
export interface Connection {
|
||||
@@ -118,7 +175,14 @@ export interface ModelConfigEntry {
|
||||
|
||||
export interface ModelConfigResponse {
|
||||
config: Record<string, ModelConfigEntry>;
|
||||
models: { id: string; name: string; provider: string; connection_id: string }[];
|
||||
models: {
|
||||
id: string;
|
||||
name: string;
|
||||
provider: string;
|
||||
connection_id: string;
|
||||
agent_id?: string;
|
||||
profile_id?: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export const getModelConfig = async (): Promise<ModelConfigResponse> =>
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
<script lang="ts">
|
||||
import Modal from '../Modal.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
import type { AgentProfile } from '$lib/apis/admin';
|
||||
|
||||
interface Props {
|
||||
profile: AgentProfile;
|
||||
isNew?: boolean;
|
||||
onclose: () => void;
|
||||
onsave: (profile: AgentProfile) => void;
|
||||
ondelete: () => void;
|
||||
}
|
||||
|
||||
let { profile, isNew = false, onclose, onsave, ondelete }: Props = $props();
|
||||
const fieldPrefix = `agent-profile-${Math.random().toString(36).slice(2)}`;
|
||||
|
||||
// svelte-ignore state_referenced_locally
|
||||
let draft = $state<AgentProfile>({
|
||||
...profile,
|
||||
models: [...(profile.models?.length ? profile.models : [])]
|
||||
});
|
||||
|
||||
function normalizeDraft(): AgentProfile {
|
||||
const currentModels = draft.models?.map((model) => model.trim()).filter(Boolean) || [];
|
||||
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() || defaultCommand(draft.agent),
|
||||
home: draft.home?.trim() || null,
|
||||
models,
|
||||
default_model: defaultModel,
|
||||
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">
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="p-4"
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) onsave(normalizeDraft());
|
||||
}}
|
||||
>
|
||||
<div class="flex items-center justify-between gap-3 mb-3">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{isNew ? $t('admin.agentsAddProfile') : draft.name}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="text-[13px] text-gray-400 dark:text-gray-600 hover:text-gray-700 dark:hover:text-gray-300 transition-colors"
|
||||
onclick={onclose}
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-3">
|
||||
<div class="flex-1">
|
||||
<label for={`${fieldPrefix}-name`} class="text-[10px] text-gray-400 dark:text-gray-600">
|
||||
{$t('admin.agentsProfileName')}
|
||||
</label>
|
||||
<input
|
||||
id={`${fieldPrefix}-name`}
|
||||
type="text"
|
||||
bind:value={draft.name}
|
||||
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"
|
||||
/>
|
||||
</div>
|
||||
<div class="w-32 shrink-0">
|
||||
<label for={`${fieldPrefix}-type`} class="text-[10px] text-gray-400 dark:text-gray-600">
|
||||
{$t('admin.agentsType')}
|
||||
</label>
|
||||
<select
|
||||
id={`${fieldPrefix}-type`}
|
||||
value={draft.agent}
|
||||
onchange={(e) => {
|
||||
const agent = e.currentTarget.value as AgentProfile['agent'];
|
||||
draft = {
|
||||
...draft,
|
||||
agent,
|
||||
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',
|
||||
launch_args: draft.launch_args || ''
|
||||
};
|
||||
}}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer"
|
||||
>
|
||||
<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>
|
||||
|
||||
<label for={`${fieldPrefix}-id`} class="text-[10px] text-gray-400 dark:text-gray-600 mt-2">
|
||||
{$t('admin.agentsProfileId')}
|
||||
</label>
|
||||
<input
|
||||
id={`${fieldPrefix}-id`}
|
||||
type="text"
|
||||
bind:value={draft.id}
|
||||
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}-command`} class="text-[10px] text-gray-400 dark:text-gray-600 mt-2">
|
||||
{$t('admin.agentsCommand')}
|
||||
</label>
|
||||
<input
|
||||
id={`${fieldPrefix}-command`}
|
||||
type="text"
|
||||
bind:value={draft.command}
|
||||
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"
|
||||
/>
|
||||
|
||||
<label for={`${fieldPrefix}-home`} class="text-[10px] text-gray-400 dark:text-gray-600 mt-2">
|
||||
{$t('admin.agentsHome')}
|
||||
</label>
|
||||
<input
|
||||
id={`${fieldPrefix}-home`}
|
||||
type="text"
|
||||
value={draft.home || ''}
|
||||
placeholder="Optional"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
oninput={(e) => (draft.home = e.currentTarget.value || null)}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
|
||||
/>
|
||||
|
||||
{#if draft.agent === 'claude_code'}
|
||||
<label
|
||||
for={`${fieldPrefix}-launch-args`}
|
||||
class="text-[10px] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>
|
||||
{$t('admin.agentsLaunchArgs')}
|
||||
</label>
|
||||
<input
|
||||
id={`${fieldPrefix}-launch-args`}
|
||||
type="text"
|
||||
bind:value={draft.launch_args}
|
||||
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 === '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}
|
||||
<button
|
||||
type="button"
|
||||
class="text-[13px] text-gray-400 hover:text-red-500 dark:hover:text-red-400 transition-colors duration-100"
|
||||
onclick={ondelete}
|
||||
title={$t('admin.agentsDeleteProfile')}
|
||||
>
|
||||
{$t('admin.agentsDeleteProfile')}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => onsave(normalizeDraft())}
|
||||
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100"
|
||||
>
|
||||
{$t('settings.save')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -0,0 +1,343 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import {
|
||||
getAgents,
|
||||
refreshAgents,
|
||||
updateAgents,
|
||||
type AgentProfile,
|
||||
type AgentsResponseProfile
|
||||
} from '$lib/apis/admin';
|
||||
import Icon from '$lib/components/Icon.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
import { refreshChatState } from '$lib/stores/chat';
|
||||
import AgentProfileModal from './AgentProfileModal.svelte';
|
||||
|
||||
type ModalState =
|
||||
| { mode: 'create'; profile: AgentProfile }
|
||||
| { mode: 'edit'; index: number; profile: AgentProfile };
|
||||
|
||||
let loading = $state(true);
|
||||
let saving = $state(false);
|
||||
let refreshing = $state(false);
|
||||
let profiles = $state<AgentProfile[]>([]);
|
||||
let detected = $state<Record<string, AgentsResponseProfile['detected']>>({});
|
||||
let available = $state<Record<string, boolean>>({});
|
||||
let saved = $state<Record<string, boolean>>({});
|
||||
let modal = $state<ModalState | null>(null);
|
||||
|
||||
const statusLabelKey: Record<string, string> = {
|
||||
ready: 'admin.agentsStatusReady',
|
||||
not_found: 'admin.agentsStatusNotFound',
|
||||
missing_dependency: 'admin.agentsStatusMissingDependency',
|
||||
auth_unknown: 'admin.agentsStatusAuthUnknown',
|
||||
error: 'admin.agentsStatusError'
|
||||
};
|
||||
|
||||
function normalizeProfile(profile: AgentProfile): AgentProfile {
|
||||
const models = profile.models?.map((m) => m.trim()).filter(Boolean);
|
||||
const nextModels = models.length ? models : [];
|
||||
const defaultModel = nextModels.includes(profile.default_model)
|
||||
? profile.default_model
|
||||
: nextModels[0] || '';
|
||||
return {
|
||||
...profile,
|
||||
id: profile.id.trim(),
|
||||
name: profile.name.trim() || profile.id.trim(),
|
||||
command: profile.command.trim() || defaultCommand(profile.agent),
|
||||
home: profile.home?.trim() || null,
|
||||
models: nextModels,
|
||||
default_model: defaultModel,
|
||||
launch_args: profile.launch_args?.trim() || '',
|
||||
api_endpoint: profile.api_endpoint?.trim() || '',
|
||||
server_url: profile.server_url?.trim() || '',
|
||||
server_password: profile.server_password?.trim() || ''
|
||||
};
|
||||
}
|
||||
|
||||
function applyResponse(data: { profiles: AgentsResponseProfile[] }) {
|
||||
profiles = data.profiles.map((entry) => entry.config);
|
||||
detected = Object.fromEntries(data.profiles.map((entry) => [entry.id, entry.detected]));
|
||||
available = Object.fromEntries(data.profiles.map((entry) => [entry.id, entry.available]));
|
||||
saved = Object.fromEntries(data.profiles.map((entry) => [entry.id, !entry.implicit]));
|
||||
}
|
||||
|
||||
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)) {
|
||||
suffix += 1;
|
||||
id = `${base}-${suffix}`;
|
||||
}
|
||||
return {
|
||||
id,
|
||||
agent,
|
||||
name: agentLabel(agent),
|
||||
mode: 'enabled',
|
||||
command: defaultCommand(agent),
|
||||
home: null,
|
||||
models: [],
|
||||
default_model: '',
|
||||
approval_mode: 'auto',
|
||||
sandbox_mode: 'workspace-write',
|
||||
permission_mode: 'default',
|
||||
launch_args: '',
|
||||
api_endpoint: '',
|
||||
server_url: '',
|
||||
server_password: ''
|
||||
};
|
||||
}
|
||||
|
||||
function profileSubtitle(profile: AgentProfile): string {
|
||||
const modelCount = profile.models?.length || 0;
|
||||
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;
|
||||
}
|
||||
|
||||
function statusTone(profile: AgentProfile): string {
|
||||
if (profile.mode === 'disabled') return 'bg-gray-300 dark:bg-gray-700';
|
||||
const status = detected[profile.id]?.status || 'error';
|
||||
if (available[profile.id] && status === 'ready') return 'bg-emerald-500 dark:bg-emerald-400';
|
||||
if (status === 'missing_dependency' || status === 'auth_unknown') {
|
||||
return 'bg-amber-400 dark:bg-amber-300';
|
||||
}
|
||||
return 'bg-gray-300 dark:bg-gray-700';
|
||||
}
|
||||
|
||||
function saveProfile(profile: AgentProfile) {
|
||||
const normalized = normalizeProfile(profile);
|
||||
const currentModal = modal;
|
||||
if (currentModal?.mode === 'edit') {
|
||||
const previousId = currentModal.profile.id;
|
||||
profiles = profiles.map((current, index) =>
|
||||
index === currentModal.index ? normalized : current
|
||||
);
|
||||
if (previousId !== normalized.id) {
|
||||
const { [previousId]: _removed, ...rest } = saved;
|
||||
saved = rest;
|
||||
}
|
||||
} else {
|
||||
profiles = [...profiles, normalized];
|
||||
}
|
||||
saved = { ...saved, [normalized.id]: true };
|
||||
modal = null;
|
||||
}
|
||||
|
||||
function deleteProfile() {
|
||||
const currentModal = modal;
|
||||
if (currentModal?.mode !== 'edit') {
|
||||
modal = null;
|
||||
return;
|
||||
}
|
||||
const profile = profiles[currentModal.index];
|
||||
profiles = profiles.filter((_, index) => index !== currentModal.index);
|
||||
if (profile) {
|
||||
const { [profile.id]: _removed, ...rest } = saved;
|
||||
saved = rest;
|
||||
}
|
||||
modal = null;
|
||||
}
|
||||
|
||||
function toggleProfile(e: Event, index: number) {
|
||||
e.stopPropagation();
|
||||
const profile = profiles[index];
|
||||
if (!profile) return;
|
||||
const mode = profile.mode === 'disabled' ? 'enabled' : 'disabled';
|
||||
profiles = profiles.map((current, i) => (i === index ? { ...current, mode } : current));
|
||||
saved = { ...saved, [profile.id]: true };
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const savedProfiles = profiles.filter((profile) => saved[profile.id]);
|
||||
if (savedProfiles.length === 0) {
|
||||
toast.success($t('settings.saved'));
|
||||
return;
|
||||
}
|
||||
saving = true;
|
||||
try {
|
||||
applyResponse(await updateAgents(savedProfiles.map(normalizeProfile)));
|
||||
await refreshChatState();
|
||||
toast.success($t('settings.saved'));
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : $t('admin.failedToSave'));
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
refreshing = true;
|
||||
try {
|
||||
applyResponse(await refreshAgents());
|
||||
await refreshChatState();
|
||||
} catch {
|
||||
toast.error($t('admin.failedToLoadConfig'));
|
||||
} finally {
|
||||
refreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
applyResponse(await getAgents());
|
||||
} catch {
|
||||
toast.error($t('admin.failedToLoadConfig'));
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col min-h-full">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white">{$t('admin.agents')}</h2>
|
||||
<div class="flex items-center gap-1">
|
||||
<button
|
||||
class="flex items-center justify-center w-6 h-6 rounded-lg text-gray-400 hover:text-gray-700 dark:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75 disabled:opacity-30"
|
||||
onclick={refresh}
|
||||
disabled={refreshing}
|
||||
title={$t('admin.agentsRefresh')}
|
||||
>
|
||||
{#if refreshing}
|
||||
<Spinner size={13} />
|
||||
{:else}
|
||||
<Icon name="refresh" size={13} />
|
||||
{/if}
|
||||
</button>
|
||||
<button
|
||||
class="flex items-center justify-center w-6 h-6 rounded-lg text-gray-400 hover:text-gray-700 dark:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
|
||||
onclick={() => (modal = { mode: 'create', profile: newProfile() })}
|
||||
title={$t('admin.agentsAddProfile')}
|
||||
>
|
||||
<Icon name="plus" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<div class="flex justify-center py-8">
|
||||
<Spinner size={16} />
|
||||
</div>
|
||||
{:else}
|
||||
<div class="divide-y divide-gray-100 dark:divide-white/5">
|
||||
{#each profiles as profile, index (profile.id)}
|
||||
<button
|
||||
class="group flex items-center gap-2 w-full min-h-9 py-1.5 text-left"
|
||||
onclick={() => (modal = { mode: 'edit', index, profile })}
|
||||
>
|
||||
<span class="flex-1 min-w-0">
|
||||
<span
|
||||
class="block text-[13px] truncate {profile.mode === 'disabled'
|
||||
? 'text-gray-400 dark:text-gray-600'
|
||||
: 'text-gray-700 dark:text-gray-300'}"
|
||||
>
|
||||
{profile.name}
|
||||
</span>
|
||||
<span class="block text-[11px] text-gray-400 dark:text-gray-600 truncate">
|
||||
{profileSubtitle(profile)}
|
||||
</span>
|
||||
{#if detected[profile.id]?.message}
|
||||
<span class="block text-[11px] text-gray-300 dark:text-gray-700 truncate">
|
||||
{detected[profile.id]?.message}
|
||||
</span>
|
||||
{/if}
|
||||
</span>
|
||||
<span
|
||||
class="hidden sm:flex items-center gap-1.5 shrink-0 text-[11px] text-gray-400 dark:text-gray-600"
|
||||
>
|
||||
<span class="w-1.5 h-1.5 rounded-full {statusTone(profile)}"></span>
|
||||
<span>{$t(statusKey(profile))}</span>
|
||||
</span>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="relative w-6 h-3.5 rounded-full shrink-0 cursor-pointer transition-colors duration-150
|
||||
{profile.mode !== 'disabled' ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
|
||||
role="switch"
|
||||
tabindex="-1"
|
||||
aria-checked={profile.mode !== 'disabled'}
|
||||
onclick={(e) => toggleProfile(e, index)}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleProfile(e, index);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
|
||||
{profile.mode !== 'disabled'
|
||||
? 'left-3 bg-white dark:bg-gray-900'
|
||||
: 'left-0.5 bg-white dark:bg-gray-500'}"
|
||||
></span>
|
||||
</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if profiles.length === 0}
|
||||
<p class="text-[13px] text-gray-400 dark:text-gray-600 py-4">No agent profiles</p>
|
||||
{/if}
|
||||
|
||||
<div class="mt-auto pt-6 flex items-center justify-between">
|
||||
<span class="text-xs text-gray-500">
|
||||
{profiles.length} profile{profiles.length === 1 ? '' : 's'}
|
||||
</span>
|
||||
<button
|
||||
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 disabled:opacity-50"
|
||||
onclick={save}
|
||||
disabled={saving}
|
||||
>
|
||||
{#if saving}
|
||||
<Spinner size={14} />
|
||||
{:else}
|
||||
{$t('settings.save')}
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if modal}
|
||||
<AgentProfileModal
|
||||
profile={modal.profile}
|
||||
isNew={modal.mode === 'create'}
|
||||
onclose={() => (modal = null)}
|
||||
onsave={saveProfile}
|
||||
ondelete={deleteProfile}
|
||||
/>
|
||||
{/if}
|
||||
@@ -61,12 +61,12 @@
|
||||
{ name: 'ARCH', desc: 'Machine architecture' },
|
||||
{ name: 'SHELL', desc: 'Default shell path' },
|
||||
{ name: 'HOME', desc: 'Home directory' },
|
||||
{ name: 'CPTR_VERSION', desc: 'cptr version' },
|
||||
{ name: 'CPTR_VERSION', desc: 'Computer version' },
|
||||
{ name: 'DATE', desc: 'Current date (ISO format)' },
|
||||
{ name: 'MODEL', desc: 'Model ID being used' }
|
||||
];
|
||||
|
||||
const DEFAULT_PROMPT_PLACEHOLDER = `You are Computer (cptr), a helpful assistant running inside the user's computer interface. You have access to tools to read, search, and modify files in the workspace, run commands, and use configured tools. Use them to help the user directly. Approach hard requests with initiative and persistence: make the best possible attempt, adapt as needed, and keep going unless a real constraint prevents progress.
|
||||
const DEFAULT_PROMPT_PLACEHOLDER = `You are Computer, a helpful assistant running inside the user's computer interface. You have access to tools to read, search, and modify files in the workspace, run commands, and use configured tools. Use them to help the user directly. Approach hard requests with initiative and persistence: make the best possible attempt, adapt as needed, and keep going unless a real constraint prevents progress.
|
||||
|
||||
{{CPTR_CONTEXT}}
|
||||
|
||||
|
||||
@@ -72,7 +72,9 @@
|
||||
|
||||
<div class="flex items-center justify-center h-dvh bg-white dark:bg-black p-6">
|
||||
<div class="w-full max-w-md">
|
||||
<h1 class="text-lg font-semibold tracking-tight text-gray-900 dark:text-white mb-3">cptr</h1>
|
||||
<h1 class="text-lg font-semibold tracking-tight text-gray-900 dark:text-white mb-3">
|
||||
Computer
|
||||
</h1>
|
||||
|
||||
{#if isSetup}
|
||||
<p class="text-xs text-gray-400 dark:text-gray-600 -mt-2 mb-3">
|
||||
|
||||
@@ -47,10 +47,7 @@
|
||||
|
||||
function onPointerUp(e: PointerEvent) {
|
||||
(e.currentTarget as HTMLElement).releasePointerCapture?.(e.pointerId);
|
||||
if (
|
||||
closeButtonEl &&
|
||||
(e.target === closeButtonEl || closeButtonEl.contains(e.target as Node))
|
||||
) {
|
||||
if (closeButtonEl && (e.target === closeButtonEl || closeButtonEl.contains(e.target as Node))) {
|
||||
return;
|
||||
}
|
||||
if (!moved) {
|
||||
@@ -74,22 +71,31 @@
|
||||
bind:this={closeButtonEl}
|
||||
class="absolute -top-0.5 -left-0.5 p-0.5 rounded-full opacity-0 group-hover:opacity-100 bg-gray-200 dark:bg-[#222] text-gray-500 dark:text-gray-400 hover:bg-gray-300 dark:hover:bg-[#333] hover:text-gray-700 dark:hover:text-gray-300 border-none cursor-pointer transition-opacity duration-150 z-10"
|
||||
aria-label={$t('a11y.dismissNotification')}
|
||||
onclick={(e) => { e.stopPropagation(); onclose(); }}
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
onclose();
|
||||
}}
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-3 h-3">
|
||||
<path d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z" />
|
||||
<path
|
||||
d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- Icon -->
|
||||
<div class="shrink-0 self-start -translate-y-0.5">
|
||||
<img src="/favicon.png" alt="cptr" class="w-5 h-5 rounded-full" />
|
||||
<img src="/favicon.png" alt="Computer" class="w-5 h-5 rounded-full" />
|
||||
</div>
|
||||
|
||||
<!-- Content -->
|
||||
<div class="min-w-0">
|
||||
{#if title}
|
||||
<div class="text-[13px] font-medium mb-0.5 overflow-hidden text-ellipsis whitespace-nowrap text-gray-900 dark:text-white">{title}</div>
|
||||
<div
|
||||
class="text-[13px] font-medium mb-0.5 overflow-hidden text-ellipsis whitespace-nowrap text-gray-900 dark:text-white"
|
||||
>
|
||||
{title}
|
||||
</div>
|
||||
{/if}
|
||||
{#if content}
|
||||
<div class="text-xs text-gray-500 dark:text-[#aaa] font-normal line-clamp-2">{content}</div>
|
||||
@@ -102,4 +108,3 @@
|
||||
min-width: var(--width, 300px);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { appVersion, showChangelog, updateAvailable, latestVersion } from '$lib/stores';
|
||||
|
||||
const REPO_URL = 'https://github.com/open-webui/computer';
|
||||
const SHARE_TEXT = 'Check out cptr. Your computer, from anywhere.';
|
||||
const SHARE_TEXT = 'Check out Computer. Your computer, from anywhere.';
|
||||
|
||||
const shareLinks = [
|
||||
{
|
||||
@@ -39,7 +39,7 @@
|
||||
href="https://github.com/open-webui/computer"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="text-xs font-semibold text-gray-900 dark:text-white hover:underline">cptr</a
|
||||
class="text-xs font-semibold text-gray-900 dark:text-white hover:underline">Computer</a
|
||||
>
|
||||
{#if $appVersion}
|
||||
<button
|
||||
@@ -104,4 +104,3 @@
|
||||
<p class="text-[11px] text-gray-300 dark:text-gray-700 pt-4">
|
||||
{$t('about.createdBy')}
|
||||
</p>
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
import About from './Settings/About.svelte';
|
||||
import Users from './Admin/Users.svelte';
|
||||
import Connections from './Admin/Connections.svelte';
|
||||
import Agents from './Admin/Agents.svelte';
|
||||
import Models from './Admin/Models.svelte';
|
||||
import Messaging from './Admin/Messaging.svelte';
|
||||
import Gateway from './Admin/Gateway.svelte';
|
||||
@@ -30,6 +31,7 @@
|
||||
| 'about'
|
||||
| 'users'
|
||||
| 'connections'
|
||||
| 'agents'
|
||||
| 'models'
|
||||
| 'messaging'
|
||||
| 'gateway'
|
||||
@@ -56,6 +58,7 @@
|
||||
const adminTabIds: Tab[] = [
|
||||
'users',
|
||||
'connections',
|
||||
'agents',
|
||||
'models',
|
||||
'messaging',
|
||||
'gateway',
|
||||
@@ -81,6 +84,7 @@
|
||||
const adminTabs: { id: Tab; label: string; icon: string }[] = $derived([
|
||||
{ id: 'users', label: $t('admin.users'), icon: 'user' },
|
||||
{ id: 'connections', label: $t('admin.connections'), icon: 'plug' },
|
||||
{ id: 'agents', label: $t('admin.agents'), icon: 'terminal' },
|
||||
{ id: 'models', label: $t('admin.models'), icon: 'cube' },
|
||||
{ id: 'messaging', label: $t('admin.messaging'), icon: 'chat-bubble' },
|
||||
{ id: 'gateway', label: $t('admin.gateway.tab'), icon: 'gateway' },
|
||||
@@ -168,11 +172,11 @@
|
||||
</nav>
|
||||
|
||||
<div class="flex-1 overflow-y-auto min-h-0 p-4 md:px-5">
|
||||
{#if activeTab === 'general'}
|
||||
<General />
|
||||
{:else if activeTab === 'memory'}
|
||||
<Memory />
|
||||
{:else if activeTab === 'pwa' && showPwaSettings}
|
||||
{#if activeTab === 'general'}
|
||||
<General />
|
||||
{:else if activeTab === 'memory'}
|
||||
<Memory />
|
||||
{:else if activeTab === 'pwa' && showPwaSettings}
|
||||
<PWA />
|
||||
{:else if activeTab === 'keyboard'}
|
||||
<Keyboard />
|
||||
@@ -184,6 +188,8 @@
|
||||
<Users />
|
||||
{:else if activeTab === 'connections'}
|
||||
<Connections />
|
||||
{:else if activeTab === 'agents'}
|
||||
<Agents />
|
||||
{:else if activeTab === 'models'}
|
||||
<Models />
|
||||
{:else if activeTab === 'messaging'}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
<script lang="ts">
|
||||
import { activeTab } from '$lib/stores';
|
||||
import { i18next } from '$lib/i18n';
|
||||
|
||||
let visible = $state(false);
|
||||
let ctrlHeld = $state(false);
|
||||
let dictating = $state(false);
|
||||
let dictationRecognition: any = null;
|
||||
let touchHandled = false;
|
||||
|
||||
// Show on touch devices when terminal is active
|
||||
@@ -51,10 +54,75 @@
|
||||
window.dispatchEvent(new CustomEvent('cptr:terminal-input', { detail: key }));
|
||||
}
|
||||
|
||||
function startDictation() {
|
||||
const SpeechRecognition =
|
||||
(window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
|
||||
if (!SpeechRecognition) {
|
||||
alert(i18next.t('chat.dictate.unsupported'));
|
||||
return;
|
||||
}
|
||||
|
||||
const recognition = new SpeechRecognition();
|
||||
dictationRecognition = recognition;
|
||||
recognition.continuous = true;
|
||||
recognition.interimResults = false;
|
||||
recognition.lang = navigator.language || 'en-US';
|
||||
|
||||
recognition.onresult = (event: any) => {
|
||||
let text = '';
|
||||
for (let i = event.resultIndex; i < event.results.length; i++) {
|
||||
const result = event.results[i];
|
||||
if (result?.isFinal) text += ` ${result[0]?.transcript || ''}`;
|
||||
}
|
||||
text = text.trim();
|
||||
if (text) sendKey(text);
|
||||
};
|
||||
|
||||
recognition.onerror = () => {
|
||||
dictating = false;
|
||||
dictationRecognition = null;
|
||||
};
|
||||
|
||||
recognition.onend = () => {
|
||||
dictating = false;
|
||||
dictationRecognition = null;
|
||||
};
|
||||
|
||||
try {
|
||||
recognition.start();
|
||||
dictating = true;
|
||||
} catch {
|
||||
dictating = false;
|
||||
dictationRecognition = null;
|
||||
}
|
||||
}
|
||||
|
||||
function stopDictation() {
|
||||
const recognition = dictationRecognition;
|
||||
dictationRecognition = null;
|
||||
dictating = false;
|
||||
try {
|
||||
recognition?.stop();
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function toggleDictation() {
|
||||
if (dictating) stopDictation();
|
||||
else startDictation();
|
||||
}
|
||||
|
||||
function toggleCtrl() {
|
||||
ctrlHeld = !ctrlHeld;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!visible && dictating) stopDictation();
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
return () => stopDictation();
|
||||
});
|
||||
|
||||
const keys = [
|
||||
{ label: 'Tab', value: '\t' },
|
||||
{ label: 'Esc', value: '\x1b' },
|
||||
@@ -73,6 +141,40 @@
|
||||
|
||||
{#if visible}
|
||||
<div class="shortcut-bar">
|
||||
<button
|
||||
class="key inline-flex items-center justify-center"
|
||||
class:active={dictating}
|
||||
aria-label="Dictate terminal input"
|
||||
title="Dictate terminal input"
|
||||
onmousedown={(e) => e.preventDefault()}
|
||||
ontouchstart={(e) => {
|
||||
e.preventDefault();
|
||||
touchHandled = true;
|
||||
toggleDictation();
|
||||
}}
|
||||
onclick={() => {
|
||||
if (touchHandled) {
|
||||
touchHandled = false;
|
||||
return;
|
||||
}
|
||||
toggleDictation();
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
class="size-3.5"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.75"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<rect x="9" y="2" width="6" height="12" rx="3" />
|
||||
<path d="M5 10a7 7 0 0 0 14 0" />
|
||||
<line x1="12" y1="19" x2="12" y2="22" />
|
||||
<line x1="8" y1="22" x2="16" y2="22" />
|
||||
</svg>
|
||||
</button>
|
||||
{#each keys as key}
|
||||
{#if key.value === '__ctrl__'}
|
||||
<button
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
import DirectoryPicker from './DirectoryPicker.svelte';
|
||||
import DropdownMenu from './DropdownMenu.svelte';
|
||||
import SettingsModal from './SettingsModal.svelte';
|
||||
import SystemInfoModal from './SystemInfoModal.svelte';
|
||||
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import { session, clearSession } from '$lib/session';
|
||||
@@ -34,6 +35,7 @@
|
||||
let showPicker = $state(false);
|
||||
let showMenu = $state(false);
|
||||
let showSettings = $state(false);
|
||||
let showSystemInfo = $state(false);
|
||||
let settingsTab = $state<string>('general');
|
||||
let wsMenuPath = $state<string | null>(null);
|
||||
let wsMenuAnchor = $state<HTMLElement | null>(null);
|
||||
@@ -214,6 +216,11 @@
|
||||
showSettings = true;
|
||||
}
|
||||
|
||||
function openSystemInfo() {
|
||||
showMenu = false;
|
||||
showSystemInfo = true;
|
||||
}
|
||||
|
||||
function logout() {
|
||||
clearSession();
|
||||
}
|
||||
@@ -282,7 +289,7 @@
|
||||
e.preventDefault();
|
||||
goto('/');
|
||||
if (typeof window !== 'undefined' && window.innerWidth < 768) sidebarOpen.set(false);
|
||||
}}><img src="/favicon.png" alt="cptr logo" class="w-4 h-4" />cptr</a
|
||||
}}><img src="/favicon.png" alt="Computer logo" class="w-4 h-4" />Computer</a
|
||||
>
|
||||
<button
|
||||
class="flex items-center justify-center w-7 h-7 rounded-lg text-gray-300 hover:text-gray-500 dark:text-gray-600 dark:hover:text-gray-400 transition-colors duration-100"
|
||||
@@ -503,6 +510,11 @@
|
||||
shortcut: formatChord($keybindings.openSettings),
|
||||
onclick: openSettings
|
||||
},
|
||||
{
|
||||
label: 'System info',
|
||||
icon: 'info',
|
||||
onclick: openSystemInfo
|
||||
},
|
||||
{ divider: true, label: '', onclick: () => {} },
|
||||
{ label: $t('sidebar.logOut'), icon: 'log-out', onclick: logout }
|
||||
]}
|
||||
@@ -538,6 +550,10 @@
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if showSystemInfo}
|
||||
<SystemInfoModal onclose={() => (showSystemInfo = false)} />
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
@reference "../../app.css";
|
||||
|
||||
|
||||
@@ -28,9 +28,10 @@
|
||||
interface Props {
|
||||
system: SystemInfo;
|
||||
processes?: Process[];
|
||||
defaultOpen?: boolean;
|
||||
}
|
||||
|
||||
let { system: sys, processes = [] }: Props = $props();
|
||||
let { system: sys, processes = [], defaultOpen = false }: Props = $props();
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1073741824) return `${(bytes / 1048576).toFixed(0)} MB`;
|
||||
@@ -64,7 +65,7 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<Collapsible title={$t('system.title')} {summary}>
|
||||
<Collapsible title={$t('system.title')} {summary} open={defaultOpen}>
|
||||
<div class="flex flex-col gap-3">
|
||||
{#if sys.cpu_usage != null}
|
||||
<div>
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import Modal from './Modal.svelte';
|
||||
import SystemInfo from './SystemInfo.svelte';
|
||||
import Spinner from './common/Spinner.svelte';
|
||||
import { getWelcome } from '$lib/apis/state';
|
||||
|
||||
interface Props {
|
||||
onclose: () => void;
|
||||
}
|
||||
|
||||
let { onclose }: Props = $props();
|
||||
|
||||
let loading = $state(true);
|
||||
let welcomeData = $state<{
|
||||
hostname?: string;
|
||||
system?: {
|
||||
os: string;
|
||||
arch: string;
|
||||
python: string;
|
||||
cpu_count: number;
|
||||
memory_total?: number;
|
||||
memory_available?: number;
|
||||
disk_total?: number;
|
||||
disk_used?: number;
|
||||
disk_free?: number;
|
||||
uptime_seconds?: number;
|
||||
load_avg?: number[];
|
||||
cpu_usage?: number;
|
||||
network?: { name: string; ip: string }[];
|
||||
};
|
||||
processes?: { pid: number; cpu: number; mem: number; name: string }[];
|
||||
} | null>(null);
|
||||
|
||||
onMount(() => {
|
||||
getWelcome()
|
||||
.then((data) => {
|
||||
welcomeData = data as typeof welcomeData;
|
||||
})
|
||||
.catch(() => {
|
||||
welcomeData = null;
|
||||
})
|
||||
.finally(() => {
|
||||
loading = false;
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<Modal {onclose} class="w-full max-w-[420px] mx-4">
|
||||
<div class="px-4 py-3.5">
|
||||
<div class="mb-3 flex items-baseline justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white">System info</h2>
|
||||
{#if welcomeData?.hostname}
|
||||
<p class="mt-0.5 truncate font-mono text-[11px] text-gray-400 dark:text-gray-600">
|
||||
{welcomeData.hostname}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<div class="flex h-28 items-center justify-center">
|
||||
<Spinner size={18} />
|
||||
</div>
|
||||
{:else if welcomeData?.system}
|
||||
<SystemInfo system={welcomeData.system} processes={welcomeData.processes ?? []} defaultOpen />
|
||||
{:else}
|
||||
<div class="py-8 text-center text-xs text-gray-400 dark:text-gray-600">
|
||||
System info unavailable
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -193,6 +193,8 @@
|
||||
const label = args.background ? 'Background sub-agent' : 'Sub-agent';
|
||||
return `${label}: "${t.length > 60 ? t.slice(0, 60) + '…' : t}"`;
|
||||
}
|
||||
case 'agent_tool':
|
||||
return args.title || 'Agent tool';
|
||||
default: {
|
||||
// External tool: {server_id}_{tool_name} → "tool_name (server_id)"
|
||||
const idx = name.indexOf('_');
|
||||
@@ -270,7 +272,10 @@
|
||||
for (const url of structuredImageUrls) {
|
||||
const escapedUrl = escapeRegExp(url);
|
||||
cleaned = cleaned.replace(new RegExp(`!\\[[^\\]]*\\]\\(${escapedUrl}\\)`, 'g'), '');
|
||||
cleaned = cleaned.replace(new RegExp(`(^|\\n)[ \\t]*${escapedUrl}[ \\t]*(?=\\n|$)`, 'g'), '$1');
|
||||
cleaned = cleaned.replace(
|
||||
new RegExp(`(^|\\n)[ \\t]*${escapedUrl}[ \\t]*(?=\\n|$)`, 'g'),
|
||||
'$1'
|
||||
);
|
||||
}
|
||||
return cleaned.replace(/\n{3,}/g, '\n\n').trim();
|
||||
}
|
||||
|
||||
@@ -212,7 +212,7 @@
|
||||
"home.start": "Start",
|
||||
"home.openFolder": "Ordner öffnen...",
|
||||
"home.recent": "Zuletzt verwendet",
|
||||
"home.folders": "Ordner",
|
||||
"home.folders": "Vorgeschlagen",
|
||||
"home.chatComingSoon": "Chat (demnächst verfügbar)",
|
||||
"directory.cancel": "Abbrechen",
|
||||
"directory.open": "\"{{name}}\" öffnen",
|
||||
@@ -293,7 +293,7 @@
|
||||
"general.webhookUrlHint": "Unterstützt Slack, Discord, Teams und generische JSON-Webhooks.",
|
||||
"general.updates": "Aktualisierungen",
|
||||
"general.updateNotifications": "Update-Benachrichtigungen",
|
||||
"general.updateNotificationsDesc": "Eine Benachrichtigung anzeigen, wenn eine neue Version von cptr verfügbar ist.",
|
||||
"general.updateNotificationsDesc": "Eine Benachrichtigung anzeigen, wenn eine neue Version von Computer verfügbar ist.",
|
||||
"general.messageQueue": "Nachrichtenwarteschlange",
|
||||
"general.queue": "Warteschlange",
|
||||
"general.interrupt": "Unterbrechen",
|
||||
@@ -597,7 +597,7 @@
|
||||
"admin.gateway.keyWarning": "Dieser Schlüssel wird nur einmal angezeigt. Speichern Sie ihn sicher.",
|
||||
"admin.gateway.loadError": "API-Schlüssel konnten nicht geladen werden",
|
||||
"admin.gateway.model": "Antwortmodell",
|
||||
"admin.gateway.modelDescription": "Gateway-Clients wählen einen Arbeitsbereich; cptr verwendet dieses Modell für die Antwort.",
|
||||
"admin.gateway.modelDescription": "Gateway-Clients wählen einen Arbeitsbereich; Computer verwendet dieses Modell für die Antwort.",
|
||||
"admin.gateway.modelFallback": "Arbeitsbereich-/Standardmodell verwenden",
|
||||
"admin.gateway.modelSaveError": "Gateway-Modell konnte nicht gespeichert werden",
|
||||
"admin.gateway.newKey": "Neuer API-Schlüssel erstellt. Jetzt kopieren",
|
||||
|
||||
@@ -235,6 +235,27 @@
|
||||
"admin.minCharsPassword": "Min 6 characters",
|
||||
|
||||
"admin.connections": "Connections",
|
||||
"admin.agents": "Agents",
|
||||
"admin.agentsRefresh": "Refresh",
|
||||
"admin.agentsAddProfile": "Add profile",
|
||||
"admin.agentsDeleteProfile": "Delete",
|
||||
"admin.agentsProfileName": "Name",
|
||||
"admin.agentsProfileId": "Profile ID",
|
||||
"admin.agentsType": "Agent",
|
||||
"admin.agentsCommand": "Command",
|
||||
"admin.agentsHome": "Home path",
|
||||
"admin.agentsApprovalMode": "Approval mode",
|
||||
"admin.agentsSandboxMode": "Sandbox",
|
||||
"admin.agentsPermissionMode": "Permission mode",
|
||||
"admin.agentsLaunchArgs": "Launch arguments",
|
||||
"admin.agentsApiEndpoint": "API endpoint",
|
||||
"admin.agentsServerUrl": "Server URL",
|
||||
"admin.agentsServerPassword": "Server password",
|
||||
"admin.agentsStatusReady": "Ready",
|
||||
"admin.agentsStatusNotFound": "Not found",
|
||||
"admin.agentsStatusMissingDependency": "Missing dependency",
|
||||
"admin.agentsStatusAuthUnknown": "Auth unknown",
|
||||
"admin.agentsStatusError": "Error",
|
||||
|
||||
"connections.loadError": "Failed to load connections",
|
||||
"connections.fieldsRequired": "Base URL and API key required",
|
||||
@@ -262,7 +283,7 @@
|
||||
"home.start": "Start",
|
||||
"home.openFolder": "Open Folder...",
|
||||
"home.recent": "Recent",
|
||||
"home.folders": "Folders",
|
||||
"home.folders": "Suggested",
|
||||
"home.chatComingSoon": "Chat (coming soon)",
|
||||
|
||||
"directory.cancel": "Cancel",
|
||||
@@ -379,7 +400,7 @@
|
||||
"general.webhookUrlHint": "Supports Slack, Discord, Teams, and generic JSON webhooks.",
|
||||
"general.updates": "Updates",
|
||||
"general.updateNotifications": "Update notifications",
|
||||
"general.updateNotificationsDesc": "Show a toast when a new version of cptr is available.",
|
||||
"general.updateNotificationsDesc": "Show a toast when a new version of Computer is available.",
|
||||
"general.messageQueue": "Message queue",
|
||||
"general.queue": "Queue",
|
||||
"general.interrupt": "Interrupt",
|
||||
@@ -482,7 +503,7 @@
|
||||
"admin.gateway.description": "Generate API keys to connect Open WebUI or any OpenAI-compatible client to your workspaces.",
|
||||
"admin.gateway.loadError": "Failed to load API keys",
|
||||
"admin.gateway.model": "Response model",
|
||||
"admin.gateway.modelDescription": "Gateway clients choose a workspace; cptr uses this model to generate the response.",
|
||||
"admin.gateway.modelDescription": "Gateway clients choose a workspace; Computer uses this model to generate the response.",
|
||||
"admin.gateway.modelFallback": "Use workspace/default model",
|
||||
"admin.gateway.modelSaveError": "Failed to save gateway model",
|
||||
"admin.gateway.createKey": "Create key",
|
||||
|
||||
@@ -212,7 +212,7 @@
|
||||
"home.start": "Inicio",
|
||||
"home.openFolder": "Abrir carpeta...",
|
||||
"home.recent": "Recientes",
|
||||
"home.folders": "Carpetas",
|
||||
"home.folders": "Sugeridos",
|
||||
"home.chatComingSoon": "Chat (próximamente)",
|
||||
"directory.cancel": "Cancelar",
|
||||
"directory.open": "Abrir \"{{name}}\"",
|
||||
@@ -293,7 +293,7 @@
|
||||
"general.webhookUrlHint": "Compatible con Slack, Discord, Teams y webhooks JSON genéricos.",
|
||||
"general.updates": "Actualizaciones",
|
||||
"general.updateNotifications": "Notificaciones de actualización",
|
||||
"general.updateNotificationsDesc": "Mostrar un aviso cuando hay una nueva versión de cptr disponible.",
|
||||
"general.updateNotificationsDesc": "Mostrar un aviso cuando hay una nueva versión de Computer disponible.",
|
||||
"general.messageQueue": "Cola de mensajes",
|
||||
"general.queue": "Cola",
|
||||
"general.interrupt": "Interrumpir",
|
||||
@@ -597,7 +597,7 @@
|
||||
"admin.gateway.keyWarning": "Esta clave solo se mostrará una vez. Guárdala de forma segura.",
|
||||
"admin.gateway.loadError": "Error al cargar las claves API",
|
||||
"admin.gateway.model": "Modelo de respuesta",
|
||||
"admin.gateway.modelDescription": "Los clientes gateway eligen un espacio de trabajo; cptr usa este modelo para generar la respuesta.",
|
||||
"admin.gateway.modelDescription": "Los clientes gateway eligen un espacio de trabajo; Computer usa este modelo para generar la respuesta.",
|
||||
"admin.gateway.modelFallback": "Usar modelo del espacio de trabajo/predeterminado",
|
||||
"admin.gateway.modelSaveError": "Error al guardar el modelo gateway",
|
||||
"admin.gateway.newKey": "Nueva clave API creada. Cópiala ahora",
|
||||
|
||||
@@ -212,7 +212,7 @@
|
||||
"home.start": "Démarrer",
|
||||
"home.openFolder": "Ouvrir un dossier...",
|
||||
"home.recent": "Récents",
|
||||
"home.folders": "Dossiers",
|
||||
"home.folders": "Suggérés",
|
||||
"home.chatComingSoon": "Chat (bientôt disponible)",
|
||||
"directory.cancel": "Annuler",
|
||||
"directory.open": "Ouvrir « {{name}} »",
|
||||
@@ -293,7 +293,7 @@
|
||||
"general.webhookUrlHint": "Prend en charge Slack, Discord, Teams et les webhooks JSON génériques.",
|
||||
"general.updates": "Mises à jour",
|
||||
"general.updateNotifications": "Notifications de mise à jour",
|
||||
"general.updateNotificationsDesc": "Afficher une notification lorsqu'une nouvelle version de cptr est disponible.",
|
||||
"general.updateNotificationsDesc": "Afficher une notification lorsqu'une nouvelle version de Computer est disponible.",
|
||||
"general.messageQueue": "File de messages",
|
||||
"general.queue": "File",
|
||||
"general.interrupt": "Interrompre",
|
||||
@@ -596,7 +596,7 @@
|
||||
"admin.gateway.keyWarning": "Cette clé ne sera affichée qu'une seule fois. Conservez-la en sécurité.",
|
||||
"admin.gateway.loadError": "Échec du chargement des clés API",
|
||||
"admin.gateway.model": "Modèle de réponse",
|
||||
"admin.gateway.modelDescription": "Les clients passerelle choisissent un espace de travail ; cptr utilise ce modèle pour générer la réponse.",
|
||||
"admin.gateway.modelDescription": "Les clients passerelle choisissent un espace de travail ; Computer utilise ce modèle pour générer la réponse.",
|
||||
"admin.gateway.modelFallback": "Utiliser le modèle de l'espace de travail/par défaut",
|
||||
"admin.gateway.modelSaveError": "Échec de l'enregistrement du modèle passerelle",
|
||||
"admin.gateway.newKey": "Nouvelle clé API créée. Copiez-la maintenant",
|
||||
|
||||
@@ -212,7 +212,7 @@
|
||||
"home.start": "スタート",
|
||||
"home.openFolder": "フォルダを開く...",
|
||||
"home.recent": "最近",
|
||||
"home.folders": "フォルダ",
|
||||
"home.folders": "おすすめ",
|
||||
"home.chatComingSoon": "チャット(近日公開)",
|
||||
"directory.cancel": "キャンセル",
|
||||
"directory.open": "「{{name}}」を開く",
|
||||
@@ -293,7 +293,7 @@
|
||||
"general.webhookUrlHint": "Slack、Discord、Teams、汎用JSONウェブフックに対応。",
|
||||
"general.updates": "アップデート",
|
||||
"general.updateNotifications": "アップデート通知",
|
||||
"general.updateNotificationsDesc": "cptrの新しいバージョンが利用可能な場合にトーストを表示します。",
|
||||
"general.updateNotificationsDesc": "Computerの新しいバージョンが利用可能な場合にトーストを表示します。",
|
||||
"general.messageQueue": "メッセージキュー",
|
||||
"general.queue": "キュー",
|
||||
"general.interrupt": "中断",
|
||||
@@ -597,7 +597,7 @@
|
||||
"admin.gateway.keyWarning": "このキーは一度だけ表示されます。安全に保管してください。",
|
||||
"admin.gateway.loadError": "APIキーの読み込みに失敗しました",
|
||||
"admin.gateway.model": "応答モデル",
|
||||
"admin.gateway.modelDescription": "ゲートウェイクライアントがワークスペースを選択し、cptrがこのモデルで応答を生成します。",
|
||||
"admin.gateway.modelDescription": "ゲートウェイクライアントがワークスペースを選択し、Computerがこのモデルで応答を生成します。",
|
||||
"admin.gateway.modelFallback": "ワークスペース/デフォルトモデルを使用",
|
||||
"admin.gateway.modelSaveError": "ゲートウェイモデルの保存に失敗しました",
|
||||
"admin.gateway.newKey": "新しいAPIキーが作成されました。今すぐコピーしてください",
|
||||
|
||||
@@ -212,7 +212,7 @@
|
||||
"home.start": "시작",
|
||||
"home.openFolder": "폴더 열기...",
|
||||
"home.recent": "최근",
|
||||
"home.folders": "폴더",
|
||||
"home.folders": "추천",
|
||||
"home.chatComingSoon": "채팅 (출시 예정)",
|
||||
"directory.cancel": "취소",
|
||||
"directory.open": "\"{{name}}\" 열기",
|
||||
@@ -293,7 +293,7 @@
|
||||
"general.webhookUrlHint": "Slack, Discord, Teams 및 일반 JSON 웹훅을 지원합니다.",
|
||||
"general.updates": "업데이트",
|
||||
"general.updateNotifications": "업데이트 알림",
|
||||
"general.updateNotificationsDesc": "cptr의 새 버전이 사용 가능할 때 알림을 표시합니다.",
|
||||
"general.updateNotificationsDesc": "Computer의 새 버전이 사용 가능할 때 알림을 표시합니다.",
|
||||
"general.messageQueue": "메시지 대기열",
|
||||
"general.queue": "대기열",
|
||||
"general.interrupt": "중단",
|
||||
@@ -597,7 +597,7 @@
|
||||
"admin.gateway.keyWarning": "이 키는 한 번만 표시됩니다. 안전하게 보관하세요.",
|
||||
"admin.gateway.loadError": "API 키 로드에 실패했습니다",
|
||||
"admin.gateway.model": "응답 모델",
|
||||
"admin.gateway.modelDescription": "게이트웨이 클라이언트가 작업 공간을 선택하고, cptr이 이 모델로 응답을 생성합니다.",
|
||||
"admin.gateway.modelDescription": "게이트웨이 클라이언트가 작업 공간을 선택하고, Computer가 이 모델로 응답을 생성합니다.",
|
||||
"admin.gateway.modelFallback": "작업 공간/기본 모델 사용",
|
||||
"admin.gateway.modelSaveError": "게이트웨이 모델 저장에 실패했습니다",
|
||||
"admin.gateway.newKey": "새 API 키가 생성되었습니다. 지금 복사하세요",
|
||||
|
||||
@@ -212,7 +212,7 @@
|
||||
"home.start": "Início",
|
||||
"home.openFolder": "Abrir pasta...",
|
||||
"home.recent": "Recentes",
|
||||
"home.folders": "Pastas",
|
||||
"home.folders": "Sugeridos",
|
||||
"home.chatComingSoon": "Chat (em breve)",
|
||||
"directory.cancel": "Cancelar",
|
||||
"directory.open": "Abrir \"{{name}}\"",
|
||||
@@ -293,7 +293,7 @@
|
||||
"general.webhookUrlHint": "Suporta Slack, Discord, Teams e webhooks JSON genéricos.",
|
||||
"general.updates": "Atualizações",
|
||||
"general.updateNotifications": "Notificações de atualização",
|
||||
"general.updateNotificationsDesc": "Mostrar um aviso quando uma nova versão do cptr estiver disponível.",
|
||||
"general.updateNotificationsDesc": "Mostrar um aviso quando uma nova versão do Computer estiver disponível.",
|
||||
"general.messageQueue": "Fila de mensagens",
|
||||
"general.queue": "Fila",
|
||||
"general.interrupt": "Interromper",
|
||||
@@ -597,7 +597,7 @@
|
||||
"admin.gateway.keyWarning": "Esta chave será exibida apenas uma vez. Guarde-a com segurança.",
|
||||
"admin.gateway.loadError": "Falha ao carregar as chaves API",
|
||||
"admin.gateway.model": "Modelo de resposta",
|
||||
"admin.gateway.modelDescription": "Clientes gateway escolhem um workspace; cptr usa este modelo para gerar a resposta.",
|
||||
"admin.gateway.modelDescription": "Clientes gateway escolhem um workspace; Computer usa este modelo para gerar a resposta.",
|
||||
"admin.gateway.modelFallback": "Usar modelo do workspace/padrão",
|
||||
"admin.gateway.modelSaveError": "Falha ao salvar o modelo gateway",
|
||||
"admin.gateway.newKey": "Nova chave API criada. Copie-a agora",
|
||||
|
||||
@@ -212,7 +212,7 @@
|
||||
"home.start": "Начало",
|
||||
"home.openFolder": "Открыть папку...",
|
||||
"home.recent": "Недавние",
|
||||
"home.folders": "Папки",
|
||||
"home.folders": "Предложенные",
|
||||
"home.chatComingSoon": "Чат (скоро)",
|
||||
"directory.cancel": "Отмена",
|
||||
"directory.open": "Открыть \"{{name}}\"",
|
||||
@@ -293,7 +293,7 @@
|
||||
"general.webhookUrlHint": "Поддерживает Slack, Discord, Teams и универсальные JSON-вебхуки.",
|
||||
"general.updates": "Обновления",
|
||||
"general.updateNotifications": "Уведомления об обновлениях",
|
||||
"general.updateNotificationsDesc": "Показывать уведомление, когда доступна новая версия cptr.",
|
||||
"general.updateNotificationsDesc": "Показывать уведомление, когда доступна новая версия Computer.",
|
||||
"general.messageQueue": "Очередь сообщений",
|
||||
"general.queue": "Очередь",
|
||||
"general.interrupt": "Прервать",
|
||||
@@ -597,7 +597,7 @@
|
||||
"admin.gateway.keyWarning": "Этот ключ будет показан только один раз. Сохраните его надёжно.",
|
||||
"admin.gateway.loadError": "Не удалось загрузить API-ключи",
|
||||
"admin.gateway.model": "Модель ответа",
|
||||
"admin.gateway.modelDescription": "Клиенты шлюза выбирают рабочее пространство; cptr использует эту модель для генерации ответа.",
|
||||
"admin.gateway.modelDescription": "Клиенты шлюза выбирают рабочее пространство; Computer использует эту модель для генерации ответа.",
|
||||
"admin.gateway.modelFallback": "Использовать модель рабочего пространства/по умолчанию",
|
||||
"admin.gateway.modelSaveError": "Не удалось сохранить модель шлюза",
|
||||
"admin.gateway.newKey": "Новый API-ключ создан. Скопируйте его сейчас",
|
||||
|
||||
@@ -212,7 +212,7 @@
|
||||
"home.start": "开始",
|
||||
"home.openFolder": "打开文件夹...",
|
||||
"home.recent": "最近",
|
||||
"home.folders": "文件夹",
|
||||
"home.folders": "建议",
|
||||
"home.chatComingSoon": "聊天(即将推出)",
|
||||
"directory.cancel": "取消",
|
||||
"directory.open": "打开「{{name}}」",
|
||||
@@ -293,7 +293,7 @@
|
||||
"general.webhookUrlHint": "支持 Slack、Discord、Teams 和通用 JSON Webhook。",
|
||||
"general.updates": "更新",
|
||||
"general.updateNotifications": "更新通知",
|
||||
"general.updateNotificationsDesc": "当 cptr 有新版本可用时显示提示。",
|
||||
"general.updateNotificationsDesc": "当 Computer 有新版本可用时显示提示。",
|
||||
"general.messageQueue": "消息队列",
|
||||
"general.queue": "队列",
|
||||
"general.interrupt": "中断",
|
||||
@@ -597,7 +597,7 @@
|
||||
"admin.gateway.keyWarning": "此密钥只会显示一次。请安全保存。",
|
||||
"admin.gateway.loadError": "加载 API 密钥失败",
|
||||
"admin.gateway.model": "响应模型",
|
||||
"admin.gateway.modelDescription": "网关客户端选择工作区;cptr 使用此模型生成响应。",
|
||||
"admin.gateway.modelDescription": "网关客户端选择工作区;Computer 使用此模型生成响应。",
|
||||
"admin.gateway.modelFallback": "使用工作区/默认模型",
|
||||
"admin.gateway.modelSaveError": "保存网关模型失败",
|
||||
"admin.gateway.newKey": "新 API 密钥已创建。请立即复制",
|
||||
|
||||
@@ -212,7 +212,7 @@
|
||||
"home.start": "開始",
|
||||
"home.openFolder": "開啟資料夾...",
|
||||
"home.recent": "最近",
|
||||
"home.folders": "資料夾",
|
||||
"home.folders": "建議",
|
||||
"home.chatComingSoon": "聊天(即將推出)",
|
||||
"directory.cancel": "取消",
|
||||
"directory.open": "開啟「{{name}}」",
|
||||
@@ -293,7 +293,7 @@
|
||||
"general.webhookUrlHint": "支援 Slack、Discord、Teams 和通用 JSON Webhook。",
|
||||
"general.updates": "更新",
|
||||
"general.updateNotifications": "更新通知",
|
||||
"general.updateNotificationsDesc": "當 cptr 有新版本可用時顯示提示。",
|
||||
"general.updateNotificationsDesc": "當 Computer 有新版本可用時顯示提示。",
|
||||
"general.messageQueue": "訊息佇列",
|
||||
"general.queue": "佇列",
|
||||
"general.interrupt": "中斷",
|
||||
@@ -597,7 +597,7 @@
|
||||
"admin.gateway.keyWarning": "此金鑰只會顯示一次。請安全儲存。",
|
||||
"admin.gateway.loadError": "載入 API 金鑰失敗",
|
||||
"admin.gateway.model": "回應模型",
|
||||
"admin.gateway.modelDescription": "閘道客戶端選擇工作區;cptr 使用此模型產生回應。",
|
||||
"admin.gateway.modelDescription": "閘道客戶端選擇工作區;Computer 使用此模型產生回應。",
|
||||
"admin.gateway.modelFallback": "使用工作區/預設模型",
|
||||
"admin.gateway.modelSaveError": "儲存閘道模型失敗",
|
||||
"admin.gateway.newKey": "新 API 金鑰已建立。請立即複製",
|
||||
|
||||
@@ -74,8 +74,8 @@ export function setTtsAudioPlaybackSource(src: string, title?: string): HTMLAudi
|
||||
// Control Center (iOS) while TTS is playing.
|
||||
if ('mediaSession' in navigator) {
|
||||
navigator.mediaSession.metadata = new MediaMetadata({
|
||||
title: title || 'cptr',
|
||||
artist: 'cptr',
|
||||
title: title || 'Computer',
|
||||
artist: 'Computer',
|
||||
artwork: [
|
||||
{ src: '/icon-192.png', sizes: '192x192', type: 'image/png' },
|
||||
{ src: '/icon-512.png', sizes: '512x512', type: 'image/png' }
|
||||
|
||||
@@ -121,7 +121,7 @@ export function bindGlobalChatListener() {
|
||||
// Browser notification (only when tab is hidden)
|
||||
if (document.hidden && get(notificationsEnabled)) {
|
||||
try {
|
||||
const notification = new Notification(`${title} • cptr`, {
|
||||
const notification = new Notification(`${title} • Computer`, {
|
||||
body: body.slice(0, 200),
|
||||
icon: '/favicon.png'
|
||||
});
|
||||
|
||||
@@ -408,11 +408,11 @@
|
||||
<title
|
||||
>{$activeTab && $activeTab.type !== 'files'
|
||||
? $currentWorkspace
|
||||
? `${$activeTab.label} / ${$currentWorkspace.name} / cptr`
|
||||
: `${$activeTab.label} / cptr`
|
||||
? `${$activeTab.label} / ${$currentWorkspace.name} / Computer`
|
||||
: `${$activeTab.label} / Computer`
|
||||
: $currentWorkspace
|
||||
? `${$currentWorkspace.name} / cptr`
|
||||
: 'cptr'}</title
|
||||
? `${$currentWorkspace.name} / Computer`
|
||||
: 'Computer'}</title
|
||||
>
|
||||
<meta name="description" content={$t('app.tagline')} />
|
||||
</svelte:head>
|
||||
|
||||
@@ -20,12 +20,13 @@
|
||||
showSearch,
|
||||
pwaPreferences
|
||||
} from '$lib/stores';
|
||||
import type { Tab, EditorGroup } from '$lib/stores';
|
||||
import type { Tab, EditorGroup, WorkspaceState } from '$lib/stores';
|
||||
import { t } from '$lib/i18n';
|
||||
import { get } from 'svelte/store';
|
||||
import { getWelcome } from '$lib/apis/state';
|
||||
import { getWelcome, getWorkspaceState } from '$lib/apis/state';
|
||||
import { createSession } from '$lib/apis/terminal';
|
||||
import { createEntry, writeFile, uploadFiles as uploadFilesApi } from '$lib/apis/files';
|
||||
import { getChats, type ChatInfo } from '$lib/apis/chat';
|
||||
import { deleteSharePayload, getSharePayload } from '$lib/intents/payloadStore';
|
||||
import type { LaunchIntent, ShareBehavior, SharePayload } from '$lib/intents/types';
|
||||
import FileBrowser from '$lib/components/FileBrowser.svelte';
|
||||
@@ -38,7 +39,6 @@
|
||||
import GroupTabBar from '$lib/components/GroupTabBar.svelte';
|
||||
import Icon from '$lib/components/Icon.svelte';
|
||||
import WorkspacePicker from '$lib/components/WorkspacePicker.svelte';
|
||||
import SystemInfo from '$lib/components/SystemInfo.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import { isSupportedWorkspacePath } from '$lib/utils/paths';
|
||||
|
||||
@@ -392,6 +392,21 @@
|
||||
recent: { name: string; path: string }[];
|
||||
} | null>(null);
|
||||
|
||||
type WorkspaceResume = {
|
||||
path: string;
|
||||
tabs: Tab[];
|
||||
terminalCount: number;
|
||||
previewPorts: number[];
|
||||
chatCount: number;
|
||||
fileCount: number;
|
||||
recentChats: ChatInfo[];
|
||||
activeChatCount: number;
|
||||
activeLabels: string[];
|
||||
};
|
||||
|
||||
let workspaceResumes = $state<Map<string, WorkspaceResume>>(new Map());
|
||||
let resumeLoadSeq = 0;
|
||||
|
||||
// Fetch welcome data whenever no workspace is active
|
||||
$effect(() => {
|
||||
if (!$currentWorkspace) {
|
||||
@@ -403,6 +418,74 @@
|
||||
}
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if ($currentWorkspace || !welcomeData) return;
|
||||
const paths = [
|
||||
...(welcomeData.recent ?? []).map((item) => item.path),
|
||||
...(welcomeData.suggestions ?? []).map((item) => item.path)
|
||||
]
|
||||
.filter((path, index, all) => path && all.indexOf(path) === index)
|
||||
.slice(0, 8);
|
||||
loadWorkspaceResumes(paths);
|
||||
});
|
||||
|
||||
async function loadWorkspaceResumes(paths: string[]) {
|
||||
const seq = ++resumeLoadSeq;
|
||||
if (!paths.length) {
|
||||
workspaceResumes = new Map();
|
||||
return;
|
||||
}
|
||||
const entries = await Promise.all(
|
||||
paths.map(async (path) => {
|
||||
try {
|
||||
const [state, chatsData] = await Promise.all([
|
||||
getWorkspaceState(path).catch(() => null),
|
||||
getChats(path, 3, 0, 'updated_at', 'desc').catch(() => null)
|
||||
]);
|
||||
if (!state) return null;
|
||||
return [
|
||||
path,
|
||||
buildWorkspaceResume(path, state as unknown as WorkspaceState, chatsData?.chats ?? [])
|
||||
] as const;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
);
|
||||
if (seq !== resumeLoadSeq) return;
|
||||
workspaceResumes = new Map(
|
||||
entries.filter((entry): entry is [string, WorkspaceResume] => !!entry)
|
||||
);
|
||||
}
|
||||
|
||||
function buildWorkspaceResume(
|
||||
path: string,
|
||||
state: WorkspaceState,
|
||||
recentChats: ChatInfo[]
|
||||
): WorkspaceResume {
|
||||
const tabs = (state.groups ?? []).flatMap((group) => group.tabs ?? []);
|
||||
const previewPorts = tabs
|
||||
.filter((tab) => tab.type === 'preview' && tab.port)
|
||||
.map((tab) => tab.port!)
|
||||
.filter((port, index, all) => all.indexOf(port) === index);
|
||||
const activeLabels = tabs
|
||||
.filter((tab) => !tab.permanent && ['terminal', 'chat', 'preview', 'file'].includes(tab.type))
|
||||
.slice(0, 3)
|
||||
.map((tab) => tab.label);
|
||||
|
||||
return {
|
||||
path,
|
||||
tabs,
|
||||
terminalCount: tabs.filter((tab) => tab.type === 'terminal').length,
|
||||
previewPorts,
|
||||
chatCount: tabs.filter((tab) => tab.type === 'chat').length,
|
||||
fileCount: tabs.filter((tab) => tab.type === 'file').length,
|
||||
recentChats,
|
||||
activeChatCount: recentChats.filter((chat) => chat.is_active).length,
|
||||
activeLabels
|
||||
};
|
||||
}
|
||||
|
||||
// Lazy-init terminal sessions for any group's active tab
|
||||
let initingTerminal = $state(false);
|
||||
$effect(() => {
|
||||
@@ -454,6 +537,48 @@
|
||||
return path;
|
||||
}
|
||||
|
||||
function resumeSignals(resume: WorkspaceResume | undefined): string[] {
|
||||
if (!resume) return [];
|
||||
const signals: string[] = [];
|
||||
if (resume.terminalCount) signals.push(`${resume.terminalCount} term`);
|
||||
if (resume.previewPorts.length)
|
||||
signals.push(resume.previewPorts.map((port) => `:${port}`).join(', '));
|
||||
if (resume.chatCount || resume.activeChatCount) {
|
||||
signals.push(
|
||||
resume.activeChatCount
|
||||
? `${resume.activeChatCount} active chat${resume.activeChatCount === 1 ? '' : 's'}`
|
||||
: `${resume.chatCount} chat${resume.chatCount === 1 ? '' : 's'}`
|
||||
);
|
||||
}
|
||||
return signals;
|
||||
}
|
||||
|
||||
function hasMeaningfulResume(resume: WorkspaceResume | undefined): boolean {
|
||||
return !!resume && (resumeSignals(resume).length > 0 || resume.activeLabels.length > 0);
|
||||
}
|
||||
|
||||
function continueWorkspace() {
|
||||
const recent = welcomeData?.recent ?? [];
|
||||
return recent.find((item) => hasMeaningfulResume(workspaceResumes.get(item.path))) ?? recent[0];
|
||||
}
|
||||
|
||||
function recentItems(continuePath?: string) {
|
||||
const recent = welcomeData?.recent ?? [];
|
||||
return recent.filter((item) => item.path !== continuePath).slice(0, 6);
|
||||
}
|
||||
|
||||
function nearbyItems() {
|
||||
return (welcomeData?.suggestions ?? []).slice(0, 5);
|
||||
}
|
||||
|
||||
const continuation = $derived(continueWorkspace());
|
||||
const continueResume = $derived(
|
||||
continuation ? workspaceResumes.get(continuation.path) : undefined
|
||||
);
|
||||
const continueSignals = $derived(resumeSignals(continueResume));
|
||||
const recent = $derived(recentItems(continuation?.path));
|
||||
const nearby = $derived(nearbyItems());
|
||||
|
||||
// ── Draggable divider ──────────────────────────────────────────
|
||||
|
||||
let isDragging = $state(false);
|
||||
@@ -579,85 +704,138 @@
|
||||
</script>
|
||||
|
||||
{#if !$currentWorkspace}
|
||||
<div class="flex items-center justify-center h-full p-6 overflow-y-auto">
|
||||
<div class="flex h-full items-center justify-center overflow-y-auto p-6">
|
||||
<div class="w-full max-w-md">
|
||||
<!-- Header -->
|
||||
<div class="mb-4">
|
||||
<div class="mb-5">
|
||||
<div class="flex items-baseline gap-2">
|
||||
<h1 class="text-lg font-semibold tracking-tight text-gray-900 dark:text-white">cptr</h1>
|
||||
<h1 class="text-lg font-semibold tracking-tight text-gray-900 dark:text-white">
|
||||
Computer
|
||||
</h1>
|
||||
{#if $appVersion}
|
||||
<button
|
||||
onclick={() => showChangelog.set(true)}
|
||||
class="text-[11px] text-gray-400 dark:text-gray-600 hover:text-gray-500 dark:hover:text-gray-400 font-mono hover:underline cursor-pointer"
|
||||
class="cursor-pointer font-mono text-[11px] text-gray-400 hover:text-gray-500 hover:underline dark:text-gray-600 dark:hover:text-gray-400"
|
||||
>
|
||||
v{$appVersion}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{#if welcomeData?.hostname}
|
||||
<p class="text-xs text-gray-400 dark:text-gray-600 mt-0.5 font-mono">
|
||||
<p class="mt-0.5 font-mono text-xs text-gray-400 dark:text-gray-600">
|
||||
{welcomeData.hostname}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- System -->
|
||||
{#if welcomeData?.system}
|
||||
<div class="mb-6">
|
||||
<SystemInfo system={welcomeData.system} processes={welcomeData.processes} />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Start -->
|
||||
<div class="mb-6">
|
||||
<h2 class="text-xs text-gray-400 dark:text-gray-600 mb-2">{$t('home.start')}</h2>
|
||||
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">{$t('home.start')}</h2>
|
||||
<button
|
||||
class="flex items-center gap-2 text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100"
|
||||
class="text-[13px] text-gray-600 transition-colors duration-100 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
|
||||
onclick={() => (showPicker = true)}
|
||||
>
|
||||
<Icon name="folder" size={15} strokeWidth={1.3} />
|
||||
{$t('home.openFolder')}
|
||||
Open workspace
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Recent -->
|
||||
{#if welcomeData?.recent?.length}
|
||||
{#if continuation}
|
||||
<div class="mb-6">
|
||||
<h2 class="text-xs text-gray-400 dark:text-gray-600 mb-2">{$t('home.recent')}</h2>
|
||||
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">Continue</h2>
|
||||
<button
|
||||
class="group w-full min-w-0 py-1.5 text-left transition-colors duration-100"
|
||||
onclick={() => quickOpen(continuation.path)}
|
||||
>
|
||||
<span class="flex min-w-0 items-baseline gap-2">
|
||||
<span
|
||||
class="truncate text-[13px] text-gray-800 group-hover:text-gray-950 dark:text-gray-200 dark:group-hover:text-white"
|
||||
>
|
||||
{continuation.name}
|
||||
</span>
|
||||
<span class="truncate font-mono text-[11px] text-gray-400 dark:text-gray-600">
|
||||
{shortenPath(continuation.path)}
|
||||
</span>
|
||||
</span>
|
||||
{#if continueSignals.length}
|
||||
<span
|
||||
class="mt-0.5 block truncate font-mono text-[10px] text-gray-400 dark:text-gray-600"
|
||||
>
|
||||
{continueSignals.join(' ')}
|
||||
</span>
|
||||
{:else if continueResume?.activeLabels.length}
|
||||
<span class="mt-0.5 block truncate text-[11px] text-gray-400 dark:text-gray-600">
|
||||
{continueResume.activeLabels.join(' · ')}
|
||||
</span>
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if recent.length}
|
||||
<div class="mb-6">
|
||||
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">{$t('home.recent')}</h2>
|
||||
<div class="flex flex-col">
|
||||
{#each welcomeData.recent.slice(0, 5) as item}
|
||||
{#each recent as item}
|
||||
{@const resume = workspaceResumes.get(item.path)}
|
||||
{@const signals = resumeSignals(resume)}
|
||||
<button
|
||||
class="flex items-center gap-3 py-1.5 group text-left transition-colors duration-100"
|
||||
class="group w-full min-w-0 py-1.5 text-left transition-colors duration-100"
|
||||
onclick={() => quickOpen(item.path)}
|
||||
>
|
||||
<span
|
||||
class="text-[13px] text-gray-700 dark:text-gray-300 group-hover:text-gray-900 dark:group-hover:text-white"
|
||||
>{item.name}</span
|
||||
>
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-600 font-mono"
|
||||
>{shortenPath(item.path)}</span
|
||||
>
|
||||
<span class="flex min-w-0 items-baseline gap-2">
|
||||
<span
|
||||
class="truncate text-[13px] text-gray-700 group-hover:text-gray-900 dark:text-gray-300 dark:group-hover:text-white"
|
||||
>
|
||||
{item.name}
|
||||
</span>
|
||||
<span class="truncate font-mono text-[11px] text-gray-400 dark:text-gray-600">
|
||||
{shortenPath(item.path)}
|
||||
</span>
|
||||
</span>
|
||||
{#if signals.length}
|
||||
<span
|
||||
class="mt-0.5 block truncate font-mono text-[10px] text-gray-400 dark:text-gray-600"
|
||||
>
|
||||
{signals.join(' ')}
|
||||
</span>
|
||||
{:else if resume?.activeLabels.length}
|
||||
<span class="mt-0.5 block truncate text-[11px] text-gray-400 dark:text-gray-600">
|
||||
{resume.activeLabels.join(' · ')}
|
||||
</span>
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{:else if !continuation}
|
||||
<div class="mb-6">
|
||||
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">{$t('home.recent')}</h2>
|
||||
<button
|
||||
class="text-[13px] text-gray-500 transition-colors duration-100 hover:text-gray-900 dark:text-gray-500 dark:hover:text-white"
|
||||
onclick={() => (showPicker = true)}
|
||||
>
|
||||
No workspaces yet
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Suggestions -->
|
||||
{#if welcomeData?.suggestions?.length}
|
||||
{#if nearby.length && !welcomeData?.recent?.length}
|
||||
<div>
|
||||
<h2 class="text-xs text-gray-400 dark:text-gray-600 mb-2">{$t('home.folders')}</h2>
|
||||
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">{$t('home.folders')}</h2>
|
||||
<div class="flex flex-col">
|
||||
{#each welcomeData.suggestions.slice(0, 5) as item}
|
||||
{#each nearby as item}
|
||||
<button
|
||||
class="flex items-center gap-2 py-1.5 text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100"
|
||||
class="flex min-w-0 items-center gap-2 py-1.5 text-left text-[13px] text-gray-600 transition-colors duration-100 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
|
||||
onclick={() => quickOpen(item.path)}
|
||||
>
|
||||
<Icon name="folder" size={14} strokeWidth={1.3} />
|
||||
<span>{item.name}</span>
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-600 font-mono"
|
||||
>{shortenPath(item.path)}</span
|
||||
>
|
||||
<Icon
|
||||
name="folder"
|
||||
size={14}
|
||||
strokeWidth={1.3}
|
||||
class="shrink-0 text-gray-400 dark:text-gray-600"
|
||||
/>
|
||||
<span class="truncate">{item.name}</span>
|
||||
<span class="truncate font-mono text-[11px] text-gray-400 dark:text-gray-600">
|
||||
{shortenPath(item.path)}
|
||||
</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Automations / cptr</title>
|
||||
<title>Automations / Computer</title>
|
||||
</svelte:head>
|
||||
|
||||
<AutomationsPanel />
|
||||
@@ -6,7 +6,7 @@
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Automation / cptr</title>
|
||||
<title>Automation / Computer</title>
|
||||
</svelte:head>
|
||||
|
||||
<AutomationsPanel {automationId} />
|
||||
@@ -11,6 +11,8 @@ from cptr.routers.chat import invalidate_model_cache
|
||||
from cptr.models import User, Auth, Config
|
||||
from cptr.utils.config import AuthResult, _get_jwt_secret, check_access, hash_password, now_ms
|
||||
from cptr.utils.crypto import decrypt_key, encrypt_key, mask_key
|
||||
from cptr.utils.agents.detection import get_agent_status, invalidate_agent_detection_cache
|
||||
from cptr.utils.agents.models import save_agent_profiles
|
||||
|
||||
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
||||
|
||||
@@ -154,6 +156,39 @@ async def put_config(body: ConfigUpdateRequest, request: Request):
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ── Agents ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
class AgentsUpdateRequest(BaseModel):
|
||||
profiles: list[dict]
|
||||
|
||||
|
||||
@router.get("/agents")
|
||||
async def get_agents(request: Request):
|
||||
"""Get configured agent profiles plus live detection status."""
|
||||
require_admin(request)
|
||||
return await get_agent_status(request.app.state)
|
||||
|
||||
|
||||
@router.put("/agents")
|
||||
async def update_agents(body: AgentsUpdateRequest, request: Request):
|
||||
"""Replace configured agent profiles."""
|
||||
require_admin(request)
|
||||
await save_agent_profiles(body.profiles)
|
||||
invalidate_agent_detection_cache(request.app.state)
|
||||
invalidate_model_cache(request.app.state)
|
||||
return await get_agent_status(request.app.state, refresh=True)
|
||||
|
||||
|
||||
@router.post("/agents/refresh")
|
||||
async def refresh_agents(request: Request):
|
||||
"""Refresh agent detection status."""
|
||||
require_admin(request)
|
||||
invalidate_agent_detection_cache(request.app.state)
|
||||
invalidate_model_cache(request.app.state)
|
||||
return await get_agent_status(request.app.state, refresh=True)
|
||||
|
||||
|
||||
# ── Connections ──────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -408,6 +443,10 @@ async def _build_model_config(request: Request):
|
||||
}
|
||||
)
|
||||
|
||||
from cptr.utils.agents.detection import get_available_agent_model_entries
|
||||
|
||||
models.extend(await get_available_agent_model_entries(request.app.state))
|
||||
|
||||
return {"config": config, "models": models}
|
||||
|
||||
|
||||
|
||||
+30
-17
@@ -172,6 +172,10 @@ async def get_models(request: Request):
|
||||
}
|
||||
)
|
||||
|
||||
from cptr.utils.agents.detection import get_available_agent_model_entries
|
||||
|
||||
models.extend(await get_available_agent_model_entries(request.app.state))
|
||||
|
||||
default_model = await Config.get("chat.default_model")
|
||||
|
||||
# Filter out inactive models
|
||||
@@ -457,8 +461,10 @@ async def send_message(body: SendMessageRequest, request: Request):
|
||||
# Auto-add .cptr to .gitignore if this is a git repo
|
||||
await asyncio.to_thread(ensure_cptr_gitignored, body.workspace)
|
||||
|
||||
# Resolve connection for model
|
||||
connection, bare_model = await _resolve_connection(body.model_id, request.app.state)
|
||||
# Resolve selected model to either an API connection or an agent profile.
|
||||
from cptr.utils.model_targets import resolve_model_target
|
||||
|
||||
target = await resolve_model_target(body.model_id, request.app.state)
|
||||
|
||||
from cptr.utils.chat_task import (
|
||||
get_pending_input_lock,
|
||||
@@ -532,10 +538,9 @@ async def send_message(body: SendMessageRequest, request: Request):
|
||||
message_id=assistant_msg.id,
|
||||
chat_id=chat.id,
|
||||
user_id=user_id,
|
||||
connection=connection,
|
||||
workspace=body.workspace,
|
||||
model=bare_model,
|
||||
regeneration_prompt=body.regeneration_prompt,
|
||||
target=target,
|
||||
)
|
||||
|
||||
# Return the created messages so the frontend can append them
|
||||
@@ -571,7 +576,11 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request):
|
||||
usage = await _get_chat_context_usage(chat, body.model_id)
|
||||
return {"ok": True, "compacted": False, "reason": "too_short", "context_usage": usage}
|
||||
|
||||
connection, bare_model = await _resolve_connection(body.model_id, request.app.state)
|
||||
from cptr.utils.model_targets import ApiModelTarget, first_api_model_target, resolve_model_target
|
||||
|
||||
target = await resolve_model_target(body.model_id, request.app.state)
|
||||
if not isinstance(target, ApiModelTarget):
|
||||
target = await first_api_model_target(request.app.state)
|
||||
|
||||
from cptr.utils.chat_task import _load_message_history
|
||||
from cptr.utils.summarize import summarize_messages
|
||||
@@ -581,6 +590,8 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request):
|
||||
usage = await _get_chat_context_usage(chat, body.model_id)
|
||||
return {"ok": True, "compacted": False, "reason": "too_short", "context_usage": usage}
|
||||
|
||||
connection = target.connection
|
||||
runtime_model = target.runtime_model
|
||||
provider = connection["provider"]
|
||||
api_key = decrypt_key(connection.get("api_key", ""), _get_jwt_secret())
|
||||
from cptr.utils.chat_task import _default_base_url
|
||||
@@ -594,7 +605,7 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request):
|
||||
provider,
|
||||
base_url,
|
||||
api_key,
|
||||
bare_model,
|
||||
runtime_model,
|
||||
api_type=api_type,
|
||||
)
|
||||
await ChatMessage.update(message_id, chat_summary=summary)
|
||||
@@ -692,8 +703,10 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ
|
||||
|
||||
await ChatMessage.update(message_id, output=output, done=False)
|
||||
|
||||
# Resolve connection and continue
|
||||
connection, bare_model = await _resolve_connection(model_id, request.app.state)
|
||||
# Resolve model target and continue
|
||||
from cptr.utils.model_targets import resolve_model_target
|
||||
|
||||
target = await resolve_model_target(model_id, request.app.state)
|
||||
workspace = chat.meta.get("workspace", "") if chat.meta else ""
|
||||
|
||||
from cptr.utils.chat_task import start_task
|
||||
@@ -702,9 +715,8 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ
|
||||
message_id=message_id,
|
||||
chat_id=chat_id,
|
||||
user_id=user_id,
|
||||
connection=connection,
|
||||
workspace=workspace,
|
||||
model=bare_model,
|
||||
target=target,
|
||||
)
|
||||
else:
|
||||
call["status"] = "rejected"
|
||||
@@ -872,11 +884,13 @@ async def queue_send_now(chat_id: str, message_id: str, request: Request):
|
||||
meta.pop("queued", None)
|
||||
await ChatMessage.update(message_id, meta=meta or None)
|
||||
|
||||
# Resolve connection and start task
|
||||
# Resolve model target and start task
|
||||
model_id = msg.model or (chat.meta or {}).get("last_model", "")
|
||||
if not model_id:
|
||||
model_id = next((m.model for m in reversed(all_msgs) if m.model), "")
|
||||
connection, bare_model = await _resolve_connection(model_id, request.app.state)
|
||||
from cptr.utils.model_targets import resolve_model_target
|
||||
|
||||
target = await resolve_model_target(model_id, request.app.state)
|
||||
workspace = (chat.meta or {}).get("workspace", "")
|
||||
meta_for_model = dict(chat.meta or {})
|
||||
if meta_for_model.get("last_model") != model_id:
|
||||
@@ -898,9 +912,8 @@ async def queue_send_now(chat_id: str, message_id: str, request: Request):
|
||||
message_id=assistant_msg.id,
|
||||
chat_id=chat_id,
|
||||
user_id=user_id,
|
||||
connection=connection,
|
||||
workspace=workspace,
|
||||
model=bare_model,
|
||||
target=target,
|
||||
)
|
||||
return {"ok": True, "chat_id": chat_id, "message_id": assistant_msg.id}
|
||||
|
||||
@@ -925,7 +938,7 @@ async def queue_delete(chat_id: str, message_id: str, request: Request):
|
||||
|
||||
async def _resolve_connection(model_id: str, app_state=None) -> tuple[dict, str]:
|
||||
"""Find connection for model.
|
||||
'openrouter/gpt-4o' → connection with prefix_id='openrouter', bare model='gpt-4o'
|
||||
'openrouter/gpt-4o' → connection with prefix_id='openrouter', runtime model='gpt-4o'
|
||||
'claude-sonnet-4-20250514' → scan all connections for match
|
||||
Raises 400 if not found.
|
||||
"""
|
||||
@@ -935,10 +948,10 @@ async def _resolve_connection(model_id: str, app_state=None) -> tuple[dict, str]
|
||||
|
||||
# Try prefix match first
|
||||
if "/" in model_id:
|
||||
prefix, bare = model_id.split("/", 1)
|
||||
prefix, runtime_model = model_id.split("/", 1)
|
||||
for conn in connections:
|
||||
if (conn.get("prefix_id") or "").strip() == prefix:
|
||||
return conn, bare
|
||||
return conn, runtime_model
|
||||
|
||||
# Scan all connections using cache
|
||||
for conn in connections:
|
||||
|
||||
+55
-39
@@ -163,14 +163,12 @@ async def create_chat_completion(request: Request, body: ChatCompletionRequest):
|
||||
# 1. Resolve model → workspace path
|
||||
workspace = await _resolve_workspace(user_id, body.model)
|
||||
|
||||
# 2. Resolve the underlying LLM connection for this workspace
|
||||
connection, bare_model, model_id = await _resolve_model(workspace)
|
||||
# 2. Resolve the selected model target for this workspace.
|
||||
target, model_id = await _resolve_model(workspace, request.app.state)
|
||||
|
||||
# Intercept OWUI utility tasks (follow-ups, title gen, tags gen).
|
||||
# These should go directly to the LLM, not through the agentic loop.
|
||||
utility_result = await _intercept_task(
|
||||
request, body, connection, bare_model, model_id
|
||||
)
|
||||
utility_result = await _intercept_task(request, body, workspace, model_id)
|
||||
if utility_result is not None:
|
||||
return utility_result
|
||||
|
||||
@@ -203,10 +201,9 @@ async def create_chat_completion(request: Request, body: ChatCompletionRequest):
|
||||
message_id=assistant_msg.id,
|
||||
chat_id=chat_id,
|
||||
user_id=user_id,
|
||||
connection=connection,
|
||||
workspace=workspace,
|
||||
model=bare_model,
|
||||
output_queue=output_queue,
|
||||
target=target,
|
||||
)
|
||||
|
||||
# 6. Stream SSE response
|
||||
@@ -467,8 +464,7 @@ _UTILITY_PATTERNS = [
|
||||
async def _intercept_task(
|
||||
request: Request,
|
||||
body: ChatCompletionRequest,
|
||||
connection: dict,
|
||||
bare_model: str,
|
||||
workspace: str,
|
||||
model_id: str,
|
||||
) -> dict | None:
|
||||
"""Detect OWUI utility tasks and proxy them directly to the LLM.
|
||||
@@ -484,7 +480,10 @@ async def _intercept_task(
|
||||
task_header = request.headers.get(OWUI_TASK_HEADER, "").strip()
|
||||
if task_header:
|
||||
logger.info("[gateway] Detected utility task via header: %s", task_header)
|
||||
return await _proxy_to_llm(body, connection, bare_model)
|
||||
utility_target = await _resolve_utility_model(workspace, request.app.state)
|
||||
return await _proxy_to_llm(
|
||||
body, utility_target.connection, utility_target.runtime_model
|
||||
)
|
||||
|
||||
# 2. Message content pattern matching (fallback)
|
||||
if not body.messages:
|
||||
@@ -500,13 +499,16 @@ async def _intercept_task(
|
||||
return None
|
||||
|
||||
logger.info("[gateway] Detected utility task via content matching")
|
||||
return await _proxy_to_llm(body, connection, bare_model)
|
||||
utility_target = await _resolve_utility_model(workspace, request.app.state)
|
||||
return await _proxy_to_llm(
|
||||
body, utility_target.connection, utility_target.runtime_model
|
||||
)
|
||||
|
||||
|
||||
async def _proxy_to_llm(
|
||||
body: ChatCompletionRequest,
|
||||
connection: dict,
|
||||
bare_model: str,
|
||||
runtime_model: str,
|
||||
) -> dict:
|
||||
"""Proxy a utility task directly to the underlying LLM."""
|
||||
from cptr.utils.ai import chat_completion
|
||||
@@ -522,7 +524,7 @@ async def _proxy_to_llm(
|
||||
provider=provider,
|
||||
base_url=base_url,
|
||||
api_key=api_key,
|
||||
model=bare_model,
|
||||
model=runtime_model,
|
||||
messages=body.messages,
|
||||
max_tokens=200,
|
||||
)
|
||||
@@ -582,8 +584,8 @@ async def _resolve_workspace(user_id: str, model_id: str) -> str:
|
||||
# ── Model connection resolution ──────────────────────────────
|
||||
|
||||
|
||||
async def _resolve_model(workspace: str) -> tuple[dict, str, str]:
|
||||
"""Find a model connection to use for the agentic loop.
|
||||
async def _resolve_model(workspace: str, app_state=None):
|
||||
"""Find a model target to use for the agentic loop.
|
||||
|
||||
Priority:
|
||||
1. Gateway model selected in Settings > Gateway
|
||||
@@ -591,15 +593,15 @@ async def _resolve_model(workspace: str) -> tuple[dict, str, str]:
|
||||
3. Default model from Settings > Models (chat.default_model)
|
||||
4. First enabled connection's first model (with auto-discovery)
|
||||
|
||||
Returns (connection_dict, bare_model, full_model_id).
|
||||
Returns (target, full_model_id).
|
||||
"""
|
||||
from cptr.routers.chat import _resolve_connection
|
||||
from cptr.utils.model_targets import first_api_model_target, resolve_model_target
|
||||
|
||||
gateway_model = await Config.get("gateway.model")
|
||||
if isinstance(gateway_model, str) and gateway_model.strip():
|
||||
try:
|
||||
connection, bare = await _resolve_connection(gateway_model.strip())
|
||||
return connection, bare, gateway_model.strip()
|
||||
target = await resolve_model_target(gateway_model.strip(), app_state)
|
||||
return target, gateway_model.strip()
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"[openai-compat] Gateway model '%s' not found, falling back",
|
||||
@@ -614,8 +616,8 @@ async def _resolve_model(workspace: str) -> tuple[dict, str, str]:
|
||||
|
||||
if model_override:
|
||||
try:
|
||||
connection, bare = await _resolve_connection(model_override)
|
||||
return connection, bare, model_override
|
||||
target = await resolve_model_target(model_override, app_state)
|
||||
return target, model_override
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"[openai-compat] Workspace model override '%s' not found, falling back",
|
||||
@@ -626,32 +628,46 @@ async def _resolve_model(workspace: str) -> tuple[dict, str, str]:
|
||||
default_model = await Config.get("chat.default_model")
|
||||
if isinstance(default_model, str) and default_model.strip():
|
||||
try:
|
||||
connection, bare = await _resolve_connection(default_model.strip())
|
||||
return connection, bare, default_model.strip()
|
||||
target = await resolve_model_target(default_model.strip(), app_state)
|
||||
return target, default_model.strip()
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"[openai-compat] Default model '%s' not found, falling back",
|
||||
default_model,
|
||||
)
|
||||
|
||||
# Fall back to the first enabled connection + its first model
|
||||
from cptr.routers.chat import _fetch_provider_models
|
||||
target = await first_api_model_target(app_state)
|
||||
return target, target.full_model_id
|
||||
|
||||
connections = await Config.get("chat.connections") or []
|
||||
for conn in connections:
|
||||
if not conn.get("enabled", True):
|
||||
continue
|
||||
model_ids = conn.get("data", {}).get("models")
|
||||
if not model_ids:
|
||||
# Attempt auto-discovery if models aren't pre-stored
|
||||
model_ids = await _fetch_provider_models(conn)
|
||||
if model_ids:
|
||||
prefix = (conn.get("prefix_id") or "").strip()
|
||||
bare = model_ids[0]
|
||||
full = f"{prefix}/{bare}" if prefix else bare
|
||||
return conn, bare, full
|
||||
|
||||
raise HTTPException(503, "No model connections configured. Add a connection in cptr settings.")
|
||||
async def _resolve_utility_model(workspace: str, app_state=None):
|
||||
"""Resolve an API model for gateway utility tasks."""
|
||||
from cptr.utils.model_targets import ApiModelTarget, first_api_model_target, resolve_model_target
|
||||
|
||||
candidates: list[str] = []
|
||||
gateway_model = await Config.get("gateway.model")
|
||||
if isinstance(gateway_model, str) and gateway_model.strip():
|
||||
candidates.append(gateway_model.strip())
|
||||
|
||||
model_file = Path(workspace) / ".cptr" / "model"
|
||||
if model_file.is_file():
|
||||
override = model_file.read_text().strip()
|
||||
if override:
|
||||
candidates.append(override)
|
||||
|
||||
default_model = await Config.get("chat.default_model")
|
||||
if isinstance(default_model, str) and default_model.strip():
|
||||
candidates.append(default_model.strip())
|
||||
|
||||
for model_id in candidates:
|
||||
try:
|
||||
target = await resolve_model_target(model_id, app_state)
|
||||
if isinstance(target, ApiModelTarget):
|
||||
return target
|
||||
except Exception:
|
||||
logger.warning("[openai-compat] Utility model '%s' not available", model_id)
|
||||
|
||||
return await first_api_model_target(app_state)
|
||||
|
||||
|
||||
# ── Session mapping ──────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Coding agent support for Codex and Claude Code."""
|
||||
@@ -0,0 +1,394 @@
|
||||
"""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, images: list[dict[str, str]] | None = None) -> dict[str, Any]:
|
||||
if not self.session_id:
|
||||
raise RuntimeError("ACP session has not started")
|
||||
prompt: list[dict[str, str]] = []
|
||||
if text.strip():
|
||||
prompt.append({"type": "text", "text": text})
|
||||
for image in images or []:
|
||||
prompt.append(
|
||||
{
|
||||
"type": "image",
|
||||
"data": image["data"],
|
||||
"mimeType": image["mimeType"],
|
||||
}
|
||||
)
|
||||
return await self.request(
|
||||
"session/prompt",
|
||||
{"sessionId": self.session_id, "prompt": prompt},
|
||||
)
|
||||
|
||||
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_tool_from_update(params: dict[str, Any]) -> dict[str, Any] | None:
|
||||
update = params.get("update")
|
||||
if not isinstance(update, dict):
|
||||
return None
|
||||
if update.get("sessionUpdate") not in {"tool_call", "tool_call_update"}:
|
||||
return None
|
||||
call_id = update.get("toolCallId")
|
||||
if not isinstance(call_id, str) or not call_id.strip():
|
||||
return None
|
||||
|
||||
raw_input = update.get("rawInput")
|
||||
command = _command_from_raw_input(raw_input)
|
||||
title = str(update.get("title") or update.get("kind") or "Agent tool").strip()
|
||||
status = _tool_status(update.get("status"))
|
||||
args: dict[str, Any] = {}
|
||||
if command:
|
||||
name = "run_command"
|
||||
args["command"] = command
|
||||
else:
|
||||
name = "agent_tool"
|
||||
args["title"] = title
|
||||
if raw_input is not None:
|
||||
args["input"] = raw_input
|
||||
output = _tool_output(update)
|
||||
return {
|
||||
"call_id": call_id.strip(),
|
||||
"name": name,
|
||||
"status": status,
|
||||
"arguments": args,
|
||||
"output": output,
|
||||
}
|
||||
|
||||
|
||||
def _tool_status(value: Any) -> str:
|
||||
normalized = str(value or "").strip().lower()
|
||||
if normalized in {"completed", "success"}:
|
||||
return "completed"
|
||||
if normalized in {"failed", "error"}:
|
||||
return "failed"
|
||||
if normalized in {"pending"}:
|
||||
return "pending"
|
||||
return "in_progress"
|
||||
|
||||
|
||||
def _command_from_raw_input(raw_input: Any) -> str | None:
|
||||
if not isinstance(raw_input, dict):
|
||||
return None
|
||||
command = raw_input.get("command")
|
||||
if isinstance(command, str) and command.strip():
|
||||
return command.strip()
|
||||
executable = raw_input.get("executable")
|
||||
args = raw_input.get("args")
|
||||
if isinstance(executable, str) and isinstance(args, list):
|
||||
parts = [executable, *(str(arg) for arg in args)]
|
||||
return " ".join(part for part in parts if part.strip())
|
||||
return None
|
||||
|
||||
|
||||
def _tool_output(update: dict[str, Any]) -> str | None:
|
||||
raw_output = update.get("rawOutput")
|
||||
if raw_output is not None:
|
||||
return raw_output if isinstance(raw_output, str) else json.dumps(raw_output, indent=2)
|
||||
content = update.get("content")
|
||||
if not isinstance(content, list):
|
||||
return None
|
||||
text: list[str] = []
|
||||
for item in content:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
nested = item.get("content")
|
||||
if isinstance(nested, dict) and nested.get("type") == "text":
|
||||
value = nested.get("text")
|
||||
if isinstance(value, str) and value.strip():
|
||||
text.append(value.strip())
|
||||
return "\n".join(text) or 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,98 @@
|
||||
"""Attachment preparation for coding agent turns."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from cptr.utils.storage import get_storage
|
||||
|
||||
|
||||
@dataclass
|
||||
class AgentAttachment:
|
||||
type: str
|
||||
name: str
|
||||
mime_type: str
|
||||
path: str
|
||||
base64: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class PreparedAgentAttachments:
|
||||
images: list[AgentAttachment]
|
||||
files: list[AgentAttachment]
|
||||
prompt_suffix: str
|
||||
|
||||
|
||||
def _safe_segment(value: str) -> str:
|
||||
safe = re.sub(r"[^a-zA-Z0-9_.-]+", "_", value).strip("._")
|
||||
return safe or "attachment"
|
||||
|
||||
|
||||
def _is_image(file_meta: dict[str, Any]) -> bool:
|
||||
content_type = str(file_meta.get("content_type") or file_meta.get("mime_type") or "")
|
||||
return file_meta.get("type") == "image" or content_type.startswith("image/")
|
||||
|
||||
|
||||
async def prepare_agent_attachments(
|
||||
*,
|
||||
workspace: str,
|
||||
chat_id: str,
|
||||
message_id: str,
|
||||
files: list[dict[str, Any]] | None,
|
||||
) -> PreparedAgentAttachments:
|
||||
if not files:
|
||||
return PreparedAgentAttachments(images=[], files=[], prompt_suffix="")
|
||||
|
||||
root = (
|
||||
Path(workspace)
|
||||
/ ".cptr"
|
||||
/ "attachments"
|
||||
/ _safe_segment(chat_id)
|
||||
/ _safe_segment(message_id)
|
||||
)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
images: list[AgentAttachment] = []
|
||||
staged_files: list[AgentAttachment] = []
|
||||
storage = get_storage()
|
||||
for file_meta in files:
|
||||
if not isinstance(file_meta, dict):
|
||||
continue
|
||||
file_id = file_meta.get("id")
|
||||
if not isinstance(file_id, str) or not file_id:
|
||||
continue
|
||||
data = await storage.get(file_id)
|
||||
if data is None:
|
||||
raise RuntimeError(
|
||||
f"Uploaded file is no longer available: {file_meta.get('name') or file_id}"
|
||||
)
|
||||
|
||||
name = _safe_segment(str(file_meta.get("name") or file_id))
|
||||
path = root / f"{_safe_segment(file_id)}-{name}"
|
||||
path.write_bytes(data)
|
||||
mime_type = str(
|
||||
file_meta.get("content_type")
|
||||
or file_meta.get("mime_type")
|
||||
or ("image/png" if _is_image(file_meta) else "application/octet-stream")
|
||||
)
|
||||
attachment = AgentAttachment(
|
||||
type="image" if _is_image(file_meta) else "file",
|
||||
name=name,
|
||||
mime_type=mime_type,
|
||||
path=str(path),
|
||||
base64=base64.b64encode(data).decode(),
|
||||
)
|
||||
if attachment.type == "image":
|
||||
images.append(attachment)
|
||||
else:
|
||||
staged_files.append(attachment)
|
||||
|
||||
suffix = ""
|
||||
if staged_files:
|
||||
lines = "\n".join(f"- {item.path}" for item in staged_files)
|
||||
suffix = f"\n\nAttached files staged in the workspace:\n{lines}"
|
||||
return PreparedAgentAttachments(images=images, files=staged_files, prompt_suffix=suffix)
|
||||
@@ -0,0 +1,234 @@
|
||||
"""Claude Code SDK adapter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import shlex
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
from cptr.utils.agents.attachments import PreparedAgentAttachments
|
||||
from cptr.utils.agents.events import (
|
||||
AgentDone,
|
||||
AgentError,
|
||||
AgentEvent,
|
||||
AgentReasoningDelta,
|
||||
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)
|
||||
|
||||
|
||||
def _claude_query_input(prompt: str, attachments: PreparedAgentAttachments) -> Any:
|
||||
if not attachments.images:
|
||||
return prompt
|
||||
content: list[dict[str, Any]] = []
|
||||
if prompt.strip():
|
||||
content.append({"type": "text", "text": prompt})
|
||||
for image in attachments.images:
|
||||
content.append(
|
||||
{
|
||||
"type": "image",
|
||||
"source": {
|
||||
"type": "base64",
|
||||
"media_type": image.mime_type,
|
||||
"data": image.base64,
|
||||
},
|
||||
}
|
||||
)
|
||||
return content
|
||||
|
||||
|
||||
def _chat_approval_mode(chat_params: dict[str, Any]) -> str:
|
||||
if "tool_approval_mode" in chat_params:
|
||||
return str(chat_params.get("tool_approval_mode") or "auto")
|
||||
if "auto_approve_tools" in chat_params:
|
||||
return "full" if chat_params.get("auto_approve_tools") else "auto"
|
||||
return "auto"
|
||||
|
||||
|
||||
def _permission_mode(chat_approval_mode: str) -> str:
|
||||
if chat_approval_mode == "full":
|
||||
return "bypassPermissions"
|
||||
if chat_approval_mode == "auto":
|
||||
return "acceptEdits"
|
||||
return "default"
|
||||
|
||||
|
||||
def _tool_update_from_claude_start(
|
||||
event: dict[str, Any],
|
||||
) -> tuple[int | None, AgentToolUpdate | None]:
|
||||
block = event.get("content_block")
|
||||
if not isinstance(block, dict):
|
||||
return None, None
|
||||
if block.get("type") not in {"tool_use", "server_tool_use", "mcp_tool_use"}:
|
||||
return None, None
|
||||
call_id = block.get("id")
|
||||
if not isinstance(call_id, str) or not call_id.strip():
|
||||
return None, None
|
||||
index = event.get("index")
|
||||
name = str(block.get("name") or block.get("type") or "Claude action").strip()
|
||||
raw_input = block.get("input")
|
||||
arguments = raw_input if isinstance(raw_input, dict) else {}
|
||||
return (
|
||||
index if isinstance(index, int) else None,
|
||||
AgentToolUpdate(
|
||||
call_id=call_id.strip(),
|
||||
name="agent_tool",
|
||||
status="in_progress",
|
||||
arguments={"title": name, **arguments},
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def run_claude_code_agent(
|
||||
*,
|
||||
profile: dict[str, Any],
|
||||
model: str,
|
||||
workspace: str,
|
||||
messages: list[dict[str, Any]],
|
||||
system_prompt: str,
|
||||
chat_params: dict[str, Any],
|
||||
resume_state: dict[str, Any] | None,
|
||||
attachments: PreparedAgentAttachments,
|
||||
) -> AsyncIterator[AgentEvent]:
|
||||
try:
|
||||
import claude_agent_sdk as sdk
|
||||
except ImportError:
|
||||
yield AgentError("Claude Code support requires the claude-agent-sdk Python package")
|
||||
return
|
||||
|
||||
prompt = _prompt_from_messages(messages)
|
||||
env = os.environ.copy()
|
||||
if profile.get("home"):
|
||||
env["HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
|
||||
permission_mode = _permission_mode(_chat_approval_mode(chat_params))
|
||||
launch_args = str(profile.get("launch_args") or "").strip()
|
||||
extra_args = shlex.split(launch_args) if launch_args else []
|
||||
|
||||
try:
|
||||
options_kwargs: dict[str, Any] = {
|
||||
"system_prompt": system_prompt or None,
|
||||
"permission_mode": permission_mode,
|
||||
"env": env,
|
||||
"include_partial_messages": True,
|
||||
}
|
||||
if workspace:
|
||||
options_kwargs["cwd"] = workspace
|
||||
if extra_args:
|
||||
options_kwargs["extra_args"] = {arg: None for arg in extra_args}
|
||||
|
||||
options = sdk.ClaudeAgentOptions(**options_kwargs)
|
||||
options.cli_path = str(profile["command"])
|
||||
if model != "default":
|
||||
options.model = model
|
||||
|
||||
client = sdk.ClaudeSDKClient(options)
|
||||
await client.connect()
|
||||
session_id = None
|
||||
if resume_state:
|
||||
value = resume_state.get("session_id")
|
||||
session_id = value if isinstance(value, str) and value else None
|
||||
|
||||
try:
|
||||
query_input = _claude_query_input(prompt, attachments)
|
||||
query = (
|
||||
client.query(query_input, session_id=session_id)
|
||||
if session_id
|
||||
else client.query(query_input)
|
||||
)
|
||||
await asyncio.wait_for(query, timeout=20)
|
||||
stream = client.receive_response()
|
||||
usage: dict[str, Any] | None = None
|
||||
observed_session_id = session_id
|
||||
tool_calls: dict[int, AgentToolUpdate] = {}
|
||||
|
||||
async for message in stream:
|
||||
event = getattr(message, "event", None)
|
||||
if isinstance(event, dict):
|
||||
event_type = event.get("type")
|
||||
if event_type == "content_block_delta":
|
||||
delta = event.get("delta", {})
|
||||
if isinstance(delta, dict):
|
||||
if delta.get("type") == "text_delta" and isinstance(
|
||||
delta.get("text"), str
|
||||
):
|
||||
yield AgentTextDelta(delta["text"])
|
||||
elif delta.get("type") == "thinking_delta" and isinstance(
|
||||
delta.get("thinking"), str
|
||||
):
|
||||
yield AgentReasoningDelta(delta["thinking"])
|
||||
elif event_type == "content_block_start":
|
||||
index, tool = _tool_update_from_claude_start(event)
|
||||
if tool:
|
||||
if index is not None:
|
||||
tool_calls[index] = tool
|
||||
yield tool
|
||||
elif event_type == "content_block_stop":
|
||||
index = event.get("index")
|
||||
tool = tool_calls.get(index) if isinstance(index, int) else None
|
||||
if tool:
|
||||
yield AgentToolUpdate(
|
||||
call_id=tool.call_id,
|
||||
name=tool.name,
|
||||
status="completed",
|
||||
arguments=tool.arguments,
|
||||
output="",
|
||||
)
|
||||
continue
|
||||
|
||||
class_name = message.__class__.__name__
|
||||
if class_name == "AssistantMessage":
|
||||
for block in getattr(message, "content", []) or []:
|
||||
if block.__class__.__name__ == "TextBlock":
|
||||
text = getattr(block, "text", "")
|
||||
if text:
|
||||
yield AgentTextDelta(text)
|
||||
elif block.__class__.__name__ == "ThinkingBlock":
|
||||
text = getattr(block, "thinking", "")
|
||||
if text:
|
||||
yield AgentReasoningDelta(text)
|
||||
elif class_name == "ResultMessage":
|
||||
observed_session_id = (
|
||||
getattr(message, "session_id", None) or observed_session_id
|
||||
)
|
||||
raw_usage = getattr(message, "usage", None)
|
||||
if isinstance(raw_usage, dict):
|
||||
usage = {
|
||||
**raw_usage,
|
||||
"total_tokens": (raw_usage.get("input_tokens") or 0)
|
||||
+ (raw_usage.get("output_tokens") or 0),
|
||||
}
|
||||
break
|
||||
|
||||
yield AgentDone(
|
||||
usage=usage,
|
||||
resume_state={
|
||||
"profile_id": profile["id"],
|
||||
"session_id": observed_session_id,
|
||||
"workspace": workspace,
|
||||
"model": model,
|
||||
},
|
||||
)
|
||||
finally:
|
||||
await client.disconnect()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - surfaced in the chat.
|
||||
yield AgentError(str(exc))
|
||||
@@ -0,0 +1,327 @@
|
||||
"""Codex app-server adapter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from contextlib import suppress
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
from cptr.utils.agents.attachments import PreparedAgentAttachments
|
||||
from cptr.utils.agents.events import (
|
||||
AgentDone,
|
||||
AgentError,
|
||||
AgentEvent,
|
||||
AgentReasoningDelta,
|
||||
AgentTextDelta,
|
||||
AgentToolUpdate,
|
||||
)
|
||||
|
||||
|
||||
class CodexAppServer:
|
||||
def __init__(self, command: str, cwd: str, env: dict[str, str]) -> None:
|
||||
self.command = command
|
||||
self.cwd = cwd
|
||||
self.env = env
|
||||
self.proc: asyncio.subprocess.Process | None = None
|
||||
self.reader_task: asyncio.Task | None = None
|
||||
self.stderr_task: asyncio.Task | None = None
|
||||
self.pending: dict[int, asyncio.Future[dict[str, Any]]] = {}
|
||||
self.events: asyncio.Queue[dict[str, Any]] = asyncio.Queue()
|
||||
self.next_id = 1
|
||||
|
||||
async def start(self) -> None:
|
||||
self.proc = await asyncio.create_subprocess_exec(
|
||||
self.command,
|
||||
"app-server",
|
||||
stdin=asyncio.subprocess.PIPE,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
cwd=self.cwd or os.getcwd(),
|
||||
env=self.env,
|
||||
)
|
||||
self.reader_task = asyncio.create_task(self._reader_loop())
|
||||
self.stderr_task = asyncio.create_task(self._stderr_loop())
|
||||
await self.request(
|
||||
"initialize",
|
||||
{
|
||||
"clientInfo": {"name": "cptr", "version": "0"},
|
||||
"capabilities": {"experimentalApi": True},
|
||||
},
|
||||
)
|
||||
await self.notify("initialized")
|
||||
|
||||
async def close(self) -> None:
|
||||
if self.proc and self.proc.returncode is None:
|
||||
self.proc.terminate()
|
||||
with suppress(asyncio.TimeoutError):
|
||||
await asyncio.wait_for(self.proc.wait(), timeout=3)
|
||||
if self.proc.returncode is None:
|
||||
self.proc.kill()
|
||||
await self.proc.wait()
|
||||
for task in (self.reader_task, self.stderr_task):
|
||||
if task:
|
||||
task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await task
|
||||
for future in self.pending.values():
|
||||
if not future.done():
|
||||
future.cancel()
|
||||
self.pending.clear()
|
||||
|
||||
async def request(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
request_id = self.next_id
|
||||
self.next_id += 1
|
||||
loop = asyncio.get_running_loop()
|
||||
future: asyncio.Future[dict[str, Any]] = loop.create_future()
|
||||
self.pending[request_id] = future
|
||||
await self._send({"id": request_id, "method": method, "params": params})
|
||||
response = await future
|
||||
if response.get("error"):
|
||||
raise RuntimeError(str(response["error"]))
|
||||
return response
|
||||
|
||||
async def notify(self, method: str, params: dict[str, Any] | None = None) -> None:
|
||||
payload: dict[str, Any] = {"method": method}
|
||||
if params is not None:
|
||||
payload["params"] = params
|
||||
await self._send(payload)
|
||||
|
||||
async def _send(self, payload: dict[str, Any]) -> None:
|
||||
assert self.proc is not None and self.proc.stdin is not None
|
||||
self.proc.stdin.write((json.dumps(payload) + "\n").encode())
|
||||
await self.proc.stdin.drain()
|
||||
|
||||
async def _reader_loop(self) -> None:
|
||||
assert self.proc is not None and self.proc.stdout is not None
|
||||
while True:
|
||||
line = await self.proc.stdout.readline()
|
||||
if not line:
|
||||
break
|
||||
try:
|
||||
message = json.loads(line.decode())
|
||||
except Exception:
|
||||
continue
|
||||
if (
|
||||
"id" in message
|
||||
and "method" not in message
|
||||
and ("result" in message or "error" in message)
|
||||
):
|
||||
future = self.pending.pop(int(message["id"]), None)
|
||||
if future and not future.done():
|
||||
future.set_result(message)
|
||||
else:
|
||||
await self.events.put(message)
|
||||
|
||||
async def _stderr_loop(self) -> None:
|
||||
assert self.proc is not None and self.proc.stderr is not None
|
||||
while await self.proc.stderr.readline():
|
||||
pass
|
||||
|
||||
|
||||
def _messages_to_prompt(messages: list[dict[str, Any]]) -> str:
|
||||
parts: list[str] = []
|
||||
for message in messages:
|
||||
role = message.get("role", "user")
|
||||
content = message.get("content", "")
|
||||
if isinstance(content, list):
|
||||
text = "\n".join(
|
||||
str(block.get("text", "")) for block in content if isinstance(block, dict)
|
||||
)
|
||||
else:
|
||||
text = str(content or "")
|
||||
if text:
|
||||
parts.append(f"[{role}]\n{text}")
|
||||
return "\n\n".join(parts)
|
||||
|
||||
|
||||
def _approval_policy(value: str) -> str:
|
||||
return {"ask": "on-request", "auto": "on-failure", "full": "never"}.get(value, "on-failure")
|
||||
|
||||
|
||||
def _chat_approval_mode(chat_params: dict[str, Any]) -> str:
|
||||
if "tool_approval_mode" in chat_params:
|
||||
return str(chat_params.get("tool_approval_mode") or "auto")
|
||||
if "auto_approve_tools" in chat_params:
|
||||
return "full" if chat_params.get("auto_approve_tools") else "auto"
|
||||
return "auto"
|
||||
|
||||
|
||||
def _sandbox_for_approval(value: str) -> str:
|
||||
if value == "ask":
|
||||
return "read-only"
|
||||
return "workspace-write"
|
||||
|
||||
|
||||
def _codex_turn_options(chat_params: dict[str, Any]) -> dict[str, str]:
|
||||
options: dict[str, str] = {}
|
||||
effort = chat_params.get("reasoningEffort") or chat_params.get("reasoning_effort")
|
||||
if isinstance(effort, str) and effort.strip():
|
||||
options["effort"] = effort.strip()
|
||||
service_tier = chat_params.get("serviceTier") or chat_params.get("service_tier")
|
||||
if isinstance(service_tier, str) and service_tier.strip():
|
||||
options["serviceTier"] = service_tier.strip()
|
||||
return options
|
||||
|
||||
|
||||
def _tool_from_item_event(method: str, params: dict[str, Any]) -> AgentToolUpdate | None:
|
||||
if method not in {"item/started", "item/completed"}:
|
||||
return None
|
||||
item = params.get("item") if isinstance(params.get("item"), dict) else {}
|
||||
item_type = str(item.get("type") or "").strip()
|
||||
normalized_type = re.sub(r"[^a-z0-9]+", " ", item_type.lower()).strip()
|
||||
if not _is_tool_item_type(normalized_type):
|
||||
return None
|
||||
call_id = params.get("itemId") or item.get("id") or item.get("callId")
|
||||
if not isinstance(call_id, str) or not call_id.strip():
|
||||
return None
|
||||
title = str(item.get("title") or item.get("name") or item_type or "Codex action").strip()
|
||||
detail = _item_detail(item)
|
||||
return AgentToolUpdate(
|
||||
call_id=call_id.strip(),
|
||||
name="run_command" if "command" in normalized_type and detail else "agent_tool",
|
||||
status="completed" if method == "item/completed" else "in_progress",
|
||||
arguments={"command": detail}
|
||||
if "command" in normalized_type and detail
|
||||
else {"title": title},
|
||||
output=detail if method == "item/completed" else None,
|
||||
)
|
||||
|
||||
|
||||
def _is_tool_item_type(normalized_type: str) -> bool:
|
||||
if not normalized_type:
|
||||
return False
|
||||
blocked = ("user", "agent message", "assistant", "reasoning", "thought", "plan", "todo")
|
||||
if any(value in normalized_type for value in blocked):
|
||||
return False
|
||||
allowed = (
|
||||
"command",
|
||||
"file change",
|
||||
"patch",
|
||||
"edit",
|
||||
"mcp",
|
||||
"dynamic tool",
|
||||
"collab",
|
||||
"web search",
|
||||
"image",
|
||||
"error",
|
||||
)
|
||||
return any(value in normalized_type for value in allowed)
|
||||
|
||||
|
||||
def _item_detail(item: dict[str, Any]) -> str | None:
|
||||
for key in ("command", "title", "summary", "text", "path", "prompt"):
|
||||
value = item.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
return None
|
||||
|
||||
|
||||
async def run_codex_agent(
|
||||
*,
|
||||
profile: dict[str, Any],
|
||||
model: str,
|
||||
workspace: str,
|
||||
messages: list[dict[str, Any]],
|
||||
system_prompt: str,
|
||||
chat_params: dict[str, Any],
|
||||
resume_state: dict[str, Any] | None,
|
||||
attachments: PreparedAgentAttachments,
|
||||
) -> AsyncIterator[AgentEvent]:
|
||||
env = os.environ.copy()
|
||||
if profile.get("home"):
|
||||
env["CODEX_HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
|
||||
client = CodexAppServer(str(profile["command"]), workspace, env)
|
||||
thread_id: str | None = None
|
||||
turn_id: str | None = None
|
||||
try:
|
||||
await client.start()
|
||||
approval_mode = _chat_approval_mode(chat_params)
|
||||
thread_params: dict[str, Any] = {
|
||||
"cwd": workspace,
|
||||
"approvalPolicy": _approval_policy(approval_mode),
|
||||
"sandbox": _sandbox_for_approval(approval_mode),
|
||||
}
|
||||
if model != "default":
|
||||
thread_params["model"] = model
|
||||
if system_prompt:
|
||||
thread_params["developerInstructions"] = system_prompt
|
||||
|
||||
response = await client.request("thread/start", thread_params)
|
||||
thread = response.get("result", {}).get("thread", {})
|
||||
thread_id = thread.get("id") if isinstance(thread, dict) else None
|
||||
if not thread_id:
|
||||
yield AgentError("Codex did not return a thread id")
|
||||
return
|
||||
|
||||
prompt = _messages_to_prompt(messages)
|
||||
turn_input: list[dict[str, Any]] = []
|
||||
if prompt:
|
||||
turn_input.append({"type": "text", "text": prompt})
|
||||
for image in attachments.images:
|
||||
turn_input.append(
|
||||
{
|
||||
"type": "image",
|
||||
"url": f"data:{image.mime_type};base64,{image.base64}",
|
||||
}
|
||||
)
|
||||
turn_response = await client.request(
|
||||
"turn/start",
|
||||
{
|
||||
"threadId": thread_id,
|
||||
"input": turn_input,
|
||||
**_codex_turn_options(chat_params),
|
||||
},
|
||||
)
|
||||
turn = turn_response.get("result", {}).get("turn", {})
|
||||
turn_id = turn.get("id") if isinstance(turn, dict) else None
|
||||
|
||||
while True:
|
||||
event = await client.events.get()
|
||||
method = event.get("method")
|
||||
params = event.get("params") if isinstance(event.get("params"), dict) else {}
|
||||
event_turn_id = params.get("turnId")
|
||||
if event_turn_id and turn_id and event_turn_id != turn_id:
|
||||
continue
|
||||
if method == "item/agentMessage/delta":
|
||||
delta = params.get("delta")
|
||||
if isinstance(delta, str) and delta:
|
||||
yield AgentTextDelta(delta)
|
||||
elif method in ("item/reasoning/textDelta", "item/reasoning/summaryTextDelta"):
|
||||
delta = params.get("delta")
|
||||
if isinstance(delta, str) and delta:
|
||||
yield AgentReasoningDelta(delta)
|
||||
else:
|
||||
tool = _tool_from_item_event(str(method or ""), params)
|
||||
if tool:
|
||||
yield tool
|
||||
if method == "turn/completed":
|
||||
yield AgentDone(
|
||||
resume_state={
|
||||
"profile_id": profile["id"],
|
||||
"thread_id": thread_id,
|
||||
"turn_id": turn_id,
|
||||
"workspace": workspace,
|
||||
"model": model,
|
||||
}
|
||||
)
|
||||
return
|
||||
elif method == "turn/failed":
|
||||
detail = params.get("message") or params.get("error") or "Codex turn failed"
|
||||
yield AgentError(str(detail))
|
||||
return
|
||||
elif method == "error":
|
||||
yield AgentError(str(params or "Codex app-server error"))
|
||||
return
|
||||
except asyncio.CancelledError:
|
||||
if thread_id and turn_id:
|
||||
with suppress(Exception):
|
||||
await client.request("turn/interrupt", {"threadId": thread_id, "turnId": turn_id})
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - surfaced in the chat.
|
||||
yield AgentError(str(exc))
|
||||
finally:
|
||||
await client.close()
|
||||
@@ -0,0 +1,145 @@
|
||||
"""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.attachments import PreparedAgentAttachments
|
||||
from cptr.utils.agents.acp import (
|
||||
AcpClient,
|
||||
acp_event_stream,
|
||||
acp_text_from_update,
|
||||
acp_tool_from_update,
|
||||
)
|
||||
from cptr.utils.agents.events import (
|
||||
AgentDone,
|
||||
AgentError,
|
||||
AgentEvent,
|
||||
AgentTextDelta,
|
||||
AgentToolUpdate,
|
||||
)
|
||||
|
||||
|
||||
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,
|
||||
attachments: PreparedAgentAttachments,
|
||||
) -> 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
|
||||
|
||||
images = [
|
||||
{"data": image.base64, "mimeType": image.mime_type} for image in attachments.images
|
||||
]
|
||||
prompt_task = asyncio.create_task(client.prompt(prompt, images=images))
|
||||
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)
|
||||
tool = acp_tool_from_update(params)
|
||||
if tool:
|
||||
yield AgentToolUpdate(**tool)
|
||||
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)
|
||||
next_tool = acp_tool_from_update(next_params)
|
||||
if next_tool:
|
||||
yield AgentToolUpdate(**next_tool)
|
||||
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()
|
||||
@@ -0,0 +1,503 @@
|
||||
"""Detection helpers for coding agent profiles."""
|
||||
|
||||
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,
|
||||
model_id_for_profile,
|
||||
normalize_agent_profiles,
|
||||
)
|
||||
|
||||
DETECTION_TTL_SECONDS = 30
|
||||
CLAUDE_MODELS = [
|
||||
"claude-fable-5",
|
||||
"claude-opus-4-8",
|
||||
"claude-opus-4-7",
|
||||
"claude-opus-4-6",
|
||||
"claude-opus-4-5",
|
||||
"claude-sonnet-4-6",
|
||||
"claude-haiku-4-5",
|
||||
]
|
||||
MIN_CLAUDE_FABLE_5 = (2, 1, 169)
|
||||
MIN_CLAUDE_OPUS_4_8 = (2, 1, 154)
|
||||
MIN_CLAUDE_OPUS_4_7 = (2, 1, 111)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AgentDetection:
|
||||
status: str
|
||||
command: str | None = None
|
||||
version: str | None = None
|
||||
message: str | None = None
|
||||
models: list[str] | None = None
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def _resolve_command(command: str) -> str | None:
|
||||
command = command.strip()
|
||||
if not command:
|
||||
return None
|
||||
expanded = os.path.expanduser(command)
|
||||
if os.path.isabs(expanded):
|
||||
return expanded if os.access(expanded, os.X_OK) else None
|
||||
return shutil.which(command)
|
||||
|
||||
|
||||
async def _run_probe(
|
||||
argv: list[str],
|
||||
timeout: float = 3.0,
|
||||
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:
|
||||
return 124, "probe timed out"
|
||||
except Exception as exc: # noqa: BLE001 - surfaced as detection status.
|
||||
return 1, str(exc)
|
||||
|
||||
text = (stdout or stderr).decode(errors="replace").strip()
|
||||
return proc.returncode or 0, text
|
||||
|
||||
|
||||
async def detect_profile(profile: dict[str, Any]) -> AgentDetection:
|
||||
command = _resolve_command(str(profile.get("command") or ""))
|
||||
if command is None:
|
||||
return AgentDetection("not_found", None, None, "Command not found")
|
||||
|
||||
code, version_text = await _run_probe([command, "--version"])
|
||||
version = version_text.splitlines()[0] if code == 0 and version_text else None
|
||||
|
||||
if profile.get("agent") == "claude_code":
|
||||
models = _claude_models_for_version(version)
|
||||
if importlib.util.find_spec("claude_agent_sdk") is None:
|
||||
return AgentDetection(
|
||||
"missing_dependency",
|
||||
command,
|
||||
version,
|
||||
"Python package claude-agent-sdk is not installed",
|
||||
models,
|
||||
)
|
||||
return AgentDetection("ready", command, version, None, models)
|
||||
|
||||
if profile.get("agent") == "codex":
|
||||
help_code, help_text = await _run_probe([command, "app-server", "--help"])
|
||||
if help_code != 0:
|
||||
return AgentDetection(
|
||||
"error",
|
||||
command,
|
||||
version,
|
||||
help_text or "codex app-server is unavailable",
|
||||
)
|
||||
models = await _probe_codex_models(command, profile)
|
||||
return AgentDetection("ready", command, version, None, models)
|
||||
|
||||
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")
|
||||
|
||||
|
||||
def _parse_version_tuple(version: str | None) -> tuple[int, int, int] | None:
|
||||
if not version:
|
||||
return None
|
||||
match = re.search(r"(\d+)\.(\d+)\.(\d+)", version)
|
||||
if not match:
|
||||
return None
|
||||
return tuple(int(part) for part in match.groups())
|
||||
|
||||
|
||||
def _version_at_least(version: tuple[int, int, int] | None, minimum: tuple[int, int, int]) -> bool:
|
||||
return version is not None and version >= minimum
|
||||
|
||||
|
||||
def _claude_models_for_version(version: str | None) -> list[str]:
|
||||
parsed = _parse_version_tuple(version)
|
||||
models = []
|
||||
for model in CLAUDE_MODELS:
|
||||
if model == "claude-fable-5" and not _version_at_least(parsed, MIN_CLAUDE_FABLE_5):
|
||||
continue
|
||||
if model == "claude-opus-4-8" and not _version_at_least(parsed, MIN_CLAUDE_OPUS_4_8):
|
||||
continue
|
||||
if model == "claude-opus-4-7" and not _version_at_least(parsed, MIN_CLAUDE_OPUS_4_7):
|
||||
continue
|
||||
models.append(model)
|
||||
return models
|
||||
|
||||
|
||||
async def _probe_codex_models(command: str, profile: dict[str, Any]) -> list[str] | None:
|
||||
from cptr.utils.agents.codex import CodexAppServer
|
||||
|
||||
env = os.environ.copy()
|
||||
if profile.get("home"):
|
||||
env["CODEX_HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
|
||||
client = CodexAppServer(command, os.getcwd(), env)
|
||||
try:
|
||||
await asyncio.wait_for(client.start(), timeout=5)
|
||||
models: list[str] = []
|
||||
cursor: str | None = None
|
||||
while True:
|
||||
response = await asyncio.wait_for(
|
||||
client.request("model/list", {"cursor": cursor} if cursor else {}),
|
||||
timeout=5,
|
||||
)
|
||||
result = response.get("result") if isinstance(response.get("result"), dict) else {}
|
||||
data = result.get("data") if isinstance(result, dict) else None
|
||||
if not isinstance(data, list):
|
||||
break
|
||||
for item in data:
|
||||
if isinstance(item, dict) and isinstance(item.get("model"), str):
|
||||
models.append(item["model"])
|
||||
next_cursor = result.get("nextCursor") if isinstance(result, dict) else None
|
||||
cursor = next_cursor if isinstance(next_cursor, str) and next_cursor else None
|
||||
if not cursor:
|
||||
break
|
||||
return models or None
|
||||
except Exception:
|
||||
return None
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
|
||||
async def _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
|
||||
if not refresh and isinstance(cache, dict):
|
||||
cached_at = cache.get("cached_at")
|
||||
if isinstance(cached_at, (int, float)) and now - cached_at < DETECTION_TTL_SECONDS:
|
||||
return cache["payload"]
|
||||
|
||||
raw_profiles = await get_raw_agent_profiles()
|
||||
implicit_defaults = raw_profiles is None
|
||||
profiles = [] if implicit_defaults else normalize_agent_profiles(raw_profiles)
|
||||
entries = []
|
||||
candidates = profiles if not implicit_defaults else default_agent_profiles()
|
||||
for profile in candidates:
|
||||
detected = await detect_profile(profile)
|
||||
if implicit_defaults and detected.status == "not_found":
|
||||
continue
|
||||
mode = profile.get("mode", "auto")
|
||||
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 models and effective_profile.get("default_model") not in models:
|
||||
effective_profile["default_model"] = models[0]
|
||||
entries.append(
|
||||
{
|
||||
"id": effective_profile["id"],
|
||||
"agent": effective_profile["agent"],
|
||||
"name": effective_profile["name"],
|
||||
"config": effective_profile,
|
||||
"detected": detected.to_dict(),
|
||||
"available": available,
|
||||
"implicit": implicit_defaults,
|
||||
"model_ids": [model_id_for_profile(effective_profile, model) for model in models],
|
||||
}
|
||||
)
|
||||
|
||||
payload = {"profiles": entries}
|
||||
if app_state is not None:
|
||||
app_state.AGENTS = {"cached_at": now, "payload": payload}
|
||||
return payload
|
||||
|
||||
|
||||
def invalidate_agent_detection_cache(app_state) -> None:
|
||||
if app_state is not None and hasattr(app_state, "AGENTS"):
|
||||
delattr(app_state, "AGENTS")
|
||||
|
||||
|
||||
async def get_available_agent_model_entries(app_state=None) -> list[dict[str, str]]:
|
||||
status = await get_agent_status(app_state)
|
||||
entries: list[dict[str, str]] = []
|
||||
for profile in status["profiles"]:
|
||||
if not profile["available"]:
|
||||
continue
|
||||
config = profile["config"]
|
||||
for model in config.get("models") or []:
|
||||
model_id = model_id_for_profile(config, model)
|
||||
entries.append(
|
||||
{
|
||||
"id": model_id,
|
||||
"name": model_id,
|
||||
"provider": "agent",
|
||||
"connection_id": f"agent:{config['id']}",
|
||||
"agent_id": config["agent"],
|
||||
"profile_id": config["id"],
|
||||
}
|
||||
)
|
||||
return entries
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Normalized event types emitted by coding agent adapters."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class AgentTextDelta:
|
||||
text: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class AgentReasoningDelta:
|
||||
text: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class AgentToolUpdate:
|
||||
call_id: str
|
||||
status: str
|
||||
name: str | None = None
|
||||
arguments: dict[str, Any] | None = None
|
||||
output: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AgentDone:
|
||||
usage: dict[str, Any] | None = None
|
||||
resume_state: dict[str, Any] | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AgentError:
|
||||
message: str
|
||||
|
||||
|
||||
AgentEvent = AgentTextDelta | AgentReasoningDelta | AgentToolUpdate | AgentDone | AgentError
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Grok ACP adapter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from contextlib import suppress
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
from cptr.utils.agents.attachments import PreparedAgentAttachments
|
||||
from cptr.utils.agents.acp import (
|
||||
AcpClient,
|
||||
acp_event_stream,
|
||||
acp_text_from_update,
|
||||
acp_tool_from_update,
|
||||
)
|
||||
from cptr.utils.agents.events import (
|
||||
AgentDone,
|
||||
AgentError,
|
||||
AgentEvent,
|
||||
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)
|
||||
|
||||
|
||||
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,
|
||||
attachments: PreparedAgentAttachments,
|
||||
) -> 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
|
||||
|
||||
images = [
|
||||
{"data": image.base64, "mimeType": image.mime_type} for image in attachments.images
|
||||
]
|
||||
prompt_task = asyncio.create_task(client.prompt(prompt, images=images))
|
||||
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)
|
||||
tool = acp_tool_from_update(params)
|
||||
if tool:
|
||||
yield AgentToolUpdate(**tool)
|
||||
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)
|
||||
next_tool = acp_tool_from_update(next_params)
|
||||
if next_tool:
|
||||
yield AgentToolUpdate(**next_tool)
|
||||
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()
|
||||
@@ -0,0 +1,237 @@
|
||||
"""Configuration model helpers for coding agents."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from cptr.models import Config
|
||||
|
||||
CONFIG_KEY_AGENT_PROFILES = "agents.profiles"
|
||||
|
||||
DEFAULT_AGENT_PROFILES: list[dict[str, Any]] = [
|
||||
{
|
||||
"id": "codex",
|
||||
"agent": "codex",
|
||||
"name": "Codex",
|
||||
"mode": "auto",
|
||||
"command": "codex",
|
||||
"home": None,
|
||||
"models": [],
|
||||
"default_model": "",
|
||||
"approval_mode": "auto",
|
||||
"sandbox_mode": "workspace-write",
|
||||
},
|
||||
{
|
||||
"id": "claude-code",
|
||||
"agent": "claude_code",
|
||||
"name": "Claude Code",
|
||||
"mode": "auto",
|
||||
"command": "claude",
|
||||
"home": None,
|
||||
"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", "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]]:
|
||||
return deepcopy(DEFAULT_AGENT_PROFILES)
|
||||
|
||||
|
||||
def normalize_agent_profile(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
profile = dict(raw)
|
||||
profile_id = str(profile.get("id") or "").strip()
|
||||
if not _PROFILE_ID_RE.fullmatch(profile_id):
|
||||
raise HTTPException(400, "agent profile id must be a slug up to 64 characters")
|
||||
|
||||
agent = str(profile.get("agent") or "").strip()
|
||||
if agent not in _VALID_AGENTS:
|
||||
raise HTTPException(400, "agent must be codex, claude_code, cursor, grok, or opencode")
|
||||
defaults = _AGENT_DEFAULTS[agent]
|
||||
|
||||
mode = str(profile.get("mode") or "auto").strip()
|
||||
if mode not in _VALID_MODES:
|
||||
raise HTTPException(400, "agent mode must be auto, enabled, or disabled")
|
||||
|
||||
command = str(profile.get("command") or "").strip()
|
||||
if not command:
|
||||
command = defaults["command"]
|
||||
|
||||
name = str(profile.get("name") or "").strip() or defaults["name"]
|
||||
home = profile.get("home")
|
||||
if isinstance(home, str):
|
||||
home = home.strip() or None
|
||||
elif home is not None:
|
||||
raise HTTPException(400, "agent home must be a string or null")
|
||||
|
||||
models = profile.get("models")
|
||||
if not isinstance(models, list):
|
||||
models = []
|
||||
normalized_models = []
|
||||
for model in models:
|
||||
if isinstance(model, str) and model.strip():
|
||||
model_id = model.strip()
|
||||
if model_id == "default":
|
||||
continue
|
||||
normalized_models.append(model_id)
|
||||
default_model = str(profile.get("default_model") or "").strip()
|
||||
if default_model == "default":
|
||||
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] = {
|
||||
"id": profile_id,
|
||||
"agent": agent,
|
||||
"name": name,
|
||||
"mode": mode,
|
||||
"command": command,
|
||||
"home": home,
|
||||
"models": normalized_models,
|
||||
"default_model": default_model,
|
||||
}
|
||||
|
||||
if agent == "codex":
|
||||
approval_mode = str(profile.get("approval_mode") or "auto").strip()
|
||||
sandbox_mode = str(profile.get("sandbox_mode") or "workspace-write").strip()
|
||||
if approval_mode not in _VALID_CODEX_APPROVAL:
|
||||
raise HTTPException(400, "codex approval_mode must be ask, auto, or full")
|
||||
if sandbox_mode not in _VALID_CODEX_SANDBOX:
|
||||
raise HTTPException(
|
||||
400, "codex sandbox_mode must be read-only, workspace-write, or danger-full-access"
|
||||
)
|
||||
normalized.update(
|
||||
{
|
||||
"approval_mode": approval_mode,
|
||||
"sandbox_mode": sandbox_mode,
|
||||
}
|
||||
)
|
||||
elif agent == "claude_code":
|
||||
permission_mode = str(profile.get("permission_mode") or "default").strip()
|
||||
if permission_mode not in _VALID_CLAUDE_PERMISSION:
|
||||
raise HTTPException(
|
||||
400, "claude permission_mode must be default, accept_edits, or bypass_permissions"
|
||||
)
|
||||
normalized.update(
|
||||
{
|
||||
"permission_mode": permission_mode,
|
||||
"launch_args": str(profile.get("launch_args") or "").strip(),
|
||||
}
|
||||
)
|
||||
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
|
||||
|
||||
|
||||
def normalize_agent_profiles(raw_profiles: Any) -> list[dict[str, Any]]:
|
||||
if raw_profiles is None:
|
||||
raw_profiles = []
|
||||
if not isinstance(raw_profiles, list):
|
||||
raise HTTPException(400, "agents.profiles must be a list")
|
||||
|
||||
profiles = []
|
||||
for profile in raw_profiles:
|
||||
if not isinstance(profile, dict):
|
||||
raise HTTPException(400, "agent profiles must be objects")
|
||||
profiles.append(normalize_agent_profile(profile))
|
||||
|
||||
seen: set[str] = set()
|
||||
for profile in profiles:
|
||||
profile_id = profile["id"]
|
||||
if profile_id in seen:
|
||||
raise HTTPException(400, f"duplicate agent profile id: {profile_id}")
|
||||
seen.add(profile_id)
|
||||
return profiles
|
||||
|
||||
|
||||
async def get_raw_agent_profiles() -> Any:
|
||||
return await Config.get(CONFIG_KEY_AGENT_PROFILES)
|
||||
|
||||
|
||||
async def save_agent_profiles(profiles: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
normalized = normalize_agent_profiles(profiles)
|
||||
await Config.upsert({CONFIG_KEY_AGENT_PROFILES: normalized})
|
||||
return normalized
|
||||
|
||||
|
||||
def model_id_for_profile(profile: dict[str, Any], model: str) -> str:
|
||||
return f"agent:{profile['id']}/{model}"
|
||||
|
||||
|
||||
def parse_agent_model_id(model_id: str) -> tuple[str, str] | None:
|
||||
if not model_id.startswith("agent:"):
|
||||
return None
|
||||
rest = model_id[len("agent:") :]
|
||||
if "/" not in rest:
|
||||
return None
|
||||
profile_id, model = rest.split("/", 1)
|
||||
if not profile_id or not model:
|
||||
return None
|
||||
return profile_id, model
|
||||
@@ -0,0 +1,365 @@
|
||||
"""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 pathlib import Path
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
import httpx
|
||||
|
||||
from cptr.utils.agents.attachments import PreparedAgentAttachments
|
||||
from cptr.utils.agents.events import (
|
||||
AgentDone,
|
||||
AgentError,
|
||||
AgentEvent,
|
||||
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)
|
||||
|
||||
|
||||
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 _opencode_parts(prompt: str, attachments: PreparedAgentAttachments) -> list[dict[str, Any]]:
|
||||
parts: list[dict[str, Any]] = []
|
||||
if prompt.strip():
|
||||
parts.append({"type": "text", "text": prompt})
|
||||
for item in [*attachments.images, *attachments.files]:
|
||||
parts.append(
|
||||
{
|
||||
"type": "file",
|
||||
"mime": item.mime_type,
|
||||
"filename": item.name,
|
||||
"url": Path(item.path).resolve().as_uri(),
|
||||
}
|
||||
)
|
||||
return parts
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _tool_from_event(event: dict[str, Any]) -> AgentToolUpdate | None:
|
||||
if event.get("type") != "message.part.updated":
|
||||
return None
|
||||
props = event.get("properties") if isinstance(event.get("properties"), dict) else {}
|
||||
part = props.get("part") if isinstance(props.get("part"), dict) else {}
|
||||
if part.get("type") != "tool":
|
||||
return None
|
||||
call_id = part.get("callID") or part.get("id")
|
||||
if not isinstance(call_id, str) or not call_id.strip():
|
||||
return None
|
||||
state = part.get("state") if isinstance(part.get("state"), dict) else {}
|
||||
tool = str(part.get("tool") or state.get("title") or "Agent tool").strip()
|
||||
status = _opencode_tool_status(state.get("status"))
|
||||
output = _opencode_tool_output(state)
|
||||
return AgentToolUpdate(
|
||||
call_id=call_id.strip(),
|
||||
name="agent_tool",
|
||||
status=status,
|
||||
arguments={"title": tool, **({"state": state} if state else {})},
|
||||
output=output,
|
||||
)
|
||||
|
||||
|
||||
def _opencode_tool_status(value: Any) -> str:
|
||||
normalized = str(value or "").strip().lower()
|
||||
if normalized == "completed":
|
||||
return "completed"
|
||||
if normalized == "error":
|
||||
return "failed"
|
||||
if normalized == "pending":
|
||||
return "pending"
|
||||
return "in_progress"
|
||||
|
||||
|
||||
def _opencode_tool_output(state: dict[str, Any]) -> str | None:
|
||||
for key in ("output", "result", "message", "error"):
|
||||
value = state.get(key)
|
||||
if value is None:
|
||||
continue
|
||||
return value if isinstance(value, str) else json.dumps(value, indent=2)
|
||||
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,
|
||||
attachments: PreparedAgentAttachments,
|
||||
) -> 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[AgentEvent | 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)
|
||||
parts = _opencode_parts(prompt, attachments)
|
||||
try:
|
||||
await _request(
|
||||
client,
|
||||
"POST",
|
||||
["session.promptAsync", "session/promptAsync", "session/prompt"],
|
||||
headers=headers,
|
||||
json_body={
|
||||
"sessionID": session_id,
|
||||
"model": parsed_model,
|
||||
"parts": parts,
|
||||
},
|
||||
)
|
||||
|
||||
while True:
|
||||
item = await event_queue.get()
|
||||
if item is None:
|
||||
break
|
||||
yield 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[AgentEvent | 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(AgentTextDelta(text))
|
||||
tool = _tool_from_event(event)
|
||||
if tool:
|
||||
await queue.put(tool)
|
||||
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)
|
||||
@@ -173,10 +173,9 @@ async def execute_automation(automation, webhook_payload: str | None = None) ->
|
||||
chats_dir.mkdir(parents=True, exist_ok=True)
|
||||
(chats_dir / f"{chat.id}.json").write_text("{}")
|
||||
|
||||
# Resolve connection for model
|
||||
from cptr.routers.chat import _resolve_connection
|
||||
from cptr.utils.model_targets import resolve_model_target
|
||||
|
||||
connection, bare_model = await _resolve_connection(model_id)
|
||||
target = await resolve_model_target(model_id)
|
||||
|
||||
# Start the agentic loop (same as interactive chat)
|
||||
from cptr.utils.chat_task import start_task
|
||||
@@ -185,9 +184,8 @@ async def execute_automation(automation, webhook_payload: str | None = None) ->
|
||||
message_id=assistant_msg.id,
|
||||
chat_id=chat.id,
|
||||
user_id=automation.user_id,
|
||||
connection=connection,
|
||||
workspace=workspace,
|
||||
model=bare_model,
|
||||
target=target,
|
||||
)
|
||||
|
||||
# Notify frontend (standard chat event so sidebar updates)
|
||||
|
||||
@@ -690,8 +690,7 @@ class BotManager:
|
||||
async def _dispatch_task(
|
||||
self, chat_id: str, event: MessageEvent, bot: dict, adapter: BaseAdapter | None,
|
||||
) -> None:
|
||||
from cptr.models import Chat, ChatMessage, Config
|
||||
from cptr.routers.chat import _resolve_connection
|
||||
from cptr.models import Chat, ChatMessage
|
||||
from cptr.utils.chat_task import start_task, _task_chat
|
||||
from cptr.utils.config import now_ms
|
||||
|
||||
@@ -727,9 +726,11 @@ class BotManager:
|
||||
parent_id=parent_id, meta=user_meta, created_at=now_ms(),
|
||||
)
|
||||
|
||||
# Resolve model connection
|
||||
# Resolve model target
|
||||
try:
|
||||
connection, bare_model = await _resolve_connection(bot["model_id"])
|
||||
from cptr.utils.model_targets import resolve_model_target
|
||||
|
||||
target = await resolve_model_target(bot["model_id"])
|
||||
except Exception:
|
||||
logger.exception("[bridge] Failed to resolve model %s", bot["model_id"])
|
||||
if adapter:
|
||||
@@ -770,9 +771,8 @@ class BotManager:
|
||||
message_id=assistant_msg.id,
|
||||
chat_id=chat_id,
|
||||
user_id=bot["user_id"],
|
||||
connection=connection,
|
||||
workspace=bot["workspace"],
|
||||
model=bare_model,
|
||||
target=target,
|
||||
)
|
||||
logger.info("[bridge] Started task for bot %s, chat %s", bot["id"][:8], chat_id[:8])
|
||||
|
||||
@@ -1024,5 +1024,3 @@ def _tool_label(name: str, args: dict) -> str:
|
||||
return query[:40] if query else name
|
||||
|
||||
return name
|
||||
|
||||
|
||||
+261
-14
@@ -30,6 +30,15 @@ from cptr.utils.tools import ALL_TOOLS, execute_tool, get_tool_list, _fn_to_sche
|
||||
from cptr.utils.chat_export import export_chat_to_file
|
||||
from cptr.utils.json_parser import extract_json
|
||||
from cptr.utils.prompt_templates import load_system_prompt as _load_system_prompt
|
||||
from cptr.utils.agents.events import (
|
||||
AgentDone,
|
||||
AgentError,
|
||||
AgentReasoningDelta,
|
||||
AgentTextDelta,
|
||||
AgentToolUpdate,
|
||||
)
|
||||
from cptr.utils.agents.attachments import prepare_agent_attachments
|
||||
from cptr.utils.model_targets import AgentModelTarget, ApiModelTarget, ModelTarget
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -55,21 +64,30 @@ def start_task(
|
||||
message_id: str,
|
||||
chat_id: str,
|
||||
user_id: str,
|
||||
connection: dict,
|
||||
workspace: str,
|
||||
model: str,
|
||||
model: str = "",
|
||||
connection: dict | None = None,
|
||||
regeneration_prompt: str | None = None,
|
||||
output_queue: asyncio.Queue | None = None,
|
||||
target: ModelTarget | None = None,
|
||||
):
|
||||
"""Launch the agentic loop as a background asyncio.Task."""
|
||||
if target is None:
|
||||
if connection is None:
|
||||
raise ValueError("start_task requires either target or connection")
|
||||
target = ApiModelTarget(
|
||||
kind="api",
|
||||
connection=connection,
|
||||
runtime_model=model,
|
||||
full_model_id=model,
|
||||
)
|
||||
task = asyncio.create_task(
|
||||
run_chat_task(
|
||||
message_id,
|
||||
chat_id,
|
||||
user_id,
|
||||
connection,
|
||||
target,
|
||||
workspace,
|
||||
model,
|
||||
regeneration_prompt,
|
||||
output_queue,
|
||||
)
|
||||
@@ -270,13 +288,13 @@ async def process_pending_chat_inputs(chat_id: str, user_id: str, workspace: str
|
||||
)
|
||||
return
|
||||
|
||||
# Resolve connection
|
||||
# Resolve model target
|
||||
try:
|
||||
from cptr.routers.chat import _resolve_connection
|
||||
from cptr.utils.model_targets import resolve_model_target
|
||||
|
||||
connection, bare_model = await _resolve_connection(model_id)
|
||||
target = await resolve_model_target(model_id)
|
||||
except Exception:
|
||||
logger.exception("[chat-input] Failed to resolve connection for model %s", model_id)
|
||||
logger.exception("[chat-input] Failed to resolve model target for %s", model_id)
|
||||
return
|
||||
|
||||
# Create assistant placeholder
|
||||
@@ -306,9 +324,8 @@ async def process_pending_chat_inputs(chat_id: str, user_id: str, workspace: str
|
||||
message_id=assistant_msg.id,
|
||||
chat_id=chat_id,
|
||||
user_id=user_id,
|
||||
connection=connection,
|
||||
workspace=workspace,
|
||||
model=bare_model,
|
||||
target=target,
|
||||
)
|
||||
logger.info(
|
||||
"[chat-input] Processed %d pending input message(s) for chat %s",
|
||||
@@ -552,11 +569,21 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
# reasoning_items) followed by the corresponding tool-result
|
||||
# messages.
|
||||
if m.output:
|
||||
native_agent_call_ids = {
|
||||
item["call_id"]
|
||||
for item in m.output
|
||||
if item.get("type") == "function_call"
|
||||
and item.get("call_id")
|
||||
and _is_native_agent_tool_item(item)
|
||||
}
|
||||
# ── Collect the set of call_ids that have outputs ──
|
||||
# This is needed to filter out orphaned function_calls
|
||||
# (e.g. from crashes, partial persistence, or data corruption).
|
||||
output_call_ids = {
|
||||
item["call_id"] for item in m.output if item.get("type") == "function_call_output"
|
||||
item["call_id"]
|
||||
for item in m.output
|
||||
if item.get("type") == "function_call_output"
|
||||
and item.get("call_id") not in native_agent_call_ids
|
||||
}
|
||||
|
||||
# ── Group output items into per-iteration turns ──
|
||||
@@ -573,6 +600,8 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
current_turn = {"reasoning": [], "calls": [], "outputs": []}
|
||||
current_turn["reasoning"].append(item)
|
||||
elif itype == "function_call" and item.get("status") == "completed":
|
||||
if item.get("call_id") in native_agent_call_ids:
|
||||
continue
|
||||
# Only include calls that have a matching output
|
||||
if item["call_id"] not in output_call_ids:
|
||||
logger.warning(
|
||||
@@ -598,7 +627,10 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
if item.get("fc_id"):
|
||||
tc["fc_id"] = item["fc_id"]
|
||||
current_turn["calls"].append(tc)
|
||||
elif itype == "function_call_output":
|
||||
elif (
|
||||
itype == "function_call_output"
|
||||
and item.get("call_id") not in native_agent_call_ids
|
||||
):
|
||||
current_turn["outputs"].append(item)
|
||||
# Skip other types (message, artifact, pending calls, etc.)
|
||||
|
||||
@@ -968,6 +1000,38 @@ def _upsert_output_item(items: list[dict], item: dict) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _safe_tool_name(name: str | None) -> str:
|
||||
if not name:
|
||||
return "agent_tool"
|
||||
value = re.sub(r"[^a-zA-Z0-9_-]+", "_", name.strip()).strip("_")
|
||||
return value or "agent_tool"
|
||||
|
||||
|
||||
def _is_native_agent_tool_item(item: dict) -> bool:
|
||||
return bool(
|
||||
item.get("native_agent")
|
||||
or (isinstance(item.get("id"), str) and item["id"].startswith("agent-"))
|
||||
)
|
||||
|
||||
|
||||
def _append_prompt_suffix(messages: list[dict], suffix: str) -> None:
|
||||
if not suffix:
|
||||
return
|
||||
for message in reversed(messages):
|
||||
if message.get("role") != "user":
|
||||
continue
|
||||
content = message.get("content", "")
|
||||
if isinstance(content, list):
|
||||
for block in content:
|
||||
if isinstance(block, dict) and block.get("type") == "text":
|
||||
block["text"] = f"{block.get('text') or ''}{suffix}"
|
||||
return
|
||||
content.append({"type": "text", "text": suffix.strip()})
|
||||
else:
|
||||
message["content"] = f"{content or ''}{suffix}"
|
||||
return
|
||||
|
||||
|
||||
def _find_safe_split(messages: list[dict], target_keep: int) -> int:
|
||||
"""Find a safe split index that doesn't break tool call pairs.
|
||||
|
||||
@@ -1060,9 +1124,8 @@ async def run_chat_task(
|
||||
message_id: str,
|
||||
chat_id: str,
|
||||
user_id: str,
|
||||
connection: dict,
|
||||
target: ModelTarget,
|
||||
workspace: str,
|
||||
model: str,
|
||||
regeneration_prompt: str | None = None,
|
||||
output_queue: asyncio.Queue | None = None,
|
||||
):
|
||||
@@ -1171,7 +1234,191 @@ async def run_chat_task(
|
||||
log("[task %s] db save (%s) result: updated=%s", message_id[:8], save_reason, saved)
|
||||
return saved
|
||||
|
||||
async def save_session(agent_target: AgentModelTarget, resume_state: dict | None):
|
||||
if not resume_state:
|
||||
return
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
if not chat:
|
||||
return
|
||||
meta = dict(chat.meta or {})
|
||||
sessions = dict(meta.get("agent_sessions") or {})
|
||||
sessions[agent_target.profile_id] = {
|
||||
**resume_state,
|
||||
"profile_id": agent_target.profile_id,
|
||||
"agent": agent_target.agent,
|
||||
"model": agent_target.model,
|
||||
"workspace": workspace,
|
||||
"updated_at": now_ms(),
|
||||
}
|
||||
meta["agent_sessions"] = sessions
|
||||
await Chat.update_meta(chat_id, meta, now_ms())
|
||||
|
||||
async def _run_agent_target(agent_target: AgentModelTarget):
|
||||
nonlocal content, text_buffer
|
||||
from cptr.utils.agents.claude_code import run_claude_code_agent
|
||||
from cptr.utils.agents.codex import run_codex_agent
|
||||
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 {}
|
||||
messages, loaded_summary = await _load_message_history(chat_id, message_id)
|
||||
memory_message, memory_files = _memory_recall_inputs(messages, regeneration_prompt)
|
||||
system = await _load_system_prompt(
|
||||
workspace,
|
||||
agent_target.full_model_id,
|
||||
user_id=user_id,
|
||||
current_message=memory_message,
|
||||
recent_messages=messages,
|
||||
mentioned_files=memory_files,
|
||||
)
|
||||
if loaded_summary:
|
||||
system += f"\n\n[CONVERSATION SUMMARY]\n{loaded_summary}"
|
||||
current_user_files = []
|
||||
if msg and msg.parent_id:
|
||||
parent_msg = await ChatMessage.get_by_id(msg.parent_id)
|
||||
meta_files = (parent_msg.meta or {}).get("files") if parent_msg else None
|
||||
if isinstance(meta_files, list):
|
||||
current_user_files = meta_files
|
||||
agent_attachments = await prepare_agent_attachments(
|
||||
workspace=workspace,
|
||||
chat_id=chat_id,
|
||||
message_id=(msg.parent_id if msg and msg.parent_id else message_id),
|
||||
files=current_user_files,
|
||||
)
|
||||
_append_prompt_suffix(messages, agent_attachments.prompt_suffix)
|
||||
if regeneration_prompt:
|
||||
messages.append({"role": "user", "content": regeneration_prompt})
|
||||
if chat_params.get("plan_mode", False):
|
||||
messages.append({"role": "user", "content": PLAN_MODE_PROMPT})
|
||||
system = await _apply_voice_mode_system_prompt(system, chat_params)
|
||||
|
||||
resume_state = None
|
||||
if chat_obj:
|
||||
sessions = (chat_obj.meta or {}).get("agent_sessions") or {}
|
||||
if isinstance(sessions, dict):
|
||||
candidate = sessions.get(agent_target.profile_id)
|
||||
if isinstance(candidate, dict):
|
||||
resume_state = candidate
|
||||
|
||||
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,
|
||||
model=agent_target.model,
|
||||
workspace=workspace,
|
||||
messages=messages,
|
||||
system_prompt=system,
|
||||
chat_params=chat_params,
|
||||
resume_state=resume_state,
|
||||
attachments=agent_attachments,
|
||||
):
|
||||
if isinstance(event, AgentTextDelta):
|
||||
content += event.text
|
||||
text_buffer += event.text
|
||||
await emit(delta=event.text)
|
||||
_sync_state()
|
||||
elif isinstance(event, AgentReasoningDelta):
|
||||
reasoning_buffer += event.text
|
||||
item = {
|
||||
"type": "reasoning",
|
||||
"id": f"reasoning-{message_id}",
|
||||
"status": "in_progress",
|
||||
"content": [{"type": "reasoning_text", "text": reasoning_buffer}],
|
||||
}
|
||||
_upsert_output_item(output_items, item)
|
||||
await emit(output=item)
|
||||
_sync_state()
|
||||
elif isinstance(event, AgentToolUpdate):
|
||||
flushed_item = _flush_text()
|
||||
if flushed_item:
|
||||
await emit(output=flushed_item)
|
||||
existing = next(
|
||||
(
|
||||
item
|
||||
for item in output_items
|
||||
if item.get("type") == "function_call"
|
||||
and item.get("call_id") == event.call_id
|
||||
),
|
||||
{},
|
||||
)
|
||||
call_item = {
|
||||
"type": "function_call",
|
||||
"id": existing.get("id") or f"agent-{event.call_id}",
|
||||
"call_id": event.call_id,
|
||||
"name": _safe_tool_name(event.name or existing.get("name")),
|
||||
"native_agent": True,
|
||||
"arguments": {
|
||||
**(existing.get("arguments") or {}),
|
||||
**(event.arguments or {}),
|
||||
},
|
||||
"status": event.status,
|
||||
}
|
||||
_upsert_output_item(output_items, call_item)
|
||||
await emit(output=call_item)
|
||||
if event.output is not None or event.status == "completed":
|
||||
output_item = {
|
||||
"type": "function_call_output",
|
||||
"call_id": event.call_id,
|
||||
"native_agent": True,
|
||||
"output": event.output or "",
|
||||
}
|
||||
_upsert_output_item(output_items, output_item)
|
||||
await emit(output=output_item)
|
||||
_sync_state()
|
||||
elif isinstance(event, AgentError):
|
||||
raise RuntimeError(event.message)
|
||||
elif isinstance(event, AgentDone):
|
||||
if reasoning_buffer:
|
||||
_upsert_output_item(
|
||||
output_items,
|
||||
{
|
||||
"type": "reasoning",
|
||||
"id": f"reasoning-{message_id}",
|
||||
"status": "completed",
|
||||
"content": [{"type": "reasoning_text", "text": reasoning_buffer}],
|
||||
},
|
||||
)
|
||||
flushed_item = _flush_text()
|
||||
if flushed_item:
|
||||
await emit(output=flushed_item)
|
||||
await save_session(agent_target, event.resume_state)
|
||||
await _save_message(
|
||||
"agent done",
|
||||
content=content,
|
||||
output=output_items,
|
||||
usage=event.usage,
|
||||
done=True,
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
return
|
||||
|
||||
flushed_item = _flush_text()
|
||||
if flushed_item:
|
||||
await emit(output=flushed_item)
|
||||
await _save_message("agent stream ended", content=content, output=output_items, done=True)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
return
|
||||
|
||||
try:
|
||||
if isinstance(target, AgentModelTarget):
|
||||
await _run_agent_target(target)
|
||||
return
|
||||
|
||||
connection = target.connection
|
||||
model = target.runtime_model
|
||||
provider = connection["provider"]
|
||||
api_key = decrypt_key(connection.get("api_key", ""), _get_jwt_secret())
|
||||
base_url = connection.get("base_url") or _default_base_url(provider)
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Resolve selected model ids to API connections or agent profiles."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal, Union
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from cptr.models import Config
|
||||
from cptr.utils.agents.detection import get_agent_status
|
||||
from cptr.utils.agents.models import parse_agent_model_id
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ApiModelTarget:
|
||||
kind: Literal["api"]
|
||||
connection: dict[str, Any]
|
||||
runtime_model: str
|
||||
full_model_id: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AgentModelTarget:
|
||||
kind: Literal["agent"]
|
||||
profile_id: str
|
||||
agent: Literal["codex", "claude_code", "cursor", "grok", "opencode"]
|
||||
model: str
|
||||
full_model_id: str
|
||||
config: dict[str, Any]
|
||||
|
||||
|
||||
ModelTarget = Union[ApiModelTarget, AgentModelTarget]
|
||||
|
||||
|
||||
async def resolve_agent_model_target(model_id: str, app_state=None) -> AgentModelTarget:
|
||||
parsed = parse_agent_model_id(model_id)
|
||||
if parsed is None:
|
||||
raise HTTPException(400, f"not an agent model: {model_id}")
|
||||
|
||||
profile_id, model = parsed
|
||||
status = await get_agent_status(app_state)
|
||||
entry = next((p for p in status["profiles"] if p["id"] == profile_id), None)
|
||||
if entry is None:
|
||||
raise HTTPException(400, f"agent profile not found: {profile_id}")
|
||||
|
||||
profile = entry["config"]
|
||||
if model not in (profile.get("models") or []):
|
||||
raise HTTPException(400, f"model '{model}' is not configured for agent profile {profile_id}")
|
||||
|
||||
if not entry["available"]:
|
||||
detection = entry.get("detected") or {}
|
||||
raise HTTPException(
|
||||
400,
|
||||
f"agent profile {profile_id} is not available: "
|
||||
f"{detection.get('message') or detection.get('status')}",
|
||||
)
|
||||
|
||||
return AgentModelTarget(
|
||||
kind="agent",
|
||||
profile_id=profile["id"],
|
||||
agent=profile["agent"],
|
||||
model=model,
|
||||
full_model_id=model_id,
|
||||
config=profile,
|
||||
)
|
||||
|
||||
|
||||
async def resolve_api_model_target(model_id: str, app_state=None) -> ApiModelTarget:
|
||||
"""Resolve an API-backed model id using the existing connection rules."""
|
||||
from cptr.routers.chat import _resolve_connection
|
||||
|
||||
connection, runtime_model = await _resolve_connection(model_id, app_state)
|
||||
return ApiModelTarget(
|
||||
kind="api",
|
||||
connection=connection,
|
||||
runtime_model=runtime_model,
|
||||
full_model_id=model_id,
|
||||
)
|
||||
|
||||
|
||||
async def resolve_model_target(model_id: str, app_state=None) -> ModelTarget:
|
||||
if parse_agent_model_id(model_id) is not None:
|
||||
return await resolve_agent_model_target(model_id, app_state)
|
||||
return await resolve_api_model_target(model_id, app_state)
|
||||
|
||||
|
||||
async def first_api_model_target(app_state=None) -> ApiModelTarget:
|
||||
from cptr.routers.chat import _fetch_provider_models
|
||||
|
||||
connections = await Config.get("chat.connections") or []
|
||||
for conn in connections:
|
||||
if not conn.get("enabled", True):
|
||||
continue
|
||||
model_ids = conn.get("data", {}).get("models")
|
||||
if not model_ids:
|
||||
model_ids = await _fetch_provider_models(conn)
|
||||
if model_ids:
|
||||
prefix = (conn.get("prefix_id") or "").strip()
|
||||
runtime_model = model_ids[0]
|
||||
full = f"{prefix}/{runtime_model}" if prefix else runtime_model
|
||||
return ApiModelTarget(
|
||||
kind="api",
|
||||
connection=conn,
|
||||
runtime_model=runtime_model,
|
||||
full_model_id=full,
|
||||
)
|
||||
raise HTTPException(503, "No API model connections configured.")
|
||||
+7
-2
@@ -2034,14 +2034,19 @@ async def _run_existing_subagent_chat(
|
||||
"""Run the agent loop for an already-created sub-agent chat."""
|
||||
from cptr.models import ChatMessage
|
||||
from cptr.utils.chat_task import run_chat_task
|
||||
from cptr.utils.model_targets import ApiModelTarget
|
||||
|
||||
await run_chat_task(
|
||||
message_id=assistant_msg_id,
|
||||
chat_id=chat_id,
|
||||
user_id=user_id,
|
||||
connection=connection,
|
||||
target=ApiModelTarget(
|
||||
kind="api",
|
||||
connection=connection,
|
||||
runtime_model=model,
|
||||
full_model_id=model,
|
||||
),
|
||||
workspace=workspace,
|
||||
model=model,
|
||||
)
|
||||
|
||||
result_msg = await ChatMessage.get_by_id(assistant_msg_id)
|
||||
|
||||
+3
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "cptr"
|
||||
version = "0.6.2"
|
||||
version = "0.7.0"
|
||||
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
|
||||
license = {file = "LICENSE"}
|
||||
readme = "README.md"
|
||||
@@ -27,12 +27,14 @@ dependencies = [
|
||||
pam = ["python-pam>=2.0"]
|
||||
mcp = ["mcp>=1.8"]
|
||||
docs = ["pypdf>=4.0", "python-docx>=1.0", "openpyxl>=3.1"]
|
||||
agents = ["claude-agent-sdk>=0.1.62"]
|
||||
all = [
|
||||
"mcp>=1.8",
|
||||
"pypdf>=4.0",
|
||||
"python-docx>=1.0",
|
||||
"openpyxl>=3.1",
|
||||
"python-pam>=2.0",
|
||||
"claude-agent-sdk>=0.1.62",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
|
||||
@@ -242,6 +242,25 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ae/3a/dbeec9d1ee0844c679f6bb5d6ad4e9f198b1224f4e7a32825f47f6192b0c/cffi-2.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0a1527a803f0a659de1af2e1fd700213caba79377e27e4693648c2923da066f9", size = 184195 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "claude-agent-sdk"
|
||||
version = "0.2.110"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "anyio" },
|
||||
{ name = "mcp" },
|
||||
{ name = "sniffio" },
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.11'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/bb/98/8fdab35ed9e1a36bc7afab4d390cc5002094a4950996c079da9aa4541cc4/claude_agent_sdk-0.2.110.tar.gz", hash = "sha256:538b548bac07a22f65686abab063a902ac76ba35989d0f073c942f96248e9fa3", size = 255632 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/aa/93/29d4fdaa13e69034faf8d3503df915b07c820e2c08e3d6a7515149cde5bb/claude_agent_sdk-0.2.110-py3-none-macosx_11_0_arm64.whl", hash = "sha256:fed0e0f4804d9f9cff80ab7d1b44142ebd1046cdd29ca74caef4c92c35fff8d8", size = 64924533 },
|
||||
{ url = "https://files.pythonhosted.org/packages/aa/03/b40bb673cd93cdc3928262c1be75fde34a7bed4bf2c2c20e04218e2005ea/claude_agent_sdk-0.2.110-py3-none-macosx_11_0_x86_64.whl", hash = "sha256:62b23869d46cef6f6ff1d00ceaa5e846e2f1d297478421c835efb8fe99369d4f", size = 69704449 },
|
||||
{ url = "https://files.pythonhosted.org/packages/f9/18/ab67cb5ce641333385bed55ed8e9665c00f7d30d1f6ab12f8463ddb7695f/claude_agent_sdk-0.2.110-py3-none-manylinux_2_17_aarch64.whl", hash = "sha256:324e49553c6303d6b267217dc2912652b97af2bc96503efd12095ae915b46b83", size = 74879555 },
|
||||
{ url = "https://files.pythonhosted.org/packages/91/88/3627d7d14310cfec66977551263e219365244a906fc7ca1209fb0c3a6cec/claude_agent_sdk-0.2.110-py3-none-manylinux_2_17_x86_64.whl", hash = "sha256:56371dd7a2c66c0bd497dc0b3cab4193a228b196f600676393d69c0ecee37cfb", size = 75924237 },
|
||||
{ url = "https://files.pythonhosted.org/packages/49/79/c9066c5c387d42c19a4b675ec1ff5219f8920cfda8ff8b527119fd69b774/claude_agent_sdk-0.2.110-py3-none-win_amd64.whl", hash = "sha256:4235d4de6d685a189c12612095ab192b759280ede1f3aed0c3e784d52c3555f9", size = 75448209 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "click"
|
||||
version = "8.1.8"
|
||||
@@ -265,7 +284,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "cptr"
|
||||
version = "0.5.2"
|
||||
version = "0.6.2"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "aiosqlite" },
|
||||
@@ -286,7 +305,11 @@ dependencies = [
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
agents = [
|
||||
{ name = "claude-agent-sdk" },
|
||||
]
|
||||
all = [
|
||||
{ name = "claude-agent-sdk" },
|
||||
{ name = "mcp" },
|
||||
{ name = "openpyxl" },
|
||||
{ name = "pypdf" },
|
||||
@@ -315,6 +338,8 @@ requires-dist = [
|
||||
{ name = "aiosqlite", specifier = ">=0.20" },
|
||||
{ name = "alembic", specifier = ">=1.13" },
|
||||
{ name = "bcrypt", specifier = ">=4.0" },
|
||||
{ name = "claude-agent-sdk", marker = "extra == 'agents'", specifier = ">=0.1.62" },
|
||||
{ name = "claude-agent-sdk", marker = "extra == 'all'", specifier = ">=0.1.62" },
|
||||
{ name = "click", specifier = ">=8.1" },
|
||||
{ name = "cryptography", specifier = ">=42.0" },
|
||||
{ name = "fastapi", extras = ["standard"], specifier = ">=0.128.8" },
|
||||
@@ -2035,6 +2060,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sniffio"
|
||||
version = "1.3.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a2/87/a6771e1546d97e7e041b6ae58d80074f81b7d5121207425c964ddf5cfdbd/sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc", size = 20372 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlalchemy"
|
||||
version = "2.0.50"
|
||||
|
||||
Reference in new issue
Block a user