25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(ai): load skills on demand via listing and use_skill tool
Abeautifulsnow504ef7e1c6f5
diff --git a/apps/desktop/src/components/editor/AiAssistant.vue b/apps/desktop/src/components/editor/AiAssistant.vueindex a280ab27c6..5e978a82ea 100644--- a/apps/desktop/src/components/editor/AiAssistant.vue+++ b/apps/desktop/src/components/editor/AiAssistant.vue@@ -1,3 +1,45 @@+<script lang="ts">+// Aliased because `<script setup>` imports the same binding and the two blocks+// share one module scope.+import { reactive as createReactiveMap } from "vue";++/**+ * Per-conversation skill state, shared by every panel instance.+ *+ * Declared in a plain `<script>` block — not in `<script setup>`, where the+ * bindings would be re-created per instance — because this has to outlive the+ * component: closing the AI panel unmounts it, and the chip's "loaded" state+ * (prd 09-30 Req 13) and the one-time hint flag (Req 14) must survive reopening+ * the same conversation.+ */++/** A skill body this conversation has loaded, kept for the life of the app run. */+interface LoadedSkillBody {+ id: string;+ name: string;+ source: "custom" | "default";+ content: string;+}++/**+ * Which skills each conversation has loaded. This is the fact the transcript+ * persists (see `AiChatMessage.loadedSkillIds`); the bodies do not go to disk at+ * all, so this map plus the persisted ids are what the chips read.+ */+const conversationLoadedSkillIds = createReactiveMap(new Map<string, string[]>());+/**+ * Bodies loaded in this app run, session-only by design. A forced load can carry+ * up to 1 MiB per skill, and the stored message array is an unbounded column that+ * is re-serialized in full on every save — so only the ids above are persisted+ * (the same shape as the #10058 selection footprint in+ * `crates/dbx-ai-provider/src/ai.rs`). The body is re-read from disk when a+ * request actually needs it.+ */+const conversationLoadedSkillBodies = createReactiveMap(new Map<string, LoadedSkillBody[]>());+/** Conversations whose one-time hint has already been shown. */+const conversationSkillHintSeen = new Set<string>();+</script>+<script setup lang="ts">import { computed, defineAsyncComponent, h, nextTick, onMounted, onUnmounted, reactive, ref, toRaw, watch, type Component } from "vue";import { uuid } from "@/lib/common/utils";@@ -65,9 +107,10 @@ import { useConnectionStore } from "@/stores/connectionStore";import { useSavedSqlStore } from "@/stores/savedSqlStore";import { usePromptTemplateStore } from "@/stores/promptTemplateStore";import { useUserSkillStore } from "@/stores/userSkillStore";-import { buildSelectedSkillChips, capSkillsToCharLimit, removeSkillIds, userSkillSourceOfId } from "@/lib/ai/userSkillSelection";+import { buildSelectedSkillChips, duplicateSkillNames, removeSkillIds, userSkillSourceOfId } from "@/lib/ai/userSkillSelection";import { aiConversationTypographyCssVariables } from "@/lib/ai/aiTypography";-import { ACTIVE_SKILLS_TOTAL_MAX, type ReadUserSkill, type ReadUserSkillFailure, type UserSkillFailureReason, type UserSkillRootSettings } from "@/types/userSkills";+import { buildSkillListing, buildSkillListingLines } from "@/lib/ai/skillListing";+import { type ReadUserSkillFailure, type UserSkillFailureReason, type UserSkillMeta, type UserSkillRootSettings, type UserSkillsListResult } from "@/types/userSkills";import { supportsAiAssistantContext } from "@/lib/database/databaseFeatureSupport";import ConnectionIcon from "@/components/icons/ConnectionIcon.vue";import ConnectionTreeSelect from "@/components/connection/ConnectionTreeSelect.vue";@@ -127,7 +170,7 @@ import {selectionContextBudgetError,truncateTextAttachmentContent,} from "@/lib/ai/aiAttachments";-import { isAiConfigModelCandidate } from "@/lib/ai/aiConfigCandidates";+import { isAiConfigModelCandidate, isCliProvider } from "@/lib/ai/aiConfigCandidates";import { deleteConversationWithCancellation, stopAiGenerationWithFallback } from "@/lib/ai/aiConversationLifecycle";import { AiGenerationGuard } from "@/lib/ai/aiGenerationGuard";import { applyStatusEvent, createGenerationStatus, createStatusTicker, liveAnnouncementText, markCancelling, shouldShowLongRunningHint, statusText, toolLabel, STATUS_IDLE_THRESHOLD_MS, type AiGenerationStatus } from "@/lib/ai/aiGenerationStatus";@@ -167,7 +210,7 @@ import { buildAiAgentStepItems, formatAgentToolName, formatToolDurationMs, toolCimport { createAiShikiCodeHighlighter, type AiCodeHighlighter } from "@/lib/ai/aiCodeHighlighter";import { createAiMessageRenderer } from "@/lib/ai/aiMessageRender";import { formatAiInlineMarkdown, handleAiMarkdownLinkClick } from "@/lib/ai/aiMarkdown";-import { aiStream, aiCancelStream, resolveAiToolApproval, saveAiConversation, saveAiRun, saveAiRunState, loadAiConversations, loadAiRuns, deleteAiConversation, listSchemas, listTables, readUserSkills, type AiConversation, type AiRun, type AiRunStatus } from "@/lib/backend/api";+import { aiStream, aiCancelStream, resolveAiToolApproval, saveAiConversation, saveAiRun, saveAiRunState, loadAiConversations, loadAiRuns, deleteAiConversation, listSchemas, listTables, listUserSkills, readUserSkills, type AiConversation, type AiRun, type AiRunStatus } from "@/lib/backend/api";import type { AiMessage } from "@/lib/backend/api";import type { AiConfigItem, AiEffortCapability, AiEffortOption, AiEffortSelection } from "@/types/ai";import type { ConnectionConfig, QueryTab, SavedSqlFile, TableInfo } from "@/types/database";@@ -198,7 +241,7 @@ import { resolveAiMessageCopyText } from "@/lib/ai/aiMessageCopy";import { buildPluginAiRequest, createPluginAiConversation, pluginComposerConnectionLabel, pluginContextConnectionId, pluginContextFromMessages, pluginContextText, streamPluginAiConversation, type AiPluginContext, type AiPluginConversationRequest } from "@/lib/ai/aiPluginConversation";import type { PluginAiRecommendationHostUpdate } from "@/lib/plugins/pluginHostBridge";-const { t } = useI18n();+const { t, locale } = useI18n();const AiChartRenderer = defineAsyncComponent({// Lazy-load the chart renderer (and with it the whole echarts bundle): echarts// is only pulled in when a message actually renders a chart-json segment.@@ -314,6 +357,14 @@ interface ChatMessage {*/routedFrom?: "auto";routedAction?: AiAction;+ /**+ * Skills this conversation has had loaded (prd 09-30 Req 13), kept on the newest+ * assistant turn of every snapshot. Only the fact is persisted: a body can reach+ * 1 MiB per skill and the stored message array is re-serialized in full on every+ * save, so bodies are re-read from disk when a request needs them (see+ * `rehydrateLoadedSkillBodies`). Same shape as `selectionsOmitted`.+ */+ loadedSkillIds?: string[];}const props = defineProps<{@@ -639,10 +690,165 @@ const userSkillStore = useUserSkillStore();const selectedSkillIds = ref<string[]>([]);const showSkillSelector = ref(false);const skillFailures = ref<ReadUserSkillFailure[]>([]);+/** Force-loads in flight, so a chip can spin and a double click cannot inject the+ * same body twice. */+const skillPreloadPending = ref<string[]>([]);++/** Tool name backing the on-demand skill load (`crates/dbx-core/src/ai/skill_tools.rs`). */+const USE_SKILL_TOOL_NAME = "use_skill";+// Chips derive from the selection truth, not from the catalog: a skill that// vanished from discovery must keep a removable chip (prd.md:37) instead of// silently becoming an id the user can no longer drop.-const selectedSkillChips = computed(() => buildSelectedSkillChips(selectedSkillIds.value, (id) => userSkillStore.metaFor(id)));+const selectedSkillChips = computed(() => buildSelectedSkillChips(selectedSkillIds.value, (id) => userSkillStore.metaFor(id), loadedSkillIds.value));++/**+ * Per-root duplicate display names, keyed by source. Two same-named skills in one+ * root are unresolvable for the model — `use_skill` addresses by name + source+ * (ADR Decision 6) and the source is identical, so it can only answer "ambiguous".+ * The selector flags those rows and tells the user the one fix that exists on+ * their side: changing one of the two `SKILL.md` frontmatter names, which is the+ * key this collision is computed from — the folder name plays no part. Cross-root+ * name collisions are normal and are deliberately not flagged.+ */+const duplicateNamesBySource = computed(() => {+ const bySource = new Map<"custom" | "default", Set<string>>();+ for (const group of userSkillStore.groupedSkills) bySource.set(group.source, duplicateSkillNames(group.skills));+ return bySource;+});++/**+ * The skill a completed `use_skill` call actually loaded, as reported by the+ * backend (`explain_data.skillId` — `crates/dbx-core/src/ai/skill_tools.rs`).+ *+ * Read from the tool *result*, never re-derived from the call arguments: the+ * arguments say what the model asked for, and an ambiguous or missing name loads+ * nothing at all. Mapping the arguments back through the catalog would light a+ * chip for a body that never arrived, and the next send would then re-read and+ * inject that wrong body into the prompt.+ */+function loadedSkillIdFromToolResult(result: unknown): string | undefined {+ if (!result || typeof result !== "object") return undefined;+ const explain = (result as { explain_data?: unknown }).explain_data;+ if (!explain || typeof explain !== "object") return undefined;+ const id = (explain as { skillId?: unknown }).skillId;+ return typeof id === "string" && id ? id : undefined;+}++/**+ * Loaded = this conversation's recorded facts (a model-initiated `use_skill` in+ * one of its runs, a forced load, or the ids restored from its own transcript).+ * Per-conversation and never recomputed per turn, so the chip cannot flicker+ * between turns; a new chat starts over, and a different conversation reads its+ * own key.+ */+/**+ * Key for the per-conversation skill maps: the conversation's id once it has one,+ * and otherwise an id for the unsaved chat — fresh per panel instance and per+ * "new chat", because such a chat cannot be reopened, so no other instance may+ * inherit its state.+ */+const unsavedConversationKey = ref(`unsaved:${uuid()}`);+const skillStateKey = computed(() => conversationId.value || unsavedConversationKey.value);++/**+ * Loaded = this conversation's recorded facts (a model-initiated `use_skill` in+ * one of its runs, a forced load, or the ids restored from its own transcript).+ * Per-conversation and never recomputed per turn, so the chip cannot flicker+ * between turns; a new chat starts over, and a different conversation reads its+ * own key.+ */+const loadedSkillIds = computed<Set<string>>(() => new Set(conversationLoadedSkillIds.get(skillStateKey.value) ?? []));++function recordConversationSkillLoad(key: string, id: string) {+ const loaded = conversationLoadedSkillIds.get(key) ?? [];+ if (loaded.includes(id)) return;+ conversationLoadedSkillIds.set(key, [...loaded, id]);+}++/**+ * Moves the unsaved chat's skill state onto the id it just adopted. The id+ * watcher covers this for the UI, but watchers flush later: `send()` mints the id+ * and reads this state in the same tick, so it calls this again itself.+ */+function migrateUnsavedSkillState(id: string) {+ const unsavedKey = unsavedConversationKey.value;+ if (!unsavedKey || unsavedKey === id) return;+ const facts = conversationLoadedSkillIds.get(unsavedKey);+ if (facts) {+ conversationLoadedSkillIds.delete(unsavedKey);+ conversationLoadedSkillIds.set(id, facts);+ }+ const bodies = conversationLoadedSkillBodies.get(unsavedKey);+ if (bodies) {+ conversationLoadedSkillBodies.delete(unsavedKey);+ conversationLoadedSkillBodies.set(id, bodies);+ }+}++/**+ * Seed the conversation's facts from its persisted transcript (Req 13 after a+ * restart). Every snapshot writes the whole list onto the newest assistant turn,+ * so the newest carrier is the authoritative one — older turns hold stale+ * subsets, and reading the union would resurrect an id a later snapshot dropped+ * (a skill that was deleted, say).+ */+function seedLoadedSkillsFromTranscript(conversationIdToSeed: string, transcript: readonly ChatMessage[]) {+ for (let i = transcript.length - 1; i >= 0; i--) {+ const persisted = transcript[i].loadedSkillIds;+ if (!persisted?.length) continue;+ const existing = conversationLoadedSkillIds.get(conversationIdToSeed) ?? [];+ const merged = [...existing, ...persisted.filter((id) => !existing.includes(id))];+ conversationLoadedSkillIds.set(conversationIdToSeed, merged);+ return;+ }+}++/**+ * Req 14's one-time hint: the first turn of a conversation in which something is+ * selected and none of it has been loaded yet. It is latched rather than derived+ * (so it does not re-render every turn) and it disappears on its own once the+ * skill it names is loaded, or when the user drops its chip.+ */+const skillHintLatch = ref<{ key: string; id: string; name: string } | null>(null);+const showSkillHint = computed(() => {+ const latch = skillHintLatch.value;+ if (!latch || latch.key !== skillStateKey.value) return false;+ return selectedSkillIds.value.includes(latch.id) && !loadedSkillIds.value.has(latch.id);+});+const skillHintText = computed(() => t("ai.skillsPreloadHint", { name: skillHintLatch.value?.name ?? "" }));+function preloadHintedSkill() {+ const id = skillHintLatch.value?.id;+ if (id) void preloadSkill(id);+}+/** The hint names one specific skill, so dropping that skill retires it. */+function forgetSkillHintFor(id: string) {+ if (skillHintLatch.value?.id === id) skillHintLatch.value = null;+}+watch([skillStateKey, () => selectedSkillChips.value.map((chip) => chip.id).join(","), () => [...loadedSkillIds.value].sort().join(",")], () => {+ if (skillCapabilityUnavailable.value) return;+ const key = skillStateKey.value;+ if (conversationSkillHintSeen.has(key)) return;+ const chips = selectedSkillChips.value;+ if (!chips.length) return;+ if (chips.some((chip) => loadedSkillIds.value.has(chip.id))) return;+ conversationSkillHintSeen.add(key);+ skillHintLatch.value = { key, id: chips[0].id, name: chips[0].name };+});+// Minting the unsaved chat's id on its first send (or when queueing) is not a+// conversation switch: move the unsaved chat's skill state onto the id it just+// adopted, or the brand-new id would read as a fresh conversation (Req 14) and+// would lose the bodies a forced load already put in this run's state (Req 13).+watch(conversationId, (id, previous) => {+ if (previous !== "" || !id) return;+ const unsavedKey = unsavedConversationKey.value;+ if (conversationSkillHintSeen.delete(unsavedKey)) conversationSkillHintSeen.add(id);+ const latch = skillHintLatch.value;+ if (latch && latch.key === unsavedKey) skillHintLatch.value = { ...latch, key: id };+ migrateUnsavedSkillState(id);+});+// The selector's capability state (predicate, gated open state, trigger label)+// lives below `activeFullConfig`, next to the config it reads.const selectableSkillIds = computed(() => userSkillStore.groupedSkills.flatMap((group) => group.skills.map((skill) => skill.id)));const canSelectAllSkills = computed(() => !userSkillStore.isLoading && !userSkillStore.lastError && selectableSkillIds.value.some((id) => !selectedSkillIds.value.includes(id)));// Selector retry-on-open mirrors the template selector above.@@ -682,6 +888,7 @@ function deselectAllSkills() {function removeSelectedSkill(id: string) {selectedSkillIds.value = removeSkillIds(selectedSkillIds.value, [id]);skillFailures.value = [];+ forgetSkillHintFor(id);}/** Banner Remove: drops every failed skill from the selection, so the next send is not blocked by a stale id. */@@ -715,9 +922,125 @@ function openSkillRootSettings() {emit("openSettings");}-function selectedSkillsAgentStep(skills: ReadUserSkill[]): AiAgentStepItem {+function selectedSkillsListedStep(skills: readonly UserSkillMeta[]): AiAgentStepItem {const details = skills.map((skill) => `${skill.name} (${t(userSkillSourceOfId(skill.id) === "custom" ? "ai.skillsGroupCustom" : "ai.skillsGroupDefault")})`).join(" · ");- return { key: "selected-skills", labelKey: "ai.agentSteps.skillsLoaded", tone: "success", toolName: skills.map((skill) => skill.name).join(", "), toolResult: details };+ return { key: "selected-skills", labelKey: "ai.agentSteps.skillsListed", tone: "success", toolName: skills.map((skill) => skill.name).join(", "), toolResult: details };+}++/**+ * Provider-shaped call id for the synthetic round. Gemini derives a tool result's+ * function name from the id (`gemini-tc-<name>-<index>`, see `build_gemini_contents`+ * in dbx-ai-provider), so a generic id would replay the result as "unknown" and+ * the provider would reject the whole request.+ */+function skillLoadCallId(skillName: string): string {+ return activeFullConfig.value?.provider === "gemini" ? `gemini-tc-${USE_SKILL_TOOL_NAME}-0` : `dbx-skill-${skillName}-${uuid()}`;+}++/** Same shape `use_skill` returns, minus the file listing: the panel's read API+ * returns the body only, and the model can still call `use_skill` for the list. */+function skillToolResultText(name: string, source: string, content: string): string {+ return `# Skill: ${name} [${source}]\n\n${content.trimEnd()}\n\nFollow this skill's instructions.\n`;+}++/** The pair a real `use_skill` round produces, for the request to replay. Built+ * per request — never written to the transcript or to storage. */+function skillRoundMessages(bodies: readonly LoadedSkillBody[]): AiMessage[] {+ return bodies.flatMap((body): AiMessage[] => {+ const callId = skillLoadCallId(body.name);+ return [+ { role: "assistant", content: "", toolCalls: [{ id: callId, name: USE_SKILL_TOOL_NAME, arguments: { skill: body.name, source: body.source } }] },+ { role: "tool", content: skillToolResultText(body.name, body.source, body.content), toolCallId: callId },+ ];+ });+}++/**+ * Req 13's forced load: read the body now and remember it for this conversation.+ *+ * The body stays in this app run (`conversationLoadedSkillBodies`); only the fact+ * that the skill is loaded is persisted. A failed read is reported and stores+ * nothing — that refusal is the guard, since a body can be up to 1 MiB and a+ * result that size would wreck the context instead of helping it.+ */+async function preloadSkill(id: string) {+ if (skillCapabilityUnavailable.value) return;+ // Re-loading would stack the same body into the request twice.+ if (loadedSkillIds.value.has(id) || skillPreloadPending.value.includes(id)) return;+ const name = userSkillStore.metaFor(id)?.name ?? id;+ skillPreloadPending.value = [...skillPreloadPending.value, id];+ try {+ const result = await readUserSkills([id], skillRootSettings());+ const skill = result.skills.find((entry) => entry.id === id);+ if (!skill) {+ const reason = result.failures.find((failure) => failure.id === id)?.reason ?? "unreadable";+ // A toast, not the send-blocked banner: no request was refused here, and the+ // banner's recovery actions all belong to a send that was.+ toast(`${t("ai.skillsPreloadFailed")}: ${name} — ${t(skillFailureReasonKey(reason))}`, 5000);+ return;+ }+ const key = skillStateKey.value;+ const source = userSkillSourceOfId(id);+ conversationLoadedSkillBodies.set(key, [...(conversationLoadedSkillBodies.get(key) ?? []), { id, name: skill.name, source, content: skill.content }]);+ recordConversationSkillLoad(key, id);+ // Only an already-stored conversation is re-persisted: a chip click must not+ // create a conversation of its own (the first send snapshots the fact).+ if (conversationId.value && conversations.value.some((conversation) => conversation.id === conversationId.value)) {+ void persistConversation();+ }+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ toast(`${t("ai.skillsPreloadFailed")}: ${name} — ${translateBackendError(t, message)}`, 5000);+ } finally {+ skillPreloadPending.value = skillPreloadPending.value.filter((pending) => pending !== id);+ }+}++/**+ * The bodies a request should replay: this run's loaded bodies, plus the ones a+ * restart left as a fact without a body.+ *+ * Re-reading those is NOT ADR Decision 3's rejected auto-fallback. That decision+ * forbade loading a skill the conversation never used into an unrelated+ * conversation, because the body then stays in the history and burns tokens+ * forever. This restores state the conversation already had, on the topic it is+ * already on, and the ids come from what the user or the model actually loaded.+ *+ * A skill that has since been deleted or grown past the read limit cannot be+ * restored: its id is dropped from the facts (so the chip stops claiming it is+ * loaded and the next snapshot persists the correction) and the reason is shown.+ */+async function rehydrateLoadedSkillBodies(key: string): Promise<LoadedSkillBody[]> {+ const ids = conversationLoadedSkillIds.get(key) ?? [];+ if (!ids.length) return [];+ const bodies = [...(conversationLoadedSkillBodies.get(key) ?? [])];+ const missing = ids.filter((id) => !bodies.some((body) => body.id === id));+ if (!missing.length) return bodies;+ try {+ const result = await readUserSkills(missing, skillRootSettings());+ for (const skill of result.skills) {+ bodies.push({ id: skill.id, name: skill.name, source: userSkillSourceOfId(skill.id), content: skill.content });+ }+ for (const failure of result.failures) {+ const name = userSkillStore.metaFor(failure.id)?.name ?? failure.id;+ toast(`${t("ai.skillsPreloadFailed")}: ${name} — ${t(skillFailureReasonKey(failure.reason))}`, 5000);+ }+ if (result.failures.length) {+ const failed = new Set(result.failures.map((failure) => failure.id));+ conversationLoadedSkillIds.set(+ key,+ ids.filter((id) => !failed.has(id)),+ );+ }+ } catch (error) {+ // The read itself failed (backend unavailable). Keep the facts — this is an+ // environment failure, not evidence that the skills are gone — and send the+ // request without the bodies rather than failing the whole send.+ const message = error instanceof Error ? error.message : String(error);+ toast(`${t("ai.skillsPreloadFailed")}: ${translateBackendError(t, message)}`, 5000);+ }+ conversationLoadedSkillBodies.set(key, bodies);+ return bodies;}// Retry store load on selector open if prior init failed (e.g. backend not yet ready at mount)@@ -1066,6 +1389,39 @@ function isModelCandidate(config: AiConfigItem): boolean {return isAiConfigModelCandidate(config, getAiProviderPreset(config.provider, config.endpoint).requiresApiKey, supportsCliProviders);}+// Skill capability belongs to DBX's built-in AI alone (prd 09-30 Req 15a): a CLI+// run returns before the agent loop builds its tool list and its surface is the+// DBX MCP server, so nothing in a CLI prompt can reference a skill.+//+// These sit here, after `activeFullConfig`, and not beside `showSkillSelector`:+// `watch()` reads its source once at creation, so a predicate placed above the+// config it reads throws the same "Cannot access before initialization" that once+// kept this panel from opening at all.+//+// The predicate reads the very config the send path resolves, so the selector and+// the send can never disagree about the provider.+const skillCapabilityUnavailable = computed(() => isCliProvider(activeFullConfig.value?.provider));+// The open state is gated here rather than left to the button's native `disabled`+// attribute: `/skill` writes the selector ref directly, and a disabled button is+// not guaranteed to stop a PopoverTrigger from opening. `showSkillSelector` stays+// the source of truth (the retry-on-open watcher reads it); writing `true` while+// unavailable is dropped, so no path reaches the silent "ticked but never sent"+// state this state exists to remove.+const skillSelectorOpen = computed<boolean>({+ get: () => showSkillSelector.value && !skillCapabilityUnavailable.value,+ set: (open) => {+ showSkillSelector.value = open && !skillCapabilityUnavailable.value;+ },+});+// Switching to a CLI provider while the selector is open must close it, otherwise+// the stale `true` would reopen the popover on a switch back to a built-in model.+watch(skillCapabilityUnavailable, (unavailable) => {+ if (unavailable) showSkillSelector.value = false;+});+// A disabled control with no explanation is the silent state being removed: the+// reason rides on the trigger's label and title whenever the capability is gone.+const skillSelectorTriggerLabel = computed(() => t(skillCapabilityUnavailable.value ? "ai.skillsUnsupportedForCliProvider" : "ai.skillsEntry"));+function getModelsForConfig(configId: string) {const config = settings.aiConfigs.find((item) => item.id === configId);if (!config) return [];@@ -1368,7 +1724,10 @@ type AiSlashEntry = { type: "action"; button: AiActionButton } | { type: "skillsconst filteredCommands = computed<AiSlashEntry[]>(() => {const query = prompt.value.slice(commandStart.value + 1).toLowerCase();- const entries: AiSlashEntry[] = [...actionButtons.value.map((button): AiSlashEntry => ({ type: "action", button })), { type: "skills" }];+ // `/skill` is dropped when the provider has no skill capability (Req 15a), so the+ // palette never offers an action that cannot happen — the disabled trigger's+ // label carries the reason.+ const entries: AiSlashEntry[] = [...actionButtons.value.map((button): AiSlashEntry => ({ type: "action", button })), ...(skillCapabilityUnavailable.value ? [] : [{ type: "skills" } as AiSlashEntry])];return entries.filter((entry) => {const haystack = entry.type === "action" ? `${entry.button.action} ${t(entry.button.key)}` : `skill ${t("ai.skillsEntry")}`;return haystack.toLowerCase().includes(query);@@ -2872,8 +3231,16 @@ function selectCommand(command: AiSlashEntry) {commandOpen.value = false;if (command.type === "skills") {skillFailures.value = [];- showSkillSelector.value = true;- nextTick(() => promptTextareaRef.value?.focus());+ // Routed through the gated open state, so the palette entry cannot open the+ // selector when the provider has no skill capability (Req 15a).+ skillSelectorOpen.value = true;+ // No `nextTick(() => textarea.focus())` on this branch, unlike the action+ // branch below. The just-opened popover autofocuses its own content, so+ // pulling focus back to the textarea fires a `focusin` outside the layer and+ // reka's DismissableLayer reads it as a focus-outside and dismisses the+ // popover on the next tick — the `/skill` entry then looks like it does+ // nothing at all. The entry fires on `mousedown` with `prevent`, so the+ // textarea already keeps focus; nothing needs to be restored.return;}activeAction.value = command.button.action;@@ -3397,6 +3764,9 @@ async function send() {}const myGeneration = aiGenerationGuard.begin();if (!auto && !conversationId.value) conversationId.value = uuid();+ // The id was minted a line ago and the watcher has not flushed yet: this send+ // must already read the skill state of the conversation it is now running for.+ if (!auto) migrateUnsavedSkillState(conversationId.value);const runConversationId = auto ? auto.conversationId : conversationId.value;const runMessages = auto ? auto.messages : messages.value;const runCreatedAt = new Date().toISOString();@@ -3457,17 +3827,50 @@ async function send() {}const generationCanContinue = () => (detachedRun ? !detachedRun.cancelRequested : aiGenerationGuard.isCurrent(myGeneration));const runIsVisible = () => !detachedRun || (assistantViewMounted && conversationId.value === runConversationId);- // Selected skills are read and validated through the backend registry right- // before the request pipeline starts (after the generation guard: no awaits- // above this point). On any failure no AI request is sent: the failure banner- // appears above the composer while the draft and selection stay untouched- // (prd send-time loading contract).- let sendSkillSnapshot: ReadUserSkill[] | undefined;- if (selectedSkillIds.value.length > 0) {+ // Selected skills are no longer read at send time: their bodies never enter the+ // prompt (they load on demand through the use_skill tool, which only the+ // built-in AI has — a CLI run receives no skill content at all). Only the+ // catalog is consulted, to tell the user that a checked skill has disappeared+ // before the request goes out. On any failure no AI request is sent: the+ // failure banner appears above the composer while the draft and selection stay+ // untouched.+ //+ // Skill capability is built-in-AI only (Req 12): a CLI provider gets neither+ // the listing nor the two tools, so the whole block is skipped for it. The+ // selector is disabled there too (Req 15a), but a selection made under an API+ // provider survives a model switch, and nothing of it may reach the CLI run.+ let sendSkillListing: string[] | undefined;+ let sendSelectedSkillMetas: UserSkillMeta[] | undefined;+ const skillsAvailable = !isCliProvider(activeConfig.provider);+ // Req 5: the listing rides along when the user ticked something OR the+ // "allow the AI to use skills automatically" Settings toggle (default off) is+ // on. `allowSkills` below then follows from the listing itself, so the two+ // skill tools ship exactly when the prompt points at them (ADR Decision 10).+ const autoSkillsEnabled = settings.desktopSettings?.custom_ai_skill_auto_enabled === true;+ if (skillsAvailable && (selectedSkillIds.value.length > 0 || autoSkillsEnabled)) {skillFailures.value = [];- const skillRead = await readUserSkills([...selectedSkillIds.value], skillRootSettings());- if (skillRead.failures.length > 0) {- skillFailures.value = skillRead.failures;+ let catalog: UserSkillsListResult;+ try {+ catalog = await listUserSkills(skillRootSettings());+ } catch {+ // The catalog gates nothing on its own: with nothing selected the request+ // just goes out skill-free, and a checked skill is reported as+ // unavailable. An unhandled rejection here would take the whole send down.+ catalog = { defaultRoot: { status: "invalid", skills: [] }, customRoot: null };+ }+ const catalogSkills = [...catalog.defaultRoot.skills, ...(catalog.customRoot?.skills ?? [])];+ const known = new Set(catalogSkills.map((skill) => skill.id));+ const failures: ReadUserSkillFailure[] = [];+ for (const id of selectedSkillIds.value) {+ if (known.has(id)) continue;+ // Distinguish "this skill is gone" from "its whole root is unavailable" —+ // the frozen reason vocabulary has one word for each, and the banner copy+ // differs.+ const rootUnavailable = userSkillSourceOfId(id) === "custom" ? !catalog.customRoot || catalog.customRoot.status !== "ok" : catalog.defaultRoot.status !== "ok";+ failures.push({ id, reason: rootUnavailable ? "root_unavailable" : "not_found" });+ }+ if (failures.length > 0) {+ skillFailures.value = failures;clearPendingWriteGrant();if (generationCanContinue()) {if (detachedRun) finishDesktopAiRun(detachedRun, "failed");@@ -3480,14 +3883,10 @@ async function send() {resolveDetachedRunSettled();return;}- // Skill bodies are only known here, so the combined budget is enforced on- // the read snapshots: overflowing skills are skipped for this send while- // the selection itself stays untouched.- const cappedSkills = capSkillsToCharLimit(skillRead.skills, ACTIVE_SKILLS_TOTAL_MAX);- if (cappedSkills.length < skillRead.skills.length) {- toast(t("ai.skillsTotalTrimmed", { max: ACTIVE_SKILLS_TOTAL_MAX }), 4000);- }- sendSkillSnapshot = cappedSkills;+ // Only the metadata survives the send: the listing is rendered here (it is+ // what the prompt carries) and the metas feed the transcript's agent step.+ sendSelectedSkillMetas = selectedSkillIds.value.flatMap((id) => catalogSkills.filter((skill) => skill.id === id));+ sendSkillListing = buildSkillListingLines(buildSkillListing({ skills: catalogSkills, selectedIds: selectedSkillIds.value }), locale.value.startsWith("zh"));}if (!(await promptTemplateStore.ensureLoaded())) {clearPendingWriteGrant();@@ -3527,8 +3926,25 @@ async function send() {const customPromptContext: CustomPromptContext = {globalInstructions: promptTemplateStore.globalInstructions,activeTemplates: runPluginContext ? [] : [...activeTemplates.value],- ...(sendSkillSnapshot?.length ? { selectedSkills: sendSkillSnapshot } : {}),+ ...(sendSkillListing?.length ? { skillListing: sendSkillListing } : {}),};+ // The skill tools ship with the listing and nothing else gates them (ADR+ // Decision 10), so this is the same condition that just put lines in the+ // prompt rather than a second decision that could drift away from it.+ const allowSkills = Boolean(sendSkillListing?.length);+ // The bodies this request should replay: the ones loaded in this session, plus+ // the ones this conversation had loaded before a restart and never kept on disk+ // (Req 13). Only when the request declares the skill tools — a send with no+ // listing carries no `use_skill`, and Gemini and Anthropic reject a replayed+ // call to a function they were not given.+ const skillBodies = allowSkills ? await rehydrateLoadedSkillBodies(runConversationId) : [];+ // Superseded while the bodies were being re-read: this generation no longer owns+ // the conversation, and `skillBodies` describes a state it may have left.+ if (!generationCanContinue()) {+ clearPendingWriteGrant();+ resolveDetachedRunSettled();+ return;+ }// Remember what was actually sent for this db_type so panels opened later can// restore it when no explicit per-db_type defaults are configured. This runs// for empty selections too: the store clears the remembered entry so a@@ -3705,8 +4121,8 @@ async function send() {}runMessages.push({ role: "assistant", content: "", sourceConnectionName: runSourceName, sourceBinding: runBinding });const assistantIdx = runMessages.length - 1;- if (requestedMode === "agent" && sendSkillSnapshot?.length) {- runMessages[assistantIdx].agentSteps = [selectedSkillsAgentStep(sendSkillSnapshot)];+ if (requestedMode === "agent" && sendSelectedSkillMetas?.length) {+ runMessages[assistantIdx].agentSteps = [selectedSkillsListedStep(sendSelectedSkillMetas)];}const sessionId = uuid();if (runIsVisible()) {@@ -3742,7 +4158,10 @@ async function send() {void persistConversationSnapshot(runConversationId, runMessages, runSourceName, tab?.database || "", runCreatedAt);}try {- const history: AiMessage[] = messagesForAgentHistory(runMessages.slice(0, -2));+ // The skill round is appended after the transcript's own turns: it reaches the+ // model as the most recent context before the new user prompt, and it is built+ // per request so the body never enters the transcript or any stored record.+ const history: AiMessage[] = [...messagesForAgentHistory(runMessages.slice(0, -2)), ...skillRoundMessages(skillBodies)];const onEvent = (event: AgentEvent) => {// Superseded by a clear/switch/new-chat (or a newer send()) — the backend// stream may still be running, but this generation no longer owns any@@ -3800,6 +4219,14 @@ async function send() {if (detachedDeltaBuffer) detachedDeltaBuffer.appendReasoning(assistantIdx, event.delta);else appendAssistantReasoning(assistantIdx, event.delta);}+ if (event.type === "output_truncated") {+ // The provider cut the answer off at its output limit; without this the card+ // would look like a finished reply. Appended in the user's own locale, like+ // every other string the panel writes.+ const notice = `\n\n[${t("ai.outputTruncated")}]`;+ if (detachedDeltaBuffer) detachedDeltaBuffer.appendText(assistantIdx, notice);+ else appendAssistantDelta(assistantIdx, notice);+ }if (event.type === "agent_end") {// End the card's "思考过程" spinner at the terminal event rather than// waiting for send()'s finally (which can lag behind CLI teardown).@@ -3822,6 +4249,19 @@ async function send() {}// Real-time agent step renderingif (event.type === "tool_call_start" || event.type === "tool_call_end") {+ // Req 13's "the model actually used it" signal. The tool round itself+ // lives inside the backend run and is never persisted back into the+ // transcript, so the event stream is where this is observed — recorded+ // under the run's own conversation, which a background send may not be+ // showing.+ //+ // Only a *completed, successful* call proves a load: `tool_call_start`+ // fires before the tool runs, and an ambiguous or missing name ends as an+ // error having loaded nothing.+ if (event.type === "tool_call_end" && event.tool_name === USE_SKILL_TOOL_NAME && !event.is_error) {+ const loadedSkillId = loadedSkillIdFromToolResult(event.result);+ if (loadedSkillId && runConversationId) recordConversationSkillLoad(runConversationId, loadedSkillId);+ }const msg = runMessages[assistantIdx];if (msg) {if (!msg.agentSteps) msg.agentSteps = [];@@ -3877,6 +4317,7 @@ async function send() {taskContractUserRequest: text,context,inlineImages: imageAttachments.map(({ mediaType, data }) => ({ mediaType, data })),+ allowSkills,},history,onEvent,@@ -3942,6 +4383,7 @@ async function send() {confirmedConnectionId: confirmedTargetConnId,confirmedDatabase: confirmedTargetDb,confirmedSchema: confirmedTargetSchema,+ allowSkills,},history,onEvent,@@ -4024,6 +4466,8 @@ async function send() {if (compaction) {const { summary, compactedMessages } = compaction;if (!detachedRun) pendingCompaction.value = null;+ // The backend counted the messages it received; the transcript is what it+ // counted (skill rounds never enter it — see `skillRoundMessages`).const insertAt = Math.min(1 + compactedMessages, runMessages.length - 1);if (summary) {runMessages.splice(insertAt, 0, {@@ -4588,6 +5032,14 @@ function clearMessages() {historyIndex.value = -1;draftBeforeHistory.value = "";recoveredDraftActive.value = false;+ // A new chat is a new conversation, so it gets its own hint identity and a+ // first hint of its own (Req 14). Its predecessor's skill state is dropped with+ // it — that chat's id can never come back.+ skillHintLatch.value = null;+ conversationSkillHintSeen.delete(unsavedConversationKey.value);+ conversationLoadedSkillIds.delete(unsavedConversationKey.value);+ conversationLoadedSkillBodies.delete(unsavedConversationKey.value);+ unsavedConversationKey.value = `unsaved:${uuid()}`;messageRenderer.value.clear();}@@ -4616,6 +5068,14 @@ function buildConversationSnapshot(targetConversationId: string, targetMessages:const first = targetMessages.find((m) => m.role === "user" && m.kind !== "contextSummary");const existingConversation = conversations.value.find((conversation) => conversation.id === targetConversationId);const binding = snapshotBinding(targetConversationId, fallbackBinding);+ let lastAssistantIndex = -1;+ for (let i = targetMessages.length - 1; i >= 0; i--) {+ if (targetMessages[i].role === "assistant") {+ lastAssistantIndex = i;+ break;+ }+ }+ const loadedSkillIdsForSnapshot = conversationLoadedSkillIds.get(targetConversationId) ?? [];return {id: targetConversationId,title: first?.pluginContext?.title || renamedConversationTitles.get(targetConversationId) || existingConversation?.title || (first ? messageTitle(first).slice(0, 50) : "Untitled"),@@ -4628,7 +5088,7 @@ function buildConversationSnapshot(targetConversationId: string, targetMessages:connectionId: binding.connectionId,database: existingConversation ? binding.database : database,schema: binding.schema,- messages: targetMessages.map((m) => ({+ messages: targetMessages.map((m, index) => ({role: m.role,content: m.content,...(m.mentions?.length ? { mentions: m.mentions } : {}),@@ -4644,6 +5104,11 @@ function buildConversationSnapshot(targetConversationId: string, targetMessages:// Preserve it on every subsequent snapshot or the second restart silently// loses the omission warning again....(m.selections?.length || m.selectionsOmitted ? { selectionsOmitted: true } : {}),+ // Skills this conversation has loaded (Req 13), carried on the newest+ // assistant turn so a reload reads back one authoritative list. Only the+ // ids: see `ChatMessage.loadedSkillIds` for why the bodies stay out of the+ // record.+ ...(index === lastAssistantIndex && loadedSkillIdsForSnapshot.length ? { loadedSkillIds: [...loadedSkillIdsForSnapshot] } : {}),})),// The conversation's single queued "send later" input, persisted so it// survives a restart (parent PRD §5).@@ -4770,6 +5235,14 @@ async function persistPendingInputRecovery(conversation: AiConversation, message...(m.kind ? { kind: m.kind } : {}),...(m.failed ? { failed: true } : {}),...(m.sourceBinding ? { sourceBinding: m.sourceBinding } : {}),+ // This is a second snapshot-writing path beside+ // `buildConversationSnapshot`, and it replaces the whole message array.+ // Every footprint a message carries must be re-projected here or the+ // restart that recovers a queued run silently drops it: the selection+ // omission warning (#10058) and the loaded-skill fact (Req 13) both only+ // survive as long as each rewrite carries them forward.+ ...(m.selections?.length || m.selectionsOmitted ? { selectionsOmitted: true } : {}),+ ...(m.loadedSkillIds?.length ? { loadedSkillIds: [...m.loadedSkillIds] } : {}),})),queuedInput: conversation.queuedInput,createdAt: conversation.createdAt,@@ -4847,6 +5320,11 @@ function chatMessagesFromConversation(conv: AiConversation): ChatMessage[] {failed: m.failed === true ? true : undefined,// Only the footprint is loaded back; the selection text itself is gone.selectionsOmitted: m.selectionsOmitted === true ? true : undefined,+ // Which skills this conversation had loaded — the fact only, and only on the+ // turn that carried it. `seedLoadedSkillsFromTranscript` reads it back into+ // the panel's per-conversation state, and the body is re-read from disk when+ // a request needs it.+ loadedSkillIds: m.loadedSkillIds?.length ? m.loadedSkillIds : undefined,// Old transcripts have no per-turn target. Capture the conversation's// current binding on load so a later rebind cannot retarget a pending card.sourceBinding: m.sourceBinding ?? (m.role === "assistant" && conv.connectionId ? { connectionId: conv.connectionId, database: conv.database, schema: conv.schema } : undefined),@@ -4875,8 +5353,15 @@ function selectConversation(conv: AiConversation) {clearAttachmentDraftState();// Drop the previous conversation's rendered Markdown instead of keeping it until the LRU evicts it.messageRenderer.value.clear();+ // The arriving conversation owns its own one-time skill hint; the watcher below+ // latches it again only if that conversation has not shown one yet (Req 14).+ skillHintLatch.value = null;const activeRun = backgroundAiRunsEnabled ? desktopAiRun<ChatMessage>(conv.id) : undefined;messages.value = activeRun?.messages ?? chatMessagesFromConversation(conv);+ // Req 13 after a restart: the transcript keeps the fact that skills were+ // loaded, so the chips can light up before anything is read again. The bodies+ // come back when a request actually needs them (`rehydrateLoadedSkillBodies`).+ seedLoadedSkillsFromTranscript(conv.id, messages.value);if (pluginContext.value) {assistantMode.value = pluginContext.value.mode === "agent" && !boundConnection.value ? "ask" : (pluginContext.value.mode ?? "ask");activeAction.value = "general";@@ -4988,6 +5473,10 @@ async function performDeleteConversation(id: string) {removeDesktopAiRun(id);}queuedInputs.delete(id);+ // The conversation's skill state goes with it; the ids can never come back.+ conversationLoadedSkillIds.delete(id);+ conversationLoadedSkillBodies.delete(id);+ conversationSkillHintSeen.delete(id);await deleteConversationWithCancellation({id,currentConversationId: () => conversationId.value,@@ -6365,9 +6854,15 @@ async function openExternalUrl(url: string) {</PopoverContent></Popover><!-- Skill selector (read-only user SKILL.md library) -->- <Popover v-model:open="showSkillSelector">+ <Popover v-model:open="skillSelectorOpen"><PopoverTrigger as-child>- <button type="button" class="ai-skills-selector-trigger flex min-w-0 items-center gap-1 rounded-[6px] border px-2 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground" :aria-label="t('ai.skillsEntry')" :title="t('ai.skillsEntry')">+ <button+ type="button"+ class="ai-skills-selector-trigger flex min-w-0 items-center gap-1 rounded-[6px] border px-2 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"+ :disabled="skillCapabilityUnavailable"+ :aria-label="skillSelectorTriggerLabel"+ :title="skillSelectorTriggerLabel"+ ><Layers class="h-3 w-3" /><span class="ai-skills-selector-label truncate">{{ t("ai.skillsEntry") }}</span><span v-if="selectedSkillIds.length" class="ai-skills-selector-count rounded-sm bg-primary px-1 text-[10px] font-medium text-primary-foreground">{{ selectedSkillIds.length }}</span>@@ -6392,13 +6887,25 @@ async function openExternalUrl(url: string) {<div class="px-2 pb-1 pt-2 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">{{ t(group.source === "custom" ? "ai.skillsGroupCustom" : "ai.skillsGroupDefault") }}</div>+ <!-- Same-root name collision: the model addresses skills by name + source,+ so it cannot pick between these two, and only changing one of the two+ frontmatter `name` values fixes it (the folder name is irrelevant). -->+ <div v-if="duplicateNamesBySource.get(group.source)?.size" class="ai-skill-duplicate-note mx-2 mb-1 rounded-sm bg-amber-500/10 px-2 py-1 text-[10px] leading-snug text-amber-600">+ {{ t("ai.skillsDuplicateNameNote") }}+ </div><template v-for="skill in group.skills" :key="skill.id"><button type="button" class="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-xs hover:bg-muted" :aria-pressed="selectedSkillIds.includes(skill.id)" @click="toggleSkillSelected(skill.id)"><div class="flex h-4 w-4 shrink-0 items-center justify-center rounded-sm border" :class="selectedSkillIds.includes(skill.id) ? 'border-primary bg-primary text-primary-foreground' : ''"><Check v-if="selectedSkillIds.includes(skill.id)" class="h-3 w-3" /></div><div class="min-w-0 flex-1 text-left">- <div class="truncate font-medium">{{ skill.name }}</div>+ <div class="flex items-center gap-1">+ <span class="truncate font-medium">{{ skill.name }}</span>+ <span v-if="duplicateNamesBySource.get(group.source)?.has(skill.name)" class="ai-skill-duplicate-name inline-flex shrink-0 items-center gap-0.5 rounded-sm bg-amber-500/15 px-1 text-[10px] font-normal text-amber-600" :title="t('ai.skillsDuplicateName')">+ <AlertTriangle class="h-2.5 w-2.5" />+ {{ t("ai.skillsDuplicateName") }}+ </span>+ </div><div class="truncate text-[10px] text-muted-foreground">{{ skill.description }}</div></div></button>@@ -6507,21 +7014,37 @@ async function openExternalUrl(url: string) {<X class="h-3 w-3 shrink-0 text-muted-foreground group-hover:text-foreground" /></button></div>+ <!-- Req 13: a chip has two states (idle / loaded in this conversation)+ and clicking its body force-loads the skill. Removal therefore needs+ its own control — one button cannot both load and remove. --><div v-if="selectedSkillChips.length" class="mb-1.5 flex flex-wrap gap-1">- <button- v-for="chip in selectedSkillChips"- :key="chip.id"- type="button"- class="group inline-flex max-w-full items-center gap-1 rounded border bg-muted/60 px-1.5 py-0.5 text-[11px] text-foreground/90 hover:bg-muted"- :class="chip.unavailable ? 'border-destructive/50 text-destructive' : 'border-border/80'"- :title="chip.description || chip.name"- @click="removeSelectedSkill(chip.id)"- >- <AlertTriangle v-if="chip.unavailable" class="h-3 w-3 shrink-0" />- <Layers v-else class="h-3 w-3 shrink-0 text-primary" />- <span class="truncate">{{ chip.name }}</span>- <span class="shrink-0 text-[9px] text-muted-foreground">{{ t(chip.source === "custom" ? "ai.skillsGroupCustom" : "ai.skillsGroupDefault") }}</span>- <X class="h-3 w-3 shrink-0 text-muted-foreground group-hover:text-foreground" />+ <span v-for="chip in selectedSkillChips" :key="chip.id" class="inline-flex max-w-full items-center rounded border bg-muted/60 text-[11px] text-foreground/90" :class="chip.unavailable ? 'border-destructive/50 text-destructive' : chip.loaded ? 'border-emerald-500/60' : 'border-border/80'">+ <button+ type="button"+ class="ai-skill-chip flex min-w-0 items-center gap-1 py-0.5 pl-1.5 pr-1 hover:bg-muted disabled:cursor-not-allowed"+ :disabled="skillCapabilityUnavailable || chip.loaded"+ :title="chip.loaded ? t('ai.skillsLoadedState') : skillCapabilityUnavailable ? t('ai.skillsUnsupportedForCliProvider') : t('ai.skillsPreload')"+ @click="preloadSkill(chip.id)"+ >+ <Loader2 v-if="skillPreloadPending.includes(chip.id)" class="h-3 w-3 shrink-0 animate-spin" />+ <Check v-else-if="chip.loaded" class="h-3 w-3 shrink-0 text-emerald-600 dark:text-emerald-400" />+ <AlertTriangle v-else-if="chip.unavailable" class="h-3 w-3 shrink-0" />+ <Layers v-else class="h-3 w-3 shrink-0 text-primary" />+ <span class="truncate" :title="chip.description || chip.name">{{ chip.name }}</span>+ <span class="shrink-0 text-[9px] text-muted-foreground">{{ t(chip.source === "custom" ? "ai.skillsGroupCustom" : "ai.skillsGroupDefault") }}</span>+ <span v-if="chip.loaded" class="shrink-0 text-[9px] font-medium text-emerald-600 dark:text-emerald-400">{{ t("ai.skillsLoadedState") }}</span>+ </button>+ <button type="button" class="ai-skill-chip-remove shrink-0 py-0.5 pl-0.5 pr-1.5 hover:text-destructive" :aria-label="t('common.remove')" :title="t('common.remove')" @click="removeSelectedSkill(chip.id)">+ <X class="h-3 w-3 shrink-0" />+ </button>+ </span>+ </div>+ <!-- Req 14: one one-time hint per conversation while nothing selected has+ been loaded yet. Clicking it is the same force-load as the chip. -->+ <div v-if="showSkillHint" class="mb-1.5">+ <button type="button" class="ai-skill-hint inline-flex max-w-full items-center gap-1 rounded border border-primary/40 bg-primary/5 px-1.5 py-0.5 text-left text-[11px] text-primary hover:bg-primary/10" :title="t('ai.skillsPreload')" @click="preloadHintedSkill">+ <Sparkles class="h-3 w-3 shrink-0" />+ <span class="truncate">{{ skillHintText }}</span></button></div><div v-if="selectedCsvAttachments.length || selectedImageAttachments.length" class="mb-1.5 flex max-h-28 flex-wrap gap-1.5 overflow-y-auto pr-0.5">diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vueindex 3c14789318..5dfdc7089b 100644--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue@@ -10247,6 +10247,15 @@ LIMIT 100;</pre</Button></div></div>+ <!-- Default off: a skill listing rides in every request once this is+ on, even with nothing selected (prd 09-30 Req 5). -->+ <div class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">+ <div class="space-y-1">+ <Label for="ai-skill-auto-enabled">{{ t("settings.aiSkillAutoEnabled") }}</Label>+ <p class="text-xs text-muted-foreground">{{ t("settings.aiSkillAutoEnabledDesc") }}</p>+ </div>+ <Switch id="ai-skill-auto-enabled" :model-value="settingsStore.desktopSettings.custom_ai_skill_auto_enabled === true" @update:model-value="(value) => settingsStore.updateDesktopSettings({ custom_ai_skill_auto_enabled: Boolean(value) })" />+ </div></div><!-- Max Retries (list mode, global) -->diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.tsindex ad991534e4..7ab23012a8 100644--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts+++ b/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts@@ -33,8 +33,25 @@ const aiAssistantMountApi = vi.hoisted(() => ({runAgentStreamInputs: [] as unknown[],// Second argument: the model-facing history the panel built for that request.runAgentStreamHistories: [] as unknown[],+ // Fifth argument: the custom prompt context (globals, templates, skill listing).+ runAgentStreamCustoms: [] as unknown[],savedConversations: [] as Array<Record<string, unknown>>,codeHighlighterDelayMs: 0,+ // Skill catalog + body a test wants the backend to answer with.+ skillCatalog: {+ defaultRoot: { status: "ok", skills: [] as Array<{ id: string; name: string; description: string }> },+ customRoot: null as { status: string; skills: Array<{ id: string; name: string; description: string }> } | null,+ },+ skillReadResult: undefined as undefined | { skills: Array<{ id: string; name: string; description: string; content: string }>; failures: Array<{ id: string; reason: string }> },+ skillReadCalls: [] as string[][],+ // How many times the panel asked for the catalog. The banner's Refresh and a+ // retried send both re-read it, so a count is what tells the two apart.+ skillListCalls: 0,+ // `supportsCliProviders` is a runtime capability, so a CLI model config is only a+ // valid active config under Tauri. The panel mounts on the web/http lane here+ // (false), where a CLI config is ineligible and its disabled selector never+ // renders — the skill-capability test flips this for its own duration.+ tauriRuntime: false,}));// `onMounted` imports the syntax highlighter lazily; this module-level delay stands in for the@@ -58,12 +75,84 @@ vi.mock("@/lib/ai/ai", async (importOriginal) => {runAgentStream: async (...args: unknown[]) => {aiAssistantMountApi.runAgentStreamInputs.push(args[0]);aiAssistantMountApi.runAgentStreamHistories.push(args[1]);+ aiAssistantMountApi.runAgentStreamCustoms.push(args[4]);const onEvent = args[2] as (event: { type: string; delta?: string }) => void;return aiAssistantMountApi.runAgentStream?.(onEvent) ?? "";},};});+vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => aiAssistantMountApi.tauriRuntime }));++// Reka's popover does not survive this harness: once a `PopoverContent` sibling+// exists, the trigger's merged click handler is dropped on its re-render, so a+// click can never open one (verified against a bare reka root in isolation).+// The panel's own logic is what these tests are about — the skill selector's open+// state, the listed rows, the chips — so the popover is stubbed to the same+// observable contract: trigger toggles, content renders only while open, and the+// closed state still emits no `[data-slot="popover-content"]`.+vi.mock("@/components/ui/popover", async () => {+ const { cloneVNode, defineComponent, h, inject, provide, ref, watch } = await import("vue");+ const contextKey = Symbol("popover-stub");+ const passthrough = (name: string) =>+ defineComponent({+ name,+ setup(_, { slots }) {+ return () => h("div", slots.default?.());+ },+ });+ const Popover = defineComponent({+ name: "PopoverStub",+ props: { open: { type: Boolean, default: false } },+ emits: ["update:open"],+ setup(props, { emit, slots }) {+ const open = ref(props.open);+ watch(+ () => props.open,+ (value) => {+ open.value = value;+ },+ );+ provide(contextKey, {+ open,+ toggle: () => {+ open.value = !open.value;+ emit("update:open", open.value);+ },+ });+ return () => h("div", { "data-slot": "popover" }, slots.default?.());+ },+ });+ const PopoverTrigger = defineComponent({+ name: "PopoverTriggerStub",+ setup(_, { slots }) {+ const context = inject<{ open: { value: boolean }; toggle: () => void } | undefined>(contextKey);+ // `as-child` semantics for a plain element trigger (the attributes land on+ // the caller's own button, which is what the panel's tests read); a trigger+ // built from a component keeps its own element and gets a wrapper instead.+ return () => {+ const attributes = {+ "data-slot": "popover-trigger",+ "aria-expanded": String(context?.open.value ?? false),+ onClick: () => context?.toggle(),+ };+ const children = slots.default?.() ?? [];+ const child = Array.isArray(children) ? children[0] : children;+ return child && typeof child.type === "string" ? cloneVNode(child, attributes) : h("span", attributes, children);+ };+ },+ });+ const PopoverContent = defineComponent({+ name: "PopoverContentStub",+ setup(_, { slots }) {+ const context = inject<{ open: { value: boolean } } | undefined>(contextKey);+ // `role="dialog"` mirrors reka's own content role, which the panel's tests read.+ return () => (context?.open.value ? h("div", { "data-slot": "popover-content", role: "dialog" }, slots.default?.()) : null);+ },+ });+ return { Popover, PopoverTrigger, PopoverContent, PopoverAnchor: passthrough("PopoverAnchorStub") };+});+vi.mock("@/lib/backend/api", async (importOriginal) => {const actual = await importOriginal<Record<string, unknown>>();const empty = () => Promise.resolve([]);@@ -75,8 +164,23 @@ vi.mock("@/lib/backend/api", async (importOriginal) => {aiAssistantMountApi.savedConversations.push(conversation);return Promise.resolve();},- readUserSkills: empty,- listUserSkills: aiAssistantMountApi.listUserSkills,+ // The send path consults the skill catalog (metadata only — bodies are read+ // on demand by the use_skill tool); an empty catalog keeps sends skill-free.+ //+ // One catalog mock serves both callers. It counts (the send path and a+ // refreshed selector both read the catalog, so a count tells them apart),+ // then delegates to the shared mock that afterEach re-arms. A test supplies a+ // catalog either by writing `skillCatalog` — the installed default+ // implementation reads it back — or by driving that mock directly.+ listUserSkills: () => {+ aiAssistantMountApi.skillListCalls += 1;+ return aiAssistantMountApi.listUserSkills();+ },+ readUserSkills: (ids: string[]) => {+ aiAssistantMountApi.skillReadCalls.push(ids);+ const result = aiAssistantMountApi.skillReadResult;+ return result ? Promise.resolve(result) : Promise.reject(new Error("readUserSkills not configured"));+ },loadAiConfigs: empty,listPlugins: empty,loadPromptTemplates: empty,@@ -103,9 +207,19 @@ afterEach(() => {aiAssistantMountApi.runAgentStream = undefined;aiAssistantMountApi.runAgentStreamInputs = [];aiAssistantMountApi.runAgentStreamHistories = [];+ aiAssistantMountApi.runAgentStreamCustoms = [];aiAssistantMountApi.savedConversations = [];aiAssistantMountApi.codeHighlighterDelayMs = 0;+ aiAssistantMountApi.skillCatalog = { defaultRoot: { status: "ok", skills: [] }, customRoot: null };+ aiAssistantMountApi.skillReadResult = undefined;+ aiAssistantMountApi.skillReadCalls = [];+ aiAssistantMountApi.skillListCalls = 0;+ aiAssistantMountApi.tauriRuntime = false;+ // Reset the shared catalog mock, then re-arm the default implementation that+ // reads `skillCatalog`: `mockReset()` alone leaves it returning undefined, so+ // every test would start from a broken catalog.aiAssistantMountApi.listUserSkills.mockReset();+ aiAssistantMountApi.listUserSkills.mockImplementation(() => Promise.resolve(aiAssistantMountApi.skillCatalog));while (cleanups.length) cleanups.pop()?.();});@@ -440,6 +554,70 @@ describe("AiAssistant mount", () => {expect(modelTrigger?.getAttribute("title")).toBe("deepseek-chat");});+ // Skill capability belongs to DBX's built-in AI only (prd 09-30 Req 15a). A CLI+ // user can still hold a selection, so the narrowed capability has to be stated:+ // a disabled control with no reason would read as a bug rather than a boundary.+ it("disables the skill selector with a reason under a CLI provider", async () => {+ const { errors, container } = await mountPanel(true, undefined, (settings) => {+ // A CLI config is only an eligible model when the runtime supports CLI+ // providers, so this test runs the panel on the Tauri lane.+ aiAssistantMountApi.tauriRuntime = true;+ settings.aiConfigs = [+ {+ id: "cli-default",+ name: "Claude Code",+ provider: "claude-code-cli",+ apiKey: "",+ authMethod: "api-key",+ endpoint: "",+ model: "",+ apiStyle: "completions",+ isDefault: true,+ },+ ];+ settings.activeModel = { configId: "cli-default", modelId: "" };+ });++ const trigger = container.querySelector<HTMLButtonElement>(".ai-skills-selector-trigger");+ expect(trigger).not.toBeNull();+ expect(trigger!.disabled).toBe(true);+ expect(trigger!.getAttribute("aria-label")).toBe(i18n.global.t("ai.skillsUnsupportedForCliProvider"));+ expect(trigger!.getAttribute("title")).toBe(i18n.global.t("ai.skillsUnsupportedForCliProvider"));+ // A disabled button is not what keeps the popover shut — clicking must not open+ // it either, or the user reaches the silent selection state this replaces.+ trigger!.click();+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(container.querySelector('[data-slot="popover-content"]')).toBeNull();+ expect(errors.map(String)).toEqual([]);+ });++ it("keeps the skill selector enabled and labelled for a built-in provider", async () => {+ const { errors, container } = await mountPanel(true, undefined, (settings) => {+ aiAssistantMountApi.tauriRuntime = true;+ settings.aiConfigs = [+ {+ id: "builtin-default",+ name: "DeepSeek",+ provider: "deepseek",+ apiKey: "test-key",+ authMethod: "api-key",+ endpoint: "https://api.deepseek.com",+ model: "deepseek-chat",+ apiStyle: "completions",+ isDefault: true,+ },+ ];+ settings.activeModel = { configId: "builtin-default", modelId: "deepseek-chat" };+ });++ const trigger = container.querySelector<HTMLButtonElement>(".ai-skills-selector-trigger");+ expect(trigger).not.toBeNull();+ expect(trigger!.disabled).toBe(false);+ expect(trigger!.getAttribute("aria-label")).toBe(i18n.global.t("ai.skillsEntry"));+ expect(trigger!.getAttribute("title")).toBe(i18n.global.t("ai.skillsEntry"));+ expect(errors.map(String)).toEqual([]);+ });+// These states settle through requestAnimationFrame plus async measurement, and the component// measures asynchronously, so they can lag the DOM. Budget by event-loop turns rather than// wall-clock: a CI worker's event loop can stall for seconds behind another worker's module@@ -964,4 +1142,600 @@ describe("AiAssistant mount", () => {expect(resaved.messages.find((message) => message.role === "user")?.selectionsOmitted).toBe(true);expect(second.errors.map(String)).toEqual([]);});++ // --- Skills (prd 09-30): the listing gate, the two chip states, the forced load ---++ const SKILL = { id: "d-review", name: "sql-review", description: "review rules" };+ const SKILL_BODY = "---\nname: sql-review\ndescription: review rules\n---\n\nAlways check the WHERE clause.";++ function configureSkillCatalog(skills: Array<{ id: string; name: string; description: string }> = [SKILL]): void {+ aiAssistantMountApi.skillCatalog = { defaultRoot: { status: "ok", skills }, customRoot: null };+ }++ function configureSkillRead(failures: Array<{ id: string; reason: string }> = []): void {+ aiAssistantMountApi.skillReadResult = failures.length ? { skills: [], failures } : { skills: [{ ...SKILL, content: SKILL_BODY }], failures: [] };+ }++ /**+ * Opens the real selector popover and returns it. Selecting a row does not close+ * it, so an already-open popover is reused.+ */+ async function openSkillSelector(container: HTMLElement): Promise<HTMLElement> {+ const trigger = container.querySelector<HTMLElement>(".ai-skills-selector-trigger")!;+ let popover = container.querySelector<HTMLElement>('[data-slot="popover-content"]');+ if (!popover) {+ trigger.click();+ await settle();+ popover = container.querySelector<HTMLElement>('[data-slot="popover-content"]');+ }+ expect(popover).not.toBeNull();+ return popover!;+ }++ /** Drives the real selector: open the popover and tick the one listed skill. */+ async function selectSkill(container: HTMLElement): Promise<void> {+ const popover = await openSkillSelector(container);+ const row = Array.from(popover.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes(SKILL.name));+ expect(row).toBeTruthy();+ row!.click();+ await settle();+ }++ function skillChip(container: HTMLElement): HTMLButtonElement | null {+ return container.querySelector<HTMLButtonElement>(".ai-skill-chip");+ }++ function skillHint(container: HTMLElement): HTMLButtonElement | null {+ return container.querySelector<HTMLButtonElement>(".ai-skill-hint");+ }++ /** The send-blocked banner is the panel's only `role="alert"` region. */+ function skillBanner(container: HTMLElement): HTMLElement | null {+ return container.querySelector<HTMLElement>('[role="alert"]');+ }++ /** A recovery action inside that banner, addressed by its rendered label. */+ function skillBannerButton(container: HTMLElement, label: string): HTMLButtonElement | undefined {+ return Array.from(container.querySelectorAll<HTMLButtonElement>('[role="alert"] button')).find((button) => button.textContent?.trim() === label);+ }++ async function sendPrompt(container: HTMLElement, text: string): Promise<void> {+ const textarea = container.querySelector<HTMLTextAreaElement>("textarea.ai-conversation-text")!;+ textarea.value = text;+ textarea.dispatchEvent(new Event("input"));+ await settle();+ sendControl(container).click();+ await settle();+ }++ function lastHistory(): Array<{ role: string; content: string; toolCalls?: Array<{ id: string; name: string; arguments: Record<string, unknown> }>; toolCallId?: string }> {+ return aiAssistantMountApi.runAgentStreamHistories.at(-1) as Array<{+ role: string;+ content: string;+ toolCalls?: Array<{ id: string; name: string; arguments: Record<string, unknown> }>;+ toolCallId?: string;+ }>;+ }++ // `/skill` rides a second command source and must reach the same selector the+ // context-row button opens, on a different trigger (the palette entry fires on+ // `mousedown` so the textarea keeps focus).+ //+ // Scope note: this file stubs the popover, so it only proves the entry exists,+ // consumes the typed command and drives the open state. The dismissal+ // regression — the programmatic open was followed by a textarea focus, which+ // reka read as focus-outside and closed the popover — is invisible behind that+ // stub and is pinned by `AiAssistant.skillPaletteFocus.spec.ts`, which mounts+ // the real popover. Keep both.+ it("opens the skill selector from the /skill palette entry", async () => {+ configureSkillCatalog();+ // Self-sufficient catalog: under `-t` this test runs alone, so the file's+ // afterEach re-arm of the default mock has not happened yet.+ aiAssistantMountApi.listUserSkills.mockImplementation(() => Promise.resolve(aiAssistantMountApi.skillCatalog));+ const { errors, container } = await mountPanel(true, POSTGRES, configureAiPanel);+ const textarea = container.querySelector<HTMLTextAreaElement>("textarea.ai-conversation-text")!;+ textarea.focus();+ textarea.value = "/skill";+ textarea.setSelectionRange(6, 6);+ textarea.dispatchEvent(new Event("input"));+ await settle();++ const paletteEntry = Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("/skill"));+ expect(paletteEntry, "/skill palette entry").toBeDefined();+ paletteEntry!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));+ await settle();++ // The typed command text is consumed either way.+ expect(textarea.value).toBe("");+ const popover = container.querySelector<HTMLElement>('[data-slot="popover-content"]');+ expect(popover, "skill selector popover").not.toBeNull();+ expect(popover!.textContent).toContain(i18n.global.t("ai.skillsGroupDefault"));+ expect(errors.map(String)).toEqual([]);+ });++ // Req 5: the toggle alone opens the gate — no selection needed — and the tool+ // flag follows the listing rather than being a second decision (ADR Decision 10).+ it("injects the skill listing from the Settings toggle with nothing selected", async () => {+ configureSkillCatalog();+ const { errors, container } = await mountPanel(true, POSTGRES, (settings) => {+ configureAiPanel(settings);+ settings.desktopSettings = { ...settings.desktopSettings, custom_ai_skill_auto_enabled: true };+ });+ expect(skillChip(container)).toBeNull();++ await sendPrompt(container, "which tables are stale?");++ const custom = aiAssistantMountApi.runAgentStreamCustoms.at(-1) as { skillListing?: string[] } | undefined;+ // The entry line is language-neutral, so the assertion does not depend on the+ // active locale; the unselected entry carries no [user-selected] marker.+ expect(custom?.skillListing?.join("\n")).toContain(`- ${SKILL.name} [default]: review rules`);+ expect((aiAssistantMountApi.runAgentStreamInputs.at(-1) as { allowSkills?: boolean }).allowSkills).toBe(true);+ // Assembled by the real prompt builder: the listing really reaches the+ // system prompt, not just the request object.+ const request = buildAgentRequest(aiAssistantMountApi.runAgentStreamInputs.at(-1) as AiRequestInput, [], custom);+ expect(request.systemPrompt).toContain(`- ${SKILL.name} [default]: review rules`);+ expect(errors.map(String)).toEqual([]);+ });++ it("lights the chip from a completed use_skill call and keeps it after reopening the panel", async () => {+ configureSkillCatalog();+ aiAssistantMountApi.runAgentStream = async (onEvent) => {+ // The id comes from the backend's own answer. Deriving it from the call+ // arguments would light a chip even when the call loaded nothing.+ onEvent({+ type: "tool_call_end",+ tool_call_id: "call-1",+ tool_name: "use_skill",+ result: { content: "skill body", explain_data: { skillId: SKILL.id } },+ is_error: false,+ });+ return "reviewed";+ };+ const first = await mountPanel(true, POSTGRES, configureAiPanel);+ await selectSkill(first.container);+ expect(skillChip(first.container)!.textContent).not.toContain(i18n.global.t("ai.skillsLoadedState"));++ await sendPrompt(first.container, "review this query");+ expect(skillChip(first.container)!.textContent).toContain(i18n.global.t("ai.skillsLoadedState"));++ // Panel closed and reopened over the same conversation. The selection itself+ // is panel-session state, so the user re-picks the skill — and the loaded+ // state must already be on the chip instead of resetting with the panel.+ const stored = aiAssistantMountApi.savedConversations.at(-1)!;+ cleanups.shift()?.();+ aiAssistantMountApi.conversations = [stored];+ aiAssistantMountApi.runAgentStreamInputs = [];+ aiAssistantMountApi.runAgentStreamHistories = [];+ aiAssistantMountApi.runAgentStreamCustoms = [];+ const second = await mountPanel(true, POSTGRES, (settings) => {+ configureAiPanel(settings);+ settings.restoreLastConversation = true;+ });+ expect(second.container.textContent).toContain("review this query");+ await selectSkill(second.container);+ expect(skillChip(second.container)!.textContent).toContain(i18n.global.t("ai.skillsLoadedState"));+ expect(second.errors.map(String)).toEqual([]);+ });++ // A `use_skill` that ends in an error loaded nothing, so no chip may claim it+ // did: a lit chip is a fact that later re-reads that skill's body into the+ // prompt.+ it("does not mark a skill loaded when the use_skill call ends in an error", async () => {+ configureSkillCatalog();+ aiAssistantMountApi.runAgentStream = async (onEvent) => {+ onEvent({ type: "tool_call_start", tool_call_id: "call-1", tool_name: "use_skill", args: { skill: SKILL.name, source: "default" } });+ // The ambiguity answer: two skills share the name, so nothing was loaded.+ onEvent({+ type: "tool_call_end",+ tool_call_id: "call-1",+ tool_name: "use_skill",+ result: { content: "Several skills are named ..." },+ is_error: true,+ });+ return "reviewed";+ };+ const { errors, container } = await mountPanel(true, POSTGRES, configureAiPanel);+ await selectSkill(container);++ await sendPrompt(container, "review this query");++ expect(skillChip(container)).not.toBeNull();+ expect(skillChip(container)!.textContent).not.toContain(i18n.global.t("ai.skillsLoadedState"));+ expect(errors.map(String)).toEqual([]);+ });++ // Regression: the load used to be recorded on `tool_call_start`, before the+ // tool had run, so an uncompleted call lit the chip.+ it("does not mark a skill loaded from an in-flight tool_call_start", async () => {+ configureSkillCatalog();+ aiAssistantMountApi.runAgentStream = async (onEvent) => {+ onEvent({ type: "tool_call_start", tool_call_id: "call-1", tool_name: "use_skill", args: { skill: SKILL.name, source: "default" } });+ return "reviewed";+ };+ const { errors, container } = await mountPanel(true, POSTGRES, configureAiPanel);+ await selectSkill(container);++ await sendPrompt(container, "review this query");++ expect(skillChip(container)).not.toBeNull();+ expect(skillChip(container)!.textContent).not.toContain(i18n.global.t("ai.skillsLoadedState"));+ expect(errors.map(String)).toEqual([]);+ });++ it("shows the one-time hint until a selected skill is loaded, and clicking it loads", async () => {+ configureSkillCatalog();+ configureSkillRead();+ const { errors, container } = await mountPanel(true, POSTGRES, configureAiPanel);++ await selectSkill(container);+ expect(skillHint(container)).not.toBeNull();+ expect(skillHint(container)!.textContent?.trim()).toBe(i18n.global.t("ai.skillsPreloadHint", { name: SKILL.name }));++ // A further turn does not spawn a second hint: it is latched, not per-turn.+ await sendPrompt(container, "anything else");+ expect(container.querySelectorAll(".ai-skill-hint").length).toBe(1);++ // Clicking it is the same force-load as the chip, and loading is what makes+ // it fall away.+ skillHint(container)!.click();+ await settle();+ expect(skillHint(container)).toBeNull();+ expect(skillChip(container)!.textContent).toContain(i18n.global.t("ai.skillsLoadedState"));+ expect(errors.map(String)).toEqual([]);+ });++ it("does not re-show the hint once it has been shown in this conversation", async () => {+ configureSkillCatalog();+ const { errors, container } = await mountPanel(true, POSTGRES, configureAiPanel);++ await selectSkill(container);+ expect(skillHint(container)).not.toBeNull();++ container.querySelector<HTMLButtonElement>(".ai-skill-chip-remove")!.click();+ await settle();+ expect(skillHint(container)).toBeNull();++ await selectSkill(container);+ expect(skillChip(container)).not.toBeNull();+ expect(skillHint(container)).toBeNull();+ expect(errors.map(String)).toEqual([]);+ });++ // Req 13's core promise: the body reaches the model, and nothing but the fact+ // reaches the record. A conversation record is the record a chat sync or backup+ // would ship, so a body (up to 1 MiB per skill) must never be written into it —+ // the same rule the #10058 selection footprint follows.+ it("replays a forced skill load without writing its body into the record", async () => {+ configureSkillCatalog();+ configureSkillRead();+ const { errors, container } = await mountPanel(true, POSTGRES, configureAiPanel);+ await selectSkill(container);++ skillChip(container)!.click();+ await settle();+ expect(aiAssistantMountApi.skillReadCalls.at(-1)).toEqual([SKILL.id]);+ expect(skillChip(container)!.textContent).toContain(i18n.global.t("ai.skillsLoadedState"));++ await sendPrompt(container, "review this query");++ const history = lastHistory();+ const call = history.find((message) => message.toolCalls?.length);+ const result = history.find((message) => message.role === "tool");+ expect(call?.toolCalls?.[0]).toMatchObject({ name: "use_skill", arguments: { skill: SKILL.name, source: "default" } });+ // The pair is a real round: the result answers the call it was paired with.+ expect(result?.toolCallId).toBe(call?.toolCalls?.[0].id);+ expect(result?.content).toContain("Always check the WHERE clause.");+ // The listing (and with it the tool table) is there for that request.+ expect((aiAssistantMountApi.runAgentStreamInputs.at(-1) as { allowSkills?: boolean }).allowSkills).toBe(true);++ const saved = aiAssistantMountApi.savedConversations.at(-1)! as unknown as {+ messages: Array<{ role: string; content: string; loadedSkillIds?: string[] }>;+ };+ // The fact, on the newest assistant turn — and no body anywhere in the record.+ expect(saved.messages.filter((message) => message.loadedSkillIds?.length).map((message) => message.loadedSkillIds)).toEqual([[SKILL.id]]);+ expect(saved.messages.some((message) => message.role === "tool")).toBe(false);+ expect(JSON.stringify(saved)).not.toContain("Always check the WHERE clause.");+ expect(errors.map(String)).toEqual([]);++ // Restart over that record: the body is gone from memory (a hand-built record+ // stands in for one written by a previous app run, so this process never held+ // the body), the chip is lit from the fact alone, and the body comes back from+ // disk for the request that needs it.+ cleanups.shift()?.();+ aiAssistantMountApi.conversations = [+ storedConversation({+ id: "conv-skill-restored",+ connectionId: "postgres",+ database: "app",+ connectionName: "PostgreSQL",+ messages: [+ { role: "user", content: "review this query" },+ { role: "assistant", content: "reviewed", loadedSkillIds: [SKILL.id] },+ ],+ }),+ ];+ aiAssistantMountApi.runAgentStreamInputs = [];+ aiAssistantMountApi.runAgentStreamHistories = [];+ aiAssistantMountApi.runAgentStreamCustoms = [];+ aiAssistantMountApi.skillReadCalls = [];+ const second = await mountPanel(true, POSTGRES, (settings) => {+ configureAiPanel(settings);+ settings.restoreLastConversation = true;+ });+ await selectSkill(second.container);+ expect(skillChip(second.container)!.textContent).toContain(i18n.global.t("ai.skillsLoadedState"));+ expect(aiAssistantMountApi.skillReadCalls).toEqual([]);++ await sendPrompt(second.container, "and the indexes?");+ expect(aiAssistantMountApi.skillReadCalls).toEqual([[SKILL.id]]);+ const replayed = lastHistory().find((message) => message.role === "tool");+ expect(replayed?.content).toContain("Always check the WHERE clause.");+ expect(second.errors.map(String)).toEqual([]);+ });++ // The body is session-only, so a conversation can outlive it (the skill was+ // deleted, or grew past the read limit). The fact must then stop claiming the+ // skill is loaded instead of leaving a lit chip over a body nobody has.+ it("clears the fact when a recorded skill can no longer be read", async () => {+ configureSkillCatalog();+ configureSkillRead([{ id: SKILL.id, reason: "oversized" }]);+ useToast().dismissToast();+ useToast().message.value = "";+ aiAssistantMountApi.conversations = [+ storedConversation({+ id: "conv-skill-gone",+ connectionId: "postgres",+ database: "app",+ connectionName: "PostgreSQL",+ messages: [+ { role: "user", content: "review this query" },+ { role: "assistant", content: "reviewed", loadedSkillIds: [SKILL.id] },+ ],+ }),+ ];+ const { errors, container } = await mountPanel(true, POSTGRES, (settings) => {+ configureAiPanel(settings);+ settings.restoreLastConversation = true;+ });+ await selectSkill(container);+ expect(skillChip(container)!.textContent).toContain(i18n.global.t("ai.skillsLoadedState"));++ await sendPrompt(container, "and the indexes?");++ // The restore was attempted for the recorded id — the body is not in this+ // process, and a distinct conversation id keeps a sibling test's session body+ // from satisfying it.+ expect(aiAssistantMountApi.skillReadCalls.at(-1)).toEqual([SKILL.id]);+ expect(useToast().message.value).toContain(i18n.global.t("ai.skillsReasonOversized"));+ expect(skillChip(container)!.textContent).not.toContain(i18n.global.t("ai.skillsLoadedState"));+ // The request still went out — without the body it could not restore.+ expect(lastHistory().some((message) => message.role === "tool")).toBe(false);+ // And the record stops asserting it: the next snapshot no longer carries it.+ const resaved = aiAssistantMountApi.savedConversations.at(-1) as { messages: Array<{ loadedSkillIds?: string[] }> };+ expect(resaved.messages.some((message) => message.loadedSkillIds?.length)).toBe(false);+ expect(errors.map(String)).toEqual([]);+ });++ // The refusal is the guard: a body that hit the read limit would be injected as+ // a tool result and wreck the context, so it is reported instead — and nothing+ // enters the history.+ it("reports a refused skill read instead of injecting a body", async () => {+ configureSkillCatalog();+ configureSkillRead([{ id: SKILL.id, reason: "oversized" }]);+ useToast().dismissToast();+ useToast().message.value = "";+ const { errors, container } = await mountPanel(true, POSTGRES, configureAiPanel);+ await selectSkill(container);++ skillChip(container)!.click();+ await settle();++ expect(aiAssistantMountApi.skillReadCalls.at(-1)).toEqual([SKILL.id]);+ expect(useToast().visible.value).toBe(true);+ expect(useToast().message.value).toContain(i18n.global.t("ai.skillsReasonOversized"));+ expect(skillChip(container)!.textContent).not.toContain(i18n.global.t("ai.skillsLoadedState"));++ await sendPrompt(container, "review this query");+ expect(lastHistory().some((message) => message.role === "tool")).toBe(false);+ expect(errors.map(String)).toEqual([]);+ });++ // The send-blocked banner (Req 15 / ADR Decision 8). Bodies load on demand, so+ // a deleted or unreadable file no longer stops a request — but a skill the user+ // ticked that is no longer in the catalog still does, and the failure has to+ // name which skill and offer the way out rather than failing silently.+ it("blocks the send and names a selected skill the catalog no longer lists", async () => {+ configureSkillCatalog();+ const { errors, container } = await mountPanel(true, POSTGRES, configureAiPanel);+ await selectSkill(container);+ expect(skillChip(container)).not.toBeNull();++ // The skill disappears between selection and send. The send path re-reads the+ // catalog (metadata only, never a body) and refuses before assembling any+ // request.+ aiAssistantMountApi.skillCatalog = { defaultRoot: { status: "ok", skills: [] }, customRoot: null };+ await sendPrompt(container, "review this query");++ expect(aiAssistantMountApi.runAgentStreamInputs).toEqual([]);+ const banner = skillBanner(container)!;+ expect(banner).not.toBeNull();+ expect(banner.textContent).toContain(i18n.global.t("ai.skillsSendBlocked"));+ expect(banner.textContent).toContain(SKILL.name);+ // An `ok` root that simply lacks the id is `not_found`. The two reasons carry+ // different copy, and only `root_unavailable` offers Open Settings.+ expect(banner.textContent).toContain(i18n.global.t("ai.skillsReasonNotFound"));+ expect(banner.textContent).not.toContain(i18n.global.t("ai.skillsReasonRootUnavailable"));+ expect(skillBannerButton(container, i18n.global.t("ai.skillsRetry"))).not.toBeUndefined();+ expect(skillBannerButton(container, i18n.global.t("ai.skillsRefresh"))).not.toBeUndefined();+ expect(skillBannerButton(container, i18n.global.t("ai.skillsOpenSettings"))).toBeUndefined();++ // Remove is the documented recovery for this case: it drops the failed id so+ // the stale selection cannot block every later send.+ const remove = Array.from(banner.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.getAttribute("aria-label") === i18n.global.t("common.remove"))!;+ expect(remove).toBeTruthy();+ remove.click();+ await settle();+ expect(skillBanner(container)).toBeNull();+ expect(skillChip(container)).toBeNull();+ expect(errors.map(String)).toEqual([]);+ });++ it("re-sends from the banner once the skill is back, and Refresh only re-reads the catalog", async () => {+ configureSkillCatalog();+ const { errors, container } = await mountPanel(true, POSTGRES, configureAiPanel);+ await selectSkill(container);+ aiAssistantMountApi.skillCatalog = { defaultRoot: { status: "ok", skills: [] }, customRoot: null };+ await sendPrompt(container, "review this query");+ expect(skillBanner(container)).not.toBeNull();++ // Refresh re-reads the catalog without sending: the failure describes what+ // the request would carry, so it stands until the request is retried.+ const before = aiAssistantMountApi.skillListCalls;+ skillBannerButton(container, i18n.global.t("ai.skillsRefresh"))!.click();+ await settle();+ expect(aiAssistantMountApi.skillListCalls).toBeGreaterThan(before);+ expect(aiAssistantMountApi.runAgentStreamInputs).toEqual([]);+ expect(skillBanner(container)).not.toBeNull();++ // Retry is a real send of the same draft. With the skill back in the+ // catalog it goes through, and the listing (with the tools) rides along.+ aiAssistantMountApi.skillCatalog = { defaultRoot: { status: "ok", skills: [SKILL] }, customRoot: null };+ skillBannerButton(container, i18n.global.t("ai.skillsRetry"))!.click();+ await settle();+ expect(aiAssistantMountApi.runAgentStreamInputs.length).toBe(1);+ expect((aiAssistantMountApi.runAgentStreamInputs[0] as { allowSkills?: boolean }).allowSkills).toBe(true);+ expect(errors.map(String)).toEqual([]);+ });++ it("reports an unavailable root and offers Open Settings only for it", async () => {+ configureSkillCatalog();+ const { errors, container } = await mountPanel(true, POSTGRES, configureAiPanel);+ await selectSkill(container);++ // The whole default root is gone (removed, disabled, or unreadable) rather+ // than just this skill. That is the one reason with a settings-shaped fix, so+ // it is the one that renders the Open Settings action.+ aiAssistantMountApi.skillCatalog = { defaultRoot: { status: "missing", skills: [] }, customRoot: null };+ await sendPrompt(container, "review this query");++ expect(aiAssistantMountApi.runAgentStreamInputs).toEqual([]);+ const banner = skillBanner(container)!;+ expect(banner.textContent).toContain(i18n.global.t("ai.skillsReasonRootUnavailable"));+ expect(banner.textContent).not.toContain(i18n.global.t("ai.skillsReasonNotFound"));+ expect(skillBannerButton(container, i18n.global.t("ai.skillsOpenSettings"))).not.toBeUndefined();+ expect(errors.map(String)).toEqual([]);+ });++ // Req 12 / 15a: a selection made under an API provider must not leak into a CLI+ // run after the user switches models — the CLI run has no skill tools at all.+ it("sends no skill content to a CLI provider even with a skill selected", async () => {+ configureSkillCatalog();+ aiAssistantMountApi.tauriRuntime = true;+ let panelSettings: ReturnType<typeof useSettingsStore> | undefined;+ const { errors, container } = await mountPanel(true, POSTGRES, (settings) => {+ panelSettings = settings;+ settings.aiConfigs = [+ {+ id: "api",+ name: "Custom",+ provider: "openai-compatible",+ apiKey: "test-key",+ authMethod: "api-key",+ endpoint: "https://example.com/v1",+ model: "test-model",+ apiStyle: "completions",+ isDefault: true,+ },+ {+ id: "cli",+ name: "Claude Code",+ provider: "claude-code-cli",+ apiKey: "",+ authMethod: "api-key",+ endpoint: "",+ model: "",+ apiStyle: "completions",+ },+ ];+ settings.activeModel = { configId: "api", modelId: "test-model" };+ });+ await selectSkill(container);+ expect(skillChip(container)).not.toBeNull();++ // Req 15a: the selection stays visible after the model switch.+ panelSettings!.activeModel = { configId: "cli", modelId: "" };+ await settle();+ expect(skillChip(container)).not.toBeNull();++ await sendPrompt(container, "review this query");++ const custom = aiAssistantMountApi.runAgentStreamCustoms.at(-1) as { skillListing?: string[] } | undefined;+ expect(custom?.skillListing).toBeUndefined();+ expect((aiAssistantMountApi.runAgentStreamInputs.at(-1) as { allowSkills?: boolean }).allowSkills).toBe(false);+ expect(errors.map(String)).toEqual([]);+ });++ // Same-root name collision. Discovery is flat, so this is two directories+ // declaring one frontmatter name; `use_skill` addresses by name + source and+ // therefore can only answer "ambiguous" here. The tool already says so — this+ // marker is how the user learns why and what to do about it.+ it("flags same-root duplicate skill names in the selector and leaves unique names alone", async () => {+ // Control run: distinct names must render no marker and no note, so the+ // assertions below cannot pass vacuously.+ configureSkillCatalog([+ { id: "d-alpha", name: "alpha", description: "first rules" },+ { id: "d-beta", name: "beta", description: "second rules" },+ ]);+ const unique = await mountPanel(true, POSTGRES, configureAiPanel);+ const uniquePopover = await openSkillSelector(unique.container);+ expect(uniquePopover.textContent).toContain("alpha");+ expect(uniquePopover.textContent).toContain("beta");+ expect(uniquePopover.querySelectorAll(".ai-skill-duplicate-name").length).toBe(0);+ expect(uniquePopover.querySelector(".ai-skill-duplicate-note")).toBeNull();+ expect(unique.errors.map(String)).toEqual([]);++ configureSkillCatalog([+ { id: "d-a", name: "sql-review", description: "rules A" },+ { id: "d-b", name: "sql-review", description: "rules B" },+ ]);+ const duplicate = await mountPanel(true, POSTGRES, configureAiPanel);+ const popover = await openSkillSelector(duplicate.container);++ const badges = Array.from(popover.querySelectorAll<HTMLElement>(".ai-skill-duplicate-name"));+ expect(badges.length).toBe(2);+ expect(badges.every((badge) => badge.textContent?.includes(i18n.global.t("ai.skillsDuplicateName")))).toBe(true);+ const note = popover.querySelector(".ai-skill-duplicate-note");+ expect(note?.textContent).toContain(i18n.global.t("ai.skillsDuplicateNameNote"));+ // The advice must name the file the user can actually edit: the collision key is+ // the frontmatter `name`, so renaming the folder would not resolve it. The literal+ // filename is identical in every locale, which makes it the stable property to pin+ // (the rest of the wording is free to change).+ expect(note?.textContent).toContain("SKILL.md");+ expect(duplicate.errors.map(String)).toEqual([]);+ });++ // The counterpart: one name in two *different* roots is resolvable (`use_skill`+ // takes a `source`), so it is normal and must stay unflagged — flagging it would+ // tell the user to rename a skill that works.+ it("does not flag a name shared across roots, where source already separates them", async () => {+ aiAssistantMountApi.skillCatalog = {+ defaultRoot: { status: "ok", skills: [{ id: "d-review", name: "sql-review", description: "default copy" }] },+ customRoot: { status: "ok", skills: [{ id: "c-review", name: "sql-review", description: "custom copy" }] },+ };+ const { errors, container } = await mountPanel(true, POSTGRES, (settings) => {+ configureAiPanel(settings);+ settings.desktopSettings = { ...settings.desktopSettings, custom_ai_skill_root_enabled: true };+ });++ const popover = await openSkillSelector(container);+ // Both groups really rendered their row, so the negative assertion below is+ // about an unflagged collision rather than about a missing catalog.+ expect(popover.textContent).toContain(i18n.global.t("ai.skillsGroupDefault"));+ expect(popover.textContent).toContain(i18n.global.t("ai.skillsGroupCustom"));+ expect(popover.textContent).toContain("default copy");+ expect(popover.textContent).toContain("custom copy");+ expect(popover.querySelectorAll(".ai-skill-duplicate-name").length).toBe(0);+ expect(popover.querySelector(".ai-skill-duplicate-note")).toBeNull();+ expect(errors.map(String)).toEqual([]);+ });});diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.skillPaletteFocus.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.skillPaletteFocus.spec.tsnew file mode 100644index 0000000000..859a302b42--- /dev/null+++ b/apps/desktop/src/components/editor/__tests__/AiAssistant.skillPaletteFocus.spec.ts@@ -0,0 +1,150 @@+// @vitest-environment happy-dom+//+// Regression spec for the `/skill` palette entry (picking `/skill` in the+// composer palette did nothing, while the identical Skills button worked).+//+// This file mounts the REAL reka-ui popover on purpose: the bug lived in reka's+// DismissableLayer, which dismisses the layer when a `focusin` lands outside it.+// `AiAssistant.mount.spec.ts` stubs the popover (its own note explains why), so+// it cannot observe a dismissal — hence a second spec with the real components.+//+// Two harness facts this spec has to arrange, or the bug is invisible:+// 1. happy-dom's `focus()` is not browser-faithful — it moves focus to a plain+// `<div>`, which a browser refuses. Reka's FocusScope focuses its container+// (a popper wrapper div) when the popover holds no tabbable element yet, so+// without the shim below the popover is dismissed by a focus event no+// browser would fire. The shim refuses focus on elements a browser refuses+// and lets the rest (buttons, `tabindex` containers, the textarea) through.+// 2. The catalog must already be loaded, so the popover mounts with its skill+// rows (tabbable buttons) and FocusScope's autofocus lands *inside* the+// layer. That is the user's real situation — the selector had been opened+// before — and it is the only state in which the textarea focus that used to+// follow can steal focus out of a freshly-opened popover.+import { createApp, h } from "vue";+import type { Pinia } from "pinia";+import { afterEach, describe, expect, it, vi } from "vitest";+import { createPinia } from "pinia";+import i18n from "@/i18n";+import { TooltipProvider } from "@/components/ui/tooltip";+import AiAssistant from "@/components/editor/AiAssistant.vue";+import { useSettingsStore } from "@/stores/settingsStore";+import { useConnectionStore } from "@/stores/connectionStore";+import { useUserSkillStore } from "@/stores/userSkillStore";+import type { ConnectionConfig } from "@/types/database";+import type { UserSkillsListResult } from "@/types/userSkills";++const SKILL = { id: "d-review", name: "sql-review", description: "review rules" };+const catalog: UserSkillsListResult = { defaultRoot: { status: "ok", skills: [SKILL] }, customRoot: null };++vi.mock("@/lib/backend/api", async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ const empty = () => Promise.resolve([]);+ return {+ ...actual,+ loadAiConversations: empty,+ loadAiRuns: empty,+ saveAiConversation: () => Promise.resolve(),+ listUserSkills: () => Promise.resolve(catalog),+ readUserSkills: empty,+ loadAiConfigs: empty,+ listPlugins: empty,+ loadPromptTemplates: empty,+ getAiGlobalCustomInstructions: () => Promise.resolve(""),+ saveAiChatSelection: () => Promise.resolve(),+ loadAiChatSelection: () => Promise.resolve(null),+ listSchemas: empty,+ listTables: empty,+ getColumns: empty,+ listIndexes: empty,+ listForeignKeys: empty,+ };+});++const POSTGRES: ConnectionConfig = { id: "postgres", name: "PostgreSQL", db_type: "postgres", host: "localhost", port: 5432, username: "", password: "", database: "app" };++const cleanups: Array<() => void> = [];++afterEach(() => {+ while (cleanups.length) cleanups.pop()?.();+});++const settle = () => new Promise((resolve) => setTimeout(resolve, 20));++/** Browser-faithful `focus()`: a plain element without a tabindex cannot take focus. */+function stubBrowserFocus(): void {+ const realFocus = HTMLElement.prototype.focus;+ const spy = vi.spyOn(HTMLElement.prototype, "focus").mockImplementation(function (this: HTMLElement, ...args: [FocusOptions?]) {+ const focusable = this instanceof HTMLButtonElement || this instanceof HTMLInputElement || this instanceof HTMLTextAreaElement || this instanceof HTMLSelectElement || this instanceof HTMLAnchorElement || this.hasAttribute("tabindex") || this.isContentEditable;+ if (!focusable) return;+ return realFocus.apply(this, args);+ });+ cleanups.push(() => spy.mockRestore());+}++async function mountPanel(): Promise<{ container: HTMLElement; pinia: Pinia }> {+ const pinia = createPinia();+ const app = createApp({ render: () => h(TooltipProvider, () => h(AiAssistant, { connection: POSTGRES })) });+ app.use(pinia);+ app.use(i18n);+ app.config.warnHandler = () => {};+ const settings = useSettingsStore(pinia);+ settings.isAiConfigLoaded = true;+ settings.aiConfigs = [+ {+ id: "custom",+ name: "Custom",+ provider: "openai-compatible",+ apiKey: "test-key",+ authMethod: "api-key",+ endpoint: "https://example.com/v1",+ model: "test-model",+ apiStyle: "completions",+ isDefault: true,+ },+ ];+ settings.activeModel = { configId: "custom", modelId: "test-model" };+ useConnectionStore(pinia).connections = [POSTGRES];+ const container = document.createElement("div");+ document.body.append(container);+ app.mount(container);+ cleanups.push(() => {+ app.unmount();+ container.remove();+ });+ await settle();+ return { container, pinia };+}++describe("AiAssistant /skill palette entry (real popover)", () => {+ it("keeps the skill selector open after picking /skill from the palette", async () => {+ stubBrowserFocus();+ const { container, pinia } = await mountPanel();+ // The user's precondition: the skill catalog is already loaded, so the popover+ // opens with its rows instead of the "Loading skills…" placeholder.+ await useUserSkillStore(pinia).refresh({ customRootEnabled: false, customRoot: null });++ const textarea = container.querySelector<HTMLTextAreaElement>("textarea.ai-conversation-text")!;+ textarea.focus();+ textarea.value = "/skill";+ textarea.setSelectionRange(6, 6);+ textarea.dispatchEvent(new Event("input"));+ await settle();++ const paletteEntry = Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.includes("/skill"));+ expect(paletteEntry, "/skill palette entry").toBeDefined();+ // Nothing is open yet, so whatever is found next came from the palette click.+ expect(document.querySelector('[role="dialog"]')).toBeNull();++ paletteEntry!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));+ await settle();++ // The typed command text is consumed either way; the popover is the assertion+ // that failed before the fix (it opened, then reka dismissed it on the+ // textarea focus that used to follow).+ expect(textarea.value).toBe("");+ const popover = document.querySelector('[role="dialog"]');+ expect(popover, "skill selector popover").not.toBeNull();+ expect(popover!.textContent).toContain(i18n.global.t("ai.skillsGroupDefault"));+ expect(popover!.textContent).toContain(SKILL.name);+ });+});diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.tsindex 44c9f6a53f..cee49d01a6 100644--- a/apps/desktop/src/i18n/locales/az.ts+++ b/apps/desktop/src/i18n/locales/az.ts@@ -3080,7 +3080,7 @@ export default withEnglishFallback({executeSafe: "Təhlükəsizlik yoxlamasından keçdi · İcra edildi",executeBlocked: "Təhlükəsizlik yoxlaması ilə bloklandı",contextCompacted: "Kontekst sıxlaşdırıldı",- skillsLoaded: "Skills yükləndi",+ skillsListed: "Skills siyahıya alındı (tələb əsasında yükləmə)",},agentStepTitles: {riskCheck: "Risk yoxlaması: {action} · {category} · {environment} · {reasons}",@@ -3308,6 +3308,7 @@ export default withEnglishFallback({templateSelectorDeselectAll: "Bütün seçimləri ləğv et",templateSelectorLoading: "Yüklənir...",skillsEntry: "Skills",+ skillsUnsupportedForCliProvider: "Skills yalnızca DBX-in daxili süni intellekti üçün əlçatandır.",skillsSelectAll: "Hamısını seç",skillsDeselectAll: "Bütün seçimləri ləğv et",skillsLoading: "Skills yüklənir…",@@ -3319,13 +3320,19 @@ export default withEnglishFallback({skillsSendBlocked: "Sorğu göndərilmədi",skillsGroupDefault: "Standart kataloq",skillsGroupCustom: "Xüsusi kataloq",+ outputTruncated: "Çıxış model limitinə çatdı və natamamdır. Davam edərək qalanını yaradın.",+ skillsDuplicateName: "Təkrarlanan ad",+ skillsDuplicateNameNote: "Bu kataloqdakı başqa bir skill eyni addan istifadə edir, ona görə AI onları ayıra bilmir. Onlardan birinin SKILL.md faylındakı name sahəsini dəyişdirin.",skillsReasonNotFound: "Skill qovluğu və ya SKILL.md artık mövcud deyil",skillsReasonRootUnavailable: "Mənbə kataloğu əlçatmazdır (deaktiv edilib, köçürülüb və ya silinib)",skillsReasonOversized: "SKILL.md 1 MiB həddini aşır",skillsReasonNotUtf8: "SKILL.md artık etibarlı UTF-8 deyil",skillsReasonInvalidFrontmatter: "SKILL.md frontmatter-də name/description yoxdur və ya format yanlışdır",skillsReasonUnreadable: "SKILL.md oxuna bilmir",- skillsTotalTrimmed: "Bəzi seçilmiş bacarıqlar birgə məzmun həddini ({max} simvol) aşdığı üçün bu göndərmədə ötürüldü.",+ skillsPreload: "Bu skili indi yüklə",+ skillsLoadedState: "Yükləndi",+ skillsPreloadHint: "Seçdiyiniz «{name}» skili bu söhbətdə hələ istifadə edilməyib · İndi yükləmək üçün klikləyin",+ skillsPreloadFailed: "Skill yüklənə bilmədi",templateSelectorEmpty: "Şablon yoxdur. Əlavə etmək üçün İdarə et düyməsinə klikləyin.",templateSelectorTooLong: "Seçilmiş şablonlar ümumi məzmun limitini ({max} simvol) aşır. Davam etmək üçün bəzilərinin seçimini ləğv edin.",templateSetDefault: "Standart olaraq təyin et",@@ -7117,6 +7124,8 @@ export default withEnglishFallback({aiSkillRootDesc: "Əlavə bir SKILL.md skill kataloqunu tarayır. ~/.agents/skills həmişə taranır.",aiSkillRootPath: "Kataloq yolu",aiSkillRootBrowse: "Göz at",+ aiSkillAutoEnabled: "AI-nın Skills-i avtomatik istifadəsinə icazə ver",+ aiSkillAutoEnabledDesc: "Heç nə seçilmədikdə belə hər sorğuya skill siyahısı əlavə edilir ki, model özü skill seçə bilsin. Skillər yalnız DBX-in daxili AI-ı üçün əlçatandır.",mcpTab: "MCP",jdbcTab: "JDBC drayverləri",securityTab: "Təhlükəsizlik",diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex a0178625c6..e78aa01265 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -3549,7 +3549,7 @@ export default {executeSafe: "Safety check passed · Executed",executeBlocked: "Blocked by safety check",contextCompacted: "Context compressed",- skillsLoaded: "Skills loaded",+ skillsListed: "Skills listed (load on demand)",},agentStepTitles: {riskCheck: "Risk check: {action} · {category} · {environment} · {reasons}",@@ -3777,6 +3777,7 @@ export default {templateSelectorDeselectAll: "Deselect All",templateSelectorLoading: "Loading...",skillsEntry: "Skills",+ skillsUnsupportedForCliProvider: "Skills are available to DBX's built-in AI only.",skillsSelectAll: "Select all",skillsDeselectAll: "Deselect all",skillsLoading: "Loading skills…",@@ -3788,13 +3789,19 @@ export default {skillsSendBlocked: "Request not sent",skillsGroupDefault: "Default directory",skillsGroupCustom: "Custom directory",+ outputTruncated: "Output reached the model limit and is incomplete. Continue to generate the rest.",+ skillsDuplicateName: "Duplicate name",+ skillsDuplicateNameNote: "Another skill in this directory has the same name, so the AI cannot tell them apart. Change the name field in one of their SKILL.md files.",skillsReasonNotFound: "The skill folder or SKILL.md no longer exists",skillsReasonRootUnavailable: "Its source directory is unavailable (disabled, moved, or deleted)",skillsReasonOversized: "SKILL.md exceeds the 1 MiB size limit",skillsReasonNotUtf8: "SKILL.md is no longer valid UTF-8",skillsReasonInvalidFrontmatter: "SKILL.md frontmatter is missing name/description or is malformed",skillsReasonUnreadable: "SKILL.md could not be read",- skillsTotalTrimmed: "Some selected skills exceed the combined content limit ({max} characters) and were skipped for this send.",+ skillsPreload: "Load this skill now",+ skillsLoadedState: "Loaded",+ skillsPreloadHint: "The skill “{name}” you selected has not been used in this conversation · Click to load it now",+ skillsPreloadFailed: "Could not load the skill",templateSelectorEmpty: "No templates. Click Manage to add.",templateSelectorTooLong: "Selected templates exceed the total content limit ({max} characters). Deselect some to continue.",templateSetDefault: "Set as default",@@ -8084,6 +8091,8 @@ export default {aiSkillRootDesc: "Scan one extra directory for SKILL.md skills. The ~/.agents/skills directory is always scanned.",aiSkillRootPath: "Directory path",aiSkillRootBrowse: "Browse",+ aiSkillAutoEnabled: "Allow the AI to use skills automatically",+ aiSkillAutoEnabledDesc: "Send the skill listing with every request, even when nothing is selected, so the model can pick a skill on its own. Skills are available to DBX's built-in AI only.",mcpTab: "MCP",jdbcTab: "JDBC Drivers",securityTab: "Security",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 51908cdcba..1a0ca082b9 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -3549,6 +3549,7 @@ export default withEnglishFallback({templateSelectorDeselectAll: "Deseleccionar todas",templateSelectorLoading: "Cargando...",skillsEntry: "Skills",+ skillsUnsupportedForCliProvider: "Las skills solo están disponibles para la IA integrada de DBX.",skillsSelectAll: "Seleccionar todo",skillsDeselectAll: "Deseleccionar todo",skillsLoading: "Cargando skills…",@@ -3560,13 +3561,19 @@ export default withEnglishFallback({skillsSendBlocked: "Solicitud no enviada",skillsGroupDefault: "Directorio predeterminado",skillsGroupCustom: "Directorio personalizado",+ outputTruncated: "La salida alcanzó el límite del modelo y está incompleta. Continúa para generar el resto.",+ skillsDuplicateName: "Nombre duplicado",+ skillsDuplicateNameNote: "Otro skill de este directorio usa el mismo nombre, así que la IA no puede distinguirlos. Cambia el campo name en uno de sus archivos SKILL.md.",skillsReasonNotFound: "La carpeta de la skill o SKILL.md ya no existe",skillsReasonRootUnavailable: "Su directorio de origen no está disponible (desactivado, movido o eliminado)",skillsReasonOversized: "SKILL.md supera el límite de 1 MiB",skillsReasonNotUtf8: "SKILL.md ya no es UTF-8 válido",skillsReasonInvalidFrontmatter: "El frontmatter de SKILL.md no tiene name/description o no es válido",skillsReasonUnreadable: "No se pudo leer SKILL.md",- skillsTotalTrimmed: "Algunas skills seleccionadas superan el límite combinado de contenido ({max} caracteres) y se omitieron en este envío.",+ skillsPreload: "Cargar esta skill ahora",+ skillsLoadedState: "Cargada",+ skillsPreloadHint: "La skill «{name}» que seleccionaste aún no se ha usado en esta conversación · Haz clic para cargarla ahora",+ skillsPreloadFailed: "No se pudo cargar la skill",templateSelectorEmpty: "Sin plantillas. Haz clic en Gestionar para añadir.",templateSelectorTooLong: "Las plantillas seleccionadas superan el límite total de contenido ({max} caracteres). Deselecciona algunas para continuar.",templateSetDefault: "Establecer como predeterminada",@@ -3631,7 +3638,7 @@ export default withEnglishFallback({executeSafe: "Verificación de seguridad superada · Ejecutado",executeBlocked: "Bloqueado por verificación de seguridad",contextCompacted: "Contexto comprimido",- skillsLoaded: "Skills cargados",+ skillsListed: "Skills listados (carga bajo demanda)",},agentStepTitles: {riskCheck: "Verificación de riesgo: {action} · {category} · {environment} · {reasons}",@@ -7372,6 +7379,8 @@ export default withEnglishFallback({aiSkillRootDesc: "Analiza un directorio adicional de skills SKILL.md. ~/.agents/skills siempre se analiza.",aiSkillRootPath: "Ruta del directorio",aiSkillRootBrowse: "Examinar",+ aiSkillAutoEnabled: "Permitir que la IA use skills automáticamente",+ aiSkillAutoEnabledDesc: "Enviar la lista de skills en cada solicitud, aunque no haya nada seleccionado, para que el modelo elija una por su cuenta. Las skills solo están disponibles para la IA integrada de DBX.",mcpTab: "MCP",jdbcTab: "Drivers JDBC",securityTab: "Seguridad",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 4010ffeadc..fd336cb44c 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -3311,6 +3311,7 @@ export default withEnglishFallback({templateSelectorDeselectAll: "Deseleziona tutto",templateSelectorLoading: "Caricamento...",skillsEntry: "Skills",+ skillsUnsupportedForCliProvider: "Le skill sono disponibili solo per l'IA integrata di DBX.",skillsSelectAll: "Seleziona tutto",skillsDeselectAll: "Deseleziona tutto",skillsLoading: "Caricamento skill…",@@ -3322,13 +3323,19 @@ export default withEnglishFallback({skillsSendBlocked: "Richiesta non inviata",skillsGroupDefault: "Directory predefinita",skillsGroupCustom: "Directory personalizzata",+ outputTruncated: "L'output ha raggiunto il limite del modello ed è incompleto. Continua per generare il resto.",+ skillsDuplicateName: "Nome duplicato",+ skillsDuplicateNameNote: "Un altro skill in questa directory usa lo stesso nome, quindi l'IA non può distinguerli. Cambia il campo name in uno dei loro file SKILL.md.",skillsReasonNotFound: "La cartella della skill o SKILL.md non esiste più",skillsReasonRootUnavailable: "La directory di origine non è disponibile (disabilitata, spostata o eliminata)",skillsReasonOversized: "SKILL.md supera il limite di 1 MiB",skillsReasonNotUtf8: "SKILL.md non è più UTF-8 valido",skillsReasonInvalidFrontmatter: "Il frontmatter di SKILL.md non ha name/description o non è valido",skillsReasonUnreadable: "Impossibile leggere SKILL.md",- skillsTotalTrimmed: "Alcune skill selezionate superano il limite combinato di contenuto ({max} caratteri) e sono state saltate in questo invio.",+ skillsPreload: "Carica questa skill ora",+ skillsLoadedState: "Caricata",+ skillsPreloadHint: "La skill «{name}» che hai selezionato non è ancora stata usata in questa conversazione · Fai clic per caricarla ora",+ skillsPreloadFailed: "Impossibile caricare la skill",templateSelectorEmpty: "Nessun modello. Clicca Gestisci per aggiungerne.",templateSelectorTooLong: "I modelli selezionati superano il limite totale di contenuto ({max} caratteri). Deseleziona alcuni per continuare.",templateSetDefault: "Imposta come predefinito",@@ -3393,7 +3400,7 @@ export default withEnglishFallback({executeSafe: "Controllo di sicurezza superato · Eseguito",executeBlocked: "Bloccato dal controllo di sicurezza",contextCompacted: "Contesto compresso",- skillsLoaded: "Skills caricati",+ skillsListed: "Skills elencati (caricamento su richiesta)",},agentStepTitles: {riskCheck: "Controllo rischi: {action} · {category} · {environment} · {reasons}",@@ -7150,6 +7157,8 @@ export default withEnglishFallback({aiSkillRootDesc: "Analizza una directory aggiuntiva di skill SKILL.md. ~/.agents/skills viene sempre analizzata.",aiSkillRootPath: "Percorso directory",aiSkillRootBrowse: "Sfoglia",+ aiSkillAutoEnabled: "Consenti all'IA di usare le skill automaticamente",+ aiSkillAutoEnabledDesc: "Invia l'elenco delle skill a ogni richiesta, anche senza selezioni, così il modello può sceglierne una da sé. Le skill sono disponibili solo per l'IA integrata di DBX.",mcpTab: "MCP",jdbcTab: "Driver JDBC",securityTab: "Sicurezza",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 44fca44b91..24ac4e2dc8 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -3429,6 +3429,7 @@ export default withEnglishFallback({templateSelectorDeselectAll: "すべて解除",templateSelectorLoading: "読み込み中...",skillsEntry: "Skills",+ skillsUnsupportedForCliProvider: "Skills は DBX 内蔵 AI でのみ利用できます。",skillsSelectAll: "すべて選択",skillsDeselectAll: "選択をすべて解除",skillsLoading: "Skills を読み込み中…",@@ -3440,13 +3441,19 @@ export default withEnglishFallback({skillsSendBlocked: "リクエストは送信されませんでした",skillsGroupDefault: "既定ディレクトリ",skillsGroupCustom: "カスタムディレクトリ",+ outputTruncated: "出力がモデルの上限に達したため、内容は不完全です。続きを生成してください。",+ skillsDuplicateName: "名前が重複",+ skillsDuplicateNameNote: "このディレクトリ内の別のスキルが同じ名前を使用しているため、AI が区別できません。どちらかの SKILL.md の name フィールドを変更してください。",skillsReasonNotFound: "Skill フォルダーまたは SKILL.md が存在しません",skillsReasonRootUnavailable: "ソースディレクトリを利用できません(無効・移動・削除)",skillsReasonOversized: "SKILL.md が 1 MiB のサイズ上限を超えています",skillsReasonNotUtf8: "SKILL.md は有効な UTF-8 ではありません",skillsReasonInvalidFrontmatter: "SKILL.md の frontmatter に name/description がないか形式が不正です",skillsReasonUnreadable: "SKILL.md を読み取れませんでした",- skillsTotalTrimmed: "選択した一部のスキルが合計上限({max} 文字)を超えたため、今回の送信ではスキップされました。",+ skillsPreload: "この Skill を今すぐ読み込む",+ skillsLoadedState: "読み込み済み",+ skillsPreloadHint: "選択した Skill「{name}」はこの会話でまだ使用されていません · クリックして今すぐ読み込む",+ skillsPreloadFailed: "Skill を読み込めませんでした",templateSelectorEmpty: "テンプレートがありません。「管理」をクリックして追加してください。",templateSelectorTooLong: "選択されたテンプレートの合計が上限({max}文字)を超えています。選択を解除してください。",templateSetDefault: "デフォルトに設定",@@ -3511,7 +3518,7 @@ export default withEnglishFallback({executeSafe: "安全チェック通過 · 実行済み",executeBlocked: "安全チェックによりブロック",contextCompacted: "コンテキストを圧縮しました",- skillsLoaded: "Skills を読み込みました",+ skillsListed: "Skills を一覧表示しました(オンデマンド読み込み)",},agentStepTitles: {riskCheck: "リスクチェック: {action} · {category} · {environment} · {reasons}",@@ -7180,6 +7187,8 @@ export default withEnglishFallback({aiSkillRootDesc: "SKILL.md スキルのディレクトリを追加で 1 件スキャンします。~/.agents/skills は常にスキャンされます。",aiSkillRootPath: "ディレクトリパス",aiSkillRootBrowse: "参照",+ aiSkillAutoEnabled: "AI に Skills の自動使用を許可する",+ aiSkillAutoEnabledDesc: "何も選択していなくてもすべてのリクエストに Skill 一覧を含め、モデルが自分で選択できるようにします。Skill は DBX 内蔵 AI でのみ利用できます。",mcpTab: "MCP",jdbcTab: "JDBCドライバー",securityTab: "セキュリティ",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex c1e31bc212..a07e4e774c 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -3246,7 +3246,7 @@ export default withEnglishFallback({executeSafe: "안전성 검사 통과 · 실행됨",executeBlocked: "안전성 검사로 차단됨",contextCompacted: "컨텍스트 압축됨",- skillsLoaded: "Skills 로드됨",+ skillsListed: "Skills 목록 표시됨(온디맨드 로드)",},agentStepTitles: {riskCheck: "위험 검사: {action} · {category} · {environment} · {reasons}",@@ -3470,6 +3470,7 @@ export default withEnglishFallback({templateSelectorDeselectAll: "모두 선택 해제",templateSelectorLoading: "불러오는 중...",skillsEntry: "Skills",+ skillsUnsupportedForCliProvider: "Skills 는 DBX 내장 AI 에서만 사용할 수 있습니다.",skillsSelectAll: "모두 선택",skillsDeselectAll: "모두 선택 해제",skillsLoading: "Skills 을(를) 로드하는 중…",@@ -3481,13 +3482,19 @@ export default withEnglishFallback({skillsSendBlocked: "요청이 전송되지 않았습니다",skillsGroupDefault: "기본 디렉터리",skillsGroupCustom: "사용자 지정 디렉터리",+ outputTruncated: "출력이 모델 한도에 도달해 내용이 불완전합니다. 계속 생성하세요.",+ skillsDuplicateName: "이름 중복",+ skillsDuplicateNameNote: "이 디렉터리의 다른 스킬이 같은 이름을 사용하고 있어 AI가 구분할 수 없습니다. 둘 중 하나의 SKILL.md에서 name 필드를 변경하세요.",skillsReasonNotFound: "Skill 폴더 또는 SKILL.md 이(가) 더 이상 존재하지 않습니다",skillsReasonRootUnavailable: "소스 디렉터리를 사용할 수 없습니다(비활성화, 이동 또는 삭제됨)",skillsReasonOversized: "SKILL.md 이(가) 1 MiB 크기 제한을 초과합니다",skillsReasonNotUtf8: "SKILL.md 이(가) 더 이상 유효한 UTF-8 이(가) 아닙니다",skillsReasonInvalidFrontmatter: "SKILL.md frontmatter 에 name/description 이(가) 없거나 형식이 잘못되었습니다",skillsReasonUnreadable: "SKILL.md 을(를) 읽을 수 없습니다",- skillsTotalTrimmed: "선택한 일부 스킬이 결합 콘텐츠 한도({max}자)를 초과하여 이번 전송에서 건너뛰었습니다.",+ skillsPreload: "이 Skill 지금 불러오기",+ skillsLoadedState: "불러옴",+ skillsPreloadHint: "선택한 Skill 「{name}」은(는) 이 대화에서 아직 사용되지 않았습니다 · 클릭하여 지금 불러오기",+ skillsPreloadFailed: "Skill 을(를) 불러올 수 없습니다",templateSelectorEmpty: "템플릿이 없습니다. 추가하려면 관리를 클릭하세요.",templateSelectorTooLong: "선택한 템플릿이 전체 내용 한도를 초과합니다 ({max}자). 계속하려면 일부를 선택 해제하세요.",templateSetDefault: "기본값으로 설정",@@ -6993,6 +7000,8 @@ export default withEnglishFallback({aiSkillRootDesc: "SKILL.md 스킬 디렉터리를 하나 더 스캔합니다. ~/.agents/skills 는 항상 스캔됩니다.",aiSkillRootPath: "디렉터리 경로",aiSkillRootBrowse: "찾아보기",+ aiSkillAutoEnabled: "AI가 Skills 를 자동으로 사용하도록 허용",+ aiSkillAutoEnabledDesc: "아무것도 선택하지 않아도 모든 요청에 Skill 목록을 포함해 모델이 스스로 선택할 수 있게 합니다. Skill 은 DBX 내장 AI 에서만 사용할 수 있습니다.",mcpTab: "MCP",jdbcTab: "JDBC 드라이버",securityTab: "보안",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex b7877e957e..29057d12f5 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -3396,6 +3396,7 @@ export default withEnglishFallback({templateSelectorDeselectAll: "Desmarcar todos",templateSelectorLoading: "Carregando...",skillsEntry: "Skills",+ skillsUnsupportedForCliProvider: "As skills estão disponíveis apenas para a IA integrada do DBX.",skillsSelectAll: "Selecionar tudo",skillsDeselectAll: "Desmarcar tudo",skillsLoading: "Carregando skills…",@@ -3407,13 +3408,19 @@ export default withEnglishFallback({skillsSendBlocked: "Solicitação não enviada",skillsGroupDefault: "Diretório padrão",skillsGroupCustom: "Diretório personalizado",+ outputTruncated: "A saída atingiu o limite do modelo e está incompleta. Continue para gerar o restante.",+ skillsDuplicateName: "Nome duplicado",+ skillsDuplicateNameNote: "Outro skill neste diretório usa o mesmo nome, então a IA não consegue distingui-los. Altere o campo name em um dos arquivos SKILL.md deles.",skillsReasonNotFound: "A pasta da skill ou o SKILL.md não existe mais",skillsReasonRootUnavailable: "O diretório de origem está indisponível (desativado, movido ou excluído)",skillsReasonOversized: "SKILL.md excede o limite de 1 MiB",skillsReasonNotUtf8: "SKILL.md não é mais UTF-8 válido",skillsReasonInvalidFrontmatter: "O frontmatter do SKILL.md está sem name/description ou é inválido",skillsReasonUnreadable: "Não foi possível ler o SKILL.md",- skillsTotalTrimmed: "Algumas skills selecionadas excedem o limite combinado de conteúdo ({max} caracteres) e foram ignoradas neste envio.",+ skillsPreload: "Carregar esta skill agora",+ skillsLoadedState: "Carregada",+ skillsPreloadHint: "A skill “{name}” que você selecionou ainda não foi usada nesta conversa · Clique para carregá-la agora",+ skillsPreloadFailed: "Não foi possível carregar a skill",templateSelectorEmpty: "Nenhum modelo. Clique em Gerenciar para adicionar.",templateSelectorTooLong: "Os modelos selecionados excedem o limite total de conteúdo ({max} caracteres). Desmarque alguns para continuar.",templateSetDefault: "Definir como padrão",@@ -3478,7 +3485,7 @@ export default withEnglishFallback({executeSafe: "Verificação de segurança aprovada · Executado",executeBlocked: "Bloqueado pela verificação de segurança",contextCompacted: "Contexto compactado",- skillsLoaded: "Skills carregados",+ skillsListed: "Skills listados (carregamento sob demanda)",},agentStepTitles: {riskCheck: "Verificação de risco: {action} · {category} · {environment} · {reasons}",@@ -7151,6 +7158,8 @@ export default withEnglishFallback({aiSkillRootDesc: "Examina um diretório adicional de skills SKILL.md. ~/.agents/skills é sempre examinado.",aiSkillRootPath: "Caminho do diretório",aiSkillRootBrowse: "Procurar",+ aiSkillAutoEnabled: "Permitir que a IA use skills automaticamente",+ aiSkillAutoEnabledDesc: "Envia a lista de skills em todas as solicitações, mesmo sem nada selecionado, para o modelo escolher uma por conta própria. As skills estão disponíveis apenas para a IA integrada do DBX.",mcpTab: "MCP",jdbcTab: "Drivers JDBC",securityTab: "Segurança",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex fed66ba762..c74ad3925d 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -3407,7 +3407,7 @@ export default withEnglishFallback({executeSafe: "Проверка безопасности пройдена · Выполнено",executeBlocked: "Заблокировано проверкой безопасности",contextCompacted: "Контекст сжат",- skillsLoaded: "Навыки загружены",+ skillsListed: "Навыки перечислены (загрузка по требованию)",},agentStepTitles: {riskCheck: "Проверка риска: {action} · {category} · {environment} · {reasons}",@@ -3635,6 +3635,7 @@ export default withEnglishFallback({templateSelectorDeselectAll: "Снять выделение",templateSelectorLoading: "Загрузка...",skillsEntry: "Навыки",+ skillsUnsupportedForCliProvider: "Навыки доступны только встроенному ИИ DBX.",skillsSelectAll: "Выбрать все",skillsDeselectAll: "Снять выделение",skillsLoading: "Загрузка навыков…",@@ -3646,13 +3647,19 @@ export default withEnglishFallback({skillsSendBlocked: "Запрос не отправлен",skillsGroupDefault: "Каталог по умолчанию",skillsGroupCustom: "Пользовательский каталог",+ outputTruncated: "Вывод достиг лимита модели и неполон. Продолжите генерацию.",+ skillsDuplicateName: "Дублирующееся имя",+ skillsDuplicateNameNote: "Другой навык в этом каталоге использует то же имя, поэтому ИИ не может их различить. Измените поле name в одном из их файлов SKILL.md.",skillsReasonNotFound: "Папка навыка или SKILL.md больше не существует",skillsReasonRootUnavailable: "Его исходный каталог недоступен (отключён, перемещён или удалён)",skillsReasonOversized: "SKILL.md превышает ограничение размера в 1 МиБ",skillsReasonNotUtf8: "SKILL.md больше не является корректным UTF-8",skillsReasonInvalidFrontmatter: "В frontmatter файла SKILL.md отсутствует name/description или он имеет неверный формат",skillsReasonUnreadable: "Не удалось прочитать SKILL.md",- skillsTotalTrimmed: "Некоторые выбранные навыки превышают общий лимит содержимого ({max} символов) и были пропущены при этой отправке.",+ skillsPreload: "Загрузить этот навык сейчас",+ skillsLoadedState: "Загружен",+ skillsPreloadHint: "Выбранный навык «{name}» ещё не использовался в этом диалоге · Нажмите, чтобы загрузить его сейчас",+ skillsPreloadFailed: "Не удалось загрузить навык",templateSelectorEmpty: "Шаблонов нет. Нажмите «Управление», чтобы добавить.",templateSelectorTooLong: "Выбранные шаблоны превышают общий лимит содержимого ({max} символов). Снимите выделение с некоторых, чтобы продолжить.",templateSetDefault: "Сделать по умолчанию",@@ -8393,6 +8400,8 @@ export default withEnglishFallback({aiSkillRootDesc: "Сканировать дополнительный каталог на наличие навыков SKILL.md. Каталог ~/.agents/skills сканируется всегда.",aiSkillRootPath: "Путь к каталогу",aiSkillRootBrowse: "Обзор",+ aiSkillAutoEnabled: "Разрешить ИИ автоматически использовать навыки",+ aiSkillAutoEnabledDesc: "Отправлять список навыков с каждым запросом, даже если ничего не выбрано, чтобы модель могла выбрать навык сама. Навыки доступны только встроенному ИИ DBX.",mcpTab: "MCP",jdbcTab: "Драйверы JDBC",securityTab: "Безопасность",diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.tsindex 7660e85937..acb924d6f4 100644--- a/apps/desktop/src/i18n/locales/tr.ts+++ b/apps/desktop/src/i18n/locales/tr.ts@@ -3054,7 +3054,7 @@ export default withEnglishFallback({executeSafe: "Güvenlik denetimi geçildi · Çalıştırıldı",executeBlocked: "Güvenlik denetimi tarafından engellendi",contextCompacted: "Bağlam sıkıştırıldı",- skillsLoaded: "Skills yüklendi",+ skillsListed: "Skills listelendi (isteğe bağlı yükleme)",},agentStepTitles: {riskCheck: "Risk denetimi: {action} · {category} · {environment} · {reasons}",@@ -3279,6 +3279,7 @@ export default withEnglishFallback({templateSelectorDeselectAll: "Tüm Seçimleri Kaldır",templateSelectorLoading: "Yükleniyor...",skillsEntry: "Skills",+ skillsUnsupportedForCliProvider: "Skills yalnızca DBX'in yerleşik yapay zekası için kullanılabilir.",skillsSelectAll: "Tümünü seç",skillsDeselectAll: "Tümünün seçimini kaldır",skillsLoading: "Skills yükleniyor…",@@ -3290,13 +3291,19 @@ export default withEnglishFallback({skillsSendBlocked: "İstek gönderilmedi",skillsGroupDefault: "Varsayılan dizin",skillsGroupCustom: "Özel dizin",+ outputTruncated: "Çıktı model sınırına ulaştı ve eksik. Devam ederek kalanını oluşturun.",+ skillsDuplicateName: "Yinelenen ad",+ skillsDuplicateNameNote: "Bu dizindeki başka bir skill aynı adı kullanıyor, bu yüzden AI ikisini ayırt edemez. Birinin SKILL.md dosyasındaki name alanını değiştirin.",skillsReasonNotFound: "Skill klasörü veya SKILL.md artık mevcut değil",skillsReasonRootUnavailable: "Kaynak dizini kullanılamıyor (devre dışı, taşınmış veya silinmiş)",skillsReasonOversized: "SKILL.md 1 MiB sınırını aşıyor",skillsReasonNotUtf8: "SKILL.md artık geçerli UTF-8 değil",skillsReasonInvalidFrontmatter: "SKILL.md frontmatter içinde name/description eksik veya biçim geçersiz",skillsReasonUnreadable: "SKILL.md okunamadı",- skillsTotalTrimmed: "Bazı seçili beceriler birleşik içerik sınırını ({max} karakter) aştığı için bu gönderimde atlandı.",+ skillsPreload: "Bu skill'i şimdi yükle",+ skillsLoadedState: "Yüklendi",+ skillsPreloadHint: "Seçtiğiniz «{name}» skill'i bu sohbette henüz kullanılmadı · Şimdi yüklemek için tıklayın",+ skillsPreloadFailed: "Skill yüklenemedi",templateSelectorEmpty: "Şablon yok. Eklemek için Yönet'e tıklayın.",templateSelectorTooLong: "Seçili şablonlar toplam içerik sınırını aşıyor ({max} karakter). Devam etmek için bazılarının seçimini kaldırın.",templateSetDefault: "Varsayılan yap",@@ -6999,6 +7006,8 @@ export default withEnglishFallback({aiSkillRootDesc: "Bir SKILL.md skill dizinini daha tarar. ~/.agents/skills her zaman taranır.",aiSkillRootPath: "Dizin yolu",aiSkillRootBrowse: "Gözat",+ aiSkillAutoEnabled: "AI'nın Skills'i otomatik kullanmasına izin ver",+ aiSkillAutoEnabledDesc: "Hiçbir şey seçilmemiş olsa bile her istekte skill listesini gönderir; böylece model kendi başına bir skill seçebilir. Skill'ler yalnızca DBX'in yerleşik AI'sında kullanılabilir.",mcpTab: "MCP",jdbcTab: "JDBC Sürücüleri",securityTab: "Güvenlik",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 8643cdadca..7ba224c5da 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -3483,7 +3483,7 @@ export default withEnglishFallback({executeSafe: "安全检查通过 · 已执行",executeBlocked: "安全检查拦截",contextCompacted: "上下文已压缩",- skillsLoaded: "已加载上下文 Skills",+ skillsListed: "Skills 已列出(按需加载)",},agentStepTitles: {riskCheck: "风险检查:{action} · {category} · {environment} · {reasons}",@@ -3711,6 +3711,7 @@ export default withEnglishFallback({templateSelectorDeselectAll: "全不选",templateSelectorLoading: "加载中...",skillsEntry: "Skills",+ skillsUnsupportedForCliProvider: "Skill 仅对 DBX 内置 AI 可用。",skillsSelectAll: "全选",skillsDeselectAll: "取消全选",skillsLoading: "正在加载 Skills…",@@ -3722,13 +3723,19 @@ export default withEnglishFallback({skillsSendBlocked: "请求未发送",skillsGroupDefault: "默认目录",skillsGroupCustom: "自定义目录",+ outputTruncated: "输出已达到模型上限,以上内容不完整。请点击继续生成。",+ skillsDuplicateName: "名称重复",+ skillsDuplicateNameNote: "该目录下另一个 Skill 使用了相同名称,AI 无法区分它们。请修改其中一个 SKILL.md 的 name 字段。",skillsReasonNotFound: "Skill 目录或 SKILL.md 已不存在",skillsReasonRootUnavailable: "来源目录不可用(已禁用、移动或删除)",skillsReasonOversized: "SKILL.md 超过 1 MiB 大小限制",skillsReasonNotUtf8: "SKILL.md 已不是有效的 UTF-8 编码",skillsReasonInvalidFrontmatter: "SKILL.md frontmatter 缺少 name/description 或格式无效",skillsReasonUnreadable: "无法读取 SKILL.md",- skillsTotalTrimmed: "部分已选 Skills 合计超出内容上限(最多 {max} 字符),本次发送已跳过。",+ skillsPreload: "立即加载该 Skill",+ skillsLoadedState: "已加载",+ skillsPreloadHint: "你选择的 Skill「{name}」本次对话尚未被 AI 使用 · 点此立即加载",+ skillsPreloadFailed: "无法加载该 Skill",templateSelectorEmpty: "暂无模板,请点击管理添加。",templateSelectorTooLong: "已选模板内容合计超过限制(最多 {max} 字符),请取消部分勾选。",templateSetDefault: "设为默认",@@ -8070,6 +8077,8 @@ export default withEnglishFallback({aiSkillRootDesc: "额外扫描一个 SKILL.md 技能目录。~/.agents/skills 目录始终会被扫描。",aiSkillRootPath: "目录路径",aiSkillRootBrowse: "浏览",+ aiSkillAutoEnabled: "允许 AI 自动使用 Skills",+ aiSkillAutoEnabledDesc: "每次请求都附带 Skill 列表(即使未勾选任何 Skill),让模型自行判断是否需要加载。Skill 仅对 DBX 内置 AI 可用。",mcpTab: "MCP",jdbcTab: "JDBC 驱动",securityTab: "安全",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 62ab7a3510..c18caede37 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -3318,6 +3318,7 @@ export default withEnglishFallback({templateSelectorDeselectAll: "取消全選",templateSelectorLoading: "載入中...",skillsEntry: "Skills",+ skillsUnsupportedForCliProvider: "Skill 僅對 DBX 內建 AI 可用。",skillsSelectAll: "全選",skillsDeselectAll: "取消全選",skillsLoading: "正在載入 Skills…",@@ -3329,13 +3330,19 @@ export default withEnglishFallback({skillsSendBlocked: "請求未送出",skillsGroupDefault: "預設目錄",skillsGroupCustom: "自訂目錄",+ outputTruncated: "輸出已達模型上限,以上內容不完整。請點擊繼續產生。",+ skillsDuplicateName: "名稱重複",+ skillsDuplicateNameNote: "此目錄下另一個 Skill 使用了相同名稱,AI 無法區分它們。請修改其中一個 SKILL.md 的 name 欄位。",skillsReasonNotFound: "Skill 目錄或 SKILL.md 已不存在",skillsReasonRootUnavailable: "來源目錄不可用(已停用、移動或刪除)",skillsReasonOversized: "SKILL.md 超過 1 MiB 大小限制",skillsReasonNotUtf8: "SKILL.md 已不是有效的 UTF-8 編碼",skillsReasonInvalidFrontmatter: "SKILL.md frontmatter 缺少 name/description 或格式無效",skillsReasonUnreadable: "無法讀取 SKILL.md",- skillsTotalTrimmed: "部分已選 Skills 合計超出內容上限(最多 {max} 字元),本次傳送已略過。",+ skillsPreload: "立即載入該 Skill",+ skillsLoadedState: "已載入",+ skillsPreloadHint: "你選擇的 Skill「{name}」本次對話尚未被 AI 使用 · 點此立即載入",+ skillsPreloadFailed: "無法載入該 Skill",templateSelectorEmpty: "尚無範本,請點擊管理以新增。",templateSelectorTooLong: "已選範本內容合計超過限制(最多 {max} 字元),請取消部分選取。",templateSetDefault: "設為預設",@@ -3375,7 +3382,7 @@ export default withEnglishFallback({executeSafe: "安全檢查通過 · 已執行",executeBlocked: "安全檢查攔截",contextCompacted: "上下文已壓縮",- skillsLoaded: "已載入上下文 Skills",+ skillsListed: "Skills 已列出(按需載入)",},agentStepTitles: {riskCheck: "風險檢查:{action} · {category} · {environment} · {reasons}",@@ -6465,6 +6472,8 @@ export default withEnglishFallback({aiSkillRootDesc: "額外掃描一個 SKILL.md 技能目錄。~/.agents/skills 目錄始終會被掃描。",aiSkillRootPath: "目錄路徑",aiSkillRootBrowse: "瀏覽",+ aiSkillAutoEnabled: "允許 AI 自動使用 Skills",+ aiSkillAutoEnabledDesc: "每次請求都附帶 Skill 清單(即使未勾選任何 Skill),讓模型自行判斷是否需要載入。Skill 僅對 DBX 內建 AI 可用。",jdbcTab: "JDBC 驅動程式",securityTab: "安全",aboutTab: "關於我們",diff --git a/apps/desktop/src/lib/__tests__/ai/ai.spec.ts b/apps/desktop/src/lib/__tests__/ai/ai.spec.tsindex afd2323af8..0d8bf5fe55 100644--- a/apps/desktop/src/lib/__tests__/ai/ai.spec.ts+++ b/apps/desktop/src/lib/__tests__/ai/ai.spec.ts@@ -1,5 +1,5 @@import { beforeAll, describe, expect, it, vi } from "vitest";-import { buildAgentRequest, buildSystemPrompt, buildUserPrompt, runAgentStream, type AiContext } from "@/lib/ai/ai";+import { buildAgentRequest, buildSystemPrompt, buildUserPrompt, runAgentStream, type AiContext, type AiRequestInput } from "@/lib/ai/ai";import * as api from "@/lib/backend/api";import { setLocale } from "@/i18n";@@ -50,6 +50,29 @@ describe("AI SQL dialect prompt", () => {await setLocale("en");});+ // The skill tools ship with the listing, so the flag and the listing must+ // travel together (ADR Decision 10); a send without a listing must not turn+ // them on.+ it("forwards the skill-listing flag only when the listing is sent", async () => {+ const stream = vi.spyOn(api, "aiAgentStream").mockResolvedValue("done");+ try {+ const input: AiRequestInput = {+ config: { provider: "openai", apiKey: "test", apiUrl: "https://example.invalid", model: "model" },+ action: "general",+ mode: "agent",+ instruction: "Use the skill",+ context: context(),+ };+ await runAgentStream({ ...input, allowSkills: true }, [], () => {}, "skill-run");+ expect(stream.mock.calls[0][15]).toBe(true);++ await runAgentStream(input, [], () => {}, "plain-run");+ expect(stream.mock.calls[1][15]).toBe(false);+ } finally {+ stream.mockRestore();+ }+ });+it("pins identifier quoting to the active database type", () => {const prompt = buildSystemPrompt("generate", context(), "ask");diff --git a/apps/desktop/src/lib/__tests__/ai/aiContext.spec.ts b/apps/desktop/src/lib/__tests__/ai/aiContext.spec.tsindex e1769ec036..0c74264314 100644--- a/apps/desktop/src/lib/__tests__/ai/aiContext.spec.ts+++ b/apps/desktop/src/lib/__tests__/ai/aiContext.spec.ts@@ -132,7 +132,7 @@ describe("Dameng AI context routing", () => {vi.fn(),"session-1",);- expect(apiMock.aiAgentStream).toHaveBeenCalledWith("session-1", expect.any(Object), "dameng-1", "APPDB", "REPORTING", "dameng", expect.any(Function), "agent", false, undefined, undefined, undefined, undefined);+ expect(apiMock.aiAgentStream).toHaveBeenCalledWith("session-1", expect.any(Object), "dameng-1", "APPDB", "REPORTING", "dameng", expect.any(Function), "agent", false, undefined, undefined, undefined, undefined, undefined, undefined, false);});it("models the AI selector as a schema and chooses the connected user by default", () => {@@ -189,7 +189,7 @@ describe("PostgreSQL AI schema routing", () => {vi.fn(),"session-postgres",);- expect(apiMock.aiAgentStream).toHaveBeenCalledWith("session-postgres", expect.any(Object), "postgres-1", "app", "main_chatdr", "postgres", expect.any(Function), "agent", false, undefined, undefined, undefined, undefined);+ expect(apiMock.aiAgentStream).toHaveBeenCalledWith("session-postgres", expect.any(Object), "postgres-1", "app", "main_chatdr", "postgres", expect.any(Function), "agent", false, undefined, undefined, undefined, undefined, undefined, undefined, false);});});diff --git a/apps/desktop/src/lib/__tests__/ai/aiSkillsPrompt.spec.ts b/apps/desktop/src/lib/__tests__/ai/aiSkillsPrompt.spec.tsindex 5eaa66d6de..bea5637fe9 100644--- a/apps/desktop/src/lib/__tests__/ai/aiSkillsPrompt.spec.ts+++ b/apps/desktop/src/lib/__tests__/ai/aiSkillsPrompt.spec.ts@@ -1,7 +1,8 @@import { beforeAll, describe, expect, it } from "vitest";import { buildSystemPrompt, type AiContext, type CustomPromptContext } from "@/lib/ai/ai";+import { buildSkillListing, buildSkillListingLines } from "@/lib/ai/skillListing";import { setLocale } from "@/i18n";-import type { ReadUserSkill } from "@/types/userSkills";+import type { UserSkillMeta } from "@/types/userSkills";function context(overrides: Partial<AiContext> = {}): AiContext {return {@@ -18,12 +19,22 @@ function context(overrides: Partial<AiContext> = {}): AiContext {};}-const skill: ReadUserSkill = {- id: "d-abc123",- name: "SQL Review",- description: "Team SQL review rules",- content: "Always prefix reviews with EXPLAIN checks.",-};+const catalog: UserSkillMeta[] = [{ id: "d-abc123", name: "SQL Review", description: "Team SQL review rules" }];++/**+ * The SKILL.md body text this feature stopped injecting. The catalog carries no+ * body at all any more, so this can only reappear in a prompt if whole-body+ * injection is reintroduced — which is exactly what the assertions below pin.+ * Skill capability is DBX's built-in AI only: a CLI run gets neither the listing+ * nor the body.+ */+const SKILL_BODY_SENTINEL = "Always prefix reviews with EXPLAIN checks.";++// Rendered through the real formatter so the test pins the prompt/catalog+// integration rather than a hand-written copy of the listing text.+function listing(isZh = false): string[] {+ return buildSkillListingLines(buildSkillListing({ skills: catalog, selectedIds: ["d-abc123"] }), isZh);+}// buildSystemPrompt picks zh/en copy via currentLocale(); pin to en so the// English-string assertions are deterministic regardless of the host OS locale.@@ -31,47 +42,60 @@ beforeAll(async () => {await setLocale("en");});-describe("selected skills prompt injection", () => {- it("injects selected skills into the SQL, Redis, and vector branches", () => {+describe("skill listing prompt injection", () => {+ it("injects the listing — and no body — into the SQL, Redis, and vector branches", () => {for (const ctx of [context(), context({ databaseType: "redis", connectionName: "Redis", database: "8" }), context({ databaseType: "qdrant", connectionName: "Qdrant", database: "vec" })]) {- const prompt = buildSystemPrompt("general", ctx, "ask", { selectedSkills: [skill] });- expect(prompt).toContain("## Selected Skills (supplementary)");- expect(prompt).toContain("### Skill: SQL Review");- expect(prompt).toContain('<ai-skill id="d-abc123">');- expect(prompt).toContain("Always prefix reviews with EXPLAIN checks.");- expect(prompt).toContain("</ai-skill>");+ const prompt = buildSystemPrompt("general", ctx, "ask", { skillListing: listing() });+ expect(prompt).toContain("## Available Skills (loaded on demand)");+ expect(prompt).toContain("- SQL Review [default] [user-selected]: Team SQL review rules");+ expect(prompt).toContain("call the use_skill tool first");+ // The matched skill is selected, so the strong wording must be present.+ expect(prompt).toContain("were chosen explicitly by the user");+ expect(prompt).not.toContain("<ai-skill");+ expect(prompt).not.toContain(SKILL_BODY_SENTINEL);}});- it("injects the zh header for zh locale", async () => {+ it("injects the zh listing header for zh locale", async () => {await setLocale("zh-CN");try {- const prompt = buildSystemPrompt("general", context(), "ask", { selectedSkills: [skill] });- expect(prompt).toContain("## 用户选择的 Skills(补充性)");- expect(prompt).toContain("按原样注入");+ const prompt = buildSystemPrompt("general", context(), "ask", { skillListing: listing(true) });+ expect(prompt).toContain("## 可用 Skills(按需加载)");+ expect(prompt).toContain("由用户显式选择");} finally {await setLocale("en");}});- it("leaves prompts byte-for-byte unchanged when no skills are selected", () => {- // AC: with no selected skills, every prompt branch is byte-identical to the+ it("keeps the custom-instructions wrapper byte-identical when a listing is added", () => {+ // The listing must sit OUTSIDE the `## Custom Instructions` wrapper: that+ // wrapper's text is shared with the templates path, so folding skills into it+ // would change the wrapper for users who never touch skills.+ const wrapper = "## Custom Instructions (supplementary)\nThe following are user-defined conventions and templates. Core safety and dialect rules above take precedence.\n\nGlobal rule.";+ const withGlobals = buildSystemPrompt("general", context(), "ask", { globalInstructions: "Global rule." });+ const withListing = buildSystemPrompt("general", context(), "ask", { globalInstructions: "Global rule.", skillListing: listing() });+ expect(withGlobals).toContain(wrapper);+ expect(withListing).toContain(wrapper);+ expect(withListing.indexOf("## Available Skills (loaded on demand)")).toBeGreaterThan(withListing.indexOf(wrapper));+ });++ it("leaves prompts byte-for-byte unchanged when nothing is listed", () => {+ // AC: with no skills selected, every prompt branch is byte-identical to the// pre-feature baseline. Absent field, empty array, and undefined custom all// must agree exactly.const baseline = buildSystemPrompt("general", context(), "ask");const withGlobals: CustomPromptContext = { globalInstructions: "Global rule." };- const withEmptySkills: CustomPromptContext = { globalInstructions: "Global rule.", selectedSkills: [] };+ const withEmptyListing: CustomPromptContext = { globalInstructions: "Global rule.", skillListing: [] };for (const ctx of [context(), context({ databaseType: "redis", connectionName: "Redis", database: "8" }), context({ databaseType: "milvus", connectionName: "Milvus", database: "vec" })]) {expect(buildSystemPrompt("general", ctx, "ask")).toBe(buildSystemPrompt("general", ctx, "ask", undefined));- expect(buildSystemPrompt("general", ctx, "ask", withEmptySkills)).toBe(buildSystemPrompt("general", ctx, "ask", withGlobals));- expect(buildSystemPrompt("general", ctx, "ask", withEmptySkills)).not.toBe(baseline); // globals still apply+ expect(buildSystemPrompt("general", ctx, "ask", withEmptyListing)).toBe(buildSystemPrompt("general", ctx, "ask", withGlobals));+ expect(buildSystemPrompt("general", ctx, "ask", withEmptyListing)).not.toBe(baseline); // globals still apply}});- it("treats blank-content skills as absent", () => {- const blank: ReadUserSkill = { ...skill, content: " " };- const withBlank = buildSystemPrompt("general", context(), "ask", { selectedSkills: [blank] });- expect(withBlank).toBe(buildSystemPrompt("general", context(), "ask"));- expect(withBlank).not.toContain("ai-skill");+ it("treats an empty listing as absent", () => {+ const withEmpty: CustomPromptContext = { skillListing: [] };+ expect(buildSystemPrompt("general", context(), "ask", withEmpty)).toBe(buildSystemPrompt("general", context(), "ask"));+ expect(buildSystemPrompt("general", context(), "ask", withEmpty)).not.toContain("Available Skills");});});diff --git a/apps/desktop/src/lib/__tests__/ai/skillListing.spec.ts b/apps/desktop/src/lib/__tests__/ai/skillListing.spec.tsnew file mode 100644index 0000000000..28b3baec13--- /dev/null+++ b/apps/desktop/src/lib/__tests__/ai/skillListing.spec.ts@@ -0,0 +1,120 @@+import { describe, expect, it } from "vitest";++import { buildSkillListing, buildSkillListingLines, SKILL_LISTING_UNCHECKED_ENTRY_MAX } from "@/lib/ai/skillListing";+import type { UserSkillMeta } from "@/types/userSkills";++function meta(id: string, name: string, description: string): UserSkillMeta {+ return { id, name, description };+}++/** `- a [default]: x` — one long-enough description to make each ladder rung reachable. */+const LONG = "d".repeat(900);++describe("buildSkillListing", () => {+ it("returns nothing for an empty catalog", () => {+ expect(buildSkillListing({ skills: [], selectedIds: [] }).lines).toEqual([]);+ });++ it("marks the source root and flags user-selected entries", () => {+ const listing = buildSkillListing({+ skills: [meta("d-1", "alpha", "A rules"), meta("c-2", "beta", "B rules")],+ selectedIds: ["d-1"],+ });++ expect(listing.lines).toEqual(["- beta [custom]: B rules", "- alpha [default] [user-selected]: A rules"]);+ expect(listing.truncated).toBe(false);+ });++ it("orders custom-root entries first, then by name, then by id", () => {+ const listing = buildSkillListing({+ skills: [meta("d-b", "zeta", "z"), meta("c-a", "Alpha", "a"), meta("d-a", "alpha", "a2"), meta("c-b", "alpha", "a3")],+ selectedIds: [],+ });++ expect(listing.lines.map((line) => line.split(":")[0])).toEqual(["- Alpha [custom]", "- alpha [custom]", "- alpha [default]", "- zeta [default]"]);+ });++ it("drops duplicate ids instead of rendering a skill twice", () => {+ const listing = buildSkillListing({ skills: [meta("d-1", "alpha", "a"), meta("d-1", "alpha", "a")], selectedIds: [] });+ expect(listing.lines).toHaveLength(1);+ });++ it("flattens multi-line descriptions into a single line", () => {+ const listing = buildSkillListing({ skills: [meta("d-1", "alpha", "line one\nline two")], selectedIds: [] });+ expect(listing.lines).toEqual(["- alpha [default]: line one line two"]);+ });++ // Ladder rung 1 → 2: an unselected description clamps to 200 while the+ // selected entry keeps its full description, because the user's explicit+ // pick is the only routing signal the model gets for it.+ it("clamps unselected descriptions before touching selected ones", () => {+ const listing = buildSkillListing({+ skills: [meta("d-1", "picked", LONG), meta("d-2", "other", LONG)],+ selectedIds: ["d-1"],+ totalMax: 1500,+ });++ expect(listing.truncated).toBe(true);+ const picked = listing.lines.find((line) => line.includes("picked"));+ expect(picked).toBe(`- picked [default] [user-selected]: ${LONG}`);++ const other = listing.lines.find((line) => line.includes("other"));+ const description = other!.split(": ")[1];+ expect(description.endsWith("…")).toBe(true);+ expect(Array.from(description)).toHaveLength(SKILL_LISTING_UNCHECKED_ENTRY_MAX);+ });++ // Ladder rung 2 → 3.+ it("reduces unselected entries to name and source when the clamp is still too wide", () => {+ const listing = buildSkillListing({+ skills: [meta("d-1", "picked", LONG), meta("d-2", "other", LONG)],+ selectedIds: ["d-1"],+ totalMax: 1000,+ });++ expect(listing.lines).toContain(`- picked [default] [user-selected]: ${LONG}`);+ expect(listing.lines).toContain("- other [default]");+ });++ // Ladder rung 3 → 4: selected entries survive even when they alone overflow+ // the budget; the listing reports the overflow instead of dropping them.+ it("drops unselected entries from the tail and never drops a selected one", () => {+ const listing = buildSkillListing({+ skills: [meta("d-1", "picked", LONG), meta("d-2", "other", LONG), meta("d-3", "another", LONG)],+ selectedIds: ["d-1"],+ totalMax: 500,+ });++ expect(listing.truncated).toBe(true);+ expect(listing.lines).toEqual(["- picked [default] [user-selected]: " + LONG]);+ });++ it("caps the entry count on the unselected tail only", () => {+ const skills = [meta("d-1", "picked", "p"), meta("d-2", "a", "a"), meta("d-3", "b", "b")];+ const listing = buildSkillListing({ skills, selectedIds: ["d-1"], maxEntries: 2 });++ // Global name order is a, b, picked — the cap drops the last unselected+ // entry (b) and keeps the selected one regardless of its position.+ expect(listing.truncated).toBe(true);+ expect(listing.lines).toEqual(["- a [default]: a", "- picked [default] [user-selected]: p"]);+ });+});++describe("buildSkillListingLines", () => {+ it("emits nothing without entries, so an unused skill feature leaves the prompt untouched", () => {+ expect(buildSkillListingLines({ lines: [], truncated: false }, false)).toEqual([]);+ });++ it("names the use_skill tool and the user-selected marker in both locales", () => {+ const listing = buildSkillListing({ skills: [meta("d-1", "alpha", "a")], selectedIds: ["d-1"] });++ const en = buildSkillListingLines(listing, false).join("\n");+ expect(en).toContain("use_skill");+ expect(en).toContain("user-selected");+ expect(en).toContain("- alpha [default] [user-selected]: a");++ const zh = buildSkillListingLines(listing, true).join("\n");+ expect(zh).toContain("use_skill");+ expect(zh).toContain("user-selected");+ });+});diff --git a/apps/desktop/src/lib/__tests__/ai/userSkillSelection.spec.ts b/apps/desktop/src/lib/__tests__/ai/userSkillSelection.spec.tsindex edeaaa101e..588b2947a1 100644--- a/apps/desktop/src/lib/__tests__/ai/userSkillSelection.spec.ts+++ b/apps/desktop/src/lib/__tests__/ai/userSkillSelection.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { buildSelectedSkillChips, capSkillsToCharLimit, removeSkillIds, userSkillSourceOfId } from "@/lib/ai/userSkillSelection";-import { ACTIVE_SKILLS_TOTAL_MAX, type ReadUserSkill, type UserSkillMeta } from "@/types/userSkills";+import { buildSelectedSkillChips, removeSkillIds, userSkillSourceOfId } from "@/lib/ai/userSkillSelection";+import type { UserSkillMeta } from "@/types/userSkills";const catalog: Record<string, UserSkillMeta> = {"d-aaa": { id: "d-aaa", name: "SQL Review", description: "review rules" },@@ -8,10 +8,6 @@ const catalog: Record<string, UserSkillMeta> = {};const lookup = (id: string): UserSkillMeta | undefined => catalog[id];-function skill(id: string, content: string): ReadUserSkill {- return { id, name: id, description: "", content };-}-describe("selected skill chips", () => {it("keeps a chip for every selected id, including vanished ones", () => {// Regression anchor for "unavailable skills have a visible recovery action":@@ -19,11 +15,24 @@ describe("selected skill chips", () => {// must still render a removable chip rather than silently disappearing.const chips = buildSelectedSkillChips(["d-aaa", "d-gone", "c-bbb"], lookup);expect(chips.map((chip) => chip.id)).toEqual(["d-aaa", "d-gone", "c-bbb"]);- expect(chips[1]).toEqual({ id: "d-gone", name: "d-gone", description: "", source: "default", unavailable: true });+ expect(chips[1]).toEqual({ id: "d-gone", name: "d-gone", description: "", source: "default", unavailable: true, loaded: false });expect(chips[0].unavailable).toBe(false);expect(chips[0].name).toBe("SQL Review");});+ // Req 13: the chip's second state is a per-conversation signal, so the chip+ // carries it rather than re-deriving it at render time.+ it("marks only the ids the conversation has loaded", () => {+ const chips = buildSelectedSkillChips(["d-aaa", "c-bbb"], lookup, ["c-bbb"]);+ expect(chips.map((chip) => chip.loaded)).toEqual([false, true]);+ // Default state for a caller with no conversation state to show.+ expect(buildSelectedSkillChips(["d-aaa"], lookup).map((chip) => chip.loaded)).toEqual([false]);+ // A loaded id may also be one the catalog no longer lists — the two flags are+ // independent, and `unavailable` must not swallow the loaded signal.+ const vanished = buildSelectedSkillChips(["d-gone"], lookup, ["d-gone"]);+ expect(vanished[0]).toMatchObject({ unavailable: true, loaded: true });+ });+it("labels the source from the id prefix so a vanished skill keeps its origin", () => {expect(userSkillSourceOfId("c-bbb")).toBe("custom");expect(userSkillSourceOfId("d-aaa")).toBe("default");@@ -50,29 +59,3 @@ describe("removeSkillIds", () => {expect(removeSkillIds(ids, ["a", "a"])).toEqual(["b"]);});});--describe("capSkillsToCharLimit", () => {- it("keeps leading skills that fit the combined budget and skips overflowing ones", () => {- // Regression anchor for "selected skills cannot grow the system prompt- // without bound": the first skill fills the budget, the oversized second- // is skipped, and the smaller third still fits.- const big = "x".repeat(60);- const capped = capSkillsToCharLimit([skill("d-1", "a".repeat(30)), skill("d-2", big), skill("d-3", "b".repeat(10))], 50);- expect(capped.map((s) => s.id)).toEqual(["d-1", "d-3"]);- });-- it("drops a single skill whose content alone exceeds the budget", () => {- expect(capSkillsToCharLimit([skill("d-1", "x".repeat(ACTIVE_SKILLS_TOTAL_MAX + 1))], ACTIVE_SKILLS_TOTAL_MAX)).toEqual([]);- expect(capSkillsToCharLimit([skill("d-1", "x".repeat(ACTIVE_SKILLS_TOTAL_MAX))], ACTIVE_SKILLS_TOTAL_MAX).map((s) => s.id)).toEqual(["d-1"]);- });-- it("preserves selection order and dedupes repeated ids", () => {- const capped = capSkillsToCharLimit([skill("d-1", "a"), skill("d-2", "b"), skill("d-1", "a")], 10);- expect(capped.map((s) => s.id)).toEqual(["d-1", "d-2"]);- });-- it("keeps everything under the real budget for realistic sizes", () => {- const skills = Array.from({ length: 8 }, (_, i) => skill(`d-${i}`, "y".repeat(2000)));- expect(capSkillsToCharLimit(skills, ACTIVE_SKILLS_TOTAL_MAX).length).toBe(8);- });-});diff --git a/apps/desktop/src/lib/ai/ai.ts b/apps/desktop/src/lib/ai/ai.tsindex f787402bb0..00b061317e 100644--- a/apps/desktop/src/lib/ai/ai.ts+++ b/apps/desktop/src/lib/ai/ai.ts@@ -3,7 +3,6 @@ import type { AiAssistantMode } from "@/types/ai";import { uuid } from "@/lib/common/utils";import type { ColumnInfo, ConnectionConfig, DatabaseType, ForeignKeyInfo, IndexInfo, QueryResult, QueryTab } from "@/types/database";import type { PromptTemplate } from "@/types/promptTemplate";-import type { ReadUserSkill } from "@/types/userSkills";import * as api from "@/lib/backend/api";import { currentLocale, type Locale } from "@/i18n";import { aiTableMentionKey, type AiTableMention } from "@/lib/ai/aiTableMentions";@@ -183,6 +182,14 @@ export interface AiRequestInput {confirmedSchema?: string;/** Stable per-conversation key forwarded to the Responses API. */promptCacheKey?: string;+ /**+ * True when this send carries a skill listing (`CustomPromptContext.skillListing`).+ * The backend appends the on-demand skill tools (`use_skill` /+ * `read_skill_file`) to the run's tool table only then, so a skill-free request+ * keeps the exact tool table it had before those tools existed. Setting it+ * without a listing gives the model tools with nothing to resolve.+ */+ allowSkills?: boolean;}export interface AiNamespaceSelection {@@ -193,33 +200,41 @@ export interface AiNamespaceSelection {export interface CustomPromptContext {globalInstructions?: string;activeTemplates?: PromptTemplate[];- /** Selected read-only SKILL.md snapshots resolved at send time (09-21-public-skill-loader). */- selectedSkills?: ReadUserSkill[];+ /**+ * Pre-rendered skill listing lines (`buildSkillListingLines`), snapshotted at+ * send time. Skill bodies are deliberately absent: they load on demand through+ * the `use_skill` tool, so the listing is the only skill text in the prompt.+ * Skill capability is DBX's built-in AI only — a CLI run never receives this.+ */+ skillListing?: string[];}function buildCustomInstructionLines(custom: CustomPromptContext | undefined, isZh: boolean): string[] {const global = custom?.globalInstructions?.trim() ?? "";const templates = (custom?.activeTemplates ?? []).filter((t) => t.content.trim());- const skills = (custom?.selectedSkills ?? []).filter((skill) => skill.content.trim());- if (!global && templates.length === 0 && skills.length === 0) return [];+ const skillListing = custom?.skillListing ?? [];const parts: string[] = [];if (global) parts.push(global);parts.push(...templates.map((t) => `### ${t.name}\n${t.content}`));- if (skills.length > 0) {- parts.push(++ const lines: string[] = [];+ // The wrapper is emitted only when there are actually custom instructions, so+ // a send with no globals/templates (and no skills) stays byte-identical to the+ // pre-skill prompt.+ if (parts.length > 0) {+ lines.push(isZh- ? "## 用户选择的 Skills(补充性)\n以下为用户显式选择的外部 SKILL.md 规则文件,按原样注入;上方核心安全及方言规则优先级更高。"- : "## Selected Skills (supplementary)\nThe following external SKILL.md rule files were explicitly selected by the user and are injected as-is. Core safety and dialect rules above take precedence.",+ ? `## 用户自定义规范(补充性)\n以下为用户定义的规范与模板;上方核心安全及方言规则优先级更高。\n\n${parts.join("\n\n")}`+ : `## Custom Instructions (supplementary)\nThe following are user-defined conventions and templates. Core safety and dialect rules above take precedence.\n\n${parts.join("\n\n")}`,);- parts.push(...skills.map((skill) => `### Skill: ${skill.name}\n<ai-skill id="${skill.id}">\n${skill.content}\n</ai-skill>`));}-- return [- isZh- ? `## 用户自定义规范(补充性)\n以下为用户定义的规范与模板;上方核心安全及方言规则优先级更高。\n\n${parts.join("\n\n")}`- : `## Custom Instructions (supplementary)\nThe following are user-defined conventions and templates. Core safety and dialect rules above take precedence.\n\n${parts.join("\n\n")}`,- ];+ // The skill listing sits OUTSIDE that wrapper on purpose: the wrapper's text is+ // shared with the templates/globals paths, so folding skills into it would make+ // those prompts differ depending on whether skills exist. The listing carries+ // its own use_skill instructions (see lib/ai/skillListing.ts).+ if (skillListing.length > 0) lines.push(skillListing.join("\n"));+ return lines;}export function buildAgentRequest(input: AiRequestInput, history?: api.AiMessage[], custom?: CustomPromptContext): { messages: api.AiMessage[]; systemPrompt: string; taskContract: api.AiTaskContract; maxTokens: number } {@@ -310,10 +325,7 @@ export async function runAgentStream(input: AiRequestInput, history: api.AiMessainput.confirmedDatabase,input.confirmedSchema,] as const;- if (selectedDatabases?.length) {- return api.aiAgentStream(...args, undefined, selectedDatabases);- }- return api.aiAgentStream(...args);+ return api.aiAgentStream(...args, undefined, selectedDatabases, input.allowSkills === true);}export function buildUserPrompt(action: AiAction, context: AiContext, instruction: string, isZh: boolean): string {diff --git a/apps/desktop/src/lib/ai/skillListing.ts b/apps/desktop/src/lib/ai/skillListing.tsnew file mode 100644index 0000000000..c8734630bb--- /dev/null+++ b/apps/desktop/src/lib/ai/skillListing.ts@@ -0,0 +1,175 @@+/**+ * Skill listing rendering for on-demand skill loading+ * (prd 09-30-skill-listing-use-skill).+ *+ * The system prompt carries only this listing — frontmatter-derived name and+ * description — never a SKILL.md body. Bodies reach the model through the+ * `use_skill` tool when the model decides the skill applies to the turn.+ *+ * Pure functions only: the budget ladder is the contract the regression tests+ * pin, so keep every decision deterministic.+ */++import { promptTemplateCharacterCount } from "@/types/promptTemplate";+import type { UserSkillMeta } from "@/types/userSkills";+import { userSkillSourceOfId } from "@/lib/ai/userSkillSelection";++/** Description cap for a normal entry. Measured p100 of real SKILL.md descriptions is 997, so this truncates nothing in practice. */+export const SKILL_LISTING_ENTRY_MAX = 1000;+/** Description cap an unselected entry degrades to (≈ the measured median of 233) before losing its description entirely. */+export const SKILL_LISTING_UNCHECKED_ENTRY_MAX = 200;+/** Combined listing budget for one request. Deliberately above ACTIVE_TEMPLATES_TOTAL_MAX (16000). */+export const SKILL_LISTING_TOTAL_MAX = 32000;+/** Fuse against a pathological skill count; the character budget binds first in practice. */+export const SKILL_LISTING_MAX_ENTRIES = 100;++/** Language-neutral so one listing line reads the same under every locale. */+const SELECTED_MARKER = "user-selected";++export interface SkillListingInput {+ /** Catalog metadata, both roots. */+ skills: readonly UserSkillMeta[];+ /** Ids the user checked for this AI panel session. */+ selectedIds: readonly string[];+ totalMax?: number;+ entryMax?: number;+ uncheckedEntryMax?: number;+ maxEntries?: number;+}++export interface SkillListing {+ /** Rendered entry lines. */+ lines: string[];+ /** True when an entry lost its description or was dropped to fit. */+ truncated: boolean;+}++interface Entry {+ id: string;+ name: string;+ description: string;+ source: string;+ selected: boolean;+}++function flat(text: string): string {+ return text.replace(/\s+/g, " ").trim();+}++function truncate(description: string, max: number): string {+ if (promptTemplateCharacterCount(description) <= max) return description;+ // Slice by code point so truncation never splits a surrogate pair.+ return `${Array.from(description)+ .slice(0, Math.max(max - 1, 0))+ .join("")}…`;+}++function renderEntry(entry: Entry, descriptionMax: number): string {+ const markers = [entry.source, ...(entry.selected ? [SELECTED_MARKER] : [])].join("] [");+ const head = `- ${flat(entry.name)} [${markers}]`;+ if (descriptionMax <= 0) return head;+ const description = truncate(flat(entry.description), descriptionMax);+ return description ? `${head}: ${description}` : head;+}++function size(lines: readonly string[]): number {+ return lines.reduce((sum, line) => sum + promptTemplateCharacterCount(line) + 1, 0) - 1;+}++/**+ * Existing #9363 ordering: the custom root lists before the default root, then+ * name (case-insensitive), then the opaque id as a stable tiebreak. Two skills+ * sharing a name across roots stay separate — the source marker in each line is+ * what lets the model, and the user reading the transcript, tell them apart.+ */+function compareEntries(a: Entry, b: Entry): number {+ if (a.source !== b.source) return a.source === "custom" ? -1 : 1;+ const byName = a.name.toLowerCase().localeCompare(b.name.toLowerCase());+ return byName !== 0 ? byName : a.id.localeCompare(b.id);+}++/**+ * Render the listing within budget.+ *+ * Ladder — each step runs only while the previous one still overflows:+ * 1. every entry with its full description;+ * 2. unselected entries clamped to `uncheckedEntryMax`;+ * 3. unselected entries reduced to name + source;+ * 4. unselected entries dropped from the tail.+ *+ * Selected entries never lose their description and are never dropped: they are+ * the user's explicit intent, and their description is the only routing signal+ * the model receives for them. If the selected entries alone exceed the budget+ * the listing overflows rather than silently dropping one of them.+ */+export function buildSkillListing(input: SkillListingInput): SkillListing {+ const totalMax = input.totalMax ?? SKILL_LISTING_TOTAL_MAX;+ const entryMax = input.entryMax ?? SKILL_LISTING_ENTRY_MAX;+ const uncheckedEntryMax = input.uncheckedEntryMax ?? SKILL_LISTING_UNCHECKED_ENTRY_MAX;+ const maxEntries = input.maxEntries ?? SKILL_LISTING_MAX_ENTRIES;++ // One global order for every entry — selected entries are made prominent by+ // their marker, not by being hoisted, so the listing reads the same way+ // regardless of what the user picked (prd: ordering follows #9363).+ const seen = new Set<string>();+ const entries: Entry[] = [];+ for (const skill of input.skills) {+ if (seen.has(skill.id)) continue;+ seen.add(skill.id);+ entries.push({+ id: skill.id,+ name: skill.name,+ description: skill.description ?? "",+ source: userSkillSourceOfId(skill.id),+ selected: input.selectedIds.includes(skill.id),+ });+ }+ entries.sort(compareEntries);++ // Only unselected entries are ever dropped, so both the entry cap and the+ // final ladder rung consume this list from its tail.+ const unselectedPositions = entries.flatMap((entry, index) => (entry.selected ? [] : [index]));+ const selectedCount = entries.length - unselectedPositions.length;++ const assemble = (droppedCount: number, descriptionMax: (entry: Entry) => number) => {+ const dropped = new Set(unselectedPositions.slice(unselectedPositions.length - droppedCount));+ return entries.filter((_, index) => !dropped.has(index)).map((entry) => renderEntry(entry, descriptionMax(entry)));+ };++ // Selected entries are never dropped, so the entry cap can only ever bite the+ // unselected tail.+ const droppedByCount = Math.max(unselectedPositions.length - Math.max(maxEntries - selectedCount, 0), 0);++ const full = assemble(droppedByCount, () => entryMax);+ if (size(full) <= totalMax) return { lines: full, truncated: droppedByCount > 0 };++ const clamped = assemble(droppedByCount, (entry) => (entry.selected ? entryMax : uncheckedEntryMax));+ if (size(clamped) <= totalMax) return { lines: clamped, truncated: true };++ for (let dropped = droppedByCount; dropped <= unselectedPositions.length; dropped += 1) {+ const lines = assemble(dropped, (entry) => (entry.selected ? entryMax : 0));+ if (size(lines) <= totalMax || dropped === unselectedPositions.length) {+ // The last rung keeps only the selected entries; they stay even if that+ // still overflows the budget, because silently dropping one of the user's+ // explicit picks is worse than an oversized listing.+ return { lines, truncated: true };+ }+ }+ /* istanbul ignore next -- the loop above always returns at its last rung. */+ return { lines: assemble(unselectedPositions.length, () => entryMax), truncated: true };+}++/**+ * The prompt block. Kept beside the renderer so the strong wording for+ * user-selected skills — the only thing standing in for the removed+ * force-injection — is covered by the same tests as the budget ladder.+ */+export function buildSkillListingLines(listing: SkillListing, isZh: boolean): string[] {+ if (listing.lines.length === 0) return [];+ const body = listing.lines.join("\n");+ return [+ isZh+ ? `## 可用 Skills(按需加载)\n以下 Skill 只有名称与描述在上下文中,正文不在。需要某个 Skill 的完整指令时,先调用 use_skill 工具加载它,再按其中的规则回答。\n标有 [${SELECTED_MARKER}] 的 Skill 由用户显式选择:本轮问题与它相关时,必须先调用 use_skill 加载后再回答。\n\n${body}`+ : `## Available Skills (loaded on demand)\nOnly names and descriptions are in context; the bodies are not. When you need a skill's full instructions, call the use_skill tool first and follow it before answering.\nSkills marked [${SELECTED_MARKER}] were chosen explicitly by the user: when the current request touches them, call use_skill before answering.\n\n${body}`,+ ];+}diff --git a/apps/desktop/src/lib/ai/userSkillSelection.ts b/apps/desktop/src/lib/ai/userSkillSelection.tsindex 1eee395a2b..4285bdf60e 100644--- a/apps/desktop/src/lib/ai/userSkillSelection.ts+++ b/apps/desktop/src/lib/ai/userSkillSelection.ts@@ -1,5 +1,4 @@-import type { ReadUserSkill, UserSkillMeta } from "@/types/userSkills";-import { promptTemplateCharacterCount } from "@/types/promptTemplate";+import type { UserSkillMeta } from "@/types/userSkills";/** A selected skill rendered as a chip, whether or not it is still discoverable. */export interface SelectedSkillChip {@@ -9,6 +8,12 @@ export interface SelectedSkillChip {source: "custom" | "default";/** True when the catalog no longer lists this id (deleted, or its root went away). */unavailable: boolean;+ /**+ * True once this conversation has had the skill loaded — by the model through+ * `use_skill`, or by the user forcing the load (prd 09-30 Req 13). A persistent+ * per-conversation signal, never a per-turn one.+ */+ loaded: boolean;}/**@@ -24,8 +29,12 @@ export function userSkillSourceOfId(id: string): "custom" | "default" {* Every selected id keeps a chip: a skill that vanished from discovery would* otherwise lose its only remove affordance and block every later send. The* fallback label is the opaque id, paired with `unavailable` for styling.+ *+ * `loadedIds` is the conversation's loaded set; an omitted one leaves every chip+ * in its default state, which is what a caller with no conversation state wants.*/-export function buildSelectedSkillChips(ids: readonly string[], lookup: (id: string) => UserSkillMeta | undefined): SelectedSkillChip[] {+export function buildSelectedSkillChips(ids: readonly string[], lookup: (id: string) => UserSkillMeta | undefined, loadedIds: Iterable<string> = []): SelectedSkillChip[] {+ const loaded = new Set(loadedIds);return ids.map((id) => {const meta = lookup(id);return {@@ -34,34 +43,37 @@ export function buildSelectedSkillChips(ids: readonly string[], lookup: (id: strdescription: meta?.description ?? "",source: userSkillSourceOfId(id),unavailable: !meta,+ loaded: loaded.has(id),};});}-/** Order-preserving removal, shared by the chip close button and the failure banner. */-export function removeSkillIds(ids: readonly string[], removed: Iterable<string>): string[] {- const dropped = new Set(removed);- return ids.filter((id) => !dropped.has(id));-}-/**- * Keep the leading skills that fit the combined character budget for one- * request. A skill whose content would push the total past maxTotal is- * skipped, but a later smaller skill still fits (same budget semantics as- * capTemplateIdsToCharLimit for templates). Selection order is preserved so- * the injected set matches the chips top to bottom.+ * Display names appearing more than once inside one source/root.+ *+ * Skill discovery is flat (`<root>/<dir>/SKILL.md`, `crates/dbx-core/src/skills.rs`),+ * so every entry in a root already has its own directory — a collision inside one+ * root is therefore always two directories declaring the same frontmatter `name`.+ * The model addresses skills by name + source (ADR Decision 6), so `use_skill`+ * can only answer "ambiguous" for these; `source` cannot separate two entries of+ * the same root. The badge in the selector exists to tell the user that, because+ * only changing one of the two frontmatter `name` values can resolve it — the+ * collision key is that field, not the directory name, so renaming a folder+ * changes nothing. The same name in *different* roots is normal and is not+ * reported here.*/-export function capSkillsToCharLimit(skills: readonly ReadUserSkill[], maxTotal: number): ReadUserSkill[] {- const kept: ReadUserSkill[] = [];+export function duplicateSkillNames(skills: readonly UserSkillMeta[]): Set<string> {const seen = new Set<string>();- let total = 0;+ const duplicates = new Set<string>();for (const skill of skills) {- if (seen.has(skill.id)) continue;- seen.add(skill.id);- const size = promptTemplateCharacterCount(skill.content);- if (total + size > maxTotal) continue;- total += size;- kept.push(skill);+ if (seen.has(skill.name)) duplicates.add(skill.name);+ else seen.add(skill.name);}- return kept;+ return duplicates;+}++/** Order-preserving removal, shared by the chip close button and the failure banner. */+export function removeSkillIds(ids: readonly string[], removed: Iterable<string>): string[] {+ const dropped = new Set(removed);+ return ids.filter((id) => !dropped.has(id));}diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.tsindex 586aae0c88..f5e5c79be7 100644--- a/apps/desktop/src/lib/backend/api.ts+++ b/apps/desktop/src/lib/backend/api.ts@@ -978,6 +978,7 @@ export type { AiConfigItem };export type {AppSupportInfo,AiMessage,+ AiToolCallRef,AiCompletionRequest,AiTaskContract,AiStreamChunk,diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex 66a2a5f553..21e555d5fe 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -341,6 +341,7 @@ const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {agent_store_dir: null,custom_ai_skill_root_enabled: false,custom_ai_skill_root: null,+ custom_ai_skill_auto_enabled: false,sidebar_table_page_size: 1000,};@@ -2119,6 +2120,7 @@ export async function aiAgentStream(confirmedSchema?: string,signal?: AbortSignal,selectedDatabases?: string[],+ allowSkills = false,): Promise<string> {const res = await fetch(apiUrl("/api/ai/agent-stream"), {method: "POST",@@ -2137,6 +2139,9 @@ export async function aiAgentStream(confirmedDatabase,confirmedSchema,selectedDatabases,+ // The web server ignores this by design: local skill files are never+ // exposed to it (there is no request field on that route either).+ allowSkills,}),signal,});diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex 9b31347ddb..3dbd34eb6e 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -325,6 +325,7 @@ export interface DesktopSettings {agent_store_dir?: string | null;custom_ai_skill_root_enabled?: boolean | null;custom_ai_skill_root?: string | null;+ custom_ai_skill_auto_enabled?: boolean | null;sidebar_table_page_size?: number | null;}@@ -592,13 +593,29 @@ export interface DriverInstallProgress {}export interface AiMessage {- role: "user" | "assistant" | "system";+ role: "user" | "assistant" | "system" | "tool";content: string;/** Transient images for this message. Persisted conversation history intentionally omits them. */images?: Array<{mediaType: string;data: string;}>;+ /** For `role: "tool"`: the call this message answers. */+ toolCallId?: string;+ /** For `role: "assistant"`: the calls this turn made. The panel builds one of+ * these per request to replay a loaded skill as a real tool round; it is never+ * written to a conversation record. */+ toolCalls?: AiToolCallRef[];+}++/** Mirrors `ToolCallRef` in `crates/dbx-ai-provider/src/ai.rs`. `providerPayload`+ * is provider-private replay data (Gemini thought signatures) that only a real+ * provider round can produce; a panel-built call leaves it unset. */+export interface AiToolCallRef {+ id: string;+ name: string;+ arguments: Record<string, unknown>;+ providerPayload?: unknown;}export interface AiTaskContract {@@ -632,6 +649,7 @@ export interface AiStreamChunk {session_id: string;delta: string;reasoning_delta?: string;+ finish_reason?: string;done: boolean;/** Web-only explicit terminal error; Tauri reports invoke failures directly. */error?: string;@@ -698,6 +716,7 @@ export type AgentEvent =*/type: "response_complete";}+ | { type: "output_truncated"; finish_reason: string }| { type: "agent_end"; input_tokens?: number; output_tokens?: number }| {type: "context_compacted";@@ -729,6 +748,7 @@ export async function aiAgentStream(confirmedSchema?: string,_signal?: AbortSignal,selectedDatabases?: string[],+ allowSkills = false,): Promise<string> {const unlisten: UnlistenFn = await listen<TauriAgentEvent>("ai-agent-event", (event) => {const payload = event.payload;@@ -753,6 +773,7 @@ export async function aiAgentStream(confirmedDatabase,confirmedSchema,selectedDatabases,+ allowSkills,});} catch (e) {unlisten();@@ -1350,6 +1371,17 @@ export interface AiChatMessage {* the turn was not empty. Absent on records written before the field existed.*/selectionsOmitted?: boolean;+ /**+ * Skills this conversation has had loaded (prd 09-30 Req 13), carried on the+ * newest assistant turn of each snapshot.+ *+ * Only the fact, never the body: a body can reach 1 MiB per skill, the stored+ * message array is an unbounded column with no per-message cap, and it is+ * re-serialized in full on every save. Bodies stay in memory and are re-read+ * from disk when a request needs them — the same shape as the #10058 selection+ * footprint above, which keeps a flag instead of its payload.+ */+ loadedSkillIds?: string[];}export interface AiConversation {diff --git a/apps/desktop/src/lib/settings/settingsSearch.ts b/apps/desktop/src/lib/settings/settingsSearch.tsindex ee3815f958..f8f8758c14 100644--- a/apps/desktop/src/lib/settings/settingsSearch.ts+++ b/apps/desktop/src/lib/settings/settingsSearch.ts@@ -306,6 +306,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] ={ id: "ai-global-retries", category: "ai", titleKey: "ai.maxRetriesGlobal", descriptionKey: "ai.maxRetriesGlobalDescription", targetId: "ai" },{ id: "ai-global-instructions", category: "ai", titleKey: "ai.globalInstructions", descriptionKey: "ai.globalInstructionsDescription", targetId: "ai" },{ id: "ai-custom-skill-root", category: "ai", titleKey: "settings.aiSkillRoot", descriptionKey: "settings.aiSkillRootDesc", targetId: "ai", visible: desktopOnly },+ { id: "ai-skill-auto-enabled", category: "ai", titleKey: "settings.aiSkillAutoEnabled", descriptionKey: "settings.aiSkillAutoEnabledDesc", targetId: "ai", visible: desktopOnly },{ id: "mcp", category: "mcp", titleKey: "settings.mcpTitle", descriptionKey: "settings.mcpDescription", targetId: "mcp" },{ id: "mcp-bin-path", category: "mcp", titleKey: "settings.mcpBinPath", targetId: "mcp" },{ id: "mcp-permissions", category: "mcp", titleKey: "settings.mcpExecutionMode", descriptionKey: "settings.mcpExecutionModeDescription", targetId: "mcp" },diff --git a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts b/apps/desktop/src/stores/__tests__/settingsStore.spec.tsindex 5dad4f0a31..84a1aa6856 100644--- a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts+++ b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts@@ -844,6 +844,15 @@ describe("normalizeDesktopSettings", () => {expect(normalizeDesktopSettings({ duckdb_worker_max_processes: 32 }).duckdb_worker_max_processes).toBe(16);expect(normalizeDesktopSettings({ duckdb_worker_max_processes: 3.6 }).duckdb_worker_max_processes).toBe(4);});++ // Req 5: the automatic skill listing costs prompt tokens on every request, so a+ // record written before the toggle existed (key absent) must normalize to off,+ // and only an explicit `true` may turn it on.+ it("defaults the automatic skill listing to off", () => {+ expect(normalizeDesktopSettings({}).custom_ai_skill_auto_enabled).toBe(false);+ expect(normalizeDesktopSettings({ custom_ai_skill_auto_enabled: null }).custom_ai_skill_auto_enabled).toBe(false);+ expect(normalizeDesktopSettings({ custom_ai_skill_auto_enabled: true }).custom_ai_skill_auto_enabled).toBe(true);+ });});describe("normalizeMcpGlobalPolicy", () => {diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.tsindex 2ed92aaa88..910f8d4fdd 100644--- a/apps/desktop/src/stores/settingsStore.ts+++ b/apps/desktop/src/stores/settingsStore.ts@@ -79,6 +79,9 @@ export interface DesktopSettings {agent_store_dir?: string | null;custom_ai_skill_root_enabled?: boolean | null;custom_ai_skill_root?: string | null;+ /** "Allow the AI to use skills automatically" (prd 09-30 Req 5): the built-in+ * AI then receives the skill listing even with nothing selected. Default off. */+ custom_ai_skill_auto_enabled?: boolean | null;sidebar_table_page_size?: number | null;}@@ -159,6 +162,7 @@ export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {agent_store_dir: null,custom_ai_skill_root_enabled: false,custom_ai_skill_root: null,+ custom_ai_skill_auto_enabled: false,sidebar_table_page_size: DEFAULT_SIDEBAR_TABLE_PAGE_SIZE,};@@ -264,6 +268,7 @@ export function normalizeDesktopSettings(settings: Partial<DesktopSettings> | nuagent_store_dir: settings?.agent_store_dir?.trim() || DEFAULT_DESKTOP_SETTINGS.agent_store_dir,custom_ai_skill_root_enabled: settings?.custom_ai_skill_root_enabled ?? DEFAULT_DESKTOP_SETTINGS.custom_ai_skill_root_enabled,custom_ai_skill_root: settings?.custom_ai_skill_root?.trim() || DEFAULT_DESKTOP_SETTINGS.custom_ai_skill_root,+ custom_ai_skill_auto_enabled: settings?.custom_ai_skill_auto_enabled ?? DEFAULT_DESKTOP_SETTINGS.custom_ai_skill_auto_enabled,sidebar_table_page_size: sidebarTablePageSize,};}diff --git a/apps/desktop/src/stores/userSkillStore.ts b/apps/desktop/src/stores/userSkillStore.tsindex 11196e1f85..595a2ff92e 100644--- a/apps/desktop/src/stores/userSkillStore.ts+++ b/apps/desktop/src/stores/userSkillStore.ts@@ -9,8 +9,9 @@ type UserSkillRootStatus = UserSkillRootListing["status"];* Metadata-only catalog of discoverable skills for the AI panel selector.* Selection state does NOT live here: it is panel-session scoped inside* AiAssistant (like activeTemplateIds), so closing the panel clears it while- * the catalog cache survives. This store never holds skill bodies - bodies- * are read once per send through the backend (prd.md:36/:56).+ * the catalog cache survives. This store never holds skill bodies — built-in+ * providers load them on demand through the use_skill tool, and CLI providers+ * do not use skills at all (prd.md:36/:56).*/export const useUserSkillStore = defineStore("userSkillStore", () => {const defaultRootSkills = ref<UserSkillMeta[]>([]);diff --git a/apps/desktop/src/types/userSkills.ts b/apps/desktop/src/types/userSkills.tsindex 88fc7e5066..92f0997d49 100644--- a/apps/desktop/src/types/userSkills.ts+++ b/apps/desktop/src/types/userSkills.ts@@ -43,11 +43,3 @@ export interface UserSkillRootSettings {customRootEnabled: boolean;customRoot: string | null;}--/**- * Combined character budget for skills injected into one AI request. Skill- * bodies are only known after the send-time read (the catalog is metadata- * only), so the budget is enforced on the read snapshots with the same- * semantics as the template budget.- */-export const ACTIVE_SKILLS_TOTAL_MAX = 65536;diff --git a/crates/dbx-ai-provider/src/agent_events.rs b/crates/dbx-ai-provider/src/agent_events.rsindex db8a501862..a956f0dbb2 100644--- a/crates/dbx-ai-provider/src/agent_events.rs+++ b/crates/dbx-ai-provider/src/agent_events.rs@@ -48,6 +48,8 @@ pub enum AgentEvent {/// stdout). Non-terminal: the frontend may stop the reply animation on it,/// but must keep listening for the real `AgentEnd` / `Error`.ResponseComplete,+ /// The provider stopped because its output limit was reached.+ OutputTruncated { finish_reason: String },/// The agent loop has finished successfully.AgentEnd { input_tokens: Option<u32>, output_tokens: Option<u32> },/// Context was compacted to stay within context window limits.diff --git a/crates/dbx-ai-provider/src/ai.rs b/crates/dbx-ai-provider/src/ai.rsindex 2da6b0da31..2115e1d362 100644--- a/crates/dbx-ai-provider/src/ai.rs+++ b/crates/dbx-ai-provider/src/ai.rs@@ -597,6 +597,11 @@ pub struct AiStreamChunk {pub delta: String,#[serde(skip_serializing_if = "Option::is_none")]pub reasoning_delta: Option<String>,+ /// Provider termination reason observed on the final stream event.+ /// `length` means output was cut by the provider limit, not that the model+ /// completed a final answer.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub finish_reason: Option<String>,pub done: bool,}@@ -636,8 +641,27 @@ pub struct AiChatMessage {/// a reloaded transcript can still tell the model the content is gone/// instead of showing an empty turn. Absent on records written before the/// field existed.+ ///+ /// NOTE (2026-10-01): the sync surface carries no conversations member today+ /// — `cloud_sync::SyncSnapshot` has no such field, and there is no projection+ /// to exclude one from — so the reason this field holds today is write+ /// amplification rather than sync exposure. If conversations ever do join the+ /// snapshot, the original reason applies again as written.#[serde(default, skip_serializing_if = "Option::is_none")]pub selections_omitted: Option<bool>,+ /// Which skills this conversation has had loaded (prd 09-30 Req 13), written+ /// onto the newest assistant message of every snapshot.+ ///+ /// Only the FACT is persisted, never the body: a body can reach 1 MiB per+ /// skill, `ai_conversations.messages_json` is an unbounded TEXT column with no+ /// per-message or per-record cap, and the whole message array is re-serialised+ /// on every save (send, streamed snapshot, chip click). A body here would be+ /// written in full each time, and would ride along with anything that ships a+ /// conversation record. Same shape as `selections_omitted` above, which keeps a+ /// footprint instead of its payload; the panel holds the body in memory for the+ /// current session and re-reads it from disk when a request needs it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub loaded_skill_ids: Option<Vec<String>>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -1366,6 +1390,17 @@ fn openai_stream_has_finish_reason(event: &serde_json::Value) -> bool {})}+/// Normalizes provider-specific output-limit labels into the two values the+/// agent event contract exposes. Other stop reasons (for example tool calls or+/// a normal stop) are intentionally not surfaced as truncation.+fn output_limit_finish_reason(reason: &str) -> Option<&'static str> {+ match reason.to_ascii_lowercase().as_str() {+ "length" => Some("length"),+ "max_tokens" | "max_output_tokens" => Some("max_tokens"),+ _ => None,+ }+}+pub fn responses_stream_text(event: &serde_json::Value) -> Option<&str> {let event_type = event["type"].as_str().unwrap_or_default();if !event_type.is_empty() && event_type != "response.output_text.delta" {@@ -3838,6 +3873,7 @@ async fn stream_claude(session_id: session_id.clone(),delta: text.to_string(),reasoning_delta: None,+ finish_reason: None,done: false,});}@@ -3854,6 +3890,7 @@ async fn stream_claude(session_id: session_id.clone(),delta: String::new(),reasoning_delta: None,+ finish_reason: None,done: true,});@@ -3936,6 +3973,7 @@ async fn stream_openai(session_id: session_id.clone(),delta: String::new(),reasoning_delta: Some(reasoning),+ finish_reason: None,done: false,});}@@ -3945,6 +3983,7 @@ async fn stream_openai(session_id: session_id.clone(),delta: text,reasoning_delta: None,+ finish_reason: None,done: false,});}@@ -3955,6 +3994,7 @@ async fn stream_openai(session_id: session_id.clone(),delta: String::new(),reasoning_delta: Some(reasoning.to_string()),+ finish_reason: None,done: false,});}@@ -3964,11 +4004,27 @@ async fn stream_openai(session_id: session_id.clone(),delta: text,reasoning_delta: None,+ finish_reason: None,done: false,});}}if finish_reason_deadline.is_none() && openai_stream_has_finish_reason(&event) {+ if let Some(reason) = event["choices"].get(0).and_then(|choice| choice["finish_reason"].as_str()).filter(|reason| !reason.is_empty()) {+ on_chunk(AiStreamChunk {+ session_id: session_id.clone(),+ delta: String::new(),+ reasoning_delta: None,+ finish_reason: Some(reason.to_string()),+ // Not `done`: this stream is not over. Both frontends+ // stop listening on the first `done` chunk, and this+ // stream deliberately keeps reading for up to a second+ // after the finish reason to collect the trailing usage+ // chunk. The batcher holds this reason and attaches it to+ // the real terminal chunk.+ done: false,+ });+ }finish_reason_deadline =Some(tokio::time::Instant::now() + std::time::Duration::from_secs(1));}@@ -3991,6 +4047,7 @@ async fn stream_openai(session_id: session_id.clone(),delta: String::new(),reasoning_delta: None,+ finish_reason: None,done: true,});@@ -4067,6 +4124,7 @@ async fn stream_responses_api(session_id: session_id.clone(),delta: text.to_string(),reasoning_delta: None,+ finish_reason: None,done: false,});}@@ -4083,6 +4141,7 @@ async fn stream_responses_api(session_id: session_id.clone(),delta: String::new(),reasoning_delta: None,+ finish_reason: None,done: true,});@@ -4161,6 +4220,7 @@ async fn stream_gemini(session_id: session_id.clone(),delta: text,reasoning_delta: None,+ finish_reason: None,done: false,});}@@ -4175,6 +4235,7 @@ async fn stream_gemini(session_id: session_id.clone(),delta: String::new(),reasoning_delta: None,+ finish_reason: None,done: true,});@@ -4202,6 +4263,8 @@ pub enum StreamToolEvent {ToolCallProviderPayload { index: u32, payload: serde_json::Value },/// A tool_use / function_call block has ended.ToolCallComplete { index: u32 },+ /// Provider termination reason, retained even when no tool call was emitted.+ FinishReason { reason: String },}/// Partially accumulated tool call during streaming.@@ -4234,6 +4297,16 @@ impl StreamingToolCallAccumulator {pub fn process(&mut self, event: StreamToolEvent, on_chunk: &impl Fn(AiStreamChunk)) {match event {StreamToolEvent::Chunk(chunk) => on_chunk(chunk),+ // Carries the reason on a non-terminal chunk on purpose: `done` ends the+ // stream for the consumer, and the batcher is built to attach this reason+ // to the terminal chunk that follows.+ StreamToolEvent::FinishReason { reason } => on_chunk(AiStreamChunk {+ session_id: String::new(),+ delta: String::new(),+ reasoning_delta: None,+ finish_reason: Some(reason),+ done: false,+ }),StreamToolEvent::ToolCallStart { index, id, name } => {// Merge with any existing entry for this index instead of// overwriting it. Some OpenAI-compatible providers (e.g. GLM)@@ -4428,6 +4501,11 @@ async fn stream_claude_with_tools(let existing_input = token_usage.as_ref().map(|u| u.input_tokens).unwrap_or(0);token_usage = Some(TokenUsage { input_tokens: existing_input, output_tokens: o as u32 });}+ if let Some(reason) = event["delta"]["stop_reason"].as_str()+ .and_then(output_limit_finish_reason)+ {+ on_event(StreamToolEvent::FinishReason { reason: reason.to_string() });+ }}"content_block_start" => {let idx = event["index"].as_u64().unwrap_or(0) as u32;@@ -4454,6 +4532,7 @@ async fn stream_claude_with_tools(session_id: session_id.clone(),delta: text.to_string(),reasoning_delta: None,+ finish_reason: None,done: false,}));}@@ -4465,6 +4544,7 @@ async fn stream_claude_with_tools(session_id: session_id.clone(),delta: String::new(),reasoning_delta: Some(thinking.to_string()),+ finish_reason: None,done: false,}));}@@ -4611,6 +4691,7 @@ async fn stream_openai_with_tools(session_id: session_id.clone(),delta: String::new(),reasoning_delta: Some(reasoning),+ finish_reason: None,done: false,}));}@@ -4620,6 +4701,7 @@ async fn stream_openai_with_tools(session_id: session_id.clone(),delta: text,reasoning_delta: None,+ finish_reason: None,done: false,}));}@@ -4630,6 +4712,7 @@ async fn stream_openai_with_tools(session_id: session_id.clone(),delta: String::new(),reasoning_delta: Some(reasoning.to_string()),+ finish_reason: None,done: false,}));}@@ -4639,6 +4722,7 @@ async fn stream_openai_with_tools(session_id: session_id.clone(),delta: text,reasoning_delta: None,+ finish_reason: None,done: false,}));}@@ -4665,6 +4749,9 @@ async fn stream_openai_with_tools(}}if finish_reason_deadline.is_none() && openai_stream_has_finish_reason(&event) {+ if let Some(reason) = event["choices"].get(0).and_then(|choice| choice["finish_reason"].as_str()).filter(|reason| !reason.is_empty()) {+ on_event(StreamToolEvent::FinishReason { reason: reason.to_string() });+ }finish_reason_deadline =Some(tokio::time::Instant::now() + std::time::Duration::from_secs(1));}@@ -4772,6 +4859,12 @@ async fn stream_responses_with_tools(if let Some(usage) = responses_token_usage(&event) {token_usage = Some(usage);}+ if let Some(reason) = event["response"]["incomplete_details"]["reason"]+ .as_str()+ .and_then(output_limit_finish_reason)+ {+ on_event(StreamToolEvent::FinishReason { reason: reason.to_string() });+ }if let Some(text) = responses_stream_text(&event) {emitted.store(true, std::sync::atomic::Ordering::Relaxed);@@ -4779,6 +4872,7 @@ async fn stream_responses_with_tools(session_id: session_id.clone(),delta: text.to_string(),reasoning_delta: None,+ finish_reason: None,done: false,}));}@@ -5025,6 +5119,12 @@ async fn stream_gemini_with_tools(token_usage = Some(TokenUsage { input_tokens: p as u32, output_tokens: c as u32 });}if let Some(candidates) = event["candidates"].as_array() {+ if let Some(reason) = candidates[0]["finishReason"]+ .as_str()+ .and_then(output_limit_finish_reason)+ {+ on_event(StreamToolEvent::FinishReason { reason: reason.to_string() });+ }if let Some(parts) = candidates[0]["content"]["parts"].as_array() {for part in parts {// Text@@ -5034,6 +5134,7 @@ async fn stream_gemini_with_tools(session_id: session_id.clone(),delta: text.to_string(),reasoning_delta: None,+ finish_reason: None,done: false,}));}@@ -5182,10 +5283,10 @@ mod tests {gemini_text, is_agens_endpoint, is_kimi_model, is_retryable_error, list_models_core, maybe_bearer_headers,maybe_tag_retry_after, measure_first_stream_chunk, merge_global_max_retries, minimax_stream_semantics,ollama_selected_model_tool_support, openai_message_content, openai_response_text, openai_stream_reasoning,- openai_stream_text, parse_dynamic_effort_capability, parse_gemini_model_list_response,- parse_model_list_response, parse_retry_after, parse_retry_after_secs, provider_requires_api_key,- redact_secrets, redact_url_query, resolve_endpoint, resolve_gemini_stream_endpoint, resolve_model_effort_core,- resolve_model_list_endpoint, resolve_ollama_show_endpoint, responses_function_tool,+ openai_stream_text, output_limit_finish_reason, parse_dynamic_effort_capability,+ parse_gemini_model_list_response, parse_model_list_response, parse_retry_after, parse_retry_after_secs,+ provider_requires_api_key, redact_secrets, redact_url_query, resolve_endpoint, resolve_gemini_stream_endpoint,+ resolve_model_effort_core, resolve_model_list_endpoint, resolve_ollama_show_endpoint, responses_function_tool,responses_max_output_tokens, responses_stream_text, responses_text, responses_token_usage,retain_ollama_completion_models, retry_after_secs, set_chat_completion_token_limit, stream, stream_claude,stream_claude_with_tools, stream_data_payload, stream_error, stream_openai_with_tools, stream_with_tools,@@ -5198,6 +5299,15 @@ mod tests {};use super::{redacted_http_detail, sensitive_values};+ #[test]+ fn normalizes_provider_output_limit_reasons() {+ assert_eq!(output_limit_finish_reason("length"), Some("length"));+ assert_eq!(output_limit_finish_reason("MAX_TOKENS"), Some("max_tokens"));+ assert_eq!(output_limit_finish_reason("max_output_tokens"), Some("max_tokens"));+ assert_eq!(output_limit_finish_reason("stop"), None);+ assert_eq!(output_limit_finish_reason("tool_calls"), None);+ }+#[test]fn structured_image_attachment_becomes_openai_image_content() {let message = AiMessage {diff --git a/crates/dbx-core/src/ai/agent_loop.rs b/crates/dbx-core/src/ai/agent_loop.rsindex 565ecab929..e58472eb98 100644--- a/crates/dbx-core/src/ai/agent_loop.rs+++ b/crates/dbx-core/src/ai/agent_loop.rs@@ -13,6 +13,7 @@ use crate::ai_cli_agent::CliAgentCommandSpec;use crate::connection::AppState;use crate::models::connection::DatabaseType;use crate::plugin_tools::{self, PluginToolSet, PreparedPluginToolCall};+use crate::skill_tools;use crate::token_usage::TokenUsage;use crate::tool_approval::{self, ToolApprovalWait};@@ -51,6 +52,17 @@ fn chunk_to_events(chunk: &AiStreamChunk) -> Vec<AgentEvent> {if let Some(ref reasoning) = chunk.reasoning_delta {events.push(AgentEvent::ReasoningDelta { delta: reasoning.clone() });}+ // Providers spell the same condition differently — OpenAI `length`, Anthropic+ // `max_tokens`, Gemini `MAX_TOKENS`, the Responses API `max_output_tokens` — so+ // compare case-insensitively: a provider wired up later must not silently miss+ // the notice over a capital letter.+ if let Some(reason) = chunk+ .finish_reason+ .as_deref()+ .filter(|reason| matches!(reason.to_ascii_lowercase().as_str(), "length" | "max_tokens" | "max_output_tokens"))+ {+ events.push(AgentEvent::OutputTruncated { finish_reason: reason.to_string() });+ }events}@@ -96,6 +108,12 @@ pub struct AgentLoopContext {/// Runtime that owns plugin sidecar sessions. The web server runs each/// agent loop on a runtime of its own, so plugin calls are spawned here.pub host_runtime: Option<tokio::runtime::Handle>,+ /// True when this request's prompt carries a skill listing (`use_skill` /+ /// `read_skill_file` ship only with it). Tool schemas are re-sent with every+ /// request, so registering the skill tools unconditionally would charge every+ /// skill-free run for tools that have nothing to resolve, and would put them+ /// in front of a model with no listing to look at (ADR Decision 10).+ pub allow_skills: bool,}#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -163,6 +181,31 @@ pub async fn run_agent_loop(.await}+/// The built-in provider's tool table for one run.+///+/// The skill tools are APPENDED here rather than registered in+/// `read_only_tools` / `all_tools`, so those two keep their exact output for+/// every skill-free request — the listing gate is the only thing that can widen+/// this table (ADR Decision 10). Ask and agent mode both get them: the gate is+/// the listing, not the mode, because reading a skill is read-only by+/// construction.+fn run_tools(+ db_type: DatabaseType,+ sql_permissions: &agent_tools::AgentSqlPermissions,+ is_agent_mode: bool,+ allow_skills: bool,+) -> Vec<ToolDefinition> {+ let mut tools = if is_agent_mode {+ agent_tools::all_tools(db_type, sql_permissions.clone())+ } else {+ agent_tools::read_only_tools(db_type)+ };+ if allow_skills {+ tools.extend(skill_tools::tool_definitions());+ }+ tools+}+#[allow(clippy::too_many_arguments)]async fn run_agent_loop_inner(config: &AiConfig,@@ -289,11 +332,7 @@ async fn run_agent_loop_inner(.await;}let mut sql_permissions = agent_ctx.sql_permissions.clone();- let mut tools = if is_agent_mode {- agent_tools::all_tools(agent_ctx.db_type, sql_permissions.clone())- } else {- agent_tools::read_only_tools(agent_ctx.db_type)- };+ let mut tools = run_tools(agent_ctx.db_type, &sql_permissions, is_agent_mode, agent_ctx.allow_skills);// Plugin tools join agent runs only; ask mode keeps its database-only// read tools.let plugin_tool_set = if is_agent_mode {@@ -1506,6 +1545,17 @@ Use this result to continue the original user task. Do not summarize this tool r}fn compact_tool_result_for_context(tool_name: &str, content: &str) -> String {+ // Both skill tools bound their own output — a page plus a cursor — so this+ // compactor has nothing to save here and everything to lose: it keeps only the+ // head and the tail, and for an instructions file the middle it drops is the+ // part that says what to do. `use_skill` needs this as much as the file reader+ // does: its answer is a body page plus a file listing, which can still cross the+ // budget, and compacting it would throw away the middle of the page the paging+ // exists to deliver.+ if matches!(tool_name, skill_tools::USE_SKILL_TOOL | skill_tools::READ_SKILL_FILE_TOOL) {+ return content.to_string();+ }+if content.chars().count() <= MAX_TOOL_RESULT_CONTEXT_CHARS {return content.to_string();}@@ -1722,6 +1772,7 @@ mod tests {prompt_cache_key: None,session_id: session_id.map(str::to_string),host_runtime: None,+ allow_skills: false,};(temp_dir, ctx)}@@ -1787,6 +1838,50 @@ mod tests {assert!(gate_plugin_tool_calls(&set, &calls, &ctx, &|_event| {}, &cancelled).await.is_none());}+ /// Full tool identity, not just names: two tables differing in a description+ /// or a schema are not "the same tools".+ fn describe(tools: &[ToolDefinition]) -> Vec<String> {+ tools+ .iter()+ .map(|tool| {+ format!(+ "{}|{}|{}|{}|{}",+ tool.name, tool.description, tool.parameters, tool.read_only, tool.parallel_ok+ )+ })+ .collect()+ }++ /// ADR Decision 10: the skill tools ship with the listing, in both modes, and+ /// a request without one gets exactly the tool table it got before they+ /// existed.+ #[test]+ fn skill_tools_ship_only_with_a_skill_listing() {+ let permissions = agent_tools::AgentSqlPermissions::default();+ for is_agent_mode in [false, true] {+ let plain = run_tools(DatabaseType::Postgres, &permissions, is_agent_mode, false);+ let unchanged = if is_agent_mode {+ agent_tools::all_tools(DatabaseType::Postgres, permissions.clone())+ } else {+ agent_tools::read_only_tools(DatabaseType::Postgres)+ };+ assert_eq!(describe(&plain), describe(&unchanged), "a skill-free request must keep its old tool table");++ let with_skills = run_tools(DatabaseType::Postgres, &permissions, is_agent_mode, true);+ let listed = describe(&with_skills);+ assert_eq!(+ listed.len(),+ plain.len() + 2,+ "both skill tools must be appended in agent_mode={is_agent_mode}"+ );+ let names: Vec<&str> = with_skills.iter().map(|tool| tool.name.as_ref()).collect();+ assert!(names.contains(&skill_tools::USE_SKILL_TOOL), "{names:?}");+ assert!(names.contains(&skill_tools::READ_SKILL_FILE_TOOL), "{names:?}");+ // Appending must not disturb the tools that were already there.+ assert_eq!(&listed[..plain.len()], &describe(&plain)[..]);+ }+ }+#[test]fn compaction_prompt_preserves_attachment_trust_boundary() {assert!(COMPACT_SYSTEM_PROMPT.contains("<attached-text-data>"));@@ -2106,6 +2201,7 @@ mod tests {session_id: "test".to_string(),delta: "hello".to_string(),reasoning_delta: None,+ finish_reason: None,done: false,};let events = chunk_to_events(&chunk);@@ -2119,6 +2215,7 @@ mod tests {session_id: "test".to_string(),delta: String::new(),reasoning_delta: Some("thinking...".to_string()),+ finish_reason: None,done: false,};let events = chunk_to_events(&chunk);@@ -2132,6 +2229,7 @@ mod tests {session_id: "test".to_string(),delta: "answer".to_string(),reasoning_delta: Some("thinking...".to_string()),+ finish_reason: None,done: false,};let events = chunk_to_events(&chunk);@@ -2142,18 +2240,37 @@ mod tests {#[test]fn chunk_to_events_returns_empty_for_empty_chunk() {- let chunk =- AiStreamChunk { session_id: "test".to_string(), delta: String::new(), reasoning_delta: None, done: false };+ let chunk = AiStreamChunk {+ session_id: "test".to_string(),+ delta: String::new(),+ reasoning_delta: None,+ finish_reason: None,+ done: false,+ };let events = chunk_to_events(&chunk);assert!(events.is_empty());}+ #[test]+ fn chunk_to_events_surfaces_output_limit_truncation() {+ let chunk = AiStreamChunk {+ session_id: "test".to_string(),+ delta: String::new(),+ reasoning_delta: None,+ finish_reason: Some("length".to_string()),+ done: true,+ };+ let events = chunk_to_events(&chunk);+ assert!(matches!(&events[0], AgentEvent::OutputTruncated { finish_reason } if finish_reason == "length"));+ }+#[test]fn chunk_to_events_reasoning_only_no_text() {let chunk = AiStreamChunk {session_id: "test".to_string(),delta: String::new(),reasoning_delta: Some("reasoning".to_string()),+ finish_reason: None,done: false,};let events = chunk_to_events(&chunk);@@ -2167,6 +2284,7 @@ mod tests {session_id: "test".to_string(),delta: "text only".to_string(),reasoning_delta: None,+ finish_reason: None,done: false,};let events = chunk_to_events(&chunk);diff --git a/crates/dbx-core/src/ai/agent_tools.rs b/crates/dbx-core/src/ai/agent_tools.rsindex 3a12a9e99f..395b5a9104 100644--- a/crates/dbx-core/src/ai/agent_tools.rs+++ b/crates/dbx-core/src/ai/agent_tools.rs@@ -5,6 +5,7 @@ use serde_json::json;use serde_json::Value;use crate::agent_events::{ToolCall, ToolDefinition, ToolResult};+use crate::ai::skill_tools;use crate::connection::AppState;use crate::db::redis_driver::{classify_command, parse_command_argv, RedisCommandResult, RedisCommandSafety};use crate::db::vector_driver;@@ -792,6 +793,13 @@ pub async fn execute_tool_scoped(} else {None};+ // `use_skill` reports which skill it actually resolved. That identity leaves+ // through the tool result's `explain_data`, which is frontend-only (the model+ // sees `content` alone — see the follow-up message built in `agent_loop`), so+ // the UI can record a load from the backend's own answer instead of+ // re-deriving it from the call arguments, which describe an intent and not an+ // outcome. Every other tool leaves this `None`.+ let mut skill_explain: Option<serde_json::Value> = None;let result = match tool_call.name.as_str() {"list_databases" => execute_list_databases(tool_call, state, connection_id).await,"list_tables" => execute_list_tables(tool_call, state, connection_id, database, default_schema, db_type).await,@@ -833,6 +841,17 @@ pub async fn execute_tool_scoped(execute_redis_command(tool_call, state, connection_id, database, database_scope).await}"get_current_time" => execute_get_current_time(tool_call),+ // Skill tools are filesystem-only: `tool_uses_database` must keep+ // returning false for them, or they would serialize on a connection lock+ // they have no reason to hold (see the test below).+ skill_tools::USE_SKILL_TOOL => match skill_tools::execute_use_skill(tool_call, state).await {+ Ok(outcome) => {+ skill_explain = outcome.loaded_skill_id.map(|id| serde_json::json!({ "skillId": id }));+ Ok(outcome.text)+ }+ Err(err) => Err(err),+ },+ skill_tools::READ_SKILL_FILE_TOOL => skill_tools::execute_read_skill_file(tool_call, state).await,_ => Err(format!("Unknown tool: {}", tool_call.name)),};@@ -842,7 +861,7 @@ pub async fn execute_tool_scoped(tool_name: tool_call.name.clone(),content,is_error: false,- explain_data: None,+ explain_data: skill_explain,},Err(err) => ToolResult {tool_call_id: tool_call.id.clone(),@@ -3081,6 +3100,17 @@ for line in sys.stdin:assert!(tool.parallel_ok, "get_current_time must be parallel_ok");}+ /// `tool_uses_database` is a closed whitelist, so this pins the whole+ /// classification: the skill tools read the filesystem, and taking a+ /// per-connection lock for them would serialize unrelated runs for nothing.+ #[test]+ fn skill_tools_do_not_take_the_connection_lock() {+ for name in [skill_tools::USE_SKILL_TOOL, skill_tools::READ_SKILL_FILE_TOOL] {+ assert!(!tool_uses_database(name), "{name} must not be classified as a database tool");+ }+ assert!(tool_uses_database("execute_query"), "the whitelist must still contain real database tools");+ }+#[test]fn execute_get_current_time_returns_valid_timestamps() {let before_secs = chrono::Utc::now().timestamp();diff --git a/crates/dbx-core/src/ai/mod.rs b/crates/dbx-core/src/ai/mod.rsindex c01d8209b8..16e75fd2ae 100644--- a/crates/dbx-core/src/ai/mod.rs+++ b/crates/dbx-core/src/ai/mod.rs@@ -7,4 +7,5 @@ pub mod agent_tools;pub mod mcp_policy;pub mod plugin_tools;pub mod prompt_template;+pub mod skill_tools;pub mod tool_approval;diff --git a/crates/dbx-core/src/ai/skill_tools.rs b/crates/dbx-core/src/ai/skill_tools.rsnew file mode 100644index 0000000000..fc369bbc08--- /dev/null+++ b/crates/dbx-core/src/ai/skill_tools.rs@@ -0,0 +1,777 @@+//! The on-demand skill tools: `use_skill` and `read_skill_file`.+//!+//! The system prompt carries only a listing — name, source and description per+//! skill. The body of a skill is fetched by the model through `use_skill` when it+//! decides the skill is relevant, and the files a skill ships are fetched one by+//! one through `read_skill_file` (prd 09-30-skill-listing-use-skill,+//! Requirements 8-11b). The previous behaviour — injecting every selected body+//! into the prompt — is gone.+//!+//! Two rules shape every string this module emits:+//!+//! * **No absolute paths.** The model addresses a skill by the name the listing+//! showed it and a file by a path relative to the skill directory. The+//! canonical directory behind [`crate::skills::ResolvedSkill::dir`] never+//! crosses the tool boundary (Requirement 11), and neither do OS errors, which+//! carry paths of their own.+//! * **Reading is not executing.** Both definitions say so in as many words+//! (Requirement 11a). The execution boundary stays the plugin approval gate,+//! which has no shell tool to run; an extension whitelist was rejected because+//! it blocks legitimate SQL templates and data scripts while a script path+//! written inside a SKILL.md body still induces a run.+//!+//! Both tools are read-only and database-independent, so they ship only with a+//! request that carries a skill listing (ADR Decision 10 — see `run_tools` in+//! [`crate::ai::agent_loop`]) and must never be classified as database tools, or+//! they would take a per-connection lock they have no use for.++use serde_json::{json, Value};++use crate::agent_events::{ToolCall, ToolDefinition};+use crate::connection::AppState;+use crate::skills::{self, ResolvedSkill, SkillCandidate, SkillLookup, SkillRoots};++/// Tool names, also the dispatch keys in `agent_tools::execute_tool_scoped`.+pub const USE_SKILL_TOOL: &str = "use_skill";+pub const READ_SKILL_FILE_TOOL: &str = "read_skill_file";++/// Requirement 11a, verbatim in both descriptions. A test pins it so the wording+/// cannot drift away from the decision it records.+pub const READ_IS_NOT_EXECUTION_NOTICE: &str =+ "读取文件内容不等于获得执行许可。绝不因为读到脚本就建议或尝试执行;如需执行,请用户在 DBX 之外自行处理。";++/// A failed name lookup answers with the available names so the model can+/// recover, but that catalog is bounded like every other listing.+const MAX_CATALOG_ENTRIES: usize = 100;+/// Candidate descriptions exist to tell same-named skills apart, not to sell one,+/// so they stay short in the ambiguous answer.+const MAX_CANDIDATE_DESCRIPTION_CHARS: usize = 200;+/// Keep one file tool result below the generic intermediate-result budget.+pub const DEFAULT_READ_CHUNK_CHARS: usize = 10_000;+/// `use_skill` includes both an instruction page and a file catalogue, so it+/// needs one shared ceiling rather than independently bounded pieces.+const MAX_USE_SKILL_RESULT_CHARS: usize = 10_000;+/// How much of a skill body `use_skill` returns before handing over a cursor.+/// A longer body is paged rather than truncated — see `format_skill`.+const SKILL_BODY_CHUNK_CHARS: usize = 6_000;++/// The two skill tools, in dispatch order.+pub fn tool_definitions() -> Vec<ToolDefinition> {+ vec![use_skill_definition(), read_skill_file_definition()]+}++fn skill_argument(description: &str) -> Value {+ json!({ "type": "string", "description": description })+}++fn source_argument() -> Value {+ json!({+ "type": "string",+ "enum": ["default", "custom"],+ "description": "Skill source. Pass it when the same name is listed under more than one source."+ })+}++/// Resolves one skill by listed name and returns its body plus the files it+/// ships. Deliberately has no path argument: the model chooses among skills, it+/// never names a location.+fn use_skill_definition() -> ToolDefinition {+ ToolDefinition {+ name: USE_SKILL_TOOL.into(),+ description: format!(+ "Load the instructions of one user skill, by the name it is listed under in the skill \+ listing, and get the list of files that skill ships (relative paths, each with its size and \+ [text]/[binary] kind). Skill bodies are not in the prompt: call this before answering with a \+ skill the user selected. A long body comes back in pages and the answer says how to read on. \+ If the name exists in more than one source, the call returns the candidates — retry with \+ `source` instead of guessing. {READ_IS_NOT_EXECUTION_NOTICE} Reading a script's source is \+ informational only."+ )+ .into(),+ parameters: json!({+ "type": "object",+ "properties": {+ "skill": skill_argument("Exact skill name as shown in the skill listing"),+ "source": source_argument()+ },+ "required": ["skill"]+ }),+ read_only: true,+ parallel_ok: true,+ }+}++/// Reads one file inside a skill directory, addressed by the relative path the+/// listing printed. This is the wider surface of the two — the path is model+/// input — so the containment and size rules live in [`crate::skills`] and are+/// re-validated on every call.+fn read_skill_file_definition() -> ToolDefinition {+ ToolDefinition {+ name: READ_SKILL_FILE_TOOL.into(),+ description: format!(+ "Read one file that a skill ships, addressed by a path relative to the skill directory \+ exactly as `use_skill` listed it (for example `references/rules.md`). Only text files \+ inside that skill directory can be read; files over 1 MiB, binary files and paths that \+ leave the skill directory are refused. Reads are bounded; pass the returned nextOffset to \+ continue. {READ_IS_NOT_EXECUTION_NOTICE} Reading a script's source is informational only."+ )+ .into(),+ parameters: json!({+ "type": "object",+ "properties": {+ "skill": skill_argument("Exact skill name as shown in the skill listing"),+ "source": source_argument(),+ "relativePath": {+ "type": "string",+ "description": "Path relative to the skill directory, as listed by use_skill"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "description": "Character offset returned as nextOffset; defaults to 0"+ },+ "limit": {+ "type": "integer",+ "minimum": 1,+ "maximum": DEFAULT_READ_CHUNK_CHARS,+ "description": "Maximum characters to return; defaults to 10000"+ }+ },+ "required": ["skill", "relativePath"]+ }),+ read_only: true,+ parallel_ok: true,+ }+}++/// Which skill the model asked for.+#[derive(Debug)]+struct SkillTarget {+ name: String,+ source: Option<String>,+}++impl SkillTarget {+ fn from_tool_call(tool_call: &ToolCall) -> Result<Self, String> {+ let name = required_argument(tool_call, "skill")?;+ let source = match tool_call.arguments.get("source") {+ None | Some(Value::Null) => None,+ Some(Value::String(value)) => match value.trim() {+ "" => None,+ "default" | "custom" => Some(value.trim().to_string()),+ other => {+ return Err(format!("`source` must be \"default\" or \"custom\", not \"{other}\""));+ }+ },+ Some(_) => return Err("`source` must be a string".to_string()),+ };+ Ok(Self { name, source })+ }+}++fn required_argument(tool_call: &ToolCall, key: &str) -> Result<String, String> {+ tool_call+ .arguments+ .get(key)+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .map(str::to_string)+ .ok_or_else(|| format!("`{key}` is required"))+}++fn optional_u64_argument(tool_call: &ToolCall, key: &str) -> Result<Option<u64>, String> {+ match tool_call.arguments.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(Value::Number(value)) => {+ value.as_u64().map(Some).ok_or_else(|| format!("`{key}` must be a non-negative integer"))+ }+ Some(_) => Err(format!("`{key}` must be a non-negative integer")),+ }+}++/// What `use_skill` resolved: the text the model reads, plus the identity the+/// backend actually loaded.+///+/// `loaded_skill_id` exists so a caller never has to re-derive "which skill was+/// loaded" from the call arguments. The arguments say what the model *asked*+/// for, and an ambiguous or missing name loads nothing at all — re-deriving an+/// id from them lights a chip, and later injects a body, for a skill that was+/// never loaded.+#[derive(Debug)]+pub struct UseSkillOutcome {+ pub text: String,+ pub loaded_skill_id: Option<String>,+}++pub async fn execute_use_skill(tool_call: &ToolCall, state: &AppState) -> Result<UseSkillOutcome, String> {+ let target = SkillTarget::from_tool_call(tool_call)?;+ let roots = load_skill_roots(state).await;+ run_blocking(move || use_skill_answer(&target, &roots)).await+}++pub async fn execute_read_skill_file(tool_call: &ToolCall, state: &AppState) -> Result<String, String> {+ let target = SkillTarget::from_tool_call(tool_call)?;+ let relative = required_argument(tool_call, "relativePath")?;+ let offset = optional_u64_argument(tool_call, "offset")?.unwrap_or(0) as usize;+ let limit =+ optional_u64_argument(tool_call, "limit")?.map(|value| value as usize).unwrap_or(DEFAULT_READ_CHUNK_CHARS);+ if limit == 0 || limit > DEFAULT_READ_CHUNK_CHARS {+ return Err(format!("`limit` must be between 1 and {DEFAULT_READ_CHUNK_CHARS}"));+ }+ let roots = load_skill_roots(state).await;+ run_blocking(move || read_skill_file_answer(&target, &relative, offset, limit, &roots)).await+}++/// Reading a skill scans directories and reads files up to 1 MiB, so it must not+/// run on the async runtime. Both callers are inside a Tokio runtime (the Tauri+/// command and the web server's per-run runtime).+async fn run_blocking<T: Send + 'static>(+ work: impl FnOnce() -> Result<T, String> + Send + 'static,+) -> Result<T, String> {+ tokio::task::spawn_blocking(work).await.map_err(|error| format!("Skill tool task failed: {error}"))?+}++/// Roots come from the persisted settings, not from the request: the model (or a+/// stale request) cannot widen which roots are scanned, and the custom root stays+/// inert while its Settings switch is off. A failed settings read degrades to the+/// default root only.+async fn load_skill_roots(state: &AppState) -> SkillRoots {+ let (custom_root_enabled, custom_root) = match state.storage.load_desktop_settings().await {+ Ok(settings) => (settings.custom_ai_skill_root_enabled, settings.custom_ai_skill_root),+ Err(error) => {+ log::warn!("[agent][skills] cannot read the skill root settings; using the default root only: {error}");+ (false, None)+ }+ };+ match tokio::task::spawn_blocking(move || SkillRoots::resolve(custom_root_enabled, custom_root.as_deref())).await {+ Ok(roots) => roots,+ Err(error) => {+ log::warn!("[agent][skills] skill root resolution failed: {error}");+ SkillRoots { default: None, custom: None }+ }+ }+}++fn use_skill_answer(target: &SkillTarget, roots: &SkillRoots) -> Result<UseSkillOutcome, String> {+ match skills::read_skill_by_name(&target.name, target.source.as_deref(), roots) {+ SkillLookup::Found(skill) => {+ let text = format_skill(&skill);+ Ok(UseSkillOutcome { text, loaded_skill_id: Some(skill.id) })+ }+ // Err rather than a text answer: `is_error` on the tool result is the+ // only thing that says "nothing was loaded". `read_skill_file` answers+ // these two cases the same way, so one recovery instruction serves both.+ SkillLookup::Ambiguous(candidates) => Err(ambiguous_answer(&target.name, &candidates)),+ SkillLookup::NotFound => Err(not_found_answer(&target.name, roots)),+ }+}++fn read_skill_file_answer(+ target: &SkillTarget,+ relative: &str,+ offset: usize,+ limit: usize,+ roots: &SkillRoots,+) -> Result<String, String> {+ let skill = match skills::read_skill_by_name(&target.name, target.source.as_deref(), roots) {+ SkillLookup::Found(skill) => skill,+ // Retrying with the right skill is the model's job; a wrong or missing+ // skill is answered exactly like `use_skill` would, so one recovery+ // instruction serves both tools.+ SkillLookup::Ambiguous(candidates) => return Err(ambiguous_answer(&target.name, &candidates)),+ SkillLookup::NotFound => return Err(not_found_answer(&target.name, roots)),+ };+ let chunk = skills::read_skill_file_relative_chunk(&skill.dir, relative, offset, limit).map_err(|reason| {+ // The reason is a frozen word from `skills`; the OS detail behind it is+ // discarded there because it carries paths.+ log::debug!("[agent][skills] read_skill_file refused for skill '{}': {reason}", skill.name);+ read_failure_message(&reason)+ })?;+ let next_offset = chunk.next_offset.map_or_else(|| "none".to_string(), |value| value.to_string());+ Ok(format!(+ "[SKILL FILE CHUNK] path={relative} offset={offset} chars={}/{} nextOffset={next_offset}\n\n{}",+ chunk.content.chars().count(),+ chunk.total_chars,+ chunk.content+ ))+}++fn format_skill(skill: &ResolvedSkill) -> String {+ let listing = skills::list_skill_files(&skill.dir);+ let body = skill.content.trim_end();+ let body_chars = body.chars().count();+ let mut output = format!("# Skill: {} [{}]\n\n", skill.name, skill.source);+ if body_chars <= SKILL_BODY_CHUNK_CHARS {+ output.push_str(body);+ output.push('\n');+ } else {+ // Page the body instead of letting it be truncated downstream. The generic+ // intermediate-result compactor keeps only the head and the tail of an+ // oversized tool result, and for an instructions file the head and the tail+ // are the least useful parts — the operational steps sit in the middle that+ // gets dropped. A bounded first page plus an explicit cursor keeps every+ // character reachable, through the same `offset` the file reader already+ // takes.+ let page: String = body.chars().take(SKILL_BODY_CHUNK_CHARS).collect();+ output.push_str(&page);+ output.push_str(&format!(+ "\n\n(this skill's body is {body_chars} characters; the first {SKILL_BODY_CHUNK_CHARS} are shown \+ above. Read the rest with `read_skill_file`, passing `relativePath` \"{}\" and `offset` \+ {SKILL_BODY_CHUNK_CHARS}; keep passing the returned nextOffset until it is absent.)\n",+ skills::SKILL_FILE_NAME+ ));+ }+ output.push_str("\n## Files in this skill\n");+ if listing.entries.is_empty() {+ output.push_str("(this skill ships no extra files)\n");+ }+ let mut catalogue_omitted_for_budget = false;+ for entry in &listing.entries {+ let kind = if entry.text { "[text]" } else { "[binary]" };+ let rendered = format!("- {} ({} bytes) {kind}\n", entry.relative_path, entry.bytes);+ // Reserve room for the continuation instructions below. Never let a+ // long filename turn a bounded first page back into a generic tool+ // result that the agent loop has to compact.+ if output.chars().count() + rendered.chars().count() + 400 > MAX_USE_SKILL_RESULT_CHARS {+ catalogue_omitted_for_budget = true;+ break;+ }+ output.push_str(&rendered);+ }+ if listing.truncated || catalogue_omitted_for_budget {+ // A capped listing must say so, or the model reads a partial file list+ // as the whole skill.+ output.push_str(+ "(the file list is truncated; use `read_skill_file` only for paths referenced by the instructions)\n",+ );+ }+ output.push_str(+ "\nFollow this skill's instructions. Use `read_skill_file` with one of these relative paths when \+ you need a file the skill references.\n",+ );+ output+}++/// The ambiguous-name answer lists the candidates and stops there: picking one+/// would be a silent wrong-skill answer, and skill names genuinely do live in+/// both roots.+fn ambiguous_answer(name: &str, candidates: &[SkillCandidate]) -> String {+ // Two skills in the *same* source cannot be told apart by `source`, so the+ // usual "retry with a source" recovery would be impossible to follow. That+ // collision is the user's to fix, so say what is true instead of sending the+ // model in a circle. The `len() > 1` guard is not cosmetic: a lone candidate+ // has nothing to be told apart from, and the wording below would be false.+ let same_source = candidates.len() > 1+ && candidates.first().is_some_and(|first| candidates.iter().all(|candidate| candidate.source == first.source));+ let mut output = format!("Several skills are named \"{name}\":\n");+ for candidate in candidates {+ output.push_str(&format!(+ "- {} [{}]: {}\n",+ candidate.name,+ candidate.source,+ truncate_chars(&candidate.description, MAX_CANDIDATE_DESCRIPTION_CHARS)+ ));+ }+ output.push_str(if same_source {+ "\nThey all live in the same source, so `source` cannot tell them apart. Continue without this skill, or tell \+ the user that two skills share this name.\n"+ } else {+ "\nCall this tool again with `source` set to one of the values above.\n"+ });+ output+}++fn not_found_answer(name: &str, roots: &SkillRoots) -> String {+ let catalog = skills::list_skill_candidates(roots);+ if catalog.is_empty() {+ return format!(+ "No skill is named \"{name}\", and no skills are available right now. Continue without a skill."+ );+ }+ // Names and sources only: the model already has the descriptions in the+ // listing, and this answer must stay cheap and path-free.+ let mut output = format!("No skill is named \"{name}\". Available skills:\n");+ for candidate in catalog.iter().take(MAX_CATALOG_ENTRIES) {+ output.push_str(&format!("- {} [{}]\n", candidate.name, candidate.source));+ }+ if catalog.len() > MAX_CATALOG_ENTRIES {+ output.push_str("(the list is truncated)\n");+ }+ output.push_str(+ "\nCall this tool again with one of those names, and pass `source` when the name is listed under both sources.",+ );+ output+}++/// Turns a frozen reason into something the model can act on. No OS text and no+/// path: every branch is a fixed string.+fn read_failure_message(reason: &str) -> String {+ let detail = match reason {+ "oversized" => "it is larger than the 1 MiB limit for skill files",+ "not_utf8" => "it is not valid UTF-8 text",+ "not_text" => "it looks binary (it contains a NUL byte), so only text files can be read",+ "unreadable" => "it could not be read",+ "root_unavailable" => "the skill root is not available",+ _ => "no such file exists in this skill directory",+ };+ format!("The skill file could not be read: {detail}.")+}++fn truncate_chars(value: &str, limit: usize) -> String {+ if value.chars().count() <= limit {+ return value.to_string();+ }+ let mut truncated: String = value.chars().take(limit).collect();+ truncated.push('…');+ truncated+}++#[cfg(test)]+mod tests {+ use super::*;++ use std::path::{Path, PathBuf};++ const SKILL_BODY: &str = "---\nname: %NAME%\ndescription: %DESC%\n---\n\nFollow these rules.\n";++ fn temp_root(tag: &str) -> PathBuf {+ let root = std::env::temp_dir().join(format!("dbx-skill-tools-{tag}-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&root).unwrap();+ root+ }++ fn write_skill(root: &Path, dir: &str, name: &str, description: &str) -> PathBuf {+ let dir = root.join(dir);+ std::fs::create_dir_all(&dir).unwrap();+ let body = SKILL_BODY.replace("%NAME%", name).replace("%DESC%", description);+ std::fs::write(dir.join(skills::SKILL_FILE_NAME), body).unwrap();+ dir+ }++ fn roots_of(default: &Path, custom: Option<&Path>) -> SkillRoots {+ SkillRoots {+ default: Some(std::fs::canonicalize(default).unwrap()),+ custom: custom.map(|path| std::fs::canonicalize(path).unwrap()),+ }+ }++ fn call(name: &str, arguments: Value) -> ToolCall {+ ToolCall { id: "call-1".to_string(), name: name.to_string(), arguments, provider_payload: None }+ }++ fn target(name: &str, source: Option<&str>) -> SkillTarget {+ SkillTarget { name: name.to_string(), source: source.map(str::to_string) }+ }++ /// Requirement 11: no tool result may carry a filesystem path. Both spellings+ /// are checked because the canonical form embeds the plain one as a substring,+ /// so a naive containment check against the canonical path alone would miss a+ /// leak of the plain path. On Windows a leaked absolute path always brings a+ /// backslash, and relative paths are normalized to `/`.+ fn assert_no_path_leak(text: &str, roots: &[&Path]) {+ assert!(!text.contains('\\'), "a backslash can only come from a real path: {text}");+ for root in roots {+ let plain = root.to_string_lossy().to_string();+ assert!(!text.contains(&plain), "the skill root leaked: {text}");+ let canonical = std::fs::canonicalize(root).unwrap().to_string_lossy().to_string();+ assert!(!text.contains(&canonical), "the canonical skill root leaked: {text}");+ }+ }++ #[test]+ fn tool_definitions_are_read_only_parallel_and_state_the_execution_boundary() {+ let definitions = tool_definitions();+ let names: Vec<&str> = definitions.iter().map(|definition| definition.name.as_ref()).collect();+ assert_eq!(names, [USE_SKILL_TOOL, READ_SKILL_FILE_TOOL]);+ for definition in &definitions {+ assert!(definition.read_only, "{} must be read-only", definition.name);+ assert!(definition.parallel_ok, "{} must stay parallel-safe", definition.name);+ assert!(+ definition.description.contains(READ_IS_NOT_EXECUTION_NOTICE),+ "{} must carry the no-execution notice verbatim",+ definition.name+ );+ assert!(definition.description.contains("informational only"), "{}", definition.name);+ // The schema is the only place the model learns how to address a+ // skill, and it must never invite a path.+ assert!(definition.parameters.pointer("/properties/skill").is_some());+ assert!(definition.parameters["required"].as_array().unwrap().contains(&json!("skill")));+ }+ let read = definitions.iter().find(|definition| definition.name == READ_SKILL_FILE_TOOL).unwrap();+ assert_eq!(read.parameters["properties"]["source"]["enum"], json!(["default", "custom"]));+ assert!(read.parameters["required"].as_array().unwrap().contains(&json!("relativePath")));+ }++ #[test]+ fn use_skill_reads_a_unique_name_and_lists_referencing_files_by_relative_path() {+ let root = temp_root("use");+ let dir = write_skill(&root, "alpha", "sql-review", "review rules");+ std::fs::create_dir_all(dir.join("references")).unwrap();+ std::fs::write(dir.join("references").join("one.md"), "one").unwrap();+ std::fs::write(dir.join("script.py"), "print(1)").unwrap();+ std::fs::write(dir.join("logo.png"), [0x89u8, b'P', 0, 1]).unwrap();+ let roots = roots_of(&root, None);++ let outcome = use_skill_answer(&target("sql-review", None), &roots).unwrap();+ let answer = &outcome.text;+ assert!(answer.contains("Follow these rules."), "the body must be returned: {answer}");+ assert!(answer.contains("references/one.md (3 bytes) [text]"), "{answer}");+ assert!(answer.contains("script.py (8 bytes) [text]"), "{answer}");+ assert!(answer.contains("logo.png (4 bytes) [binary]"), "{answer}");+ assert!(answer.contains("read_skill_file"), "the answer must say how to read them");+ // The load names the skill it resolved; that id is what a caller records.+ assert!(+ outcome.loaded_skill_id.as_deref().is_some_and(|id| id.starts_with("d-")),+ "{:?}",+ outcome.loaded_skill_id+ );+ assert_no_path_leak(answer, &[&root]);+ }++ #[test]+ fn use_skill_says_when_the_file_listing_is_truncated() {+ let root = temp_root("truncated");+ let dir = write_skill(&root, "many", "many-files", "d");+ for index in 0..skills::SKILL_LISTING_MAX_ENTRIES + 3 {+ std::fs::write(dir.join(format!("file-{index:03}.md")), "x").unwrap();+ }+ let roots = roots_of(&root, None);++ let answer = use_skill_answer(&target("many-files", None), &roots).unwrap().text;+ assert!(answer.contains("truncated"), "{answer}");+ // SKILL.md is one of the capped entries; every listed file here is text.+ assert_eq!(answer.matches(" bytes) [text]").count(), skills::SKILL_LISTING_MAX_ENTRIES, "{answer}");+ }++ /// A body longer than one answer must come back paged, not truncated: the+ /// generic intermediate-result compactor keeps only the head and the tail of an+ /// oversized result, and for an instructions file the middle it drops is the+ /// part that says what to do.+ #[test]+ fn use_skill_pages_a_body_that_does_not_fit_one_answer() {+ let root = temp_root("paged-body");+ let dir = root.join("big");+ std::fs::create_dir_all(&dir).unwrap();+ // A marker at the very end: it is only reachable through the cursor, so it+ // also proves the continuation lands in the region the first page omitted.+ let filler = "x".repeat(SKILL_BODY_CHUNK_CHARS + 5_000);+ let body = format!("---\nname: big-skill\ndescription: long\n---\n\n{filler}\nEND-OF-BODY\n");+ std::fs::write(dir.join(skills::SKILL_FILE_NAME), &body).unwrap();+ let roots = roots_of(&root, None);++ let answer = use_skill_answer(&target("big-skill", None), &roots).unwrap().text;+ assert!(!answer.contains("END-OF-BODY"), "an oversized body must not come back whole: {answer}");+ assert!(answer.contains("Read the rest with `read_skill_file`"), "{answer}");+ assert!(answer.chars().count() <= MAX_USE_SKILL_RESULT_CHARS, "{answer}");+ assert!(answer.contains("nextOffset"), "{answer}");+ assert!(+ answer.contains(&format!("`offset` {SKILL_BODY_CHUNK_CHARS}")),+ "the answer must name the cursor to continue from: {answer}"+ );+ assert_no_path_leak(&answer, &[&root]);++ // The cursor is in the same coordinates the file reader uses, so following it+ // really does reach the tail.+ let rest = read_skill_file_answer(+ &target("big-skill", None),+ skills::SKILL_FILE_NAME,+ SKILL_BODY_CHUNK_CHARS,+ DEFAULT_READ_CHUNK_CHARS,+ &roots,+ )+ .unwrap();+ assert!(rest.contains("END-OF-BODY"), "the cursor must reach the tail: {rest}");+ assert_no_path_leak(&rest, &[&root]);+ }++ #[test]+ fn use_skill_returns_candidates_instead_of_guessing_between_sources() {+ let root = temp_root("ambiguous");+ write_skill(&root, "one", "shared", "first description");+ let custom = temp_root("ambiguous-custom");+ write_skill(&custom, "two", "shared", "second description");+ let roots = roots_of(&root, Some(&custom));++ let answer = use_skill_answer(&target("shared", None), &roots).unwrap_err();+ assert!(answer.contains("shared [default]: first description"), "{answer}");+ assert!(answer.contains("shared [custom]: second description"), "{answer}");+ assert!(answer.contains("`source`"), "the model must be told how to disambiguate: {answer}");+ assert!(!answer.contains("Follow these rules."), "an ambiguous name must not return a body: {answer}");+ assert_no_path_leak(&answer, &[&root, &custom]);++ // The retry with a source resolves it.+ let chosen = use_skill_answer(&target("shared", Some("custom")), &roots).unwrap().text;+ assert!(chosen.contains("# Skill: shared [custom]"), "{chosen}");+ }++ /// Two skills in ONE source are a dead end for this tool: `source` is the+ /// documented discriminator and here both candidates carry the same one. The+ /// answer must say that instead of telling the model to retry with a value+ /// that cannot separate them.+ #[test]+ fn ambiguous_skills_in_one_source_do_not_pretend_source_can_separate_them() {+ let root = temp_root("collision");+ write_skill(&root, "one", "shared", "first description");+ write_skill(&root, "two", "shared", "second description");+ let roots = roots_of(&root, None);++ let answer = use_skill_answer(&target("shared", None), &roots).unwrap_err();+ assert!(answer.contains("shared [default]: first description"), "{answer}");+ assert!(answer.contains("shared [default]: second description"), "{answer}");+ assert!(!answer.contains("again with `source`"), "source cannot separate two entries in one root: {answer}");+ assert!(answer.contains("cannot tell them apart"), "{answer}");+ assert_no_path_leak(&answer, &[&root]);+ }++ #[test]+ fn use_skill_answers_a_missing_name_with_the_catalog() {+ let root = temp_root("missing");+ write_skill(&root, "alpha", "sql-review", "rules");+ let custom = temp_root("missing-custom");+ write_skill(&custom, "beta", "team-rules", "team");+ let roots = roots_of(&root, Some(&custom));++ let answer = use_skill_answer(&target("sql-reveiw", None), &roots).unwrap_err();+ assert!(answer.contains("- sql-review [default]"), "{answer}");+ assert!(answer.contains("- team-rules [custom]"), "{answer}");+ assert_no_path_leak(&answer, &[&root, &custom]);++ // No roots at all (default root missing, custom root disabled) is an+ // empty catalog, not a failure.+ let empty = SkillRoots { default: None, custom: None };+ let answer = use_skill_answer(&target("sql-review", None), &empty).unwrap_err();+ assert!(answer.contains("no skills are available"), "{answer}");+ }++ #[test]+ fn read_skill_file_returns_a_file_inside_the_skill_directory() {+ let root = temp_root("read");+ let dir = write_skill(&root, "alpha", "sql-review", "rules");+ std::fs::create_dir_all(dir.join("references")).unwrap();+ std::fs::write(dir.join("references").join("one.md"), "reference body").unwrap();+ let roots = roots_of(&root, None);++ let content = read_skill_file_answer(+ &target("sql-review", None),+ "references/one.md",+ 0,+ DEFAULT_READ_CHUNK_CHARS,+ &roots,+ )+ .unwrap();+ assert!(content.contains("reference body"));+ assert!(read_skill_file_answer(&target("sql-review", None), "SKILL.md", 0, DEFAULT_READ_CHUNK_CHARS, &roots)+ .unwrap()+ .contains("name: sql-review"));+ }++ #[test]+ fn read_skill_file_refuses_escapes_absolutes_and_unreadable_files() {+ let root = temp_root("reject");+ let dir = write_skill(&root, "alpha", "sql-review", "rules");+ std::fs::write(root.join("outside.md"), "outside body").unwrap();+ let roots = roots_of(&root, None);+ let skill = target("sql-review", None);++ for escape in+ ["../outside.md", "references/../../outside.md", "..\\outside.md", "/etc/hosts", "C:\\Windows\\win.ini"]+ {+ let error = read_skill_file_answer(&skill, escape, 0, DEFAULT_READ_CHUNK_CHARS, &roots).unwrap_err();+ assert!(error.contains("no such file"), "{escape:?} must be refused: {error}");+ assert!(!error.contains(escape), "an error must not echo the requested path: {error}");+ }+ assert!(+ read_skill_file_answer(&skill, "references", 0, DEFAULT_READ_CHUNK_CHARS, &roots).is_err(),+ "a directory is not a file"+ );++ std::fs::write(dir.join("with-nul.md"), b"text\0more").unwrap();+ let error = read_skill_file_answer(&skill, "with-nul.md", 0, DEFAULT_READ_CHUNK_CHARS, &roots).unwrap_err();+ assert!(error.contains("binary"), "{error}");++ // No NUL byte here, so this must reach the encoding check instead of+ // being mistaken for binary.+ std::fs::write(dir.join("broken.md"), [0xFFu8, 0xFE]).unwrap();+ assert!(read_skill_file_answer(&skill, "broken.md", 0, DEFAULT_READ_CHUNK_CHARS, &roots)+ .unwrap_err()+ .contains("UTF-8"));++ let big = dir.join("big.md");+ std::fs::write(&big, "x").unwrap();+ std::fs::OpenOptions::new().write(true).open(&big).unwrap().set_len(skills::MAX_SKILL_FILE_BYTES + 1).unwrap();+ assert!(read_skill_file_answer(&skill, "big.md", 0, DEFAULT_READ_CHUNK_CHARS, &roots)+ .unwrap_err()+ .contains("1 MiB"));+ }++ /// The tool layer must hand the *canonical skill directory* to the+ /// containment check — a root-prefix check would accept this junction, since+ /// both directories do live under the root. Windows equivalent of the unix+ /// `symlink` test in `skills::tests`; see the note there for what a junction+ /// cannot cover.+ #[cfg(windows)]+ #[test]+ fn read_skill_file_cannot_follow_a_junction_out_of_the_skill_directory() {+ let root = temp_root("junction");+ let dir = write_skill(&root, "alpha", "sql-review", "rules");+ let outside = temp_root("junction-outside");+ std::fs::write(outside.join("secret.md"), "secret").unwrap();+ let output = std::process::Command::new("cmd")+ .args(["/C", "mklink", "/J"])+ .arg(dir.join("linkdir"))+ .arg(&outside)+ .output()+ .expect("cmd must be runnable to create a junction");+ assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));++ let roots = roots_of(&root, None);+ let error = read_skill_file_answer(+ &target("sql-review", None),+ "linkdir/secret.md",+ 0,+ DEFAULT_READ_CHUNK_CHARS,+ &roots,+ )+ .unwrap_err();+ assert!(error.contains("no such file"), "{error}");++ let answer = use_skill_answer(&target("sql-review", None), &roots).unwrap().text;+ assert!(!answer.contains("linkdir"), "the listing must not advertise a link that leaves the skill: {answer}");+ }++ #[test]+ fn arguments_are_validated_before_any_filesystem_work() {+ assert_eq!(SkillTarget::from_tool_call(&call(USE_SKILL_TOOL, json!({}))).unwrap_err(), "`skill` is required");+ assert_eq!(+ SkillTarget::from_tool_call(&call(USE_SKILL_TOOL, json!({ "skill": " " }))).unwrap_err(),+ "`skill` is required"+ );+ assert_eq!(+ SkillTarget::from_tool_call(&call(USE_SKILL_TOOL, json!({ "skill": "a", "source": "bogus" }))).unwrap_err(),+ "`source` must be \"default\" or \"custom\", not \"bogus\""+ );+ assert_eq!(+ SkillTarget::from_tool_call(&call(USE_SKILL_TOOL, json!({ "skill": "a", "source": 7 }))).unwrap_err(),+ "`source` must be a string"+ );+ // An empty or absent source means "no filter", not "no source matches".+ let target =+ SkillTarget::from_tool_call(&call(USE_SKILL_TOOL, json!({ "skill": "a", "source": " " }))).unwrap();+ assert_eq!(target.name, "a");+ assert!(target.source.is_none());+ assert_eq!(+ required_argument(&call(READ_SKILL_FILE_TOOL, json!({ "skill": "a" })), "relativePath").unwrap_err(),+ "`relativePath` is required"+ );+ }++ #[test]+ fn candidate_descriptions_are_trimmed_to_a_hint() {+ let long = "x".repeat(MAX_CANDIDATE_DESCRIPTION_CHARS + 50);+ let candidates = vec![SkillCandidate { name: "shared".to_string(), source: "default", description: long }];+ let answer = ambiguous_answer("shared", &candidates);+ assert!(answer.contains('…'), "{answer}");+ assert!(answer.len() < MAX_CANDIDATE_DESCRIPTION_CHARS + 200, "{answer}");+ }+}diff --git a/crates/dbx-core/src/lib.rs b/crates/dbx-core/src/lib.rsindex e882ab6d7b..51e82905f1 100644--- a/crates/dbx-core/src/lib.rs+++ b/crates/dbx-core/src/lib.rs@@ -18,6 +18,7 @@ pub use ai::agent_kv;pub use ai::agent_loop;pub use ai::agent_tools;pub use ai::plugin_tools;+pub use ai::skill_tools;pub use ai::tool_approval;pub use dbx_drivers::agent_catalog;pub use dbx_drivers::agent_connection;@@ -87,6 +88,7 @@ pub use query::redis_ops;pub use safety::risk_metrics;pub mod scheduled_backup;pub mod schema;+pub mod skills;pub use connection::session_credentials;pub use connection::task_supervisor;pub use data::script_generator;diff --git a/crates/dbx-core/src/persistence/cloud_sync.rs b/crates/dbx-core/src/persistence/cloud_sync.rsindex 419cebfefb..fdb9e1cbbf 100644--- a/crates/dbx-core/src/persistence/cloud_sync.rs+++ b/crates/dbx-core/src/persistence/cloud_sync.rs@@ -69,6 +69,10 @@ const DESKTOP_DEVICE_LOCAL_SETTINGS: &[&str] = &["agent_store_dir","custom_ai_skill_root_enabled","custom_ai_skill_root",+ // Device-local like the two above: it gates which of *this* device's skill+ // files reach the prompt, so a synced "on" would inject another machine's+ // catalog here.+ "custom_ai_skill_auto_enabled",];const NON_SYNCABLE_DESKTOP_SETTINGS: &[&str] = &["debug_logging_enabled"];const NON_SYNCABLE_EDITOR_SETTINGS: &[&str] = &[@@ -954,6 +958,7 @@ fn syncable_desktop_settings(mut settings: DesktopSettings) -> DesktopSettings {settings.agent_store_dir = None;settings.custom_ai_skill_root_enabled = false;settings.custom_ai_skill_root = None;+ settings.custom_ai_skill_auto_enabled = false;settings.debug_logging_enabled = false;settings}diff --git a/crates/dbx-core/src/persistence/storage.rs b/crates/dbx-core/src/persistence/storage.rsindex 25e3af6d4b..ceb08a4e33 100644--- a/crates/dbx-core/src/persistence/storage.rs+++ b/crates/dbx-core/src/persistence/storage.rs@@ -445,6 +445,13 @@ pub struct DesktopSettings {pub custom_ai_skill_root_enabled: bool,#[serde(default)]pub custom_ai_skill_root: Option<String>,+ /// "Allow the AI to use skills automatically" (prd 09-30 Req 5). When on,+ /// the built-in AI receives the skill listing even with nothing selected, so+ /// the model can pick a skill up on its own. Off by default: a listing costs+ /// prompt tokens on every request, and the user's selection stays the+ /// explicit gate.+ #[serde(default)]+ pub custom_ai_skill_auto_enabled: bool,#[serde(default = "default_sidebar_table_page_size")]pub sidebar_table_page_size: usize,}@@ -970,6 +977,7 @@ impl Default for DesktopSettings {agent_store_dir: None,custom_ai_skill_root_enabled: false,custom_ai_skill_root: None,+ custom_ai_skill_auto_enabled: false,sidebar_table_page_size: default_sidebar_table_page_size(),}}@@ -4834,6 +4842,10 @@ impl Storage {settings.remove("custom_ai_skill_root");}}+ settings.insert(+ "custom_ai_skill_auto_enabled".to_string(),+ serde_json::Value::Bool(desktop_settings.custom_ai_skill_auto_enabled),+ );settings.insert("sidebar_table_page_size".to_string(),serde_json::Value::Number(serde_json::Number::from(desktop_settings.sidebar_table_page_size)),@@ -4912,6 +4924,10 @@ impl Storage {.map(str::trim).filter(|value| !value.is_empty()).map(ToString::to_string),+ custom_ai_skill_auto_enabled: settings+ .get("custom_ai_skill_auto_enabled")+ .and_then(|value| value.as_bool())+ .unwrap_or_else(|| DesktopSettings::default().custom_ai_skill_auto_enabled),sidebar_table_page_size: settings.get("sidebar_table_page_size").and_then(|value| value.as_u64())@@ -9794,6 +9810,7 @@ mod tests {covered_messages: None,source_binding: None,selections_omitted: None,+ loaded_skill_ids: None,}],queued_input: None,created_at: updated_at.to_string(),@@ -10137,6 +10154,36 @@ mod tests {let _ = std::fs::remove_file(path);}+ // prd 09-30 Req 13: a conversation keeps the FACT that skills were loaded so+ // the panel can light its chips after a restart. The body itself is+ // deliberately not part of the record — see the field comment in+ // `dbx-ai-provider`. This pins both halves: the ids round-trip, and a record+ // written before the field existed still loads.+ #[tokio::test]+ async fn ai_conversation_roundtrips_loaded_skill_ids() {+ let path = temp_db_path("ai-conversation-loaded-skills");+ let storage = crate::persistence::test_storage::open(&path).await.unwrap();++ let mut conversation = ai_conversation("skills-conv", "0000");+ conversation.messages[0].loaded_skill_ids = Some(vec!["d-abc".to_string(), "c-def".to_string()]);+ storage.save_ai_conversation(&conversation).await.unwrap();++ let loaded = storage.load_ai_conversations().await.unwrap();+ assert_eq!(+ loaded[0].messages[0].loaded_skill_ids.as_deref(),+ Some(["d-abc".to_string(), "c-def".to_string()].as_slice())+ );+ // No body: the stored message is exactly the id list.+ let stored = serde_json::to_value(&loaded[0].messages[0]).unwrap();+ assert!(stored.get("loadedSkillIds").and_then(|value| value.as_array()).is_some());+ assert!(stored.get("toolCalls").is_none());++ let legacy: AiChatMessage = serde_json::from_str(r#"{"role":"assistant","content":"old turn"}"#).unwrap();+ assert!(legacy.loaded_skill_ids.is_none());++ let _ = std::fs::remove_file(path);+ }+#[tokio::test]async fn ai_conversation_upgrades_legacy_schema_and_binds_a_unique_connection() {let path = temp_db_path("ai-conversation-legacy-binding");@@ -12294,6 +12341,7 @@ mod tests {agent_store_dir: Some("/tmp/dbx-agents".to_string()),custom_ai_skill_root_enabled: DesktopSettings::default().custom_ai_skill_root_enabled,custom_ai_skill_root: None,+ custom_ai_skill_auto_enabled: DesktopSettings::default().custom_ai_skill_auto_enabled,sidebar_table_page_size: DesktopSettings::default().sidebar_table_page_size,}).await@@ -12317,6 +12365,7 @@ mod tests {agent_store_dir: Some("/tmp/dbx-agents".to_string()),custom_ai_skill_root_enabled: DesktopSettings::default().custom_ai_skill_root_enabled,custom_ai_skill_root: None,+ custom_ai_skill_auto_enabled: DesktopSettings::default().custom_ai_skill_auto_enabled,sidebar_table_page_size: DesktopSettings::default().sidebar_table_page_size,});@@ -12362,6 +12411,42 @@ mod tests {assert_eq!(raw.get("custom_ai_skill_root"), None);}+ /// Req 5's toggle defaults off, so a database written before it existed (the+ /// key absent) must load as off rather than as "unset means on".+ #[tokio::test]+ async fn desktop_settings_roundtrip_custom_ai_skill_auto_enabled() {+ let path = temp_db_path("desktop-settings-custom-ai-skill-auto");+ let storage = crate::persistence::test_storage::open(&path).await.unwrap();++ assert!(!storage.load_desktop_settings().await.unwrap().custom_ai_skill_auto_enabled);++ storage+ .save_desktop_settings(&DesktopSettings {+ custom_ai_skill_auto_enabled: true,+ ..DesktopSettings::default()+ })+ .await+ .unwrap();++ assert!(storage.load_desktop_settings().await.unwrap().custom_ai_skill_auto_enabled);+ let raw = storage.load_app_settings_json().await.unwrap();+ assert_eq!(raw.get("custom_ai_skill_auto_enabled").and_then(|value| value.as_bool()), Some(true));++ storage+ .save_desktop_settings(&DesktopSettings {+ custom_ai_skill_auto_enabled: false,+ ..DesktopSettings::default()+ })+ .await+ .unwrap();+ assert!(!storage.load_desktop_settings().await.unwrap().custom_ai_skill_auto_enabled);++ // An explicit `false` is written through (not removed), which is what+ // keeps a synced record distinguishable from "never configured".+ let raw = storage.load_app_settings_json().await.unwrap();+ assert_eq!(raw.get("custom_ai_skill_auto_enabled").and_then(|value| value.as_bool()), Some(false));+ }+#[tokio::test]async fn desktop_settings_save_removes_legacy_background_preference() {let path = temp_db_path("desktop-settings-remove-legacy-background");diff --git a/crates/dbx-core/src/skills/mod.rs b/crates/dbx-core/src/skills/mod.rsnew file mode 100644index 0000000000..fdd81a75c5--- /dev/null+++ b/crates/dbx-core/src/skills/mod.rs@@ -0,0 +1,1239 @@+//! Read-only discovery and reading of user-level SKILL.md skills.+//!+//! Two roots are scanned: the default user-level root (HOME/.agents/skills) and+//! an optional user-configured custom root (Settings > AI). The service is+//! strictly read-only: there is no create/write/delete API. Skills are+//! identified by deterministic opaque ids derived from the root source and the+//! canonical relative skill directory name, so ids survive Refresh (prd.md:34).+//! Absolute paths never leave this module (prd.md:33).+//!+//! Lives in `dbx-core` rather than beside the Tauri commands because the AI+//! agent loop needs the same discovery and path-boundary logic+//! (prd 09-30-skill-listing-use-skill). `src-tauri/src/commands/user_skills.rs`+//! is a thin adapter over [`list_skills`] / [`read_skills`]; there must be+//! exactly one implementation of the containment rules, since a second copy is+//! a second place for a symlink escape to be missed.++use std::collections::HashSet;+use std::io::Read;+use std::path::{Path, PathBuf};++use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};++pub const SKILL_FILE_NAME: &str = "SKILL.md";+/// Hard per-file safety limit: a larger SKILL.md is invalid and omitted from+/// discovery, and blocks the send when selected (prd.md:26/:37).+pub const MAX_SKILL_FILE_BYTES: u64 = 1_048_576;+/// Send-time reads take at most 1 MiB + 1 byte so a file that grows after the+/// metadata check is rejected instead of loaded unboundedly (prd.md:38).+const READ_LIMIT_BYTES: u64 = MAX_SKILL_FILE_BYTES + 1;+/// The opening frontmatter block must close within the first 64 KiB.+const FRONTMATTER_SCAN_BYTES: usize = 64 * 1024;++const DEFAULT_ROOT_PREFIX: &str = "d";+const CUSTOM_ROOT_PREFIX: &str = "c";++const ROOT_STATUS_OK: &str = "ok";+const ROOT_STATUS_MISSING: &str = "missing";+const ROOT_STATUS_INVALID: &str = "invalid";++/// Bounded failure vocabulary. Underlying I/O detail (which can contain+/// absolute paths or OS-specific text) is deliberately discarded rather than+/// forwarded, so nothing path-shaped reaches the frontend (prd.md:33).+const REASON_NOT_FOUND: &str = "not_found";+const REASON_ROOT_UNAVAILABLE: &str = "root_unavailable";+const REASON_OVERSIZED: &str = "oversized";+const REASON_NOT_UTF8: &str = "not_utf8";+const REASON_INVALID_FRONTMATTER: &str = "invalid_frontmatter";+const REASON_UNREADABLE: &str = "unreadable";++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct UserSkillMeta {+ pub id: String,+ pub name: String,+ pub description: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct UserSkillRootListing {+ /// One of "ok" | "missing" | "invalid".+ pub status: String,+ pub skills: Vec<UserSkillMeta>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct UserSkillsListResult {+ pub default_root: UserSkillRootListing,+ pub custom_root: Option<UserSkillRootListing>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ReadUserSkill {+ pub id: String,+ pub name: String,+ pub description: String,+ pub content: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ReadUserSkillFailure {+ pub id: String,+ /// One of "not_found" | "root_unavailable" | "oversized" | "not_utf8" | "invalid_frontmatter" | "unreadable".+ pub reason: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct UserSkillsReadResult {+ pub skills: Vec<ReadUserSkill>,+ pub failures: Vec<ReadUserSkillFailure>,+}++/// Lists skill metadata for both roots. The default root is always scanned;+/// the custom root only when it is enabled in Settings (prd.md:27). An absent+/// root yields an empty listing rather than an error (prd.md:35).+///+/// Blocking filesystem work: callers offload it to a blocking pool.+pub fn list_skills(custom_root_enabled: bool, custom_root: Option<&str>) -> UserSkillsListResult {+ let default_root = match default_skills_root() {+ Some(path) => root_listing(&path, DEFAULT_ROOT_PREFIX),+ None => empty_listing(ROOT_STATUS_MISSING),+ };+ let custom_root = if custom_root_enabled {+ enabled_custom_root(custom_root).map(|path| root_listing(&path, CUSTOM_ROOT_PREFIX))+ } else {+ None+ };+ UserSkillsListResult { default_root, custom_root }+}++/// Reads the currently selected skills by id. Every id is resolved only+/// through re-derivation over a fresh scan of the owning root, so a deleted,+/// moved, or root-escaping skill fails instead of silently resolving to a+/// stale path (prd.md:37).+///+/// Blocking filesystem work: callers offload it to a blocking pool.+pub fn read_skills(ids: &[String], custom_root_enabled: bool, custom_root: Option<&str>) -> UserSkillsReadResult {+ let roots = SkillRoots::resolve(custom_root_enabled, custom_root);+ read_user_skills_from(ids, roots.default.as_deref(), roots.custom.as_deref())+}++/// Root resolution is injected so tests can exercise both roots without+/// depending on the developer home directory.+fn read_user_skills_from(+ ids: &[String],+ default_root: Option<&Path>,+ custom_root: Option<&Path>,+) -> UserSkillsReadResult {+ let mut skills = Vec::new();+ let mut failures = Vec::new();+ let mut seen_ids: HashSet<&str> = HashSet::new();+ for id in ids {+ // A repeated id must not inject the same skill text twice.+ if !seen_ids.insert(id.as_str()) {+ continue;+ }+ let prefix = match id.split_once('-') {+ Some((prefix, _)) if prefix == DEFAULT_ROOT_PREFIX || prefix == CUSTOM_ROOT_PREFIX => prefix,+ _ => {+ failures.push(ReadUserSkillFailure { id: id.clone(), reason: REASON_NOT_FOUND.to_string() });+ continue;+ }+ };+ let root = match prefix {+ DEFAULT_ROOT_PREFIX => default_root,+ _ => custom_root,+ };+ let Some(root) = root else {+ failures.push(ReadUserSkillFailure { id: id.clone(), reason: REASON_ROOT_UNAVAILABLE.to_string() });+ continue;+ };+ match read_skill_from_root(root, prefix, id) {+ Ok(skill) => skills.push(skill),+ Err(reason) => failures.push(ReadUserSkillFailure { id: id.clone(), reason }),+ }+ }+ UserSkillsReadResult { skills, failures }+}++fn enabled_custom_root(custom_root: Option<&str>) -> Option<PathBuf> {+ let trimmed = custom_root.map(str::trim).filter(|value| !value.is_empty())?;+ let canonical = std::fs::canonicalize(trimmed).ok()?;+ canonical.is_dir().then_some(canonical)+}++fn default_skills_root() -> Option<PathBuf> {+ Some(home_dir()?.join(".agents").join("skills"))+}++fn home_dir() -> Option<PathBuf> {+ std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).ok().map(PathBuf::from)+}++fn empty_listing(status: &str) -> UserSkillRootListing {+ UserSkillRootListing { status: status.to_string(), skills: Vec::new() }+}++fn root_listing(path: &Path, prefix: &str) -> UserSkillRootListing {+ match std::fs::canonicalize(path) {+ Ok(canonical) if canonical.is_dir() => {+ UserSkillRootListing { status: ROOT_STATUS_OK.to_string(), skills: scan_root(&canonical, prefix) }+ }+ Ok(_) => empty_listing(ROOT_STATUS_INVALID),+ Err(_) => empty_listing(ROOT_STATUS_MISSING),+ }+}++/// Scans the direct children of a canonical root. Symlink policy (prd.md:40):+/// an entry is only discoverable when its canonical target stays inside the+/// root, so a symlink that escapes the root is invisible to discovery.+///+/// The containment rules themselves live in [`scan_root_entries`]; this is only+/// the id-projection plus the listing order.+fn scan_root(canonical_root: &Path, prefix: &str) -> Vec<UserSkillMeta> {+ let mut skills: Vec<UserSkillMeta> = scan_root_entries(canonical_root)+ .into_iter()+ .map(|entry| UserSkillMeta {+ id: skill_id(prefix, &entry.dir_name),+ name: entry.name,+ description: entry.description,+ })+ .collect();+ skills.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.id.cmp(&b.id)));+ skills+}++/// Listing reads only the head of the file: the size gate plus a bounded+/// prefix read are enough to parse the opening frontmatter block+/// (prd.md:26 - "parse their frontmatter according to the public convention").+/// The body is never read here (prd.md:56).+fn discover_skill_metadata(path: &Path) -> Option<(String, String)> {+ let stat = std::fs::metadata(path).ok()?;+ if !stat.is_file() || stat.len() > MAX_SKILL_FILE_BYTES {+ return None;+ }+ let file = std::fs::File::open(path).ok()?;+ let mut bytes = Vec::new();+ file.take(FRONTMATTER_SCAN_BYTES as u64).read_to_end(&mut bytes).ok()?;+ parse_frontmatter(decode_prefix(&bytes, stat.len())?)+}++/// Decodes the bounded listing prefix strictly, so an unreadable file is not+/// offered as a choice (it would always fail at send time). A multi-byte+/// character cut by the prefix read is not an encoding error: when the file+/// continues past the prefix, the trailing partial character is trimmed. The+/// bytes beyond the prefix stay unvalidated here and are checked at send time.+fn decode_prefix(bytes: &[u8], file_len: u64) -> Option<&str> {+ match std::str::from_utf8(bytes) {+ Ok(text) => Some(text),+ Err(error) if error.error_len().is_none() && file_len > bytes.len() as u64 => {+ std::str::from_utf8(&bytes[..error.valid_up_to()]).ok()+ }+ Err(_) => None,+ }+}++/// Reads and fully validates one selected skill file. The metadata size check+/// is followed by a 1 MiB + 1 byte bounded read, so a file that grows between+/// the two is rejected as oversized instead of loaded unboundedly (prd.md:38).+fn read_skill_from_root(canonical_root: &Path, prefix: &str, id: &str) -> Result<ReadUserSkill, String> {+ for entry in contained_skill_dirs(canonical_root) {+ if skill_id(prefix, &entry.dir_name) != id {+ continue;+ }+ let resolved = read_contained_skill(canonical_root, prefix, &entry.dir_name, &entry.dir)?;+ return Ok(ReadUserSkill {+ id: resolved.id,+ name: resolved.name,+ description: resolved.description,+ content: resolved.content,+ });+ }+ Err(REASON_NOT_FOUND.to_string())+}++fn read_skill_file(path: &Path, id: &str) -> Result<ReadUserSkill, String> {+ let stat = std::fs::metadata(path).map_err(|_| REASON_NOT_FOUND.to_string())?;+ if !stat.is_file() {+ return Err(REASON_NOT_FOUND.to_string());+ }+ if stat.len() > MAX_SKILL_FILE_BYTES {+ return Err(REASON_OVERSIZED.to_string());+ }+ let file = std::fs::File::open(path).map_err(|_| REASON_UNREADABLE.to_string())?;+ let mut bytes = Vec::new();+ file.take(READ_LIMIT_BYTES).read_to_end(&mut bytes).map_err(|_| REASON_UNREADABLE.to_string())?;+ if bytes.len() as u64 > MAX_SKILL_FILE_BYTES {+ return Err(REASON_OVERSIZED.to_string());+ }+ let text = String::from_utf8(bytes).map_err(|_| REASON_NOT_UTF8.to_string())?;+ let (name, description) = parse_frontmatter(&text).ok_or_else(|| REASON_INVALID_FRONTMATTER.to_string())?;+ Ok(ReadUserSkill { id: id.to_string(), name, description, content: text })+}++/// Deterministic opaque id: root source prefix plus a truncated SHA-256 of the+/// canonical relative skill directory name. Stable across Refresh and restarts+/// of the registry (prd.md:34). The id carries no path material to the client.+fn skill_id(prefix: &str, dir_name: &str) -> String {+ let digest = Sha256::digest(dir_name.as_bytes());+ let mut id = String::from(prefix);+ id.push('-');+ for byte in &digest[..8] {+ id.push_str(&format!("{:02x}", byte));+ }+ id+}++/// Parses the opening YAML frontmatter block per the public SKILL.md+/// convention: required non-empty name and description, unknown keys ignored.+/// Returns None when the block is missing, unclosed, oversized, or lacks a+/// required field (prd.md:26/:52).+fn parse_frontmatter(text: &str) -> Option<(String, String)> {+ let text = text.strip_prefix("\u{feff}").unwrap_or(text);+ let mut lines = text.lines();+ if lines.next()?.trim_end() != "---" {+ return None;+ }+ let mut block = String::new();+ let mut closed = false;+ for line in lines {+ if line.trim_end() == "---" {+ closed = true;+ break;+ }+ block.push_str(line);+ block.push('\n');+ if block.len() > FRONTMATTER_SCAN_BYTES {+ return None;+ }+ }+ if !closed {+ return None;+ }+ let frontmatter: SkillFrontmatter = serde_yaml_ng::from_str(&block).ok()?;+ let name = frontmatter.name?.trim().to_string();+ let description = frontmatter.description?.trim().to_string();+ if name.is_empty() || description.is_empty() {+ return None;+ }+ Some((name, description))+}++#[derive(Debug, Deserialize)]+struct SkillFrontmatter {+ #[serde(default)]+ name: Option<String>,+ #[serde(default)]+ description: Option<String>,+}++// ── Roots, name resolution and referencing files ──────────────────────────+//+// Added for the AI agent's `use_skill` / `read_skill_file` tools+// (prd 09-30-skill-listing-use-skill, Requirements 8-11b). Two rules hold for+// everything below:+// * the boundary is the CANONICALIZED SKILL DIRECTORY, not the root prefix,+// and it is re-validated on every read — a check done only at scan time+// leaks the first time a path is swapped underneath us;+// * no absolute path may leave this module. The agent sees relative paths.++/// Source label used in the listing and the tool arguments. Deliberately the+/// words the prompt shows (`[default]` / `[custom]`), so the model can pass back+/// exactly what it read.+const SOURCE_DEFAULT: &str = "default";+const SOURCE_CUSTOM: &str = "custom";++/// The referencing-file listing is bounded in both directions: a skill may ship+/// hundreds of files (measured: up to 60+ on this machine), and an unbounded+/// listing would spend the tool result on paths.+pub const SKILL_LISTING_MAX_ENTRIES: usize = 50;+pub const SKILL_LISTING_MAX_DEPTH: usize = 4;+/// Binary classification sniffs a prefix rather than reading the file twice.+const BINARY_SNIFF_BYTES: usize = 8 * 1024;+/// Directories that only ever hold build output or vendored dependencies.+const SKIPPED_DIR_NAMES: &[&str] = &["node_modules", "target", "dist", "build", "__pycache__", "venv"];++const REASON_NOT_TEXT: &str = "not_text";++fn source_label(prefix: &str) -> &'static str {+ if prefix == CUSTOM_ROOT_PREFIX {+ SOURCE_CUSTOM+ } else {+ SOURCE_DEFAULT+ }+}++/// Canonicalized skill roots. The agent tools resolve roots here instead of+/// accepting a path from the caller, so every containment check below has one+/// trusted origin.+pub struct SkillRoots {+ pub default: Option<PathBuf>,+ pub custom: Option<PathBuf>,+}++impl SkillRoots {+ pub fn resolve(custom_root_enabled: bool, custom_root: Option<&str>) -> Self {+ let default =+ default_skills_root().and_then(|path| std::fs::canonicalize(&path).ok()).filter(|path| path.is_dir());+ let custom = if custom_root_enabled { enabled_custom_root(custom_root) } else { None };+ Self { default, custom }+ }++ fn iter(&self) -> impl Iterator<Item = (&'static str, &Path)> {+ [(DEFAULT_ROOT_PREFIX, self.default.as_deref()), (CUSTOM_ROOT_PREFIX, self.custom.as_deref())]+ .into_iter()+ .filter_map(|(prefix, root)| root.map(|root| (prefix, root)))+ }+}++/// One discoverable skill, with the directory the tools need. Kept private: the+/// directory must not escape, so callers get [`ResolvedSkill`] instead.+struct ScannedSkill {+ dir_name: String,+ name: String,+ description: String,+ dir: PathBuf,+}++/// A skill the model asked for by name, already read in full.+pub struct ResolvedSkill {+ pub id: String,+ pub name: String,+ pub description: String,+ pub content: String,+ pub source: &'static str,+ /// Canonical skill directory. Stays inside this module (Requirement 11).+ pub dir: PathBuf,+}++/// One candidate of an ambiguous name, shown back to the model so it can retry+/// with a `source` instead of the tool guessing between two real skills.+pub struct SkillCandidate {+ pub name: String,+ pub source: &'static str,+ pub description: String,+}++pub enum SkillLookup {+ Found(Box<ResolvedSkill>),+ Ambiguous(Vec<SkillCandidate>),+ NotFound,+}++/// One directory under a canonical root that obeys the symlink policy. This is+/// the *only* implementation of the containment rules — the discovery scan, the+/// id read and the name read all start here, so a policy fix cannot land in one+/// path and miss another.+struct ContainedSkillDir {+ dir_name: String,+ dir: PathBuf,+}++fn contained_skill_dirs(canonical_root: &Path) -> Vec<ContainedSkillDir> {+ let mut found = Vec::new();+ let Ok(entries) = std::fs::read_dir(canonical_root) else { return found };+ for entry in entries.flatten() {+ let dir_name = entry.file_name().to_string_lossy().to_string();+ if dir_name.starts_with('.') {+ continue;+ }+ let Ok(canonical_dir) = entry.path().canonicalize() else { continue };+ if !canonical_dir.starts_with(canonical_root) || !canonical_dir.is_dir() {+ continue;+ }+ let skill_file = canonical_dir.join(SKILL_FILE_NAME);+ let Ok(canonical_skill_file) = skill_file.canonicalize() else { continue };+ // A skill directory may be linked within the allowed root, but its+ // entry file must obey the same containment rule. Otherwise a normal+ // directory could hide a SKILL.md symlink to an arbitrary local file.+ if !canonical_skill_file.starts_with(canonical_root) {+ continue;+ }+ found.push(ContainedSkillDir { dir_name, dir: canonical_dir });+ }+ found+}++/// The *discoverable* skills: contained directories whose SKILL.md yields usable+/// frontmatter metadata. Discovery is deliberately NOT part of the read path —+/// see [`read_contained_skill`] — so a file that fails discovery still reports+/// its own reason (`not_utf8`, `oversized`) when read by id, which is what the+/// frozen reason vocabulary and its user-facing copy promise.+fn scan_root_entries(canonical_root: &Path) -> Vec<ScannedSkill> {+ let mut found = Vec::new();+ for ContainedSkillDir { dir_name, dir } in contained_skill_dirs(canonical_root) {+ let Some((name, description)) = discover_skill_metadata(&dir.join(SKILL_FILE_NAME)) else { continue };+ found.push(ScannedSkill { dir_name, name, description, dir });+ }+ found+}++/// Reads one contained skill directory, re-validating its entry file against the+/// root at read time. The scan-time verdict can be stale by the time a send or a+/// tool call arrives (another process may have swapped SKILL.md for an escaping+/// symlink), and the boundary is the canonical skill directory — not the root+/// prefix — so the check is against the root the entry actually came from.+///+/// Takes the directory rather than a discovered entry on purpose: the read path+/// must not inherit discovery's gate, or a file that failed discovery would be+/// reported as `not_found` instead of its real reason.+fn read_contained_skill(+ canonical_root: &Path,+ prefix: &str,+ dir_name: &str,+ dir: &Path,+) -> Result<ResolvedSkill, String> {+ let id = skill_id(prefix, dir_name);+ let canonical_skill_file = dir.join(SKILL_FILE_NAME).canonicalize().map_err(|_| REASON_NOT_FOUND.to_string())?;+ if !canonical_skill_file.starts_with(canonical_root) {+ return Err(REASON_NOT_FOUND.to_string());+ }+ let skill = read_skill_file(&canonical_skill_file, &id)?;+ Ok(ResolvedSkill {+ id,+ name: skill.name,+ description: skill.description,+ content: skill.content,+ source: source_label(prefix),+ dir: dir.to_path_buf(),+ })+}++/// Resolves a skill by the name the listing showed the model.+///+/// Matching is exact on purpose: the listing prints the frontmatter name+/// verbatim, and a fuzzy matcher would turn "did you mean" into a silent wrong+/// skill. `source` disambiguates the genuinely common case of one name living in+/// both roots; when the name is still ambiguous the caller gets the candidates+/// rather than a coin flip (Requirement 8).+pub fn read_skill_by_name(name: &str, source: Option<&str>, roots: &SkillRoots) -> SkillLookup {+ let wanted = name.trim();+ if wanted.is_empty() {+ return SkillLookup::NotFound;+ }+ let mut matches: Vec<(&'static str, PathBuf, ScannedSkill)> = Vec::new();+ for (prefix, root) in roots.iter() {+ if source.is_some_and(|source| source != source_label(prefix)) {+ continue;+ }+ for entry in scan_root_entries(root) {+ if entry.name == wanted {+ matches.push((prefix, root.to_path_buf(), entry));+ }+ }+ }+ match matches.len() {+ 0 => SkillLookup::NotFound,+ 1 => {+ let (prefix, root, entry) = matches.remove(0);+ // A skill that passed discovery can still fail the read-time gate+ // (oversized after growth, encoding, vanished). Reported as+ // not-found so no absolute path reaches the model.+ match read_contained_skill(&root, prefix, &entry.dir_name, &entry.dir) {+ Ok(skill) => SkillLookup::Found(Box::new(skill)),+ Err(_) => SkillLookup::NotFound,+ }+ }+ _ => SkillLookup::Ambiguous(+ matches+ .into_iter()+ .map(|(prefix, _root, entry)| SkillCandidate {+ name: entry.name,+ source: source_label(prefix),+ description: entry.description,+ })+ .collect(),+ ),+ }+}++/// Every discoverable skill as name + source + description, in root order+/// (default, then custom) and name order inside a root. The recovery answer of a+/// failed name lookup prints the names and sources from here, and nothing else:+/// the agent must never see a path.+pub fn list_skill_candidates(roots: &SkillRoots) -> Vec<SkillCandidate> {+ let mut candidates = Vec::new();+ for (prefix, root) in roots.iter() {+ candidates.extend(scan_root_entries(root).into_iter().map(|entry| SkillCandidate {+ name: entry.name,+ source: source_label(prefix),+ description: entry.description,+ }));+ }+ candidates+}++/// One entry of a skill's referencing-file listing. `bytes` and `text` are what+/// let the model decide whether reading the file is worth a second tool call.+pub struct SkillFileEntry {+ pub relative_path: String,+ pub bytes: u64,+ pub text: bool,+}++pub struct SkillFileListing {+ pub entries: Vec<SkillFileEntry>,+ pub truncated: bool,+}++/// A bounded, character-addressed slice of a skill file.+pub struct SkillFileChunk {+ pub content: String,+ pub total_chars: usize,+ pub next_offset: Option<usize>,+}++fn is_binary_prefix(bytes: &[u8]) -> bool {+ bytes.contains(&0)+}++fn sniff_is_text(path: &Path) -> bool {+ let Ok(file) = std::fs::File::open(path) else { return true };+ let mut prefix = Vec::new();+ if file.take(BINARY_SNIFF_BYTES as u64).read_to_end(&mut prefix).is_err() {+ return true;+ }+ !is_binary_prefix(&prefix)+}++/// Lists the files a skill ships beside its SKILL.md, relative to the skill+/// directory, skipping hidden entries and build/vendor directories. Both the+/// depth and the entry count are capped; `truncated` tells the caller to say so+/// rather than present a partial listing as complete.+pub fn list_skill_files(canonical_dir: &Path) -> SkillFileListing {+ let mut entries = Vec::new();+ let mut truncated = false;+ let mut stack = vec![(canonical_dir.to_path_buf(), 0usize)];+ 'outer: while let Some((current, depth)) = stack.pop() {+ if depth > SKILL_LISTING_MAX_DEPTH {+ continue;+ }+ let Ok(read) = std::fs::read_dir(¤t) else { continue };+ let mut children: Vec<_> = read.flatten().collect();+ children.sort_by_key(|entry| entry.file_name());+ for entry in children {+ let name = entry.file_name().to_string_lossy().to_string();+ if name.starts_with('.') || SKIPPED_DIR_NAMES.contains(&name.as_str()) {+ continue;+ }+ let Ok(canonical) = entry.path().canonicalize() else { continue };+ // Same boundary as the scan: a link that leaves the skill directory+ // is invisible, so the listing cannot advertise an outside path.+ if !canonical.starts_with(canonical_dir) {+ continue;+ }+ let Ok(metadata) = std::fs::metadata(&canonical) else { continue };+ if metadata.is_dir() {+ stack.push((canonical, depth + 1));+ continue;+ }+ if !metadata.is_file() {+ continue;+ }+ if entries.len() >= SKILL_LISTING_MAX_ENTRIES {+ truncated = true;+ break 'outer;+ }+ let Ok(relative) = canonical.strip_prefix(canonical_dir) else { continue };+ entries.push(SkillFileEntry {+ relative_path: relative.to_string_lossy().replace('\\', "/"),+ bytes: metadata.len(),+ text: sniff_is_text(&canonical),+ });+ }+ }+ entries.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));+ SkillFileListing { entries, truncated }+}++/// Reads one referencing file inside a skill directory.+///+/// Every rejection is a bounded reason, never an OS error string: those carry+/// absolute paths. `..` and absolute inputs are refused outright rather than+/// left to the containment check, so the intent is explicit and the reason+/// stable. A file containing a NUL byte is classified as binary and refused as+/// `not_text` (Requirement 11a) — reading a file is not permission to run it,+/// and the tool description says so.+pub fn read_skill_file_relative(canonical_dir: &Path, relative: &str) -> Result<String, String> {+ let trimmed = relative.trim();+ if trimmed.is_empty() {+ return Err(REASON_NOT_FOUND.to_string());+ }+ let requested = Path::new(trimmed);+ if requested.is_absolute() || trimmed.split(['/', '\\']).any(|segment| segment == "..") {+ return Err(REASON_NOT_FOUND.to_string());+ }+ let canonical = canonical_dir.join(requested).canonicalize().map_err(|_| REASON_NOT_FOUND.to_string())?;+ if !canonical.starts_with(canonical_dir) {+ return Err(REASON_NOT_FOUND.to_string());+ }+ let stat = std::fs::metadata(&canonical).map_err(|_| REASON_NOT_FOUND.to_string())?;+ if !stat.is_file() {+ return Err(REASON_NOT_FOUND.to_string());+ }+ if stat.len() > MAX_SKILL_FILE_BYTES {+ return Err(REASON_OVERSIZED.to_string());+ }+ let file = std::fs::File::open(&canonical).map_err(|_| REASON_UNREADABLE.to_string())?;+ let mut bytes = Vec::new();+ file.take(READ_LIMIT_BYTES).read_to_end(&mut bytes).map_err(|_| REASON_UNREADABLE.to_string())?;+ if bytes.len() as u64 > MAX_SKILL_FILE_BYTES {+ return Err(REASON_OVERSIZED.to_string());+ }+ // NUL is valid UTF-8, so this must run before the decode to be reachable.+ if is_binary_prefix(&bytes) {+ return Err(REASON_NOT_TEXT.to_string());+ }+ String::from_utf8(bytes).map_err(|_| REASON_NOT_UTF8.to_string())+}++/// Reads a bounded slice after applying all normal containment and file checks.+pub fn read_skill_file_relative_chunk(+ canonical_dir: &Path,+ relative: &str,+ offset: usize,+ limit: usize,+) -> Result<SkillFileChunk, String> {+ // A zero limit would yield an empty chunk whose cursor never advances, so a+ // caller following `next_offset` would loop forever. Treat it as one instead of+ // answering `not_found`, which would blame the file for an argument. The tool+ // layer rejects 0 outright with a message the model can act on, so this only+ // covers direct callers.+ let limit = limit.max(1);+ let content = read_skill_file_relative(canonical_dir, relative)?;+ let total_chars = content.chars().count();+ let chunk: String = content.chars().skip(offset).take(limit).collect();+ let consumed = offset.saturating_add(chunk.chars().count());+ let next_offset = (consumed < total_chars).then_some(consumed);+ Ok(SkillFileChunk { content: chunk, total_chars, next_offset })+}++#[cfg(test)]+mod tests {+ use super::*;++ const VALID_BODY: &str = "---\nname: sql-review\ndescription: Team SQL review rules\n---\n\nFollow the rules.\n";++ fn temp_skills_root(tag: &str) -> PathBuf {+ let root = std::env::temp_dir().join(format!("dbx-user-skills-{tag}-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&root).unwrap();+ root+ }++ fn write_skill(root: &Path, dir: &str, body: &str) -> PathBuf {+ let dir = root.join(dir);+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join(SKILL_FILE_NAME), body).unwrap();+ dir+ }++ fn set_file_len(skill_dir: &Path, len: u64) {+ let file = std::fs::OpenOptions::new().write(true).open(skill_dir.join(SKILL_FILE_NAME)).unwrap();+ file.set_len(len).unwrap();+ }++ #[test]+ fn parses_frontmatter_and_ignores_extra_keys() {+ let (name, description) =+ parse_frontmatter("---\nname: \"sql-review\"\ndescription: Team rules\nmetadata:\n short: x\nallowed-tools: [read]\n---\n\nBody.\n").unwrap();+ assert_eq!(name, "sql-review");+ assert_eq!(description, "Team rules");+ }++ #[test]+ fn frontmatter_must_open_and_close_at_the_top() {+ assert!(parse_frontmatter("name: x\ndescription: y\n").is_none());+ assert!(parse_frontmatter("---\nname: x\ndescription: y\n").is_none());+ assert!(parse_frontmatter("body first\n---\nname: x\ndescription: y\n---\n").is_none());+ }++ #[test]+ fn frontmatter_requires_name_and_description() {+ assert!(parse_frontmatter("---\ndescription: only desc\n---\n").is_none());+ assert!(parse_frontmatter("---\nname: only name\n---\n").is_none());+ assert!(parse_frontmatter("---\nname:\ndescription: y\n---\n").is_none());+ assert!(parse_frontmatter("---\nname: x\ndescription: \n---\n").is_none());+ }++ #[test]+ fn skill_ids_are_deterministic_and_root_scoped() {+ assert_eq!(skill_id("d", "alpha"), skill_id("d", "alpha"));+ assert_ne!(skill_id("d", "alpha"), skill_id("c", "alpha"));+ assert_ne!(skill_id("d", "alpha"), skill_id("d", "beta"));+ assert!(skill_id("d", "alpha").starts_with("d-"));+ assert_eq!(skill_id("d", "alpha").len(), 18);+ }++ #[test]+ fn scan_lists_valid_skills_and_omits_others() {+ let root = temp_skills_root("scan");+ write_skill(&root, "alpha", VALID_BODY);+ write_skill(&root, "zulu", VALID_BODY);+ write_skill(&root, "nodesc", "---\nname: nodesc\n---\nbody\n");+ write_skill(&root, ".hidden", VALID_BODY);+ let nested = root.join("nested");+ std::fs::create_dir_all(nested.join("deep")).unwrap();+ std::fs::write(nested.join("deep").join(SKILL_FILE_NAME), VALID_BODY).unwrap();+ let oversized = write_skill(&root, "oversized", VALID_BODY);+ set_file_len(&oversized, MAX_SKILL_FILE_BYTES + 1);+ let canonical = std::fs::canonicalize(&root).unwrap();+ let skills = scan_root(&canonical, "d");+ let names: Vec<String> = skills.iter().map(|skill| skill.name.clone()).collect();+ assert_eq!(names, vec!["sql-review", "sql-review"]);+ assert_ne!(skills[0].id, skills[1].id);+ assert!(skills.iter().all(|skill| skill.id.starts_with("d-")));+ }++ #[test]+ fn root_listing_reports_missing_and_invalid() {+ let root = temp_skills_root("listing");+ write_skill(&root, "alpha", VALID_BODY);+ let missing = root_listing(&root.join("does-not-exist"), "d");+ assert_eq!(missing.status, "missing");+ assert!(missing.skills.is_empty());+ let file_marker = root.join("plain-file.txt");+ std::fs::write(&file_marker, "x").unwrap();+ assert_eq!(root_listing(&file_marker, "d").status, "invalid");+ assert_eq!(root_listing(&root, "d").status, "ok");+ }++ #[test]+ fn read_returns_full_content_and_enforces_the_one_mib_boundary() {+ let root = temp_skills_root("read");+ let exact = write_skill(&root, "exact", VALID_BODY);+ set_file_len(&exact, MAX_SKILL_FILE_BYTES);+ let toobig = write_skill(&root, "toobig", VALID_BODY);+ set_file_len(&toobig, MAX_SKILL_FILE_BYTES + 1);+ let canonical = std::fs::canonicalize(&root).unwrap();+ let exact_skill = read_skill_from_root(&canonical, "d", &skill_id("d", "exact")).unwrap();+ assert_eq!(exact_skill.name, "sql-review");+ assert_eq!(exact_skill.content.len(), MAX_SKILL_FILE_BYTES as usize);+ assert_eq!(read_skill_from_root(&canonical, "d", &skill_id("d", "toobig")).unwrap_err(), "oversized");+ }++ #[test]+ fn read_reports_not_found_for_missing_and_root_unavailable_for_disabled_roots() {+ let root = temp_skills_root("missing");+ let skill_dir = write_skill(&root, "gone", VALID_BODY);+ let canonical = std::fs::canonicalize(&root).unwrap();+ let id = skill_id("d", "gone");+ assert!(read_skill_from_root(&canonical, "d", &id).is_ok());+ std::fs::remove_dir_all(skill_dir).unwrap();+ assert_eq!(read_skill_from_root(&canonical, "d", &id).unwrap_err(), "not_found");++ let custom = temp_skills_root("custom");+ write_skill(&custom, "team", VALID_BODY);+ let custom_id = skill_id("c", "team");+ let disabled = read_skills(std::slice::from_ref(&custom_id), false, Some(custom.to_str().unwrap()));+ assert_eq!(disabled.failures.len(), 1);+ assert_eq!(disabled.failures[0].reason, "root_unavailable");+ let vanished = read_skills(&[custom_id], true, Some(custom.join("nope").to_str().unwrap()));+ assert_eq!(vanished.failures[0].reason, "root_unavailable");+ }++ #[test]+ fn read_preserves_request_order_and_collects_failures() {+ // Both roots are injected: a `d-` id resolved through the real home+ // directory would make this test depend on the machine it runs on.+ let root = temp_skills_root("order");+ write_skill(&root, "keep", VALID_BODY);+ std::fs::write(root.join("plain.txt"), "x").unwrap();+ let canonical = std::fs::canonicalize(&root).unwrap();+ let result = read_user_skills_from(+ &["d-bogus".to_string(), skill_id("d", "keep"), skill_id("d", "never-existed")],+ Some(&canonical),+ None,+ );+ assert_eq!(result.skills.len(), 1);+ assert_eq!(result.skills[0].id, skill_id("d", "keep"));+ assert_eq!(result.failures.len(), 2);+ assert_eq!(result.failures[0].id, "d-bogus");+ assert_eq!(result.failures[0].reason, "not_found");+ assert_eq!(result.failures[1].reason, "not_found");+ }++ #[test]+ fn read_skips_duplicate_ids() {+ let root = temp_skills_root("dedupe");+ write_skill(&root, "once", VALID_BODY);+ let canonical = std::fs::canonicalize(&root).unwrap();+ let id = skill_id("d", "once");+ let result = read_user_skills_from(&[id.clone(), id.clone(), id], Some(&canonical), None);+ assert_eq!(result.skills.len(), 1);+ assert!(result.failures.is_empty());+ // Deduplication must not swallow a failure: a repeated bad id is+ // still reported exactly once.+ let duplicated_bad = ["d-bogus".to_string(), "d-bogus".to_string()];+ let failed = read_user_skills_from(&duplicated_bad, Some(&canonical), None);+ assert!(failed.skills.is_empty());+ assert_eq!(failed.failures.len(), 1);+ assert_eq!(failed.failures[0].id, "d-bogus");+ }++ #[test]+ fn listing_omits_a_file_that_is_not_valid_utf8() {+ let root = temp_skills_root("invalid-utf8");+ let dir = root.join("broken");+ std::fs::create_dir_all(&dir).unwrap();+ let mut bytes = b"---\nname: br".to_vec();+ bytes.push(0xFF);+ bytes.extend_from_slice(b"oken\ndescription: desc\n---\n\nBody.\n");+ std::fs::write(dir.join(SKILL_FILE_NAME), &bytes).unwrap();+ let canonical = std::fs::canonicalize(&root).unwrap();+ assert!(scan_root(&canonical, "d").is_empty());+ assert_eq!(read_skill_from_root(&canonical, "d", &skill_id("d", "broken")).unwrap_err(), "not_utf8");+ }++ #[test]+ fn listing_tolerates_a_multibyte_character_cut_by_the_prefix_read() {+ let root = temp_skills_root("prefix-cut");+ let frontmatter = "---\nname: cut\ndescription: boundary\n---\n";+ let mut body = String::from(frontmatter);+ body.push_str(&"a".repeat(FRONTMATTER_SCAN_BYTES - frontmatter.len() - 1));+ body.push('\u{e9}');+ body.push_str(&"b".repeat(64));+ write_skill(&root, "cut", &body);+ let canonical = std::fs::canonicalize(&root).unwrap();+ let skills = scan_root(&canonical, "d");+ assert_eq!(skills.len(), 1);+ assert_eq!(skills[0].name, "cut");+ }++ #[cfg(unix)]+ #[test]+ fn symlink_policy_allows_inside_root_only() {+ use std::os::unix::fs::symlink;+ let root = temp_skills_root("links");+ write_skill(&root, "real", VALID_BODY);+ symlink(root.join("real"), root.join("inside")).unwrap();+ let outside = temp_skills_root("outside");+ write_skill(&outside, "escapee", VALID_BODY);+ symlink(outside.join("escapee"), root.join("escape")).unwrap();+ let canonical = std::fs::canonicalize(&root).unwrap();+ let skills = scan_root(&canonical, "d");+ let ids: Vec<String> = skills.iter().map(|skill| skill.id.clone()).collect();+ assert!(ids.contains(&skill_id("d", "inside")));+ assert!(!ids.contains(&skill_id("d", "escape")));+ }++ #[cfg(unix)]+ #[test]+ fn skill_file_symlink_cannot_escape_the_root() {+ use std::os::unix::fs::symlink;++ let root = temp_skills_root("file-link");+ let escape_dir = write_skill(&root, "file-escape", VALID_BODY);+ let outside = temp_skills_root("file-link-outside");+ let outside_file = outside.join("SKILL.md");+ std::fs::write(&outside_file, VALID_BODY).unwrap();+ std::fs::remove_file(escape_dir.join(SKILL_FILE_NAME)).unwrap();+ symlink(&outside_file, escape_dir.join(SKILL_FILE_NAME)).unwrap();++ let canonical = std::fs::canonicalize(&root).unwrap();+ let id = skill_id("d", "file-escape");+ assert!(!scan_root(&canonical, "d").iter().any(|skill| skill.id == id));+ assert_eq!(read_skill_from_root(&canonical, "d", &id).unwrap_err(), REASON_NOT_FOUND);+ }++ // ── name resolution and referencing files (agent tools) ────────────────++ fn write_named_skill(root: &Path, dir: &str, name: &str, description: &str) -> PathBuf {+ write_skill(root, dir, &format!("---\nname: {name}\ndescription: {description}\n---\n\nBody of {name}.\n"))+ }++ fn roots_of(default: &Path, custom: Option<&Path>) -> SkillRoots {+ SkillRoots {+ default: Some(std::fs::canonicalize(default).unwrap()),+ custom: custom.map(|path| std::fs::canonicalize(path).unwrap()),+ }+ }++ #[test]+ fn read_skill_by_name_resolves_a_unique_name_and_reports_its_source() {+ let root = temp_skills_root("byname");+ write_named_skill(&root, "alpha", "sql-review", "review rules");+ let roots = roots_of(&root, None);++ let SkillLookup::Found(skill) = read_skill_by_name("sql-review", None, &roots) else {+ panic!("a unique name must resolve");+ };+ assert_eq!(skill.source, "default");+ assert_eq!(skill.name, "sql-review");+ assert!(skill.content.contains("Body of sql-review."));+ assert_eq!(skill.dir, roots.default.clone().unwrap().join("alpha"));+ assert!(skill.id.starts_with("d-"));+ }++ #[test]+ fn read_skill_by_name_never_guesses_between_real_skills() {+ let root = temp_skills_root("ambiguous");+ write_named_skill(&root, "one", "shared", "first");+ write_named_skill(&root, "two", "shared", "second");+ let custom = temp_skills_root("ambiguous-custom");+ write_named_skill(&custom, "three", "shared", "third");+ let roots = roots_of(&root, Some(&custom));++ let SkillLookup::Ambiguous(candidates) = read_skill_by_name("shared", None, &roots) else {+ panic!("three skills share the name; the tool must list them, not pick one");+ };+ assert_eq!(candidates.len(), 3);+ assert!(candidates.iter().any(|candidate| candidate.source == "custom"));++ // `source` narrows it, but two entries in the same root stay ambiguous:+ // guessing between them would be a silent wrong answer.+ let SkillLookup::Ambiguous(candidates) = read_skill_by_name("shared", Some("default"), &roots) else {+ panic!("two entries in one root remain ambiguous");+ };+ assert_eq!(candidates.len(), 2);++ let SkillLookup::Found(skill) = read_skill_by_name("shared", Some("custom"), &roots) else {+ panic!("source must disambiguate");+ };+ assert_eq!(skill.source, "custom");+ assert_eq!(skill.description, "third");+ }++ #[test]+ fn read_skill_by_name_matches_exactly_and_refuses_an_empty_name() {+ let root = temp_skills_root("exact-name");+ write_named_skill(&root, "alpha", "sql-review", "rules");+ let roots = roots_of(&root, None);++ assert!(matches!(read_skill_by_name("", None, &roots), SkillLookup::NotFound));+ assert!(matches!(read_skill_by_name(" ", None, &roots), SkillLookup::NotFound));+ // Exact matching is deliberate: the listing prints the name verbatim, so+ // a fuzzy matcher would turn "did you mean" into a silent wrong skill.+ assert!(matches!(read_skill_by_name("SQL-Review", None, &roots), SkillLookup::NotFound));+ assert!(matches!(read_skill_by_name("d-abc", None, &roots), SkillLookup::NotFound));+ }++ #[test]+ fn list_skill_candidates_reports_names_and_sources_only() {+ let root = temp_skills_root("candidates");+ write_named_skill(&root, "alpha", "sql-review", "rules");+ let custom = temp_skills_root("candidates-custom");+ write_named_skill(&custom, "beta", "team-rules", "team");+ let roots = roots_of(&root, Some(&custom));++ let candidates = list_skill_candidates(&roots);+ let listed: Vec<(&str, &str)> =+ candidates.iter().map(|candidate| (candidate.name.as_str(), candidate.source)).collect();+ // Root order is fixed (default first) so the recovery answer is stable.+ assert_eq!(listed, [("sql-review", "default"), ("team-rules", "custom")]);+ for candidate in &candidates {+ assert!(!candidate.description.is_empty());+ }+ }++ #[test]+ fn list_skill_files_uses_relative_paths_and_skips_hidden_and_vendor_dirs() {+ let root = temp_skills_root("listing-files");+ let dir = write_named_skill(&root, "alpha", "alpha", "d");+ std::fs::create_dir_all(dir.join("references").join("deep")).unwrap();+ std::fs::write(dir.join("references").join("one.md"), "one").unwrap();+ std::fs::write(dir.join("references").join("deep").join("two.md"), "two").unwrap();+ std::fs::write(dir.join("script.py"), "print(1)").unwrap();+ std::fs::create_dir_all(dir.join("node_modules")).unwrap();+ std::fs::write(dir.join("node_modules").join("dep.js"), "x").unwrap();+ std::fs::create_dir_all(dir.join(".hidden")).unwrap();+ std::fs::write(dir.join(".hidden").join("secret.md"), "x").unwrap();+ let binary = vec![0x89u8, b'P', b'N', b'G', 0, 1, 2, 3];+ std::fs::write(dir.join("logo.png"), &binary).unwrap();++ let canonical = std::fs::canonicalize(&dir).unwrap();+ let listing = list_skill_files(&canonical);+ let paths: Vec<&str> = listing.entries.iter().map(|entry| entry.relative_path.as_str()).collect();+ assert_eq!(paths, vec!["SKILL.md", "logo.png", "references/deep/two.md", "references/one.md", "script.py"]);+ // The model must be able to paste the path straight back into+ // read_skill_file, so separators are normalized regardless of platform.+ assert!(listing.entries.iter().all(|entry| !entry.relative_path.contains('\\')));+ assert!(!listing.truncated);++ let png = listing.entries.iter().find(|entry| entry.relative_path == "logo.png").unwrap();+ assert!(!png.text, "a NUL byte marks the file as binary");+ assert_eq!(png.bytes, binary.len() as u64);+ assert!(listing.entries.iter().find(|entry| entry.relative_path == "script.py").unwrap().text);+ }++ #[test]+ fn list_skill_files_reports_truncation_instead_of_a_partial_list() {+ let root = temp_skills_root("listing-cap");+ let dir = write_named_skill(&root, "many", "many", "d");+ for index in 0..SKILL_LISTING_MAX_ENTRIES + 5 {+ std::fs::write(dir.join(format!("file-{index:03}.md")), "x").unwrap();+ }+ let canonical = std::fs::canonicalize(&dir).unwrap();+ let listing = list_skill_files(&canonical);+ assert_eq!(listing.entries.len(), SKILL_LISTING_MAX_ENTRIES);+ assert!(listing.truncated, "a capped listing must say so rather than look complete");+ }++ #[test]+ fn read_skill_file_chunk_returns_cursor_without_splitting_utf8() {+ let root = temp_skills_root("chunk");+ let dir = write_skill(&root, "alpha", VALID_BODY);+ std::fs::write(dir.join("reference.md"), "甲乙丙丁戊己").unwrap();+ let canonical = std::fs::canonicalize(&root).unwrap();++ let first = read_skill_file_relative_chunk(&canonical.join("alpha"), "reference.md", 0, 2).unwrap();+ assert_eq!(first.content, "甲乙");+ assert_eq!(first.total_chars, 6);+ assert_eq!(first.next_offset, Some(2));++ let last = read_skill_file_relative_chunk(&canonical.join("alpha"), "reference.md", 2, 10).unwrap();+ assert_eq!(last.content, "丙丁戊己");+ assert_eq!(last.next_offset, None);+ }++ #[test]+ fn read_skill_file_relative_reads_inside_the_skill_directory_only() {+ let root = temp_skills_root("read-rel");+ let dir = write_named_skill(&root, "alpha", "alpha", "d");+ std::fs::create_dir_all(dir.join("references")).unwrap();+ std::fs::write(dir.join("references").join("one.md"), "reference body").unwrap();+ std::fs::write(root.join("outside.md"), "outside body").unwrap();+ let canonical = std::fs::canonicalize(&dir).unwrap();++ assert_eq!(read_skill_file_relative(&canonical, "references/one.md").unwrap(), "reference body");+ assert!(read_skill_file_relative(&canonical, "SKILL.md").unwrap().contains("name: alpha"));++ // Escapes and absolutes are refused outright rather than left to the+ // containment check, so the reason stays stable across platforms.+ // The Windows-shaped absolute path matters: `is_absolute` is false for+ // "/etc/hosts" there, and the containment check is what catches it.+ for escape in [+ "../outside.md",+ "references/../../outside.md",+ "..\\outside.md",+ "/etc/hosts",+ "C:\\Windows\\win.ini",+ " ",+ ] {+ assert_eq!(+ read_skill_file_relative(&canonical, escape).unwrap_err(),+ REASON_NOT_FOUND,+ "must reject {escape:?}"+ );+ }+ // A directory and a missing name are both not-found, never a read.+ assert_eq!(read_skill_file_relative(&canonical, "references").unwrap_err(), REASON_NOT_FOUND);+ assert_eq!(read_skill_file_relative(&canonical, "nope.md").unwrap_err(), REASON_NOT_FOUND);+ }++ #[test]+ fn read_skill_file_relative_refuses_binary_oversized_and_non_utf8_files() {+ let root = temp_skills_root("read-reject");+ let dir = write_named_skill(&root, "alpha", "alpha", "d");+ let canonical = std::fs::canonicalize(&dir).unwrap();++ std::fs::write(dir.join("with-nul.md"), b"text\0more").unwrap();+ assert_eq!(read_skill_file_relative(&canonical, "with-nul.md").unwrap_err(), REASON_NOT_TEXT);++ // No NUL here, so this must fall through to the encoding check rather+ // than being mistaken for binary.+ std::fs::write(dir.join("broken.md"), [0xFFu8, 0xFE]).unwrap();+ assert_eq!(read_skill_file_relative(&canonical, "broken.md").unwrap_err(), REASON_NOT_UTF8);++ let big = dir.join("big.md");+ std::fs::write(&big, "x").unwrap();+ std::fs::OpenOptions::new().write(true).open(&big).unwrap().set_len(MAX_SKILL_FILE_BYTES + 1).unwrap();+ assert_eq!(read_skill_file_relative(&canonical, "big.md").unwrap_err(), REASON_OVERSIZED);+ }++ #[cfg(unix)]+ #[test]+ fn read_skill_file_relative_cannot_follow_a_link_out_of_the_skill_directory() {+ use std::os::unix::fs::symlink;+ let root = temp_skills_root("rel-link");+ let dir = write_named_skill(&root, "alpha", "alpha", "d");+ let outside = temp_skills_root("rel-link-outside");+ let outside_file = outside.join("secret.md");+ std::fs::write(&outside_file, "secret").unwrap();+ symlink(&outside_file, dir.join("link.md")).unwrap();+ symlink(&outside, dir.join("linkdir")).unwrap();+ let canonical = std::fs::canonicalize(&dir).unwrap();++ assert_eq!(read_skill_file_relative(&canonical, "link.md").unwrap_err(), REASON_NOT_FOUND);+ assert_eq!(read_skill_file_relative(&canonical, "linkdir/secret.md").unwrap_err(), REASON_NOT_FOUND);+ let listing = list_skill_files(&canonical);+ assert!(!listing.entries.iter().any(|entry| entry.relative_path.starts_with("link")));+ }++ // ── Windows reparse-point equivalents ──────────────────────────────────+ //+ // The `#[cfg(unix)]` tests above are COMPILED OUT on Windows rather than+ // skipped at runtime (`0 ignored` in a Windows run proves it), which would+ // leave the containment rule untested on the platform DBX ships — and that+ // rule is what stops `read_skill_file` (model-controlled input) from reading+ // an arbitrary local file. A directory junction is a reparse point that+ // `std::fs::canonicalize` (`GetFinalPathNameByHandleW`) resolves exactly+ // like a symlink, and creating one needs no+ // SeCreateSymbolicLinkPrivilege, so the directory cases run unconditionally+ // here instead of behind a privilege check.+ //+ // Still uncovered on Windows, deliberately: a FILE-level link. `symlink_file`+ // needs Developer Mode or that privilege, and a junction cannot stand in for+ // it, so a test that creates one either fails on every machine without the+ // privilege or passes while asserting nothing. The containment check runs on+ // the canonicalized path and is indifferent to which reparse point produced+ // it, so what the junction tests leave unverified is narrow — that Windows+ // resolves file symlinks exactly as it resolves junctions in `canonicalize`.+ // Hard links stay uncovered on every platform: `canonicalize` does not reveal+ // their target at all.+ #[cfg(windows)]+ fn create_junction(link: &Path, target: &Path) {+ // `mklink` is a cmd builtin and refuses to overwrite, so callers only+ // pass paths that cannot exist yet. A failing junction creation is a loud+ // failure, never a silent skip: a green test that asserts nothing is+ // worse than a red one.+ let output = std::process::Command::new("cmd")+ .args(["/C", "mklink", "/J"])+ .arg(link)+ .arg(target)+ .output()+ .expect("cmd must be runnable to create a junction");+ assert!(+ output.status.success(),+ "junction creation failed: {}{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ }++ #[cfg(windows)]+ #[test]+ fn junction_policy_allows_inside_root_only() {+ let root = temp_skills_root("junction-links");+ let real = write_skill(&root, "real", VALID_BODY);+ create_junction(&root.join("inside"), &real);+ let outside = temp_skills_root("junction-outside");+ let escapee = write_skill(&outside, "escapee", VALID_BODY);+ create_junction(&root.join("escape"), &escapee);++ let canonical = std::fs::canonicalize(&root).unwrap();+ let ids: Vec<String> = scan_root(&canonical, "d").into_iter().map(|skill| skill.id).collect();+ assert!(ids.contains(&skill_id("d", "inside")));+ assert!(!ids.contains(&skill_id("d", "escape")), "a junction out of the root must stay invisible");+ }++ #[cfg(windows)]+ #[test]+ fn junction_inside_a_skill_directory_cannot_be_read_or_listed() {+ let root = temp_skills_root("junction-rel");+ let dir = write_named_skill(&root, "alpha", "alpha", "d");+ let outside = temp_skills_root("junction-rel-outside");+ std::fs::write(outside.join("secret.md"), "secret").unwrap();+ create_junction(&dir.join("linkdir"), &outside);++ let canonical = std::fs::canonicalize(&dir).unwrap();+ assert_eq!(read_skill_file_relative(&canonical, "linkdir/secret.md").unwrap_err(), REASON_NOT_FOUND);+ let listing = list_skill_files(&canonical);+ assert!(!listing.entries.iter().any(|entry| entry.relative_path.starts_with("linkdir")));+ }+}diff --git a/crates/dbx-web/src/routes/ai.rs b/crates/dbx-web/src/routes/ai.rsindex 4b70f19645..c013ab2fc4 100644--- a/crates/dbx-web/src/routes/ai.rs+++ b/crates/dbx-web/src/routes/ai.rs@@ -520,6 +520,11 @@ pub async fn ai_agent_stream(// The loop below runs on its own current-thread runtime; plugin// sidecar calls must stay on the server runtime that owns the sessions.host_runtime: Some(tokio::runtime::Handle::current()),+ // Always false, and deliberately not a request field: the on-demand+ // skill tools read the user's local skill files, which the web server+ // never exposes (prd 09-30-skill-listing-use-skill, Requirement 16).+ // A future caller cannot opt in by adding a JSON key.+ allow_skills: false,};let sid = session_id.clone();diff --git a/docs/content/docs/ai-assistant.cn.mdx b/docs/content/docs/ai-assistant.cn.mdxindex f6f096534e..e2445eea1a 100644--- a/docs/content/docs/ai-assistant.cn.mdx+++ b/docs/content/docs/ai-assistant.cn.mdx@@ -129,11 +129,17 @@ AI 上下文可以包含:## Skills(SKILL.md)-Desktop 可以把只读的 [`SKILL.md`](https://developers.openai.com/codex/skills) 规则文件作为补充性指令附加到请求中。技能始终从 `~/.agents/skills` 发现;设置 → AI 中还可以额外启用一个自定义目录。两个目录独立校验,同名技能并列保留并标注来源(`默认目录` / `自定义目录`),自定义目录的技能排在前面。+Desktop 可以把只读的 [`SKILL.md`](https://developers.openai.com/codex/skills) 规则文件作为补充性指令使用。技能始终从 `~/.agents/skills` 发现;设置 → AI 中还可以额外启用一个自定义目录。两个目录独立校验,同名技能并列保留并标注来源(`默认目录` / `自定义目录`),自定义目录的技能排在前面。-在输入区的 `Skills` 入口(或输入 `/skill`)选择技能,选中项以芯片形式显示在输入框上方,可随时移除。选择的生命周期是一个打开的 AI 面板:切换会话、新建会话都会保留;关闭面板或重启 DBX 即清空。选择不会持久化,DBX 也绝不写入技能文件。+进入模型上下文的只有每个技能的**名称与描述**(listing);技能正文改为**按需加载**——模型判断需要时调用 `use_skill` 工具,DBX 才从磁盘读取正文并返回;技能附带的文件(参考文档、脚本、模板)再由模型逐个用 `read_skill_file` 读取。DBX 绝不写入技能文件,读到文件内容也不等于获得执行许可。-技能正文只在发送时从磁盘读取,并当场校验:文件被删除或不可读、frontmatter 无效、不是 UTF-8、超过单文件 1 MiB 上限、符号链接逃逸出所在目录,都会阻断发送,并在输入框上方显示横幅,标明失败的技能并提供重试、刷新、移除或打开设置等恢复操作。未选择任何技能时,提示词与既有行为逐字节一致。Web 端不提供该功能。+在输入区的 `Skills` 入口(或输入 `/skill`)选择技能,选中项以芯片形式显示在输入框上方,可随时移除。**勾选不排他**:选中项在 listing 中标记为用户指定、优先级更高,但模型同样可以从同一份 listing 里加载未勾选的技能。开启**设置 → AI → 允许 AI 自动使用 Skills**(默认关闭)后,即使未勾选任何技能,每次请求也会附带 listing,由模型自行挑选。++芯片有两态:默认态与**本会话中已加载**。模型调用过 `use_skill`,或你点击芯片手动加载过,该芯片就会标记为「已加载」。**点击芯片会立即加载该技能**:DBX 当场读取正文并放进本次对话,下一轮起模型就能看到它。「已加载」按会话记录,关闭后重新打开 AI 面板仍然保留,新建会话则重置。重启 DBX 后 DBX 记住的是「这个技能加载过」这一事实本身:下一次请求需要它时会重新从磁盘读取正文,因此期间被删除、或超过大小限制的技能会退回未加载状态并说明原因。若已勾选的技能在本次对话中始终没有被加载,输入框上方会出现**一次性**提示,点击即可立即加载(每个会话只提示一次)。++Skill 仅对 DBX 内置 AI 可用。CLI 供应商(Claude Code / Codex / Cursor / OpenCode / Grok / Qoder / CodeBuddy / Pi)拿不到 listing、正文与 skill 工具;其选择器会被禁用并说明原因,已勾选的芯片仍然可见、可移除。++因为按需加载,发送时不再读取正文:正文文件被删除、frontmatter 无效、不是 UTF-8 等失败会在**加载时**暴露,而不是阻断发送。唯一的例外是已勾选的技能已不在目录中——此时仍会阻断发送,并在输入框上方显示横幅标明失败的技能,提供重试、刷新、移除或打开设置等恢复操作。超过 1 MiB 的文件、二进制文件、以及离开技能目录的路径一律拒绝。未勾选任何技能且开关关闭时,提示词与既有行为逐字节一致。Web 端不提供该功能。## 插件工具diff --git a/docs/content/docs/ai-assistant.mdx b/docs/content/docs/ai-assistant.mdxindex 286d527de6..3d2892149b 100644--- a/docs/content/docs/ai-assistant.mdx+++ b/docs/content/docs/ai-assistant.mdx@@ -131,11 +131,17 @@ Templates enter model context. Do not put passwords, tokens, or unnecessary busi## Skills (SKILL.md)-Desktop can attach read-only [`SKILL.md`](https://developers.openai.com/codex/skills) rule files to a request as supplementary instructions. Skills are always discovered in `~/.agents/skills`; Settings → AI can additionally enable one custom directory. Each directory is validated independently, same names are kept side by side and labeled by source (`Default directory` / `Custom directory`), and custom-directory skills sort first.+Desktop can use read-only [`SKILL.md`](https://developers.openai.com/codex/skills) rule files as supplementary instructions. Skills are always discovered in `~/.agents/skills`; Settings → AI can additionally enable one custom directory. Each directory is validated independently, same names are kept side by side and labeled by source (`Default directory` / `Custom directory`), and custom-directory skills sort first.-Select skills from the composer `Skills` entry (or type `/skill`) and remove them from the chips above the input. The selection lives for the lifetime of one open AI panel — conversation switches and new conversations keep it; closing the panel or restarting DBX clears it. Nothing is persisted, and DBX never writes to skill files.+Only each skill's **name and description** reach the model, as a listing. A skill's body is loaded **on demand**: when the model decides it needs one it calls the `use_skill` tool, and only then does DBX read the body from disk and return it. Files a skill ships (references, scripts, templates) are read one by one with `read_skill_file`. DBX never writes to skill files, and reading a file's content is never permission to run it.-Skill bodies are read only when a request is sent, directly from disk, and validated then: file deleted or unreadable, invalid frontmatter, non-UTF-8 content, over the 1 MiB per-file limit, or a symlink escaping its root blocks the send with a banner above the composer naming the failed skill and offering Retry, Refresh, Remove, or Open Settings. With no skills selected, prompts are byte-for-byte identical to the pre-feature behavior. Web ships this feature unsupported.+Select skills from the composer `Skills` entry (or type `/skill`); selected skills appear as chips above the input and can be removed at any time. **Selecting is not exclusive**: the user-selected entries are marked in the listing and take priority, but the model may also load an unticked skill from that same listing. With **Settings → AI → Allow the AI to use skills automatically** turned on (off by default) the listing is sent with every request even when nothing is selected, so the model can pick a skill on its own.++A chip has two states: its default state, and **loaded in this conversation**. A chip gains the loaded marker once the model has called `use_skill` for that skill, or once you loaded it yourself. **Clicking a chip loads that skill immediately**: DBX reads the body there and then and puts it into the conversation, so the following turns answer with it. The loaded state is per conversation — it survives closing and reopening the AI panel, and a new conversation starts over. What DBX remembers after a restart is that the skill was loaded: the body is read from disk again when the next request needs it, so a skill that was deleted or grew past the read limit in the meantime goes back to its unloaded state and says why. While a selected skill has not been loaded yet, a **one-time** hint above the input offers to load it (each conversation shows that hint once).++Skills are available to DBX's built-in AI only. A CLI provider (Claude Code, Codex, Cursor, OpenCode, Grok, Qoder, CodeBuddy, Pi) receives no listing, no skill body, and no skill tools; its skill selector is disabled with the reason shown, and skills that were already selected stay visible and removable.++Because loading is on demand, nothing is read at send time: a deleted or unreadable file, invalid frontmatter, or a body that is not UTF-8 text now fails when the skill is loaded instead of blocking the send. The one exception is a checked skill that is no longer in the catalog: sending stays blocked, with a banner above the composer naming the failed skill and offering Retry, Refresh, Remove, or Open Settings. Files over the 1 MiB limit, binary files, and paths that leave a skill directory are refused. With no skills selected and the toggle off, prompts are byte-for-byte identical to the pre-feature behavior. Web ships this feature unsupported.## Plugin Toolsdiff --git a/src-tauri/src/commands/ai.rs b/src-tauri/src/commands/ai.rsindex fe7dd996be..7b20913392 100644--- a/src-tauri/src/commands/ai.rs+++ b/src-tauri/src/commands/ai.rs@@ -235,6 +235,7 @@ impl<R: tauri::Runtime> AiAgentEventBatcher<R> {struct AiStreamChunkBatch {delta: String,reasoning: Option<String>,+ finish_reason: Option<String>,last_emit: Option<std::time::Instant>,}@@ -266,8 +267,12 @@ impl<R: tauri::Runtime> AiStreamChunkBatcher<R> {fn handle(&self, mut chunk: AiStreamChunk) {let mut batch = self.lock_batch();+ if let Some(reason) = chunk.finish_reason.take() {+ batch.finish_reason = Some(reason);+ }if chunk.done {self.flush_locked(&mut batch);+ chunk.finish_reason = batch.finish_reason.take();self.emit_chunk(chunk);return;}@@ -300,6 +305,7 @@ impl<R: tauri::Runtime> AiStreamChunkBatcher<R> {session_id: self.session_id.clone(),delta: std::mem::take(&mut batch.delta),reasoning_delta: batch.reasoning.take(),+ finish_reason: None,done: false,});}@@ -372,6 +378,9 @@ pub async fn ai_agent_stream(confirmed_database: Option<String>,confirmed_schema: Option<String>,selected_databases: Option<Vec<String>>,+ // Set by the frontend exactly when this send carries a skill listing; the+ // agent loop appends the skill tools only then (ADR Decision 10).+ allow_skills: Option<bool>,) -> Result<String, String> {let mut request = resolve_cli_provider_request(request);merge_global_max_retries(@@ -435,6 +444,7 @@ pub async fn ai_agent_stream(prompt_cache_key: request.prompt_cache_key.clone(),session_id: Some(session_id.clone()),host_runtime: Some(tokio::runtime::Handle::current()),+ allow_skills: allow_skills.unwrap_or(false),};let is_agent_mode = mode.as_deref() == Some("agent");@@ -642,6 +652,7 @@ mod tests {session_id: "session-2".to_string(),delta: "a".to_string(),reasoning_delta: None,+ finish_reason: None,done: false,});// Held within the interval …@@ -649,6 +660,7 @@ mod tests {session_id: "session-2".to_string(),delta: "b".to_string(),reasoning_delta: Some("r".to_string()),+ finish_reason: None,done: false,});// … and flushed in order before the terminal chunk is forwarded.@@ -656,6 +668,7 @@ mod tests {session_id: "session-2".to_string(),delta: String::new(),reasoning_delta: None,+ finish_reason: None,done: true,});diff --git a/src-tauri/src/commands/user_skills.rs b/src-tauri/src/commands/user_skills.rsindex da3c55c52f..2e82a7fbe7 100644--- a/src-tauri/src/commands/user_skills.rs+++ b/src-tauri/src/commands/user_skills.rs@@ -1,102 +1,23 @@-//! Read-only discovery and reading of user-level SKILL.md skills.+//! Tauri command layer for user-level SKILL.md skills (prd 09-21-public-skill-loader).//!-//! Two roots are scanned: the default user-level root (HOME/.agents/skills) and-//! an optional user-configured custom root (Settings > AI). The service is-//! strictly read-only: there is no create/write/delete API. Skills are-//! identified by deterministic opaque ids derived from the root source and the-//! canonical relative skill directory name, so ids survive Refresh (prd.md:34).-//! Absolute paths never leave this module (prd.md:33).+//! The discovery, path-boundary and frontmatter logic lives in+//! [`dbx_core::skills`] because the AI agent loop needs exactly the same rules+//! (prd 09-30-skill-listing-use-skill). This module is only the transport+//! adapter: it keeps the command names, parameter names and camelCase JSON+//! shapes the frontend already depends on, and offloads the blocking+//! filesystem work off the async runtime.-use std::collections::HashSet;-use std::io::Read;-use std::path::{Path, PathBuf};--use serde::{Deserialize, Serialize};-use sha2::{Digest, Sha256};--pub const SKILL_FILE_NAME: &str = "SKILL.md";-/// Hard per-file safety limit: a larger SKILL.md is invalid and omitted from-/// discovery, and blocks the send when selected (prd.md:26/:37).-pub const MAX_SKILL_FILE_BYTES: u64 = 1_048_576;-/// Send-time reads take at most 1 MiB + 1 byte so a file that grows after the-/// metadata check is rejected instead of loaded unboundedly (prd.md:38).-const READ_LIMIT_BYTES: u64 = MAX_SKILL_FILE_BYTES + 1;-/// The opening frontmatter block must close within the first 64 KiB.-const FRONTMATTER_SCAN_BYTES: usize = 64 * 1024;--const DEFAULT_ROOT_PREFIX: &str = "d";-const CUSTOM_ROOT_PREFIX: &str = "c";--const ROOT_STATUS_OK: &str = "ok";-const ROOT_STATUS_MISSING: &str = "missing";-const ROOT_STATUS_INVALID: &str = "invalid";--/// Bounded failure vocabulary. Underlying I/O detail (which can contain-/// absolute paths or OS-specific text) is deliberately discarded rather than-/// forwarded, so nothing path-shaped reaches the frontend (prd.md:33).-const REASON_NOT_FOUND: &str = "not_found";-const REASON_ROOT_UNAVAILABLE: &str = "root_unavailable";-const REASON_OVERSIZED: &str = "oversized";-const REASON_NOT_UTF8: &str = "not_utf8";-const REASON_INVALID_FRONTMATTER: &str = "invalid_frontmatter";-const REASON_UNREADABLE: &str = "unreadable";--#[derive(Debug, Clone, PartialEq, Eq, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct UserSkillMeta {- pub id: String,- pub name: String,- pub description: String,-}--#[derive(Debug, Clone, PartialEq, Eq, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct UserSkillRootListing {- /// One of "ok" | "missing" | "invalid".- pub status: String,- pub skills: Vec<UserSkillMeta>,-}--#[derive(Debug, Clone, PartialEq, Eq, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct UserSkillsListResult {- pub default_root: UserSkillRootListing,- pub custom_root: Option<UserSkillRootListing>,-}--#[derive(Debug, Clone, PartialEq, Eq, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct ReadUserSkill {- pub id: String,- pub name: String,- pub description: String,- pub content: String,-}--#[derive(Debug, Clone, PartialEq, Eq, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct ReadUserSkillFailure {- pub id: String,- /// One of "not_found" | "root_unavailable" | "oversized" | "not_utf8" | "invalid_frontmatter" | "unreadable".- pub reason: String,-}--#[derive(Debug, Clone, PartialEq, Eq, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct UserSkillsReadResult {- pub skills: Vec<ReadUserSkill>,- pub failures: Vec<ReadUserSkillFailure>,-}+use dbx_core::skills::{self, UserSkillsListResult, UserSkillsReadResult};/// Lists skill metadata for both roots. The default root is always scanned;-/// the custom root only when it is enabled in Settings (prd.md:27). An absent-/// root yields an empty listing rather than an error (prd.md:35).+/// the custom root only when it is enabled in Settings. An absent root yields+/// an empty listing rather than an error.#[tauri::command]pub async fn list_user_skills(custom_root_enabled: bool,custom_root: Option<String>,) -> Result<UserSkillsListResult, String> {- tauri::async_runtime::spawn_blocking(move || list_user_skills_blocking(custom_root_enabled, custom_root.as_deref()))+ tauri::async_runtime::spawn_blocking(move || skills::list_skills(custom_root_enabled, custom_root.as_deref())).await.map_err(|error| error.to_string())}@@ -104,497 +25,14 @@ pub async fn list_user_skills(/// Reads the currently selected skills by id. Every id is resolved only/// through re-derivation over a fresh scan of the owning root, so a deleted,/// moved, or root-escaping skill fails instead of silently resolving to a-/// stale path (prd.md:37).+/// stale path.#[tauri::command]pub async fn read_user_skills(ids: Vec<String>,custom_root_enabled: bool,custom_root: Option<String>,) -> Result<UserSkillsReadResult, String> {- tauri::async_runtime::spawn_blocking(move || {- read_user_skills_blocking(&ids, custom_root_enabled, custom_root.as_deref())- })- .await- .map_err(|error| error.to_string())-}--fn list_user_skills_blocking(custom_root_enabled: bool, custom_root: Option<&str>) -> UserSkillsListResult {- let default_root = match default_skills_root() {- Some(path) => root_listing(&path, DEFAULT_ROOT_PREFIX),- None => empty_listing(ROOT_STATUS_MISSING),- };- let custom_root = if custom_root_enabled {- enabled_custom_root(custom_root).map(|path| root_listing(&path, CUSTOM_ROOT_PREFIX))- } else {- None- };- UserSkillsListResult { default_root, custom_root }-}--fn read_user_skills_blocking(- ids: &[String],- custom_root_enabled: bool,- custom_root: Option<&str>,-) -> UserSkillsReadResult {- let default_root =- default_skills_root().and_then(|path| std::fs::canonicalize(&path).ok()).filter(|path| path.is_dir());- let custom_root = if custom_root_enabled { enabled_custom_root(custom_root) } else { None };- read_user_skills_from(ids, default_root.as_deref(), custom_root.as_deref())-}--/// Root resolution is injected so tests can exercise both roots without-/// depending on the developer home directory.-fn read_user_skills_from(- ids: &[String],- default_root: Option<&Path>,- custom_root: Option<&Path>,-) -> UserSkillsReadResult {- let mut skills = Vec::new();- let mut failures = Vec::new();- let mut seen_ids: HashSet<&str> = HashSet::new();- for id in ids {- // A repeated id must not inject the same skill text twice.- if !seen_ids.insert(id.as_str()) {- continue;- }- let prefix = match id.split_once('-') {- Some((prefix, _)) if prefix == DEFAULT_ROOT_PREFIX || prefix == CUSTOM_ROOT_PREFIX => prefix,- _ => {- failures.push(ReadUserSkillFailure { id: id.clone(), reason: REASON_NOT_FOUND.to_string() });- continue;- }- };- let root = match prefix {- DEFAULT_ROOT_PREFIX => default_root,- _ => custom_root,- };- let Some(root) = root else {- failures.push(ReadUserSkillFailure { id: id.clone(), reason: REASON_ROOT_UNAVAILABLE.to_string() });- continue;- };- match read_skill_from_root(root, prefix, id) {- Ok(skill) => skills.push(skill),- Err(reason) => failures.push(ReadUserSkillFailure { id: id.clone(), reason }),- }- }- UserSkillsReadResult { skills, failures }-}--fn enabled_custom_root(custom_root: Option<&str>) -> Option<PathBuf> {- let trimmed = custom_root.map(str::trim).filter(|value| !value.is_empty())?;- let canonical = std::fs::canonicalize(trimmed).ok()?;- canonical.is_dir().then_some(canonical)-}--fn default_skills_root() -> Option<PathBuf> {- Some(home_dir()?.join(".agents").join("skills"))-}--fn home_dir() -> Option<PathBuf> {- std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).ok().map(PathBuf::from)-}--fn empty_listing(status: &str) -> UserSkillRootListing {- UserSkillRootListing { status: status.to_string(), skills: Vec::new() }-}--fn root_listing(path: &Path, prefix: &str) -> UserSkillRootListing {- match std::fs::canonicalize(path) {- Ok(canonical) if canonical.is_dir() => {- UserSkillRootListing { status: ROOT_STATUS_OK.to_string(), skills: scan_root(&canonical, prefix) }- }- Ok(_) => empty_listing(ROOT_STATUS_INVALID),- Err(_) => empty_listing(ROOT_STATUS_MISSING),- }-}--/// Scans the direct children of a canonical root. Symlink policy (prd.md:40):-/// an entry is only discoverable when its canonical target stays inside the-/// root, so a symlink that escapes the root is invisible to discovery.-fn scan_root(canonical_root: &Path, prefix: &str) -> Vec<UserSkillMeta> {- let mut skills = Vec::new();- let Ok(entries) = std::fs::read_dir(canonical_root) else { return skills };- for entry in entries.flatten() {- let dir_name = entry.file_name().to_string_lossy().to_string();- if dir_name.starts_with('.') {- continue;- }- let Ok(canonical_dir) = entry.path().canonicalize() else { continue };- if !canonical_dir.starts_with(canonical_root) || !canonical_dir.is_dir() {- continue;- }- let skill_file = canonical_dir.join(SKILL_FILE_NAME);- let Ok(canonical_skill_file) = skill_file.canonicalize() else { continue };- // A skill directory may be linked within the allowed root, but its- // entry file must obey the same containment rule. Otherwise a normal- // directory could hide a SKILL.md symlink to an arbitrary local file.- if !canonical_skill_file.starts_with(canonical_root) {- continue;- }- let Some((name, description)) = discover_skill_metadata(&canonical_skill_file) else { continue };- skills.push(UserSkillMeta { id: skill_id(prefix, &dir_name), name, description });- }- skills.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.id.cmp(&b.id)));- skills-}--/// Listing reads only the head of the file: the size gate plus a bounded-/// prefix read are enough to parse the opening frontmatter block-/// (prd.md:26 - "parse their frontmatter according to the public convention").-/// The body is never read here (prd.md:56).-fn discover_skill_metadata(path: &Path) -> Option<(String, String)> {- let stat = std::fs::metadata(path).ok()?;- if !stat.is_file() || stat.len() > MAX_SKILL_FILE_BYTES {- return None;- }- let file = std::fs::File::open(path).ok()?;- let mut bytes = Vec::new();- file.take(FRONTMATTER_SCAN_BYTES as u64).read_to_end(&mut bytes).ok()?;- parse_frontmatter(decode_prefix(&bytes, stat.len())?)-}--/// Decodes the bounded listing prefix strictly, so an unreadable file is not-/// offered as a choice (it would always fail at send time). A multi-byte-/// character cut by the prefix read is not an encoding error: when the file-/// continues past the prefix, the trailing partial character is trimmed. The-/// bytes beyond the prefix stay unvalidated here and are checked at send time.-fn decode_prefix(bytes: &[u8], file_len: u64) -> Option<&str> {- match std::str::from_utf8(bytes) {- Ok(text) => Some(text),- Err(error) if error.error_len().is_none() && file_len > bytes.len() as u64 => {- std::str::from_utf8(&bytes[..error.valid_up_to()]).ok()- }- Err(_) => None,- }-}--/// Reads and fully validates one selected skill file. The metadata size check-/// is followed by a 1 MiB + 1 byte bounded read, so a file that grows between-/// the two is rejected as oversized instead of loaded unboundedly (prd.md:38).-fn read_skill_from_root(canonical_root: &Path, prefix: &str, id: &str) -> Result<ReadUserSkill, String> {- let entries = std::fs::read_dir(canonical_root).map_err(|_| REASON_NOT_FOUND.to_string())?;- for entry in entries.flatten() {- let dir_name = entry.file_name().to_string_lossy().to_string();- if dir_name.starts_with('.') || skill_id(prefix, &dir_name) != id {- continue;- }- let canonical_dir = entry.path().canonicalize().map_err(|_| REASON_NOT_FOUND.to_string())?;- if !canonical_dir.starts_with(canonical_root) || !canonical_dir.is_dir() {- return Err(REASON_NOT_FOUND.to_string());- }- let skill_file = canonical_dir.join(SKILL_FILE_NAME);- let canonical_skill_file = skill_file.canonicalize().map_err(|_| REASON_NOT_FOUND.to_string())?;- // Re-check the entry file on every send, not just its parent directory:- // another process may have swapped SKILL.md for an escaping symlink- // after it was discovered.- if !canonical_skill_file.starts_with(canonical_root) {- return Err(REASON_NOT_FOUND.to_string());- }- return read_skill_file(&canonical_skill_file, id);- }- Err(REASON_NOT_FOUND.to_string())-}--fn read_skill_file(path: &Path, id: &str) -> Result<ReadUserSkill, String> {- let stat = std::fs::metadata(path).map_err(|_| REASON_NOT_FOUND.to_string())?;- if !stat.is_file() {- return Err(REASON_NOT_FOUND.to_string());- }- if stat.len() > MAX_SKILL_FILE_BYTES {- return Err(REASON_OVERSIZED.to_string());- }- let file = std::fs::File::open(path).map_err(|_| REASON_UNREADABLE.to_string())?;- let mut bytes = Vec::new();- file.take(READ_LIMIT_BYTES).read_to_end(&mut bytes).map_err(|_| REASON_UNREADABLE.to_string())?;- if bytes.len() as u64 > MAX_SKILL_FILE_BYTES {- return Err(REASON_OVERSIZED.to_string());- }- let text = String::from_utf8(bytes).map_err(|_| REASON_NOT_UTF8.to_string())?;- let (name, description) = parse_frontmatter(&text).ok_or_else(|| REASON_INVALID_FRONTMATTER.to_string())?;- Ok(ReadUserSkill { id: id.to_string(), name, description, content: text })-}--/// Deterministic opaque id: root source prefix plus a truncated SHA-256 of the-/// canonical relative skill directory name. Stable across Refresh and restarts-/// of the registry (prd.md:34). The id carries no path material to the client.-fn skill_id(prefix: &str, dir_name: &str) -> String {- let digest = Sha256::digest(dir_name.as_bytes());- let mut id = String::from(prefix);- id.push('-');- for byte in &digest[..8] {- id.push_str(&format!("{:02x}", byte));- }- id-}--/// Parses the opening YAML frontmatter block per the public SKILL.md-/// convention: required non-empty name and description, unknown keys ignored.-/// Returns None when the block is missing, unclosed, oversized, or lacks a-/// required field (prd.md:26/:52).-fn parse_frontmatter(text: &str) -> Option<(String, String)> {- let text = text.strip_prefix("\u{feff}").unwrap_or(text);- let mut lines = text.lines();- if lines.next()?.trim_end() != "---" {- return None;- }- let mut block = String::new();- let mut closed = false;- for line in lines {- if line.trim_end() == "---" {- closed = true;- break;- }- block.push_str(line);- block.push('\n');- if block.len() > FRONTMATTER_SCAN_BYTES {- return None;- }- }- if !closed {- return None;- }- let frontmatter: SkillFrontmatter = serde_yaml_ng::from_str(&block).ok()?;- let name = frontmatter.name?.trim().to_string();- let description = frontmatter.description?.trim().to_string();- if name.is_empty() || description.is_empty() {- return None;- }- Some((name, description))-}--#[derive(Debug, Deserialize)]-struct SkillFrontmatter {- #[serde(default)]- name: Option<String>,- #[serde(default)]- description: Option<String>,-}--#[cfg(test)]-mod tests {- use super::*;-- const VALID_BODY: &str = "---\nname: sql-review\ndescription: Team SQL review rules\n---\n\nFollow the rules.\n";-- fn temp_skills_root(tag: &str) -> PathBuf {- let root = std::env::temp_dir().join(format!("dbx-user-skills-{tag}-{}", uuid::Uuid::new_v4()));- std::fs::create_dir_all(&root).unwrap();- root- }-- fn write_skill(root: &Path, dir: &str, body: &str) -> PathBuf {- let dir = root.join(dir);- std::fs::create_dir_all(&dir).unwrap();- std::fs::write(dir.join(SKILL_FILE_NAME), body).unwrap();- dir- }-- fn set_file_len(skill_dir: &Path, len: u64) {- let file = std::fs::OpenOptions::new().write(true).open(skill_dir.join(SKILL_FILE_NAME)).unwrap();- file.set_len(len).unwrap();- }-- #[test]- fn parses_frontmatter_and_ignores_extra_keys() {- let (name, description) =- parse_frontmatter("---\nname: \"sql-review\"\ndescription: Team rules\nmetadata:\n short: x\nallowed-tools: [read]\n---\n\nBody.\n").unwrap();- assert_eq!(name, "sql-review");- assert_eq!(description, "Team rules");- }-- #[test]- fn frontmatter_must_open_and_close_at_the_top() {- assert!(parse_frontmatter("name: x\ndescription: y\n").is_none());- assert!(parse_frontmatter("---\nname: x\ndescription: y\n").is_none());- assert!(parse_frontmatter("body first\n---\nname: x\ndescription: y\n---\n").is_none());- }-- #[test]- fn frontmatter_requires_name_and_description() {- assert!(parse_frontmatter("---\ndescription: only desc\n---\n").is_none());- assert!(parse_frontmatter("---\nname: only name\n---\n").is_none());- assert!(parse_frontmatter("---\nname:\ndescription: y\n---\n").is_none());- assert!(parse_frontmatter("---\nname: x\ndescription: \n---\n").is_none());- }-- #[test]- fn skill_ids_are_deterministic_and_root_scoped() {- assert_eq!(skill_id("d", "alpha"), skill_id("d", "alpha"));- assert_ne!(skill_id("d", "alpha"), skill_id("c", "alpha"));- assert_ne!(skill_id("d", "alpha"), skill_id("d", "beta"));- assert!(skill_id("d", "alpha").starts_with("d-"));- assert_eq!(skill_id("d", "alpha").len(), 18);- }-- #[test]- fn scan_lists_valid_skills_and_omits_others() {- let root = temp_skills_root("scan");- write_skill(&root, "alpha", VALID_BODY);- write_skill(&root, "zulu", VALID_BODY);- write_skill(&root, "nodesc", "---\nname: nodesc\n---\nbody\n");- write_skill(&root, ".hidden", VALID_BODY);- let nested = root.join("nested");- std::fs::create_dir_all(nested.join("deep")).unwrap();- std::fs::write(nested.join("deep").join(SKILL_FILE_NAME), VALID_BODY).unwrap();- let oversized = write_skill(&root, "oversized", VALID_BODY);- set_file_len(&oversized, MAX_SKILL_FILE_BYTES + 1);- let canonical = std::fs::canonicalize(&root).unwrap();- let skills = scan_root(&canonical, "d");- let names: Vec<String> = skills.iter().map(|skill| skill.name.clone()).collect();- assert_eq!(names, vec!["sql-review", "sql-review"]);- assert_ne!(skills[0].id, skills[1].id);- assert!(skills.iter().all(|skill| skill.id.starts_with("d-")));- }-- #[test]- fn root_listing_reports_missing_and_invalid() {- let root = temp_skills_root("listing");- write_skill(&root, "alpha", VALID_BODY);- let missing = root_listing(&root.join("does-not-exist"), "d");- assert_eq!(missing.status, "missing");- assert!(missing.skills.is_empty());- let file_marker = root.join("plain-file.txt");- std::fs::write(&file_marker, "x").unwrap();- assert_eq!(root_listing(&file_marker, "d").status, "invalid");- assert_eq!(root_listing(&root, "d").status, "ok");- }-- #[test]- fn read_returns_full_content_and_enforces_the_one_mib_boundary() {- let root = temp_skills_root("read");- let exact = write_skill(&root, "exact", VALID_BODY);- set_file_len(&exact, MAX_SKILL_FILE_BYTES);- let toobig = write_skill(&root, "toobig", VALID_BODY);- set_file_len(&toobig, MAX_SKILL_FILE_BYTES + 1);- let canonical = std::fs::canonicalize(&root).unwrap();- let exact_skill = read_skill_from_root(&canonical, "d", &skill_id("d", "exact")).unwrap();- assert_eq!(exact_skill.name, "sql-review");- assert_eq!(exact_skill.content.len(), MAX_SKILL_FILE_BYTES as usize);- assert_eq!(read_skill_from_root(&canonical, "d", &skill_id("d", "toobig")).unwrap_err(), "oversized");- }-- #[test]- fn read_reports_not_found_for_missing_and_root_unavailable_for_disabled_roots() {- let root = temp_skills_root("missing");- let skill_dir = write_skill(&root, "gone", VALID_BODY);- let canonical = std::fs::canonicalize(&root).unwrap();- let id = skill_id("d", "gone");- assert!(read_skill_from_root(&canonical, "d", &id).is_ok());- std::fs::remove_dir_all(skill_dir).unwrap();- assert_eq!(read_skill_from_root(&canonical, "d", &id).unwrap_err(), "not_found");-- let custom = temp_skills_root("custom");- write_skill(&custom, "team", VALID_BODY);- let custom_id = skill_id("c", "team");- let disabled =- read_user_skills_blocking(std::slice::from_ref(&custom_id), false, Some(custom.to_str().unwrap()));- assert_eq!(disabled.failures.len(), 1);- assert_eq!(disabled.failures[0].reason, "root_unavailable");- let vanished = read_user_skills_blocking(&[custom_id], true, Some(custom.join("nope").to_str().unwrap()));- assert_eq!(vanished.failures[0].reason, "root_unavailable");- }-- #[test]- fn read_preserves_request_order_and_collects_failures() {- // Both roots are injected: a `d-` id resolved through the real home- // directory would make this test depend on the machine it runs on.- let root = temp_skills_root("order");- write_skill(&root, "keep", VALID_BODY);- std::fs::write(root.join("plain.txt"), "x").unwrap();- let canonical = std::fs::canonicalize(&root).unwrap();- let result = read_user_skills_from(- &["d-bogus".to_string(), skill_id("d", "keep"), skill_id("d", "never-existed")],- Some(&canonical),- None,- );- assert_eq!(result.skills.len(), 1);- assert_eq!(result.skills[0].id, skill_id("d", "keep"));- assert_eq!(result.failures.len(), 2);- assert_eq!(result.failures[0].id, "d-bogus");- assert_eq!(result.failures[0].reason, "not_found");- assert_eq!(result.failures[1].reason, "not_found");- }-- #[test]- fn read_skips_duplicate_ids() {- let root = temp_skills_root("dedupe");- write_skill(&root, "once", VALID_BODY);- let canonical = std::fs::canonicalize(&root).unwrap();- let id = skill_id("d", "once");- let result = read_user_skills_from(&[id.clone(), id.clone(), id], Some(&canonical), None);- assert_eq!(result.skills.len(), 1);- assert!(result.failures.is_empty());- // Deduplication must not swallow a failure: a repeated bad id is- // still reported exactly once.- let duplicated_bad = ["d-bogus".to_string(), "d-bogus".to_string()];- let failed = read_user_skills_from(&duplicated_bad, Some(&canonical), None);- assert!(failed.skills.is_empty());- assert_eq!(failed.failures.len(), 1);- assert_eq!(failed.failures[0].id, "d-bogus");- }-- #[test]- fn listing_omits_a_file_that_is_not_valid_utf8() {- let root = temp_skills_root("invalid-utf8");- let dir = root.join("broken");- std::fs::create_dir_all(&dir).unwrap();- let mut bytes = b"---\nname: br".to_vec();- bytes.push(0xFF);- bytes.extend_from_slice(b"oken\ndescription: desc\n---\n\nBody.\n");- std::fs::write(dir.join(SKILL_FILE_NAME), &bytes).unwrap();- let canonical = std::fs::canonicalize(&root).unwrap();- assert!(scan_root(&canonical, "d").is_empty());- assert_eq!(read_skill_from_root(&canonical, "d", &skill_id("d", "broken")).unwrap_err(), "not_utf8");- }-- #[test]- fn listing_tolerates_a_multibyte_character_cut_by_the_prefix_read() {- let root = temp_skills_root("prefix-cut");- let frontmatter = "---\nname: cut\ndescription: boundary\n---\n";- let mut body = String::from(frontmatter);- body.push_str(&"a".repeat(FRONTMATTER_SCAN_BYTES - frontmatter.len() - 1));- body.push('\u{e9}');- body.push_str(&"b".repeat(64));- write_skill(&root, "cut", &body);- let canonical = std::fs::canonicalize(&root).unwrap();- let skills = scan_root(&canonical, "d");- assert_eq!(skills.len(), 1);- assert_eq!(skills[0].name, "cut");- }-- #[cfg(unix)]- #[test]- fn symlink_policy_allows_inside_root_only() {- use std::os::unix::fs::symlink;- let root = temp_skills_root("links");- write_skill(&root, "real", VALID_BODY);- symlink(root.join("real"), root.join("inside")).unwrap();- let outside = temp_skills_root("outside");- write_skill(&outside, "escapee", VALID_BODY);- symlink(outside.join("escapee"), root.join("escape")).unwrap();- let canonical = std::fs::canonicalize(&root).unwrap();- let skills = scan_root(&canonical, "d");- let ids: Vec<String> = skills.iter().map(|skill| skill.id.clone()).collect();- assert!(ids.contains(&skill_id("d", "inside")));- assert!(!ids.contains(&skill_id("d", "escape")));- }-- #[cfg(unix)]- #[test]- fn skill_file_symlink_cannot_escape_the_root() {- use std::os::unix::fs::symlink;-- let root = temp_skills_root("file-link");- let escape_dir = write_skill(&root, "file-escape", VALID_BODY);- let outside = temp_skills_root("file-link-outside");- let outside_file = outside.join("SKILL.md");- std::fs::write(&outside_file, VALID_BODY).unwrap();- std::fs::remove_file(escape_dir.join(SKILL_FILE_NAME)).unwrap();- symlink(&outside_file, escape_dir.join(SKILL_FILE_NAME)).unwrap();-- let canonical = std::fs::canonicalize(&root).unwrap();- let id = skill_id("d", "file-escape");- assert!(!scan_root(&canonical, "d").iter().any(|skill| skill.id == id));- assert_eq!(read_skill_from_root(&canonical, "d", &id).unwrap_err(), REASON_NOT_FOUND);- }+ tauri::async_runtime::spawn_blocking(move || skills::read_skills(&ids, custom_root_enabled, custom_root.as_deref()))+ .await+ .map_err(|error| error.to_string())}