mirror of
https://github.com/open-webui/computer.git
synced 2026-11-23 14:10:45 -05:00
38 files changed
+841
-280
No files matched your search
@@ -5,6 +5,32 @@ 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.9.8] - 2026-07-15
|
||||
|
||||
### Added
|
||||
|
||||
- 🏠 **Choose how `.cptr` is handled in projects.** Admins can now turn the automatic `.gitignore` entry on or off, so local chats, memory, caches, audio samples, and generated files stay private by default unless you choose otherwise.
|
||||
- 🤖 **A llama.cpp connection mode.** OpenAI-compatible connections can now be marked as llama.cpp, so Qwen and other local reasoning models can receive prior thinking in the format llama.cpp expects.
|
||||
- 🧩 **Skills can open their own companion files.** `view_skill` can now load files such as `references/guide.md` from the selected skill folder, without opening broader home-directory access.
|
||||
- 🌐 **Sized browser screenshots.** Browser tasks can request a screenshot at a specific size and Computer will restore the normal page view afterward.
|
||||
|
||||
### Changed
|
||||
|
||||
- ⚙️ **Admin switches behave like switches.** In Models, Agents, Connections, Messaging, and Tool Servers, click the row text to edit and click the switch only to turn something on or off.
|
||||
- 🔎 **Workspace search respects `.gitignore`.** File search and content search now skip ignored folders and files, keeping generated output, caches, and local Computer data out of normal results.
|
||||
- 🧠 **Reasoning replay is stricter by default.** Computer now keeps strict OpenAI-compatible connections clean, and only sends llama.cpp-style `reasoning_content` when the connection is set to llama.cpp.
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🧠 **The chat size meter no longer freezes behind llama.cpp.** Computer now normalizes token usage from OpenAI-compatible streams and sends live context updates to the chat while a response is still running.
|
||||
- 💬 **Compacted chats survive regenerated answers better.** Summaries are saved on a stable kept user message when possible, so regenerating an assistant answer is less likely to lose the compacted history.
|
||||
- ✂️ **Manual compact keeps the latest turn available.** Compacting a chat now summarizes the older branch and leaves the newest message ready for the next response.
|
||||
- 🧠 **Prior reasoning is preserved more reliably.** Reasoning from ordinary replies, tool-call turns, Chat Completions streams, and Responses streams is less likely to be dropped before the next model request.
|
||||
- 🎨 **Token usage details match the chosen theme.** The usage popover now uses Computer's app surface colors instead of the wrong gray background.
|
||||
- ✨ **Messages render more faithfully.** Your own messages can show Markdown, and raw markup appears as text instead of disappearing.
|
||||
- 🗂️ **Commit suggestions are less brittle.** If the model returns a plain commit message instead of perfect structured output, Computer can still use the useful parts.
|
||||
- 📝 **File edits keep text encoding consistent.** Created and edited files are written as UTF-8, which avoids surprises with non-ASCII project files.
|
||||
|
||||
## [0.9.7] - 2026-07-12
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -66,6 +66,10 @@ CHAT_COMPACT_TOKEN_THRESHOLD = int(os.environ.get("CHAT_COMPACT_TOKEN_THRESHOLD"
|
||||
# Claude SDK stdout JSON buffer; chat/tool output caps apply later after parsing.
|
||||
CLAUDE_CODE_MAX_BUFFER_SIZE = _env_int("CPTR_CLAUDE_CODE_MAX_BUFFER_SIZE", 128 * 1024 * 1024)
|
||||
|
||||
# ── Workspace storage ───────────────────────────────────────
|
||||
WORKSPACE_AUTO_GITIGNORE_DOT_CPTR_ENV = os.environ.get("CPTR_AUTO_GITIGNORE_DOT_CPTR")
|
||||
WORKSPACE_AUTO_GITIGNORE_DOT_CPTR = _env_bool("CPTR_AUTO_GITIGNORE_DOT_CPTR", "true")
|
||||
|
||||
# ── Execute timeout ─────────────────────────────────────────
|
||||
# Default wait (seconds) for run_command / check_task when the caller
|
||||
# doesn't pass an explicit wait value. None = return immediately.
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.4.0",
|
||||
"version": "0.4.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "frontend",
|
||||
"version": "0.3.4",
|
||||
"version": "0.4.1",
|
||||
"dependencies": {
|
||||
"@codemirror/lang-cpp": "^6.0.3",
|
||||
"@codemirror/lang-css": "^6.3.1",
|
||||
|
||||
@@ -93,4 +93,4 @@
|
||||
"tippy.js": "^6.3.7",
|
||||
"xlsx": "^0.18.5"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,8 +29,8 @@
|
||||
--app-fg: #525252;
|
||||
--app-fg-muted: color-mix(in oklab, var(--app-fg) 62%, var(--app-bg));
|
||||
--app-fg-subtle: color-mix(in oklab, var(--app-fg) 48%, var(--app-bg));
|
||||
--app-border: color-mix(in oklab, var(--app-fg) 7%, transparent);
|
||||
--app-divider: color-mix(in oklab, var(--app-fg) 5%, transparent);
|
||||
--app-border: color-mix(in oklab, var(--app-fg) 5%, transparent);
|
||||
--app-divider: color-mix(in oklab, var(--app-fg) 3.5%, transparent);
|
||||
--app-hover: color-mix(in oklab, var(--app-fg) 6%, transparent);
|
||||
--app-active: color-mix(in oklab, var(--app-fg) 7%, transparent);
|
||||
--app-ui-font: var(--font-sans);
|
||||
|
||||
@@ -130,6 +130,7 @@ export interface Connection {
|
||||
name: string;
|
||||
provider: string;
|
||||
api_type: string;
|
||||
provider_type?: 'default' | 'llama.cpp' | null;
|
||||
prefix_id: string | null;
|
||||
base_url: string | null;
|
||||
api_key: string | null;
|
||||
@@ -146,6 +147,7 @@ export const createConnection = (conn: {
|
||||
name: string;
|
||||
provider: string;
|
||||
api_type?: string;
|
||||
provider_type?: 'default' | 'llama.cpp' | null;
|
||||
prefix_id?: string | null;
|
||||
base_url?: string | null;
|
||||
api_key?: string | null;
|
||||
|
||||
@@ -171,8 +171,11 @@ export const answerAskUser = (
|
||||
export const cancelTask = (chatId: string, messageId: string) =>
|
||||
fetchJSON(`/api/chats/${chatId}/messages/${messageId}/cancel`, { method: 'POST' });
|
||||
|
||||
export const compactChat = (chatId: string, modelId: string) =>
|
||||
fetchJSON<CompactChatResult>(`/api/chats/${chatId}/compact`, jsonBody({ model_id: modelId }));
|
||||
export const compactChat = (chatId: string, modelId?: string | null) =>
|
||||
fetchJSON<CompactChatResult>(
|
||||
`/api/chats/${chatId}/compact`,
|
||||
jsonBody({ model_id: modelId || null })
|
||||
);
|
||||
|
||||
export const updateCurrentMessage = (chatId: string, messageId: string) =>
|
||||
fetchJSON<{ ok: boolean }>(`/api/chats/${chatId}/current`, jsonBody({ message_id: messageId }));
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
} from '$lib/apis/admin';
|
||||
import Icon from '$lib/components/Icon.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
import { refreshChatState } from '$lib/stores/chat';
|
||||
import AgentProfileModal from './AgentProfileModal.svelte';
|
||||
@@ -179,8 +180,7 @@
|
||||
modal = null;
|
||||
}
|
||||
|
||||
function toggleProfile(e: Event, index: number) {
|
||||
e.stopPropagation();
|
||||
function toggleProfile(index: number) {
|
||||
const profile = profiles[index];
|
||||
if (!profile) return;
|
||||
const mode = profile.mode === 'disabled' ? 'enabled' : 'disabled';
|
||||
@@ -262,11 +262,12 @@
|
||||
{: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">
|
||||
<div class="group flex items-center gap-2 w-full min-h-9 py-1.5 text-left">
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 min-w-0 text-left"
|
||||
onclick={() => (modal = { mode: 'edit', index, profile })}
|
||||
>
|
||||
<span
|
||||
class="block text-[0.8125rem] truncate {profile.mode === 'disabled'
|
||||
? 'text-gray-400 dark:text-gray-600'
|
||||
@@ -282,36 +283,15 @@
|
||||
{detected[profile.id]?.message}
|
||||
</span>
|
||||
{/if}
|
||||
</span>
|
||||
</button>
|
||||
<span
|
||||
class="hidden sm:flex items-center gap-1.5 shrink-0 text-[0.6875rem] 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>
|
||||
<ToggleSwitch value={profile.mode !== 'disabled'} onchange={() => toggleProfile(index)} />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import { refreshChatState } from '$lib/stores/chat';
|
||||
import { t } from '$lib/i18n';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
|
||||
|
||||
let connections = $state<Connection[]>([]);
|
||||
let loading = $state(true);
|
||||
@@ -35,9 +36,7 @@
|
||||
load();
|
||||
}
|
||||
|
||||
async function toggleEnabled(e: Event, conn: Connection) {
|
||||
e.stopPropagation();
|
||||
const newVal = !conn.enabled;
|
||||
async function toggleEnabled(conn: Connection, newVal: boolean) {
|
||||
// Optimistic update
|
||||
conn.enabled = newVal;
|
||||
connections = [...connections];
|
||||
@@ -72,37 +71,17 @@
|
||||
{:else}
|
||||
<div>
|
||||
{#each connections as conn}
|
||||
<button
|
||||
class="group flex items-center gap-2 w-full h-7 text-left"
|
||||
onclick={() => (editConn = conn)}
|
||||
>
|
||||
<span
|
||||
class="flex-1 text-[0.8125rem] truncate
|
||||
<div class="group flex items-center gap-2 w-full h-7 text-left">
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 min-w-0 text-left text-[0.8125rem] truncate
|
||||
{conn.enabled ? 'text-gray-700 dark:text-gray-300' : 'text-gray-400 dark:text-gray-600'}"
|
||||
onclick={() => (editConn = conn)}
|
||||
>
|
||||
{conn.name}
|
||||
</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
|
||||
{conn.enabled ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
|
||||
role="switch"
|
||||
tabindex="-1"
|
||||
aria-checked={conn.enabled}
|
||||
onclick={(e) => toggleEnabled(e, conn)}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleEnabled(e, conn);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
|
||||
{conn.enabled ? 'left-3 bg-white dark:bg-gray-900' : 'left-0.5 bg-white dark:bg-gray-500'}"
|
||||
></span>
|
||||
</span>
|
||||
</button>
|
||||
</button>
|
||||
<ToggleSwitch value={conn.enabled} onchange={(value) => toggleEnabled(conn, value)} />
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
{#if connections.length === 0}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
let formName = $state('');
|
||||
let formProvider = $state<'openai' | 'anthropic'>('openai');
|
||||
let formApiType = $state<'chat_completions' | 'responses'>('chat_completions');
|
||||
let formProviderType = $state<'default' | 'llama.cpp'>('default');
|
||||
let formBaseUrl = $state('');
|
||||
let formApiKey = $state('');
|
||||
let formPrefixId = $state('');
|
||||
@@ -49,6 +50,7 @@
|
||||
name,
|
||||
provider: formProvider,
|
||||
api_type: formProvider === 'openai' ? formApiType : 'chat_completions',
|
||||
provider_type: formProvider === 'openai' ? formProviderType : 'default',
|
||||
prefix_id: formPrefixId.trim() || null,
|
||||
base_url: formBaseUrl.trim(),
|
||||
api_key: formApiKey.trim(),
|
||||
@@ -115,6 +117,21 @@
|
||||
<option value="chat_completions">{$t('connections.chatCompletions')}</option>
|
||||
<option value="responses">{$t('connections.responses')}</option>
|
||||
</select>
|
||||
|
||||
<label
|
||||
for="create-provider-type"
|
||||
class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>
|
||||
Provider Type
|
||||
</label>
|
||||
<select
|
||||
id="create-provider-type"
|
||||
bind:value={formProviderType}
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer"
|
||||
>
|
||||
<option value="default">Default</option>
|
||||
<option value="llama.cpp">llama.cpp</option>
|
||||
</select>
|
||||
{/if}
|
||||
|
||||
<label class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2"
|
||||
|
||||
@@ -27,6 +27,9 @@
|
||||
let formApiType = $state<'chat_completions' | 'responses'>(
|
||||
connection.api_type === 'responses' ? 'responses' : 'chat_completions'
|
||||
);
|
||||
let formProviderType = $state<'default' | 'llama.cpp'>(
|
||||
connection.provider_type === 'llama.cpp' ? 'llama.cpp' : 'default'
|
||||
);
|
||||
let formBaseUrl = $state(connection.base_url || '');
|
||||
let formApiKey = $state('');
|
||||
let formPrefixId = $state(connection.prefix_id || '');
|
||||
@@ -61,6 +64,7 @@
|
||||
name,
|
||||
provider: formProvider,
|
||||
api_type: formProvider === 'openai' ? formApiType : 'chat_completions',
|
||||
provider_type: formProvider === 'openai' ? formProviderType : 'default',
|
||||
prefix_id: formPrefixId.trim() || null,
|
||||
base_url: formBaseUrl.trim(),
|
||||
models
|
||||
@@ -151,6 +155,21 @@
|
||||
<option value="chat_completions">{$t('connections.chatCompletions')}</option>
|
||||
<option value="responses">{$t('connections.responses')}</option>
|
||||
</select>
|
||||
|
||||
<label
|
||||
for="edit-provider-type"
|
||||
class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>
|
||||
Provider Type
|
||||
</label>
|
||||
<select
|
||||
id="edit-provider-type"
|
||||
bind:value={formProviderType}
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer"
|
||||
>
|
||||
<option value="default">Default</option>
|
||||
<option value="llama.cpp">llama.cpp</option>
|
||||
</select>
|
||||
{/if}
|
||||
|
||||
<label class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2"
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { listBots, deleteBot, startBot, stopBot, type BotData } from '$lib/apis/bots';
|
||||
import { t } from '$lib/i18n';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
|
||||
|
||||
let bots = $state<BotData[]>([]);
|
||||
let loading = $state(true);
|
||||
@@ -29,8 +30,7 @@
|
||||
load();
|
||||
}
|
||||
|
||||
async function toggleRunning(e: Event, bot: BotData) {
|
||||
e.stopPropagation();
|
||||
async function toggleRunning(bot: BotData) {
|
||||
const wasRunning = bot.is_running;
|
||||
// Optimistic
|
||||
bot.is_running = !wasRunning;
|
||||
@@ -108,27 +108,7 @@
|
||||
<Icon name="trash" size={11} />
|
||||
</button>
|
||||
|
||||
<!-- Toggle switch -->
|
||||
<!-- 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
|
||||
{bot.is_running ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
|
||||
role="switch"
|
||||
tabindex="-1"
|
||||
aria-checked={bot.is_running}
|
||||
onclick={(e) => toggleRunning(e, bot)}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleRunning(e, bot);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
|
||||
{bot.is_running ? 'left-3 bg-white dark:bg-gray-900' : 'left-0.5 bg-white dark:bg-gray-500'}"
|
||||
></span>
|
||||
</span>
|
||||
<ToggleSwitch value={bot.is_running} onchange={() => toggleRunning(bot)} />
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
|
||||
@@ -278,9 +278,7 @@ Files:
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleModel(e: Event, model: ModelEntry) {
|
||||
e.stopPropagation();
|
||||
const newVal = !model.is_active;
|
||||
async function toggleModel(model: ModelEntry, newVal: boolean) {
|
||||
model.is_active = newVal;
|
||||
models = [...models];
|
||||
try {
|
||||
@@ -659,38 +657,18 @@ Files:
|
||||
|
||||
<!-- Per-model list -->
|
||||
{#each models as model}
|
||||
<button
|
||||
class="group flex items-center gap-2 w-full h-7 text-left"
|
||||
onclick={() => (selectedId = selectedId === model.id ? null : model.id)}
|
||||
>
|
||||
<span
|
||||
class="flex-1 text-[0.8125rem] truncate {model.is_active
|
||||
<div class="group flex items-center gap-2 w-full h-7 text-left">
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 min-w-0 text-left text-[0.8125rem] truncate {model.is_active
|
||||
? 'text-gray-700 dark:text-gray-300'
|
||||
: 'text-gray-400 dark:text-gray-600'}"
|
||||
onclick={() => (selectedId = selectedId === model.id ? null : model.id)}
|
||||
>
|
||||
{model.name}
|
||||
</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
|
||||
{model.is_active ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
|
||||
role="switch"
|
||||
tabindex="-1"
|
||||
aria-checked={model.is_active}
|
||||
onclick={(e) => toggleModel(e, model)}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleModel(e, model);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
|
||||
{model.is_active ? 'left-3 bg-white dark:bg-gray-900' : 'left-0.5 bg-white dark:bg-gray-500'}"
|
||||
></span>
|
||||
</span>
|
||||
</button>
|
||||
</button>
|
||||
<ToggleSwitch value={model.is_active} onchange={(value) => toggleModel(model, value)} />
|
||||
</div>
|
||||
|
||||
{#if selectedId === model.id}
|
||||
{@render compactThresholdField(
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import Icon from '../Icon.svelte';
|
||||
import Modal from '../Modal.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import {
|
||||
listToolServers,
|
||||
@@ -188,9 +189,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleEnabled(e: Event, s: ToolServer) {
|
||||
e.stopPropagation();
|
||||
const newVal = !s.enabled;
|
||||
async function toggleEnabled(s: ToolServer, newVal: boolean) {
|
||||
s.enabled = newVal;
|
||||
servers = [...servers];
|
||||
try {
|
||||
@@ -222,10 +221,7 @@
|
||||
{:else}
|
||||
<div>
|
||||
{#each servers as s}
|
||||
<button
|
||||
class="group flex items-center gap-2 w-full h-7 text-left"
|
||||
onclick={() => openEdit(s)}
|
||||
>
|
||||
<div class="group flex items-center gap-2 w-full h-7 text-left">
|
||||
<span
|
||||
class="text-[0.625rem] font-mono shrink-0
|
||||
{s.type === 'mcp' || s.type === 'mcp_stdio'
|
||||
@@ -234,33 +230,16 @@
|
||||
>
|
||||
{s.type === 'mcp' ? 'MCP' : s.type === 'mcp_stdio' ? 'STDIO' : 'API'}
|
||||
</span>
|
||||
<span
|
||||
class="flex-1 text-[0.8125rem] truncate
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 min-w-0 text-left text-[0.8125rem] truncate
|
||||
{s.enabled ? 'text-gray-700 dark:text-gray-300' : 'text-gray-400 dark:text-gray-600'}"
|
||||
onclick={() => openEdit(s)}
|
||||
>
|
||||
{s.name || s.command || s.url}
|
||||
</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
|
||||
{s.enabled ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
|
||||
role="switch"
|
||||
tabindex="-1"
|
||||
aria-checked={s.enabled}
|
||||
onclick={(e) => toggleEnabled(e, s)}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleEnabled(e, s);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span
|
||||
class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
|
||||
{s.enabled ? 'left-3 bg-white dark:bg-gray-900' : 'left-0.5 bg-white dark:bg-gray-500'}"
|
||||
></span>
|
||||
</span>
|
||||
</button>
|
||||
</button>
|
||||
<ToggleSwitch value={s.enabled} onchange={(value) => toggleEnabled(s, value)} />
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
{#if servers.length === 0}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { getAdminConfig, updateConfig } from '$lib/apis/admin';
|
||||
import { t } from '$lib/i18n';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
|
||||
|
||||
let loading = $state(true);
|
||||
let saving = $state(false);
|
||||
let autoGitignoreDotCptr = $state(true);
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
const config = await getAdminConfig();
|
||||
autoGitignoreDotCptr = config['workspace.auto_gitignore_dot_cptr'] !== false;
|
||||
} catch {
|
||||
toast.error($t('admin.failedToLoadConfig'));
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
});
|
||||
|
||||
async function save() {
|
||||
saving = true;
|
||||
try {
|
||||
await updateConfig({ 'workspace.auto_gitignore_dot_cptr': autoGitignoreDotCptr });
|
||||
toast.success($t('settings.saved'));
|
||||
} catch {
|
||||
toast.error($t('admin.failedToSave'));
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col min-h-full">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">{$t('admin.workspace')}</h2>
|
||||
|
||||
{#if loading}
|
||||
<div class="flex justify-center py-8"><Spinner size={16} /></div>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400"
|
||||
>{$t('admin.workspaceAutoGitignoreDotCptr')}</span
|
||||
>
|
||||
<ToggleSwitch
|
||||
value={autoGitignoreDotCptr}
|
||||
onchange={(value) => {
|
||||
autoGitignoreDotCptr = value;
|
||||
}}
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600 -mt-1">
|
||||
{$t('admin.workspaceAutoGitignoreDotCptrHint')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="mt-auto pt-6 flex justify-end">
|
||||
<button
|
||||
class="text-[0.8125rem] 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}>{$t('settings.save')}</button
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -21,6 +21,7 @@
|
||||
import AdminWeb from './Admin/Web.svelte';
|
||||
import ToolServers from './Admin/ToolServers.svelte';
|
||||
import Subagents from './Admin/Subagents.svelte';
|
||||
import Workspace from './Admin/Workspace.svelte';
|
||||
import { session } from '$lib/session';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
@@ -43,7 +44,8 @@
|
||||
| 'images'
|
||||
| 'web'
|
||||
| 'toolservers'
|
||||
| 'subagents';
|
||||
| 'subagents'
|
||||
| 'workspace';
|
||||
|
||||
interface Props {
|
||||
onclose: () => void;
|
||||
@@ -71,6 +73,7 @@
|
||||
'web',
|
||||
'toolservers',
|
||||
'subagents',
|
||||
'workspace',
|
||||
'memory',
|
||||
'skills'
|
||||
];
|
||||
@@ -99,6 +102,7 @@
|
||||
{ id: 'web', label: $t('admin.web'), icon: 'globe' },
|
||||
{ id: 'toolservers', label: $t('admin.toolServers'), icon: 'plug' },
|
||||
{ id: 'subagents', label: $t('admin.subagents'), icon: 'user' },
|
||||
{ id: 'workspace', label: $t('admin.workspace'), icon: 'folder' },
|
||||
{ id: 'memory', label: $t('settings.memory'), icon: 'brain' },
|
||||
{ id: 'skills', label: 'Skills', icon: 'spark' }
|
||||
]);
|
||||
@@ -218,6 +222,8 @@
|
||||
<ToolServers />
|
||||
{:else if activeTab === 'subagents'}
|
||||
<Subagents />
|
||||
{:else if activeTab === 'workspace'}
|
||||
<Workspace />
|
||||
{/if}
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -754,7 +754,7 @@
|
||||
onmouseenter={() => (showUsageTooltip = true)}
|
||||
onmouseleave={() => (showUsageTooltip = false)}
|
||||
aria-label={$t('chat.usageInfo')}
|
||||
use:tooltip={$t('chat.usageInfo')}
|
||||
use:tooltip={showUsageTooltip ? null : $t('chat.usageInfo')}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
@@ -774,18 +774,15 @@
|
||||
{#if showUsageTooltip}
|
||||
<div
|
||||
class="absolute bottom-full left-1/2 -translate-x-1/2 mb-1.5 z-50
|
||||
bg-gray-900 dark:bg-gray-800 text-gray-100 dark:text-gray-100
|
||||
rounded-lg shadow-lg px-2.5 py-1.5 text-[0.625rem] font-mono
|
||||
app-surface rounded-lg shadow-lg px-2.5 py-1.5 text-[0.625rem] font-mono
|
||||
whitespace-nowrap pointer-events-none
|
||||
min-w-[10rem] border border-transparent dark:border-gray-700"
|
||||
min-w-[10rem] border"
|
||||
>
|
||||
<div class="space-y-0.5">
|
||||
{#each Object.entries(usage) as [key, value]}
|
||||
<div class="flex justify-between gap-4">
|
||||
<span class="text-gray-400 dark:text-gray-400">{formatUsageLabel(key)}</span>
|
||||
<span class="tabular-nums text-white dark:text-gray-200"
|
||||
>{formatUsageValue(key, value)}</span
|
||||
>
|
||||
<span class="app-muted">{formatUsageLabel(key)}</span>
|
||||
<span class="tabular-nums">{formatUsageValue(key, value)}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
@@ -794,7 +791,8 @@
|
||||
class="absolute top-full left-1/2 -translate-x-1/2 w-0 h-0
|
||||
border-l-[0.3125rem] border-l-transparent
|
||||
border-r-[0.3125rem] border-r-transparent
|
||||
border-t-[0.3125rem] border-t-gray-900 dark:border-t-gray-800"
|
||||
border-t-[0.3125rem]"
|
||||
style="border-top-color: var(--app-bg);"
|
||||
></div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -532,6 +532,7 @@
|
||||
delta?: string;
|
||||
output?: any;
|
||||
tasks?: ChatTask[];
|
||||
context_usage?: ContextUsage | null;
|
||||
done?: boolean;
|
||||
error?: string;
|
||||
pending_inputs_processed?: boolean;
|
||||
@@ -574,6 +575,9 @@
|
||||
chatTitle = data.title;
|
||||
updateTab(tabId, data.chat_id, data.title);
|
||||
}
|
||||
if (data.context_usage) {
|
||||
contextUsage = data.context_usage;
|
||||
}
|
||||
|
||||
// Follow-up state changed server-side: reload to see new transcript/generation state.
|
||||
if (data.pending_inputs_processed || data.async_subagent_pending) {
|
||||
@@ -1024,12 +1028,12 @@
|
||||
toast.message($t('chat.compactNoChat'));
|
||||
return;
|
||||
}
|
||||
if (!selectedModel || sending || streaming) return;
|
||||
if (sending || streaming) return;
|
||||
sending = true;
|
||||
inputText = '';
|
||||
const toastId = toast.loading($t('chat.compacting'));
|
||||
try {
|
||||
const result = await apiCompactChat(chatId, selectedModel);
|
||||
const result = await apiCompactChat(chatId, selectedModel || null);
|
||||
contextUsage = result.context_usage ?? contextUsage;
|
||||
if (result.compacted) {
|
||||
toast.success($t('chat.compactDone'), { id: toastId });
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { tick } from 'svelte';
|
||||
import Icon from '../Icon.svelte';
|
||||
import MarkdownRenderer from '$lib/components/markdown/MarkdownRenderer.svelte';
|
||||
import MessageTimestamp from './MessageTimestamp.svelte';
|
||||
import { fileIconName } from '$lib/utils/fileIcon';
|
||||
import { openFileTab, setFileBrowserCwd, setActiveTab } from '$lib/stores';
|
||||
@@ -245,11 +246,10 @@
|
||||
{/if}
|
||||
<div class="flex justify-end">
|
||||
<div class="max-w-[90%] px-4 py-2 rounded-3xl app-interactive-active">
|
||||
<div
|
||||
class="text-[0.8125rem] leading-relaxed text-gray-900 dark:text-gray-200 whitespace-pre-wrap break-words"
|
||||
>
|
||||
{#each parsedContent as segment}{#if segment.type === 'text'}{segment.value}{:else}{@const isDir =
|
||||
segment.path.endsWith('/')}{@const cleanPath = isDir
|
||||
<div class="text-[0.8125rem] leading-relaxed text-gray-900 dark:text-gray-200 break-words">
|
||||
{#each parsedContent as segment}{#if segment.type === 'text'}<MarkdownRenderer
|
||||
content={segment.value}
|
||||
/>{:else}{@const isDir = segment.path.endsWith('/')}{@const cleanPath = isDir
|
||||
? segment.path.slice(0, -1)
|
||||
: segment.path}<button
|
||||
class="inline-flex items-center gap-0.5 bg-blue-500/10 text-blue-400 rounded px-1.5 py-px mx-0.5 text-xs font-mono align-baseline border-none cursor-pointer hover:bg-blue-500/20 transition-colors"
|
||||
|
||||
@@ -3,18 +3,25 @@
|
||||
value: boolean;
|
||||
onchange?: (value: boolean) => void;
|
||||
disabled?: boolean;
|
||||
ariaLabel?: string;
|
||||
}
|
||||
let { value, onchange, disabled = false, ariaLabel = 'Toggle' }: Props = $props();
|
||||
|
||||
function toggle(event: MouseEvent) {
|
||||
event.stopPropagation();
|
||||
onchange?.(!value);
|
||||
}
|
||||
let { value, onchange, disabled = false }: Props = $props();
|
||||
</script>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="relative w-7 h-4 rounded-full transition-colors duration-150 shrink-0
|
||||
{value ? 'bg-gray-900 dark:bg-white' : 'bg-gray-300 dark:bg-gray-700'}"
|
||||
onclick={() => onchange?.(!value)}
|
||||
onclick={toggle}
|
||||
{disabled}
|
||||
role="switch"
|
||||
aria-checked={value}
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
<span
|
||||
class="absolute top-[0.125rem] w-3 h-3 rounded-full transition-all duration-150
|
||||
|
||||
@@ -153,7 +153,7 @@
|
||||
{token.raw}
|
||||
{/if}
|
||||
{:else if token.type === 'html'}
|
||||
<!-- Skip raw HTML for safety -->
|
||||
{(token as Tokens.HTML).text || token.raw}
|
||||
{:else if token.type === 'def'}
|
||||
<!-- Link reference definition, no visual output -->
|
||||
{:else if token.type === 'space'}
|
||||
|
||||
@@ -141,6 +141,8 @@
|
||||
class="text-blue-500 dark:text-blue-400 bg-blue-500/8 dark:bg-blue-400/10 rounded px-1 cursor-pointer hover:underline transition-colors"
|
||||
title={$t('markdown.linkTo', { target: wl.target })}>{wl.label}</span
|
||||
>
|
||||
{:else}
|
||||
{item.raw}
|
||||
{/if}
|
||||
{/if}
|
||||
{/each}
|
||||
@@ -274,6 +274,9 @@
|
||||
"admin.minCharsPassword": "Min 6 characters",
|
||||
"admin.connections": "Connections",
|
||||
"admin.agents": "Agents",
|
||||
"admin.workspace": "Workspace",
|
||||
"admin.workspaceAutoGitignoreDotCptr": "Add .cptr to .gitignore",
|
||||
"admin.workspaceAutoGitignoreDotCptrHint": "Keeps local chats, memory, caches, and generated assets out of git by default. Turn this off if you want to track .cptr and manage exclusions inside .cptr/.gitignore.",
|
||||
"admin.agentsRefresh": "Refresh",
|
||||
"admin.agentsAddProfile": "Add profile",
|
||||
"admin.agentsDeleteProfile": "Delete",
|
||||
|
||||
@@ -235,6 +235,9 @@ async def create_connection(body: CreateConnectionRequest, request: Request):
|
||||
"name": body.name,
|
||||
"provider": body.provider,
|
||||
"api_type": body.api_type, # "chat_completions" | "responses" (openai only)
|
||||
"provider_type": "llama.cpp"
|
||||
if body.provider == "openai" and body.provider_type == "llama.cpp"
|
||||
else "default",
|
||||
"prefix_id": body.prefix_id,
|
||||
"base_url": body.base_url,
|
||||
"api_key": encrypt_key(body.api_key, _get_jwt_secret()) if body.api_key else None,
|
||||
@@ -260,8 +263,16 @@ async def update_connection(conn_id: str, body: UpdateConnectionRequest, request
|
||||
conn["name"] = body.name
|
||||
if body.provider is not None:
|
||||
conn["provider"] = body.provider
|
||||
if body.provider != "openai":
|
||||
conn["provider_type"] = "default"
|
||||
if body.api_type is not None:
|
||||
conn["api_type"] = body.api_type
|
||||
if "provider_type" in body.model_fields_set:
|
||||
conn["provider_type"] = (
|
||||
"llama.cpp"
|
||||
if conn.get("provider") == "openai" and body.provider_type == "llama.cpp"
|
||||
else "default"
|
||||
)
|
||||
if body.prefix_id is not None:
|
||||
conn["prefix_id"] = body.prefix_id or None
|
||||
if body.base_url is not None:
|
||||
@@ -389,6 +400,7 @@ class CreateConnectionRequest(BaseModel):
|
||||
name: str
|
||||
provider: str # "anthropic" | "openai"
|
||||
api_type: str = "chat_completions" # "chat_completions" | "responses" (openai only)
|
||||
provider_type: Optional[str] = None # None | "default" | "llama.cpp" (openai only)
|
||||
prefix_id: Optional[str] = None # e.g. "openrouter" → "openrouter/model-id"
|
||||
base_url: Optional[str] = None
|
||||
api_key: Optional[str] = None
|
||||
@@ -400,6 +412,7 @@ class UpdateConnectionRequest(BaseModel):
|
||||
name: Optional[str] = None
|
||||
provider: Optional[str] = None
|
||||
api_type: Optional[str] = None
|
||||
provider_type: Optional[str] = None
|
||||
prefix_id: Optional[str] = None
|
||||
base_url: Optional[str] = None
|
||||
api_key: Optional[str] = None
|
||||
|
||||
@@ -72,8 +72,8 @@ def _get_user(request: Request) -> str:
|
||||
def _workspace_audio_cache_dir(workspace: str | None, kind: str) -> Path | None:
|
||||
# Voice samples are project context, so they live under the workspace .cptr
|
||||
# folder and move with the project. That keeps STT and TTS artifacts available
|
||||
# for reuse, debugging, and the local data flywheel while ensure_cptr_gitignored
|
||||
# keeps them out of git.
|
||||
# for reuse, debugging, and the local data flywheel. By default,
|
||||
# ensure_cptr_gitignored keeps them out of git.
|
||||
if not workspace:
|
||||
return None
|
||||
ws = Path(workspace).expanduser().resolve()
|
||||
|
||||
+22
-14
@@ -457,6 +457,7 @@ async def _get_chat_context_usage(chat, model_id: str | None = None) -> dict | N
|
||||
estimate_context_usage,
|
||||
estimate_messages_tokens,
|
||||
load_compact_token_threshold,
|
||||
usage_context_tokens,
|
||||
)
|
||||
|
||||
messages, existing_summary = await _load_message_history(chat.id, message_id)
|
||||
@@ -470,9 +471,8 @@ async def _get_chat_context_usage(chat, model_id: str | None = None) -> dict | N
|
||||
usage_checkpoint = await _get_latest_usage_checkpoint(chat.id, message_id)
|
||||
if usage_checkpoint:
|
||||
trailing_messages, usage = usage_checkpoint
|
||||
tokens = usage.get("input_tokens")
|
||||
if isinstance(tokens, int) and tokens > 0:
|
||||
tokens += usage.get("output_tokens", 0)
|
||||
tokens = usage_context_tokens(usage)
|
||||
if tokens > 0:
|
||||
if trailing_messages:
|
||||
tokens += estimate_messages_tokens(
|
||||
[{"role": m.role, "content": m.content or ""} for m in trailing_messages]
|
||||
@@ -495,6 +495,8 @@ async def _infer_chat_model(chat_id: str) -> str:
|
||||
async def _get_latest_usage_checkpoint(
|
||||
chat_id: str, message_id: str
|
||||
) -> tuple[list[ChatMessage], dict] | None:
|
||||
from cptr.utils.context import normalize_usage, usage_context_tokens
|
||||
|
||||
all_msgs = await ChatMessage.get_all_by_chat(chat_id)
|
||||
msg_map = {m.id: m for m in all_msgs}
|
||||
chain = []
|
||||
@@ -508,8 +510,8 @@ async def _get_latest_usage_checkpoint(
|
||||
message = chain[index]
|
||||
if message.chat_summary:
|
||||
return None
|
||||
usage = message.usage or {}
|
||||
if message.role == "assistant" and usage.get("input_tokens"):
|
||||
usage = normalize_usage(message.usage)
|
||||
if message.role == "assistant" and usage_context_tokens(usage):
|
||||
return chain[index + 1 :], usage
|
||||
return None
|
||||
|
||||
@@ -700,7 +702,7 @@ class SendMessageRequest(BaseModel):
|
||||
|
||||
|
||||
class CompactRequest(BaseModel):
|
||||
model_id: str
|
||||
model_id: Optional[str] = None
|
||||
|
||||
|
||||
@router.post("")
|
||||
@@ -864,13 +866,16 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request):
|
||||
raise HTTPException(404, "chat not found")
|
||||
if await _chat_has_active_generation(chat_id):
|
||||
raise HTTPException(409, "wait for the current response to finish before compacting")
|
||||
model_id = body.model_id or await _infer_chat_model(chat_id)
|
||||
if not model_id:
|
||||
raise HTTPException(400, "choose a model before compacting")
|
||||
|
||||
message_id = await _get_context_leaf_message_id(chat)
|
||||
if not message_id:
|
||||
return {"ok": True, "compacted": False, "reason": "empty", "context_usage": None}
|
||||
current_msg = await ChatMessage.get_by_id(message_id)
|
||||
if not current_msg or not current_msg.parent_id:
|
||||
usage = await _get_chat_context_usage(chat, body.model_id)
|
||||
usage = await _get_chat_context_usage(chat, model_id)
|
||||
return {"ok": True, "compacted": False, "reason": "too_short", "context_usage": usage}
|
||||
|
||||
from cptr.utils.model_targets import (
|
||||
@@ -879,16 +884,18 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request):
|
||||
resolve_model_target,
|
||||
)
|
||||
|
||||
target = await resolve_model_target(body.model_id, request.app.state)
|
||||
target = await resolve_model_target(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.chat_task import _load_message_history, _summary_checkpoint_message_id
|
||||
from cptr.utils.summarize import summarize_messages
|
||||
|
||||
messages, existing_summary = await _load_message_history(chat_id, current_msg.parent_id)
|
||||
if not messages:
|
||||
usage = await _get_chat_context_usage(chat, body.model_id)
|
||||
compacted_messages = messages[:-1]
|
||||
keep_zone = messages[-1:]
|
||||
if not compacted_messages or not keep_zone:
|
||||
usage = await _get_chat_context_usage(chat, model_id)
|
||||
return {"ok": True, "compacted": False, "reason": "too_short", "context_usage": usage}
|
||||
|
||||
connection = target.connection
|
||||
@@ -901,7 +908,7 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request):
|
||||
api_type = connection.get("api_type", "chat_completions")
|
||||
|
||||
summary = await summarize_messages(
|
||||
messages,
|
||||
compacted_messages,
|
||||
existing_summary,
|
||||
provider,
|
||||
base_url,
|
||||
@@ -909,12 +916,13 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request):
|
||||
runtime_model,
|
||||
api_type=api_type,
|
||||
)
|
||||
await ChatMessage.update(message_id, chat_summary=summary)
|
||||
checkpoint_message_id = _summary_checkpoint_message_id(keep_zone, message_id)
|
||||
await ChatMessage.update(checkpoint_message_id, chat_summary=summary)
|
||||
|
||||
from cptr.utils.chat_export import export_chat_to_file
|
||||
|
||||
await export_chat_to_file(chat_id)
|
||||
usage = await _get_chat_context_usage(chat, body.model_id)
|
||||
usage = await _get_chat_context_usage(chat, model_id)
|
||||
return {
|
||||
"ok": True,
|
||||
"compacted": True,
|
||||
|
||||
+20
-5
@@ -11,6 +11,7 @@ from typing import List, Optional
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from cptr.utils.json_parser import extract_json
|
||||
from cptr.utils.git import (
|
||||
GitError,
|
||||
branches,
|
||||
@@ -153,6 +154,23 @@ The summary must be imperative, under 72 characters, and have no trailing period
|
||||
The description should be one short paragraph explaining the meaningful change. Do not invent details."""
|
||||
|
||||
|
||||
def _parse_commit_message_response(text: str) -> tuple[str, str]:
|
||||
message = extract_json(text)
|
||||
summary = str(message.get("summary", "")).strip() if isinstance(message, dict) else ""
|
||||
description = str(message.get("description", "")).strip() if isinstance(message, dict) else ""
|
||||
if summary:
|
||||
return summary.splitlines()[0][:72], description
|
||||
|
||||
lines = [
|
||||
line.strip()
|
||||
for line in text.strip().splitlines()
|
||||
if line.strip() and not line.strip().startswith("```")
|
||||
]
|
||||
if not lines:
|
||||
return "", ""
|
||||
return lines[0][:72], "\n".join(lines[1:]).strip()
|
||||
|
||||
|
||||
class CheckoutRequest(BaseModel):
|
||||
root: str
|
||||
branch: str
|
||||
@@ -260,7 +278,6 @@ async def generate_commit_message(body: CommitMessageRequest, request: Request):
|
||||
from cptr.utils.chat_task import _default_base_url
|
||||
from cptr.utils.config import _get_jwt_secret
|
||||
from cptr.utils.crypto import decrypt_key
|
||||
from cptr.utils.json_parser import extract_json
|
||||
from cptr.utils.model_targets import ApiModelTarget, resolve_model_target
|
||||
from cptr.models import Config
|
||||
|
||||
@@ -285,12 +302,10 @@ async def generate_commit_message(body: CommitMessageRequest, request: Request):
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=502, detail="Could not generate a commit message") from e
|
||||
message = extract_json(text)
|
||||
summary = str(message.get("summary", "")).strip().splitlines()[0] if isinstance(message, dict) else ""
|
||||
description = str(message.get("description", "")).strip() if isinstance(message, dict) else ""
|
||||
summary, description = _parse_commit_message_response(text)
|
||||
if not summary:
|
||||
raise HTTPException(status_code=502, detail="Could not generate a commit message")
|
||||
return {"summary": summary[:72], "description": description}
|
||||
return {"summary": summary, "description": description}
|
||||
|
||||
|
||||
@router.post("/checkout")
|
||||
|
||||
+33
-12
@@ -18,6 +18,8 @@ from typing import Optional
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from pydantic import BaseModel
|
||||
|
||||
from cptr.utils.gitignore import is_gitignored, load_gitignore
|
||||
|
||||
router = APIRouter(prefix="/api/workspace/files", tags=["workspace-files"])
|
||||
|
||||
|
||||
@@ -355,22 +357,35 @@ def _is_search_ignored(name: str) -> bool:
|
||||
return name in SEARCH_IGNORE_DIRS or name.endswith(".egg-info")
|
||||
|
||||
|
||||
def _walk_match_entries(root: Path, show_hidden: bool):
|
||||
def _walk_match_entries(
|
||||
root: Path,
|
||||
show_hidden: bool,
|
||||
gitignore: tuple[Path, tuple] | None = None,
|
||||
):
|
||||
"""Yield visible files and directories without following symlinks."""
|
||||
if gitignore is None:
|
||||
gitignore = load_gitignore(root)
|
||||
ignore_base, ignore_patterns = gitignore
|
||||
|
||||
try:
|
||||
entries = sorted(root.iterdir(), key=lambda item: item.name.lower())
|
||||
except (OSError, PermissionError):
|
||||
return
|
||||
|
||||
for item in entries:
|
||||
if _is_search_ignored(item.name) or (not show_hidden and item.name.startswith(".")):
|
||||
continue
|
||||
try:
|
||||
item_is_dir = item.is_dir()
|
||||
if (
|
||||
_is_search_ignored(item.name)
|
||||
or (not show_hidden and item.name.startswith("."))
|
||||
or is_gitignored(item, ignore_base, ignore_patterns, is_dir=item_is_dir)
|
||||
):
|
||||
continue
|
||||
if item.is_symlink():
|
||||
yield item, "file"
|
||||
elif item.is_dir():
|
||||
elif item_is_dir:
|
||||
yield item, "directory"
|
||||
yield from _walk_match_entries(item, show_hidden)
|
||||
yield from _walk_match_entries(item, show_hidden, gitignore)
|
||||
elif item.is_file():
|
||||
yield item, "file"
|
||||
except (OSError, PermissionError):
|
||||
@@ -408,7 +423,6 @@ def _content_matches_with_rg(
|
||||
"--column",
|
||||
"--max-count",
|
||||
str(MAX_CONTENT_MATCHES_PER_FILE + 1),
|
||||
"--no-ignore",
|
||||
]
|
||||
if show_hidden:
|
||||
args.append("--hidden")
|
||||
@@ -489,7 +503,9 @@ def find_file_matches(
|
||||
files = {path.resolve() for path, kind in entries if kind == "file" and not path.is_symlink()}
|
||||
content_result = _content_matches_with_rg(root, query, query_lower, show_hidden, files)
|
||||
content_matches, _ = (
|
||||
content_result if content_result is not None else _content_matches_with_python(files, query_lower)
|
||||
content_result
|
||||
if content_result is not None
|
||||
else _content_matches_with_python(files, query_lower)
|
||||
)
|
||||
|
||||
matches: list[tuple[int, int, FileMatch]] = []
|
||||
@@ -593,13 +609,19 @@ def walk_and_rank_files(root: Path, query: str, limit: int = 20) -> list[SearchR
|
||||
query_lower = query.strip().lower().replace("\\", "/")
|
||||
matches: list[tuple[int, int, SearchResult]] = []
|
||||
max_collect = limit * 10
|
||||
ignore_base, ignore_patterns = load_gitignore(root)
|
||||
|
||||
def walk(directory: Path, depth: int = 0):
|
||||
if depth > 8 or len(matches) >= max_collect:
|
||||
return
|
||||
try:
|
||||
for item in sorted(directory.iterdir(), key=lambda p: p.name.lower()):
|
||||
if item.name in SEARCH_IGNORE_DIRS or item.name.startswith("."):
|
||||
item_is_dir = item.is_dir()
|
||||
if (
|
||||
item.name in SEARCH_IGNORE_DIRS
|
||||
or item.name.startswith(".")
|
||||
or is_gitignored(item, ignore_base, ignore_patterns, is_dir=item_is_dir)
|
||||
):
|
||||
continue
|
||||
if len(matches) >= max_collect:
|
||||
return
|
||||
@@ -619,7 +641,7 @@ def walk_and_rank_files(root: Path, query: str, limit: int = 20) -> list[SearchR
|
||||
SearchResult(
|
||||
path=str(item),
|
||||
name=item.name,
|
||||
type="directory" if item.is_dir() else "file",
|
||||
type="directory" if item_is_dir else "file",
|
||||
),
|
||||
)
|
||||
)
|
||||
@@ -631,12 +653,12 @@ def walk_and_rank_files(root: Path, query: str, limit: int = 20) -> list[SearchR
|
||||
SearchResult(
|
||||
path=str(item),
|
||||
name=item.name,
|
||||
type="directory" if item.is_dir() else "file",
|
||||
type="directory" if item_is_dir else "file",
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
if item.is_dir():
|
||||
if item_is_dir:
|
||||
walk(item, depth + 1)
|
||||
except (PermissionError, OSError):
|
||||
pass
|
||||
@@ -646,7 +668,6 @@ def walk_and_rank_files(root: Path, query: str, limit: int = 20) -> list[SearchR
|
||||
return [m[2] for m in matches[:limit]]
|
||||
|
||||
|
||||
|
||||
# ── File management ──────────────────────────────────────────────
|
||||
|
||||
|
||||
|
||||
+182
-30
@@ -390,26 +390,40 @@ async def stream_anthropic(
|
||||
|
||||
|
||||
def _reasoning_items_to_content(items: list[dict]) -> str:
|
||||
"""Convert Responses API reasoning items to a reasoning_content string.
|
||||
"""Convert replayable reasoning items to a reasoning_content string.
|
||||
|
||||
Reasoning items may expose text in content or summary blocks. We extract
|
||||
those text blocks and join them for Chat Completions-compatible providers.
|
||||
"""
|
||||
texts: list[str] = []
|
||||
for item in items:
|
||||
blocks = item.get("content") or item.get("summary") or []
|
||||
for block in blocks:
|
||||
if isinstance(block, dict) and block.get("type") == "text" and block.get("text"):
|
||||
texts.append(block["text"])
|
||||
for blocks in (item.get("content"), item.get("summary")):
|
||||
if isinstance(blocks, str):
|
||||
if blocks:
|
||||
texts.append(blocks)
|
||||
elif isinstance(blocks, list):
|
||||
for block in blocks:
|
||||
if isinstance(block, str):
|
||||
if block:
|
||||
texts.append(block)
|
||||
elif (
|
||||
isinstance(block, dict)
|
||||
and block.get("type") in ("text", "output_text", "summary_text")
|
||||
and block.get("text")
|
||||
):
|
||||
texts.append(block["text"])
|
||||
return "\n".join(texts)
|
||||
|
||||
|
||||
def _to_openai_messages(messages: list[dict], instructions: str) -> list[dict]:
|
||||
def _to_openai_messages(
|
||||
messages: list[dict], instructions: str, *, provider_type: str = "default"
|
||||
) -> list[dict]:
|
||||
"""Canonical messages → OpenAI Chat Completions format.
|
||||
|
||||
Converts reasoning_items (Responses API format) to reasoning_content
|
||||
(Chat Completions format) for providers like Kimi that require it.
|
||||
Strips other non-standard fields (fc_id in tool_calls).
|
||||
Strict default OpenAI-compatible requests do not receive provider-specific
|
||||
reasoning fields. llama.cpp compatibility replays text reasoning as
|
||||
reasoning_content. Other non-standard fields (fc_id in tool_calls) are
|
||||
stripped.
|
||||
"""
|
||||
result = []
|
||||
if instructions:
|
||||
@@ -431,33 +445,42 @@ def _to_openai_messages(messages: list[dict], instructions: str) -> list[dict]:
|
||||
data_uri = f"data:{block.get('media_type', 'image/jpeg')};base64,{block.get('base64', '')}"
|
||||
formatted_content.append({"type": "image_url", "image_url": {"url": data_uri}})
|
||||
new_m = dict(m)
|
||||
new_m.pop("reasoning_items", None)
|
||||
if new_m.get("tool_calls"):
|
||||
new_m["tool_calls"] = [
|
||||
{k: v for k, v in tc.items() if k != "fc_id"}
|
||||
for tc in new_m["tool_calls"]
|
||||
]
|
||||
new_m["content"] = formatted_content
|
||||
# Convert reasoning_items → reasoning_content for round-tripping
|
||||
ri = new_m.pop("reasoning_items", None)
|
||||
if ri and new_m.get("role") == "assistant":
|
||||
ri = m.get("reasoning_items")
|
||||
if provider_type == "llama.cpp" and ri and new_m.get("role") == "assistant":
|
||||
rc = _reasoning_items_to_content(ri)
|
||||
if rc:
|
||||
new_m["reasoning_content"] = rc
|
||||
result.append(new_m)
|
||||
else:
|
||||
out = dict(m)
|
||||
# Convert reasoning_items → reasoning_content for round-tripping
|
||||
ri = out.pop("reasoning_items", None)
|
||||
if ri and out.get("role") == "assistant":
|
||||
rc = _reasoning_items_to_content(ri)
|
||||
if rc:
|
||||
out["reasoning_content"] = rc
|
||||
# Clean tool_calls: remove fc_id which is Responses-API-only
|
||||
out.pop("reasoning_items", None)
|
||||
if out.get("tool_calls"):
|
||||
out["tool_calls"] = [
|
||||
{k: v for k, v in tc.items() if k != "fc_id"} for tc in out["tool_calls"]
|
||||
]
|
||||
ri = m.get("reasoning_items")
|
||||
if provider_type == "llama.cpp" and ri and out.get("role") == "assistant":
|
||||
rc = _reasoning_items_to_content(ri)
|
||||
if rc:
|
||||
out["reasoning_content"] = rc
|
||||
result.append(out)
|
||||
return result
|
||||
|
||||
|
||||
async def stream_openai_completions(
|
||||
form_data: ChatCompletionForm, url: str, key: str, *, request_params: dict | None = None
|
||||
form_data: ChatCompletionForm,
|
||||
url: str,
|
||||
key: str,
|
||||
*,
|
||||
request_params: dict | None = None,
|
||||
provider_type: str = "default",
|
||||
) -> AsyncIterator[dict]:
|
||||
tools = [
|
||||
{
|
||||
@@ -473,7 +496,9 @@ async def stream_openai_completions(
|
||||
|
||||
body: dict = {
|
||||
"model": form_data.model,
|
||||
"messages": _to_openai_messages(form_data.messages, form_data.instructions),
|
||||
"messages": _to_openai_messages(
|
||||
form_data.messages, form_data.instructions, provider_type=provider_type
|
||||
),
|
||||
"stream": True,
|
||||
"stream_options": {"include_usage": True},
|
||||
}
|
||||
@@ -511,17 +536,21 @@ async def stream_openai_completions(
|
||||
)
|
||||
resp.raise_for_status()
|
||||
tool_calls: dict[int, dict] = {}
|
||||
reasoning_buffer = "" # Accumulate reasoning_content deltas (Kimi, DeepSeek)
|
||||
reasoning_buffer = ""
|
||||
reasoning_item: dict | None = None
|
||||
reasoning_details: list = []
|
||||
|
||||
def complete_reasoning_item() -> dict | None:
|
||||
nonlocal reasoning_buffer, reasoning_item
|
||||
nonlocal reasoning_buffer, reasoning_item, reasoning_details
|
||||
if reasoning_item is None:
|
||||
return None
|
||||
reasoning_item["status"] = "completed"
|
||||
if reasoning_details:
|
||||
reasoning_item["reasoning_details"] = copy.deepcopy(reasoning_details)
|
||||
item = copy.deepcopy(reasoning_item)
|
||||
reasoning_item = None
|
||||
reasoning_buffer = ""
|
||||
reasoning_details = []
|
||||
return item
|
||||
|
||||
async for line in resp.aiter_lines():
|
||||
@@ -531,9 +560,25 @@ async def stream_openai_completions(
|
||||
choices = chunk.get("choices", [])
|
||||
delta = choices[0].get("delta", {}) if choices else {}
|
||||
|
||||
# Capture reasoning_content from providers like Kimi / DeepSeek
|
||||
if delta.get("reasoning_content"):
|
||||
reasoning_buffer += delta["reasoning_content"]
|
||||
reasoning_delta = (
|
||||
delta.get("reasoning_content")
|
||||
or delta.get("reasoning")
|
||||
or delta.get("thinking")
|
||||
)
|
||||
if delta.get("reasoning_details"):
|
||||
details = delta["reasoning_details"]
|
||||
if isinstance(details, list):
|
||||
reasoning_details.extend(copy.deepcopy(details))
|
||||
else:
|
||||
reasoning_details.append(copy.deepcopy(details))
|
||||
if reasoning_item is None:
|
||||
reasoning_item = _reasoning_output_item()
|
||||
reasoning_item["reasoning_details"] = copy.deepcopy(reasoning_details)
|
||||
emitted = True
|
||||
yield {"type": "output", "item": copy.deepcopy(reasoning_item)}
|
||||
|
||||
if reasoning_delta:
|
||||
reasoning_buffer += reasoning_delta
|
||||
if reasoning_item is None:
|
||||
reasoning_item = _reasoning_output_item()
|
||||
reasoning_item["content"][0]["text"] = reasoning_buffer
|
||||
@@ -617,7 +662,29 @@ async def stream_openai_completions(
|
||||
# ── OpenAI Responses API ─────────────────────────────────────
|
||||
|
||||
|
||||
def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]:
|
||||
def _replayable_reasoning_items(items: list[dict] | None, *, provider_type: str) -> list[dict]:
|
||||
replayable: list[dict] = []
|
||||
for item in items or []:
|
||||
if (
|
||||
not isinstance(item, dict)
|
||||
or item.get("type") != "reasoning"
|
||||
or item.get("status") not in (None, "completed")
|
||||
or str(item.get("id", "")).startswith("reasoning-")
|
||||
):
|
||||
continue
|
||||
text = _reasoning_items_to_content([item])
|
||||
if not text and not item.get("encrypted_content") and not item.get("reasoning_details"):
|
||||
continue
|
||||
out = copy.deepcopy(item)
|
||||
if provider_type == "llama.cpp" and text:
|
||||
out["content"] = [{"type": "text", "text": text}]
|
||||
replayable.append(out)
|
||||
return replayable
|
||||
|
||||
|
||||
def _to_responses_input(
|
||||
messages: list[dict], instructions: str, *, provider_type: str = "default"
|
||||
) -> list[dict]:
|
||||
"""Canonical messages → Responses API input items."""
|
||||
# Pre-collect all tool result call_ids so we can validate function_calls
|
||||
# have matching outputs. This prevents orphaned function_calls (from
|
||||
@@ -649,7 +716,9 @@ def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]:
|
||||
)
|
||||
elif role == "assistant" and m.get("tool_calls"):
|
||||
# Emit reasoning items before function calls (required by reasoning models)
|
||||
for ri in m.get("reasoning_items", []):
|
||||
for ri in _replayable_reasoning_items(
|
||||
m.get("reasoning_items"), provider_type=provider_type
|
||||
):
|
||||
items.append(ri)
|
||||
for tc in m["tool_calls"]:
|
||||
call_id = tc.get("id", "")
|
||||
@@ -677,6 +746,11 @@ def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]:
|
||||
}
|
||||
)
|
||||
else:
|
||||
if role == "assistant":
|
||||
for ri in _replayable_reasoning_items(
|
||||
m.get("reasoning_items"), provider_type=provider_type
|
||||
):
|
||||
items.append(ri)
|
||||
content = m.get("content", "")
|
||||
if isinstance(content, list):
|
||||
formatted_content = []
|
||||
@@ -695,7 +769,12 @@ def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]:
|
||||
|
||||
|
||||
async def stream_openai_responses(
|
||||
form_data: ChatCompletionForm, url: str, key: str, *, request_params: dict | None = None
|
||||
form_data: ChatCompletionForm,
|
||||
url: str,
|
||||
key: str,
|
||||
*,
|
||||
request_params: dict | None = None,
|
||||
provider_type: str = "default",
|
||||
) -> AsyncIterator[dict]:
|
||||
tools = [
|
||||
{
|
||||
@@ -709,7 +788,9 @@ async def stream_openai_responses(
|
||||
|
||||
body: dict = {
|
||||
"model": form_data.model,
|
||||
"input": _to_responses_input(form_data.messages, form_data.instructions),
|
||||
"input": _to_responses_input(
|
||||
form_data.messages, form_data.instructions, provider_type=provider_type
|
||||
),
|
||||
"stream": True,
|
||||
}
|
||||
if form_data.instructions:
|
||||
@@ -749,6 +830,20 @@ async def stream_openai_responses(
|
||||
error_body.decode(errors="replace"),
|
||||
)
|
||||
resp.raise_for_status()
|
||||
output_items_by_id: dict[str, dict] = {}
|
||||
active_reasoning_item: dict | None = None
|
||||
|
||||
def get_reasoning_item(event: dict) -> dict:
|
||||
nonlocal active_reasoning_item
|
||||
item_id = event.get("item_id") or event.get("output_item_id") or "rs_stream"
|
||||
if item_id in output_items_by_id:
|
||||
active_reasoning_item = output_items_by_id[item_id]
|
||||
if active_reasoning_item is None:
|
||||
active_reasoning_item = _reasoning_output_item()
|
||||
active_reasoning_item["id"] = item_id
|
||||
output_items_by_id[item_id] = active_reasoning_item
|
||||
return active_reasoning_item
|
||||
|
||||
async for line in resp.aiter_lines():
|
||||
if not line.startswith("data: "):
|
||||
continue
|
||||
@@ -762,8 +857,53 @@ async def stream_openai_responses(
|
||||
emitted = True
|
||||
yield {"type": "text_delta", "content": event["delta"]}
|
||||
|
||||
elif etype == "response.output_item.added":
|
||||
item = event.get("item") or {}
|
||||
item_id = item.get("id")
|
||||
if item_id:
|
||||
output_items_by_id[item_id] = copy.deepcopy(item)
|
||||
if item.get("type") == "reasoning":
|
||||
active_reasoning_item = output_items_by_id.get(item_id) or item
|
||||
|
||||
elif etype in (
|
||||
"response.reasoning.delta",
|
||||
"response.reasoning_text.delta",
|
||||
):
|
||||
item = get_reasoning_item(event)
|
||||
delta = event.get("delta", "")
|
||||
content = item.setdefault("content", [{"type": "text", "text": ""}])
|
||||
if not content:
|
||||
content.append({"type": "text", "text": ""})
|
||||
if isinstance(content[0], dict):
|
||||
content[0]["type"] = content[0].get("type") or "text"
|
||||
content[0]["text"] = f"{content[0].get('text', '')}{delta}"
|
||||
emitted = True
|
||||
yield {"type": "output", "item": copy.deepcopy(item)}
|
||||
|
||||
elif etype == "response.reasoning_summary_text.delta":
|
||||
item = get_reasoning_item(event)
|
||||
delta = event.get("delta", "")
|
||||
summary = item.setdefault("summary", [{"type": "summary_text", "text": ""}])
|
||||
if not summary:
|
||||
summary.append({"type": "summary_text", "text": ""})
|
||||
if isinstance(summary[0], dict):
|
||||
summary[0]["type"] = summary[0].get("type") or "summary_text"
|
||||
summary[0]["text"] = f"{summary[0].get('text', '')}{delta}"
|
||||
emitted = True
|
||||
yield {"type": "output", "item": copy.deepcopy(item)}
|
||||
|
||||
elif etype == "response.reasoning_summary_part.added":
|
||||
item = get_reasoning_item(event)
|
||||
part = event.get("part")
|
||||
if part:
|
||||
item.setdefault("summary", []).append(copy.deepcopy(part))
|
||||
emitted = True
|
||||
yield {"type": "output", "item": copy.deepcopy(item)}
|
||||
|
||||
elif etype == "response.output_item.done":
|
||||
item = event["item"]
|
||||
if item.get("id"):
|
||||
output_items_by_id[item["id"]] = copy.deepcopy(item)
|
||||
if item["type"] == "function_call":
|
||||
emitted = True
|
||||
yield {
|
||||
@@ -775,6 +915,11 @@ async def stream_openai_responses(
|
||||
}
|
||||
elif item["type"] == "reasoning":
|
||||
# Reasoning items must be round-tripped for reasoning models
|
||||
if (
|
||||
active_reasoning_item is not None
|
||||
and active_reasoning_item.get("id") == item.get("id")
|
||||
):
|
||||
active_reasoning_item = None
|
||||
emitted = True
|
||||
yield {
|
||||
"type": "output",
|
||||
@@ -787,6 +932,13 @@ async def stream_openai_responses(
|
||||
raise RuntimeError(f"Responses API error: {msg}")
|
||||
|
||||
elif etype == "response.completed":
|
||||
if (
|
||||
active_reasoning_item is not None
|
||||
and _reasoning_items_to_content([active_reasoning_item])
|
||||
):
|
||||
active_reasoning_item["status"] = "completed"
|
||||
emitted = True
|
||||
yield {"type": "output", "item": copy.deepcopy(active_reasoning_item)}
|
||||
usage = event.get("response", {}).get("usage", {})
|
||||
if usage:
|
||||
emitted = True
|
||||
|
||||
@@ -325,12 +325,26 @@ class CDPClient:
|
||||
|
||||
# ── Observation ────────────────────────────────────────
|
||||
|
||||
async def screenshot(self) -> bytes:
|
||||
async def screenshot(self, width: int | None = None, height: int | None = None) -> bytes:
|
||||
"""Capture a screenshot of the current viewport. Returns PNG bytes."""
|
||||
result = await self._send(
|
||||
"Page.captureScreenshot", {"format": "png", "quality": 80}
|
||||
)
|
||||
return base64.b64decode(result["data"])
|
||||
if width is not None and height is not None:
|
||||
await self._send(
|
||||
"Emulation.setDeviceMetricsOverride",
|
||||
{
|
||||
"width": width,
|
||||
"height": height,
|
||||
"deviceScaleFactor": 1,
|
||||
"mobile": False,
|
||||
},
|
||||
)
|
||||
try:
|
||||
result = await self._send(
|
||||
"Page.captureScreenshot", {"format": "png", "quality": 80}
|
||||
)
|
||||
return base64.b64decode(result["data"])
|
||||
finally:
|
||||
if width is not None and height is not None:
|
||||
await self._send("Emulation.clearDeviceMetricsOverride")
|
||||
|
||||
async def get_text(self) -> str:
|
||||
"""Extract visible text content from the page."""
|
||||
|
||||
+85
-18
@@ -14,7 +14,13 @@ from typing import Any
|
||||
|
||||
from cptr.events import EVENTS, publish_event
|
||||
from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS
|
||||
from cptr.utils.context import resolve_compact_token_threshold, should_compact
|
||||
from cptr.utils.context import (
|
||||
build_context_usage,
|
||||
normalize_usage,
|
||||
resolve_compact_token_threshold,
|
||||
should_compact,
|
||||
usage_context_tokens,
|
||||
)
|
||||
from cptr.utils.skills import (
|
||||
bump_skill_view,
|
||||
discover_skills,
|
||||
@@ -754,7 +760,7 @@ async def generate_chat_title(
|
||||
|
||||
# Do not overwrite a title manually set while this request was running.
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
fallback = user_content[:50].strip() or "New Chat"
|
||||
fallback = user_message[:50].strip() or "New Chat"
|
||||
if not chat or chat.title != fallback:
|
||||
return
|
||||
|
||||
@@ -812,7 +818,7 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
# (truly empty placeholder on first run)
|
||||
if m.id == message_id and not m.done and not m.content and not m.output:
|
||||
continue
|
||||
entry: dict = {"role": m.role, "content": m.content or ""}
|
||||
entry: dict = {"id": m.id, "role": m.role, "content": m.content or ""}
|
||||
|
||||
# Transform uploaded images into base64 multimodal blocks; inline text files
|
||||
if m.role == "user":
|
||||
@@ -903,6 +909,16 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
for item in m.output:
|
||||
itype = item.get("type")
|
||||
if itype == "reasoning":
|
||||
if (
|
||||
item.get("status") not in (None, "completed")
|
||||
or str(item.get("id", "")).startswith("reasoning-")
|
||||
or (
|
||||
not item.get("encrypted_content")
|
||||
and not item.get("reasoning_details")
|
||||
and _reasoning_text_len(item) <= 0
|
||||
)
|
||||
):
|
||||
continue
|
||||
# A reasoning item after we already have outputs means
|
||||
# a new API iteration started — flush the current turn.
|
||||
if current_turn["outputs"]:
|
||||
@@ -945,7 +961,7 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
# Skip other types (message, artifact, pending calls, etc.)
|
||||
|
||||
# Don't forget the last turn
|
||||
if current_turn["calls"] or current_turn["outputs"]:
|
||||
if current_turn["reasoning"] or current_turn["calls"] or current_turn["outputs"]:
|
||||
turns.append(current_turn)
|
||||
|
||||
if not turns:
|
||||
@@ -959,6 +975,18 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
call_names = {
|
||||
tc["id"]: tc.get("function", {}).get("name", "") for tc in turn["calls"]
|
||||
}
|
||||
if turn["reasoning"] and not matched_calls and not turn["outputs"]:
|
||||
if ti == 0:
|
||||
entry["reasoning_items"] = turn["reasoning"]
|
||||
else:
|
||||
result.append(entry)
|
||||
entry = {
|
||||
"id": m.id,
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"reasoning_items": turn["reasoning"],
|
||||
}
|
||||
continue
|
||||
if matched_calls:
|
||||
if ti == 0:
|
||||
# First turn: attach to the existing entry
|
||||
@@ -970,6 +998,7 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
# result from previous turn) before creating a new one.
|
||||
result.append(entry)
|
||||
entry = {
|
||||
"id": m.id,
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": matched_calls,
|
||||
@@ -979,6 +1008,7 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic
|
||||
for out in turn["outputs"]:
|
||||
result.append(entry)
|
||||
entry = {
|
||||
"id": m.id,
|
||||
"role": "tool",
|
||||
"tool_call_id": out["call_id"],
|
||||
"content": _tool_result_for_model(
|
||||
@@ -1116,7 +1146,6 @@ def _tool_result_for_model(tool_name: str, result: str) -> str:
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _append_tool_to_messages(
|
||||
messages: list[dict],
|
||||
event: dict,
|
||||
@@ -1281,10 +1310,18 @@ def _scrub_incomplete_items(output_items: list[dict]) -> None:
|
||||
|
||||
def _reasoning_text_len(item: dict) -> int:
|
||||
"""Return displayable reasoning text length for diagnostics."""
|
||||
blocks = item.get("summary") or item.get("content") or []
|
||||
if not isinstance(blocks, list):
|
||||
return 0
|
||||
return sum(len(block.get("text") or "") for block in blocks if isinstance(block, dict))
|
||||
total = 0
|
||||
for blocks in (item.get("summary"), item.get("content")):
|
||||
if isinstance(blocks, str):
|
||||
total += len(blocks)
|
||||
elif isinstance(blocks, list):
|
||||
total += sum(
|
||||
len(block.get("text") or "")
|
||||
for block in blocks
|
||||
if isinstance(block, dict)
|
||||
and block.get("type") in ("text", "output_text", "summary_text")
|
||||
)
|
||||
return total
|
||||
|
||||
|
||||
def _output_debug_stats(output_items: list[dict] | None) -> tuple[dict[str, int], int, int]:
|
||||
@@ -1390,6 +1427,16 @@ def _find_safe_split(messages: list[dict], target_keep: int) -> int:
|
||||
return min(split, n - 2) # always keep at least 2
|
||||
|
||||
|
||||
def _summary_checkpoint_message_id(keep_zone: list[dict], fallback: str) -> str:
|
||||
for message in keep_zone:
|
||||
if message.get("role") == "user" and message.get("id"):
|
||||
return message["id"]
|
||||
for message in keep_zone:
|
||||
if message.get("id"):
|
||||
return message["id"]
|
||||
return fallback
|
||||
|
||||
|
||||
# ── Connection resolution ───────────────────────────────────
|
||||
|
||||
|
||||
@@ -2046,7 +2093,10 @@ async def run_chat_task(
|
||||
api_type=api_type,
|
||||
)
|
||||
|
||||
await ChatMessage.update(summary_message_id, chat_summary=summary)
|
||||
checkpoint_message_id = _summary_checkpoint_message_id(
|
||||
keep_zone, summary_message_id
|
||||
)
|
||||
await ChatMessage.update(checkpoint_message_id, chat_summary=summary)
|
||||
loaded_summary = summary
|
||||
|
||||
# Append summary to system prompt (works for all providers)
|
||||
@@ -2077,7 +2127,7 @@ async def run_chat_task(
|
||||
logger.info(
|
||||
"[task %s] compacted: checkpoint=%s dropped %d msgs, kept %d, summary=%d chars",
|
||||
message_id[:8],
|
||||
summary_message_id[:8],
|
||||
checkpoint_message_id[:8],
|
||||
len(drop_zone),
|
||||
len(keep_zone),
|
||||
len(summary),
|
||||
@@ -2114,6 +2164,7 @@ async def run_chat_task(
|
||||
],
|
||||
}
|
||||
)
|
||||
api_messages = [{k: v for k, v in m.items() if k != "id"} for m in api_messages]
|
||||
|
||||
form_data = ChatCompletionForm(
|
||||
model=model,
|
||||
@@ -2121,6 +2172,11 @@ async def run_chat_task(
|
||||
instructions=system,
|
||||
tools=tools,
|
||||
)
|
||||
provider_type = (
|
||||
"llama.cpp"
|
||||
if provider == "openai" and connection.get("provider_type") == "llama.cpp"
|
||||
else "default"
|
||||
)
|
||||
|
||||
if provider == "anthropic":
|
||||
stream = stream_anthropic(
|
||||
@@ -2128,11 +2184,19 @@ async def run_chat_task(
|
||||
)
|
||||
elif connection.get("api_type") == "responses":
|
||||
stream = stream_openai_responses(
|
||||
form_data, base_url, api_key, request_params=request_params
|
||||
form_data,
|
||||
base_url,
|
||||
api_key,
|
||||
request_params=request_params,
|
||||
provider_type=provider_type,
|
||||
)
|
||||
else:
|
||||
stream = stream_openai_completions(
|
||||
form_data, base_url, api_key, request_params=request_params
|
||||
form_data,
|
||||
base_url,
|
||||
api_key,
|
||||
request_params=request_params,
|
||||
provider_type=provider_type,
|
||||
)
|
||||
|
||||
restart = False
|
||||
@@ -2188,13 +2252,16 @@ async def run_chat_task(
|
||||
await emit(output=item)
|
||||
|
||||
elif event["type"] == "usage":
|
||||
usage = {k: v for k, v in event.items() if k != "type"}
|
||||
if "total_tokens" not in usage:
|
||||
usage["total_tokens"] = usage.get("input_tokens", 0) + usage.get(
|
||||
"output_tokens", 0
|
||||
)
|
||||
usage = normalize_usage({k: v for k, v in event.items() if k != "type"})
|
||||
last_usage = usage
|
||||
new_messages_since = 0
|
||||
tokens = usage_context_tokens(usage)
|
||||
if tokens > 0:
|
||||
await emit(
|
||||
context_usage=build_context_usage(
|
||||
tokens, threshold=compact_token_threshold, source="estimated"
|
||||
)
|
||||
)
|
||||
|
||||
elif event["type"] == "done":
|
||||
# Stream ended. Usage may have arrived earlier, multiple times, or never.
|
||||
|
||||
@@ -46,6 +46,7 @@ def should_compact(
|
||||
"""
|
||||
resolved_threshold = threshold or _get_threshold()
|
||||
|
||||
last_usage = normalize_usage(last_usage)
|
||||
if last_usage and last_usage.get("input_tokens"):
|
||||
# Real base from last API call + estimate only new additions
|
||||
base = last_usage["input_tokens"] + last_usage.get("output_tokens", 0)
|
||||
@@ -72,6 +73,36 @@ def build_context_usage(tokens: int, *, threshold: int | None = None, source: st
|
||||
}
|
||||
|
||||
|
||||
def normalize_usage(usage: dict | None) -> dict | None:
|
||||
"""Return provider usage with cptr's canonical token field names."""
|
||||
if not usage:
|
||||
return None
|
||||
normalized = dict(usage)
|
||||
input_tokens = _parse_nonnegative_int(
|
||||
normalized.get("input_tokens", normalized.get("prompt_tokens"))
|
||||
)
|
||||
output_tokens = _parse_nonnegative_int(
|
||||
normalized.get("output_tokens", normalized.get("completion_tokens"))
|
||||
)
|
||||
total_tokens = _parse_nonnegative_int(normalized.get("total_tokens"))
|
||||
if total_tokens == 0:
|
||||
total_tokens = input_tokens + output_tokens
|
||||
normalized["input_tokens"] = input_tokens
|
||||
normalized["output_tokens"] = output_tokens
|
||||
normalized["total_tokens"] = total_tokens
|
||||
return normalized
|
||||
|
||||
|
||||
def usage_context_tokens(usage: dict | None) -> int:
|
||||
"""Best available context token count from normalized or provider usage."""
|
||||
usage = normalize_usage(usage)
|
||||
if not usage:
|
||||
return 0
|
||||
if usage.get("input_tokens"):
|
||||
return usage["input_tokens"] + usage.get("output_tokens", 0)
|
||||
return usage.get("total_tokens", 0)
|
||||
|
||||
|
||||
def estimate_context_usage(
|
||||
messages: list[dict], system_prompt: str, *, threshold: int | None = None
|
||||
) -> dict:
|
||||
@@ -89,6 +120,14 @@ def _parse_positive_int(value: object) -> int | None:
|
||||
return parsed if parsed > 0 else None
|
||||
|
||||
|
||||
def _parse_nonnegative_int(value: object) -> int:
|
||||
try:
|
||||
parsed = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
return max(0, parsed)
|
||||
|
||||
|
||||
def resolve_compact_token_threshold(
|
||||
model: str | None = None,
|
||||
*,
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Small .gitignore matcher for fallback file walkers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fnmatch import fnmatch
|
||||
from pathlib import Path
|
||||
|
||||
GitignorePattern = tuple[str, bool, bool, bool]
|
||||
|
||||
|
||||
def load_gitignore(root: Path) -> tuple[Path, tuple[GitignorePattern, ...]]:
|
||||
"""Load the nearest repo/root .gitignore patterns for a search root."""
|
||||
base = _ignore_base(root.resolve())
|
||||
gitignore = base / ".gitignore"
|
||||
if not gitignore.is_file():
|
||||
return base, ()
|
||||
|
||||
patterns: list[GitignorePattern] = []
|
||||
for raw in gitignore.read_text(encoding="utf-8", errors="replace").splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if line.startswith("\\#") or line.startswith("\\!"):
|
||||
line = line[1:]
|
||||
negated = line.startswith("!")
|
||||
if negated:
|
||||
line = line[1:].strip()
|
||||
directory_only = line.endswith("/")
|
||||
pattern = line.strip("/")
|
||||
if pattern:
|
||||
patterns.append((pattern, negated, directory_only, "/" in pattern))
|
||||
return base, tuple(patterns)
|
||||
|
||||
|
||||
def is_gitignored(
|
||||
path: Path,
|
||||
base: Path,
|
||||
patterns: tuple[GitignorePattern, ...],
|
||||
*,
|
||||
is_dir: bool,
|
||||
) -> bool:
|
||||
if not patterns:
|
||||
return False
|
||||
try:
|
||||
rel = path.resolve().relative_to(base).as_posix()
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
ignored = False
|
||||
name = path.name
|
||||
for pattern, negated, directory_only, anchored in patterns:
|
||||
if directory_only and not is_dir:
|
||||
continue
|
||||
if _matches_gitignore_pattern(pattern, rel, name, directory_only, anchored):
|
||||
ignored = not negated
|
||||
return ignored
|
||||
|
||||
|
||||
def _ignore_base(root: Path) -> Path:
|
||||
current = root if root.is_dir() else root.parent
|
||||
fallback = current
|
||||
for parent in (current, *current.parents):
|
||||
if (parent / ".git").exists():
|
||||
return parent
|
||||
if (parent / ".gitignore").is_file():
|
||||
fallback = parent
|
||||
return fallback
|
||||
|
||||
|
||||
def _matches_gitignore_pattern(
|
||||
pattern: str,
|
||||
rel: str,
|
||||
name: str,
|
||||
directory_only: bool,
|
||||
anchored: bool,
|
||||
) -> bool:
|
||||
if anchored:
|
||||
return (
|
||||
rel == pattern
|
||||
or (directory_only and rel.startswith(f"{pattern}/"))
|
||||
or fnmatch(rel, pattern)
|
||||
)
|
||||
return any(fnmatch(part, pattern) for part in rel.split("/")) or fnmatch(name, pattern)
|
||||
@@ -685,6 +685,7 @@ def format_skill_content(skill: SkillContent) -> str:
|
||||
"",
|
||||
f"Skill directory: {skill_dir}",
|
||||
"Relative paths in this skill are relative to the skill directory.",
|
||||
"Load listed resources with view_skill using this skill name and file_path.",
|
||||
]
|
||||
|
||||
if skill.resources:
|
||||
|
||||
+77
-18
@@ -18,9 +18,11 @@ import mimetypes
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from pathlib import Path, PureWindowsPath
|
||||
from typing import Any, Literal, Optional, get_args, get_origin, get_type_hints
|
||||
|
||||
from cptr.env import CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS, EXECUTE_TIMEOUT
|
||||
from cptr.utils.gitignore import is_gitignored, load_gitignore
|
||||
|
||||
try:
|
||||
import fcntl
|
||||
@@ -716,13 +718,22 @@ async def _search_python(query: str, full: Path, case_insensitive: bool) -> str:
|
||||
def _walk_and_search():
|
||||
results = []
|
||||
ignore = {".git", "node_modules", "__pycache__", ".venv", "venv"}
|
||||
ignore_base, ignore_patterns = load_gitignore(full)
|
||||
q = query.lower() if case_insensitive else query
|
||||
|
||||
for root, dirs, files in os.walk(full):
|
||||
dirs[:] = [d for d in dirs if d not in ignore]
|
||||
root_path = Path(root)
|
||||
dirs[:] = [
|
||||
d
|
||||
for d in dirs
|
||||
if d not in ignore
|
||||
and not is_gitignored(root_path / d, ignore_base, ignore_patterns, is_dir=True)
|
||||
]
|
||||
for fname in files:
|
||||
fpath = Path(root) / fname
|
||||
if _is_dotenv(fpath):
|
||||
if _is_dotenv(fpath) or is_gitignored(
|
||||
fpath, ignore_base, ignore_patterns, is_dir=False
|
||||
):
|
||||
continue
|
||||
text = _read_text_for_search(fpath)
|
||||
if text is None:
|
||||
@@ -767,7 +778,7 @@ async def create_file(
|
||||
artifact_path = artifact_dir / f"{ts}_{artifact_type}.md"
|
||||
|
||||
def _write_artifact():
|
||||
artifact_path.write_text(content)
|
||||
artifact_path.write_text(content, encoding="utf-8")
|
||||
|
||||
await asyncio.to_thread(_write_artifact)
|
||||
|
||||
@@ -793,7 +804,7 @@ async def create_file(
|
||||
|
||||
def _write():
|
||||
full.parent.mkdir(parents=True, exist_ok=True)
|
||||
full.write_text(content)
|
||||
full.write_text(content, encoding="utf-8")
|
||||
|
||||
await asyncio.to_thread(_write)
|
||||
return f"Created {path} ({len(content)} bytes, {len(content.splitlines())} lines)"
|
||||
@@ -820,7 +831,7 @@ async def create_artifact(
|
||||
artifact_path = artifact_dir / f"{ts}_{artifact_type}.md"
|
||||
|
||||
def _write():
|
||||
artifact_path.write_text(content)
|
||||
artifact_path.write_text(content, encoding="utf-8")
|
||||
|
||||
await asyncio.to_thread(_write)
|
||||
|
||||
@@ -972,7 +983,7 @@ async def write_file(path: str, content: str, *, workspace: str) -> str:
|
||||
|
||||
def _write():
|
||||
full.parent.mkdir(parents=True, exist_ok=True)
|
||||
full.write_text(content)
|
||||
full.write_text(content, encoding="utf-8")
|
||||
|
||||
await asyncio.to_thread(_write)
|
||||
return f"Wrote {len(content)} bytes to {path}"
|
||||
@@ -1043,7 +1054,7 @@ async def edit_file(
|
||||
return f"Error: file not found: {path}"
|
||||
|
||||
def _edit():
|
||||
content = full.read_text(errors="replace")
|
||||
content = full.read_text(encoding="utf-8", errors="replace")
|
||||
|
||||
if start_line > 0 or end_line > 0:
|
||||
lines = content.splitlines(keepends=True)
|
||||
@@ -1075,7 +1086,7 @@ async def edit_file(
|
||||
)
|
||||
new_content = content.replace(target, replacement, 1)
|
||||
|
||||
full.write_text(new_content)
|
||||
full.write_text(new_content, encoding="utf-8")
|
||||
return None # success sentinel
|
||||
|
||||
result = await asyncio.to_thread(_edit)
|
||||
@@ -1115,7 +1126,7 @@ async def multi_edit_file(
|
||||
return "Error: edits must be a non-empty JSON array"
|
||||
|
||||
def _apply():
|
||||
content = full.read_text(errors="replace")
|
||||
content = full.read_text(encoding="utf-8", errors="replace")
|
||||
applied = 0
|
||||
|
||||
for i, edit in enumerate(edit_list):
|
||||
@@ -1138,7 +1149,7 @@ async def multi_edit_file(
|
||||
content = content.replace(target, replacement, 1)
|
||||
applied += 1
|
||||
|
||||
full.write_text(content)
|
||||
full.write_text(content, encoding="utf-8")
|
||||
return f"Applied {applied} edits to {path}"
|
||||
|
||||
return await asyncio.to_thread(_apply)
|
||||
@@ -1605,11 +1616,13 @@ _activated_skills: set[str] = set()
|
||||
|
||||
async def view_skill(
|
||||
skill_name: str,
|
||||
file_path: str = "",
|
||||
*,
|
||||
workspace: str,
|
||||
) -> str:
|
||||
"""Load the full instructions and resource listing for an available skill.
|
||||
:param skill_name: The name of the skill to load (from the <available_skills> catalog).
|
||||
:param file_path: Optional relative path to a bundled skill file (for example references/api.md).
|
||||
"""
|
||||
from cptr.models import Config
|
||||
from cptr.utils.skills import bump_skill_view, load_skill, format_skill_content
|
||||
@@ -1617,14 +1630,51 @@ async def view_skill(
|
||||
if (await Config.get("skills.enabled")) in (False, "false", "0"):
|
||||
return "Error: skills are disabled by the administrator."
|
||||
|
||||
# Deduplication: if already activated, return short notice
|
||||
if skill_name in _activated_skills:
|
||||
return f"Skill '{skill_name}' is already loaded in this session. Refer to the existing <skill_content> above."
|
||||
|
||||
skill = load_skill(workspace, skill_name)
|
||||
if not skill:
|
||||
return f"Error: skill '{skill_name}' not found. Check <available_skills> for valid names."
|
||||
|
||||
if file_path:
|
||||
skill_dir = Path(skill.location).parent
|
||||
p = Path(file_path)
|
||||
windows_path = PureWindowsPath(file_path)
|
||||
if p.is_absolute() or windows_path.is_absolute() or windows_path.drive:
|
||||
return "Error: skill file path must be relative to the skill directory."
|
||||
if ".." in p.parts or ".." in windows_path.parts:
|
||||
return "Error: skill file path cannot contain '..' traversal components."
|
||||
|
||||
target = (skill_dir / file_path).resolve()
|
||||
try:
|
||||
target.relative_to(skill_dir.resolve())
|
||||
except (ValueError, OSError):
|
||||
return "Error: skill file path escapes the skill directory."
|
||||
if _is_dotenv(target):
|
||||
return _DOTENV_ERROR
|
||||
if not target.is_file():
|
||||
return f"Error: skill file not found: {file_path}"
|
||||
if target.suffix.lower() in IMAGE_EXTENSIONS:
|
||||
return await asyncio.to_thread(_read_image_file, target, file_path)
|
||||
|
||||
def _read_skill_file():
|
||||
size = target.stat().st_size
|
||||
if size > 500_000:
|
||||
return f"Error: skill file too large ({size} bytes, max 500KB)"
|
||||
try:
|
||||
content = target.read_text(errors="strict")
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
return f"Error: binary skill file ({target.suffix}), cannot read as text"
|
||||
return (
|
||||
f'<skill_file name="{skill.name}" path="{file_path}">\n'
|
||||
f"{content}\n"
|
||||
"</skill_file>"
|
||||
)
|
||||
|
||||
return await asyncio.to_thread(_read_skill_file)
|
||||
|
||||
# Deduplication: if already activated, return short notice
|
||||
if skill_name in _activated_skills:
|
||||
return f"Skill '{skill_name}' is already loaded in this session. Refer to the existing <skill_content> above."
|
||||
|
||||
_activated_skills.add(skill_name)
|
||||
bump_skill_view(workspace, skill_name, skill.source)
|
||||
return format_skill_content(skill)
|
||||
@@ -1805,15 +1855,24 @@ async def browser_type(ref: str, text: str, *, __context__: dict) -> str:
|
||||
return await client.snapshot()
|
||||
|
||||
|
||||
async def browser_screenshot(*, __context__: dict) -> str:
|
||||
"""Take a screenshot of the current browser page. Saves the image to the workspace."""
|
||||
async def browser_screenshot(
|
||||
width: Optional[int] = None, height: Optional[int] = None, *, __context__: dict
|
||||
) -> str:
|
||||
"""Take a screenshot of the current browser page. Saves the image to the workspace.
|
||||
:param width: Optional screenshot viewport width in CSS pixels.
|
||||
:param height: Optional screenshot viewport height in CSS pixels.
|
||||
"""
|
||||
cfg = await _get_browser_config()
|
||||
if cfg.get("provider", "local") != "local":
|
||||
return "Error: browser_screenshot requires Local CDP provider."
|
||||
if (width is None) != (height is None):
|
||||
return "Error: browser_screenshot width and height must be provided together."
|
||||
if width is not None and height is not None and (width <= 0 or height <= 0):
|
||||
return "Error: browser_screenshot width and height must be positive integers."
|
||||
|
||||
chat_id = __context__.get("chat_id", "default")
|
||||
client = await _get_cdp_session(chat_id)
|
||||
png_bytes = await client.screenshot()
|
||||
png_bytes = await client.screenshot(width=width, height=height)
|
||||
|
||||
# Save to workspace
|
||||
workspace = __context__.get("workspace", ".")
|
||||
|
||||
@@ -4,9 +4,30 @@ from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from cptr import env
|
||||
from cptr.utils.config import load_config
|
||||
|
||||
|
||||
def auto_gitignore_cptr_enabled() -> bool:
|
||||
if env.WORKSPACE_AUTO_GITIGNORE_DOT_CPTR_ENV is not None:
|
||||
return env.WORKSPACE_AUTO_GITIGNORE_DOT_CPTR
|
||||
|
||||
config = load_config()
|
||||
value = None
|
||||
workspace = config.get("workspace", {})
|
||||
if isinstance(workspace, dict):
|
||||
value = workspace.get("auto_gitignore_dot_cptr")
|
||||
app_config = config.get("app_config", {})
|
||||
if isinstance(app_config, dict):
|
||||
value = app_config.get("workspace.auto_gitignore_dot_cptr", value)
|
||||
return _bool_config(value, default=True)
|
||||
|
||||
|
||||
def ensure_cptr_gitignored(workspace: str | Path) -> None:
|
||||
"""If workspace is a git repo, ensure .cptr is listed in .gitignore."""
|
||||
if not auto_gitignore_cptr_enabled():
|
||||
return
|
||||
|
||||
ws = Path(workspace)
|
||||
if not (ws / ".git").exists():
|
||||
return
|
||||
@@ -26,3 +47,15 @@ def ensure_cptr_gitignored(workspace: str | Path) -> None:
|
||||
gitignore.write_text(content, encoding="utf-8")
|
||||
else:
|
||||
gitignore.write_text(f"{entry}\n", encoding="utf-8")
|
||||
|
||||
|
||||
def _bool_config(value: object, default: bool) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
normalized = value.strip().lower()
|
||||
if normalized in {"true", "1", "yes", "on"}:
|
||||
return True
|
||||
if normalized in {"false", "0", "no", "off"}:
|
||||
return False
|
||||
return default
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "cptr"
|
||||
version = "0.9.7"
|
||||
version = "0.9.8"
|
||||
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
|
||||
license = {file = "LICENSE"}
|
||||
readme = "README.md"
|
||||
|
||||
Reference in new issue
Block a user