@weibaohui/experts-management 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,6 +17,10 @@
17
17
  - **专家详情**:角色定义全文、关联技能、团队成员、快捷指令、plugin.json 原文、文件清单与体积
18
18
  - **内置自动同步**:与技能市场同款管线——clone `--depth 1 --filter=blob:none --sparse` + 每日 fetch/reset,支持 GitCode 私有仓库 access token(只写不回读)
19
19
 
20
+ - **编辑已安装专家**:角色定义(Agent MD)全文编辑、元数据表单(显示名/职业/描述/标签/快捷指令/默认开场,中英双语)、关联技能管理(从技能库复制副本进专家、移除仅删专家副本)、头像上传——仅「我的」(用户库)专家可编辑,内置只读;保存即生效
21
+
22
+ - **分享专家**:详情弹窗一键分享——AI 读取本机 GitCode 令牌,fork 官方仓库 → 建分支 → 提交专家目录到 `experts/` 子树 → 创建 PR;提示词可编辑,执行过程实时可见(与技能分享同管线)
23
+
20
24
  ## 安装
21
25
 
22
26
  ```bash
package/client/bundle.js CHANGED
@@ -8,6 +8,109 @@ window.__ModuleLoader__.load({
8
8
  var exports = module.exports
9
9
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" })
10
10
  var React = require("react")
11
+ /**
12
+ * @weibaohui/dsh-plugin-kit — client source(由消费者构建脚本内联进 bundle,
13
+ * 不经 loader 运行时加载)。对外暴露 PluginKit:
14
+ *
15
+ * PluginKit.substituteParams(template, params) — {{key}} 模板插值
16
+ * PluginKit.makeActionShareDialog(React, opts) — 返回 ActionShareDialog 组件
17
+ *
18
+ * ActionShareDialog props:
19
+ * title / hint / rows: [[label, value], ...] / initialPrompt
20
+ * run: async (prompt) => { jobId } — 发起执行
21
+ * poll: async (jobId) => { status, output, code }
22
+ * labels: { copy, copied, run, running, done, failed, outputLabel, close }
23
+ * onClose
24
+ *
25
+ * 全部样式内联(主题 token + 回退值),消费者无需自带 CSS。
26
+ */
27
+ var PluginKit = (function () {
28
+ function substituteParams(template, params) {
29
+ var out = String(template || '')
30
+ for (var key in (params || {})) out = out.split('{{' + key + '}}').join(String(params[key]))
31
+ return out
32
+ }
33
+
34
+ function makeActionShareDialog(React, options) {
35
+ options = options || {}
36
+ var h = React.createElement
37
+ var useState = React.useState
38
+ var useEffect = React.useEffect
39
+ var doFetch = options.fetch || (typeof fetch !== 'undefined' ? fetch : null)
40
+ var inputStyle = { width: '100%', minHeight: 190, resize: 'vertical', fontFamily: 'var(--dsw-font-family)', lineHeight: 1.6, fontSize: 12, background: 'var(--dsw-alias-bg-layer-2,transparent)', color: 'inherit', border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', borderRadius: '8px', padding: '10px', boxSizing: 'border-box' }
41
+ var btnStyle = { background: 'transparent', color: 'inherit', border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', borderRadius: '8px', padding: '5px 12px', fontSize: 13, cursor: 'pointer', font: 'inherit' }
42
+ var primaryStyle = Object.assign({}, btnStyle, { background: 'var(--dsw-alias-brand-primary,#4a7dff)', borderColor: 'var(--dsw-alias-brand-primary,#4a7dff)', color: '#fff' })
43
+
44
+ return function ActionShareDialog(props) {
45
+ var title = props.title
46
+ var hint = props.hint
47
+ var labels = props.labels || {}
48
+ var _p = useState(props.initialPrompt || '')
49
+ var prompt = _p[0]; var setPrompt = _p[1]
50
+ var _j = useState(null)
51
+ var job = _j[0]; var setJob = _j[1]
52
+ var _b = useState(false)
53
+ var busy = _b[0]; var setBusy = _b[1]
54
+ var _c = useState(false)
55
+ var copied = _c[0]; var setCopied = _c[1]
56
+ var _e = useState('')
57
+ var error = _e[0]; var setError = _e[1]
58
+ var _d = useState(false)
59
+ var dirty = _d[0]; var setDirty = _d[1]
60
+
61
+ // initialPrompt 异步到位(如宿主先要下发真实路径)时跟随刷新;用户编辑过则不打断
62
+ useEffect(function () {
63
+ if (!dirty) setPrompt(props.initialPrompt || '')
64
+ }, [props.initialPrompt])
65
+
66
+ useEffect(function () {
67
+ if (job === null || job.status !== 'running' || typeof props.poll !== 'function') return
68
+ var timer = setInterval(function () {
69
+ props.poll(job.jobId).then(function (d) {
70
+ setJob({ jobId: job.jobId, status: d.status, output: d.output || '', code: d.code !== undefined ? d.code : null, sessionId: d.sessionId })
71
+ }).catch(function () {})
72
+ }, 1500)
73
+ return function () { clearInterval(timer) }
74
+ }, [job !== null && job.jobId])
75
+
76
+ var doRun = function () {
77
+ if (typeof props.run !== 'function') return
78
+ setBusy(true); setError('')
79
+ props.run(prompt).then(function (r) {
80
+ setJob({ jobId: r.jobId, status: 'running', output: '', code: null })
81
+ }).catch(function (e) { setError(String(e && e.message)) }).finally(function () { setBusy(false) })
82
+ }
83
+ var copy = function () {
84
+ if (typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText) {
85
+ navigator.clipboard.writeText(prompt).then(function () { setCopied(true); setTimeout(function () { setCopied(false) }, 1500) }).catch(function () {})
86
+ }
87
+ }
88
+ var statusText = job === null ? '' : job.status === 'running' ? (labels.running || 'running') : job.status === 'done' ? (labels.done || 'done') : (labels.failed || 'failed') + (job.code != null ? ' (' + job.code + ')' : '')
89
+
90
+ return h('div', { onClick: function (e) { if (e.target === e.currentTarget && props.onClose) props.onClose() }, style: { position: 'fixed', inset: 0, zIndex: 2147483000, background: 'rgba(0,0,0,.45)', display: 'flex', alignItems: 'center', justifyContent: 'center' } },
91
+ h('div', { style: { width: 'min(640px,92vw)', maxHeight: '86vh', overflow: 'auto', background: 'var(--dsw-alias-bg-layer-1,#fff)', border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', borderRadius: '16px', padding: '20px', display: 'flex', flexDirection: 'column', gap: 12, color: 'var(--dsw-alias-label-primary,inherit)', font: 'var(--dsw-font-family,inherit)' } },
92
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
93
+ h('div', { style: { fontSize: 17, fontWeight: 600 } }, title || ''),
94
+ h('button', { onClick: props.onClose, style: Object.assign({}, btnStyle, { marginLeft: 'auto', width: 28, height: 28, padding: 0, borderRadius: 28 }) }, '✕')),
95
+ hint ? h('div', { style: { fontSize: 12, opacity: .7 } }, hint) : null,
96
+ (props.rows || []).length > 0 ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 4, fontSize: 13 } },
97
+ props.rows.map(function (r, i) {
98
+ return r[1] ? h('div', { key: i }, h('b', null, r[0] + ':'), h('span', null, r[1])) : null
99
+ })) : null,
100
+ h('textarea', { value: prompt, onChange: function (e) { setDirty(true); setPrompt(e.target.value) }, spellCheck: false, style: inputStyle }),
101
+ error !== '' ? h('div', { style: { fontSize: 12, color: 'var(--dsw-alias-state-error,#c75050)' } }, error) : null,
102
+ job !== null ? h('div', null,
103
+ h('div', { style: { fontSize: 12, opacity: .7, margin: '4px 0' } }, (labels.outputLabel || 'Output') + ' · ' + statusText),
104
+ h('pre', { style: { maxHeight: 220, margin: 0, overflow: 'auto', whiteSpace: 'pre-wrap', fontSize: 12, background: 'var(--dsw-alias-bg-layer-2,transparent)', border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.2))', borderRadius: '8px', padding: '8px' } }, job.output || '…')) : null,
105
+ h('div', { style: { display: 'flex', gap: 8 } },
106
+ h('button', { onClick: copy, style: btnStyle }, copied ? (labels.copied || 'Copied') : (labels.copy || 'Copy')),
107
+ h('button', { onClick: doRun, disabled: busy || (job !== null && job.status === 'running'), style: primaryStyle }, job !== null && job.status === 'running' ? (labels.running || 'Running…') : (labels.run || 'Run')))))
108
+ }
109
+ }
110
+
111
+ return { substituteParams: substituteParams, makeActionShareDialog: makeActionShareDialog }
112
+ })()
113
+
11
114
  /**
12
115
  * dsh-plugin-experts-management - Browser half.
13
116
  *
@@ -92,6 +195,34 @@ window.__ModuleLoader__.load({
92
195
  install: '安装',
93
196
  installing: '安装中…',
94
197
  installedDone: '已安装到用户库',
198
+ shareBtn: '分享',
199
+ shareTitle: '分享专家到官方仓库',
200
+ shareHint: 'AI 将读取本机令牌,fork 官方仓库 → 建分支 → 提交该专家目录 → 创建 PR。确认或修改提示词后,复制到当前会话发送执行。',
201
+ shareParamName: '专家名',
202
+ shareParamVersion: '版本',
203
+ shareParamDir: '本机目录',
204
+ copyPrompt: '复制提示词',
205
+ copied: '已复制',
206
+ runBtn: '执行',
207
+ running: '执行中…',
208
+ runDone: '完成',
209
+ runFailed: '失败',
210
+ outputLabel: '执行输出',
211
+ editMeta: '编辑资料',
212
+ displayName: '显示名',
213
+ professionLabel: '职业',
214
+ displayDescription: '描述',
215
+ defaultInitPrompt: '默认开场',
216
+ tagsLabel: '标签',
217
+ edit: '编辑',
218
+ save: '保存',
219
+ cancel: '取消',
220
+ saved: '已保存',
221
+ attachSkill: '添加技能',
222
+ detach: '移除',
223
+ detachConfirm: '仅移除专家的技能副本,不影响技能库本体。确认移除?',
224
+ uploadAvatar: '更换头像',
225
+ uploading: '上传中…',
95
226
  overwrite: '覆盖安装',
96
227
  remove: '删除',
97
228
  removing: '删除中…',
@@ -161,6 +292,34 @@ window.__ModuleLoader__.load({
161
292
  install: 'Install',
162
293
  installing: 'Installing…',
163
294
  installedDone: 'Installed to the user library',
295
+ shareBtn: 'Share',
296
+ shareTitle: 'Share expert to the official repo',
297
+ shareHint: 'AI will read the local token, fork the official repo → create a branch → commit the expert directory → open a PR. Review or edit the prompt, then copy it into the conversation to run.',
298
+ shareParamName: 'Expert',
299
+ shareParamVersion: 'Version',
300
+ shareParamDir: 'Local dir',
301
+ copyPrompt: 'Copy prompt',
302
+ copied: 'Copied',
303
+ runBtn: 'Run',
304
+ running: 'Running…',
305
+ runDone: 'Done',
306
+ runFailed: 'Failed',
307
+ outputLabel: 'Output',
308
+ editMeta: 'Edit profile',
309
+ displayName: 'Display name',
310
+ professionLabel: 'Profession',
311
+ displayDescription: 'Description',
312
+ defaultInitPrompt: 'Default opener',
313
+ tagsLabel: 'Tags',
314
+ edit: 'Edit',
315
+ save: 'Save',
316
+ cancel: 'Cancel',
317
+ saved: 'Saved',
318
+ attachSkill: 'Add skill',
319
+ detach: 'Remove',
320
+ detachConfirm: "Only the expert's copy is removed — the skill library is untouched. Remove?",
321
+ uploadAvatar: 'Change avatar',
322
+ uploading: 'Uploading…',
164
323
  overwrite: 'Overwrite install',
165
324
  remove: 'Delete',
166
325
  removing: 'Deleting…',
@@ -262,7 +421,7 @@ window.__ModuleLoader__.load({
262
421
  .exp-skill-row:last-child{border-bottom:0}
263
422
  .exp-form-row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
264
423
  .exp-form-row label{display:flex;flex-direction:column;gap:4px;font-size:12px;color:var(--dsw-alias-label-secondary);flex:1;min-width:160px}
265
- .exp-input{background:var(--dsw-alias-specific-input-major);border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:6px 10px;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;width:100%}
424
+ .exp-flash{font-size:12px;color:var(--dsw-alias-state-positive,#3aa76d)}.exp-input{background:var(--dsw-alias-specific-input-major);border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:6px 10px;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;width:100%}
266
425
  .exp-status-line{display:flex;gap:14px;flex-wrap:wrap;font-size:12px;color:var(--dsw-alias-label-secondary)}
267
426
  .exp-toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:var(--dsw-alias-bg-layer-3);border:1px solid var(--dsw-alias-border-l3);color:var(--dsw-alias-label-primary);border-radius:10px;padding:8px 18px;font-size:13px;z-index:80;box-shadow:0 8px 24px rgba(0,0,0,.25)}
268
427
  .exp-checkline{display:flex;gap:6px;align-items:center;font-size:13px;color:var(--dsw-alias-label-secondary)}
@@ -626,18 +785,136 @@ window.__ModuleLoader__.load({
626
785
  : h('div', { className: 'exp-member-avatar', title: t('avatarLoadFailed') }, '👤')
627
786
  }
628
787
 
629
- function DetailModal({ name, source, t, onClose, onInstalled, onDeleted }) {
788
+ let shareDialogComponent = null
789
+ function getShareDialogComponent() {
790
+ if (shareDialogComponent === null) shareDialogComponent = PluginKit.makeActionShareDialog(__React)
791
+ return shareDialogComponent
792
+ }
793
+
794
+ /** 专家分享提示词:提交到 ntd-resource 的 experts/ 子树(与技能分享同管线、同 token)。 */
795
+ const EXPERT_SHARE_PROMPT = [
796
+ '请把本地专家「{{expertName}}」{{version}}打包提交到 GitCode 官方仓库 weibaohui/ntd-resource 的 experts/ 子树,作为一个 PR 供维护者审核。',
797
+ '',
798
+ '## 关键信息',
799
+ '- 专家目录:{{resourceDir}}(~ 表示当前用户家目录,执行前先展开为绝对路径)',
800
+ '- 官方仓库:weibaohui/ntd-resource(GitCode,API base = https://api.gitcode.com)',
801
+ '- PAT 位置:{{settingsFile}} 中 skills-management.market 段的 token 字段(由技能市场设置面板保存,与技能分享同源)。',
802
+ '',
803
+ '## 执行步骤(严格按顺序)',
804
+ '1. 读取 PAT:读取 {{settingsFile}},定位 skills-management.market 段下的 token 字段。token 是敏感凭据,读取后不要把明文打印到输出、日志或最终结果里。',
805
+ '2. 展开专家目录为绝对路径,遍历该目录(含 agents/、skills/、avatars/ 子目录与 .codebuddy-plugin/plugin.json),收集每个文件的「相对该目录的路径」与内容;跳过 .git 一类同步元数据。',
806
+ '3. 把第 1 步读到的 token 作为 HTTP 认证令牌(bearer),按顺序调用 GitCode API:',
807
+ ' a. 验证用户:`GET https://api.gitcode.com/api/v5/user`,拿到 login 字段——后续所有 URL 里的 {owner} 一律用它。',
808
+ ' b. fork:`POST https://api.gitcode.com/api/v5/repos/weibaohui/ntd-resource/forks`;若返回 409/422 表示已 fork,视为成功。',
809
+ ' c. 建分支:`POST https://api.gitcode.com/api/v5/repos/{owner}/ntd-resource/branches`,JSON body 为 {"branch_name":"experts/{{expertName}}-<unix 时间戳>","refs":"main"}。',
810
+ ' d. 写文件:对第 2 步收集的每个文件,`POST https://api.gitcode.com/api/v5/repos/{owner}/ntd-resource/contents/experts/{{该文件相对专家目录的路径}}`。**必须**用 experts/ 前缀,不能写到仓库根目录。表单字段 content=<文件字节的 base64>、message="贡献专家 {{expertName}} {{version}}"、branch=<步骤 c 的分支名>。',
811
+ ' e. 创建 PR:`POST https://api.gitcode.com/api/v5/repos/weibaohui/ntd-resource/pulls`,JSON body 为 {"title":"[专家] {{expertName}} {{version}}","body":"专家目录 {{resourceDir}} 的文件清单与用途简介","head":"{owner}:{branch}","base":"main"}。',
812
+ '4. 完成后,最终输出 PR 的网页链接(响应里的 web_url 字段)。',
813
+ '',
814
+ '## 注意',
815
+ '- token 是敏感凭据,任何输出里都不要回显其明文。',
816
+ '- 如果任一步骤失败,先检查错误信息,不要盲目重试;若 token 失效,提示用户到技能市场的 ⚙ 设置面板重新填写。',
817
+ '- 全程与最终汇报都使用中文。',
818
+ ].join('\n')
819
+
820
+ function DetailModal({ name, source, t, onClose, onInstalled, onDeleted, onToast }) {
630
821
  const [detail, setDetail] = useState(null)
631
822
  const [error, setError] = useState('')
632
823
  const [busy, setBusy] = useState(false)
633
824
  const [agentMd, setAgentMd] = useState(null)
825
+ const detailUrl = () => `${API}/detail?name=${encodeURIComponent(name)}${source ? `&source=${encodeURIComponent(source)}` : ''}`
826
+ const loadDetail = () => fetchJson(detailUrl())
827
+ .then((d) => setDetail(d))
828
+ .catch((e) => setError(String(e && e.message)))
829
+ useEffect(() => { loadDetail() }, [name, source])
830
+ // ── 编辑态(v0.3,仅 dsh 用户库专家)──
831
+ const [editingMd, setEditingMd] = useState(null) // {agent, content} | null
832
+ const [metaEdit, setMetaEdit] = useState(false)
833
+ const [metaForm, setMetaForm] = useState(null)
834
+ const [skillsEdit, setSkillsEdit] = useState(false)
835
+ const [availSkills, setAvailSkills] = useState(null)
836
+ const [saving, setSaving] = useState(false)
837
+ const [savedFlash, setSavedFlash] = useState('')
838
+ const [avatarBusy, setAvatarBusy] = useState(false)
839
+ const [shareOpen, setShareOpen] = useState(false)
840
+ const [shareSettingsFile, setShareSettingsFile] = useState('')
841
+ const avatarInputRef = useRef(null)
634
842
  useEffect(() => {
635
- let live = true
636
- fetchJson(`${API}/detail?name=${encodeURIComponent(name)}${source ? `&source=${encodeURIComponent(source)}` : ''}`)
637
- .then((d) => { if (live) setDetail(d) })
638
- .catch((e) => { if (live) setError(String(e && e.message)) })
639
- return () => { live = false }
640
- }, [name, source])
843
+ if (shareOpen === false) return
844
+ fetchJson(`${API}/share/status`).then((d) => setShareSettingsFile(d.settingsFile || '')).catch(() => setShareSettingsFile(''))
845
+ }, [shareOpen])
846
+ const flash = (text) => { setSavedFlash(text); setTimeout(() => setSavedFlash(''), 1600) }
847
+ const startEditMd = (agentName) => {
848
+ fetchJson(`${API}/agent-md?name=${encodeURIComponent(name)}${source ? `&source=${encodeURIComponent(source)}` : ''}&agent=${encodeURIComponent(agentName)}`)
849
+ .then((r) => setEditingMd({ agent: agentName, content: r.content }))
850
+ .catch((e) => setError(String(e && e.message)))
851
+ }
852
+ const saveMd = async () => {
853
+ setSaving(true); setError('')
854
+ try {
855
+ await fetchJson(`${API}/agent-md`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, agent: editingMd.agent, content: editingMd.content }) })
856
+ setEditingMd(null); flash(t('saved')); loadDetail()
857
+ } catch (e) { setError(String(e && e.message)) } finally { setSaving(false) }
858
+ }
859
+ const startMetaEdit = () => {
860
+ const p = (detail && detail.pluginJson) || {}
861
+ const loc = (v) => ({ zh: (v && v.zh) || '', en: (v && v.en) || '' })
862
+ const tags = Array.isArray(p.tags) ? p.tags : []
863
+ setMetaForm({
864
+ displayName: loc(p.displayName), profession: loc(p.profession),
865
+ displayDescription: loc(p.displayDescription), defaultInitPrompt: loc(p.defaultInitPrompt),
866
+ tagsZh: tags.map((x) => x.zh || '').filter(Boolean).join(','),
867
+ tagsEn: tags.map((x) => x.en || '').filter(Boolean).join(','),
868
+ quickPrompts: Array.isArray(p.quickPrompts) ? p.quickPrompts : [],
869
+ })
870
+ setMetaEdit(true)
871
+ }
872
+ const saveMeta = async () => {
873
+ setSaving(true); setError('')
874
+ const splitList = (v) => String(v || '').split(/[,,]/).map((x) => x.trim()).filter(Boolean)
875
+ const body = { metadata: {
876
+ displayName: metaForm.displayName, profession: metaForm.profession,
877
+ displayDescription: metaForm.displayDescription, defaultInitPrompt: metaForm.defaultInitPrompt,
878
+ tags: (function () {
879
+ const zhList = splitList(metaForm.tagsZh); const enList = splitList(metaForm.tagsEn)
880
+ const len = Math.max(zhList.length, enList.length)
881
+ return Array.from({ length: len }, (_, i) => ({ zh: zhList[i] || '', en: enList[i] || '' })).filter((t) => t.zh !== '' || t.en !== '')
882
+ })(),
883
+ quickPrompts: metaForm.quickPrompts,
884
+ } }
885
+ try {
886
+ await fetchJson(`${API}/metadata`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, ...body }) })
887
+ setMetaEdit(false); flash(t('saved')); loadDetail()
888
+ } catch (e) { setError(String(e && e.message)) } finally { setSaving(false) }
889
+ }
890
+ const detachSkill = (skillName) => {
891
+ if (!window.confirm(t('detachConfirm'))) return
892
+ fetchJson(`${API}/expert-skills`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, detach: [skillName] }) })
893
+ .then(() => { flash(t('saved')); loadDetail() })
894
+ .catch((e) => setError(String(e && e.message)))
895
+ }
896
+ const openSkillsEdit = () => {
897
+ setSkillsEdit(true)
898
+ if (availSkills === null) {
899
+ fetchJson(`${API}/available-skills`).then((d) => setAvailSkills(d.skills || [])).catch((e) => setError(String(e && e.message)))
900
+ }
901
+ }
902
+ const attachSkill = (skillName) => {
903
+ fetchJson(`${API}/expert-skills`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, attach: [skillName] }) })
904
+ .then(() => { flash(t('saved')); loadDetail() })
905
+ .catch((e) => setError(String(e && e.message)))
906
+ }
907
+ const onAvatarFile = async (e) => {
908
+ const f = e.target.files && e.target.files[0]
909
+ e.target.value = ''
910
+ if (!f) return
911
+ setAvatarBusy(true); setError('')
912
+ try {
913
+ const buf = new Uint8Array(await f.arrayBuffer())
914
+ await fetchJson(`${API}/avatar?name=${encodeURIComponent(name)}`, { method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: buf })
915
+ flash(t('saved')); loadDetail()
916
+ } catch (ex) { setError(String(ex && ex.message)) } finally { setAvatarBusy(false) }
917
+ }
641
918
  const loadAgentMd = () => {
642
919
  fetchJson(`${API}/agent-md?name=${encodeURIComponent(name)}${source ? `&source=${encodeURIComponent(source)}` : ''}`)
643
920
  .then((r) => setAgentMd(r.content))
@@ -679,6 +956,24 @@ window.__ModuleLoader__.load({
679
956
  kv(t('filesLabel'), `${detail.fileCount} / ${formatSize(detail.totalSize)}`),
680
957
  kv(t('dirLabel'), detail.dir)),
681
958
  detail.readOnly ? h('div', { className: 'exp-kv' }, h('span', { style: { color: 'var(--dsw-alias-label-tertiary)' } }, t('sourceReadonly'))) : null,
959
+ detail.source === 'dsh' ? h('div', { className: 'exp-form-row' },
960
+ h('button', { className: 'exp-btn', disabled: busy || saving || avatarBusy, onClick: startMetaEdit }, t('editMeta')),
961
+ h('button', { className: 'exp-btn', disabled: busy || saving || avatarBusy, onClick: () => { if (avatarInputRef.current) avatarInputRef.current.click() } }, avatarBusy ? t('uploading') : t('uploadAvatar')),
962
+ savedFlash ? h('span', { className: 'exp-flash' }, savedFlash) : null,
963
+ h('input', { ref: avatarInputRef, type: 'file', accept: 'image/png,image/jpeg,image/gif,image/webp', style: { display: 'none' }, onChange: onAvatarFile })) : null,
964
+ metaEdit && metaForm ? h('div', { className: 'exp-section' },
965
+ h('div', { className: 'exp-section-title' }, t('editMeta')),
966
+ ...['displayName', 'profession', 'displayDescription', 'defaultInitPrompt'].map((key) => h('div', { key, style: { marginBottom: '8px' } },
967
+ h('div', { className: 'exp-section-title', style: { margin: '4px 0' } }, t(key === 'profession' ? 'professionLabel' : key === 'tags' ? 'tagsLabel' : key)),
968
+ h('input', { className: 'exp-input', value: metaForm[key].zh, placeholder: 'zh', onChange: (e) => setMetaForm({ ...metaForm, [key]: { ...metaForm[key], zh: e.target.value } }), style: { marginBottom: '4px', width: '100%' } }),
969
+ h('input', { className: 'exp-input', value: metaForm[key].en, placeholder: 'en', onChange: (e) => setMetaForm({ ...metaForm, [key]: { ...metaForm[key], en: e.target.value } }), style: { width: '100%' } }))),
970
+ h('div', { style: { marginBottom: '8px' } },
971
+ h('div', { className: 'exp-section-title', style: { margin: '4px 0' } }, t('tagsLabel')),
972
+ h('input', { className: 'exp-input', value: metaForm.tagsZh, placeholder: 'zh,逗号分隔', onChange: (e) => setMetaForm({ ...metaForm, tagsZh: e.target.value }), style: { marginBottom: '4px', width: '100%' } }),
973
+ h('input', { className: 'exp-input', value: metaForm.tagsEn, placeholder: 'en, comma separated', onChange: (e) => setMetaForm({ ...metaForm, tagsEn: e.target.value }), style: { width: '100%' } })),
974
+ h('div', { className: 'exp-form-row' },
975
+ h('button', { className: 'exp-btn', 'data-primary': 'true', disabled: saving, onClick: saveMeta }, saving ? '…' : t('save')),
976
+ h('button', { className: 'exp-btn', disabled: saving, onClick: () => setMetaEdit(false) }, t('cancel')))) : null,
682
977
  (detail.quickPromptsZh || []).length > 0 ? h('div', { className: 'exp-section' },
683
978
  h('div', { className: 'exp-section-title' }, t('quickPrompts')),
684
979
  ...detail.quickPromptsZh.slice(0, 5).map((q, i) => h('div', { className: 'exp-kv', key: i }, '• ', q))) : null,
@@ -694,13 +989,33 @@ window.__ModuleLoader__.load({
694
989
  h('div', { className: 'exp-section-title' }, t('skills')),
695
990
  ...detail.skillMeta.map((s) => h('div', { className: 'exp-skill-row', key: s.skillName },
696
991
  h('div', { style: { fontSize: 13 } }, `${s.emoji ? s.emoji + ' ' : ''}${s.skillName}`),
697
- h('div', { className: 'exp-profession' }, s.descriptionZh || s.descriptionEn || s.description || '')))) : null,
992
+ h('div', { className: 'exp-profession' }, s.descriptionZh || s.descriptionEn || s.description || ''),
993
+ detail.source === 'dsh' ? h('button', { className: 'exp-btn', style: { marginLeft: 'auto' }, onClick: () => detachSkill(s.skillName) }, t('detach')) : null)),
994
+ detail.source === 'dsh' ? h('div', { className: 'exp-form-row' },
995
+ skillsEdit ? null : h('button', { className: 'exp-btn', onClick: openSkillsEdit }, t('attachSkill'))) : null,
996
+ detail.source === 'dsh' && skillsEdit ? h('div', { className: 'exp-form-row' },
997
+ availSkills === null ? h('span', { className: 'exp-profession' }, '…')
998
+ : availSkills.length === 0 ? h('span', { className: 'exp-profession' }, '—')
999
+ : availSkills.map((sk) => h('button', { key: sk.name, className: 'exp-btn', title: sk.description, onClick: () => attachSkill(sk.name) }, `+ ${sk.name}`))) : null) : null,
698
1000
  (detail.agentFiles || []).length > 0 ? h('div', { className: 'exp-section' },
699
1001
  h('div', { className: 'exp-section-title' }, t('agents')),
700
1002
  ...detail.agentFiles.map((a) => h('div', { className: 'exp-skill-row', key: a.relPath },
701
1003
  h('div', { style: { fontSize: 13 } }, `${a.emoji ? a.emoji + ' ' : ''}${a.name}${a.name === detail.leadAgentFile ? ' ★' : ''}`),
702
- h('div', { className: 'exp-profession' }, a.description || '')))) : null,
1004
+ h('div', { className: 'exp-profession' }, a.description || ''),
1005
+ detail.source === 'dsh' ? h('button', { className: 'exp-btn', style: { marginLeft: 'auto' }, onClick: () => startEditMd(a.name) }, t('edit')) : null))) : null,
1006
+ editingMd !== null ? h('div', { className: 'exp-section' },
1007
+ h('div', { className: 'exp-section-title' }, `${t('edit')} · ${editingMd.agent}`),
1008
+ h('textarea', {
1009
+ className: 'exp-input', value: editingMd.content,
1010
+ onChange: (e) => setEditingMd({ ...editingMd, content: e.target.value }),
1011
+ spellCheck: false,
1012
+ style: { width: '100%', minHeight: '260px', fontFamily: 'ui-monospace,monospace', fontSize: '12px', lineHeight: 1.6, whiteSpace: 'pre-wrap', background: 'var(--dsw-alias-bg-layer-2,transparent)', color: 'inherit', border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', borderRadius: '8px', padding: '10px', boxSizing: 'border-box' },
1013
+ }),
1014
+ h('div', { className: 'exp-form-row' },
1015
+ h('button', { className: 'exp-btn', 'data-primary': 'true', disabled: saving, onClick: saveMd }, saving ? '…' : t('save')),
1016
+ h('button', { className: 'exp-btn', disabled: saving, onClick: () => setEditingMd(null) }, t('cancel')))) : null,
703
1017
  h('div', { className: 'exp-form-row' },
1018
+ h('button', { className: 'exp-btn', onClick: () => setShareOpen(true) }, t('shareBtn')),
704
1019
  h('button', { className: 'exp-btn', onClick: () => (agentMd === null ? loadAgentMd() : setAgentMd(null)) }, agentMd === null ? t('viewAgentMd') : t('hideAgentMd')),
705
1020
  detail.source !== 'dsh'
706
1021
  ? h('button', { className: 'exp-btn', 'data-primary': 'true', disabled: busy, onClick: () => install(false) }, busy ? t('installing') : t('install'))
@@ -712,7 +1027,16 @@ window.__ModuleLoader__.load({
712
1027
  detail.plugin ? h('details', null,
713
1028
  h('summary', { style: { cursor: 'pointer', fontSize: 12, color: 'var(--dsw-alias-label-tertiary)' } }, t('pluginJson')),
714
1029
  h('pre', { className: 'exp-pre' }, JSON.stringify(detail.plugin, null, 2))) : null,
715
- ) : null))
1030
+ ) : null,
1031
+ shareOpen ? h(getShareDialogComponent(), {
1032
+ title: t('shareTitle'), hint: t('shareHint'),
1033
+ rows: [[t('shareParamName'), detail.name], [t('shareParamVersion'), detail.version || '1.0.0'], [t('shareParamDir'), detail.dir]],
1034
+ initialPrompt: PluginKit.substituteParams(EXPERT_SHARE_PROMPT, { expertName: detail.name, version: detail.version || '1.0.0', resourceDir: detail.dir, settingsFile: shareSettingsFile }),
1035
+ labels: { copy: t('copyPrompt'), copied: t('copied'), run: t('runBtn'), running: t('running'), done: t('runDone'), failed: t('runFailed'), outputLabel: t('outputLabel') },
1036
+ run: (prompt) => fetchJson(`${API}/share/run`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt, dir: detail.dir }) }),
1037
+ poll: (id) => fetchJson(`${API}/share/run?id=${encodeURIComponent(id)}`),
1038
+ onClose: () => setShareOpen(false),
1039
+ }) : null))
716
1040
  }
717
1041
 
718
1042
  function BuiltinSettingsDialog({ t, onClose, onToast, onSynced }) {
package/client/index.js CHANGED
@@ -82,6 +82,34 @@ const ZH = {
82
82
  install: '安装',
83
83
  installing: '安装中…',
84
84
  installedDone: '已安装到用户库',
85
+ shareBtn: '分享',
86
+ shareTitle: '分享专家到官方仓库',
87
+ shareHint: 'AI 将读取本机令牌,fork 官方仓库 → 建分支 → 提交该专家目录 → 创建 PR。确认或修改提示词后,复制到当前会话发送执行。',
88
+ shareParamName: '专家名',
89
+ shareParamVersion: '版本',
90
+ shareParamDir: '本机目录',
91
+ copyPrompt: '复制提示词',
92
+ copied: '已复制',
93
+ runBtn: '执行',
94
+ running: '执行中…',
95
+ runDone: '完成',
96
+ runFailed: '失败',
97
+ outputLabel: '执行输出',
98
+ editMeta: '编辑资料',
99
+ displayName: '显示名',
100
+ professionLabel: '职业',
101
+ displayDescription: '描述',
102
+ defaultInitPrompt: '默认开场',
103
+ tagsLabel: '标签',
104
+ edit: '编辑',
105
+ save: '保存',
106
+ cancel: '取消',
107
+ saved: '已保存',
108
+ attachSkill: '添加技能',
109
+ detach: '移除',
110
+ detachConfirm: '仅移除专家的技能副本,不影响技能库本体。确认移除?',
111
+ uploadAvatar: '更换头像',
112
+ uploading: '上传中…',
85
113
  overwrite: '覆盖安装',
86
114
  remove: '删除',
87
115
  removing: '删除中…',
@@ -151,6 +179,34 @@ const EN = {
151
179
  install: 'Install',
152
180
  installing: 'Installing…',
153
181
  installedDone: 'Installed to the user library',
182
+ shareBtn: 'Share',
183
+ shareTitle: 'Share expert to the official repo',
184
+ shareHint: 'AI will read the local token, fork the official repo → create a branch → commit the expert directory → open a PR. Review or edit the prompt, then copy it into the conversation to run.',
185
+ shareParamName: 'Expert',
186
+ shareParamVersion: 'Version',
187
+ shareParamDir: 'Local dir',
188
+ copyPrompt: 'Copy prompt',
189
+ copied: 'Copied',
190
+ runBtn: 'Run',
191
+ running: 'Running…',
192
+ runDone: 'Done',
193
+ runFailed: 'Failed',
194
+ outputLabel: 'Output',
195
+ editMeta: 'Edit profile',
196
+ displayName: 'Display name',
197
+ professionLabel: 'Profession',
198
+ displayDescription: 'Description',
199
+ defaultInitPrompt: 'Default opener',
200
+ tagsLabel: 'Tags',
201
+ edit: 'Edit',
202
+ save: 'Save',
203
+ cancel: 'Cancel',
204
+ saved: 'Saved',
205
+ attachSkill: 'Add skill',
206
+ detach: 'Remove',
207
+ detachConfirm: "Only the expert's copy is removed — the skill library is untouched. Remove?",
208
+ uploadAvatar: 'Change avatar',
209
+ uploading: 'Uploading…',
154
210
  overwrite: 'Overwrite install',
155
211
  remove: 'Delete',
156
212
  removing: 'Deleting…',
@@ -252,7 +308,7 @@ const STYLE = `<style>
252
308
  .exp-skill-row:last-child{border-bottom:0}
253
309
  .exp-form-row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
254
310
  .exp-form-row label{display:flex;flex-direction:column;gap:4px;font-size:12px;color:var(--dsw-alias-label-secondary);flex:1;min-width:160px}
255
- .exp-input{background:var(--dsw-alias-specific-input-major);border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:6px 10px;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;width:100%}
311
+ .exp-flash{font-size:12px;color:var(--dsw-alias-state-positive,#3aa76d)}.exp-input{background:var(--dsw-alias-specific-input-major);border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:6px 10px;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;width:100%}
256
312
  .exp-status-line{display:flex;gap:14px;flex-wrap:wrap;font-size:12px;color:var(--dsw-alias-label-secondary)}
257
313
  .exp-toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:var(--dsw-alias-bg-layer-3);border:1px solid var(--dsw-alias-border-l3);color:var(--dsw-alias-label-primary);border-radius:10px;padding:8px 18px;font-size:13px;z-index:80;box-shadow:0 8px 24px rgba(0,0,0,.25)}
258
314
  .exp-checkline{display:flex;gap:6px;align-items:center;font-size:13px;color:var(--dsw-alias-label-secondary)}
@@ -616,18 +672,136 @@ function MemberAvatar({ expertName, source, member, t }) {
616
672
  : h('div', { className: 'exp-member-avatar', title: t('avatarLoadFailed') }, '👤')
617
673
  }
618
674
 
619
- function DetailModal({ name, source, t, onClose, onInstalled, onDeleted }) {
675
+ let shareDialogComponent = null
676
+ function getShareDialogComponent() {
677
+ if (shareDialogComponent === null) shareDialogComponent = PluginKit.makeActionShareDialog(__React)
678
+ return shareDialogComponent
679
+ }
680
+
681
+ /** 专家分享提示词:提交到 ntd-resource 的 experts/ 子树(与技能分享同管线、同 token)。 */
682
+ const EXPERT_SHARE_PROMPT = [
683
+ '请把本地专家「{{expertName}}」{{version}}打包提交到 GitCode 官方仓库 weibaohui/ntd-resource 的 experts/ 子树,作为一个 PR 供维护者审核。',
684
+ '',
685
+ '## 关键信息',
686
+ '- 专家目录:{{resourceDir}}(~ 表示当前用户家目录,执行前先展开为绝对路径)',
687
+ '- 官方仓库:weibaohui/ntd-resource(GitCode,API base = https://api.gitcode.com)',
688
+ '- PAT 位置:{{settingsFile}} 中 skills-management.market 段的 token 字段(由技能市场设置面板保存,与技能分享同源)。',
689
+ '',
690
+ '## 执行步骤(严格按顺序)',
691
+ '1. 读取 PAT:读取 {{settingsFile}},定位 skills-management.market 段下的 token 字段。token 是敏感凭据,读取后不要把明文打印到输出、日志或最终结果里。',
692
+ '2. 展开专家目录为绝对路径,遍历该目录(含 agents/、skills/、avatars/ 子目录与 .codebuddy-plugin/plugin.json),收集每个文件的「相对该目录的路径」与内容;跳过 .git 一类同步元数据。',
693
+ '3. 把第 1 步读到的 token 作为 HTTP 认证令牌(bearer),按顺序调用 GitCode API:',
694
+ ' a. 验证用户:`GET https://api.gitcode.com/api/v5/user`,拿到 login 字段——后续所有 URL 里的 {owner} 一律用它。',
695
+ ' b. fork:`POST https://api.gitcode.com/api/v5/repos/weibaohui/ntd-resource/forks`;若返回 409/422 表示已 fork,视为成功。',
696
+ ' c. 建分支:`POST https://api.gitcode.com/api/v5/repos/{owner}/ntd-resource/branches`,JSON body 为 {"branch_name":"experts/{{expertName}}-<unix 时间戳>","refs":"main"}。',
697
+ ' d. 写文件:对第 2 步收集的每个文件,`POST https://api.gitcode.com/api/v5/repos/{owner}/ntd-resource/contents/experts/{{该文件相对专家目录的路径}}`。**必须**用 experts/ 前缀,不能写到仓库根目录。表单字段 content=<文件字节的 base64>、message="贡献专家 {{expertName}} {{version}}"、branch=<步骤 c 的分支名>。',
698
+ ' e. 创建 PR:`POST https://api.gitcode.com/api/v5/repos/weibaohui/ntd-resource/pulls`,JSON body 为 {"title":"[专家] {{expertName}} {{version}}","body":"专家目录 {{resourceDir}} 的文件清单与用途简介","head":"{owner}:{branch}","base":"main"}。',
699
+ '4. 完成后,最终输出 PR 的网页链接(响应里的 web_url 字段)。',
700
+ '',
701
+ '## 注意',
702
+ '- token 是敏感凭据,任何输出里都不要回显其明文。',
703
+ '- 如果任一步骤失败,先检查错误信息,不要盲目重试;若 token 失效,提示用户到技能市场的 ⚙ 设置面板重新填写。',
704
+ '- 全程与最终汇报都使用中文。',
705
+ ].join('\n')
706
+
707
+ function DetailModal({ name, source, t, onClose, onInstalled, onDeleted, onToast }) {
620
708
  const [detail, setDetail] = useState(null)
621
709
  const [error, setError] = useState('')
622
710
  const [busy, setBusy] = useState(false)
623
711
  const [agentMd, setAgentMd] = useState(null)
712
+ const detailUrl = () => `${API}/detail?name=${encodeURIComponent(name)}${source ? `&source=${encodeURIComponent(source)}` : ''}`
713
+ const loadDetail = () => fetchJson(detailUrl())
714
+ .then((d) => setDetail(d))
715
+ .catch((e) => setError(String(e && e.message)))
716
+ useEffect(() => { loadDetail() }, [name, source])
717
+ // ── 编辑态(v0.3,仅 dsh 用户库专家)──
718
+ const [editingMd, setEditingMd] = useState(null) // {agent, content} | null
719
+ const [metaEdit, setMetaEdit] = useState(false)
720
+ const [metaForm, setMetaForm] = useState(null)
721
+ const [skillsEdit, setSkillsEdit] = useState(false)
722
+ const [availSkills, setAvailSkills] = useState(null)
723
+ const [saving, setSaving] = useState(false)
724
+ const [savedFlash, setSavedFlash] = useState('')
725
+ const [avatarBusy, setAvatarBusy] = useState(false)
726
+ const [shareOpen, setShareOpen] = useState(false)
727
+ const [shareSettingsFile, setShareSettingsFile] = useState('')
728
+ const avatarInputRef = useRef(null)
624
729
  useEffect(() => {
625
- let live = true
626
- fetchJson(`${API}/detail?name=${encodeURIComponent(name)}${source ? `&source=${encodeURIComponent(source)}` : ''}`)
627
- .then((d) => { if (live) setDetail(d) })
628
- .catch((e) => { if (live) setError(String(e && e.message)) })
629
- return () => { live = false }
630
- }, [name, source])
730
+ if (shareOpen === false) return
731
+ fetchJson(`${API}/share/status`).then((d) => setShareSettingsFile(d.settingsFile || '')).catch(() => setShareSettingsFile(''))
732
+ }, [shareOpen])
733
+ const flash = (text) => { setSavedFlash(text); setTimeout(() => setSavedFlash(''), 1600) }
734
+ const startEditMd = (agentName) => {
735
+ fetchJson(`${API}/agent-md?name=${encodeURIComponent(name)}${source ? `&source=${encodeURIComponent(source)}` : ''}&agent=${encodeURIComponent(agentName)}`)
736
+ .then((r) => setEditingMd({ agent: agentName, content: r.content }))
737
+ .catch((e) => setError(String(e && e.message)))
738
+ }
739
+ const saveMd = async () => {
740
+ setSaving(true); setError('')
741
+ try {
742
+ await fetchJson(`${API}/agent-md`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, agent: editingMd.agent, content: editingMd.content }) })
743
+ setEditingMd(null); flash(t('saved')); loadDetail()
744
+ } catch (e) { setError(String(e && e.message)) } finally { setSaving(false) }
745
+ }
746
+ const startMetaEdit = () => {
747
+ const p = (detail && detail.pluginJson) || {}
748
+ const loc = (v) => ({ zh: (v && v.zh) || '', en: (v && v.en) || '' })
749
+ const tags = Array.isArray(p.tags) ? p.tags : []
750
+ setMetaForm({
751
+ displayName: loc(p.displayName), profession: loc(p.profession),
752
+ displayDescription: loc(p.displayDescription), defaultInitPrompt: loc(p.defaultInitPrompt),
753
+ tagsZh: tags.map((x) => x.zh || '').filter(Boolean).join(','),
754
+ tagsEn: tags.map((x) => x.en || '').filter(Boolean).join(','),
755
+ quickPrompts: Array.isArray(p.quickPrompts) ? p.quickPrompts : [],
756
+ })
757
+ setMetaEdit(true)
758
+ }
759
+ const saveMeta = async () => {
760
+ setSaving(true); setError('')
761
+ const splitList = (v) => String(v || '').split(/[,,]/).map((x) => x.trim()).filter(Boolean)
762
+ const body = { metadata: {
763
+ displayName: metaForm.displayName, profession: metaForm.profession,
764
+ displayDescription: metaForm.displayDescription, defaultInitPrompt: metaForm.defaultInitPrompt,
765
+ tags: (function () {
766
+ const zhList = splitList(metaForm.tagsZh); const enList = splitList(metaForm.tagsEn)
767
+ const len = Math.max(zhList.length, enList.length)
768
+ return Array.from({ length: len }, (_, i) => ({ zh: zhList[i] || '', en: enList[i] || '' })).filter((t) => t.zh !== '' || t.en !== '')
769
+ })(),
770
+ quickPrompts: metaForm.quickPrompts,
771
+ } }
772
+ try {
773
+ await fetchJson(`${API}/metadata`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, ...body }) })
774
+ setMetaEdit(false); flash(t('saved')); loadDetail()
775
+ } catch (e) { setError(String(e && e.message)) } finally { setSaving(false) }
776
+ }
777
+ const detachSkill = (skillName) => {
778
+ if (!window.confirm(t('detachConfirm'))) return
779
+ fetchJson(`${API}/expert-skills`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, detach: [skillName] }) })
780
+ .then(() => { flash(t('saved')); loadDetail() })
781
+ .catch((e) => setError(String(e && e.message)))
782
+ }
783
+ const openSkillsEdit = () => {
784
+ setSkillsEdit(true)
785
+ if (availSkills === null) {
786
+ fetchJson(`${API}/available-skills`).then((d) => setAvailSkills(d.skills || [])).catch((e) => setError(String(e && e.message)))
787
+ }
788
+ }
789
+ const attachSkill = (skillName) => {
790
+ fetchJson(`${API}/expert-skills`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, attach: [skillName] }) })
791
+ .then(() => { flash(t('saved')); loadDetail() })
792
+ .catch((e) => setError(String(e && e.message)))
793
+ }
794
+ const onAvatarFile = async (e) => {
795
+ const f = e.target.files && e.target.files[0]
796
+ e.target.value = ''
797
+ if (!f) return
798
+ setAvatarBusy(true); setError('')
799
+ try {
800
+ const buf = new Uint8Array(await f.arrayBuffer())
801
+ await fetchJson(`${API}/avatar?name=${encodeURIComponent(name)}`, { method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: buf })
802
+ flash(t('saved')); loadDetail()
803
+ } catch (ex) { setError(String(ex && ex.message)) } finally { setAvatarBusy(false) }
804
+ }
631
805
  const loadAgentMd = () => {
632
806
  fetchJson(`${API}/agent-md?name=${encodeURIComponent(name)}${source ? `&source=${encodeURIComponent(source)}` : ''}`)
633
807
  .then((r) => setAgentMd(r.content))
@@ -669,6 +843,24 @@ function DetailModal({ name, source, t, onClose, onInstalled, onDeleted }) {
669
843
  kv(t('filesLabel'), `${detail.fileCount} / ${formatSize(detail.totalSize)}`),
670
844
  kv(t('dirLabel'), detail.dir)),
671
845
  detail.readOnly ? h('div', { className: 'exp-kv' }, h('span', { style: { color: 'var(--dsw-alias-label-tertiary)' } }, t('sourceReadonly'))) : null,
846
+ detail.source === 'dsh' ? h('div', { className: 'exp-form-row' },
847
+ h('button', { className: 'exp-btn', disabled: busy || saving || avatarBusy, onClick: startMetaEdit }, t('editMeta')),
848
+ h('button', { className: 'exp-btn', disabled: busy || saving || avatarBusy, onClick: () => { if (avatarInputRef.current) avatarInputRef.current.click() } }, avatarBusy ? t('uploading') : t('uploadAvatar')),
849
+ savedFlash ? h('span', { className: 'exp-flash' }, savedFlash) : null,
850
+ h('input', { ref: avatarInputRef, type: 'file', accept: 'image/png,image/jpeg,image/gif,image/webp', style: { display: 'none' }, onChange: onAvatarFile })) : null,
851
+ metaEdit && metaForm ? h('div', { className: 'exp-section' },
852
+ h('div', { className: 'exp-section-title' }, t('editMeta')),
853
+ ...['displayName', 'profession', 'displayDescription', 'defaultInitPrompt'].map((key) => h('div', { key, style: { marginBottom: '8px' } },
854
+ h('div', { className: 'exp-section-title', style: { margin: '4px 0' } }, t(key === 'profession' ? 'professionLabel' : key === 'tags' ? 'tagsLabel' : key)),
855
+ h('input', { className: 'exp-input', value: metaForm[key].zh, placeholder: 'zh', onChange: (e) => setMetaForm({ ...metaForm, [key]: { ...metaForm[key], zh: e.target.value } }), style: { marginBottom: '4px', width: '100%' } }),
856
+ h('input', { className: 'exp-input', value: metaForm[key].en, placeholder: 'en', onChange: (e) => setMetaForm({ ...metaForm, [key]: { ...metaForm[key], en: e.target.value } }), style: { width: '100%' } }))),
857
+ h('div', { style: { marginBottom: '8px' } },
858
+ h('div', { className: 'exp-section-title', style: { margin: '4px 0' } }, t('tagsLabel')),
859
+ h('input', { className: 'exp-input', value: metaForm.tagsZh, placeholder: 'zh,逗号分隔', onChange: (e) => setMetaForm({ ...metaForm, tagsZh: e.target.value }), style: { marginBottom: '4px', width: '100%' } }),
860
+ h('input', { className: 'exp-input', value: metaForm.tagsEn, placeholder: 'en, comma separated', onChange: (e) => setMetaForm({ ...metaForm, tagsEn: e.target.value }), style: { width: '100%' } })),
861
+ h('div', { className: 'exp-form-row' },
862
+ h('button', { className: 'exp-btn', 'data-primary': 'true', disabled: saving, onClick: saveMeta }, saving ? '…' : t('save')),
863
+ h('button', { className: 'exp-btn', disabled: saving, onClick: () => setMetaEdit(false) }, t('cancel')))) : null,
672
864
  (detail.quickPromptsZh || []).length > 0 ? h('div', { className: 'exp-section' },
673
865
  h('div', { className: 'exp-section-title' }, t('quickPrompts')),
674
866
  ...detail.quickPromptsZh.slice(0, 5).map((q, i) => h('div', { className: 'exp-kv', key: i }, '• ', q))) : null,
@@ -684,13 +876,33 @@ function DetailModal({ name, source, t, onClose, onInstalled, onDeleted }) {
684
876
  h('div', { className: 'exp-section-title' }, t('skills')),
685
877
  ...detail.skillMeta.map((s) => h('div', { className: 'exp-skill-row', key: s.skillName },
686
878
  h('div', { style: { fontSize: 13 } }, `${s.emoji ? s.emoji + ' ' : ''}${s.skillName}`),
687
- h('div', { className: 'exp-profession' }, s.descriptionZh || s.descriptionEn || s.description || '')))) : null,
879
+ h('div', { className: 'exp-profession' }, s.descriptionZh || s.descriptionEn || s.description || ''),
880
+ detail.source === 'dsh' ? h('button', { className: 'exp-btn', style: { marginLeft: 'auto' }, onClick: () => detachSkill(s.skillName) }, t('detach')) : null)),
881
+ detail.source === 'dsh' ? h('div', { className: 'exp-form-row' },
882
+ skillsEdit ? null : h('button', { className: 'exp-btn', onClick: openSkillsEdit }, t('attachSkill'))) : null,
883
+ detail.source === 'dsh' && skillsEdit ? h('div', { className: 'exp-form-row' },
884
+ availSkills === null ? h('span', { className: 'exp-profession' }, '…')
885
+ : availSkills.length === 0 ? h('span', { className: 'exp-profession' }, '—')
886
+ : availSkills.map((sk) => h('button', { key: sk.name, className: 'exp-btn', title: sk.description, onClick: () => attachSkill(sk.name) }, `+ ${sk.name}`))) : null) : null,
688
887
  (detail.agentFiles || []).length > 0 ? h('div', { className: 'exp-section' },
689
888
  h('div', { className: 'exp-section-title' }, t('agents')),
690
889
  ...detail.agentFiles.map((a) => h('div', { className: 'exp-skill-row', key: a.relPath },
691
890
  h('div', { style: { fontSize: 13 } }, `${a.emoji ? a.emoji + ' ' : ''}${a.name}${a.name === detail.leadAgentFile ? ' ★' : ''}`),
692
- h('div', { className: 'exp-profession' }, a.description || '')))) : null,
891
+ h('div', { className: 'exp-profession' }, a.description || ''),
892
+ detail.source === 'dsh' ? h('button', { className: 'exp-btn', style: { marginLeft: 'auto' }, onClick: () => startEditMd(a.name) }, t('edit')) : null))) : null,
893
+ editingMd !== null ? h('div', { className: 'exp-section' },
894
+ h('div', { className: 'exp-section-title' }, `${t('edit')} · ${editingMd.agent}`),
895
+ h('textarea', {
896
+ className: 'exp-input', value: editingMd.content,
897
+ onChange: (e) => setEditingMd({ ...editingMd, content: e.target.value }),
898
+ spellCheck: false,
899
+ style: { width: '100%', minHeight: '260px', fontFamily: 'ui-monospace,monospace', fontSize: '12px', lineHeight: 1.6, whiteSpace: 'pre-wrap', background: 'var(--dsw-alias-bg-layer-2,transparent)', color: 'inherit', border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', borderRadius: '8px', padding: '10px', boxSizing: 'border-box' },
900
+ }),
901
+ h('div', { className: 'exp-form-row' },
902
+ h('button', { className: 'exp-btn', 'data-primary': 'true', disabled: saving, onClick: saveMd }, saving ? '…' : t('save')),
903
+ h('button', { className: 'exp-btn', disabled: saving, onClick: () => setEditingMd(null) }, t('cancel')))) : null,
693
904
  h('div', { className: 'exp-form-row' },
905
+ h('button', { className: 'exp-btn', onClick: () => setShareOpen(true) }, t('shareBtn')),
694
906
  h('button', { className: 'exp-btn', onClick: () => (agentMd === null ? loadAgentMd() : setAgentMd(null)) }, agentMd === null ? t('viewAgentMd') : t('hideAgentMd')),
695
907
  detail.source !== 'dsh'
696
908
  ? h('button', { className: 'exp-btn', 'data-primary': 'true', disabled: busy, onClick: () => install(false) }, busy ? t('installing') : t('install'))
@@ -702,7 +914,16 @@ function DetailModal({ name, source, t, onClose, onInstalled, onDeleted }) {
702
914
  detail.plugin ? h('details', null,
703
915
  h('summary', { style: { cursor: 'pointer', fontSize: 12, color: 'var(--dsw-alias-label-tertiary)' } }, t('pluginJson')),
704
916
  h('pre', { className: 'exp-pre' }, JSON.stringify(detail.plugin, null, 2))) : null,
705
- ) : null))
917
+ ) : null,
918
+ shareOpen ? h(getShareDialogComponent(), {
919
+ title: t('shareTitle'), hint: t('shareHint'),
920
+ rows: [[t('shareParamName'), detail.name], [t('shareParamVersion'), detail.version || '1.0.0'], [t('shareParamDir'), detail.dir]],
921
+ initialPrompt: PluginKit.substituteParams(EXPERT_SHARE_PROMPT, { expertName: detail.name, version: detail.version || '1.0.0', resourceDir: detail.dir, settingsFile: shareSettingsFile }),
922
+ labels: { copy: t('copyPrompt'), copied: t('copied'), run: t('runBtn'), running: t('running'), done: t('runDone'), failed: t('runFailed'), outputLabel: t('outputLabel') },
923
+ run: (prompt) => fetchJson(`${API}/share/run`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt, dir: detail.dir }) }),
924
+ poll: (id) => fetchJson(`${API}/share/run?id=${encodeURIComponent(id)}`),
925
+ onClose: () => setShareOpen(false),
926
+ }) : null))
706
927
  }
707
928
 
708
929
  function BuiltinSettingsDialog({ t, onClose, onToast, onSynced }) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weibaohui/experts-management",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "dsh 插件 · 专家管理:管理 ntd 格式的专家与专家团队(plugin.json + Agent MD + 技能集),浏览/安装 50+ 内置专家市场;每个专家注册为「仅用户可调用」的技能,在对话输入框用 /expert-名称 即可以该专家的身份执行任务(宿主确定性注入角色定义与技能清单,不占用模型目录 token)。",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -44,6 +44,7 @@
44
44
  "node": ">=22.5"
45
45
  },
46
46
  "dependencies": {
47
+ "@weibaohui/dsh-plugin-kit": "^0.1.0",
47
48
  "yaml": "^2.9.0"
48
49
  },
49
50
  "devDependencies": {
package/src/index.js CHANGED
@@ -19,8 +19,9 @@
19
19
  */
20
20
 
21
21
  const { createReadStream } = require('node:fs')
22
- const { execFile } = require('node:child_process')
23
22
  const { randomUUID } = require('node:crypto')
23
+ const { execFile } = require('node:child_process')
24
+ const { createShareRunJob } = require('@weibaohui/dsh-plugin-kit')
24
25
  const fsP = require('node:fs/promises')
25
26
  const { basename, join, relative, resolve, sep } = require('node:path')
26
27
  const { homedir } = require('node:os')
@@ -516,6 +517,42 @@ function baseSettings(config) {
516
517
  return base
517
518
  }
518
519
 
520
+ // ── 编辑端点(v0.3):只写 dsh 用户库;内置只读 ─────────────────────────
521
+ const EDIT_BODY_MAX_BYTES = 8 * 1024 * 1024
522
+
523
+ /** 魔数嗅探图片类型;非白名单格式返回 null。 */
524
+ function sniffImage(buf) {
525
+ if (!buf || buf.length < 12) return null
526
+ if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) return { ext: 'png', type: 'image/png' }
527
+ if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return { ext: 'jpg', type: 'image/jpeg' }
528
+ const head = buf.slice(0, 12)
529
+ if (head.toString('latin1').startsWith('GIF8')) return { ext: 'gif', type: 'image/gif' }
530
+ if (head.toString('latin1').startsWith('RIFF') && head.toString('latin1').slice(8) === 'WEBP') return { ext: 'webp', type: 'image/webp' }
531
+ return null
532
+ }
533
+
534
+ const readRawBody = (req, cap) => new Promise((fulfil, reject) => {
535
+ let size = 0
536
+ const chunks = []
537
+ req.on('data', (chunk) => {
538
+ size += chunk.length
539
+ if (size > cap) { reject(new Error(`image exceeds ${cap} bytes`)); if (typeof req.destroy === 'function') req.destroy(); return }
540
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
541
+ })
542
+ req.on('end', () => fulfil(Buffer.concat(chunks)))
543
+ req.on('error', reject)
544
+ })
545
+
546
+ /** 编辑端点公共前置:只解析 dsh 用户库副本(内置只读);名字围栏。 */
547
+ async function locateEditable(locateExpert, name) {
548
+ if (typeof name !== 'string' || name === '') throw new Error('body must provide name')
549
+ const { expert } = await locateExpert(name, 'dsh')
550
+ if (!isSafeExpertName(expert.name)) throw new Error(`invalid expert name: ${expert.name}`)
551
+ return expert
552
+ }
553
+
554
+ const MD_MAX_CHARS = 512 * 1024
555
+
519
556
  // ── Module export ────────────────────────────────────────────────────────
520
557
 
521
558
  module.exports = {
@@ -774,6 +811,14 @@ module.exports = {
774
811
  })
775
812
 
776
813
  // ── HTTP API ─────────────────────────────────────────────────────────
814
+ // 分享执行:进程内 agents 服务(web app 自身)可用则流式,否则 headless spawn
815
+ const shareRunJobs = new Map()
816
+ let shareServices = null
817
+ try {
818
+ if (ctx.inject && typeof ctx.inject === 'function') {
819
+ ctx.inject(['agents', 'agentDefaultModel', 'sessions'], (svcs) => { shareServices = svcs })
820
+ }
821
+ } catch {}
777
822
  ctx.effect(() => ctx.webServer.register({
778
823
  kind: 'prefix',
779
824
  path: '/experts-management/api',
@@ -813,9 +858,11 @@ module.exports = {
813
858
  const name = query.get('name') || ''
814
859
  const { expert, row } = await locateExpert(name, query.get('source') || undefined)
815
860
  const { fileCount, totalSize } = await countFilesAndSize(expert.dir)
861
+ const rawPluginText = await fsP.readFile(expert.pluginJsonPath, 'utf8')
816
862
  sendJson(res, 200, {
817
863
  ...expert,
818
- plugin: parsePluginJson(await fsP.readFile(expert.pluginJsonPath, 'utf8')),
864
+ plugin: parsePluginJson(rawPluginText),
865
+ pluginJson: JSON.parse(rawPluginText),
819
866
  leadAgentFile: resolveLeadAgentFile(expert)?.name,
820
867
  dir: displayPath(expert.dir),
821
868
  sourceLabel: row.label,
@@ -870,7 +917,12 @@ module.exports = {
870
917
  if (req.method === 'POST' && apiPath.endsWith('/experts-management/api/install')) {
871
918
  const body = await readJsonBody(req)
872
919
  if (typeof body.name !== 'string' || body.name === '') { sendJson(res, 400, { error: 'body must provide name' }); return }
873
- const { expert } = await locateExpert(body.name, typeof body.from === 'string' && body.from !== '' && body.from !== 'builtin' ? body.from : undefined)
920
+ // from 兼容 client source 字段;'auto'/缺省一律钉死为 builtin——
921
+ // 若解析到 dsh 源,overwrite 会先 rm 自己再空拷(v0.2.0 数据丢失事故),此路彻底封死
922
+ const from = typeof body.from === 'string' && body.from !== '' ? body.from
923
+ : typeof body.source === 'string' && body.source !== '' ? body.source : 'builtin'
924
+ if (from === 'dsh') throw new Error('cannot install from the dsh library (it is the install destination)')
925
+ const { expert } = await locateExpert(body.name, from)
874
926
  if (!isSafeExpertName(expert.name)) throw new Error(`invalid expert name: ${expert.name}`)
875
927
  const target = join(installedDir, expert.name)
876
928
  if (body.overwrite !== true) {
@@ -899,6 +951,180 @@ module.exports = {
899
951
  return
900
952
  }
901
953
 
954
+ // ── 编辑端点(v0.3):仅 dsh 用户库可编辑,内置只读 ──
955
+
956
+ // PUT /experts-management/api/agent-md {name, agent?, content} — 角色定义全文
957
+ if (req.method === 'PUT' && apiPath.endsWith('/experts-management/api/agent-md')) {
958
+ const body = await readJsonBody(req)
959
+ const expert = await locateEditable(locateExpert, body.name)
960
+ if (typeof body.content !== 'string' || body.content.trim() === '') throw new Error('content must be a non-empty string')
961
+ if (body.content.length > MD_MAX_CHARS) throw new Error(`content exceeds ${MD_MAX_CHARS} chars`)
962
+ const normRel = (p0) => String(p0 || '').replace(/^\.\//, '')
963
+ const agentFile = body.agent !== undefined && body.agent !== ''
964
+ ? expert.agentFiles.find((a) => a.name === body.agent || normRel(a.relPath) === normRel(body.agent) || basename(a.mdPath) === body.agent)
965
+ : resolveLeadAgentFile(expert)
966
+ if (agentFile === undefined) throw new Error(`agent not found in expert '${expert.name}'`)
967
+ const full = resolveWithin(expert.dir, agentFile.relPath)
968
+ if (full === undefined || resolve(full) !== resolve(agentFile.mdPath)) throw new Error('agent file path escaped the expert dir')
969
+ await atomicWriteJs(full, body.content)
970
+ invalidate()
971
+ sendJson(res, 200, { ok: true, agent: agentFile.name })
972
+ return
973
+ }
974
+
975
+ // PUT /experts-management/api/metadata {name, metadata} — plugin.json 展示字段(读-改-写保留未知键)
976
+ if (req.method === 'PUT' && apiPath.endsWith('/experts-management/api/metadata')) {
977
+ const body = await readJsonBody(req)
978
+ const meta = body.metadata
979
+ if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) throw new Error('metadata must be an object')
980
+ const expert = await locateEditable(locateExpert, body.name)
981
+ const pluginJson = JSON.parse(await fsP.readFile(expert.pluginJsonPath, 'utf8'))
982
+ const normLocalized = (v) => ({ zh: typeof v.zh === 'string' ? v.zh : '', en: typeof v.en === 'string' ? v.en : '' })
983
+ for (const key of ['displayName', 'profession', 'displayDescription', 'defaultInitPrompt']) {
984
+ if (meta[key] === undefined) continue
985
+ const v = meta[key]
986
+ if (v === null || typeof v !== 'object' || Array.isArray(v)) throw new Error(`${key} must be an object`)
987
+ for (const lang of ['zh', 'en']) {
988
+ if (v[lang] !== undefined && (typeof v[lang] !== 'string' || v[lang].length > 2000)) throw new Error(`${key}.${lang} must be a string (≤2000 chars)`)
989
+ }
990
+ pluginJson[key] = normLocalized(v)
991
+ }
992
+ const listOfLocalized = (v, label) => {
993
+ if (!Array.isArray(v) || v.length > 20) throw new Error(`${label} must be an array (≤20)`)
994
+ return v.map((item) => {
995
+ if (item === null || typeof item !== 'object' || Array.isArray(item)) throw new Error(`${label} items must be objects`)
996
+ return { zh: typeof item.zh === 'string' ? item.zh.slice(0, 2000) : '', en: typeof item.en === 'string' ? item.en.slice(0, 2000) : '' }
997
+ }).filter((item) => item.zh !== '' || item.en !== '')
998
+ }
999
+ if (meta.tags !== undefined) pluginJson.tags = listOfLocalized(meta.tags, 'tags')
1000
+ if (meta.quickPrompts !== undefined) pluginJson.quickPrompts = listOfLocalized(meta.quickPrompts, 'quickPrompts')
1001
+ await atomicWriteJs(expert.pluginJsonPath, JSON.stringify(pluginJson, null, 2))
1002
+ invalidate()
1003
+ sendJson(res, 200, { ok: true, plugin: pluginJson })
1004
+ return
1005
+ }
1006
+
1007
+ // PUT /experts-management/api/expert-skills {name, attach?, detach?} — 技能副本同步
1008
+ if (req.method === 'PUT' && apiPath.endsWith('/experts-management/api/expert-skills')) {
1009
+ const body = await readJsonBody(req)
1010
+ const attach = Array.isArray(body.attach) ? body.attach.map(String) : []
1011
+ const detach = Array.isArray(body.detach) ? body.detach.map(String) : []
1012
+ if (attach.length === 0 && detach.length === 0) throw new Error('attach and detach must not both be empty')
1013
+ const kebab = (n) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(n)
1014
+ for (const n of [...attach, ...detach]) {
1015
+ if (!kebab(n)) throw new Error(`invalid skill name: ${n}`)
1016
+ }
1017
+ const expert = await locateEditable(locateExpert, body.name)
1018
+ const pluginJson = JSON.parse(await fsP.readFile(expert.pluginJsonPath, 'utf8'))
1019
+ // detach 先验后删(任一未附 → 整体拒绝,避免半套变更)
1020
+ const detachDirs = []
1021
+ for (const n of detach) {
1022
+ const dir = resolveWithin(expert.dir, `./skills/${n}`)
1023
+ if (dir === undefined) throw new Error(`skill '${n}' is not attached to expert '${expert.name}'`)
1024
+ const st = await fsP.stat(dir).catch(() => undefined)
1025
+ if (st === undefined || !st.isDirectory()) throw new Error(`skill '${n}' is not attached to expert '${expert.name}'`)
1026
+ detachDirs.push({ n, dir })
1027
+ }
1028
+ // attach 全部先在用户技能库解析源目录(任一缺失整体拒绝)
1029
+ const libRoot = join(dshHome(), 'skills')
1030
+ const attachDirs = []
1031
+ for (const n of attach) {
1032
+ const from = join(libRoot, n)
1033
+ const st = await fsP.stat(join(from, 'SKILL.md')).catch(() => undefined)
1034
+ if (st === undefined || !st.isFile()) throw new Error(`skill '${n}' not found in the user skill library (${libRoot})`)
1035
+ attachDirs.push({ n, from })
1036
+ }
1037
+ for (const d of detachDirs) await fsP.rm(d.dir, { recursive: true, force: true })
1038
+ for (const a of attachDirs) {
1039
+ const target = join(expert.dir, 'skills', a.n)
1040
+ await fsP.rm(target, { recursive: true, force: true }) // 同名覆盖 = 技能库更新同步进专家
1041
+ await copyDir(a.from, target)
1042
+ }
1043
+ // plugin.json.skills = 声明同步:原序保留存活项 + 追加新 attach(以 skills/ 目录实况为准)
1044
+ const skillRoot = join(expert.dir, 'skills')
1045
+ const present = new Set()
1046
+ try {
1047
+ for (const ent of await fsP.readdir(skillRoot, { withFileTypes: true })) if (ent.isDirectory()) present.add(ent.name)
1048
+ } catch { /* 无 skills 目录 */ }
1049
+ const oldNames = (Array.isArray(pluginJson.skills) ? pluginJson.skills : []).map((r) => String(r).replace(/^\.\/skills\//, '').replace(/^\.\//, ''))
1050
+ const finalNames = []
1051
+ for (const n of [...oldNames, ...attach]) {
1052
+ if (present.has(n) && !finalNames.includes(n)) finalNames.push(n)
1053
+ }
1054
+ pluginJson.skills = finalNames.map((n) => `./skills/${n}`)
1055
+ await atomicWriteJs(expert.pluginJsonPath, JSON.stringify(pluginJson, null, 2))
1056
+ invalidate()
1057
+ sendJson(res, 200, { ok: true, skills: pluginJson.skills })
1058
+ return
1059
+ }
1060
+
1061
+ // POST /experts-management/api/avatar?name= — 原始图片体(魔数嗅探)
1062
+ if (req.method === 'POST' && apiPath.endsWith('/experts-management/api/avatar')) {
1063
+ const expert = await locateEditable(locateExpert, query.get('name') || '')
1064
+ const imgBody = await readRawBody(req, EDIT_BODY_MAX_BYTES)
1065
+ const img = sniffImage(imgBody)
1066
+ if (img === null) throw new Error('unsupported image (png/jpg/gif/webp only)')
1067
+ const rel = `avatars/expert.${img.ext}`
1068
+ await atomicWriteJs(join(expert.dir, rel), imgBody)
1069
+ const pluginJson = JSON.parse(await fsP.readFile(expert.pluginJsonPath, 'utf8'))
1070
+ pluginJson.avatar = rel
1071
+ await atomicWriteJs(expert.pluginJsonPath, JSON.stringify(pluginJson, null, 2))
1072
+ invalidate()
1073
+ sendJson(res, 200, { ok: true, avatar: rel })
1074
+ return
1075
+ }
1076
+
1077
+ // GET /experts-management/api/available-skills — 技能关联选择器数据源:
1078
+ // 用户技能库(~/.dsh/skills)目录直读。刻意不走 skills 注册表——那会把
1079
+ // 市场货架库存(5900+ 条)漏进来;也不附 bundled/项目级技能。
1080
+ if (req.method === 'GET' && apiPath.endsWith('/experts-management/api/available-skills')) {
1081
+ const libRoot = join(dshHome(), 'skills')
1082
+ const list = []
1083
+ let libEntries = []
1084
+ try { libEntries = await fsP.readdir(libRoot, { withFileTypes: true }) } catch { /* 无技能库 */ }
1085
+ for (const ent of libEntries) {
1086
+ if (!ent.isDirectory() || !isSafeExpertName(ent.name)) continue
1087
+ let content
1088
+ try { content = await fsP.readFile(join(libRoot, ent.name, 'SKILL.md'), 'utf8') } catch { continue }
1089
+ const parsed = parseSkillMd(content)
1090
+ const description = String(parsed.descriptionZh ?? parsed.descriptionEn ?? parsed.description ?? '').slice(0, 200)
1091
+ list.push({ name: ent.name, description })
1092
+ }
1093
+ list.sort((a, b) => a.name.localeCompare(b.name))
1094
+ sendJson(res, 200, { skills: list })
1095
+ return
1096
+ }
1097
+
1098
+ // GET /experts-management/api/share/status — 分享弹窗数据(settings 真实路径)
1099
+ if (req.method === 'GET' && apiPath.endsWith('/experts-management/api/share/status')) {
1100
+ sendJson(res, 200, { settingsFile: join(dshHome(), 'settings.yaml') })
1101
+ return
1102
+ }
1103
+
1104
+ // POST /experts-management/api/share/run {prompt, dir} → 真实 agent 会话执行
1105
+ if (req.method === 'POST' && apiPath.endsWith('/experts-management/api/share/run')) {
1106
+ const body = await readJsonBody(req)
1107
+ if (typeof body.prompt !== 'string' || body.prompt.trim() === '') { sendJson(res, 400, { error: 'body must provide prompt' }); return }
1108
+ if (typeof body.dir !== 'string' || body.dir === '') { sendJson(res, 400, { error: 'body must provide dir' }); return }
1109
+ // 支持 ~ 前缀(client 传的是 displayPath 折叠过的路径)
1110
+ const dir = resolve(String(body.dir).startsWith('~') ? join(homedir(), String(body.dir).slice(2)) : body.dir)
1111
+ const stat = await fsP.stat(dir).catch(() => undefined)
1112
+ if (stat === undefined || !stat.isDirectory()) { sendJson(res, 400, { error: `dir not found: ${displayPath(dir)}` }); return }
1113
+ const binary = process.env.EXPERTS_DSH_BIN || 'dsh'
1114
+ const job = createShareRunJob({ binary, prompt: body.prompt, dir, jobs: shareRunJobs, logger: ctx.logger, services: shareServices })
1115
+ sendJson(res, 202, { jobId: job.id, status: job.status })
1116
+ return
1117
+ }
1118
+
1119
+ // GET /experts-management/api/share/run?id= → 任务状态/输出
1120
+ if (req.method === 'GET' && apiPath.endsWith('/experts-management/api/share/run')) {
1121
+ const id = query.get('id') || ''
1122
+ const job = shareRunJobs.get(id)
1123
+ if (job === undefined) { sendJson(res, 404, { error: 'job not found' }); return }
1124
+ sendJson(res, 200, { ...job, output: job.output.slice(-32 * 1024) })
1125
+ return
1126
+ }
1127
+
902
1128
  // GET /experts-management/api/builtin/status
903
1129
  if (req.method === 'GET' && apiPath.endsWith('/experts-management/api/builtin/status')) {
904
1130
  await builtinStateLoaded