@twinsearth/dsh-fang 3.0.7 → 3.0.8

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/client.js CHANGED
@@ -346,6 +346,21 @@ window.__ModuleLoader__.load({
346
346
  } catch { /* 旧宿主没有 auth-token 路由:保持空 token */ }
347
347
  return fangAuthToken
348
348
  }
349
+ // v3.0.8 诊断日志:面板内所有错误集中展示,供开发/调试查看。
350
+ const diagLog = []
351
+ function diag(level, message, detail = '') {
352
+ const entry = {
353
+ at: Date.now(),
354
+ level: String(level || 'bad'),
355
+ message: String(message ?? ''),
356
+ detail: String(detail ?? '').slice(0, 2000),
357
+ }
358
+ diagLog.push(entry)
359
+ if (diagLog.length > 3000) diagLog.shift()
360
+ try { window.__fangUiLog?.push?.({ kind: 'diag', level: entry.level, message: entry.message }) } catch { /* ignore */ }
361
+ try { window.dispatchEvent(new CustomEvent('fang:diag')) } catch { /* ignore */ }
362
+ }
363
+
349
364
  async function api(path, options) {
350
365
  const url = String(path)
351
366
  const token = await ensureFangAuthToken()
@@ -360,7 +375,9 @@ window.__ModuleLoader__.load({
360
375
  ...(options ?? {}),
361
376
  })
362
377
  } catch (error) {
363
- return { status: 0, body: null, diagnostic: { url, message: String(error?.message ?? error) } }
378
+ const message = String(error?.message ?? error)
379
+ diag('bad', '网络请求失败:' + url, message)
380
+ return { status: 0, body: null, diagnostic: { url, message } }
364
381
  }
365
382
  const etag = (res.headers && typeof res.headers.get === 'function' && res.headers.get('etag')) || ''
366
383
  if (res.status === 304) return { status: 304, body: null, notModified: true, etag }
@@ -1076,6 +1093,7 @@ window.__ModuleLoader__.load({
1076
1093
  }
1077
1094
  const notify = (tone, text, options = {}) => {
1078
1095
  S.toast = { tone, text, id: Date.now() + Math.random() }
1096
+ if (tone === 'bad' || tone === 'warn') diag(tone, text)
1079
1097
  if (toastTimer) window.clearTimeout(toastTimer)
1080
1098
  toastTimer = window.setTimeout(() => { if (alive) { S.toast = null; render() } }, options.sticky ? 8000 : 4200)
1081
1099
  if (tone === 'bad') announce(text, 'assertive')
@@ -1584,6 +1602,14 @@ window.__ModuleLoader__.load({
1584
1602
  beginRename, commitRename, cancelRename, selectSession, toggleSet, toggleForkGroup,
1585
1603
  toggleTemporary, setView: (next) => { S.view = next; schedule(true) },
1586
1604
  loadForkSessions, loadMirror, mirrorAction, loadLink, probeMother, notify, announce,
1605
+ backupMother: () => mirrorAction('backup', async () => (await api('/fang/api/mirror/backup', {
1606
+ method: 'POST', body: JSON.stringify({ bucket: 'restore', label: '手动备份' }),
1607
+ })).body),
1608
+ diagnostics: {
1609
+ list: () => diagLog.slice(-3000),
1610
+ push: (level, message, detail) => diag(level, message, detail),
1611
+ clear: () => { diagLog.length = 0; try { window.dispatchEvent(new CustomEvent('fang:diag')) } catch { /* ignore */ } },
1612
+ },
1587
1613
  setEditingValue: (value) => { if (S.editing) S.editing.value = value },
1588
1614
  getEditing: () => S.editing,
1589
1615
  setModalError: (message) => { if (S.modal) { S.modal.error = message; render(true) } },
@@ -1795,7 +1821,7 @@ window.__ModuleLoader__.load({
1795
1821
  }, ...slots)
1796
1822
  }
1797
1823
 
1798
- function toggleMotherPalette(anchor) {
1824
+ function toggleMotherPalette(anchor, app) {
1799
1825
  const host = anchor?.parentElement
1800
1826
  if (!host) return
1801
1827
  const existing = host.querySelector('[data-zone="palette"]')
@@ -1809,9 +1835,8 @@ window.__ModuleLoader__.load({
1809
1835
  borderRadius: '12px', boxShadow: '0 12px 32px rgba(0,0,0,.18)',
1810
1836
  },
1811
1837
  },
1812
- h('button', { type: 'button', class: 'btn btn--ghost btn--sm', 'data-btn-id': 'mother-clone', onClick: () => app.notify('warn', '克隆母体尚未接线') }, '克隆(PC 客户端)'),
1813
1838
  h('button', { type: 'button', class: 'btn btn--ghost btn--sm', 'data-btn-id': 'mother-open', onClick: () => openMotherPortal() }, '打开母体 Web'),
1814
- h('button', { type: 'button', class: 'btn btn--ghost btn--sm', 'data-btn-id': 'mother-backup', onClick: () => app.notify('warn', '备份入口尚未接线') }, '备份当前母体'))
1839
+ h('button', { type: 'button', class: 'btn btn--ghost btn--sm', 'data-btn-id': 'mother-backup', onClick: () => app.backupMother() }, '备份当前母体'))
1815
1840
  host.style.position = 'relative'
1816
1841
  host.appendChild(palette)
1817
1842
  if (!window.__fangPaletteEsc) {
@@ -1860,7 +1885,7 @@ window.__ModuleLoader__.load({
1860
1885
  const motherButton = button('Mother', {
1861
1886
  variant: 'ghost', size: 'sm', icon: icon('globe', 14),
1862
1887
  title: '母体浮窗:版本、备份、升级与连接自检(只读优先,写操作均二次确认)',
1863
- onClick: (event) => toggleMotherPalette(event?.currentTarget),
1888
+ onClick: (event) => toggleMotherPalette(event?.currentTarget, app),
1864
1889
  fk: 'mother', dataBtnId: 'M-04',
1865
1890
  })
1866
1891
  motherButton.addEventListener('dblclick', (event) => {
@@ -2829,6 +2854,203 @@ window.__ModuleLoader__.load({
2829
2854
  return React.createElement('div', { ref, className: 'fang-mount', style: props.style || { display: 'block', minWidth: 0 } })
2830
2855
  }
2831
2856
 
2857
+ function mountDiagnostics(app) {
2858
+ const doc = document
2859
+ const btn = doc.createElement('button')
2860
+ btn.id = 'fang-diag-btn'
2861
+ btn.setAttribute('data-btn-id', 'LOG-01')
2862
+ btn.type = 'button'
2863
+ btn.textContent = '日志'
2864
+ Object.assign(btn.style, {
2865
+ position: 'fixed', right: '16px', bottom: '16px', zIndex: '9999',
2866
+ height: '34px', padding: '0 12px', borderRadius: '10px',
2867
+ border: '1px solid rgba(127,127,127,.4)', background: '#fff', color: '#111',
2868
+ font: '600 13px/1 system-ui, sans-serif', cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,.18)',
2869
+ })
2870
+ const overlay = doc.createElement('div')
2871
+ overlay.id = 'fang-diag-panel'
2872
+ overlay.hidden = true
2873
+ Object.assign(overlay.style, {
2874
+ position: 'fixed', right: '16px', bottom: '58px', zIndex: '9999',
2875
+ width: 'min(520px, calc(100vw - 32px))', maxHeight: '60vh', overflow: 'auto',
2876
+ background: '#fff', color: '#111', border: '1px solid rgba(127,127,127,.35)',
2877
+ borderRadius: '12px', boxShadow: '0 12px 40px rgba(0,0,0,.25)', padding: '10px',
2878
+ font: '12px/1.5 ui-monospace, SFMono-Regular, Consolas, monospace',
2879
+ })
2880
+ const head = doc.createElement('div')
2881
+ head.style.cssText = 'display:flex;align-items:center;gap:6px;margin-bottom:8px;flex-wrap:wrap'
2882
+ const title = doc.createElement('strong')
2883
+ title.textContent = '瓮城日志'
2884
+ let filter = 'all'
2885
+ let limit = 100
2886
+ const filterButtons = []
2887
+ const makeFilter = (key, label, id) => {
2888
+ const b = doc.createElement('button')
2889
+ b.type = 'button'; b.textContent = label; b.setAttribute('data-btn-id', id)
2890
+ b.style.cssText = 'height:24px;padding:0 8px;border-radius:7px;border:1px solid rgba(127,127,127,.4);background:transparent;color:inherit;cursor:pointer;font:inherit'
2891
+ b.onclick = () => { filter = key; limit = 100; renderLogs() }
2892
+ filterButtons.push({ key, b })
2893
+ return b
2894
+ }
2895
+ const spacer = doc.createElement('span')
2896
+ spacer.style.flex = '1'
2897
+ const clear = doc.createElement('button')
2898
+ clear.type = 'button'; clear.textContent = '清空'; clear.setAttribute('data-btn-id', 'LOG-02')
2899
+ clear.onclick = () => { app.diagnostics.clear(); limit = 100 }
2900
+ const close = doc.createElement('button')
2901
+ close.type = 'button'; close.textContent = '关闭'; close.setAttribute('data-btn-id', 'LOG-03')
2902
+ close.onclick = () => { overlay.hidden = true }
2903
+ head.append(title, makeFilter('all', '全部', 'LOG-05'), makeFilter('bad', '错误', 'LOG-06'), makeFilter('warn', '警告', 'LOG-07'), spacer, clear, close)
2904
+ const list = doc.createElement('div')
2905
+ const loadMore = doc.createElement('button')
2906
+ loadMore.type = 'button'; loadMore.setAttribute('data-btn-id', 'LOG-04')
2907
+ loadMore.style.cssText = 'margin-top:8px;height:30px;width:100%;border-radius:8px;border:1px dashed rgba(127,127,127,.45);background:transparent;color:inherit;cursor:pointer;font:inherit'
2908
+ loadMore.onclick = () => { limit += 300; renderLogs() }
2909
+ overlay.append(head, list, loadMore)
2910
+ function renderLogs() {
2911
+ const all = app.diagnostics.list()
2912
+ const entries = all.filter((entry) => filter === 'all' || entry.level === filter).slice().reverse()
2913
+ list.replaceChildren()
2914
+ btn.textContent = all.length ? `日志 (${all.length})` : '日志'
2915
+ for (const { key, b } of filterButtons) {
2916
+ b.style.background = key === filter ? 'rgba(127,127,127,.18)' : 'transparent'
2917
+ b.style.fontWeight = key === filter ? '700' : '400'
2918
+ }
2919
+ if (!entries.length) {
2920
+ const empty = doc.createElement('div')
2921
+ empty.textContent = filter === 'all' ? '暂无报错或警告' : (filter === 'bad' ? '暂无错误' : '暂无警告')
2922
+ empty.style.opacity = '.6'
2923
+ list.append(empty)
2924
+ loadMore.hidden = true
2925
+ return
2926
+ }
2927
+ for (const entry of entries.slice(0, limit)) {
2928
+ const row = doc.createElement('div')
2929
+ row.setAttribute('data-fang-log-row', '1')
2930
+ row.style.cssText = 'padding:6px 0;border-top:1px solid rgba(127,127,127,.18);white-space:pre-wrap;word-break:break-word'
2931
+ const when = new Date(entry.at).toLocaleTimeString()
2932
+ row.textContent = `[${when}] ${entry.level} · ${entry.message}${entry.detail ? '\n' + entry.detail : ''}`
2933
+ if (entry.level === 'bad') row.style.color = '#b42318'
2934
+ else if (entry.level === 'warn') row.style.color = '#b54708'
2935
+ list.append(row)
2936
+ }
2937
+ const remaining = entries.length - Math.min(limit, entries.length)
2938
+ loadMore.hidden = remaining <= 0
2939
+ loadMore.textContent = remaining > 0 ? `加载更多(剩余 ${remaining})` : ''
2940
+ }
2941
+ btn.onclick = () => { overlay.hidden = !overlay.hidden; renderLogs() }
2942
+ const onDiag = () => renderLogs()
2943
+ const onError = (event) => app.diagnostics.push('bad', event.message || 'window error', `${event.filename || ''}:${event.lineno || ''}`)
2944
+ const onRejection = (event) => app.diagnostics.push('bad', 'unhandledrejection', String(event.reason?.message ?? event.reason ?? ''))
2945
+ window.addEventListener('fang:diag', onDiag)
2946
+ window.addEventListener('error', onError)
2947
+ window.addEventListener('unhandledrejection', onRejection)
2948
+ doc.body.append(btn, overlay)
2949
+ renderLogs()
2950
+ return () => {
2951
+ window.removeEventListener('fang:diag', onDiag)
2952
+ window.removeEventListener('error', onError)
2953
+ window.removeEventListener('unhandledrejection', onRejection)
2954
+ btn.remove()
2955
+ overlay.remove()
2956
+ }
2957
+ }
2958
+
2959
+ function mountConnectionInfo(app) {
2960
+ const doc = document
2961
+ const trigger = doc.createElement('button')
2962
+ trigger.id = 'fang-conn-trigger'
2963
+ trigger.type = 'button'
2964
+ trigger.setAttribute('data-btn-id', 'CONN-00')
2965
+ trigger.textContent = '连接信息'
2966
+ Object.assign(trigger.style, {
2967
+ position: 'fixed', left: '16px', bottom: '16px', zIndex: '9999',
2968
+ height: '34px', padding: '0 12px', borderRadius: '10px',
2969
+ border: '1px solid rgba(127,127,127,.4)', background: '#fff', color: '#111',
2970
+ font: '600 13px/1 system-ui, sans-serif', cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,.18)',
2971
+ })
2972
+ const popup = doc.createElement('div')
2973
+ popup.id = 'fang-conn-popup'
2974
+ popup.hidden = true
2975
+ Object.assign(popup.style, {
2976
+ position: 'fixed', left: '16px', bottom: '58px', zIndex: '9999',
2977
+ display: 'none', alignItems: 'center', gap: '6px', maxWidth: 'calc(100vw - 32px)',
2978
+ padding: '6px 8px', borderRadius: '10px', background: '#fff', color: '#111',
2979
+ border: '1px solid rgba(127,127,127,.35)', boxShadow: '0 4px 14px rgba(0,0,0,.14)',
2980
+ font: '12px/1.4 ui-monospace, Consolas, monospace',
2981
+ })
2982
+ const label = doc.createElement('span')
2983
+ label.id = 'fang-conn-url'
2984
+ label.style.cssText = 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:42vw'
2985
+ const eye = doc.createElement('button')
2986
+ eye.type = 'button'
2987
+ eye.setAttribute('data-btn-id', 'CONN-01')
2988
+ eye.textContent = '显示'
2989
+ const copy = doc.createElement('button')
2990
+ copy.type = 'button'
2991
+ copy.setAttribute('data-btn-id', 'CONN-02')
2992
+ copy.textContent = '复制'
2993
+ const close = doc.createElement('button')
2994
+ close.type = 'button'
2995
+ close.setAttribute('data-btn-id', 'CONN-03')
2996
+ close.textContent = '关闭'
2997
+ for (const btn of [eye, copy, close]) {
2998
+ btn.style.cssText = 'height:28px;padding:0 8px;border-radius:8px;border:1px solid rgba(127,127,127,.4);background:transparent;color:inherit;cursor:pointer;font:inherit'
2999
+ }
3000
+ let full = ''
3001
+ let baseUrl = ''
3002
+ let revealed = false
3003
+ let opened = false
3004
+ let loaded = false
3005
+ const mask = (url) => {
3006
+ try {
3007
+ const token = new URL(url).searchParams.get('token') || ''
3008
+ return String(url).replace(/([?&]token=)[^&]*/, (_, prefix) => prefix + '•'.repeat(Math.min(16, token.length || 8)))
3009
+ } catch { return url }
3010
+ }
3011
+ const render = () => {
3012
+ popup.hidden = !opened
3013
+ popup.style.display = opened ? 'flex' : 'none'
3014
+ if (!opened) { label.textContent = ''; label.title = ''; return }
3015
+ label.textContent = full && revealed ? full : (baseUrl ? baseUrl + '/?token=••••••••' : '连接信息加载中…')
3016
+ label.title = revealed ? full : ''
3017
+ eye.textContent = revealed ? '隐藏' : '显示'
3018
+ }
3019
+ const load = async () => {
3020
+ if (loaded) return
3021
+ loaded = true
3022
+ try {
3023
+ const info = await window.fangShell?.desktopInfo?.()
3024
+ if (info?.upstream) baseUrl = String(info.upstream).replace(/\/+$/, '')
3025
+ } catch { /* ignore */ }
3026
+ if (!baseUrl) baseUrl = String(location.origin || '')
3027
+ }
3028
+ trigger.onclick = async () => {
3029
+ opened = !opened
3030
+ if (opened) await load()
3031
+ revealed = false
3032
+ render()
3033
+ }
3034
+ eye.onclick = async () => {
3035
+ if (!revealed) {
3036
+ try {
3037
+ const info = await window.fangShell?.revealToken?.()
3038
+ if (info?.token) full = baseUrl + '/?token=' + encodeURIComponent(String(info.token))
3039
+ } catch { /* ignore */ }
3040
+ }
3041
+ revealed = !revealed
3042
+ render()
3043
+ }
3044
+ copy.onclick = async () => {
3045
+ try { await navigator.clipboard.writeText(full); app.notify('ok', '已复制连接地址') } catch { app.notify('warn', '复制失败:浏览器未授权剪贴板') }
3046
+ }
3047
+ close.onclick = () => { opened = false; revealed = false; render() }
3048
+ popup.append(label, eye, copy, close)
3049
+ doc.body.append(trigger, popup)
3050
+ render()
3051
+ return () => { trigger.remove(); popup.remove() }
3052
+ }
3053
+
2832
3054
  function mountPanel(host) {
2833
3055
  // v3.0.7 UI 分析日志:记录面板挂载与所有按钮/链接点击,供自动冒烟/诊断读取
2834
3056
  try {
@@ -2850,7 +3072,10 @@ window.__ModuleLoader__.load({
2850
3072
  window.__fangUiLog.push({ at: Date.now(), kind: 'panel-mount' })
2851
3073
  } catch { /* 宿主无 window 时忽略 */ }
2852
3074
  const app = createConsole(host)
2853
- return () => app.destroy()
3075
+ const unmountDiagnostics = mountDiagnostics(app)
3076
+ const unmountConnection = mountConnectionInfo(app)
3077
+ try { host.ownerDocument?.getElementById('fang-fallback')?.remove() } catch { /* ignore */ }
3078
+ return () => { unmountConnection(); unmountDiagnostics(); app.destroy() }
2854
3079
  }
2855
3080
 
2856
3081
  // 左侧导航图标:单击由宿主行负责打开面板;双击 = 快速派生(与面板按钮同一单飞)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/dsh-fang",
3
- "version": "3.0.7",
3
+ "version": "3.0.8",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "dsh-Fang (瓮城) — mother/fork plugin development environment for DeepSeek Harness: one readonly mother, a disposable child dsh-Web per task.",
@@ -37,6 +37,13 @@ export function resolveProfileDir(profileTag, env = process.env) {
37
37
  return path.join(resolveDshHome(env), 'profiles', profileTag)
38
38
  }
39
39
 
40
+ /** 用户级数据根:$FANG_HOME(默认由安装器设为 D:\fang;未设置时保持旧布局)。 */
41
+ export function resolveFangHome(env = process.env) {
42
+ const raw = env && env.FANG_HOME
43
+ if (typeof raw === 'string' && raw.trim()) return path.resolve(raw.trim())
44
+ return ''
45
+ }
46
+
40
47
  /**
41
48
  * Every path a Fang plugin needs. Pure: no directory is created here.
42
49
  * @returns {{dataDir:string, profileTag:string, dshHome:string, ledgerFile:string, stateFile:string,
@@ -48,16 +55,24 @@ export function resolveFangLayout(options = {}) {
48
55
  dataRoot = '',
49
56
  bufferRoot = '',
50
57
  forksRoot = '',
58
+ fangHome = '',
51
59
  env = process.env,
52
60
  argv = process.argv,
53
61
  } = options
54
62
  const profileTag = detectProfileTag(argv, env)
55
63
  const dshHome = resolveDshHome(env)
56
- const dataDir = dataRoot ? path.resolve(dataRoot) : path.join(dshHome, 'fang', profileTag)
64
+ const resolvedFangHome = fangHome ? path.resolve(fangHome) : resolveFangHome(env)
65
+ const dataDir = dataRoot
66
+ ? path.resolve(dataRoot)
67
+ : (resolvedFangHome ? path.join(resolvedFangHome, 'mirror', profileTag) : path.join(dshHome, 'fang', profileTag))
68
+ const forkHomesDir = forksRoot
69
+ ? path.resolve(forksRoot)
70
+ : (resolvedFangHome ? path.join(resolvedFangHome, 'essence') : path.join(dataDir, 'forks'))
57
71
  return {
58
72
  dataDir,
59
73
  profileTag,
60
74
  dshHome,
75
+ fangHome: resolvedFangHome,
61
76
  ledgerFile: path.join(dataDir, 'audit.jsonl'),
62
77
  stateFile: path.join(dataDir, 'state.json'),
63
78
  forksFile: path.join(dataDir, 'forks.json'),
@@ -67,7 +82,9 @@ export function resolveFangLayout(options = {}) {
67
82
  snapshotsDir: path.join(dataDir, 'snapshots'),
68
83
  roundsDir: path.join(dataDir, 'rounds'),
69
84
  runDir: path.join(dataDir, 'run'),
70
- forkHomesDir: forksRoot ? path.resolve(forksRoot) : path.join(dataDir, 'forks'),
85
+ forkHomesDir,
86
+ essenceRoot: forkHomesDir,
87
+ sessionsRoot: resolvedFangHome ? path.join(resolvedFangHome, 'sessions') : '',
71
88
  }
72
89
  }
73
90
 
@@ -125,7 +125,7 @@ export const AUDIT = {
125
125
  RUNTIME_ERROR: 'runtime-error',
126
126
  }
127
127
 
128
- export const FANG_VERSION = '3.0.7'
128
+ export const FANG_VERSION = '3.0.8'
129
129
 
130
130
  /**
131
131
  * @typedef {object} ForkInfo
@@ -0,0 +1,68 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // v3.0.8 branch persistence: one JSON file per task under <dataDir>/tasks/<taskId>/branches.json.
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { activateBranch, createBranch, createSession, setBranchStatus } from './branch.mjs'
6
+
7
+ export class BranchStore {
8
+ constructor(dataDir) {
9
+ this.dataDir = dataDir
10
+ }
11
+
12
+ file(taskId) {
13
+ return path.join(this.dataDir, 'tasks', String(taskId), 'branches.json')
14
+ }
15
+
16
+ load(taskId) {
17
+ try {
18
+ const raw = JSON.parse(fs.readFileSync(this.file(taskId), 'utf8'))
19
+ return {
20
+ sessionId: raw.sessionId,
21
+ activeBranchId: raw.activeBranchId,
22
+ branches: new Map(Object.entries(raw.branches || {})),
23
+ }
24
+ } catch {
25
+ return createSession(String(taskId))
26
+ }
27
+ }
28
+
29
+ save(taskId, session) {
30
+ const file = this.file(taskId)
31
+ fs.mkdirSync(path.dirname(file), { recursive: true })
32
+ const payload = {
33
+ sessionId: session.sessionId,
34
+ activeBranchId: session.activeBranchId,
35
+ branches: Object.fromEntries(session.branches),
36
+ }
37
+ const tmp = file + '.tmp'
38
+ fs.writeFileSync(tmp, JSON.stringify(payload, null, 2) + '\n', 'utf8')
39
+ fs.renameSync(tmp, file)
40
+ return payload
41
+ }
42
+
43
+ list(taskId) {
44
+ const session = this.load(taskId)
45
+ return { ok: true, sessionId: session.sessionId, activeBranchId: session.activeBranchId, branches: [...session.branches.values()] }
46
+ }
47
+
48
+ create(taskId, input) {
49
+ const session = this.load(taskId)
50
+ const branch = createBranch(session, input)
51
+ this.save(taskId, session)
52
+ return { ok: true, branch }
53
+ }
54
+
55
+ activate(taskId, branchId) {
56
+ const session = this.load(taskId)
57
+ const branch = activateBranch(session, branchId)
58
+ this.save(taskId, session)
59
+ return { ok: true, branch, activeBranchId: session.activeBranchId }
60
+ }
61
+
62
+ setStatus(taskId, branchId, status) {
63
+ const session = this.load(taskId)
64
+ const branch = setBranchStatus(session, branchId, status)
65
+ this.save(taskId, session)
66
+ return { ok: true, branch }
67
+ }
68
+ }
@@ -0,0 +1,52 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // v3.0.8 branch model: one session, many branch logs, one writer per branch, no merge.
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+
6
+ export function createSession(sessionId) {
7
+ const main = { branchId: 'main', parentBranchId: null, baseTurn: 0, status: 'active', createdAt: Date.now() }
8
+ return { sessionId, activeBranchId: 'main', branches: new Map([['main', main]]) }
9
+ }
10
+
11
+ export function createBranch(session, { branchId, parentBranchId = session.activeBranchId, baseTurn = 0 }) {
12
+ if (!branchId || branchId === 'main') throw new Error('invalid-branch-id')
13
+ if (session.branches.has(branchId)) throw new Error('branch-exists')
14
+ if (!session.branches.has(parentBranchId)) throw new Error('parent-missing')
15
+ session.branches.set(branchId, { branchId, parentBranchId, baseTurn, status: 'active', createdAt: Date.now() })
16
+ return session.branches.get(branchId)
17
+ }
18
+
19
+ export function activateBranch(session, branchId) {
20
+ const branch = session.branches.get(branchId)
21
+ if (!branch) throw new Error('branch-missing')
22
+ if (branch.status !== 'active') throw new Error('branch-not-active')
23
+ session.activeBranchId = branchId
24
+ return branch
25
+ }
26
+
27
+ export function setBranchStatus(session, branchId, status) {
28
+ if (!['sealed', 'archived'].includes(status)) throw new Error('invalid-status')
29
+ const branch = session.branches.get(branchId)
30
+ if (!branch) throw new Error('branch-missing')
31
+ if (branchId === session.activeBranchId) throw new Error('cannot-seal-active')
32
+ branch.status = status
33
+ return branch
34
+ }
35
+
36
+ export function branchPath(root, sessionId, branchId) {
37
+ return path.join(root, sessionId, 'branches', branchId)
38
+ }
39
+
40
+ export function acquireWriter(root, sessionId, branchId) {
41
+ const dir = branchPath(root, sessionId, branchId)
42
+ fs.mkdirSync(dir, { recursive: true })
43
+ const lock = path.join(dir, 'writer.lock')
44
+ try {
45
+ fs.writeFileSync(lock, String(process.pid), { flag: 'wx' })
46
+ } catch {
47
+ const error = new Error('branch-busy')
48
+ error.code = '409'
49
+ throw error
50
+ }
51
+ return { release() { try { fs.rmSync(lock, { force: true }) } catch { /* ignore */ } } }
52
+ }
@@ -0,0 +1,67 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // v3.0.9 read-only broker adapter: issues only read capabilities. Write is intentionally absent.
3
+ const READ_ROOTS = new Set(['essence', 'sessions'])
4
+
5
+ export function issueReadCapability(broker, identity, root) {
6
+ if (!READ_ROOTS.has(root)) throw new Error('read-root-not-allowed')
7
+ const role = identity?.role
8
+ if (!role) throw new Error('identity-missing')
9
+ return broker.issue({
10
+ role,
11
+ root,
12
+ op: 'read',
13
+ essenceId: String(identity.essenceId || ''),
14
+ forkId: String(identity.forkId || ''),
15
+ })
16
+ }
17
+
18
+ export function checkReadCapability(broker, token, scope) {
19
+ if (!READ_ROOTS.has(scope?.root)) return { ok: false, error: 'access-denied', reason: 'read-root-not-allowed' }
20
+ return broker.resolve({
21
+ token,
22
+ root: scope.root,
23
+ op: 'read',
24
+ essenceId: scope.essenceId || '',
25
+ ownerEssenceId: scope.ownerEssenceId || '',
26
+ forkId: scope.forkId || '',
27
+ ownerForkId: scope.ownerForkId || '',
28
+ path: scope.path || '',
29
+ })
30
+ }
31
+
32
+ function headerValue(headers, name) {
33
+ const key = Object.keys(headers || {}).find((k) => k.toLowerCase() === name)
34
+ return key ? headers[key] : ''
35
+ }
36
+
37
+ export function resolveIdentity({ headers = {}, url = '/' }, resolveToken) {
38
+ const auth = String(headerValue(headers, 'x-fang-auth') || '')
39
+ const bearer = /^Bearer\s+(.+)$/i.exec(String(headerValue(headers, 'authorization') || ''))?.[1] || ''
40
+ let query = ''
41
+ try { query = new URL(url, 'http://127.0.0.1').searchParams.get('token') || '' } catch { /* ignore */ }
42
+ const token = auth || bearer || query
43
+ if (!token) return { ok: false, status: 401, error: 'unauthorized' }
44
+ if (typeof resolveToken !== 'function') return { ok: false, status: 401, error: 'unauthorized' }
45
+ const identity = resolveToken(token)
46
+ if (!identity) return { ok: false, status: 401, error: 'unauthorized' }
47
+ if (identity.denied) return { ok: false, status: 403, error: 'access-denied', reason: String(identity.reason || 'denied') }
48
+ if (!identity.role) return { ok: false, status: 401, error: 'unauthorized' }
49
+ return {
50
+ ok: true,
51
+ token,
52
+ role: String(identity.role),
53
+ essenceId: String(identity.essenceId || ''),
54
+ forkId: String(identity.forkId || ''),
55
+ }
56
+ }
57
+
58
+ export function denialToHttp(result) {
59
+ if (result?.ok) return null
60
+ const status = result?.status === 403 ? 403 : 401
61
+ return {
62
+ status,
63
+ body: status === 403
64
+ ? { ok: false, error: 'access-denied', reason: String(result?.reason || 'denied') }
65
+ : { ok: false, error: 'unauthorized' },
66
+ }
67
+ }
@@ -0,0 +1,45 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+
3
+ import crypto from 'node:crypto'
4
+ import { canAccess } from './roots.mjs'
5
+
6
+ export class Broker {
7
+ constructor(secret) {
8
+ this.secret = secret || crypto.randomBytes(32)
9
+ this.audit = []
10
+ }
11
+
12
+ issue({ role, root, op, essenceId = '', forkId = '', ttlMs = 60_000 }) {
13
+ const payload = Buffer.from(JSON.stringify({ role, root, op, essenceId, forkId, exp: Date.now() + ttlMs })).toString('base64url')
14
+ const sig = crypto.createHmac('sha256', this.secret).update(payload).digest('base64url')
15
+ return `${payload}.${sig}`
16
+ }
17
+
18
+ verify(token) {
19
+ const [payload, sig] = String(token || '').split('.')
20
+ if (!payload || !sig) return null
21
+ const expected = crypto.createHmac('sha256', this.secret).update(payload).digest('base64url')
22
+ if (sig.length !== expected.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))) return null
23
+ try {
24
+ const caps = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
25
+ if (!caps.exp || caps.exp < Date.now()) return null
26
+ return caps
27
+ } catch { return null }
28
+ }
29
+
30
+ resolve({ token, root, op, essenceId = '', ownerEssenceId = '', forkId = '', ownerForkId = '', path = '' }) {
31
+ const caps = this.verify(token)
32
+ const deny = (reason) => {
33
+ this.audit.push({ ok: false, reason, root, op, essenceId, forkId, at: Date.now() })
34
+ return { ok: false, error: 'access-denied', reason }
35
+ }
36
+ if (!caps) return deny('bad-capability')
37
+ if (caps.root !== root || caps.op !== op) return deny('capability-mismatch')
38
+ if (caps.role !== 'coordinator' && caps.essenceId && ownerEssenceId && caps.essenceId !== ownerEssenceId) return deny('wrong-essence')
39
+ if (caps.role === 'fork' && caps.forkId && ownerForkId && caps.forkId !== ownerForkId) return deny('wrong-fork')
40
+ const allowed = canAccess({ role: caps.role, root, op, essenceId: caps.essenceId || essenceId, ownerEssenceId, forkId: caps.forkId || forkId, ownerForkId, path })
41
+ if (!allowed) return deny('matrix')
42
+ this.audit.push({ ok: true, root, op, essenceId: caps.essenceId, forkId: caps.forkId, at: Date.now() })
43
+ return { ok: true, role: caps.role }
44
+ }
45
+ }
@@ -29,8 +29,11 @@ export const REQUIRED_ROUTE_PATHS = Object.freeze([
29
29
  '/fang/api/mirror/recompute-status',
30
30
  '/fang/api/compat',
31
31
  '/fang/api/essence/list',
32
+ '/fang/api/upgrade/status',
33
+ '/fang/api/tasks/branches',
34
+ '/fang/api/reflow/policy',
32
35
  ])
33
- export const DEFAULT_EXPECTED_ROUTE_COUNT = 61
36
+ export const DEFAULT_EXPECTED_ROUTE_COUNT = 67
34
37
 
35
38
  /**
36
39
  * 列出需要做导入检查的插件模块文件(排序稳定)。
@@ -0,0 +1,30 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // v3.0.9 fail-closed path guard: canonicalize and keep every path inside its root.
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+
6
+ export function safeJoin(root, ...parts) {
7
+ const base = path.resolve(root)
8
+ const target = path.resolve(base, ...parts)
9
+ if (target !== base && !target.startsWith(base + path.sep)) throw new Error('path-escape')
10
+ if (String(target).includes('\0')) throw new Error('path-escape')
11
+ return target
12
+ }
13
+
14
+ export function assertInside(root, target, { followSymlink = true } = {}) {
15
+ const base = path.resolve(root)
16
+ let resolved = path.resolve(target)
17
+ if (followSymlink) {
18
+ try { resolved = fs.realpathSync.native(resolved) } catch {
19
+ try { resolved = path.join(fs.realpathSync.native(path.dirname(resolved)), path.basename(resolved)) } catch { /* keep lexical */ }
20
+ }
21
+ try {
22
+ const realBase = fs.realpathSync.native(base)
23
+ if (resolved !== realBase && !resolved.startsWith(realBase + path.sep)) throw new Error('path-escape')
24
+ } catch (error) {
25
+ if (error?.message === 'path-escape') throw error
26
+ }
27
+ }
28
+ if (resolved !== base && !resolved.startsWith(base + path.sep)) throw new Error('path-escape')
29
+ return resolved
30
+ }
@@ -0,0 +1,41 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // v3.0.8 reflow: seal → verify → quarantine → adopt. No merge, no config/credential upload.
3
+ export const REFLOW_STATES = Object.freeze(['sealed', 'verified', 'quarantine', 'adopted'])
4
+
5
+ const NEXT = {
6
+ sealed: 'verified', // seal → verify
7
+ verified: 'adopted', // verify → adopt
8
+ quarantine: 'adopted', // only after explicit quarantine resolution
9
+ adopted: null,
10
+ }
11
+
12
+ const FORBIDDEN_KEYS = new Set(['token', 'password', 'secret', 'credential', 'auth', 'cookie', 'sessionkey', 'apikey'])
13
+
14
+ export function transition(current, event) {
15
+ if (event === 'quarantine') {
16
+ if (current !== 'verified') return { ok: false, error: 'invalid-transition' }
17
+ return { ok: true, state: 'quarantine' }
18
+ }
19
+ if (event === 'adopt' && current === 'verified') return { ok: true, state: 'adopted' }
20
+ if (event === 'recover' && current === 'quarantine') return { ok: true, state: 'verified' }
21
+ return { ok: false, error: 'invalid-transition' }
22
+ }
23
+
24
+ export function assertSafeArtifact(artifact) {
25
+ const walk = (value) => {
26
+ if (Array.isArray(value)) return value.forEach(walk)
27
+ if (!value || typeof value !== 'object') return
28
+ for (const [key, child] of Object.entries(value)) {
29
+ if (FORBIDDEN_KEYS.has(String(key).toLowerCase())) throw new Error('reflow-forbidden-field:' + key)
30
+ walk(child)
31
+ }
32
+ }
33
+ walk(artifact)
34
+ return true
35
+ }
36
+
37
+ export function canAdopt(state, artifact) {
38
+ if (state !== 'verified') return { ok: false, error: 'not-verified' }
39
+ try { assertSafeArtifact(artifact) } catch (error) { return { ok: false, error: String(error.message) } }
40
+ return { ok: true }
41
+ }
@@ -0,0 +1,30 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+
3
+ export const ROOTS = Object.freeze({ MIRROR: 'mirror', ESSENCE: 'essence', SESSIONS: 'sessions' })
4
+ export const ROLES = Object.freeze({ COORDINATOR: 'coordinator', MOTHER: 'mother', ESSENCE: 'essence', FORK: 'fork' })
5
+
6
+ const MATRIX = {
7
+ [ROLES.COORDINATOR]: { mirror: 'rw', essence: 'rw', sessions: 'rw' },
8
+ [ROLES.MOTHER]: { mirror: 'r', essence: 'none', sessions: 'none' },
9
+ [ROLES.ESSENCE]: { mirror: 'r', essence: 'rw', sessions: 'none' },
10
+ [ROLES.FORK]: { mirror: 'none', essence: 'r', sessions: 'rw' },
11
+ }
12
+
13
+ export function decisionFor(role, root) {
14
+ const row = MATRIX[role]
15
+ if (!row || !Object.prototype.hasOwnProperty.call(row, root)) return 'none'
16
+ return row[root]
17
+ }
18
+
19
+ export function canAccess({ role, root, op, essenceId, ownerEssenceId, forkId, ownerForkId, path }) {
20
+ const base = decisionFor(role, root)
21
+ if (base === 'none') return false
22
+ if (base === 'r' && op === 'write') return false
23
+ if (role === ROLES.ESSENCE && root === ROOTS.ESSENCE && essenceId && ownerEssenceId && essenceId !== ownerEssenceId) return false
24
+ if (role === ROLES.FORK) {
25
+ if (root === ROOTS.ESSENCE && essenceId && ownerEssenceId && essenceId !== ownerEssenceId) return false
26
+ if (root === ROOTS.SESSIONS && forkId && ownerForkId && forkId !== ownerForkId) return false
27
+ }
28
+ if (typeof path === 'string' && (path.includes('..') || path.includes('\0'))) return false
29
+ return true
30
+ }
@@ -0,0 +1,20 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // v3.0.9 read-only upgrade status. Pure function: no IO, no upgrade/backup side effects.
3
+ export function buildUpgradeStatus({ version = '', mirror = null, essences = [] } = {}) {
4
+ const current = mirror?.current ?? null
5
+ const latest = mirror?.latest ?? null
6
+ const mother = {
7
+ current,
8
+ latest,
9
+ updateAvailable: Boolean(current && latest && current !== latest),
10
+ lastBackupAt: Number(mirror?.lastBackupAt) || 0,
11
+ backupIntervalHours: [6, 12, 24].includes(Number(mirror?.backupIntervalHours)) ? Number(mirror.backupIntervalHours) : 24,
12
+ }
13
+ const list = Array.isArray(essences) ? essences.map((e) => ({
14
+ id: String(e?.id ?? ''),
15
+ name: String(e?.name ?? ''),
16
+ status: String(e?.status ?? 'unknown'),
17
+ stale: Boolean(e?.stale),
18
+ })) : []
19
+ return { ok: true, version: String(version || ''), mother, essences: list, operation: null }
20
+ }
@@ -27,8 +27,10 @@ import { PreferencesStore } from '../lib/preferences.mjs'
27
27
  import { EssenceManager, OFFICIAL_ESSENCE_ID } from '../lib/essence.mjs'
28
28
  import { MirrorUpgradeCoordinator } from '../lib/upgrade-coordinator.mjs'
29
29
  import { DEFAULT_EXPECTED_ROUTE_COUNT, readCompatStatus, runCompatGate, writeCompatStatus } from '../lib/compat.mjs'
30
+ import { buildUpgradeStatus } from '../lib/upgrade-status.mjs'
30
31
  import { checkRequestAuth, loadAuthToken } from '../lib/http-auth.mjs'
31
32
  import { buildEssenceActions, buildTaskActions } from '../lib/ui-actions.mjs'
33
+ import { BranchStore } from '../lib/branch-store.mjs'
32
34
  import { fileURLToPath } from 'node:url'
33
35
  import zlib from 'node:zlib'
34
36
 
@@ -151,6 +153,7 @@ export function apply(ctx, config) {
151
153
  const role = gate.role
152
154
 
153
155
  const layout = resolveFangLayout({ dataRoot: cfg.dataRoot, forksRoot: cfg.forksRoot })
156
+ const branchStore = new BranchStore(layout.dataDir)
154
157
  // v3.0.5/B1:安装级 token(0600 文件 / env / 显式配置);关闭仅限测试
155
158
  const authToken = cfg.authEnabled === false
156
159
  ? ''
@@ -1387,11 +1390,22 @@ export function apply(ctx, config) {
1387
1390
  }), { public: true })
1388
1391
 
1389
1392
  route('GET', `${prefix}/api/status`, (req, res) => json(res, 200, service.status()))
1393
+ route('GET', `${prefix}/api/upgrade/status`, (req, res) => {
1394
+ let mirror = null
1395
+ let essences = []
1396
+ try { mirror = service.status()?.mirror ?? null } catch { /* empty */ }
1397
+ try { essences = service.listEssences?.() ?? [] } catch { /* empty */ }
1398
+ return json(res, 200, buildUpgradeStatus({ version: FANG_VERSION, mirror, essences }))
1399
+ })
1390
1400
  route('GET', `${prefix}/api/tasks`, (req, res) => json(res, 200, { ok: true, tasks: service.listTasks() }))
1391
1401
  route('POST', `${prefix}/api/tasks/create`, async (req, res) => {
1392
1402
  const body = await readBody(req)
1393
- const out = await service.createTask({ title: body?.title, template: body?.template, collaborators: body?.collaborators })
1394
- return json(res, out.ok ? 200 : 409, out)
1403
+ try {
1404
+ const out = await service.createTask({ title: body?.title, template: body?.template, collaborators: body?.collaborators })
1405
+ return json(res, out.ok ? 200 : 409, out)
1406
+ } catch (error) {
1407
+ return json(res, 500, { ok: false, error: String(error?.message ?? error) })
1408
+ }
1395
1409
  })
1396
1410
  route('GET', `${prefix}/api/tasks/status`, async (req, res) => {
1397
1411
  const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
@@ -1601,6 +1615,55 @@ export function apply(ctx, config) {
1601
1615
  })
1602
1616
  return json(res, out.ok ? 200 : 409, out)
1603
1617
  })
1618
+ // v3.0.8 分支 HTTP 面(注册在末尾,避免影响既有路由初始化顺序)
1619
+ route('GET', `${prefix}/api/tasks/branches`, (req, res) => {
1620
+ const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
1621
+ const taskId = String(query.get('taskId') ?? '')
1622
+ if (!taskId) return json(res, 400, { ok: false, error: 'taskId-required' })
1623
+ return json(res, 200, branchStore.list(taskId))
1624
+ })
1625
+ route('POST', `${prefix}/api/tasks/branches`, async (req, res) => {
1626
+ const body = await readBody(req)
1627
+ const taskId = String(body?.taskId ?? '')
1628
+ if (!taskId) return json(res, 400, { ok: false, error: 'taskId-required' })
1629
+ try {
1630
+ return json(res, 200, branchStore.create(taskId, {
1631
+ branchId: String(body?.branchId ?? ''),
1632
+ parentBranchId: body?.parentBranchId ? String(body.parentBranchId) : undefined,
1633
+ baseTurn: Number(body?.baseTurn) || 0,
1634
+ }))
1635
+ } catch (error) {
1636
+ return json(res, 400, { ok: false, error: String(error?.message ?? error) })
1637
+ }
1638
+ })
1639
+ route('POST', `${prefix}/api/tasks/branches/activate`, async (req, res) => {
1640
+ const body = await readBody(req)
1641
+ try {
1642
+ return json(res, 200, branchStore.activate(String(body?.taskId ?? ''), String(body?.branchId ?? '')))
1643
+ } catch (error) {
1644
+ return json(res, 400, { ok: false, error: String(error?.message ?? error) })
1645
+ }
1646
+ })
1647
+ route('POST', `${prefix}/api/tasks/branches/status`, async (req, res) => {
1648
+ const body = await readBody(req)
1649
+ try {
1650
+ return json(res, 200, branchStore.setStatus(String(body?.taskId ?? ''), String(body?.branchId ?? ''), String(body?.status ?? '')))
1651
+ } catch (error) {
1652
+ return json(res, 400, { ok: false, error: String(error?.message ?? error) })
1653
+ }
1654
+ })
1655
+ route('GET', `${prefix}/api/reflow/policy`, (req, res) => json(res, 200, {
1656
+ ok: true,
1657
+ states: ['sealed', 'verified', 'quarantine', 'adopted'],
1658
+ transitions: {
1659
+ sealed: ['verified'],
1660
+ verified: ['quarantine', 'adopted'],
1661
+ quarantine: ['verified'],
1662
+ adopted: [],
1663
+ },
1664
+ forbiddenFields: ['token', 'password', 'secret', 'credential', 'auth', 'cookie', 'sessionkey', 'apikey'],
1665
+ merge: false,
1666
+ }))
1604
1667
  })
1605
1668
  }
1606
1669
  }
@@ -0,0 +1,121 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // v3.0.8 MCP stdio server: JSON-RPC 2.0, 8 default tools + opId polling.
3
+ import path from 'node:path'
4
+ import { pathToFileURL } from 'node:url'
5
+ import { TOOLS, OpStore, listTools } from './tools.mjs'
6
+
7
+ const META_TOOLS = [
8
+ { name: 'get_op', description: '轮询长任务 opId(不假取消)', inputSchema: { type: 'object', properties: { opId: { type: 'string' } }, required: ['opId'] } },
9
+ { name: 'abandon_op', description: '放弃轮询;不宣称已停止服务端任务', inputSchema: { type: 'object', properties: { opId: { type: 'string' } }, required: ['opId'] } },
10
+ ]
11
+
12
+ export function createHandlers({ callTool, clock = Date.now } = {}) {
13
+ const ops = new OpStore({ clock })
14
+ const defs = [...listTools(), ...META_TOOLS]
15
+ const names = new Set(defs.map((tool) => tool.name))
16
+ const call = async (name, args = {}) => {
17
+ if (name === 'get_op') return ops.get(args.opId)
18
+ if (name === 'abandon_op') return ops.abandon(args.opId)
19
+ if (!names.has(name)) throw new Error('tool-not-found: ' + name)
20
+ const spec = TOOLS.find((tool) => tool.name === name)
21
+ if (spec?.kind === 'op') return ops.start(name, args, () => callTool(name, args))
22
+ return callTool(name, args)
23
+ }
24
+ return { defs, call }
25
+ }
26
+
27
+ export function createServer({ callTool } = {}) {
28
+ const handlers = createHandlers({ callTool })
29
+ return async function handleRequest(request) {
30
+ const { id = null, method, params } = request || {}
31
+ const reply = (result) => ({ jsonrpc: '2.0', id, result })
32
+ const fail = (code, message) => ({ jsonrpc: '2.0', id, error: { code, message } })
33
+ try {
34
+ if (method === 'initialize') {
35
+ return reply({
36
+ protocolVersion: '2024-11-05',
37
+ capabilities: { tools: {} },
38
+ serverInfo: { name: 'dsh-fang', version: '3.0.8' },
39
+ })
40
+ }
41
+ if (method === 'ping') return reply({})
42
+ if (method === 'tools/list') {
43
+ return reply({ tools: handlers.defs.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) })
44
+ }
45
+ if (method === 'tools/call') {
46
+ const name = String(params?.name || '')
47
+ const result = await handlers.call(name, params?.arguments || {})
48
+ return reply({ content: [{ type: 'text', text: JSON.stringify(result) }], isError: Boolean(result && result.ok === false) })
49
+ }
50
+ return fail(-32601, 'method not found: ' + method)
51
+ } catch (error) {
52
+ return fail(-32603, String(error?.message ?? error))
53
+ }
54
+ }
55
+ }
56
+
57
+ const SENSITIVE_KEYS = new Set(['token', 'authtoken', 'datadir', 'clipath', 'template', 'password', 'secret', 'cookie'])
58
+
59
+ function sanitize(value) {
60
+ if (Array.isArray(value)) return value.map(sanitize)
61
+ if (!value || typeof value !== 'object') return value
62
+ const out = {}
63
+ for (const [key, child] of Object.entries(value)) {
64
+ if (SENSITIVE_KEYS.has(String(key).toLowerCase())) continue
65
+ out[key] = sanitize(child)
66
+ }
67
+ return out
68
+ }
69
+
70
+ export function createHttpCallTool({ baseUrl, token, fetchImpl = fetch }) {
71
+ const base = String(baseUrl || '').replace(/\/+$/, '')
72
+ const route = {
73
+ status: ['GET', '/fang/api/status'],
74
+ tasks: ['GET', '/fang/api/tasks'],
75
+ task_status: ['GET', '/fang/api/tasks/status'],
76
+ essence_list: ['GET', '/fang/api/essence/list'],
77
+ upgrade_status: ['GET', '/fang/api/upgrade/status'],
78
+ compat: ['GET', '/fang/api/compat'],
79
+ derive: ['POST', '/fang/api/derive'],
80
+ archive: ['POST', '/fang/api/tasks/archive'],
81
+ }
82
+ return async function callTool(name, args = {}) {
83
+ const entry = route[name]
84
+ if (!entry) throw new Error('tool-not-configured: ' + name)
85
+ const [method, routePath] = entry
86
+ let url = base + routePath
87
+ if (name === 'task_status') url += '?taskId=' + encodeURIComponent(String(args.taskId || ''))
88
+ const headers = { accept: 'application/json' }
89
+ if (token) headers['x-fang-auth'] = token
90
+ const init = { method, headers }
91
+ if (method === 'POST') {
92
+ headers['content-type'] = 'application/json'
93
+ init.body = JSON.stringify(args)
94
+ }
95
+ const response = await fetchImpl(url, init)
96
+ const body = await response.json().catch(() => ({}))
97
+ return { ok: response.ok && body.ok !== false, status: response.status, body: sanitize(body) }
98
+ }
99
+ }
100
+
101
+ async function main() {
102
+ const readline = await import('node:readline')
103
+ const baseUrl = process.env.FANG_URL || process.env.FANG_UPSTREAM || 'http://127.0.0.1:61758'
104
+ const token = process.env.FANG_TOKEN || process.env.DSH_FANG_AUTH_TOKEN || ''
105
+ const handle = createServer({ callTool: createHttpCallTool({ baseUrl, token }) })
106
+ const rl = readline.createInterface({ input: process.stdin })
107
+ rl.on('line', async (line) => {
108
+ if (!line.trim()) return
109
+ let request
110
+ try { request = JSON.parse(line) } catch {
111
+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } }) + '\n')
112
+ return
113
+ }
114
+ const response = await handle(request)
115
+ if (response) process.stdout.write(JSON.stringify(response) + '\n')
116
+ })
117
+ }
118
+
119
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
120
+ main().catch((error) => { console.error(error); process.exit(1) })
121
+ }
@@ -0,0 +1,65 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // v3.0.8 MCP tool registry: 8 default tools, 4 high-risk hidden, opId idempotency, no fake cancel.
3
+ import crypto from 'node:crypto'
4
+
5
+ export const HIGH_RISK_TOOLS = Object.freeze(['promote', 'delete', 'restart', 'mirror_upgrade'])
6
+
7
+ export const TOOLS = Object.freeze([
8
+ { name: 'status', description: '母体/宿主状态(只读)', kind: 'sync', inputSchema: { type: 'object', properties: {} } },
9
+ { name: 'tasks', description: '分身任务列表(只读)', kind: 'sync', inputSchema: { type: 'object', properties: {} } },
10
+ { name: 'task_status', description: '单个分身任务状态(只读)', kind: 'sync', inputSchema: { type: 'object', properties: { taskId: { type: 'string' } }, required: ['taskId'] } },
11
+ { name: 'derive', description: '派生新分身', kind: 'op', inputSchema: { type: 'object', properties: { title: { type: 'string' } } } },
12
+ { name: 'archive', description: '归档分身(保留 home)', kind: 'op', inputSchema: { type: 'object', properties: { taskId: { type: 'string' } }, required: ['taskId'] } },
13
+ { name: 'essence_list', description: '元主/原身列表(只读)', kind: 'sync', inputSchema: { type: 'object', properties: {} } },
14
+ { name: 'upgrade_status', description: '升级状态(只读)', kind: 'sync', inputSchema: { type: 'object', properties: {} } },
15
+ { name: 'compat', description: 'compat 门禁状态(只读)', kind: 'sync', inputSchema: { type: 'object', properties: {} } },
16
+ ...HIGH_RISK_TOOLS.map((name) => ({
17
+ name, description: '高风险工具(默认不暴露)', kind: 'op', highRisk: true,
18
+ inputSchema: { type: 'object', properties: {} },
19
+ })),
20
+ ])
21
+
22
+ export function listTools({ includeHighRisk = false } = {}) {
23
+ return TOOLS.filter((tool) => includeHighRisk || !tool.highRisk)
24
+ }
25
+
26
+ export class OpStore {
27
+ constructor({ clock = Date.now, timeoutMs = 120_000 } = {}) {
28
+ this.clock = clock
29
+ this.timeoutMs = timeoutMs
30
+ this.ops = new Map()
31
+ this.keys = new Map()
32
+ }
33
+
34
+ start(name, args = {}, run) {
35
+ const key = args.idempotencyKey ? `${name}:${args.idempotencyKey}` : ''
36
+ if (key && this.keys.has(key)) return { ok: true, opId: this.keys.get(key), deduped: true }
37
+ const opId = 'op_' + crypto.randomBytes(8).toString('hex')
38
+ this.ops.set(opId, { opId, name, state: 'running', abandoned: false, startedAt: this.clock(), result: null, error: null })
39
+ if (key) this.keys.set(key, opId)
40
+ Promise.resolve().then(run).then((result) => {
41
+ const op = this.ops.get(opId)
42
+ if (!op || op.state !== 'running') return
43
+ op.state = 'completed'; op.result = result ?? null
44
+ }).catch((error) => {
45
+ const op = this.ops.get(opId)
46
+ if (!op || op.state !== 'running') return
47
+ op.state = 'failed'; op.error = String(error?.message ?? error)
48
+ })
49
+ return { ok: true, opId, deduped: false }
50
+ }
51
+
52
+ get(opId) {
53
+ const op = this.ops.get(String(opId))
54
+ if (!op) return { ok: false, error: 'op-not-found' }
55
+ if (op.state === 'running' && this.clock() - op.startedAt > this.timeoutMs) op.state = 'timeout'
56
+ return { ok: true, opId: op.opId, name: op.name, state: op.state, abandoned: op.abandoned, result: op.result, error: op.error }
57
+ }
58
+
59
+ abandon(opId) {
60
+ const op = this.ops.get(String(opId))
61
+ if (!op) return { ok: false, error: 'op-not-found' }
62
+ op.abandoned = true
63
+ return { ok: true, opId: op.opId, state: op.state, abandoned: true }
64
+ }
65
+ }