diff --git a/CHANGELOG.md b/CHANGELOG.md index 97c57da..4812689 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/cptr/app.py b/cptr/app.py index 2cee5f0..4022736 100644 --- a/cptr/app.py +++ b/cptr/app.py @@ -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(): diff --git a/cptr/frontend/package.json b/cptr/frontend/package.json index 53ad033..21348c9 100644 --- a/cptr/frontend/package.json +++ b/cptr/frontend/package.json @@ -1,7 +1,7 @@ { "name": "frontend", "private": true, - "version": "0.2.0", + "version": "0.2.3", "type": "module", "scripts": { "dev": "vite dev", diff --git a/cptr/frontend/src/lib/apis/admin.ts b/cptr/frontend/src/lib/apis/admin.ts index b12eb51..10de548 100644 --- a/cptr/frontend/src/lib/apis/admin.ts +++ b/cptr/frontend/src/lib/apis/admin.ts @@ -109,7 +109,7 @@ export const verifyConnection = (id: string) => export interface ModelConfigEntry { is_active?: boolean; - params?: { request_params?: Record }; + params?: { request_params?: Record; system_prompt?: string }; } export interface ModelConfigResponse { diff --git a/cptr/frontend/src/lib/apis/skills.ts b/cptr/frontend/src/lib/apis/skills.ts new file mode 100644 index 0000000..82025c1 --- /dev/null +++ b/cptr/frontend/src/lib/apis/skills.ts @@ -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(`/api/skills?workspace=${encodeURIComponent(workspace)}`); diff --git a/cptr/frontend/src/lib/components/Admin/CreateConnectionModal.svelte b/cptr/frontend/src/lib/components/Admin/CreateConnectionModal.svelte index 1fcbe53..2f94378 100644 --- a/cptr/frontend/src/lib/components/Admin/CreateConnectionModal.svelte +++ b/cptr/frontend/src/lib/components/Admin/CreateConnectionModal.svelte @@ -156,6 +156,7 @@ +

{$t('connections.modelsHint')}

m.trim()) .filter(Boolean) - : undefined; + : null; const name = formName.trim() || (() => { @@ -192,6 +192,7 @@ +

{$t('connections.modelsHint')}

(null); let globalRows = $state([]); + 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 { + const params: Record = {}; + 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[] = []; 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 @@ } +{#snippet systemPromptField(value: string, onInput: (v: string) => void, placeholder: string)} +
+ {$t('models.systemPrompt')} + +
+ + {#if value.trim()} + + {/if} +
+ {#if showVariables} +
+ {#each TEMPLATE_VARIABLES as v} +
+ {`{{${v.name}}}`} + {v.desc} +
+ {/each} +
+ {/if} +
+{/snippet} + {#snippet paramRows(rows: ParamRow[], onInput: () => void, onRemove: (i: number) => void, onAdd: () => void)}
- request params + request params {#each rows as row, i}
- - -
@@ -149,30 +249,56 @@ {/snippet}
-

{$t('admin.models')}

- {#if loading}
{:else}
+

+ {$t('admin.models')} +

{#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)} > - + {model.name} 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); + } + }} > - + {#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} -

{$t('models.noModels')}

+

+ {$t('models.noModels')} +

{/if}
@@ -223,5 +380,3 @@
{/if}
- - diff --git a/cptr/frontend/src/lib/components/Settings/About.svelte b/cptr/frontend/src/lib/components/Settings/About.svelte index 9790e3b..cb9de7a 100644 --- a/cptr/frontend/src/lib/components/Settings/About.svelte +++ b/cptr/frontend/src/lib/components/Settings/About.svelte @@ -1,6 +1,6 @@

@@ -22,7 +22,18 @@ >v{$appVersion} {/if} + {#if $updateAvailable} + · + v{$latestVersion} available + {/if} +

{$t('app.tagline')}

@@ -44,3 +55,4 @@

{$t('about.createdBy')}

+ diff --git a/cptr/frontend/src/lib/components/Settings/General.svelte b/cptr/frontend/src/lib/components/Settings/General.svelte index b2a6892..e07e324 100644 --- a/cptr/frontend/src/lib/components/Settings/General.svelte +++ b/cptr/frontend/src/lib/components/Settings/General.svelte @@ -1,11 +1,12 @@ + +
+
+ + {$t('update.available', { version: $latestVersion })} + + + + {$t('update.viewRelease')} + + + +
+
diff --git a/cptr/frontend/src/lib/components/chat/ChatInput.svelte b/cptr/frontend/src/lib/components/chat/ChatInput.svelte index 2aa55ae..54d5d12 100644 --- a/cptr/frontend/src/lib/components/chat/ChatInput.svelte +++ b/cptr/frontend/src/lib/components/chat/ChatInput.svelte @@ -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 | 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 { + 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); diff --git a/cptr/frontend/src/lib/components/chat/SkillMention.ts b/cptr/frontend/src/lib/components/chat/SkillMention.ts new file mode 100644 index 0000000..5fe9552 --- /dev/null +++ b/cptr/frontend/src/lib/components/chat/SkillMention.ts @@ -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[]; + 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)]; +} diff --git a/cptr/frontend/src/lib/components/chat/SkillSuggestionPopup.svelte b/cptr/frontend/src/lib/components/chat/SkillSuggestionPopup.svelte new file mode 100644 index 0000000..97ea264 --- /dev/null +++ b/cptr/frontend/src/lib/components/chat/SkillSuggestionPopup.svelte @@ -0,0 +1,74 @@ + + +
+ {#if items.length === 0} +
No skills found
+ {:else} +
+ Skills +
+
+ {#each items as item, i (item.id)} + + + {/each} +
+ {/if} +
diff --git a/cptr/frontend/src/lib/i18n/locales/de.json b/cptr/frontend/src/lib/i18n/locales/de.json index 66bea88..aea7b5e 100644 --- a/cptr/frontend/src/lib/i18n/locales/de.json +++ b/cptr/frontend/src/lib/i18n/locales/de.json @@ -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}}" } diff --git a/cptr/frontend/src/lib/i18n/locales/en.json b/cptr/frontend/src/lib/i18n/locales/en.json index 69a0704..88068ca 100644 --- a/cptr/frontend/src/lib/i18n/locales/en.json +++ b/cptr/frontend/src/lib/i18n/locales/en.json @@ -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}}" } diff --git a/cptr/frontend/src/lib/i18n/locales/es.json b/cptr/frontend/src/lib/i18n/locales/es.json index d1a7b38..1d8206d 100644 --- a/cptr/frontend/src/lib/i18n/locales/es.json +++ b/cptr/frontend/src/lib/i18n/locales/es.json @@ -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}}" } diff --git a/cptr/frontend/src/lib/i18n/locales/fr.json b/cptr/frontend/src/lib/i18n/locales/fr.json index 163e6c1..5f3461f 100644 --- a/cptr/frontend/src/lib/i18n/locales/fr.json +++ b/cptr/frontend/src/lib/i18n/locales/fr.json @@ -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}}" } diff --git a/cptr/frontend/src/lib/i18n/locales/ja.json b/cptr/frontend/src/lib/i18n/locales/ja.json index 2f57291..42063da 100644 --- a/cptr/frontend/src/lib/i18n/locales/ja.json +++ b/cptr/frontend/src/lib/i18n/locales/ja.json @@ -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}}" } diff --git a/cptr/frontend/src/lib/i18n/locales/ko.json b/cptr/frontend/src/lib/i18n/locales/ko.json index d9215a5..4a37f59 100644 --- a/cptr/frontend/src/lib/i18n/locales/ko.json +++ b/cptr/frontend/src/lib/i18n/locales/ko.json @@ -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}}" } diff --git a/cptr/frontend/src/lib/i18n/locales/pt-BR.json b/cptr/frontend/src/lib/i18n/locales/pt-BR.json index ce2e890..5f39676 100644 --- a/cptr/frontend/src/lib/i18n/locales/pt-BR.json +++ b/cptr/frontend/src/lib/i18n/locales/pt-BR.json @@ -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}}" } diff --git a/cptr/frontend/src/lib/i18n/locales/ru.json b/cptr/frontend/src/lib/i18n/locales/ru.json index b5e5ff5..f4bf945 100644 --- a/cptr/frontend/src/lib/i18n/locales/ru.json +++ b/cptr/frontend/src/lib/i18n/locales/ru.json @@ -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}}" } diff --git a/cptr/frontend/src/lib/i18n/locales/zh-CN.json b/cptr/frontend/src/lib/i18n/locales/zh-CN.json index 078e361..be0981f 100644 --- a/cptr/frontend/src/lib/i18n/locales/zh-CN.json +++ b/cptr/frontend/src/lib/i18n/locales/zh-CN.json @@ -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}}" } diff --git a/cptr/frontend/src/lib/i18n/locales/zh-TW.json b/cptr/frontend/src/lib/i18n/locales/zh-TW.json index 13e5863..0f96c2f 100644 --- a/cptr/frontend/src/lib/i18n/locales/zh-TW.json +++ b/cptr/frontend/src/lib/i18n/locales/zh-TW.json @@ -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" } diff --git a/cptr/frontend/src/lib/stores.ts b/cptr/frontend/src/lib/stores.ts index a4c5977..787be49 100644 --- a/cptr/frontend/src/lib/stores.ts +++ b/cptr/frontend/src/lib/stores.ts @@ -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; // 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>({}); 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).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 { 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); + if (prefs.showUpdateToast !== undefined) showUpdateToastPref.set(prefs.showUpdateToast as boolean); } catch { // First run, no preferences yet } diff --git a/cptr/frontend/src/routes/+layout.svelte b/cptr/frontend/src/routes/+layout.svelte index 108ef2b..9c0ae91 100644 --- a/cptr/frontend/src/routes/+layout.svelte +++ b/cptr/frontend/src/routes/+layout.svelte @@ -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" /> - {$currentWorkspace ? `${$currentWorkspace.name} / cptr` : 'cptr'} + {$activeTab && $activeTab.type !== 'files' + ? $currentWorkspace + ? `${$activeTab.label} / ${$currentWorkspace.name} / cptr` + : `${$activeTab.label} / cptr` + : $currentWorkspace + ? `${$currentWorkspace.name} / cptr` + : 'cptr'} @@ -280,6 +319,14 @@ (showSettings = false)} /> {/if} + {#if $updateAvailable && showUpdateToast} + { + showUpdateToast = false; + localStorage.setItem('dismissedUpdateToast', Date.now().toString()); + }} + /> + {/if} {:else}
diff --git a/cptr/routers/__init__.py b/cptr/routers/__init__.py index a127096..ca203bc 100644 --- a/cptr/routers/__init__.py +++ b/cptr/routers/__init__.py @@ -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", diff --git a/cptr/routers/admin.py b/cptr/routers/admin.py index 6a11aeb..7ab2436 100644 --- a/cptr/routers/admin.py +++ b/cptr/routers/admin.py @@ -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) diff --git a/cptr/routers/chat.py b/cptr/routers/chat.py index 5167029..a36e1da 100644 --- a/cptr/routers/chat.py +++ b/cptr/routers/chat.py @@ -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 "" diff --git a/cptr/routers/skills.py b/cptr/routers/skills.py new file mode 100644 index 0000000..72546f7 --- /dev/null +++ b/cptr/routers/skills.py @@ -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 + ] diff --git a/cptr/utils/automations.py b/cptr/utils/automations.py index 7f18661..979e097 100644 --- a/cptr/utils/automations.py +++ b/cptr/utils/automations.py @@ -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(), ) diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 053fd4a..4f1a4a5 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -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\n{instructions}\n" - base += ( + instructions_block = ( + f"\n{instructions}\n" "\n\nThe above 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 = { diff --git a/cptr/utils/skills.py b/cptr/utils/skills.py new file mode 100644 index 0000000..a9a6a28 --- /dev/null +++ b/cptr/utils/skills.py @@ -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 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.", + "", + "", + ] + + for s in skills: + lines.append("") + lines.append(f" {s.name}") + lines.append(f" {s.description}") + lines.append(f" {s.location}") + lines.append("") + + lines.append("") + return "\n".join(lines) + + +def format_skill_content(skill: SkillContent) -> str: + """Format loaded skill content with structured wrapping (per spec). + + Wraps in tags with listing + so the model can identify skill instructions and available files. + """ + skill_dir = str(Path(skill.location).parent) + + parts = [ + f'', + 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("") + for r in skill.resources[:50]: # cap listing for large dirs + parts.append(f" {r}") + if len(skill.resources) > 50: + parts.append(f" ") + parts.append("") + + parts.append("") + return "\n".join(parts) diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index ced4b87..bce8ff6 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -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 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 above." + + skill = load_skill(workspace, skill_name) + if not skill: + return f"Error: skill '{skill_name}' not found. Check 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}" diff --git a/pyproject.toml b/pyproject.toml index eeab441..603530a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"