Merge pull request #35 from open-webui/main

0.2.3
This commit is contained in:
Tim Baek authored and GitHub committed 2026-06-12 05:01:09 -05:00
commit e1392b93a7
35 files changed
+1683 -271

No files matched your search

+16
View File
@@ -5,6 +5,22 @@ 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.2.3] - 2026-06-12
### Added
- 🧩 **Skills system.** Define reusable instruction sets (SKILL.md files) in your workspace or globally. Skills are auto-discovered and surfaced in the system prompt; the AI loads them on demand via a new `view_skill` tool. Type `$` in the chat input to mention a skill directly.
- 🔔 **Update notifications.** Admins now see a non-intrusive toast when a new version is available, with a link to release notes. Dismissals are remembered for 24 hours. Toggle in Settings > General.
- 📝 **Per-model system prompts.** Configure custom system prompts per model or as a global default from the Models admin page. Supports `{{VARIABLE}}` template placeholders (workspace name, file tree, instructions, skills, OS, date, model).
- 📄 **Workspace system prompt override.** Place a `.cptr/system.md` file in any workspace to fully override the system prompt for that project.
### Changed
- 🔧 **Context-aware tool execution.** Automation tools (`create_automation`, `list_automations`, etc.) now receive full execution context (user ID, model ID) instead of just the workspace path, fixing automations being created as the wrong user.
- 🏷️ **Dynamic page titles.** Browser tab titles now reflect the active file or chat tab (e.g. "stores.ts / myproject / cptr") instead of just the workspace name.
- 🔗 **"Update available" badge in About.** The Settings > About page now shows a link to the latest release when a newer version exists.
- 🌍 **i18n updates.** Added translation keys for system prompts, model templates, update notifications, and connection editing across all 10 supported locales.
## [0.2.2] - 2026-06-11
### Added
+31
View File
@@ -15,6 +15,7 @@ from cptr.routers import (
git_router,
proxy_router,
search_router,
skills_router,
state_router,
terminal_router,
workspace_router,
@@ -192,6 +193,7 @@ app.include_router(files_router)
app.include_router(git_router)
app.include_router(proxy_router)
app.include_router(search_router)
app.include_router(skills_router)
app.include_router(state_router)
app.include_router(terminal_router)
app.include_router(workspace_router)
@@ -213,6 +215,35 @@ async def get_changelog():
return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
@app.get("/api/version/updates")
async def get_version_updates(request: Request):
"""Check GitHub for the latest release. Admin-only."""
from cptr.routers.admin import require_admin
from importlib.metadata import version as pkg_version
require_admin(request)
try:
current = pkg_version("cptr")
except Exception:
current = "dev"
try:
import httpx
async with httpx.AsyncClient(timeout=2) as client:
r = await client.get(
"https://api.github.com/repos/open-webui/computer/releases/latest",
headers={"Accept": "application/vnd.github+json"},
)
r.raise_for_status()
tag = r.json().get("tag_name", "")
latest = tag.lstrip("v") if tag else current
return {"current": current, "latest": latest}
except Exception:
return {"current": current, "latest": current}
# PWA manifest (backend-driven so each instance has its own identity)
@app.get("/manifest.json")
async def pwa_manifest():
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "frontend",
"private": true,
"version": "0.2.0",
"version": "0.2.3",
"type": "module",
"scripts": {
"dev": "vite dev",
+1 -1
View File
@@ -109,7 +109,7 @@ export const verifyConnection = (id: string) =>
export interface ModelConfigEntry {
is_active?: boolean;
params?: { request_params?: Record<string, unknown> };
params?: { request_params?: Record<string, unknown>; system_prompt?: string };
}
export interface ModelConfigResponse {
+16
View File
@@ -0,0 +1,16 @@
/**
* Skills API: list available skills for the $ mention picker.
*/
import { fetchJSON } from '$lib/apis';
export interface SkillInfo {
name: string;
description: string;
location: string;
source: string; // "workspace" | "global"
license?: string;
compatibility?: string;
}
export const getSkills = (workspace: string) =>
fetchJSON<SkillInfo[]>(`/api/skills?workspace=${encodeURIComponent(workspace)}`);
@@ -156,6 +156,7 @@
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2"
>{$t('connections.models')}</label
>
<p class="text-[10px] text-gray-300 dark:text-gray-700 mb-0.5">{$t('connections.modelsHint')}</p>
<input
type="text"
placeholder="claude-sonnet-4-20250514, claude-opus-4-20250514"
@@ -46,7 +46,7 @@
.split(',')
.map((m) => m.trim())
.filter(Boolean)
: undefined;
: null;
const name =
formName.trim() ||
(() => {
@@ -192,6 +192,7 @@
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2"
>{$t('connections.models')}</label
>
<p class="text-[10px] text-gray-300 dark:text-gray-700 mb-0.5">{$t('connections.modelsHint')}</p>
<input
type="text"
placeholder="claude-sonnet-4-20250514, claude-opus-4-20250514"
@@ -17,6 +17,7 @@
provider: string;
is_active: boolean;
rows: ParamRow[];
systemPrompt: string;
dirty: boolean;
};
@@ -26,8 +27,30 @@
let selectedId = $state<string | null>(null);
let globalRows = $state<ParamRow[]>([]);
let globalSystemPrompt = $state('');
let globalDirty = $state(false);
let globalExpanded = $state(false);
let showVariables = $state(false);
const TEMPLATE_VARIABLES = [
{ name: 'WORKSPACE_NAME', desc: 'Workspace folder name' },
{ name: 'WORKSPACE_PATH', desc: 'Full workspace path' },
{ name: 'FILE_TREE', desc: 'File listing (top-level + 1 depth)' },
{ name: 'INSTRUCTIONS', desc: 'MEMORY.md / AGENTS.md / CLAUDE.md content' },
{ name: 'OS', desc: 'Operating system (macOS, Linux, Windows)' },
{ name: 'DATE', desc: 'Current date (ISO format)' },
{ name: 'MODEL', desc: 'Model ID being used' }
];
const DEFAULT_PROMPT_PLACEHOLDER = `You are a helpful coding assistant. You have access to tools to read, search, and modify files in the workspace. Use them to help the user with their coding tasks.
For complex tasks, create an implementation plan first using create_artifact, then wait for approval before coding.
{{INSTRUCTIONS}}
Workspace: {{WORKSPACE_NAME}}
Files:
{{FILE_TREE}}`;
let hasDirty = $derived(globalDirty || models.some((m) => m.dirty));
@@ -58,13 +81,15 @@
const data = await getModelConfig();
const config = data.config || {};
globalRows = parseRows(config['*']);
globalExpanded = globalRows.length > 0;
globalSystemPrompt = config['*']?.params?.system_prompt || '';
globalExpanded = globalRows.length > 0 || !!globalSystemPrompt;
models = data.models.map((m) => {
const mc = config[m.id];
return {
...m,
is_active: mc?.is_active !== false,
rows: parseRows(mc),
systemPrompt: (mc?.params as any)?.system_prompt || '',
dirty: false
};
});
@@ -89,24 +114,30 @@
}
}
function buildParams(rows: ParamRow[], systemPrompt: string): Record<string, unknown> {
const params: Record<string, unknown> = {};
const rp = rowsToRequestParams(rows);
if (Object.keys(rp).length) params.request_params = rp;
if (systemPrompt.trim()) params.system_prompt = systemPrompt.trim();
return params;
}
async function saveAll() {
saving = true;
try {
const promises: Promise<unknown>[] = [];
if (globalDirty) {
const rp = rowsToRequestParams(globalRows);
promises.push(
updateModelConfig('*', {
params: Object.keys(rp).length ? { request_params: rp } : {}
params: buildParams(globalRows, globalSystemPrompt)
})
);
}
for (const model of models) {
if (model.dirty) {
const rp = rowsToRequestParams(model.rows);
promises.push(
updateModelConfig(model.id, {
params: Object.keys(rp).length ? { request_params: rp } : {}
params: buildParams(model.rows, model.systemPrompt)
})
);
}
@@ -123,17 +154,86 @@
}
</script>
{#snippet systemPromptField(value: string, onInput: (v: string) => void, placeholder: string)}
<div class="mb-2">
<span class="text-[10px] text-gray-400 dark:text-gray-600 uppercase tracking-wide"
>{$t('models.systemPrompt')}</span
>
<textarea
class="w-full mt-1 bg-gray-50 dark:bg-white/4 border border-gray-200 dark:border-white/8 rounded-lg px-2.5 py-2 text-[11px] font-mono text-gray-600 dark:text-gray-400 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none resize-y leading-relaxed"
rows="6"
{placeholder}
value={value}
oninput={(e) => onInput((e.target as HTMLTextAreaElement).value)}
spellcheck="false"
></textarea>
<div class="flex items-center gap-2 mt-1">
<button
class="text-[10px] text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-400 transition-colors duration-75"
onclick={() => (showVariables = !showVariables)}
>
{$t('models.templateVariables')} {showVariables ? '▾' : '▸'}
</button>
{#if value.trim()}
<button
class="text-[10px] text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-400 transition-colors duration-75"
onclick={() => onInput('')}
>
{$t('models.resetToDefault')}
</button>
{/if}
</div>
{#if showVariables}
<div
class="mt-1 rounded-lg bg-gray-50 dark:bg-white/3 border border-gray-100 dark:border-white/5 px-2.5 py-2"
>
{#each TEMPLATE_VARIABLES as v}
<div class="flex items-baseline gap-2 h-5">
<code
class="text-[10px] font-mono text-gray-500 dark:text-gray-500 shrink-0 select-all"
>{`{{${v.name}}}`}</code
>
<span class="text-[10px] text-gray-400 dark:text-gray-600 truncate"
>{v.desc}</span
>
</div>
{/each}
</div>
{/if}
</div>
{/snippet}
{#snippet paramRows(rows: ParamRow[], onInput: () => void, onRemove: (i: number) => void, onAdd: () => void)}
<div class="mb-2">
<span class="text-[10px] text-gray-400 dark:text-gray-600 uppercase tracking-wide">request params</span>
<span class="text-[10px] text-gray-400 dark:text-gray-600 uppercase tracking-wide"
>request params</span
>
{#each rows as row, i}
<div class="group/row flex items-center gap-1.5 h-6">
<input type="text" placeholder="key" bind:value={row.key} oninput={onInput} autocomplete="off" spellcheck="false"
class="w-24 shrink-0 bg-transparent text-[11px] font-mono text-gray-500 dark:text-gray-500 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none" />
<input type="text" placeholder="value" bind:value={row.value} oninput={onInput} autocomplete="off" spellcheck="false"
class="flex-1 min-w-0 bg-transparent text-[11px] font-mono text-gray-500 dark:text-gray-500 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none" />
<button type="button" onclick={() => onRemove(i)}
class="shrink-0 text-gray-300 dark:text-gray-700 opacity-0 group-hover/row:opacity-100 hover:text-gray-500 dark:hover:text-gray-400 transition-colors duration-75" aria-label="Remove">
<input
type="text"
placeholder="key"
bind:value={row.key}
oninput={onInput}
autocomplete="off"
spellcheck="false"
class="w-24 shrink-0 bg-transparent text-[11px] font-mono text-gray-500 dark:text-gray-500 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none"
/>
<input
type="text"
placeholder="value"
bind:value={row.value}
oninput={onInput}
autocomplete="off"
spellcheck="false"
class="flex-1 min-w-0 bg-transparent text-[11px] font-mono text-gray-500 dark:text-gray-500 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none"
/>
<button
type="button"
onclick={() => onRemove(i)}
class="shrink-0 text-gray-300 dark:text-gray-700 opacity-0 group-hover/row:opacity-100 hover:text-gray-500 dark:hover:text-gray-400 transition-colors duration-75"
aria-label="Remove"
>
<Icon name="xmark" size={8} />
</button>
</div>
@@ -149,30 +249,56 @@
{/snippet}
<div class="flex flex-col h-full">
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4 shrink-0">{$t('admin.models')}</h2>
{#if loading}
<div class="flex justify-center py-8"><Spinner size={16} /></div>
{:else}
<div class="flex-1 min-h-0 overflow-y-auto">
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">
{$t('admin.models')}
</h2>
<!-- Global defaults -->
<button
class="group flex items-center gap-2 w-full h-7 text-left"
onclick={() => (globalExpanded = !globalExpanded)}
>
<span class="flex-1 text-[13px] text-gray-500 dark:text-gray-400">{$t('models.defaults')}</span>
{#if globalRows.filter((r) => r.key.trim()).length > 0}
<span class="text-[10px] text-gray-400 dark:text-gray-600">{globalRows.filter((r) => r.key.trim()).length}</span>
<span class="flex-1 text-[13px] text-gray-500 dark:text-gray-400"
>{$t('models.defaults')}</span
>
{#if globalRows.filter((r) => r.key.trim()).length > 0 || globalSystemPrompt.trim()}
<span class="text-[10px] text-gray-400 dark:text-gray-600">
{#if globalSystemPrompt.trim()}prompt{/if}
{#if globalRows.filter((r) => r.key.trim()).length > 0}
{globalRows.filter((r) => r.key.trim()).length} params
{/if}
</span>
{/if}
<Icon name={globalExpanded ? 'chevron-down' : 'chevron-right'} size={10} class="shrink-0 text-gray-300 dark:text-gray-700" />
<Icon
name={globalExpanded ? 'chevron-down' : 'chevron-right'}
size={10}
class="shrink-0 text-gray-300 dark:text-gray-700"
/>
</button>
{#if globalExpanded}
{@render systemPromptField(
globalSystemPrompt,
(v) => {
globalSystemPrompt = v;
globalDirty = true;
},
DEFAULT_PROMPT_PLACEHOLDER
)}
{@render paramRows(
globalRows,
() => (globalDirty = true),
(i) => { globalRows = globalRows.filter((_, idx) => idx !== i); globalDirty = true; },
() => { globalRows = [...globalRows, { key: '', value: '' }]; globalDirty = true; }
(i) => {
globalRows = globalRows.filter((_, idx) => idx !== i);
globalDirty = true;
},
() => {
globalRows = [...globalRows, { key: '', value: '' }];
globalDirty = true;
}
)}
{/if}
@@ -182,34 +308,65 @@
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-[13px] truncate {model.is_active ? 'text-gray-700 dark:text-gray-300' : 'text-gray-400 dark:text-gray-600'}">
<span
class="flex-1 text-[13px] truncate {model.is_active
? 'text-gray-700 dark:text-gray-300'
: 'text-gray-400 dark:text-gray-600'}"
>
{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}
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); } }}
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
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>
{#if selectedId === model.id}
{@render systemPromptField(
model.systemPrompt,
(v) => {
model.systemPrompt = v;
model.dirty = true;
},
$t('models.systemPromptInherited')
)}
{@render paramRows(
model.rows,
() => (model.dirty = true),
(i) => { model.rows = model.rows.filter((_, idx) => idx !== i); model.dirty = true; },
() => { model.rows = [...model.rows, { key: '', value: '' }]; model.dirty = true; }
(i) => {
model.rows = model.rows.filter((_, idx) => idx !== i);
model.dirty = true;
},
() => {
model.rows = [...model.rows, { key: '', value: '' }];
model.dirty = true;
}
)}
{/if}
{/each}
{#if models.length === 0}
<p class="text-[13px] text-gray-400 dark:text-gray-600 py-4">{$t('models.noModels')}</p>
<p class="text-[13px] text-gray-400 dark:text-gray-600 py-4">
{$t('models.noModels')}
</p>
{/if}
</div>
@@ -223,5 +380,3 @@
</div>
{/if}
</div>
@@ -1,6 +1,6 @@
<script lang="ts">
import { t } from '$lib/i18n';
import { appVersion, showChangelog } from '$lib/stores';
import { appVersion, showChangelog, updateAvailable, latestVersion } from '$lib/stores';
</script>
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">
@@ -22,7 +22,18 @@
>v{$appVersion}</button
>
{/if}
{#if $updateAvailable}
<span class="text-[11px] text-gray-300 dark:text-gray-600">·</span>
<a
href="https://github.com/open-webui/computer/releases"
target="_blank"
rel="noopener noreferrer"
class="text-[11px] text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
>v{$latestVersion} available</a
>
{/if}
</div>
<p class="text-[13px] text-gray-500 mt-0.5 mb-4">{$t('app.tagline')}</p>
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-1">
@@ -44,3 +55,4 @@
<p class="text-[11px] text-gray-300 dark:text-gray-700 pt-8">
{$t('about.createdBy')}
</p>
@@ -1,11 +1,12 @@
<script lang="ts">
import { toast } from 'svelte-sonner';
import Icon from '../Icon.svelte';
import { theme, streamingBehavior } from '$lib/stores';
import { theme, streamingBehavior, showUpdateToastPref } from '$lib/stores';
import type { Theme, StreamingBehavior } from '$lib/stores';
import { t, locale, changeLocale, supportedLocales } from '$lib/i18n';
import { notificationsEnabled, notificationSound } from '$lib/stores/chat';
import { fetchJSON } from '$lib/apis';
import { session } from '$lib/session';
import ToggleSwitch from '../common/ToggleSwitch.svelte';
import { onMount } from 'svelte';
@@ -132,6 +133,17 @@
</div>
</div>
{#if $session?.role === 'admin'}
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">Updates</h3>
<label class="flex items-center justify-between cursor-pointer">
<span class="text-xs text-gray-600 dark:text-gray-400">Update notifications</span>
<ToggleSwitch value={$showUpdateToastPref} onchange={(v) => showUpdateToastPref.set(v)} />
</label>
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-1">
Show a toast when a new version of cptr is available.
</p>
{/if}
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">Message queue</h3>
<div class="flex gap-1">
{#each [{ value: 'queue' as StreamingBehavior, label: 'Queue' }, { value: 'interrupt' as StreamingBehavior, label: 'Interrupt' }] as opt}
@@ -0,0 +1,39 @@
<script lang="ts">
import { t } from '$lib/i18n';
import { latestVersion } from '$lib/stores';
import Icon from './Icon.svelte';
import { fade } from 'svelte/transition';
let { onclose }: { onclose: () => void } = $props();
</script>
<div
class="fixed bottom-4 right-4 z-50"
in:fade={{ duration: 100 }}
out:fade={{ duration: 75 }}
>
<div
class="flex items-center gap-2 rounded-lg border border-gray-200 dark:border-white/6 bg-white dark:bg-[#1a1a1a] px-3 py-2"
>
<span class="text-[11px] text-gray-500 dark:text-gray-400">
{$t('update.available', { version: $latestVersion })}
</span>
<a
href="https://github.com/open-webui/computer/releases"
target="_blank"
rel="noopener noreferrer"
class="text-[11px] text-gray-900 dark:text-white hover:underline font-medium"
>
{$t('update.viewRelease')}
</a>
<button
onclick={onclose}
class="ml-0.5 flex items-center justify-center w-5 h-5 rounded text-gray-300 hover:text-gray-500 dark:text-gray-600 dark:hover:text-gray-400 transition-colors duration-75"
aria-label="Dismiss"
>
<Icon name="xmark" size={12} />
</button>
</div>
</div>
@@ -9,8 +9,11 @@
import { all, createLowlight } from 'lowlight';
import { createFileMention, extractMentionedFiles, type FileMentionAttrs } from './FileMention';
import { createSkillMention, extractMentionedSkills, type SkillMentionAttrs } from './SkillMention';
import FileSuggestionPopup from './FileSuggestionPopup.svelte';
import SkillSuggestionPopup from './SkillSuggestionPopup.svelte';
import { searchFiles } from '$lib/apis/files';
import { getSkills } from '$lib/apis/skills';
import { uploadFile } from '$lib/apis/files';
import ModelSelector from '../common/ModelSelector.svelte';
import SendButton from './SendButton.svelte';
@@ -265,6 +268,156 @@
}
}
// ── $skill mention suggestion ──────────────────────
let skillPopupEl: HTMLDivElement | null = null;
let skillPopupComponent: Record<string, any> | null = null;
let skillActiveClientRectFn: (() => DOMRect | null) | null = null;
let skillRepositionRafId: number | null = null;
let cachedSkills: SkillMentionAttrs[] | null = null;
async function fetchSkillSuggestions({ query }: { query: string }): Promise<SkillMentionAttrs[]> {
if (!workspace) return [];
try {
// Cache skills list (small, doesn't change during a session)
if (!cachedSkills) {
const data = await getSkills(workspace);
cachedSkills = data.map((s) => ({
id: s.name,
label: s.name,
description: s.description,
source: s.source,
}));
}
if (!query) return cachedSkills;
const q = query.toLowerCase();
return cachedSkills.filter(
(s) => s.label.toLowerCase().includes(q) || (s.description || '').toLowerCase().includes(q)
);
} catch {
return [];
}
}
function mountSkillPopup(
items: SkillMentionAttrs[],
selectedIdx: number,
onselect: (i: number) => void
) {
if (skillPopupComponent) {
try { unmount(skillPopupComponent); } catch {}
skillPopupComponent = null;
}
if (!skillPopupEl) {
skillPopupEl = document.createElement('div');
document.body.appendChild(skillPopupEl);
}
skillPopupComponent = mount(SkillSuggestionPopup, {
target: skillPopupEl,
props: { items, selectedIndex: selectedIdx, onselect }
});
}
function startSkillRepositionLoop() {
stopSkillRepositionLoop();
function tick() {
if (skillActiveClientRectFn) {
updateSkillPopupPosition(skillActiveClientRectFn());
skillRepositionRafId = requestAnimationFrame(tick);
}
}
skillRepositionRafId = requestAnimationFrame(tick);
}
function stopSkillRepositionLoop() {
if (skillRepositionRafId !== null) {
cancelAnimationFrame(skillRepositionRafId);
skillRepositionRafId = null;
}
}
function createSkillSuggestionRenderer() {
let selectedIndex = 0;
let currentItems: SkillMentionAttrs[] = [];
let command: ((attrs: SkillMentionAttrs) => void) | null = null;
function doSelect(index: number) {
const item = currentItems[index];
if (item && command) command(item);
}
function remount() {
mountSkillPopup(currentItems, selectedIndex, doSelect);
}
return {
onStart(props: any) {
command = props.command;
currentItems = props.items;
selectedIndex = 0;
skillActiveClientRectFn = props.clientRect ?? null;
remount();
updateSkillPopupPosition(props.clientRect?.());
startSkillRepositionLoop();
},
onUpdate(props: any) {
command = props.command;
currentItems = props.items;
selectedIndex = 0;
skillActiveClientRectFn = props.clientRect ?? null;
remount();
updateSkillPopupPosition(props.clientRect?.());
},
onKeyDown({ event }: { event: KeyboardEvent }) {
if (event.key === 'ArrowDown') {
selectedIndex = (selectedIndex + 1) % Math.max(currentItems.length, 1);
remount();
return true;
}
if (event.key === 'ArrowUp') {
selectedIndex = (selectedIndex - 1 + currentItems.length) % Math.max(currentItems.length, 1);
remount();
return true;
}
if (event.key === 'Enter') {
const item = currentItems[selectedIndex];
if (item && command) command(item);
return true;
}
if (event.key === 'Escape') {
destroySkillPopup();
return true;
}
return false;
},
onExit() {
destroySkillPopup();
}
};
}
function updateSkillPopupPosition(rect: DOMRect | null) {
if (!skillPopupEl || !rect) return;
const child = skillPopupEl.firstElementChild as HTMLElement | null;
if (!child) return;
const popupHeight = child.offsetHeight || 200;
child.style.position = 'fixed';
child.style.left = `${Math.max(8, Math.min(rect.left, window.innerWidth - 340))}px`;
child.style.top = `${rect.top - popupHeight - 8}px`;
}
function destroySkillPopup() {
stopSkillRepositionLoop();
skillActiveClientRectFn = null;
if (skillPopupComponent) {
try { unmount(skillPopupComponent); } catch {}
skillPopupComponent = null;
}
if (skillPopupEl) {
skillPopupEl.remove();
skillPopupEl = null;
}
}
// ── Editor lifecycle ────────────────────────────
onMount(() => {
if (!editorEl) return;
@@ -274,6 +427,11 @@
render: createSuggestionRenderer
});
const skillMention = createSkillMention({
items: fetchSkillSuggestions,
render: createSkillSuggestionRenderer
});
editor = new Editor({
element: editorEl,
extensions: [
@@ -284,7 +442,8 @@
Markdown,
Placeholder.configure({ placeholder }),
CodeBlockLowlight.configure({ lowlight }),
fileMention
fileMention,
skillMention
],
content: inputText || '',
contentType: inputText ? 'markdown' : undefined,
@@ -297,7 +456,7 @@
handleKeyDown: (view, event) => {
if (event.key === 'Enter' && !event.shiftKey) {
// Don't send while suggestion popup is open — let it confirm selection
if (popupComponent) return false;
if (popupComponent || skillPopupComponent) return false;
const { state } = view;
const head = state.selection.$head;
@@ -326,6 +485,7 @@
onDestroy(() => {
destroyPopup();
destroySkillPopup();
editor?.destroy();
editor = null;
});
@@ -359,6 +519,11 @@
attachedUploads = [];
}
export function getSkillIds(): string[] {
if (!editor) return [];
return extractMentionedSkills(editor.getJSON());
}
// Allow sending during streaming (message will be enqueued server-side)
const canSend = $derived(inputText.trim() && selectedModel && !sending);
</script>
@@ -0,0 +1,64 @@
/**
* TipTap Mention extension configured for $skill mentions.
*
* Similar to FileMention but uses '$' as the trigger character
* and wired to the skills API for suggestions.
*/
import Mention from '@tiptap/extension-mention';
export interface SkillMentionAttrs {
id: string; // skill name
label: string; // display name
description?: string; // skill description (for popup)
source?: string; // "workspace" | "global" (for popup badge)
}
/**
* Create the configured Mention extension for skills.
* Uses '$' as the trigger character.
*/
export function createSkillMention(suggestionOptions: {
items: (props: { query: string }) => Promise<SkillMentionAttrs[]> | SkillMentionAttrs[];
render: () => {
onStart: (props: any) => void;
onUpdate: (props: any) => void;
onKeyDown: (props: any) => boolean;
onExit: () => void;
};
}) {
return Mention.extend({ name: 'skillMention' }).configure({
HTMLAttributes: {
class: 'bg-purple-500/10 text-purple-400 rounded px-1 py-px text-xs font-mono'
},
renderText({ node }) {
return `$${node.attrs.label ?? node.attrs.id}`;
},
suggestion: {
char: '$',
allowSpaces: false,
...suggestionOptions
}
});
}
/**
* Extract all skill mention names from a TipTap editor JSON doc.
*/
export function extractMentionedSkills(doc: any): string[] {
const skills: string[] = [];
function walk(node: any) {
if (node.type === 'skillMention' && node.attrs?.id) {
skills.push(node.attrs.id);
}
if (node.content) {
for (const child of node.content) {
walk(child);
}
}
}
if (doc) walk(doc);
return [...new Set(skills)];
}
@@ -0,0 +1,74 @@
<script lang="ts">
import Icon from '../Icon.svelte';
interface SuggestionItem {
id: string;
label: string;
description?: string;
source?: string;
}
interface Props {
items: SuggestionItem[];
selectedIndex: number;
onselect: (index: number) => void;
}
let { items, selectedIndex, onselect }: Props = $props();
let listEl: HTMLDivElement | undefined = $state();
// Scroll selected item into view
$effect(() => {
if (listEl && selectedIndex >= 0) {
const el = listEl.children[selectedIndex] as HTMLElement | undefined;
el?.scrollIntoView({ block: 'nearest' });
}
});
</script>
<div
class="fixed z-50 w-72 max-h-48 overflow-y-auto rounded-xl bg-white dark:bg-[#1a1a1a] border border-gray-150 dark:border-white/6 shadow-xl p-0.5"
>
{#if items.length === 0}
<div class="px-3 py-2 text-xs text-gray-400 dark:text-gray-600">No skills found</div>
{:else}
<div class="text-[10px] text-gray-400 dark:text-gray-600 px-2.5 pt-1.5 pb-0.5">
Skills
</div>
<div bind:this={listEl}>
{#each items as item, i (item.id)}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<button
class="flex items-start gap-2 w-full px-2 py-1.5 rounded-xl text-xs text-left transition-colors duration-75
{i === selectedIndex
? 'bg-gray-50 dark:bg-white/5 text-gray-900 dark:text-white'
: 'text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5 hover:text-gray-900 dark:hover:text-white'}"
onmousedown={(e) => {
e.preventDefault();
onselect(i);
}}
onmouseenter={() => (selectedIndex = i)}
>
<span
class="flex items-center justify-center w-4 shrink-0 mt-0.5 text-purple-400 dark:text-purple-400"
>
<svg viewBox="0 0 16 16" fill="currentColor" class="size-3.5">
<path d="M8.75 1a.75.75 0 0 0-1.5 0v1.249c-1.373.158-2.476.682-3.33 1.536C3.066 4.639 2.5 5.77 2.5 7.25c0 1.296-.266 2.193-.613 2.852-.35.663-.83 1.132-1.268 1.507a.75.75 0 0 0 .494 1.315h3.137a3.75 3.75 0 0 0 7.5 0h3.137a.75.75 0 0 0 .494-1.315c-.438-.375-.919-.844-1.268-1.507-.347-.659-.613-1.556-.613-2.852 0-1.48-.566-2.611-1.42-3.465-.854-.854-1.957-1.378-3.33-1.536V1ZM6.5 12.924a2.25 2.25 0 0 0 3 0h-3Z" />
</svg>
</span>
<span class="flex-1 min-w-0 flex flex-col overflow-hidden">
<span class="flex items-center gap-1.5">
<span class="truncate font-medium">{item.label}</span>
{#if item.source && item.source !== 'workspace'}
<span class="text-[9px] text-gray-400 dark:text-gray-600 bg-gray-100 dark:bg-white/5 rounded px-1 shrink-0">{item.source}</span>
{/if}
</span>
{#if item.description}
<span class="text-[10px] text-gray-400 dark:text-gray-600 truncate">{item.description}</span>
{/if}
</span>
</button>
{/each}
</div>
{/if}
</div>
+34 -21
View File
@@ -1,6 +1,5 @@
{
"app.tagline": "Dein Computer, von überall.",
"auth.createAccountHint": "Erstelle ein Konto, um loszulegen.",
"auth.signInSystemHint": "Melde dich mit deinem Systemkonto an.",
"auth.setup": "Einrichtung",
@@ -20,7 +19,6 @@
"auth.minChars": "Mindestens 6 Zeichen",
"auth.connectionFailed": "Verbindung fehlgeschlagen",
"auth.accountPending": "Konto erstellt. Warte auf die Freigabe durch den Administrator.",
"sidebar.workspaces": "Arbeitsbereiche",
"sidebar.addWorkspace": "Arbeitsbereich hinzufügen",
"sidebar.collapse": "Einklappen",
@@ -31,14 +29,13 @@
"sidebar.remove": "Entfernen",
"sidebar.workspaceOptions": "Arbeitsbereich-Optionen",
"sidebar.closeSidebar": "Seitenleiste schließen",
"sidebar.showMore": "Mehr anzeigen",
"bar.newFile": "Neue Datei",
"bar.newTerminal": "Neues Terminal",
"bar.closeTab": "Tab schließen",
"bar.new": "Neu...",
"bar.sidebar": "Seitenleiste",
"bar.toggleSidebar": "Seitenleiste umschalten",
"files.filter": "Filtern...",
"files.refresh": "Aktualisieren",
"files.sort": "Sortieren",
@@ -73,10 +70,16 @@
"files.showHidden": "Dotfiles anzeigen",
"files.hideHidden": "Dotfiles ausblenden",
"files.failedToLoad": "Verzeichnis konnte nicht geladen werden",
"search.placeholder": "Suchen...",
"search.search": "Suche",
"search.chats": "Chats",
"search.files": "Dateien",
"search.noResults": "Keine Ergebnisse gefunden",
"search.recentChats": "Letzte Chats",
"search.noRecentChats": "Keine letzten Chats",
"quickOpen.searchFiles": "Dateien suchen...",
"quickOpen.noFiles": "Keine Dateien gefunden",
"settings.back": "Zurück",
"settings.general": "Allgemein",
"settings.account": "Konto",
@@ -84,18 +87,15 @@
"settings.save": "Speichern",
"settings.saved": "Gespeichert",
"settings.saving": "Speichern…",
"general.title": "Allgemein",
"general.theme": "Design",
"general.light": "Hell",
"general.dark": "Dunkel",
"general.system": "System",
"general.language": "Sprache",
"general.tools": "Tools",
"general.autoApproveTools": "Alle Tool-Aufrufe automatisch genehmigen",
"general.autoApproveToolsDesc": "Tool-Aufrufe (Schreiben, Ausführen usw.) automatisch ohne Bestätigung erlauben",
"account.title": "Konto",
"account.displayName": "Anzeigename",
"account.displayNamePlaceholder": "Anzeigename eingeben",
@@ -113,11 +113,9 @@
"account.uploadFailed": "Hochladen fehlgeschlagen",
"account.failedToUpdate": "Aktualisierung fehlgeschlagen",
"account.failedToRemoveAvatar": "Avatar konnte nicht entfernt werden",
"about.title": "Über",
"about.license": "Lizenz",
"about.createdBy": "Erstellt von Tim Baek, hergestellt auf der Erde",
"git.changes": "Änderungen",
"git.history": "Verlauf",
"git.fetch": "Abrufen",
@@ -160,7 +158,6 @@
"git.discard": "Verwerfen",
"git.copyFilePath": "Dateipfad kopieren",
"git.copyRelativePath": "Relativen Pfad kopieren",
"admin.users": "Benutzer",
"admin.settings": "Einstellungen",
"admin.noUsers": "Keine Benutzer",
@@ -191,9 +188,7 @@
"admin.delete": "Löschen",
"admin.usernameRequired": "Benutzername erforderlich",
"admin.minCharsPassword": "Mindestens 6 Zeichen",
"admin.connections": "Verbindungen",
"connections.loadError": "Verbindungen konnten nicht geladen werden",
"connections.fieldsRequired": "Basis-URL und API-Schlüssel erforderlich",
"connections.added": "Verbindung hinzugefügt",
@@ -208,18 +203,18 @@
"connections.baseUrl": "Basis-URL",
"connections.prefixId": "Präfix-ID",
"connections.models": "Modelle (durch Kommas getrennt, optional)",
"connections.modelsHint": "Leer lassen, um automatisch vom Anbieter zu erkennen.",
"connections.cancel": "Abbrechen",
"connections.add": "Hinzufügen",
"connections.edit": "Verbindung bearbeiten",
"connections.updated": "Verbindung aktualisiert",
"connections.verify": "Prüfen",
"bar.newChat": "Neuer Chat",
"home.start": "Start",
"home.openFolder": "Ordner öffnen...",
"home.recent": "Zuletzt verwendet",
"home.folders": "Ordner",
"home.chatComingSoon": "Chat (demnächst verfügbar)",
"directory.cancel": "Abbrechen",
"directory.open": "\"{{name}}\" öffnen",
"directory.hidden": "Versteckte",
@@ -227,24 +222,20 @@
"directory.goBack": "Zurück",
"directory.typePath": "Type a path... (Tab to complete)",
"directory.retry": "Erneut versuchen",
"saveDialog.fileNamePlaceholder": "Dateiname…",
"saveDialog.emptyFolder": "Leerer Ordner",
"saveDialog.cancel": "Abbrechen",
"saveDialog.save": "Speichern",
"saveDialog.hidden": "Versteckte",
"saveDialog.retry": "Erneut versuchen",
"port.preview": "Vorschau",
"port.via": "über {{name}}",
"system.title": "System",
"system.cpu": "CPU",
"system.memory": "Speicher",
"system.disk": "Festplatte",
"system.cores": "{{count}} Kerne",
"system.process": "PROZESS",
"admin.web": "Web",
"admin.webEnabled": "Webzugriff aktivieren",
"admin.webEnabledHint": "KI kann das Web durchsuchen und URLs abrufen.",
@@ -265,5 +256,27 @@
"admin.webCcBaseUrl": "Basis-URL",
"admin.webCcKey": "API-Schlüssel",
"admin.webCcModel": "Modell",
"admin.webCcHint": "Beliebiger OpenAI-kompatibler Endpunkt (z. B. Perplexity Sonar, LiteLLM-Proxy)"
"admin.webCcHint": "Beliebiger OpenAI-kompatibler Endpunkt (z. B. Perplexity Sonar, LiteLLM-Proxy)",
"admin.models": "Modelle",
"models.defaults": "Standardwerte",
"models.noDefaults": "Keine globalen Standardwerte",
"models.noParams": "Keine Parameter",
"models.noModels": "Keine Modelle verfügbar",
"models.addConnection": "Zuerst eine Verbindung hinzufügen.",
"models.failedToLoad": "Modellkonfiguration konnte nicht geladen werden",
"models.failedToToggle": "Modell konnte nicht umgeschaltet werden",
"models.failedToSave": "Speichern fehlgeschlagen",
"models.savedDefaults": "Globale Standardwerte gespeichert",
"models.savedParams": "Parameter für {{name}} gespeichert",
"models.add": "+ Hinzufügen",
"models.save": "Speichern",
"models.systemPrompt": "System-Prompt",
"models.systemPromptHint": "Standardanweisungen für das Modell. Verwenden Sie {{VARIABLES}} für dynamische Inhalte.",
"models.systemPromptInherited": "Erbt den globalen Standard",
"models.templateVariables": "Variablen",
"models.resetToDefault": "Zurücksetzen",
"update.available": "Eine neue Version (v{{version}}) ist verfügbar.",
"update.viewRelease": "Versionshinweise ansehen →",
"update.updateAvailable": "Update verfügbar: v{{version}}"
}
+14 -1
View File
@@ -217,8 +217,11 @@
"connections.baseUrl": "Base URL",
"connections.prefixId": "Prefix ID",
"connections.models": "Models (comma-separated, optional)",
"connections.modelsHint": "Leave blank to auto-discover from provider.",
"connections.cancel": "Cancel",
"connections.add": "Add",
"connections.edit": "Edit Connection",
"connections.updated": "Connection updated",
"connections.verify": "Verify",
"bar.newChat": "New Chat",
@@ -288,5 +291,15 @@
"models.savedDefaults": "Saved global defaults",
"models.savedParams": "Saved params for {{name}}",
"models.add": "+ Add",
"models.save": "Save"
"models.save": "Save",
"models.systemPrompt": "System Prompt",
"models.systemPromptHint": "Default instructions sent to the model. Use {{VARIABLES}} for dynamic content.",
"models.systemPromptInherited": "Inherits global default",
"models.templateVariables": "Variables",
"models.resetToDefault": "Reset",
"update.available": "A new version (v{{version}}) is available.",
"update.viewRelease": "View release notes →",
"update.updateAvailable": "Update available: v{{version}}"
}
+36 -1
View File
@@ -31,6 +31,7 @@
"sidebar.remove": "Eliminar",
"sidebar.workspaceOptions": "Opciones del espacio de trabajo",
"sidebar.closeSidebar": "Cerrar barra lateral",
"sidebar.showMore": "Mostrar más",
"bar.newFile": "Nuevo archivo",
"bar.newTerminal": "Nueva terminal",
@@ -74,6 +75,14 @@
"files.hideHidden": "Ocultar dotfiles",
"files.failedToLoad": "Error al cargar el directorio",
"search.placeholder": "Buscar...",
"search.search": "Buscar",
"search.chats": "Chats",
"search.files": "Archivos",
"search.noResults": "No se encontraron resultados",
"search.recentChats": "Chats recientes",
"search.noRecentChats": "Sin chats recientes",
"quickOpen.searchFiles": "Buscar archivos...",
"quickOpen.noFiles": "No se encontraron archivos",
@@ -208,8 +217,11 @@
"connections.baseUrl": "URL base",
"connections.prefixId": "ID de prefijo",
"connections.models": "Modelos (separados por comas, opcional)",
"connections.modelsHint": "Dejar en blanco para auto-descubrir del proveedor.",
"connections.cancel": "Cancelar",
"connections.add": "Agregar",
"connections.edit": "Editar conexión",
"connections.updated": "Conexión actualizada",
"connections.verify": "Verificar",
"bar.newChat": "Nuevo chat",
@@ -265,5 +277,28 @@
"admin.webCcBaseUrl": "URL base",
"admin.webCcKey": "Clave de API",
"admin.webCcModel": "Modelo",
"admin.webCcHint": "Cualquier endpoint compatible con OpenAI (ej. Perplexity Sonar, proxy LiteLLM)"
"admin.webCcHint": "Cualquier endpoint compatible con OpenAI (ej. Perplexity Sonar, proxy LiteLLM)",
"admin.models": "Modelos",
"models.defaults": "Predeterminados",
"models.noDefaults": "Sin valores predeterminados globales",
"models.noParams": "Sin parámetros",
"models.noModels": "Sin modelos disponibles",
"models.addConnection": "Agrega una conexión primero.",
"models.failedToLoad": "Error al cargar configuración de modelos",
"models.failedToToggle": "Error al alternar modelo",
"models.failedToSave": "Error al guardar",
"models.savedDefaults": "Valores predeterminados globales guardados",
"models.savedParams": "Parámetros guardados para {{name}}",
"models.add": "+ Agregar",
"models.save": "Guardar",
"models.systemPrompt": "Prompt del sistema",
"models.systemPromptHint": "Instrucciones predeterminadas enviadas al modelo. Usa {{VARIABLES}} para contenido dinámico.",
"models.systemPromptInherited": "Hereda el predeterminado global",
"models.templateVariables": "Variables",
"models.resetToDefault": "Restablecer",
"update.available": "Hay una nueva versión (v{{version}}) disponible.",
"update.viewRelease": "Ver notas de la versión →",
"update.updateAvailable": "Actualización disponible: v{{version}}"
}
+34 -21
View File
@@ -1,6 +1,5 @@
{
"app.tagline": "Votre ordinateur, où que vous soyez.",
"auth.createAccountHint": "Créez votre compte pour commencer.",
"auth.signInSystemHint": "Connectez-vous avec votre compte système.",
"auth.setup": "Configuration",
@@ -20,7 +19,6 @@
"auth.minChars": "6 caractères minimum",
"auth.connectionFailed": "Échec de la connexion",
"auth.accountPending": "Compte créé. En attente de l'approbation de l'administrateur.",
"sidebar.workspaces": "Espaces de travail",
"sidebar.addWorkspace": "Ajouter un espace de travail",
"sidebar.collapse": "Réduire",
@@ -31,14 +29,13 @@
"sidebar.remove": "Supprimer",
"sidebar.workspaceOptions": "Options de l'espace de travail",
"sidebar.closeSidebar": "Fermer la barre latérale",
"sidebar.showMore": "Afficher plus",
"bar.newFile": "Nouveau fichier",
"bar.newTerminal": "Nouveau terminal",
"bar.closeTab": "Fermer l'onglet",
"bar.new": "Nouveau...",
"bar.sidebar": "Barre latérale",
"bar.toggleSidebar": "Afficher/masquer la barre latérale",
"files.filter": "Filtrer...",
"files.refresh": "Actualiser",
"files.sort": "Trier",
@@ -73,10 +70,16 @@
"files.showHidden": "Afficher les dotfiles",
"files.hideHidden": "Masquer les dotfiles",
"files.failedToLoad": "Échec du chargement du répertoire",
"search.placeholder": "Rechercher...",
"search.search": "Recherche",
"search.chats": "Conversations",
"search.files": "Fichiers",
"search.noResults": "Aucun résultat trouvé",
"search.recentChats": "Conversations récentes",
"search.noRecentChats": "Aucune conversation récente",
"quickOpen.searchFiles": "Rechercher des fichiers...",
"quickOpen.noFiles": "Aucun fichier trouvé",
"settings.back": "Retour",
"settings.general": "Général",
"settings.account": "Compte",
@@ -84,18 +87,15 @@
"settings.save": "Enregistrer",
"settings.saved": "Enregistré",
"settings.saving": "Enregistrement…",
"general.title": "Général",
"general.theme": "Thème",
"general.light": "Clair",
"general.dark": "Sombre",
"general.system": "Système",
"general.language": "Langue",
"general.tools": "Outils",
"general.autoApproveTools": "Approuver automatiquement tous les appels d’outils",
"general.autoApproveToolsDesc": "Autoriser automatiquement les appels d’outils (écriture, exécution, etc.) sans confirmation",
"account.title": "Compte",
"account.displayName": "Nom d'affichage",
"account.displayNamePlaceholder": "Saisissez un nom d'affichage",
@@ -113,11 +113,9 @@
"account.uploadFailed": "Échec de l'importation",
"account.failedToUpdate": "Échec de la mise à jour",
"account.failedToRemoveAvatar": "Échec de la suppression de l'avatar",
"about.title": "À propos",
"about.license": "Licence",
"about.createdBy": "Créé par Tim Baek, fabriqué sur Terre",
"git.changes": "Modifications",
"git.history": "Historique",
"git.fetch": "Récupérer",
@@ -160,7 +158,6 @@
"git.discard": "Annuler",
"git.copyFilePath": "Copier le chemin du fichier",
"git.copyRelativePath": "Copier le chemin relatif",
"admin.users": "Utilisateurs",
"admin.settings": "Paramètres",
"admin.noUsers": "Aucun utilisateur",
@@ -191,9 +188,7 @@
"admin.delete": "Supprimer",
"admin.usernameRequired": "Nom d'utilisateur requis",
"admin.minCharsPassword": "6 caractères minimum",
"admin.connections": "Connexions",
"connections.loadError": "Échec du chargement des connexions",
"connections.fieldsRequired": "URL de base et clé API requises",
"connections.added": "Connexion ajoutée",
@@ -208,18 +203,18 @@
"connections.baseUrl": "URL de base",
"connections.prefixId": "ID de préfixe",
"connections.models": "Modèles (séparés par des virgules, facultatif)",
"connections.modelsHint": "Laisser vide pour la découverte automatique du fournisseur.",
"connections.cancel": "Annuler",
"connections.add": "Ajouter",
"connections.edit": "Modifier la connexion",
"connections.updated": "Connexion mise à jour",
"connections.verify": "Vérifier",
"bar.newChat": "Nouveau chat",
"home.start": "Démarrer",
"home.openFolder": "Ouvrir un dossier...",
"home.recent": "Récents",
"home.folders": "Dossiers",
"home.chatComingSoon": "Chat (bientôt disponible)",
"directory.cancel": "Annuler",
"directory.open": "Ouvrir « {{name}} »",
"directory.hidden": "Masqués",
@@ -227,24 +222,20 @@
"directory.goBack": "Retour",
"directory.typePath": "Type a path... (Tab to complete)",
"directory.retry": "Réessayer",
"saveDialog.fileNamePlaceholder": "Nom du fichier…",
"saveDialog.emptyFolder": "Dossier vide",
"saveDialog.cancel": "Annuler",
"saveDialog.save": "Enregistrer",
"saveDialog.hidden": "Masqués",
"saveDialog.retry": "Réessayer",
"port.preview": "Aperçu",
"port.via": "via {{name}}",
"system.title": "Système",
"system.cpu": "CPU",
"system.memory": "Mémoire",
"system.disk": "Disque",
"system.cores": "{{count}} cœurs",
"system.process": "PROCESSUS",
"admin.web": "Web",
"admin.webEnabled": "Activer l’accès web",
"admin.webEnabledHint": "L’IA peut rechercher sur le web et récupérer des URL.",
@@ -265,5 +256,27 @@
"admin.webCcBaseUrl": "URL de base",
"admin.webCcKey": "Clé API",
"admin.webCcModel": "Modèle",
"admin.webCcHint": "Tout endpoint compatible OpenAI (ex. Perplexity Sonar, proxy LiteLLM)"
"admin.webCcHint": "Tout endpoint compatible OpenAI (ex. Perplexity Sonar, proxy LiteLLM)",
"admin.models": "Modèles",
"models.defaults": "Valeurs par défaut",
"models.noDefaults": "Aucune valeur par défaut globale",
"models.noParams": "Aucun paramètre",
"models.noModels": "Aucun modèle disponible",
"models.addConnection": "Ajoutez d’abord une connexion.",
"models.failedToLoad": "Échec du chargement de la configuration des modèles",
"models.failedToToggle": "Échec du basculement du modèle",
"models.failedToSave": "Échec de la sauvegarde",
"models.savedDefaults": "Valeurs par défaut globales enregistrées",
"models.savedParams": "Paramètres enregistrés pour {{name}}",
"models.add": "+ Ajouter",
"models.save": "Enregistrer",
"models.systemPrompt": "Prompt système",
"models.systemPromptHint": "Instructions par défaut envoyées au modèle. Utilisez {{VARIABLES}} pour le contenu dynamique.",
"models.systemPromptInherited": "Hérite de la valeur par défaut globale",
"models.templateVariables": "Variables",
"models.resetToDefault": "Réinitialiser",
"update.available": "Une nouvelle version (v{{version}}) est disponible.",
"update.viewRelease": "Voir les notes de version →",
"update.updateAvailable": "Mise à jour disponible : v{{version}}"
}
+34 -21
View File
@@ -1,6 +1,5 @@
{
"app.tagline": "どこからでも、あなたのコンピュータへ。",
"auth.createAccountHint": "アカウントを作成して始めましょう。",
"auth.signInSystemHint": "システムアカウントでサインインしてください。",
"auth.setup": "セットアップ",
@@ -20,7 +19,6 @@
"auth.minChars": "6文字以上",
"auth.connectionFailed": "接続に失敗しました",
"auth.accountPending": "アカウントが作成されました。管理者の承認をお待ちください。",
"sidebar.workspaces": "ワークスペース",
"sidebar.addWorkspace": "ワークスペースを追加",
"sidebar.collapse": "折りたたむ",
@@ -31,14 +29,13 @@
"sidebar.remove": "削除",
"sidebar.workspaceOptions": "ワークスペースオプション",
"sidebar.closeSidebar": "サイドバーを閉じる",
"sidebar.showMore": "もっと見る",
"bar.newFile": "新規ファイル",
"bar.newTerminal": "新規ターミナル",
"bar.closeTab": "タブを閉じる",
"bar.new": "新規...",
"bar.sidebar": "サイドバー",
"bar.toggleSidebar": "サイドバー切り替え",
"files.filter": "フィルター...",
"files.refresh": "更新",
"files.sort": "並び替え",
@@ -73,10 +70,16 @@
"files.showHidden": "ドットファイルを表示",
"files.hideHidden": "ドットファイルを非表示",
"files.failedToLoad": "ディレクトリの読み込みに失敗しました",
"search.placeholder": "検索...",
"search.search": "検索",
"search.chats": "チャット",
"search.files": "ファイル",
"search.noResults": "結果が見つかりません",
"search.recentChats": "最近のチャット",
"search.noRecentChats": "最近のチャットはありません",
"quickOpen.searchFiles": "ファイルを検索...",
"quickOpen.noFiles": "ファイルが見つかりません",
"settings.back": "戻る",
"settings.general": "一般",
"settings.account": "アカウント",
@@ -84,18 +87,15 @@
"settings.save": "保存",
"settings.saved": "保存しました",
"settings.saving": "保存中…",
"general.title": "一般",
"general.theme": "テーマ",
"general.light": "ライト",
"general.dark": "ダーク",
"general.system": "システム",
"general.language": "言語",
"general.tools": "ツール",
"general.autoApproveTools": "すべてのツール呼び出しを自動承認",
"general.autoApproveToolsDesc": "ツール呼び出し(書き込み、実行など)を確認なしで自動的に許可します",
"account.title": "アカウント",
"account.displayName": "表示名",
"account.displayNamePlaceholder": "表示名を入力",
@@ -113,11 +113,9 @@
"account.uploadFailed": "アップロードに失敗しました",
"account.failedToUpdate": "更新に失敗しました",
"account.failedToRemoveAvatar": "アバターの削除に失敗しました",
"about.title": "概要",
"about.license": "ライセンス",
"about.createdBy": "Tim Baek が作成、地球にて",
"git.changes": "変更",
"git.history": "履歴",
"git.fetch": "フェッチ",
@@ -160,7 +158,6 @@
"git.discard": "破棄",
"git.copyFilePath": "ファイルパスをコピー",
"git.copyRelativePath": "相対パスをコピー",
"admin.users": "ユーザー",
"admin.settings": "設定",
"admin.noUsers": "ユーザーがいません",
@@ -191,9 +188,7 @@
"admin.delete": "削除",
"admin.usernameRequired": "ユーザー名を入力してください",
"admin.minCharsPassword": "6文字以上",
"admin.connections": "接続",
"connections.loadError": "接続の読み込みに失敗しました",
"connections.fieldsRequired": "ベースURLとAPIキーが必要です",
"connections.added": "接続を追加しました",
@@ -208,18 +203,18 @@
"connections.baseUrl": "ベースURL",
"connections.prefixId": "プレフィックスID",
"connections.models": "モデル(カンマ区切り、任意)",
"connections.modelsHint": "空白のままでプロバイダーから自動検出します。",
"connections.cancel": "キャンセル",
"connections.add": "追加",
"connections.edit": "接続を編集",
"connections.updated": "接続が更新されました",
"connections.verify": "確認",
"bar.newChat": "新しいチャット",
"home.start": "スタート",
"home.openFolder": "フォルダを開く...",
"home.recent": "最近",
"home.folders": "フォルダ",
"home.chatComingSoon": "チャット(近日公開)",
"directory.cancel": "キャンセル",
"directory.open": "「{{name}}」を開く",
"directory.hidden": "隠しファイル",
@@ -227,24 +222,20 @@
"directory.goBack": "戻る",
"directory.typePath": "Type a path... (Tab to complete)",
"directory.retry": "再試行",
"saveDialog.fileNamePlaceholder": "ファイル名…",
"saveDialog.emptyFolder": "空のフォルダ",
"saveDialog.cancel": "キャンセル",
"saveDialog.save": "保存",
"saveDialog.hidden": "隠しファイル",
"saveDialog.retry": "再試行",
"port.preview": "プレビュー",
"port.via": "{{name}} 経由",
"system.title": "システム",
"system.cpu": "CPU",
"system.memory": "メモリ",
"system.disk": "ディスク",
"system.cores": "{{count}} コア",
"system.process": "プロセス",
"admin.web": "Web",
"admin.webEnabled": "Webアクセスを有効にする",
"admin.webEnabledHint": "AIがWebを検索し、URLを取得できます。",
@@ -265,5 +256,27 @@
"admin.webCcBaseUrl": "ベースURL",
"admin.webCcKey": "APIキー",
"admin.webCcModel": "モデル",
"admin.webCcHint": "OpenAI互換エンドポイント(例: Perplexity Sonar、LiteLLMプロキシ)"
"admin.webCcHint": "OpenAI互換エンドポイント(例: Perplexity Sonar、LiteLLMプロキシ)",
"admin.models": "モデル",
"models.defaults": "デフォルト",
"models.noDefaults": "グローバルデフォルトなし",
"models.noParams": "パラメータなし",
"models.noModels": "利用可能なモデルがありません",
"models.addConnection": "まず接続を追加してください。",
"models.failedToLoad": "モデル設定の読み込みに失敗しました",
"models.failedToToggle": "モデルの切り替えに失敗しました",
"models.failedToSave": "保存に失敗しました",
"models.savedDefaults": "グローバルデフォルトを保存しました",
"models.savedParams": "{{name}} のパラメータを保存しました",
"models.add": "+ 追加",
"models.save": "保存",
"models.systemPrompt": "システムプロンプト",
"models.systemPromptHint": "モデルに送信されるデフォルトの指示。{{VARIABLES}} で動的コンテンツを使用。",
"models.systemPromptInherited": "グローバルデフォルトを継承",
"models.templateVariables": "変数",
"models.resetToDefault": "リセット",
"update.available": "新しいバージョン (v{{version}}) が利用可能です。",
"update.viewRelease": "リリースノートを見る →",
"update.updateAvailable": "アップデート利用可能: v{{version}}"
}
+34 -21
View File
@@ -1,6 +1,5 @@
{
"app.tagline": "어디서든, 당신의 컴퓨터로.",
"auth.createAccountHint": "계정을 만들어 시작하세요.",
"auth.signInSystemHint": "시스템 계정으로 로그인하세요.",
"auth.setup": "설정",
@@ -20,7 +19,6 @@
"auth.minChars": "최소 6자",
"auth.connectionFailed": "연결 실패",
"auth.accountPending": "계정이 생성되었습니다. 관리자 승인을 기다려 주세요.",
"sidebar.workspaces": "워크스페이스",
"sidebar.addWorkspace": "워크스페이스 추가",
"sidebar.collapse": "접기",
@@ -31,14 +29,13 @@
"sidebar.remove": "제거",
"sidebar.workspaceOptions": "워크스페이스 옵션",
"sidebar.closeSidebar": "사이드바 닫기",
"sidebar.showMore": "더 보기",
"bar.newFile": "새 파일",
"bar.newTerminal": "새 터미널",
"bar.closeTab": "탭 닫기",
"bar.new": "새로 만들기...",
"bar.sidebar": "사이드바",
"bar.toggleSidebar": "사이드바 전환",
"files.filter": "필터...",
"files.refresh": "새로고침",
"files.sort": "정렬",
@@ -73,10 +70,16 @@
"files.showHidden": "닷파일 표시",
"files.hideHidden": "닷파일 숨기기",
"files.failedToLoad": "디렉터리 로드 실패",
"search.placeholder": "검색...",
"search.search": "검색",
"search.chats": "채팅",
"search.files": "파일",
"search.noResults": "결과를 찾을 수 없습니다",
"search.recentChats": "최근 채팅",
"search.noRecentChats": "최근 채팅 없음",
"quickOpen.searchFiles": "파일 검색...",
"quickOpen.noFiles": "파일을 찾을 수 없습니다",
"settings.back": "뒤로",
"settings.general": "일반",
"settings.account": "계정",
@@ -84,18 +87,15 @@
"settings.save": "저장",
"settings.saved": "저장됨",
"settings.saving": "저장 중…",
"general.title": "일반",
"general.theme": "테마",
"general.light": "라이트",
"general.dark": "다크",
"general.system": "시스템",
"general.language": "언어",
"general.tools": "도구",
"general.autoApproveTools": "모든 도구 호출 자동 승인",
"general.autoApproveToolsDesc": "도구 호출(쓰기, 실행 등)을 확인 없이 자동으로 허용합니다",
"account.title": "계정",
"account.displayName": "표시 이름",
"account.displayNamePlaceholder": "표시 이름 입력",
@@ -113,11 +113,9 @@
"account.uploadFailed": "업로드 실패",
"account.failedToUpdate": "업데이트 실패",
"account.failedToRemoveAvatar": "아바타 제거 실패",
"about.title": "정보",
"about.license": "라이선스",
"about.createdBy": "Tim Baek 제작, 지구에서 만듦",
"git.changes": "변경사항",
"git.history": "기록",
"git.fetch": "가져오기",
@@ -160,7 +158,6 @@
"git.discard": "폐기",
"git.copyFilePath": "파일 경로 복사",
"git.copyRelativePath": "상대 경로 복사",
"admin.users": "사용자",
"admin.settings": "설정",
"admin.noUsers": "사용자 없음",
@@ -191,9 +188,7 @@
"admin.delete": "삭제",
"admin.usernameRequired": "사용자 이름을 입력하세요",
"admin.minCharsPassword": "최소 6자",
"admin.connections": "연결",
"connections.loadError": "연결을 불러오지 못했습니다",
"connections.fieldsRequired": "기본 URL과 API 키가 필요합니다",
"connections.added": "연결이 추가되었습니다",
@@ -208,18 +203,18 @@
"connections.baseUrl": "기본 URL",
"connections.prefixId": "접두사 ID",
"connections.models": "모델(쉼표로 구분, 선택 사항)",
"connections.modelsHint": "비워두면 프로바이더에서 자동 감지합니다.",
"connections.cancel": "취소",
"connections.add": "추가",
"connections.edit": "연결 편집",
"connections.updated": "연결이 업데이트되었습니다",
"connections.verify": "확인",
"bar.newChat": "새 채팅",
"home.start": "시작",
"home.openFolder": "폴더 열기...",
"home.recent": "최근",
"home.folders": "폴더",
"home.chatComingSoon": "채팅 (출시 예정)",
"directory.cancel": "취소",
"directory.open": "\"{{name}}\" 열기",
"directory.hidden": "숨김 파일",
@@ -227,24 +222,20 @@
"directory.goBack": "뒤로",
"directory.typePath": "Type a path... (Tab to complete)",
"directory.retry": "재시도",
"saveDialog.fileNamePlaceholder": "파일 이름…",
"saveDialog.emptyFolder": "빈 폴더",
"saveDialog.cancel": "취소",
"saveDialog.save": "저장",
"saveDialog.hidden": "숨김 파일",
"saveDialog.retry": "재시도",
"port.preview": "미리보기",
"port.via": "{{name}} 경유",
"system.title": "시스템",
"system.cpu": "CPU",
"system.memory": "메모리",
"system.disk": "디스크",
"system.cores": "{{count}} 코어",
"system.process": "프로세스",
"admin.web": "웹",
"admin.webEnabled": "웹 액세스 활성화",
"admin.webEnabledHint": "AI가 웹을 검색하고 URL을 가져올 수 있습니다.",
@@ -265,5 +256,27 @@
"admin.webCcBaseUrl": "기본 URL",
"admin.webCcKey": "API 키",
"admin.webCcModel": "모델",
"admin.webCcHint": "OpenAI 호환 엔드포인트 사용 (예: Perplexity Sonar, LiteLLM 프록시)"
"admin.webCcHint": "OpenAI 호환 엔드포인트 사용 (예: Perplexity Sonar, LiteLLM 프록시)",
"admin.models": "모델",
"models.defaults": "기본값",
"models.noDefaults": "글로벌 기본값 없음",
"models.noParams": "파라미터 없음",
"models.noModels": "사용 가능한 모델이 없습니다",
"models.addConnection": "먼저 연결을 추가하세요.",
"models.failedToLoad": "모델 설정 로드 실패",
"models.failedToToggle": "모델 전환 실패",
"models.failedToSave": "저장 실패",
"models.savedDefaults": "글로벌 기본값 저장됨",
"models.savedParams": "{{name}} 파라미터 저장됨",
"models.add": "+ 추가",
"models.save": "저장",
"models.systemPrompt": "시스템 프롬프트",
"models.systemPromptHint": "모델에 전송되는 기본 지시. {{VARIABLES}}로 동적 콘텐츠 사용.",
"models.systemPromptInherited": "글로벌 기본값 상속",
"models.templateVariables": "변수",
"models.resetToDefault": "초기화",
"update.available": "새 버전 (v{{version}})이 사용 가능합니다.",
"update.viewRelease": "릴리스 노트 보기 →",
"update.updateAvailable": "업데이트 가능: v{{version}}"
}
+34 -21
View File
@@ -1,6 +1,5 @@
{
"app.tagline": "Seu computador, de qualquer lugar.",
"auth.createAccountHint": "Crie sua conta para começar.",
"auth.signInSystemHint": "Faça login com sua conta do sistema.",
"auth.setup": "Configuração",
@@ -20,7 +19,6 @@
"auth.minChars": "Mínimo de 6 caracteres",
"auth.connectionFailed": "Falha na conexão",
"auth.accountPending": "Conta criada. Aguardando aprovação do administrador.",
"sidebar.workspaces": "Áreas de trabalho",
"sidebar.addWorkspace": "Adicionar área de trabalho",
"sidebar.collapse": "Recolher",
@@ -31,14 +29,13 @@
"sidebar.remove": "Remover",
"sidebar.workspaceOptions": "Opções da área de trabalho",
"sidebar.closeSidebar": "Fechar barra lateral",
"sidebar.showMore": "Mostrar mais",
"bar.newFile": "Novo arquivo",
"bar.newTerminal": "Novo terminal",
"bar.closeTab": "Fechar aba",
"bar.new": "Novo...",
"bar.sidebar": "Barra lateral",
"bar.toggleSidebar": "Alternar barra lateral",
"files.filter": "Filtrar...",
"files.refresh": "Atualizar",
"files.sort": "Ordenar",
@@ -73,10 +70,16 @@
"files.showHidden": "Mostrar dotfiles",
"files.hideHidden": "Ocultar dotfiles",
"files.failedToLoad": "Falha ao carregar diretório",
"search.placeholder": "Pesquisar...",
"search.search": "Pesquisar",
"search.chats": "Conversas",
"search.files": "Arquivos",
"search.noResults": "Nenhum resultado encontrado",
"search.recentChats": "Conversas recentes",
"search.noRecentChats": "Sem conversas recentes",
"quickOpen.searchFiles": "Buscar arquivos...",
"quickOpen.noFiles": "Nenhum arquivo encontrado",
"settings.back": "Voltar",
"settings.general": "Geral",
"settings.account": "Conta",
@@ -84,18 +87,15 @@
"settings.save": "Salvar",
"settings.saved": "Salvo",
"settings.saving": "Salvando…",
"general.title": "Geral",
"general.theme": "Tema",
"general.light": "Claro",
"general.dark": "Escuro",
"general.system": "Sistema",
"general.language": "Idioma",
"general.tools": "Ferramentas",
"general.autoApproveTools": "Aprovar automaticamente todas as chamadas de ferramentas",
"general.autoApproveToolsDesc": "Permitir automaticamente chamadas de ferramentas (escrever, executar etc.) sem confirmação",
"account.title": "Conta",
"account.displayName": "Nome de exibição",
"account.displayNamePlaceholder": "Digite o nome de exibição",
@@ -113,11 +113,9 @@
"account.uploadFailed": "Falha no envio",
"account.failedToUpdate": "Falha ao atualizar",
"account.failedToRemoveAvatar": "Falha ao remover avatar",
"about.title": "Sobre",
"about.license": "Licença",
"about.createdBy": "Criado por Tim Baek, feito na Terra",
"git.changes": "Alterações",
"git.history": "Histórico",
"git.fetch": "Buscar",
@@ -160,7 +158,6 @@
"git.discard": "Descartar",
"git.copyFilePath": "Copiar caminho do arquivo",
"git.copyRelativePath": "Copiar caminho relativo",
"admin.users": "Usuários",
"admin.settings": "Configurações",
"admin.noUsers": "Sem usuários",
@@ -191,9 +188,7 @@
"admin.delete": "Excluir",
"admin.usernameRequired": "Nome de usuário obrigatório",
"admin.minCharsPassword": "Mínimo de 6 caracteres",
"admin.connections": "Conexões",
"connections.loadError": "Falha ao carregar conexões",
"connections.fieldsRequired": "URL base e chave de API obrigatórias",
"connections.added": "Conexão adicionada",
@@ -208,18 +203,18 @@
"connections.baseUrl": "URL base",
"connections.prefixId": "ID de prefixo",
"connections.models": "Modelos (separados por vírgula, opcional)",
"connections.modelsHint": "Deixe em branco para descoberta automática do provedor.",
"connections.cancel": "Cancelar",
"connections.add": "Adicionar",
"connections.edit": "Editar conexão",
"connections.updated": "Conexão atualizada",
"connections.verify": "Verificar",
"bar.newChat": "Novo chat",
"home.start": "Início",
"home.openFolder": "Abrir pasta...",
"home.recent": "Recentes",
"home.folders": "Pastas",
"home.chatComingSoon": "Chat (em breve)",
"directory.cancel": "Cancelar",
"directory.open": "Abrir \"{{name}}\"",
"directory.hidden": "Ocultos",
@@ -227,24 +222,20 @@
"directory.goBack": "Voltar",
"directory.typePath": "Type a path... (Tab to complete)",
"directory.retry": "Tentar novamente",
"saveDialog.fileNamePlaceholder": "Nome do arquivo…",
"saveDialog.emptyFolder": "Pasta vazia",
"saveDialog.cancel": "Cancelar",
"saveDialog.save": "Salvar",
"saveDialog.hidden": "Ocultos",
"saveDialog.retry": "Tentar novamente",
"port.preview": "Visualizar",
"port.via": "via {{name}}",
"system.title": "Sistema",
"system.cpu": "CPU",
"system.memory": "Memória",
"system.disk": "Disco",
"system.cores": "{{count}} núcleos",
"system.process": "PROCESSO",
"admin.web": "Web",
"admin.webEnabled": "Ativar acesso à web",
"admin.webEnabledHint": "A IA pode pesquisar na web e buscar URLs.",
@@ -265,5 +256,27 @@
"admin.webCcBaseUrl": "URL base",
"admin.webCcKey": "Chave de API",
"admin.webCcModel": "Modelo",
"admin.webCcHint": "Qualquer endpoint compatível com OpenAI (ex. Perplexity Sonar, proxy LiteLLM)"
"admin.webCcHint": "Qualquer endpoint compatível com OpenAI (ex. Perplexity Sonar, proxy LiteLLM)",
"admin.models": "Modelos",
"models.defaults": "Padrões",
"models.noDefaults": "Sem padrões globais",
"models.noParams": "Sem parâmetros",
"models.noModels": "Nenhum modelo disponível",
"models.addConnection": "Adicione uma conexão primeiro.",
"models.failedToLoad": "Falha ao carregar configuração de modelos",
"models.failedToToggle": "Falha ao alternar modelo",
"models.failedToSave": "Falha ao salvar",
"models.savedDefaults": "Padrões globais salvos",
"models.savedParams": "Parâmetros salvos para {{name}}",
"models.add": "+ Adicionar",
"models.save": "Salvar",
"models.systemPrompt": "Prompt do sistema",
"models.systemPromptHint": "Instruções padrão enviadas ao modelo. Use {{VARIABLES}} para conteúdo dinâmico.",
"models.systemPromptInherited": "Herda o padrão global",
"models.templateVariables": "Variáveis",
"models.resetToDefault": "Redefinir",
"update.available": "Uma nova versão (v{{version}}) está disponível.",
"update.viewRelease": "Ver notas da versão →",
"update.updateAvailable": "Atualização disponível: v{{version}}"
}
+34 -21
View File
@@ -1,6 +1,5 @@
{
"app.tagline": "Ваш компьютер, откуда угодно.",
"auth.createAccountHint": "Создайте аккаунт, чтобы начать.",
"auth.signInSystemHint": "Войдите с помощью системной учётной записи.",
"auth.setup": "Настройка",
@@ -20,7 +19,6 @@
"auth.minChars": "Минимум 6 символов",
"auth.connectionFailed": "Ошибка подключения",
"auth.accountPending": "Аккаунт создан. Ожидайте одобрения администратора.",
"sidebar.workspaces": "Рабочие области",
"sidebar.addWorkspace": "Добавить рабочую область",
"sidebar.collapse": "Свернуть",
@@ -31,14 +29,13 @@
"sidebar.remove": "Удалить",
"sidebar.workspaceOptions": "Параметры рабочей области",
"sidebar.closeSidebar": "Закрыть боковую панель",
"sidebar.showMore": "Показать ещё",
"bar.newFile": "Новый файл",
"bar.newTerminal": "Новый терминал",
"bar.closeTab": "Закрыть вкладку",
"bar.new": "Создать...",
"bar.sidebar": "Боковая панель",
"bar.toggleSidebar": "Переключить боковую панель",
"files.filter": "Фильтр...",
"files.refresh": "Обновить",
"files.sort": "Сортировка",
@@ -73,10 +70,16 @@
"files.showHidden": "Показать dotfiles",
"files.hideHidden": "Скрыть dotfiles",
"files.failedToLoad": "Не удалось загрузить каталог",
"search.placeholder": "Поиск...",
"search.search": "Поиск",
"search.chats": "Чаты",
"search.files": "Файлы",
"search.noResults": "Результаты не найдены",
"search.recentChats": "Недавние чаты",
"search.noRecentChats": "Нет недавних чатов",
"quickOpen.searchFiles": "Поиск файлов...",
"quickOpen.noFiles": "Файлы не найдены",
"settings.back": "Назад",
"settings.general": "Основные",
"settings.account": "Аккаунт",
@@ -84,18 +87,15 @@
"settings.save": "Сохранить",
"settings.saved": "Сохранено",
"settings.saving": "Сохранение…",
"general.title": "Основные",
"general.theme": "Тема",
"general.light": "Светлая",
"general.dark": "Тёмная",
"general.system": "Системная",
"general.language": "Язык",
"general.tools": "Инструменты",
"general.autoApproveTools": "Автоматически одобрять все вызовы инструментов",
"general.autoApproveToolsDesc": "Автоматически разрешать вызовы инструментов (запись, запуск и т. д.) без подтверждения",
"account.title": "Аккаунт",
"account.displayName": "Отображаемое имя",
"account.displayNamePlaceholder": "Введите отображаемое имя",
@@ -113,11 +113,9 @@
"account.uploadFailed": "Ошибка загрузки",
"account.failedToUpdate": "Ошибка обновления",
"account.failedToRemoveAvatar": "Не удалось удалить аватар",
"about.title": "О программе",
"about.license": "Лицензия",
"about.createdBy": "Создано Tim Baek, сделано на Земле",
"git.changes": "Изменения",
"git.history": "История",
"git.fetch": "Получить",
@@ -160,7 +158,6 @@
"git.discard": "Отменить",
"git.copyFilePath": "Копировать путь к файлу",
"git.copyRelativePath": "Копировать относительный путь",
"admin.users": "Пользователи",
"admin.settings": "Настройки",
"admin.noUsers": "Нет пользователей",
@@ -191,9 +188,7 @@
"admin.delete": "Удалить",
"admin.usernameRequired": "Введите имя пользователя",
"admin.minCharsPassword": "Минимум 6 символов",
"admin.connections": "Подключения",
"connections.loadError": "Не удалось загрузить подключения",
"connections.fieldsRequired": "Требуются базовый URL и API-ключ",
"connections.added": "Подключение добавлено",
@@ -208,18 +203,18 @@
"connections.baseUrl": "Базовый URL",
"connections.prefixId": "ID префикса",
"connections.models": "Модели (через запятую, необязательно)",
"connections.modelsHint": "Оставьте пустым для автообнаружения от провайдера.",
"connections.cancel": "Отмена",
"connections.add": "Добавить",
"connections.edit": "Редактировать подключение",
"connections.updated": "Подключение обновлено",
"connections.verify": "Проверить",
"bar.newChat": "Новый чат",
"home.start": "Начало",
"home.openFolder": "Открыть папку...",
"home.recent": "Недавние",
"home.folders": "Папки",
"home.chatComingSoon": "Чат (скоро)",
"directory.cancel": "Отмена",
"directory.open": "Открыть \"{{name}}\"",
"directory.hidden": "Скрытые",
@@ -227,24 +222,20 @@
"directory.goBack": "Назад",
"directory.typePath": "Type a path... (Tab to complete)",
"directory.retry": "Повторить",
"saveDialog.fileNamePlaceholder": "Имя файла…",
"saveDialog.emptyFolder": "Пустая папка",
"saveDialog.cancel": "Отмена",
"saveDialog.save": "Сохранить",
"saveDialog.hidden": "Скрытые",
"saveDialog.retry": "Повторить",
"port.preview": "Предпросмотр",
"port.via": "через {{name}}",
"system.title": "Система",
"system.cpu": "ЦП",
"system.memory": "Память",
"system.disk": "Диск",
"system.cores": "{{count}} ядер",
"system.process": "ПРОЦЕСС",
"admin.web": "Веб",
"admin.webEnabled": "Включить доступ к вебу",
"admin.webEnabledHint": "ИИ может искать в вебе и получать URL-адреса.",
@@ -265,5 +256,27 @@
"admin.webCcBaseUrl": "Базовый URL",
"admin.webCcKey": "API-ключ",
"admin.webCcModel": "Модель",
"admin.webCcHint": "Любой OpenAI-совместимый эндпоинт (напр. Perplexity Sonar, прокси LiteLLM)"
"admin.webCcHint": "Любой OpenAI-совместимый эндпоинт (напр. Perplexity Sonar, прокси LiteLLM)",
"admin.models": "Модели",
"models.defaults": "Значения по умолчанию",
"models.noDefaults": "Нет глобальных значений по умолчанию",
"models.noParams": "Нет параметров",
"models.noModels": "Нет доступных моделей",
"models.addConnection": "Сначала добавьте подключение.",
"models.failedToLoad": "Не удалось загрузить конфигурацию моделей",
"models.failedToToggle": "Не удалось переключить модель",
"models.failedToSave": "Не удалось сохранить",
"models.savedDefaults": "Глобальные значения по умолчанию сохранены",
"models.savedParams": "Параметры для {{name}} сохранены",
"models.add": "+ Добавить",
"models.save": "Сохранить",
"models.systemPrompt": "Системный промпт",
"models.systemPromptHint": "Инструкции по умолчанию для модели. Используйте {{VARIABLES}} для динамического содержимого.",
"models.systemPromptInherited": "Наследует глобальные настройки",
"models.templateVariables": "Переменные",
"models.resetToDefault": "Сбросить",
"update.available": "Доступна новая версия (v{{version}}).",
"update.viewRelease": "Посмотреть заметки о выпуске →",
"update.updateAvailable": "Доступно обновление: v{{version}}"
}
+34 -21
View File
@@ -1,6 +1,5 @@
{
"app.tagline": "随时随地,掌控你的电脑。",
"auth.createAccountHint": "创建账户以开始使用。",
"auth.signInSystemHint": "使用系统账户登录。",
"auth.setup": "初始设置",
@@ -20,7 +19,6 @@
"auth.minChars": "至少6个字符",
"auth.connectionFailed": "连接失败",
"auth.accountPending": "账户已创建,等待管理员审批。",
"sidebar.workspaces": "工作区",
"sidebar.addWorkspace": "添加工作区",
"sidebar.collapse": "收起",
@@ -31,14 +29,13 @@
"sidebar.remove": "移除",
"sidebar.workspaceOptions": "工作区选项",
"sidebar.closeSidebar": "关闭侧边栏",
"sidebar.showMore": "显示更多",
"bar.newFile": "新建文件",
"bar.newTerminal": "新建终端",
"bar.closeTab": "关闭标签",
"bar.new": "新建...",
"bar.sidebar": "侧边栏",
"bar.toggleSidebar": "切换侧边栏",
"files.filter": "筛选...",
"files.refresh": "刷新",
"files.sort": "排序",
@@ -73,10 +70,16 @@
"files.showHidden": "显示点文件",
"files.hideHidden": "隐藏点文件",
"files.failedToLoad": "加载目录失败",
"search.placeholder": "搜索...",
"search.search": "搜索",
"search.chats": "对话",
"search.files": "文件",
"search.noResults": "未找到结果",
"search.recentChats": "最近对话",
"search.noRecentChats": "没有最近对话",
"quickOpen.searchFiles": "搜索文件...",
"quickOpen.noFiles": "未找到文件",
"settings.back": "返回",
"settings.general": "通用",
"settings.account": "账户",
@@ -84,18 +87,15 @@
"settings.save": "保存",
"settings.saved": "已保存",
"settings.saving": "保存中…",
"general.title": "通用",
"general.theme": "主题",
"general.light": "浅色",
"general.dark": "深色",
"general.system": "跟随系统",
"general.language": "语言",
"general.tools": "工具",
"general.autoApproveTools": "自动批准所有工具调用",
"general.autoApproveToolsDesc": "自动允许工具调用(写入、运行等),无需确认",
"account.title": "账户",
"account.displayName": "显示名称",
"account.displayNamePlaceholder": "输入显示名称",
@@ -113,11 +113,9 @@
"account.uploadFailed": "上传失败",
"account.failedToUpdate": "更新失败",
"account.failedToRemoveAvatar": "移除头像失败",
"about.title": "关于",
"about.license": "许可证",
"about.createdBy": "由 Tim Baek 创建,诞生于地球",
"git.changes": "更改",
"git.history": "历史",
"git.fetch": "拉取",
@@ -160,7 +158,6 @@
"git.discard": "丢弃",
"git.copyFilePath": "复制文件路径",
"git.copyRelativePath": "复制相对路径",
"admin.users": "用户",
"admin.settings": "设置",
"admin.noUsers": "暂无用户",
@@ -191,9 +188,7 @@
"admin.delete": "删除",
"admin.usernameRequired": "请输入用户名",
"admin.minCharsPassword": "至少6个字符",
"admin.connections": "连接",
"connections.loadError": "无法加载连接",
"connections.fieldsRequired": "需要基础 URL 和 API 密钥",
"connections.added": "连接已添加",
@@ -208,18 +203,18 @@
"connections.baseUrl": "基础 URL",
"connections.prefixId": "前缀 ID",
"connections.models": "模型(逗号分隔,可选)",
"connections.modelsHint": "留空以从提供商自动发现。",
"connections.cancel": "取消",
"connections.add": "添加",
"connections.edit": "编辑连接",
"connections.updated": "连接已更新",
"connections.verify": "验证",
"bar.newChat": "新建聊天",
"home.start": "开始",
"home.openFolder": "打开文件夹...",
"home.recent": "最近",
"home.folders": "文件夹",
"home.chatComingSoon": "聊天(即将推出)",
"directory.cancel": "取消",
"directory.open": "打开「{{name}}」",
"directory.hidden": "隐藏文件",
@@ -227,24 +222,20 @@
"directory.goBack": "返回",
"directory.typePath": "Type a path... (Tab to complete)",
"directory.retry": "重试",
"saveDialog.fileNamePlaceholder": "文件名…",
"saveDialog.emptyFolder": "空文件夹",
"saveDialog.cancel": "取消",
"saveDialog.save": "保存",
"saveDialog.hidden": "隐藏文件",
"saveDialog.retry": "重试",
"port.preview": "预览",
"port.via": "来自 {{name}}",
"system.title": "系统",
"system.cpu": "CPU",
"system.memory": "内存",
"system.disk": "磁盘",
"system.cores": "{{count}} 核",
"system.process": "进程",
"admin.web": "网页",
"admin.webEnabled": "启用网页访问",
"admin.webEnabledHint": "AI 可以搜索网页并获取 URL。",
@@ -265,5 +256,27 @@
"admin.webCcBaseUrl": "基础 URL",
"admin.webCcKey": "API 密钥",
"admin.webCcModel": "模型",
"admin.webCcHint": "使用任何 OpenAI 兼容端点(如 Perplexity Sonar、LiteLLM 代理)"
"admin.webCcHint": "使用任何 OpenAI 兼容端点(如 Perplexity Sonar、LiteLLM 代理)",
"admin.models": "模型",
"models.defaults": "默认值",
"models.noDefaults": "没有全局默认值",
"models.noParams": "没有参数",
"models.noModels": "没有可用模型",
"models.addConnection": "请先添加连接。",
"models.failedToLoad": "加载模型配置失败",
"models.failedToToggle": "切换模型失败",
"models.failedToSave": "保存失败",
"models.savedDefaults": "全局默认值已保存",
"models.savedParams": "{{name}} 的参数已保存",
"models.add": "+ 添加",
"models.save": "保存",
"models.systemPrompt": "系统提示词",
"models.systemPromptHint": "发送给模型的默认指令。使用 {{VARIABLES}} 插入动态内容。",
"models.systemPromptInherited": "继承全局默认值",
"models.templateVariables": "变量",
"models.resetToDefault": "重置",
"update.available": "新版本 (v{{version}}) 可用。",
"update.viewRelease": "查看发行说明 →",
"update.updateAvailable": "有可用更新: v{{version}}"
}
+12 -22
View File
@@ -1,6 +1,5 @@
{
"app.tagline": "隨時隨地,掌控你的電腦。",
"auth.createAccountHint": "建立帳號以開始使用。",
"auth.signInSystemHint": "使用系統帳號登入。",
"auth.setup": "初始設定",
@@ -20,7 +19,6 @@
"auth.minChars": "至少6個字元",
"auth.connectionFailed": "連線失敗",
"auth.accountPending": "帳號已建立,等待管理員核准。",
"sidebar.workspaces": "工作區",
"sidebar.addWorkspace": "新增工作區",
"sidebar.collapse": "收合",
@@ -31,14 +29,12 @@
"sidebar.remove": "移除",
"sidebar.workspaceOptions": "工作區選項",
"sidebar.closeSidebar": "關閉側邊欄",
"bar.newFile": "新增檔案",
"bar.newTerminal": "新增終端機",
"bar.closeTab": "關閉分頁",
"bar.new": "新增...",
"bar.sidebar": "側邊欄",
"bar.toggleSidebar": "切換側邊欄",
"files.filter": "篩選...",
"files.refresh": "重新整理",
"files.sort": "排序",
@@ -73,10 +69,8 @@
"files.showHidden": "顯示點檔",
"files.hideHidden": "隱藏點檔",
"files.failedToLoad": "載入目錄失敗",
"quickOpen.searchFiles": "搜尋檔案...",
"quickOpen.noFiles": "找不到檔案",
"settings.back": "返回",
"settings.general": "一般",
"settings.account": "帳號",
@@ -84,18 +78,15 @@
"settings.save": "儲存",
"settings.saved": "已儲存",
"settings.saving": "儲存中…",
"general.title": "一般",
"general.theme": "佈景主題",
"general.light": "淺色",
"general.dark": "深色",
"general.system": "跟隨系統",
"general.language": "語言",
"general.tools": "工具",
"general.autoApproveTools": "自動核准所有工具呼叫",
"general.autoApproveToolsDesc": "自動允許工具呼叫(寫入、執行等),無需確認",
"account.title": "帳號",
"account.displayName": "顯示名稱",
"account.displayNamePlaceholder": "輸入顯示名稱",
@@ -113,11 +104,9 @@
"account.uploadFailed": "上傳失敗",
"account.failedToUpdate": "更新失敗",
"account.failedToRemoveAvatar": "移除頭像失敗",
"about.title": "關於",
"about.license": "授權條款",
"about.createdBy": "由 Tim Baek 創建,誕生於地球",
"git.changes": "變更",
"git.history": "歷史",
"git.fetch": "擷取",
@@ -160,7 +149,6 @@
"git.discard": "捨棄",
"git.copyFilePath": "複製檔案路徑",
"git.copyRelativePath": "複製相對路徑",
"admin.users": "使用者",
"admin.settings": "設定",
"admin.noUsers": "尚無使用者",
@@ -191,9 +179,7 @@
"admin.delete": "刪除",
"admin.usernameRequired": "請輸入使用者名稱",
"admin.minCharsPassword": "至少6個字元",
"admin.connections": "連線",
"connections.loadError": "無法載入連線",
"connections.fieldsRequired": "需要基礎 URL 和 API 金鑰",
"connections.added": "已新增連線",
@@ -211,15 +197,12 @@
"connections.cancel": "取消",
"connections.add": "新增",
"connections.verify": "驗證",
"bar.newChat": "新增聊天",
"home.start": "開始",
"home.openFolder": "開啟資料夾...",
"home.recent": "最近",
"home.folders": "資料夾",
"home.chatComingSoon": "聊天(即將推出)",
"directory.cancel": "取消",
"directory.open": "開啟「{{name}}」",
"directory.hidden": "隱藏檔案",
@@ -227,24 +210,20 @@
"directory.goBack": "返回",
"directory.typePath": "Type a path... (Tab to complete)",
"directory.retry": "重試",
"saveDialog.fileNamePlaceholder": "檔案名稱…",
"saveDialog.emptyFolder": "空資料夾",
"saveDialog.cancel": "取消",
"saveDialog.save": "儲存",
"saveDialog.hidden": "隱藏檔案",
"saveDialog.retry": "重試",
"port.preview": "預覽",
"port.via": "來自 {{name}}",
"system.title": "系統",
"system.cpu": "CPU",
"system.memory": "記憶體",
"system.disk": "磁碟",
"system.cores": "{{count}} 核心",
"system.process": "處理程序",
"admin.web": "網頁",
"admin.webEnabled": "啟用網頁存取",
"admin.webEnabledHint": "AI 可以搜尋網頁並擷取 URL。",
@@ -265,5 +244,16 @@
"admin.webCcBaseUrl": "基礎 URL",
"admin.webCcKey": "API 金鑰",
"admin.webCcModel": "模型",
"admin.webCcHint": "使用任何 OpenAI 相容端點(如 Perplexity Sonar、LiteLLM 代理)"
"admin.webCcHint": "使用任何 OpenAI 相容端點(如 Perplexity Sonar、LiteLLM 代理)",
"admin.models": "Models",
"models.defaults": "Defaults",
"models.noModels": "No models available",
"models.failedToLoad": "Failed to load model config",
"models.failedToToggle": "Failed to toggle model",
"models.failedToSave": "Failed to save",
"models.systemPrompt": "System Prompt",
"models.systemPromptHint": "Default instructions sent to the model. Use {{VARIABLES}} for dynamic content.",
"models.systemPromptInherited": "Inherits global default",
"models.templateVariables": "Variables",
"models.resetToDefault": "Reset"
}
+22 -1
View File
@@ -77,6 +77,7 @@ export interface UserPreferences {
version?: string; // last seen app version for changelog
selectedModelId?: string; // last selected chat model, synced across browsers
requestParams?: Record<string, unknown>; // arbitrary params merged into API request body
showUpdateToast?: boolean; // show version update notifications (default true)
}
export type Theme = 'dark' | 'light' | 'system';
@@ -139,7 +140,22 @@ export const planMode = writable(false);
export const requestParams = writable<Record<string, unknown>>({});
export const appVersion = writable('');
export const lastSeenVersion = writable('');
export const latestVersion = writable('');
export const updateAvailable = derived(
[appVersion, latestVersion],
([$app, $latest]) => {
if (!$app || !$latest || $app === 'dev' || $app === '0.0.0') return false;
return (
$app.localeCompare($latest, undefined, {
numeric: true,
sensitivity: 'case',
caseFirst: 'upper'
}) < 0
);
}
);
export const showChangelog = writable(false);
export const showUpdateToastPref = writable(true);
export const showSearch = writable(false);
/** @deprecated Use toolApprovalMode */
export const autoApproveTools = {
@@ -288,7 +304,8 @@ function persistPreferences(): void {
keybindings: get(keybindings),
version: get(lastSeenVersion),
selectedModelId: get(selectedModelId) || undefined,
requestParams: Object.keys(get(requestParams)).length ? get(requestParams) : undefined
requestParams: Object.keys(get(requestParams)).length ? get(requestParams) : undefined,
showUpdateToast: get(showUpdateToastPref)
};
savePreferences(prefs as unknown as Record<string, unknown>).catch(() => {});
}, 300);
@@ -331,6 +348,9 @@ function subscribeForPersistence() {
selectedModelId.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
showUpdateToastPref.subscribe(() => {
if (get(stateLoaded)) persistPreferences();
});
i18next.on('languageChanged', () => {
if (get(stateLoaded)) persistPreferences();
});
@@ -358,6 +378,7 @@ export async function loadPreferences(): Promise<void> {
if (prefs.version) lastSeenVersion.set(prefs.version as string);
if (prefs.selectedModelId) selectedModelId.set(prefs.selectedModelId as string);
if (prefs.requestParams) requestParams.set(prefs.requestParams as Record<string, unknown>);
if (prefs.showUpdateToast !== undefined) showUpdateToastPref.set(prefs.showUpdateToast as boolean);
} catch {
// First run, no preferences yet
}
+50 -3
View File
@@ -13,6 +13,7 @@
import SettingsModal from '$lib/components/SettingsModal.svelte';
import AuthScreen from '$lib/components/AuthScreen.svelte';
import ChangelogModal from '$lib/components/ChangelogModal.svelte';
import UpdateToast from '$lib/components/UpdateToast.svelte';
import { Toaster } from 'svelte-sonner';
import {
activeTab,
@@ -26,20 +27,25 @@
closeGroup,
appVersion,
lastSeenVersion,
latestVersion,
updateAvailable,
showChangelog,
showSearch
showSearch,
showUpdateToastPref
} from '$lib/stores';
import { matchKeybinding, executeAction } from '$lib/stores/keybindings';
import { systemEvents } from '$lib/stores/systemEvents.svelte';
import { socketStore } from '$lib/stores/socket.svelte';
import { setSession, clearSession } from '$lib/session';
import { setSession, clearSession, session } from '$lib/session';
import { getSession, getConfig } from '$lib/apis/auth';
import { fetchJSON } from '$lib/apis';
import { gitStatusStore } from '$lib/stores/gitStatus.svelte';
import { t } from '$lib/i18n';
import { refreshChatState, bindGlobalChatListener } from '$lib/stores/chat';
let { children } = $props();
let showSettings = $state(false);
let showUpdateToast = $state(false);
// Auth state
type AuthState = 'checking' | 'needs_setup' | 'needs_login' | 'authenticated';
@@ -141,6 +147,9 @@
authState = 'authenticated';
initState();
refreshChatState();
// Check for version updates (admin only, after session is set)
checkForUpdates();
} else {
const cfg = await getConfig();
authMode = cfg.auth_mode || 'password';
@@ -174,6 +183,30 @@
authState = 'needs_login';
}
async function checkForUpdates() {
try {
const sess = $session;
if (!sess || sess.role !== 'admin') return;
if (!$showUpdateToastPref) return;
// 24-hour dismiss cooldown
const dismissed = localStorage.getItem('dismissedUpdateToast');
if (dismissed) {
const elapsed = Date.now() - Number(dismissed);
if (elapsed < 24 * 60 * 60 * 1000) return;
}
const data = await fetchJSON<{ current: string; latest: string }>('/api/version/updates');
latestVersion.set(data.latest);
// Show toast if update is available (reactive via $updateAvailable)
if (data.current !== data.latest) {
showUpdateToast = true;
}
} catch {
// Silently ignore (non-admin, network error, etc.)
}
}
function handleKeydown(e: KeyboardEvent) {
const action = matchKeybinding(e);
if (!action) return;
@@ -229,7 +262,13 @@
href="https://fonts.googleapis.com/css2?family=Inter:wght@300..700&family=JetBrains+Mono:wght@400;500&display=swap"
rel="stylesheet"
/>
<title>{$currentWorkspace ? `${$currentWorkspace.name} / cptr` : 'cptr'}</title>
<title>{$activeTab && $activeTab.type !== 'files'
? $currentWorkspace
? `${$activeTab.label} / ${$currentWorkspace.name} / cptr`
: `${$activeTab.label} / cptr`
: $currentWorkspace
? `${$currentWorkspace.name} / cptr`
: 'cptr'}</title>
<meta name="description" content={$t('app.tagline')} />
</svelte:head>
@@ -280,6 +319,14 @@
<SettingsModal onclose={() => (showSettings = false)} />
{/if}
<ChangelogModal />
{#if $updateAvailable && showUpdateToast}
<UpdateToast
onclose={() => {
showUpdateToast = false;
localStorage.setItem('dismissedUpdateToast', Date.now().toString());
}}
/>
{/if}
{:else}
<div class="flex items-center justify-center h-dvh bg-white dark:bg-black">
<Spinner size={20} />
+2
View File
@@ -9,6 +9,7 @@ from cptr.routers.files import router as files_router
from cptr.routers.git import router as git_router
from cptr.routers.proxy import router as proxy_router
from cptr.routers.search import router as search_router
from cptr.routers.skills import router as skills_router
from cptr.routers.state import router as state_router
from cptr.routers.terminal import router as terminal_router
from cptr.routers.workspace import router as workspace_router
@@ -23,6 +24,7 @@ __all__ = [
"git_router",
"proxy_router",
"search_router",
"skills_router",
"state_router",
"terminal_router",
"workspace_router",
+3
View File
@@ -223,6 +223,9 @@ async def update_connection(conn_id: str, body: UpdateConnectionRequest, request
conn["enabled"] = body.enabled
if body.models is not None:
conn.setdefault("data", {})["models"] = body.models
elif "models" in body.model_fields_set:
# Explicit null → clear whitelist, enable auto-discovery
conn.get("data", {}).pop("models", None)
await _save_connections(connections)
invalidate_model_cache(request.app.state)
+26 -5
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
import logging
from pathlib import Path
from typing import List, Optional
@@ -14,6 +15,8 @@ from cptr.models import Chat, ChatMessage, Config
from cptr.utils.config import check_access, now_ms, _get_jwt_secret
from cptr.utils.crypto import decrypt_key
log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/chats", tags=["chats"])
COOKIE_NAME = "cptr_session"
@@ -228,7 +231,14 @@ async def _fetch_provider_models(conn: dict) -> list[str]:
)
if r.status_code == 200:
data = r.json()
return [m["id"] for m in data.get("data", [])]
models = [m["id"] for m in data.get("data", [])]
log.info("Auto-discovered %d models from %s", len(models), url)
return models
else:
log.warning(
"Model auto-discovery failed for %s: HTTP %d",
url, r.status_code,
)
elif provider == "openai":
url = (base_url or "https://api.openai.com/v1") + "/models"
@@ -241,10 +251,20 @@ async def _fetch_provider_models(conn: dict) -> list[str]:
)
if r.status_code == 200:
data = r.json()
return [m["id"] for m in data.get("data", [])]
models = [m["id"] for m in data.get("data", [])]
log.info("Auto-discovered %d models from %s", len(models), url)
return models
else:
log.warning(
"Model auto-discovery failed for %s: HTTP %d",
url, r.status_code,
)
else:
log.warning("Unknown provider '%s', skipping model auto-discovery", provider)
except Exception:
pass
log.exception("Model auto-discovery error for connection %s", conn.get("id", "?"))
return []
@@ -492,8 +512,10 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ
# Execute the tool
from cptr.utils.tools import execute_tool
model_id = msg.model or ""
result = await execute_tool(
call["name"], call.get("arguments", {}), chat.meta.get("workspace", "")
call["name"], call.get("arguments", {}),
{"workspace": chat.meta.get("workspace", ""), "user_id": user_id, "model_id": model_id},
)
call["status"] = "completed"
output.append(
@@ -520,7 +542,6 @@ 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
model_id = msg.model or ""
connection, bare_model = await _resolve_connection(model_id, request.app.state)
workspace = chat.meta.get("workspace", "") if chat.meta else ""
+39
View File
@@ -0,0 +1,39 @@
"""Skills API: lightweight read-only endpoint for the $ mention picker."""
from __future__ import annotations
import asyncio
from typing import Optional
from fastapi import APIRouter, Query
from pydantic import BaseModel
router = APIRouter(prefix="/api/skills", tags=["skills"])
class SkillResponse(BaseModel):
name: str
description: str
location: str
source: str # "workspace" or "global"
license: Optional[str] = None
compatibility: Optional[str] = None
@router.get("", response_model=list[SkillResponse])
async def list_skills(workspace: str = Query(..., description="Workspace path")):
"""List available skills (frontmatter only) for the $ mention picker."""
from cptr.utils.skills import discover_skills
skills = await asyncio.to_thread(discover_skills, workspace)
return [
SkillResponse(
name=s.name,
description=s.description,
location=s.location,
source=s.source,
license=s.license,
compatibility=s.compatibility,
)
for s in skills
]
+1 -1
View File
@@ -140,7 +140,7 @@ async def execute_automation(automation, webhook_payload: str | None = None) ->
meta={
"workspace": workspace,
"automation_id": automation.id,
"params": {},
"params": {"tool_approval_mode": "full"},
},
created_at=now_ms(),
)
+153 -24
View File
@@ -13,6 +13,7 @@ from pathlib import Path
from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_MAX_CHARS
from cptr.utils.context import should_compact
from cptr.utils.skills import discover_skills, load_skill, build_catalog_xml, format_skill_content
from cptr.utils.summarize import summarize_messages
from cptr.models import Chat, ChatMessage, Config
from cptr.socket.main import emit_to_user
@@ -305,36 +306,131 @@ def _load_instruction_files(workspace: str, max_bytes: int = 32_000) -> str:
return "\n\n".join(parts)
def _load_system_prompt(workspace: str) -> str:
"""Load system prompt: .cptr/system.md > default. Appends instruction files + file tree."""
ws_prompt = Path(workspace) / ".cptr" / "system.md"
if ws_prompt.is_file():
base = ws_prompt.read_text(errors="replace").strip()
else:
base = (
"You are a helpful coding assistant. "
"You have access to tools to read, search, and modify files in the workspace. "
"Use them to help the user with their coding tasks.\n\n"
"For complex tasks, create an implementation plan first using "
"create_artifact, then wait for approval before coding."
)
# ── Template engine ─────────────────────────────────────────
# Load MEMORY.md / AGENTS.md / CLAUDE.md from workspace root
import platform
import re
from datetime import date
_TEMPLATE_RE = re.compile(r"\{\{(\w+)\}\}")
DEFAULT_SYSTEM_PROMPT = (
"You are a helpful coding assistant. "
"You have access to tools to read, search, and modify files in the workspace. "
"Use them to help the user with their coding tasks.\n\n"
"For complex tasks, create an implementation plan first using "
"create_artifact, then wait for approval before coding."
"\n\n{{INSTRUCTIONS}}"
"\n\n{{SKILLS}}"
"\n\nWorkspace: {{WORKSPACE_NAME}}"
"\nFiles:\n{{FILE_TREE}}"
)
def _render_template(template: str, variables: dict[str, str]) -> str:
"""Render {{VARIABLE}} placeholders in a template string.
- Known variables are substituted with their values.
- Unrecognized {{...}} tokens are left as-is.
- Cleans up excess blank lines left by empty variable substitutions.
"""
def _replace(match: re.Match) -> str:
key = match.group(1)
if key in variables:
return variables[key]
return match.group(0) # leave unrecognized tokens as-is
result = _TEMPLATE_RE.sub(_replace, template)
# Clean up triple+ blank lines left by empty substitutions
result = re.sub(r"\n{3,}", "\n\n", result)
return result.strip()
def _build_template_variables(workspace: str, model: str = "") -> dict[str, str]:
"""Build the dict of template variable values for the current context."""
ws_path = Path(workspace)
# Build instructions content
instructions = _load_instruction_files(workspace)
if instructions:
base += f"\n\n<instructions>\n{instructions}\n</instructions>"
base += (
instructions_block = (
f"<instructions>\n{instructions}\n</instructions>"
"\n\nThe above <instructions> were loaded from instruction files in the workspace root. "
"These files persist across sessions. "
"You can update them with your file tools to save learnings, decisions, or "
"project conventions for future sessions."
)
else:
instructions_block = ""
tree = _get_file_tree(workspace)
if tree:
base += f"\n\nWorkspace: {Path(workspace).name}\nFiles:\n{tree}"
# Build skills catalog
skills = discover_skills(workspace)
skills_block = build_catalog_xml(skills)
return base
return {
"WORKSPACE_NAME": ws_path.name if ws_path.is_dir() else "",
"WORKSPACE_PATH": str(ws_path),
"FILE_TREE": _get_file_tree(workspace),
"INSTRUCTIONS": instructions_block,
"SKILLS": skills_block,
"OS": platform.system().replace("Darwin", "macOS"),
"DATE": date.today().isoformat(),
"MODEL": model,
}
async def _load_system_prompt(workspace: str, model: str = "") -> str:
"""Load system prompt with template variable rendering.
Resolution order (most specific wins):
1. .cptr/system.md in the workspace (file override)
2. Per-model system_prompt from chat.models config
3. Global (*) system_prompt from chat.models config
4. DEFAULT_SYSTEM_PROMPT constant (hardcoded fallback)
All sources support {{VARIABLE}} template substitution.
"""
template = None
# 1. Workspace file override (.cptr/system.md)
ws_prompt = Path(workspace) / ".cptr" / "system.md"
if ws_prompt.is_file():
template = ws_prompt.read_text(errors="replace").strip()
# 2 & 3. Config-based prompts (per-model → global)
if template is None:
try:
chat_models_config = await Config.get("chat.models") or {}
# Per-model prompt
if model:
model_prompt = (
chat_models_config
.get(model, {})
.get("params", {})
.get("system_prompt")
)
if model_prompt:
template = model_prompt
# Global prompt
if template is None:
global_prompt = (
chat_models_config
.get("*", {})
.get("params", {})
.get("system_prompt")
)
if global_prompt:
template = global_prompt
except Exception:
logger.debug("[system_prompt] Failed to load from config", exc_info=True)
# 4. Hardcoded fallback
if template is None:
template = DEFAULT_SYSTEM_PROMPT
# Render template variables
variables = _build_template_variables(workspace, model)
return _render_template(template, variables)
# ── Title generation ────────────────────────────────────────
@@ -696,7 +792,7 @@ async def run_chat_task(
api_key = decrypt_key(connection.get("api_key", ""), _get_jwt_secret())
base_url = connection.get("base_url") or _default_base_url(provider)
system = _load_system_prompt(workspace)
system = await _load_system_prompt(workspace, model)
messages, loaded_summary = await _load_message_history(chat_id, message_id)
if loaded_summary:
system += f"\n\n[CONVERSATION SUMMARY]\n{loaded_summary}"
@@ -704,9 +800,33 @@ async def run_chat_task(
messages.append({"role": "user", "content": regeneration_prompt})
tools = get_tool_list()
# Load chat params for approval mode
# Remove view_skill tool if no skills are available
skills = discover_skills(workspace)
if not skills:
tools = [t for t in tools if t["name"] != "view_skill"]
# Parse $skill-name mentions from the user message to auto-activate skills
chat_obj = await Chat.get_by_id(chat_id)
chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
attached_skill_ids: list[str] = []
if skills and messages:
# Find the last user message
last_user = next((m for m in reversed(messages) if m["role"] == "user"), None)
if last_user:
import re as _re
mentioned = _re.findall(r'\$([a-z0-9](?:[a-z0-9-]*[a-z0-9])?)', last_user["content"])
skill_names = {s.name for s in skills}
attached_skill_ids = [m for m in mentioned if m in skill_names]
if attached_skill_ids:
from cptr.utils.tools import _activated_skills
skill_blocks = []
for sid in attached_skill_ids:
skill = load_skill(workspace, sid)
if skill:
skill_blocks.append(format_skill_content(skill))
_activated_skills.add(sid) # mark as activated for dedup
if skill_blocks:
system += "\n\n" + "\n\n".join(skill_blocks)
# Plan mode: strip write tools, inject prompt as user message (not system, to preserve cache)
plan_mode = chat_params.get("plan_mode", False)
@@ -762,8 +882,17 @@ async def run_chat_task(
loaded_summary = summary
# Append summary to system prompt (works for all providers)
system = _load_system_prompt(workspace)
system = await _load_system_prompt(workspace, model)
system += f"\n\n[CONVERSATION SUMMARY]\n{summary}"
# Re-inject attached skills after compaction (protect from pruning)
if attached_skill_ids:
skill_blocks = []
for sid in attached_skill_ids:
skill = load_skill(workspace, sid)
if skill:
skill_blocks.append(format_skill_content(skill))
if skill_blocks:
system += "\n\n" + "\n\n".join(skill_blocks)
messages = keep_zone
last_usage = None # reset after compaction
new_messages_since = 0
@@ -818,7 +947,7 @@ async def run_chat_task(
if name == "create_artifact":
result = await create_artifact(**event["arguments"], workspace=workspace)
else:
result = await execute_tool(name, event["arguments"], workspace)
result = await execute_tool(name, event["arguments"], {"workspace": workspace, "user_id": user_id, "model_id": model})
item["status"] = "completed"
output_items.append(item)
result_item = {
+402
View File
@@ -0,0 +1,402 @@
"""Agent Skills support following the agentskills.io specification.
Skills are folders containing a SKILL.md file with YAML frontmatter
(name + description) and markdown instructions. Optional subdirectories
include scripts/, references/, and assets/.
Discovery follows progressive disclosure:
1. Catalog (startup): name + description only (~50-100 tokens/skill)
2. Instructions (activation): full SKILL.md body (<5000 tokens recommended)
3. Resources (on-demand): scripts, references, assets loaded individually
See: https://agentskills.io/specification
"""
from __future__ import annotations
import logging
import re
from dataclasses import dataclass, field
from pathlib import Path
import yaml
logger = logging.getLogger(__name__)
# ── Discovery paths ─────────────────────────────────────────
# Workspace-level: scan client-specific + cross-client convention paths.
# First match on skill name wins within the same scope.
WORKSPACE_SKILL_DIRS = [
".cptr/skills",
".agents/skills",
".claude/skills",
".codex/skills",
]
# Global (user-level): only our own directory
GLOBAL_SKILL_DIRS = [
str(Path.home() / ".cptr" / "skills"),
]
# Directories to skip during scanning
_SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv"}
# Max scan limits (per spec recommendation)
_MAX_SCAN_DEPTH = 4
_MAX_SCAN_DIRS = 2000
# ── Data classes ────────────────────────────────────────────
@dataclass
class SkillMeta:
"""Tier 1: lightweight metadata for the catalog."""
name: str
description: str
location: str # absolute path to SKILL.md
source: str # "workspace" or "global"
# Optional spec fields
license: str | None = None
compatibility: str | None = None
metadata: dict | None = None
allowed_tools: str | None = None
@dataclass
class SkillContent(SkillMeta):
"""Tier 2: full instructions + resource listing."""
body: str = "" # markdown body after frontmatter
resources: list[str] = field(default_factory=list) # relative paths of bundled files
# ── Frontmatter parsing ────────────────────────────────────
_FRONTMATTER_RE = re.compile(r"\A---\s*\n(.*?)\n---\s*\n?(.*)", re.DOTALL)
def parse_frontmatter(text: str) -> tuple[dict, str]:
"""Split SKILL.md into (frontmatter_dict, body_string).
Handles malformed YAML (unquoted colons) with a fallback retry.
Returns ({}, body) if frontmatter is missing or unparseable.
"""
match = _FRONTMATTER_RE.match(text)
if not match:
return {}, text.strip()
yaml_block = match.group(1)
body = match.group(2).strip()
# Try parsing YAML
try:
fm = yaml.safe_load(yaml_block)
if isinstance(fm, dict):
return fm, body
return {}, body
except yaml.YAMLError:
pass
# Fallback: try wrapping problematic values in quotes
# Common issue: unquoted colons in description values
fixed_lines = []
for line in yaml_block.splitlines():
if ":" in line and not line.strip().startswith("#"):
key_part, _, val_part = line.partition(":")
val = val_part.strip()
# If value contains a colon and isn't already quoted
if ":" in val and not (val.startswith('"') or val.startswith("'")):
indent = len(line) - len(line.lstrip())
fixed_lines.append(f"{' ' * indent}{key_part.strip()}: \"{val}\"")
continue
fixed_lines.append(line)
try:
fm = yaml.safe_load("\n".join(fixed_lines))
if isinstance(fm, dict):
logger.debug("[skills] Parsed frontmatter with colon-quoting fallback")
return fm, body
except yaml.YAMLError:
pass
logger.warning("[skills] Unparseable YAML frontmatter")
return {}, body
# ── Name validation ─────────────────────────────────────────
_NAME_RE = re.compile(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$")
def validate_name(name: str, parent_dir: str) -> list[str]:
"""Validate skill name per spec. Returns list of warnings (lenient).
Spec constraints:
- 1-64 characters
- Lowercase letters, numbers, and hyphens only
- Must not start or end with a hyphen
- Must not contain consecutive hyphens
- Must match the parent directory name
"""
warnings: list[str] = []
if not name:
warnings.append("name is empty")
return warnings
if len(name) > 64:
warnings.append(f"name exceeds 64 characters ({len(name)})")
if not _NAME_RE.match(name):
warnings.append(f"name '{name}' contains invalid characters (must be lowercase alphanumeric + hyphens)")
if "--" in name:
warnings.append(f"name '{name}' contains consecutive hyphens")
if name != parent_dir:
warnings.append(f"name '{name}' doesn't match parent directory '{parent_dir}'")
return warnings
# ── Discovery ───────────────────────────────────────────────
def _scan_skills_dir(skills_dir: Path, source: str) -> list[SkillMeta]:
"""Scan a single skills directory for skill folders containing SKILL.md."""
results: list[SkillMeta] = []
if not skills_dir.is_dir():
return results
dirs_scanned = 0
try:
for item in sorted(skills_dir.iterdir()):
if dirs_scanned >= _MAX_SCAN_DIRS:
logger.warning("[skills] Hit max scan limit (%d dirs)", _MAX_SCAN_DIRS)
break
if not item.is_dir() or item.name in _SKIP_DIRS or item.name.startswith("."):
continue
dirs_scanned += 1
skill_md = item / "SKILL.md"
if not skill_md.is_file():
continue
try:
text = skill_md.read_text(errors="replace")
except OSError:
logger.debug("[skills] Failed to read %s", skill_md)
continue
fm, _body = parse_frontmatter(text)
name = str(fm.get("name", "")).strip()
description = str(fm.get("description", "")).strip()
# Skip if description is missing (per spec: essential for disclosure)
if not description:
logger.warning("[skills] Skipping %s: missing description", skill_md)
continue
# Use folder name as fallback if name is missing
if not name:
name = item.name
logger.debug("[skills] Using folder name as skill name: %s", name)
# Lenient validation: warn but load
warnings = validate_name(name, item.name)
for w in warnings:
logger.warning("[skills] %s: %s", skill_md, w)
results.append(SkillMeta(
name=name,
description=description[:1024],
location=str(skill_md.resolve()),
source=source,
license=fm.get("license"),
compatibility=fm.get("compatibility"),
metadata=fm.get("metadata") if isinstance(fm.get("metadata"), dict) else None,
allowed_tools=fm.get("allowed-tools"),
))
except PermissionError:
logger.debug("[skills] Permission denied scanning %s", skills_dir)
return results
def discover_skills(workspace: str) -> list[SkillMeta]:
"""Discover all available skills from workspace + global directories.
Scans workspace-level dirs first, then global. Deduplicates by name:
workspace skills take precedence over global skills.
Returns list of SkillMeta (frontmatter only, no body content).
"""
seen_names: set[str] = set()
all_skills: list[SkillMeta] = []
ws = Path(workspace)
# 1. Workspace-level skills (project-specific, git-trackable)
if ws.is_dir():
for rel_dir in WORKSPACE_SKILL_DIRS:
skills_dir = ws / rel_dir
for skill in _scan_skills_dir(skills_dir, source="workspace"):
if skill.name not in seen_names:
seen_names.add(skill.name)
all_skills.append(skill)
else:
logger.debug(
"[skills] Skipping duplicate '%s' from %s (already found)",
skill.name, skill.location,
)
# 2. Global skills (user-level, available across all workspaces)
for dir_path in GLOBAL_SKILL_DIRS:
skills_dir = Path(dir_path).expanduser()
for skill in _scan_skills_dir(skills_dir, source="global"):
if skill.name not in seen_names:
seen_names.add(skill.name)
all_skills.append(skill)
else:
logger.debug(
"[skills] Global skill '%s' shadowed by workspace skill",
skill.name,
)
if all_skills:
logger.info(
"[skills] Discovered %d skills (%d workspace, %d global)",
len(all_skills),
sum(1 for s in all_skills if s.source == "workspace"),
sum(1 for s in all_skills if s.source == "global"),
)
return all_skills
# ── Loading (tier 2) ────────────────────────────────────────
def _enumerate_resources(skill_dir: Path) -> list[str]:
"""List all files in a skill folder (relative paths), excluding SKILL.md."""
resources: list[str] = []
def _walk(directory: Path, prefix: str = "", depth: int = 0):
if depth >= _MAX_SCAN_DEPTH:
return
try:
for item in sorted(directory.iterdir()):
if item.name in _SKIP_DIRS:
continue
rel = f"{prefix}{item.name}" if not prefix else f"{prefix}/{item.name}"
if item.is_file() and item.name != "SKILL.md":
resources.append(rel)
elif item.is_dir():
_walk(item, rel, depth + 1)
except PermissionError:
pass
_walk(skill_dir)
return resources
def load_skill(workspace: str, skill_name: str) -> SkillContent | None:
"""Load full skill content (tier 2): body + resource listing.
Finds the skill by name using the same discovery order,
reads the full SKILL.md, and enumerates bundled files.
"""
# Find the skill's location
skills = discover_skills(workspace)
meta = next((s for s in skills if s.name == skill_name), None)
if not meta:
return None
skill_md = Path(meta.location)
try:
text = skill_md.read_text(errors="replace")
except OSError:
logger.error("[skills] Failed to read %s", skill_md)
return None
fm, body = parse_frontmatter(text)
skill_dir = skill_md.parent
resources = _enumerate_resources(skill_dir)
return SkillContent(
name=meta.name,
description=meta.description,
location=meta.location,
source=meta.source,
license=meta.license,
compatibility=meta.compatibility,
metadata=meta.metadata,
allowed_tools=meta.allowed_tools,
body=body,
resources=resources,
)
# ── Catalog & structured output ─────────────────────────────
def build_catalog_xml(skills: list[SkillMeta]) -> str:
"""Build the <available_skills> XML catalog for the system prompt.
Includes behavioral instructions telling the model how to use skills.
Returns empty string if no skills.
"""
if not skills:
return ""
lines = [
"The following skills provide specialized instructions for specific tasks.",
"When a task matches a skill's description, call the view_skill tool",
"with the skill's name to load its full instructions.",
"",
"<available_skills>",
]
for s in skills:
lines.append("<skill>")
lines.append(f" <name>{s.name}</name>")
lines.append(f" <description>{s.description}</description>")
lines.append(f" <location>{s.location}</location>")
lines.append("</skill>")
lines.append("</available_skills>")
return "\n".join(lines)
def format_skill_content(skill: SkillContent) -> str:
"""Format loaded skill content with structured wrapping (per spec).
Wraps in <skill_content> tags with <skill_resources> listing
so the model can identify skill instructions and available files.
"""
skill_dir = str(Path(skill.location).parent)
parts = [
f'<skill_content name="{skill.name}">',
skill.body,
"",
f"Skill directory: {skill_dir}",
"Relative paths in this skill are relative to the skill directory.",
]
if skill.resources:
parts.append("")
parts.append("<skill_resources>")
for r in skill.resources[:50]: # cap listing for large dirs
parts.append(f" <file>{r}</file>")
if len(skill.resources) > 50:
parts.append(f" <!-- ... and {len(skill.resources) - 50} more files -->")
parts.append("</skill_resources>")
parts.append("</skill_content>")
return "\n".join(parts)
+61 -28
View File
@@ -1,8 +1,12 @@
"""Tool definitions: plain functions with schema introspection.
Tools are real async functions. Schemas are auto-generated from
type hints + docstrings via inspect. The LLM never sees the
`workspace` parameter; it's injected by the task runner.
type hints + docstrings via inspect. Keyword-only parameters are
never exposed to the LLM — they carry injected execution context:
- Legacy tools use ``*, workspace: str`` (injected by execute_tool).
- Context-aware tools use ``*, __context__: dict`` containing
workspace, user_id, and model_id (injected by execute_tool).
"""
from __future__ import annotations
@@ -694,9 +698,8 @@ async def create_automation(
name: str,
prompt: str,
rrule: str,
model_id: str = "",
*,
workspace: str,
__context__: dict,
) -> str:
"""Create a scheduled automation that runs a prompt on a recurring or one-time schedule.
The rrule parameter must be a valid iCalendar RRULE string. Common examples:
@@ -708,8 +711,11 @@ async def create_automation(
:param name: A short descriptive name for the automation.
:param prompt: The instructions/prompt to execute on each run.
:param rrule: An iCalendar RRULE string defining the schedule.
:param model_id: Model to use (optional, defaults to the current chat model).
"""
workspace = __context__["workspace"]
user_id = __context__["user_id"]
model_id = __context__.get("model_id", "")
try:
import time
from cptr.models.automations import Automation as AutomationModel
@@ -721,22 +727,14 @@ async def create_automation(
except ValueError as e:
return json.dumps({"error": f"Invalid schedule: {e}"})
# If no model_id provided, try to detect from admin config
if not model_id:
try:
from cptr.models.config import AdminConfig
cfg = await AdminConfig.get()
model_id = (cfg.meta or {}).get("default_model", "") if cfg else ""
except Exception:
pass
if not model_id:
return json.dumps({"error": "Could not detect model. Please provide model_id."})
return json.dumps({"error": "Could not detect model from current chat context."})
now_ns = int(time.time() * 1_000_000_000)
nxt = next_run_ns(rrule)
automation = await AutomationModel.create(
user_id="default",
user_id=user_id,
name=name,
prompt=prompt,
model_id=model_id,
@@ -762,18 +760,21 @@ async def list_automations(
status: str = "",
count: int = 10,
*,
workspace: str,
__context__: dict,
) -> str:
"""List scheduled automations for the current workspace.
:param status: Filter by status: "active", "paused", or empty for all.
:param count: Maximum number of automations to return (default: 10).
"""
workspace = __context__["workspace"]
user_id = __context__["user_id"]
try:
from cptr.models.automations import Automation as AutomationModel
from cptr.utils.automations import next_n_runs_ns
items, total = await AutomationModel.get_by_workspace(
user_id="default",
user_id=user_id,
workspace=workspace or None,
status=status or None,
limit=count,
@@ -802,7 +803,7 @@ async def update_automation(
rrule: str = "",
model_id: str = "",
*,
workspace: str,
__context__: dict,
) -> str:
"""Update an existing automation. Only provided fields are changed.
:param automation_id: The ID of the automation to update.
@@ -857,7 +858,7 @@ async def update_automation(
async def toggle_automation(
automation_id: str,
*,
workspace: str,
__context__: dict,
) -> str:
"""Pause or resume a scheduled automation. If active, it will be paused. If paused, it will be resumed.
:param automation_id: The ID of the automation to toggle.
@@ -888,7 +889,7 @@ async def toggle_automation(
async def delete_automation(
automation_id: str,
*,
workspace: str,
__context__: dict,
) -> str:
"""Delete a scheduled automation and all its run history.
:param automation_id: The ID of the automation to delete.
@@ -910,6 +911,34 @@ async def delete_automation(
return json.dumps({"error": str(e)})
# ── Skill tools ─────────────────────────────────────────────
# Track activated skills per session (cleared on import)
_activated_skills: set[str] = set()
async def view_skill(
skill_name: 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).
"""
from cptr.utils.skills import load_skill, format_skill_content
# 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."
_activated_skills.add(skill_name)
return format_skill_content(skill)
# ── Registry ────────────────────────────────────────────────
TOOLS: dict[str, dict] = {
@@ -921,6 +950,7 @@ TOOLS: dict[str, dict] = {
"web_search": {"fn": web_search, "auto": True},
"read_url": {"fn": read_url, "auto": True},
"list_automations": {"fn": list_automations, "auto": True},
"view_skill": {"fn": view_skill, "auto": True},
# Write / mutate (require approval unless auto_approve_all)
"create_file": {"fn": create_file, "auto": False},
"edit_file": {"fn": edit_file, "auto": False},
@@ -965,7 +995,8 @@ def _fn_to_schema(name: str, fn) -> dict:
properties: dict[str, dict] = {}
required: list[str] = []
for pname, param in sig.parameters.items():
if pname == "workspace":
# Skip injected context params (keyword-only, never exposed to LLM)
if param.kind == inspect.Parameter.KEYWORD_ONLY:
continue
ptype = _TYPE_MAP.get(hints.get(pname), "string") # type: ignore[arg-type]
prop: dict = {"type": ptype}
@@ -973,10 +1004,7 @@ def _fn_to_schema(name: str, fn) -> dict:
prop["description"] = param_descs[pname]
properties[pname] = prop
# Positional with no default → required
if (
param.default is inspect.Parameter.empty
and param.kind != inspect.Parameter.KEYWORD_ONLY
):
if param.default is inspect.Parameter.empty:
required.append(pname)
return {
"name": name,
@@ -994,13 +1022,18 @@ def get_tool_list() -> list[dict]:
return [_fn_to_schema(name, t["fn"]) for name, t in TOOLS.items()]
async def execute_tool(name: str, args: dict, workspace: str) -> str:
"""Execute a tool by name. Returns output string."""
async def execute_tool(name: str, args: dict, __context__: dict) -> str:
"""Execute a tool by name, injecting execution context."""
info = TOOLS.get(name)
if not info:
return f"Error: unknown tool: {name}"
fn = info["fn"]
try:
return await fn(**args, workspace=workspace)
sig = inspect.signature(fn)
if "__context__" in sig.parameters:
return await fn(**args, __context__=__context__)
else:
# Legacy tools: inject workspace directly
return await fn(**args, workspace=__context__["workspace"])
except Exception as e:
return f"Error executing {name}: {e}"
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "cptr"
version = "0.2.2"
version = "0.2.3"
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
license = {file = "LICENSE"}
readme = "README.md"