Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Split SkillsTree out of SkillsSidebarSection (PRD-7687) (#3115)
tim-inkeepfcba21cddca5
diff --git a/packages/app/src/components/SkillsSidebarSection.tsx b/packages/app/src/components/SkillsSidebarSection.tsxindex 28a426879..8d5783aea 100644--- a/packages/app/src/components/SkillsSidebarSection.tsx+++ b/packages/app/src/components/SkillsSidebarSection.tsx@@ -6,54 +6,15 @@ import {type SkillsListEntry,} from '@inkeep/open-knowledge-core';import { Trans, useLingui } from '@lingui/react/macro';-import { FILE_TREE_TAG_NAME, type FileTreeSortComparator } from '@pierre/trees';-import { useFileTree } from '@pierre/trees/react';-import { Compass, Loader2, Sparkles, SquarePen, Upload } from 'lucide-react';-import { __iconNode as lockIcon } from 'lucide-react/dist/esm/icons/lock';-import { __iconNode as packageIcon } from 'lucide-react/dist/esm/icons/package';-import { useTheme } from 'next-themes';-import { lazy, type ReactNode, Suspense, useEffect, useRef, useState } from 'react';+import { Loader2 } from 'lucide-react';+import { lazy, Suspense, useEffect, useState } from 'react';import { toast } from 'sonner';-import { AgentBrandIcon } from '@/components/AgentIconCluster';-import { createFileTreeStyle } from '@/components/file-tree-density';-import {- buildOkFileTreeOptions,- createLucideSpriteSymbol,- OK_FILE_TREE_READONLY_UNSAFE_CSS,-} from '@/components/file-tree-shared';import type { AddSkillTab } from '@/components/ImportSkillDialog';import { NewSkillDialog } from '@/components/NewSkillDialog';-import { OkFileTree } from '@/components/OkFileTree';-import {- INSTALL_EDITORS,- SKILL_INSTALL_MENU_WIDTH,- SkillInstallMenuItems,- useSkillHostToggles,-} from '@/components/SkillInstallMenu';-import {- type SkillActions,- SkillContextMenuItems,- SkillFileContextMenuItems,- useSkillActions,-} from '@/components/skill-actions';-import {- applyInstallClusters,- HOST_POOL_KEY_ATTR,- installPillFromEvent,- type RowInstallDecor,- SKILL_INSTALL_CLUSTER_CSS,-} from '@/components/skill-install-cluster';+import { EMPTY_SCOPE_SENTINEL, SkillsTree } from '@/components/SkillsTree';+import { useSkillActions } from '@/components/skill-actions';import { Button } from '@/components/ui/button';-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from '@/components/ui/dropdown-menu';import { SidebarGroup, SidebarGroupContent } from '@/components/ui/sidebar';-import { asDirectoryHandle } from '@/components/use-selection-mirror';import { useDocumentContext } from '@/editor/DocumentContext';import { findLocalSkillPreviewTabId } from '@/editor/editor-tabs';import { useCreateBlankSkill } from '@/hooks/use-create-blank-skill';@@ -72,12 +33,9 @@ import { subscribeToSkillsChanged } from '@/lib/documents-events';import { skillEntryFileLiveDocName, skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';import {SKILL_SCOPE_ORDER,- skillClusterHosts,+ skillDir,skillDisplayName,- skillEntryDirs,- skillHostRootDir,skillNameSetsByScope,- tildeHomePath,useSkillScopeDescriptions,useSkillScopeLabels,} from '@/lib/skill-scope';@@ -96,12 +54,6 @@ const ImportSkillDialog = lazy(() =>import('@/components/ImportSkillDialog').then((m) => ({ default: m.ImportSkillDialog })),);-/** A skill dir is the parent of its `SKILL.md`; the detected preview reads it as a local source. */-function skillDir(skillMdPath: string): string {- const i = skillMdPath.lastIndexOf('/');- return i > 0 ? skillMdPath.slice(0, i) : skillMdPath;-}-// OK's own core product skills — managing them with OK is circular, so they// never show as "Detected". Its shipped *packs* (`open-knowledge-pack-*`) are// fair game to adopt, so they are NOT excluded.@@ -111,97 +63,6 @@ const OK_OWN_SKILLS = new Set(['open-knowledge-write-skill',]);-// A scope with ZERO skills renders no child, and Pierre drops a childless-// directory from the visible tree — so the GLOBAL / PROJECT header would vanish-// and the sibling scope slides to the top (breaks "project always first" when the-// project has no skills). Give an empty scope ONE sentinel child so its folder +-// header always render in SKILL_SCOPE_ORDER. The sentinel row is display:none'd-// (SKILLS_TREE_CSS) and every row handler skips it (skillFor/detectedFor return-// undefined for it). Underscores can't appear in a real skill name (SKILL_NAME_REGEX),-// so it can't collide. Works WITH `flattenEmptyDirectories: false` — that keeps the-// resulting single-child folder from collapsing back into the sentinel.-const EMPTY_SCOPE_SENTINEL = '__ok_empty_scope__';--// Built-in skills are locked (bundled, read-only) — a lock glyph on the row is-// the "you can't edit this" signal, in place of a state badge. Registered as a-// sprite symbol the same way FileTree's link/agent decoration icons are.-const BUILTIN_LOCK_ICON_ID = 'ok-skills-builtin-lock-decoration';-// Plugin-cache residents get a package glyph — same "you can't edit this here"-// signal as the built-in lock, with the way out in the tooltip.-const PLUGIN_PACKAGE_ICON_ID = 'ok-skills-plugin-package-decoration';-const SKILLS_DECORATION_EXTRA_SYMBOLS =- createLucideSpriteSymbol(BUILTIN_LOCK_ICON_ID, lockIcon) +- createLucideSpriteSymbol(PLUGIN_PACKAGE_ICON_ID, packageIcon);--// Per-tree CSS (Pierre `unsafeCSS`):-// - Installed/Draft/Detected decoration badge: ~11px, right-aligned, never truncates.-// - Focus ring only on the SELECTED (open) row, not a merely-focused one.-// - Scope rows (top-level = aria-level 1): hidden folder icon + uppercase muted-// text, so GLOBAL / PROJECT read as section labels rather than plain folders.-const SKILLS_TREE_CSS = `- [data-item-section='decoration'] { flex: 1 0 auto; }- [data-item-section='decoration'] > span { max-width: none; font-size: 0.6875rem; }- [data-item-focused='true']:not([data-item-selected='true'])::before {- outline-color: transparent;- }- /* Never mid-word-break a skill name — long names truncate with an ellipsis- instead of wrapping into hyphenless fragments. */- [data-item-section='content'] {- white-space: nowrap;- overflow: hidden;- text-overflow: ellipsis;- word-break: normal;- }- /* Keep the icon section: for a folder it IS the disclosure chevron (rotates- open/closed) — the collapse affordance for GLOBAL / PROJECT. */- [aria-level='1'] [data-item-section='content'] {- text-transform: uppercase;- letter-spacing: 0.04em;- font-size: 0.75rem;- font-family: var(--font-mono);- /* Deliberately darker than the chevron's --trees-fg-muted: the label is- read, the twisty is only an affordance. Own declaration, so it also- survives the selected-state !important on the row below. */- color: var(--muted-foreground);- }- /* The disclosure chevron otherwise tints to Pierre's primary selected-fg when- the scope row is focused/selected — pin it muted in every state. */- [aria-level='1'] [data-item-section='icon'] { color: var(--trees-fg-muted) !important; }- /* Scope rows only expand — Pierre still selects them on click, but they must- never look selected: kill the selection background, the primary text/twisty- color, and the focus ring. (!important beats Pierre's selected-state rules.) */- [aria-level='1'][data-item-selected='true'] {- background-color: transparent !important;- color: var(--trees-fg-muted) !important;- }- [aria-level='1']::before { outline: none !important; }- /* Empty-scope sentinel child: structural only (forces the scope folder to- render); never shown to the user. */- [data-item-path$='/${EMPTY_SCOPE_SENTINEL}'] { display: none !important; }-`;--/** A tree path `<ScopeLabel>/<skillDisplay>/<sub…>` split into its parts. */-interface TreeNode {- scopeLabel: string;- /** undefined = the scope row itself (top level). */- skillDisplay: string | undefined;- /** path within the skill (SKILL.md, references/x, …); null = the skill folder. */- sub: string | null;- isDir: boolean;-}--function parseTreePath(treePath: string): TreeNode {- const isDir = treePath.endsWith('/');- const clean = isDir ? treePath.slice(0, -1) : treePath;- const parts = clean.split('/');- return {- scopeLabel: parts[0] ?? '',- skillDisplay: parts.length >= 2 ? parts[1] : undefined,- sub: parts.length >= 3 ? parts.slice(2).join('/') : null,- isDir,- };-}-/*** "Skills" section of the file sidebar — ONE `<OkFileTree>` (the same Pierre* component as the main file tree). GLOBAL / PROJECT are top-level folder rows@@ -745,623 +606,6 @@ export function SkillsSidebarSection({ skillsMode = false }: { skillsMode?: bool);}-/**- * The single Pierre tree. Remounted by the parent on path/state changes so it- * re-derives decorations; selection is synced imperatively (below) so opening a- * doc never remounts. Owns the decoration / context-menu / selection wiring for- * both managed and detected rows.- */-function SkillsTree({- paths,- activePath,- initialExpandedPaths,- onExpandedChange,- sort,- skillByPrefix,- detectedByPrefix,- labelToScope,- scopeDescription,- existingNames,- actions,- onOpenSkillMd,- onOpenFile,- onOpenDetected,- onOpenManaged,- onNewSkill,- onAddSkill,-}: {- paths: readonly string[];- activePath: string | undefined;- initialExpandedPaths: readonly string[];- /** Report live user-expanded folder paths to the parent so a remount can- * restore expansion (§2.7/§2.8). Called only when the set changes. */- onExpandedChange: (paths: ReadonlySet<string>) => void;- sort: FileTreeSortComparator;- skillByPrefix: Map<string, SkillsListEntry>;- detectedByPrefix: Map<string, CatalogSkill>;- labelToScope: Map<string, SkillScope>;- scopeDescription: Record<SkillScope, string>;- existingNames: Record<SkillScope, Set<string>>;- actions: SkillActions;- onOpenSkillMd: (skill: SkillsListEntry) => void;- onOpenFile: (skill: SkillsListEntry, filePath: string) => void;- onOpenDetected: (skill: CatalogSkill, sub?: string) => void;- onOpenManaged: (skill: SkillsListEntry) => void;- onNewSkill: (scope: SkillScope) => void;- onAddSkill: (scope: SkillScope, tab: AddSkillTab) => void;-}) {- const { t } = useLingui();- const { resolvedTheme } = useTheme();- const hostRef = useRef<HTMLDivElement | null>(null);- // Hidden light-DOM pool of brand icons the shadow-DOM injector clones from.- const iconPoolRef = useRef<HTMLDivElement | null>(null);- const [ready, setReady] = useState(false);- useEffect(() => setReady(true), []);- // Install pill → the per-agent install menu (a real Radix menu in the LIGHT- // DOM, anchored at the clicked pill's screen rect — Radix can't render into- // Pierre's shadow root).- const [installMenu, setInstallMenu] = useState<{- skill: SkillsListEntry;- x: number;- y: number;- } | null>(null);- // Re-inject clusters whenever any skill's host set changes: the tree only- // remounts on the installed/not-installed BIT (`stateKey`), so adding a host- // (1→2 agents) wouldn't otherwise refresh the icons. This signal in the- // injection effect's deps forces a re-run without a full remount.- const installSignal = [...skillByPrefix.values()]- .map((s) => `${s.name}:${[...s.hosts].sort().join(',')}`)- .join('|');- const prefixOf = (node: TreeNode): string | undefined =>- node.skillDisplay === undefined ? undefined : `${node.scopeLabel}/${node.skillDisplay}`;- const skillFor = (node: TreeNode): SkillsListEntry | undefined => {- const p = prefixOf(node);- return p === undefined ? undefined : skillByPrefix.get(p);- };- const detectedFor = (node: TreeNode): CatalogSkill | undefined => {- const p = prefixOf(node);- return p === undefined ? undefined : detectedByPrefix.get(p);- };- // Row hover-title = the skill's real on-disk LOCATION (§4.2/§4.4), replacing the- // default "Global/name" tree-path tooltip that gave a global skill no origin. A- // bundle-file row appends its file path. Detected rows keep the default (their- // "Detected in ~/.harness" badge already discloses the home). Built-ins are- // read-only projected copies (not in `.ok/skills`), so show their real projected- // SKILL.md dir from `absolutePath` rather than the derived store path.- const titleForPath = (treePath: string): string | null => {- const node = parseTreePath(treePath);- // Scope header row (no skill name) → no path tooltip: skills at either- // level live wherever their folder is (editor dirs or `.ok/skills`),- // so a single store dir would lie. The header's context-menu label- // carries the scope description instead.- if (node.skillDisplay === undefined) return null;- const d = detectedFor(node);- // Detected rows → the real harness path(s) it lives in, not "Global/name"- // (the meaningless tree path). Rendered at the ROW's scope so a project- // detection reads `.claude/skills/...`, not the user home `~/.`. A skill- // deduped across harnesses lists each.- if (d) {- const scope = labelToScope.get(node.scopeLabel) ?? 'global';- const paths = d.sourceHarnesses.map(- (h) => `${skillHostRootDir(h, scope)}/${node.skillDisplay}`,- );- return node.sub ? paths.map((p) => `${p}/${node.sub}`).join(', ') : paths.join(', ');- }- const skill = skillFor(node);- if (!skill) return null;- if (skill.managed) {- const base = skill.absolutePath ? tildeHomePath(skillDir(skill.absolutePath)) : null;- if (!base) return null;- return node.sub ? `${base}/${node.sub}` : base;- }- // EVERY path the skill occupies (canonical first, then per-host copies) —- // path-first disclosure so "where does this live / load from" needs no- // decoding of brand names. User symlinks are disclosed as links.- const labels = skillEntryDirs(skill).map((d) => {- const dir = node.sub ? `${d.dir}/${node.sub}` : d.dir;- return d.symlink ? t`${dir} (symlink)` : dir;- });- return labels.join(', ');- };- // Whether a row gets a context menu at all. Built-in (managed) skills are- // read-only — no mutate menu — and neither are their bundle files or nested- // folders. `renderContextMenu` returns null for exactly these; this predicate- // MUST mirror it (kept adjacent so they change together), and the hover `···`- // trigger is suppressed for rows where it is false (§2.1/§2.2).- const rowHasContextMenu = (node: TreeNode): boolean => {- const scope = labelToScope.get(node.scopeLabel);- if (!scope) return false;- if (node.skillDisplay === undefined) return true; // scope row → New / Upload / Explore- if (detectedFor(node)) return true; // detected → Edit- const skill = skillFor(node);- if (!skill) return false;- if (skill.managed) return false; // built-in = read-only (§2.1/§2.2)- return true; // skill row, SKILL.md, a bundle folder (New file), or a file- };- // Latest predicate for the shadow-root observer below, without re-subscribing- // the observer every render (its closure identity changes with `skills` /- // `detected`). Updated in an effect — never mutate a ref during render.- const rowHasContextMenuRef = useRef(rowHasContextMenu);- useEffect(() => {- rowHasContextMenuRef.current = rowHasContextMenu;- });- // Per-row install decoration for the imperative injector: an agent-icon cluster- // (installed → its editors; detected → its harnesses) or an Install pill- // (uninstalled). Built-ins return null (they keep the native lock decoration).- const poolKeyFor = (id: string): string =>- (INSTALL_EDITORS as readonly string[]).includes(id) ? id : 'generic';- const decorForPath = (treePath: string): RowInstallDecor => {- const node = parseTreePath(treePath);- if (node.skillDisplay === undefined || node.sub !== null) return null;- const d = detectedFor(node);- if (d) {- const scope = labelToScope.get(node.scopeLabel) ?? 'global';- return {- kind: 'icons',- poolKeys: d.sourceHarnesses.map(poolKeyFor),- title: t`Detected in ${d.sourceHarnesses.map((h) => skillHostRootDir(h, scope)).join(', ')}`,- };- }- const skill = skillFor(node);- if (!skill || skill.managed) return null;- // Editors first (brand icons), plus the `.agents` hub as a neutral mark —- // an in-place skill hosted only in `.agents` is loaded (by hub-reading- // harnesses), not uninstalled. Alias-covered VIEWERS (an editor whose- // skills folder is a symlink into a root holding this skill, e.g.- // `.codex/skills` → `.agents/skills`) ride the cluster too — they read- // the skill even though no location is theirs. `skillClusterHosts` IS the- // derivation the toolbar pill uses, so the two surfaces cannot disagree.- const hosts = skillClusterHosts(skill);- if (hosts.length > 0)- return {- kind: 'icons',- poolKeys: hosts.map(poolKeyFor),- title: t`Installed in ${hosts.map((h) => skillHostRootDir(h, skill.scope)).join(', ')}`,- };- return { kind: 'install', title: t`Install ${skill.name}` };- };- // Live inputs for the injection observer, which is set up once but must see the- // latest skills/theme/callbacks. Never mutate a ref during render.- const injectInputsRef = useRef({ decorForPath, skillFor, installLabel: t`Install` });- useEffect(() => {- injectInputsRef.current = { decorForPath, skillFor, installLabel: t`Install` };- });- // The tree does NOT remount when the active doc changes (remount key excludes- // `activePath` — see stateKey), so an inline `onSelectionChange` would close over a- // STALE `activePath` frozen at the tree's last mount and wrongly bail (or fail to- // bail) the "don't re-dispatch the already-active row" check. Keep the real handler- // in a ref reassigned every render (so it captures the LIVE `activePath` + open- // callbacks) and hand the tree a stable pass-through — the same pattern OkFileTree- // uses. Manual memo (useCallback) is banned, so the ref is how we stay current.- const handleSelectionChangeRef = useRef<(selected: readonly string[]) => void>(() => {});-- const { model } = useFileTree({- ...buildOkFileTreeOptions({- paths,- initialExpansion: 'closed',- initialExpandedPaths,- initialSelectedPaths: activePath ? [activePath] : undefined,- stickyFolders: false,- enableContextMenu: true,- unsafeCSS: `${OK_FILE_TREE_READONLY_UNSAFE_CSS}\n${SKILLS_TREE_CSS}\n${SKILL_INSTALL_CLUSTER_CSS}`,- extraSpriteSymbols: SKILLS_DECORATION_EXTRA_SYMBOLS,- renderRowDecoration: ({ item }) => {- const node = parseTreePath(item.path);- // Only a skill folder row (has a display name, no sub) gets a decoration.- if (node.skillDisplay === undefined || node.sub !== null) return null;- const skill = skillFor(node);- // Built-in skills are locked (bundled, read-only) — a lock glyph says- // "can't edit" more clearly than a text badge, and drops the confusing- // "Managed" wording. This is the ONLY native Pierre decoration left; the- // install-state marks (agent-icon cluster for installed/detected, an- // Install pill for uninstalled) are injected imperatively via- // `applyInstallClusters` below, because a multi-icon cluster + button- // can't fit Pierre's one-text-or-one-icon decoration slot.- if (skill?.managed) {- return { icon: BUILTIN_LOCK_ICON_ID, title: t`Built-in (read-only)` };- }- const det = detectedFor(node);- if (det?.provenance.plugin !== undefined) {- return {- icon: PLUGIN_PACKAGE_ICON_ID,- title: t`Part of the ${det.provenance.plugin} plugin — read-only; open it to edit a copy`,- };- }- return null;- },- }),- // Direct on the useFileTree object (NOT inside buildOkFileTreeOptions) so the- // React Compiler doesn't flag the ref read as happening during render. Routing- // only; the highlight is reconciled by the selection-sync effect below.- onSelectionChange: (selected) => handleSelectionChangeRef.current(selected),- sort,- // Pierre collapses single-child folder CHAINS by default, so a scope with- // exactly one skill flattens `Project/` into that skill and the scope header- // vanishes — inconsistent by skill count (0 or 2+ show it, 1 hides it) and it- // drops the header's New/Add menu. The project always carries the built-in- // `open-knowledge` skill, so "no custom skills" IS the one-child case. Disable- // flattening so GLOBAL / PROJECT (and each skill folder) always render.- flattenEmptyDirectories: false,- });-- // Reassigned every render so the pass-through handler above captures the LIVE- // `activePath` + open callbacks + `model` (declared just above). Manual memo is- // banned; the ref is how we stay current.- useEffect(() => {- handleSelectionChangeRef.current = (selected) => {- const p = selected[0];- if (!p || p === activePath) return;- const node = parseTreePath(p);- if (node.sub !== null && node.isDir) return;- const d = detectedFor(node);- if (d) {- // A detected skill row / SKILL.md / reference file opens the editable- // in-place buffer. The folder stays expanded via the selection-sync- // effect below (which re-expands on activePath change — the moment the- // async open lands, overriding Pierre's folder-click collapse).- onOpenDetected(d, node.sub ?? undefined);- return;- }- const skill = skillFor(node);- if (!skill) return;- if (node.sub === null || node.sub === SKILL_MD_PATH) {- // A built-in's SKILL.md opens the read-only preview; a managed skill's opens- // its editor. Reference files fall to openFile below.- (skill.managed ? onOpenManaged : onOpenSkillMd)(skill);- } else {- onOpenFile(skill, node.sub);- }- };- });-- // Snapshot which folders the user has expanded into the parent-owned- // `expandedRef`, so the parent can restore expansion when this tree remounts- // on a rename / install-state change (§2.7/§2.8). Pierre fires no expand event,- // so read `isExpanded()` on every model change. Folder inputs go through a ref- // so the subscription re-runs only on `model` change, not every render.- const folderInputsRef = useRef({- labelToScope,- skillByPrefix,- detectedByPrefix,- onExpandedChange,- });- useEffect(() => {- folderInputsRef.current = { labelToScope, skillByPrefix, detectedByPrefix, onExpandedChange };- });- const lastSentRef = useRef<ReadonlySet<string>>(new Set());- useEffect(() => {- const sync = () => {- const inputs = folderInputsRef.current;- const next = new Set<string>();- const check = (folderPath: string) => {- if (asDirectoryHandle(model.getItem(folderPath))?.isExpanded()) next.add(folderPath);- };- for (const label of inputs.labelToScope.keys()) check(`${label}/`);- for (const prefix of inputs.skillByPrefix.keys()) check(`${prefix}/`);- for (const prefix of inputs.detectedByPrefix.keys()) check(`${prefix}/`);- // Only notify the parent when the expanded set actually changed — `subscribe`- // fires on every model mutation, and a redundant setState would re-render.- const prev = lastSentRef.current;- if (prev.size === next.size && [...next].every((p) => prev.has(p))) return;- lastSentRef.current = next;- inputs.onExpandedChange(next);- };- sync();- return model.subscribe(sync);- }, [model]);-- // Selection = the open doc. Pierre selects folders on click (and folder-click- // opens SKILL.md), so re-assert selection + focus onto the actual open row —- // this also gives it the blue selected+focused ring. `focusPath` is internal- // focus, not DOM focus, so it doesn't steal from the editor.- useEffect(() => {- if (!ready) return;- for (const p of model.getSelectedPaths()) {- if (p !== activePath) model.getItem(p)?.deselect();- }- if (activePath) {- model.getItem(activePath)?.select();- model.focusPath(activePath);- // Keep the open skill's folder expanded. A detected-skill open is async- // (endpoint round-trip) and a folder-row click toggles the folder shut;- // this effect runs on activePath change (the moment the doc lands), so- // re-expanding here is what actually holds the folder open. Managed skills- // open synchronously — expanding their folder on open is harmless.- const node = parseTreePath(activePath);- if (node.skillDisplay !== undefined) {- asDirectoryHandle(model.getItem(`${node.scopeLabel}/${node.skillDisplay}/`))?.expand();- }- }- }, [ready, activePath, model]);-- // Restore ALL expected-expanded folders after a (re)mount. The tree remounts on- // any `paths` change — notably a detected skill lazy-loading its reference files- // when opened — and Pierre's `initialExpandedPaths` does not reliably re-open- // folders other than the active row's ancestors, so previously-open sibling- // folders collapsed. Keyed on `[ready, model]` so it fires once per (re)mount,- // never on a plain click: it re-asserts the parent's expected set (which already- // reflects the user's latest expand/collapse via `userExpanded`), so it can't- // fight a live user collapse. Read via ref to avoid re-running on the array's- // per-render identity change.- const expandedPathsRef = useRef(initialExpandedPaths);- useEffect(() => {- expandedPathsRef.current = initialExpandedPaths;- });- useEffect(() => {- if (!ready) return;- for (const p of expandedPathsRef.current) {- asDirectoryHandle(model.getItem(p))?.expand();- }- }, [ready, model]);-- // Suppress Pierre's floating `···` context-menu trigger for rows with no menu- // (built-in skills + their files) — otherwise it shows a button that does- // nothing (§2.1/§2.2). Pierre renders ONE floating anchor over the hovered- // row; watch the hover marker and toggle the anchor's visibility. Same- // shadow-root + signal as OkFileTree's title-stamp observer.- useEffect(() => {- if (!ready) return;- const shadow = hostRef.current?.querySelector(FILE_TREE_TAG_NAME)?.shadowRoot;- if (!shadow) return;- const sync = () => {- const anchor = shadow.querySelector<HTMLElement>('[data-type="context-menu-anchor"]');- if (!anchor) return;- const hoveredPath = shadow.querySelector<HTMLElement>(- '[data-item-context-hover="true"][data-item-path]',- )?.dataset.itemPath;- const suppress =- hoveredPath !== undefined && !rowHasContextMenuRef.current(parseTreePath(hoveredPath));- anchor.style.display = suppress ? 'none' : '';- };- sync();- const observer = new MutationObserver(sync);- observer.observe(shadow, {- subtree: true,- childList: true,- attributes: true,- attributeFilter: ['data-item-context-hover'],- });- return () => observer.disconnect();- }, [ready]);-- // Inject the install-state marks (agent-icon cluster / Install pill) into each- // skill row's decoration lane. A cluster + button can't fit Pierre's- // one-text-or-one-icon decoration slot, so it's hand-built here (same shadow- // observer pattern as the title stamp), cloning brand `<svg>`s from the hidden- // pool. The Install pill opens the skill so its toolbar install menu (the full- // per-agent picker) appears. `resolvedTheme` is a dep so the pool's re-colored- // icons re-clone on a light/dark flip. `installSignal` is an intentional re-run- // trigger — the effect reads live data through refs, so a host-set change isn't- // visible in the body, but we must re-inject when it changes.- // biome-ignore lint/correctness/useExhaustiveDependencies: installSignal is an intentional re-inject trigger (see comment above).- useEffect(() => {- if (!ready) return;- const shadow = hostRef.current?.querySelector(FILE_TREE_TAG_NAME)?.shadowRoot;- if (!shadow) return;- const run = () =>- applyInstallClusters(shadow, {- decorFor: (p) => injectInputsRef.current.decorForPath(p),- iconPool: iconPoolRef.current,- installLabel: injectInputsRef.current.installLabel,- version: resolvedTheme ?? 'light',- });- run();- const observer = new MutationObserver(run);- observer.observe(shadow, {- subtree: true,- childList: true,- attributes: true,- attributeFilter: ['data-item-path'],- });- // Capture phase so the pill opens the menu before Pierre's row selection.- const onClick = (e: Event) => {- const pill = installPillFromEvent(e.target);- if (!pill) return;- e.preventDefault();- e.stopPropagation();- const skill = injectInputsRef.current.skillFor(parseTreePath(pill.path));- if (skill) setInstallMenu({ skill, x: pill.rect.left, y: pill.rect.bottom });- };- shadow.addEventListener('click', onClick, true);- // No cluster-specific hint. The row already carries a native tooltip naming- // every path the skill occupies — strictly more than the cluster's roots —- // so a second, differently-styled bubble alongside it read as a glitch, and- // every other row in this tree explains itself through the native one.- // The cluster carries `role="img"` + `aria-label`, so screen readers get the- // install state as a name (an `aria-label` alone on a span would not).- return () => {- observer.disconnect();- shadow.removeEventListener('click', onClick, true);- };- }, [ready, resolvedTheme, installSignal]);-- return (- <>- {/* Hidden light-DOM pool: React renders the brand icons (real brand colors +- theme via TargetIcon), the shadow-DOM injector clones them into rows- where Tailwind/shadcn can't reach. `generic` covers the agent-agnostic- `~/.agents` dir and any harness without a brand mark. */}- <div- ref={iconPoolRef}- aria-hidden- style={{ position: 'absolute', width: 0, height: 0, overflow: 'hidden' }}- >- {INSTALL_EDITORS.map((id) => (- <span key={id} {...{ [HOST_POOL_KEY_ATTR]: id }}>- <AgentBrandIcon host={id} />- </span>- ))}- <span {...{ [HOST_POOL_KEY_ATTR]: 'generic' }}>- <Sparkles />- </span>- </div>- {/* The Install pill's per-agent menu — a real Radix menu in the light DOM,- anchored via a zero-size fixed trigger at the clicked pill's rect. */}- {installMenu ? (- <DropdownMenu- open- onOpenChange={(open) => {- if (!open) setInstallMenu(null);- }}- >- <DropdownMenuTrigger asChild>- <span- aria-hidden- style={{- position: 'fixed',- left: installMenu.x,- top: installMenu.y,- width: 0,- height: 0,- }}- />- </DropdownMenuTrigger>- <DropdownMenuContent align="start" className={SKILL_INSTALL_MENU_WIDTH}>- <SkillInstallMenuBody- skill={installMenu.skill}- actions={actions}- onRunStart={() => setInstallMenu(null)}- />- </DropdownMenuContent>- </DropdownMenu>- ) : null}- <OkFileTree- model={model}- hostRef={hostRef}- ready={ready}- className="min-h-0"- style={createFileTreeStyle(resolvedTheme)}- sizeToContent- titleForPath={titleForPath}- renderContextMenu={(item, context) => {- const node = parseTreePath(item.path);- if (!rowHasContextMenu(node)) return null;- const scope = labelToScope.get(node.scopeLabel);- if (!scope) return null;- let menuItems: ReactNode;- if (node.skillDisplay === undefined) {- // Scope row → scope description + New skill (creates a blank directly) /- // Upload / Explore (each opens the add-skill modal on its tab).- menuItems = (- <>- <DropdownMenuLabel className="max-w-56 whitespace-normal font-normal text-muted-foreground text-xs">- {scopeDescription[scope]}- </DropdownMenuLabel>- <DropdownMenuSeparator />- <DropdownMenuItem onSelect={() => onNewSkill(scope)}>- <SquarePen aria-hidden />- <Trans>New skill</Trans>- </DropdownMenuItem>- <DropdownMenuItem onSelect={() => onAddSkill(scope, 'upload')}>- <Upload aria-hidden />- <Trans>Upload skill</Trans>- </DropdownMenuItem>- <DropdownMenuItem onSelect={() => onAddSkill(scope, 'skills-sh')}>- <Compass aria-hidden />- <Trans>Explore skills</Trans>- </DropdownMenuItem>- </>- );- } else {- const d = detectedFor(node);- if (d) {- // Detected skill row → open the editable in-place buffer (same as- // clicking the row). No manage flow.- menuItems = (- <DropdownMenuItem onSelect={() => onOpenDetected(d)}>- <SquarePen aria-hidden />- <Trans>Edit</Trans>- </DropdownMenuItem>- );- } else {- const skill = skillFor(node);- if (!skill) return null;- if (skill.managed) return null; // managed built-in = read-only, no mutate menu- if (node.sub === null || node.sub === SKILL_MD_PATH) {- menuItems = (- <SkillContextMenuItems- skill={skill}- actions={actions}- existingNames={existingNames[skill.scope]}- />- );- } else if (node.isDir) {- // Every bundle dir offers New file seeded with its own path.- // `node.sub` is non-null here (the null case is handled above).- menuItems = (- <DropdownMenuItem- onSelect={() => actions.requestFileCreate(skill, `${node.sub}/`)}- >- <Trans>New file</Trans>- </DropdownMenuItem>- );- } else {- menuItems = (- <SkillFileContextMenuItems skill={skill} filePath={node.sub} actions={actions} />- );- }- }- }- return (- <DropdownMenu- open- modal={false}- onOpenChange={(open) => {- if (!open) context.close({ restoreFocus: false });- }}- >- <DropdownMenuTrigger asChild>- <span- aria-hidden="true"- data-file-tree-context-menu-root="true"- className="block size-px"- />- </DropdownMenuTrigger>- <DropdownMenuContent- sideOffset={0}- align="start"- data-file-tree-context-menu-root="true"- className="min-w-52"- >- {menuItems}- </DropdownMenuContent>- </DropdownMenu>- );- }}- />- </>- );-}--/**- * Install-menu body for the sidebar Install pill — resolves one skill's per-agent- * toggle state and renders the SHARED menu items (the exact menu the editor- * toolbar badge shows). Split into its own component because `useSkillHostToggles`- * is a hook that must mount only while a skill is selected.- */-function SkillInstallMenuBody({- skill,- actions,- onRunStart,-}: {- skill: SkillsListEntry;- actions: SkillActions;- /** Close the popover before a multi-location run starts: the rows are read- * from a disk scan that refetches mid-run, so leaving it open shows them flip- * and then settle, which reads as breakage. */- onRunStart: () => void;-}) {- const toggles = useSkillHostToggles(skill, actions);- return (- <SkillInstallMenuItems- toggles={toggles}- skill={skill}- onResolveFork={(editor) => actions.requestForkResolve(skill, editor)}- onRunStart={onRunStart}- />- );-}-/*** Local-only skills-are-hidden prompt. In local-only mode the whole `.ok/`* tree is git-ignored, so `.ok/skills/` (shareable content) can't be committeddiff --git a/packages/app/src/components/SkillsTree.tsx b/packages/app/src/components/SkillsTree.tsxnew file mode 100644index 000000000..0df68fcfa--- /dev/null+++ b/packages/app/src/components/SkillsTree.tsx@@ -0,0 +1,769 @@+/**+ * The Pierre `<OkFileTree>` half of the Skills sidebar, split out of+ * `SkillsSidebarSection.tsx`. The section owns data loading, dialogs and the+ * section chrome, and hands this everything it needs as props.+ *+ * `EMPTY_SCOPE_SENTINEL` lives here because `SKILLS_TREE_CSS` interpolates it;+ * the section imports it back, so the dependency runs section -> tree only.+ */+import type { CatalogSkill, SkillScope, SkillsListEntry } from '@inkeep/open-knowledge-core';+import { Trans, useLingui } from '@lingui/react/macro';+import { FILE_TREE_TAG_NAME, type FileTreeSortComparator } from '@pierre/trees';+import { useFileTree } from '@pierre/trees/react';+import { Compass, Sparkles, SquarePen, Upload } from 'lucide-react';+import { __iconNode as lockIcon } from 'lucide-react/dist/esm/icons/lock';+import { __iconNode as packageIcon } from 'lucide-react/dist/esm/icons/package';+import { useTheme } from 'next-themes';+import { type ReactNode, useEffect, useRef, useState } from 'react';+import { AgentBrandIcon } from '@/components/AgentIconCluster';+import { createFileTreeStyle } from '@/components/file-tree-density';+import {+ buildOkFileTreeOptions,+ createLucideSpriteSymbol,+ OK_FILE_TREE_READONLY_UNSAFE_CSS,+} from '@/components/file-tree-shared';+import type { AddSkillTab } from '@/components/ImportSkillDialog';+import { OkFileTree } from '@/components/OkFileTree';+import {+ INSTALL_EDITORS,+ SKILL_INSTALL_MENU_WIDTH,+ SkillInstallMenuItems,+ useSkillHostToggles,+} from '@/components/SkillInstallMenu';+import {+ type SkillActions,+ SkillContextMenuItems,+ SkillFileContextMenuItems,+} from '@/components/skill-actions';+import {+ applyInstallClusters,+ HOST_POOL_KEY_ATTR,+ installPillFromEvent,+ type RowInstallDecor,+ SKILL_INSTALL_CLUSTER_CSS,+} from '@/components/skill-install-cluster';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { asDirectoryHandle } from '@/components/use-selection-mirror';+import {+ skillClusterHosts,+ skillDir,+ skillEntryDirs,+ skillHostRootDir,+ tildeHomePath,+} from '@/lib/skill-scope';+import { SKILL_MD_PATH } from '@/lib/skill-sort';++// A scope with ZERO skills renders no child, and Pierre drops a childless+// directory from the visible tree — so the GLOBAL / PROJECT header would vanish+// and the sibling scope slides to the top (breaks "project always first" when the+// project has no skills). Give an empty scope ONE sentinel child so its folder ++// header always render in SKILL_SCOPE_ORDER. The sentinel row is display:none'd+// (SKILLS_TREE_CSS) and every row handler skips it (skillFor/detectedFor return+// undefined for it). Underscores can't appear in a real skill name (SKILL_NAME_REGEX),+// so it can't collide. Works WITH `flattenEmptyDirectories: false` — that keeps the+// resulting single-child folder from collapsing back into the sentinel.+export const EMPTY_SCOPE_SENTINEL = '__ok_empty_scope__';++// Built-in skills are locked (bundled, read-only) — a lock glyph on the row is+// the "you can't edit this" signal, in place of a state badge. Registered as a+// sprite symbol the same way FileTree's link/agent decoration icons are.+const BUILTIN_LOCK_ICON_ID = 'ok-skills-builtin-lock-decoration';+// Plugin-cache residents get a package glyph — same "you can't edit this here"+// signal as the built-in lock, with the way out in the tooltip.+const PLUGIN_PACKAGE_ICON_ID = 'ok-skills-plugin-package-decoration';+const SKILLS_DECORATION_EXTRA_SYMBOLS =+ createLucideSpriteSymbol(BUILTIN_LOCK_ICON_ID, lockIcon) ++ createLucideSpriteSymbol(PLUGIN_PACKAGE_ICON_ID, packageIcon);++// Per-tree CSS (Pierre `unsafeCSS`):+// - Installed/Draft/Detected decoration badge: ~11px, right-aligned, never truncates.+// - Focus ring only on the SELECTED (open) row, not a merely-focused one.+// - Scope rows (top-level = aria-level 1): hidden folder icon + uppercase muted+// text, so GLOBAL / PROJECT read as section labels rather than plain folders.+const SKILLS_TREE_CSS = `+ [data-item-section='decoration'] { flex: 1 0 auto; }+ [data-item-section='decoration'] > span { max-width: none; font-size: 0.6875rem; }+ [data-item-focused='true']:not([data-item-selected='true'])::before {+ outline-color: transparent;+ }+ /* Never mid-word-break a skill name — long names truncate with an ellipsis+ instead of wrapping into hyphenless fragments. */+ [data-item-section='content'] {+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ word-break: normal;+ }+ /* Keep the icon section: for a folder it IS the disclosure chevron (rotates+ open/closed) — the collapse affordance for GLOBAL / PROJECT. */+ [aria-level='1'] [data-item-section='content'] {+ text-transform: uppercase;+ letter-spacing: 0.04em;+ font-size: 0.75rem;+ font-family: var(--font-mono);+ /* Deliberately darker than the chevron's --trees-fg-muted: the label is+ read, the twisty is only an affordance. Own declaration, so it also+ survives the selected-state !important on the row below. */+ color: var(--muted-foreground);+ }+ /* The disclosure chevron otherwise tints to Pierre's primary selected-fg when+ the scope row is focused/selected — pin it muted in every state. */+ [aria-level='1'] [data-item-section='icon'] { color: var(--trees-fg-muted) !important; }+ /* Scope rows only expand — Pierre still selects them on click, but they must+ never look selected: kill the selection background, the primary text/twisty+ color, and the focus ring. (!important beats Pierre's selected-state rules.) */+ [aria-level='1'][data-item-selected='true'] {+ background-color: transparent !important;+ color: var(--trees-fg-muted) !important;+ }+ [aria-level='1']::before { outline: none !important; }+ /* Empty-scope sentinel child: structural only (forces the scope folder to+ render); never shown to the user. */+ [data-item-path$='/${EMPTY_SCOPE_SENTINEL}'] { display: none !important; }+`;++/** A tree path `<ScopeLabel>/<skillDisplay>/<sub…>` split into its parts. */+interface TreeNode {+ scopeLabel: string;+ /** undefined = the scope row itself (top level). */+ skillDisplay: string | undefined;+ /** path within the skill (SKILL.md, references/x, …); null = the skill folder. */+ sub: string | null;+ isDir: boolean;+}++function parseTreePath(treePath: string): TreeNode {+ const isDir = treePath.endsWith('/');+ const clean = isDir ? treePath.slice(0, -1) : treePath;+ const parts = clean.split('/');+ return {+ scopeLabel: parts[0] ?? '',+ skillDisplay: parts.length >= 2 ? parts[1] : undefined,+ sub: parts.length >= 3 ? parts.slice(2).join('/') : null,+ isDir,+ };+}++/**+ * The single Pierre tree. Remounted by the parent on path/state changes so it+ * re-derives decorations; selection is synced imperatively (below) so opening a+ * doc never remounts. Owns the decoration / context-menu / selection wiring for+ * both managed and detected rows.+ */+export function SkillsTree({+ paths,+ activePath,+ initialExpandedPaths,+ onExpandedChange,+ sort,+ skillByPrefix,+ detectedByPrefix,+ labelToScope,+ scopeDescription,+ existingNames,+ actions,+ onOpenSkillMd,+ onOpenFile,+ onOpenDetected,+ onOpenManaged,+ onNewSkill,+ onAddSkill,+}: {+ paths: readonly string[];+ activePath: string | undefined;+ initialExpandedPaths: readonly string[];+ /** Report live user-expanded folder paths to the parent so a remount can+ * restore expansion (§2.7/§2.8). Called only when the set changes. */+ onExpandedChange: (paths: ReadonlySet<string>) => void;+ sort: FileTreeSortComparator;+ skillByPrefix: Map<string, SkillsListEntry>;+ detectedByPrefix: Map<string, CatalogSkill>;+ labelToScope: Map<string, SkillScope>;+ scopeDescription: Record<SkillScope, string>;+ existingNames: Record<SkillScope, Set<string>>;+ actions: SkillActions;+ onOpenSkillMd: (skill: SkillsListEntry) => void;+ onOpenFile: (skill: SkillsListEntry, filePath: string) => void;+ onOpenDetected: (skill: CatalogSkill, sub?: string) => void;+ onOpenManaged: (skill: SkillsListEntry) => void;+ onNewSkill: (scope: SkillScope) => void;+ onAddSkill: (scope: SkillScope, tab: AddSkillTab) => void;+}) {+ const { t } = useLingui();+ const { resolvedTheme } = useTheme();+ const hostRef = useRef<HTMLDivElement | null>(null);+ // Hidden light-DOM pool of brand icons the shadow-DOM injector clones from.+ const iconPoolRef = useRef<HTMLDivElement | null>(null);+ const [ready, setReady] = useState(false);+ useEffect(() => setReady(true), []);+ // Install pill → the per-agent install menu (a real Radix menu in the LIGHT+ // DOM, anchored at the clicked pill's screen rect — Radix can't render into+ // Pierre's shadow root).+ const [installMenu, setInstallMenu] = useState<{+ skill: SkillsListEntry;+ x: number;+ y: number;+ } | null>(null);+ // Re-inject clusters whenever any skill's host set changes: the tree only+ // remounts on the installed/not-installed BIT (`stateKey`), so adding a host+ // (1→2 agents) wouldn't otherwise refresh the icons. This signal in the+ // injection effect's deps forces a re-run without a full remount.+ const installSignal = [...skillByPrefix.values()]+ .map((s) => `${s.name}:${[...s.hosts].sort().join(',')}`)+ .join('|');+ const prefixOf = (node: TreeNode): string | undefined =>+ node.skillDisplay === undefined ? undefined : `${node.scopeLabel}/${node.skillDisplay}`;+ const skillFor = (node: TreeNode): SkillsListEntry | undefined => {+ const p = prefixOf(node);+ return p === undefined ? undefined : skillByPrefix.get(p);+ };+ const detectedFor = (node: TreeNode): CatalogSkill | undefined => {+ const p = prefixOf(node);+ return p === undefined ? undefined : detectedByPrefix.get(p);+ };+ // Row hover-title = the skill's real on-disk LOCATION (§4.2/§4.4), replacing the+ // default "Global/name" tree-path tooltip that gave a global skill no origin. A+ // bundle-file row appends its file path. Detected rows keep the default (their+ // "Detected in ~/.harness" badge already discloses the home). Built-ins are+ // read-only projected copies (not in `.ok/skills`), so show their real projected+ // SKILL.md dir from `absolutePath` rather than the derived store path.+ const titleForPath = (treePath: string): string | null => {+ const node = parseTreePath(treePath);+ // Scope header row (no skill name) → no path tooltip: skills at either+ // level live wherever their folder is (editor dirs or `.ok/skills`),+ // so a single store dir would lie. The header's context-menu label+ // carries the scope description instead.+ if (node.skillDisplay === undefined) return null;+ const d = detectedFor(node);+ // Detected rows → the real harness path(s) it lives in, not "Global/name"+ // (the meaningless tree path). Rendered at the ROW's scope so a project+ // detection reads `.claude/skills/...`, not the user home `~/.`. A skill+ // deduped across harnesses lists each.+ if (d) {+ const scope = labelToScope.get(node.scopeLabel) ?? 'global';+ const paths = d.sourceHarnesses.map(+ (h) => `${skillHostRootDir(h, scope)}/${node.skillDisplay}`,+ );+ return node.sub ? paths.map((p) => `${p}/${node.sub}`).join(', ') : paths.join(', ');+ }+ const skill = skillFor(node);+ if (!skill) return null;+ if (skill.managed) {+ const base = skill.absolutePath ? tildeHomePath(skillDir(skill.absolutePath)) : null;+ if (!base) return null;+ return node.sub ? `${base}/${node.sub}` : base;+ }+ // EVERY path the skill occupies (canonical first, then per-host copies) —+ // path-first disclosure so "where does this live / load from" needs no+ // decoding of brand names. User symlinks are disclosed as links.+ const labels = skillEntryDirs(skill).map((d) => {+ const dir = node.sub ? `${d.dir}/${node.sub}` : d.dir;+ return d.symlink ? t`${dir} (symlink)` : dir;+ });+ return labels.join(', ');+ };+ // Whether a row gets a context menu at all. Built-in (managed) skills are+ // read-only — no mutate menu — and neither are their bundle files or nested+ // folders. `renderContextMenu` returns null for exactly these; this predicate+ // MUST mirror it (kept adjacent so they change together), and the hover `···`+ // trigger is suppressed for rows where it is false (§2.1/§2.2).+ const rowHasContextMenu = (node: TreeNode): boolean => {+ const scope = labelToScope.get(node.scopeLabel);+ if (!scope) return false;+ if (node.skillDisplay === undefined) return true; // scope row → New / Upload / Explore+ if (detectedFor(node)) return true; // detected → Edit+ const skill = skillFor(node);+ if (!skill) return false;+ if (skill.managed) return false; // built-in = read-only (§2.1/§2.2)+ return true; // skill row, SKILL.md, a bundle folder (New file), or a file+ };+ // Latest predicate for the shadow-root observer below, without re-subscribing+ // the observer every render (its closure identity changes with `skills` /+ // `detected`). Updated in an effect — never mutate a ref during render.+ const rowHasContextMenuRef = useRef(rowHasContextMenu);+ useEffect(() => {+ rowHasContextMenuRef.current = rowHasContextMenu;+ });+ // Per-row install decoration for the imperative injector: an agent-icon cluster+ // (installed → its editors; detected → its harnesses) or an Install pill+ // (uninstalled). Built-ins return null (they keep the native lock decoration).+ const poolKeyFor = (id: string): string =>+ (INSTALL_EDITORS as readonly string[]).includes(id) ? id : 'generic';+ const decorForPath = (treePath: string): RowInstallDecor => {+ const node = parseTreePath(treePath);+ if (node.skillDisplay === undefined || node.sub !== null) return null;+ const d = detectedFor(node);+ if (d) {+ const scope = labelToScope.get(node.scopeLabel) ?? 'global';+ return {+ kind: 'icons',+ poolKeys: d.sourceHarnesses.map(poolKeyFor),+ title: t`Detected in ${d.sourceHarnesses.map((h) => skillHostRootDir(h, scope)).join(', ')}`,+ };+ }+ const skill = skillFor(node);+ if (!skill || skill.managed) return null;+ // Editors first (brand icons), plus the `.agents` hub as a neutral mark —+ // an in-place skill hosted only in `.agents` is loaded (by hub-reading+ // harnesses), not uninstalled. Alias-covered VIEWERS (an editor whose+ // skills folder is a symlink into a root holding this skill, e.g.+ // `.codex/skills` → `.agents/skills`) ride the cluster too — they read+ // the skill even though no location is theirs. `skillClusterHosts` IS the+ // derivation the toolbar pill uses, so the two surfaces cannot disagree.+ const hosts = skillClusterHosts(skill);+ if (hosts.length > 0)+ return {+ kind: 'icons',+ poolKeys: hosts.map(poolKeyFor),+ title: t`Installed in ${hosts.map((h) => skillHostRootDir(h, skill.scope)).join(', ')}`,+ };+ return { kind: 'install', title: t`Install ${skill.name}` };+ };+ // Live inputs for the injection observer, which is set up once but must see the+ // latest skills/theme/callbacks. Never mutate a ref during render.+ const injectInputsRef = useRef({ decorForPath, skillFor, installLabel: t`Install` });+ useEffect(() => {+ injectInputsRef.current = { decorForPath, skillFor, installLabel: t`Install` };+ });+ // The tree does NOT remount when the active doc changes (remount key excludes+ // `activePath` — see stateKey), so an inline `onSelectionChange` would close over a+ // STALE `activePath` frozen at the tree's last mount and wrongly bail (or fail to+ // bail) the "don't re-dispatch the already-active row" check. Keep the real handler+ // in a ref reassigned every render (so it captures the LIVE `activePath` + open+ // callbacks) and hand the tree a stable pass-through — the same pattern OkFileTree+ // uses. Manual memo (useCallback) is banned, so the ref is how we stay current.+ const handleSelectionChangeRef = useRef<(selected: readonly string[]) => void>(() => {});++ const { model } = useFileTree({+ ...buildOkFileTreeOptions({+ paths,+ initialExpansion: 'closed',+ initialExpandedPaths,+ initialSelectedPaths: activePath ? [activePath] : undefined,+ stickyFolders: false,+ enableContextMenu: true,+ unsafeCSS: `${OK_FILE_TREE_READONLY_UNSAFE_CSS}\n${SKILLS_TREE_CSS}\n${SKILL_INSTALL_CLUSTER_CSS}`,+ extraSpriteSymbols: SKILLS_DECORATION_EXTRA_SYMBOLS,+ renderRowDecoration: ({ item }) => {+ const node = parseTreePath(item.path);+ // Only a skill folder row (has a display name, no sub) gets a decoration.+ if (node.skillDisplay === undefined || node.sub !== null) return null;+ const skill = skillFor(node);+ // Built-in skills are locked (bundled, read-only) — a lock glyph says+ // "can't edit" more clearly than a text badge, and drops the confusing+ // "Managed" wording. This is the ONLY native Pierre decoration left; the+ // install-state marks (agent-icon cluster for installed/detected, an+ // Install pill for uninstalled) are injected imperatively via+ // `applyInstallClusters` below, because a multi-icon cluster + button+ // can't fit Pierre's one-text-or-one-icon decoration slot.+ if (skill?.managed) {+ return { icon: BUILTIN_LOCK_ICON_ID, title: t`Built-in (read-only)` };+ }+ const det = detectedFor(node);+ if (det?.provenance.plugin !== undefined) {+ return {+ icon: PLUGIN_PACKAGE_ICON_ID,+ title: t`Part of the ${det.provenance.plugin} plugin — read-only; open it to edit a copy`,+ };+ }+ return null;+ },+ }),+ // Direct on the useFileTree object (NOT inside buildOkFileTreeOptions) so the+ // React Compiler doesn't flag the ref read as happening during render. Routing+ // only; the highlight is reconciled by the selection-sync effect below.+ onSelectionChange: (selected) => handleSelectionChangeRef.current(selected),+ sort,+ // Pierre collapses single-child folder CHAINS by default, so a scope with+ // exactly one skill flattens `Project/` into that skill and the scope header+ // vanishes — inconsistent by skill count (0 or 2+ show it, 1 hides it) and it+ // drops the header's New/Add menu. The project always carries the built-in+ // `open-knowledge` skill, so "no custom skills" IS the one-child case. Disable+ // flattening so GLOBAL / PROJECT (and each skill folder) always render.+ flattenEmptyDirectories: false,+ });++ // Reassigned every render so the pass-through handler above captures the LIVE+ // `activePath` + open callbacks + `model` (declared just above). Manual memo is+ // banned; the ref is how we stay current.+ useEffect(() => {+ handleSelectionChangeRef.current = (selected) => {+ const p = selected[0];+ if (!p || p === activePath) return;+ const node = parseTreePath(p);+ if (node.sub !== null && node.isDir) return;+ const d = detectedFor(node);+ if (d) {+ // A detected skill row / SKILL.md / reference file opens the editable+ // in-place buffer. The folder stays expanded via the selection-sync+ // effect below (which re-expands on activePath change — the moment the+ // async open lands, overriding Pierre's folder-click collapse).+ onOpenDetected(d, node.sub ?? undefined);+ return;+ }+ const skill = skillFor(node);+ if (!skill) return;+ if (node.sub === null || node.sub === SKILL_MD_PATH) {+ // A built-in's SKILL.md opens the read-only preview; a managed skill's opens+ // its editor. Reference files fall to openFile below.+ (skill.managed ? onOpenManaged : onOpenSkillMd)(skill);+ } else {+ onOpenFile(skill, node.sub);+ }+ };+ });++ // Snapshot which folders the user has expanded into the parent-owned+ // `expandedRef`, so the parent can restore expansion when this tree remounts+ // on a rename / install-state change (§2.7/§2.8). Pierre fires no expand event,+ // so read `isExpanded()` on every model change. Folder inputs go through a ref+ // so the subscription re-runs only on `model` change, not every render.+ const folderInputsRef = useRef({+ labelToScope,+ skillByPrefix,+ detectedByPrefix,+ onExpandedChange,+ });+ useEffect(() => {+ folderInputsRef.current = { labelToScope, skillByPrefix, detectedByPrefix, onExpandedChange };+ });+ const lastSentRef = useRef<ReadonlySet<string>>(new Set());+ useEffect(() => {+ const sync = () => {+ const inputs = folderInputsRef.current;+ const next = new Set<string>();+ const check = (folderPath: string) => {+ if (asDirectoryHandle(model.getItem(folderPath))?.isExpanded()) next.add(folderPath);+ };+ for (const label of inputs.labelToScope.keys()) check(`${label}/`);+ for (const prefix of inputs.skillByPrefix.keys()) check(`${prefix}/`);+ for (const prefix of inputs.detectedByPrefix.keys()) check(`${prefix}/`);+ // Only notify the parent when the expanded set actually changed — `subscribe`+ // fires on every model mutation, and a redundant setState would re-render.+ const prev = lastSentRef.current;+ if (prev.size === next.size && [...next].every((p) => prev.has(p))) return;+ lastSentRef.current = next;+ inputs.onExpandedChange(next);+ };+ sync();+ return model.subscribe(sync);+ }, [model]);++ // Selection = the open doc. Pierre selects folders on click (and folder-click+ // opens SKILL.md), so re-assert selection + focus onto the actual open row —+ // this also gives it the blue selected+focused ring. `focusPath` is internal+ // focus, not DOM focus, so it doesn't steal from the editor.+ useEffect(() => {+ if (!ready) return;+ for (const p of model.getSelectedPaths()) {+ if (p !== activePath) model.getItem(p)?.deselect();+ }+ if (activePath) {+ model.getItem(activePath)?.select();+ model.focusPath(activePath);+ // Keep the open skill's folder expanded. A detected-skill open is async+ // (endpoint round-trip) and a folder-row click toggles the folder shut;+ // this effect runs on activePath change (the moment the doc lands), so+ // re-expanding here is what actually holds the folder open. Managed skills+ // open synchronously — expanding their folder on open is harmless.+ const node = parseTreePath(activePath);+ if (node.skillDisplay !== undefined) {+ asDirectoryHandle(model.getItem(`${node.scopeLabel}/${node.skillDisplay}/`))?.expand();+ }+ }+ }, [ready, activePath, model]);++ // Restore ALL expected-expanded folders after a (re)mount. The tree remounts on+ // any `paths` change — notably a detected skill lazy-loading its reference files+ // when opened — and Pierre's `initialExpandedPaths` does not reliably re-open+ // folders other than the active row's ancestors, so previously-open sibling+ // folders collapsed. Keyed on `[ready, model]` so it fires once per (re)mount,+ // never on a plain click: it re-asserts the parent's expected set (which already+ // reflects the user's latest expand/collapse via `userExpanded`), so it can't+ // fight a live user collapse. Read via ref to avoid re-running on the array's+ // per-render identity change.+ const expandedPathsRef = useRef(initialExpandedPaths);+ useEffect(() => {+ expandedPathsRef.current = initialExpandedPaths;+ });+ useEffect(() => {+ if (!ready) return;+ for (const p of expandedPathsRef.current) {+ asDirectoryHandle(model.getItem(p))?.expand();+ }+ }, [ready, model]);++ // Suppress Pierre's floating `···` context-menu trigger for rows with no menu+ // (built-in skills + their files) — otherwise it shows a button that does+ // nothing (§2.1/§2.2). Pierre renders ONE floating anchor over the hovered+ // row; watch the hover marker and toggle the anchor's visibility. Same+ // shadow-root + signal as OkFileTree's title-stamp observer.+ useEffect(() => {+ if (!ready) return;+ const shadow = hostRef.current?.querySelector(FILE_TREE_TAG_NAME)?.shadowRoot;+ if (!shadow) return;+ const sync = () => {+ const anchor = shadow.querySelector<HTMLElement>('[data-type="context-menu-anchor"]');+ if (!anchor) return;+ const hoveredPath = shadow.querySelector<HTMLElement>(+ '[data-item-context-hover="true"][data-item-path]',+ )?.dataset.itemPath;+ const suppress =+ hoveredPath !== undefined && !rowHasContextMenuRef.current(parseTreePath(hoveredPath));+ anchor.style.display = suppress ? 'none' : '';+ };+ sync();+ const observer = new MutationObserver(sync);+ observer.observe(shadow, {+ subtree: true,+ childList: true,+ attributes: true,+ attributeFilter: ['data-item-context-hover'],+ });+ return () => observer.disconnect();+ }, [ready]);++ // Inject the install-state marks (agent-icon cluster / Install pill) into each+ // skill row's decoration lane. A cluster + button can't fit Pierre's+ // one-text-or-one-icon decoration slot, so it's hand-built here (same shadow+ // observer pattern as the title stamp), cloning brand `<svg>`s from the hidden+ // pool. The Install pill opens the skill so its toolbar install menu (the full+ // per-agent picker) appears. `resolvedTheme` is a dep so the pool's re-colored+ // icons re-clone on a light/dark flip. `installSignal` is an intentional re-run+ // trigger — the effect reads live data through refs, so a host-set change isn't+ // visible in the body, but we must re-inject when it changes.+ // biome-ignore lint/correctness/useExhaustiveDependencies: installSignal is an intentional re-inject trigger (see comment above).+ useEffect(() => {+ if (!ready) return;+ const shadow = hostRef.current?.querySelector(FILE_TREE_TAG_NAME)?.shadowRoot;+ if (!shadow) return;+ const run = () =>+ applyInstallClusters(shadow, {+ decorFor: (p) => injectInputsRef.current.decorForPath(p),+ iconPool: iconPoolRef.current,+ installLabel: injectInputsRef.current.installLabel,+ version: resolvedTheme ?? 'light',+ });+ run();+ const observer = new MutationObserver(run);+ observer.observe(shadow, {+ subtree: true,+ childList: true,+ attributes: true,+ attributeFilter: ['data-item-path'],+ });+ // Capture phase so the pill opens the menu before Pierre's row selection.+ const onClick = (e: Event) => {+ const pill = installPillFromEvent(e.target);+ if (!pill) return;+ e.preventDefault();+ e.stopPropagation();+ const skill = injectInputsRef.current.skillFor(parseTreePath(pill.path));+ if (skill) setInstallMenu({ skill, x: pill.rect.left, y: pill.rect.bottom });+ };+ shadow.addEventListener('click', onClick, true);+ // No cluster-specific hint. The row already carries a native tooltip naming+ // every path the skill occupies — strictly more than the cluster's roots —+ // so a second, differently-styled bubble alongside it read as a glitch, and+ // every other row in this tree explains itself through the native one.+ // The cluster carries `role="img"` + `aria-label`, so screen readers get the+ // install state as a name (an `aria-label` alone on a span would not).+ return () => {+ observer.disconnect();+ shadow.removeEventListener('click', onClick, true);+ };+ }, [ready, resolvedTheme, installSignal]);++ return (+ <>+ {/* Hidden light-DOM pool: React renders the brand icons (real brand colors ++ theme via TargetIcon), the shadow-DOM injector clones them into rows+ where Tailwind/shadcn can't reach. `generic` covers the agent-agnostic+ `~/.agents` dir and any harness without a brand mark. */}+ <div+ ref={iconPoolRef}+ aria-hidden+ style={{ position: 'absolute', width: 0, height: 0, overflow: 'hidden' }}+ >+ {INSTALL_EDITORS.map((id) => (+ <span key={id} {...{ [HOST_POOL_KEY_ATTR]: id }}>+ <AgentBrandIcon host={id} />+ </span>+ ))}+ <span {...{ [HOST_POOL_KEY_ATTR]: 'generic' }}>+ <Sparkles />+ </span>+ </div>+ {/* The Install pill's per-agent menu — a real Radix menu in the light DOM,+ anchored via a zero-size fixed trigger at the clicked pill's rect. */}+ {installMenu ? (+ <DropdownMenu+ open+ onOpenChange={(open) => {+ if (!open) setInstallMenu(null);+ }}+ >+ <DropdownMenuTrigger asChild>+ <span+ aria-hidden+ style={{+ position: 'fixed',+ left: installMenu.x,+ top: installMenu.y,+ width: 0,+ height: 0,+ }}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className={SKILL_INSTALL_MENU_WIDTH}>+ <SkillInstallMenuBody+ skill={installMenu.skill}+ actions={actions}+ onRunStart={() => setInstallMenu(null)}+ />+ </DropdownMenuContent>+ </DropdownMenu>+ ) : null}+ <OkFileTree+ model={model}+ hostRef={hostRef}+ ready={ready}+ className="min-h-0"+ style={createFileTreeStyle(resolvedTheme)}+ sizeToContent+ titleForPath={titleForPath}+ renderContextMenu={(item, context) => {+ const node = parseTreePath(item.path);+ if (!rowHasContextMenu(node)) return null;+ const scope = labelToScope.get(node.scopeLabel);+ if (!scope) return null;+ let menuItems: ReactNode;+ if (node.skillDisplay === undefined) {+ // Scope row → scope description + New skill (creates a blank directly) /+ // Upload / Explore (each opens the add-skill modal on its tab).+ menuItems = (+ <>+ <DropdownMenuLabel className="max-w-56 whitespace-normal font-normal text-muted-foreground text-xs">+ {scopeDescription[scope]}+ </DropdownMenuLabel>+ <DropdownMenuSeparator />+ <DropdownMenuItem onSelect={() => onNewSkill(scope)}>+ <SquarePen aria-hidden />+ <Trans>New skill</Trans>+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => onAddSkill(scope, 'upload')}>+ <Upload aria-hidden />+ <Trans>Upload skill</Trans>+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => onAddSkill(scope, 'skills-sh')}>+ <Compass aria-hidden />+ <Trans>Explore skills</Trans>+ </DropdownMenuItem>+ </>+ );+ } else {+ const d = detectedFor(node);+ if (d) {+ // Detected skill row → open the editable in-place buffer (same as+ // clicking the row). No manage flow.+ menuItems = (+ <DropdownMenuItem onSelect={() => onOpenDetected(d)}>+ <SquarePen aria-hidden />+ <Trans>Edit</Trans>+ </DropdownMenuItem>+ );+ } else {+ const skill = skillFor(node);+ if (!skill) return null;+ if (skill.managed) return null; // managed built-in = read-only, no mutate menu+ if (node.sub === null || node.sub === SKILL_MD_PATH) {+ menuItems = (+ <SkillContextMenuItems+ skill={skill}+ actions={actions}+ existingNames={existingNames[skill.scope]}+ />+ );+ } else if (node.isDir) {+ // Every bundle dir offers New file seeded with its own path.+ // `node.sub` is non-null here (the null case is handled above).+ menuItems = (+ <DropdownMenuItem+ onSelect={() => actions.requestFileCreate(skill, `${node.sub}/`)}+ >+ <Trans>New file</Trans>+ </DropdownMenuItem>+ );+ } else {+ menuItems = (+ <SkillFileContextMenuItems skill={skill} filePath={node.sub} actions={actions} />+ );+ }+ }+ }+ return (+ <DropdownMenu+ open+ modal={false}+ onOpenChange={(open) => {+ if (!open) context.close({ restoreFocus: false });+ }}+ >+ <DropdownMenuTrigger asChild>+ <span+ aria-hidden="true"+ data-file-tree-context-menu-root="true"+ className="block size-px"+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ sideOffset={0}+ align="start"+ data-file-tree-context-menu-root="true"+ className="min-w-52"+ >+ {menuItems}+ </DropdownMenuContent>+ </DropdownMenu>+ );+ }}+ />+ </>+ );+}++/**+ * Install-menu body for the sidebar Install pill — resolves one skill's per-agent+ * toggle state and renders the SHARED menu items (the exact menu the editor+ * toolbar badge shows). Split into its own component because `useSkillHostToggles`+ * is a hook that must mount only while a skill is selected.+ */+function SkillInstallMenuBody({+ skill,+ actions,+ onRunStart,+}: {+ skill: SkillsListEntry;+ actions: SkillActions;+ /** Close the popover before a multi-location run starts: the rows are read+ * from a disk scan that refetches mid-run, so leaving it open shows them flip+ * and then settle, which reads as breakage. */+ onRunStart: () => void;+}) {+ const toggles = useSkillHostToggles(skill, actions);+ return (+ <SkillInstallMenuItems+ toggles={toggles}+ skill={skill}+ onResolveFork={(editor) => actions.requestForkResolve(skill, editor)}+ onRunStart={onRunStart}+ />+ );+}diff --git a/packages/app/src/lib/skill-scope.ts b/packages/app/src/lib/skill-scope.tsindex 088666a7e..e9b717afe 100644--- a/packages/app/src/lib/skill-scope.ts+++ b/packages/app/src/lib/skill-scope.ts@@ -66,6 +66,12 @@ export function tildeHomePath(abs: string): string {return abs.replace(/^\/(?:Users|home)\/[^/]+/, '~').replace(/^\/root/, '~');}+/** A skill dir is the parent of its `SKILL.md`; the detected preview reads it as a local source. */+export function skillDir(skillMdPath: string): string {+ const i = skillMdPath.lastIndexOf('/');+ return i > 0 ? skillMdPath.slice(0, i) : skillMdPath;+}+/*** Short level titles shared by every skills surface. The `global` scope is* user-level (available in every project); `project` skills live in this KBdiff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 64adbe2ef..d2511491a 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -466,7 +466,7 @@ msgstr "{diffHrs}h ago"msgid "{diffMin}m ago"msgstr "{diffMin}m ago"-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "{dir} (symlink)"msgstr "{dir} (symlink)"@@ -1829,7 +1829,7 @@ msgstr "Build and keep track of the world behind your story. A home for your chamsgid "Building <0>openknowledge.skill</0> and opening the Claude Desktop App"msgstr "Building <0>openknowledge.skill</0> and opening the Claude Desktop App"-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Built-in (read-only)"msgstr "Built-in (read-only)"@@ -3691,7 +3691,7 @@ msgid "Details about the error you just hit are included. Secrets like API keysmsgstr "Details about the error you just hit are included. Secrets like API keys and tokens are redacted automatically."#. placeholder {0}: d.sourceHarnesses.map((h) => skillHostRootDir(h, scope)).join(', ')-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Detected in {0}"msgstr "Detected in {0}"@@ -4026,7 +4026,7 @@ msgstr "Each selected tool gets an OpenKnowledge MCP entry."#: src/components/AppMenubar.tsx#: src/components/settings/LintingSection.tsx-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsx#: src/components/TemplateForm.tsx#: src/components/TemplateRow.tsx#: src/editor/extensions/InternalLinkPropPanel.tsx@@ -4412,7 +4412,7 @@ msgstr "Explain how your codebase works so teammates and AI agents can find theimsgid "Explore"msgstr "Explore"-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Explore skills"msgstr "Explore skills"@@ -5710,12 +5710,12 @@ msgstr "Insert, delete, move, copy, and indent source editor lines through CodeM#: src/components/settings/IntegrationsSection.tsx#: src/components/skill-actions.tsx#: src/components/SkillPreviewTab.tsx-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Install"msgstr "Install"#. placeholder {0}: skill.name-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Install {0}"msgstr "Install {0}"@@ -5826,7 +5826,7 @@ msgid "Installed at {path} — click to remove"msgstr "Installed at {path} — click to remove"#. placeholder {0}: hosts.map((h) => skillHostRootDir(h, skill.scope)).join(', ')-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Installed in {0}"msgstr "Installed in {0}"@@ -6698,7 +6698,7 @@ msgstr "New changes from your remote appear in your copy automatically."#: src/components/FileTree.tsx#: src/components/NewItemDialog.tsx#: src/components/skill-actions.tsx-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsx#: src/lib/keyboard-shortcuts.tsmsgid "New file"msgstr "New file"@@ -6769,7 +6769,7 @@ msgstr "New session"#: src/components/command-palette-commands.ts#: src/components/NewSkillDialog.tsx-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "New skill"msgstr "New skill"@@ -7853,7 +7853,7 @@ msgid "Parse failed"msgstr "Parse failed"#. placeholder {0}: det.provenance.plugin-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Part of the {0} plugin — read-only; open it to edit a copy"msgstr "Part of the {0} plugin — read-only; open it to edit a copy"@@ -11584,7 +11584,7 @@ msgstr "Upload from computer"msgid "Upload may have succeeded but the sidebar is out of date — refresh to resync"msgstr "Upload may have succeeded but the sidebar is out of date — refresh to resync"-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Upload skill"msgstr "Upload skill"diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 23be53da2..cc041d3d7 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -466,7 +466,7 @@ msgstr ""msgid "{diffMin}m ago"msgstr ""-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "{dir} (symlink)"msgstr ""@@ -1825,7 +1825,7 @@ msgstr ""msgid "Building <0>openknowledge.skill</0> and opening the Claude Desktop App"msgstr ""-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Built-in (read-only)"msgstr ""@@ -3687,7 +3687,7 @@ msgid "Details about the error you just hit are included. Secrets like API keysmsgstr ""#. placeholder {0}: d.sourceHarnesses.map((h) => skillHostRootDir(h, scope)).join(', ')-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Detected in {0}"msgstr ""@@ -4022,7 +4022,7 @@ msgstr ""#: src/components/AppMenubar.tsx#: src/components/settings/LintingSection.tsx-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsx#: src/components/TemplateForm.tsx#: src/components/TemplateRow.tsx#: src/editor/extensions/InternalLinkPropPanel.tsx@@ -4408,7 +4408,7 @@ msgstr ""msgid "Explore"msgstr ""-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Explore skills"msgstr ""@@ -5706,12 +5706,12 @@ msgstr ""#: src/components/settings/IntegrationsSection.tsx#: src/components/skill-actions.tsx#: src/components/SkillPreviewTab.tsx-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Install"msgstr ""#. placeholder {0}: skill.name-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Install {0}"msgstr ""@@ -5822,7 +5822,7 @@ msgid "Installed at {path} — click to remove"msgstr ""#. placeholder {0}: hosts.map((h) => skillHostRootDir(h, skill.scope)).join(', ')-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Installed in {0}"msgstr ""@@ -6694,7 +6694,7 @@ msgstr ""#: src/components/FileTree.tsx#: src/components/NewItemDialog.tsx#: src/components/skill-actions.tsx-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsx#: src/lib/keyboard-shortcuts.tsmsgid "New file"msgstr ""@@ -6765,7 +6765,7 @@ msgstr ""#: src/components/command-palette-commands.ts#: src/components/NewSkillDialog.tsx-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "New skill"msgstr ""@@ -7849,7 +7849,7 @@ msgid "Parse failed"msgstr ""#. placeholder {0}: det.provenance.plugin-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Part of the {0} plugin — read-only; open it to edit a copy"msgstr ""@@ -11580,7 +11580,7 @@ msgstr ""msgid "Upload may have succeeded but the sidebar is out of date — refresh to resync"msgstr ""-#: src/components/SkillsSidebarSection.tsx+#: src/components/SkillsTree.tsxmsgid "Upload skill"msgstr ""diff --git a/packages/app/tests/integration/error-envelope-coverage.test.ts b/packages/app/tests/integration/error-envelope-coverage.test.tsindex 794b3ee5d..881cc106d 100644--- a/packages/app/tests/integration/error-envelope-coverage.test.ts+++ b/packages/app/tests/integration/error-envelope-coverage.test.ts@@ -20,8 +20,20 @@ import { readFileSync } from 'node:fs';import { join } from 'node:path';import { describe, expect, test } from 'vitest';-const API_EXT_PATH = join(import.meta.dirname, '../../../server/src/api-extension.ts');-const source = readFileSync(API_EXT_PATH, 'utf8');+const SERVER_SRC = join(import.meta.dirname, '../../../server/src');+/**+ * Route handlers do not all live in one file: the six skills.sh handlers sit in+ * `skills-sh-handlers.ts`, built by a factory the route table destructures. Every+ * scan below runs over each source, because a handler that moves out of+ * `api-extension.ts` would otherwise escape these rules silently rather than+ * failing anything.+ */+const HANDLER_SOURCES = ['api-extension.ts', 'skills-sh-handlers.ts'].map((file) => ({+ file,+ text: readFileSync(join(SERVER_SRC, file), 'utf8'),+}));+/** The route table and the shared success spine live in `api-extension.ts` only. */+const source = HANDLER_SOURCES[0]?.text ?? '';function listAllHandlers(): string[] {// Handlers in `api-extension.ts` come in three shapes:@@ -37,11 +49,10 @@ function listAllHandlers(): string[] {// Inner functions co-located with a wrapper are excluded from the public// handler list — they are scanned as part of the parent's body slice via// `extractHandlerBody`.- const fnNames = [...source.matchAll(/async function (handle\w+)\(/g)].map((m) => m[1]);- const wrapperNames = [...source.matchAll(/const (handle\w+) = withValidation\(/g)].map(- (m) => m[1],- );- const routerNames = [...source.matchAll(/const (handle\w+) = methodRouter\(/g)].map((m) => m[1]);+ const all = HANDLER_SOURCES.map((h) => h.text).join('\n');+ const fnNames = [...all.matchAll(/async function (handle\w+)\(/g)].map((m) => m[1]);+ const wrapperNames = [...all.matchAll(/const (handle\w+) = withValidation\(/g)].map((m) => m[1]);+ const routerNames = [...all.matchAll(/const (handle\w+) = methodRouter\(/g)].map((m) => m[1]);const innerNames = new Set(wrapperNames.map((wrapper) => `${wrapper}Inner`).filter((inner) => fnNames.includes(inner)),);@@ -54,9 +65,14 @@ function extractHandlerBody(name: string): string | null {const fnDecl = `async function ${name}(`;const constDecl = `const ${name} = withValidation(`;const routerDecl = `const ${name} = methodRouter(`;- const fnIdx = source.indexOf(fnDecl);- const constIdx = source.indexOf(constDecl);- const routerIdx = source.indexOf(routerDecl);+ // Whichever source declares it; a lifted handler is not in `api-extension.ts`.+ const owner =+ HANDLER_SOURCES.find(+ (h) => h.text.includes(fnDecl) || h.text.includes(constDecl) || h.text.includes(routerDecl),+ )?.text ?? source;+ const fnIdx = owner.indexOf(fnDecl);+ const constIdx = owner.indexOf(constDecl);+ const routerIdx = owner.indexOf(routerDecl);let start = -1;if (fnIdx !== -1) start = fnIdx;else if (constIdx !== -1) start = constIdx;@@ -70,18 +86,21 @@ function extractHandlerBody(name: string): string | null {// the inner body is included in the slice for `handleX`.const innerName = `${name}Inner`;const innerDecl = `\n async function ${innerName}(`;- const innerIdx = source.indexOf(innerDecl, start + 1);+ const innerIdx = owner.indexOf(innerDecl, start + 1);const searchFrom = innerIdx === -1 ? start + 1 : innerIdx + 1;- const nextFn = source.indexOf('\n async function handle', searchFrom);- const nextConst = source.indexOf('\n const handle', searchFrom);+ const nextFn = owner.indexOf('\n async function handle', searchFrom);+ const nextConst = owner.indexOf('\n const handle', searchFrom);// The last handler in the file has no successor — bound at the route table// declaration `\n const routes:` so we don't accidentally fold the// onRequest extension (which itself uses `errorResponse(...)` for the// /api/* Origin gate) into the prior handler's slice.- const nextRoutes = source.indexOf('\n const routes:', searchFrom);- const candidates = [nextFn, nextConst, nextRoutes].filter((i) => i !== -1);+ const nextRoutes = owner.indexOf('\n const routes:', searchFrom);+ // The factory module ends its handler run at the returned record instead of+ // a route table, so bound on that too or the last handler swallows it.+ const nextReturn = owner.indexOf('\n return {', searchFrom);+ const candidates = [nextFn, nextConst, nextRoutes, nextReturn].filter((i) => i !== -1);const next = candidates.length === 0 ? -1 : Math.min(...candidates);- return source.slice(start, next === -1 ? source.length : next);+ return owner.slice(start, next === -1 ? owner.length : next);}const INLINE_ERROR_RE = /json\(\s*res\s*,\s*\d+\s*,\s*\{\s*ok:\s*false\b/;@@ -223,7 +242,11 @@ describe('error envelope coverage (FR17, D36 a) — fail-on-any-occurrence', ()for (const name of all) {const body = extractHandlerBody(name);if (!body) {- failures.push(`${name}: not found in api-extension.ts`);+ // Names every source actually searched, so a lifted handler that goes+ // missing does not send the reader back to `api-extension.ts` alone.+ failures.push(+ `${name}: body not found in any handler source (${HANDLER_SOURCES.map((h) => h.file).join(', ')})`,+ );continue;}if (INLINE_ERROR_RE.test(body)) {@@ -328,38 +351,48 @@ describe('error envelope coverage (FR17, D36 a) — fail-on-any-occurrence', ()expect(INLINE_BARE_SUCCESS_RE.test(spineBody)).toBe(false);});- test('zero inline { ok: false } envelopes anywhere in api-extension.ts', () => {+ test('zero inline { ok: false } envelopes in any handler source', () => {// Whole-file sweep: catches inline literals outside per-handler bodies// (helper functions, the onRequest extension, route-table fallthroughs).// The per-handler scan above bounds at the `\n const routes:` declaration// and would miss anything below; this assertion is the structural// backstop.- const matches = [...source.matchAll(/json\(\s*res\s*,\s*\d+\s*,\s*\{\s*ok:\s*false\b/g)];+ const matches = HANDLER_SOURCES.flatMap((h) =>+ [...h.text.matchAll(/json\(\s*res\s*,\s*\d+\s*,\s*\{\s*ok:\s*false\b/g)].map((m) => ({+ m,+ h,+ })),+ );if (matches.length > 0) {- const locations = matches.map((m) => {- const lineNumber = source.slice(0, m.index ?? 0).split('\n').length;- return `api-extension.ts:${lineNumber}`;+ const locations = matches.map(({ m, h }) => {+ const lineNumber = h.text.slice(0, m.index ?? 0).split('\n').length;+ return `${h.file}:${lineNumber}`;});expect(locations).toEqual([]);}expect(matches.length).toBe(0);});- test('zero inline { ok: true } success wrappers anywhere in api-extension.ts', () => {+ test('zero inline { ok: true } success wrappers in any handler source', () => {// The `ok: true` wrapper is dropped from success bodies. Same whole-file// sweep as above: fail-on-any-occurrence.- const matches = [...source.matchAll(/json\(\s*res\s*,\s*\d+\s*,\s*\{\s*ok:\s*true\b/g)];+ const matches = HANDLER_SOURCES.flatMap((h) =>+ [...h.text.matchAll(/json\(\s*res\s*,\s*\d+\s*,\s*\{\s*ok:\s*true\b/g)].map((m) => ({+ m,+ h,+ })),+ );if (matches.length > 0) {- const locations = matches.map((m) => {- const lineNumber = source.slice(0, m.index ?? 0).split('\n').length;- return `api-extension.ts:${lineNumber}`;+ const locations = matches.map(({ m, h }) => {+ const lineNumber = h.text.slice(0, m.index ?? 0).split('\n').length;+ return `${h.file}:${lineNumber}`;});expect(locations).toEqual([]);}expect(matches.length).toBe(0);});- test('zero bare json(res, 2xx, ...) success emits anywhere in api-extension.ts', () => {+ test('zero bare json(res, 2xx, ...) success emits in any handler source', () => {// Every success body MUST flow through `successResponse(...)` so the// schema-vs-server drift class is closed structurally at the wire// boundary. Whole-file sweep mirrors the `{ ok: false/true }` ratchets@@ -374,18 +407,20 @@ describe('error envelope coverage (FR17, D36 a) — fail-on-any-occurrence', ()// (errors). A future regression that re-adds an inline `json(res, 2xx,// ...)` helper would surface here regardless of whether the regression// is inside a per-handler body or a shared utility.- const matches = [...source.matchAll(/\bjson\(\s*res\s*,\s*2[0-9]{2}\s*,/g)];+ const matches = HANDLER_SOURCES.flatMap((h) =>+ [...h.text.matchAll(/\bjson\(\s*res\s*,\s*2[0-9]{2}\s*,/g)].map((m) => ({ m, h })),+ );if (matches.length > 0) {- const locations = matches.map((m) => {- const lineNumber = source.slice(0, m.index ?? 0).split('\n').length;- return `api-extension.ts:${lineNumber}`;+ const locations = matches.map(({ m, h }) => {+ const lineNumber = h.text.slice(0, m.index ?? 0).split('\n').length;+ return `${h.file}:${lineNumber}`;});expect(locations).toEqual([]);}expect(matches.length).toBe(0);});- test('zero NDJSON `JSON.stringify({ ok: false, ... })` legacy envelope shapes anywhere in api-extension.ts', () => {+ test('zero NDJSON `JSON.stringify({ ok: false, ... })` legacy envelope shapes in any handler source', () => {// Streaming endpoints (clone, auth-login, auth-repos) emit NDJSON via// `res.write(JSON.stringify({...}) + '\n')`. The two whole-file sweeps// above only catch the synchronous `json(res, ...)` shape — a future@@ -396,27 +431,31 @@ describe('error envelope coverage (FR17, D36 a) — fail-on-any-occurrence', ()// `streamingProblemEvent` / `createStreamingErrorWriter` — there is no// legitimate reason to emit `{ ok: false, ... }` JSON literals from// streaming or non-streaming code.- const matches = [...source.matchAll(/JSON\.stringify\(\s*\{\s*ok:\s*false\b/g)];+ const matches = HANDLER_SOURCES.flatMap((h) =>+ [...h.text.matchAll(/JSON\.stringify\(\s*\{\s*ok:\s*false\b/g)].map((m) => ({ m, h })),+ );if (matches.length > 0) {- const locations = matches.map((m) => {- const lineNumber = source.slice(0, m.index ?? 0).split('\n').length;- return `api-extension.ts:${lineNumber}`;+ const locations = matches.map(({ m, h }) => {+ const lineNumber = h.text.slice(0, m.index ?? 0).split('\n').length;+ return `${h.file}:${lineNumber}`;});expect(locations).toEqual([]);}expect(matches.length).toBe(0);});- test('zero NDJSON `JSON.stringify({ ok: true, ... })` legacy envelope shapes anywhere in api-extension.ts', () => {+ test('zero NDJSON `JSON.stringify({ ok: true, ... })` legacy envelope shapes in any handler source', () => {// The `ok: true` wrapper is dropped from success bodies. Streaming// success events use `{ type: 'complete', ... }` (or `progress`) — a// future regression into the legacy wrapped shape is invisible to the// synchronous `json(res, ...)` sweep.- const matches = [...source.matchAll(/JSON\.stringify\(\s*\{\s*ok:\s*true\b/g)];+ const matches = HANDLER_SOURCES.flatMap((h) =>+ [...h.text.matchAll(/JSON\.stringify\(\s*\{\s*ok:\s*true\b/g)].map((m) => ({ m, h })),+ );if (matches.length > 0) {- const locations = matches.map((m) => {- const lineNumber = source.slice(0, m.index ?? 0).split('\n').length;- return `api-extension.ts:${lineNumber}`;+ const locations = matches.map(({ m, h }) => {+ const lineNumber = h.text.slice(0, m.index ?? 0).split('\n').length;+ return `${h.file}:${lineNumber}`;});expect(locations).toEqual([]);}diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 287409321..83ec07328 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -212,8 +212,6 @@ import {ShareTargetStatusResponseSchema,SKILL_NAME_REGEX,SkillDeleteSuccessSchema,- SkillDetailSchema,- SkillDiscoverSchema,SkillDuplicateRequestSchema,SkillDuplicateSuccessSchema,SkillEditExternalRequestSchema,@@ -237,11 +235,8 @@ import {SkillMoveScopeRequestSchema,SkillMoveScopeSuccessSchema,SkillMoveSuccessSchema,- SkillPreviewSchema,SkillPutRequestSchema,SkillPutSuccessSchema,- type SkillRefResolution,- SkillRefResolutionSchema,SkillReimportRequestSchema,SkillReimportSuccessSchema,SkillRestoreRequestSchema,@@ -253,7 +248,6 @@ import {SkillsImportBulkSuccessSchema,SkillsInstalledSuccessSchema,SkillsListSuccessSchema,- SkillsSearchSuccessSchema,SkillTargetsGetSuccessSchema,SkillTargetsPutRequestSchema,SkillTargetsPutSuccessSchema,@@ -314,18 +308,12 @@ import {import {acquiredBundleTooLarge,discoverSkillDirs,- discoverWellKnownSkills,enumerateInstalledSkills,fetchSource,findByContentHash,- inspectPluginBundleDir,inspectPluginSource,- parseGitHubRepoSearch,- parseOpenGraph,parseSkillDir,parseSkillsLock,- parseSkillsShSearch,- parseSkillsShWebsiteSource,parseSource,pluginRepositoryUrl,readSkillDirMeta,@@ -340,7 +328,6 @@ import {SkillFetchError,type SkillsLock,type SourceSpec,- skillsShSkillLinks,upsertLockEntry,type WellKnownIndex,} from '@inkeep/open-knowledge-core/skills-catalog';@@ -766,6 +753,7 @@ import {scanSkillFolderStates,unlinkEditorSkillFolder,} from './skill-folder-links.ts';+import { rejectDisallowedGitSpec } from './skill-git-spec-guard.ts';import { resolveSkillInstallReportSettings } from './skill-install-report-config.ts';import {readFolderExpectations,@@ -779,8 +767,8 @@ import {resolveSkillPlacementPath,} from './skill-placements.ts';import { restoreSkillVersion } from './skill-restore.ts';-import { getPopularSkills } from './skills-leaderboard.ts';import { mutateSkillsLock, readSkillsLockFile } from './skills-lock-store.ts';+import { createSkillsShHandlers } from './skills-sh-handlers.ts';import { reportSkillInstall } from './skills-sh-install-report.ts';import { SuggestLinksTargetNotFoundError, suggestLinks } from './suggest-links.ts';import type { SyncEngine } from './sync-engine.ts';@@ -793,25 +781,6 @@ import { recordTimelineCoalesced } from './timeline-telemetry.ts';// Recreating the histogram every request allocates + registers a fresh// instrument on every hit.let _httpDurationHist: ReturnType<ReturnType<typeof getMeter>['createHistogram']> | null = null;-/**- * Defense-in-depth git-transport gate for the skill-acquisition routes- * (preview / discover / import / reimport). Sends a 400 and returns true when- * `spec` is a git source whose URL is not an allowlisted transport. `parseSource`- * already rejects non-allowlisted transports (its ALLOWED_GIT_TRANSPORTS mirrors- * `isAllowedGitUrl`), so in practice this never fires — it is a drift tripwire at- * the trust boundary before `git clone`, re-closing the ext::/fd:: RCE class if- * the two allowlists ever diverge.- */-function rejectDisallowedGitSpec(res: ServerResponse, spec: SourceSpec, handler: string): boolean {- if (spec.kind === 'git' && !isAllowedGitUrl(spec.url)) {- errorResponse(res, 400, 'urn:ok:error:url-not-allowed', 'Git URL protocol is not allowed.', {- handler,- cause: new Error(`url=${spec.url}`),- });- return true;- }- return false;-}const SKILL_IMPORT_WRITE_LIMITS = {maxFileBytes: SKILL_IMPORT_MAX_FILE_BYTES,@@ -7698,528 +7667,6 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {{ handler: 'skills-installed', method: 'GET', skipBodyParse: true },);- // `GET /api/skills/search?q=<query>` — proxy skill discovery. Primary backend is- // the keyless skills.sh endpoint its own CLI uses (undocumented, so we- // defensive-parse and fall back to GitHub-topic search on error or shape drift).- // The GitHub fallback is degraded (repo-level, no install-count ranking); the- // response's `backend`/`degraded` let the client drop the install-count sort.- const handleSkillsSearch = withValidation(- EmptyRequestSchema,- async (req, res) => {- const url = new URL(req.url ?? '', 'http://localhost');- const q = url.searchParams.get('q')?.trim() ?? '';- if (q.length < 2) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Search query must be at least 2 characters.',- { handler: 'skills-search' },- );- return;- }- try {- const r = await fetch(`https://skills.sh/api/search?q=${encodeURIComponent(q)}&limit=30`, {- signal: AbortSignal.timeout(8000),- });- if (r.ok) {- const results = parseSkillsShSearch(await r.json());- successResponse(- res,- 200,- SkillsSearchSuccessSchema,- { results, backend: 'skills.sh', degraded: false },- { handler: 'skills-search' },- );- return;- }- log.warn(- { status: r.status },- 'skills.sh search unavailable — falling back to GitHub topic search',- );- } catch (e) {- log.warn({ err: e }, 'skills.sh search failed — falling back to GitHub topic search');- }- try {- const ghQ = encodeURIComponent(`${q} topic:agent-skills`);- const gh = await fetch(`https://api.github.com/search/repositories?q=${ghQ}&per_page=30`, {- signal: AbortSignal.timeout(8000),- headers: { Accept: 'application/vnd.github+json' },- });- if (!gh.ok) {- // 403 (unauthenticated rate cap) / 429 are the common cases. Reporting- // these as an empty result set told the user "No skills found" — that- // the skill does not exist — when both backends were simply refusing- // to answer. Take the same exit as the outer catch so the client says- // the search failed instead.- log.warn({ status: gh.status }, 'GitHub skill search fallback returned non-ok');- errorResponse(- res,- 502,- 'urn:ok:error:internal-server-error',- 'Skill discovery is temporarily unavailable.',- { handler: 'skills-search', detail: `GitHub fallback returned ${gh.status}.` },- );- return;- }- const results = parseGitHubRepoSearch(await gh.json());- successResponse(- res,- 200,- SkillsSearchSuccessSchema,- { results, backend: 'github-fallback', degraded: true },- { handler: 'skills-search' },- );- } catch (e) {- errorResponse(- res,- 502,- 'urn:ok:error:internal-server-error',- 'Skill discovery is temporarily unavailable.',- { handler: 'skills-search', cause: e },- );- }- },- { handler: 'skills-search', method: 'GET', skipBodyParse: true },- );-- // `GET /api/skills/popular?limit=<n>` — the Discover blank-state list. No keyless- // leaderboard endpoint exists (token-gated), so the server scrapes the skills.sh- // front-page RSC payload, cached + best-effort (see `getPopularSkills`). An empty- // list (backend degraded) tells the client to fall back to topic chips.- const handleSkillsPopular = withValidation(- EmptyRequestSchema,- async (req, res) => {- const url = new URL(req.url ?? '', 'http://localhost');- const limitRaw = Number(url.searchParams.get('limit'));- const limit =- Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(Math.floor(limitRaw), 60) : 24;- // `getPopularSkills` is best-effort (swallows fetch/parse failures and- // returns []), but guard the wire boundary anyway — the sibling- // `handleSkillsSearch` does the same, and it keeps the handler correct if- // the leaderboard helper's contract ever changes to throw.- try {- const results = await getPopularSkills(limit);- successResponse(- res,- 200,- SkillsSearchSuccessSchema,- { results, backend: 'skills.sh', degraded: results.length === 0 },- { handler: 'skills-popular' },- );- } catch (e) {- errorResponse(- res,- 502,- 'urn:ok:error:internal-server-error',- 'Popular skills are temporarily unavailable.',- { handler: 'skills-popular', cause: e },- );- }- },- { handler: 'skills-popular', method: 'GET', skipBodyParse: true },- );-- // `GET /api/skills/detail?source=&name=` — enrich one discovery result for the- // info modal. The shared catalog-source parser owns both GitHub and website- // route shapes. The rich preview comes from the skills.sh page's Open Graph- // tags because the page itself cannot be iframed (`x-frame-options: DENY`).- const handleSkillsDetail = withValidation(- EmptyRequestSchema,- async (req, res) => {- const url = new URL(req.url ?? '', 'http://localhost');- const source = url.searchParams.get('source')?.trim() ?? '';- const name = url.searchParams.get('name')?.trim() ?? '';- if (!source || !name) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'source and name are required.', {- handler: 'skills-detail',- });- return;- }- const links = skillsShSkillLinks(source, name);- if (!links) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unrecognized skill source.', {- handler: 'skills-detail',- });- return;- }- const { skillsUrl, sourceKind, sourceUrl } = links;- let og: { title?: string; description?: string; image?: string } = {};- let pageReached = false;- try {- const r = await fetch(skillsUrl, { signal: AbortSignal.timeout(8000) });- if (r.ok) {- pageReached = true;- og = parseOpenGraph(await r.text());- }- } catch (e) {- log.warn({ err: e, skillsUrl }, 'skills.sh detail fetch failed — degrading to repo link');- }- successResponse(- res,- 200,- SkillDetailSchema,- {- title: og.title ?? name,- description: og.description ?? '',- image: og.image ?? null,- skillsUrl: pageReached ? skillsUrl : null,- sourceKind,- sourceUrl,- },- { handler: 'skills-detail' },- );- },- { handler: 'skills-detail', method: 'GET', skipBodyParse: true },- );-- // `GET /api/skills/preview?source=&name=` fetches one un-imported bundle so- // Explore can render the exact files before installation. Repository and- // website sources converge on the same temporary-directory parser here.- // ponytail: remote sources are fetched per preview open; add a short-lived- // cache keyed on source+ref if click-through churn becomes a problem.- const handleSkillsPreview = withValidation(- EmptyRequestSchema,- async (req, res) => {- const url = new URL(req.url ?? '', 'http://localhost');- const source = url.searchParams.get('source')?.trim() ?? '';- const name = url.searchParams.get('name')?.trim() ?? '';- if (!source) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'source is required.', {- handler: 'skills-preview',- });- return;- }- let resolvedSkillsSh: Awaited<ReturnType<typeof resolveSkillsShImportSource>> = null;- try {- resolvedSkillsSh = await resolveSkillsShImportSource(source, name || undefined);- } catch (error) {- if (error instanceof SkillFetchError) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not resolve source.', {- handler: 'skills-preview',- cause: error,- });- return;- }- throw error;- }- const spec = resolvedSkillsSh?.spec ?? parseSource(source);- if (!spec) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unrecognized preview source.', {- handler: 'skills-preview',- detail: 'Expected owner/repo, a git URL, a website source, or a local path.',- });- return;- }- if (rejectDisallowedGitSpec(res, spec, 'skills-preview')) return;- let cleanup: (() => void) | undefined;- try {- const fetched = await fetchSource(spec);- cleanup = fetched.cleanup;- const dirs = discoverSkillDirs(fetched.dir);- if (dirs.length === 0) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'No SKILL.md found in source.', {- handler: 'skills-preview',- });- return;- }- // Match the search row's name against the dir basename OR the SKILL.md- // frontmatter name (they often differ). A named MISS is a 404 here for- // the same reason it is one on import: this is the consent surface. The- // old fallback to `dirs[0]` rendered a different skill's prose under the- // requested name — the header still said "a preview of <name>" and the- // properties block still showed `<name>` — and then import refused the- // same miss, so the user read one skill and could only install another.- let pick = dirs[0];- if (name) {- const found =- dirs.find((d) => d.name === name) ??- dirs.find((d) => readSkillDirMeta(d.dir)?.name === name);- if (!found) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Named skill not in source.', {- handler: 'skills-preview',- detail: `"${name}" not among: ${dirs.map((d) => d.name).join(', ')}.`,- });- return;- }- pick = found;- }- const tooLarge = acquiredBundleTooLarge(pick.dir);- if (tooLarge) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Skill bundle is too large.', {- handler: 'skills-preview',- detail: tooLarge,- });- return;- }- const parsed = parseSkillDir(pick.dir);- if (!parsed) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'SKILL.md unreadable in source.', {- handler: 'skills-preview',- });- return;- }- const plugin = inspectPluginSource(source);- // The skills.sh source repo may itself be a plugin bundling several- // skills — skills.sh never flags that, but the clone carries the- // manifest and we already have it in hand (`fetched.dir`). Read-only.- const pluginBundle = inspectPluginBundleDir(fetched.dir);- successResponse(- res,- 200,- SkillPreviewSchema,- {- name: parsed.name,- description: parsed.description,- skillMd: parsed.skillMd,- // Strip raw `bytes` (binary files) — a preview renders text or shows- // the file as binary (`content: null`); the bytes are not JSON-safe- // and only matter on import.- files: parsed.files.map((f) => ({ relPath: f.relPath, content: f.content })),- plugin: plugin ?? undefined,- pluginBundle: pluginBundle ?? undefined,- },- { handler: 'skills-preview' },- );- } catch (e) {- if (e instanceof SkillFetchError) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {- handler: 'skills-preview',- cause: e,- });- return;- }- errorResponse(res, 502, 'urn:ok:error:internal-server-error', 'Preview is unavailable.', {- handler: 'skills-preview',- cause: e,- });- } finally {- cleanup?.();- }- },- { handler: 'skills-preview', method: 'GET', skipBodyParse: true },- );-- // `GET /api/skills/discover?source=` enumerates a repository/local tree or a- // website's well-known index so the Import modal can offer an exact picker.- // ponytail: remote indexes/repos are fetched per call; cache by source+ref if- // debounced typing churn becomes a problem.- const handleSkillsDiscover = withValidation(- EmptyRequestSchema,- async (req, res) => {- const url = new URL(req.url ?? '', 'http://localhost');- const source = url.searchParams.get('source')?.trim() ?? '';- if (!source) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'source is required.', {- handler: 'skills-discover',- });- return;- }- const websiteSource = parseSkillsShWebsiteSource(source);- if (websiteSource) {- try {- const skills = await discoverWellKnownSkills(`https://${websiteSource.hostname}`);- successResponse(- res,- 200,- SkillDiscoverSchema,- { skills },- { handler: 'skills-discover' },- );- } catch (error) {- if (error instanceof SkillFetchError) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {- handler: 'skills-discover',- cause: error,- });- return;- }- throw error;- }- return;- }- const spec = parseSource(source);- if (!spec) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unrecognized source.', {- handler: 'skills-discover',- detail: 'Expected owner/repo, a git URL, a website source, or a local path.',- });- return;- }- if (rejectDisallowedGitSpec(res, spec, 'skills-discover')) return;- let cleanup: (() => void) | undefined;- try {- const fetched = await fetchSource(spec);- cleanup = fetched.cleanup;- const dirs = discoverSkillDirs(fetched.dir);- // Prefer the SKILL.md frontmatter name (what the import path matches and- // what a user recognizes); fall back to the dir basename.- const skills = dirs.map((d) => {- // Metadata-only: a listing has no use for bundle bytes, and reading- // them for every skill in a large repo is how a preview turns into an- // out-of-memory kill.- const meta = readSkillDirMeta(d.dir);- return { name: meta?.name ?? d.name, description: meta?.description ?? null };- });- successResponse(res, 200, SkillDiscoverSchema, { skills }, { handler: 'skills-discover' });- } catch (e) {- if (e instanceof SkillFetchError) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {- handler: 'skills-discover',- cause: e,- });- return;- }- errorResponse(res, 502, 'urn:ok:error:internal-server-error', 'Discovery is unavailable.', {- handler: 'skills-discover',- cause: e,- });- } finally {- cleanup?.();- }- },- { handler: 'skills-discover', method: 'GET', skipBodyParse: true },- );-- // `GET /api/skills/resolve-ref?ref=<name>&scope=<scope>&from=<skill>` — resolve- // a skill's `/other-skill` reference by TRUSTED-PROVENANCE precedence, never a- // marketplace-wide name search (that would import a stranger's same-name skill- // thinking it's the dependency). Ladder: (1) already installed → local; (2) a- // sibling in the referencing skill's own origin repo/plugin → import via- // source; (3) a same-publisher skills.sh result with the exact name → import- // via publisher; else none, and the caller offers MANUAL Explore search.- const handleSkillsResolveRef = withValidation(- EmptyRequestSchema,- async (req, res) => {- const url = new URL(req.url ?? '', 'http://localhost');- const ref = url.searchParams.get('ref')?.trim() ?? '';- const from = url.searchParams.get('from')?.trim() ?? '';- const scope = url.searchParams.get('scope')?.trim() === 'global' ? 'global' : 'project';- if (!ref || !SKILL_NAME_REGEX.test(ref) || ref.length > 64) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'A valid ref is required.', {- handler: 'skills-resolve-ref',- });- return;- }- // Top-level guard like every sibling skills handler: `readSkillsLock`- // (existsSync → readFileSync) can throw on EACCES / a TOCTOU race, and an- // unguarded throw would surface as a context-less 500 from the outer- // catch.- try {- const respond = (resolution: SkillRefResolution) =>- successResponse(res, 200, SkillRefResolutionSchema, resolution, {- handler: 'skills-resolve-ref',- });-- // 1. LOCAL — same scope first, then the other. Already-present wins: it's- // what the user chose to have, and importing a same-name skill would fork.- for (const s of [scope, scope === 'project' ? 'global' : 'project'] as const) {- const realDir = resolveSkillDirForRead(s, ref);- if (realDir !== null) {- // Return the REAL dir, not just the name: the caller opens this skill,- // and deriving the doc name from the name alone assumes the retired- // store layout.- respond({- kind: 'local',- scope: s,- name: ref,- dir: relative(s === 'project' ? contentDir : skillsHome, realDir)- .split(sep)- .join('/'),- });- return;- }- }-- // Referencing skill's provenance from its scope lockfile (import origin).- const lockBase = scope === 'project' ? projectDir : skillsHome;- const entry =- from && lockBase- ? readSkillsLock(join(lockBase, ...SKILLS_LOCK_REL)).skills[from]- : undefined;-- // 2. SAME SOURCE — a sibling in the referencing skill's own repo/plugin.- // (A plugin's siblings resolve here too: its source is the plugin dir.)- if (entry?.source) {- const resolvedSkillsSh = await resolveSkillsShImportSource(entry.source, ref);- const spec = resolvedSkillsSh?.spec ?? parseSource(entry.source);- const allowed = spec && !(spec.kind === 'git' && !isAllowedGitUrl(spec.url));- if (spec && allowed) {- let cleanup: (() => void) | undefined;- try {- const fetched = await fetchSource(spec);- cleanup = fetched.cleanup;- const names = discoverSkillDirs(fetched.dir).map(- (d) => readSkillDirMeta(d.dir)?.name ?? d.name,- );- if (names.includes(ref)) {- respond({ kind: 'import', source: entry.source, ref, via: 'source' });- return;- }- } catch (err) {- // Source unreachable (clone failure / bad source) — fall through to- // the publisher rung, but leave a trail so a stale/deleted origin- // repo doesn't degrade ref resolution silently.- log.debug(- { err, ref, from, source: entry.source },- 'resolve-ref: source rung unreachable, falling through to publisher',- );- } finally {- cleanup?.();- }- }- }-- // 3. SAME PUBLISHER — a same-publisher skills.sh result with the EXACT name.- // Constrained (publisher + exact name), not a fuzzy match; a unique hit only.- if (entry?.publisher) {- try {- const r = await fetch(- `https://skills.sh/api/search?q=${encodeURIComponent(ref)}&limit=30`,- { signal: AbortSignal.timeout(8000) },- );- if (r.ok) {- const matches = parseSkillsShSearch(await r.json()).filter(- (x) => x.name === ref && x.publisher === entry.publisher,- );- if (matches.length === 1) {- const match = matches[0];- if (match) {- respond({ kind: 'import', source: match.source, ref, via: 'publisher' });- return;- }- }- }- } catch (err) {- // skills.sh unreachable or a malformed (e.g. HTML during an outage)- // response — no publisher resolution this call. Log so an outage is- // distinguishable from "skill genuinely absent from this publisher".- log.debug(- { err, ref, publisher: entry.publisher },- 'resolve-ref: skills.sh unavailable, no publisher resolution',- );- }- }-- // 4. NONE — no trusted signal. The caller keeps the missing-ref marker- // and offers manual Explore search; OK never auto-picks a fuzzy match.- respond({ kind: 'none' });- } catch (err) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Could not resolve the reference.',- {- handler: 'skills-resolve-ref',- cause: err instanceof Error ? err : new Error(String(err)),- },- );- }- },- { handler: 'skills-resolve-ref', method: 'GET', skipBodyParse: true },- );-/*** Bulk backlink-count lookup. `GET /api/backlink-counts?docNames=a,b,c`* returns `{ counts: { a: 3, b: 0, c: 2 } }`. Serves listing UIs@@ -25880,6 +25327,17 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {{ handler: 'comment' },);+ // Built here, not at their old spot ~18k lines up: `skillsHome` is a `const`+ // initialized further down, so an earlier call would hit its temporal dead zone.+ const {+ handleSkillsSearch,+ handleSkillsPopular,+ handleSkillsDetail,+ handleSkillsPreview,+ handleSkillsDiscover,+ handleSkillsResolveRef,+ } = createSkillsShHandlers({ log, skillsHome, projectDir, contentDir, resolveSkillDirForRead });+const routes: Record<string, (req: IncomingMessage, res: ServerResponse) => Promise<void>> = {'/api/config': handleApiConfig,'/api/config/diagnostics': handleConfigDiagnostics,diff --git a/packages/server/src/skill-git-spec-guard.ts b/packages/server/src/skill-git-spec-guard.tsnew file mode 100644index 000000000..b2f8125cd--- /dev/null+++ b/packages/server/src/skill-git-spec-guard.ts@@ -0,0 +1,28 @@+import type { ServerResponse } from 'node:http';+import type { SourceSpec } from '@inkeep/open-knowledge-core/skills-catalog';+import { errorResponse } from './http/error-response.ts';+import { isAllowedGitUrl } from './local-op-security.ts';++/**+ * Defense-in-depth git-transport gate for the skill-acquisition routes+ * (preview / discover / import / reimport). Sends a 400 and returns true when+ * `spec` is a git source whose URL is not an allowlisted transport. `parseSource`+ * already rejects non-allowlisted transports (its ALLOWED_GIT_TRANSPORTS mirrors+ * `isAllowedGitUrl`), so in practice this never fires — it is a drift tripwire at+ * the trust boundary before `git clone`, re-closing the ext::/fd:: RCE class if+ * the two allowlists ever diverge.+ */+export function rejectDisallowedGitSpec(+ res: ServerResponse,+ spec: SourceSpec,+ handler: string,+): boolean {+ if (spec.kind === 'git' && !isAllowedGitUrl(spec.url)) {+ errorResponse(res, 400, 'urn:ok:error:url-not-allowed', 'Git URL protocol is not allowed.', {+ handler,+ cause: new Error(`url=${spec.url}`),+ });+ return true;+ }+ return false;+}diff --git a/packages/server/src/skills-sh-handlers.ts b/packages/server/src/skills-sh-handlers.tsnew file mode 100644index 000000000..8a0a2873a--- /dev/null+++ b/packages/server/src/skills-sh-handlers.ts@@ -0,0 +1,609 @@+/**+ * The six skills.sh discovery handlers, lifted out of `api-extension.ts`.+ *+ * Stateless proxy and cache reads: no `session`, no `dc`, no `transact`. What+ * they closed over in the extension arrives as {@link SkillsShHandlerDeps} so+ * the route table keeps referencing them by name.+ *+ * `resolveSkillDirForRead` is passed in rather than imported because it is a+ * closure local of the extension. The factory call therefore has to sit AFTER+ * `skillsHome` is initialized (it is a `const`, so an earlier call would hit its+ * temporal dead zone); it lives immediately above the route table.+ */++import type { IncomingMessage, ServerResponse } from 'node:http';+import { join, relative, sep } from 'node:path';+import type { SkillRefResolution } from '@inkeep/open-knowledge-core';+import {+ EmptyRequestSchema,+ SKILL_NAME_REGEX,+ SkillDetailSchema,+ SkillDiscoverSchema,+ SkillPreviewSchema,+ SkillRefResolutionSchema,+ SkillsSearchSuccessSchema,+} from '@inkeep/open-knowledge-core';+import {+ acquiredBundleTooLarge,+ discoverSkillDirs,+ discoverWellKnownSkills,+ fetchSource,+ inspectPluginBundleDir,+ inspectPluginSource,+ parseGitHubRepoSearch,+ parseOpenGraph,+ parseSkillDir,+ parseSkillsShSearch,+ parseSkillsShWebsiteSource,+ parseSource,+ readSkillDirMeta,+ resolveSkillsShImportSource,+ SKILLS_LOCK_REL,+ SkillFetchError,+ skillsShSkillLinks,+} from '@inkeep/open-knowledge-core/skills-catalog';+import { errorResponse } from './http/error-response.ts';+import { withValidation } from './http/request-validation.ts';+import { successResponse } from './http/success-response.ts';+import { isAllowedGitUrl } from './local-op-security.ts';+import type { PinoLogger } from './logger.ts';+import { rejectDisallowedGitSpec } from './skill-git-spec-guard.ts';+import { getPopularSkills } from './skills-leaderboard.ts';+import { readSkillsLockFile } from './skills-lock-store.ts';++export interface SkillsShHandlerDeps {+ log: PinoLogger;+ skillsHome: string;+ projectDir: string | undefined;+ contentDir: string;+ resolveSkillDirForRead: (+ scope: 'project' | 'global',+ name: string,+ host?: string,+ ) => string | null;+}++export type SkillsShHandlers = Record<+ | 'handleSkillsSearch'+ | 'handleSkillsPopular'+ | 'handleSkillsDetail'+ | 'handleSkillsPreview'+ | 'handleSkillsDiscover'+ | 'handleSkillsResolveRef',+ (req: IncomingMessage, res: ServerResponse) => Promise<void>+>;++export function createSkillsShHandlers(deps: SkillsShHandlerDeps): SkillsShHandlers {+ const { log, skillsHome, projectDir, contentDir, resolveSkillDirForRead } = deps;++ // `GET /api/skills/search?q=<query>` — proxy skill discovery. Primary backend is+ // the keyless skills.sh endpoint its own CLI uses (undocumented, so we+ // defensive-parse and fall back to GitHub-topic search on error or shape drift).+ // The GitHub fallback is degraded (repo-level, no install-count ranking); the+ // response's `backend`/`degraded` let the client drop the install-count sort.+ const handleSkillsSearch = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ const url = new URL(req.url ?? '', 'http://localhost');+ const q = url.searchParams.get('q')?.trim() ?? '';+ if (q.length < 2) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Search query must be at least 2 characters.',+ { handler: 'skills-search' },+ );+ return;+ }+ try {+ const r = await fetch(`https://skills.sh/api/search?q=${encodeURIComponent(q)}&limit=30`, {+ signal: AbortSignal.timeout(8000),+ });+ if (r.ok) {+ const results = parseSkillsShSearch(await r.json());+ successResponse(+ res,+ 200,+ SkillsSearchSuccessSchema,+ { results, backend: 'skills.sh', degraded: false },+ { handler: 'skills-search' },+ );+ return;+ }+ log.warn(+ { status: r.status },+ 'skills.sh search unavailable — falling back to GitHub topic search',+ );+ } catch (e) {+ log.warn({ err: e }, 'skills.sh search failed — falling back to GitHub topic search');+ }+ try {+ const ghQ = encodeURIComponent(`${q} topic:agent-skills`);+ const gh = await fetch(`https://api.github.com/search/repositories?q=${ghQ}&per_page=30`, {+ signal: AbortSignal.timeout(8000),+ headers: { Accept: 'application/vnd.github+json' },+ });+ if (!gh.ok) {+ // 403 (unauthenticated rate cap) / 429 are the common cases. Reporting+ // these as an empty result set told the user "No skills found" — that+ // the skill does not exist — when both backends were simply refusing+ // to answer. Take the same exit as the outer catch so the client says+ // the search failed instead.+ log.warn({ status: gh.status }, 'GitHub skill search fallback returned non-ok');+ errorResponse(+ res,+ 502,+ 'urn:ok:error:internal-server-error',+ 'Skill discovery is temporarily unavailable.',+ { handler: 'skills-search', detail: `GitHub fallback returned ${gh.status}.` },+ );+ return;+ }+ const results = parseGitHubRepoSearch(await gh.json());+ successResponse(+ res,+ 200,+ SkillsSearchSuccessSchema,+ { results, backend: 'github-fallback', degraded: true },+ { handler: 'skills-search' },+ );+ } catch (e) {+ errorResponse(+ res,+ 502,+ 'urn:ok:error:internal-server-error',+ 'Skill discovery is temporarily unavailable.',+ { handler: 'skills-search', cause: e },+ );+ }+ },+ { handler: 'skills-search', method: 'GET', skipBodyParse: true },+ );++ // `GET /api/skills/popular?limit=<n>` — the Discover blank-state list. No keyless+ // leaderboard endpoint exists (token-gated), so the server scrapes the skills.sh+ // front-page RSC payload, cached + best-effort (see `getPopularSkills`). An empty+ // list (backend degraded) tells the client to fall back to topic chips.+ const handleSkillsPopular = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ const url = new URL(req.url ?? '', 'http://localhost');+ const limitRaw = Number(url.searchParams.get('limit'));+ const limit =+ Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(Math.floor(limitRaw), 60) : 24;+ // `getPopularSkills` is best-effort (swallows fetch/parse failures and+ // returns []), but guard the wire boundary anyway — the sibling+ // `handleSkillsSearch` does the same, and it keeps the handler correct if+ // the leaderboard helper's contract ever changes to throw.+ try {+ const results = await getPopularSkills(limit);+ successResponse(+ res,+ 200,+ SkillsSearchSuccessSchema,+ { results, backend: 'skills.sh', degraded: results.length === 0 },+ { handler: 'skills-popular' },+ );+ } catch (e) {+ errorResponse(+ res,+ 502,+ 'urn:ok:error:internal-server-error',+ 'Popular skills are temporarily unavailable.',+ { handler: 'skills-popular', cause: e },+ );+ }+ },+ { handler: 'skills-popular', method: 'GET', skipBodyParse: true },+ );++ // `GET /api/skills/detail?source=&name=` — enrich one discovery result for the+ // info modal. The shared catalog-source parser owns both GitHub and website+ // route shapes. The rich preview comes from the skills.sh page's Open Graph+ // tags because the page itself cannot be iframed (`x-frame-options: DENY`).+ const handleSkillsDetail = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ const url = new URL(req.url ?? '', 'http://localhost');+ const source = url.searchParams.get('source')?.trim() ?? '';+ const name = url.searchParams.get('name')?.trim() ?? '';+ if (!source || !name) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'source and name are required.', {+ handler: 'skills-detail',+ });+ return;+ }+ const links = skillsShSkillLinks(source, name);+ if (!links) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unrecognized skill source.', {+ handler: 'skills-detail',+ });+ return;+ }+ const { skillsUrl, sourceKind, sourceUrl } = links;+ let og: { title?: string; description?: string; image?: string } = {};+ let pageReached = false;+ try {+ const r = await fetch(skillsUrl, { signal: AbortSignal.timeout(8000) });+ if (r.ok) {+ pageReached = true;+ og = parseOpenGraph(await r.text());+ }+ } catch (e) {+ log.warn({ err: e, skillsUrl }, 'skills.sh detail fetch failed — degrading to repo link');+ }+ successResponse(+ res,+ 200,+ SkillDetailSchema,+ {+ title: og.title ?? name,+ description: og.description ?? '',+ image: og.image ?? null,+ skillsUrl: pageReached ? skillsUrl : null,+ sourceKind,+ sourceUrl,+ },+ { handler: 'skills-detail' },+ );+ },+ { handler: 'skills-detail', method: 'GET', skipBodyParse: true },+ );++ // `GET /api/skills/preview?source=&name=` fetches one un-imported bundle so+ // Explore can render the exact files before installation. Repository and+ // website sources converge on the same temporary-directory parser here.+ // ponytail: remote sources are fetched per preview open; add a short-lived+ // cache keyed on source+ref if click-through churn becomes a problem.+ const handleSkillsPreview = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ const url = new URL(req.url ?? '', 'http://localhost');+ const source = url.searchParams.get('source')?.trim() ?? '';+ const name = url.searchParams.get('name')?.trim() ?? '';+ if (!source) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'source is required.', {+ handler: 'skills-preview',+ });+ return;+ }+ let resolvedSkillsSh: Awaited<ReturnType<typeof resolveSkillsShImportSource>> = null;+ try {+ resolvedSkillsSh = await resolveSkillsShImportSource(source, name || undefined);+ } catch (error) {+ if (error instanceof SkillFetchError) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not resolve source.', {+ handler: 'skills-preview',+ cause: error,+ });+ return;+ }+ throw error;+ }+ const spec = resolvedSkillsSh?.spec ?? parseSource(source);+ if (!spec) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unrecognized preview source.', {+ handler: 'skills-preview',+ detail: 'Expected owner/repo, a git URL, a website source, or a local path.',+ });+ return;+ }+ if (rejectDisallowedGitSpec(res, spec, 'skills-preview')) return;+ let cleanup: (() => void) | undefined;+ try {+ const fetched = await fetchSource(spec);+ cleanup = fetched.cleanup;+ const dirs = discoverSkillDirs(fetched.dir);+ if (dirs.length === 0) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'No SKILL.md found in source.', {+ handler: 'skills-preview',+ });+ return;+ }+ // Match the search row's name against the dir basename OR the SKILL.md+ // frontmatter name (they often differ). A named MISS is a 404 here for+ // the same reason it is one on import: this is the consent surface. The+ // old fallback to `dirs[0]` rendered a different skill's prose under the+ // requested name — the header still said "a preview of <name>" and the+ // properties block still showed `<name>` — and then import refused the+ // same miss, so the user read one skill and could only install another.+ let pick = dirs[0];+ if (name) {+ const found =+ dirs.find((d) => d.name === name) ??+ dirs.find((d) => readSkillDirMeta(d.dir)?.name === name);+ if (!found) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Named skill not in source.', {+ handler: 'skills-preview',+ detail: `"${name}" not among: ${dirs.map((d) => d.name).join(', ')}.`,+ });+ return;+ }+ pick = found;+ }+ const tooLarge = acquiredBundleTooLarge(pick.dir);+ if (tooLarge) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Skill bundle is too large.', {+ handler: 'skills-preview',+ detail: tooLarge,+ });+ return;+ }+ const parsed = parseSkillDir(pick.dir);+ if (!parsed) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'SKILL.md unreadable in source.', {+ handler: 'skills-preview',+ });+ return;+ }+ const plugin = inspectPluginSource(source);+ // The skills.sh source repo may itself be a plugin bundling several+ // skills — skills.sh never flags that, but the clone carries the+ // manifest and we already have it in hand (`fetched.dir`). Read-only.+ const pluginBundle = inspectPluginBundleDir(fetched.dir);+ successResponse(+ res,+ 200,+ SkillPreviewSchema,+ {+ name: parsed.name,+ description: parsed.description,+ skillMd: parsed.skillMd,+ // Strip raw `bytes` (binary files) — a preview renders text or shows+ // the file as binary (`content: null`); the bytes are not JSON-safe+ // and only matter on import.+ files: parsed.files.map((f) => ({ relPath: f.relPath, content: f.content })),+ plugin: plugin ?? undefined,+ pluginBundle: pluginBundle ?? undefined,+ },+ { handler: 'skills-preview' },+ );+ } catch (e) {+ if (e instanceof SkillFetchError) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {+ handler: 'skills-preview',+ cause: e,+ });+ return;+ }+ errorResponse(res, 502, 'urn:ok:error:internal-server-error', 'Preview is unavailable.', {+ handler: 'skills-preview',+ cause: e,+ });+ } finally {+ cleanup?.();+ }+ },+ { handler: 'skills-preview', method: 'GET', skipBodyParse: true },+ );++ // `GET /api/skills/discover?source=` enumerates a repository/local tree or a+ // website's well-known index so the Import modal can offer an exact picker.+ // ponytail: remote indexes/repos are fetched per call; cache by source+ref if+ // debounced typing churn becomes a problem.+ const handleSkillsDiscover = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ const url = new URL(req.url ?? '', 'http://localhost');+ const source = url.searchParams.get('source')?.trim() ?? '';+ if (!source) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'source is required.', {+ handler: 'skills-discover',+ });+ return;+ }+ const websiteSource = parseSkillsShWebsiteSource(source);+ if (websiteSource) {+ try {+ const skills = await discoverWellKnownSkills(`https://${websiteSource.hostname}`);+ successResponse(+ res,+ 200,+ SkillDiscoverSchema,+ { skills },+ { handler: 'skills-discover' },+ );+ } catch (error) {+ if (error instanceof SkillFetchError) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {+ handler: 'skills-discover',+ cause: error,+ });+ return;+ }+ throw error;+ }+ return;+ }+ const spec = parseSource(source);+ if (!spec) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unrecognized source.', {+ handler: 'skills-discover',+ detail: 'Expected owner/repo, a git URL, a website source, or a local path.',+ });+ return;+ }+ if (rejectDisallowedGitSpec(res, spec, 'skills-discover')) return;+ let cleanup: (() => void) | undefined;+ try {+ const fetched = await fetchSource(spec);+ cleanup = fetched.cleanup;+ const dirs = discoverSkillDirs(fetched.dir);+ // Prefer the SKILL.md frontmatter name (what the import path matches and+ // what a user recognizes); fall back to the dir basename.+ const skills = dirs.map((d) => {+ // Metadata-only: a listing has no use for bundle bytes, and reading+ // them for every skill in a large repo is how a preview turns into an+ // out-of-memory kill.+ const meta = readSkillDirMeta(d.dir);+ return { name: meta?.name ?? d.name, description: meta?.description ?? null };+ });+ successResponse(res, 200, SkillDiscoverSchema, { skills }, { handler: 'skills-discover' });+ } catch (e) {+ if (e instanceof SkillFetchError) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {+ handler: 'skills-discover',+ cause: e,+ });+ return;+ }+ errorResponse(res, 502, 'urn:ok:error:internal-server-error', 'Discovery is unavailable.', {+ handler: 'skills-discover',+ cause: e,+ });+ } finally {+ cleanup?.();+ }+ },+ { handler: 'skills-discover', method: 'GET', skipBodyParse: true },+ );++ // `GET /api/skills/resolve-ref?ref=<name>&scope=<scope>&from=<skill>` — resolve+ // a skill's `/other-skill` reference by TRUSTED-PROVENANCE precedence, never a+ // marketplace-wide name search (that would import a stranger's same-name skill+ // thinking it's the dependency). Ladder: (1) already installed → local; (2) a+ // sibling in the referencing skill's own origin repo/plugin → import via+ // source; (3) a same-publisher skills.sh result with the exact name → import+ // via publisher; else none, and the caller offers MANUAL Explore search.+ const handleSkillsResolveRef = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ const url = new URL(req.url ?? '', 'http://localhost');+ const ref = url.searchParams.get('ref')?.trim() ?? '';+ const from = url.searchParams.get('from')?.trim() ?? '';+ const scope = url.searchParams.get('scope')?.trim() === 'global' ? 'global' : 'project';+ if (!ref || !SKILL_NAME_REGEX.test(ref) || ref.length > 64) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'A valid ref is required.', {+ handler: 'skills-resolve-ref',+ });+ return;+ }+ // Top-level guard like every sibling skills handler: `readSkillsLockFile`+ // (existsSync → readFileSync) can throw on EACCES / a TOCTOU race, and an+ // unguarded throw would surface as a context-less 500 from the outer+ // catch.+ try {+ const respond = (resolution: SkillRefResolution) =>+ successResponse(res, 200, SkillRefResolutionSchema, resolution, {+ handler: 'skills-resolve-ref',+ });++ // 1. LOCAL — same scope first, then the other. Already-present wins: it's+ // what the user chose to have, and importing a same-name skill would fork.+ for (const s of [scope, scope === 'project' ? 'global' : 'project'] as const) {+ const realDir = resolveSkillDirForRead(s, ref);+ if (realDir !== null) {+ // Return the REAL dir, not just the name: the caller opens this skill,+ // and deriving the doc name from the name alone assumes the retired+ // store layout.+ respond({+ kind: 'local',+ scope: s,+ name: ref,+ dir: relative(s === 'project' ? contentDir : skillsHome, realDir)+ .split(sep)+ .join('/'),+ });+ return;+ }+ }++ // Referencing skill's provenance from its scope lockfile (import origin).+ const lockBase = scope === 'project' ? projectDir : skillsHome;+ const entry =+ from && lockBase+ ? readSkillsLockFile(join(lockBase, ...SKILLS_LOCK_REL)).skills[from]+ : undefined;++ // 2. SAME SOURCE — a sibling in the referencing skill's own repo/plugin.+ // (A plugin's siblings resolve here too: its source is the plugin dir.)+ if (entry?.source) {+ const resolvedSkillsSh = await resolveSkillsShImportSource(entry.source, ref);+ const spec = resolvedSkillsSh?.spec ?? parseSource(entry.source);+ const allowed = spec && !(spec.kind === 'git' && !isAllowedGitUrl(spec.url));+ if (spec && allowed) {+ let cleanup: (() => void) | undefined;+ try {+ const fetched = await fetchSource(spec);+ cleanup = fetched.cleanup;+ const names = discoverSkillDirs(fetched.dir).map(+ (d) => readSkillDirMeta(d.dir)?.name ?? d.name,+ );+ if (names.includes(ref)) {+ respond({ kind: 'import', source: entry.source, ref, via: 'source' });+ return;+ }+ } catch (err) {+ // Source unreachable (clone failure / bad source) — fall through to+ // the publisher rung, but leave a trail so a stale/deleted origin+ // repo doesn't degrade ref resolution silently.+ log.debug(+ { err, ref, from, source: entry.source },+ 'resolve-ref: source rung unreachable, falling through to publisher',+ );+ } finally {+ cleanup?.();+ }+ }+ }++ // 3. SAME PUBLISHER — a same-publisher skills.sh result with the EXACT name.+ // Constrained (publisher + exact name), not a fuzzy match; a unique hit only.+ if (entry?.publisher) {+ try {+ const r = await fetch(+ `https://skills.sh/api/search?q=${encodeURIComponent(ref)}&limit=30`,+ { signal: AbortSignal.timeout(8000) },+ );+ if (r.ok) {+ const matches = parseSkillsShSearch(await r.json()).filter(+ (x) => x.name === ref && x.publisher === entry.publisher,+ );+ if (matches.length === 1) {+ const match = matches[0];+ if (match) {+ respond({ kind: 'import', source: match.source, ref, via: 'publisher' });+ return;+ }+ }+ }+ } catch (err) {+ // skills.sh unreachable or a malformed (e.g. HTML during an outage)+ // response — no publisher resolution this call. Log so an outage is+ // distinguishable from "skill genuinely absent from this publisher".+ log.debug(+ { err, ref, publisher: entry.publisher },+ 'resolve-ref: skills.sh unavailable, no publisher resolution',+ );+ }+ }++ // 4. NONE — no trusted signal. The caller keeps the missing-ref marker+ // and offers manual Explore search; OK never auto-picks a fuzzy match.+ respond({ kind: 'none' });+ } catch (err) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Could not resolve the reference.',+ {+ handler: 'skills-resolve-ref',+ cause: err instanceof Error ? err : new Error(String(err)),+ },+ );+ }+ },+ { handler: 'skills-resolve-ref', method: 'GET', skipBodyParse: true },+ );++ return {+ handleSkillsSearch,+ handleSkillsPopular,+ handleSkillsDetail,+ handleSkillsPreview,+ handleSkillsDiscover,+ handleSkillsResolveRef,+ };+}