@twinsearth/dsh-fang 3.0.8 → 3.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -1
- package/client.js +1373 -70
- package/cordis.patch.yml +9 -0
- package/package.json +5 -1
- package/src/kernel/paths.mjs +35 -5
- package/src/kernel/types.mjs +2 -1
- package/src/lib/branch-store.mjs +18 -2
- package/src/lib/branch.mjs +32 -10
- package/src/lib/compat.mjs +12 -3
- package/src/lib/composer-journal.mjs +75 -0
- package/src/lib/default-essence.mjs +61 -0
- package/src/lib/essence.mjs +259 -12
- package/src/lib/fork-config-lock.mjs +54 -0
- package/src/lib/fs-guard.mjs +9 -11
- package/src/lib/http-auth.mjs +64 -7
- package/src/lib/preferences.mjs +11 -0
- package/src/lib/ui-actions.mjs +15 -12
- package/src/lib/upgrade-status.mjs +28 -5
- package/src/plugins/adapter.mjs +45 -2
- package/src/plugins/forker.mjs +32 -3
- package/src/plugins/orchestrator.mjs +1089 -48
- package/src/plugins/session-bridge.mjs +53 -10
- package/src/plugins/session-catalog.mjs +20 -0
- package/src/plugins/session-router.mjs +21 -2
- package/src/plugins/session-sync.mjs +18 -2
|
@@ -12,7 +12,7 @@ import fs from 'node:fs'
|
|
|
12
12
|
import path from 'node:path'
|
|
13
13
|
|
|
14
14
|
import {
|
|
15
|
-
z, roleGate, resolveFangLayout, resolveProfileDir,
|
|
15
|
+
z, roleGate, resolveFangLayout, resolveProfileDir, resolveSessionsLayout,
|
|
16
16
|
SERVICE, AUDIT, TASK_STATUS, FORK_STATUS, FANG_VERSION, ADAPTER_OP,
|
|
17
17
|
exists, ensureDir, readJson, writeJsonAtomic, writeFileAtomic, sha256, removeTree, copyTree,
|
|
18
18
|
newId, iso, nowMs, bus, sleep, parseWebUrl, probeWebUrl,
|
|
@@ -24,13 +24,16 @@ import { describeMotherLink, probeLink, readSharedProfileSummary } from '../lib/
|
|
|
24
24
|
import { MirrorManager } from '../lib/mirror.mjs'
|
|
25
25
|
import { buildMirrorStatusResponse } from '../lib/mirror-etag.mjs'
|
|
26
26
|
import { PreferencesStore } from '../lib/preferences.mjs'
|
|
27
|
-
import { EssenceManager, OFFICIAL_ESSENCE_ID } from '../lib/essence.mjs'
|
|
27
|
+
import { EssenceManager, OFFICIAL_ESSENCE_ID, VIP_QUOTAS } from '../lib/essence.mjs'
|
|
28
|
+
import { applyForkConfigLock, setProfileConfigReadonly } from '../lib/fork-config-lock.mjs'
|
|
29
|
+
import { DEFAULT_ESSENCE_NAME, planDefaultEssence } from '../lib/default-essence.mjs'
|
|
28
30
|
import { MirrorUpgradeCoordinator } from '../lib/upgrade-coordinator.mjs'
|
|
29
31
|
import { DEFAULT_EXPECTED_ROUTE_COUNT, readCompatStatus, runCompatGate, writeCompatStatus } from '../lib/compat.mjs'
|
|
30
32
|
import { buildUpgradeStatus } from '../lib/upgrade-status.mjs'
|
|
31
|
-
import { checkRequestAuth, loadAuthToken } from '../lib/http-auth.mjs'
|
|
33
|
+
import { authErrorBody, checkRequestAuth, loadAuthToken } from '../lib/http-auth.mjs'
|
|
32
34
|
import { buildEssenceActions, buildTaskActions } from '../lib/ui-actions.mjs'
|
|
33
35
|
import { BranchStore } from '../lib/branch-store.mjs'
|
|
36
|
+
import { ComposerJournal } from '../lib/composer-journal.mjs'
|
|
34
37
|
import { fileURLToPath } from 'node:url'
|
|
35
38
|
import zlib from 'node:zlib'
|
|
36
39
|
|
|
@@ -46,6 +49,10 @@ export const Config = z.object({
|
|
|
46
49
|
.description('母体 profile 名;留空 = 当前 profile(分身模板来源)'),
|
|
47
50
|
profileTemplate: z.string().default('')
|
|
48
51
|
.description('分身 profile 模板目录;留空 = 当前 profile 目录(Forker 的 cleanTemplate 会覆盖)'),
|
|
52
|
+
fangHome: z.string().default('')
|
|
53
|
+
.description('三区数据根(相当于 FANG_HOME);留空 = 自动(新装默认 D:\\ToFuture,已有旧数据沿用旧布局)'),
|
|
54
|
+
defaultEssenceAuto: z.boolean().default(true)
|
|
55
|
+
.description('新用户自动生成“默认元宝”(仅当没有任何用户元主、且默认插件已有安装时;失败不影响启动)'),
|
|
49
56
|
cliPath: z.string().default('')
|
|
50
57
|
.description('dsh 启动器路径;留空自动探测(PATH 上的 dsh / 安装目录 dsh.cmd)'),
|
|
51
58
|
dataRoot: z.string().default('')
|
|
@@ -152,8 +159,9 @@ export function apply(ctx, config) {
|
|
|
152
159
|
if (!gate.active) return
|
|
153
160
|
const role = gate.role
|
|
154
161
|
|
|
155
|
-
const layout = resolveFangLayout({ dataRoot: cfg.dataRoot, forksRoot: cfg.forksRoot })
|
|
162
|
+
const layout = resolveFangLayout({ dataRoot: cfg.dataRoot, forksRoot: cfg.forksRoot, fangHome: cfg.fangHome })
|
|
156
163
|
const branchStore = new BranchStore(layout.dataDir)
|
|
164
|
+
const composerJournal = new ComposerJournal(layout.dataDir)
|
|
157
165
|
// v3.0.5/B1:安装级 token(0600 文件 / env / 显式配置);关闭仅限测试
|
|
158
166
|
const authToken = cfg.authEnabled === false
|
|
159
167
|
? ''
|
|
@@ -228,6 +236,8 @@ export function apply(ctx, config) {
|
|
|
228
236
|
adapter: f.adapter ?? { ok: false, error: 'not-handshaked' },
|
|
229
237
|
collaborators: Array.isArray(f.collaborators) ? f.collaborators : [],
|
|
230
238
|
template: f.template ?? '',
|
|
239
|
+
essenceId: f.essenceId ?? null,
|
|
240
|
+
sourceEssence: f.sourceEssence ?? null,
|
|
231
241
|
}
|
|
232
242
|
}
|
|
233
243
|
|
|
@@ -357,6 +367,19 @@ export function apply(ctx, config) {
|
|
|
357
367
|
updatedAt: t.updatedAt ?? live?.exitedAt ?? t.createdAt,
|
|
358
368
|
projectBytes: t.projectBytes ?? 0,
|
|
359
369
|
essenceId: t.essenceId ?? null,
|
|
370
|
+
// 视图层才扫描会话(normalizeTask 在 apply 早期执行,不能引用后声明的 scanForkSessions)。
|
|
371
|
+
sessions: (() => { const list = scanForkSessions(t); return { count: list.length, violation: list.length > 1 } })(),
|
|
372
|
+
// 来源原身已被删除:分身仍可运行/归档/还原/删除,但不能重新派生。
|
|
373
|
+
essenceDeleted: Boolean(t.essenceId) && (t.essenceDeleted === true || isTombstoned(t.essenceId)),
|
|
374
|
+
// 方案 B:同一分身可挂多个分支会话,但同时只有一个 active。
|
|
375
|
+
branch: (() => {
|
|
376
|
+
try {
|
|
377
|
+
const store = branchStore.list(t.taskId)
|
|
378
|
+
return { activeBranchId: store.activeBranchId ?? t.activeBranchId ?? null, sessionId: store.sessionId ?? null, count: Array.isArray(store.branches) ? store.branches.length : 0 }
|
|
379
|
+
} catch {
|
|
380
|
+
return { activeBranchId: t.activeBranchId ?? null, sessionId: null, count: 0 }
|
|
381
|
+
}
|
|
382
|
+
})(),
|
|
360
383
|
pid: live?.pid ?? t.pid ?? null,
|
|
361
384
|
port: t.port ?? null,
|
|
362
385
|
url: stripUrlToken(t.url),
|
|
@@ -421,6 +444,93 @@ export function apply(ctx, config) {
|
|
|
421
444
|
return { ok: true, bytes, sessionId, workspacePath, workspaceKey, workspaceTitle, indexFile }
|
|
422
445
|
}
|
|
423
446
|
|
|
447
|
+
// v3.0.9 单会话强制:扫分身自己的 sessions,保留最新一个,其余移到 quarantine-sessions/。
|
|
448
|
+
const scanForkSessions = (task) => {
|
|
449
|
+
const root = path.join(String(task?.homeDir ?? ''), 'sessions')
|
|
450
|
+
const out = []
|
|
451
|
+
try {
|
|
452
|
+
for (const workspace of fs.readdirSync(root, { withFileTypes: true })) {
|
|
453
|
+
if (!workspace.isDirectory()) continue
|
|
454
|
+
const wsDir = path.join(root, workspace.name)
|
|
455
|
+
for (const session of fs.readdirSync(wsDir, { withFileTypes: true })) {
|
|
456
|
+
if (!session.isDirectory()) continue
|
|
457
|
+
const full = path.join(wsDir, session.name)
|
|
458
|
+
let mtime = 0
|
|
459
|
+
try { mtime = fs.statSync(full).mtimeMs } catch { mtime = 0 }
|
|
460
|
+
out.push({ workspaceKey: workspace.name, sessionId: session.name, path: full, mtime })
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
} catch { /* 没有 sessions 目录 */ }
|
|
464
|
+
return out.sort((a, b) => b.mtime - a.mtime)
|
|
465
|
+
}
|
|
466
|
+
const applySingleSessionGuard = (task) => {
|
|
467
|
+
// 受管的分支子会话不参与“单会话”隔离(它们由分支库登记,属于同一分身的合法分支)。
|
|
468
|
+
const branchSessionIds = new Set()
|
|
469
|
+
try {
|
|
470
|
+
for (const branch of branchStore.list(task.taskId).branches ?? []) {
|
|
471
|
+
if (branch?.sessionId) branchSessionIds.add(String(branch.sessionId))
|
|
472
|
+
}
|
|
473
|
+
const storeSession = branchStore.load?.(task.taskId)?.sessionId
|
|
474
|
+
if (storeSession) branchSessionIds.add(String(storeSession))
|
|
475
|
+
} catch { /* 无分支库 */ }
|
|
476
|
+
const sessions = scanForkSessions(task).filter((session) => !branchSessionIds.has(session.sessionId))
|
|
477
|
+
const bindBranches = (keptId) => { try { branchStore?.bindSession?.(task.taskId, keptId) } catch { /* ignore */ } }
|
|
478
|
+
if (sessions.length <= 1) {
|
|
479
|
+
const kept = sessions[0]?.sessionId ?? null
|
|
480
|
+
bindBranches(kept)
|
|
481
|
+
return { ok: true, kept, quarantined: [] }
|
|
482
|
+
}
|
|
483
|
+
const [keep, ...rest] = sessions
|
|
484
|
+
const stamp = String(nowMs())
|
|
485
|
+
const quarantined = []
|
|
486
|
+
for (const session of rest) {
|
|
487
|
+
const target = path.join(task.homeDir, 'quarantine-sessions', stamp, session.workspaceKey, session.sessionId)
|
|
488
|
+
try {
|
|
489
|
+
ensureDir(path.dirname(target))
|
|
490
|
+
try { fs.renameSync(session.path, target) } catch { copyTree(session.path, target); removeTree(session.path) }
|
|
491
|
+
quarantined.push({ workspaceKey: session.workspaceKey, sessionId: session.sessionId, movedTo: target, at: nowMs() })
|
|
492
|
+
} catch { /* 移动失败保留原样,不破坏数据 */ }
|
|
493
|
+
}
|
|
494
|
+
if (quarantined.length > 0) {
|
|
495
|
+
task.quarantinedSessions = (Array.isArray(task.quarantinedSessions) ? task.quarantinedSessions : []).concat(quarantined)
|
|
496
|
+
persist()
|
|
497
|
+
audit('fork-session-quarantined', { taskId: task.taskId, kept: keep.sessionId, moved: quarantined.length })
|
|
498
|
+
}
|
|
499
|
+
bindBranches(keep.sessionId)
|
|
500
|
+
return { ok: true, kept: keep.sessionId, quarantined }
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const tombstonesFile = path.join(layout.dataDir, 'deleted-essences.json')
|
|
504
|
+
const loadTombstones = () => {
|
|
505
|
+
try {
|
|
506
|
+
const doc = readJson(tombstonesFile, {})
|
|
507
|
+
return Array.isArray(doc?.ids) ? doc.ids.map(String) : []
|
|
508
|
+
} catch { return [] }
|
|
509
|
+
}
|
|
510
|
+
const isTombstoned = (essenceId) => loadTombstones().includes(String(essenceId ?? ''))
|
|
511
|
+
const addTombstone = (essenceId, name) => {
|
|
512
|
+
const ids = new Set(loadTombstones())
|
|
513
|
+
ids.add(String(essenceId))
|
|
514
|
+
writeJsonAtomic(tombstonesFile, { ids: [...ids], updatedAt: nowMs(), last: { id: String(essenceId), name: String(name ?? ''), at: nowMs() } })
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// v3.0.9 默认元宝:新用户免创建,自动生成一个带默认插件清单的元主。
|
|
518
|
+
const defaultEssenceFile = path.join(layout.dataDir, 'default-essence.json')
|
|
519
|
+
const readDefaultEssenceId = () => {
|
|
520
|
+
try { return String(readJson(defaultEssenceFile, {})?.essenceId ?? '') } catch { return '' }
|
|
521
|
+
}
|
|
522
|
+
const writeDefaultEssenceId = (essenceId) => writeJsonAtomic(defaultEssenceFile, { essenceId: String(essenceId), at: nowMs() })
|
|
523
|
+
const listInstalledPlugins = async () => {
|
|
524
|
+
try {
|
|
525
|
+
const pm = safeGet('pluginManager')
|
|
526
|
+
if (!pm || typeof pm.listPlugins !== 'function') return null
|
|
527
|
+
const out = await pm.listPlugins()
|
|
528
|
+
if (Array.isArray(out)) return out
|
|
529
|
+
if (Array.isArray(out?.plugins)) return out.plugins
|
|
530
|
+
return null
|
|
531
|
+
} catch { return null }
|
|
532
|
+
}
|
|
533
|
+
|
|
424
534
|
const service = {
|
|
425
535
|
role,
|
|
426
536
|
version: FANG_VERSION,
|
|
@@ -445,6 +555,28 @@ export function apply(ctx, config) {
|
|
|
445
555
|
const profile = `fang-${taskId.replace(/^task_/, '').slice(0, 12)}`
|
|
446
556
|
const homeDir = path.join(layout.forkHomesDir, taskId)
|
|
447
557
|
const template = String(input.template ?? '').trim()
|
|
558
|
+
// v3.0.9:从原身派生时,模板来源是该原身的 merged/profile(分身只生产,不回写原身)。
|
|
559
|
+
// v3.0.9:未指定来源时,若存在“默认元宝”,快速派生直接以它为模板(新用户小白路径)。
|
|
560
|
+
let essenceIdInput = String(input.essenceId ?? '').trim()
|
|
561
|
+
if (!essenceIdInput && !template) {
|
|
562
|
+
const presetId = readDefaultEssenceId()
|
|
563
|
+
if (presetId && essenceManager.getMeta(presetId)?.id) essenceIdInput = presetId
|
|
564
|
+
}
|
|
565
|
+
let sourceEssence = null
|
|
566
|
+
if (essenceIdInput) {
|
|
567
|
+
const essenceId = essenceIdInput
|
|
568
|
+
const meta = essenceManager.getMeta(essenceId)
|
|
569
|
+
if (!meta || typeof meta.id !== 'string') {
|
|
570
|
+
return { ok: false, error: isTombstoned(essenceId) ? 'essence-deleted' : 'unknown-essence' }
|
|
571
|
+
}
|
|
572
|
+
if (meta.archived === true) return { ok: false, error: 'essence-archived' }
|
|
573
|
+
await essenceManager.ensureFresh(essenceId)
|
|
574
|
+
const fresh = essenceManager.getMeta(essenceId)
|
|
575
|
+
sourceEssence = { id: essenceId, name: meta.name, fingerprint: fresh?.lastMergedFingerprint ?? null }
|
|
576
|
+
}
|
|
577
|
+
const profileTemplate = sourceEssence
|
|
578
|
+
? essenceManager.mergedProfileDir(sourceEssence.id)
|
|
579
|
+
: (template || templateDir())
|
|
448
580
|
const task = normalizeTask({
|
|
449
581
|
taskId,
|
|
450
582
|
title,
|
|
@@ -454,6 +586,8 @@ export function apply(ctx, config) {
|
|
|
454
586
|
createdAt: nowMs(),
|
|
455
587
|
collaborators: Array.isArray(input.collaborators) ? input.collaborators : [],
|
|
456
588
|
template,
|
|
589
|
+
essenceId: sourceEssence?.id ?? null,
|
|
590
|
+
sourceEssence,
|
|
457
591
|
adapter: { ok: false, error: 'handshaking' },
|
|
458
592
|
})
|
|
459
593
|
tasks.set(taskId, task)
|
|
@@ -465,7 +599,10 @@ export function apply(ctx, config) {
|
|
|
465
599
|
taskTitle: title,
|
|
466
600
|
homeDir,
|
|
467
601
|
profile,
|
|
468
|
-
profileTemplate
|
|
602
|
+
profileTemplate,
|
|
603
|
+
// 从原身派生:配置必须真的来自原身 merged(不能被 clean template 覆盖),
|
|
604
|
+
// node_modules 仍 junction 到母体模块树。
|
|
605
|
+
...(sourceEssence ? { cleanTemplate: false, nodeModulesSource: path.join(templateDir(), 'node_modules') } : {}),
|
|
469
606
|
})
|
|
470
607
|
if (provisioned && provisioned.ok === false) {
|
|
471
608
|
task.status = TASK_STATUS.FAILED
|
|
@@ -513,14 +650,28 @@ export function apply(ctx, config) {
|
|
|
513
650
|
}
|
|
514
651
|
|
|
515
652
|
if (input.importSession && typeof input.importSession === 'object') {
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
653
|
+
const importSpec = input.importSession
|
|
654
|
+
// 新入口:只给 sessionId(元主栏“派生”按钮)→ 由会话目录整目录复制进分身。
|
|
655
|
+
if (importSpec.sessionId && !importSpec.sourceFile) {
|
|
656
|
+
try {
|
|
657
|
+
const imported = importSessionsInto(homeDir, [importSpec.sessionId])
|
|
658
|
+
task.importedSession = imported[0] ? { ok: true, ...imported[0] } : { ok: false, reason: 'not-imported' }
|
|
659
|
+
audit(AUDIT.FORK_CREATED + '-import', { taskId, ...task.importedSession })
|
|
660
|
+
} catch (e) {
|
|
661
|
+
task.importedSession = { ok: false, reason: 'import-failed', error: String(e?.message ?? e) }
|
|
662
|
+
audit(AUDIT.FORK_CRASHED + '-import', { taskId, error: task.importedSession.error })
|
|
663
|
+
}
|
|
664
|
+
persist()
|
|
665
|
+
} else {
|
|
666
|
+
try {
|
|
667
|
+
task.importedSession = importSessionIntoFork(homeDir, importSpec)
|
|
668
|
+
audit(AUDIT.FORK_CREATED + '-import', { taskId, ...task.importedSession })
|
|
669
|
+
} catch (e) {
|
|
670
|
+
task.importedSession = { ok: false, reason: 'import-failed', error: String(e?.message ?? e) }
|
|
671
|
+
audit(AUDIT.FORK_CRASHED + '-import', { taskId, error: task.importedSession.error })
|
|
672
|
+
}
|
|
673
|
+
persist()
|
|
522
674
|
}
|
|
523
|
-
persist()
|
|
524
675
|
}
|
|
525
676
|
|
|
526
677
|
const started = await f.spawn({
|
|
@@ -1013,6 +1164,54 @@ export function apply(ctx, config) {
|
|
|
1013
1164
|
},
|
|
1014
1165
|
|
|
1015
1166
|
/** 还原存档:用原 home/profile 重新 spawn(新端口 + 新 token),再握手。 */
|
|
1167
|
+
/** 分身配置重置:把来源原身的 merged/profile 重新覆盖到分身 profile(保留 node_modules 与会话)。 */
|
|
1168
|
+
async resetForkConfig(taskId) {
|
|
1169
|
+
const id = String(taskId ?? '')
|
|
1170
|
+
const task = tasks.get(id)
|
|
1171
|
+
if (!task) return { ok: false, error: 'unknown-task' }
|
|
1172
|
+
if (!task.essenceId) return { ok: false, error: 'no-source-essence' }
|
|
1173
|
+
const meta = essenceManager.getMeta(task.essenceId)
|
|
1174
|
+
if (!meta || typeof meta.id !== 'string') return { ok: false, error: 'source-essence-missing' }
|
|
1175
|
+
if (meta.archived === true) return { ok: false, error: 'source-essence-archived' }
|
|
1176
|
+
await essenceManager.ensureFresh(task.essenceId)
|
|
1177
|
+
const source = essenceManager.mergedProfileDir(task.essenceId)
|
|
1178
|
+
const target = path.join(task.homeDir, 'profiles', task.profile)
|
|
1179
|
+
if (!exists(target)) return { ok: false, error: 'fork-profile-missing' }
|
|
1180
|
+
setProfileConfigReadonly(target, false)
|
|
1181
|
+
const picked = []
|
|
1182
|
+
for (const rel of ['package.json', 'cordis.patch.yml', 'cordis.yml']) {
|
|
1183
|
+
const from = path.join(source, rel)
|
|
1184
|
+
if (!exists(from)) continue
|
|
1185
|
+
fs.copyFileSync(from, path.join(target, rel))
|
|
1186
|
+
picked.push(rel)
|
|
1187
|
+
}
|
|
1188
|
+
const settings = path.join(source, 'settings')
|
|
1189
|
+
if (exists(settings)) {
|
|
1190
|
+
const to = path.join(target, 'settings')
|
|
1191
|
+
if (exists(to)) removeTree(to)
|
|
1192
|
+
copyTree(settings, to)
|
|
1193
|
+
picked.push('settings/')
|
|
1194
|
+
}
|
|
1195
|
+
// 重置后重新加回“生产盘”锁(插件安装/设置入口仍禁用),并把配置设回只读。
|
|
1196
|
+
const configLock = applyForkConfigLock(target)
|
|
1197
|
+
const profileReadonly = setProfileConfigReadonly(target, true)
|
|
1198
|
+
task.configSyncedAt = nowMs()
|
|
1199
|
+
task.configSyncedFrom = task.essenceId
|
|
1200
|
+
persist()
|
|
1201
|
+
audit('fork-config-reset', { taskId: id, essenceId: task.essenceId, files: picked, configLock, profileReadonly })
|
|
1202
|
+
return { ok: true, taskId: id, essenceId: task.essenceId, files: picked, configLock, profileReadonly }
|
|
1203
|
+
},
|
|
1204
|
+
|
|
1205
|
+
/** 强制单会话:运行中拒绝;停止/归档态把多余会话移到 quarantine-sessions/。 */
|
|
1206
|
+
enforceSingleSession(taskId) {
|
|
1207
|
+
const id = String(taskId ?? '')
|
|
1208
|
+
const task = tasks.get(id)
|
|
1209
|
+
if (!task) return { ok: false, error: 'unknown-task' }
|
|
1210
|
+
const live = forker()?.status?.(id)
|
|
1211
|
+
if (live?.running) return { ok: false, error: 'task-running', taskId: id }
|
|
1212
|
+
return { ...applySingleSessionGuard(task), taskId: id }
|
|
1213
|
+
},
|
|
1214
|
+
|
|
1016
1215
|
async restoreTask(taskId) {
|
|
1017
1216
|
const id = String(taskId ?? '')
|
|
1018
1217
|
const task = tasks.get(id)
|
|
@@ -1021,6 +1220,9 @@ export function apply(ctx, config) {
|
|
|
1021
1220
|
if (!task.homeDir || !exists(task.homeDir)) {
|
|
1022
1221
|
return { ok: false, error: 'archive-home-missing', taskId: id, homeDir: task.homeDir ?? '' }
|
|
1023
1222
|
}
|
|
1223
|
+
try { assertInside(layout.forkHomesDir, task.homeDir, 'fork-home') } catch (error) {
|
|
1224
|
+
return { ok: false, error: 'path-escape', taskId: id, detail: String(error?.message ?? error) }
|
|
1225
|
+
}
|
|
1024
1226
|
const forkProfileDir = path.join(task.homeDir, 'profiles', task.profile)
|
|
1025
1227
|
const forkBundle = path.join(forkProfileDir, 'node_modules', '@local', 'dsh-fang')
|
|
1026
1228
|
if (!exists(forkBundle)) {
|
|
@@ -1028,6 +1230,16 @@ export function apply(ctx, config) {
|
|
|
1028
1230
|
}
|
|
1029
1231
|
const f = forker()
|
|
1030
1232
|
if (!f || typeof f.spawn !== 'function') return { ok: false, error: 'forker-unavailable', taskId: id }
|
|
1233
|
+
// 从原身派生的分身:还原前先把配置重置回来源原身(分身只生产,不保留配置改动)。
|
|
1234
|
+
let configReset = null
|
|
1235
|
+
if (task.essenceId) {
|
|
1236
|
+
try { configReset = await service.resetForkConfig(id) } catch (error) {
|
|
1237
|
+
configReset = { ok: false, error: String(error?.message ?? error) }
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
// 还原前强制单会话(多余会话移到 quarantine,不删除),再做配置重置后的启动。
|
|
1241
|
+
let sessionGuard = null
|
|
1242
|
+
try { sessionGuard = applySingleSessionGuard(task) } catch { sessionGuard = { ok: false } }
|
|
1031
1243
|
const started = await f.spawn({
|
|
1032
1244
|
forkId: id,
|
|
1033
1245
|
homeDir: task.homeDir,
|
|
@@ -1054,7 +1266,7 @@ export function apply(ctx, config) {
|
|
|
1054
1266
|
persist()
|
|
1055
1267
|
audit(AUDIT.TASK_RESTORED, { taskId: id, ok: true, adapter })
|
|
1056
1268
|
bus.emit('fang/task-restored', { taskId: id, url: task.url, port: task.port })
|
|
1057
|
-
return { ok: true, restored: true, taskId: id, title: task.title, url: task.url, port: task.port, adapter }
|
|
1269
|
+
return { ok: true, restored: true, taskId: id, title: task.title, url: task.url, port: task.port, adapter, configReset, sessionGuard }
|
|
1058
1270
|
},
|
|
1059
1271
|
|
|
1060
1272
|
/** 永久删除存档:reap(杀进程 + 删 home + 删记录);forker 记录已丢时按 home 兜底清理。 */
|
|
@@ -1121,6 +1333,15 @@ export function apply(ctx, config) {
|
|
|
1121
1333
|
role,
|
|
1122
1334
|
profileTag: layout.profileTag,
|
|
1123
1335
|
dataDir: layout.dataDir,
|
|
1336
|
+
// 三区路径(无需 D: 访问即可在面板/接口核对目录是否已迁移)
|
|
1337
|
+
layout: {
|
|
1338
|
+
fangHome: layout.fangHome || '',
|
|
1339
|
+
dataDir: layout.dataDir,
|
|
1340
|
+
essenceRoot: layout.essenceRoot,
|
|
1341
|
+
forkHomesDir: layout.forkHomesDir,
|
|
1342
|
+
runtimeRoot: layout.runtimeRoot,
|
|
1343
|
+
sessionsRoot: layout.sessionsRoot || '',
|
|
1344
|
+
},
|
|
1124
1345
|
mother: { profile: motherProfile, cliPath: cliPath(), template: templateDir() },
|
|
1125
1346
|
tasks: { total: list.length, ready, running, max: cfg.maxForks, list },
|
|
1126
1347
|
// v1 兼容视图:Client 徽标与旧调用方仍读 forks.*
|
|
@@ -1222,7 +1443,7 @@ export function apply(ctx, config) {
|
|
|
1222
1443
|
const preferencesStore = new PreferencesStore({ mirrorRoot, logger: ctx.logger ?? {} })
|
|
1223
1444
|
preferencesStore.load()
|
|
1224
1445
|
const essenceManager = new EssenceManager({
|
|
1225
|
-
essencesRoot:
|
|
1446
|
+
essencesRoot: layout.essenceRoot,
|
|
1226
1447
|
mirrorRoot,
|
|
1227
1448
|
logger: ctx.logger ?? {},
|
|
1228
1449
|
})
|
|
@@ -1234,19 +1455,161 @@ export function apply(ctx, config) {
|
|
|
1234
1455
|
ctx.logger?.warn?.('[essence] official essence seed failed', { error: String(error?.message ?? error) })
|
|
1235
1456
|
}
|
|
1236
1457
|
upgradeCoordinator = new MirrorUpgradeCoordinator({ essence: essenceManager, logger: ctx.logger ?? {} })
|
|
1458
|
+
// 元主运行态的 forkId 命名(稳定、可用于 forker 记录与端口池)
|
|
1459
|
+
const runtimeForkId = (essenceId) => 'rt-' + String(essenceId).replace(/^essence-/, '').replace(/[^A-Za-z0-9-]/g, '-')
|
|
1460
|
+
// v3.0.9 三区口径:运行态 home 统一在 runtimeRoot(FANG_HOME 下是 sessions/<essenceId>/home)。
|
|
1461
|
+
const runtimeHomeFor = (essenceId) => path.join(layout.runtimeRoot, String(essenceId), 'home')
|
|
1462
|
+
// 路径守卫:任何拼接出来的目标必须落在给定根内(拒绝 .. / 绝对路径逃逸)。
|
|
1463
|
+
const assertInside = (root, target, label) => {
|
|
1464
|
+
const resolvedRoot = path.resolve(String(root))
|
|
1465
|
+
const resolved = path.resolve(String(target))
|
|
1466
|
+
if (resolved !== resolvedRoot && !resolved.startsWith(resolvedRoot + path.sep)) {
|
|
1467
|
+
throw new Error(`path-escape: ${label} (${resolved} not under ${resolvedRoot})`)
|
|
1468
|
+
}
|
|
1469
|
+
return resolved
|
|
1470
|
+
}
|
|
1471
|
+
// v3.0.9 会话配额:数该元主运行态隔离 home 里的会话目录(归档数不再计入——归档目录由实例自管)。
|
|
1472
|
+
const countEssenceSessions = (essenceId, meta) => {
|
|
1473
|
+
const home = path.join(runtimeHomeFor(essenceId), 'sessions')
|
|
1474
|
+
let used = 0
|
|
1475
|
+
try {
|
|
1476
|
+
for (const workspace of fs.readdirSync(home, { withFileTypes: true })) {
|
|
1477
|
+
if (!workspace.isDirectory()) continue
|
|
1478
|
+
const wsDir = path.join(home, workspace.name)
|
|
1479
|
+
for (const session of fs.readdirSync(wsDir, { withFileTypes: true })) {
|
|
1480
|
+
if (session.isDirectory()) used += 1
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
} catch { used = 0 }
|
|
1484
|
+
const tier = String(meta?.tier ?? 'free')
|
|
1485
|
+
const limit = Number(VIP_QUOTAS[tier]?.maxActiveSessions) || VIP_QUOTAS.free.maxActiveSessions
|
|
1486
|
+
return { used, limit, over: used >= limit }
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
// 把母体的工作区索引按“被导入的会话”过滤后合并进隔离 home,界面上按工作区名分组而不是 key。
|
|
1490
|
+
const mergeWorkspaceIndexFor = (homeDir, importedSessions) => {
|
|
1491
|
+
try {
|
|
1492
|
+
const motherLayout = resolveSessionsLayout()
|
|
1493
|
+
const motherRaw = exists(motherLayout.workspaceFile) ? fs.readFileSync(motherLayout.workspaceFile, 'utf8') : ''
|
|
1494
|
+
const mother = parseWorkspaceIndex(motherRaw)
|
|
1495
|
+
const keys = new Set(importedSessions.map((session) => String(session.workspaceKey)))
|
|
1496
|
+
const ids = new Set(importedSessions.map((session) => String(session.sessionId)))
|
|
1497
|
+
const targetFile = path.join(homeDir, 'storages', 'workspace.json')
|
|
1498
|
+
const existing = exists(targetFile) ? parseWorkspaceIndex(fs.readFileSync(targetFile, 'utf8')) : { workspaces: [], global: { archivedSessionIds: [], pinnedSessionIds: [] } }
|
|
1499
|
+
const byPath = new Map(existing.workspaces.map((workspace) => [workspace.path, workspace]))
|
|
1500
|
+
for (const workspace of mother.workspaces) {
|
|
1501
|
+
if (!keys.has(encodeWorkspaceKey(workspace.path))) continue
|
|
1502
|
+
const previous = byPath.get(workspace.path)
|
|
1503
|
+
const sessionIds = [...new Set([...(previous?.sessionIds ?? []), ...workspace.sessionIds.filter((id) => ids.has(id))])]
|
|
1504
|
+
byPath.set(workspace.path, { ...workspace, sessionIds })
|
|
1505
|
+
}
|
|
1506
|
+
const workspaces = [...byPath.values()]
|
|
1507
|
+
const archivedSessionIds = [...new Set([
|
|
1508
|
+
...(existing.global?.archivedSessionIds ?? []),
|
|
1509
|
+
...mother.global.archivedSessionIds.filter((id) => ids.has(id)),
|
|
1510
|
+
])]
|
|
1511
|
+
const pinnedSessionIds = [...new Set([
|
|
1512
|
+
...(existing.global?.pinnedSessionIds ?? []),
|
|
1513
|
+
...mother.global.pinnedSessionIds.filter((id) => ids.has(id)),
|
|
1514
|
+
])]
|
|
1515
|
+
const tables = {}
|
|
1516
|
+
for (const workspace of workspaces) {
|
|
1517
|
+
tables[workspace.id] = {
|
|
1518
|
+
path: workspace.path, title: workspace.title, sessionIds: workspace.sessionIds,
|
|
1519
|
+
createdAt: workspace.createdAt, updatedAt: workspace.updatedAt,
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
ensureDir(path.dirname(targetFile))
|
|
1523
|
+
writeJsonAtomic(targetFile, {
|
|
1524
|
+
unit: { name: 'workspace', version: 2 },
|
|
1525
|
+
global: {
|
|
1526
|
+
initialized: true,
|
|
1527
|
+
defaultWorkspaceId: workspaces[0]?.id ?? null,
|
|
1528
|
+
workspaceIds: workspaces.map((workspace) => workspace.id),
|
|
1529
|
+
archivedSessionIds,
|
|
1530
|
+
pinnedSessionIds,
|
|
1531
|
+
},
|
|
1532
|
+
tables: { workspaces: tables },
|
|
1533
|
+
})
|
|
1534
|
+
return { ok: true, workspaces: workspaces.length }
|
|
1535
|
+
} catch (error) {
|
|
1536
|
+
return { ok: false, error: String(error?.message ?? error) }
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
const importSessionsInto = (homeDir, sessionIds) => {
|
|
1541
|
+
const ids = [...new Set((Array.isArray(sessionIds) ? sessionIds : []).map((id) => String(id ?? '').trim()).filter(Boolean))]
|
|
1542
|
+
if (ids.length === 0) return []
|
|
1543
|
+
if (ids.length > 5) throw new Error('too-many-sessions (max 5)')
|
|
1544
|
+
const catalog = safeGet(SERVICE.sessionCatalog)
|
|
1545
|
+
if (!catalog || typeof catalog.listSessions !== 'function') throw new Error('session-catalog-unavailable')
|
|
1546
|
+
const listed = catalog.listSessions({ limit: 500, includeArchived: false })
|
|
1547
|
+
const rows = Array.isArray(listed?.sessions) ? listed.sessions : []
|
|
1548
|
+
const sessionsRoot = String(listed?.sessionsRoot ?? '')
|
|
1549
|
+
if (!sessionsRoot) throw new Error('sessions-root-missing')
|
|
1550
|
+
const byId = new Map(rows.map((row) => [String(row.sessionId), row]))
|
|
1551
|
+
const imported = []
|
|
1552
|
+
for (const id of ids) {
|
|
1553
|
+
const row = byId.get(id)
|
|
1554
|
+
if (!row) throw new Error('unknown-session: ' + id)
|
|
1555
|
+
if (row.archived === true) throw new Error('archived-session-not-importable: ' + id)
|
|
1556
|
+
const workspaceKey = String(row.workspaceKey ?? '')
|
|
1557
|
+
if (!workspaceKey || workspaceKey.includes('..') || workspaceKey.includes('/') || workspaceKey.includes('\\')) {
|
|
1558
|
+
throw new Error('invalid-workspace-key: ' + workspaceKey)
|
|
1559
|
+
}
|
|
1560
|
+
const source = path.join(sessionsRoot, workspaceKey, id)
|
|
1561
|
+
if (!exists(source)) throw new Error('session-dir-missing: ' + id)
|
|
1562
|
+
const target = assertInside(homeDir, path.join(homeDir, 'sessions', workspaceKey, id), 'session-import')
|
|
1563
|
+
ensureDir(path.dirname(target))
|
|
1564
|
+
if (exists(target)) removeTree(target)
|
|
1565
|
+
copyTree(source, target)
|
|
1566
|
+
imported.push({ sessionId: id, title: row.title ?? null, workspaceKey })
|
|
1567
|
+
}
|
|
1568
|
+
// 工作区索引合并:让实例按工作区名分组,而不是显示 --E-GPT-- 这样的 key。
|
|
1569
|
+
const index = mergeWorkspaceIndexFor(homeDir, imported)
|
|
1570
|
+
if (index.ok === false) {
|
|
1571
|
+
try { audit('workspace-index-merge-failed', { homeDir, error: index.error }) } catch { /* ignore */ }
|
|
1572
|
+
}
|
|
1573
|
+
return imported
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1237
1576
|
const mirrorService = {
|
|
1238
|
-
status: () =>
|
|
1577
|
+
status: () => {
|
|
1578
|
+
const status = mirrorManager.getStatus()
|
|
1579
|
+
let preferences = null
|
|
1580
|
+
let sync = null
|
|
1581
|
+
try { preferences = preferencesStore.get() } catch { preferences = null }
|
|
1582
|
+
try { sync = readJson(path.join(mirrorRoot, 'sync-state.json'), null) } catch { sync = null }
|
|
1583
|
+
return { ...status, preferences, sync }
|
|
1584
|
+
},
|
|
1239
1585
|
getPreferences: () => preferencesStore.get(),
|
|
1240
1586
|
setPreferences: (patch = {}) => preferencesStore.update(patch),
|
|
1241
1587
|
listEssences: () => {
|
|
1242
1588
|
const defaultEssence = essenceManager.getDefault()
|
|
1589
|
+
// 元主是否落后于母体镜像:lastMergedFingerprint !== 当前镜像指纹。
|
|
1590
|
+
let mirrorFingerprint = ''
|
|
1591
|
+
try { mirrorFingerprint = String(essenceManager.loadMirror().fingerprint ?? '') } catch { /* mirror 不可读时全部标 stale=false */ }
|
|
1243
1592
|
const essences = essenceManager.list().map((meta) => {
|
|
1244
1593
|
const ui = buildEssenceActions({ locked: meta.locked === true, archived: meta.archived === true })
|
|
1594
|
+
const stale = mirrorFingerprint.length > 0 && meta.archived !== true
|
|
1595
|
+
&& String(meta.lastMergedFingerprint ?? '') !== mirrorFingerprint
|
|
1596
|
+
const sessionQuota = countEssenceSessions(meta.id, meta)
|
|
1245
1597
|
return {
|
|
1246
1598
|
...meta,
|
|
1247
1599
|
locked: meta.locked === true,
|
|
1248
1600
|
official: meta.official === true,
|
|
1249
1601
|
archived: meta.archived === true,
|
|
1602
|
+
stale,
|
|
1603
|
+
sessions: sessionQuota,
|
|
1604
|
+
// 设计稿字段:quota.sessions = { used, limit, over }
|
|
1605
|
+
quota: { sessions: sessionQuota },
|
|
1606
|
+
// 运行态:面板据此把「打开」切换成「停止」。
|
|
1607
|
+
runtime: (() => {
|
|
1608
|
+
try {
|
|
1609
|
+
const live = forker()?.status?.(runtimeForkId(meta.id))
|
|
1610
|
+
return live ? { running: live.running === true, pid: live.pid ?? null, port: live.port ?? null } : { running: false, pid: null, port: null }
|
|
1611
|
+
} catch { return { running: false, pid: null, port: null } }
|
|
1612
|
+
})(),
|
|
1250
1613
|
pluginCount: (() => { try { return essenceManager.pluginCount(meta.id) } catch { return 0 } })(),
|
|
1251
1614
|
actions: ui.actions,
|
|
1252
1615
|
blocks: ui.blocks,
|
|
@@ -1258,18 +1621,377 @@ export function apply(ctx, config) {
|
|
|
1258
1621
|
defaultId: defaultEssence.essenceId,
|
|
1259
1622
|
defaultEssence,
|
|
1260
1623
|
essences,
|
|
1624
|
+
mirrorFingerprint,
|
|
1625
|
+
staleCount: essences.filter(item => item.stale === true).length,
|
|
1261
1626
|
capacity: { slots: 7, defaultLimit: 5, used: essences.filter(item => item.archived !== true).length },
|
|
1262
1627
|
}
|
|
1263
1628
|
},
|
|
1264
1629
|
createEssence: (input = {}) => essenceManager.create({
|
|
1265
1630
|
name: input?.name, tier: input?.tier, parentId: input?.parentId ?? null,
|
|
1631
|
+
defaultPatchEntries: Array.isArray(input?.defaultPatchEntries) ? input.defaultPatchEntries : undefined,
|
|
1266
1632
|
}),
|
|
1633
|
+
defaultPreset: async () => {
|
|
1634
|
+
const entries = await listInstalledPlugins()
|
|
1635
|
+
const plan = planDefaultEssence(entries ?? [])
|
|
1636
|
+
const existingId = readDefaultEssenceId()
|
|
1637
|
+
const meta = existingId ? essenceManager.getMeta(existingId) : null
|
|
1638
|
+
return { ok: true, pluginManager: Array.isArray(entries), plan, defaultEssenceId: meta?.id ? existingId : '', exists: Boolean(meta?.id) }
|
|
1639
|
+
},
|
|
1640
|
+
ensureDefaultEssence: async ({ apply = false, force = false, mode = 'copy-local' } = {}) => {
|
|
1641
|
+
const existingId = readDefaultEssenceId()
|
|
1642
|
+
const existing = existingId ? essenceManager.getMeta(existingId) : null
|
|
1643
|
+
if (existing?.id) return { ok: true, existed: true, created: false, essenceId: existingId, mode }
|
|
1644
|
+
const entries = await listInstalledPlugins()
|
|
1645
|
+
const plan = planDefaultEssence(entries ?? [])
|
|
1646
|
+
const userEssences = essenceManager.list().filter((meta) => meta.official !== true)
|
|
1647
|
+
if (!force && userEssences.length > 0) return { ok: false, error: 'user-essence-exists', plan, mode }
|
|
1648
|
+
if (apply !== true) return { ok: true, dryRun: true, plan, mode }
|
|
1649
|
+
if (mode === 'preset') {
|
|
1650
|
+
const patchEntries = []
|
|
1651
|
+
const pending = []
|
|
1652
|
+
for (const group of plan.groups) {
|
|
1653
|
+
for (const plugin of group.plugins) {
|
|
1654
|
+
if (!plugin.installed) { pending.push({ spec: plugin.spec, group: group.key }); continue }
|
|
1655
|
+
patchEntries.push({ id: plugin.pluginId || plugin.spec, name: plugin.spec, disabled: group.enabled !== true })
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
if (patchEntries.length === 0) return { ok: false, error: 'no-installed-default-plugins', plan, pending, mode }
|
|
1659
|
+
const created = essenceManager.create({ name: DEFAULT_ESSENCE_NAME, tier: 'free', defaultPatchEntries: patchEntries })
|
|
1660
|
+
writeDefaultEssenceId(created.id)
|
|
1661
|
+
try {
|
|
1662
|
+
writeJsonAtomic(path.join(essenceManager.essenceRoot(created.id), 'default-preset.json'), {
|
|
1663
|
+
at: nowMs(), mode, version: plan.version, groups: plan.groups, patchEntries, pending,
|
|
1664
|
+
})
|
|
1665
|
+
} catch { /* marker 失败不影响创建 */ }
|
|
1666
|
+
audit('default-essence-created', { essenceId: created.id, mode, installed: patchEntries.length, pending: pending.length })
|
|
1667
|
+
return { ok: true, created: true, mode, essenceId: created.id, plan, pending }
|
|
1668
|
+
}
|
|
1669
|
+
// copy-local(默认):只复制本机插件的启用/禁用 + 设置;不复制任何会话/数据/代码/凭据。
|
|
1670
|
+
let captured
|
|
1671
|
+
try {
|
|
1672
|
+
captured = essenceManager.captureFromProfile(templateDir(), { name: DEFAULT_ESSENCE_NAME, tier: 'free' })
|
|
1673
|
+
} catch (error) {
|
|
1674
|
+
return { ok: false, error: 'capture-failed', detail: String(error?.message ?? error), plan, mode }
|
|
1675
|
+
}
|
|
1676
|
+
const created = captured.meta ?? captured
|
|
1677
|
+
writeDefaultEssenceId(created.id)
|
|
1678
|
+
try {
|
|
1679
|
+
writeJsonAtomic(path.join(essenceManager.essenceRoot(created.id), 'default-preset.json'), {
|
|
1680
|
+
at: nowMs(), mode, source: templateDir(),
|
|
1681
|
+
captured: captured.captured ?? null,
|
|
1682
|
+
conflicts: captured.conflicts ?? [],
|
|
1683
|
+
note: '只复制插件启用状态与设置;未复制会话/项目/凭据/Token',
|
|
1684
|
+
})
|
|
1685
|
+
} catch { /* marker 失败不影响创建 */ }
|
|
1686
|
+
audit('default-essence-created', { essenceId: created.id, mode, source: templateDir() })
|
|
1687
|
+
return { ok: true, created: true, mode, essenceId: created.id, plan, captured: captured.captured ?? null, conflicts: captured.conflicts ?? [] }
|
|
1688
|
+
},
|
|
1267
1689
|
renameEssence: (essenceId, name) => essenceManager.rename(essenceId, name),
|
|
1268
1690
|
archiveEssence: (essenceId, archived = true) => essenceManager.archive(essenceId, archived === true),
|
|
1269
|
-
deleteEssence: (essenceId) =>
|
|
1270
|
-
|
|
1691
|
+
deleteEssence: (essenceId) => {
|
|
1692
|
+
const id = String(essenceId ?? '').trim()
|
|
1693
|
+
const meta = essenceManager.getMeta(id)
|
|
1694
|
+
// 删除配置/插件目录,但**保留运行态会话**:旧布局把运行时 home 放在原身目录里,先搬出去。
|
|
1695
|
+
const legacyHome = path.join(essenceManager.essenceRoot(id), 'runtime', 'home')
|
|
1696
|
+
const preserved = runtimeHomeFor(id)
|
|
1697
|
+
try {
|
|
1698
|
+
if (exists(legacyHome) && !exists(preserved)) {
|
|
1699
|
+
ensureDir(path.dirname(preserved))
|
|
1700
|
+
copyTree(legacyHome, preserved)
|
|
1701
|
+
}
|
|
1702
|
+
} catch { /* 保留失败不阻塞删除,如实返回 */ }
|
|
1703
|
+
const removed = essenceManager.remove(id)
|
|
1704
|
+
addTombstone(id, meta?.name)
|
|
1705
|
+
return { ...removed, essenceId: id, tombstone: true, sessionsPreserved: exists(preserved) }
|
|
1706
|
+
},
|
|
1707
|
+
copyEssence: (essenceId, name) => {
|
|
1708
|
+
const result = essenceManager.copy(essenceId, { name })
|
|
1709
|
+
// v3.0.9:沙盒会话(运行态隔离 home 里的 sessions)随副本一起复制,副本可继续开发。
|
|
1710
|
+
const candidates = [
|
|
1711
|
+
path.join(runtimeHomeFor(String(essenceId)), 'sessions'),
|
|
1712
|
+
path.join(essenceManager.essenceRoot(String(essenceId)), 'runtime', 'home', 'sessions'),
|
|
1713
|
+
path.join(layout.dataDir, 'runtime', runtimeForkId(String(essenceId)), 'home', 'sessions'),
|
|
1714
|
+
]
|
|
1715
|
+
const source = candidates.find((dir) => exists(dir))
|
|
1716
|
+
let sessionsCopied = 0
|
|
1717
|
+
if (source) {
|
|
1718
|
+
const target = path.join(runtimeHomeFor(result.id), 'sessions')
|
|
1719
|
+
try {
|
|
1720
|
+
copyTree(source, target)
|
|
1721
|
+
const walk = (dir) => {
|
|
1722
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
1723
|
+
const file = path.join(dir, entry.name)
|
|
1724
|
+
if (entry.isDirectory()) walk(file)
|
|
1725
|
+
else if (entry.isFile()) sessionsCopied += 1
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
walk(target)
|
|
1729
|
+
} catch { /* 会话复制失败不阻塞配置副本,如实返回 0 */ }
|
|
1730
|
+
// 工作区索引也随副本走,否则副本里会话会按 workspace key 显示。
|
|
1731
|
+
const sourceIndex = path.join(path.dirname(path.dirname(source)), 'storages', 'workspace.json')
|
|
1732
|
+
if (exists(sourceIndex)) {
|
|
1733
|
+
const targetIndex = path.join(runtimeHomeFor(result.id), 'storages', 'workspace.json')
|
|
1734
|
+
try { ensureDir(path.dirname(targetIndex)); fs.copyFileSync(sourceIndex, targetIndex) } catch { /* ignore */ }
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
return { ...result, copy: { ...(result.copy ?? {}), sessionsCopied } }
|
|
1738
|
+
},
|
|
1739
|
+
// v3.0.9 母体 → 元主:克隆母体 profile 的可写层(patch/依赖/设置),不带凭据与会话。
|
|
1740
|
+
captureEssence: (input = {}) => {
|
|
1741
|
+
const result = essenceManager.captureFromProfile(templateDir(), {
|
|
1742
|
+
name: input?.name,
|
|
1743
|
+
tier: input?.tier,
|
|
1744
|
+
parentId: input?.parentId ?? null,
|
|
1745
|
+
includeDependencies: input?.includeDependencies !== false,
|
|
1746
|
+
includeSettings: input?.includeSettings !== false,
|
|
1747
|
+
})
|
|
1748
|
+
const defaultEssence = input?.setDefault === true ? essenceManager.setDefault(result.meta.id) : null
|
|
1749
|
+
return { ...result, default: defaultEssence }
|
|
1750
|
+
},
|
|
1271
1751
|
setDefaultEssence: (essenceId) => essenceManager.setDefault(essenceId),
|
|
1272
|
-
downloadEssence: (essenceId) =>
|
|
1752
|
+
downloadEssence: (essenceId, options = {}) => {
|
|
1753
|
+
const bundle = essenceManager.downloadBundle(essenceId, { full: options?.full === true })
|
|
1754
|
+
if (bundle.full !== true) return bundle
|
|
1755
|
+
// 整包迁移还要带走运行态沙盒:会话 + 工作区索引(运行态 home 在原身文件夹之外)。
|
|
1756
|
+
const id = String(essenceId)
|
|
1757
|
+
const home = runtimeHomeFor(id)
|
|
1758
|
+
const addFile = (relative, file) => {
|
|
1759
|
+
try {
|
|
1760
|
+
const bytes = fs.readFileSync(file)
|
|
1761
|
+
bundle.files.push({ path: relative, base64: bytes.toString('base64') })
|
|
1762
|
+
bundle.bytes += bytes.length
|
|
1763
|
+
} catch { /* 读失败跳过,不阻塞导出 */ }
|
|
1764
|
+
}
|
|
1765
|
+
const indexFile = path.join(home, 'storages', 'workspace.json')
|
|
1766
|
+
if (exists(indexFile)) addFile('runtime/home/storages/workspace.json', indexFile)
|
|
1767
|
+
const sessionsDir = path.join(home, 'sessions')
|
|
1768
|
+
if (exists(sessionsDir)) {
|
|
1769
|
+
const walk = (dir, rel) => {
|
|
1770
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
1771
|
+
const fullPath = path.join(dir, entry.name)
|
|
1772
|
+
const nextRel = rel ? rel + '/' + entry.name : entry.name
|
|
1773
|
+
if (entry.isDirectory()) walk(fullPath, nextRel)
|
|
1774
|
+
else if (entry.isFile()) addFile('runtime/home/sessions/' + nextRel, fullPath)
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
walk(sessionsDir, '')
|
|
1778
|
+
}
|
|
1779
|
+
return bundle
|
|
1780
|
+
},
|
|
1781
|
+
backupEssence: (essenceId) => essenceManager.backup(essenceId),
|
|
1782
|
+
restoreEssence: (essenceId) => essenceManager.restoreBackup(essenceId),
|
|
1783
|
+
importEssence: (input = {}) => essenceManager.importBundle(input?.bundle ?? input, {
|
|
1784
|
+
name: input?.name, tier: input?.tier, parentId: input?.parentId ?? null,
|
|
1785
|
+
}),
|
|
1786
|
+
// v3.0.9 原身运行态:用元主 merged/profile 起一个**隔离 home** 的配置态实例。
|
|
1787
|
+
// 隔离边界:DSH_HOME = essences/<id>/runtime/home(自己的 sessions/storages),
|
|
1788
|
+
// 不写母体 sessions;node_modules 通过 junction 指向母体模块树(不复制)。
|
|
1789
|
+
startEssenceRuntime: async (essenceId, input = {}) => {
|
|
1790
|
+
const id = String(essenceId ?? '').trim()
|
|
1791
|
+
const meta = essenceManager.getMeta(id)
|
|
1792
|
+
if (!meta || typeof meta.id !== 'string') throw new Error('unknown-essence')
|
|
1793
|
+
if (meta.archived === true) throw new Error('essence-archived')
|
|
1794
|
+
// 进行中会话配额(默认 10;归档不限;达到上限拒绝再开实例)。
|
|
1795
|
+
const sessionQuota = countEssenceSessions(id, meta)
|
|
1796
|
+
if (sessionQuota.over) throw new Error(`session-quota-exceeded: ${sessionQuota.used}/${sessionQuota.limit}`)
|
|
1797
|
+
const f = forker()
|
|
1798
|
+
if (!f || typeof f.provision !== 'function' || typeof f.spawn !== 'function') throw new Error('forker-unavailable')
|
|
1799
|
+
await essenceManager.ensureFresh(id)
|
|
1800
|
+
const merged = essenceManager.mergedProfileDir(id)
|
|
1801
|
+
if (!exists(merged)) throw new Error('merged-profile-missing')
|
|
1802
|
+
assertInside(layout.essenceRoot, merged, 'essence-merged')
|
|
1803
|
+
const motherModules = path.join(templateDir(), 'node_modules')
|
|
1804
|
+
const link = path.join(merged, 'node_modules')
|
|
1805
|
+
if (exists(motherModules) && !exists(link)) {
|
|
1806
|
+
try { fs.symlinkSync(motherModules, link, 'junction') } catch { /* 已存在或权限不足时继续,forker 会再尝试 */ }
|
|
1807
|
+
}
|
|
1808
|
+
const forkId = runtimeForkId(id)
|
|
1809
|
+
// v3.0.9 三区:运行态 home 在 runtimeRoot 下(FANG_HOME 时是 sessions/<essenceId>/home),
|
|
1810
|
+
// 原身文件夹只保留配置,项目/会话/任务文件不落原身目录。
|
|
1811
|
+
const homeDir = runtimeHomeFor(id)
|
|
1812
|
+
assertInside(layout.runtimeRoot, homeDir, 'runtime-home')
|
|
1813
|
+
const legacyHomes = [
|
|
1814
|
+
path.join(layout.dataDir, 'runtime', forkId, 'home'),
|
|
1815
|
+
path.join(essenceManager.essenceRoot(id), 'runtime', 'home'),
|
|
1816
|
+
]
|
|
1817
|
+
if (!exists(homeDir)) {
|
|
1818
|
+
const legacyHome = legacyHomes.find((dir) => exists(dir))
|
|
1819
|
+
if (legacyHome) {
|
|
1820
|
+
try { ensureDir(path.dirname(homeDir)); copyTree(legacyHome, homeDir) } catch { /* 迁移失败不阻塞 */ }
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
const provisioned = await f.provision({
|
|
1824
|
+
forkId, taskTitle: `元主运行时 · ${String(meta.name ?? id)}`,
|
|
1825
|
+
homeDir, profile: 'essence-runtime', profileTemplate: merged,
|
|
1826
|
+
})
|
|
1827
|
+
if (!provisioned.ok) throw new Error(String(provisioned.error ?? 'runtime-provision-failed'))
|
|
1828
|
+
// 先导入选中的进行中会话,再拉起实例(实例启动时就能看到它们)。
|
|
1829
|
+
const importedSessions = importSessionsInto(homeDir, input?.sessionIds)
|
|
1830
|
+
// 注意:forker.spawn 需要显式 homeDir/profile(它不从 provision 记录里猜)。
|
|
1831
|
+
const started = await f.spawn({
|
|
1832
|
+
forkId,
|
|
1833
|
+
homeDir,
|
|
1834
|
+
profile: 'essence-runtime',
|
|
1835
|
+
cliPath: cliPath(),
|
|
1836
|
+
env: { DSH_FANG_ROLE: 'fork', DSH_FANG_TASK_ID: forkId },
|
|
1837
|
+
})
|
|
1838
|
+
if (!started.ok) throw new Error(`runtime-spawn-failed: ${started.error ?? 'unknown'} (forkId=${forkId}, homeDir=${homeDir}, profile=essence-runtime)`)
|
|
1839
|
+
return {
|
|
1840
|
+
ok: true, essenceId: id, forkId,
|
|
1841
|
+
url: started.url, port: started.port, pid: started.pid,
|
|
1842
|
+
sandboxHome: homeDir,
|
|
1843
|
+
importedSessions,
|
|
1844
|
+
}
|
|
1845
|
+
},
|
|
1846
|
+
stopEssenceRuntime: (essenceId) => {
|
|
1847
|
+
const id = String(essenceId ?? '').trim()
|
|
1848
|
+
const f = forker()
|
|
1849
|
+
if (!f || typeof f.stop !== 'function') return { ok: false, error: 'forker-unavailable' }
|
|
1850
|
+
const forkId = runtimeForkId(id)
|
|
1851
|
+
const out = f.stop(forkId)
|
|
1852
|
+
return { ok: true, essenceId: id, forkId, stopped: out?.ok !== false }
|
|
1853
|
+
},
|
|
1854
|
+
essenceRuntimeStatus: (essenceId) => {
|
|
1855
|
+
const id = String(essenceId ?? '').trim()
|
|
1856
|
+
const f = forker()
|
|
1857
|
+
if (!f || typeof f.status !== 'function') return { ok: false, error: 'forker-unavailable' }
|
|
1858
|
+
const forkId = runtimeForkId(id)
|
|
1859
|
+
let runtime = null
|
|
1860
|
+
try { runtime = f.status(forkId) ?? null } catch { runtime = null }
|
|
1861
|
+
return { ok: true, essenceId: id, forkId, runtime }
|
|
1862
|
+
},
|
|
1863
|
+
/** 打开前可选导入的「进行中」会话(最多 50 条给选择器,提交时服务端再限 5 条)。 */
|
|
1864
|
+
essenceOpenCandidates: () => {
|
|
1865
|
+
const catalog = safeGet(SERVICE.sessionCatalog)
|
|
1866
|
+
if (!catalog || typeof catalog.listSessions !== 'function') return { ok: false, error: 'session-catalog-unavailable' }
|
|
1867
|
+
const listed = catalog.listSessions({ limit: 200, includeArchived: false })
|
|
1868
|
+
const sessions = (Array.isArray(listed?.sessions) ? listed.sessions : [])
|
|
1869
|
+
.filter((row) => row?.archived !== true)
|
|
1870
|
+
.slice(0, 50)
|
|
1871
|
+
.map((row) => ({
|
|
1872
|
+
sessionId: row.sessionId,
|
|
1873
|
+
title: row.title ?? null,
|
|
1874
|
+
workspaceTitle: row.workspaceTitle ?? null,
|
|
1875
|
+
updatedAt: row.updatedAt ?? 0,
|
|
1876
|
+
}))
|
|
1877
|
+
return { ok: true, sessions, total: sessions.length }
|
|
1878
|
+
},
|
|
1879
|
+
/** 元主详情页数据:元数据 + overlay 插件条目 + 设置项 + 备份/运行态/日志(不含凭据)。 */
|
|
1880
|
+
essenceDetail: (essenceId) => {
|
|
1881
|
+
const id = String(essenceId ?? '').trim()
|
|
1882
|
+
const meta = essenceManager.getMeta(id)
|
|
1883
|
+
if (!meta || typeof meta.id !== 'string') throw new Error('unknown-essence')
|
|
1884
|
+
const root = essenceManager.essenceRoot(id)
|
|
1885
|
+
const overlay = essenceManager.loadOverlay(root)
|
|
1886
|
+
const patchEntries = (overlay.patchEntries || []).map((entry) => ({
|
|
1887
|
+
id: String(entry?.id ?? ''),
|
|
1888
|
+
name: String(entry?.name ?? ''),
|
|
1889
|
+
disabled: entry?.disabled === true,
|
|
1890
|
+
}))
|
|
1891
|
+
const f = forker()
|
|
1892
|
+
let runtime = null
|
|
1893
|
+
let logs = ''
|
|
1894
|
+
try { runtime = f?.status?.(runtimeForkId(id)) ?? null } catch { runtime = null }
|
|
1895
|
+
try { logs = String(f?.logs?.(runtimeForkId(id), 120) || '') } catch { logs = '' }
|
|
1896
|
+
return {
|
|
1897
|
+
ok: true,
|
|
1898
|
+
essenceId: id,
|
|
1899
|
+
meta,
|
|
1900
|
+
overlay: { patchEntries, settings: Object.keys(overlay.settings || {}) },
|
|
1901
|
+
sessions: countEssenceSessions(id, meta),
|
|
1902
|
+
backup: exists(path.join(root, 'Backup')),
|
|
1903
|
+
runtime,
|
|
1904
|
+
logs,
|
|
1905
|
+
}
|
|
1906
|
+
},
|
|
1907
|
+
/** 打开运行态:返回带临时 token 的 URL(仅内存,不落盘)。 */ openEssenceRuntime: (essenceId) => {
|
|
1908
|
+
const id = String(essenceId ?? '').trim()
|
|
1909
|
+
const f = forker()
|
|
1910
|
+
if (!f || typeof f.openUrl !== 'function') return { ok: false, error: 'forker-unavailable' }
|
|
1911
|
+
const out = f.openUrl(runtimeForkId(id))
|
|
1912
|
+
if (!out || out.ok === false) return { ok: false, error: out?.error ?? 'not-running' }
|
|
1913
|
+
return { ok: true, essenceId: id, url: out.url, port: out.port ?? null }
|
|
1914
|
+
},
|
|
1915
|
+
// v3.0.9 升级链路 2.1:把本机母体 profile(PC 客户端那份)克隆成镜像基础层。
|
|
1916
|
+
cloneMotherProfile: (input = {}) => {
|
|
1917
|
+
const sourceDir = path.resolve(String(input?.sourceDir || templateDir()))
|
|
1918
|
+
const packageFile = path.join(sourceDir, 'package.json')
|
|
1919
|
+
if (!exists(packageFile)) throw new Error('mother profile has no package.json: ' + sourceDir)
|
|
1920
|
+
const activeProfile = path.join(mirrorRoot, 'active', 'profile')
|
|
1921
|
+
const relative = path.relative(path.resolve(mirrorRoot), sourceDir)
|
|
1922
|
+
if (relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))) {
|
|
1923
|
+
throw new Error('clone: source is already inside the mirror')
|
|
1924
|
+
}
|
|
1925
|
+
let backup = null
|
|
1926
|
+
try { backup = mirrorManager.backup({ label: '克隆母体前自动备份' }) } catch { /* 首次克隆没有可备份内容 */ }
|
|
1927
|
+
if (exists(activeProfile)) removeTree(activeProfile)
|
|
1928
|
+
ensureDir(activeProfile)
|
|
1929
|
+
const picked = []
|
|
1930
|
+
for (const rel of ['package.json', 'cordis.patch.yml', 'cordis.yml']) {
|
|
1931
|
+
const from = path.join(sourceDir, rel)
|
|
1932
|
+
if (!exists(from)) continue
|
|
1933
|
+
fs.copyFileSync(from, path.join(activeProfile, rel))
|
|
1934
|
+
picked.push(rel)
|
|
1935
|
+
}
|
|
1936
|
+
const settingsDir = path.join(sourceDir, 'settings')
|
|
1937
|
+
if (exists(settingsDir)) { copyTree(settingsDir, path.join(activeProfile, 'settings')); picked.push('settings/') }
|
|
1938
|
+
let version = ''
|
|
1939
|
+
try { version = String(readJson(packageFile, {})?.version ?? '') } catch { version = '' }
|
|
1940
|
+
const meta = mirrorManager.readMeta()
|
|
1941
|
+
mirrorManager.writeMeta({
|
|
1942
|
+
...meta,
|
|
1943
|
+
version: version || meta.version || 'unknown',
|
|
1944
|
+
installedAt: nowMs(),
|
|
1945
|
+
lastBackupAt: backup?.createdAt ?? meta.lastBackupAt,
|
|
1946
|
+
})
|
|
1947
|
+
writeJsonAtomic(path.join(mirrorRoot, 'sync-state.json'), { lastSyncAt: nowMs(), sourceDir })
|
|
1948
|
+
return {
|
|
1949
|
+
ok: true,
|
|
1950
|
+
sourceDir,
|
|
1951
|
+
target: activeProfile,
|
|
1952
|
+
files: picked,
|
|
1953
|
+
version: version || meta.version || 'unknown',
|
|
1954
|
+
backup: backup ? { id: backup.id, bucket: backup.bucket, createdAt: backup.createdAt } : null,
|
|
1955
|
+
}
|
|
1956
|
+
},
|
|
1957
|
+
/** 空白母体(初始盘):备份当前 → 清空 active/profile → 版本标记 blank。 */
|
|
1958
|
+
blankMother: () => {
|
|
1959
|
+
const activeProfile = path.join(mirrorRoot, 'active', 'profile')
|
|
1960
|
+
let backup = null
|
|
1961
|
+
try { backup = mirrorManager.backup({ label: '空白母体前自动备份' }) } catch { /* 首次为空 */ }
|
|
1962
|
+
if (exists(activeProfile)) removeTree(activeProfile)
|
|
1963
|
+
ensureDir(activeProfile)
|
|
1964
|
+
const meta = mirrorManager.readMeta()
|
|
1965
|
+
mirrorManager.writeMeta({
|
|
1966
|
+
...meta,
|
|
1967
|
+
version: 'blank',
|
|
1968
|
+
installedAt: nowMs(),
|
|
1969
|
+
lastBackupAt: backup?.createdAt ?? meta.lastBackupAt,
|
|
1970
|
+
})
|
|
1971
|
+
return {
|
|
1972
|
+
ok: true,
|
|
1973
|
+
version: 'blank',
|
|
1974
|
+
target: activeProfile,
|
|
1975
|
+
backup: backup ? { id: backup.id, bucket: backup.bucket, createdAt: backup.createdAt } : null,
|
|
1976
|
+
}
|
|
1977
|
+
},
|
|
1978
|
+
// v3.0.9 升级链路 3:母体变化后,元主按 overlay 重放到新镜像(配置不动)。
|
|
1979
|
+
syncEssences: async (input = {}) => {
|
|
1980
|
+
const essenceId = String(input?.essenceId ?? '').trim()
|
|
1981
|
+
if (!essenceId) {
|
|
1982
|
+
const out = await essenceManager.recomputeAll({ concurrency: Number(input?.concurrency) || 2 })
|
|
1983
|
+
return { ok: true, mode: 'all', ...out }
|
|
1984
|
+
}
|
|
1985
|
+
const meta = essenceManager.getMeta(essenceId)
|
|
1986
|
+
if (meta.locked === true) return { ok: false, error: 'locked', essenceId }
|
|
1987
|
+
if (meta.archived === true) return { ok: false, error: 'archived', essenceId }
|
|
1988
|
+
const fresh = await essenceManager.ensureFresh(essenceId)
|
|
1989
|
+
return {
|
|
1990
|
+
ok: true, mode: 'one', essenceId,
|
|
1991
|
+
recomputed: fresh.recomputed === true,
|
|
1992
|
+
status: fresh.meta?.status ?? 'unknown',
|
|
1993
|
+
}
|
|
1994
|
+
},
|
|
1273
1995
|
backup: (input = {}) => mirrorManager.backup({
|
|
1274
1996
|
label: input?.label, bucket: input?.bucket === 'restore' ? 'restore' : 'backup',
|
|
1275
1997
|
}),
|
|
@@ -1296,6 +2018,21 @@ export function apply(ctx, config) {
|
|
|
1296
2018
|
if (status.meta?.nextBackupAt !== null && Date.now() >= status.meta.nextBackupAt) {
|
|
1297
2019
|
mirrorManager.maybeAutoBackup()
|
|
1298
2020
|
}
|
|
2021
|
+
// 母体自动同步:按偏好 6/12/24h 从本机 profile 克隆到镜像(关闭时不跑)。
|
|
2022
|
+
const prefs = preferencesStore.get()
|
|
2023
|
+
const syncHours = Number(prefs?.syncIntervalHours)
|
|
2024
|
+
if (Number.isFinite(syncHours) && syncHours > 0) {
|
|
2025
|
+
let last = 0
|
|
2026
|
+
try { last = Number(readJson(path.join(mirrorRoot, 'sync-state.json'), {})?.lastSyncAt) || 0 } catch { last = 0 }
|
|
2027
|
+
if (Date.now() - last >= syncHours * 3_600_000) {
|
|
2028
|
+
try {
|
|
2029
|
+
mirrorService.cloneMotherProfile({})
|
|
2030
|
+
ctx.logger?.info?.('[mirror] auto-sync completed', { hours: syncHours })
|
|
2031
|
+
} catch (error) {
|
|
2032
|
+
ctx.logger?.warn?.('[mirror] auto-sync failed', { error: String(error?.message ?? error) })
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
1299
2036
|
} catch (error) {
|
|
1300
2037
|
ctx.logger?.warn?.('[mirror] auto backup tick failed', { error: String(error?.message ?? error) })
|
|
1301
2038
|
}
|
|
@@ -1347,12 +2084,32 @@ export function apply(ctx, config) {
|
|
|
1347
2084
|
ctx.effect(() => () => clearInterval(t))
|
|
1348
2085
|
}
|
|
1349
2086
|
|
|
2087
|
+
// v3.0.9:连接信息要的宿主服务(只有 Web 运行时才有;分身/无 Web 环境允许缺失)。
|
|
2088
|
+
// 必须用 ctx.inject 取——直接 child.get 在插件上下文里拿不到这两个服务。
|
|
2089
|
+
let connectionService = null
|
|
2090
|
+
let webAppService = null
|
|
2091
|
+
ctx.inject(['connection'], (child) => {
|
|
2092
|
+
try { connectionService = child.get('connection') ?? child.connection ?? null } catch { connectionService = null }
|
|
2093
|
+
})
|
|
2094
|
+
ctx.inject(['webApp'], (child) => {
|
|
2095
|
+
try { webAppService = child.get('webApp') ?? child.webApp ?? null } catch { webAppService = null }
|
|
2096
|
+
})
|
|
2097
|
+
|
|
1350
2098
|
// ── HTTP 门户 ──────────────────────────────────────────────────────────
|
|
1351
2099
|
if (cfg.routes?.enabled !== false) {
|
|
1352
2100
|
ctx.inject(['webServer'], (child) => {
|
|
1353
2101
|
const webServer = child.get('webServer') ?? child.webServer
|
|
1354
2102
|
if (!webServer || typeof webServer.register !== 'function') return
|
|
1355
2103
|
compatWebServer = webServer
|
|
2104
|
+
// v3.0.8:把当前宿主 origin 写到 dataDir/endpoint.json,供 Electron 面板发现,
|
|
2105
|
+
// 避免桌面宿主端口每次变化后必须手工设置 FANG_UPSTREAM。
|
|
2106
|
+
try {
|
|
2107
|
+
const origin = typeof webServer.getOrigin === 'function' ? webServer.getOrigin() : ''
|
|
2108
|
+
if (origin) {
|
|
2109
|
+
fs.mkdirSync(layout.dataDir, { recursive: true })
|
|
2110
|
+
fs.writeFileSync(path.join(layout.dataDir, 'endpoint.json'), JSON.stringify({ url: origin, updatedAt: new Date().toISOString() }) + '\n')
|
|
2111
|
+
}
|
|
2112
|
+
} catch { /* endpoint discovery is best-effort */ }
|
|
1356
2113
|
const prefix = String(cfg.routes?.prefix ?? '/fang').replace(/\/+$/, '') || '/fang'
|
|
1357
2114
|
|
|
1358
2115
|
const json = (res, code, obj) => {
|
|
@@ -1370,38 +2127,123 @@ export function apply(ctx, config) {
|
|
|
1370
2127
|
const route = (method, pathname, handler, routeOptions) => webServer.register({
|
|
1371
2128
|
kind: 'exact',
|
|
1372
2129
|
path: pathname,
|
|
2130
|
+
method,
|
|
1373
2131
|
handler: async (req, res) => {
|
|
1374
|
-
|
|
1375
|
-
//
|
|
2132
|
+
// v3.0.5/B1:loopback Host + Origin/CSRF + 安装 token(fail-closed)。
|
|
2133
|
+
// Auth must run before the method check: a token-less POST is 401, not 405.
|
|
1376
2134
|
const decision = checkRequestAuth(req, {
|
|
1377
2135
|
token: authToken,
|
|
1378
2136
|
publicRoute: authToken.length === 0 || routeOptions?.public === true,
|
|
1379
2137
|
})
|
|
1380
|
-
if (!decision.ok) return json(res, decision.status,
|
|
2138
|
+
if (!decision.ok) return json(res, decision.status, authErrorBody(decision))
|
|
2139
|
+
if (req.method !== method) {
|
|
2140
|
+
try { res.setHeader?.('allow', method) } catch { /* fake res */ }
|
|
2141
|
+
return json(res, 405, { ok: false, error: 'method-not-allowed', code: 'method-not-allowed' })
|
|
2142
|
+
}
|
|
1381
2143
|
try { return await handler(req, res) } catch (e) {
|
|
1382
|
-
return json(res, 500, { ok: false, error: 'handler-threw', detail: String(e?.message ?? e) })
|
|
2144
|
+
return json(res, 500, { ok: false, error: 'handler-threw', code: 'handler-threw', detail: String(e?.message ?? e) })
|
|
2145
|
+
}
|
|
2146
|
+
},
|
|
2147
|
+
})
|
|
2148
|
+
|
|
2149
|
+
// The DSH webServer keys exact routes by path only, so GET+POST on the same
|
|
2150
|
+
// path cannot be two `register()` calls (the second throws and later routes
|
|
2151
|
+
// silently never register). One handler dispatches by method instead.
|
|
2152
|
+
const routeMethods = (pathname, handlers, routeOptions) => webServer.register({
|
|
2153
|
+
kind: 'exact',
|
|
2154
|
+
path: pathname,
|
|
2155
|
+
method: Object.keys(handlers).join(','),
|
|
2156
|
+
handler: async (req, res) => {
|
|
2157
|
+
const decision = checkRequestAuth(req, {
|
|
2158
|
+
token: authToken,
|
|
2159
|
+
publicRoute: authToken.length === 0 || routeOptions?.public === true,
|
|
2160
|
+
})
|
|
2161
|
+
if (!decision.ok) return json(res, decision.status, authErrorBody(decision))
|
|
2162
|
+
const allow = Object.keys(handlers)
|
|
2163
|
+
const fn = handlers[String(req.method ?? 'GET').toUpperCase()]
|
|
2164
|
+
if (typeof fn !== 'function') {
|
|
2165
|
+
try { res.setHeader?.('allow', allow.join(', ')) } catch { /* fake res */ }
|
|
2166
|
+
return json(res, 405, { ok: false, error: 'method-not-allowed', code: 'method-not-allowed' })
|
|
2167
|
+
}
|
|
2168
|
+
try { return await fn(req, res) } catch (e) {
|
|
2169
|
+
return json(res, 500, { ok: false, error: 'handler-threw', code: 'handler-threw', detail: String(e?.message ?? e) })
|
|
1383
2170
|
}
|
|
1384
2171
|
},
|
|
1385
2172
|
})
|
|
1386
2173
|
|
|
2174
|
+
// ── 分支路由共用:taskId 必须是注册表里的安全 id ─────────────────────
|
|
2175
|
+
// 既保证 404 语义一致(tasks/status 对未知任务返回 404),也阻断把
|
|
2176
|
+
// `../` 之类的 taskId 带进 BranchStore.file() 的路径逃逸。
|
|
2177
|
+
const safeTaskId = (value) => /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(String(value ?? ''))
|
|
2178
|
+
const requireTask = (value) => {
|
|
2179
|
+
const taskId = String(value ?? '').trim()
|
|
2180
|
+
if (!taskId) return { ok: false, status: 400, error: 'taskId-required' }
|
|
2181
|
+
if (!safeTaskId(taskId) || !tasks.has(taskId)) return { ok: false, status: 404, error: 'unknown-task' }
|
|
2182
|
+
return { ok: true, taskId }
|
|
2183
|
+
}
|
|
2184
|
+
const branchErrorStatus = (code) => {
|
|
2185
|
+
switch (String(code ?? '')) {
|
|
2186
|
+
case 'invalid-branch-id':
|
|
2187
|
+
case 'invalid-status':
|
|
2188
|
+
case 'invalid-task-id':
|
|
2189
|
+
return 400
|
|
2190
|
+
case 'branch-missing':
|
|
2191
|
+
case 'parent-missing':
|
|
2192
|
+
return 404
|
|
2193
|
+
case 'branch-exists':
|
|
2194
|
+
case 'branch-not-active':
|
|
2195
|
+
case 'cannot-seal-active':
|
|
2196
|
+
return 409
|
|
2197
|
+
default:
|
|
2198
|
+
return 500
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
|
|
1387
2202
|
// 浏览器面板 bootstrap:同源读取 token(Host/Origin 已校验;不跨站)
|
|
1388
2203
|
route('GET', `${prefix}/api/auth-token`, (req, res) => json(res, 200, {
|
|
1389
2204
|
ok: true, token: authToken,
|
|
1390
2205
|
}), { public: true })
|
|
1391
2206
|
|
|
2207
|
+
// 母体不可删除:即使有人直接打接口也返回 403,而不是“没有这个路由”。
|
|
2208
|
+
// 仅 POST(allow-list 只允许 GET/POST;DELETE 语义由该 403 表达)。
|
|
2209
|
+
route('POST', `${prefix}/api/mother/delete`, (req, res) => json(res, 403, { ok: false, error: 'mother-immutable' }))
|
|
2210
|
+
|
|
2211
|
+
// 完整连接地址(带进程 token):Web 端「连接信息」用它,不再依赖桌面壳。
|
|
2212
|
+
// 桌面壳缺失时也能给出可复制的真实登录地址;拿不到 token 时如实标 tokenized:false。
|
|
2213
|
+
route('GET', `${prefix}/api/connection`, (req, res) => {
|
|
2214
|
+
const advertised = (() => { try { return String(webAppService?.getAdvertisedUrl?.() ?? '') } catch { return '' } })()
|
|
2215
|
+
const origin = (() => { try { return String(webServer.getOrigin?.() ?? '') } catch { return '' } })()
|
|
2216
|
+
const base = advertised || origin
|
|
2217
|
+
let url = base
|
|
2218
|
+
let tokenized = false
|
|
2219
|
+
try {
|
|
2220
|
+
if (base && typeof connectionService?.authenticatedUrl === 'function') {
|
|
2221
|
+
const next = connectionService.authenticatedUrl(base)
|
|
2222
|
+
if (next) { url = String(next); tokenized = url !== base }
|
|
2223
|
+
}
|
|
2224
|
+
} catch { /* 无 connection 服务时退回裸地址,不假装成功 */ }
|
|
2225
|
+
return json(res, 200, {
|
|
2226
|
+
ok: true, url, origin, advertisedUrl: advertised, tokenized, available: Boolean(url),
|
|
2227
|
+
})
|
|
2228
|
+
})
|
|
2229
|
+
|
|
1392
2230
|
route('GET', `${prefix}/api/status`, (req, res) => json(res, 200, service.status()))
|
|
1393
2231
|
route('GET', `${prefix}/api/upgrade/status`, (req, res) => {
|
|
1394
2232
|
let mirror = null
|
|
1395
2233
|
let essences = []
|
|
1396
|
-
|
|
1397
|
-
try {
|
|
1398
|
-
|
|
2234
|
+
let compat = null
|
|
2235
|
+
try { mirror = mirrorService.status() } catch { /* empty */ }
|
|
2236
|
+
try { essences = mirrorService.listEssences()?.essences ?? [] } catch { /* empty */ }
|
|
2237
|
+
try { compat = readCompatStatus(layout.dataDir) } catch { /* empty */ }
|
|
2238
|
+
let failedTasks = 0
|
|
2239
|
+
try { failedTasks = [...tasks.values()].filter(task => task.status === TASK_STATUS.FAILED).length } catch { /* empty */ }
|
|
2240
|
+
return json(res, 200, buildUpgradeStatus({ version: FANG_VERSION, mirror, essences, compat, tasks: { failed: failedTasks } }))
|
|
1399
2241
|
})
|
|
1400
2242
|
route('GET', `${prefix}/api/tasks`, (req, res) => json(res, 200, { ok: true, tasks: service.listTasks() }))
|
|
1401
2243
|
route('POST', `${prefix}/api/tasks/create`, async (req, res) => {
|
|
1402
2244
|
const body = await readBody(req)
|
|
1403
2245
|
try {
|
|
1404
|
-
const out = await service.createTask({ title: body?.title, template: body?.template, collaborators: body?.collaborators })
|
|
2246
|
+
const out = await service.createTask({ title: body?.title, template: body?.template, collaborators: body?.collaborators, essenceId: body?.essenceId })
|
|
1405
2247
|
return json(res, out.ok ? 200 : 409, out)
|
|
1406
2248
|
} catch (error) {
|
|
1407
2249
|
return json(res, 500, { ok: false, error: String(error?.message ?? error) })
|
|
@@ -1430,6 +2272,21 @@ export function apply(ctx, config) {
|
|
|
1430
2272
|
const out = await service.restoreTask(String(body?.taskId ?? ''))
|
|
1431
2273
|
return json(res, out.ok ? 200 : 409, out)
|
|
1432
2274
|
})
|
|
2275
|
+
// v3.0.9:强制单会话(运行中拒绝;停止/归档态把多余会话隔离到 quarantine-sessions/)
|
|
2276
|
+
route('POST', `${prefix}/api/tasks/sessions/enforce`, async (req, res) => {
|
|
2277
|
+
const body = await readBody(req)
|
|
2278
|
+
const out = service.enforceSingleSession(String(body?.taskId ?? ''))
|
|
2279
|
+
return json(res, out.ok ? 200 : 409, out)
|
|
2280
|
+
})
|
|
2281
|
+
route('POST', `${prefix}/api/tasks/reset`, async (req, res) => {
|
|
2282
|
+
const body = await readBody(req)
|
|
2283
|
+
try {
|
|
2284
|
+
const out = await service.resetForkConfig(String(body?.taskId ?? ''))
|
|
2285
|
+
return json(res, out.ok ? 200 : 409, out)
|
|
2286
|
+
} catch (error) {
|
|
2287
|
+
return json(res, 500, { ok: false, error: 'reset-failed', detail: String(error?.message ?? error) })
|
|
2288
|
+
}
|
|
2289
|
+
})
|
|
1433
2290
|
route('POST', `${prefix}/api/tasks/archive/delete`, async (req, res) => {
|
|
1434
2291
|
const body = await readBody(req)
|
|
1435
2292
|
const out = await service.deleteArchivedTask(String(body?.taskId ?? ''))
|
|
@@ -1521,12 +2378,29 @@ export function apply(ctx, config) {
|
|
|
1521
2378
|
const out = mirrorService.setBackupInterval(body?.hours)
|
|
1522
2379
|
return json(res, out.ok ? 200 : 400, out)
|
|
1523
2380
|
})
|
|
2381
|
+
// v3.0.9 升级链路 2.1:从本机母体 profile 克隆镜像基础层(先自动备份)。
|
|
2382
|
+
route('POST', `${prefix}/api/mirror/clone-profile`, async (req, res) => {
|
|
2383
|
+
const body = await readBody(req)
|
|
2384
|
+
try { return json(res, 200, { ok: true, ...mirrorService.cloneMotherProfile(body) }) } catch (error) {
|
|
2385
|
+
return json(res, 400, { ok: false, error: 'clone-failed', detail: String(error?.message ?? error) })
|
|
2386
|
+
}
|
|
2387
|
+
})
|
|
2388
|
+
// 空白母体(初始盘):备份当前 → active/profile 清空 → 版本 blank
|
|
2389
|
+
route('POST', `${prefix}/api/mirror/blank`, async (req, res) => {
|
|
2390
|
+
const body = await readBody(req)
|
|
2391
|
+
try { return json(res, 200, { ok: true, ...mirrorService.blankMother(body) }) } catch (error) {
|
|
2392
|
+
return json(res, 400, { ok: false, error: 'blank-failed', detail: String(error?.message ?? error) })
|
|
2393
|
+
}
|
|
2394
|
+
})
|
|
1524
2395
|
// v3.0.8 镜像偏好:对话框交互超时 15/30/60s(宿主侧持久化)
|
|
1525
2396
|
route('GET', `${prefix}/api/mirror/preferences`, (req, res) => json(res, 200, mirrorService.getPreferences()))
|
|
1526
2397
|
route('POST', `${prefix}/api/mirror/preferences/set`, async (req, res) => {
|
|
1527
2398
|
const body = await readBody(req)
|
|
1528
2399
|
try {
|
|
1529
|
-
const
|
|
2400
|
+
const patch = {}
|
|
2401
|
+
if (body?.activeIdleTimeoutMs !== undefined) patch.activeIdleTimeoutMs = body.activeIdleTimeoutMs
|
|
2402
|
+
if (body?.syncIntervalHours !== undefined) patch.syncIntervalHours = body.syncIntervalHours
|
|
2403
|
+
const preferences = mirrorService.setPreferences(patch)
|
|
1530
2404
|
return json(res, 200, preferences)
|
|
1531
2405
|
} catch (error) {
|
|
1532
2406
|
return json(res, 400, { ok: false, error: String(error?.message ?? error) })
|
|
@@ -1542,6 +2416,68 @@ export function apply(ctx, config) {
|
|
|
1542
2416
|
return json(res, 400, { ok: false, error: String(error?.message ?? error) })
|
|
1543
2417
|
}
|
|
1544
2418
|
})
|
|
2419
|
+
// v3.0.9 母体 → 元主:从当前母体 profile 的可写层生成一个可配置元主。
|
|
2420
|
+
route('POST', `${prefix}/api/essence/capture`, async (req, res) => {
|
|
2421
|
+
const body = await readBody(req)
|
|
2422
|
+
try { return json(res, 200, { ok: true, ...mirrorService.captureEssence(body) }) } catch (error) {
|
|
2423
|
+
return json(res, 400, { ok: false, error: 'capture-failed', detail: String(error?.message ?? error) })
|
|
2424
|
+
}
|
|
2425
|
+
})
|
|
2426
|
+
// v3.0.9 升级链路 3:把元主 overlay 重放到当前镜像(单个或全部)。
|
|
2427
|
+
route('POST', `${prefix}/api/essence/sync`, async (req, res) => {
|
|
2428
|
+
const body = await readBody(req)
|
|
2429
|
+
try { return json(res, 200, { ok: true, ...(await mirrorService.syncEssences(body)) }) } catch (error) {
|
|
2430
|
+
return json(res, 400, { ok: false, error: 'sync-failed', detail: String(error?.message ?? error) })
|
|
2431
|
+
}
|
|
2432
|
+
})
|
|
2433
|
+
// v3.0.9 原身运行态:start / stop(隔离 home 的配置态实例)
|
|
2434
|
+
// 注意:DSH webServer 按 path 键路由,GET+POST 必须走 routeMethods 一次注册,
|
|
2435
|
+
// 否则第二次 register 抛出,后面的路由会静默丢失(实测踩过)。
|
|
2436
|
+
routeMethods(`${prefix}/api/essence/runtime`, {
|
|
2437
|
+
GET: (req, res) => {
|
|
2438
|
+
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
2439
|
+
return json(res, 200, mirrorService.essenceRuntimeStatus(query.get('essenceId')))
|
|
2440
|
+
},
|
|
2441
|
+
POST: async (req, res) => {
|
|
2442
|
+
const body = await readBody(req)
|
|
2443
|
+
const action = String(body?.action ?? 'start')
|
|
2444
|
+
try {
|
|
2445
|
+
if (action === 'stop') return json(res, 200, mirrorService.stopEssenceRuntime(body?.essenceId))
|
|
2446
|
+
return json(res, 200, await mirrorService.startEssenceRuntime(body?.essenceId, body))
|
|
2447
|
+
} catch (error) {
|
|
2448
|
+
return json(res, 400, { ok: false, error: 'runtime-failed', detail: String(error?.message ?? error) })
|
|
2449
|
+
}
|
|
2450
|
+
},
|
|
2451
|
+
})
|
|
2452
|
+
route('GET', `${prefix}/api/essence/detail`, (req, res) => {
|
|
2453
|
+
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
2454
|
+
try { return json(res, 200, mirrorService.essenceDetail(query.get('essenceId'))) } catch (error) {
|
|
2455
|
+
return json(res, 400, { ok: false, error: 'detail-failed', detail: String(error?.message ?? error) })
|
|
2456
|
+
}
|
|
2457
|
+
})
|
|
2458
|
+
route('GET', `${prefix}/api/essence/open/candidates`, (req, res) => json(res, 200, mirrorService.essenceOpenCandidates()))
|
|
2459
|
+
route('GET', `${prefix}/api/essence/runtime/open`, (req, res) => {
|
|
2460
|
+
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
2461
|
+
return json(res, 200, mirrorService.openEssenceRuntime(query.get('essenceId')))
|
|
2462
|
+
})
|
|
2463
|
+
route('POST', `${prefix}/api/essence/backup`, async (req, res) => {
|
|
2464
|
+
const body = await readBody(req)
|
|
2465
|
+
try { return json(res, 200, { ok: true, ...mirrorService.backupEssence(String(body?.essenceId ?? '')) }) } catch (error) {
|
|
2466
|
+
return json(res, 400, { ok: false, error: 'backup-failed', detail: String(error?.message ?? error) })
|
|
2467
|
+
}
|
|
2468
|
+
})
|
|
2469
|
+
route('POST', `${prefix}/api/essence/restore`, async (req, res) => {
|
|
2470
|
+
const body = await readBody(req)
|
|
2471
|
+
try { return json(res, 200, { ok: true, ...mirrorService.restoreEssence(String(body?.essenceId ?? '')) }) } catch (error) {
|
|
2472
|
+
return json(res, 400, { ok: false, error: 'restore-failed', detail: String(error?.message ?? error) })
|
|
2473
|
+
}
|
|
2474
|
+
})
|
|
2475
|
+
route('POST', `${prefix}/api/essence/import`, async (req, res) => {
|
|
2476
|
+
const body = await readBody(req)
|
|
2477
|
+
try { return json(res, 200, { ok: true, ...mirrorService.importEssence(body) }) } catch (error) {
|
|
2478
|
+
return json(res, 400, { ok: false, error: 'import-failed', detail: String(error?.message ?? error) })
|
|
2479
|
+
}
|
|
2480
|
+
})
|
|
1545
2481
|
route('POST', `${prefix}/api/essence/rename`, async (req, res) => {
|
|
1546
2482
|
const body = await readBody(req)
|
|
1547
2483
|
try { return json(res, 200, { ok: true, essence: mirrorService.renameEssence(String(body?.essenceId ?? ''), body?.name) }) } catch (error) {
|
|
@@ -1575,7 +2511,8 @@ export function apply(ctx, config) {
|
|
|
1575
2511
|
route('GET', `${prefix}/api/essence/download`, (req, res) => {
|
|
1576
2512
|
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
1577
2513
|
try {
|
|
1578
|
-
const
|
|
2514
|
+
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
2515
|
+
const bundle = mirrorService.downloadEssence(String(query.get('essenceId') ?? ''), { full: query.get('full') === '1' })
|
|
1579
2516
|
res.writeHead(200, {
|
|
1580
2517
|
'content-type': 'application/json; charset=utf-8',
|
|
1581
2518
|
'content-disposition': `attachment; filename="essence-${bundle.essenceId}.json"`,
|
|
@@ -1616,40 +2553,88 @@ export function apply(ctx, config) {
|
|
|
1616
2553
|
return json(res, out.ok ? 200 : 409, out)
|
|
1617
2554
|
})
|
|
1618
2555
|
// v3.0.8 分支 HTTP 面(注册在末尾,避免影响既有路由初始化顺序)
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
2556
|
+
routeMethods(`${prefix}/api/tasks/branches`, {
|
|
2557
|
+
GET: (req, res) => {
|
|
2558
|
+
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
2559
|
+
const checked = requireTask(query.get('taskId'))
|
|
2560
|
+
if (!checked.ok) return json(res, checked.status, { ok: false, error: checked.error, code: checked.error })
|
|
2561
|
+
return json(res, 200, branchStore.list(checked.taskId))
|
|
2562
|
+
},
|
|
2563
|
+
POST: async (req, res) => {
|
|
2564
|
+
const body = await readBody(req)
|
|
2565
|
+
const checked = requireTask(body?.taskId)
|
|
2566
|
+
if (!checked.ok) return json(res, checked.status, { ok: false, error: checked.error, code: checked.error })
|
|
2567
|
+
try {
|
|
2568
|
+
return json(res, 200, branchStore.create(checked.taskId, {
|
|
2569
|
+
branchId: String(body?.branchId ?? ''),
|
|
2570
|
+
parentBranchId: body?.parentBranchId ? String(body.parentBranchId) : undefined,
|
|
2571
|
+
baseTurn: Number(body?.baseTurn) || 0,
|
|
2572
|
+
}))
|
|
2573
|
+
} catch (error) {
|
|
2574
|
+
const code = String(error?.message ?? error)
|
|
2575
|
+
return json(res, branchErrorStatus(code), { ok: false, error: code, code })
|
|
2576
|
+
}
|
|
2577
|
+
},
|
|
1624
2578
|
})
|
|
1625
|
-
route('POST', `${prefix}/api/tasks/branches`, async (req, res) => {
|
|
2579
|
+
route('POST', `${prefix}/api/tasks/branches/activate`, async (req, res) => {
|
|
1626
2580
|
const body = await readBody(req)
|
|
1627
|
-
const
|
|
1628
|
-
if (!
|
|
2581
|
+
const checked = requireTask(body?.taskId)
|
|
2582
|
+
if (!checked.ok) return json(res, checked.status, { ok: false, error: checked.error, code: checked.error })
|
|
1629
2583
|
try {
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
2584
|
+
const out = branchStore.activate(checked.taskId, String(body?.branchId ?? ''))
|
|
2585
|
+
// 方案 B:激活即切换 active 分支会话(同一分身可有多个分支会话,但同时只有 1 个 active)。
|
|
2586
|
+
const task = tasks.get(checked.taskId)
|
|
2587
|
+
if (task) {
|
|
2588
|
+
task.activeBranchId = out.activeBranchId
|
|
2589
|
+
persist()
|
|
2590
|
+
}
|
|
2591
|
+
audit('fork-branch-activated', { taskId: checked.taskId, branchId: out.activeBranchId, childSessionId: out.branch?.sessionId ?? null })
|
|
2592
|
+
return json(res, 200, out)
|
|
1635
2593
|
} catch (error) {
|
|
1636
|
-
|
|
2594
|
+
const code = String(error?.message ?? error)
|
|
2595
|
+
return json(res, branchErrorStatus(code), { ok: false, error: code, code })
|
|
1637
2596
|
}
|
|
1638
2597
|
})
|
|
1639
|
-
route('POST', `${prefix}/api/tasks/branches/
|
|
2598
|
+
route('POST', `${prefix}/api/tasks/branches/status`, async (req, res) => {
|
|
1640
2599
|
const body = await readBody(req)
|
|
2600
|
+
const checked = requireTask(body?.taskId)
|
|
2601
|
+
if (!checked.ok) return json(res, checked.status, { ok: false, error: checked.error, code: checked.error })
|
|
1641
2602
|
try {
|
|
1642
|
-
return json(res, 200, branchStore.
|
|
2603
|
+
return json(res, 200, branchStore.setStatus(checked.taskId, String(body?.branchId ?? ''), String(body?.status ?? '')))
|
|
1643
2604
|
} catch (error) {
|
|
1644
|
-
|
|
2605
|
+
const code = String(error?.message ?? error)
|
|
2606
|
+
return json(res, branchErrorStatus(code), { ok: false, error: code, code })
|
|
1645
2607
|
}
|
|
1646
2608
|
})
|
|
1647
|
-
|
|
2609
|
+
// 方案 A:物理分支——在分身自己的宿主里 sessions.fork,子会话挂回同一分身。
|
|
2610
|
+
route('POST', `${prefix}/api/tasks/branches/fork`, async (req, res) => {
|
|
1648
2611
|
const body = await readBody(req)
|
|
2612
|
+
const checked = requireTask(body?.taskId)
|
|
2613
|
+
if (!checked.ok) return json(res, checked.status, { ok: false, error: checked.error, code: checked.error })
|
|
2614
|
+
const task = tasks.get(checked.taskId)
|
|
2615
|
+
if (!task) return json(res, 404, { ok: false, error: 'unknown-task' })
|
|
2616
|
+
if (task.status === TASK_STATUS.ARCHIVED) return json(res, 409, { ok: false, error: 'task-archived' })
|
|
2617
|
+
const client = await remoteFor(task)
|
|
2618
|
+
if (!client || typeof client.command !== 'function') return json(res, 502, { ok: false, error: 'adapter-unavailable' })
|
|
2619
|
+
const current = branchStore.list(checked.taskId)
|
|
2620
|
+
const sourceSessionId = String(body?.sessionId ?? current.sessionId ?? '').trim()
|
|
2621
|
+
if (!sourceSessionId) return json(res, 409, { ok: false, error: 'no-session' })
|
|
2622
|
+
const branchId = String(body?.branchId ?? '').trim() || `b${Date.now().toString(36)}`
|
|
2623
|
+
const baseTurn = Number.isFinite(Number(body?.baseTurn)) ? Number(body.baseTurn) : 0
|
|
1649
2624
|
try {
|
|
1650
|
-
|
|
2625
|
+
const out = await client.command('fork-session', { sessionId: sourceSessionId, boundary: baseTurn || undefined })
|
|
2626
|
+
const result = out?.data?.result ?? out?.data ?? null
|
|
2627
|
+
if (!out?.ok || result?.ok === false) {
|
|
2628
|
+
const code = String(result?.code ?? result?.error ?? out?.error ?? 'fork-failed')
|
|
2629
|
+
return json(res, 502, { ok: false, error: code, detail: result })
|
|
2630
|
+
}
|
|
2631
|
+
const childSessionId = result?.childSessionId ?? result?.id ?? null
|
|
2632
|
+
const branch = branchStore.create(checked.taskId, { branchId, baseTurn, sessionId: childSessionId })
|
|
2633
|
+
audit('fork-branch-created', { taskId: checked.taskId, branchId, childSessionId })
|
|
2634
|
+
return json(res, 200, { ok: true, branch: branch.branch, childSessionId, sourceSessionId })
|
|
1651
2635
|
} catch (error) {
|
|
1652
|
-
|
|
2636
|
+
const code = String(error?.message ?? error)
|
|
2637
|
+
return json(res, branchErrorStatus(code), { ok: false, error: code, code })
|
|
1653
2638
|
}
|
|
1654
2639
|
})
|
|
1655
2640
|
route('GET', `${prefix}/api/reflow/policy`, (req, res) => json(res, 200, {
|
|
@@ -1664,6 +2649,62 @@ export function apply(ctx, config) {
|
|
|
1664
2649
|
forbiddenFields: ['token', 'password', 'secret', 'credential', 'auth', 'cookie', 'sessionkey', 'apikey'],
|
|
1665
2650
|
merge: false,
|
|
1666
2651
|
}))
|
|
2652
|
+
|
|
2653
|
+
// v3.0.9 composer journal: persist unsent drafts and a read-only queue mirror
|
|
2654
|
+
// so a restart/crash can offer recovery. Nothing is auto-sent.
|
|
2655
|
+
routeMethods(`${prefix}/api/composer/journal`, {
|
|
2656
|
+
GET: (req, res) => {
|
|
2657
|
+
const key = new URL(String(req.url ?? '/'), 'http://x').searchParams.get('key') || ''
|
|
2658
|
+
if (!key) return json(res, 400, { ok: false, error: 'journal-key-required' })
|
|
2659
|
+
return json(res, 200, { ok: true, entry: composerJournal.get(key) })
|
|
2660
|
+
},
|
|
2661
|
+
POST: async (req, res) => {
|
|
2662
|
+
const body = await readBody(req)
|
|
2663
|
+
const key = String(body?.key ?? '')
|
|
2664
|
+
if (!key) return json(res, 400, { ok: false, error: 'journal-key-required' })
|
|
2665
|
+
try {
|
|
2666
|
+
return json(res, 200, { ok: true, entry: composerJournal.save(key, body) })
|
|
2667
|
+
} catch (error) {
|
|
2668
|
+
return json(res, 400, { ok: false, error: String(error?.message ?? error) })
|
|
2669
|
+
}
|
|
2670
|
+
},
|
|
2671
|
+
})
|
|
2672
|
+
|
|
2673
|
+
// v3.0.8 contract: an unknown /fang/api/* path must be a JSON 404 under the
|
|
2674
|
+
// same Host/Origin/token gate — not an unauthenticated empty 404 from the host.
|
|
2675
|
+
// Exact routes above win because the webServer matches exact before prefix.
|
|
2676
|
+
// 默认元宝(新用户免创建):dry-run 计划 + 应用。
|
|
2677
|
+
route('GET', `${prefix}/api/essence/default-preset`, async (req, res) => {
|
|
2678
|
+
try { return json(res, 200, await mirrorService.defaultPreset()) } catch (error) {
|
|
2679
|
+
return json(res, 500, { ok: false, error: String(error?.message ?? error) })
|
|
2680
|
+
}
|
|
2681
|
+
})
|
|
2682
|
+
route('POST', `${prefix}/api/essence/default`, async (req, res) => {
|
|
2683
|
+
const body = await readBody(req)
|
|
2684
|
+
try {
|
|
2685
|
+
const out = await mirrorService.ensureDefaultEssence({ apply: body?.apply === true, force: body?.force === true, mode: body?.mode === 'preset' ? 'preset' : 'copy-local' })
|
|
2686
|
+
return json(res, out.ok === false ? 409 : 200, out)
|
|
2687
|
+
} catch (error) {
|
|
2688
|
+
return json(res, 500, { ok: false, error: String(error?.message ?? error) })
|
|
2689
|
+
}
|
|
2690
|
+
})
|
|
2691
|
+
// 新用户延迟自动创建(不阻塞启动;无已装默认插件时不创建)。
|
|
2692
|
+
if (cfg.defaultEssenceAuto !== false) {
|
|
2693
|
+
const timer = setTimeout(() => { mirrorService.ensureDefaultEssence({ apply: true, mode: 'copy-local' }).catch(() => {}) }, 8000)
|
|
2694
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
2695
|
+
}
|
|
2696
|
+
|
|
2697
|
+
webServer.register({
|
|
2698
|
+
kind: 'prefix',
|
|
2699
|
+
path: `${prefix}/api`, handler: async (req, res) => {
|
|
2700
|
+
const decision = checkRequestAuth(req, {
|
|
2701
|
+
token: authToken,
|
|
2702
|
+
publicRoute: authToken.length === 0,
|
|
2703
|
+
})
|
|
2704
|
+
if (!decision.ok) return json(res, decision.status, authErrorBody(decision))
|
|
2705
|
+
return json(res, 404, { ok: false, error: 'not-found', code: 'not-found' })
|
|
2706
|
+
},
|
|
2707
|
+
})
|
|
1667
2708
|
})
|
|
1668
2709
|
}
|
|
1669
2710
|
}
|