DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
refactor(dsh-tauri-panel-extension): reshape the routes into REST resources
hairyfb8651e4271fe
diff --git a/packages/dsh-tauri-panel-extension/docs/upstream-sync-log.md b/packages/dsh-tauri-panel-extension/docs/upstream-sync-log.mdindex a426d1c0..65bf3833 100644--- a/packages/dsh-tauri-panel-extension/docs/upstream-sync-log.md+++ b/packages/dsh-tauri-panel-extension/docs/upstream-sync-log.md@@ -55,7 +55,7 @@## 有意保留的差异-- 侧栏扩展继续使用自身 API 前缀 `/dsh-tauri-panel-extension/*`,不改为上游的 `/dsh-plugin-capabilities/*`。+- 侧栏扩展的路由前缀随桌面统一为 `/api/desktop/dsh-tauri-panel-extension/*`,不改为上游的 `/dsh-plugin-capabilities/*`。- MCP 管理继续写入当前扩展约定的 profile / DSH home 路径。- 不移植上游设置页的“技能与 MCP”一级标题。- 不移植上游 Market(技能市场 / MCP 市场)模块。diff --git a/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.tsx b/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.tsxindex 9b82337a..2b32d834 100644--- a/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.tsx+++ b/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.tsx@@ -1,11 +1,12 @@import type { ReactElement } from 'react'-import type { McpRow } from '../apis/index.type'+import type { McpSaveBody } from '../apis/index.type'+import type { McpRow } from '../types'import type { McpEditorMode, McpEditorState, McpImportItem, McpTabProps } from './mcp-tab.types'import { Button, Modal, StateDot } from '@deepseek-ai/dsh-client-ui-primitives'import { ArrowRotateRight, Icon, PlugConnection, useMountStyle } from 'dsh-tauri-ui/client'import { compact } from 'dsh-tauri/client'import { useEffect, useState } from 'react'-import { getMcp, getMcpImportScan, postMcpCheck, postMcpImportApply, postMcpRemove, postMcpSave, postMcpToggle } from '../apis'+import { deleteMcp, getImportScan, getMcp, postImportApply, postMcp, postMcpCheck, postMcpToggle } from '../apis'import { MCP_RESTART_INITIAL_DELAY_MS, MCP_RESTART_POLL_INTERVAL_MS, MCP_RESTART_TIMEOUT_MS, MCP_TAB_STYLE_ID } from '../constants'import { useTimers } from '../hooks/use-timers'import { restartHost } from '../service/restart'@@ -34,14 +35,17 @@ export function McpTab({ t }: McpTabProps): ReactElement {const [pasteError, setPasteError] = useState<string | null>(null)const [scope, setScope] = useState<'all' | 'global' | 'profile'>('all')const [checking, setChecking] = useState<string | null>(null)+ const [globalError, setGlobalError] = useState('')const { later } = useTimers()useEffect(() => {let current = truevoid getMcp().then((body) => {- if (current)+ if (current) {setServers(body.servers)+ setGlobalError(body.globalError ?? '')+ }},(error: Error) => {if (current) {@@ -59,7 +63,7 @@ export function McpTab({ t }: McpTabProps): ReactElement {setImportOpen(true)setImportItems(null)try {- const body = await getMcpImportScan()+ const body = await getImportScan()const existing = new Set(body.existing)setImportItems(body.servers.map(server => ({server,@@ -79,7 +83,7 @@ export function McpTab({ t }: McpTabProps): ReactElement {const items = importItems.filter(item => item.checked && !item.existing).map(item => ({ agent: item.server.agent, name: item.server.name }))setBusy(true)try {- const body = await postMcpImportApply({ items })+ const body = await postImportApply({ items })const failed = body.results.filter(item => !item.ok)setOutcome(failed.length === 0? null@@ -100,7 +104,7 @@ export function McpTab({ t }: McpTabProps): ReactElement {setChecking(row.id)try {const result = await postMcpCheck({ id: row.id })- setOutcome({ ok: result.ok, text: result.ok ? `${t('connectivityOk')}${result.latencyMs ? ` (${result.latencyMs}ms)` : ''}` : `${t('connectivityFailed')}: ${result.error ?? ''}` })+ setOutcome({ ok: result.ok, text: result.ok ? `${t('connectivityOk')}${result.detail ? ` (${result.detail})` : ''}` : `${t('connectivityFailed')}: ${result.detail ?? ''}` })}catch (error) {setOutcome({ ok: false, text: `${t('connectivityFailed')}: ${String(error)}` })@@ -175,7 +179,7 @@ export function McpTab({ t }: McpTabProps): ReactElement {const doSave = async (): Promise<void> => {if (editor === null)return- let input: Record<string, unknown>+ let input: McpSaveBodyif (editorMode === 'json') {const parsed = parseMcpJson(pasteJson)if ('error' in parsed) {@@ -212,7 +216,7 @@ export function McpTab({ t }: McpTabProps): ReactElement {setFormError(null)setPasteError(null)try {- await postMcpSave(input)+ await postMcp(input)setEditor(null)setOutcome(null)reloadList(true)@@ -245,7 +249,7 @@ export function McpTab({ t }: McpTabProps): ReactElement {returnsetBusy(true)try {- await postMcpRemove({ id: confirmId })+ await deleteMcp({ id: confirmId })setOutcome(null)reloadList(true)}@@ -350,7 +354,7 @@ export function McpTab({ t }: McpTabProps): ReactElement {{row.transport === 'stdio' ? `${row.command ?? ''} ${(row.args ?? []).join(' ')}` : row.url ?? ''}</p>{row.shadowed === true && <p className="dshp-extension__form-error">{t('shadowedByGlobal')}</p>}- {row.globalError !== undefined && <p className="dshp-extension__form-error">{row.globalError}</p>}+ {globalError !== '' && <p className="dshp-extension__form-error">{globalError}</p>}<div className="dshp-extension__card-row"><span className="dshp-extension__spacer" /><Button variant="ghost" size="sm" disabled={busy || checking === row.id} onClick={() => void checkConnectivity(row)}>{checking === row.id ? t('checkRunning') : t('checkLabel')}</Button>diff --git a/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.types.ts b/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.types.tsindex 624871e0..6c98da7a 100644--- a/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.types.ts+++ b/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.types.ts@@ -1,5 +1,5 @@-import type { ImportedServerView } from '../apis/index.type'import type { Translate } from '../locales/index.types'+import type { ImportedServerView } from '../types'export type McpEditorMode = 'json' | 'form'diff --git a/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.tsx b/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.tsxindex 311ecedb..1dfe92c2 100644--- a/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.tsx+++ b/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.tsx@@ -1,11 +1,11 @@import type { ReactElement } from 'react'-import type { SkillRowView } from '../apis/index.type'+import type { SkillRowView } from '../types'import type { OpenTarget, SkillEditorState, SkillsTabProps } from './skills-tab.types'import { Button, Modal, StateDot } from '@deepseek-ai/dsh-client-ui-primitives'import { ArrowRotateRight, GraduationCap, Icon, LogoGithub, useMountStyle } from 'dsh-tauri-ui/client'import { orderBy, uniq } from 'dsh-tauri/client'import { useEffect, useMemo, useState } from 'react'-import { getSkill, getSkills, postOpen, postRootsAdd, postSkillDelete, postSkillPolicy, postSkillSave, postSkillsRefresh } from '../apis'+import { deleteSkill, getSkill, getSkills, postOpenDir, postRoots, postSkill, postSkillPolicy, postSkillsRefresh } from '../apis'import { MarkdownPreview } from '../components/markdown'import { IMPORT_REFRESH_DELAYS_MS, SKILL_REFRESH_INTERVAL_MS, SKILL_REFRESH_TIMEOUT_MS, SKILLS_TAB_STYLE_ID, SOURCE_LOCALE_KEYS } from '../constants'import { useTimers } from '../hooks/use-timers'@@ -79,7 +79,7 @@ export function SkillsTab({ t, createSkill }: SkillsTabProps): ReactElement {const openExisting = async (skill: SkillRowView): Promise<void> => {setBusy(true)try {- const body = await getSkill(skill.name)+ const body = await getSkill({ name: skill.name })setPreview(!skill.editable)setEditor({ mode: skill.editable ? 'edit' : 'view', name: skill.name, description: skill.description, whenToUse: skill.whenToUse ?? '', modelInvocable: skill.invocation.modelInvocable, userInvocable: skill.invocation.userInvocable, content: body.content })}@@ -94,7 +94,7 @@ export function SkillsTab({ t, createSkill }: SkillsTabProps): ReactElement {setBusy(true)setFormError(null)try {- await postSkillSave({ name: editor.name.trim(), description: editor.description, whenToUse: editor.whenToUse.trim() || undefined, modelInvocable: editor.modelInvocable, userInvocable: editor.userInvocable, content: editor.content })+ await postSkill({ name: editor.name.trim(), description: editor.description, whenToUse: editor.whenToUse.trim() || undefined, modelInvocable: editor.modelInvocable, userInvocable: editor.userInvocable, content: editor.content })setEditor(null)setOutcome({ ok: true, text: t('saved') })refreshUntil(rows => rows.some(row => row.name === name))@@ -109,7 +109,7 @@ export function SkillsTab({ t, createSkill }: SkillsTabProps): ReactElement {const name = confirmNamesetBusy(true)try {- await postSkillDelete({ name })+ await deleteSkill({ name })setOutcome({ ok: true, text: t('saved') })refreshUntil(rows => !rows.some(row => row.name === name))}@@ -137,7 +137,7 @@ export function SkillsTab({ t, createSkill }: SkillsTabProps): ReactElement {const doOpen = async (target: OpenTarget): Promise<void> => {try {- await postOpen(target)+ await postOpenDir(target)}catch (error) { setOutcome({ ok: false, text: `${t('failed')}: ${error instanceof Error ? error.message : String(error)}` }) }}@@ -163,7 +163,7 @@ export function SkillsTab({ t, createSkill }: SkillsTabProps): ReactElement {setBusy(true)setFormError(null)try {- await postRootsAdd(url)+ await postRoots({ kind: 'git', url })setOutcome({ ok: true, text: t('importRepositorySuccess') })setImportOpen(false)setRepositoryUrl('')diff --git a/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.utils.ts b/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.utils.tsindex 69e08256..fe2728bf 100644--- a/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.utils.ts+++ b/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.utils.ts@@ -1,5 +1,5 @@-import type { SkillRowView } from '../apis/index.type'import type { LocaleKey } from '../locales/index.types'+import type { SkillRowView } from '../types'import { GITHUB_REPOSITORY_PATTERN } from '../constants'export function policyTag(skill: SkillRowView): { key?: LocaleKey, off: boolean } {diff --git a/packages/dsh-tauri-panel-extension/src/client/constants/index.ts b/packages/dsh-tauri-panel-extension/src/client/constants/index.tsindex e0c8ae99..49989b04 100644--- a/packages/dsh-tauri-panel-extension/src/client/constants/index.ts+++ b/packages/dsh-tauri-panel-extension/src/client/constants/index.ts@@ -1,7 +1,7 @@import type { LocaleKey } from '../locales/index.types'import { PLUGIN_ID } from '../../shared/constants'-export { API_PREFIX, PLUGIN_ID as PLUGIN_ID } from '../../shared/constants'+export { PLUGIN_ID } from '../../shared/constants'export const CONVERSATION_INPUT_LEFT_SLOT = 'conversation.input.left'export const PANEL_ID = PLUGIN_IDdiff --git a/packages/dsh-tauri-panel-extension/src/client/service/restart.ts b/packages/dsh-tauri-panel-extension/src/client/service/restart.tsindex 246115a2..9477a059 100644--- a/packages/dsh-tauri-panel-extension/src/client/service/restart.ts+++ b/packages/dsh-tauri-panel-extension/src/client/service/restart.ts@@ -1,4 +1,4 @@-import { postRestart } from '../apis'+import { postHostRestart } from '../apis'import { isDesktopHost } from './restart.utils'export async function restartHost(): Promise<{ ok: boolean, error?: string }> {@@ -7,7 +7,7 @@ export async function restartHost(): Promise<{ ok: boolean, error?: string }> {return { ok: true }}try {- await postRestart()+ await postHostRestart()}catch {}diff --git a/packages/dsh-tauri-panel-extension/src/client/types/index.ts b/packages/dsh-tauri-panel-extension/src/client/types/index.tsnew file mode 100644index 00000000..ce5fc951--- /dev/null+++ b/packages/dsh-tauri-panel-extension/src/client/types/index.ts@@ -0,0 +1 @@+export type { ImportedServerView, McpRowView as McpRow, SkillRowView } from '../apis/index.type'diff --git a/packages/dsh-tauri-panel-extension/src/host/apply.ts b/packages/dsh-tauri-panel-extension/src/host/apply.tsindex 78228926..ef744e36 100644--- a/packages/dsh-tauri-panel-extension/src/host/apply.ts+++ b/packages/dsh-tauri-panel-extension/src/host/apply.ts@@ -1,15 +1,16 @@import type { HostContext } from 'dsh-tauri'import type { Config } from './apply.types'-import type { PanelExtensionHost } from './config/runtime.types'+import type { PanelExtensionHost } from './types'import { fileURLToPath } from 'node:url'import { dirname, join } from 'pathe'import { PLUGIN_ID } from '../shared/constants'-import { DEFAULT_PROFILE } from './config/constants'import { clearHostRuntime, resetProviderRuntime, setCurrentHostInstance } from './config/runtime'import { routes } from './routes'import { profile } from './service/profile'import { provider } from './service/provider'+const DEFAULT_PROFILE = 'web'+export type { Config } from './apply.types'export const name = PLUGIN_IDdiff --git a/packages/dsh-tauri-panel-extension/src/host/config/constants.ts b/packages/dsh-tauri-panel-extension/src/host/config/constants.tsindex 20b64d67..58881f2e 100644--- a/packages/dsh-tauri-panel-extension/src/host/config/constants.ts+++ b/packages/dsh-tauri-panel-extension/src/host/config/constants.ts@@ -1,43 +1,9 @@-export const PLUGIN_STATE_DIRECTORY = 'dsh-tauri-panel-extension'+import { DSH_HOME } from 'dsh-tauri'+import { join } from 'pathe'-export const DEFAULT_PROFILE = 'web'--export const PROFILES_DIRECTORY = 'profiles'-export const SKILL_DATA_DIRECTORY = 'skills'-export const REPOS_DIRECTORY = 'repos'export const SKILL_FILE_NAME = 'SKILL.md'-export const STATE_FILE_NAME = 'state.json'+export const SKILLS_DATA_DIR = join(DSH_HOME, 'skills')export const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/-export const SKILL_FILE_PATTERN = /[/\\]SKILL\.md$/-export const SKILL_DOCUMENT_PATTERN = /[/\\][^/\\]+\.md$/-export const SKILL_DESCRIPTION_MAX_LENGTH = 1024-export const SKILL_WHEN_TO_USE_MAX_LENGTH = 2048-export const SKILL_CONTENT_MAX_BYTES = 256 * 1024-export const MCP_PLUGIN = '@deepseek-ai/dsh-mcp-client'-export const SERVER_NAME_RE = /^[\w-]{1,32}$/export const PATCH_FILE_NAME = 'cordis.patch.yml'-export const EMPTY_PATCH = '[]'-export const MCP_CHECK_TIMEOUT_MS = 5_000--export const GITHUB_URL_RE = /^(?:https?:\/\/)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(?:tree|archive)\/([^/#?]+?)(?:\.tar\.gz)?)?(?:#([^/?#]+))?(?:[/?#].*)?$/-export const GITHUB_SHORT_RE = /^([\w.-]+)\/([\w.-]+)$/-export const GITHUB_FETCH_TIMEOUT_MS = 60_000-export const TARBALL_MAX_BYTES = 256 * 1024 * 1024--export const TAR_LIMITS = {- entryBytes: 64 * 1024 * 1024,- totalBytes: 256 * 1024 * 1024,- entries: 20_000,-} as const--export const RMTREE_RETRIES = { maxRetries: 10, retryDelay: 200 } as const--export const RESTART_KILL_DELAY_MS = 500--export const CLAUDE_MCP_FILES = ['.claude/settings.json', '.claude.json'] as const-export const CURSOR_MCP_FILE = '.cursor/mcp.json'-export const GEMINI_MCP_FILE = '.gemini/settings.json'-export const CODEX_MCP_FILE = '.codex/config.toml'-export const AGENT_SKILL_DIRECTORIES = ['.claude/skills', '.codex/skills'] as constdiff --git a/packages/dsh-tauri-panel-extension/src/host/config/runtime.ts b/packages/dsh-tauri-panel-extension/src/host/config/runtime.tsindex c776a251..e6da813f 100644--- a/packages/dsh-tauri-panel-extension/src/host/config/runtime.ts+++ b/packages/dsh-tauri-panel-extension/src/host/config/runtime.ts@@ -1,5 +1,5 @@import type { ProviderRuntime } from '../service/provider.types'-import type { PanelExtensionHost } from './runtime.types'+import type { PanelExtensionHost } from '../types'import { defineHostRuntime } from 'dsh-tauri'export const { setCurrentHostInstance, getCurrentHostInstance } = defineHostRuntime<PanelExtensionHost>()diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/restart/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/host/restart/post.tssimilarity index 94%rename from packages/dsh-tauri-panel-extension/src/host/routes/restart/post.tsrename to packages/dsh-tauri-panel-extension/src/host/routes/host/restart/post.tsindex 9116e0b1..f6503812 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/restart/post.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/host/restart/post.ts@@ -1,5 +1,5 @@import { defineEventHandler } from 'dsh-tauri'-import { restart } from '../../service/restart'+import { restart } from '../../../service/restart'export default defineEventHandler((event) => {const headers = event.req.headersdiff --git a/packages/dsh-tauri-panel-extension/src/host/routes/import/apply/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/import/apply/post.tsindex 5984f9ec..da62bd4a 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/import/apply/post.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/import/apply/post.ts@@ -1,13 +1,12 @@+import type { EventHandlerRequest } from 'dsh-tauri'import type { McpInput } from '../../../service/mcp.types'-import type { ExtensionRouteDeps } from '../../index.types'+import type { ExtensionRouteDeps, McpApplyImportResponse, McpImportApplyBody } from '../../index.types'import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'import { agents } from '../../../service/agents'import { mcp } from '../../../service/mcp'import { mcpScopeDir, normalizeMcpScope, validateMcpInput } from '../../../service/mcp.utils'-interface McpImportApplyBody { items?: unknown, scope?: unknown }--export default defineEventHandler(async (event) => {+export default defineEventHandler<EventHandlerRequest, Promise<McpApplyImportResponse | { error: string }>>(async (event) => {const deps = dshRouteDepsOf<ExtensionRouteDeps>(event)!const body = await readBody<McpImportApplyBody>(event, { type: 'json' })try {diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/import/scan/get.ts b/packages/dsh-tauri-panel-extension/src/host/routes/import/scan/get.tsindex d5460519..1bcb749c 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/import/scan/get.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/import/scan/get.ts@@ -1,9 +1,9 @@-import type { ExtensionRouteDeps } from '../../index.types'+import type { ExtensionRouteDeps, McpImportScanResponse } from '../../index.types'import { defineEventHandler, dshRouteDepsOf } from 'dsh-tauri'import { agents } from '../../../service/agents'import { mcp } from '../../../service/mcp'-export default defineEventHandler((event) => {+export default defineEventHandler((event): McpImportScanResponse | { error: string } => {const deps = dshRouteDepsOf<ExtensionRouteDeps>(event)!try {return {diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/index.test.ts b/packages/dsh-tauri-panel-extension/src/host/routes/index.test.tsindex 9b051511..29ec6c77 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/index.test.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/index.test.ts@@ -1,7 +1,7 @@import type { HostRoute, RoutesContext } from 'dsh-tauri'import type { IncomingMessage, Server, ServerResponse } from 'node:http'import type { AddressInfo } from 'node:net'-import type { PanelExtensionHost } from '../config/runtime.types'+import type { PanelExtensionHost } from '../types'import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'import { createServer } from 'node:http'import { tmpdir } from 'node:os'@@ -9,7 +9,6 @@ import { join } from 'pathe'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { routes } from '.'import { resetTestDshHome } from '../../../../.test/test-utils'-import { API_PREFIX as P } from '../../shared/constants'import { setCurrentHostInstance } from '../config/runtime'vi.mock('dsh-tauri', async (importOriginal) => {@@ -18,30 +17,47 @@ vi.mock('dsh-tauri', async (importOriginal) => {return { ...actual, DSH_HOME: home }})+const P = '/api/desktop/dsh-tauri-panel-extension'+const routeKey = (kind: string, path: string): string => `${kind}\u0000${path}`const EXPECTED_ROUTES: ReadonlyArray<readonly [string, string]> = [['GET', `${P}/skills`],['POST', `${P}/skills/refresh`],['GET', `${P}/skill`],- ['POST', `${P}/skill/save`],- ['POST', `${P}/skill/delete`],+ ['POST', `${P}/skill`],+ ['DELETE', `${P}/skill`],['POST', `${P}/skill/policy`],- ['POST', `${P}/open`],+ ['POST', `${P}/open/dir`],['GET', `${P}/mcp`],- ['POST', `${P}/mcp/save`],+ ['POST', `${P}/mcp`],+ ['DELETE', `${P}/mcp`],['POST', `${P}/mcp/toggle`],- ['POST', `${P}/mcp/remove`],['POST', `${P}/mcp/check`],['POST', `${P}/mcp/copy`],['GET', `${P}/import/scan`],['POST', `${P}/import/apply`],['GET', `${P}/roots`],- ['POST', `${P}/roots/add`],- ['POST', `${P}/roots/remove`],- ['POST', `${P}/restart`],+ ['POST', `${P}/roots`],+ ['DELETE', `${P}/roots`],+ ['POST', `${P}/host/restart`],]+/** 同一路径的多个方法由 defineRoutes 收敛为一行注册。 */+const EXPECTED_PATHS: readonly string[] = [...new Set(EXPECTED_ROUTES.map(([, path]) => path))]++const ALLOW_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const++function allowFor(path: string): string {+ const methods = new Set(EXPECTED_ROUTES.filter(([, candidate]) => candidate === path).map(([method]) => method))+ if (methods.has('GET'))+ methods.add('HEAD')+ return ALLOW_ORDER.filter(method => method === 'OPTIONS' || methods.has(method)).join(', ')+}++/** 所有路径都未声明 PATCH,用于统一验证 405 + allow。 */+const UNDECLARED_METHOD = 'PATCH'+const SKILL = {name: 'demo-skill',description: 'A demo skill',@@ -136,32 +152,26 @@ afterEach(async () => {})describe('能力管理器路由声明', () => {- it('按迁移前的路径与方法声明 19 条 exact 路由,卸载后清空注册', () => {+ it('按资源化的路径与方法声明 exact 路由,卸载后清空注册', () => {const harness = createHarness()dirs.push(harness.dir)const dispose = mount(harness)expect([...harness.registered.keys()].sort())- .toEqual(EXPECTED_ROUTES.map(([, path]) => routeKey('exact', path)).sort())- expect(harness.registered.size).toBe(19)+ .toEqual(EXPECTED_PATHS.map(path => routeKey('exact', path)).sort())+ expect(harness.registered.size).toBe(EXPECTED_PATHS.length)dispose()expect(harness.registered.size).toBe(0)})- it('读路由拒绝变更方法,变更路由拒绝读方法(405 + allow 头)', async () => {+ it('未声明的方法拒绝访问(405 + allow 头)', async () => {const { base, dispose } = await start()- const wrongMethodOnRead = await fetch(`${base}${P}/skills`, { method: 'POST' })- expect(wrongMethodOnRead.status).toBe(405)- expect(wrongMethodOnRead.headers.get('allow')).toBe('GET, HEAD, OPTIONS')-- const mutatePaths = EXPECTED_ROUTES.filter(([method]) => method === 'POST').map(([, path]) => path)- expect(mutatePaths).toHaveLength(14)- for (const path of mutatePaths) {- const response = await fetch(`${base}${path}`)+ for (const path of EXPECTED_PATHS) {+ const response = await fetch(`${base}${path}`, { method: UNDECLARED_METHOD })expect(response.status, path).toBe(405)- expect(response.headers.get('allow'), path).toBe('POST, OPTIONS')+ expect(response.headers.get('allow'), path).toBe(allowFor(path))}dispose()@@ -172,9 +182,9 @@ describe('能力管理器路由声明', () => {const read = await fetch(`${base}${P}/mcp`, { method: 'OPTIONS' })expect(read.status).toBe(204)- expect(read.headers.get('allow')).toBe('GET, HEAD, OPTIONS')+ expect(read.headers.get('allow')).toBe('GET, HEAD, POST, DELETE, OPTIONS')- const mutate = await fetch(`${base}${P}/mcp/save`, { method: 'OPTIONS' })+ const mutate = await fetch(`${base}${P}/mcp/toggle`, { method: 'OPTIONS' })expect(mutate.status).toBe(204)expect(mutate.headers.get('allow')).toBe('POST, OPTIONS')@@ -229,18 +239,18 @@ describe('能力管理器路由声明', () => {it('pOST 变更路由对缺失字段返回 400 领域错误', async () => {const { base, dispose } = await start()- const cases: ReadonlyArray<readonly [string, Record<string, unknown>, string]> = [- [`${P}/mcp/toggle`, {}, 'id and disabled are required'],- [`${P}/mcp/remove`, {}, 'id is required'],- [`${P}/mcp/check`, {}, 'id is required'],- [`${P}/mcp/copy`, {}, 'id is required'],- [`${P}/roots/remove`, {}, 'id is required'],- [`${P}/roots/add`, { kind: 'zip' }, 'kind must be local or git'],- [`${P}/open`, {}, 'target is required'],+ const cases: ReadonlyArray<readonly [string, string, Record<string, unknown>, string]> = [+ ['POST', `${P}/mcp/toggle`, {}, 'id and disabled are required'],+ ['DELETE', `${P}/mcp`, {}, 'id is required'],+ ['POST', `${P}/mcp/check`, {}, 'id is required'],+ ['POST', `${P}/mcp/copy`, {}, 'id is required'],+ ['DELETE', `${P}/roots`, {}, 'id is required'],+ ['POST', `${P}/roots`, { kind: 'zip' }, 'kind must be local or git'],+ ['POST', `${P}/open/dir`, {}, 'target is required'],]- for (const [path, body, error] of cases) {+ for (const [method, path, body, error] of cases) {const response = await fetch(`${base}${path}`, {- method: 'POST',+ method,headers: { 'content-type': 'application/json' },body: JSON.stringify(body),})@@ -271,14 +281,14 @@ describe('能力管理器路由声明', () => {dispose()})- it('pOST /restart 拒绝无 Origin 或带转发痕迹的请求(403,不触达进程控制)', async () => {+ it('pOST /host/restart 拒绝无 Origin 或带转发痕迹的请求(403,不触达进程控制)', async () => {const { base, dispose } = await start()- const noOrigin = await fetch(`${base}${P}/restart`, { method: 'POST' })+ const noOrigin = await fetch(`${base}${P}/host/restart`, { method: 'POST' })expect(noOrigin.status).toBe(403)expect(await noOrigin.json()).toEqual({ error: 'untrusted origin' })- const forwarded = await fetch(`${base}${P}/restart`, {+ const forwarded = await fetch(`${base}${P}/host/restart`, {method: 'POST',headers: { 'origin': base, 'x-forwarded-for': '127.0.0.1' },})@@ -299,7 +309,7 @@ describe('能力管理器路由声明', () => {const firstBase = await listen(first.registered)const secondBase = await listen(second.registered)- const saved = await fetch(`${firstBase}${P}/mcp/save`, {+ const saved = await fetch(`${firstBase}${P}/mcp`, {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({ serverName: 'only-first', transport: 'http', url: 'http://127.0.0.1:9/mcp' }),diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/index.ts b/packages/dsh-tauri-panel-extension/src/host/routes/index.tsindex 070e3732..02020e73 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/index.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/index.ts@@ -1,48 +1,47 @@import type { ExtensionRouteDeps } from './index.types'import { defineRoutes } from 'dsh-tauri'-import { API_PREFIX } from '../../shared/constants'+import restart from './host/restart/post'import importApply from './import/apply/post'import importScan from './import/scan/get'import mcpCheck from './mcp/check/post'import mcpCopy from './mcp/copy/post'+import mcpRemove from './mcp/delete'import mcp from './mcp/get'-import mcpRemove from './mcp/remove/post'-import mcpSave from './mcp/save/post'+import mcpSave from './mcp/post'import mcpToggle from './mcp/toggle/post'-import open from './open/post'-import restart from './restart/post'-import rootsAdd from './roots/add/post'+import openDir from './open/dir/post'+import rootsRemove from './roots/delete'import roots from './roots/get'-import rootsRemove from './roots/remove/post'-import skillDelete from './skill/delete/post'+import rootsAdd from './roots/post'+import skillDelete from './skill/delete'import skill from './skill/get'import skillPolicy from './skill/policy/post'-import skillSave from './skill/save/post'+import skillSave from './skill/post'import skills from './skills/get'import skillsRefresh from './skills/refresh/post'export const routes = defineRoutes<ExtensionRouteDeps>((disposer) => {- disposer.get({ kind: 'exact', path: `${API_PREFIX}/skills` }, skills)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/skills/refresh` }, skillsRefresh)- disposer.get({ kind: 'exact', path: `${API_PREFIX}/skill` }, skill)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/skill/save` }, skillSave)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/skill/delete` }, skillDelete)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/skill/policy` }, skillPolicy)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/open` }, open)+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/skills' }, skills)+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/skills/refresh' }, skillsRefresh)+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/skill' }, skill)+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/skill' }, skillSave)+ disposer.delete({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/skill' }, skillDelete)+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/skill/policy' }, skillPolicy)+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/open/dir' }, openDir)- disposer.get({ kind: 'exact', path: `${API_PREFIX}/mcp` }, mcp)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/mcp/save` }, mcpSave)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/mcp/toggle` }, mcpToggle)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/mcp/remove` }, mcpRemove)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/mcp/check` }, mcpCheck)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/mcp/copy` }, mcpCopy)+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/mcp' }, mcp)+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/mcp' }, mcpSave)+ disposer.delete({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/mcp' }, mcpRemove)+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/mcp/toggle' }, mcpToggle)+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/mcp/check' }, mcpCheck)+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/mcp/copy' }, mcpCopy)- disposer.get({ kind: 'exact', path: `${API_PREFIX}/import/scan` }, importScan)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/import/apply` }, importApply)+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/import/scan' }, importScan)+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/import/apply' }, importApply)- disposer.get({ kind: 'exact', path: `${API_PREFIX}/roots` }, roots)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/roots/add` }, rootsAdd)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/roots/remove` }, rootsRemove)+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/roots' }, roots)+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/roots' }, rootsAdd)+ disposer.delete({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/roots' }, rootsRemove)- disposer.post({ kind: 'exact', path: `${API_PREFIX}/restart` }, restart)+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-panel-extension/host/restart' }, restart)})diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/index.types.ts b/packages/dsh-tauri-panel-extension/src/host/routes/index.types.tsindex a5090519..cb84230f 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/index.types.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/index.types.ts@@ -2,3 +2,184 @@ export interface ExtensionRouteDeps {profileDirPath: stringremountProvider: () => Promise<void>}++export interface ActionResult {+ ok: boolean+ error?: string+}++export interface SkillRepositoryView {+ id: string+ label: string+ kind: 'local' | 'git'+ githubUrl?: string+}++export interface SkillRowView {+ name: string+ description: string+ whenToUse?: string+ invocation: { modelInvocable: boolean, userInvocable: boolean }+ source: string+ provider: string+ editable: boolean+ removable: boolean+ dir?: string+ policyEditable: boolean+ repository?: SkillRepositoryView+}++export interface SkillsResponse {+ skills: SkillRowView[]+}++export interface SkillContentResponse {+ name: string+ content: string+}++export interface SkillSourceView {+ id: string+ kind: 'local' | 'git'+ label: string+ url?: string+ ref?: string+ path?: string+ roots: string[]+ materialDir?: string+ addedAt: number+ live: boolean+}++export interface RootAddResponse {+ ok: boolean+ root: SkillSourceView+}++export interface ImportedServerView {+ agent: 'claude-code' | 'codex' | 'cursor' | 'gemini'+ name: string+ transport: 'stdio' | 'streamable-http'+ command?: string+ args?: string[]+ env?: Record<string, string>+ url?: string+ headers?: Record<string, string>+}++export interface McpRowView {+ id: string+ layer?: 'global' | 'profile'+ shadowed?: boolean+ scope?: 'global' | 'profile'+ serverName: string+ transport: 'stdio' | 'streamable-http'+ disabled: boolean+ command?: string+ args?: string[]+ env?: Record<string, string>+ cwd?: string+ url?: string+ headers?: Record<string, string>+}++export interface McpListResponse {+ servers: McpRowView[]+ globalError?: string+ restartNeeded: boolean+}++export interface McpSaveResponse {+ ok: boolean+ id: string+ restartNeeded: boolean+}++export interface McpActionResult {+ ok: boolean+ restartNeeded: boolean+}++export interface McpCheckResponse {+ ok: boolean+ detail: string+}++export interface McpImportScanResponse {+ servers: ImportedServerView[]+ existing: string[]+}++export interface McpApplyImportResponse {+ ok: boolean+ results: Array<{ name: string, ok: boolean, error?: string }>+ restartNeeded: boolean+}++export interface SkillSaveBody {+ name: string+ description: string+ whenToUse?: string+ modelInvocable?: boolean+ userInvocable?: boolean+ content: string+}++export interface SkillDeleteBody {+ name: string+}++export interface SkillPolicyBody {+ name: string+ enabled: boolean+}++export interface SkillOpenBody {+ target: 'user-skills' | 'plugin-state' | 'skill' | 'root'+ name?: string+ id?: string+}++export interface RootAddBody {+ kind: 'local' | 'git'+ path?: string+ url?: string+}++export interface RootRemoveBody {+ id: string+}++export interface McpSaveBody {+ id: string+ serverName: string+ transport: 'stdio' | 'streamable-http'+ command?: string+ args?: string[]+ env?: Record<string, string>+ cwd?: string+ url?: string+ headers?: Record<string, string>+ scope?: 'global' | 'profile'+}++export interface McpRemoveBody {+ id: string+ scope?: 'global' | 'profile'+}++export interface McpToggleBody {+ id: string+ disabled: boolean+ scope?: 'global' | 'profile'+}++export interface McpCheckBody {+ id: string+ scope?: 'global' | 'profile'+}++export interface McpImportApplyBody {+ items: Array<{ agent: string, name: string }>+ scope?: 'global' | 'profile'+}diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/check/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/check/post.tsindex c0d7c90c..a730c5e0 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/check/post.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/check/post.ts@@ -1,11 +1,11 @@-import type { ExtensionRouteDeps } from '../../index.types'+import type { EventHandlerRequest } from 'dsh-tauri'+import type { McpCheckResult } from '../../../service/mcp.types'+import type { ExtensionRouteDeps, McpCheckBody } from '../../index.types'import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'import { mcp } from '../../../service/mcp'import { mcpScopeDir, normalizeMcpScope } from '../../../service/mcp.utils'-interface McpCheckBody { id?: unknown, scope?: unknown }--export default defineEventHandler(async (event) => {+export default defineEventHandler<EventHandlerRequest, Promise<McpCheckResult | { error: string }>>(async (event) => {const deps = dshRouteDepsOf<ExtensionRouteDeps>(event)!const body = await readBody<McpCheckBody>(event, { type: 'json' })if (typeof body?.id !== 'string') {diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/remove/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/delete.tssimilarity index 65%rename from packages/dsh-tauri-panel-extension/src/host/routes/mcp/remove/post.tsrename to packages/dsh-tauri-panel-extension/src/host/routes/mcp/delete.tsindex d09f2130..9e01d9b0 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/remove/post.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/delete.ts@@ -1,11 +1,10 @@-import type { ExtensionRouteDeps } from '../../index.types'+import type { EventHandlerRequest } from 'dsh-tauri'+import type { ExtensionRouteDeps, McpActionResult, McpRemoveBody } from '../index.types'import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'-import { mcp } from '../../../service/mcp'-import { mcpScopeDir, normalizeMcpScope } from '../../../service/mcp.utils'+import { mcp } from '../../service/mcp'+import { mcpScopeDir, normalizeMcpScope } from '../../service/mcp.utils'-interface McpRemoveBody { id?: unknown, scope?: unknown }--export default defineEventHandler(async (event) => {+export default defineEventHandler<EventHandlerRequest, Promise<McpActionResult | { error: string }>>(async (event) => {const deps = dshRouteDepsOf<ExtensionRouteDeps>(event)!const body = await readBody<McpRemoveBody>(event, { type: 'json' })if (typeof body?.id !== 'string') {diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/get.ts b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/get.tsindex 99812462..caa2674d 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/get.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/get.ts@@ -1,8 +1,8 @@-import type { ExtensionRouteDeps } from '../index.types'+import type { ExtensionRouteDeps, McpListResponse } from '../index.types'import { defineEventHandler, dshRouteDepsOf } from 'dsh-tauri'import { mcp } from '../../service/mcp'-export default defineEventHandler((event) => {+export default defineEventHandler((event): McpListResponse | { error: string } => {const deps = dshRouteDepsOf<ExtensionRouteDeps>(event)!return { ...mcp.list(deps.profileDirPath), restartNeeded: true }})diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/save/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/post.tssimilarity index 65%rename from packages/dsh-tauri-panel-extension/src/host/routes/mcp/save/post.tsrename to packages/dsh-tauri-panel-extension/src/host/routes/mcp/post.tsindex 56d64abd..c8837892 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/save/post.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/post.ts@@ -1,12 +1,12 @@-import type { McpInput } from '../../../service/mcp.types'-import type { ExtensionRouteDeps } from '../../index.types'+import type { EventHandlerRequest } from 'dsh-tauri'+import type { ExtensionRouteDeps, McpSaveBody, McpSaveResponse } from '../index.types'import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'-import { mcp } from '../../../service/mcp'-import { mcpScopeDir, normalizeMcpScope, validateMcpInput } from '../../../service/mcp.utils'+import { mcp } from '../../service/mcp'+import { mcpScopeDir, normalizeMcpScope, validateMcpInput } from '../../service/mcp.utils'-export default defineEventHandler(async (event) => {+export default defineEventHandler<EventHandlerRequest, Promise<McpSaveResponse | { error: string }>>(async (event) => {const deps = dshRouteDepsOf<ExtensionRouteDeps>(event)!- const body = await readBody<McpInput & { scope?: unknown }>(event, { type: 'json' })+ const body = await readBody<McpSaveBody>(event, { type: 'json' })if (body === undefined) {event.res.status = 400return { error: 'invalid-body' }diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/toggle/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/toggle/post.tsindex 80626500..1121882e 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/toggle/post.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/toggle/post.ts@@ -1,11 +1,10 @@-import type { ExtensionRouteDeps } from '../../index.types'+import type { EventHandlerRequest } from 'dsh-tauri'+import type { ExtensionRouteDeps, McpActionResult, McpToggleBody } from '../../index.types'import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'-import { mcpToggle } from '../../../service/mcp-toggle'+import { mcp } from '../../../service/mcp'import { mcpScopeDir, normalizeMcpScope } from '../../../service/mcp.utils'-interface McpToggleBody { id?: unknown, disabled?: unknown, scope?: unknown }--export default defineEventHandler(async (event) => {+export default defineEventHandler<EventHandlerRequest, Promise<McpActionResult | { error: string }>>(async (event) => {const deps = dshRouteDepsOf<ExtensionRouteDeps>(event)!const body = await readBody<McpToggleBody>(event, { type: 'json' })if (typeof body?.id !== 'string' || typeof body.disabled !== 'boolean') {@@ -15,7 +14,7 @@ export default defineEventHandler(async (event) => {const id = body.idconst disabled = body.disabledtry {- const ok = mcpToggle.save(mcpScopeDir(normalizeMcpScope(body.scope), deps.profileDirPath), id, disabled)+ const ok = mcp.toggle(mcpScopeDir(normalizeMcpScope(body.scope), deps.profileDirPath), id, disabled)if (!ok) {event.res.status = 404return { error: 'server row not found' }diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/open/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/open/dir/post.tssimilarity index 72%rename from packages/dsh-tauri-panel-extension/src/host/routes/open/post.tsrename to packages/dsh-tauri-panel-extension/src/host/routes/open/dir/post.tsindex 0d420fd1..21f752f7 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/open/post.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/open/dir/post.ts@@ -1,14 +1,16 @@+import type { EventHandlerRequest } from 'dsh-tauri'+import type { ActionResult, SkillOpenBody } from '../../index.types'import { mkdirSync } from 'node:fs'import { defineEventHandler, readBody } from 'dsh-tauri'-import { SKILL_DOCUMENT_PATTERN, SKILL_FILE_PATTERN } from '../../config/constants'-import { opener } from '../../service/opener'-import { skillCatalog } from '../../service/skill-catalog'-import { skillRoot } from '../../service/skill-root'-import { skillsDataDir } from '../../utils/paths.utils'+import { SKILLS_DATA_DIR } from '../../../config/constants'+import { opener } from '../../../service/opener'+import { skills } from '../../../service/skills'-interface SkillOpenBody { target?: unknown, name?: unknown, id?: unknown }+const SKILL_FILE_PATTERN = /[/\\]SKILL\.md$/-export default defineEventHandler(async (event) => {+const SKILL_DOCUMENT_PATTERN = /[/\\][^/\\]+\.md$/++export default defineEventHandler<EventHandlerRequest, Promise<ActionResult | { error: string }>>(async (event) => {const body = await readBody<SkillOpenBody>(event, { type: 'json' })if (typeof body?.target !== 'string') {event.res.status = 400@@ -17,7 +19,7 @@ export default defineEventHandler(async (event) => {try {let dir: string | undefinedif (body.target === 'user-skills' || body.target === 'plugin-state') {- dir = skillsDataDir()+ dir = SKILLS_DATA_DIRmkdirSync(dir, { recursive: true })}else if (body.target === 'skill') {@@ -25,7 +27,7 @@ export default defineEventHandler(async (event) => {event.res.status = 400return { error: 'name is required' }}- const definition = await skillCatalog.peek(body.name)+ const definition = await skills.get(body.name)if (definition === null) {event.res.status = 404return { error: 'skill not found' }@@ -39,7 +41,7 @@ export default defineEventHandler(async (event) => {event.res.status = 400return { error: 'id is required' }}- const entry = (await skillRoot.list()).find(row => row.id === body.id)+ const entry = (await skills.listSources()).find(row => row.id === body.id)if (entry === undefined) {event.res.status = 404return { error: 'repository not found' }diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/roots/remove/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/roots/delete.tssimilarity index 63%rename from packages/dsh-tauri-panel-extension/src/host/routes/roots/remove/post.tsrename to packages/dsh-tauri-panel-extension/src/host/routes/roots/delete.tsindex 5afb74eb..927b7d33 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/roots/remove/post.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/roots/delete.ts@@ -1,11 +1,10 @@-import type { ExtensionRouteDeps } from '../../index.types'+import type { EventHandlerRequest } from 'dsh-tauri'+import type { ActionResult, ExtensionRouteDeps, RootRemoveBody } from '../index.types'import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'-import { rmtree } from '../../../service/rmtree'-import { skillRoot } from '../../../service/skill-root'+import { rmtree } from '../../service/rmtree'+import { skills } from '../../service/skills'-interface RootRemoveBody { id?: unknown }--export default defineEventHandler(async (event) => {+export default defineEventHandler<EventHandlerRequest, Promise<ActionResult | { error: string }>>(async (event) => {const body = await readBody<RootRemoveBody>(event, { type: 'json' })if (typeof body?.id !== 'string') {event.res.status = 400@@ -13,7 +12,7 @@ export default defineEventHandler(async (event) => {}const id = body.idtry {- const removed = await skillRoot.remove(id)+ const removed = await skills.removeSource(id)if (removed === null) {event.res.status = 404return { error: 'repository not found' }diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/roots/get.ts b/packages/dsh-tauri-panel-extension/src/host/routes/roots/get.tsindex 946f643e..7ce4887e 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/roots/get.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/roots/get.ts@@ -1,7 +1,7 @@import { defineEventHandler } from 'dsh-tauri'-import { rootView } from '../../service/skill-catalog.utils'-import { skillRoot } from '../../service/skill-root'+import { skills } from '../../service/skills'+import { rootView } from '../../service/skills.utils'export default defineEventHandler(async () => {- return { roots: (await skillRoot.list()).map(rootView) }+ return { roots: (await skills.listSources()).map(rootView) }})diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/roots/add/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/roots/post.tssimilarity index 73%rename from packages/dsh-tauri-panel-extension/src/host/routes/roots/add/post.tsrename to packages/dsh-tauri-panel-extension/src/host/routes/roots/post.tsindex d3317151..866d4ba6 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/roots/add/post.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/roots/post.ts@@ -1,11 +1,10 @@-import type { ExtensionRouteDeps } from '../../index.types'+import type { EventHandlerRequest } from 'dsh-tauri'+import type { ExtensionRouteDeps, RootAddBody, RootAddResponse } from '../index.types'import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'-import { repos } from '../../../service/repos'-import { rootView } from '../../../service/skill-catalog.utils'+import { repos } from '../../service/repos'+import { rootView } from '../../service/skills.utils'-interface RootAddBody { kind?: unknown, path?: unknown, url?: unknown }--export default defineEventHandler(async (event) => {+export default defineEventHandler<EventHandlerRequest, Promise<RootAddResponse | { error: string }>>(async (event) => {const body = await readBody<RootAddBody>(event, { type: 'json' })if (body?.kind !== 'local' && body?.kind !== 'git') {event.res.status = 400diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/skill/delete/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/skill/delete.tssimilarity index 62%rename from packages/dsh-tauri-panel-extension/src/host/routes/skill/delete/post.tsrename to packages/dsh-tauri-panel-extension/src/host/routes/skill/delete.tsindex ee914596..4e27ea86 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/skill/delete/post.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/skill/delete.ts@@ -1,9 +1,9 @@+import type { EventHandlerRequest } from 'dsh-tauri'+import type { ActionResult, SkillDeleteBody } from '../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'-import { skills } from '../../../service/skills'+import { skills } from '../../service/skills'-interface SkillDeleteBody { name?: unknown }--export default defineEventHandler(async (event) => {+export default defineEventHandler<EventHandlerRequest, Promise<ActionResult | { error: string }>>(async (event) => {const body = await readBody<SkillDeleteBody>(event, { type: 'json' })const name = typeof body?.name === 'string' ? body.name : ''try {diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/skill/get.ts b/packages/dsh-tauri-panel-extension/src/host/routes/skill/get.tsindex 2917bf29..e3d3d563 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/skill/get.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/skill/get.ts@@ -1,11 +1,13 @@+import type { EventHandlerRequest } from 'dsh-tauri'+import type { SkillContentResponse } from '../index.types'import { defineEventHandler, getQuery } from 'dsh-tauri'-import { skillCatalog } from '../../service/skill-catalog'+import { skills } from '../../service/skills'-export default defineEventHandler(async (event) => {+export default defineEventHandler<EventHandlerRequest, Promise<SkillContentResponse | { error: string }>>(async (event) => {const query = getQuery(event) as { name?: unknown }const name = typeof query.name === 'string' ? query.name : ''try {- const definition = await skillCatalog.peek(name)+ const definition = await skills.get(name)if (definition === null) {event.res.status = 404return { error: 'skill not found' }diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/skill/policy/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/skill/policy/post.tsindex 0bce7c21..0b48412d 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/skill/policy/post.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/skill/policy/post.ts@@ -1,10 +1,9 @@+import type { EventHandlerRequest } from 'dsh-tauri'+import type { ActionResult, SkillPolicyBody } from '../../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'-import { skillCatalog } from '../../../service/skill-catalog'-import { skillPolicy } from '../../../service/skill-policy'+import { skills } from '../../../service/skills'-interface SkillPolicyBody { name?: unknown, enabled?: unknown }--export default defineEventHandler(async (event) => {+export default defineEventHandler<EventHandlerRequest, Promise<ActionResult | { error: string }>>(async (event) => {const body = await readBody<SkillPolicyBody>(event, { type: 'json' })if (typeof body?.name !== 'string' || typeof body?.enabled !== 'boolean') {event.res.status = 400@@ -13,7 +12,7 @@ export default defineEventHandler(async (event) => {const name = body.nameconst enabled = body.enabledtry {- const definition = await skillCatalog.peek(name)+ const definition = await skills.get(name)if (definition === null) {event.res.status = 404return { error: 'skill not found' }@@ -22,7 +21,7 @@ export default defineEventHandler(async (event) => {event.res.status = 422return { error: 'skill has no file on disk (runtime-registered)' }}- skillPolicy.save(definition.path, enabled)+ skills.setPolicy(definition.path, enabled)return { ok: true }}catch (error) {diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/skill/save/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/skill/post.tssimilarity index 65%rename from packages/dsh-tauri-panel-extension/src/host/routes/skill/save/post.tsrename to packages/dsh-tauri-panel-extension/src/host/routes/skill/post.tsindex bef8479b..715244fd 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/skill/save/post.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/skill/post.ts@@ -1,13 +1,14 @@-import type { SkillInput } from '../../../service/skills.types'+import type { EventHandlerRequest } from 'dsh-tauri'+import type { SkillInput } from '../../service/skills.types'+import type { ActionResult, SkillSaveBody } from '../index.types'import { defineEventHandler, readBody } from 'dsh-tauri'import { join } from 'pathe'-import { SKILL_FILE_NAME } from '../../../config/constants'-import { skillCatalog } from '../../../service/skill-catalog'-import { skills } from '../../../service/skills'-import { validateSkillInput } from '../../../service/skills.utils'+import { SKILL_FILE_NAME } from '../../config/constants'+import { skills } from '../../service/skills'+import { validateSkillInput } from '../../service/skills.utils'-export default defineEventHandler(async (event) => {- const body = await readBody<Partial<SkillInput>>(event, { type: 'json' })+export default defineEventHandler<EventHandlerRequest, Promise<ActionResult | { error: string }>>(async (event) => {+ const body = await readBody<SkillSaveBody>(event, { type: 'json' })const input: SkillInput = {name: typeof body?.name === 'string' ? body.name : '',description: typeof body?.description === 'string' ? body.description : '',@@ -22,7 +23,7 @@ export default defineEventHandler(async (event) => {event.res.status = 400return { error: invalid }}- const existing = (await skillCatalog.resolve()).find(skill => skill.name === input.name)+ const existing = (await skills.getCatalog()).find(skill => skill.name === input.name)if (existing !== undefined) {if (existing.dir === undefined || !existing.editable) {event.res.status = 403diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/skills/get.ts b/packages/dsh-tauri-panel-extension/src/host/routes/skills/get.tsindex eb76b9b5..a5a292f7 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/skills/get.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/skills/get.ts@@ -1,9 +1,11 @@+import type { EventHandlerRequest } from 'dsh-tauri'+import type { SkillsResponse } from '../index.types'import { defineEventHandler } from 'dsh-tauri'-import { skillCatalog } from '../../service/skill-catalog'+import { skills } from '../../service/skills'-export default defineEventHandler(async (event) => {+export default defineEventHandler<EventHandlerRequest, Promise<SkillsResponse | { error: string }>>(async (event) => {try {- return { skills: await skillCatalog.resolve() }+ return { skills: await skills.getCatalog() }}catch (error) {event.res.status = 500diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/skills/refresh/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/skills/refresh/post.tsindex d3c8f151..4613d15c 100644--- a/packages/dsh-tauri-panel-extension/src/host/routes/skills/refresh/post.ts+++ b/packages/dsh-tauri-panel-extension/src/host/routes/skills/refresh/post.ts@@ -1,11 +1,12 @@-import type { ExtensionRouteDeps } from '../../index.types'+import type { EventHandlerRequest } from 'dsh-tauri'+import type { ExtensionRouteDeps, SkillsResponse } from '../../index.types'import { defineEventHandler, dshRouteDepsOf } from 'dsh-tauri'-import { skillCatalog } from '../../../service/skill-catalog'+import { skills } from '../../../service/skills'-export default defineEventHandler(async (event) => {+export default defineEventHandler<EventHandlerRequest, Promise<SkillsResponse | { error: string }>>(async (event) => {try {await dshRouteDepsOf<ExtensionRouteDeps>(event)!.remountProvider()- return { skills: await skillCatalog.resolve() }+ return { skills: await skills.getCatalog() }}catch (error) {event.res.status = 500diff --git a/packages/dsh-tauri-panel-extension/src/host/service/agents.ts b/packages/dsh-tauri-panel-extension/src/host/service/agents.tsindex 04a7f2cb..c48933e9 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/agents.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/agents.ts@@ -5,13 +5,16 @@ import { defineService } from 'dsh-tauri'import { compact, filter, isEmpty, isObject, isString, pickBy, uniqBy } from 'lodash-es'import { join } from 'pathe'import { parse as parseToml } from 'smol-toml'-import {- AGENT_SKILL_DIRECTORIES,- CLAUDE_MCP_FILES,- CODEX_MCP_FILE,- CURSOR_MCP_FILE,- GEMINI_MCP_FILE,-} from '../config/constants'++const CLAUDE_MCP_FILES = ['.claude/settings.json', '.claude.json'] as const++const CURSOR_MCP_FILE = '.cursor/mcp.json'++const GEMINI_MCP_FILE = '.gemini/settings.json'++const CODEX_MCP_FILE = '.codex/config.toml'++const AGENT_SKILL_DIRECTORIES = ['.claude/skills', '.codex/skills'] as constexport const agents = defineService({resolve(home: string = homedir()): ImportedServer[] {diff --git a/packages/dsh-tauri-panel-extension/src/host/service/mcp-toggle.ts b/packages/dsh-tauri-panel-extension/src/host/service/mcp-toggle.tsdeleted file mode 100644index f7ae687a..00000000--- a/packages/dsh-tauri-panel-extension/src/host/service/mcp-toggle.ts+++ /dev/null@@ -1,18 +0,0 @@-import { defineService } from 'dsh-tauri'-import { loadPatch, managedInsert, mcpRowItems, savePatch } from './mcp.utils'--export const mcpToggle = defineService({- save(dirPath: string, id: string, disabled: boolean): boolean {- const doc = loadPatch(dirPath)- managedInsert(doc)- const hit = mcpRowItems(doc).find(({ node }) => String(node.get('id') ?? '') === id)- if (hit === undefined)- return false- if (disabled)- hit.node.set('disabled', true)- else- hit.node.delete('disabled')- savePatch(dirPath, doc)- return true- },-})diff --git a/packages/dsh-tauri-panel-extension/src/host/service/mcp.ts b/packages/dsh-tauri-panel-extension/src/host/service/mcp.tsindex eb40353b..bcbc02a6 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/mcp.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/mcp.ts@@ -5,7 +5,7 @@ import process from 'node:process'import { defineService, DSH_HOME } from 'dsh-tauri'import { compact, isEmpty } from 'lodash-es'import { join } from 'pathe'-import { MCP_CHECK_TIMEOUT_MS, MCP_PLUGIN, PATCH_FILE_NAME } from '../config/constants'+import { MCP_PLUGIN, PATCH_FILE_NAME } from '../config/constants'import {insertListOf,loadPatch,@@ -18,6 +18,8 @@ import {toNode,} from './mcp.utils'+const MCP_CHECK_TIMEOUT_MS = 5_000+export const mcp = defineService({list(profileDirPath: string): McpListResult {let globalRows: McpRow[] = []@@ -115,6 +117,20 @@ export const mcp = defineService({return true},+ toggle(dirPath: string, id: string, disabled: boolean): boolean {+ const doc = loadPatch(dirPath)+ managedInsert(doc)+ const hit = mcpRowItems(doc).find(({ node }) => String(node.get('id') ?? '') === id)+ if (hit === undefined)+ return false+ if (disabled)+ hit.node.set('disabled', true)+ else+ hit.node.delete('disabled')+ savePatch(dirPath, doc)+ return true+ },+async check(row: McpRow, options: McpCheckOptions = {}): Promise<McpCheckResult> {const pathEnv = options.pathEnv ?? process.env.PATH ?? ''if (row.transport === 'stdio') {diff --git a/packages/dsh-tauri-panel-extension/src/host/service/mcp.utils.ts b/packages/dsh-tauri-panel-extension/src/host/service/mcp.utils.tsindex 3761331d..7cdb2548 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/mcp.utils.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/mcp.utils.ts@@ -5,7 +5,11 @@ import { DSH_HOME } from 'dsh-tauri'import { compact, every, isObject, isString, isUndefined, omitBy } from 'lodash-es'import { join } from 'pathe'import { Document, parseDocument } from 'yaml'-import { EMPTY_PATCH, MCP_PLUGIN, PATCH_FILE_NAME, SERVER_NAME_RE } from '../config/constants'+import { MCP_PLUGIN, PATCH_FILE_NAME } from '../config/constants'++const SERVER_NAME_RE = /^[\w-]{1,32}$/++const EMPTY_PATCH = '[]'export function normalizeMcpScope(value: unknown): McpScope {return value === 'global' ? 'global' : 'profile'diff --git a/packages/dsh-tauri-panel-extension/src/host/service/provider.ts b/packages/dsh-tauri-panel-extension/src/host/service/provider.tsindex d870495b..fe52e541 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/provider.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/provider.ts@@ -4,7 +4,7 @@ import { getCurrentHostInstance, providerRuntime } from '../config/runtime'import { providerHooks } from '../events'import { agents } from './agents'import { loadFilesystemSkillPlugin } from './provider.utils'-import { skillRoot } from './skill-root'+import { skills } from './skills'export const provider = defineService({start(packagedDir: string): Promise<void> {@@ -39,7 +39,7 @@ async function remount(packagedDir: string): Promise<void> {returnconst roots = [packagedDir,- ...(await skillRoot.list()).flatMap(entry => entry.roots),+ ...(await skills.listSources()).flatMap(entry => entry.roots),...agents.peek(),].filter(dir => existsSync(dir))try {diff --git a/packages/dsh-tauri-panel-extension/src/host/service/repos.ts b/packages/dsh-tauri-panel-extension/src/host/service/repos.tsindex 68c2e026..dd92800d 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/repos.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/repos.ts@@ -1,19 +1,22 @@-import type { SkillRootEntry } from './skill-root.types'+import type { SkillSourceEntry } from './skills.types'import { Buffer } from 'node:buffer'import { existsSync, mkdirSync, statSync, symlinkSync } from 'node:fs'import process from 'node:process'import { defineService } from 'dsh-tauri'import { $fetch } from 'ofetch'import { basename, join, resolve } from 'pathe'-import { GITHUB_FETCH_TIMEOUT_MS, TARBALL_MAX_BYTES } from '../config/constants'import { materialDirFor } from '../utils/paths.utils'import { detectSkillRoots, newEntryId, parseGitHubSource } from './repos.utils'import { rmtree } from './rmtree'-import { skillRoot } from './skill-root'+import { skills } from './skills'import { tar } from './tar'+const GITHUB_FETCH_TIMEOUT_MS = 60_000++const TARBALL_MAX_BYTES = 256 * 1024 * 1024+export const repos = defineService({- async create(path: string): Promise<SkillRootEntry> {+ async create(path: string): Promise<SkillSourceEntry> {const resolved = resolve(path.trim().replace(/^"|"$/g, ''))if (!existsSync(resolved) || !statSync(resolved).isDirectory())throw new Error(`not a directory: ${resolved}`)@@ -32,16 +35,16 @@ export const repos = defineService({rmtree.remove(material)throw new Error('single-skill local folders need a directory link; try adding their parent folder instead')}- return skillRoot.save({ id, kind: 'local', label: basename(resolved), path: resolved, roots: [material], materialDir: material })+ return skills.saveSource({ id, kind: 'local', label: basename(resolved), path: resolved, roots: [material], materialDir: material })}- return skillRoot.save({ id: newEntryId('local'), kind: 'local', label: basename(resolved), path: resolved, roots: detected.roots })+ return skills.saveSource({ id: newEntryId('local'), kind: 'local', label: basename(resolved), path: resolved, roots: detected.roots })},- async import(url: string): Promise<SkillRootEntry> {+ async import(url: string): Promise<SkillSourceEntry> {const source = parseGitHubSource(url)if (source === null)throw new Error('expected a GitHub repository URL or owner/repo')- const existing = await skillRoot.load(source.githubUrl) ?? await skillRoot.load(source.label)+ const existing = await skills.getSource(source.githubUrl) ?? await skills.getSource(source.label)if (existing !== null)throw new Error(`${source.label} is already registered`)@@ -60,7 +63,7 @@ export const repos = defineService({if (!detected.single && detected.roots.length === 0)throw new Error('no SKILL.md found in that repository')const roots = detected.single ? [material] : detected.roots- return await skillRoot.save(+ return await skills.saveSource({ id, kind: 'git', label: source.label, url: source.githubUrl, ref: source.ref, roots, materialDir: material },)}diff --git a/packages/dsh-tauri-panel-extension/src/host/service/repos.utils.ts b/packages/dsh-tauri-panel-extension/src/host/service/repos.utils.tsindex da1f06c5..72dd6ee1 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/repos.utils.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/repos.utils.ts@@ -1,9 +1,13 @@import type { DetectedRoots, GitHubSource } from './repos.types'-import type { SkillRootEntry } from './skill-root.types'+import type { SkillSourceEntry } from './skills.types'import { randomBytes } from 'node:crypto'import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'import { join } from 'pathe'-import { GITHUB_SHORT_RE, GITHUB_URL_RE, SKILL_FILE_NAME } from '../config/constants'+import { SKILL_FILE_NAME } from '../config/constants'++const GITHUB_URL_RE = /^(?:https?:\/\/)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(?:tree|archive)\/([^/#?]+?)(?:\.tar\.gz)?)?(?:#([^/?#]+))?(?:[/?#].*)?$/++const GITHUB_SHORT_RE = /^([\w.-]+)\/([\w.-]+)$/export function parseGitHubSource(input: string): GitHubSource | null {const trimmed = input.trim()@@ -66,7 +70,7 @@ export function detectSkillRoots(checkout: string): DetectedRoots {return { roots, single: false }}-export function newEntryId(kind: SkillRootEntry['kind']): string {+export function newEntryId(kind: SkillSourceEntry['kind']): string {return `${kind}-${randomBytes(4).toString('hex')}`}diff --git a/packages/dsh-tauri-panel-extension/src/host/service/restart.ts b/packages/dsh-tauri-panel-extension/src/host/service/restart.tsindex 6e644747..747e3458 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/restart.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/restart.ts@@ -6,7 +6,8 @@ import process from 'node:process'import { defineService } from 'dsh-tauri'import { dirname, resolve } from 'pathe'import { PLUGIN_ID } from '../../shared/constants'-import { RESTART_KILL_DELAY_MS } from '../config/constants'++const RESTART_KILL_DELAY_MS = 500export const restart = defineService({start(): RestartOutcome {diff --git a/packages/dsh-tauri-panel-extension/src/host/service/rmtree.ts b/packages/dsh-tauri-panel-extension/src/host/service/rmtree.tsindex fc33ffa3..1db3b8bd 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/rmtree.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/rmtree.ts@@ -2,7 +2,8 @@ import type { Dirent } from 'node:fs'import { chmodSync, readdirSync, rmSync } from 'node:fs'import { defineService } from 'dsh-tauri'import { join } from 'pathe'-import { RMTREE_RETRIES } from '../config/constants'++const RMTREE_RETRIES = { maxRetries: 10, retryDelay: 200 } as constexport const rmtree = defineService({remove(path: string): void {diff --git a/packages/dsh-tauri-panel-extension/src/host/service/skill-catalog.ts b/packages/dsh-tauri-panel-extension/src/host/service/skill-catalog.tsdeleted file mode 100644index bc00797a..00000000--- a/packages/dsh-tauri-panel-extension/src/host/service/skill-catalog.ts+++ /dev/null@@ -1,78 +0,0 @@-import type { SkillRepositoryMetadata, SkillRow } from './skill-catalog.types'-import type { SkillRootEntry } from './skill-root.types'-import type { HostSkill, HostSkillDefinition } from './skills.types'-import { defineService } from 'dsh-tauri'-import { orderBy } from 'lodash-es'-import { isAbsolute, relative, resolve, sep } from 'pathe'-import { getCurrentHostInstance } from '../config/runtime'-import { skillsDataDir } from '../utils/paths.utils'-import { skillRoot } from './skill-root'--export const skillCatalog = defineService({- async resolve(): Promise<SkillRow[]> {- const skills = await getCurrentHostInstance().skills.list()- const entries = await skillRoot.list()- const rows = await Promise.all(skills.map(skill => toSkillRow(skill, entries)))- return orderBy(rows, [row => row.repository === undefined], ['asc'])- },-- async peek(name: string): Promise<HostSkillDefinition | null> {- return (await getCurrentHostInstance().skills.get(name)) ?? null- },-})--// --- internal -----async function customSkillWritable(dir: string): Promise<boolean> {- const state = skillsDataDir()- if (dir === state || dir.startsWith(state + sep))- return true- return (await skillRoot.list()).some(entry =>- entry.roots.some(root => dir === root || dir.startsWith(root + sep)))-}--async function skillWritable(skill: HostSkill, dir: string | undefined): Promise<boolean> {- if (dir === undefined)- return false- if (skill.source === 'user-dsh')- return true- return skill.source === 'custom' && await customSkillWritable(dir)-}--function pathWithin(path: string, parent: string): boolean {- const child = resolve(path)- const root = resolve(parent)- const nested = relative(root, child)- return nested === '' || (!nested.startsWith(`..${sep}`) && nested !== '..' && !isAbsolute(nested))-}--function repositoryForSkill(- skill: HostSkill,- entries: SkillRootEntry[],-): SkillRepositoryMetadata | undefined {- const dir = skill.resourceBase?.kind === 'directory' ? skill.resourceBase.path : undefined- if (dir === undefined)- return undefined- const entry = entries.find(candidate => candidate.roots.some(root => pathWithin(dir, root)))- if (entry === undefined)- return undefined- return {- id: entry.id,- label: entry.label,- kind: entry.kind,- ...(entry.kind === 'git' && entry.url !== undefined ? { githubUrl: entry.url } : {}),- }-}--async function toSkillRow(skill: HostSkill, entries: SkillRootEntry[]): Promise<SkillRow> {- const dir = skill.resourceBase?.kind === 'directory' ? skill.resourceBase.path : undefined- const repository = repositoryForSkill(skill, entries)- return {- ...skill,- editable: await skillWritable(skill, dir),- removable: skill.source === 'user-dsh',- ...(dir !== undefined ? { dir } : {}),- policyEditable: dir !== undefined,- ...(repository !== undefined ? { repository } : {}),- }-}diff --git a/packages/dsh-tauri-panel-extension/src/host/service/skill-catalog.types.ts b/packages/dsh-tauri-panel-extension/src/host/service/skill-catalog.types.tsdeleted file mode 100644index 7e81ee37..00000000--- a/packages/dsh-tauri-panel-extension/src/host/service/skill-catalog.types.ts+++ /dev/null@@ -1,16 +0,0 @@-import type { HostSkill } from './skills.types'--export interface SkillRepositoryMetadata {- id: string- label: string- kind: 'local' | 'git'- githubUrl?: string-}--export type SkillRow = HostSkill & {- editable: boolean- removable: boolean- dir?: string- policyEditable: boolean- repository?: SkillRepositoryMetadata-}diff --git a/packages/dsh-tauri-panel-extension/src/host/service/skill-catalog.utils.ts b/packages/dsh-tauri-panel-extension/src/host/service/skill-catalog.utils.tsdeleted file mode 100644index 44fc2fca..00000000--- a/packages/dsh-tauri-panel-extension/src/host/service/skill-catalog.utils.ts+++ /dev/null@@ -1,6 +0,0 @@-import type { SkillRootEntry, SkillRootView } from './skill-root.types'-import { directoryExists } from '../utils/filesystem.utils'--export function rootView(entry: SkillRootEntry): SkillRootView {- return { ...entry, live: entry.roots.every(root => directoryExists(root)) }-}diff --git a/packages/dsh-tauri-panel-extension/src/host/service/skill-policy.ts b/packages/dsh-tauri-panel-extension/src/host/service/skill-policy.tsdeleted file mode 100644index 73ebf339..00000000--- a/packages/dsh-tauri-panel-extension/src/host/service/skill-policy.ts+++ /dev/null@@ -1,9 +0,0 @@-import { readFileSync, writeFileSync } from 'node:fs'-import { defineService } from 'dsh-tauri'-import { rewriteSkillPolicy } from './skills.utils'--export const skillPolicy = defineService({- save(file: string, enabled: boolean): void {- writeFileSync(file, rewriteSkillPolicy(readFileSync(file, 'utf8'), enabled), 'utf8')- },-})diff --git a/packages/dsh-tauri-panel-extension/src/host/service/skill-root.ts b/packages/dsh-tauri-panel-extension/src/host/service/skill-root.tsdeleted file mode 100644index f4226c44..00000000--- a/packages/dsh-tauri-panel-extension/src/host/service/skill-root.ts+++ /dev/null@@ -1,52 +0,0 @@-import type { PluginState, SkillRootEntry } from './skill-root.types'-import { defineService } from 'dsh-tauri'-import { STATE_FILE_NAME } from '../config/constants'-import { storage } from '../storage'--export const skillRoot = defineService({- async load(url: string): Promise<SkillRootEntry | null> {- return (await readAll()).find(entry => entry.url === url) ?? null- },-- async list(): Promise<SkillRootEntry[]> {- return readAll()- },-- async save(entry: Omit<SkillRootEntry, 'addedAt'>): Promise<SkillRootEntry> {- const skillRoots = await readAll()- const stored: SkillRootEntry = { ...entry, addedAt: Date.now() }- skillRoots.push(stored)- await writeAll(skillRoots)- return stored- },-- async remove(id: string): Promise<SkillRootEntry | null> {- const skillRoots = await readAll()- const at = skillRoots.findIndex(entry => entry.id === id)- if (at === -1)- return null- const [removed] = skillRoots.splice(at, 1)- await writeAll(skillRoots)- return removed- },-})--// --- internal -----async function readAll(): Promise<SkillRootEntry[]> {- const parsed = await storage.getItem<Partial<PluginState>>(STATE_FILE_NAME)- if (!Array.isArray(parsed?.skillRoots))- return []- return parsed.skillRoots.filter(isSkillRootEntry)-}--async function writeAll(skillRoots: SkillRootEntry[]): Promise<void> {- await storage.setItem(STATE_FILE_NAME, `${JSON.stringify({ skillRoots }, null, 2)}\n`)-}--function isSkillRootEntry(entry: unknown): entry is SkillRootEntry {- if (typeof entry !== 'object' || entry === null)- return false- const candidate = entry as Record<string, unknown>- return typeof candidate.id === 'string' && Array.isArray(candidate.roots)-}diff --git a/packages/dsh-tauri-panel-extension/src/host/service/skill-root.types.ts b/packages/dsh-tauri-panel-extension/src/host/service/skill-root.types.tsdeleted file mode 100644index ca70bf8f..00000000--- a/packages/dsh-tauri-panel-extension/src/host/service/skill-root.types.ts+++ /dev/null@@ -1,17 +0,0 @@-export interface SkillRootEntry {- id: string- kind: 'local' | 'git'- label: string- url?: string- ref?: string- path?: string- roots: string[]- materialDir?: string- addedAt: number-}--export interface PluginState {- skillRoots: SkillRootEntry[]-}--export type SkillRootView = SkillRootEntry & { live: boolean }diff --git a/packages/dsh-tauri-panel-extension/src/host/service/skills.ts b/packages/dsh-tauri-panel-extension/src/host/service/skills.tsindex f098ed61..6b412ef0 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/skills.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/skills.ts@@ -1,11 +1,30 @@-import type { SkillInput } from './skills.types'+import type {+ HostSkill,+ HostSkillDefinition,+ PluginState,+ SkillInput,+ SkillRepositoryMetadata,+ SkillRow,+ SkillSourceEntry,+} from './skills.types'import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'import { defineService } from 'dsh-tauri'-import { SKILL_NAME_RE } from '../config/constants'+import { orderBy } from 'lodash-es'+import { isAbsolute, relative, resolve, sep } from 'pathe'+import { SKILL_NAME_RE, SKILLS_DATA_DIR } from '../config/constants'+import { getCurrentHostInstance } from '../config/runtime'+import { storage } from '../storage'import { skillDir, skillFilePath } from '../utils/paths.utils'-import { rewriteSkillContent, serializeSkill } from './skills.utils'+import { isSkillSourceEntry, rewriteSkillContent, rewriteSkillPolicy, serializeSkill } from './skills.utils'++const STATE_FILE_NAME = 'state.json'export const skills = defineService({+ // --- Skill 基础操作 ---+ async get(name: string): Promise<HostSkillDefinition | null> {+ return (await getCurrentHostInstance().skills.get(name)) ?? null+ },+save(input: SkillInput, file?: string): string {if (file !== undefined) {writeFileSync(file, rewriteSkillContent(readFileSync(file, 'utf8'), input), 'utf8')@@ -26,4 +45,110 @@ export const skills = defineService({rmSync(dir, { recursive: true, force: true })return true},++ // --- Skill 视图/展示目录 ---+ async getCatalog(): Promise<SkillRow[]> {+ const hostSkills = await getCurrentHostInstance().skills.list()+ const sources = await readSources()+ const rows = await Promise.all(hostSkills.map(skill => toSkillRow(skill, sources)))+ return orderBy(rows, [row => row.repository === undefined], ['asc'])+ },++ // --- Skill 来源/仓库 ---+ async listSources(): Promise<SkillSourceEntry[]> {+ return readSources()+ },++ async getSource(url: string): Promise<SkillSourceEntry | null> {+ return (await readSources()).find(entry => entry.url === url) ?? null+ },++ async saveSource(entry: Omit<SkillSourceEntry, 'addedAt'>): Promise<SkillSourceEntry> {+ const sources = await readSources()+ const stored: SkillSourceEntry = { ...entry, addedAt: Date.now() }+ sources.push(stored)+ await writeSources(sources)+ return stored+ },++ async removeSource(id: string): Promise<SkillSourceEntry | null> {+ const sources = await readSources()+ const at = sources.findIndex(entry => entry.id === id)+ if (at === -1)+ return null+ const [removed] = sources.splice(at, 1)+ await writeSources(sources)+ return removed+ },++ // --- Skill 策略配置 ---+ setPolicy(file: string, enabled: boolean): void {+ writeFileSync(file, rewriteSkillPolicy(readFileSync(file, 'utf8'), enabled), 'utf8')+ },})++// --- internal ---++async function readSources(): Promise<SkillSourceEntry[]> {+ const parsed = await storage.getItem<Partial<PluginState>>(STATE_FILE_NAME)+ if (!Array.isArray(parsed?.skillRoots))+ return []+ return parsed.skillRoots.filter(isSkillSourceEntry)+}++async function writeSources(sources: SkillSourceEntry[]): Promise<void> {+ await storage.setItem(STATE_FILE_NAME, `${JSON.stringify({ skillRoots: sources }, null, 2)}\n`)+}++async function customSkillWritable(dir: string): Promise<boolean> {+ if (dir === SKILLS_DATA_DIR || dir.startsWith(SKILLS_DATA_DIR + sep))+ return true+ return (await readSources()).some(entry =>+ entry.roots.some(root => dir === root || dir.startsWith(root + sep)))+}++async function skillWritable(skill: HostSkill, dir: string | undefined): Promise<boolean> {+ if (dir === undefined)+ return false+ if (skill.source === 'user-dsh')+ return true+ return skill.source === 'custom' && await customSkillWritable(dir)+}++function pathWithin(path: string, parent: string): boolean {+ const child = resolve(path)+ const root = resolve(parent)+ const nested = relative(root, child)+ return nested === '' || (!nested.startsWith(`..${sep}`) && nested !== '..' && !isAbsolute(nested))+}++function repositoryForSkill(+ skill: HostSkill,+ entries: SkillSourceEntry[],+): SkillRepositoryMetadata | undefined {+ const dir = skill.resourceBase?.kind === 'directory' ? skill.resourceBase.path : undefined+ if (dir === undefined)+ return undefined+ const entry = entries.find(candidate => candidate.roots.some(root => pathWithin(dir, root)))+ if (entry === undefined)+ return undefined+ return {+ id: entry.id,+ label: entry.label,+ kind: entry.kind,+ ...(entry.kind === 'git' && entry.url !== undefined ? { githubUrl: entry.url } : {}),+ }+}++async function toSkillRow(skill: HostSkill, entries: SkillSourceEntry[]): Promise<SkillRow> {+ const dir = skill.resourceBase?.kind === 'directory' ? skill.resourceBase.path : undefined+ const repository = repositoryForSkill(skill, entries)+ return {+ ...skill,+ editable: await skillWritable(skill, dir),+ removable: skill.source === 'user-dsh',+ ...(dir !== undefined ? { dir } : {}),+ policyEditable: dir !== undefined,+ ...(repository !== undefined ? { repository } : {}),+ }+}diff --git a/packages/dsh-tauri-panel-extension/src/host/service/skills.types.ts b/packages/dsh-tauri-panel-extension/src/host/service/skills.types.tsindex b8cb687d..d19b6ebc 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/skills.types.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/skills.types.ts@@ -28,3 +28,36 @@ export interface SkillInput {userInvocable: booleancontent: string}++export interface SkillRepositoryMetadata {+ id: string+ label: string+ kind: 'local' | 'git'+ githubUrl?: string+}++export type SkillRow = HostSkill & {+ editable: boolean+ removable: boolean+ dir?: string+ policyEditable: boolean+ repository?: SkillRepositoryMetadata+}++export interface SkillSourceEntry {+ id: string+ kind: 'local' | 'git'+ label: string+ url?: string+ ref?: string+ path?: string+ roots: string[]+ materialDir?: string+ addedAt: number+}++export interface PluginState {+ skillRoots: SkillSourceEntry[]+}++export type SkillSourceView = SkillSourceEntry & { live: boolean }diff --git a/packages/dsh-tauri-panel-extension/src/host/service/skills.utils.ts b/packages/dsh-tauri-panel-extension/src/host/service/skills.utils.tsindex d8330479..575101a4 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/skills.utils.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/skills.utils.ts@@ -1,11 +1,24 @@-import type { SkillInput } from './skills.types'+import type { SkillInput, SkillSourceEntry, SkillSourceView } from './skills.types'import { isEmpty } from 'lodash-es'-import {- SKILL_CONTENT_MAX_BYTES,- SKILL_DESCRIPTION_MAX_LENGTH,- SKILL_NAME_RE,- SKILL_WHEN_TO_USE_MAX_LENGTH,-} from '../config/constants'+import { SKILL_NAME_RE } from '../config/constants'+import { directoryExists } from '../utils/filesystem.utils'++const SKILL_DESCRIPTION_MAX_LENGTH = 1024++const SKILL_WHEN_TO_USE_MAX_LENGTH = 2048++const SKILL_CONTENT_MAX_BYTES = 256 * 1024++export function rootView(entry: SkillSourceEntry): SkillSourceView {+ return { ...entry, live: entry.roots.every(root => directoryExists(root)) }+}++export function isSkillSourceEntry(entry: unknown): entry is SkillSourceEntry {+ if (typeof entry !== 'object' || entry === null)+ return false+ const candidate = entry as Record<string, unknown>+ return typeof candidate.id === 'string' && Array.isArray(candidate.roots)+}export function serializeSkill(input: SkillInput): string {const lines = [diff --git a/packages/dsh-tauri-panel-extension/src/host/service/tar.ts b/packages/dsh-tauri-panel-extension/src/host/service/tar.tsindex 63af40b3..814e0c56 100644--- a/packages/dsh-tauri-panel-extension/src/host/service/tar.ts+++ b/packages/dsh-tauri-panel-extension/src/host/service/tar.ts@@ -4,7 +4,12 @@ import { mkdirSync, writeFileSync } from 'node:fs'import { gunzipSync } from 'node:zlib'import { defineService } from 'dsh-tauri'import { dirname, join } from 'pathe'-import { TAR_LIMITS } from '../config/constants'++const TAR_LIMITS = {+ entryBytes: 64 * 1024 * 1024,+ totalBytes: 256 * 1024 * 1024,+ entries: 20_000,+} as constexport const tar = defineService({save(archive: Buffer, target: string, options: ExtractOptions = {}): number {diff --git a/packages/dsh-tauri-panel-extension/src/host/storage/index.ts b/packages/dsh-tauri-panel-extension/src/host/storage/index.tsindex 60b07210..ec6001a9 100644--- a/packages/dsh-tauri-panel-extension/src/host/storage/index.ts+++ b/packages/dsh-tauri-panel-extension/src/host/storage/index.ts@@ -1,6 +1,5 @@-import { DSH_HOME, fsAtomicDriver } from 'dsh-tauri'-import { join } from 'pathe'+import { fsAtomicDriver } from 'dsh-tauri'import { createStorage } from 'unstorage'-import { SKILL_DATA_DIRECTORY } from '../config/constants'+import { SKILLS_DATA_DIR } from '../config/constants'-export const storage = createStorage({ driver: fsAtomicDriver({ base: join(DSH_HOME, SKILL_DATA_DIRECTORY) }) })+export const storage = createStorage({ driver: fsAtomicDriver({ base: SKILLS_DATA_DIR }) })diff --git a/packages/dsh-tauri-panel-extension/src/host/config/runtime.types.ts b/packages/dsh-tauri-panel-extension/src/host/types/index.tssimilarity index 100%rename from packages/dsh-tauri-panel-extension/src/host/config/runtime.types.tsrename to packages/dsh-tauri-panel-extension/src/host/types/index.tsdiff --git a/packages/dsh-tauri-panel-extension/src/host/utils/paths.utils.ts b/packages/dsh-tauri-panel-extension/src/host/utils/paths.utils.tsindex 51ec6f11..08985271 100644--- a/packages/dsh-tauri-panel-extension/src/host/utils/paths.utils.ts+++ b/packages/dsh-tauri-panel-extension/src/host/utils/paths.utils.ts@@ -1,13 +1,13 @@import { DSH_HOME } from 'dsh-tauri'import { join } from 'pathe'-import { PROFILES_DIRECTORY, REPOS_DIRECTORY, SKILL_DATA_DIRECTORY, SKILL_FILE_NAME } from '../config/constants'+import { SKILL_FILE_NAME, SKILLS_DATA_DIR } from '../config/constants'-export function skillsDataDir(): string {- return join(DSH_HOME, SKILL_DATA_DIRECTORY)-}+const PROFILES_DIRECTORY = 'profiles'++const REPOS_DIRECTORY = 'repos'export function skillDir(name: string): string {- return join(skillsDataDir(), name)+ return join(SKILLS_DATA_DIR, name)}export function skillFilePath(name: string): string {@@ -15,7 +15,7 @@ export function skillFilePath(name: string): string {}export function materialDirFor(entryId: string): string {- return join(skillsDataDir(), REPOS_DIRECTORY, entryId)+ return join(SKILLS_DATA_DIR, REPOS_DIRECTORY, entryId)}export function profileDir(profile: string): string {diff --git a/packages/dsh-tauri-panel-extension/src/shared/constants.ts b/packages/dsh-tauri-panel-extension/src/shared/constants.tsindex c9662749..5ab119cb 100644--- a/packages/dsh-tauri-panel-extension/src/shared/constants.ts+++ b/packages/dsh-tauri-panel-extension/src/shared/constants.ts@@ -1,3 +1 @@export const PLUGIN_ID = 'dsh-tauri-panel-extension'--export const API_PREFIX = `/${PLUGIN_ID}`