@twinsearth/dsh-fang 3.0.8 → 3.0.10

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/cordis.patch.yml CHANGED
@@ -133,3 +133,12 @@
133
133
  routes:
134
134
  enabled: true
135
135
  prefix: /fang
136
+
137
+ # Child plugin of the fang bundle: composer draft/queue journal (client half).
138
+ # The main Web panel is the fang client half itself (package.json dsh.client),
139
+ # so the plugin is fully usable without the PC Electron client.
140
+ - id: fang-web-entry
141
+ name: '@twinsearth/dsh-fang-web-entry'
142
+
143
+ - id: fang-queue-journal
144
+ name: '@twinsearth/dsh-fang-queue-journal'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/dsh-fang",
3
- "version": "3.0.8",
3
+ "version": "3.0.10",
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.",
@@ -33,6 +33,11 @@
33
33
  "dsh": {
34
34
  "bundle": {
35
35
  "patch": "./cordis.patch.yml"
36
+ },
37
+ "client": {
38
+ "platform": "web",
39
+ "immediately": true,
40
+ "inject": []
36
41
  }
37
42
  },
38
43
  "scripts": {
@@ -42,6 +47,10 @@
42
47
  "engines": {
43
48
  "node": ">=22"
44
49
  },
50
+ "optionalDependencies": {
51
+ "@twinsearth/dsh-fang-queue-journal": "0.1.2",
52
+ "@twinsearth/dsh-fang-web-entry": "0.1.1"
53
+ },
45
54
  "repository": {
46
55
  "type": "git",
47
56
  "url": "git+https://github.com/TwinsEarth/dsh-fang.git"
@@ -7,6 +7,7 @@
7
7
  // Forks: every fork owns its own $DSH_HOME, so the same rule isolates it from the mother.
8
8
  import os from 'node:os'
9
9
  import path from 'node:path'
10
+ import fs from 'node:fs'
10
11
 
11
12
  /** `--profile name` > `--profile=name` > $DSH_PROFILE > .../profiles/<name> > 'default' */
12
13
  export function detectProfileTag(argv = process.argv, env = process.env) {
@@ -37,10 +38,28 @@ export function resolveProfileDir(profileTag, env = process.env) {
37
38
  return path.join(resolveDshHome(env), 'profiles', profileTag)
38
39
  }
39
40
 
40
- /** 用户级数据根:$FANG_HOME(默认由安装器设为 D:\fang;未设置时保持旧布局)。 */
41
+ /** 用户级数据根:$FANG_HOME 优先;未设置时新装默认 D:\ToFuture(旧布局有数据则继续用旧布局)。 */
41
42
  export function resolveFangHome(env = process.env) {
42
43
  const raw = env && env.FANG_HOME
43
44
  if (typeof raw === 'string' && raw.trim()) return path.resolve(raw.trim())
45
+ // 迁移指针:<DSH_HOME>/fang/fang-home.txt 第一行写明数据根(无需改环境变量/配置即可切换)。
46
+ try {
47
+ const pointer = path.join(resolveDshHome(env), 'fang', 'fang-home.txt')
48
+ if (fs.existsSync(pointer)) {
49
+ const first = fs.readFileSync(pointer, 'utf8').replace(/^\uFEFF/, '').split(/\r?\n/)[0].trim()
50
+ if (first && path.isAbsolute(first)) return path.resolve(first)
51
+ }
52
+ } catch { /* ignore */ }
53
+ // 兼容:已有 $DSH_HOME/fang/<tag> 数据的安装不搬家,继续旧布局。
54
+ try {
55
+ if (fs.existsSync(path.join(resolveDshHome(env), 'fang'))) return ''
56
+ } catch { /* ignore */ }
57
+ // 新装默认主文件夹(Windows:D:\ToFuture)——只对“真正的默认安装”生效:
58
+ // 显式设置 DSH_HOME(e2e/测试/便携安装)时不得跳盘,否则会写进真实 D: 数据根。
59
+ const explicitDshHome = Boolean(env && String(env.DSH_HOME ?? '').trim())
60
+ if (!explicitDshHome && process.platform === 'win32') {
61
+ try { if (fs.existsSync('D:\\')) return 'D:\\ToFuture' } catch { /* ignore */ }
62
+ }
44
63
  return ''
45
64
  }
46
65
 
@@ -61,13 +80,23 @@ export function resolveFangLayout(options = {}) {
61
80
  } = options
62
81
  const profileTag = detectProfileTag(argv, env)
63
82
  const dshHome = resolveDshHome(env)
64
- const resolvedFangHome = fangHome ? path.resolve(fangHome) : resolveFangHome(env)
83
+ // 显式传入 dataRoot/forksRoot(测试、独立部署)时不要自动跳到 FANG_HOME 默认值,
84
+ // 否则临时目录测试会写进真实的 D:\ToFuture。
85
+ const explicitRoots = Boolean(String(dataRoot ?? '').trim() || String(forksRoot ?? '').trim() || String(bufferRoot ?? '').trim())
86
+ const hasEnvFangHome = Boolean(String(env?.FANG_HOME ?? '').trim())
87
+ const resolvedFangHome = fangHome
88
+ ? path.resolve(fangHome)
89
+ : (explicitRoots && !hasEnvFangHome ? '' : resolveFangHome(env))
65
90
  const dataDir = dataRoot
66
91
  ? path.resolve(dataRoot)
67
92
  : (resolvedFangHome ? path.join(resolvedFangHome, 'mirror', profileTag) : path.join(dshHome, 'fang', profileTag))
93
+ // 三区分离:母体=mirror/<tag>,原身=essence/,分身=forks/,会话/运行态=sessions/。
94
+ const essenceRoot = resolvedFangHome ? path.join(resolvedFangHome, 'essence') : path.join(dataDir, 'essences')
68
95
  const forkHomesDir = forksRoot
69
96
  ? path.resolve(forksRoot)
70
- : (resolvedFangHome ? path.join(resolvedFangHome, 'essence') : path.join(dataDir, 'forks'))
97
+ : (resolvedFangHome ? path.join(resolvedFangHome, 'forks') : path.join(dataDir, 'forks'))
98
+ const sessionsRoot = resolvedFangHome ? path.join(resolvedFangHome, 'sessions') : ''
99
+ const runtimeRoot = resolvedFangHome ? path.join(resolvedFangHome, 'sessions') : path.join(dataDir, 'runtime')
71
100
  return {
72
101
  dataDir,
73
102
  profileTag,
@@ -83,8 +112,9 @@ export function resolveFangLayout(options = {}) {
83
112
  roundsDir: path.join(dataDir, 'rounds'),
84
113
  runDir: path.join(dataDir, 'run'),
85
114
  forkHomesDir,
86
- essenceRoot: forkHomesDir,
87
- sessionsRoot: resolvedFangHome ? path.join(resolvedFangHome, 'sessions') : '',
115
+ essenceRoot,
116
+ runtimeRoot,
117
+ sessionsRoot,
88
118
  }
89
119
  }
90
120
 
@@ -125,7 +125,7 @@ export const AUDIT = {
125
125
  RUNTIME_ERROR: 'runtime-error',
126
126
  }
127
127
 
128
- export const FANG_VERSION = '3.0.8'
128
+ export const FANG_VERSION = '3.0.10'
129
129
 
130
130
  /**
131
131
  * @typedef {object} ForkInfo
@@ -181,6 +181,7 @@ export const ADAPTER_OP = {
181
181
  APPROVALS: 'approvals',
182
182
  APPROVAL_DECIDE: 'approval-decide',
183
183
  ARCHIVE: 'archive',
184
+ FORK_SESSION: 'fork-session',
184
185
  }
185
186
 
186
187
  /** Adapter HTTP route suffixes (fork side). */
@@ -4,18 +4,24 @@ import fs from 'node:fs'
4
4
  import path from 'node:path'
5
5
  import { activateBranch, createBranch, createSession, setBranchStatus } from './branch.mjs'
6
6
 
7
+ /** taskId is a path segment under <dataDir>/tasks; reject separators and traversal. */
8
+ const TASK_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/
9
+
7
10
  export class BranchStore {
8
11
  constructor(dataDir) {
9
12
  this.dataDir = dataDir
10
13
  }
11
14
 
12
15
  file(taskId) {
13
- return path.join(this.dataDir, 'tasks', String(taskId), 'branches.json')
16
+ const id = String(taskId ?? '')
17
+ if (!TASK_ID_RE.test(id)) throw new Error('invalid-task-id')
18
+ return path.join(this.dataDir, 'tasks', id, 'branches.json')
14
19
  }
15
20
 
16
21
  load(taskId) {
22
+ const file = this.file(taskId) // validate outside the read fallback
17
23
  try {
18
- const raw = JSON.parse(fs.readFileSync(this.file(taskId), 'utf8'))
24
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
19
25
  return {
20
26
  sessionId: raw.sessionId,
21
27
  activeBranchId: raw.activeBranchId,
@@ -52,6 +58,16 @@ export class BranchStore {
52
58
  return { ok: true, branch }
53
59
  }
54
60
 
61
+ /** 把分支库的 sessionId 绑定到该分身真实会话(启动/还原时由单会话守卫调用)。 */
62
+ bindSession(taskId, sessionId) {
63
+ const session = this.load(taskId)
64
+ const next = String(sessionId ?? '').trim()
65
+ if (!next || session.sessionId === next) return { ok: true, sessionId: session.sessionId, changed: false }
66
+ session.sessionId = next
67
+ this.save(taskId, session)
68
+ return { ok: true, sessionId: session.sessionId, changed: true }
69
+ }
70
+
55
71
  activate(taskId, branchId) {
56
72
  const session = this.load(taskId)
57
73
  const branch = activateBranch(session, branchId)
@@ -3,38 +3,60 @@
3
3
  import fs from 'node:fs'
4
4
  import path from 'node:path'
5
5
 
6
+ /** Branch/session ids become directory names; keep them to safe single segments. */
7
+ export const BRANCH_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
8
+ export const SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/
9
+
10
+ function assertBranchId(branchId) {
11
+ const id = String(branchId ?? '')
12
+ if (!BRANCH_ID_RE.test(id)) throw new Error('invalid-branch-id')
13
+ return id
14
+ }
15
+
16
+ function assertSessionId(sessionId) {
17
+ const id = String(sessionId ?? '')
18
+ if (!SESSION_ID_RE.test(id)) throw new Error('invalid-session-id')
19
+ return id
20
+ }
21
+
6
22
  export function createSession(sessionId) {
7
23
  const main = { branchId: 'main', parentBranchId: null, baseTurn: 0, status: 'active', createdAt: Date.now() }
8
24
  return { sessionId, activeBranchId: 'main', branches: new Map([['main', main]]) }
9
25
  }
10
26
 
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')
27
+ export function createBranch(session, { branchId, parentBranchId = session.activeBranchId, baseTurn = 0, sessionId = null }) {
28
+ const id = assertBranchId(branchId)
29
+ if (id === 'main') throw new Error('invalid-branch-id')
30
+ if (session.branches.has(id)) throw new Error('branch-exists')
14
31
  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)
32
+ session.branches.set(id, {
33
+ branchId: id, parentBranchId, baseTurn, status: 'active', createdAt: Date.now(),
34
+ sessionId: typeof sessionId === 'string' && sessionId.trim() ? sessionId.trim() : null,
35
+ })
36
+ return session.branches.get(id)
17
37
  }
18
38
 
19
39
  export function activateBranch(session, branchId) {
20
- const branch = session.branches.get(branchId)
40
+ const id = assertBranchId(branchId)
41
+ const branch = session.branches.get(id)
21
42
  if (!branch) throw new Error('branch-missing')
22
43
  if (branch.status !== 'active') throw new Error('branch-not-active')
23
- session.activeBranchId = branchId
44
+ session.activeBranchId = id
24
45
  return branch
25
46
  }
26
47
 
27
48
  export function setBranchStatus(session, branchId, status) {
49
+ const id = assertBranchId(branchId)
28
50
  if (!['sealed', 'archived'].includes(status)) throw new Error('invalid-status')
29
- const branch = session.branches.get(branchId)
51
+ const branch = session.branches.get(id)
30
52
  if (!branch) throw new Error('branch-missing')
31
- if (branchId === session.activeBranchId) throw new Error('cannot-seal-active')
53
+ if (id === session.activeBranchId) throw new Error('cannot-seal-active')
32
54
  branch.status = status
33
55
  return branch
34
56
  }
35
57
 
36
58
  export function branchPath(root, sessionId, branchId) {
37
- return path.join(root, sessionId, 'branches', branchId)
59
+ return path.join(root, assertSessionId(sessionId), 'branches', assertBranchId(branchId))
38
60
  }
39
61
 
40
62
  export function acquireWriter(root, sessionId, branchId) {
@@ -24,6 +24,7 @@ export const COMPAT_EXCLUDED_PLUGINS = Object.freeze(['imports.mjs'])
24
24
  /** 路由契约:客户端升级后仍必须存在的核心路由(诊断/升级/镜像)。 */
25
25
  export const REQUIRED_ROUTE_PATHS = Object.freeze([
26
26
  '/fang/api/status',
27
+ '/fang/api/auth-token',
27
28
  '/fang/api/mirror/status',
28
29
  '/fang/api/mirror/upgrade',
29
30
  '/fang/api/mirror/recompute-status',
@@ -32,8 +33,9 @@ export const REQUIRED_ROUTE_PATHS = Object.freeze([
32
33
  '/fang/api/upgrade/status',
33
34
  '/fang/api/tasks/branches',
34
35
  '/fang/api/reflow/policy',
36
+ '/fang/api/composer/journal',
35
37
  ])
36
- export const DEFAULT_EXPECTED_ROUTE_COUNT = 67
38
+ export const DEFAULT_EXPECTED_ROUTE_COUNT = 69
37
39
 
38
40
  /**
39
41
  * 列出需要做导入检查的插件模块文件(排序稳定)。
@@ -100,10 +102,17 @@ export async function runCompatGate(options) {
100
102
 
101
103
  // 3) 路由契约:数量 + 必需路径
102
104
  const routeCount = routePaths === null ? expectedRouteCount : routePaths.length
103
- if (routePaths !== null && routeCount !== expectedRouteCount) {
105
+ // 只把「路由凭空少了」当错误:新增路由(例如带进程 token 的连接信息)不应
106
+ // 让整个子插件集被关掉;数量增长记一条 warning,保持可见但不拦。
107
+ if (routePaths !== null && routeCount < expectedRouteCount) {
104
108
  findings.push({
105
109
  code: 'route-count-mismatch', severity: 'error',
106
- message: `路由数量 ${routeCount} != 期望 ${expectedRouteCount}`,
110
+ message: `路由数量 ${routeCount} < 期望 ${expectedRouteCount}`,
111
+ })
112
+ } else if (routePaths !== null && routeCount > expectedRouteCount) {
113
+ findings.push({
114
+ code: 'route-count-growth', severity: 'warning',
115
+ message: `路由数量 ${routeCount} > 期望 ${expectedRouteCount}(新增路由,非错误)`,
107
116
  })
108
117
  }
109
118
  if (routePaths !== null) {
@@ -0,0 +1,75 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Composer journal: persist the user's unsent draft and queued-message mirror so a
3
+ // restart/crash can offer recovery. It never sends anything by itself.
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+
7
+ const MAX_DRAFT = 100_000
8
+ const MAX_QUEUE = 100
9
+ const MAX_ITEM = 4_000
10
+
11
+ function cleanText(value, limit) {
12
+ return String(value ?? '').replace(/\0/g, '').slice(0, limit)
13
+ }
14
+
15
+ export class ComposerJournal {
16
+ constructor(dataDir) {
17
+ this.file = path.join(dataDir, 'composer-journal.json')
18
+ }
19
+
20
+ load() {
21
+ try {
22
+ const raw = JSON.parse(fs.readFileSync(this.file, 'utf8'))
23
+ return raw && typeof raw === 'object' ? raw : {}
24
+ } catch { return {} }
25
+ }
26
+
27
+ saveFile(all) {
28
+ fs.mkdirSync(path.dirname(this.file), { recursive: true })
29
+ const tmp = this.file + '.tmp'
30
+ fs.writeFileSync(tmp, JSON.stringify(all, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })
31
+ fs.renameSync(tmp, this.file)
32
+ }
33
+
34
+ get(key) {
35
+ const entry = this.load()[String(key)]
36
+ return entry && typeof entry === 'object' ? entry : null
37
+ }
38
+
39
+ save(key, input = {}) {
40
+ const id = cleanText(key, 200)
41
+ if (!id) throw new Error('journal-key-required')
42
+ const queue = Array.isArray(input.queue)
43
+ ? input.queue.slice(-MAX_QUEUE).map((item) => ({
44
+ text: cleanText(item?.text, MAX_ITEM),
45
+ at: Number(item?.at) || Date.now(),
46
+ })).filter((item) => item.text.trim())
47
+ : []
48
+ const entry = {
49
+ key: id,
50
+ draft: cleanText(input.draft, MAX_DRAFT),
51
+ queue,
52
+ path: cleanText(input.path, 500),
53
+ updatedAt: new Date().toISOString(),
54
+ }
55
+ const all = this.load()
56
+ all[id] = entry
57
+ // Keep the journal bounded: 100 sessions is plenty for recovery.
58
+ const keys = Object.keys(all)
59
+ if (keys.length > 100) {
60
+ keys.sort((a, b) => String(all[a]?.updatedAt || '').localeCompare(String(all[b]?.updatedAt || '')))
61
+ for (const stale of keys.slice(0, keys.length - 100)) delete all[stale]
62
+ }
63
+ this.saveFile(all)
64
+ return entry
65
+ }
66
+
67
+ remove(key) {
68
+ const all = this.load()
69
+ const id = String(key)
70
+ if (!all[id]) return false
71
+ delete all[id]
72
+ this.saveFile(all)
73
+ return true
74
+ }
75
+ }
@@ -0,0 +1,61 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // 新用户默认“元宝”:安装不激活 / 安装并激活 两组插件,以及本机插件配置复制选项。
3
+ export const DEFAULT_ESSENCE_NAME = '默认元宝'
4
+
5
+ export const DEFAULT_ESSENCE_PRESET = Object.freeze({
6
+ version: 1,
7
+ groups: Object.freeze([
8
+ {
9
+ key: 'installed-inactive',
10
+ title: '安装不激活',
11
+ enabled: false,
12
+ specs: Object.freeze([
13
+ '@twinsearth/dsh-2xray',
14
+ '@michengai/dsh-agency-agents',
15
+ 'dsh-better-sidebar',
16
+ 'dsh-context',
17
+ '@liustack/modlens',
18
+ '@liustack/modsearch',
19
+ ]),
20
+ },
21
+ {
22
+ key: 'installed-active',
23
+ title: '安装并激活',
24
+ enabled: true,
25
+ specs: Object.freeze([
26
+ 'dshmarket',
27
+ '@twinsearth/dsh-im2a-plugin',
28
+ '@openviking/dsh-memory-plugin',
29
+ '@twinsearth/w2m-dsh-plugin',
30
+ ]),
31
+ },
32
+ ]),
33
+ })
34
+
35
+ /** 从 pluginManager.listPlugins() 的结果里判断某个包是否已安装(模糊匹配包名末尾)。 */
36
+ export function matchInstalled(entries, spec) {
37
+ const wanted = String(spec ?? '').toLowerCase()
38
+ const bare = wanted.includes('/') ? wanted.split('/').pop() : wanted
39
+ for (const entry of entries ?? []) {
40
+ const name = String(entry?.name ?? entry?.id ?? '').toLowerCase()
41
+ if (!name) continue
42
+ if (name === wanted || name.endsWith('/' + bare) || name.includes(bare)) return entry
43
+ }
44
+ return null
45
+ }
46
+
47
+ export function planDefaultEssence(entries) {
48
+ return {
49
+ name: DEFAULT_ESSENCE_NAME,
50
+ version: DEFAULT_ESSENCE_PRESET.version,
51
+ groups: DEFAULT_ESSENCE_PRESET.groups.map((group) => ({
52
+ key: group.key,
53
+ title: group.title,
54
+ enabled: group.enabled,
55
+ plugins: group.specs.map((spec) => {
56
+ const hit = matchInstalled(entries, spec)
57
+ return { spec, installed: Boolean(hit), pluginId: hit?.id ?? null }
58
+ }),
59
+ })),
60
+ }
61
+ }