Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

refactor(dsh-tauri-panel-extension): colocate types and split the host config, events and services

hairyfe407cee2b816
diff --git a/packages/dsh-tauri-panel-extension/package.json b/packages/dsh-tauri-panel-extension/package.json
index 69a7c00d..4019bb6c 100644
--- a/packages/dsh-tauri-panel-extension/package.json
+++ b/packages/dsh-tauri-panel-extension/package.json
@@ -63,6 +63,7 @@
"dsh-tauri": "workspace:*",
"dsh-tauri-ui": "workspace:*",
"hookable": "catalog:utils",
+ "lodash-es": "catalog:utils",
"ofetch": "catalog:utils",
"pathe": "catalog:utils",
"unstorage": "catalog:utils",
@@ -71,6 +72,7 @@
"devDependencies": {
"@deepseek-ai/cordis": "catalog:dsh",
"@deepseek-ai/dsh-skill-filesystem": "catalog:dsh",
+ "@types/lodash-es": "catalog:types",
"dompurify": "catalog:ui",
"dsh-tauri-tsdown": "workspace:*",
"marked": "catalog:ui",
diff --git a/packages/dsh-tauri-panel-extension/src/client/apis/index.ts b/packages/dsh-tauri-panel-extension/src/client/apis/index.ts
index 74faad10..eee84cb6 100644
--- a/packages/dsh-tauri-panel-extension/src/client/apis/index.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/apis/index.ts
@@ -4,82 +4,66 @@ import { API_PREFIX } from '../../shared/constants'
export const baseURL = API_PREFIX
-/** @method get 查询技能列表。 */
export function getSkills(): Promise<Types.SkillsResponse> {
return fetch(`${baseURL}/skills`)
}
-/** @method post 强制宿主重扫全部技能根。 */
export function postSkillsRefresh(): Promise<Types.SkillsResponse> {
return fetch(`${baseURL}/skills/refresh`, { method: 'POST', body: {} })
}
-/** @method get 读取单个技能内容。 */
export function getSkill(name: string): Promise<Types.SkillContentResponse> {
return fetch(`${baseURL}/skill?name=${encodeURIComponent(name)}`)
}
-/** @method post 保存技能。 */
export function postSkillSave(body: Types.PostSkillSaveBody): Promise<Types.ActionResult> {
return fetch(`${baseURL}/skill/save`, { method: 'POST', body })
}
-/** @method post 删除技能。 */
export function postSkillDelete(body: Types.PostSkillDeleteBody): Promise<Types.ActionResult> {
return fetch(`${baseURL}/skill/delete`, { method: 'POST', body })
}
-/** @method post 切换技能加载策略。 */
export function postSkillPolicy(body: Types.PostSkillPolicyBody): Promise<Types.ActionResult> {
return fetch(`${baseURL}/skill/policy`, { method: 'POST', body })
}
-/** @method post 打开用户技能目录或某技能。 */
export function postOpen(target: { target: 'user-skills' | 'skill', name?: string }): Promise<Types.ActionResult> {
return fetch(`${baseURL}/open`, { method: 'POST', body: target })
}
-/** @method post 导入 GitHub 技能仓库。 */
export function postRootsAdd(url: string): Promise<Types.ActionResult> {
return fetch(`${baseURL}/roots/add`, { method: 'POST', body: { kind: 'git', url } })
}
-/** @method get 查询 MCP 服务器列表。 */
export function getMcp(): Promise<Types.McpListResponse> {
return fetch(`${baseURL}/mcp`)
}
-/** @method post 保存 MCP 服务器。 */
export function postMcpSave(body: Record<string, unknown>): Promise<Types.McpSaveResponse> {
return fetch(`${baseURL}/mcp/save`, { method: 'POST', body })
}
-/** @method post 检查 MCP 服务器连通性。 */
export function postMcpCheck(body: { id: string }): Promise<Types.McpConnectivityResponse> {
return fetch(`${baseURL}/mcp/check`, { method: 'POST', body })
}
-/** @method post 启用/禁用 MCP 服务器。 */
export function postMcpToggle(body: Types.PostMcpToggleBody): Promise<Types.ActionResult> {
return fetch(`${baseURL}/mcp/toggle`, { method: 'POST', body })
}
-/** @method post 移除 MCP 服务器。 */
export function postMcpRemove(body: Types.PostMcpRemoveBody): Promise<Types.ActionResult> {
return fetch(`${baseURL}/mcp/remove`, { method: 'POST', body })
}
-/** @method get 扫描可导入的 MCP 配置。 */
export function getMcpImportScan(): Promise<Types.McpImportScanResponse> {
return fetch(`${baseURL}/import/scan`)
}
-/** @method post 应用 MCP 导入项。 */
export function postMcpImportApply(body: Types.PostMcpApplyImportBody): Promise<Types.McpApplyImportResponse> {
return fetch(`${baseURL}/import/apply`, { method: 'POST', body })
}
-/** @method post 请求宿主重启(连接会断开)。 */
export function postRestart(): Promise<unknown> {
return fetch(`${baseURL}/restart`, { method: 'POST', body: {} })
}
diff --git a/packages/dsh-tauri-panel-extension/src/client/apis/index.type.ts b/packages/dsh-tauri-panel-extension/src/client/apis/index.type.ts
index ec5c8373..941459a5 100644
--- a/packages/dsh-tauri-panel-extension/src/client/apis/index.type.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/apis/index.type.ts
@@ -1,81 +1,111 @@
-import type { ImportedServerView, McpRow, SkillRowView } from '../types'
+export interface McpRow {
+ id: string
+ layer?: 'global' | 'profile'
+ shadowed?: boolean
+ globalError?: string
+ 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 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 type { ImportedServerView, McpRow, SkillRowView }
+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
+ editable: boolean
+ removable: boolean
+ dir?: string
+ policyEditable: boolean
+ repository?: SkillRepositoryView
+}
-/** GET /skills、POST /skills/refresh 响应。 */
export interface SkillsResponse {
skills: SkillRowView[]
}
-/** GET /skill 响应。 */
export interface SkillContentResponse {
content: string
}
-/** 简单动作结果(save/delete/policy/open/import/mcp 变更)。 */
export interface ActionResult {
ok: boolean
error?: string
}
-/** POST /mcp/save 响应(宿主返回新服务器 id)。 */
export interface McpSaveResponse {
ok: boolean
id: string
}
-/** GET /mcp 响应。 */
export interface McpListResponse {
servers: McpRow[]
global?: McpRow[]
profile?: McpRow[]
}
-/** POST /mcp/check connectivity response. */
export interface McpConnectivityResponse {
ok: boolean
latencyMs?: number
error?: string
}
-/** GET /import/scan 响应。 */
export interface McpImportScanResponse {
servers: ImportedServerView[]
existing: string[]
}
-/** POST /import/apply 响应。 */
export interface McpApplyImportResponse {
ok: boolean
results: Array<{ name: string, ok: boolean, error?: string }>
}
-/** POST /skill/save 请求体。 */
export type PostSkillSaveBody = Record<string, unknown>
-/** POST /skill/delete 请求体。 */
export interface PostSkillDeleteBody {
name: string
}
-/** POST /skill/policy 请求体。 */
export interface PostSkillPolicyBody {
name: string
enabled: boolean
}
-/** POST /mcp/toggle 请求体。 */
export interface PostMcpToggleBody {
id: string
disabled: boolean
}
-/** POST /mcp/remove 请求体。 */
export interface PostMcpRemoveBody {
id: string
}
-/** POST /import/apply 请求体。 */
export interface PostMcpApplyImportBody {
items: Array<{ agent: string, name: string }>
}
diff --git a/packages/dsh-tauri-panel-extension/src/client/components/extension-panel.cssr.ts b/packages/dsh-tauri-panel-extension/src/client/components/extension-panel.cssr.ts
index 07a7483d..cc79e935 100644
--- a/packages/dsh-tauri-panel-extension/src/client/components/extension-panel.cssr.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/components/extension-panel.cssr.ts
@@ -1,16 +1,14 @@
-import { cssr, styles as sharedStyles } from 'dsh-tauri-ui/client'
+import { cssr, panelContainer, styles as sharedStyles } from 'dsh-tauri-ui/client'
const { c, bem: { b, e } } = cssr
const { primary, tertiary, borderL2: border, business } = sharedStyles
-/** 扩展面板外壳(extension-panel.tsx):Tabs 布局。 */
export default b('extension', [
e('section', {
+ ...panelContainer,
display: 'flex',
flexDirection: 'column',
gap: '14px',
- width: '100%',
- maxWidth: '760px',
color: primary,
}),
e('tabs', {
diff --git a/packages/dsh-tauri-panel-extension/src/client/components/extension-panel.tsx b/packages/dsh-tauri-panel-extension/src/client/components/extension-panel.tsx
index 0c025e2e..3853a477 100644
--- a/packages/dsh-tauri-panel-extension/src/client/components/extension-panel.tsx
+++ b/packages/dsh-tauri-panel-extension/src/client/components/extension-panel.tsx
@@ -1,25 +1,18 @@
-/**
- * components/extension-panel.tsx — 扩展面板:技能 / MCP 两个 tab 的容器 UI。
- *
- * 只负责 tab 切换(键盘导航 + visited 惰性挂载);各 tab 内容由
- * SkillsTab / McpTab 子组件承担(直接消费 apis/)。
- */
-
import type { ReactElement } from 'react'
-import type { Translate } from '../types'
import { useMountStyle } from 'dsh-tauri-ui/client'
import { useEffect, useId, useRef, useState } from 'react'
import { EXTENSION_PANEL_STYLE_ID } from '../constants'
+import { locale } from '../locales'
import extensionPanelStyle from './extension-panel.cssr'
import { McpTab } from './mcp-tab'
import { SkillsTab } from './skills-tab'
export interface ExtensionPanelProps {
- t: Translate
createSkill: () => Promise<void>
}
-export function ExtensionPanel({ t, createSkill }: ExtensionPanelProps): ReactElement {
+export function ExtensionPanel({ createSkill }: ExtensionPanelProps): ReactElement {
+ const t = locale.text
useMountStyle(extensionPanelStyle, EXTENSION_PANEL_STYLE_ID)
const tabsId = useId()
const tabRefs = useRef<Array<HTMLButtonElement | null>>([])
diff --git a/packages/dsh-tauri-panel-extension/src/client/components/markdown.cssr.ts b/packages/dsh-tauri-panel-extension/src/client/components/markdown.cssr.ts
index 5eb3b4a0..8736e7d8 100644
--- a/packages/dsh-tauri-panel-extension/src/client/components/markdown.cssr.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/components/markdown.cssr.ts
@@ -3,7 +3,6 @@ import { cssr, styles as sharedStyles } from 'dsh-tauri-ui/client'
const { c, bem: { b, e } } = cssr
const { primary, borderL2: border, business, layer1, layer3 } = sharedStyles
-/** 技能详情 Markdown 预览(markdown.tsx)。 */
export default b('extension', [
e('md-preview', {
minHeight: '320px',
diff --git a/packages/dsh-tauri-panel-extension/src/client/components/mcp-editor-form.cssr.ts b/packages/dsh-tauri-panel-extension/src/client/components/mcp-editor-form.cssr.ts
index 73b1338a..c547902c 100644
--- a/packages/dsh-tauri-panel-extension/src/client/components/mcp-editor-form.cssr.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/components/mcp-editor-form.cssr.ts
@@ -3,7 +3,6 @@ import { cssr, styles as sharedStyles } from 'dsh-tauri-ui/client'
const { c, bem: { b, e } } = cssr
const { primary, tertiary, borderL2: border, business } = sharedStyles
-/** MCP 服务器编辑器(mcp-editor-form.tsx):编辑器页签 + JSON 编辑区。 */
export default b('extension', [
e('editor-tabs', { display: 'flex', gap: '4px', borderBottom: `1px solid ${border}` }),
e('editor-tab', {
diff --git a/packages/dsh-tauri-panel-extension/src/client/components/mcp-editor-form.tsx b/packages/dsh-tauri-panel-extension/src/client/components/mcp-editor-form.tsx
index 4db548c2..a0c232a5 100644
--- a/packages/dsh-tauri-panel-extension/src/client/components/mcp-editor-form.tsx
+++ b/packages/dsh-tauri-panel-extension/src/client/components/mcp-editor-form.tsx
@@ -1,11 +1,6 @@
-/**
- * components/mcp-editor-form.tsx — MCP 服务器编辑器(json 粘贴 / 表单双 tab)。
- *
- * 纯受控表单:状态由父组件(McpTab)持有,这里只渲染与回调。
- */
-
import type { ReactElement } from 'react'
-import type { McpEditorMode, McpEditorState, Translate } from '../types'
+import type { Translate } from '../locales/index.types'
+import type { McpEditorMode, McpEditorState } from './mcp-tab.types'
import { Button } from '@deepseek-ai/dsh-client-ui-primitives'
import { useMountStyle } from 'dsh-tauri-ui/client'
import { MCP_EDITOR_FORM_STYLE_ID } from '../constants'
diff --git a/packages/dsh-tauri-panel-extension/src/client/components/mcp-import-dialog.cssr.ts b/packages/dsh-tauri-panel-extension/src/client/components/mcp-import-dialog.cssr.ts
index e10c40b6..d6d6666e 100644
--- a/packages/dsh-tauri-panel-extension/src/client/components/mcp-import-dialog.cssr.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/components/mcp-import-dialog.cssr.ts
@@ -3,7 +3,6 @@ import { cssr, styles as sharedStyles } from 'dsh-tauri-ui/client'
const { bem: { b, e, m } } = cssr
const { secondary, tertiary } = sharedStyles
-/** MCP 批量导入弹窗(mcp-import-dialog.tsx):分组滚动列表 + 勾选行。 */
export default b('extension', [
e('import-scroll', {
display: 'flex',
diff --git a/packages/dsh-tauri-panel-extension/src/client/components/mcp-import-dialog.tsx b/packages/dsh-tauri-panel-extension/src/client/components/mcp-import-dialog.tsx
index 0fadeb56..e06aa4fd 100644
--- a/packages/dsh-tauri-panel-extension/src/client/components/mcp-import-dialog.tsx
+++ b/packages/dsh-tauri-panel-extension/src/client/components/mcp-import-dialog.tsx
@@ -1,16 +1,11 @@
-/**
- * components/mcp-import-dialog.tsx — MCP 跨目录导入弹窗(按 agent 分组勾选)。
- *
- * 纯受控组件:勾选状态由父组件(McpTab)持有,这里只渲染与回调。
- */
-
import type { ReactElement } from 'react'
-import type { McpImportItem, Translate } from '../types'
+import type { Translate } from '../locales/index.types'
+import type { McpImportItem } from './mcp-tab.types'
import { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
import { useMountStyle } from 'dsh-tauri-ui/client'
import { MCP_IMPORT_DIALOG_STYLE_ID } from '../constants'
-import { importGroups } from '../utils/mcp'
import mcpImportDialogStyle from './mcp-import-dialog.cssr'
+import { importGroups } from './mcp-tab.utils'
export interface McpImportDialogProps {
t: Translate
diff --git a/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.cssr.ts b/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.cssr.ts
index 07c3b17f..70859222 100644
--- a/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.cssr.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.cssr.ts
@@ -3,7 +3,6 @@ import { cssr, styles as sharedStyles } from 'dsh-tauri-ui/client'
const { c, bem: { b, e } } = cssr
const { primary, borderL2: border, business, layer1 } = sharedStyles
-/** MCP 列表(mcp-tab.tsx):list-head 内的范围筛选下拉。 */
export default b('extension', [
e('scope', {
boxSizing: 'border-box',
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.tsx
index b2f76adb..eb16331e 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,26 +1,19 @@
-/**
- * components/mcp-tab.tsx — Settings → Plugins “MCP” tab:管理 profile 的
- * mcp-client 行。Mutations 改写 profile patch 并需要 dsh 重启——banner 在有
- * 桌面壳时把重启交给壳层。
- *
- * 职责拆分:纯解析/分组逻辑在 lib/mcp.ts,受控表单/导入弹窗在
- * components/mcp-editor-form.tsx 与 mcp-import-dialog.tsx,定时器管理在
- * hooks/use-timers.ts;本组件只保留列表状态与业务编排。
- */
-
import type { ReactElement } from 'react'
-import type { McpEditorMode, McpEditorState, McpImportItem, McpRow, McpTabProps } from '../types'
+import type { McpRow } from '../apis/index.type'
+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 { 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 { handlePostMcpRestart, isMcpDesktop } from '../service/handle-post-mcp-restart'
-import { mapToPairs, parseMcpJson, parsePairs } from '../utils/mcp'
+import { restartHost } from '../service/restart'
+import { isDesktopHost } from '../service/restart.utils'
import { McpEditorForm } from './mcp-editor-form'
import { McpImportDialog } from './mcp-import-dialog'
import mcpTabStyle from './mcp-tab.cssr'
+import { mapToPairs, parseMcpJson, parsePairs } from './mcp-tab.utils'
export function McpTab({ t }: McpTabProps): ReactElement {
useMountStyle(mcpTabStyle, MCP_TAB_STYLE_ID)
@@ -146,7 +139,6 @@ export function McpTab({ t }: McpTabProps): ReactElement {
})
}
- /** Fill the form from pasted JSON (mcpServers wrapper, bare entry, dsh row). */
const doPasteFill = (): void => {
if (editor === null || pasteJson.trim() === '')
return
@@ -155,8 +147,6 @@ export function McpTab({ t }: McpTabProps): ReactElement {
setPasteError(parsed.error)
return
}
- // Existing rows keep their identity (serverName + transport); a pasted
- // config of the other transport cannot apply to them.
const lockIdentity = editor.id !== ''
if (lockIdentity && parsed.transport !== editor.transport) {
setPasteError(t('pasteTransportMismatch'))
@@ -170,14 +160,14 @@ export function McpTab({ t }: McpTabProps): ReactElement {
...(!lockIdentity ? { transport: parsed.transport } : {}),
...(parsed.transport === 'stdio'
? {
- command: parsed.command ?? editor.command,
- args: (parsed.args ?? []).join('\n'),
- env: mapToPairs(parsed.env, '='),
- }
+ command: parsed.command ?? editor.command,
+ args: (parsed.args ?? []).join('\n'),
+ env: mapToPairs(parsed.env, '='),
+ }
: {
- url: parsed.url ?? editor.url,
- headers: mapToPairs(parsed.headers, ':'),
- }),
+ url: parsed.url ?? editor.url,
+ headers: mapToPairs(parsed.headers, ':'),
+ }),
})
setEditorMode('form')
}
@@ -208,14 +198,14 @@ export function McpTab({ t }: McpTabProps): ReactElement {
transport: editor.transport,
...(editor.transport === 'stdio'
? {
- command: editor.command.trim(),
- args: editor.args.split(/\r?\n/).map(line => line.trim()).filter(line => line !== ''),
- env: parsePairs(editor.env, '='),
- }
+ command: editor.command.trim(),
+ args: compact(editor.args.split(/\r?\n/).map(line => line.trim())),
+ env: parsePairs(editor.env, '='),
+ }
: {
- url: editor.url.trim(),
- headers: parsePairs(editor.headers, ':'),
- }),
+ url: editor.url.trim(),
+ headers: parsePairs(editor.headers, ':'),
+ }),
}
}
setBusy(true)
@@ -271,9 +261,8 @@ export function McpTab({ t }: McpTabProps): ReactElement {
const doRestart = (): void => {
setRestartConfirm(false)
setRestarting(true)
- void handlePostMcpRestart()
- // 桌面模式:壳层重启完成后会重载窗口。独立模式:轮询本源,恢复即刷新。
- if (isMcpDesktop())
+ void restartHost()
+ if (isDesktopHost())
return
const deadline = Date.now() + MCP_RESTART_TIMEOUT_MS
const poll = (): void => {
@@ -296,15 +285,15 @@ export function McpTab({ t }: McpTabProps): ReactElement {
<span>{restarting ? t('restarting') : t('restartNeeded')}</span>
<span className="dshp-extension__banner-hint">
{restarting
- ? (!isMcpDesktop() && t('restartPortHint'))
- : isMcpDesktop()
+ ? (!isDesktopHost() && t('restartPortHint'))
+ : isDesktopHost()
? (
- <>
- {t('restartDesktopHint')}
- {' '}
- <Button variant="outline" size="sm" onClick={() => setRestartConfirm(true)}>{t('restartNow')}</Button>
- </>
- )
+ <>
+ {t('restartDesktopHint')}
+ {' '}
+ <Button variant="outline" size="sm" onClick={() => setRestartConfirm(true)}>{t('restartNow')}</Button>
+ </>
+ )
: t('restartOtherHint')}
</span>
</div>
@@ -312,7 +301,7 @@ export function McpTab({ t }: McpTabProps): ReactElement {
)
return (
- <div className="dshp-extension__section">
+ <div className="dshp-extension__section" style={{ margin: '0' }}>
<div className="dshp-extension__head">
<Icon as={PlugConnection} />
<h3>{t('mcpTitle')}</h3>
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.ts
new file mode 100644
index 00000000..624871e0
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.types.ts
@@ -0,0 +1,35 @@
+import type { ImportedServerView } from '../apis/index.type'
+import type { Translate } from '../locales/index.types'
+
+export type McpEditorMode = 'json' | 'form'
+
+export interface McpEditorState {
+ id: string
+ serverName: string
+ transport: 'stdio' | 'streamable-http'
+ command: string
+ args: string
+ env: string
+ url: string
+ headers: string
+}
+
+export interface McpImportItem {
+ server: ImportedServerView
+ existing: boolean
+ checked: boolean
+}
+
+export interface ParsedMcpJson {
+ serverName?: string
+ transport: 'stdio' | 'streamable-http'
+ command?: string
+ args?: string[]
+ env?: Record<string, string>
+ url?: string
+ headers?: Record<string, string>
+}
+
+export interface McpTabProps {
+ t: Translate
+}
diff --git a/packages/dsh-tauri-panel-extension/src/client/utils/mcp.ts b/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.utils.ts
similarity index 73%
rename from packages/dsh-tauri-panel-extension/src/client/utils/mcp.ts
rename to packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.utils.ts
index 44b5b6f6..154fb209 100644
--- a/packages/dsh-tauri-panel-extension/src/client/utils/mcp.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/components/mcp-tab.utils.ts
@@ -1,22 +1,10 @@
-/**
- * lib/mcp.ts — MCP 导入/解析的纯函数(无 DOM、无 React、无副作用)。
- * 从 mcp-tab.tsx 剥离,便于单测与复用。
- */
+import type { McpImportItem, ParsedMcpJson } from './mcp-tab.types'
+import { isEmpty, omitBy, orderBy, uniq } from 'dsh-tauri/client'
-import type { McpImportItem, ParsedMcpJson } from '../types'
-
-/** Group import candidates by source agent, known agents first. */
export function importGroups(items: McpImportItem[]): Array<{ agent: string, label: string, items: Array<{ item: McpImportItem, index: number }> }> {
const label = (agent: string): string => agent === 'claude-code' ? 'Claude Code' : agent === 'codex' ? 'Codex' : agent === 'cursor' ? 'Cursor' : agent === 'gemini' ? 'Gemini CLI' : agent
const order = ['claude-code', 'codex', 'cursor', 'gemini']
- const agents = [...new Set(items.map(item => item.server.agent))]
- .sort((a, b) => {
- const rank = (agent: string): number => {
- const at = order.indexOf(agent)
- return at === -1 ? order.length : at
- }
- return rank(a) - rank(b) || a.localeCompare(b)
- })
+ const agents = orderBy(uniq(items.map(item => item.server.agent)), agent => order.indexOf(agent))
return agents.map(agent => ({
agent,
label: label(agent),
@@ -24,7 +12,6 @@ export function importGroups(items: McpImportItem[]): Array<{ agent: string, lab
}))
}
-/** KEY=VALUE / KEY: VALUE lines to a map. */
export function parsePairs(text: string, separator: ':' | '='): Record<string, string> {
const map: Record<string, string> = {}
for (const line of text.split(/\r?\n/)) {
@@ -45,10 +32,6 @@ export function mapToPairs(map: Record<string, string> | undefined, separator: s
return Object.entries(map).map(([key, value]) => `${key}${separator}${value.includes('\n') ? JSON.stringify(value) : value}`).join('\n')
}
-/**
- * Parse one MCP server from pasted JSON: a bare entry, a dsh row, or a
- * `{"mcpServers": {…}}` wrapper (first entry wins). Returns the reason on bad input.
- */
export function parseMcpJson(text: string): ParsedMcpJson | { error: string } {
let parsed: unknown
try {
@@ -74,12 +57,8 @@ export function parseMcpJson(text: string): ParsedMcpJson | { error: string } {
const stringMap = (value: unknown): Record<string, string> | undefined => {
if (typeof value !== 'object' || value === null || Array.isArray(value))
return undefined
- const out: Record<string, string> = {}
- for (const [key, entry] of Object.entries(value)) {
- if (typeof entry === 'string')
- out[key] = entry
- }
- return Object.keys(out).length > 0 ? out : undefined
+ const out = omitBy(value as Record<string, unknown>, entry => typeof entry !== 'string') as Record<string, string>
+ return isEmpty(out) ? undefined : out
}
const args = Array.isArray(record.args) && record.args.every(entry => typeof entry === 'string')
? record.args as string[]
@@ -100,13 +79,6 @@ export function parseMcpJson(text: string): ParsedMcpJson | { error: string } {
?? (typeof record.name === 'string' && record.name !== '@deepseek-ai/dsh-mcp-client' ? record.name : undefined)
const env = stringMap(record.env)
const headers = stringMap(record.headers)
- return {
- ...(serverName !== undefined ? { serverName } : {}),
- transport,
- ...(command !== undefined ? { command } : {}),
- ...(args !== undefined ? { args } : {}),
- ...(env !== undefined ? { env } : {}),
- ...(url !== undefined ? { url } : {}),
- ...(headers !== undefined ? { headers } : {}),
- }
+ const draft: ParsedMcpJson = { serverName, transport, command, args, env, url, headers }
+ return omitBy(draft, value => value === undefined) as ParsedMcpJson
}
diff --git a/packages/dsh-tauri-panel-extension/src/client/components/skill-creator-prefill.tsx b/packages/dsh-tauri-panel-extension/src/client/components/skill-creator-prefill.tsx
index c07fd402..8277dbb5 100644
--- a/packages/dsh-tauri-panel-extension/src/client/components/skill-creator-prefill.tsx
+++ b/packages/dsh-tauri-panel-extension/src/client/components/skill-creator-prefill.tsx
@@ -1,12 +1,4 @@
-/**
- * components/skill-creator-prefill.tsx — 新会话草稿预填组件。
- *
- * 注册进 conversation.input.left;当 createSkill 流程登记了该会话 id 时,
- * 挂载后把技能创建器草稿写进输入框,随后从登记集合移除(一次性)。
- * 组件不渲染 store 内容,故只经 `store.prefill.consume` 读写,不订阅快照。
- */
-
-import type { ConversationInputLeftProps } from '../types'
+import type { ConversationInputLeftProps } from './skill-creator-prefill.types'
import { useEffect } from 'react'
import { SKILL_CREATOR_DRAFT } from '../constants'
import { store } from '../store'
diff --git a/packages/dsh-tauri-panel-extension/src/client/components/skill-creator-prefill.types.ts b/packages/dsh-tauri-panel-extension/src/client/components/skill-creator-prefill.types.ts
new file mode 100644
index 00000000..21bb14f6
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/client/components/skill-creator-prefill.types.ts
@@ -0,0 +1,8 @@
+export interface InputActions {
+ setDraft: (text: string) => void
+}
+
+export interface ConversationInputLeftProps {
+ sessionId: string
+ inputActions: InputActions
+}
diff --git a/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.cssr.ts b/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.cssr.ts
index 511a458b..28ffd265 100644
--- a/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.cssr.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.cssr.ts
@@ -3,7 +3,6 @@ import { cssr, styles as sharedStyles } from 'dsh-tauri-ui/client'
const { c, bem: { b, e } } = cssr
const { primary, secondary, tertiary, borderL2: border, business, layer1, layer3, hover } = sharedStyles
-/** 技能列表(skills-tab.tsx):头部 + 横幅 + 刷新。 */
export default b('extension', [
e('head', {
display: 'flex',
@@ -143,7 +142,6 @@ export default b('extension', [
}, [
c('&:hover', { textDecoration: 'underline' }),
]),
- // 技能编辑器弹窗的「预览 / 编辑」分段切换(skills-tab.tsx editor modal)。
e('segments', {
display: 'inline-flex',
gap: '4px',
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.tsx
index 0566ebfa..311ecedb 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,22 +1,16 @@
-/**
- * components/skills-tab.tsx — Settings → Plugins “Skills” tab:查看/编辑技能、
- * 导入 GitHub 技能仓库、切换加载策略。
- *
- * 职责拆分:policyTag / normalizeRepository 在 lib/skills.ts,定时器与挂载守卫
- * 在 hooks/use-timers.ts;本组件只保留列表状态与业务编排。
- */
-
import type { ReactElement } from 'react'
-import type { OpenTarget, SkillEditorState, SkillRowView, SkillsTabProps } from '../types'
+import type { SkillRowView } from '../apis/index.type'
+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 { 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'
-import { normalizeRepository, policyTag } from '../utils/skills'
import skillsTabStyle from './skills-tab.cssr'
+import { normalizeRepository, policyTag } from './skills-tab.utils'
export function SkillsTab({ t, createSkill }: SkillsTabProps): ReactElement {
useMountStyle(skillsTabStyle, SKILLS_TAB_STYLE_ID)
@@ -61,8 +55,6 @@ export function SkillsTab({ t, createSkill }: SkillsTabProps): ReactElement {
setOutcome({ ok: true, text: t('refreshed') })
}
catch {
- // A transient rescan failure (e.g. a locked provider) should still let
- // the user see the last-good catalog without restarting the page.
setReload(value => value + 1)
}
finally { setBusy(false) }
@@ -190,12 +182,12 @@ export function SkillsTab({ t, createSkill }: SkillsTabProps): ReactElement {
}
const needle = query.trim().toLowerCase()
- const filtered = useMemo(() => (skills ?? []).map((skill, index) => ({ skill, index })).filter(({ skill }) => (sourceFilter === 'all' || skill.source === sourceFilter) && (needle === '' || skill.name.toLowerCase().includes(needle) || skill.description.toLowerCase().includes(needle))).sort((a, b) => Number(b.skill.repository !== undefined) - Number(a.skill.repository !== undefined) || a.index - b.index).map(({ skill }) => skill), [needle, skills, sourceFilter])
- const sources = skills === null ? [] : [...new Set(skills.map(skill => skill.source))]
+ const filtered = useMemo(() => orderBy((skills ?? []).filter(skill => (sourceFilter === 'all' || skill.source === sourceFilter) && (needle === '' || skill.name.toLowerCase().includes(needle) || skill.description.toLowerCase().includes(needle))), [skill => skill.repository === undefined]), [needle, skills, sourceFilter])
+ const sources = skills === null ? [] : uniq(skills.map(skill => skill.source))
const readOnly = editor?.mode === 'view'
return (
- <div className="dshp-extension__section">
+ <div className="dshp-extension__section" style={{ margin: '0' }}>
<div className="dshp-extension__head">
<Icon as={GraduationCap} />
<h3>{t('skillsTitle')}</h3>
diff --git a/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.types.ts b/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.types.ts
new file mode 100644
index 00000000..9fdd1b6d
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.types.ts
@@ -0,0 +1,18 @@
+import type { Translate } from '../locales/index.types'
+
+export interface SkillEditorState {
+ mode: 'edit' | 'view'
+ name: string
+ description: string
+ whenToUse: string
+ modelInvocable: boolean
+ userInvocable: boolean
+ content: string
+}
+
+export type OpenTarget = { target: 'user-skills' } | { target: 'skill', name: string }
+
+export interface SkillsTabProps {
+ t: Translate
+ createSkill: () => Promise<void>
+}
diff --git a/packages/dsh-tauri-panel-extension/src/client/utils/skills.ts b/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.utils.ts
similarity index 69%
rename from packages/dsh-tauri-panel-extension/src/client/utils/skills.ts
rename to packages/dsh-tauri-panel-extension/src/client/components/skills-tab.utils.ts
index af5f1305..69e08256 100644
--- a/packages/dsh-tauri-panel-extension/src/client/utils/skills.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/components/skills-tab.utils.ts
@@ -1,12 +1,8 @@
-/**
- * lib/skills.ts — 技能列表展示的纯函数(无 DOM、无 React、无副作用)。
- * 从 skills-tab.tsx 剥离,便于单测与复用。
- */
-
-import type { SkillRowView } from '../types'
+import type { SkillRowView } from '../apis/index.type'
+import type { LocaleKey } from '../locales/index.types'
import { GITHUB_REPOSITORY_PATTERN } from '../constants'
-export function policyTag(skill: SkillRowView): { key?: string, off: boolean } {
+export function policyTag(skill: SkillRowView): { key?: LocaleKey, off: boolean } {
const { modelInvocable, userInvocable } = skill.invocation
if (!modelInvocable && !userInvocable)
return { key: 'skillDisabled', off: true }
diff --git a/packages/dsh-tauri-panel-extension/src/client/constants/index.ts b/packages/dsh-tauri-panel-extension/src/client/constants/index.ts
index b567bfaf..f0c45042 100644
--- a/packages/dsh-tauri-panel-extension/src/client/constants/index.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/constants/index.ts
@@ -1,30 +1,27 @@
+import type { LocaleKey } from '../locales/index.types'
import { PLUGIN_NAME } from '../../shared/constants'
export { API_PREFIX, PLUGIN_NAME as PLUGIN_ID } from '../../shared/constants'
-export const LOCALE_NAMESPACE = PLUGIN_NAME
-export const PANEL_PROTOCOL_NAME = 'panel.protocol'
-/**
- * 宿主私有面板槽:本插件只用它作为「宿主已 apply」的就绪门槛
- * (实际注册经 panel.protocol.registerPanel,槽名由宿主按核心版本决定)。
- */
-export const PANEL_SLOT_NAME = 'sidebar.panel.action'
export const CONVERSATION_INPUT_LEFT_SLOT = 'conversation.input.left'
-export const PANEL_ID = 'dsh-tauri-panel-extension'
-/** 面板条目在侧栏清单里的排序位。 */
+export const PANEL_ID = PLUGIN_NAME
export const PANEL_ACTION_ORDER = 40
-/** 宿主协议未就绪时的重试间隔。 */
-export const PROTOCOL_RETRY_MS = 50
-export const INPUT_PREFILL_ID = 'dsh-tauri-panel-extension.skill-prefill'
+export const INPUT_PREFILL_ID = `${PLUGIN_NAME}.skill-prefill`
export const INPUT_PREFILL_ORDER = 40
export const INPUT_PREFILL_PRIORITY = 0
-export const STYLE_ID = 'dsh-tauri-panel-extension-styles'
-export const EXTENSION_PANEL_STYLE_ID = 'dsh-tauri-panel-extension-panel-styles'
-export const SKILLS_TAB_STYLE_ID = 'dsh-tauri-panel-extension-skills-tab-styles'
-export const MCP_TAB_STYLE_ID = 'dsh-tauri-panel-extension-mcp-tab-styles'
-export const MARKDOWN_STYLE_ID = 'dsh-tauri-panel-extension-markdown-styles'
-export const MCP_EDITOR_FORM_STYLE_ID = 'dsh-tauri-panel-extension-editor-form-styles'
-export const MCP_IMPORT_DIALOG_STYLE_ID = 'dsh-tauri-panel-extension-import-dialog-styles'
+export const STYLE_ID = `${PLUGIN_NAME}-styles`
+export const EXTENSION_PANEL_STYLE_ID = `${PLUGIN_NAME}-panel-styles`
+export const SKILLS_TAB_STYLE_ID = `${PLUGIN_NAME}-skills-tab-styles`
+export const MCP_TAB_STYLE_ID = `${PLUGIN_NAME}-mcp-tab-styles`
+export const MARKDOWN_STYLE_ID = `${PLUGIN_NAME}-markdown-styles`
+export const MCP_EDITOR_FORM_STYLE_ID = `${PLUGIN_NAME}-editor-form-styles`
+export const MCP_IMPORT_DIALOG_STYLE_ID = `${PLUGIN_NAME}-import-dialog-styles`
+
+export const LOCALE_EFFECT = `${PLUGIN_NAME}: locale`
+export const STYLES_EFFECT = `${PLUGIN_NAME}: styles`
+export const SKILL_CREATOR_PREFILL_EFFECT = `${PLUGIN_NAME}: skill creator prefill`
+export const EXTENSION_PANEL_EFFECT = `${PLUGIN_NAME}: extension panel`
+
export const SKILL_CREATOR_DRAFT = '/skill-creator '
export const SKILL_REFRESH_INTERVAL_MS = 300
export const SKILL_REFRESH_TIMEOUT_MS = 5_000
@@ -34,7 +31,7 @@ export const MCP_RESTART_POLL_INTERVAL_MS = 1_500
export const MCP_RESTART_TIMEOUT_MS = 60_000
export const GITHUB_REPOSITORY_PATTERN = /^(?:https?:\/\/github\.com\/)?[\w.-]+\/[\w.-]+\/?$/i
-export const SOURCE_LOCALE_KEYS: Readonly<Record<string, string>> = {
+export const SOURCE_LOCALE_KEYS: Readonly<Record<string, LocaleKey>> = {
'project-dsh': 'sourceProjectDsh',
'project-agents': 'sourceProjectAgents',
'user-dsh': 'sourceUserDsh',
diff --git a/packages/dsh-tauri-panel-extension/src/client/hooks/use-timers.ts b/packages/dsh-tauri-panel-extension/src/client/hooks/use-timers.ts
index f49e636c..7a6e9bbd 100644
--- a/packages/dsh-tauri-panel-extension/src/client/hooks/use-timers.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/hooks/use-timers.ts
@@ -1,22 +1,11 @@
-/**
- * hooks/use-timers.ts — 受控定时器集合 + mounted 守卫。
- *
- * 多个 tab(skills / mcp)都需要「组件卸载时清理全部 timer、回调只在仍挂载时
- * 执行」的同一形态;抽成共享 hook,避免每个组件各自维护 `timers.current` +
- * `mounted.current` + 清理 effect。
- */
-
import type { MutableRefObject } from 'react'
import { useEffect, useRef } from 'react'
export interface TimersController {
- /** 组件是否仍挂载(异步续接守卫;卸载时置 false)。 */
mounted: MutableRefObject<boolean>
- /** 登记一个 timer;组件卸载时统一清理,且回调只会在仍挂载时触发。 */
later: (callback: () => void, delay: number) => void
}
-/** 创建受控 timer 集合;组件卸载时统一清理并停止后续回调。 */
export function useTimers(): TimersController {
const timers = useRef<Set<number>>(new Set())
const mounted = useRef(true)
diff --git a/packages/dsh-tauri-panel-extension/src/client/index.ts b/packages/dsh-tauri-panel-extension/src/client/index.ts
index ed34c035..d9ae06a2 100644
--- a/packages/dsh-tauri-panel-extension/src/client/index.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/index.ts
@@ -1,38 +1,23 @@
-/**
- * client/index.ts — 扩展面板客户端装配入口。
- *
- * 只做 import + 组装:三个 `defineRegister` feature(locale / 全局样式 / 技能创建器
- * 预填 / 扩展面板)各自收敛一类运行时资源,经 `ctx.effect` 挂载与卸载;跨核心版本的
- * 服务布局差异由 feature 的 `adapter`(第三个参数)承担,装配层不再自行 `compat(ctx)`。
- * 无业务实现。结构分层见 AGENTS.md 客户端目录模板:types/ utils/ hooks/ apis/
- * components/ register/ store/ 各司其职。
- */
-
-import type { ExtensionClientContext } from './types'
-import { mountStyle } from 'dsh-tauri-ui/client'
-import { defineRegister } from 'dsh-tauri/client'
-import { PLUGIN_ID, STYLE_ID } from './constants'
-import { registerExtensionLocale } from './locales'
+import type { ClientContext } from 'dsh-tauri/client'
+import {
+ EXTENSION_PANEL_EFFECT,
+ LOCALE_EFFECT,
+ PLUGIN_ID,
+ SKILL_CREATOR_PREFILL_EFFECT,
+ STYLES_EFFECT,
+} from './constants'
+import { locale } from './locales'
import { extensionPanelFeature } from './register/extension-panel'
import { skillCreatorPrefillFeature } from './register/skill-creator-prefill'
-import extensionIndexStyle from './styles/index.cssr'
+import { stylesFeature } from './register/styles'
export const name = PLUGIN_ID
-export const inject = ['slots', 'locale', 'sessions', 'workspaces']
-/** 双语字典安装 feature(卸载时注销两个语言的注册句柄)。 */
-const localeFeature = defineRegister<ExtensionClientContext>((controller, ctx) => {
- controller.add(registerExtensionLocale(ctx))
-})
-
-/** 全局样式 feature(css-render 树只在 effect 生命周期内挂载)。 */
-const stylesFeature = defineRegister<ExtensionClientContext>((controller) => {
- controller.add(mountStyle(extensionIndexStyle, STYLE_ID))
-})
+export const inject = ['slots', 'locale', 'sessions', 'workspaces']
-export function apply(ctx: ExtensionClientContext): void {
- ctx.effect(localeFeature, `${PLUGIN_ID}: locale`)
- ctx.effect(stylesFeature, `${PLUGIN_ID}: styles`)
- ctx.effect(skillCreatorPrefillFeature, `${PLUGIN_ID}: skill creator prefill`)
- ctx.effect(extensionPanelFeature, `${PLUGIN_ID}: extension panel`)
+export function apply(ctx: ClientContext): void {
+ ctx.effect(locale.registerLocale, LOCALE_EFFECT)
+ ctx.effect(stylesFeature, STYLES_EFFECT)
+ ctx.effect(skillCreatorPrefillFeature, SKILL_CREATOR_PREFILL_EFFECT)
+ ctx.effect(extensionPanelFeature, EXTENSION_PANEL_EFFECT)
}
diff --git a/packages/dsh-tauri-panel-extension/src/client/locales/index.ts b/packages/dsh-tauri-panel-extension/src/client/locales/index.ts
index 2c299ffc..e41d66ce 100644
--- a/packages/dsh-tauri-panel-extension/src/client/locales/index.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/locales/index.ts
@@ -1,5 +1,5 @@
-import type { ExtensionClientContext } from '../types'
-import { LOCALE_NAMESPACE } from '../constants'
+import { defineLocale } from 'dsh-tauri/client'
+import { PLUGIN_ID } from '../constants'
const zh = {
extension: '扩展技能',
@@ -229,19 +229,4 @@ const en: Record<LocaleKey, string> = {
shadowedByGlobal: 'a global row with the same id wins — this row has no effect',
}
-/**
- * 注册 zh/en 双语字典;返回注销句柄(卸载时同时注销两个语言)。
- *
- * 安装器只做注册,不再自己 `ctx.effect`:调用方(`register/locale` feature)用
- * `controller.add(...)` 把返回值收敛进统一清理队列。
- */
-export function registerExtensionLocale(ctx: ExtensionClientContext): () => void {
- const disposers = [
- ctx.locale.register(LOCALE_NAMESPACE, 'zh', zh),
- ctx.locale.register(LOCALE_NAMESPACE, 'en', en),
- ]
- return () => {
- for (const dispose of disposers)
- dispose()
- }
-}
+export const locale = defineLocale(PLUGIN_ID, { zh, en })
diff --git a/packages/dsh-tauri-panel-extension/src/client/locales/index.types.ts b/packages/dsh-tauri-panel-extension/src/client/locales/index.types.ts
new file mode 100644
index 00000000..9c3b173b
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/client/locales/index.types.ts
@@ -0,0 +1,4 @@
+import type { locale } from './index'
+
+export type Translate = typeof locale.text
+export type LocaleKey = Parameters<Translate>[0]
diff --git a/packages/dsh-tauri-panel-extension/src/client/register/extension-panel.tsx b/packages/dsh-tauri-panel-extension/src/client/register/extension-panel.tsx
index dbd9fe0f..5abf02dc 100644
--- a/packages/dsh-tauri-panel-extension/src/client/register/extension-panel.tsx
+++ b/packages/dsh-tauri-panel-extension/src/client/register/extension-panel.tsx
@@ -1,82 +1,41 @@
-/**
- * register/extension-panel.tsx — 扩展面板的 slot 注册 feature。
- *
- * 走 **官方全局面板协议**(0.1.5-rc.1 起):`panel.protocol.registerPanel` 由宿主
- * 代注册 `sidebar.panellist`(入口行)+ `main`(内容),选中态由官方
- * `ctx.layout.selectPanel` 统一派发。旧核心宿主内部回退到私有槽 + 会话区替换。
- * 完整契约见 dsh-tauri-panel/PROTOCOL.md。
- *
- * 注册逻辑与组件分离:这里只负责「等宿主协议就绪 → 一次性注册」,含重试等待。
- * 跨核心版本的会话 / 工作区服务布局差异由 `adapter`(`defineRegister` 第三个参数)
- * 承担,本文件不再自行 `compat(ctx)`。UI 在 components/extension-panel.tsx。
- */
-
-import type { ReactElement } from 'react'
-import type { ExtensionClientContext, PanelProtocol, Translate } from '../types'
-import { Icon, Puzzle } from 'dsh-tauri-ui/client'
-import { defineRegister } from 'dsh-tauri/client'
+import type { ClientContext, PanelHandle } from 'dsh-tauri/client'
+import { Icon, PanelWidthSync, Puzzle } from 'dsh-tauri-ui/client'
+import { definePanel, defineRegister } from 'dsh-tauri/client'
import { ExtensionPanel } from '../components/extension-panel'
-import {
- LOCALE_NAMESPACE,
- PANEL_ACTION_ORDER,
- PANEL_ID,
- PANEL_PROTOCOL_NAME,
- PANEL_SLOT_NAME,
- PROTOCOL_RETRY_MS,
-} from '../constants'
+import { PANEL_ACTION_ORDER, PANEL_ID } from '../constants'
+import { locale } from '../locales'
import { store } from '../store'
-import { chooseWorkspace, sessionSnapshotOf, workspaceSnapshotOf } from '../utils/workspace'
+import { chooseWorkspace, sessionSnapshotOf, workspaceSnapshotOf } from './extension-panel.utils'
-export const extensionPanelFeature = defineRegister<ExtensionClientContext>((controller, ctx, adapter) => {
- const t = ctx.locale.bind(LOCALE_NAMESPACE) as Translate
- controller.add(ctx.slots.inject(PANEL_SLOT_NAME as never, () => {
- let registration: (() => void) | undefined
- let cancelRetry: (() => void) | undefined
+export const extensionPanelFeature = defineRegister<ClientContext>((controller, ctx, adapter) => {
+ let panel: PanelHandle | undefined
- const attemptRegistration = (): void => {
- if (registration)
- return
- const protocol = ctx.reflect.get(PANEL_PROTOCOL_NAME) as PanelProtocol | undefined
- if (typeof protocol?.registerPanel !== 'function')
- return
- const createSkill = async (): Promise<void> => {
- const id = chooseWorkspace(
- sessionSnapshotOf(adapter.sessions.list?.getSnapshot()),
- workspaceSnapshotOf(adapter.workspaces.list?.getSnapshot()),
- )
- if (id === undefined)
- throw new Error(t('workspaceUnavailable'))
- const sessionId = await adapter.workspaces.connectWorkspace?.(id)
- if (typeof sessionId !== 'string' || sessionId === '')
- throw new Error(t('workspaceUnavailable'))
- store.prefill.add(sessionId)
- protocol.closePanelContent?.()
- adapter.sessions.open?.(sessionId)
- }
- const Content = (): ReactElement => (
- <ExtensionPanel
- t={t}
- createSkill={createSkill}
- />
- )
- registration = protocol.registerPanel({
- id: PANEL_ID,
- order: PANEL_ACTION_ORDER,
- locale: LOCALE_NAMESPACE,
- label: () => t('extension'),
- icon: <Icon as={Puzzle} />,
- render: Content,
- })
- cancelRetry?.()
- cancelRetry = undefined
- }
+ const createSkill = async (): Promise<void> => {
+ const id = chooseWorkspace(
+ sessionSnapshotOf(adapter.sessions.list?.getSnapshot()),
+ workspaceSnapshotOf(adapter.workspaces.list?.getSnapshot()),
+ )
+ if (id === undefined)
+ throw new Error(locale.text('workspaceUnavailable'))
+ const sessionId = await adapter.workspaces.connectWorkspace?.(id)
+ if (typeof sessionId !== 'string' || sessionId === '')
+ throw new Error(locale.text('workspaceUnavailable'))
+ store.prefill.add(sessionId)
+ panel?.close()
+ adapter.sessions.open?.(sessionId)
+ }
- attemptRegistration()
- if (!registration)
- cancelRetry = controller.interval(attemptRegistration, PROTOCOL_RETRY_MS)
- return () => {
- cancelRetry?.()
- registration?.()
- }
- }))
+ panel = definePanel(ctx, {
+ id: PANEL_ID,
+ order: PANEL_ACTION_ORDER,
+ locale: locale.NS,
+ label: () => locale.text('extension'),
+ icon: props => <Icon as={Puzzle} size={props.size} />,
+ render: () => (
+ <PanelWidthSync>
+ <ExtensionPanel createSkill={createSkill} />
+ </PanelWidthSync>
+ ),
+ })
+ controller.add(panel.dispose)
})
diff --git a/packages/dsh-tauri-panel-extension/src/client/register/extension-panel.types.ts b/packages/dsh-tauri-panel-extension/src/client/register/extension-panel.types.ts
new file mode 100644
index 00000000..80d3c04f
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/client/register/extension-panel.types.ts
@@ -0,0 +1,16 @@
+export interface SessionListSnapshot {
+ current?: string
+ ids: string[]
+}
+
+export interface WorkspaceListItem {
+ workspaceId?: string
+ id?: string
+ sessionIds?: readonly string[]
+ updatedAt?: number | string
+}
+
+export interface WorkspaceListSnapshot {
+ items?: WorkspaceListItem[]
+ recentWorkspaceId?: string
+}
diff --git a/packages/dsh-tauri-panel-extension/src/client/utils/workspace.ts b/packages/dsh-tauri-panel-extension/src/client/register/extension-panel.utils.ts
similarity index 76%
rename from packages/dsh-tauri-panel-extension/src/client/utils/workspace.ts
rename to packages/dsh-tauri-panel-extension/src/client/register/extension-panel.utils.ts
index c0c6a59c..2c4ae8b4 100644
--- a/packages/dsh-tauri-panel-extension/src/client/utils/workspace.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/register/extension-panel.utils.ts
@@ -1,17 +1,9 @@
-/**
- * utils/workspace.ts — 工作区选择与运行时快照归一化。
- *
- * 适配层的 `sessions.list` / `workspaces.list` 投影读出来是 `unknown`(官方服务
- * 布局逐版本漂移),这里统一归一化成组件可用的稳定快照形状。
- */
-
-import type { SessionListSnapshot, WorkspaceListItem, WorkspaceListSnapshot } from '../types'
+import type { SessionListSnapshot, WorkspaceListItem, WorkspaceListSnapshot } from './extension-panel.types'
function workspaceId(item: WorkspaceListItem): string | undefined {
return item.workspaceId ?? item.id
}
-/** 归一化会话列表投影:只有字符串 current 与字符串 id 数组算有效。 */
export function sessionSnapshotOf(value: unknown): SessionListSnapshot {
if (typeof value !== 'object' || value === null)
return { ids: [] }
@@ -22,7 +14,6 @@ export function sessionSnapshotOf(value: unknown): SessionListSnapshot {
}
}
-/** 归一化工作区列表投影:条目按 id/sessionIds 逐字段取值。 */
export function workspaceSnapshotOf(value: unknown): WorkspaceListSnapshot {
if (typeof value !== 'object' || value === null)
return {}
@@ -36,7 +27,6 @@ export function workspaceSnapshotOf(value: unknown): WorkspaceListSnapshot {
}
}
-/** Follow DSH's New Session target order: current session, recent workspace, first workspace. */
export function chooseWorkspace(
sessions: SessionListSnapshot,
workspaces: WorkspaceListSnapshot,
diff --git a/packages/dsh-tauri-panel-extension/src/client/register/skill-creator-prefill.ts b/packages/dsh-tauri-panel-extension/src/client/register/skill-creator-prefill.ts
index 71fdf783..b31d454a 100644
--- a/packages/dsh-tauri-panel-extension/src/client/register/skill-creator-prefill.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/register/skill-creator-prefill.ts
@@ -1,11 +1,3 @@
-/**
- * register/skill-creator-prefill.ts — 技能创建器草稿预填的 slot 注册 feature。
- *
- * 注册进 conversation.input.left 槽;`defineRegister` 的 controller 统一释放 inject
- * 句柄,并在装配与卸载时清理待预填登记集合。
- */
-
-import type { ExtensionClientContext } from '../types'
import { defineRegister } from 'dsh-tauri/client'
import { SkillCreatorPrefill } from '../components/skill-creator-prefill'
import {
@@ -17,7 +9,7 @@ import {
} from '../constants'
import { store } from '../store'
-export const skillCreatorPrefillFeature = defineRegister<ExtensionClientContext>((controller, ctx) => {
+export const skillCreatorPrefillFeature = defineRegister((controller, ctx) => {
store.prefill.clear()
controller.add(ctx.slots.inject(CONVERSATION_INPUT_LEFT_SLOT as never, () => ctx.slots.register({
name: CONVERSATION_INPUT_LEFT_SLOT,
diff --git a/packages/dsh-tauri-panel-extension/src/client/register/styles.ts b/packages/dsh-tauri-panel-extension/src/client/register/styles.ts
new file mode 100644
index 00000000..b72ffd62
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/client/register/styles.ts
@@ -0,0 +1,8 @@
+import { mountStyle } from 'dsh-tauri-ui/client'
+import { defineRegister } from 'dsh-tauri/client'
+import { STYLE_ID } from '../constants'
+import extensionIndexStyle from '../styles/index.cssr'
+
+export const stylesFeature = defineRegister((controller) => {
+ controller.add(mountStyle(extensionIndexStyle, STYLE_ID))
+})
diff --git a/packages/dsh-tauri-panel-extension/src/client/service/handle-post-mcp-restart.ts b/packages/dsh-tauri-panel-extension/src/client/service/handle-post-mcp-restart.ts
deleted file mode 100644
index e5a9ebb3..00000000
--- a/packages/dsh-tauri-panel-extension/src/client/service/handle-post-mcp-restart.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- * service/handle-post-mcp-restart.ts — 需要宿主配合的 API 处理:MCP 重启。
- *
- * 桌面端优先经宿主 `window.dshDesktop.restartSidecar` 重启 sidecar;Web 环境
- * 回退 HTTP 重启(连接会断开,宿主完成重启后恢复)。
- */
-import { postRestart } from '../apis'
-
-/** 触发 MCP 服务重启(桌面优先,HTTP 兜底)。 */
-export async function handlePostMcpRestart(): Promise<void> {
- if (window.dshDesktop !== undefined) {
- window.dshDesktop.restartSidecar?.()
- return
- }
- try {
- await postRestart()
- }
- catch { /* The connection normally closes while the host restarts. */ }
-}
-
-/** 是否为桌面宿主(决定重启提示文案)。 */
-export function isMcpDesktop(): boolean {
- return typeof window !== 'undefined' && window.dshDesktop !== undefined
-}
diff --git a/packages/dsh-tauri-panel-extension/src/client/service/restart.ts b/packages/dsh-tauri-panel-extension/src/client/service/restart.ts
new file mode 100644
index 00000000..246115a2
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/client/service/restart.ts
@@ -0,0 +1,15 @@
+import { postRestart } from '../apis'
+import { isDesktopHost } from './restart.utils'
+
+export async function restartHost(): Promise<{ ok: boolean, error?: string }> {
+ if (isDesktopHost()) {
+ window.dshDesktop?.restartSidecar?.()
+ return { ok: true }
+ }
+ try {
+ await postRestart()
+ }
+ catch {
+ }
+ return { ok: true }
+}
diff --git a/packages/dsh-tauri-panel-extension/src/client/service/restart.types.ts b/packages/dsh-tauri-panel-extension/src/client/service/restart.types.ts
new file mode 100644
index 00000000..98f81002
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/client/service/restart.types.ts
@@ -0,0 +1,9 @@
+export interface DesktopBridge {
+ restartSidecar?: () => void
+}
+
+declare global {
+ interface Window {
+ dshDesktop?: DesktopBridge
+ }
+}
diff --git a/packages/dsh-tauri-panel-extension/src/client/service/restart.utils.ts b/packages/dsh-tauri-panel-extension/src/client/service/restart.utils.ts
new file mode 100644
index 00000000..0fa1c503
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/client/service/restart.utils.ts
@@ -0,0 +1,3 @@
+export function isDesktopHost(): boolean {
+ return typeof window !== 'undefined' && window.dshDesktop !== undefined
+}
diff --git a/packages/dsh-tauri-panel-extension/src/client/store/index.ts b/packages/dsh-tauri-panel-extension/src/client/store/index.ts
index a47e5964..2df4148f 100644
--- a/packages/dsh-tauri-panel-extension/src/client/store/index.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/store/index.ts
@@ -1,19 +1,5 @@
-/**
- * store/index.ts — 扩展面板的客户端状态总入口(valtio-define 协议)。
- *
- * 领域 store 各自一个 `store/modules/<domain>.ts`;本文件只做聚合。
- * 读写约定:外部读 `store.<domain>.<field>`,外部写 `store.<domain>.<action>(...)`;
- * 组件内订阅用 `useStore(store.<domain>)`,非 React 消费方(DOM 补丁 / 控制器 /
- * service)用 `store.<domain>.$subscribe(listener)` / `$subscribeKey` / `$patch` / `$state`。
- */
-
import { prefill } from './modules/prefill'
-export { prefill }
-
-export type { PrefillState } from '../types'
-
-/** 插件共享状态(模块级单例;插件重载时随 bundle 重建,可接受)。 */
export const store = {
prefill,
}
diff --git a/packages/dsh-tauri-panel-extension/src/client/store/modules/prefill.ts b/packages/dsh-tauri-panel-extension/src/client/store/modules/prefill.ts
index a60862ba..b7988890 100644
--- a/packages/dsh-tauri-panel-extension/src/client/store/modules/prefill.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/store/modules/prefill.ts
@@ -1,31 +1,15 @@
-/**
- * store/modules/prefill.ts — 技能创建器的待预填会话集合(插件级共享状态)。
- *
- * createSkill 打开新会话前登记会话 id;输入区左侧的 prefill 组件挂载时消费
- * (命中即移除,保证一次性)。状态源集中在这里,读写一律经 actions。
- */
+import type { PrefillState } from './prefill.types'
+import { defineStore, remove, uniq } from 'dsh-tauri/client'
-import type { PrefillState } from '../../types'
-import { defineStore } from 'dsh-tauri/client'
-
-/** 全局唯一共享状态源(模块级单例)。 */
export const prefill = defineStore({
state: (): PrefillState => ({ pendingSessionIds: [] }),
actions: {
- /** 登记一个等待预填草稿的会话(createSkill 打开新会话前调用)。 */
add(sessionId: string) {
- if (!this.pendingSessionIds.includes(sessionId))
- this.pendingSessionIds.push(sessionId)
+ this.pendingSessionIds = uniq([...this.pendingSessionIds, sessionId])
},
- /** 消费该会话的预填资格;命中即移除,返回本次是否命中。 */
consume(sessionId: string): boolean {
- const at = this.pendingSessionIds.indexOf(sessionId)
- if (at === -1)
- return false
- this.pendingSessionIds.splice(at, 1)
- return true
+ return remove(this.pendingSessionIds, id => id === sessionId).length > 0
},
- /** 清空登记集合(feature 装配与卸载时调用)。 */
clear() {
this.pendingSessionIds = []
},
diff --git a/packages/dsh-tauri-panel-extension/src/client/store/modules/prefill.types.ts b/packages/dsh-tauri-panel-extension/src/client/store/modules/prefill.types.ts
new file mode 100644
index 00000000..ca07b794
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/client/store/modules/prefill.types.ts
@@ -0,0 +1,3 @@
+export interface PrefillState {
+ pendingSessionIds: string[]
+}
diff --git a/packages/dsh-tauri-panel-extension/src/client/styles/index.cssr.ts b/packages/dsh-tauri-panel-extension/src/client/styles/index.cssr.ts
index 5b8fbacc..d0a18bdf 100644
--- a/packages/dsh-tauri-panel-extension/src/client/styles/index.cssr.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/styles/index.cssr.ts
@@ -3,7 +3,6 @@ import { cssr, styles as sharedStyles } from 'dsh-tauri-ui/client'
const { c, bem: { b, e, m } } = cssr
const { primary, secondary, tertiary, borderL2: border, business, layer1, layer3, hover } = sharedStyles
-/** 跨组件通用:卡片列表 / 标签 / 空态文案 / 代码块(技能与 MCP 页共享)。 */
export default b('extension', [
e('intro', { margin: '0', fontSize: '13px', lineHeight: '20px', color: tertiary }),
e('empty', { margin: '0', fontSize: '13px', lineHeight: '20px', color: tertiary }),
@@ -26,7 +25,6 @@ export default b('extension', [
boxShadow: `0 0 0 2px color-mix(in srgb,${business} 18%,transparent)`,
}),
]),
- // 表单字段:技能编辑器 / MCP 编辑器 / 导入弹窗共享,挂载于 apply 全局生效。
e('form', { display: 'flex', flexDirection: 'column', gap: '10px' }),
e('label', {
display: 'flex',
@@ -114,11 +112,8 @@ export default b('extension', [
fontSize: '12px',
lineHeight: '18px',
}),
- // Modal 根元素自身同时携带 .dshp-extension 与 __modal-wide/__modal-form:
- // 必须用 & 复合选择器命中同一元素(后代选择器永远不中)。
c('&.dshp-extension__modal-wide.dshp-extension__modal-wide', { width: 'min(680px,100%)' }),
c('&.dshp-extension__modal-form.dshp-extension__modal-form', { width: 'min(760px,100%)' }),
- // contentClassName 落在 Modal 内容层(dialog 根的后代),保持后代选择器。
c('.dshp-extension__modal-scroll.dshp-extension__modal-scroll', { maxHeight: 'calc(100vh - 160px)', overflowY: 'auto' }),
e('cards', {
display: 'grid',
diff --git a/packages/dsh-tauri-panel-extension/src/client/types/index.ts b/packages/dsh-tauri-panel-extension/src/client/types/index.ts
deleted file mode 100644
index 4db692e5..00000000
--- a/packages/dsh-tauri-panel-extension/src/client/types/index.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * types/index.ts — 客户端共享类型聚合 barrel。
- *
- * 按领域分文件(protocol / skills / mcp / runtime / store),本文件只 re-export,
- * 保持「client/types/ 是共享类型唯一集中位置」的约定,同时避免单个
- * types 文件塞多领域。
- */
-
-export * from './mcp'
-export * from './protocol'
-export * from './runtime'
-export * from './skills'
-export * from './store'
diff --git a/packages/dsh-tauri-panel-extension/src/client/types/mcp.ts b/packages/dsh-tauri-panel-extension/src/client/types/mcp.ts
deleted file mode 100644
index edd97ae1..00000000
--- a/packages/dsh-tauri-panel-extension/src/client/types/mcp.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-/** types/mcp.ts — MCP 服务器管理领域类型(McpTab 相关)。 */
-
-import type { Translate } from './protocol'
-
-export interface McpRow {
- id: string
- /** Configuration layer; global rows are inherited and read-only by default. */
- layer?: 'global' | 'profile'
- shadowed?: boolean
- globalError?: string
- 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 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 type McpEditorMode = 'json' | 'form'
-
-export interface McpEditorState {
- id: string
- serverName: string
- transport: 'stdio' | 'streamable-http'
- command: string
- args: string
- env: string
- url: string
- headers: string
-}
-
-export interface McpImportItem {
- server: ImportedServerView
- existing: boolean
- checked: boolean
-}
-
-export interface ParsedMcpJson {
- serverName?: string
- transport: 'stdio' | 'streamable-http'
- command?: string
- args?: string[]
- env?: Record<string, string>
- url?: string
- headers?: Record<string, string>
-}
-
-export interface McpTabProps {
- t: Translate
-}
diff --git a/packages/dsh-tauri-panel-extension/src/client/types/protocol.ts b/packages/dsh-tauri-panel-extension/src/client/types/protocol.ts
deleted file mode 100644
index bde9e434..00000000
--- a/packages/dsh-tauri-panel-extension/src/client/types/protocol.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-/** types/protocol.ts — 扩展面板协议类型(panel.protocol 服务面 + 注入面)。 */
-
-import type { ClientContext } from 'dsh-tauri/client'
-import type { ComponentType, ReactElement, ReactNode } from 'react'
-
-export interface IconProps {
- size?: number
- className?: string
-}
-
-export interface Translate {
- (key: string): string
-}
-
-export interface ExtensionLocaleService {
- register: (namespace: string, locale: string, dictionary: Record<string, string>) => () => void
- bind: (namespace: string) => Translate
-}
-
-export type ExtensionClientContext = ClientContext & { locale: ExtensionLocaleService }
-
-export interface PanelContentSpec {
- id: string
- render: ComponentType<{ t?: Translate }>
- locale?: string
-}
-
-export interface PanelActionItemProps {
- id: string
- icon?: ReactElement
- onClick?: () => void
- children?: ReactNode
-}
-
-/**
- * panel.protocol 的一次性面板注册入参(宿主按核心版本代注册官方全局面板)。
- * 完整契约见 dsh-tauri-panel/PROTOCOL.md。
- */
-export interface PanelRegistration {
- /** 面板唯一标识;同时用作 `main` 的 key。 */
- id: string
- /** 展示文案;thunk 读时求值,跟随语言切换而无需重新注册。 */
- label: string | (() => string)
- /** 面板本体。 */
- render: ComponentType<{ t?: Translate }>
- /** 面板本体文案命名空间。 */
- locale?: string
- /** 条目图标。 */
- icon?: ReactElement
- /** 清单排序位,升序。 */
- order?: number
-}
-
-export interface PanelProtocol {
- ActionItem: (props: PanelActionItemProps) => ReactElement
- renderPanelContent: (spec: PanelContentSpec) => void
- closePanelContent: () => void
- /**
- * 注册一个全局面板(图标 + 内容),返回注销句柄。
- * (可选:老版本宿主无此字段,消费方探测后再用。)
- */
- registerPanel?: (entry: PanelRegistration) => () => void
- /** ≥0.1.5-rc.1:报告右侧栏占不占 track / 是否全屏。(可选。) */
- openRightPanel?: (track: boolean, fullscreen: boolean) => void
- /** ≥0.1.5-rc.1:报告右侧栏隐藏。(可选。) */
- closeRightPanel?: () => void
-}
diff --git a/packages/dsh-tauri-panel-extension/src/client/types/runtime.ts b/packages/dsh-tauri-panel-extension/src/client/types/runtime.ts
deleted file mode 100644
index 34e502d2..00000000
--- a/packages/dsh-tauri-panel-extension/src/client/types/runtime.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-/** types/runtime.ts — 宿主运行时快照与桌面桥类型。 */
-
-export interface InputActions {
- setDraft: (text: string) => void
-}
-
-export interface ConversationInputLeftProps {
- sessionId: string
- inputActions: InputActions
-}
-
-export interface SessionListSnapshot {
- current?: string
- ids: string[]
-}
-
-export interface WorkspaceListItem {
- workspaceId?: string
- id?: string
- sessionIds?: readonly string[]
- updatedAt?: number | string
-}
-
-export interface WorkspaceListSnapshot {
- items?: WorkspaceListItem[]
- recentWorkspaceId?: string
-}
-
-export interface DesktopBridge {
- restartSidecar?: () => void
-}
-
-declare global {
- interface Window {
- dshDesktop?: DesktopBridge
- }
-}
diff --git a/packages/dsh-tauri-panel-extension/src/client/types/skills.ts b/packages/dsh-tauri-panel-extension/src/client/types/skills.ts
deleted file mode 100644
index 172dd71d..00000000
--- a/packages/dsh-tauri-panel-extension/src/client/types/skills.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-/** types/skills.ts — 技能管理领域类型(SkillsTab 相关)。 */
-
-import type { Translate } from './protocol'
-
-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
- editable: boolean
- removable: boolean
- dir?: string
- policyEditable: boolean
- repository?: SkillRepositoryView
-}
-
-export interface SkillEditorState {
- mode: 'edit' | 'view'
- name: string
- description: string
- whenToUse: string
- modelInvocable: boolean
- userInvocable: boolean
- content: string
-}
-
-export type OpenTarget = { target: 'user-skills' } | { target: 'skill', name: string }
-
-export interface SkillsTabProps {
- t: Translate
- createSkill: () => Promise<void>
-}
diff --git a/packages/dsh-tauri-panel-extension/src/client/types/store.ts b/packages/dsh-tauri-panel-extension/src/client/types/store.ts
deleted file mode 100644
index 03610a35..00000000
--- a/packages/dsh-tauri-panel-extension/src/client/types/store.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-/** types/store.ts — valtio-define store 的状态形状(store/modules/* 的 state 类型)。 */
-
-/** 技能创建器草稿预填:等待消费的会话 id 集合。 */
-export interface PrefillState {
- pendingSessionIds: string[]
-}
diff --git a/packages/dsh-tauri-panel-extension/src/host/apply.ts b/packages/dsh-tauri-panel-extension/src/host/apply.ts
index 59f21331..93d021ed 100644
--- a/packages/dsh-tauri-panel-extension/src/host/apply.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/apply.ts
@@ -1,153 +1,43 @@
-/**
- * dsh-tauri-panel-extension host entry: mount the manager's HTTP routes once
- * the profile composes both the web server and the skill registry, and mount
- * a host-plane filesystem skill provider so the Settings page sees a live
- * catalog (the web composition deliberately leaves the host row to presets).
- * The provider's custom roots also take the user-registered skill
- * repositories from the plugin state file, and remount whenever those
- * change — the catalog follows without a dsh restart.
- *
- * provider 重挂载是状态机轴:before/after/error 钩子经 host/hooks.ts 的
- * providerHooks(hookable)暴露,供诊断与第三方联动。
- */
-
import type { HostContext } from 'dsh-tauri'
-import type { ExtensionRouteDeps } from './types'
-import { existsSync } from 'node:fs'
+import type { Config } from './apply.types'
+import type { PanelExtensionHost } from './config/runtime.types'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'pathe'
import { PLUGIN_NAME } from '../shared/constants'
-import { providerHooks } from './hooks'
+import { DEFAULT_PROFILE } from './config/constants'
+import { clearHostRuntime, resetProviderRuntime, setCurrentHostInstance } from './config/runtime'
import { routes } from './routes'
-import { agentSkillRoots } from './service/agents'
-import { argvProfile, profileDir } from './service/profile'
-import { getSkillRoots } from './service/skill-root'
+import { profile } from './service/profile'
+import { provider } from './service/provider'
-export const name = PLUGIN_NAME
+export type { Config } from './apply.types'
-/**
- * The package's own vendored skills (`skills/` at the package root — resolves
- * identically from src/ under vitest and from lib/ when installed). Scanned as
- * a custom root, so every session sees them through the registry's global
- * layer while the files stay zero-copy and travel with plugin installs.
- */
-export function packagedSkillsDir(): string {
- return join(dirname(fileURLToPath(import.meta.url)), '..', 'skills')
-}
-
-/** Optional cordis.yml configuration; profile defaults to the booted one. */
-export interface Config {
- /** Profile whose patch layer holds the MCP rows; defaults to argv or `web`. */
- profile?: string
-}
+export const name = PLUGIN_NAME
export const inject = ['webServer', 'skills', 'connection']
-/** The provider plugin's structural shape (name/apply export). */
-interface FilesystemSkillPlugin {
- name: string
- apply: (context: unknown, config?: unknown) => void
-}
-
-/** Platform loader subset used to resolve DSH-owned packages from its base URL. */
-interface PlatformPluginLoader {
- import: (name: string) => Promise<unknown>
- unwrapExports: (exports: unknown) => unknown
-}
+export { loadFilesystemSkillPlugin } from './service/provider.utils'
-export async function loadFilesystemSkillPlugin(loader: PlatformPluginLoader): Promise<FilesystemSkillPlugin> {
- return loader.unwrapExports(
- await loader.import('@deepseek-ai/dsh-skill-filesystem'),
- ) as FilesystemSkillPlugin
-}
-
-/** The disposable fiber `ctx.plugin()` returns, as far as we use it. */
-interface PluginFiber {
- dispose: () => Promise<void>
+export function packagedSkillsDir(): string {
+ return join(dirname(fileURLToPath(import.meta.url)), '..', 'skills')
}
export function apply(ctx: HostContext, config?: Config): void {
- const profile = config?.profile ?? argvProfile() ?? 'web'
- ctx.inject(['webServer', 'skills', 'connection'], (hostCtx) => {
- // The web bundle disables the host-plane `skill-filesystem` row on
- // purpose (presets own per-session discovery). The Settings manager
- // mounts its own host-plane provider as a CHILD of this plugin: it dies
- // with us, registers into the registry's global layer (deployment-level
- // providers are exactly what that layer is for — agents read the merged
- // catalog), and preset layers keep their semantics (nearest layer still
- // wins duplicate names). Custom roots, in scan order: the package's own
- // vendored skills (read-only, update with the plugin), the user's
- // registered repositories (local paths and GitHub checkouts, managed
- // from the Settings page), then other agents' skill roots
- // (~/.claude/skills, ~/.codex/skills) — zero-copy, live-synced both
- // ways. Registering or removing a repository remounts the provider with
- // the new root set; a failed load only means an empty catalog — the
- // routes keep serving.
- let providerFiber: PluginFiber | undefined
- let disposed = false
- ctx.effect(() => {
- const disposer = (): void => {
- disposed = true
- }
- let chain: Promise<void> = Promise.resolve()
- const remountProvider = (): Promise<void> => {
- // Serialize remounts; concurrent add/remove requests must not
- // interleave dispose and re-plugin on the same provider.
- chain = chain.then(async () => {
- if (disposed)
- return
- void providerHooks.callHook('provider:before-remount')
- // Internal Desktop plugins are linked from a resource directory with
- // no node_modules. Resolve DSH-owned packages through the platform
- // loader (the same path used by preset rows), not native ESM relative
- // to this linked plugin's real path.
- const loader = (hostCtx as unknown as { loader: PlatformPluginLoader }).loader
- const plugin = await loadFilesystemSkillPlugin(loader)
- if (providerFiber !== undefined) {
- const old = providerFiber
- providerFiber = undefined
- try {
- await old.dispose()
- }
- catch {
- /* unloading raced us */
- }
- }
- if (disposed)
- return
- const roots = [
- packagedSkillsDir(),
- ...(await getSkillRoots()).flatMap(entry => entry.roots),
- ...agentSkillRoots(),
- ].filter(dir => existsSync(dir))
- try {
- providerFiber = hostCtx.plugin(plugin, roots.length > 0 ? { customSkillDirs: roots } : {}) as PluginFiber
- void providerHooks.callHook('provider:after-remount', roots)
- }
- catch (error) {
- // Context already disposed: nothing left to mount for.
- void providerHooks.callHook('provider:error', error)
- }
- })
- chain = chain.catch((error: unknown) => {
- // A missing runtime provider dependency previously degraded into a
- // healthy empty catalog in packaged Desktop builds. Keep routes
- // available, but surface the actual initialization failure.
- void providerHooks.callHook('provider:error', error)
- hostCtx.logger.error(
- `dsh-tauri-panel-extension: failed to mount filesystem skill provider: ${error instanceof Error ? error.message : String(error)}`,
- )
- })
- return chain
- }
- void remountProvider()
-
- const deps: ExtensionRouteDeps = {
- profileDirPath: profileDir(profile),
- remountProvider,
- }
- ctx.effect(() => routes(hostCtx as unknown as HostContext, deps), 'dsh-tauri-panel-extension: routes')
- return disposer
- }, 'dsh-tauri-panel-extension: skill provider')
+ ctx.inject(inject, (hostCtx) => {
+ setCurrentHostInstance(hostCtx as unknown as PanelExtensionHost)
+ resetProviderRuntime()
+ const remountProvider = (): Promise<void> => provider.start(packagedSkillsDir())
+ const profileDirPath = profile.peek(config?.profile ?? profile.resolve() ?? DEFAULT_PROFILE)
+ ctx.effect(() => startProvider(remountProvider), 'dsh-tauri-panel-extension: skill provider')
+ ctx.effect(
+ () => routes(hostCtx as unknown as HostContext, { profileDirPath, remountProvider }),
+ 'dsh-tauri-panel-extension: routes',
+ )
+ return clearHostRuntime
})
}
+
+function startProvider(remountProvider: () => Promise<void>): () => void {
+ void remountProvider()
+ return clearHostRuntime
+}
diff --git a/packages/dsh-tauri-panel-extension/src/host/apply.types.ts b/packages/dsh-tauri-panel-extension/src/host/apply.types.ts
new file mode 100644
index 00000000..ef5a04e5
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/apply.types.ts
@@ -0,0 +1,3 @@
+export interface Config {
+ profile?: string
+}
diff --git a/packages/dsh-tauri-panel-extension/src/host/config/constants.ts b/packages/dsh-tauri-panel-extension/src/host/config/constants.ts
new file mode 100644
index 00000000..20b64d67
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/config/constants.ts
@@ -0,0 +1,43 @@
+export const PLUGIN_STATE_DIRECTORY = 'dsh-tauri-panel-extension'
+
+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 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 const
diff --git a/packages/dsh-tauri-panel-extension/src/host/config/runtime.ts b/packages/dsh-tauri-panel-extension/src/host/config/runtime.ts
new file mode 100644
index 00000000..c776a251
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/config/runtime.ts
@@ -0,0 +1,24 @@
+import type { ProviderRuntime } from '../service/provider.types'
+import type { PanelExtensionHost } from './runtime.types'
+import { defineHostRuntime } from 'dsh-tauri'
+
+export const { setCurrentHostInstance, getCurrentHostInstance } = defineHostRuntime<PanelExtensionHost>()
+
+export const providerRuntime: ProviderRuntime = {
+ fiber: undefined,
+ chain: Promise.resolve(),
+ disposed: false,
+}
+
+export function resetProviderRuntime(): void {
+ providerRuntime.fiber = undefined
+ providerRuntime.chain = Promise.resolve()
+ providerRuntime.disposed = false
+}
+
+export function clearHostRuntime(): void {
+ providerRuntime.fiber = undefined
+ providerRuntime.chain = Promise.resolve()
+ providerRuntime.disposed = true
+ setCurrentHostInstance(undefined)
+}
diff --git a/packages/dsh-tauri-panel-extension/src/host/config/runtime.types.ts b/packages/dsh-tauri-panel-extension/src/host/config/runtime.types.ts
new file mode 100644
index 00000000..919ebf0a
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/config/runtime.types.ts
@@ -0,0 +1,9 @@
+import type { FilesystemSkillPlugin, PlatformPluginLoader, PluginFiber } from '../service/provider.types'
+import type { SkillsService } from '../service/skills.types'
+
+export interface PanelExtensionHost {
+ skills: SkillsService
+ loader: PlatformPluginLoader
+ plugin: (plugin: FilesystemSkillPlugin, config?: unknown) => PluginFiber
+ logger: { error: (message: string) => void }
+}
diff --git a/packages/dsh-tauri-panel-extension/src/host/constants/index.ts b/packages/dsh-tauri-panel-extension/src/host/constants/index.ts
deleted file mode 100644
index 3f5c2923..00000000
--- a/packages/dsh-tauri-panel-extension/src/host/constants/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-/** host/constants.ts — 宿主侧私有常量(跨 half 协议常量见 shared/constants.ts)。 */
-
-/** 目录位于 DSH_HOME 之下,仅本插件使用。 */
-export const PLUGIN_STATE_DIRECTORY = 'dsh-tauri-panel-extension'
diff --git a/packages/dsh-tauri-panel-extension/src/host/events/index.ts b/packages/dsh-tauri-panel-extension/src/host/events/index.ts
new file mode 100644
index 00000000..7a0b72b7
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/events/index.ts
@@ -0,0 +1,9 @@
+import { createHooks } from 'hookable'
+
+export interface ProviderLifecycleHooks {
+ 'provider:before-remount': () => void
+ 'provider:after-remount': (roots: string[]) => void
+ 'provider:error': (error: unknown) => void
+}
+
+export const providerHooks = createHooks<ProviderLifecycleHooks>()
diff --git a/packages/dsh-tauri-panel-extension/src/host/hooks/index.ts b/packages/dsh-tauri-panel-extension/src/host/hooks/index.ts
deleted file mode 100644
index 7c83621a..00000000
--- a/packages/dsh-tauri-panel-extension/src/host/hooks/index.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * host/hooks.ts — 宿主 filesystem skill provider 的生命周期钩子(hookable)。
- *
- * remountProvider(根集变更 → 卸载旧 fiber + 挂载新 fiber)是真实的状态机轴;
- * 前后/错误钩子让诊断与联动(日志、统计、第三方行为)不侵入 apply 本体。
- */
-
-import { createHooks } from 'hookable'
-
-/** provider 重挂载对外可扩展的生命周期钩子。 */
-export interface ProviderLifecycleHooks {
- /** 根集变更、重挂载开始前(旧 fiber 尚未卸载)。 */
- 'provider:before-remount': () => void
- /** 重挂载完成后(roots 为本次挂载的扫描根集合)。 */
- 'provider:after-remount': (roots: string[]) => void
- /** 挂载失败(错误对象;路由继续可用,provider 降级为空目录)。 */
- 'provider:error': (error: unknown) => void
-}
-
-function createProviderHooks() {
- return createHooks<ProviderLifecycleHooks>()
-}
-
-/** provider 钩子注册表(插件级单例;未注册的钩子名调用是空操作)。 */
-export const providerHooks = createProviderHooks()
diff --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.ts
index 02837bcb..5984f9ec 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,17 +1,10 @@
-/**
- * routes/import/apply/post.ts — POST /import/apply:把选中的外部 MCP 行导入 profile。
- *
- * 逐条落盘并逐条回报结果(已存在 / 校验不过都不算成功),响应整体 `ok` 取各项与。
- * 方法限制 / 连接鉴权 / 回环与跨源 / 1 MiB 上限由 `defineRoutes` 统一承担。
- */
-
-import type { McpInput } from '../../../service/mcp'
-import type { ExtensionRouteDeps } from '../../../types'
+import type { McpInput } from '../../../service/mcp.types'
+import type { ExtensionRouteDeps } from '../../index.types'
import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'
-import { scanAllMcp } from '../../../service/agents'
-import { listMcpScoped, mcpScopeDir, normalizeMcpScope, upsertMcp, validateMcpInput } from '../../../service/mcp'
+import { agents } from '../../../service/agents'
+import { mcp } from '../../../service/mcp'
+import { mcpScopeDir, normalizeMcpScope, validateMcpInput } from '../../../service/mcp.utils'
-/** 导入请求体:items 为 (agent, name) 选择集。 */
interface McpImportApplyBody { items?: unknown, scope?: unknown }
export default defineEventHandler(async (event) => {
@@ -26,10 +19,10 @@ export default defineEventHandler(async (event) => {
)
const dir = mcpScopeDir(normalizeMcpScope(body?.scope), deps.profileDirPath)
const results: Array<{ name: string, ok: boolean, error?: string }> = []
- for (const server of scanAllMcp()) {
+ for (const server of agents.resolve()) {
if (!wanted.has(`${server.agent}/${server.name}`))
continue
- const existing = listMcpScoped(deps.profileDirPath).servers.some(row => row.serverName === server.name)
+ const existing = mcp.list(deps.profileDirPath).servers.some(row => row.serverName === server.name)
if (existing) {
results.push({ name: server.name, ok: false, error: 'already in profile' })
continue
@@ -47,7 +40,7 @@ export default defineEventHandler(async (event) => {
results.push({ name: server.name, ok: false, error: invalid })
continue
}
- upsertMcp(dir, input)
+ mcp.save(dir, input)
results.push({ name: server.name, ok: true })
}
return { ok: results.every(item => item.ok), results, restartNeeded: true }
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.ts
index a4c58673..d5460519 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,22 +1,14 @@
-/**
- * routes/import/scan/get.ts — GET /import/scan:扫描外部 agent 的 MCP 配置。
- *
- * 返回可导入项,以及 profile 层已存在的 serverName(浏览器据此置灰)。
- * 方法限制 / OPTIONS / 连接鉴权由 `defineRoutes` 统一承担。
- */
-
-import type { ExtensionRouteDeps } from '../../../types'
+import type { ExtensionRouteDeps } from '../../index.types'
import { defineEventHandler, dshRouteDepsOf } from 'dsh-tauri'
-import { scanAllMcp } from '../../../service/agents'
-import { listMcpScoped } from '../../../service/mcp'
+import { agents } from '../../../service/agents'
+import { mcp } from '../../../service/mcp'
export default defineEventHandler((event) => {
const deps = dshRouteDepsOf<ExtensionRouteDeps>(event)!
try {
return {
- servers: scanAllMcp(),
- // Profile serverNames, so the browser can grey out existing ones.
- existing: listMcpScoped(deps.profileDirPath).servers.map(row => row.serverName),
+ servers: agents.resolve(),
+ existing: mcp.list(deps.profileDirPath).servers.map(row => row.serverName),
}
}
catch (error) {
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.ts
index 97da52fc..9b051511 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,18 +1,7 @@
-/**
- * host/routes/index.test.ts — 能力管理器路由声明的协议回归。
- *
- * 覆盖(迁移契约):19 条路由的 (kind, path) 与声明方法、方法不符时 405 + allow 头、
- * OPTIONS 预检 204、GET /skills 的行形状、GET /mcp 的载荷形状、POST 的 400 领域错误、
- * 非 JSON 体 400、重启路由对非同源 / 带转发痕迹请求的 403。
- *
- * 走真实 node:http 服务(h3 的 toNodeHandler 依赖真实 req/res 流),并在测试内复刻
- * 宿主 webserver 的 exact 匹配契约;连接鉴权 / 回环 / 跨源边界由 dsh-tauri 的
- * `defineRoutes` 统一承担(其自身已有覆盖),这里只锁本插件的路径、方法与响应形状。
- */
-
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 { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
import { createServer } from 'node:http'
import { tmpdir } from 'node:os'
@@ -21,6 +10,7 @@ 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) => {
const actual = await importOriginal<typeof import('dsh-tauri')>()
@@ -30,7 +20,6 @@ vi.mock('dsh-tauri', async (importOriginal) => {
const routeKey = (kind: string, path: string): string => `${kind}\u0000${path}`
-/** 迁移前的路由表(路径 + 方法),防止声明漂移。 */
const EXPECTED_ROUTES: ReadonlyArray<readonly [string, string]> = [
['GET', `${P}/skills`],
['POST', `${P}/skills/refresh`],
@@ -53,7 +42,6 @@ const EXPECTED_ROUTES: ReadonlyArray<readonly [string, string]> = [
['POST', `${P}/restart`],
]
-/** 宿主 skills 服务面返回的一行(不带 resourceBase:可编辑性判定不依赖磁盘)。 */
const SKILL = {
name: 'demo-skill',
description: 'A demo skill',
@@ -68,7 +56,6 @@ interface Harness {
dir: string
}
-/** 假宿主 ctx:注册表模拟宿主 webserver(重复 (kind,path) 抛错,disposer 删行)。 */
function createHarness(): Harness {
const dir = mkdtempSync(join(tmpdir(), 'dsh-panel-extension-'))
const registered = new Map<string, HostRoute>()
@@ -88,7 +75,6 @@ function createHarness(): Harness {
},
},
logger: { error: () => {} },
- // 业务面:插件 HostContext 的扩展点,defineRoutes 只把 ctx 原样透传给 handler。
skills: {
list: async () => [SKILL],
get: async (name: string) => (name === SKILL.name
@@ -99,8 +85,8 @@ function createHarness(): Harness {
}
}
-/** 按协议注册:`routes(ctx, deps)` 返回本次注册的卸载函数(deps 随注册传入,无需全局状态)。 */
function mount(harness: Harness): () => void {
+ setCurrentHostInstance(harness.ctx as unknown as PanelExtensionHost)
return routes(harness.ctx as RoutesContext, {
profileDirPath: join(harness.dir, 'profiles', 'web'),
remountProvider: async () => {},
@@ -110,7 +96,6 @@ function mount(harness: Harness): () => void {
const servers: Server[] = []
const dirs: string[] = []
-/** 复刻宿主 webserver 的 exact 匹配契约,起一个真实 HTTP 服务并返回 base URL。 */
async function listen(registered: Map<string, HostRoute>): Promise<string> {
const server = createServer((request: IncomingMessage, response: ServerResponse) => {
const pathname = new URL(request.url ?? '/', 'http://127.0.0.1').pathname
@@ -132,7 +117,6 @@ async function listen(registered: Map<string, HostRoute>): Promise<string> {
return `http://127.0.0.1:${(server.address() as AddressInfo).port}`
}
-/** 起一个服务并挂上本次注册的路由。 */
async function start(): Promise<{ base: string, dispose: () => void }> {
const harness = createHarness()
dirs.push(harness.dir)
@@ -277,7 +261,6 @@ describe('能力管理器路由声明', () => {
})
expect(invalidJson.status).toBe(400)
- // 请求体一律按 JSON 解析:urlencoded 体不会被当成合法对象放行。
const urlencoded = await fetch(`${base}${P}/mcp/toggle`, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
@@ -306,8 +289,6 @@ describe('能力管理器路由声明', () => {
})
it('同一份声明两次注册下各读各的 deps(两次注册互不串台)', async () => {
- // 两次注册各带自己的 profileDirPath(数据根 DSH_HOME 是全局的,profile 目录不是)。
- // 迁移前的模块级单例绑定会被后一次注册覆盖,先注册的一方会读后一方的目录——本用例即该回归。
const first = createHarness()
const second = createHarness()
dirs.push(first.dir, second.dir)
diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/index.ts b/packages/dsh-tauri-panel-extension/src/host/routes/index.ts
index 8370bc42..070e3732 100644
--- a/packages/dsh-tauri-panel-extension/src/host/routes/index.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/routes/index.ts
@@ -1,46 +1,4 @@
-/**
- * host/routes/index.ts — 能力管理器 HTTP 路由(`/dsh-tauri-panel-extension/*`)。
- *
- * 声明协议(见 docs/plugins/dsh-tauri-设计重构迁移.md 第 1 条 + 第 6.1 节):本文件只做
- * 「导入 handler + 登记 (方法, 路径)」,每个处理器的实现放在 `./<资源路径>/<method>.ts`
- * 下,文件内默认导出一个 h3 处理器(`defineEventHandler` 已在其内定义,这里不再二次包装)。
- *
- * **目录层级 = URL 层级**(用户硬性要求):`routes/` 下的相对目录路径与
- * `API_PREFIX` 之后的 URL 路径严格 1:1,URL 里几段,目录就几层。例如
- * `POST ${API_PREFIX}/mcp/save` 落在 `routes/mcp/save/post.ts`,
- * `GET ${API_PREFIX}/import/scan` 落在 `routes/import/scan/get.ts`。
- *
- * 路由表(URL 与迁移前逐字相同,仅目录层级对齐):
- * GET /skills 技能目录
- * POST /skills/refresh 重挂 provider 后重扫
- * GET /skill 单个技能内容(?name=)
- * POST /skill/save 保存技能
- * POST /skill/delete 删除用户技能
- * POST /skill/policy 切换技能加载策略
- * POST /open 打开技能目录 / 仓库目录
- * GET /mcp MCP 行列表(global + profile 合并)
- * POST /mcp/save 新增 / 覆盖一行
- * POST /mcp/toggle 启停一行
- * POST /mcp/remove 移除一行
- * POST /mcp/check 连通性检查
- * POST /mcp/copy 复制到另一 patch 层
- * GET /import/scan 扫描外部 agent 的 MCP 配置
- * POST /import/apply 导入选中项
- * GET /roots 自定义技能仓库列表
- * POST /roots/add 注册仓库(local / git)
- * POST /roots/remove 注销仓库
- * POST /restart 独立 `dsh web` 自重启
- *
- * 运行期由 `apply` 的 `ctx.effect(() => routes(ctx, deps), '<plugin>: routes')` 注册。
- * 方法限制(405 + allow)、OPTIONS 204、连接鉴权(401/403)、变更操作的回环与跨源
- * 校验、1 MiB 请求体上限全部由 `defineRoutes` 统一承担,处理器里不再重复实现。
- *
- * 处理器需要的 apply 期依赖(profile patch 目录 / 数据根 / provider 重挂载)无法从事件
- * 里的宿主 ctx 取回,因此经注册期第二参数传入、请求期由处理器用 `dshRouteDepsOf(event)`
- * 取回;deps 由本次注册的闭包捕获,同一份声明在两组 deps 下注册时各读各的,没有模块级可变状态。
- */
-
-import type { ExtensionRouteDeps } from '../types'
+import type { ExtensionRouteDeps } from './index.types'
import { defineRoutes } from 'dsh-tauri'
import { API_PREFIX } from '../../shared/constants'
import importApply from './import/apply/post'
@@ -63,12 +21,6 @@ import skillSave from './skill/save/post'
import skills from './skills/get'
import skillsRefresh from './skills/refresh/post'
-/**
- * 能力管理器路由声明:URL 与 `routes/**` 目录逐段对齐(`mcp/save/post.ts` ↔
- * POST `${API_PREFIX}/mcp/save`,其余同理)。
- *
- * @returns `registerRoutes(ctx, deps)` —— 注册全部路由并返回卸载函数(交给 `ctx.effect`)。
- */
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)
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.ts
new file mode 100644
index 00000000..a5090519
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/routes/index.types.ts
@@ -0,0 +1,4 @@
+export interface ExtensionRouteDeps {
+ profileDirPath: string
+ remountProvider: () => Promise<void>
+}
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.ts
index 3628b0c7..c0d7c90c 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,16 +1,8 @@
-/**
- * routes/mcp/check/post.ts — POST /mcp/check:一行 MCP 服务器的连通性检查。
- *
- * 不启动进程:stdio 行按 PATH 校验命令(spawn 会留下控制台窗口与副作用),
- * streamable-http 行走一次短 GET。方法限制 / 连接鉴权 / 回环与跨源 / 1 MiB 上限
- * 由 `defineRoutes` 统一承担。
- */
-
-import type { ExtensionRouteDeps } from '../../../types'
+import type { ExtensionRouteDeps } from '../../index.types'
import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'
-import { checkMcpRow, listMcp, mcpScopeDir, normalizeMcpScope } from '../../../service/mcp'
+import { mcp } from '../../../service/mcp'
+import { mcpScopeDir, normalizeMcpScope } from '../../../service/mcp.utils'
-/** 检查请求体:只有 id 参与。 */
interface McpCheckBody { id?: unknown, scope?: unknown }
export default defineEventHandler(async (event) => {
@@ -23,12 +15,12 @@ export default defineEventHandler(async (event) => {
const id = body.id
try {
const dir = mcpScopeDir(normalizeMcpScope(body.scope), deps.profileDirPath)
- const row = listMcp(dir).find(item => item.id === id)
+ const row = mcp.peek(dir).find(item => item.id === id)
if (row === undefined) {
event.res.status = 404
return { error: 'server row not found' }
}
- return await checkMcpRow(row)
+ return await mcp.check(row)
}
catch (error) {
event.res.status = 500
diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/copy/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/copy/post.ts
index 292e978c..989c114a 100644
--- a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/copy/post.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/copy/post.ts
@@ -1,15 +1,8 @@
-/**
- * routes/mcp/copy/post.ts — POST /mcp/copy:把一行复制到另一个 patch 层。
- *
- * 复制体的 id 重新分配(`upsertMcp` 会去重);响应回报实际落点 scope。
- * 方法限制 / 连接鉴权 / 回环与跨源 / 1 MiB 上限由 `defineRoutes` 统一承担。
- */
-
-import type { ExtensionRouteDeps } from '../../../types'
+import type { ExtensionRouteDeps } from '../../index.types'
import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'
-import { listMcp, mcpRowToInput, mcpScopeDir, normalizeMcpScope, upsertMcp } from '../../../service/mcp'
+import { mcp } from '../../../service/mcp'
+import { mcpRowToInput, mcpScopeDir, normalizeMcpScope } from '../../../service/mcp.utils'
-/** 复制请求体:id 必填,toScope 缺省即 profile 层。 */
interface McpCopyBody { id?: unknown, scope?: unknown, toScope?: unknown }
export default defineEventHandler(async (event) => {
@@ -22,13 +15,13 @@ export default defineEventHandler(async (event) => {
const id = body.id
try {
const sourceDir = mcpScopeDir(normalizeMcpScope(body.scope), deps.profileDirPath)
- const source = listMcp(sourceDir).find(item => item.id === id)
+ const source = mcp.peek(sourceDir).find(item => item.id === id)
if (source === undefined) {
event.res.status = 404
return { error: 'server row not found' }
}
const scope = normalizeMcpScope(body.toScope)
- const createdId = upsertMcp(
+ const createdId = mcp.save(
mcpScopeDir(scope, deps.profileDirPath),
mcpRowToInput(source),
)
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.ts
index aa4b194f..99812462 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,15 +1,8 @@
-/**
- * routes/mcp/get.ts — GET /mcp:MCP 行列表(机器级 + profile 层合并)。
- *
- * 行变更都需要 dsh 重启才能组合,故列表恒带 `restartNeeded`。方法限制 / OPTIONS /
- * 连接鉴权由 `defineRoutes` 统一承担。
- */
-
-import type { ExtensionRouteDeps } from '../../types'
+import type { ExtensionRouteDeps } from '../index.types'
import { defineEventHandler, dshRouteDepsOf } from 'dsh-tauri'
-import { listMcpScoped } from '../../service/mcp'
+import { mcp } from '../../service/mcp'
export default defineEventHandler((event) => {
const deps = dshRouteDepsOf<ExtensionRouteDeps>(event)!
- return { ...listMcpScoped(deps.profileDirPath), restartNeeded: true }
+ return { ...mcp.list(deps.profileDirPath), restartNeeded: true }
})
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/remove/post.ts
index aeefa441..d09f2130 100644
--- a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/remove/post.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/remove/post.ts
@@ -1,15 +1,8 @@
-/**
- * routes/mcp/remove/post.ts — POST /mcp/remove:移除一行 MCP 服务器。
- *
- * 行不存在返回 404;成功恒带 `restartNeeded`。方法限制 / 连接鉴权 / 回环与跨源 /
- * 1 MiB 上限由 `defineRoutes` 统一承担。
- */
-
-import type { ExtensionRouteDeps } from '../../../types'
+import type { ExtensionRouteDeps } from '../../index.types'
import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'
-import { mcpScopeDir, normalizeMcpScope, removeMcp } from '../../../service/mcp'
+import { mcp } from '../../../service/mcp'
+import { mcpScopeDir, normalizeMcpScope } from '../../../service/mcp.utils'
-/** 移除请求体:只有 id 参与。 */
interface McpRemoveBody { id?: unknown, scope?: unknown }
export default defineEventHandler(async (event) => {
@@ -21,7 +14,7 @@ export default defineEventHandler(async (event) => {
}
const id = body.id
try {
- const ok = removeMcp(mcpScopeDir(normalizeMcpScope(body.scope), deps.profileDirPath), id)
+ const ok = mcp.remove(mcpScopeDir(normalizeMcpScope(body.scope), deps.profileDirPath), id)
if (!ok) {
event.res.status = 404
return { error: 'server row not found' }
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/save/post.ts
index 7c19c440..56d64abd 100644
--- a/packages/dsh-tauri-panel-extension/src/host/routes/mcp/save/post.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/routes/mcp/save/post.ts
@@ -1,15 +1,8 @@
-/**
- * routes/mcp/save/post.ts — POST /mcp/save:新增或覆盖一行 MCP 服务器。
- *
- * 行写进 profile 或机器级 patch 层(`scope === 'global'`),恒回报
- * `restartNeeded`。方法限制 / 连接鉴权 / 回环与跨源 / 1 MiB 上限由
- * `defineRoutes` 统一承担。
- */
-
-import type { McpInput } from '../../../service/mcp'
-import type { ExtensionRouteDeps } from '../../../types'
+import type { McpInput } from '../../../service/mcp.types'
+import type { ExtensionRouteDeps } from '../../index.types'
import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'
-import { mcpScopeDir, normalizeMcpScope, upsertMcp, validateMcpInput } from '../../../service/mcp'
+import { mcp } from '../../../service/mcp'
+import { mcpScopeDir, normalizeMcpScope, validateMcpInput } from '../../../service/mcp.utils'
export default defineEventHandler(async (event) => {
const deps = dshRouteDepsOf<ExtensionRouteDeps>(event)!
@@ -25,7 +18,7 @@ export default defineEventHandler(async (event) => {
return { error: invalid }
}
const scope = normalizeMcpScope(body.scope)
- const id = upsertMcp(mcpScopeDir(scope, deps.profileDirPath), body)
+ const id = mcp.save(mcpScopeDir(scope, deps.profileDirPath), body)
return { ok: true, id, restartNeeded: true }
}
catch (error) {
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.ts
index 7421a914..80626500 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,15 +1,8 @@
-/**
- * routes/mcp/toggle/post.ts — POST /mcp/toggle:启用 / 停用一行 MCP 服务器。
- *
- * 行不存在返回 404(不是静默成功);成功恒带 `restartNeeded`。方法限制 / 连接鉴权 /
- * 回环与跨源 / 1 MiB 上限由 `defineRoutes` 统一承担。
- */
-
-import type { ExtensionRouteDeps } from '../../../types'
+import type { ExtensionRouteDeps } from '../../index.types'
import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'
-import { mcpScopeDir, normalizeMcpScope, setMcpDisabled } from '../../../service/mcp'
+import { mcpToggle } from '../../../service/mcp-toggle'
+import { mcpScopeDir, normalizeMcpScope } from '../../../service/mcp.utils'
-/** 启停请求体:id + disabled 都必须成立。 */
interface McpToggleBody { id?: unknown, disabled?: unknown, scope?: unknown }
export default defineEventHandler(async (event) => {
@@ -22,7 +15,7 @@ export default defineEventHandler(async (event) => {
const id = body.id
const disabled = body.disabled
try {
- const ok = setMcpDisabled(mcpScopeDir(normalizeMcpScope(body.scope), deps.profileDirPath), id, disabled)
+ const ok = mcpToggle.save(mcpScopeDir(normalizeMcpScope(body.scope), deps.profileDirPath), id, disabled)
if (!ok) {
event.res.status = 404
return { 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/post.ts
index 4fe85ea8..0d420fd1 100644
--- a/packages/dsh-tauri-panel-extension/src/host/routes/open/post.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/routes/open/post.ts
@@ -1,23 +1,14 @@
-/**
- * routes/open/post.ts — POST /open:在系统文件管理器里打开技能 / 仓库目录。
- *
- * 目标一律服务端解析(用户技能根、插件状态根、某技能所在目录、某注册仓库目录);
- * 浏览器从不提供原始路径,因此无法被改造成任意目录打开。方法限制 / 连接鉴权 /
- * 回环与跨源 / 1 MiB 上限由 `defineRoutes` 统一承担。
- */
-
-import type { PanelExtensionHost } from '../../types'
import { mkdirSync } from 'node:fs'
-import { defineEventHandler, dshContextOf, readBody } from 'dsh-tauri'
-import { openDirectory } from '../../service/opener'
-import { getSkillRoots, skillsRootDir } from '../../service/skill-root'
-import { userSkillsDir } from '../../service/skills'
+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'
-/** 打开请求体:target 决定用哪个字段(name / id)。 */
interface SkillOpenBody { target?: unknown, name?: unknown, id?: unknown }
export default defineEventHandler(async (event) => {
- const host = dshContextOf(event) as unknown as PanelExtensionHost
const body = await readBody<SkillOpenBody>(event, { type: 'json' })
if (typeof body?.target !== 'string') {
event.res.status = 400
@@ -25,13 +16,8 @@ export default defineEventHandler(async (event) => {
}
try {
let dir: string | undefined
- if (body.target === 'user-skills') {
- dir = userSkillsDir()
- // 用户还没建过任何技能时该目录不存在;「打开技能目录」应按需创建而非报错。
- mkdirSync(dir, { recursive: true })
- }
- else if (body.target === 'plugin-state') {
- dir = skillsRootDir()
+ if (body.target === 'user-skills' || body.target === 'plugin-state') {
+ dir = skillsDataDir()
mkdirSync(dir, { recursive: true })
}
else if (body.target === 'skill') {
@@ -39,14 +25,13 @@ export default defineEventHandler(async (event) => {
event.res.status = 400
return { error: 'name is required' }
}
- const definition = await host.skills.get(body.name)
- if (definition === undefined) {
+ const definition = await skillCatalog.peek(body.name)
+ if (definition === null) {
event.res.status = 404
return { error: 'skill not found' }
}
- // 文件型技能打开它所在目录(SKILL.md 的父目录);目录型技能直接用其根。
dir = definition.path !== undefined
- ? definition.path.replace(/[/\\]SKILL\.md$/, '').replace(/[/\\][^/\\]+\.md$/, '')
+ ? definition.path.replace(SKILL_FILE_PATTERN, '').replace(SKILL_DOCUMENT_PATTERN, '')
: definition.resourceBase?.kind === 'directory' ? definition.resourceBase.path : undefined
}
else if (body.target === 'root') {
@@ -54,7 +39,7 @@ export default defineEventHandler(async (event) => {
event.res.status = 400
return { error: 'id is required' }
}
- const entry = (await getSkillRoots()).find(row => row.id === body.id)
+ const entry = (await skillRoot.list()).find(row => row.id === body.id)
if (entry === undefined) {
event.res.status = 404
return { error: 'repository not found' }
@@ -65,7 +50,7 @@ export default defineEventHandler(async (event) => {
event.res.status = 400
return { error: 'unknown target' }
}
- if (dir === undefined || !openDirectory(dir)) {
+ if (dir === undefined || !opener.open(dir)) {
event.res.status = 422
return { error: 'directory is not available on disk' }
}
diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/restart/post.ts b/packages/dsh-tauri-panel-extension/src/host/routes/restart/post.ts
index 3af9f187..9116e0b1 100644
--- a/packages/dsh-tauri-panel-extension/src/host/routes/restart/post.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/routes/restart/post.ts
@@ -1,20 +1,10 @@
-/**
- * routes/restart/post.ts — POST /restart:独立 `dsh web` 的自重启。
- *
- * 进程控制:只有直接的同源回环请求有权触发(回环由 `defineRoutes` 统一把关,
- * 这里再拒一次带转发痕迹的请求——那说明回环对端是代理而不是用户浏览器)。
- * 桌面模式下重启归壳层所有(restartOwnedByShell 返回 409),避免被监督的
- * sidecar 自我替换。
- */
-
import { defineEventHandler } from 'dsh-tauri'
-import { dshLaunch, restartOwnedByShell, scheduleRestart } from '../../service/restart'
+import { restart } from '../../service/restart'
export default defineEventHandler((event) => {
const headers = event.req.headers
const origin = headers.get('origin')
const host = headers.get('host')
- // 同源判定:带 Origin 且与 Host 逐字相符才算用户浏览器直连。
let sameOrigin = false
if (origin !== null && host !== null) {
try {
@@ -30,10 +20,10 @@ export default defineEventHandler((event) => {
event.res.status = 403
return { error: 'untrusted origin' }
}
- if (restartOwnedByShell()) {
+ const outcome = restart.start()
+ if (outcome.owned) {
event.res.status = 409
return { error: 'restart is owned by the desktop shell' }
}
- const { pid, replacementPid, logOut } = scheduleRestart(dshLaunch())
- return { ok: true, pid, replacementPid, logOut }
+ return { ok: true, pid: outcome.pid, replacementPid: outcome.replacementPid, logOut: outcome.logOut }
})
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/add/post.ts
index 3270c60d..d3317151 100644
--- a/packages/dsh-tauri-panel-extension/src/host/routes/roots/add/post.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/routes/roots/add/post.ts
@@ -1,18 +1,8 @@
-/**
- * routes/roots/add/post.ts — POST /roots/add:注册一个自定义技能仓库。
- *
- * local 走原地扫描(单技能目录会包一层 junction 包装目录),git 走 tarball 下载。
- * 注册后必须先重挂宿主 provider(其目录 watcher 持有新根的句柄),注册失败一律
- * 400 并把领域错误原文回给浏览器。方法限制 / 连接鉴权 / 回环与跨源 / 1 MiB 上限
- * 由 `defineRoutes` 统一承担。
- */
-
-import type { ExtensionRouteDeps } from '../../../types'
+import type { ExtensionRouteDeps } from '../../index.types'
import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'
-import { addGitRepo, addLocalRepo } from '../../../service/repos'
-import { toRootView } from '../../../service/skill-catalog'
+import { repos } from '../../../service/repos'
+import { rootView } from '../../../service/skill-catalog.utils'
-/** 注册请求体:kind 决定用 path 还是 url。 */
interface RootAddBody { kind?: unknown, path?: unknown, url?: unknown }
export default defineEventHandler(async (event) => {
@@ -25,17 +15,17 @@ export default defineEventHandler(async (event) => {
try {
const entry = kind === 'local'
? typeof body.path === 'string' && body.path.trim() !== ''
- ? await addLocalRepo(body.path)
+ ? await repos.create(body.path)
: undefined
: typeof body.url === 'string' && body.url.trim() !== ''
- ? await addGitRepo(body.url)
+ ? await repos.import(body.url)
: undefined
if (entry === undefined) {
event.res.status = 400
return { error: kind === 'local' ? 'path is required' : 'url is required' }
}
await dshRouteDepsOf<ExtensionRouteDeps>(event)!.remountProvider()
- return { ok: true, root: toRootView(entry) }
+ return { ok: true, root: rootView(entry) }
}
catch (error) {
event.res.status = 400
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.ts
index a13596ff..946f643e 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,14 +1,7 @@
-/**
- * routes/roots/get.ts — GET /roots:已注册的自定义技能仓库列表。
- *
- * 每条附 `live` 标志(根目录可能已从磁盘消失)。方法限制 / OPTIONS / 连接鉴权由
- * `defineRoutes` 统一承担。
- */
-
import { defineEventHandler } from 'dsh-tauri'
-import { toRootView } from '../../service/skill-catalog'
-import { getSkillRoots } from '../../service/skill-root'
+import { rootView } from '../../service/skill-catalog.utils'
+import { skillRoot } from '../../service/skill-root'
export default defineEventHandler(async () => {
- return { roots: (await getSkillRoots()).map(toRootView) }
+ return { roots: (await skillRoot.list()).map(rootView) }
})
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/remove/post.ts
index c61951f3..5afb74eb 100644
--- a/packages/dsh-tauri-panel-extension/src/host/routes/roots/remove/post.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/routes/roots/remove/post.ts
@@ -1,19 +1,8 @@
-/**
- * routes/roots/remove/post.ts — POST /roots/remove:注销一个自定义技能仓库。
- *
- * Unwatch before unlink: the provider's directory watchers hold handles on the
- * material tree, and removing a watched tree on Windows fails with EPERM (the
- * state is already saved by then, which is why the repo still disappears
- * despite the error). 方法限制 / 连接鉴权 / 回环与跨源 / 1 MiB 上限由
- * `defineRoutes` 统一承担。
- */
-
-import type { ExtensionRouteDeps } from '../../../types'
+import type { ExtensionRouteDeps } from '../../index.types'
import { defineEventHandler, dshRouteDepsOf, readBody } from 'dsh-tauri'
-import { removeTree } from '../../../service/rmtree'
-import { deleteSkillRoot } from '../../../service/skill-root'
+import { rmtree } from '../../../service/rmtree'
+import { skillRoot } from '../../../service/skill-root'
-/** 注销请求体:只有 id 参与。 */
interface RootRemoveBody { id?: unknown }
export default defineEventHandler(async (event) => {
@@ -24,14 +13,14 @@ export default defineEventHandler(async (event) => {
}
const id = body.id
try {
- const removed = await deleteSkillRoot(id)
- if (removed === undefined) {
+ const removed = await skillRoot.remove(id)
+ if (removed === null) {
event.res.status = 404
return { error: 'repository not found' }
}
await dshRouteDepsOf<ExtensionRouteDeps>(event)!.remountProvider()
if (removed.materialDir !== undefined)
- removeTree(removed.materialDir)
+ rmtree.remove(removed.materialDir)
return { ok: true }
}
catch (error) {
diff --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/post.ts
index 790e48f6..ee914596 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/post.ts
@@ -1,21 +1,13 @@
-/**
- * routes/skill/delete/post.ts — POST /skill/delete:删除用户根下的一个技能。
- *
- * 名称语法由 `deleteSkill` 内的 SKILL_NAME_RE 把关(不合法即未命中 → 404)。
- * 方法限制 / 连接鉴权 / 回环与跨源 / 1 MiB 上限由 `defineRoutes` 统一承担。
- */
-
import { defineEventHandler, readBody } from 'dsh-tauri'
-import { deleteSkill } from '../../../service/skills'
+import { skills } from '../../../service/skills'
-/** 删除请求体:只有 name 参与。 */
interface SkillDeleteBody { name?: unknown }
export default defineEventHandler(async (event) => {
const body = await readBody<SkillDeleteBody>(event, { type: 'json' })
const name = typeof body?.name === 'string' ? body.name : ''
try {
- if (!deleteSkill(name)) {
+ if (!skills.remove(name)) {
event.res.status = 404
return { error: 'skill not found' }
}
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.ts
index c36af24d..2917bf29 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,20 +1,12 @@
-/**
- * routes/skill/get.ts — GET /skill?name=<name>:单个技能的内容。
- *
- * 查询串一律用 h3 内置的 `getQuery`;名称缺失或非法时按空名查询,命中不到即 404。
- * 方法限制 / OPTIONS / 连接鉴权由 `defineRoutes` 统一承担。
- */
-
-import type { PanelExtensionHost } from '../../types'
-import { defineEventHandler, dshContextOf, getQuery } from 'dsh-tauri'
+import { defineEventHandler, getQuery } from 'dsh-tauri'
+import { skillCatalog } from '../../service/skill-catalog'
export default defineEventHandler(async (event) => {
- const host = dshContextOf(event) as unknown as PanelExtensionHost
const query = getQuery(event) as { name?: unknown }
const name = typeof query.name === 'string' ? query.name : ''
try {
- const definition = await host.skills.get(name)
- if (definition === undefined) {
+ const definition = await skillCatalog.peek(name)
+ if (definition === null) {
event.res.status = 404
return { 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.ts
index ba1a679a..0bce7c21 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,20 +1,10 @@
-/**
- * routes/skill/policy/post.ts — POST /skill/policy:切换一个技能的加载策略。
- *
- * 只改技能文件 frontmatter 里的两个 invocation 键(见 service/skills.ts 的
- * setSkillPolicy)。运行时注册(无磁盘文件)的技能返回 422,而不是静默成功。
- * 方法限制 / 连接鉴权 / 回环与跨源 / 1 MiB 上限由 `defineRoutes` 统一承担。
- */
+import { defineEventHandler, readBody } from 'dsh-tauri'
+import { skillCatalog } from '../../../service/skill-catalog'
+import { skillPolicy } from '../../../service/skill-policy'
-import type { PanelExtensionHost } from '../../../types'
-import { defineEventHandler, dshContextOf, readBody } from 'dsh-tauri'
-import { setSkillPolicy } from '../../../service/skills'
-
-/** 策略请求体:name + enabled 都必须成立。 */
interface SkillPolicyBody { name?: unknown, enabled?: unknown }
export default defineEventHandler(async (event) => {
- const host = dshContextOf(event) as unknown as PanelExtensionHost
const body = await readBody<SkillPolicyBody>(event, { type: 'json' })
if (typeof body?.name !== 'string' || typeof body?.enabled !== 'boolean') {
event.res.status = 400
@@ -23,8 +13,8 @@ export default defineEventHandler(async (event) => {
const name = body.name
const enabled = body.enabled
try {
- const definition = await host.skills.get(name)
- if (definition === undefined) {
+ const definition = await skillCatalog.peek(name)
+ if (definition === null) {
event.res.status = 404
return { error: 'skill not found' }
}
@@ -32,7 +22,7 @@ export default defineEventHandler(async (event) => {
event.res.status = 422
return { error: 'skill has no file on disk (runtime-registered)' }
}
- setSkillPolicy(definition.path, enabled)
+ skillPolicy.save(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/save/post.ts
index 1b66723f..bef8479b 100644
--- a/packages/dsh-tauri-panel-extension/src/host/routes/skill/save/post.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/routes/skill/save/post.ts
@@ -1,20 +1,12 @@
-/**
- * routes/skill/save/post.ts — POST /skill/save:保存(新建或就地编辑)一个技能。
- *
- * 请求级逻辑(读体、归一化字段、校验、置状态码)都在处理器体内;写入原语在
- * `../../service/skills.ts`,可写性判定在 `../../service/skill-catalog.ts`。
- * 方法限制 / 连接鉴权 / 回环与跨源 / 1 MiB 上限由 `defineRoutes` 统一承担。
- */
-
-import type { SkillInput } from '../../../service/skills'
-import type { PanelExtensionHost } from '../../../types'
-import { defineEventHandler, dshContextOf, readBody } from 'dsh-tauri'
+import type { SkillInput } from '../../../service/skills.types'
+import { defineEventHandler, readBody } from 'dsh-tauri'
import { join } from 'pathe'
-import { skillWritable } from '../../../service/skill-catalog'
-import { updateSkillFile, validateSkillInput, writeSkill } from '../../../service/skills'
+import { SKILL_FILE_NAME } from '../../../config/constants'
+import { skillCatalog } from '../../../service/skill-catalog'
+import { skills } from '../../../service/skills'
+import { validateSkillInput } from '../../../service/skills.utils'
export default defineEventHandler(async (event) => {
- const host = dshContextOf(event) as unknown as PanelExtensionHost
const body = await readBody<Partial<SkillInput>>(event, { type: 'json' })
const input: SkillInput = {
name: typeof body?.name === 'string' ? body.name : '',
@@ -30,21 +22,16 @@ export default defineEventHandler(async (event) => {
event.res.status = 400
return { error: invalid }
}
- // An existing skill edits in place (its own folder, whichever editable source
- // it comes from — preserving frontmatter keys the editor does not own); a new
- // name creates in the user root. The file location is resolved server-side
- // from the catalog, never taken from the request.
- const existing = (await host.skills.list()).find(skill => skill.name === input.name)
+ const existing = (await skillCatalog.resolve()).find(skill => skill.name === input.name)
if (existing !== undefined) {
- const dir = existing.resourceBase?.kind === 'directory' ? existing.resourceBase.path : undefined
- if (dir === undefined || !await skillWritable(existing, dir)) {
+ if (existing.dir === undefined || !existing.editable) {
event.res.status = 403
return { error: `skills from source '${existing.source}' are read-only` }
}
- updateSkillFile(join(dir, 'SKILL.md'), input)
+ skills.save(input, join(existing.dir, SKILL_FILE_NAME))
}
else {
- writeSkill(input)
+ skills.save(input)
}
return { ok: true, name: input.name }
}
diff --git a/packages/dsh-tauri-panel-extension/src/host/routes/skills/get.ts b/packages/dsh-tauri-panel-extension/src/host/routes/skills/get.ts
index d63a3f02..eb76b9b5 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,19 +1,9 @@
-/**
- * routes/skills/get.ts — GET /skills:技能目录(设置页卡片的数据面)。
- *
- * 请求级逻辑(置状态码、组织响应)在处理器体内;目录投影在
- * `../../service/skill-catalog.ts`。方法限制 / OPTIONS / 连接鉴权 / 回环与跨源
- * 由 `defineRoutes` 统一承担。
- */
-
-import type { PanelExtensionHost } from '../../types'
-import { defineEventHandler, dshContextOf } from 'dsh-tauri'
-import { listSkillRows } from '../../service/skill-catalog'
+import { defineEventHandler } from 'dsh-tauri'
+import { skillCatalog } from '../../service/skill-catalog'
export default defineEventHandler(async (event) => {
- const host = dshContextOf(event) as unknown as PanelExtensionHost
try {
- return { skills: await listSkillRows(host) }
+ return { skills: await skillCatalog.resolve() }
}
catch (error) {
event.res.status = 500
diff --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.ts
index 01d58e75..d3c8f151 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,20 +1,11 @@
-/**
- * routes/skills/refresh/post.ts — POST /skills/refresh:显式重扫技能目录。
- *
- * 重挂宿主 provider 会重跑全部根的发现(打包技能、注册仓库、`~/.claude|.codex`,
- * 以及 provider 自带的默认根),并使注册表的 collect 缓存失效,因此随后的列表能
- * 反映新增技能而无需重启。方法限制 / 连接鉴权 / 回环与跨源由 `defineRoutes` 承担。
- */
-
-import type { ExtensionRouteDeps, PanelExtensionHost } from '../../../types'
-import { defineEventHandler, dshContextOf, dshRouteDepsOf } from 'dsh-tauri'
-import { listSkillRows } from '../../../service/skill-catalog'
+import type { ExtensionRouteDeps } from '../../index.types'
+import { defineEventHandler, dshRouteDepsOf } from 'dsh-tauri'
+import { skillCatalog } from '../../../service/skill-catalog'
export default defineEventHandler(async (event) => {
- const host = dshContextOf(event) as unknown as PanelExtensionHost
try {
await dshRouteDepsOf<ExtensionRouteDeps>(event)!.remountProvider()
- return { skills: await listSkillRows(host) }
+ return { skills: await skillCatalog.resolve() }
}
catch (error) {
event.res.status = 500
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/agents.ts b/packages/dsh-tauri-panel-extension/src/host/service/agents.ts
index ae359713..04a7f2cb 100644
--- a/packages/dsh-tauri-panel-extension/src/host/service/agents.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/service/agents.ts
@@ -1,55 +1,56 @@
-/**
- * Foreign-agent config readers: MCP servers from Claude Code (~/.claude.json,
- * ~/.claude/settings.json), Codex (~/.codex/config.toml), Cursor
- * (~/.cursor/mcp.json) and Gemini CLI (~/.gemini/settings.json). Pure reads of
- * well-known paths; anything missing or malformed yields an empty list.
- */
-
-import type { McpTransport } from './mcp.ts'
+import type { ImportedServer } from './agents.types'
import { existsSync, readFileSync } from 'node:fs'
import { homedir } from 'node:os'
+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'
-/** One MCP server discovered in a foreign agent's config. */
-export interface ImportedServer {
- agent: 'claude-code' | 'codex' | 'cursor' | 'gemini'
- name: string
- transport: McpTransport
- command?: string
- args?: string[]
- env?: Record<string, string>
- url?: string
- headers?: Record<string, string>
-}
+export const agents = defineService({
+ resolve(home: string = homedir()): ImportedServer[] {
+ return uniqBy(
+ [...scanClaudeMcp(home), ...scanCodexMcp(home), ...scanCursorMcp(home), ...scanGeminiMcp(home)],
+ server => `${server.agent}/${server.name}`,
+ )
+ },
+
+ peek(home: string = homedir()): string[] {
+ return AGENT_SKILL_DIRECTORIES
+ .map(directory => join(home, directory))
+ .filter(path => existsSync(path))
+ },
+})
+
+// --- internal ---
-/** Keep only string-valued entries of a record (configs may hold numbers). */
function stringEntries(value: unknown): Record<string, string> | undefined {
- if (typeof value !== 'object' || value === null || Array.isArray(value))
+ if (!isObject(value) || Array.isArray(value))
return undefined
- const out: Record<string, string> = {}
- for (const [key, entry] of Object.entries(value)) {
- if (typeof entry === 'string')
- out[key] = entry
- }
- return Object.keys(out).length > 0 ? out : undefined
+ const out = pickBy(value as Record<string, unknown>, isString)
+ return isEmpty(out) ? undefined : out
}
function stringArray(value: unknown): string[] | undefined {
if (!Array.isArray(value))
return undefined
- const out = value.filter((entry): entry is string => typeof entry === 'string')
- return out.length > 0 ? out : undefined
+ const out = filter(value, isString)
+ return isEmpty(out) ? undefined : out
}
-/** Map one mcpServers entry (Claude / Cursor share the shape); null for unsupported shapes (sse). */
function mapMcpServersEntry(agent: ImportedServer['agent'], name: string, entry: unknown): ImportedServer | null {
- if (typeof entry !== 'object' || entry === null)
+ if (!isObject(entry))
return null
const record = entry as Record<string, unknown>
- const type = typeof record.type === 'string' ? record.type : 'stdio'
- if (type === 'stdio' || (type === 'stdio' && record.command !== undefined)) {
- if (typeof record.command !== 'string' || record.command === '')
+ const type = isString(record.type) ? record.type : 'stdio'
+ if (type === 'stdio') {
+ if (!isString(record.command) || record.command === '')
return null
return {
agent,
@@ -61,7 +62,7 @@ function mapMcpServersEntry(agent: ImportedServer['agent'], name: string, entry:
}
}
if (type === 'http' || type === 'streamable-http') {
- if (typeof record.url !== 'string' || record.url === '')
+ if (!isString(record.url) || record.url === '')
return null
return {
agent,
@@ -71,38 +72,54 @@ function mapMcpServersEntry(agent: ImportedServer['agent'], name: string, entry:
headers: stringEntries(record.headers),
}
}
- // 'sse' and anything else: dsh's mcp-client speaks stdio + streamable-http only.
return null
}
-/** MCP servers from Claude Code's user-scope config files. */
-export function scanClaudeMcp(home: string = homedir()): ImportedServer[] {
+function mapAgentEntry(
+ agent: ImportedServer['agent'],
+ name: string,
+ entry: unknown,
+ urlKey: 'httpUrl' | 'url',
+): ImportedServer | null {
+ if (!isObject(entry))
+ return null
+ const record = entry as Record<string, unknown>
+ if (isString(record.command) && record.command !== '') {
+ return {
+ agent,
+ name,
+ transport: 'stdio',
+ command: record.command,
+ args: stringArray(record.args),
+ env: stringEntries(record.env),
+ }
+ }
+ const url = record[urlKey]
+ if (isString(url) && url !== '')
+ return { agent, name, transport: 'streamable-http', url }
+ return null
+}
+
+function scanClaudeMcp(home: string): ImportedServer[] {
const merged: Record<string, unknown> = {}
- for (const file of [join(home, '.claude', 'settings.json'), join(home, '.claude.json')]) {
- if (!existsSync(file))
+ for (const file of CLAUDE_MCP_FILES) {
+ const path = join(home, file)
+ if (!existsSync(path))
continue
try {
- const parsed = JSON.parse(readFileSync(file, 'utf8')) as { mcpServers?: unknown }
- if (typeof parsed.mcpServers === 'object' && parsed.mcpServers !== null) {
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as { mcpServers?: unknown }
+ if (isObject(parsed.mcpServers))
Object.assign(merged, parsed.mcpServers)
- }
}
catch {
- // Broken or partial config: skip the file, keep earlier merges.
+ continue
}
}
- const out: ImportedServer[] = []
- for (const [name, entry] of Object.entries(merged)) {
- const mapped = mapMcpServersEntry('claude-code', name, entry)
- if (mapped !== null)
- out.push(mapped)
- }
- return out
+ return compact(Object.entries(merged).map(([name, entry]) => mapMcpServersEntry('claude-code', name, entry)))
}
-/** MCP servers from Cursor's ~/.cursor/mcp.json (mcpServers, Claude-shaped). */
-export function scanCursorMcp(home: string = homedir()): ImportedServer[] {
- const file = join(home, '.cursor', 'mcp.json')
+function scanCursorMcp(home: string): ImportedServer[] {
+ const file = join(home, CURSOR_MCP_FILE)
if (!existsSync(file))
return []
let parsed: { mcpServers?: unknown }
@@ -112,23 +129,13 @@ export function scanCursorMcp(home: string = homedir()): ImportedServer[] {
catch {
return []
}
- if (typeof parsed.mcpServers !== 'object' || parsed.mcpServers === null)
+ if (!isObject(parsed.mcpServers))
return []
- const out: ImportedServer[] = []
- for (const [name, entry] of Object.entries(parsed.mcpServers)) {
- const mapped = mapMcpServersEntry('cursor', name, entry)
- if (mapped !== null)
- out.push(mapped)
- }
- return out
+ return compact(Object.entries(parsed.mcpServers).map(([name, entry]) => mapMcpServersEntry('cursor', name, entry)))
}
-/**
- * MCP servers from Gemini CLI's ~/.gemini/settings.json (mcpServers; httpUrl
- * keys map to streamable-http, plain `url` marks SSE and is skipped).
- */
-export function scanGeminiMcp(home: string = homedir()): ImportedServer[] {
- const file = join(home, '.gemini', 'settings.json')
+function scanGeminiMcp(home: string): ImportedServer[] {
+ const file = join(home, GEMINI_MCP_FILE)
if (!existsSync(file))
return []
let parsed: { mcpServers?: unknown }
@@ -138,34 +145,13 @@ export function scanGeminiMcp(home: string = homedir()): ImportedServer[] {
catch {
return []
}
- if (typeof parsed.mcpServers !== 'object' || parsed.mcpServers === null)
+ if (!isObject(parsed.mcpServers))
return []
- const out: ImportedServer[] = []
- for (const [name, entry] of Object.entries(parsed.mcpServers)) {
- if (typeof entry !== 'object' || entry === null)
- continue
- const record = entry as Record<string, unknown>
- if (typeof record.command === 'string' && record.command !== '') {
- out.push({
- agent: 'gemini',
- name,
- transport: 'stdio',
- command: record.command,
- args: stringArray(record.args),
- env: stringEntries(record.env),
- })
- }
- else if (typeof record.httpUrl === 'string' && record.httpUrl !== '') {
- out.push({ agent: 'gemini', name, transport: 'streamable-http', url: record.httpUrl })
- }
- // `url`-only entries are SSE endpoints, which dsh's client cannot speak.
- }
- return out
+ return compact(Object.entries(parsed.mcpServers).map(([name, entry]) => mapAgentEntry('gemini', name, entry, 'httpUrl')))
}
-/** MCP servers from Codex's config.toml ([mcp_servers.<name>] tables). */
-export function scanCodexMcp(home: string = homedir()): ImportedServer[] {
- const file = join(home, '.codex', 'config.toml')
+function scanCodexMcp(home: string): ImportedServer[] {
+ const file = join(home, CODEX_MCP_FILE)
if (!existsSync(file))
return []
let root: Record<string, unknown>
@@ -176,45 +162,7 @@ export function scanCodexMcp(home: string = homedir()): ImportedServer[] {
return []
}
const table = root.mcp_servers
- if (typeof table !== 'object' || table === null)
+ if (!isObject(table))
return []
- const out: ImportedServer[] = []
- for (const [name, entry] of Object.entries(table)) {
- if (typeof entry !== 'object' || entry === null)
- continue
- const record = entry as Record<string, unknown>
- if (typeof record.command === 'string' && record.command !== '') {
- out.push({
- agent: 'codex',
- name,
- transport: 'stdio',
- command: record.command,
- args: stringArray(record.args),
- env: stringEntries(record.env),
- })
- }
- else if (typeof record.url === 'string' && record.url !== '') {
- out.push({ agent: 'codex', name, transport: 'streamable-http', url: record.url })
- }
- }
- return out
-}
-
-/** All foreign-agent MCP servers, deduplicated by (agent, name). */
-export function scanAllMcp(home: string = homedir()): ImportedServer[] {
- const seen = new Set<string>()
- return [...scanClaudeMcp(home), ...scanCodexMcp(home), ...scanCursorMcp(home), ...scanGeminiMcp(home)]
- .filter((server) => {
- const key = `${server.agent}/${server.name}`
- if (seen.has(key))
- return false
- seen.add(key)
- return true
- })
-}
-
-/** Other agents' skill roots that exist on this machine. */
-export function agentSkillRoots(home: string = homedir()): string[] {
- return [join(home, '.claude', 'skills'), join(home, '.codex', 'skills')]
- .filter(path => existsSync(path))
+ return compact(Object.entries(table).map(([name, entry]) => mapAgentEntry('codex', name, entry, 'url')))
}
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/agents.types.ts b/packages/dsh-tauri-panel-extension/src/host/service/agents.types.ts
new file mode 100644
index 00000000..f9d9e3cc
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/agents.types.ts
@@ -0,0 +1,12 @@
+import type { McpTransport } from './mcp.types'
+
+export interface ImportedServer {
+ agent: 'claude-code' | 'codex' | 'cursor' | 'gemini'
+ name: string
+ transport: McpTransport
+ command?: string
+ args?: string[]
+ env?: Record<string, string>
+ url?: string
+ headers?: Record<string, string>
+}
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.ts
new file mode 100644
index 00000000..f7ae687a
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/mcp-toggle.ts
@@ -0,0 +1,18 @@
+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.ts
index 79a77dea..eb40353b 100644
--- a/packages/dsh-tauri-panel-extension/src/host/service/mcp.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/service/mcp.ts
@@ -1,414 +1,150 @@
-/**
- * MCP server rows in the profile's own patch layer: one
- * `@deepseek-ai/dsh-mcp-client` row per server. The YAML document API keeps
- * foreign rows and comments intact across edits. Row changes need a dsh
- * restart to compose — callers surface that as a pending-restart notice.
- *
- * The loader's patch grammar distinguishes creates from overrides: a bare
- * `- id: …` entry only overrides an existing row (target missing → skipped
- * with a warning), while new rows must live in an anonymous `- insert:`
- * list. Managed rows therefore always sit inside one insert entry, and any
- * legacy bare rows (written before this contract was understood) are
- * absorbed into it on the next write.
- *
- * Rows live in one of two patch layers: the profile's own
- * `cordis.patch.yml`, or the machine-wide `$DSH_HOME/cordis.patch.yml`
- * (dsh composes it over every profile, after the profile layer — a home row
- * with the same id wins). The primitives below address one layer via the
- * directory holding its `cordis.patch.yml`; `listMcpScoped` merges both.
- */
-
-import type { YAMLMap, YAMLSeq } from 'yaml'
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import type { YAMLMap } from 'yaml'
+import type { McpCheckOptions, McpCheckResult, McpInput, McpListResult, McpRow, McpRowView } from './mcp.types'
+import { existsSync } from 'node:fs'
import process from 'node:process'
-import { DSH_HOME } from 'dsh-tauri'
+import { defineService, DSH_HOME } from 'dsh-tauri'
+import { compact, isEmpty } from 'lodash-es'
import { join } from 'pathe'
-import { Document, parseDocument } from 'yaml'
-/** The plugin every managed row instantiates. */
-export const MCP_PLUGIN = '@deepseek-ai/dsh-mcp-client'
-
-/** MCP serverName grammar (dsh-mcp-client's contract). */
-export const SERVER_NAME_RE = /^[\w-]{1,32}$/
-
-/** Transport choices the client supports. */
-export type McpTransport = 'stdio' | 'streamable-http'
-
-/** Which patch layer a row lives in. */
-export type McpScope = 'global' | 'profile'
-
-/** One managed row, as shown to the browser. */
-export interface McpRow {
- id: string
- serverName: string
- transport: McpTransport
- disabled: boolean
- command?: string
- args?: string[]
- env?: Record<string, string>
- cwd?: string
- url?: string
- headers?: Record<string, string>
-}
-
-/** One row tagged with its layer. */
-export interface McpRowView extends McpRow {
- scope: McpScope
- /** Profile rows only: a global row with the same id composes after this one and wins. */
- shadowed?: boolean
-}
-
-/** Merged listing across both patch layers. */
-export interface McpListResult {
- servers: McpRowView[]
- /** The home layer exists but could not be read; its rows are not shown. */
- globalError?: string
-}
-
-/** Write request for one server row (id empty = create). */
-export type McpInput = Omit<McpRow, 'disabled'> & { disabled?: boolean }
-
-/**
- * Refuse to touch a patch file the parser could not fully read. parseDocument
- * parks syntax errors in doc.errors (it does not throw), and the failure only
- * resurfaces at String(doc) as the internals-leaking "Document with errors
- * cannot be stringified". Nothing gets written either way, but the banner must
- * say what is actually wrong and which file to fix.
- */
-function assertPatchParses(path: string, doc: Document): void {
- if (doc.errors.length === 0)
- return
- const at = String(doc.errors[0].message).split('\n', 1)[0]
- const total = doc.errors.length > 1 ? `, +${doc.errors.length - 1} more` : ''
- throw new Error(
- `配置文件 ${path} 存在 YAML 语法错误(${at}${total}),未写入任何内容,请修复该文件后重试`
- + ` / YAML syntax error in the patch file (${at}${total}); nothing was written — fix it and retry`,
- )
-}
-
-/** Load one layer's patch (`<dirPath>/cordis.patch.yml`) as a YAML document; `[]` for a missing file. */
-function loadPatch(dirPath: string): Document {
- const path = join(dirPath, 'cordis.patch.yml')
- const text = existsSync(path) ? readFileSync(path, 'utf8') : '[]'
- const doc = parseDocument(text)
- assertPatchParses(path, doc)
- const contents = doc.contents as YAMLSeq | null
- // The default-empty file parses as a flow `[]`; the patch layer is
- // human-edited block YAML, so flip the flag before anything appends.
- if (contents !== null && contents.flow === true && contents.items.length === 0)
- contents.flow = false
- return doc
-}
-
-function savePatch(dirPath: string, doc: Document): void {
- mkdirSync(dirPath, { recursive: true })
- writeFileSync(join(dirPath, 'cordis.patch.yml'), String(doc), 'utf8')
-}
-
-/** Wrap a plain value into a YAML node (yaml v2 exposes no standalone createNode). */
-function toNode<T>(value: unknown): T {
- return new Document(value as never).contents as T
-}
-
-/** The patch row sequence; an empty file's null root becomes an empty seq. */
-function rowSeq(doc: Document): YAMLSeq<YAMLMap> {
- if (doc.contents === null) {
- doc.contents = toNode<YAMLSeq<YAMLMap>>([])
- // An empty seq defaults to flow style (`[]`); the file must stay block.
- ;(doc.contents as YAMLSeq).flow = false
- }
- return doc.contents as YAMLSeq<YAMLMap>
-}
-
-function isSeqNode(value: unknown): value is YAMLSeq<YAMLMap> {
- return typeof value === 'object' && value !== null && Array.isArray((value as YAMLSeq).items)
-}
-
-/** A patch entry's insert list when it is the anonymous create form. */
-function insertListOf(item: YAMLMap): YAMLSeq<YAMLMap> | undefined {
- if (item.has('id'))
- return undefined
- const node = item.get('insert')
- return isSeqNode(node) ? node : undefined
-}
-
-/** Every managed row: legacy bare entries (no list) and insert-list rows. */
-function mcpRowItems(doc: Document): { node: YAMLMap, list?: YAMLSeq<YAMLMap> }[] {
- const found: { node: YAMLMap, list?: YAMLSeq<YAMLMap> }[] = []
- for (const item of rowSeq(doc).items ?? []) {
- if (item.get('name') === MCP_PLUGIN)
- found.push({ node: item })
- const list = insertListOf(item)
- for (const row of list?.items ?? []) {
- if (row.get('name') === MCP_PLUGIN)
- found.push({ node: row, list })
+import { MCP_CHECK_TIMEOUT_MS, MCP_PLUGIN, PATCH_FILE_NAME } from '../config/constants'
+import {
+ insertListOf,
+ loadPatch,
+ managedInsert,
+ mcpRowItems,
+ readRows,
+ rowSeq,
+ savePatch,
+ takenIds,
+ toNode,
+} from './mcp.utils'
+
+export const mcp = defineService({
+ list(profileDirPath: string): McpListResult {
+ let globalRows: McpRow[] = []
+ let globalError: string | undefined
+ if (existsSync(join(DSH_HOME, PATCH_FILE_NAME))) {
+ try {
+ globalRows = readRows(DSH_HOME)
+ }
+ catch (error) {
+ globalError = error instanceof Error ? error.message : String(error)
+ }
+ }
+ const globalIds = new Set(compact(globalRows.map(row => row.id)))
+ return {
+ servers: [
+ ...globalRows.map((row): McpRowView => ({ ...row, scope: 'global' })),
+ ...readRows(profileDirPath).map((row): McpRowView => ({
+ ...row,
+ scope: 'profile',
+ ...(globalIds.has(row.id) ? { shadowed: true } : {}),
+ })),
+ ],
+ ...(globalError !== undefined ? { globalError } : {}),
+ }
+ },
+
+ peek(dirPath: string): McpRow[] {
+ return readRows(dirPath)
+ },
+
+ save(dirPath: string, input: McpInput): string {
+ const inputId = input.id ?? ''
+ const doc = loadPatch(dirPath)
+ const list = managedInsert(doc)
+ const existing = inputId !== ''
+ ? mcpRowItems(doc).find(({ node }) => String(node.get('id') ?? '') === inputId)
+ : undefined
+
+ let id = inputId !== '' ? inputId : `mcp-${input.serverName}`
+ if (existing === undefined) {
+ const taken = takenIds(doc)
+ let suffix = 2
+ while (taken.has(id))
+ id = `mcp-${input.serverName}-${suffix++}`
}
- }
- return found
-}
-
-/** Map one row node to its browser-facing shape. */
-function rowToMcp(doc: Document, item: YAMLMap): McpRow {
- // config is a YAMLMap node — materialize it before property access.
- const configNode = item.get('config') as unknown
- const plain = (typeof configNode === 'object' && configNode !== null && typeof (configNode as { toJS?: unknown }).toJS === 'function'
- ? (configNode as { toJS: (document: Document) => unknown }).toJS(doc)
- : {}) as Record<string, unknown>
- return {
- id: String(item.get('id') ?? ''),
- serverName: String(plain.serverName ?? ''),
- transport: plain.transport === 'streamable-http' ? 'streamable-http' : 'stdio',
- disabled: item.get('disabled') === true,
- ...(typeof plain.command === 'string' && plain.command !== '' ? { command: plain.command } : {}),
- ...(Array.isArray(plain.args) ? { args: plain.args.map(String) } : {}),
- ...(isStringMap(plain.env) ? { env: plain.env } : {}),
- ...(typeof plain.cwd === 'string' && plain.cwd !== '' ? { cwd: plain.cwd } : {}),
- ...(typeof plain.url === 'string' && plain.url !== '' ? { url: plain.url } : {}),
- ...(isStringMap(plain.headers) ? { headers: plain.headers } : {}),
- }
-}
-
-function isStringMap(value: unknown): value is Record<string, string> {
- if (typeof value !== 'object' || value === null || Array.isArray(value))
- return false
- return Object.values(value).every(entry => typeof entry === 'string')
-}
-/**
- * The insert list that owns managed rows, creating it when absent and
- * absorbing legacy bare rows into it. Absorbed rows were inert under the
- * loader's override-only reading of bare entries, so the move is not just
- * cosmetic — it is what makes them compose.
- */
-function managedInsert(doc: Document): YAMLSeq<YAMLMap> {
- const seq = rowSeq(doc)
- const bare: YAMLMap[] = []
- let target: YAMLSeq<YAMLMap> | undefined
- for (const item of seq.items ?? []) {
- if (item.get('name') === MCP_PLUGIN)
- bare.push(item)
- const list = insertListOf(item)
- if (list !== undefined && list.items.some(row => row.get('name') === MCP_PLUGIN))
- target ??= list
- }
- if (target === undefined) {
- const entry = toNode<YAMLMap>({ insert: [] })
- seq.add(entry)
- target = entry.get('insert') as YAMLSeq<YAMLMap>
- target.flow = false
- }
- for (const row of bare) {
- seq.items.splice(seq.items.indexOf(row), 1)
- target.add(row)
- }
- return target
-}
+ const config: Record<string, unknown> = input.transport === 'stdio'
+ ? {
+ serverName: input.serverName,
+ transport: input.transport,
+ command: input.command,
+ ...(!isEmpty(input.args) ? { args: input.args } : {}),
+ ...(!isEmpty(input.env) ? { env: input.env } : {}),
+ ...(!isEmpty(input.cwd) ? { cwd: input.cwd } : {}),
+ }
+ : {
+ serverName: input.serverName,
+ transport: input.transport,
+ url: input.url,
+ ...(!isEmpty(input.headers) ? { headers: input.headers } : {}),
+ }
+ const row: Record<string, unknown> = { id, name: MCP_PLUGIN, config }
+ if (input.disabled === true)
+ row.disabled = true
-/** Every id in use: top-level patch entries and rows inside insert lists. */
-function takenIds(doc: Document): Set<string> {
- const taken = new Set<string>()
- for (const item of rowSeq(doc).items ?? []) {
- const id = String(item.get('id') ?? '')
- if (id !== '')
- taken.add(id)
- for (const row of insertListOf(item)?.items ?? []) {
- const rowId = String(row.get('id') ?? '')
- if (rowId !== '')
- taken.add(rowId)
+ const node = toNode<YAMLMap>(row)
+ if (existing === undefined) {
+ list.add(node)
+ }
+ else if (existing.list !== undefined) {
+ existing.list.items.splice(existing.list.items.indexOf(existing.node), 1, node)
+ }
+ else {
+ rowSeq(doc).items.splice(rowSeq(doc).items.indexOf(existing.node), 1, node)
}
- }
- return taken
-}
-
-/** Read every mcp-client row in one patch layer (`<dirPath>/cordis.patch.yml`). */
-export function listMcp(dirPath: string): McpRow[] {
- const doc = loadPatch(dirPath)
- return mcpRowItems(doc).map(({ node }) => rowToMcp(doc, node))
-}
-/**
- * Merge both patch layers for the browser: global rows first (dsh composes
- * them after the profile layer, so they win), profile rows tagged `shadowed`
- * when a global row claims the same id. A broken home layer must not take
- * the whole page down — its read failure degrades to `globalError` and the
- * profile layer still lists (the assertPatchParses message names the file
- * and the parser location, which is what the banner shows).
- */
-export function listMcpScoped(profileDirPath: string): McpListResult {
- let globalRows: McpRow[] = []
- let globalError: string | undefined
- if (existsSync(join(DSH_HOME, 'cordis.patch.yml'))) {
+ savePatch(dirPath, doc)
+ return id
+ },
+
+ remove(dirPath: string, id: string): boolean {
+ const doc = loadPatch(dirPath)
+ managedInsert(doc)
+ const hit = mcpRowItems(doc).find(({ node }) => String(node.get('id') ?? '') === id)
+ if (hit === undefined || hit.list === undefined)
+ return false
+ hit.list.items.splice(hit.list.items.indexOf(hit.node), 1)
+
+ const seq = rowSeq(doc)
+ const owner = (seq.items ?? []).find(item => insertListOf(item) === hit.list)
+ if (owner !== undefined && hit.list.items.length === 0 && owner.items.length === 1)
+ seq.items.splice(seq.items.indexOf(owner), 1)
+
+ savePatch(dirPath, doc)
+ return true
+ },
+
+ async check(row: McpRow, options: McpCheckOptions = {}): Promise<McpCheckResult> {
+ const pathEnv = options.pathEnv ?? process.env.PATH ?? ''
+ if (row.transport === 'stdio') {
+ const command = row.command ?? ''
+ if (command === '')
+ return { ok: false, detail: 'row has no command' }
+ return resolveCommandOnPath(command, pathEnv, options.platform)
+ ? { ok: true, detail: command }
+ : { ok: false, detail: `${command} not found on PATH` }
+ }
+ if (row.url === undefined || !/^https?:\/\//.test(row.url))
+ return { ok: false, detail: 'row has no http url' }
try {
- globalRows = listMcp(DSH_HOME)
+ const response = await fetch(row.url, {
+ headers: { accept: 'application/json, text/event-stream' },
+ signal: AbortSignal.timeout(options.timeoutMs ?? MCP_CHECK_TIMEOUT_MS),
+ })
+ return { ok: true, detail: `HTTP ${response.status}` }
}
catch (error) {
- globalError = error instanceof Error ? error.message : String(error)
+ const message = error instanceof Error ? error.message : String(error)
+ const cause = (error as { cause?: { code?: unknown } }).cause?.code
+ return { ok: false, detail: cause !== undefined ? String(cause) : message }
}
- }
- const globalIds = new Set(globalRows.map(row => row.id).filter(id => id !== ''))
- return {
- servers: [
- ...globalRows.map((row): McpRowView => ({ ...row, scope: 'global' })),
- ...listMcp(profileDirPath).map((row): McpRowView => ({
- ...row,
- scope: 'profile',
- ...(globalIds.has(row.id) ? { shadowed: true } : {}),
- })),
- ],
- ...(globalError !== undefined ? { globalError } : {}),
- }
-}
-
-/** Resolve a write target: the layer's directory holding its cordis.patch.yml. */
-export function mcpScopeDir(scope: McpScope, profileDirPath: string): string {
- return scope === 'global' ? DSH_HOME : profileDirPath
-}
-
-/**
- * 归一化请求里的 `scope` 字段:只有显式 `'global'` 才落到机器级 patch 层。
- *
- * 纯函数(无状态码、无响应组织),供各 MCP 路由处理器共用;非法值按 profile 处理,
- * 与迁移前一致。
- */
-export function normalizeMcpScope(value: unknown): McpScope {
- return value === 'global' ? 'global' : 'profile'
-}
-
-/** Validate one write request; returns the rejection reason or null. */
-export function validateMcpInput(input: McpInput): string | null {
- if (!SERVER_NAME_RE.test(input.serverName))
- return 'serverName must be 1-32 chars of A-Z a-z 0-9 _ -'
- // The route casts raw JSON to McpInput; a create request may omit `id`.
- const id = input.id ?? ''
- if (id.includes('/') || id.includes('..'))
- return 'invalid id'
- if (input.transport === 'stdio') {
- if (input.command === undefined || input.command.trim() === '')
- return 'stdio transport requires a command'
- }
- else if (input.url === undefined || !/^https?:\/\//.test(input.url)) {
- return 'http transport requires an http(s) url'
- }
- return null
-}
-
-/** Add or replace one server row. Returns the (possibly deduplicated) id. */
-export function upsertMcp(dirPath: string, input: McpInput): string {
- const inputId = input.id ?? ''
- const doc = loadPatch(dirPath)
- const list = managedInsert(doc)
-
- const existing = inputId !== ''
- ? mcpRowItems(doc).find(({ node }) => String(node.get('id') ?? '') === inputId)
- : undefined
-
- let id = inputId !== '' ? inputId : `mcp-${input.serverName}`
- if (existing === undefined) {
- const taken = takenIds(doc)
- let suffix = 2
- while (taken.has(id)) id = `mcp-${input.serverName}-${suffix++}`
- }
-
- const config: Record<string, unknown> = input.transport === 'stdio'
- ? {
- serverName: input.serverName,
- transport: input.transport,
- command: input.command,
- ...(input.args !== undefined && input.args.length > 0 ? { args: input.args } : {}),
- ...(input.env !== undefined && Object.keys(input.env).length > 0 ? { env: input.env } : {}),
- ...(input.cwd !== undefined && input.cwd !== '' ? { cwd: input.cwd } : {}),
- }
- : {
- serverName: input.serverName,
- transport: input.transport,
- url: input.url,
- ...(input.headers !== undefined && Object.keys(input.headers).length > 0 ? { headers: input.headers } : {}),
- }
- const row: Record<string, unknown> = { id, name: MCP_PLUGIN, config }
- if (input.disabled === true)
- row.disabled = true
-
- const node = toNode<YAMLMap>(row)
- if (existing === undefined) {
- list.add(node)
- }
- else if (existing.list !== undefined) {
- existing.list.items.splice(existing.list.items.indexOf(existing.node), 1, node)
- }
- else {
- // Bare rows were absorbed above; reaching here means a foreign-shaped row.
- rowSeq(doc).items.splice(rowSeq(doc).items.indexOf(existing.node), 1, node)
- }
-
- savePatch(dirPath, doc)
- return id
-}
-
-/** Flip one row's disabled flag (absent = enabled). Returns false when missing. */
-export function setMcpDisabled(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
-}
-
-/** Remove one server row. Returns false when missing. */
-export function removeMcp(dirPath: string, id: string): boolean {
- const doc = loadPatch(dirPath)
- managedInsert(doc)
- const hit = mcpRowItems(doc).find(({ node }) => String(node.get('id') ?? '') === id)
- if (hit === undefined || hit.list === undefined)
- return false
- hit.list.items.splice(hit.list.items.indexOf(hit.node), 1)
-
- // An insert entry left with no rows is dead weight; drop it when the
- // insert list is all it holds.
- const seq = rowSeq(doc)
- const owner = (seq.items ?? []).find(item => insertListOf(item) === hit.list)
- if (owner !== undefined && hit.list.items.length === 0 && owner.items.length === 1) {
- seq.items.splice(seq.items.indexOf(owner), 1)
- }
-
- savePatch(dirPath, doc)
- return true
-}
+ },
+})
-/**
- * Rebuild a create request from an existing row (id emptied; identity fields
- * carried over) — used to copy a row into the other patch layer.
- */
-export function mcpRowToInput(row: McpRow): McpInput {
- return {
- id: '',
- serverName: row.serverName,
- transport: row.transport,
- disabled: row.disabled,
- ...(row.transport === 'stdio'
- ? {
- command: row.command,
- ...(row.args !== undefined ? { args: row.args } : {}),
- ...(row.env !== undefined ? { env: row.env } : {}),
- ...(row.cwd !== undefined ? { cwd: row.cwd } : {}),
- }
- : {
- url: row.url,
- ...(row.headers !== undefined ? { headers: row.headers } : {}),
- }),
- }
-}
+// --- internal ---
-/**
- * Whether a stdio command would resolve at spawn time: a bare name is looked
- * up in the PATH entries (with the Windows executable extensions), anything
- * with a path separator must exist as given. Pure filesystem reads — no
- * process is spawned, so no console-window or side-effect concerns.
- */
-export function resolveCommandOnPath(command: string, pathEnv: string, platform: string = process.platform): boolean {
+function resolveCommandOnPath(command: string, pathEnv: string, platform: string = process.platform): boolean {
if (command.includes('/') || command.includes('\\'))
return existsSync(command)
const exts = platform === 'win32' ? ['', '.com', '.exe', '.bat', '.cmd'] : ['']
@@ -424,42 +160,3 @@ export function resolveCommandOnPath(command: string, pathEnv: string, platform:
}
return false
}
-
-/** Outcome of a connectivity check, as the browser renders it. */
-export interface McpCheckResult {
- ok: boolean
- /** Short technical detail for the hint line ("HTTP 200", "not found on PATH"). */
- detail?: string
-}
-
-/**
- * Probe one server row without starting it: stdio rows are validated against
- * the PATH (a spawn would leave console windows and side effects behind),
- * streamable-http rows get a short GET — any HTTP status proves reachability,
- * since MCP endpoints legitimately answer 405 to plain GETs.
- */
-export async function checkMcpRow(row: McpRow, options: { timeoutMs?: number, pathEnv?: string, platform?: string } = {}): Promise<McpCheckResult> {
- const pathEnv = options.pathEnv ?? process.env.PATH ?? ''
- if (row.transport === 'stdio') {
- const command = row.command ?? ''
- if (command === '')
- return { ok: false, detail: 'row has no command' }
- return resolveCommandOnPath(command, pathEnv, options.platform)
- ? { ok: true, detail: command }
- : { ok: false, detail: `${command} not found on PATH` }
- }
- if (row.url === undefined || !/^https?:\/\//.test(row.url))
- return { ok: false, detail: 'row has no http url' }
- try {
- const response = await fetch(row.url, {
- headers: { accept: 'application/json, text/event-stream' },
- signal: AbortSignal.timeout(options.timeoutMs ?? 5000),
- })
- return { ok: true, detail: `HTTP ${response.status}` }
- }
- catch (error) {
- const message = error instanceof Error ? error.message : String(error)
- const cause = (error as { cause?: { code?: unknown } }).cause?.code
- return { ok: false, detail: cause !== undefined ? String(cause) : message }
- }
-}
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/mcp.types.ts b/packages/dsh-tauri-panel-extension/src/host/service/mcp.types.ts
new file mode 100644
index 00000000..63e3b5ea
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/mcp.types.ts
@@ -0,0 +1,39 @@
+export type McpTransport = 'stdio' | 'streamable-http'
+
+export type McpScope = 'global' | 'profile'
+
+export interface McpRow {
+ id: string
+ serverName: string
+ transport: McpTransport
+ disabled: boolean
+ command?: string
+ args?: string[]
+ env?: Record<string, string>
+ cwd?: string
+ url?: string
+ headers?: Record<string, string>
+}
+
+export interface McpRowView extends McpRow {
+ scope: McpScope
+ shadowed?: boolean
+}
+
+export interface McpListResult {
+ servers: McpRowView[]
+ globalError?: string
+}
+
+export type McpInput = Omit<McpRow, 'disabled'> & { disabled?: boolean }
+
+export interface McpCheckResult {
+ ok: boolean
+ detail?: string
+}
+
+export interface McpCheckOptions {
+ timeoutMs?: number
+ pathEnv?: string
+ platform?: string
+}
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.ts
new file mode 100644
index 00000000..3761331d
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/mcp.utils.ts
@@ -0,0 +1,172 @@
+import type { YAMLMap, YAMLSeq } from 'yaml'
+import type { McpInput, McpRow, McpScope } from './mcp.types'
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+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'
+
+export function normalizeMcpScope(value: unknown): McpScope {
+ return value === 'global' ? 'global' : 'profile'
+}
+
+export function mcpScopeDir(scope: McpScope, profileDirPath: string): string {
+ return scope === 'global' ? DSH_HOME : profileDirPath
+}
+
+export function mcpRowToInput(row: McpRow): McpInput {
+ const detail: Record<string, unknown> = row.transport === 'stdio'
+ ? { args: row.args, env: row.env, cwd: row.cwd }
+ : { headers: row.headers }
+ return {
+ id: '',
+ serverName: row.serverName,
+ transport: row.transport,
+ disabled: row.disabled,
+ ...(row.transport === 'stdio' ? { command: row.command } : { url: row.url }),
+ ...omitBy(detail, isUndefined),
+ }
+}
+
+export function validateMcpInput(input: McpInput): string | null {
+ if (!SERVER_NAME_RE.test(input.serverName))
+ return 'serverName must be 1-32 chars of A-Z a-z 0-9 _ -'
+ const id = input.id ?? ''
+ if (id.includes('/') || id.includes('..'))
+ return 'invalid id'
+ if (input.transport === 'stdio') {
+ if (input.command === undefined || input.command.trim() === '')
+ return 'stdio transport requires a command'
+ }
+ else if (input.url === undefined || !/^https?:\/\//.test(input.url)) {
+ return 'http transport requires an http(s) url'
+ }
+ return null
+}
+
+export function loadPatch(dirPath: string): Document {
+ const path = join(dirPath, PATCH_FILE_NAME)
+ const text = existsSync(path) ? readFileSync(path, 'utf8') : EMPTY_PATCH
+ const doc = parseDocument(text)
+ assertPatchParses(path, doc)
+ const contents = doc.contents as YAMLSeq | null
+ if (contents !== null && contents.flow === true && contents.items.length === 0)
+ contents.flow = false
+ return doc
+}
+
+export function savePatch(dirPath: string, doc: Document): void {
+ mkdirSync(dirPath, { recursive: true })
+ writeFileSync(join(dirPath, PATCH_FILE_NAME), String(doc), 'utf8')
+}
+
+export function toNode<T>(value: unknown): T {
+ return new Document(value as never).contents as T
+}
+
+export function rowSeq(doc: Document): YAMLSeq<YAMLMap> {
+ if (doc.contents === null) {
+ const seq = toNode<YAMLSeq<YAMLMap>>([])
+ seq.flow = false
+ doc.contents = seq
+ }
+ return doc.contents as YAMLSeq<YAMLMap>
+}
+
+export function insertListOf(item: YAMLMap): YAMLSeq<YAMLMap> | undefined {
+ if (item.has('id'))
+ return undefined
+ const node = item.get('insert')
+ return isSeqNode(node) ? node : undefined
+}
+
+export function mcpRowItems(doc: Document): { node: YAMLMap, list?: YAMLSeq<YAMLMap> }[] {
+ const found: { node: YAMLMap, list?: YAMLSeq<YAMLMap> }[] = []
+ for (const item of rowSeq(doc).items ?? []) {
+ if (item.get('name') === MCP_PLUGIN)
+ found.push({ node: item })
+ const list = insertListOf(item)
+ for (const row of list?.items ?? []) {
+ if (row.get('name') === MCP_PLUGIN)
+ found.push({ node: row, list })
+ }
+ }
+ return found
+}
+
+export function managedInsert(doc: Document): YAMLSeq<YAMLMap> {
+ const seq = rowSeq(doc)
+ const bare: YAMLMap[] = []
+ let target: YAMLSeq<YAMLMap> | undefined
+ for (const item of seq.items ?? []) {
+ if (item.get('name') === MCP_PLUGIN)
+ bare.push(item)
+ const list = insertListOf(item)
+ if (list !== undefined && list.items.some(row => row.get('name') === MCP_PLUGIN))
+ target ??= list
+ }
+ if (target === undefined) {
+ const entry = toNode<YAMLMap>({ insert: [] })
+ seq.add(entry)
+ target = entry.get('insert') as YAMLSeq<YAMLMap>
+ target.flow = false
+ }
+ for (const row of bare) {
+ seq.items.splice(seq.items.indexOf(row), 1)
+ target.add(row)
+ }
+ return target
+}
+
+export function takenIds(doc: Document): Set<string> {
+ const nodes = (rowSeq(doc).items ?? []).flatMap(item => [item, ...(insertListOf(item)?.items ?? [])])
+ return new Set(compact(nodes.map(node => String(node.get('id') ?? ''))))
+}
+
+export function readRows(dirPath: string): McpRow[] {
+ const doc = loadPatch(dirPath)
+ return mcpRowItems(doc).map(({ node }) => rowToMcp(doc, node))
+}
+
+// --- internal ---
+
+function assertPatchParses(path: string, doc: Document): void {
+ if (doc.errors.length === 0)
+ return
+ const at = String(doc.errors[0].message).split('\n', 1)[0]
+ const total = doc.errors.length > 1 ? `, +${doc.errors.length - 1} more` : ''
+ throw new Error(
+ `配置文件 ${path} 存在 YAML 语法错误(${at}${total}),未写入任何内容,请修复该文件后重试`
+ + ` / YAML syntax error in the patch file (${at}${total}); nothing was written — fix it and retry`,
+ )
+}
+
+function isSeqNode(value: unknown): value is YAMLSeq<YAMLMap> {
+ return typeof value === 'object' && value !== null && Array.isArray((value as YAMLSeq).items)
+}
+
+function isStringMap(value: unknown): value is Record<string, string> {
+ if (!isObject(value) || Array.isArray(value))
+ return false
+ return every(value, isString)
+}
+
+function rowToMcp(doc: Document, item: YAMLMap): McpRow {
+ const configNode = item.get('config') as unknown
+ const plain = (isObject(configNode) && typeof (configNode as { toJS?: unknown }).toJS === 'function'
+ ? (configNode as { toJS: (document: Document) => unknown }).toJS(doc)
+ : {}) as Record<string, unknown>
+ return {
+ id: String(item.get('id') ?? ''),
+ serverName: String(plain.serverName ?? ''),
+ transport: plain.transport === 'streamable-http' ? 'streamable-http' : 'stdio',
+ disabled: item.get('disabled') === true,
+ ...(typeof plain.command === 'string' && plain.command !== '' ? { command: plain.command } : {}),
+ ...(Array.isArray(plain.args) ? { args: plain.args.map(String) } : {}),
+ ...(isStringMap(plain.env) ? { env: plain.env } : {}),
+ ...(typeof plain.cwd === 'string' && plain.cwd !== '' ? { cwd: plain.cwd } : {}),
+ ...(typeof plain.url === 'string' && plain.url !== '' ? { url: plain.url } : {}),
+ ...(isStringMap(plain.headers) ? { headers: plain.headers } : {}),
+ }
+}
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/opener.ts b/packages/dsh-tauri-panel-extension/src/host/service/opener.ts
index 0fcfa5a8..a885cd09 100644
--- a/packages/dsh-tauri-panel-extension/src/host/service/opener.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/service/opener.ts
@@ -1,38 +1,27 @@
-/**
- * Open a directory in the OS file manager, from the dsh sidecar process.
- * Spawned detached with all stdio ignored — a GUI file manager needs no
- * pipes, and explorer.exe reports failure through exit codes we must not
- * await (it exits non-zero even on success in several Windows versions).
- */
-
import { spawn } from 'node:child_process'
import { statSync } from 'node:fs'
import process from 'node:process'
+import { defineService } from 'dsh-tauri'
-/** Open one directory; resolves true when a launcher was started. */
-export function openDirectory(dir: string): boolean {
- try {
- if (!statSync(dir).isDirectory())
+export const opener = defineService({
+ open(dir: string): boolean {
+ try {
+ if (!statSync(dir).isDirectory())
+ return false
+ }
+ catch {
+ return false
+ }
+ const target = process.platform === 'win32' ? dir.split('/').join('\\') : dir
+ const launcher = process.platform === 'win32' ? 'explorer' : process.platform === 'darwin' ? 'open' : 'xdg-open'
+ try {
+ const child = spawn(launcher, [target], { detached: true, stdio: 'ignore' })
+ child.once('error', () => {})
+ child.unref()
+ return true
+ }
+ catch {
return false
- }
- catch {
- return false
- }
- if (process.platform === 'win32') {
- // explorer 对正斜杠路径会静默回落到默认文件夹(实测打开成了「文档」),必须喂反斜杠。
- dir = dir.split('/').join('\\')
- }
- const launcher = process.platform === 'win32' ? 'explorer' : process.platform === 'darwin' ? 'open' : 'xdg-open'
- try {
- // GUI 启动器不能带 windowsHide:该 flag 把 SW_HIDE 写进 STARTUPINFO,explorer 的
- // 首个窗口据此创建为隐藏——实机表现是「打开目录」点了没反应,窗口其实开了。
- const child = spawn(launcher, [dir], { detached: true, stdio: 'ignore' })
- // 启动器解析失败时 'error' 异步到达;没有监听会升级成 uncaughtException 炸掉 sidecar。
- child.once('error', () => {})
- child.unref()
- return true
- }
- catch {
- return false
- }
-}
+ }
+ },
+})
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/profile.ts b/packages/dsh-tauri-panel-extension/src/host/service/profile.ts
index e16b9997..c9480a02 100644
--- a/packages/dsh-tauri-panel-extension/src/host/service/profile.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/service/profile.ts
@@ -1,18 +1,16 @@
-/** Profile discovery (pure reads; same contract as dsh-plugin-install). */
-
import process from 'node:process'
-import { DSH_HOME } from 'dsh-tauri'
-import { join } from 'pathe'
+import { defineService } from 'dsh-tauri'
+import { profileDir } from '../utils/paths.utils'
-/** Profile that boots this UI: `--profile <name>` on the CLI invocation. */
-export function argvProfile(argv: readonly string[] = process.argv): string | undefined {
- const flag = argv.indexOf('--profile')
- if (flag !== -1 && flag + 1 < argv.length && !argv[flag + 1].startsWith('-'))
- return argv[flag + 1]
- return undefined
-}
+export const profile = defineService({
+ resolve(argv: readonly string[] = process.argv): string | null {
+ const flag = argv.indexOf('--profile')
+ if (flag !== -1 && flag + 1 < argv.length && !argv[flag + 1].startsWith('-'))
+ return argv[flag + 1]
+ return null
+ },
-/** Directory of a profile under DSH_HOME(数据根一律引用核心的 DSH_HOME)。 */
-export function profileDir(profile: string): string {
- return join(DSH_HOME, 'profiles', profile)
-}
+ peek(name: string): string {
+ return profileDir(name)
+ },
+})
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/provider.ts b/packages/dsh-tauri-panel-extension/src/host/service/provider.ts
new file mode 100644
index 00000000..d870495b
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/provider.ts
@@ -0,0 +1,52 @@
+import { existsSync } from 'node:fs'
+import { defineService } from 'dsh-tauri'
+import { getCurrentHostInstance, providerRuntime } from '../config/runtime'
+import { providerHooks } from '../events'
+import { agents } from './agents'
+import { loadFilesystemSkillPlugin } from './provider.utils'
+import { skillRoot } from './skill-root'
+
+export const provider = defineService({
+ start(packagedDir: string): Promise<void> {
+ providerRuntime.chain = providerRuntime.chain
+ .then(() => remount(packagedDir))
+ .catch((error: unknown) => {
+ void providerHooks.callHook('provider:error', error)
+ const message = error instanceof Error ? error.message : String(error)
+ getCurrentHostInstance().logger.error(`dsh-tauri-panel-extension: failed to mount filesystem skill provider: ${message}`)
+ })
+ return providerRuntime.chain
+ },
+})
+
+// --- internal ---
+
+async function remount(packagedDir: string): Promise<void> {
+ if (providerRuntime.disposed)
+ return
+ void providerHooks.callHook('provider:before-remount')
+ const host = getCurrentHostInstance()
+ const plugin = await loadFilesystemSkillPlugin(host.loader)
+ if (providerRuntime.fiber !== undefined) {
+ const old = providerRuntime.fiber
+ providerRuntime.fiber = undefined
+ try {
+ await old.dispose()
+ }
+ catch {}
+ }
+ if (providerRuntime.disposed)
+ return
+ const roots = [
+ packagedDir,
+ ...(await skillRoot.list()).flatMap(entry => entry.roots),
+ ...agents.peek(),
+ ].filter(dir => existsSync(dir))
+ try {
+ providerRuntime.fiber = host.plugin(plugin, roots.length > 0 ? { customSkillDirs: roots } : {})
+ void providerHooks.callHook('provider:after-remount', roots)
+ }
+ catch (error) {
+ void providerHooks.callHook('provider:error', error)
+ }
+}
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/provider.types.ts b/packages/dsh-tauri-panel-extension/src/host/service/provider.types.ts
new file mode 100644
index 00000000..a4ee6ac5
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/provider.types.ts
@@ -0,0 +1,19 @@
+export interface PlatformPluginLoader {
+ import: (name: string) => Promise<unknown>
+ unwrapExports: (exports: unknown) => unknown
+}
+
+export interface FilesystemSkillPlugin {
+ name: string
+ apply: (context: unknown, config?: unknown) => void
+}
+
+export interface PluginFiber {
+ dispose: () => Promise<void>
+}
+
+export interface ProviderRuntime {
+ fiber: PluginFiber | undefined
+ chain: Promise<void>
+ disposed: boolean
+}
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/provider.utils.ts b/packages/dsh-tauri-panel-extension/src/host/service/provider.utils.ts
new file mode 100644
index 00000000..bfc87ce9
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/provider.utils.ts
@@ -0,0 +1,7 @@
+import type { FilesystemSkillPlugin, PlatformPluginLoader } from './provider.types'
+
+export async function loadFilesystemSkillPlugin(loader: PlatformPluginLoader): Promise<FilesystemSkillPlugin> {
+ return loader.unwrapExports(
+ await loader.import('@deepseek-ai/dsh-skill-filesystem'),
+ ) as FilesystemSkillPlugin
+}
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/repos.ts b/packages/dsh-tauri-panel-extension/src/host/service/repos.ts
index ced36c3a..68c2e026 100644
--- a/packages/dsh-tauri-panel-extension/src/host/service/repos.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/service/repos.ts
@@ -1,204 +1,82 @@
-import type { SkillRootEntry } from '../service/skill-root'
-/**
- * Custom skill repositories the user registers from the Settings page:
- * a local directory (scanned in place, zero-copy) or a GitHub repo (tarball
- * download into the plugin's state dir, no git dependency). Detection adapts
- * to the three layouts skill collections actually use — one skill at the
- * repo root, skills as immediate children, or a nested `skills/`-style
- * folder — and registers the matching scan roots for the filesystem
- * provider.
- */
-
+import type { SkillRootEntry } from './skill-root.types'
import { Buffer } from 'node:buffer'
-import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync } from 'node:fs'
+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 { removeTree } from './rmtree.ts'
-import { createSkillRoot, findSkillRootByUrl, materialDirFor, newEntryId } from './skill-root'
-import { extractTarGz } from './tar.ts'
-
-/** One GitHub source, parsed from whatever URL shape the user pasted. */
-export interface GitHubSource {
- owner: string
- repo: string
- ref?: string
- /** `owner/repo`, the display label and dedupe key. */
- label: string
- /** Canonical browser URL exposed to the client as clickable metadata. */
- githubUrl: string
- tarballUrl: string
-}
-
-const GITHUB_URL_RE = /^(?:https?:\/\/)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(?:tree|archive)\/([^/#?]+?)(?:\.tar\.gz)?)?(?:#([^/?#]+))?(?:[/?#].*)?$/
-const GITHUB_SHORT_RE = /^([\w.-]+)\/([\w.-]+)$/
+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 { tar } from './tar'
-/** Parse a GitHub reference; returns null for anything unrecognizable. */
-export function parseGitHubSource(input: string): GitHubSource | null {
- const trimmed = input.trim()
- if (trimmed === '')
- return null
- let owner = ''
- let repo = ''
- let ref: string | undefined
- let match = GITHUB_URL_RE.exec(trimmed)
- if (match !== null) {
- // Capture order: owner, repo, /tree/<ref>, #<ref>.
- const treeRef = match[3] !== undefined ? match[3] : undefined
- const hashRef = match[4] !== undefined ? match[4] : undefined
- owner = match[1]
- repo = match[2]
- ref = treeRef ?? hashRef
- }
- else {
- match = GITHUB_SHORT_RE.exec(trimmed)
- if (match === null) {
- return null
+export const repos = defineService({
+ async create(path: string): Promise<SkillRootEntry> {
+ const resolved = resolve(path.trim().replace(/^"|"$/g, ''))
+ if (!existsSync(resolved) || !statSync(resolved).isDirectory())
+ throw new Error(`not a directory: ${resolved}`)
+ const detected = detectSkillRoots(resolved)
+ if (!detected.single && detected.roots.length === 0)
+ throw new Error('no SKILL.md found under that path (expected a skill folder or a folder of skill folders)')
+ if (detected.single) {
+ const id = newEntryId('local')
+ const material = materialDirFor(id)
+ rmtree.remove(material)
+ mkdirSync(material, { recursive: true })
+ try {
+ symlinkSync(resolved, join(material, 'skill'), process.platform === 'win32' ? 'junction' : 'dir')
+ }
+ catch {
+ 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 })
}
- ;[, owner, repo] = match
- ref = undefined
- }
- // `owner/repo/tree/<ref>` may URL-encode slashes in the ref — keep as-is;
- // codeload addresses refs by name, branches with slashes included.
- const decodedRef = ref !== undefined ? decodeURIComponent(ref) : undefined
- const label = `${owner}/${repo}`
- const encodedRef = decodedRef?.split('/').map(segment => encodeURIComponent(segment)).join('/')
- const githubUrl = `https://github.com/${owner}/${repo}${encodedRef === undefined ? '' : `/tree/${encodedRef}`}`
- const tarballUrl = `https://codeload.github.com/${owner}/${repo}/tar.gz/${decodedRef ?? 'HEAD'}`
- return { owner, repo, ref: decodedRef, label, githubUrl, tarballUrl }
-}
-
-/** Where skill layouts were found inside one checkout. */
-export interface DetectedRoots {
- /** Scan roots to register (empty + single=false means “no skills”). */
- roots: string[]
- /** The checkout itself is one skill (SKILL.md at its root). */
- single: boolean
-}
+ return skillRoot.save({ id: newEntryId('local'), kind: 'local', label: basename(resolved), path: resolved, roots: detected.roots })
+ },
-/** A plausible flat skill file: markdown with frontmatter. */
-function looksLikeSkillFile(file: string): boolean {
- try {
- return readFileSync(file, 'utf8').startsWith('---')
- }
- catch {
- return false
- }
-}
-
-/** Does one directory directly hold skills (bundle children or flat .md)? */
-function holdsSkills(dir: string): boolean {
- let entries: string[]
- try {
- entries = readdirSync(dir)
- }
- catch {
- return false
- }
- if (existsSync(join(dir, 'SKILL.md')))
- return true
- for (const name of entries) {
- if (name.endsWith('.md') && looksLikeSkillFile(join(dir, name)))
- return true
- }
- for (const name of entries) {
- const child = join(dir, name)
- try {
- if (statSync(child).isDirectory() && existsSync(join(child, 'SKILL.md')))
- return true
- }
- catch {
- // racing deletion or unreadable entry: ignore
- }
- }
- return false
-}
+ async import(url: string): Promise<SkillRootEntry> {
+ 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)
+ if (existing !== null)
+ throw new Error(`${source.label} is already registered`)
-/**
- * Find the scan roots for one checkout: the checkout itself when its
- * immediate children are skills, plus any child directory that only makes
- * sense as a collection wrapper (`skills/`, `document-skills/`, …). A
- * checkout with SKILL.md at its own root is one single skill — the caller
- * must give the provider its PARENT as the scan root.
- */
-export function detectSkillRoots(checkout: string): DetectedRoots {
- if (existsSync(join(checkout, 'SKILL.md')))
- return { roots: [], single: true }
- const roots: string[] = []
- if (holdsSkills(checkout))
- roots.push(checkout)
- let entries: string[]
- try {
- entries = readdirSync(checkout)
- }
- catch {
- return { roots, single: false }
- }
- for (const name of entries) {
- if (name.startsWith('.'))
- continue
- const child = join(checkout, name)
- try {
- if (!statSync(child).isDirectory())
- continue
- }
- catch {
- continue
- }
- if (existsSync(join(child, 'SKILL.md')))
- continue // already covered by the parent root
- if (holdsSkills(child))
- roots.push(child)
- }
- return { roots, single: false }
-}
+ const archive = Buffer.from(await downloadTarball(source.tarballUrl))
+ if (archive.byteLength > TARBALL_MAX_BYTES)
+ throw new Error('repository tarball too large')
-/** Register a local directory as a skill repository. */
-export async function addLocalRepo(path: string): Promise<SkillRootEntry> {
- const resolved = resolve(path.trim().replace(/^"|"$/g, ''))
- if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {
- throw new Error(`not a directory: ${resolved}`)
- }
- const detected = detectSkillRoots(resolved)
- if (!detected.single && detected.roots.length === 0) {
- throw new Error('no SKILL.md found under that path (expected a skill folder or a folder of skill folders)')
- }
- if (detected.single) {
- // One skill living at the given path: the provider scans a ROOT, so wrap
- // the path in a dedicated directory holding a single link to it.
- const id = newEntryId('local')
+ const id = newEntryId('git')
const material = materialDirFor(id)
- removeTree(material)
- mkdirSync(material, { recursive: true })
+ rmtree.remove(material)
+ const checkout = join(material, 'repo')
try {
- symlinkSync(resolved, join(material, 'skill'), process.platform === 'win32' ? 'junction' : 'dir')
+ mkdirSync(checkout, { recursive: true })
+ tar.save(archive, checkout, { stripComponents: 1 })
+ const detected = detectSkillRoots(checkout)
+ 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(
+ { id, kind: 'git', label: source.label, url: source.githubUrl, ref: source.ref, roots, materialDir: material },
+ )
}
- catch {
- removeTree(material)
- throw new Error('single-skill local folders need a directory link; try adding their parent folder instead')
+ catch (error) {
+ rmtree.remove(material)
+ throw error
}
- return createSkillRoot({ id, kind: 'local', label: basename(resolved), path: resolved, roots: [material], materialDir: material })
- }
- return createSkillRoot({ id: newEntryId('local'), kind: 'local', label: basename(resolved), path: resolved, roots: detected.roots })
-}
+ },
+})
-/** Download cap for a repo tarball. */
-const TARBALL_MAX_BYTES = 256 * 1024 * 1024
+// --- internal ---
-/**
- * 下载仓库 tarball(二进制):默认走 ofetch(timeout 60s、关闭重试、错误信息本地化);
- * 传入 fetcher(测试注入原生 fetch)时保持原生语义,二者都返回 ArrayBuffer。
- */
-async function downloadTarball(url: string, fetcher?: typeof fetch): Promise<ArrayBuffer> {
- if (fetcher) {
- const response = await fetcher(url, { signal: AbortSignal.timeout(60_000) })
- if (!response.ok)
- throw new Error(`download failed (HTTP ${response.status}) for ${url}`)
- return response.arrayBuffer()
- }
+async function downloadTarball(url: string): Promise<ArrayBuffer> {
const response = await $fetch.raw(url, {
responseType: 'arrayBuffer',
- timeout: 60_000,
+ timeout: GITHUB_FETCH_TIMEOUT_MS,
retry: 0,
onResponseError: ({ response }) => {
throw new Error(`download failed (HTTP ${response.status}) for ${url}`)
@@ -206,53 +84,3 @@ async function downloadTarball(url: string, fetcher?: typeof fetch): Promise<Arr
})
return response._data as ArrayBuffer
}
-
-/** Register a GitHub repo: tarball download → extract → detect → persist. */
-export async function addGitRepo(
- url: string,
- options: { fetcher?: typeof fetch } = {},
-): Promise<SkillRootEntry> {
- const source = parseGitHubSource(url)
- if (source === null)
- throw new Error('expected a GitHub repository URL or owner/repo')
- const existing = await findSkillRootByUrl(source.githubUrl) ?? await findSkillRootByUrl(source.label)
- if (existing !== undefined)
- throw new Error(`${source.label} is already registered`)
-
- const archive = Buffer.from(await downloadTarball(source.tarballUrl, options.fetcher))
- if (archive.byteLength > TARBALL_MAX_BYTES)
- throw new Error('repository tarball too large')
-
- const id = newEntryId('git')
- const material = materialDirFor(id)
- removeTree(material)
- const checkout = join(material, 'repo')
- try {
- mkdirSync(checkout, { recursive: true })
- extractTarGz(archive, checkout, { stripComponents: 1 })
- const detected = detectSkillRoots(checkout)
- if (!detected.single && detected.roots.length === 0) {
- throw new Error('no SKILL.md found in that repository')
- }
- // A single-skill repo is discovered through the material dir itself; a
- // collection registers the checkout (plus nested collection wrappers).
- const roots = detected.single ? [material] : detected.roots
- return createSkillRoot(
- { id, kind: 'git', label: source.label, url: source.githubUrl, ref: source.ref, roots, materialDir: material },
- )
- }
- catch (error) {
- removeTree(material)
- throw error
- }
-}
-
-/** Validate one scan root still exists; entries can go stale on disk. */
-export function rootExists(path: string): boolean {
- try {
- return statSync(path).isDirectory()
- }
- catch {
- return false
- }
-}
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/repos.types.ts b/packages/dsh-tauri-panel-extension/src/host/service/repos.types.ts
new file mode 100644
index 00000000..2aef0877
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/repos.types.ts
@@ -0,0 +1,13 @@
+export interface GitHubSource {
+ owner: string
+ repo: string
+ ref?: string
+ label: string
+ githubUrl: string
+ tarballUrl: string
+}
+
+export interface DetectedRoots {
+ roots: string[]
+ single: boolean
+}
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.ts
new file mode 100644
index 00000000..da1f06c5
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/repos.utils.ts
@@ -0,0 +1,109 @@
+import type { DetectedRoots, GitHubSource } from './repos.types'
+import type { SkillRootEntry } from './skill-root.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'
+
+export function parseGitHubSource(input: string): GitHubSource | null {
+ const trimmed = input.trim()
+ if (trimmed === '')
+ return null
+ let owner = ''
+ let repo = ''
+ let ref: string | undefined
+ let match = GITHUB_URL_RE.exec(trimmed)
+ if (match !== null) {
+ owner = match[1]
+ repo = match[2]
+ ref = match[3] ?? match[4]
+ }
+ else {
+ match = GITHUB_SHORT_RE.exec(trimmed)
+ if (match === null) {
+ return null
+ }
+ ;[, owner, repo] = match
+ ref = undefined
+ }
+ const decodedRef = ref !== undefined ? decodeURIComponent(ref) : undefined
+ const label = `${owner}/${repo}`
+ const encodedRef = decodedRef?.split('/').map(segment => encodeURIComponent(segment)).join('/')
+ const githubUrl = `https://github.com/${owner}/${repo}${encodedRef === undefined ? '' : `/tree/${encodedRef}`}`
+ const tarballUrl = `https://codeload.github.com/${owner}/${repo}/tar.gz/${decodedRef ?? 'HEAD'}`
+ return { owner, repo, ref: decodedRef, label, githubUrl, tarballUrl }
+}
+
+export function detectSkillRoots(checkout: string): DetectedRoots {
+ if (existsSync(join(checkout, SKILL_FILE_NAME)))
+ return { roots: [], single: true }
+ const roots: string[] = []
+ if (holdsSkills(checkout))
+ roots.push(checkout)
+ let entries: string[]
+ try {
+ entries = readdirSync(checkout)
+ }
+ catch {
+ return { roots, single: false }
+ }
+ for (const name of entries) {
+ if (name.startsWith('.'))
+ continue
+ const child = join(checkout, name)
+ try {
+ if (!statSync(child).isDirectory())
+ continue
+ }
+ catch {
+ continue
+ }
+ if (existsSync(join(child, SKILL_FILE_NAME)))
+ continue
+ if (holdsSkills(child))
+ roots.push(child)
+ }
+ return { roots, single: false }
+}
+
+export function newEntryId(kind: SkillRootEntry['kind']): string {
+ return `${kind}-${randomBytes(4).toString('hex')}`
+}
+
+// --- internal ---
+
+function looksLikeSkillFile(file: string): boolean {
+ try {
+ return readFileSync(file, 'utf8').startsWith('---')
+ }
+ catch {
+ return false
+ }
+}
+
+function holdsSkills(dir: string): boolean {
+ let entries: string[]
+ try {
+ entries = readdirSync(dir)
+ }
+ catch {
+ return false
+ }
+ if (existsSync(join(dir, SKILL_FILE_NAME)))
+ return true
+ for (const name of entries) {
+ if (name.endsWith('.md') && looksLikeSkillFile(join(dir, name)))
+ return true
+ }
+ for (const name of entries) {
+ const child = join(dir, name)
+ try {
+ if (statSync(child).isDirectory() && existsSync(join(child, SKILL_FILE_NAME)))
+ return true
+ }
+ catch {
+ continue
+ }
+ }
+ return false
+}
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/restart.ts b/packages/dsh-tauri-panel-extension/src/host/service/restart.ts
index 41555921..79975e47 100644
--- a/packages/dsh-tauri-panel-extension/src/host/service/restart.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/service/restart.ts
@@ -1,58 +1,40 @@
-/**
- * Self-restart for standalone `dsh web`: relaunch the exact invocation that
- * booted this host, then stop this process — so MCP row changes compose
- * without leaving the UI. The desktop shell owns restarts there
- * (DSH_DESKTOP=1 refuses this path — a supervised sidecar must never
- * replace itself, or the supervisor respawns a second process).
- *
- * The replacement is spawned directly with windowsHide: CREATE_NO_WINDOW
- * gives it a hidden console its own console children inherit (no popping
- * windows), unlike a DETACHED_PROCESS spawn which leaves children to create
- * visible consoles. No helper process and no powershell wrapper — on at
- * least one machine a node→node→powershell→node chain was silently blocked
- * by host software before the inner node could even start, while direct
- * node→node spawns are the most battle-tested pattern there is.
- */
-
+import type { RestartOutcome } from './restart.types'
import { spawn } from 'node:child_process'
import { openSync } from 'node:fs'
import { tmpdir } from 'node:os'
import process from 'node:process'
+import { defineService } from 'dsh-tauri'
import { dirname, resolve } from 'pathe'
+import { PLUGIN_NAME } from '../../shared/constants'
+import { RESTART_KILL_DELAY_MS } from '../config/constants'
+
+export const restart = defineService({
+ start(): RestartOutcome {
+ if (restartOwnedByShell())
+ return { owned: true }
+ return { owned: false, ...scheduleRestart(dshLaunch()) }
+ },
+})
+
+// --- internal ---
-/** The boot invocation to replay: entry from argv, execArgv preserved. */
-export function dshLaunch(argv: readonly string[] = process.argv, execArgv: readonly string[] = process.execArgv): {
- file: string
- args: string[]
- cwd: string | undefined
- viaShell: boolean
-} {
+function dshLaunch(
+ argv: readonly string[] = process.argv,
+ execArgv: readonly string[] = process.execArgv,
+): { file: string, args: string[], cwd: string | undefined, viaShell: boolean } {
const entry = argv[1]
if (entry !== undefined && /[\\/](?:bin\.(?:js|ts)|dsh)$/.test(entry)) {
- // Source launches (`pnpm dsh`) pass a relative entry that the child would
- // resolve against its OWN cwd — absolutize, and keep cwd near the entry
- // so execArgv module hooks (tsx/esm) stay resolvable.
const abs = resolve(entry)
return { file: process.execPath, args: [...execArgv, abs, ...argv.slice(2)], cwd: dirname(abs), viaShell: false }
}
- // Bare `dsh` on Windows is a .cmd shim only a shell can start.
return { file: 'dsh', args: [...argv.slice(2)], cwd: undefined, viaShell: process.platform === 'win32' }
}
-/**
- * Relaunch this exact dsh invocation, then stop this process. The replacement
- * boots slowly (module loading) while this process dies within 500 ms, so
- * port handover needs no delay even for fixed-port launches. Replacement
- * output is logged under tmpdir for post-mortem.
- */
-export function scheduleRestart(launch: ReturnType<typeof dshLaunch>): {
- pid: number
- replacementPid: number | undefined
- logOut: string
- logErr: string
-} {
+function scheduleRestart(
+ launch: ReturnType<typeof dshLaunch>,
+): { pid: number, replacementPid: number | undefined, logOut: string } {
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
- const logOut = `${tmpdir()}${tmpdir().endsWith('/') ? '' : '\\'}dsh-tauri-panel-extension-restart-${stamp}.out.log`
+ const logOut = `${tmpdir()}${tmpdir().endsWith('/') ? '' : '\\'}${PLUGIN_NAME}-restart-${stamp}.out.log`
const logErr = logOut.replace('.out.log', '.err.log')
const child = spawn(launch.file, launch.args, {
cwd: launch.cwd,
@@ -62,13 +44,10 @@ export function scheduleRestart(launch: ReturnType<typeof dshLaunch>): {
windowsHide: true,
})
child.unref()
- setTimeout(() => process.kill(process.pid, 'SIGTERM'), 500)
- return { pid: process.pid, replacementPid: child.pid, logOut, logErr }
+ setTimeout(() => process.kill(process.pid, 'SIGTERM'), RESTART_KILL_DELAY_MS)
+ return { pid: process.pid, replacementPid: child.pid, logOut }
}
-/**
- * Restart ownership: the desktop shell supervises the sidecar and restarts it.
- */
-export function restartOwnedByShell(env: NodeJS.ProcessEnv = process.env): boolean {
+function restartOwnedByShell(env: NodeJS.ProcessEnv = process.env): boolean {
return env.DSH_DESKTOP === '1'
}
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/restart.types.ts b/packages/dsh-tauri-panel-extension/src/host/service/restart.types.ts
new file mode 100644
index 00000000..e317f4c8
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/restart.types.ts
@@ -0,0 +1,3 @@
+export type RestartOutcome
+ = | { owned: true }
+ | { owned: false, pid: number, replacementPid: number | undefined, logOut: string }
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/rmtree.ts b/packages/dsh-tauri-panel-extension/src/host/service/rmtree.ts
index 4c4d562c..fc33ffa3 100644
--- a/packages/dsh-tauri-panel-extension/src/host/service/rmtree.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/service/rmtree.ts
@@ -1,18 +1,20 @@
-/**
- * Windows-hardened recursive delete for repository material. The skill
- * provider watches these trees live, and antivirus or search indexers
- * briefly hold handles onto freshly written files, so a plain rmSync
- * races open handles and dies with EPERM. Two mitigations: clear the
- * read-only attribute first (unlinking a read-only entry fails on
- * Windows), then retry the removal so short-lived locks run out.
- */
-
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'
+
+export const rmtree = defineService({
+ remove(path: string): void {
+ try {
+ clearReadOnly(path)
+ }
+ catch {}
+ rmSync(path, { recursive: true, force: true, ...RMTREE_RETRIES })
+ },
+})
-/** Windows lock holders usually let go within a second or two. */
-const RETRIES = { maxRetries: 10, retryDelay: 200 } as const
+// --- internal ---
function clearReadOnly(dir: string): void {
let entries: Dirent[]
@@ -20,46 +22,26 @@ function clearReadOnly(dir: string): void {
entries = readdirSync(dir, { withFileTypes: true })
}
catch {
- return // unreadable: rmSync will surface the real error
+ return
}
for (const entry of entries) {
const child = join(dir, entry.name)
- // Links read as neither file nor directory here; chmod would hit the
- // link TARGET (possibly the user's own folder), so they are skipped —
- // rmSync removes the link itself without following it.
if (entry.isDirectory()) {
try {
chmodSync(child, 0o777)
}
- catch {
- /* racing delete */
- }
+ catch {}
clearReadOnly(child)
}
else if (entry.isFile()) {
try {
chmodSync(child, 0o666)
}
- catch {
- /* racing delete */
- }
+ catch {}
}
}
try {
chmodSync(dir, 0o777)
}
- catch {
- /* racing delete */
- }
-}
-
-/** Delete one directory tree (or lone file), tolerating Windows lock races. */
-export function removeTree(path: string): void {
- try {
- clearReadOnly(path)
- }
- catch {
- // walk failure: rmSync reports the underlying error anyway
- }
- rmSync(path, { recursive: true, force: true, ...RETRIES })
+ catch {}
}
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.ts
index 73c5780c..bc00797a 100644
--- a/packages/dsh-tauri-panel-extension/src/host/service/skill-catalog.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/service/skill-catalog.ts
@@ -1,49 +1,37 @@
-/**
- * host/service/skill-catalog.ts — 技能目录投影(领域逻辑,不是请求级助手)。
- *
- * 把宿主 skills 注册表报告的 SkillSummary 投影成设置页看到的行:附加可编辑/
- * 可删除判定、磁盘目录与所属仓库元数据;并提供注册仓库的行视图。路由处理器
- * 只做「读参 → 调本文件 → 组织响应」,不在此重复状态码与响应形状。
- */
-
-import type { HostSkill, PanelExtensionHost, SkillRepositoryMetadata } from '../types'
-import type { SkillRootEntry } from './skill-root'
+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 { rootExists } from './repos'
-import { getSkillRoots, skillsRootDir } from './skill-root'
+import { getCurrentHostInstance } from '../config/runtime'
+import { skillsDataDir } from '../utils/paths.utils'
+import { skillRoot } from './skill-root'
-/** One catalog skill as the browser sees it (edit flags and repository metadata added). */
-export type SkillRow = HostSkill & {
- editable: boolean
- removable: boolean
- dir?: string
- policyEditable: boolean
- /** Registered root containing this skill, if any. */
- repository?: SkillRepositoryMetadata
-}
+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'])
+ },
-/** One registered repository plus a liveness flag (roots can go stale). */
-export function toRootView(entry: SkillRootEntry): SkillRootEntry & { live: boolean } {
- return { ...entry, live: entry.roots.every(root => rootExists(root)) }
-}
+ async peek(name: string): Promise<HostSkillDefinition | null> {
+ return (await getCurrentHostInstance().skills.get(name)) ?? null
+ },
+})
+
+// --- internal ---
-/**
- * A 'custom' skill is writable only when its folder sits inside a root this
- * plugin manages: the materialized repositories under the plugin state dir,
- * or a registered local root. Vendored skills shipped inside the plugin
- * package (under node_modules) are custom-sourced too but stay read-only —
- * edits there would die with the next plugin update.
- */
async function customSkillWritable(dir: string): Promise<boolean> {
- const state = skillsRootDir()
+ const state = skillsDataDir()
if (dir === state || dir.startsWith(state + sep))
return true
- return (await getSkillRoots()).some(entry =>
+ return (await skillRoot.list()).some(entry =>
entry.roots.some(root => dir === root || dir.startsWith(root + sep)))
}
-/** Whether the save route may write this catalog row back to disk. */
-export async function skillWritable(skill: HostSkill, dir: string | undefined): Promise<boolean> {
+async function skillWritable(skill: HostSkill, dir: string | undefined): Promise<boolean> {
if (dir === undefined)
return false
if (skill.source === 'user-dsh')
@@ -58,7 +46,6 @@ function pathWithin(path: string, parent: string): boolean {
return nested === '' || (!nested.startsWith(`..${sep}`) && nested !== '..' && !isAbsolute(nested))
}
-/** Match a catalog row to the registered root that contributed its directory. */
function repositoryForSkill(
skill: HostSkill,
entries: SkillRootEntry[],
@@ -89,17 +76,3 @@ async function toSkillRow(skill: HostSkill, entries: SkillRootEntry[]): Promise<
...(repository !== undefined ? { repository } : {}),
}
}
-
-/** Repository skills are first; groups retain the registry's stable order. */
-function sortSkillRows(rows: SkillRow[]): SkillRow[] {
- return rows.map((row, index) => ({ row, index }))
- .sort((left, right) => Number(right.row.repository !== undefined) - Number(left.row.repository !== undefined) || left.index - right.index)
- .map(item => item.row)
-}
-
-/** Collect the current catalog from the registry and shape it into rows. */
-export async function listSkillRows(host: PanelExtensionHost): Promise<SkillRow[]> {
- const skills = await host.skills.list()
- const entries = await getSkillRoots()
- return sortSkillRows(await Promise.all(skills.map(skill => toSkillRow(skill, entries))))
-}
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.ts
new file mode 100644
index 00000000..7e81ee37
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/skill-catalog.types.ts
@@ -0,0 +1,16 @@
+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.ts
new file mode 100644
index 00000000..44fc2fca
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/skill-catalog.utils.ts
@@ -0,0 +1,6 @@
+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.ts
new file mode 100644
index 00000000..73ebf339
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/skill-policy.ts
@@ -0,0 +1,9 @@
+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.ts
index efc5ec47..f4226c44 100644
--- a/packages/dsh-tauri-panel-extension/src/host/service/skill-root.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/service/skill-root.ts
@@ -1,99 +1,52 @@
-/**
- * host/service/skill-root.ts — 用户注册的自定义技能仓库领域原语(skills 功能目录)。
- *
- * 状态文档:`$DSH_HOME/skills/state.json`(skillRoots 数组)。create / delete /
- * get 原语;写走 storage.setItem(原子写),读走 storage.getItem。
- */
-
-import { randomBytes } from 'node:crypto'
-import { DSH_HOME } from 'dsh-tauri'
-import { join } from 'pathe'
+import type { PluginState, SkillRootEntry } from './skill-root.types'
+import { defineService } from 'dsh-tauri'
+import { STATE_FILE_NAME } from '../config/constants'
import { storage } from '../storage'
-/** One user-registered custom skill repository. */
-export interface SkillRootEntry {
- /** Stable id (used by the remove route and directory names). */
- id: string
- /** `local` — a path on this machine; `git` — extracted from a GitHub URL. */
- kind: 'local' | 'git'
- /** Display label (repo `owner/name` or the local path's basename). */
- label: string
- /** The source URL (git entries). */
- url?: string
- /** Branch/tag/ref the tarball was pulled from (git entries). */
- ref?: string
- /** Local path the user pointed at (local entries). */
- path?: string
- /** Scan roots this entry contributes (single-skill repos get a wrapper dir). */
- roots: string[]
- /** Where this entry's downloaded/junctioned material lives, if any. */
- materialDir?: string
- addedAt: number
+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)
}
-/** On-disk state document. */
-export interface PluginState {
- skillRoots: SkillRootEntry[]
+async function writeAll(skillRoots: SkillRootEntry[]): Promise<void> {
+ await storage.setItem(STATE_FILE_NAME, `${JSON.stringify({ skillRoots }, null, 2)}\n`)
}
-const STATE_KEY = 'state.json'
-
-/** skills 功能目录的绝对路径(material 落盘与只读判定用,与 storage base 一致)。 */
-export function skillsRootDir(): string {
- return join(DSH_HOME, 'skills')
-}
-
-/** 校验磁盘状态里的一条 entry(历史文档可能被手改成任意形状)。 */
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)
}
-
-/** 读取全部注册的自定义技能仓库。 */
-export async function getSkillRoots(): Promise<SkillRootEntry[]> {
- const parsed = await storage.getItem<Partial<PluginState>>(STATE_KEY)
- if (!Array.isArray(parsed?.skillRoots))
- return []
- return parsed.skillRoots.filter(isSkillRootEntry)
-}
-
-/** 按 GitHub 源 URL 查找已注册仓库(含 legacy labels)。 */
-export async function findSkillRootByUrl(url: string): Promise<SkillRootEntry | undefined> {
- return (await getSkillRoots()).find(entry => entry.url === url)
-}
-
-/** 新增唯一 entry id。 */
-export function newEntryId(kind: 'local' | 'git'): string {
- return `${kind}-${randomBytes(4).toString('hex')}`
-}
-
-/** 某 entry 的下载物目录(git 提取、junction 包装)。 */
-export function materialDirFor(entryId: string): string {
- return join(skillsRootDir(), 'repos', entryId)
-}
-
-/** 追加一个 entry 并持久化。返回存储的 entry。 */
-export async function createSkillRoot(entry: Omit<SkillRootEntry, 'addedAt'>): Promise<SkillRootEntry> {
- const skillRoots = await getSkillRoots()
- const stored: SkillRootEntry = { ...entry, addedAt: Date.now() }
- skillRoots.push(stored)
- await storage.setItem(STATE_KEY, `${JSON.stringify({ skillRoots }, null, 2)}\n`)
- return stored
-}
-
-/**
- * 注销一个 entry 并持久化。material 目录不在此删除:provider 仍在 watch 它,
- * 删除被 watch 的树在 Windows 上会 EPERM。调用方先 remountProvider,再用返回的
- * entry.materialDir 清树。返回被移除的 entry;id 未知返回 undefined。
- */
-export async function deleteSkillRoot(id: string): Promise<SkillRootEntry | undefined> {
- const skillRoots = await getSkillRoots()
- const at = skillRoots.findIndex(entry => entry.id === id)
- if (at === -1)
- return undefined
- const [removed] = skillRoots.splice(at, 1)
- await storage.setItem(STATE_KEY, `${JSON.stringify({ skillRoots }, null, 2)}\n`)
- return removed
-}
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.ts
new file mode 100644
index 00000000..ca70bf8f
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/skill-root.types.ts
@@ -0,0 +1,17 @@
+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.ts
index 1949e8fa..f098ed61 100644
--- a/packages/dsh-tauri-panel-extension/src/host/service/skills.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/service/skills.ts
@@ -1,141 +1,29 @@
-/**
- * Skill catalog plumbing: frontmatter serialization for user-root SKILL.md
- * files plus create/update/delete against `$DSH_HOME/skills`. Discovery is the
- * host's business — the filesystem provider watches the directory, so writes
- * land in the catalog without any restart.
- */
-
+import type { SkillInput } from './skills.types'
import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
-import { DSH_HOME } from 'dsh-tauri'
-import { join } from 'pathe'
-
-/** Host skill name grammar (dsh-skill's SKILL_NAME). */
-export const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
-
-/** One skill write request from the browser. */
-export interface SkillInput {
- name: string
- description: string
- whenToUse?: string
- modelInvocable: boolean
- userInvocable: boolean
- content: string
-}
-
-/** The user-owned skill root this plugin writes into (provider rank 400). */
-export function userSkillsDir(): string {
- return join(DSH_HOME, 'skills')
-}
-
-/** YAML double-quoted scalar (JSON string syntax is valid YAML 1.2). */
-function quote(value: string): string {
- return JSON.stringify(value)
-}
-
-/** Frontmatter + body for one skill file. Policy keys only when non-default. */
-export function serializeSkill(input: SkillInput): string {
- const lines = [
- `name: ${input.name}`,
- `description: ${quote(input.description)}`,
- ]
- if (input.whenToUse !== undefined && input.whenToUse !== '')
- lines.push(`whenToUse: ${quote(input.whenToUse)}`)
- if (!input.modelInvocable)
- lines.push('disable-model-invocation: true')
- if (!input.userInvocable)
- lines.push('user-invocable: false')
- const body = input.content.replace(/\r\n/g, '\n').trim()
- return `---\n${lines.join('\n')}\n---\n\n${body}\n`
-}
-
-/** Validate one write request; returns the rejection reason or null. */
-export function validateSkillInput(input: SkillInput): string | null {
- if (!SKILL_NAME_RE.test(input.name))
- return 'name must be kebab-case (a-z, 0-9, dashes)'
- if (input.description.trim() === '')
- return 'description is required'
- if (input.description.length > 1024)
- return 'description too long (max 1024)'
- if (input.whenToUse !== undefined && input.whenToUse.length > 2048)
- return 'whenToUse too long (max 2048)'
- if (input.content.length > 256 * 1024)
- return 'content too large (max 256 KiB)'
- return null
-}
-
-/** Directory holding one user skill's SKILL.md; name grammar blocks traversal. */
-function skillDir(name: string): string {
- return join(userSkillsDir(), name)
-}
-
-/** Create or update a user skill. Returns the written path. */
-export function writeSkill(input: SkillInput): string {
- const dir = skillDir(input.name)
- mkdirSync(dir, { recursive: true })
- const file = join(dir, 'SKILL.md')
- writeFileSync(file, serializeSkill(input), 'utf8')
- return file
-}
-
-/** Delete a user skill directory. Returns false when it does not exist. */
-export function deleteSkill(name: string): boolean {
- if (!SKILL_NAME_RE.test(name))
- return false
- const dir = skillDir(name)
- if (!existsSync(dir) || !statSync(dir).isDirectory())
- return false
- // Only ever remove the exact directory this name resolves to under the
- // skills root; the regex already pins it to one safe path segment.
- rmSync(dir, { recursive: true, force: true })
- return true
-}
-
-/**
- * Flip one skill file's load policy by editing only the two invocation keys
- * in its frontmatter — `disable-model-invocation: true` plus
- * `user-invocable: false` together take the skill out of both the model and
- * the human catalogs on every standard-provider surface; enabling removes
- * both keys (defaults permit both surfaces). Works on any file-backed skill
- * (user, project, agent, bundled, custom); the rest of the file, including
- * custom keys, ordering, and body, survives byte-for-byte.
- */
-export function setSkillPolicy(file: string, enabled: boolean): void {
- const text = readFileSync(file, 'utf8')
- const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)
- if (match === null)
- throw new Error('skill file has no frontmatter block')
- const newline = text.includes('\r\n---') ? '\r\n' : '\n'
- const body = text.slice(match[0].length)
- const lines = match[1].split(/\r?\n/)
- const kept = lines.filter(line => !/^(?:disable-model-invocation|user-invocable):/.test(line))
- if (!enabled)
- kept.push('disable-model-invocation: true', 'user-invocable: false')
- writeFileSync(file, `---${newline}${kept.join(newline)}${newline}---${body}`, 'utf8')
-}
-
-/**
- * Edit an existing skill file in place — for skills that do not live in the
- * user root (registered custom repositories). Only the keys the editor owns
- * (name, description, whenToUse, the two invocation flags) are rewritten;
- * every other frontmatter key — license, allowed-tools, anything a
- * repository ships — survives in order, like setSkillPolicy. The body is
- * replaced by the editor's content.
- */
-export function updateSkillFile(file: string, input: SkillInput): void {
- const text = readFileSync(file, 'utf8')
- const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)
- if (match === null)
- throw new Error('skill file has no frontmatter block')
- const newline = text.includes('\r\n---') ? '\r\n' : '\n'
- const lines = match[1].split(/\r?\n/)
- const kept = lines.filter(line => !/^(?:name|description|whenToUse|disable-model-invocation|user-invocable):/.test(line))
- const head = [`name: ${input.name}`, `description: ${quote(input.description)}`]
- if (input.whenToUse !== undefined && input.whenToUse !== '')
- head.push(`whenToUse: ${quote(input.whenToUse)}`)
- if (!input.modelInvocable)
- kept.push('disable-model-invocation: true')
- if (!input.userInvocable)
- kept.push('user-invocable: false')
- const body = input.content.replace(/\r\n/g, '\n').trim()
- writeFileSync(file, `---${newline}${[...head, ...kept].join(newline)}${newline}---${newline}${newline}${body}${newline}`, 'utf8')
-}
+import { defineService } from 'dsh-tauri'
+import { SKILL_NAME_RE } from '../config/constants'
+import { skillDir, skillFilePath } from '../utils/paths.utils'
+import { rewriteSkillContent, serializeSkill } from './skills.utils'
+
+export const skills = defineService({
+ save(input: SkillInput, file?: string): string {
+ if (file !== undefined) {
+ writeFileSync(file, rewriteSkillContent(readFileSync(file, 'utf8'), input), 'utf8')
+ return file
+ }
+ const target = skillFilePath(input.name)
+ mkdirSync(skillDir(input.name), { recursive: true })
+ writeFileSync(target, serializeSkill(input), 'utf8')
+ return target
+ },
+
+ remove(name: string): boolean {
+ if (!SKILL_NAME_RE.test(name))
+ return false
+ const dir = skillDir(name)
+ if (!existsSync(dir) || !statSync(dir).isDirectory())
+ return false
+ rmSync(dir, { recursive: true, force: true })
+ return true
+ },
+})
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.ts
new file mode 100644
index 00000000..b8cb687d
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/skills.types.ts
@@ -0,0 +1,30 @@
+export interface HostSkill {
+ readonly name: string
+ readonly description: string
+ readonly whenToUse?: string
+ readonly invocation: { modelInvocable: boolean, userInvocable: boolean }
+ readonly source: string
+ readonly provider: string
+ readonly resourceBase?: { kind: 'directory', path: string } | { kind: 'url', url: string } | { kind: 'opaque', description: string }
+}
+
+export interface HostSkillDefinition {
+ readonly name: string
+ readonly content: string
+ readonly path?: string
+ readonly resourceBase?: HostSkill['resourceBase']
+}
+
+export interface SkillsService {
+ list: (options?: { cwd?: string }) => Promise<HostSkill[]>
+ get: (name: string, options?: { cwd?: string }) => Promise<HostSkillDefinition | undefined>
+}
+
+export interface SkillInput {
+ name: string
+ description: string
+ whenToUse?: string
+ modelInvocable: boolean
+ userInvocable: boolean
+ content: string
+}
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.ts
new file mode 100644
index 00000000..d8330479
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/skills.utils.ts
@@ -0,0 +1,72 @@
+import type { SkillInput } 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'
+
+export function serializeSkill(input: SkillInput): string {
+ const lines = [
+ `name: ${input.name}`,
+ `description: ${JSON.stringify(input.description)}`,
+ ]
+ if (!isEmpty(input.whenToUse))
+ lines.push(`whenToUse: ${JSON.stringify(input.whenToUse)}`)
+ if (!input.modelInvocable)
+ lines.push('disable-model-invocation: true')
+ if (!input.userInvocable)
+ lines.push('user-invocable: false')
+ const body = input.content.replace(/\r\n/g, '\n').trim()
+ return `---\n${lines.join('\n')}\n---\n\n${body}\n`
+}
+
+export function validateSkillInput(input: SkillInput): string | null {
+ if (!SKILL_NAME_RE.test(input.name))
+ return 'name must be kebab-case (a-z, 0-9, dashes)'
+ if (input.description.trim() === '')
+ return 'description is required'
+ if (input.description.length > SKILL_DESCRIPTION_MAX_LENGTH)
+ return `description too long (max ${SKILL_DESCRIPTION_MAX_LENGTH})`
+ if ((input.whenToUse?.length ?? 0) > SKILL_WHEN_TO_USE_MAX_LENGTH)
+ return `whenToUse too long (max ${SKILL_WHEN_TO_USE_MAX_LENGTH})`
+ if (input.content.length > SKILL_CONTENT_MAX_BYTES)
+ return 'content too large (max 256 KiB)'
+ return null
+}
+
+export function rewriteSkillContent(text: string, input: SkillInput): string {
+ const { newline, lines } = frontmatterOf(text)
+ const kept = lines.filter(line => !/^(?:name|description|whenToUse|disable-model-invocation|user-invocable):/.test(line))
+ const head = [`name: ${input.name}`, `description: ${JSON.stringify(input.description)}`]
+ if (!isEmpty(input.whenToUse))
+ head.push(`whenToUse: ${JSON.stringify(input.whenToUse)}`)
+ if (!input.modelInvocable)
+ kept.push('disable-model-invocation: true')
+ if (!input.userInvocable)
+ kept.push('user-invocable: false')
+ const body = input.content.replace(/\r\n/g, '\n').trim()
+ return `---${newline}${[...head, ...kept].join(newline)}${newline}---${newline}${newline}${body}${newline}`
+}
+
+export function rewriteSkillPolicy(text: string, enabled: boolean): string {
+ const { newline, lines, body } = frontmatterOf(text)
+ const kept = lines.filter(line => !/^(?:disable-model-invocation|user-invocable):/.test(line))
+ if (!enabled)
+ kept.push('disable-model-invocation: true', 'user-invocable: false')
+ return `---${newline}${kept.join(newline)}${newline}---${body}`
+}
+
+// --- internal ---
+
+function frontmatterOf(text: string): { newline: string, lines: string[], body: string } {
+ const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)
+ if (match === null)
+ throw new Error('skill file has no frontmatter block')
+ return {
+ newline: text.includes('\r\n---') ? '\r\n' : '\n',
+ lines: match[1].split(/\r?\n/),
+ body: text.slice(match[0].length),
+ }
+}
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/tar.ts b/packages/dsh-tauri-panel-extension/src/host/service/tar.ts
index b7dfbd86..63af40b3 100644
--- a/packages/dsh-tauri-panel-extension/src/host/service/tar.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/service/tar.ts
@@ -1,25 +1,79 @@
import type { Buffer } from 'node:buffer'
-/**
- * Minimal pure-JS tar.gz extraction (node zlib + a USTAR/GNU/PAX-path
- * reader). GitHub codeload tarballs are all we ever unpack — regular files
- * and directories, no links — so unsupported entry types are skipped rather
- * than rejected, and every name is checked against escape before it touches
- * the filesystem. No subprocess: the dsh sidecar must not spawn tar.
- */
-
+import type { ExtractOptions, TarHeader } from './tar.types'
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'
+
+export const tar = defineService({
+ save(archive: Buffer, target: string, options: ExtractOptions = {}): number {
+ const bytes = gunzipSync(archive)
+ const strip = options.stripComponents ?? 0
+ let offset = 0
+ let written = 0
+ let total = 0
+ let pendingLongName: string | undefined
+ let pendingPath: string | undefined
+ while (offset + 512 <= bytes.length) {
+ const header = readHeader(bytes.subarray(offset, offset + 512))
+ if (header === null)
+ break
+ offset += 512
+ const contentEnd = offset + header.size
+ if (contentEnd > bytes.length)
+ throw new Error('truncated tar entry')
+ const content = bytes.subarray(offset, contentEnd)
+ offset += Math.ceil(header.size / 512) * 512
+ if (header.size > TAR_LIMITS.entryBytes)
+ throw new Error('tar entry too large')
+ total += header.size
+ if (total > TAR_LIMITS.totalBytes)
+ throw new Error('tar archive too large')
+ if (++written > TAR_LIMITS.entries)
+ throw new Error('too many tar entries')
+
+ if (header.type === 'L') {
+ pendingLongName = field(content, 0, content.length)
+ continue
+ }
+ if (header.type === 'x' || header.type === 'X') {
+ pendingPath = paxRecords(content).get('path')
+ continue
+ }
+ if (header.type === 'g')
+ continue
+
+ let name = pendingLongName ?? pendingPath ?? header.name
+ pendingLongName = undefined
+ pendingPath = undefined
+
+ const parts = name.split('/')
+ if (parts.length <= strip)
+ continue
+ name = parts.slice(strip).join('/')
+ if (name === '' || name === '/')
+ continue
+
+ const isDir = header.type === '5' || ((header.type === '0' || header.type === '\0') && name.endsWith('/'))
+ if (header.type !== '0' && header.type !== '\0' && header.type !== '5')
+ continue
+
+ const resolved = safeJoin(target, name)
+ if (resolved === null)
+ throw new Error(`unsafe tar entry name: ${name}`)
+ if (isDir) {
+ mkdirSync(resolved, { recursive: true })
+ continue
+ }
+ mkdirSync(dirname(resolved), { recursive: true })
+ writeFileSync(resolved, content)
+ }
+ return written
+ },
+})
-/** Guard rails for untrusted archives. */
-const LIMITS = {
- /** Per-entry cap (a skill repo holds markdown and small assets). */
- entryBytes: 64 * 1024 * 1024,
- /** Whole-archive content cap. */
- totalBytes: 256 * 1024 * 1024,
- /** Entry count cap (also bounds loop time on corrupt input). */
- entries: 20_000,
-} as const
+// --- internal ---
function octal(block: Buffer, offset: number, length: number): number {
const raw = block.toString('utf8', offset, offset + length).replace(/[\0 ]+$/, '')
@@ -31,20 +85,13 @@ function field(block: Buffer, offset: number, length: number): string {
return block.toString('utf8', offset, Math.min(at === -1 ? offset + length : at, offset + length))
}
-/** One parsed tar header. */
-interface TarHeader {
- name: string
- size: number
- type: string
-}
-
function readHeader(block: Buffer): TarHeader | null {
- // A zeroed block ends the archive (the checksum of an empty block is 0).
if (block.every(byte => byte === 0))
return null
const checksum = octal(block, 148, 8)
let sum = 0
- for (let at = 0; at < 512; at++) sum += at >= 148 && at < 156 ? 32 : block[at]
+ for (let at = 0; at < 512; at++)
+ sum += at >= 148 && at < 156 ? 32 : block[at]
if (sum !== checksum)
return null
const magic = block.toString('utf8', 257, 257 + 6)
@@ -57,7 +104,6 @@ function readHeader(block: Buffer): TarHeader | null {
return { name, size: octal(block, 124, 12), type: block.toString('utf8', 156, 157) }
}
-/** Resolve one entry name under the target, rejecting escapes. */
function safeJoin(target: string, name: string): string | null {
const normalized = name.replace(/\\/g, '/')
if (normalized.startsWith('/') || /^[A-Z]:/i.test(normalized))
@@ -75,7 +121,6 @@ function safeJoin(target: string, name: string): string | null {
return join(target, ...parts)
}
-/** PAX extended header records (`<len> key=value\n` lines) → key/value map. */
function paxRecords(content: Buffer): Map<string, string> {
const out = new Map<string, string>()
let cursor = 0
@@ -94,82 +139,3 @@ function paxRecords(content: Buffer): Map<string, string> {
}
return out
}
-
-/** Number of leading path components to drop (GitHub tarballs wrap one). */
-export interface ExtractOptions {
- stripComponents?: number
-}
-
-/**
- * Extract a gzip'd tar buffer into `target` (created when absent). Returns
- * the entry count written. Throws on structure errors and oversize archives.
- */
-export function extractTarGz(archive: Buffer, target: string, options: ExtractOptions = {}): number {
- const tar = gunzipSync(archive)
- const strip = options.stripComponents ?? 0
- let offset = 0
- let written = 0
- let total = 0
- let pendingLongName: string | undefined
- let pendingPath: string | undefined
- while (offset + 512 <= tar.length) {
- const header = readHeader(tar.subarray(offset, offset + 512))
- if (header === null)
- break
- offset += 512
- const contentEnd = offset + header.size
- if (contentEnd > tar.length)
- throw new Error('truncated tar entry')
- const content = tar.subarray(offset, contentEnd)
- offset += Math.ceil(header.size / 512) * 512
- if (header.size > LIMITS.entryBytes)
- throw new Error('tar entry too large')
- total += header.size
- if (total > LIMITS.totalBytes)
- throw new Error('tar archive too large')
- if (++written > LIMITS.entries)
- throw new Error('too many tar entries')
-
- // Metadata entries carry the name for the entry that follows.
- if (header.type === 'L') {
- pendingLongName = field(content, 0, content.length)
- continue
- }
- if (header.type === 'x' || header.type === 'X') {
- pendingPath = paxRecords(content).get('path')
- continue
- }
- if (header.type === 'g')
- continue // global pax: nothing we need
-
- let name = pendingLongName ?? pendingPath ?? header.name
- pendingLongName = undefined
- pendingPath = undefined
-
- const parts = name.split('/')
- if (parts.length <= strip)
- continue // nothing left after stripping
- name = parts.slice(strip).join('/')
- // The stripped top-level directory itself ("pkg/" → "") owns nothing.
- if (name === '' || name === '/')
- continue
-
- // Directories: type '5' or a trailing slash. Symlinks/hardlinks/other
- // types are skipped — skill repos that depend on them degrade loudly
- // elsewhere instead of planting links from untrusted input.
- const isDir = header.type === '5' || ((header.type === '0' || header.type === '\0') && name.endsWith('/'))
- if (header.type !== '0' && header.type !== '\0' && header.type !== '5')
- continue
-
- const resolved = safeJoin(target, name)
- if (resolved === null)
- throw new Error(`unsafe tar entry name: ${name}`)
- if (isDir) {
- mkdirSync(resolved, { recursive: true })
- continue
- }
- mkdirSync(dirname(resolved), { recursive: true })
- writeFileSync(resolved, content)
- }
- return written
-}
diff --git a/packages/dsh-tauri-panel-extension/src/host/service/tar.types.ts b/packages/dsh-tauri-panel-extension/src/host/service/tar.types.ts
new file mode 100644
index 00000000..e161e56f
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/service/tar.types.ts
@@ -0,0 +1,9 @@
+export interface ExtractOptions {
+ stripComponents?: number
+}
+
+export interface TarHeader {
+ name: string
+ size: number
+ type: string
+}
diff --git a/packages/dsh-tauri-panel-extension/src/host/storage/index.ts b/packages/dsh-tauri-panel-extension/src/host/storage/index.ts
index 9f8cf3c4..60b07210 100644
--- a/packages/dsh-tauri-panel-extension/src/host/storage/index.ts
+++ b/packages/dsh-tauri-panel-extension/src/host/storage/index.ts
@@ -1,18 +1,6 @@
-/**
- * host/storage/index.ts — 扩展面板持久化存储入口(skills 功能目录)。
- *
- * 只暴露模块级 `storage` 单例;skill root 的读取/变更在 host/service/skill-root.ts
- * 实现,不在此写包装。
- */
-
import { DSH_HOME, fsAtomicDriver } from 'dsh-tauri'
import { join } from 'pathe'
import { createStorage } from 'unstorage'
+import { SKILL_DATA_DIRECTORY } from '../config/constants'
-/**
- * skills 功能目录存储(`$DSH_HOME/skills`;key 如 `state.json`)。
- *
- * base 必须是**绝对路径**:`fsAtomicDriver` 会把相对 base 拼到 dsh-tauri 内部的
- * `DSH_HOME` 上,那样 `vi.mock('dsh-tauri')` 换掉数据根时驱动仍会写真实目录。
- */
-export const storage = createStorage({ driver: fsAtomicDriver({ base: join(DSH_HOME, 'skills') }) })
+export const storage = createStorage({ driver: fsAtomicDriver({ base: join(DSH_HOME, SKILL_DATA_DIRECTORY) }) })
diff --git a/packages/dsh-tauri-panel-extension/src/host/types/index.ts b/packages/dsh-tauri-panel-extension/src/host/types/index.ts
deleted file mode 100644
index a4d1a7f1..00000000
--- a/packages/dsh-tauri-panel-extension/src/host/types/index.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-/** Shared types across the capabilities manager modules. */
-
-/** One skill as the host registry reports it (SkillSummary subset). */
-export interface HostSkill {
- readonly name: string
- readonly description: string
- readonly whenToUse?: string
- readonly invocation: { modelInvocable: boolean, userInvocable: boolean }
- readonly source: string
- readonly provider: string
- /** Provider-specific base (directory skills carry their folder here). */
- readonly resourceBase?: { kind: 'directory', path: string } | { kind: 'url', url: string } | { kind: 'opaque', description: string }
-}
-
-/** Loaded skill definition subset the routes consume. */
-export interface HostSkillDefinition {
- readonly name: string
- readonly content: string
- readonly path?: string
- readonly resourceBase?: HostSkill['resourceBase']
-}
-
-/** The skills service subset this plugin consumes (structural). */
-export interface SkillsService {
- list: (options?: { cwd?: string }) => Promise<HostSkill[]>
- get: (name: string, options?: { cwd?: string }) => Promise<HostSkillDefinition | undefined>
-}
-
-/** Repository metadata attached to a skill row for client navigation. */
-export interface SkillRepositoryMetadata {
- /** Stable repository registration id. */
- id: string
- /** Human-readable local folder or `owner/repo` label. */
- label: string
- kind: 'local' | 'git'
- /** Canonical clickable GitHub URL; present only for GitHub imports. */
- githubUrl?: string
-}
-
-/**
- * 宿主 ctx 里本插件路由消费的能力子集(结构兼容,不需要适配)。
- *
- * 方法限制 / OPTIONS / 连接鉴权 / 回环与跨源由 `dsh-tauri` 的 `defineRoutes` 统一承担,
- * 因此这里不再声明 webServer / connection。
- */
-export interface PanelExtensionHost {
- skills: SkillsService
-}
-
-/**
- * 路由的 apply 期依赖面(`routes(ctx, deps)` 的 deps 形状)。
- *
- * profile patch 目录与 provider 重挂载函数在装配期解析、不作为宿主服务暴露,处理器
- * 无法从事件取回,因此随注册传入、由处理器经 `dshRouteDepsOf(event)` 取回(宿主 ctx
- * 本身仍由 `dshContextOf(event)` 取回,不走 deps)。deps 由本次注册的闭包捕获,同一
- * 份声明在两组 deps 下注册时各读各的依赖。
- */
-export interface ExtensionRouteDeps {
- /** profile 的 patch 目录(`<DSH_HOME>/profiles/<profile>`)。 */
- profileDirPath: string
- /**
- * 重挂宿主 filesystem skill provider(根集变更后重新扫描全部技能根)。
- * 技能「刷新」与仓库增删都要先走它,避免删被 watch 的树(Windows EPERM)。
- */
- remountProvider: () => Promise<void>
-}
diff --git a/packages/dsh-tauri-panel-extension/src/host/utils/filesystem.utils.ts b/packages/dsh-tauri-panel-extension/src/host/utils/filesystem.utils.ts
new file mode 100644
index 00000000..3931b565
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/utils/filesystem.utils.ts
@@ -0,0 +1,10 @@
+import { statSync } from 'node:fs'
+
+export function directoryExists(path: string): boolean {
+ try {
+ return statSync(path).isDirectory()
+ }
+ catch {
+ return false
+ }
+}
diff --git a/packages/dsh-tauri-panel-extension/src/host/utils/paths.utils.ts b/packages/dsh-tauri-panel-extension/src/host/utils/paths.utils.ts
new file mode 100644
index 00000000..51ec6f11
--- /dev/null
+++ b/packages/dsh-tauri-panel-extension/src/host/utils/paths.utils.ts
@@ -0,0 +1,23 @@
+import { DSH_HOME } from 'dsh-tauri'
+import { join } from 'pathe'
+import { PROFILES_DIRECTORY, REPOS_DIRECTORY, SKILL_DATA_DIRECTORY, SKILL_FILE_NAME } from '../config/constants'
+
+export function skillsDataDir(): string {
+ return join(DSH_HOME, SKILL_DATA_DIRECTORY)
+}
+
+export function skillDir(name: string): string {
+ return join(skillsDataDir(), name)
+}
+
+export function skillFilePath(name: string): string {
+ return join(skillDir(name), SKILL_FILE_NAME)
+}
+
+export function materialDirFor(entryId: string): string {
+ return join(skillsDataDir(), REPOS_DIRECTORY, entryId)
+}
+
+export function profileDir(profile: string): string {
+ return join(DSH_HOME, PROFILES_DIRECTORY, profile)
+}
diff --git a/packages/dsh-tauri-panel-extension/src/index.ts b/packages/dsh-tauri-panel-extension/src/index.ts
index 282e0e76..db5f3fad 100644
--- a/packages/dsh-tauri-panel-extension/src/index.ts
+++ b/packages/dsh-tauri-panel-extension/src/index.ts
@@ -1,27 +1,12 @@
-/**
- * dsh-tauri-panel-extension 宿主侧(node half):能力管理器。
- *
- * 三层目录(host / client / shared):
- * - index.ts(本文件) public barrel(公开面不变:name/inject/apply + 能力函数);
- * - shared/constants 跨 half 协议常量(插件名 / API 前缀);
- * - host/ Node half:apply(装配 + provider 重挂载)、hooks/
- * (hookable provider 钩子)、routes/(领域路由组合)、
- * storage/(unstorage 状态持久化)、service/
- * (repos / skills / mcp / agents / tar / opener / rmtree /
- * profile / restart 领域能力)、types/ / constants/;
- * - client/ Browser half(API 调用 + 设置页三个 tab)。
- */
-
import { PLUGIN_NAME } from './shared/constants'
-/** 插件名(诊断元数据,与导出的 name 一致)。 */
export const name = PLUGIN_NAME
export const inject = ['webServer', 'skills', 'connection']
export { apply, loadFilesystemSkillPlugin, packagedSkillsDir } from './host/apply'
export type { Config } from './host/apply'
-export { providerHooks } from './host/hooks'
-export type { ProviderLifecycleHooks } from './host/hooks'
+export { providerHooks } from './host/events'
+export type { ProviderLifecycleHooks } from './host/events'
export { routes } from './host/routes'
-export type { ExtensionRouteDeps } from './host/types'
+export type { ExtensionRouteDeps } from './host/routes/index.types'
diff --git a/packages/dsh-tauri-panel-extension/src/shared/constants.ts b/packages/dsh-tauri-panel-extension/src/shared/constants.ts
index 27031acb..423a3a99 100644
--- a/packages/dsh-tauri-panel-extension/src/shared/constants.ts
+++ b/packages/dsh-tauri-panel-extension/src/shared/constants.ts
@@ -1,11 +1,3 @@
-/**
- * shared/constants.ts — 跨 host/client 的稳定协议常量(panel-extension)。
- * Adapted from qinyre/dsh-plugin-capabilities. Copyright (c) 2026 qinyre.
- * Licensed under the MIT License.
- */
-
-/** 稳定 host/plugin 标识。 */
export const PLUGIN_NAME = 'dsh-tauri-panel-extension'
-/** HTTP 命名空间暴露给客户端半区。 */
export const API_PREFIX = `/${PLUGIN_NAME}`
diff --git a/packages/dsh-tauri-panel-extension/tsconfig.json b/packages/dsh-tauri-panel-extension/tsconfig.json
deleted file mode 100644
index 32a0dfe3..00000000
--- a/packages/dsh-tauri-panel-extension/tsconfig.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "extends": "../../tsconfig.json",
- "include": ["src/**/*.ts", "src/**/*.tsx"]
-}