mirror of
https://github.com/open-webui/computer.git
synced 2026-11-23 22:11:29 -05:00
refac
This commit is contained in:
1 parent
c536fe6e52
commit
76da3f5062
25 files changed
+924
-53
No files matched your search
@@ -97,6 +97,12 @@ export const getChat = (chatId: string, modelId?: string) => {
|
||||
export const deleteChat = (chatId: string) =>
|
||||
fetchJSON<{ ok: boolean }>(`/api/chats/${chatId}`, { method: 'DELETE' });
|
||||
|
||||
export const forkChat = (chatId: string, messageId?: string | null) =>
|
||||
fetchJSON<{ ok: boolean; chat_id: string }>(
|
||||
`/api/chats/${chatId}/fork`,
|
||||
jsonBody({ message_id: messageId ?? null })
|
||||
);
|
||||
|
||||
// ── Mutations ───────────────────────────────────────────────
|
||||
|
||||
export const sendMessage = (
|
||||
|
||||
@@ -11,6 +11,14 @@ export interface SkillInfo {
|
||||
license?: string;
|
||||
compatibility?: string;
|
||||
managed?: boolean;
|
||||
created_by?: string | null;
|
||||
created_from?: string | null;
|
||||
view_count?: number;
|
||||
use_count?: number;
|
||||
update_count?: number;
|
||||
last_viewed_at?: string | null;
|
||||
last_used_at?: string | null;
|
||||
last_updated_at?: string | null;
|
||||
}
|
||||
|
||||
export const getSkills = (workspace: string) =>
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { getAdminConfig, updateConfig } from '$lib/apis/admin';
|
||||
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
|
||||
let loading = $state(true);
|
||||
let saving = $state(false);
|
||||
let backgroundReview = $state(true);
|
||||
let reviewInterval = $state(10);
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
const config = await getAdminConfig();
|
||||
backgroundReview =
|
||||
config['skills.background_review_enabled'] !== false &&
|
||||
config['skills.background_review_enabled'] !== 'false';
|
||||
reviewInterval = Number(config['skills.review_interval_turns']) || 10;
|
||||
} catch {
|
||||
toast.error('Failed to load config');
|
||||
}
|
||||
loading = false;
|
||||
});
|
||||
|
||||
async function save() {
|
||||
saving = true;
|
||||
try {
|
||||
await updateConfig({
|
||||
'skills.background_review_enabled': backgroundReview,
|
||||
'skills.review_interval_turns': Math.max(1, Number(reviewInterval) || 10)
|
||||
});
|
||||
toast.success('Saved');
|
||||
} catch {
|
||||
toast.error('Failed to save');
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col min-h-full">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">Skills</h2>
|
||||
|
||||
{#if loading}
|
||||
<div class="flex justify-center py-8"><Spinner size={16} /></div>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400">Background review</span>
|
||||
<ToggleSwitch
|
||||
value={backgroundReview}
|
||||
onchange={(v) => {
|
||||
backgroundReview = v;
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600 -mt-1">
|
||||
Let Computer create or update managed skills after successful reusable work.
|
||||
</p>
|
||||
|
||||
{#if backgroundReview}
|
||||
<div>
|
||||
<label class="text-xs text-gray-600 dark:text-gray-400" for="skills-review-interval"
|
||||
>Review interval</label
|
||||
>
|
||||
<div class="flex items-center gap-1.5 mt-1">
|
||||
<input
|
||||
id="skills-review-interval"
|
||||
type="number"
|
||||
bind:value={reviewInterval}
|
||||
min="1"
|
||||
class="w-16 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
|
||||
/>
|
||||
<span class="text-[0.6875rem] text-gray-400 dark:text-gray-600">turns</span>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="mt-5 pt-4 border-t border-gray-100 dark:border-white/8">
|
||||
<button
|
||||
class="h-8 px-3 rounded-lg text-xs bg-gray-900 dark:bg-white text-white dark:text-black hover:bg-gray-700 dark:hover:bg-gray-200 transition-colors disabled:opacity-50"
|
||||
disabled={saving}
|
||||
onclick={save}
|
||||
>
|
||||
{saving ? 'Saving...' : 'Save'}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -882,6 +882,11 @@
|
||||
closeMenu();
|
||||
}
|
||||
|
||||
function copyPath(entry: TreeEntry) {
|
||||
navigator.clipboard.writeText(entry.path);
|
||||
closeMenu();
|
||||
}
|
||||
|
||||
async function confirmRename(entryPath: string) {
|
||||
const oldName = entryPath.split('/').pop() ?? '';
|
||||
if (!renameValue.trim() || renameValue === oldName) {
|
||||
@@ -1347,6 +1352,7 @@
|
||||
{ label: '', divider: true, onclick: () => {} }
|
||||
]
|
||||
: []),
|
||||
{ label: $t('files.copyPath'), icon: 'copy', onclick: () => copyPath(contextMenu!.entry) },
|
||||
{ label: $t('files.rename'), icon: 'pencil', onclick: () => startRename(contextMenu!.entry) },
|
||||
...(contextMenu.entry.type !== 'directory'
|
||||
? [
|
||||
|
||||
@@ -62,6 +62,12 @@
|
||||
/>
|
||||
<path d="M6 16V3" />
|
||||
<path d="M8 18H9C12.5 18 18 15.9 18 9.5V8" />
|
||||
{:else if name === 'chat-fork'}
|
||||
<path d="M4 12H9" />
|
||||
<path d="M9 12C12.5 12 12.5 7 16 7H20" />
|
||||
<path d="M17 4L20 7L17 10" />
|
||||
<path d="M9 12C12.5 12 12.5 17 16 17H20" />
|
||||
<path d="M17 14L20 17L17 20" />
|
||||
{:else if name === 'chat-bubble'}
|
||||
<path
|
||||
d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 13.8214 2.48697 15.5291 3.33782 17L2.5 21.5L7 20.6622C8.47087 21.513 10.1786 22 12 22Z"
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
import Connections from './Admin/Connections.svelte';
|
||||
import Agents from './Admin/Agents.svelte';
|
||||
import Models from './Admin/Models.svelte';
|
||||
import Skills from './Admin/Skills.svelte';
|
||||
import Messaging from './Admin/Messaging.svelte';
|
||||
import Gateway from './Admin/Gateway.svelte';
|
||||
import AudioSettings from './Admin/AudioSettings.svelte';
|
||||
@@ -37,6 +38,7 @@
|
||||
| 'connections'
|
||||
| 'agents'
|
||||
| 'models'
|
||||
| 'skills'
|
||||
| 'messaging'
|
||||
| 'gateway'
|
||||
| 'audio'
|
||||
@@ -64,6 +66,7 @@
|
||||
'connections',
|
||||
'agents',
|
||||
'models',
|
||||
'skills',
|
||||
'messaging',
|
||||
'gateway',
|
||||
'audio',
|
||||
@@ -92,6 +95,7 @@
|
||||
{ id: 'connections', label: $t('admin.connections'), icon: 'plug' },
|
||||
{ id: 'agents', label: $t('admin.agents'), icon: 'terminal' },
|
||||
{ id: 'models', label: $t('admin.models'), icon: 'cube' },
|
||||
{ id: 'skills', label: 'Skills', icon: 'spark' },
|
||||
{ id: 'messaging', label: $t('admin.messaging'), icon: 'chat-bubble' },
|
||||
{ id: 'gateway', label: $t('admin.gateway.tab'), icon: 'gateway' },
|
||||
{ id: 'audio', label: $t('admin.audio.title'), icon: 'microphone' },
|
||||
@@ -203,6 +207,8 @@
|
||||
<Agents />
|
||||
{:else if activeTab === 'models'}
|
||||
<Models />
|
||||
{:else if activeTab === 'skills'}
|
||||
<Skills />
|
||||
{:else if activeTab === 'messaging'}
|
||||
<Messaging />
|
||||
{:else if activeTab === 'gateway'}
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
speaking?: boolean;
|
||||
onapprove: (messageId: string, callId: string, approved: boolean) => void;
|
||||
onnavigate?: (direction: -1 | 1) => void;
|
||||
onfork?: () => void;
|
||||
onregenerate?: () => void;
|
||||
onedit?: (content: string, output: any[] | null, submit: boolean) => void;
|
||||
onspeak?: () => void;
|
||||
@@ -45,6 +46,7 @@
|
||||
speaking = false,
|
||||
onapprove,
|
||||
onnavigate,
|
||||
onfork,
|
||||
onregenerate,
|
||||
onedit,
|
||||
onspeak
|
||||
@@ -603,6 +605,7 @@
|
||||
disabled={siblingIndex === 0}
|
||||
onclick={() => onnavigate?.(-1)}
|
||||
aria-label={$t('chat.prevResponse')}
|
||||
use:tooltip={$t('chat.prevResponse')}
|
||||
>
|
||||
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"
|
||||
><path
|
||||
@@ -621,6 +624,7 @@
|
||||
disabled={siblingIndex === siblingTotal - 1}
|
||||
onclick={() => onnavigate?.(1)}
|
||||
aria-label={$t('chat.nextResponse')}
|
||||
use:tooltip={$t('chat.nextResponse')}
|
||||
>
|
||||
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"
|
||||
><path
|
||||
@@ -637,6 +641,7 @@
|
||||
class="p-0.5 rounded text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={startEdit}
|
||||
aria-label={$t('chat.editResponse')}
|
||||
use:tooltip={$t('chat.editResponse')}
|
||||
>
|
||||
<svg
|
||||
class="w-3.5 h-3.5"
|
||||
@@ -657,6 +662,7 @@
|
||||
class="p-0.5 rounded text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={copyContent}
|
||||
aria-label={$t('chat.copyResponse')}
|
||||
use:tooltip={copied ? $t('about.copied') : $t('chat.copyResponse')}
|
||||
>
|
||||
{#if copied}
|
||||
<svg
|
||||
@@ -697,7 +703,7 @@
|
||||
: 'text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300'}"
|
||||
onclick={onspeak}
|
||||
aria-label={speaking ? $t('chat.stopSpeaking') : $t('chat.speakResponses')}
|
||||
title={speaking ? $t('chat.stopSpeaking') : $t('chat.speakResponses')}
|
||||
use:tooltip={speaking ? $t('chat.stopSpeaking') : $t('chat.speakResponses')}
|
||||
>
|
||||
<Icon name="speaker" size={14} />
|
||||
</button>
|
||||
@@ -707,6 +713,7 @@
|
||||
class="p-0.5 rounded text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={onregenerate}
|
||||
aria-label={$t('chat.regenerateResponse')}
|
||||
use:tooltip={$t('chat.regenerateResponse')}
|
||||
>
|
||||
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"
|
||||
><path
|
||||
@@ -718,6 +725,16 @@
|
||||
>
|
||||
</button>
|
||||
{/if}
|
||||
{#if done && onfork}
|
||||
<button
|
||||
class="p-0.5 rounded text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={onfork}
|
||||
aria-label={$t('chat.forkResponse')}
|
||||
use:tooltip={$t('chat.forkResponse')}
|
||||
>
|
||||
<Icon name="chat-fork" size={14} strokeWidth={1.8} />
|
||||
</button>
|
||||
{/if}
|
||||
{#if done && usage && Object.keys(usage).length > 0}
|
||||
<div class="relative flex items-center">
|
||||
<button
|
||||
@@ -726,6 +743,7 @@
|
||||
onmouseenter={() => (showUsageTooltip = true)}
|
||||
onmouseleave={() => (showUsageTooltip = false)}
|
||||
aria-label={$t('chat.usageInfo')}
|
||||
use:tooltip={$t('chat.usageInfo')}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
@@ -776,6 +794,7 @@
|
||||
class="p-0.5 rounded text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={shareContent}
|
||||
aria-label={$t('chat.share')}
|
||||
use:tooltip={$t('chat.share')}
|
||||
>
|
||||
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"
|
||||
><path
|
||||
|
||||
@@ -75,6 +75,7 @@
|
||||
hasChatContent?: boolean;
|
||||
onsend: () => void;
|
||||
oncompact?: () => void;
|
||||
onfork?: () => void;
|
||||
onplan?: () => void;
|
||||
onstatus?: () => void;
|
||||
onskillslist?: () => void;
|
||||
@@ -96,6 +97,7 @@
|
||||
hasChatContent = false,
|
||||
onsend,
|
||||
oncompact,
|
||||
onfork,
|
||||
onplan,
|
||||
onstatus,
|
||||
onskillslist,
|
||||
@@ -358,23 +360,32 @@
|
||||
let skillActiveClientRectFn: (() => DOMRect | null) | null = null;
|
||||
let skillRepositionRafId: number | null = null;
|
||||
let cachedSkills: SkillMentionAttrs[] | null = null;
|
||||
let cachedSkillsWorkspace = '';
|
||||
let slashSkillSuggestions = $state<SkillMentionAttrs[]>([]);
|
||||
let slashSkillsRequestId = 0;
|
||||
|
||||
async function getCachedSkills(): Promise<SkillMentionAttrs[]> {
|
||||
if (!workspace) return [];
|
||||
if (!cachedSkills || cachedSkillsWorkspace !== workspace) {
|
||||
const data = await getSkills(workspace);
|
||||
cachedSkills = data.map((s) => ({
|
||||
id: s.name,
|
||||
label: s.name,
|
||||
description: s.description,
|
||||
source: s.source
|
||||
}));
|
||||
cachedSkillsWorkspace = workspace;
|
||||
}
|
||||
return cachedSkills;
|
||||
}
|
||||
|
||||
async function fetchSkillSuggestions({ query }: { query: string }): Promise<SkillMentionAttrs[]> {
|
||||
if (!workspace) return [];
|
||||
try {
|
||||
// Cache skills list (small, doesn't change during a session)
|
||||
if (!cachedSkills) {
|
||||
const data = await getSkills(workspace);
|
||||
cachedSkills = data.map((s) => ({
|
||||
id: s.name,
|
||||
label: s.name,
|
||||
description: s.description,
|
||||
source: s.source
|
||||
}));
|
||||
}
|
||||
if (!query) return cachedSkills;
|
||||
const skills = await getCachedSkills();
|
||||
if (!query) return skills;
|
||||
const q = query.toLowerCase();
|
||||
return cachedSkills.filter(
|
||||
return skills.filter(
|
||||
(s) => s.label.toLowerCase().includes(q) || (s.description || '').toLowerCase().includes(q)
|
||||
);
|
||||
} catch {
|
||||
@@ -547,19 +558,19 @@
|
||||
if (event.key === 'ArrowDown') {
|
||||
event.preventDefault();
|
||||
selectedSlashCommandIndex =
|
||||
(selectedSlashCommandIndex + 1) % Math.max(slashCommandIds.length, 1);
|
||||
(selectedSlashCommandIndex + 1) % Math.max(slashSuggestionIds.length, 1);
|
||||
return true;
|
||||
}
|
||||
if (event.key === 'ArrowUp') {
|
||||
event.preventDefault();
|
||||
selectedSlashCommandIndex =
|
||||
(selectedSlashCommandIndex - 1 + slashCommandIds.length) %
|
||||
Math.max(slashCommandIds.length, 1);
|
||||
(selectedSlashCommandIndex - 1 + slashSuggestionIds.length) %
|
||||
Math.max(slashSuggestionIds.length, 1);
|
||||
return true;
|
||||
}
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
runSlashCommand(slashCommandIds[selectedSlashCommandIndex]);
|
||||
runSlashSuggestion(slashSuggestionIds[selectedSlashCommandIndex]);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -935,6 +946,7 @@
|
||||
if (hasChatContent && oncompact && '/compact'.startsWith(slashCommandQuery))
|
||||
ids.push('compact');
|
||||
if (onplan && '/plan'.startsWith(slashCommandQuery)) ids.push('plan');
|
||||
if (hasChatContent && onfork && '/fork'.startsWith(slashCommandQuery)) ids.push('fork');
|
||||
if (hasChatContent && onstatus && '/status'.startsWith(slashCommandQuery)) ids.push('status');
|
||||
if (
|
||||
hasChatContent &&
|
||||
@@ -951,22 +963,95 @@
|
||||
ids.push('skills:create');
|
||||
return ids;
|
||||
});
|
||||
const showSlashCommands = $derived(slashCommandIds.length > 0);
|
||||
const slashSuggestionIds = $derived([
|
||||
...slashCommandIds.map((id) => `command:${id}`),
|
||||
...slashSkillSuggestions.map((skill) => `skill:${skill.id}`)
|
||||
]);
|
||||
const showSlashCommands = $derived(slashSuggestionIds.length > 0);
|
||||
const contextPercent = $derived(Math.max(0, Math.round(contextUsage?.percent ?? 0)));
|
||||
const contextCirclePercent = $derived(Math.min(contextPercent, 100));
|
||||
const contextCircleOffset = $derived(50.27 * (1 - contextCirclePercent / 100));
|
||||
|
||||
$effect(() => {
|
||||
if (selectedSlashCommandIndex >= slashCommandIds.length) selectedSlashCommandIndex = 0;
|
||||
if (selectedSlashCommandIndex >= slashSuggestionIds.length) selectedSlashCommandIndex = 0;
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const query = slashCommandQuery;
|
||||
const requestId = ++slashSkillsRequestId;
|
||||
if (!query.startsWith('/') || !workspace) {
|
||||
slashSkillSuggestions = [];
|
||||
return;
|
||||
}
|
||||
void fetchSkillSuggestions({ query: query.slice(1) }).then((items) => {
|
||||
if (requestId !== slashSkillsRequestId) return;
|
||||
slashSkillSuggestions = items.slice(0, 5);
|
||||
});
|
||||
});
|
||||
|
||||
function selectedSlashCommand(commandId: string) {
|
||||
return slashSuggestionIds[selectedSlashCommandIndex] === `command:${commandId}`;
|
||||
}
|
||||
|
||||
function selectSlashCommand(commandId: string) {
|
||||
selectedSlashCommandIndex = slashSuggestionIds.indexOf(`command:${commandId}`);
|
||||
}
|
||||
|
||||
function selectedSlashSkill(skillId: string) {
|
||||
return slashSuggestionIds[selectedSlashCommandIndex] === `skill:${skillId}`;
|
||||
}
|
||||
|
||||
function selectSlashSkill(skillId: string) {
|
||||
selectedSlashCommandIndex = slashSuggestionIds.indexOf(`skill:${skillId}`);
|
||||
}
|
||||
|
||||
function runSlashSuggestion(suggestionId: string | undefined) {
|
||||
if (suggestionId?.startsWith('skill:')) {
|
||||
const skillId = suggestionId.slice('skill:'.length);
|
||||
const skill = slashSkillSuggestions.find((item) => item.id === skillId);
|
||||
runSlashSkill(skill ?? { id: skillId, label: skillId });
|
||||
return;
|
||||
}
|
||||
runSlashCommand(suggestionId?.replace(/^command:/, ''));
|
||||
}
|
||||
|
||||
function runSlashSkill(skill: SkillMentionAttrs) {
|
||||
if (!editor || editor.isDestroyed) {
|
||||
inputText = `$${skill.label} `;
|
||||
return;
|
||||
}
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.clearContent()
|
||||
.insertContent([
|
||||
{
|
||||
type: 'skillMention',
|
||||
attrs: {
|
||||
id: skill.id,
|
||||
label: skill.label,
|
||||
description: skill.description,
|
||||
source: skill.source
|
||||
}
|
||||
},
|
||||
{ type: 'text', text: ' ' }
|
||||
])
|
||||
.run();
|
||||
}
|
||||
|
||||
function runSlashCommand(commandId: string | undefined) {
|
||||
if (commandId === 'compact' && (sending || streaming)) return;
|
||||
if (commandId === 'fork' && (sending || streaming)) return;
|
||||
if (commandId === 'compact' && oncompact) {
|
||||
inputText = '';
|
||||
oncompact();
|
||||
return;
|
||||
}
|
||||
if (commandId === 'fork' && onfork) {
|
||||
inputText = '';
|
||||
onfork();
|
||||
return;
|
||||
}
|
||||
if (commandId === 'plan' && onplan) {
|
||||
inputText = '';
|
||||
onplan();
|
||||
@@ -990,7 +1075,7 @@
|
||||
}
|
||||
|
||||
function handleSubmit() {
|
||||
runSlashCommand(slashCommandIds[0]);
|
||||
runSlashSuggestion(slashSuggestionIds[0]);
|
||||
}
|
||||
|
||||
// Allow sending during streaming (message will be enqueued server-side)
|
||||
@@ -1041,9 +1126,11 @@
|
||||
<div
|
||||
class="app-theme app-surface absolute left-2 bottom-full mb-1 z-50 w-60 max-h-40 overflow-y-auto rounded-xl border shadow-xl p-0.5"
|
||||
>
|
||||
<div class="app-muted mb-0.5 px-2 pt-1 pb-0.5 text-[0.625rem] leading-none">
|
||||
{$t('chat.commands')}
|
||||
</div>
|
||||
{#if slashCommandIds.length > 0}
|
||||
<div class="app-muted mb-0.5 px-2 pt-1 pb-0.5 text-[0.625rem] leading-none">
|
||||
{$t('chat.commands')}
|
||||
</div>
|
||||
{/if}
|
||||
{#if slashCommandIds.includes('compact')}
|
||||
<button
|
||||
type="button"
|
||||
@@ -1053,15 +1140,13 @@
|
||||
placement: 'right'
|
||||
}}
|
||||
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
|
||||
{slashCommandIds[selectedSlashCommandIndex] === 'compact'
|
||||
? 'app-interactive-active'
|
||||
: ''} disabled:opacity-50"
|
||||
{selectedSlashCommand('compact') ? 'app-interactive-active' : ''} disabled:opacity-50"
|
||||
disabled={sending || streaming}
|
||||
onmousedown={(e) => e.preventDefault()}
|
||||
onclick={() => {
|
||||
runSlashCommand('compact');
|
||||
}}
|
||||
onmouseenter={() => (selectedSlashCommandIndex = slashCommandIds.indexOf('compact'))}
|
||||
onmouseenter={() => selectSlashCommand('compact')}
|
||||
>
|
||||
<span class="app-icon-muted flex items-center justify-center w-4 shrink-0">
|
||||
<svg class="size-3.5 -rotate-90" viewBox="0 0 20 20" aria-hidden="true">
|
||||
@@ -1104,12 +1189,12 @@
|
||||
placement: 'right'
|
||||
}}
|
||||
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
|
||||
{slashCommandIds[selectedSlashCommandIndex] === 'plan' ? 'app-interactive-active' : ''}"
|
||||
{selectedSlashCommand('plan') ? 'app-interactive-active' : ''}"
|
||||
onmousedown={(e) => e.preventDefault()}
|
||||
onclick={() => {
|
||||
runSlashCommand('plan');
|
||||
}}
|
||||
onmouseenter={() => (selectedSlashCommandIndex = slashCommandIds.indexOf('plan'))}
|
||||
onmouseenter={() => selectSlashCommand('plan')}
|
||||
>
|
||||
<span class="app-icon-muted flex items-center justify-center w-4 shrink-0">
|
||||
<svg
|
||||
@@ -1136,6 +1221,34 @@
|
||||
</span>
|
||||
</button>
|
||||
{/if}
|
||||
{#if slashCommandIds.includes('fork')}
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Fork: clone this chat into a new copy."
|
||||
use:tooltip={{
|
||||
content: 'Clone this chat into a new copy.',
|
||||
placement: 'right'
|
||||
}}
|
||||
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
|
||||
{selectedSlashCommand('fork') ? 'app-interactive-active' : ''} disabled:opacity-50"
|
||||
disabled={sending || streaming}
|
||||
onmousedown={(e) => e.preventDefault()}
|
||||
onclick={() => {
|
||||
runSlashCommand('fork');
|
||||
}}
|
||||
onmouseenter={() => selectSlashCommand('fork')}
|
||||
>
|
||||
<span class="app-icon-muted flex items-center justify-center w-4 shrink-0">
|
||||
<Icon name="chat-fork" size={14} strokeWidth={1.8} />
|
||||
</span>
|
||||
<span class="flex-1 min-w-0 flex items-baseline gap-1.5 overflow-hidden">
|
||||
<span class="truncate">{$t('chat.commandFork')}</span>
|
||||
<span class="app-muted text-[0.625rem] truncate shrink-0">
|
||||
{$t('chat.commandForkDesc')}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
{/if}
|
||||
{#if slashCommandIds.includes('status')}
|
||||
<button
|
||||
type="button"
|
||||
@@ -1145,12 +1258,12 @@
|
||||
placement: 'right'
|
||||
}}
|
||||
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
|
||||
{slashCommandIds[selectedSlashCommandIndex] === 'status' ? 'app-interactive-active' : ''}"
|
||||
{selectedSlashCommand('status') ? 'app-interactive-active' : ''}"
|
||||
onmousedown={(e) => e.preventDefault()}
|
||||
onclick={() => {
|
||||
runSlashCommand('status');
|
||||
}}
|
||||
onmouseenter={() => (selectedSlashCommandIndex = slashCommandIds.indexOf('status'))}
|
||||
onmouseenter={() => selectSlashCommand('status')}
|
||||
>
|
||||
<span class="app-icon-muted flex items-center justify-center w-4 shrink-0">
|
||||
<svg
|
||||
@@ -1184,12 +1297,12 @@
|
||||
placement: 'right'
|
||||
}}
|
||||
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
|
||||
{slashCommandIds[selectedSlashCommandIndex] === 'skills:list' ? 'app-interactive-active' : ''}"
|
||||
{selectedSlashCommand('skills:list') ? 'app-interactive-active' : ''}"
|
||||
onmousedown={(e) => e.preventDefault()}
|
||||
onclick={() => {
|
||||
runSlashCommand('skills:list');
|
||||
}}
|
||||
onmouseenter={() => (selectedSlashCommandIndex = slashCommandIds.indexOf('skills:list'))}
|
||||
onmouseenter={() => selectSlashCommand('skills:list')}
|
||||
>
|
||||
<span class="app-icon-muted flex items-center justify-center w-4 shrink-0">
|
||||
<Icon name="list" size={14} />
|
||||
@@ -1209,13 +1322,12 @@
|
||||
placement: 'right'
|
||||
}}
|
||||
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
|
||||
{slashCommandIds[selectedSlashCommandIndex] === 'skills:create' ? 'app-interactive-active' : ''}"
|
||||
{selectedSlashCommand('skills:create') ? 'app-interactive-active' : ''}"
|
||||
onmousedown={(e) => e.preventDefault()}
|
||||
onclick={() => {
|
||||
runSlashCommand('skills:create');
|
||||
}}
|
||||
onmouseenter={() =>
|
||||
(selectedSlashCommandIndex = slashCommandIds.indexOf('skills:create'))}
|
||||
onmouseenter={() => selectSlashCommand('skills:create')}
|
||||
>
|
||||
<span class="app-icon-muted flex items-center justify-center w-4 shrink-0">
|
||||
<Icon name="plus" size={14} />
|
||||
@@ -1226,6 +1338,36 @@
|
||||
</span>
|
||||
</button>
|
||||
{/if}
|
||||
{#if slashSkillSuggestions.length > 0}
|
||||
<div class="app-muted mb-0.5 px-2 pt-1 pb-0.5 text-[0.625rem] leading-none">Skills</div>
|
||||
{#each slashSkillSuggestions as skill (skill.id)}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Use skill: ${skill.label}`}
|
||||
use:tooltip={{
|
||||
content: skill.description || 'Use this skill in the message.',
|
||||
placement: 'right'
|
||||
}}
|
||||
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
|
||||
{selectedSlashSkill(skill.id) ? 'app-interactive-active' : ''}"
|
||||
onmousedown={(e) => e.preventDefault()}
|
||||
onclick={() => {
|
||||
runSlashSkill(skill);
|
||||
}}
|
||||
onmouseenter={() => selectSlashSkill(skill.id)}
|
||||
>
|
||||
<span class="app-icon-muted flex items-center justify-center w-4 shrink-0">
|
||||
<Icon name="spark" size={13} strokeWidth={1.7} />
|
||||
</span>
|
||||
<span class="flex-1 min-w-0 flex items-baseline gap-1.5 overflow-hidden">
|
||||
<span class="truncate">{skill.label}</span>
|
||||
{#if skill.source && skill.source !== 'workspace'}
|
||||
<span class="app-muted text-[0.625rem] truncate shrink-0">{skill.source}</span>
|
||||
{/if}
|
||||
</span>
|
||||
</button>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
getChat,
|
||||
getChats,
|
||||
deleteChat as apiDeleteChat,
|
||||
forkChat as apiForkChat,
|
||||
sendMessage as apiSendMessage,
|
||||
approveToolCall,
|
||||
cancelTask,
|
||||
@@ -30,6 +31,7 @@
|
||||
import { get } from 'svelte/store';
|
||||
import {
|
||||
currentWorkspace,
|
||||
openChatTab,
|
||||
toolApprovalMode,
|
||||
planMode,
|
||||
streamingBehavior,
|
||||
@@ -728,6 +730,10 @@
|
||||
await handleManualCompact();
|
||||
return;
|
||||
}
|
||||
if (hasChatContent && text === '/fork') {
|
||||
await handleForkChat();
|
||||
return;
|
||||
}
|
||||
if (text === '/plan') {
|
||||
handlePlanCommand();
|
||||
inputText = '';
|
||||
@@ -906,6 +912,23 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function handleForkChat(messageId?: string | null) {
|
||||
if (!chatId || sending || streaming) return;
|
||||
sending = true;
|
||||
inputText = '';
|
||||
const toastId = toast.loading($t('chat.forking'));
|
||||
try {
|
||||
const result = await apiForkChat(chatId, messageId ?? currentMessageId);
|
||||
openChatTab(result.chat_id);
|
||||
toast.success($t('chat.forkDone'), { id: toastId });
|
||||
} catch (err: any) {
|
||||
toast.error(err?.message || $t('chat.forkFailed'), { id: toastId });
|
||||
} finally {
|
||||
sending = false;
|
||||
chatInputEl?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function handlePlanCommand() {
|
||||
planMode.set(!get(planMode));
|
||||
}
|
||||
@@ -1592,6 +1615,7 @@
|
||||
siblingTotal={siblingIds.length}
|
||||
speaking={speakingMessageId === msg.id}
|
||||
onnavigate={(dir) => handleNavigate(msg.id, dir)}
|
||||
onfork={sending || streaming ? undefined : () => handleForkChat(msg.id)}
|
||||
onregenerate={() => handleRegenerate(msg.id)}
|
||||
onedit={(c, o, submit) => handleEditMessage(msg.id, c, o, submit)}
|
||||
onspeak={() => speakMessage(msg.id)}
|
||||
@@ -1645,6 +1669,7 @@
|
||||
tasks={chatTasks}
|
||||
onsend={send}
|
||||
oncompact={handleManualCompact}
|
||||
onfork={handleForkChat}
|
||||
onplan={handlePlanCommand}
|
||||
onstatus={handleStatusCommand}
|
||||
onskillslist={handleSkillsListCommand}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import MessageTimestamp from './MessageTimestamp.svelte';
|
||||
import { fileIconName } from '$lib/utils/fileIcon';
|
||||
import { openFileTab, setFileBrowserCwd, setActiveTab } from '$lib/stores';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
@@ -253,6 +254,7 @@
|
||||
disabled={siblingIndex === 0}
|
||||
onclick={() => onnavigate?.(-1)}
|
||||
aria-label={$t('chat.prevMessage')}
|
||||
use:tooltip={$t('chat.prevMessage')}
|
||||
>
|
||||
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"
|
||||
><path
|
||||
@@ -271,6 +273,7 @@
|
||||
disabled={siblingIndex === siblingTotal - 1}
|
||||
onclick={() => onnavigate?.(1)}
|
||||
aria-label={$t('chat.nextMessage')}
|
||||
use:tooltip={$t('chat.nextMessage')}
|
||||
>
|
||||
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"
|
||||
><path
|
||||
@@ -287,6 +290,7 @@
|
||||
class="p-1 rounded-md text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={startEdit}
|
||||
aria-label={$t('chat.editMessage')}
|
||||
use:tooltip={$t('chat.editMessage')}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
@@ -308,6 +312,7 @@
|
||||
class="p-1 rounded-md text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={copyContent}
|
||||
aria-label={$t('chat.copyMessage')}
|
||||
use:tooltip={copied ? $t('about.copied') : $t('chat.copyMessage')}
|
||||
>
|
||||
{#if copied}
|
||||
<svg
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"files.deleteItemConfirm_other": "{{count}} Elemente löschen?",
|
||||
"files.deleteEntryConfirm": "{{type}} \"{{name}}\" löschen?",
|
||||
"files.moreActions": "Weitere Aktionen",
|
||||
"files.copyPath": "Pfad kopieren",
|
||||
"files.rename": "Umbenennen",
|
||||
"files.download": "Herunterladen",
|
||||
"files.delete": "Löschen",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"files.deleteItemConfirm_other": "Delete {{count}} items?",
|
||||
"files.deleteEntryConfirm": "Delete {{type}} \"{{name}}\"?",
|
||||
"files.moreActions": "More actions",
|
||||
"files.copyPath": "Copy path",
|
||||
"files.rename": "Rename",
|
||||
"files.download": "Download",
|
||||
"files.delete": "Delete",
|
||||
@@ -612,6 +613,8 @@
|
||||
"chat.commandPlan": "Plan mode",
|
||||
"chat.commandPlanOn": "On",
|
||||
"chat.commandPlanOff": "Off",
|
||||
"chat.commandFork": "Fork",
|
||||
"chat.commandForkDesc": "Clone chat",
|
||||
"chat.commandStatus": "Status",
|
||||
"chat.commandStatusDesc": "Context usage, chat id",
|
||||
"chat.statusContextUsage": "Context usage",
|
||||
@@ -624,6 +627,10 @@
|
||||
"chat.compactSkipped": "Nothing to compact yet",
|
||||
"chat.compactFailed": "Failed to compact context",
|
||||
"chat.compactNoChat": "Start a chat before compacting",
|
||||
"chat.forking": "Forking chat...",
|
||||
"chat.forkDone": "Chat forked",
|
||||
"chat.forkFailed": "Failed to fork chat",
|
||||
"chat.forkResponse": "Fork chat",
|
||||
"chat.prevMessage": "Previous message",
|
||||
"chat.nextMessage": "Next message",
|
||||
"chat.editMessage": "Edit message",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"files.deleteItemConfirm_other": "¿Eliminar {{count}} elementos?",
|
||||
"files.deleteEntryConfirm": "¿Eliminar {{type}} \"{{name}}\"?",
|
||||
"files.moreActions": "Más acciones",
|
||||
"files.copyPath": "Copiar ruta",
|
||||
"files.rename": "Renombrar",
|
||||
"files.download": "Descargar",
|
||||
"files.delete": "Eliminar",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"files.deleteItemConfirm_other": "Supprimer {{count}} éléments ?",
|
||||
"files.deleteEntryConfirm": "Supprimer le {{type}} « {{name}} » ?",
|
||||
"files.moreActions": "Plus d'actions",
|
||||
"files.copyPath": "Copier le chemin",
|
||||
"files.rename": "Renommer",
|
||||
"files.download": "Télécharger",
|
||||
"files.delete": "Supprimer",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"files.deleteItemConfirm_other": "{{count}} 件のアイテムを削除しますか?",
|
||||
"files.deleteEntryConfirm": "{{type}}「{{name}}」を削除しますか?",
|
||||
"files.moreActions": "その他の操作",
|
||||
"files.copyPath": "パスをコピー",
|
||||
"files.rename": "名前変更",
|
||||
"files.download": "ダウンロード",
|
||||
"files.delete": "削除",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"files.deleteItemConfirm_other": "{{count}}개 항목을 삭제하시겠습니까?",
|
||||
"files.deleteEntryConfirm": "{{type}} \"{{name}}\"을(를) 삭제하시겠습니까?",
|
||||
"files.moreActions": "추가 작업",
|
||||
"files.copyPath": "경로 복사",
|
||||
"files.rename": "이름 변경",
|
||||
"files.download": "다운로드",
|
||||
"files.delete": "삭제",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"files.deleteItemConfirm_other": "Excluir {{count}} itens?",
|
||||
"files.deleteEntryConfirm": "Excluir {{type}} \"{{name}}\"?",
|
||||
"files.moreActions": "Mais ações",
|
||||
"files.copyPath": "Copiar caminho",
|
||||
"files.rename": "Renomear",
|
||||
"files.download": "Baixar",
|
||||
"files.delete": "Excluir",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"files.deleteItemConfirm_other": "Удалить {{count}} элементов?",
|
||||
"files.deleteEntryConfirm": "Удалить {{type}} \"{{name}}\"?",
|
||||
"files.moreActions": "Ещё действия",
|
||||
"files.copyPath": "Копировать путь",
|
||||
"files.rename": "Переименовать",
|
||||
"files.download": "Скачать",
|
||||
"files.delete": "Удалить",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"files.deleteItemConfirm_other": "确定删除 {{count}} 个项目?",
|
||||
"files.deleteEntryConfirm": "确定删除{{type}}「{{name}}」?",
|
||||
"files.moreActions": "更多操作",
|
||||
"files.copyPath": "复制路径",
|
||||
"files.rename": "重命名",
|
||||
"files.download": "下载",
|
||||
"files.delete": "删除",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"files.deleteItemConfirm_other": "確定刪除 {{count}} 個項目?",
|
||||
"files.deleteEntryConfirm": "確定刪除{{type}}「{{name}}」?",
|
||||
"files.moreActions": "更多操作",
|
||||
"files.copyPath": "複製路徑",
|
||||
"files.rename": "重新命名",
|
||||
"files.download": "下載",
|
||||
"files.delete": "刪除",
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from copy import deepcopy
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
@@ -514,6 +515,79 @@ async def delete_chat(chat_id: str, request: Request):
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
class ForkChatRequest(BaseModel):
|
||||
message_id: Optional[str] = None
|
||||
|
||||
|
||||
@router.post("/{chat_id}/fork")
|
||||
async def fork_chat(chat_id: str, request: Request, body: ForkChatRequest | None = None):
|
||||
"""Clone a completed chat branch through the selected message."""
|
||||
user_id = _get_user(request)
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
if not chat or chat.user_id != user_id:
|
||||
raise HTTPException(404, "chat not found")
|
||||
if await _chat_has_active_generation(chat_id):
|
||||
raise HTTPException(409, "wait for the current response to finish before forking")
|
||||
|
||||
messages = await ChatMessage.get_all_by_chat(chat_id)
|
||||
if not messages:
|
||||
raise HTTPException(400, "chat has no messages to fork")
|
||||
message_by_id = {message.id: message for message in messages}
|
||||
source_message_id = (body.message_id if body else None) or chat.current_message_id or messages[-1].id
|
||||
source_message = message_by_id.get(source_message_id)
|
||||
if not source_message:
|
||||
raise HTTPException(404, "message not found")
|
||||
|
||||
branch: list[ChatMessage] = []
|
||||
seen: set[str] = set()
|
||||
current: ChatMessage | None = source_message
|
||||
while current:
|
||||
if current.id in seen:
|
||||
raise HTTPException(400, "message branch contains a cycle")
|
||||
seen.add(current.id)
|
||||
branch.append(current)
|
||||
current = message_by_id.get(current.parent_id) if current.parent_id else None
|
||||
branch.reverse()
|
||||
|
||||
meta = deepcopy(chat.meta or {})
|
||||
meta["forked_from"] = chat.id
|
||||
meta["forked_from_message_id"] = source_message.id
|
||||
now = now_ms()
|
||||
fork = await Chat.create(
|
||||
user_id=user_id,
|
||||
title=f"{chat.title} (fork)",
|
||||
meta=meta,
|
||||
created_at=now,
|
||||
)
|
||||
if chat.summary:
|
||||
await Chat.update_summary(fork.id, chat.summary, now)
|
||||
|
||||
id_map: dict[str, str] = {}
|
||||
for message in branch:
|
||||
copied = await ChatMessage.create(
|
||||
chat_id=fork.id,
|
||||
role=message.role,
|
||||
content=message.content,
|
||||
parent_id=id_map.get(message.parent_id) if message.parent_id else None,
|
||||
model=message.model,
|
||||
done=message.done,
|
||||
output=deepcopy(message.output),
|
||||
usage=deepcopy(message.usage),
|
||||
meta=deepcopy(message.meta),
|
||||
created_at=message.created_at,
|
||||
)
|
||||
id_map[message.id] = copied.id
|
||||
if message.chat_summary:
|
||||
await ChatMessage.update(copied.id, chat_summary=message.chat_summary)
|
||||
|
||||
await Chat.update_current_message(fork.id, id_map[source_message.id], now)
|
||||
|
||||
from cptr.utils.chat_export import export_chat_to_file
|
||||
|
||||
await export_chat_to_file(fork.id)
|
||||
return {"ok": True, "chat_id": fork.id}
|
||||
|
||||
|
||||
# ── Send a message ──────────────────────────────────────────
|
||||
|
||||
|
||||
|
||||
+17
-1
@@ -1,4 +1,4 @@
|
||||
"""Skills API: lightweight read-only endpoint for the $ mention picker."""
|
||||
"""Skills API: lightweight endpoint for the $ mention picker."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -19,6 +19,14 @@ class SkillResponse(BaseModel):
|
||||
license: Optional[str] = None
|
||||
compatibility: Optional[str] = None
|
||||
managed: bool = False
|
||||
created_by: Optional[str] = None
|
||||
created_from: Optional[str] = None
|
||||
view_count: int = 0
|
||||
use_count: int = 0
|
||||
update_count: int = 0
|
||||
last_viewed_at: Optional[str] = None
|
||||
last_used_at: Optional[str] = None
|
||||
last_updated_at: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("", response_model=list[SkillResponse])
|
||||
@@ -36,6 +44,14 @@ async def list_skills(workspace: str = Query(..., description="Workspace path"))
|
||||
license=s.license,
|
||||
compatibility=s.compatibility,
|
||||
managed=s.managed,
|
||||
created_by=s.created_by,
|
||||
created_from=s.created_from,
|
||||
view_count=s.view_count,
|
||||
use_count=s.use_count,
|
||||
update_count=s.update_count,
|
||||
last_viewed_at=s.last_viewed_at,
|
||||
last_used_at=s.last_used_at,
|
||||
last_updated_at=s.last_updated_at,
|
||||
)
|
||||
for s in skills
|
||||
]
|
||||
+99
-6
@@ -14,7 +14,7 @@ import uuid
|
||||
from cptr.events import EVENTS, publish_event
|
||||
from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS
|
||||
from cptr.utils.context import resolve_compact_token_threshold, should_compact
|
||||
from cptr.utils.skills import discover_skills, load_skill, format_skill_content
|
||||
from cptr.utils.skills import bump_skill_view, discover_skills, load_skill, 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
|
||||
@@ -31,6 +31,7 @@ from cptr.utils.tools import (
|
||||
ALL_TOOLS,
|
||||
clear_active_tasks,
|
||||
create_artifact,
|
||||
disabled_builtin_tool_names,
|
||||
execute_tool,
|
||||
get_tool_list,
|
||||
_fn_to_schema,
|
||||
@@ -163,7 +164,38 @@ def _build_skill_create_prompt(user_request: str) -> str:
|
||||
)
|
||||
|
||||
|
||||
def _apply_skills_create_prompt(messages: list[dict]) -> bool:
|
||||
def _message_has_real_content(message: dict) -> bool:
|
||||
text = _plain_message_text(message.get("content")).strip()
|
||||
if message.get("role") == "user" and text.startswith("/"):
|
||||
return False
|
||||
return bool(
|
||||
text or message.get("tool_calls") or message.get("reasoning_items") or message.get("output")
|
||||
)
|
||||
|
||||
|
||||
def _has_prior_real_chat_content(messages: list[dict], loaded_summary: str | None = None) -> bool:
|
||||
if loaded_summary and loaded_summary.strip():
|
||||
return True
|
||||
last_user_idx = next(
|
||||
(idx for idx in range(len(messages) - 1, -1, -1) if messages[idx].get("role") == "user"),
|
||||
len(messages),
|
||||
)
|
||||
return any(
|
||||
message.get("role") == "user" and _message_has_real_content(message)
|
||||
for message in messages[:last_user_idx]
|
||||
)
|
||||
|
||||
|
||||
def _build_skill_create_gate_prompt() -> str:
|
||||
return (
|
||||
"[/skills:create] The user tried to create a skill before this chat had "
|
||||
"any prior real content. Explain briefly that skill creation needs an "
|
||||
"existing chat with the workflow or source material already in it, then "
|
||||
"ask them to continue in a chat with content first."
|
||||
)
|
||||
|
||||
|
||||
def _apply_skills_create_prompt(messages: list[dict], *, allowed: bool) -> bool:
|
||||
for message in reversed(messages):
|
||||
if message.get("role") != "user":
|
||||
continue
|
||||
@@ -171,7 +203,11 @@ def _apply_skills_create_prompt(messages: list[dict]) -> bool:
|
||||
match = SKILLS_CREATE_RE.match(text.strip())
|
||||
if not match:
|
||||
return False
|
||||
message["content"] = _build_skill_create_prompt(match.group(1) or "")
|
||||
message["content"] = (
|
||||
_build_skill_create_prompt(match.group(1) or "")
|
||||
if allowed
|
||||
else _build_skill_create_gate_prompt()
|
||||
)
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -1315,6 +1351,16 @@ async def run_chat_task(
|
||||
content = (msg.content or "") if msg else ""
|
||||
output_items: list[dict] = list(msg.output or []) if msg else []
|
||||
text_buffer = "" # Accumulates text between tool calls
|
||||
task_completed_success = False
|
||||
review_messages: list[dict] = []
|
||||
review_model_connection: dict | None = None
|
||||
review_model_name = ""
|
||||
review_chat_params: dict = {}
|
||||
review_builtin_tools: dict | None = None
|
||||
loaded_skill_names: set[str] = set()
|
||||
tool_names_used: set[str] = set()
|
||||
skill_create_requested = False
|
||||
skill_authoring_allowed = False
|
||||
|
||||
logger.info(
|
||||
"[task %s] start: existing content=%d chars, output=%d items",
|
||||
@@ -1391,7 +1437,8 @@ async def run_chat_task(
|
||||
await Chat.update_meta(chat_id, meta, now_ms())
|
||||
|
||||
async def _run_agent_target(agent_target: AgentModelTarget):
|
||||
nonlocal content, text_buffer
|
||||
nonlocal content, text_buffer, task_completed_success, skill_authoring_allowed
|
||||
nonlocal skill_create_requested
|
||||
from cptr.utils.agents.claude_code import run_claude_code_agent
|
||||
from cptr.utils.agents.cline import run_cline_agent
|
||||
from cptr.utils.agents.codex import run_codex_agent
|
||||
@@ -1402,7 +1449,10 @@ async def run_chat_task(
|
||||
chat_obj = await Chat.get_by_id(chat_id)
|
||||
chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
|
||||
messages, loaded_summary = await _load_message_history(chat_id, message_id)
|
||||
_apply_skills_create_prompt(messages)
|
||||
skill_authoring_allowed = _has_prior_real_chat_content(messages, loaded_summary)
|
||||
skill_create_requested = _apply_skills_create_prompt(
|
||||
messages, allowed=skill_authoring_allowed
|
||||
)
|
||||
memory_message, memory_files = _memory_recall_inputs(messages, regeneration_prompt)
|
||||
system = await _load_system_prompt(
|
||||
workspace,
|
||||
@@ -1629,6 +1679,7 @@ async def run_chat_task(
|
||||
data={"workspace": event_workspace, "preview": preview},
|
||||
message=preview,
|
||||
)
|
||||
task_completed_success = True
|
||||
return
|
||||
|
||||
flushed_item = _flush_text()
|
||||
@@ -1669,7 +1720,10 @@ async def run_chat_task(
|
||||
chat_models_config = {}
|
||||
builtin_tools = resolve_builtin_tools_config(chat_models_config, model, configured_model)
|
||||
messages, loaded_summary = await _load_message_history(chat_id, message_id)
|
||||
_apply_skills_create_prompt(messages)
|
||||
skill_authoring_allowed = _has_prior_real_chat_content(messages, loaded_summary)
|
||||
skill_create_requested = _apply_skills_create_prompt(
|
||||
messages, allowed=skill_authoring_allowed
|
||||
)
|
||||
memory_message, memory_files = _memory_recall_inputs(messages, regeneration_prompt)
|
||||
system = await _load_system_prompt(
|
||||
workspace,
|
||||
@@ -1684,6 +1738,8 @@ async def run_chat_task(
|
||||
if regeneration_prompt:
|
||||
messages.append({"role": "user", "content": regeneration_prompt})
|
||||
tools = await get_tool_list(builtin_tools=builtin_tools)
|
||||
if not skill_authoring_allowed:
|
||||
tools = [t for t in tools if t["name"] != "manage_skill"]
|
||||
|
||||
# Remove view_skill tool if no skills are available
|
||||
skills = discover_skills(workspace)
|
||||
@@ -1717,6 +1773,8 @@ async def run_chat_task(
|
||||
if skill:
|
||||
skill_blocks.append(format_skill_content(skill))
|
||||
_activated_skills.add(sid) # mark as activated for dedup
|
||||
loaded_skill_names.add(sid)
|
||||
bump_skill_view(workspace, sid, skill.source)
|
||||
if skill_blocks:
|
||||
system += "\n\n" + "\n\n".join(skill_blocks)
|
||||
|
||||
@@ -1733,6 +1791,14 @@ async def run_chat_task(
|
||||
logger.info(
|
||||
"[task %s] plan mode active, %d tools available", message_id[:8], len(tools)
|
||||
)
|
||||
review_messages = messages
|
||||
review_model_connection = connection
|
||||
review_model_name = model
|
||||
review_chat_params = {
|
||||
**chat_params,
|
||||
"subagent": bool(chat_obj and (chat_obj.meta or {}).get("subagent")),
|
||||
}
|
||||
review_builtin_tools = builtin_tools
|
||||
|
||||
# Tool approval mode: 'ask' | 'auto' | 'full'
|
||||
# ask = require approval for ALL tools (including reads)
|
||||
@@ -1959,6 +2025,7 @@ async def run_chat_task(
|
||||
data={"workspace": event_workspace, "preview": preview},
|
||||
message=preview,
|
||||
)
|
||||
task_completed_success = True
|
||||
return
|
||||
|
||||
# ── Process collected tool calls ────────────────────
|
||||
@@ -1987,6 +2054,11 @@ async def run_chat_task(
|
||||
needs_approval = None
|
||||
for tc in pending_calls:
|
||||
name = tc["name"]
|
||||
tool_names_used.add(name)
|
||||
if name == "view_skill":
|
||||
skill_name = str(tc.get("arguments", {}).get("skill_name") or "").strip()
|
||||
if skill_name:
|
||||
loaded_skill_names.add(skill_name)
|
||||
tool = ALL_TOOLS.get(name)
|
||||
should_auto = approval_mode == "full" or (
|
||||
approval_mode == "auto" and tool and tool["auto"]
|
||||
@@ -2190,6 +2262,7 @@ async def run_chat_task(
|
||||
data={"workspace": event_workspace, "preview": preview},
|
||||
message=preview,
|
||||
)
|
||||
task_completed_success = True
|
||||
return
|
||||
|
||||
# Max iterations reached
|
||||
@@ -2320,6 +2393,26 @@ async def run_chat_task(
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("[memory] Failed to review conversation", exc_info=True)
|
||||
try:
|
||||
from cptr.utils.skills import review_skills_after_turn
|
||||
|
||||
await review_skills_after_turn(
|
||||
workspace=workspace,
|
||||
conversation_messages=review_messages,
|
||||
assistant_reply=content,
|
||||
model_connection=review_model_connection,
|
||||
model=review_model_name,
|
||||
loaded_skill_names=loaded_skill_names,
|
||||
tool_names=tool_names_used,
|
||||
skill_create_requested=skill_create_requested,
|
||||
plan_mode=bool(review_chat_params.get("plan_mode")),
|
||||
subagent=bool(review_chat_params.get("subagent")),
|
||||
skills_enabled=task_completed_success
|
||||
and skill_authoring_allowed
|
||||
and "manage_skill" not in disabled_builtin_tool_names(review_builtin_tools),
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("[skills] Failed to review conversation", exc_info=True)
|
||||
# Process any pending user prompts or internal subagent results.
|
||||
try:
|
||||
await process_pending_chat_inputs(chat_id, user_id, workspace)
|
||||
|
||||
+349
-1
@@ -14,10 +14,16 @@ See: https://agentskills.io/specification
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Literal
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Literal
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
@@ -43,6 +49,20 @@ GLOBAL_SKILL_DIRS = [
|
||||
MANAGED_WORKSPACE_SKILL_DIR = ".cptr/skills"
|
||||
MANAGED_GLOBAL_SKILL_DIR = Path.home() / ".cptr" / "skills"
|
||||
ALLOWED_BUNDLE_DIRS = {"references", "templates", "scripts", "assets"}
|
||||
DEFAULT_SKILL_SETTINGS: dict[str, Any] = {
|
||||
"background_review_enabled": True,
|
||||
"review_interval_turns": 10,
|
||||
}
|
||||
SKILL_USAGE_DEFAULT: dict[str, Any] = {
|
||||
"created_from": None,
|
||||
"view_count": 0,
|
||||
"use_count": 0,
|
||||
"update_count": 0,
|
||||
"last_viewed_at": None,
|
||||
"last_used_at": None,
|
||||
"last_updated_at": None,
|
||||
}
|
||||
USAGE_FILE_NAME = "usage.json"
|
||||
|
||||
# Directories to skip during scanning
|
||||
_SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv"}
|
||||
@@ -69,6 +89,14 @@ class SkillMeta:
|
||||
metadata: dict | None = None
|
||||
allowed_tools: str | None = None
|
||||
managed: bool = False
|
||||
created_by: str | None = None
|
||||
created_from: str | None = None
|
||||
view_count: int = 0
|
||||
use_count: int = 0
|
||||
update_count: int = 0
|
||||
last_viewed_at: str | None = None
|
||||
last_used_at: str | None = None
|
||||
last_updated_at: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -133,6 +161,115 @@ def parse_frontmatter(text: str) -> tuple[dict, str]:
|
||||
return {}, body
|
||||
|
||||
|
||||
def _usage_path(workspace: str, source: str) -> Path:
|
||||
if source == "global":
|
||||
return MANAGED_GLOBAL_SKILL_DIR.expanduser().parent / USAGE_FILE_NAME
|
||||
if not workspace:
|
||||
raise ValueError("workspace is required for workspace usage")
|
||||
return Path(workspace).expanduser().resolve() / ".cptr" / USAGE_FILE_NAME
|
||||
|
||||
|
||||
def read_usage(workspace: str, source: str = "workspace") -> dict[str, Any]:
|
||||
path = _usage_path(workspace, source)
|
||||
if not path.is_file():
|
||||
return {"version": 1, "skills": {}}
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return {"version": 1, "skills": {}}
|
||||
if not isinstance(data, dict):
|
||||
return {"version": 1, "skills": {}}
|
||||
skills = data.get("skills")
|
||||
if not isinstance(skills, dict):
|
||||
skills = {}
|
||||
return {"version": 1, "skills": skills}
|
||||
|
||||
|
||||
def write_usage(workspace: str, source: str, data: dict[str, Any]) -> None:
|
||||
path = _usage_path(workspace, source)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_name(f".{path.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def bump_skill_view(workspace: str, name: str, source: str = "workspace", *, used: bool = True) -> None:
|
||||
try:
|
||||
data = read_usage(workspace, source)
|
||||
skills = data.setdefault("skills", {})
|
||||
rec = skills.setdefault(name, dict(SKILL_USAGE_DEFAULT))
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
rec["view_count"] = int(rec.get("view_count") or 0) + 1
|
||||
rec["last_viewed_at"] = now
|
||||
if used:
|
||||
rec["use_count"] = int(rec.get("use_count") or 0) + 1
|
||||
rec["last_used_at"] = now
|
||||
write_usage(workspace, source, data)
|
||||
except Exception:
|
||||
logger.debug("[skills] Failed to bump view usage for %s", name, exc_info=True)
|
||||
|
||||
|
||||
def bump_skill_update(
|
||||
workspace: str,
|
||||
name: str,
|
||||
source: str = "workspace",
|
||||
*,
|
||||
created_from: str | None = None,
|
||||
) -> None:
|
||||
try:
|
||||
data = read_usage(workspace, source)
|
||||
skills = data.setdefault("skills", {})
|
||||
rec = skills.setdefault(name, dict(SKILL_USAGE_DEFAULT))
|
||||
rec["update_count"] = int(rec.get("update_count") or 0) + 1
|
||||
rec["last_updated_at"] = datetime.now(timezone.utc).isoformat()
|
||||
if created_from and not rec.get("created_from"):
|
||||
rec["created_from"] = created_from
|
||||
write_usage(workspace, source, data)
|
||||
except Exception:
|
||||
logger.debug("[skills] Failed to bump update usage for %s", name, exc_info=True)
|
||||
|
||||
|
||||
def _frontmatter_bounds(content: str) -> tuple[dict, str] | None:
|
||||
if not content.startswith("---\n"):
|
||||
return None
|
||||
match = re.search(r"\n---\s*\n", content[4:])
|
||||
if not match:
|
||||
return None
|
||||
end = match.start() + 4
|
||||
fm_text = content[4:end]
|
||||
body = content[match.end() + 4 :]
|
||||
try:
|
||||
fm = yaml.safe_load(fm_text) or {}
|
||||
except yaml.YAMLError:
|
||||
fm = {}
|
||||
return fm if isinstance(fm, dict) else {}, body
|
||||
|
||||
|
||||
def _with_skill_metadata(
|
||||
content: str,
|
||||
*,
|
||||
created_from: str | None = None,
|
||||
preserve_created: dict | None = None,
|
||||
) -> str:
|
||||
parsed = _frontmatter_bounds(content)
|
||||
if not parsed:
|
||||
return content.strip() + "\n"
|
||||
fm, body = parsed
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
if preserve_created:
|
||||
for key in ("created_by", "created_from", "created_at"):
|
||||
if preserve_created.get(key) and not fm.get(key):
|
||||
fm[key] = preserve_created[key]
|
||||
if created_from:
|
||||
fm.setdefault("created_by", "computer")
|
||||
fm.setdefault("created_from", created_from)
|
||||
fm.setdefault("created_at", now)
|
||||
if fm.get("created_by") == "computer" or created_from or preserve_created:
|
||||
fm["updated_at"] = now
|
||||
frontmatter = yaml.safe_dump(fm, sort_keys=False, allow_unicode=True).strip()
|
||||
return f"---\n{frontmatter}\n---\n{body.lstrip()}".strip() + "\n"
|
||||
|
||||
|
||||
# ── Name validation ─────────────────────────────────────────
|
||||
|
||||
_NAME_RE = re.compile(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$")
|
||||
@@ -197,6 +334,7 @@ def _scan_skills_dir(skills_dir: Path, source: str, workspace: str = "") -> list
|
||||
return results
|
||||
|
||||
dirs_scanned = 0
|
||||
usage = read_usage(workspace, source).get("skills", {})
|
||||
try:
|
||||
for item in sorted(skills_dir.iterdir()):
|
||||
if dirs_scanned >= _MAX_SCAN_DIRS:
|
||||
@@ -236,6 +374,9 @@ def _scan_skills_dir(skills_dir: Path, source: str, workspace: str = "") -> list
|
||||
warnings = validate_name(name, item.name)
|
||||
for w in warnings:
|
||||
logger.warning("[skills] %s: %s", skill_md, w)
|
||||
rec = usage.get(name) if isinstance(usage, dict) else {}
|
||||
if not isinstance(rec, dict):
|
||||
rec = {}
|
||||
|
||||
results.append(
|
||||
SkillMeta(
|
||||
@@ -248,6 +389,14 @@ def _scan_skills_dir(skills_dir: Path, source: str, workspace: str = "") -> list
|
||||
metadata=fm.get("metadata") if isinstance(fm.get("metadata"), dict) else None,
|
||||
allowed_tools=fm.get("allowed-tools"),
|
||||
managed=_is_managed_skill(skill_md, workspace),
|
||||
created_by=fm.get("created_by"),
|
||||
created_from=fm.get("created_from"),
|
||||
view_count=int(rec.get("view_count") or 0),
|
||||
use_count=int(rec.get("use_count") or 0),
|
||||
update_count=int(rec.get("update_count") or 0),
|
||||
last_viewed_at=rec.get("last_viewed_at"),
|
||||
last_used_at=rec.get("last_used_at"),
|
||||
last_updated_at=rec.get("last_updated_at"),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -417,8 +566,10 @@ def create_managed_skill(
|
||||
name: str,
|
||||
content: str,
|
||||
scope: Literal["workspace", "global"] = "workspace",
|
||||
created_from: str | None = None,
|
||||
) -> dict:
|
||||
name = _validate_skill_name(name)
|
||||
content = _with_skill_metadata(content, created_from=created_from)
|
||||
_validate_skill_content(name, content)
|
||||
if any(skill.name == name for skill in discover_skills(workspace)):
|
||||
raise ValueError(f"skill '{name}' already exists")
|
||||
@@ -427,9 +578,31 @@ def create_managed_skill(
|
||||
if skill_md.exists():
|
||||
raise ValueError(f"skill '{name}' already exists")
|
||||
_write_text_atomic(skill_md, content.strip() + "\n")
|
||||
if created_from:
|
||||
bump_skill_update(workspace, name, scope, created_from=created_from)
|
||||
return {"success": True, "name": name, "location": str(skill_md.resolve())}
|
||||
|
||||
|
||||
def update_managed_skill(workspace: str, name: str, content: str) -> dict:
|
||||
name = _validate_skill_name(name)
|
||||
skill_dir = _managed_skill_dir(workspace, name)
|
||||
skill_md = skill_dir / "SKILL.md"
|
||||
old = skill_md.read_text(encoding="utf-8", errors="replace") if skill_md.exists() else ""
|
||||
old_fm, _ = parse_frontmatter(old)
|
||||
content = _with_skill_metadata(content, preserve_created=old_fm)
|
||||
_validate_skill_content(name, content)
|
||||
_write_text_atomic(skill_md, content.strip() + "\n")
|
||||
source = "global" if skill_dir.is_relative_to(MANAGED_GLOBAL_SKILL_DIR.expanduser().resolve()) else "workspace"
|
||||
bump_skill_update(workspace, name, source)
|
||||
return {"success": True, "name": name, "location": str(skill_md.resolve())}
|
||||
|
||||
|
||||
def delete_managed_skill(workspace: str, name: str) -> dict:
|
||||
skill_dir = _managed_skill_dir(workspace, name)
|
||||
shutil.rmtree(skill_dir)
|
||||
return {"success": True, "name": name}
|
||||
|
||||
|
||||
def _managed_skill_dir(workspace: str, name: str) -> Path:
|
||||
name = _validate_skill_name(name)
|
||||
skill = next((s for s in discover_skills(workspace) if s.name == name), None)
|
||||
@@ -459,6 +632,8 @@ def write_managed_skill_file(
|
||||
if not target.is_relative_to(skill_dir):
|
||||
raise ValueError("file_path escapes the skill")
|
||||
_write_text_atomic(target, file_content)
|
||||
source = "global" if skill_dir.is_relative_to(MANAGED_GLOBAL_SKILL_DIR.expanduser().resolve()) else "workspace"
|
||||
bump_skill_update(workspace, name, source)
|
||||
return {"success": True, "name": name, "location": str(target)}
|
||||
|
||||
|
||||
@@ -520,3 +695,176 @@ def format_skill_content(skill: SkillContent) -> str:
|
||||
|
||||
parts.append("</skill_content>")
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
async def get_skill_settings() -> dict[str, Any]:
|
||||
try:
|
||||
from cptr.models import Config
|
||||
|
||||
raw = await Config.get_namespace("skills")
|
||||
except Exception:
|
||||
raw = {}
|
||||
settings = dict(DEFAULT_SKILL_SETTINGS)
|
||||
for key, value in raw.items():
|
||||
short = key.removeprefix("skills.")
|
||||
settings[short] = value
|
||||
try:
|
||||
settings["review_interval_turns"] = max(1, int(settings["review_interval_turns"]))
|
||||
except (TypeError, ValueError):
|
||||
settings["review_interval_turns"] = DEFAULT_SKILL_SETTINGS["review_interval_turns"]
|
||||
settings["background_review_enabled"] = settings.get("background_review_enabled") not in (
|
||||
False,
|
||||
"false",
|
||||
"0",
|
||||
)
|
||||
return settings
|
||||
|
||||
|
||||
async def review_skills_after_turn(
|
||||
*,
|
||||
workspace: str,
|
||||
conversation_messages: list[dict[str, Any]],
|
||||
assistant_reply: str,
|
||||
model_connection: dict | None,
|
||||
model: str,
|
||||
loaded_skill_names: set[str],
|
||||
tool_names: set[str],
|
||||
skill_create_requested: bool,
|
||||
plan_mode: bool,
|
||||
subagent: bool,
|
||||
skills_enabled: bool,
|
||||
) -> None:
|
||||
if (
|
||||
not workspace
|
||||
or not assistant_reply.strip()
|
||||
or not model_connection
|
||||
or plan_mode
|
||||
or subagent
|
||||
or not skills_enabled
|
||||
):
|
||||
return
|
||||
settings = await get_skill_settings()
|
||||
if not settings["background_review_enabled"]:
|
||||
return
|
||||
if not tool_names and not skill_create_requested and not loaded_skill_names:
|
||||
return
|
||||
user_turns = sum(1 for message in conversation_messages if message.get("role") == "user")
|
||||
if user_turns <= 0 or user_turns % int(settings["review_interval_turns"]) != 0:
|
||||
return
|
||||
asyncio.create_task(
|
||||
run_skill_review(
|
||||
workspace=workspace,
|
||||
conversation_messages=list(conversation_messages),
|
||||
assistant_reply=assistant_reply,
|
||||
model_connection=dict(model_connection),
|
||||
model=model,
|
||||
loaded_skill_names=set(loaded_skill_names),
|
||||
tool_names=set(tool_names),
|
||||
skill_create_requested=skill_create_requested,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def run_skill_review(
|
||||
*,
|
||||
workspace: str,
|
||||
conversation_messages: list[dict[str, Any]],
|
||||
assistant_reply: str,
|
||||
model_connection: dict,
|
||||
model: str,
|
||||
loaded_skill_names: set[str],
|
||||
tool_names: set[str],
|
||||
skill_create_requested: bool,
|
||||
) -> None:
|
||||
try:
|
||||
from cptr.utils.ai import chat_completion
|
||||
from cptr.utils.chat_task import _default_base_url
|
||||
from cptr.utils.config import _get_jwt_secret
|
||||
from cptr.utils.crypto import decrypt_key
|
||||
from cptr.utils.json_parser import extract_json
|
||||
from cptr.utils.memory import summarize_recent_conversation
|
||||
|
||||
skills = discover_skills(workspace)
|
||||
transcript = summarize_recent_conversation(conversation_messages, assistant_reply)
|
||||
catalog = "\n".join(
|
||||
f"- {skill.name} ({skill.source}, {'managed' if skill.managed else 'read-only'}): {skill.description}"
|
||||
for skill in skills[:80]
|
||||
) or "- none"
|
||||
loaded_blocks = []
|
||||
for name in sorted(loaded_skill_names):
|
||||
skill = load_skill(workspace, name)
|
||||
if not skill or not skill.managed:
|
||||
continue
|
||||
content = skill.content
|
||||
if len(content) > 5000:
|
||||
content = content[:4500] + "\n...(truncated)..."
|
||||
loaded_blocks.append(f"## {name}\n{content}")
|
||||
loaded_context = "\n\n".join(loaded_blocks) or "None."
|
||||
prompt = (
|
||||
"Review the completed conversation and decide whether Computer learned a reusable "
|
||||
"workflow that should become or improve a skill. Return ONLY JSON with this shape:\n"
|
||||
'{"actions":[{"action":"create|update|write_file|none","name":"skill-name",'
|
||||
'"reason":"short reason","content":"full SKILL.md for create/update",'
|
||||
'"file_path":"references/example.md","file_content":"support file content"}]}\n\n'
|
||||
"Rules:\n"
|
||||
"- Use action=none when nothing durable was learned.\n"
|
||||
"- Prefer updating a loaded managed skill, then another managed skill, then writing a support file, then creating one new workspace skill.\n"
|
||||
"- Create or update only for reusable procedures, user corrections, durable commands, verification steps, or workflows likely to recur.\n"
|
||||
"- Do not save one-off task summaries, transient local failures, secrets, vague preferences, or project facts better suited for memory.\n"
|
||||
"- Never delete. Never update read-only skills. Never write outside references/, templates/, scripts/, or assets/.\n\n"
|
||||
f"Workspace: {workspace}\n"
|
||||
f"Tools used this turn: {', '.join(sorted(tool_names)) or 'none'}\n"
|
||||
f"/skills:create requested: {skill_create_requested}\n"
|
||||
f"Loaded skills: {', '.join(sorted(loaded_skill_names)) or 'none'}\n\n"
|
||||
f"Available skills:\n{catalog}\n\n"
|
||||
f"Loaded managed skill contents:\n{loaded_context}\n\n"
|
||||
f"Conversation:\n{transcript}"
|
||||
)
|
||||
provider = model_connection["provider"]
|
||||
api_key = decrypt_key(model_connection.get("api_key", ""), _get_jwt_secret())
|
||||
base_url = model_connection.get("base_url") or _default_base_url(provider)
|
||||
text = await chat_completion(
|
||||
provider=provider,
|
||||
base_url=base_url,
|
||||
api_key=api_key,
|
||||
model=model,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
system="You are Computer's private skill reviewer. Return only valid JSON.",
|
||||
max_tokens=1800,
|
||||
api_type=model_connection.get("api_type", "chat_completions"),
|
||||
)
|
||||
parsed = extract_json(text)
|
||||
if not isinstance(parsed, dict):
|
||||
return
|
||||
actions = parsed.get("actions")
|
||||
if not isinstance(actions, list):
|
||||
return
|
||||
managed = {skill.name for skill in discover_skills(workspace) if skill.managed}
|
||||
for action in actions[:3]:
|
||||
if not isinstance(action, dict):
|
||||
continue
|
||||
kind = action.get("action")
|
||||
name = str(action.get("name") or "").strip()
|
||||
if kind == "none":
|
||||
continue
|
||||
if kind == "create":
|
||||
content = action.get("content")
|
||||
if isinstance(content, str) and content.strip():
|
||||
create_managed_skill(
|
||||
workspace,
|
||||
name,
|
||||
content,
|
||||
scope="workspace",
|
||||
created_from="background_review",
|
||||
)
|
||||
elif kind == "update":
|
||||
content = action.get("content")
|
||||
if name in managed and isinstance(content, str) and content.strip():
|
||||
update_managed_skill(workspace, name, content)
|
||||
elif kind == "write_file":
|
||||
file_path = action.get("file_path")
|
||||
file_content = action.get("file_content")
|
||||
if name in managed and isinstance(file_path, str) and isinstance(file_content, str):
|
||||
write_managed_skill_file(workspace, name, file_path, file_content)
|
||||
except Exception:
|
||||
logger.debug("[skills] Failed to review conversation for skills", exc_info=True)
|
||||
+19
-9
@@ -1611,7 +1611,7 @@ async def view_skill(
|
||||
"""Load the full instructions and resource listing for an available skill.
|
||||
:param skill_name: The name of the skill to load (from the <available_skills> catalog).
|
||||
"""
|
||||
from cptr.utils.skills import load_skill, format_skill_content
|
||||
from cptr.utils.skills import bump_skill_view, load_skill, format_skill_content
|
||||
|
||||
# Deduplication: if already activated, return short notice
|
||||
if skill_name in _activated_skills:
|
||||
@@ -1622,11 +1622,12 @@ async def view_skill(
|
||||
return f"Error: skill '{skill_name}' not found. Check <available_skills> for valid names."
|
||||
|
||||
_activated_skills.add(skill_name)
|
||||
bump_skill_view(workspace, skill_name, skill.source)
|
||||
return format_skill_content(skill)
|
||||
|
||||
|
||||
async def manage_skill(
|
||||
action: Literal["create", "write_file"],
|
||||
action: Literal["create", "update", "write_file", "delete"],
|
||||
name: str,
|
||||
content: Optional[str] = None,
|
||||
scope: Literal["workspace", "global"] = "workspace",
|
||||
@@ -1635,26 +1636,35 @@ async def manage_skill(
|
||||
*,
|
||||
__context__: dict,
|
||||
) -> str:
|
||||
"""Create Computer-managed skills and supporting bundle files.
|
||||
"""Create, update, or delete Computer-managed skills and supporting bundle files.
|
||||
|
||||
Use this only when the user asks to create a reusable skill. New skills
|
||||
default to the current workspace. For supporting files, write only under
|
||||
references/, templates/, scripts/, or assets/.
|
||||
:param action: "create" to write SKILL.md, or "write_file" to add a bundle file.
|
||||
Use this only when the user asks to create, update, or delete a reusable skill.
|
||||
New skills default to the current workspace. For supporting files, write only
|
||||
under references/, templates/, scripts/, or assets/.
|
||||
:param action: "create" to write SKILL.md, "update" to replace SKILL.md, "write_file" to add a bundle file, or "delete" to remove a managed skill.
|
||||
:param name: Lowercase hyphenated skill name.
|
||||
:param content: Full SKILL.md content for action="create".
|
||||
:param content: Full SKILL.md content for action="create" or action="update".
|
||||
:param scope: "workspace" for .cptr/skills, or "global" for ~/.cptr/skills.
|
||||
:param file_path: Relative bundle path for action="write_file".
|
||||
:param file_content: File content for action="write_file".
|
||||
"""
|
||||
from cptr.utils.skills import create_managed_skill, write_managed_skill_file
|
||||
from cptr.utils.skills import (
|
||||
create_managed_skill,
|
||||
delete_managed_skill,
|
||||
update_managed_skill,
|
||||
write_managed_skill_file,
|
||||
)
|
||||
|
||||
workspace = __context__.get("workspace", "")
|
||||
try:
|
||||
if action == "create":
|
||||
result = create_managed_skill(workspace, name, content or "", scope)
|
||||
elif action == "update":
|
||||
result = update_managed_skill(workspace, name, content or "")
|
||||
elif action == "write_file":
|
||||
result = write_managed_skill_file(workspace, name, file_path or "", file_content)
|
||||
elif action == "delete":
|
||||
result = delete_managed_skill(workspace, name)
|
||||
else:
|
||||
result = {"success": False, "error": f"unsupported action '{action}'"}
|
||||
except Exception as e:
|
||||
|
||||
Reference in new issue
Block a user