@twinsearth/dsh-fang 3.1.10 → 3.1.12
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 +114 -1
- package/docs/FORK-SEED.md +64 -0
- package/package.json +1 -1
- package/src/kernel/types.mjs +1 -1
- package/src/lib/fork-seed.mjs +304 -0
- package/src/lib/pnpm-store.mjs +5 -0
- package/src/plugins/adapter.mjs +5 -0
- package/src/plugins/forker.mjs +36 -0
- package/src/plugins/orchestrator.mjs +1 -1
package/client.js
CHANGED
|
@@ -435,6 +435,109 @@ window.__ModuleLoader__.load({
|
|
|
435
435
|
return { status: res.status, body, etag }
|
|
436
436
|
}
|
|
437
437
|
|
|
438
|
+
// ── Web 端角色徽标(母体 / 元主 / 分身)──────────────────────────────
|
|
439
|
+
// 同一个 Fang 插件同时运行在三种 Web 实例里;侧栏 HARNESS 右侧用红字标出当前身份,
|
|
440
|
+
// 避免“每次进来不知道是哪个”。宿主侧栏品牌行是 DSH 壳自己的 DOM,单槽
|
|
441
|
+
// (sidebar.brand.name)替换会抹掉官方词标,因此这里在词标后**追加**一个只读徽标,
|
|
442
|
+
// 并在宿主重渲染把节点摘掉时自动补回。
|
|
443
|
+
const WEB_ROLE_LABEL = Object.freeze({ mother: '母体', essence: '元主', fork: '分身' })
|
|
444
|
+
const WEB_ROLE_BADGE_ID = 'fang-web-role-badge'
|
|
445
|
+
async function detectWebRole() {
|
|
446
|
+
// 母体:/fang/api/status 由母体路由提供,role=mother。
|
|
447
|
+
try {
|
|
448
|
+
const status = await api('/fang/api/status')
|
|
449
|
+
if (status.status === 200 && status.body && status.body.ok !== false) {
|
|
450
|
+
const role = String(status.body.role ?? 'mother')
|
|
451
|
+
if (role === 'mother') return 'mother'
|
|
452
|
+
}
|
|
453
|
+
} catch { /* fall through to adapter handshake */ }
|
|
454
|
+
// 元主 / 分身:两者都是 fork 角色的 DSH 实例;adapter hello 给出 kind。
|
|
455
|
+
try {
|
|
456
|
+
const hello = await api('/fang/adapter/hello')
|
|
457
|
+
if (hello.status === 200 && hello.body) {
|
|
458
|
+
const kind = String(hello.body.kind ?? '')
|
|
459
|
+
if (kind === 'mother' || kind === 'essence' || kind === 'fork') return kind
|
|
460
|
+
// 旧宿主没有 kind:元宝运行态的 forkId 是 rt-<essenceId>,任务是 task_/标题 id。
|
|
461
|
+
const taskId = String(hello.body.taskId ?? '')
|
|
462
|
+
return /^rt-/.test(taskId) ? 'essence' : 'fork'
|
|
463
|
+
}
|
|
464
|
+
} catch { /* unknown */ }
|
|
465
|
+
return ''
|
|
466
|
+
}
|
|
467
|
+
function mountWebRoleBadge() {
|
|
468
|
+
if (typeof document === 'undefined') return () => {}
|
|
469
|
+
try { injectStyle(document) } catch { /* style optional */ }
|
|
470
|
+
let role = ''
|
|
471
|
+
let timer = 0
|
|
472
|
+
let observer = null
|
|
473
|
+
let observed = null
|
|
474
|
+
const findBrandName = () => {
|
|
475
|
+
const candidates = document.querySelectorAll('[class*="brandName"]')
|
|
476
|
+
for (const node of candidates) {
|
|
477
|
+
if (node && node.parentElement && node.closest('[class*="brand"], [class*="brandIdentity"]')) return node
|
|
478
|
+
}
|
|
479
|
+
return candidates[0] ?? null
|
|
480
|
+
}
|
|
481
|
+
const paint = (el) => {
|
|
482
|
+
if (!el) return
|
|
483
|
+
const label = WEB_ROLE_LABEL[role] ?? ''
|
|
484
|
+
const hidden = label === ''
|
|
485
|
+
const title = label ? ('当前 Web 端:' + label) : '正在识别 Web 端身份…'
|
|
486
|
+
// Idempotent: the mutation observer watches this parent, so rewriting an
|
|
487
|
+
// unchanged text node would feed itself and spin forever.
|
|
488
|
+
if (el.textContent !== label) el.textContent = label
|
|
489
|
+
if (el.hidden !== hidden) el.hidden = hidden
|
|
490
|
+
if (el.dataset.fangWebRole !== role) el.dataset.fangWebRole = role
|
|
491
|
+
if (el.title !== title) el.title = title
|
|
492
|
+
if (el.getAttribute('aria-label') !== title) el.setAttribute('aria-label', title)
|
|
493
|
+
}
|
|
494
|
+
const place = () => {
|
|
495
|
+
if (!document || !document.body) return false
|
|
496
|
+
let el = document.getElementById(WEB_ROLE_BADGE_ID)
|
|
497
|
+
if (el && el.isConnected && el.parentElement) { paint(el); return true }
|
|
498
|
+
const brandName = findBrandName()
|
|
499
|
+
if (!brandName || !brandName.parentElement) return false
|
|
500
|
+
el = document.createElement('span')
|
|
501
|
+
el.id = WEB_ROLE_BADGE_ID
|
|
502
|
+
el.className = 'fang-web-role'
|
|
503
|
+
el.setAttribute('role', 'status')
|
|
504
|
+
el.setAttribute('aria-live', 'polite')
|
|
505
|
+
brandName.parentElement.insertBefore(el, brandName.nextSibling)
|
|
506
|
+
paint(el)
|
|
507
|
+
// 宿主重渲染只可能发生在品牌行内部:盯住它的父节点,摘掉就补回。
|
|
508
|
+
if (observer) { try { observer.disconnect() } catch { /* ignore */ } }
|
|
509
|
+
observer = new MutationObserver(() => { try { place() } catch { /* ignore */ } })
|
|
510
|
+
try { observer.observe(brandName.parentElement, { childList: true, subtree: true }) } catch { /* ignore */ }
|
|
511
|
+
observed = brandName.parentElement
|
|
512
|
+
return true
|
|
513
|
+
}
|
|
514
|
+
const install = () => {
|
|
515
|
+
if (place()) { if (timer) { clearInterval(timer); timer = 0 } return true }
|
|
516
|
+
return false
|
|
517
|
+
}
|
|
518
|
+
install()
|
|
519
|
+
// 侧栏可能晚于插件激活渲染;最多等 20s,不无限占定时器。
|
|
520
|
+
if (!document.getElementById(WEB_ROLE_BADGE_ID)) {
|
|
521
|
+
let tries = 0
|
|
522
|
+
timer = setInterval(() => {
|
|
523
|
+
tries += 1
|
|
524
|
+
if (install() || tries >= 80) { clearInterval(timer); timer = 0 }
|
|
525
|
+
}, 250)
|
|
526
|
+
}
|
|
527
|
+
void (async () => {
|
|
528
|
+
const detected = await detectWebRole()
|
|
529
|
+
if (!detected) return
|
|
530
|
+
role = detected
|
|
531
|
+
install()
|
|
532
|
+
})()
|
|
533
|
+
return () => {
|
|
534
|
+
if (timer) { clearInterval(timer); timer = 0 }
|
|
535
|
+
if (observer) { try { observer.disconnect() } catch { /* ignore */ } observer = null }
|
|
536
|
+
void observed
|
|
537
|
+
try { document.getElementById(WEB_ROLE_BADGE_ID)?.remove() } catch { /* ignore */ }
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
438
541
|
function resolveMotherOrigin() {
|
|
439
542
|
// In the Electron shell the panel origin is the loopback proxy, which only
|
|
440
543
|
// serves /fang/api/*; the mother portal lives on the upstream DSH origin.
|
|
@@ -936,6 +1039,14 @@ window.__ModuleLoader__.load({
|
|
|
936
1039
|
.toast--bad{background:rgba(168,13,38,.96)}
|
|
937
1040
|
.toast--warn{background:rgba(120,58,6,.95)}
|
|
938
1041
|
.live{position:absolute!important;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
|
|
1042
|
+
/* Web 端角色徽标:母体 / 元主 / 分身 —— 挂在侧栏品牌词右侧,仅用于识别当前实例身份。 */
|
|
1043
|
+
.fang-web-role{display:inline-flex;align-items:center;height:18px;margin-left:7px;padding:0 6px;border-radius:6px;
|
|
1044
|
+
border:1px solid rgba(200,16,46,.32);background:rgba(200,16,46,.07);color:#C8102E;
|
|
1045
|
+
font-size:11.5px;font-weight:700;letter-spacing:.02em;line-height:1;white-space:nowrap;
|
|
1046
|
+
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif;vertical-align:middle;
|
|
1047
|
+
-webkit-app-region:no-drag;user-select:none}
|
|
1048
|
+
.fang-web-role[hidden]{display:none}
|
|
1049
|
+
.fang-web-role--unknown{visibility:hidden}
|
|
939
1050
|
|
|
940
1051
|
@media (max-width:760px){
|
|
941
1052
|
.fang-console{padding:12px 12px 18px}
|
|
@@ -6009,10 +6120,12 @@ window.__ModuleLoader__.load({
|
|
|
6009
6120
|
// ── 插件入口 ──────────────────────────────────────────────────────────
|
|
6010
6121
|
return {
|
|
6011
6122
|
mountPanel,
|
|
6012
|
-
...(typeof window !== 'undefined' && window.__FANG_TEST_HOOK__ ? { __renderDecisionMini: renderDecisionMini } : {}),
|
|
6123
|
+
...(typeof window !== 'undefined' && window.__FANG_TEST_HOOK__ ? { __renderDecisionMini: renderDecisionMini, __mountWebRoleBadge: mountWebRoleBadge, __detectWebRole: detectWebRole } : {}),
|
|
6013
6124
|
inject: ['slots'],
|
|
6014
6125
|
apply(ctx) {
|
|
6015
6126
|
const disposers = []
|
|
6127
|
+
// v3.1.12:侧栏 HARNESS 右侧的 Web 端身份徽标(母体 / 元主 / 分身)。
|
|
6128
|
+
disposers.push(mountWebRoleBadge())
|
|
6016
6129
|
// 母体 Web = DSH 主会话视图;Web 端直接切回 conversation 面板。
|
|
6017
6130
|
const goMother = () => {
|
|
6018
6131
|
try {
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# FORK-SEED — 派生分身的默认第三方插件
|
|
2
|
+
|
|
3
|
+
> v3.1.12 起:新机器 / 新用户的干净分身不再只有 `base + web-app + fang`,而是按
|
|
4
|
+
> “安装不激活 / 安装并激活”两组清单带上默认第三方插件。
|
|
5
|
+
|
|
6
|
+
## 默认清单(2026-11-11)
|
|
7
|
+
|
|
8
|
+
安装不激活(只进 `dependencies` + `node_modules`,不加入 profile bundles):
|
|
9
|
+
|
|
10
|
+
```text
|
|
11
|
+
@twinsearth/dsh-2xray
|
|
12
|
+
@michengai/dsh-agency-agents
|
|
13
|
+
dsh-better-sidebar
|
|
14
|
+
dsh-context
|
|
15
|
+
@liustack/modlens
|
|
16
|
+
@liustack/modsearch
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
安装并激活(额外写入 `dsh.profile.bundles`,分身启动即加载):
|
|
20
|
+
|
|
21
|
+
```text
|
|
22
|
+
dshmarket
|
|
23
|
+
@twinsearth/dsh-im2a-plugin
|
|
24
|
+
@openviking/dsh-memory-plugin
|
|
25
|
+
@twinsearth/w2m-dsh-plugin
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## 行为
|
|
29
|
+
|
|
30
|
+
- 位置:`fang-forker` 插件 Config 的 `forkSeed`:
|
|
31
|
+
- `enabled`(默认 true);
|
|
32
|
+
- `install[]`、`activate[]`(默认值即上面的清单)。
|
|
33
|
+
- 时机:**每次 spawn**(首次派生与崩溃重启都会走)在启动 DSH 子进程前执行;
|
|
34
|
+
已按指纹缓存,首次安装后重启只重新打 profile patch,不重复安装。
|
|
35
|
+
- 安装:独立 seed home(`<forksRoot>/.plugin-seed/seed-<fingerprint>`)里用 DSH 自带 pnpm
|
|
36
|
+
执行 `dsh plugin --profile seed add ...`;模块树以 hardlink 合并进分身的 `node_modules`,
|
|
37
|
+
不替换 mother 镜像里的运行时包。
|
|
38
|
+
- 两种派生入口(开发者推荐 / 绿色“派生新分身”)都走同一个 `Forker.spawn`,因此清单一致。
|
|
39
|
+
- 失败不阻塞分身启动:结果在 spawn 返回值 `forkSeed`(`ok/error/detail/cached`)与审计中可见。
|
|
40
|
+
- 环境变量 `DSH_FANG_FORK_SEED=0` 可全局关闭(e2e/CI 使用,避免每次联网装包)。
|
|
41
|
+
|
|
42
|
+
## 自定义
|
|
43
|
+
|
|
44
|
+
在母亲 profile 的 Cordis 覆盖层里改 `fang-forker` 的 config,例如:
|
|
45
|
+
|
|
46
|
+
```yaml
|
|
47
|
+
- id: fang-forker
|
|
48
|
+
config:
|
|
49
|
+
forkSeed:
|
|
50
|
+
enabled: true
|
|
51
|
+
install:
|
|
52
|
+
- '@twinsearth/dsh-2xray'
|
|
53
|
+
activate:
|
|
54
|
+
- dshmarket
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`install` 只装不激活;`activate` 会同时进依赖与 profile bundles。包名会做格式校验,
|
|
58
|
+
非法名(路径、参数注入)会被忽略。
|
|
59
|
+
|
|
60
|
+
## 边界
|
|
61
|
+
|
|
62
|
+
- 首次派生需要联网从 npm 安装;离线时分会话仍可启动,只是 `forkSeed.ok=false`。
|
|
63
|
+
- 仅作用于**任务分身**;元宝运行态(`essence-runtime`)继续继承元宝自己的模块树。
|
|
64
|
+
- 已在运行的旧分身在下次重启时补装(配置回放后重新打 patch)。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@twinsearth/dsh-fang",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.12",
|
|
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.",
|
package/src/kernel/types.mjs
CHANGED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
3
|
+
//
|
|
4
|
+
// fork-seed — 派生分身的默认第三方插件种子(v3.1.12)。
|
|
5
|
+
//
|
|
6
|
+
// 新机器/新用户的干净分身模板只有 base + web-app + fang;这里按“安装不激活 /
|
|
7
|
+
// 安装并激活”两组清单,把默认第三方插件装进**每个新分身自己的 profile**:
|
|
8
|
+
// * install = 只写入 dependencies 并安装 node_modules,不加入 profile bundles;
|
|
9
|
+
// * activate = 额外加入 profile 的 dsh.profile.bundles,DSH 启动时就会加载。
|
|
10
|
+
// 安装缓存在 <forkHomes>/.plugin-seed/seed-<fingerprint>,用 dsh 自带 pnpm 完成;
|
|
11
|
+
// 模块树通过 hardlink 合并进分身 `node_modules`,不替换原有的 mother 镜像条目。
|
|
12
|
+
import { spawn } from 'node:child_process'
|
|
13
|
+
import crypto from 'node:crypto'
|
|
14
|
+
import fs from 'node:fs'
|
|
15
|
+
import path from 'node:path'
|
|
16
|
+
|
|
17
|
+
import { ensureDir, exists, hardlinkTree, isLink, removeTree, writeJsonAtomic } from '../kernel/index.mjs'
|
|
18
|
+
|
|
19
|
+
/** 用户给定的默认清单(2026-11-11)。新增/调整只改这里,再同步 docs/CHANGELOG。 */
|
|
20
|
+
export const DEFAULT_FORK_SEED = Object.freeze({
|
|
21
|
+
enabled: true,
|
|
22
|
+
install: Object.freeze([
|
|
23
|
+
'@twinsearth/dsh-2xray',
|
|
24
|
+
'@michengai/dsh-agency-agents',
|
|
25
|
+
'dsh-better-sidebar',
|
|
26
|
+
'dsh-context',
|
|
27
|
+
'@liustack/modlens',
|
|
28
|
+
'@liustack/modsearch',
|
|
29
|
+
]),
|
|
30
|
+
activate: Object.freeze([
|
|
31
|
+
'dshmarket',
|
|
32
|
+
'@twinsearth/dsh-im2a-plugin',
|
|
33
|
+
'@openviking/dsh-memory-plugin',
|
|
34
|
+
'@twinsearth/w2m-dsh-plugin',
|
|
35
|
+
]),
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
/** npm 包名(可带 scope),防止配置把路径/参数注入 pnpm 命令。 */
|
|
39
|
+
const PACKAGE_NAME_RE = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i
|
|
40
|
+
|
|
41
|
+
/** 把用户配置归一成 { enabled, install, activate, packages }(去重、过滤非法名)。 */
|
|
42
|
+
export function normalizeForkSeed(input = {}) {
|
|
43
|
+
const raw = input && typeof input === 'object' ? input : {}
|
|
44
|
+
const enabled = raw.enabled !== false
|
|
45
|
+
const clean = (list) => [...new Set((Array.isArray(list) ? list : []).map((item) => String(item ?? '').trim()).filter((name) => PACKAGE_NAME_RE.test(name)))]
|
|
46
|
+
const install = clean(raw.install ?? DEFAULT_FORK_SEED.install)
|
|
47
|
+
const activate = clean(raw.activate ?? DEFAULT_FORK_SEED.activate)
|
|
48
|
+
const packages = [...install, ...activate.filter((name) => !install.includes(name))]
|
|
49
|
+
return { enabled, install, activate, packages }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 种子指纹:配置变化即换缓存目录(排序,顺序不同但集合相同不换缓存)。 */
|
|
53
|
+
export function forkSeedFingerprint(seed) {
|
|
54
|
+
const norm = normalizeForkSeed(seed)
|
|
55
|
+
const canonical = { packages: [...norm.packages].sort(), activate: [...norm.activate].sort() }
|
|
56
|
+
return crypto.createHash('sha256').update(JSON.stringify(canonical)).digest('hex').slice(0, 16)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function readJson(file, fallback = null) {
|
|
60
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return fallback }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function packageDirName(name) {
|
|
64
|
+
return name.split('/')
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function seedPackageDir(modulesDir, name) {
|
|
68
|
+
return path.join(String(modulesDir ?? ''), ...packageDirName(name))
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function readInstalledVersion(modulesDir, name) {
|
|
72
|
+
const pkg = readJson(path.join(seedPackageDir(modulesDir, name), 'package.json'), null)
|
|
73
|
+
return pkg && typeof pkg.version === 'string' ? pkg.version : ''
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 把种子模块合并进分身 `node_modules`:
|
|
78
|
+
* * 普通包:整目录 hardlink 覆盖;
|
|
79
|
+
* * scope:把目标 scope(可能是 junction / 真实目录)先展开成真实目录,再覆盖 seed 里的子包。
|
|
80
|
+
* 不删除 seed 之外的目标条目(mother 镜像要继续可用)。
|
|
81
|
+
*/
|
|
82
|
+
export function mergeSeedModules(seedModulesDir, targetModulesDir) {
|
|
83
|
+
const source = String(seedModulesDir ?? '')
|
|
84
|
+
const target = String(targetModulesDir ?? '')
|
|
85
|
+
if (!source || !exists(source)) return { ok: false, error: 'seed-modules-missing' }
|
|
86
|
+
if (!target || !exists(target)) return { ok: false, error: 'target-modules-missing' }
|
|
87
|
+
const copied = []
|
|
88
|
+
const scopes = []
|
|
89
|
+
const warnings = []
|
|
90
|
+
for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
|
|
91
|
+
const name = entry.name
|
|
92
|
+
if (name.startsWith('.') || !entry.isDirectory()) continue
|
|
93
|
+
const from = path.join(source, name)
|
|
94
|
+
const to = path.join(target, name)
|
|
95
|
+
try {
|
|
96
|
+
if (name.startsWith('@')) {
|
|
97
|
+
mergeScope(from, to)
|
|
98
|
+
scopes.push(name)
|
|
99
|
+
} else {
|
|
100
|
+
removeTree(to)
|
|
101
|
+
hardlinkTree(from, to)
|
|
102
|
+
copied.push(name)
|
|
103
|
+
}
|
|
104
|
+
} catch (error) {
|
|
105
|
+
warnings.push(`${name}: ${String(error?.message ?? error)}`)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return { ok: warnings.length === 0, copied, scopes, warnings }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function mergeScope(seedScope, targetScope) {
|
|
112
|
+
const staging = `${targetScope}.fang-seed-merge`
|
|
113
|
+
removeTree(staging)
|
|
114
|
+
ensureDir(staging)
|
|
115
|
+
// 1) 保留目标 scope 既有子包(可能是指向 mother 模块树的 junction)。
|
|
116
|
+
if (exists(targetScope) || isLink(targetScope)) {
|
|
117
|
+
for (const child of fs.readdirSync(targetScope, { withFileTypes: true })) {
|
|
118
|
+
const from = path.join(targetScope, child.name)
|
|
119
|
+
const to = path.join(staging, child.name)
|
|
120
|
+
try {
|
|
121
|
+
if (child.isSymbolicLink()) {
|
|
122
|
+
const resolved = fs.realpathSync(from)
|
|
123
|
+
hardlinkTree(resolved, to)
|
|
124
|
+
} else if (child.isDirectory()) hardlinkTree(from, to)
|
|
125
|
+
} catch { /* keep the rest */ }
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
// 2) seed 子包覆盖同名项。
|
|
129
|
+
for (const child of fs.readdirSync(seedScope, { withFileTypes: true })) {
|
|
130
|
+
if (!child.isDirectory()) continue
|
|
131
|
+
const from = path.join(seedScope, child.name)
|
|
132
|
+
const to = path.join(staging, child.name)
|
|
133
|
+
removeTree(to)
|
|
134
|
+
hardlinkTree(from, to)
|
|
135
|
+
}
|
|
136
|
+
// 3) 原子替换 scope 目录。
|
|
137
|
+
removeTree(targetScope)
|
|
138
|
+
try { fs.renameSync(staging, targetScope) } catch {
|
|
139
|
+
removeTree(staging)
|
|
140
|
+
hardlinkTree(seedScope, targetScope)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* 把种子写进分身 profile 的 package.json:
|
|
146
|
+
* dependencies += 所有种子包(已有 spec 不覆盖);
|
|
147
|
+
* dsh.profile.bundles += activate 列表(放在 fang 之后,去重)。
|
|
148
|
+
* @returns {{packageJson:object, changed:boolean, addedDependencies:string[], addedBundles:string[]}}
|
|
149
|
+
*/
|
|
150
|
+
export function forkSeedProfilePatch(profilePkg, seed, versions = {}) {
|
|
151
|
+
const norm = normalizeForkSeed(seed)
|
|
152
|
+
const pkg = profilePkg && typeof profilePkg === 'object' ? JSON.parse(JSON.stringify(profilePkg)) : {}
|
|
153
|
+
const dependencies = pkg.dependencies && typeof pkg.dependencies === 'object' ? pkg.dependencies : {}
|
|
154
|
+
const addedDependencies = []
|
|
155
|
+
for (const name of norm.packages) {
|
|
156
|
+
if (typeof dependencies[name] === 'string' && dependencies[name].trim()) continue
|
|
157
|
+
const version = String(versions[name] ?? '').trim()
|
|
158
|
+
dependencies[name] = version ? `^${version}` : '*'
|
|
159
|
+
addedDependencies.push(name)
|
|
160
|
+
}
|
|
161
|
+
if (Object.keys(dependencies).length > 0) pkg.dependencies = dependencies
|
|
162
|
+
pkg.dsh = pkg.dsh && typeof pkg.dsh === 'object' ? pkg.dsh : {}
|
|
163
|
+
pkg.dsh.profile = pkg.dsh.profile && typeof pkg.dsh.profile === 'object' ? pkg.dsh.profile : {}
|
|
164
|
+
const bundles = Array.isArray(pkg.dsh.profile.bundles) ? [...pkg.dsh.profile.bundles] : []
|
|
165
|
+
const addedBundles = []
|
|
166
|
+
for (const name of norm.activate) {
|
|
167
|
+
if (bundles.includes(name)) continue
|
|
168
|
+
bundles.push(name)
|
|
169
|
+
addedBundles.push(name)
|
|
170
|
+
}
|
|
171
|
+
pkg.dsh.profile.bundles = bundles
|
|
172
|
+
return { packageJson: pkg, changed: addedDependencies.length > 0 || addedBundles.length > 0, addedDependencies, addedBundles }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const SEED_MARKER = '.fang-fork-seed.json'
|
|
176
|
+
|
|
177
|
+
/** 从 dsh CLI 路径推导 DSH 自带 pnpm 入口(.../runtime/cli/bin/dsh.cmd → .../runtime/primary-runtime/dependencies/pnpm/bin/pnpm.mjs)。 */
|
|
178
|
+
export function resolvePnpmEntry(cliPath) {
|
|
179
|
+
const cli = String(cliPath ?? '').trim()
|
|
180
|
+
if (!cli) return null
|
|
181
|
+
const cliDir = path.dirname(path.resolve(cli))
|
|
182
|
+
const candidates = [
|
|
183
|
+
path.resolve(cliDir, '..', '..', 'primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.mjs'),
|
|
184
|
+
path.resolve(cliDir, '..', '..', '..', 'runtime', 'primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.mjs'),
|
|
185
|
+
]
|
|
186
|
+
return candidates.find((candidate) => exists(candidate)) ?? null
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* 默认安装器:在一个**普通 pnpm 项目**里安装种子(不初始化 DSH profile,避免被默认
|
|
191
|
+
* dsh-llm 之类无法解析的基线依赖拖死)。只装插件包本身,peer 依赖交给宿主解析。
|
|
192
|
+
*/
|
|
193
|
+
export async function installSeedWithPnpm({ cliPath, seedHome, packages, timeoutMs = 300000 }) {
|
|
194
|
+
const pnpmEntry = resolvePnpmEntry(cliPath)
|
|
195
|
+
if (!pnpmEntry) return { ok: false, error: 'pnpm-not-found', detail: `cliPath=${cliPath}` }
|
|
196
|
+
const seedDir = path.join(seedHome, 'seed')
|
|
197
|
+
ensureDir(seedDir)
|
|
198
|
+
const dependencies = Object.fromEntries([...packages].sort().map((name) => [name, 'latest']))
|
|
199
|
+
writeJsonAtomic(path.join(seedDir, 'package.json'), { name: 'fang-fork-seed', private: true, dependencies })
|
|
200
|
+
fs.writeFileSync(path.join(seedDir, 'pnpm-workspace.yaml'), [
|
|
201
|
+
'packages:',
|
|
202
|
+
' - .',
|
|
203
|
+
'',
|
|
204
|
+
'nodeLinker: hoisted',
|
|
205
|
+
'autoInstallPeers: false',
|
|
206
|
+
'strictPeerDependencies: false',
|
|
207
|
+
'minimumReleaseAge: 0',
|
|
208
|
+
'',
|
|
209
|
+
].join('\n'), 'utf8')
|
|
210
|
+
const nodeBin = process.execPath
|
|
211
|
+
const args = [pnpmEntry, 'install', '--ignore-scripts', '--config.confirmModulesPurge=false']
|
|
212
|
+
const result = await new Promise((resolve) => {
|
|
213
|
+
let output = ''
|
|
214
|
+
let child = null
|
|
215
|
+
let timer = null
|
|
216
|
+
const done = (value) => { if (timer) clearTimeout(timer); resolve(value) }
|
|
217
|
+
try {
|
|
218
|
+
child = spawn(nodeBin, args, {
|
|
219
|
+
cwd: seedDir,
|
|
220
|
+
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
|
|
221
|
+
windowsHide: true,
|
|
222
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
223
|
+
})
|
|
224
|
+
} catch (error) {
|
|
225
|
+
done({ ok: false, error: 'spawn-failed', detail: String(error?.message ?? error) })
|
|
226
|
+
return
|
|
227
|
+
}
|
|
228
|
+
const append = (chunk) => { output = (output + String(chunk)).slice(-8000) }
|
|
229
|
+
child.stdout?.on('data', append)
|
|
230
|
+
child.stderr?.on('data', append)
|
|
231
|
+
timer = setTimeout(() => { try { child.kill() } catch { /* ignore */ } done({ ok: false, error: 'seed-install-timeout', detail: output.slice(-1200) }) }, Math.max(1000, Number(timeoutMs) || 300000))
|
|
232
|
+
child.on('error', (error) => done({ ok: false, error: 'spawn-failed', detail: String(error?.message ?? error) }))
|
|
233
|
+
child.on('exit', (code) => done(code === 0 ? { ok: true, detail: output.slice(-1200) } : { ok: false, error: 'seed-install-failed', code, detail: output.slice(-2400) }))
|
|
234
|
+
})
|
|
235
|
+
return { ...result, modulesDir: path.join(seedDir, 'node_modules') }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* 给一个分身 profile 装备默认插件种子。幂等:同一指纹已应用则直接返回。
|
|
240
|
+
* @returns {Promise<{ok:boolean, skipped?:boolean, cached?:boolean, packages?:string[], activate?:string[],
|
|
241
|
+
* versions?:Record<string,string>, merged?:object, error?:string, detail?:string}>}
|
|
242
|
+
*/
|
|
243
|
+
export async function applyForkSeedToProfile({ seed, profileDir, profileModulesDir, seedRoot, cliPath, timeoutMs = 300000, install = installSeedWithPnpm } = {}) {
|
|
244
|
+
const norm = normalizeForkSeed(seed)
|
|
245
|
+
if (!norm.enabled || norm.packages.length === 0) return { ok: true, skipped: true }
|
|
246
|
+
const profile = String(profileDir ?? '')
|
|
247
|
+
if (!profile || !exists(path.join(profile, 'package.json'))) return { ok: false, error: 'profile-package-missing' }
|
|
248
|
+
if (!cliPath) return { ok: false, error: 'cli-path-missing' }
|
|
249
|
+
const fingerprint = forkSeedFingerprint(norm)
|
|
250
|
+
const markerFile = path.join(profile, SEED_MARKER)
|
|
251
|
+
const marker = readJson(markerFile, null)
|
|
252
|
+
const modulesDir = String(profileModulesDir ?? path.join(profile, 'node_modules'))
|
|
253
|
+
const seedHome = path.join(String(seedRoot ?? path.join(path.dirname(profile), '.plugin-seed')), `seed-${fingerprint}`)
|
|
254
|
+
const seedModules = path.join(seedHome, 'seed', 'node_modules')
|
|
255
|
+
|
|
256
|
+
const cached = marker && marker.fingerprint === fingerprint
|
|
257
|
+
? norm.packages.every((name) => exists(seedPackageDir(seedModules, name)) && exists(seedPackageDir(modulesDir, name)))
|
|
258
|
+
: false
|
|
259
|
+
if (cached) {
|
|
260
|
+
// v3.1.12: every spawn replays the clean template over the profile config, which
|
|
261
|
+
// wipes the seeded dependencies/bundles. The seed modules and marker survive, so
|
|
262
|
+
// re-apply the cheap profile patch on the cached path (no install, no module copy).
|
|
263
|
+
const cachedPkg = readJson(path.join(profile, 'package.json'), null)
|
|
264
|
+
if (!cachedPkg) return { ok: false, error: 'profile-package-invalid' }
|
|
265
|
+
const patched = forkSeedProfilePatch(cachedPkg, norm, marker.versions ?? {})
|
|
266
|
+
if (patched.changed) writeJsonAtomic(path.join(profile, 'package.json'), patched.packageJson)
|
|
267
|
+
return {
|
|
268
|
+
ok: true, cached: true, packages: norm.packages, activate: norm.activate, versions: marker.versions ?? {},
|
|
269
|
+
patched: { addedDependencies: patched.addedDependencies, addedBundles: patched.addedBundles },
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (!norm.packages.every((name) => exists(seedPackageDir(seedModules, name)))) {
|
|
274
|
+
const installResult = await install({ cliPath, seedHome, packages: norm.packages, timeoutMs })
|
|
275
|
+
if (!installResult?.ok) return { ok: false, error: installResult?.error ?? 'seed-install-failed', detail: installResult?.detail ?? '' }
|
|
276
|
+
}
|
|
277
|
+
const unknown = norm.packages.filter((name) => !exists(seedPackageDir(seedModules, name)))
|
|
278
|
+
if (unknown.length > 0) return { ok: false, error: 'seed-packages-missing', detail: unknown.join(',') }
|
|
279
|
+
const versions = Object.fromEntries(norm.packages.map((name) => [name, readInstalledVersion(seedModules, name)]).filter(([, version]) => version))
|
|
280
|
+
|
|
281
|
+
const profilePkg = readJson(path.join(profile, 'package.json'), null)
|
|
282
|
+
if (!profilePkg) return { ok: false, error: 'profile-package-invalid' }
|
|
283
|
+
const patched = forkSeedProfilePatch(profilePkg, norm, versions)
|
|
284
|
+
if (patched.changed) writeJsonAtomic(path.join(profile, 'package.json'), patched.packageJson)
|
|
285
|
+
|
|
286
|
+
const merged = mergeSeedModules(seedModules, modulesDir)
|
|
287
|
+
if (!merged.ok) {
|
|
288
|
+
return {
|
|
289
|
+
ok: false, error: 'seed-modules-merge-failed', detail: (merged.warnings ?? []).join('; '),
|
|
290
|
+
packages: norm.packages, versions, merged,
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
writeJsonAtomic(markerFile, {
|
|
294
|
+
fingerprint,
|
|
295
|
+
packages: norm.packages,
|
|
296
|
+
activate: norm.activate,
|
|
297
|
+
versions,
|
|
298
|
+
appliedAt: Date.now(),
|
|
299
|
+
merged: { copied: merged.copied.length, scopes: merged.scopes.length },
|
|
300
|
+
})
|
|
301
|
+
return { ok: true, packages: norm.packages, activate: norm.activate, versions, merged, patched: { addedDependencies: patched.addedDependencies, addedBundles: patched.addedBundles } }
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export { SEED_MARKER }
|
package/src/lib/pnpm-store.mjs
CHANGED
|
@@ -168,6 +168,11 @@ export function ensureEssenceRuntimePnpmConfig({ profileDir, modulesDir, sourceM
|
|
|
168
168
|
nodeLinker,
|
|
169
169
|
storeDir,
|
|
170
170
|
packageImportMethod: 'copy',
|
|
171
|
+
// v3.1.11:元宝运行态是“用户显式更新插件”的交互场景,pnpm 11 默认的
|
|
172
|
+
// minimumReleaseAge(供应链观察期)会把刚发布的自家插件判为过新:
|
|
173
|
+
// ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION(3.1.10 / queue-journal 0.1.4 实测)。
|
|
174
|
+
// 母体的供应链策略不在这里改动;只在运行态关闭观察期,保证插件更新/卸载可用。
|
|
175
|
+
minimumReleaseAge: '0',
|
|
171
176
|
})
|
|
172
177
|
const npmrc = upsertNpmrc(profile, { storeDir, packageImportMethod: 'copy' })
|
|
173
178
|
const patched = patchModulesManifest(modules, { storeDir, virtualStoreDir })
|
package/src/plugins/adapter.mjs
CHANGED
|
@@ -655,6 +655,11 @@ export function apply(ctx, config) {
|
|
|
655
655
|
ok: true,
|
|
656
656
|
role,
|
|
657
657
|
taskId,
|
|
658
|
+
// Web 端身份徽标用:母体 / 元主(元宝运行态)/ 分身(任务)。
|
|
659
|
+
// 元宝运行态由 orchestrator 注入 DSH_FANG_ESSENCE=1;旧运行态按 rt- 前缀兜底。
|
|
660
|
+
kind: role === 'mother'
|
|
661
|
+
? 'mother'
|
|
662
|
+
: ((typeof process !== 'undefined' && process.env?.DSH_FANG_ESSENCE === '1') || String(taskId ?? '').startsWith('rt-') ? 'essence' : 'fork'),
|
|
658
663
|
version: FANG_VERSION,
|
|
659
664
|
protocol: ADAPTER_PROTOCOL_VERSION,
|
|
660
665
|
sessionId,
|
package/src/plugins/forker.mjs
CHANGED
|
@@ -61,6 +61,7 @@ import {
|
|
|
61
61
|
} from '../kernel/index.mjs'
|
|
62
62
|
import { computeBackoff, planRestart, reconcileOrphans, writeForkMeta, probeHttpAlive, SUPERVISION_DEFAULTS } from '../lib/fork-supervisor.mjs'
|
|
63
63
|
import { applyForkConfigLock, setProfileConfigReadonly } from '../lib/fork-config-lock.mjs'
|
|
64
|
+
import { DEFAULT_FORK_SEED, applyForkSeedToProfile } from '../lib/fork-seed.mjs'
|
|
64
65
|
|
|
65
66
|
export const name = 'fang-forker'
|
|
66
67
|
export const inject = []
|
|
@@ -145,6 +146,16 @@ export const Config = z
|
|
|
145
146
|
.description('true:用内置干净模板(不继承母体脏 profile);false:沿用 profileTemplate'),
|
|
146
147
|
bundleName: z.string().default('@twinsearth/dsh-fang').description('干净模板 profile.bundles 的第三个 bundle'),
|
|
147
148
|
forkProfileTag: z.string().default('web-base').description('干净模板 profile 标签(模板目录/缺省 profile 名)'),
|
|
149
|
+
// v3.1.12:新机器/新用户的干净分身默认不带第三方插件;这里按“安装不激活 /
|
|
150
|
+
// 安装并激活”两组清单给每个新分身装默认插件(开关可关;失败不阻塞分身启动)。
|
|
151
|
+
forkSeed: z
|
|
152
|
+
.object({
|
|
153
|
+
enabled: z.boolean().default(true).description('派生新分身时安装默认第三方插件种子'),
|
|
154
|
+
install: z.array(z.string()).default([...DEFAULT_FORK_SEED.install]).description('只安装、不加入 profile bundles 的插件包名'),
|
|
155
|
+
activate: z.array(z.string()).default([...DEFAULT_FORK_SEED.activate]).description('安装并加入 profile bundles 的插件包名'),
|
|
156
|
+
})
|
|
157
|
+
.default({})
|
|
158
|
+
.description('派生分身的默认第三方插件种子'),
|
|
148
159
|
supervise: z.boolean().default(false)
|
|
149
160
|
.description('restart a crashed (already-ready) fork with exponential backoff; the patch layer enables it'),
|
|
150
161
|
maxRestarts: z.natural().default(SUPERVISION_DEFAULTS.maxRestarts)
|
|
@@ -1052,6 +1063,30 @@ export function apply(ctx, config) {
|
|
|
1052
1063
|
} catch (e) {
|
|
1053
1064
|
rec.nodeModulesMirror = { ok: false, changed: false, error: msgOf(e) }
|
|
1054
1065
|
}
|
|
1066
|
+
// v3.1.12:默认第三方插件种子。install=只安装;activate=安装并激活(写入 bundles)。
|
|
1067
|
+
// 种子安装在独立 seed home(dsh 自带 pnpm),模块以 hardlink 合并进分身 node_modules;
|
|
1068
|
+
// 同一指纹只装一次。失败不阻塞分身启动,但结果保留在 rec.forkSeed 供 UI 诊断。
|
|
1069
|
+
rec.forkSeed = null
|
|
1070
|
+
if (cfg.forkSeed?.enabled !== false && !String(profile).startsWith('essence-') && process.env.DSH_FANG_FORK_SEED !== '0') {
|
|
1071
|
+
const seedRoot = path.join(path.dirname(path.resolve(homeDir)), '.plugin-seed')
|
|
1072
|
+
try { setProfileConfigReadonly(rec.profileDir, false) } catch { /* ignore */ }
|
|
1073
|
+
try {
|
|
1074
|
+
rec.forkSeed = await applyForkSeedToProfile({
|
|
1075
|
+
seed: cfg.forkSeed ?? DEFAULT_FORK_SEED,
|
|
1076
|
+
profileDir: rec.profileDir,
|
|
1077
|
+
seedRoot,
|
|
1078
|
+
cliPath,
|
|
1079
|
+
logger: ctx?.logger,
|
|
1080
|
+
})
|
|
1081
|
+
} catch (e) {
|
|
1082
|
+
rec.forkSeed = { ok: false, error: 'fork-seed-threw', detail: msgOf(e) }
|
|
1083
|
+
} finally {
|
|
1084
|
+
try { setProfileConfigReadonly(rec.profileDir, true) } catch { /* ignore */ }
|
|
1085
|
+
}
|
|
1086
|
+
if (rec.forkSeed?.ok === false) {
|
|
1087
|
+
audit(AUDIT.FORK_CREATED, { forkId, forkSeedError: rec.forkSeed.error, forkSeedDetail: String(rec.forkSeed.detail ?? '').slice(0, 600) })
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1055
1090
|
writeForkMetaOf(rec)
|
|
1056
1091
|
// 广播新 token:首次派生 = 生成,重启 = 刷新;订阅者拿到的是「当前 token」,
|
|
1057
1092
|
// 不是「进程就绪」信号(进程就绪以 fang/fork-started 为准)。
|
|
@@ -1205,6 +1240,7 @@ export function apply(ctx, config) {
|
|
|
1205
1240
|
url: rec.url,
|
|
1206
1241
|
token: rec.token,
|
|
1207
1242
|
...(expectedPort > 0 ? { allocatedPort: expectedPort } : {}),
|
|
1243
|
+
...(rec.forkSeed ? { forkSeed: rec.forkSeed } : {}),
|
|
1208
1244
|
})
|
|
1209
1245
|
}
|
|
1210
1246
|
// The tokenized banner is normally on stdout; scanning stderr too costs nothing.
|
|
@@ -2246,7 +2246,7 @@ export function apply(ctx, config) {
|
|
|
2246
2246
|
homeDir,
|
|
2247
2247
|
profile: 'essence-runtime',
|
|
2248
2248
|
cliPath: cliPath(),
|
|
2249
|
-
env: { DSH_FANG_ROLE: 'fork', DSH_FANG_TASK_ID: forkId },
|
|
2249
|
+
env: { DSH_FANG_ROLE: 'fork', DSH_FANG_TASK_ID: forkId, DSH_FANG_ESSENCE: '1' },
|
|
2250
2250
|
})
|
|
2251
2251
|
if (!started.ok) throw new Error(`runtime-spawn-failed: ${started.error ?? 'unknown'} (forkId=${forkId}, homeDir=${homeDir}, profile=essence-runtime)`)
|
|
2252
2252
|
return {
|