@twinsearth/dsh-fang 3.1.21 → 3.1.23
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 +231 -3
- package/package.json +2 -2
- package/src/kernel/types.mjs +1 -1
- package/tools/recover-queue.mjs +133 -0
package/client.js
CHANGED
|
@@ -1756,6 +1756,15 @@ window.__ModuleLoader__.load({
|
|
|
1756
1756
|
}
|
|
1757
1757
|
|
|
1758
1758
|
async function deriveTask(payload) {
|
|
1759
|
+
// v3.1.23:元主派生必须绑定一个会话(不允许空白快速派生出来源不明的一次性分身)。
|
|
1760
|
+
if (!String(payload?.sessionId ?? '').trim()) {
|
|
1761
|
+
try {
|
|
1762
|
+
if ((await detectWebRole()) === 'essence') {
|
|
1763
|
+
setNotice({ tone: 'warn', title: '元主派生需要先选择一个会话', message: '请在左侧会话列表中选中一个进行中的会话,再点「从此会话派生」。' })
|
|
1764
|
+
return
|
|
1765
|
+
}
|
|
1766
|
+
} catch { /* 识别失败则按原行为 */ }
|
|
1767
|
+
}
|
|
1759
1768
|
if (deriveStore.inflight) return
|
|
1760
1769
|
deriveStore.lastGesture = Date.now()
|
|
1761
1770
|
S.notice = null
|
|
@@ -6411,6 +6420,211 @@ window.__ModuleLoader__.load({
|
|
|
6411
6420
|
*
|
|
6412
6421
|
* 只在 role === 'fork' 时生效;母体/元主不受影响。
|
|
6413
6422
|
*/
|
|
6423
|
+
|
|
6424
|
+
/**
|
|
6425
|
+
* v3.1.23:元主(essence)Web 的界面收敛。
|
|
6426
|
+
*
|
|
6427
|
+
* 用户要求:
|
|
6428
|
+
* 1) 元主端不允许执行会话 / 任务 / 指令(派生与调度由房主 Router 负责);
|
|
6429
|
+
* 2) 元主派生新分身必须选一个会话,分身内不允许新建会话(只能分叉会话);
|
|
6430
|
+
* 3) 元主 Web 隐藏「工作区」「新会话」,只保留 插件安装/设置 与 系统设置,
|
|
6431
|
+
* 默认进入即打开插件设置页。
|
|
6432
|
+
*
|
|
6433
|
+
* 实现方式:DOM 收敛 + 事件拦截 + 一次性落地页跳转;不依赖宿主内部 API。
|
|
6434
|
+
*/
|
|
6435
|
+
function mountEssenceUiLocks() {
|
|
6436
|
+
if (typeof document === 'undefined' || !document.body) return () => {}
|
|
6437
|
+
const doc = document
|
|
6438
|
+
let disposed = false
|
|
6439
|
+
let active = false
|
|
6440
|
+
let observer = null
|
|
6441
|
+
const NAV_HIDDEN = ['工作区', '新会话', '新建会话', 'Workspace', 'New session', 'New Session']
|
|
6442
|
+
const NOTICE_ID = 'fang-essence-notice'
|
|
6443
|
+
|
|
6444
|
+
const clean = (text) => String(text || '').replace(/[\u200b-\u200d\ufeff]/g, '').replace(/\s+/g, ' ').trim()
|
|
6445
|
+
const isPanelRow = (node) => {
|
|
6446
|
+
try {
|
|
6447
|
+
if (!node || node.tagName !== 'BUTTON') return false
|
|
6448
|
+
if (/panelRow/i.test(String(node.className || ''))) return true
|
|
6449
|
+
return Boolean(node.closest('nav, aside, [class*="sidebar"], [class*="sideBar"], [class*="sider"]'))
|
|
6450
|
+
} catch { return false }
|
|
6451
|
+
}
|
|
6452
|
+
const matchNav = (text) => {
|
|
6453
|
+
const value = clean(text)
|
|
6454
|
+
if (!value) return false
|
|
6455
|
+
// 实机发现:宿主会把快捷键拼在文案后面(「新会话Ctrl+Alt+N」),
|
|
6456
|
+
// 因此按「标签前缀」匹配,而不是要求空格分隔。
|
|
6457
|
+
return NAV_HIDDEN.some((label) => value === label || value.startsWith(label))
|
|
6458
|
+
}
|
|
6459
|
+
const isPluginNav = (text) => {
|
|
6460
|
+
const value = clean(text)
|
|
6461
|
+
return value === '插件' || value === 'Plugins' || /^插件(\s|$)/.test(value) || /^Plugins?(\s|$)/.test(value)
|
|
6462
|
+
}
|
|
6463
|
+
|
|
6464
|
+
const hideNavRows = () => {
|
|
6465
|
+
if (disposed || !active) return
|
|
6466
|
+
for (const node of doc.querySelectorAll('button')) {
|
|
6467
|
+
if (!isPanelRow(node)) continue
|
|
6468
|
+
const text = clean(node.textContent)
|
|
6469
|
+
if (!matchNav(text)) continue
|
|
6470
|
+
if (node.dataset.fangEssenceHidden === '1' && node.hidden) continue
|
|
6471
|
+
node.dataset.fangEssenceHidden = '1'
|
|
6472
|
+
node.hidden = true
|
|
6473
|
+
node.setAttribute('aria-hidden', 'true')
|
|
6474
|
+
node.style.setProperty('display', 'none', 'important')
|
|
6475
|
+
// 有些宿主用父级容器承载整行(工作区整块),一并收掉
|
|
6476
|
+
const row = node.closest('[class*="panelRow"],[class*="workspaceRow"],[data-workspace-row]')
|
|
6477
|
+
if (row && row !== node) {
|
|
6478
|
+
row.hidden = true
|
|
6479
|
+
row.dataset.fangEssenceHidden = '1'
|
|
6480
|
+
row.style.setProperty('display', 'none', 'important')
|
|
6481
|
+
}
|
|
6482
|
+
}
|
|
6483
|
+
}
|
|
6484
|
+
|
|
6485
|
+
/**
|
|
6486
|
+
* v3.1.23 实机补充:等工作区不是单个按钮,而是「工作区」分组标题 + 若干工作区行。
|
|
6487
|
+
* 元主只做插件控制台,因此整段收起:标题所在分组 + 所有工作区行。
|
|
6488
|
+
*/
|
|
6489
|
+
const hideWorkspaceBlock = () => {
|
|
6490
|
+
if (disposed || !active) return
|
|
6491
|
+
// ① 分组标题:文本恰好是「工作区」的任意元素(标题/按钮/标签)
|
|
6492
|
+
for (const node of doc.querySelectorAll('div,span,h2,h3,button,a')) {
|
|
6493
|
+
const text = clean(node.textContent)
|
|
6494
|
+
if (text !== '工作区' && text !== 'Workspace') continue
|
|
6495
|
+
const blockNode = node.closest('[class*="panelRow"],[class*="workspaceRow"],[class*="section"],[class*="group"]') || node.parentElement
|
|
6496
|
+
if (!blockNode || blockNode === doc.body) continue
|
|
6497
|
+
if (blockNode.dataset.fangEssenceHidden === '1') continue
|
|
6498
|
+
blockNode.dataset.fangEssenceHidden = '1'
|
|
6499
|
+
blockNode.hidden = true
|
|
6500
|
+
blockNode.setAttribute('aria-hidden', 'true')
|
|
6501
|
+
blockNode.style.setProperty('display', 'none', 'important')
|
|
6502
|
+
}
|
|
6503
|
+
// ② 工作区行(默认工作区 / 某个工作区名)
|
|
6504
|
+
for (const node of doc.querySelectorAll('button,div,li')) {
|
|
6505
|
+
if (!node || node.dataset.fangEssenceHidden === '1') continue
|
|
6506
|
+
const text = clean(node.textContent)
|
|
6507
|
+
if (!/^(默认工作区|工作区|Workspace)/.test(text)) continue
|
|
6508
|
+
if (!node.closest('[class*="sidebar"],[class*="sideBar"],[class*="sider"],nav,aside')) continue
|
|
6509
|
+
node.dataset.fangEssenceHidden = '1'
|
|
6510
|
+
node.hidden = true
|
|
6511
|
+
node.setAttribute('aria-hidden', 'true')
|
|
6512
|
+
node.style.setProperty('display', 'none', 'important')
|
|
6513
|
+
}
|
|
6514
|
+
}
|
|
6515
|
+
|
|
6516
|
+
/** 隐藏输入区:元主不执行会话/指令(避免误以为能在这里跑任务)。 */
|
|
6517
|
+
const hideComposer = () => {
|
|
6518
|
+
if (disposed || !active) return
|
|
6519
|
+
for (const textarea of doc.querySelectorAll('textarea')) {
|
|
6520
|
+
const box = textarea.closest('[class*="composer"],[class*="Composer"]') || textarea.parentElement?.parentElement
|
|
6521
|
+
if (!box) continue
|
|
6522
|
+
if (box.dataset.fangEssenceHidden === '1') continue
|
|
6523
|
+
box.dataset.fangEssenceHidden = '1'
|
|
6524
|
+
box.hidden = true
|
|
6525
|
+
box.setAttribute('aria-hidden', 'true')
|
|
6526
|
+
box.style.setProperty('display', 'none', 'important')
|
|
6527
|
+
}
|
|
6528
|
+
for (const node of doc.querySelectorAll('button')) {
|
|
6529
|
+
const label = clean(node.getAttribute?.('aria-label') || node.textContent)
|
|
6530
|
+
if (!/^(发送|Send|发送消息)$/.test(label)) continue
|
|
6531
|
+
if (node.dataset.fangEssenceHidden === '1') continue
|
|
6532
|
+
node.dataset.fangEssenceHidden = '1'
|
|
6533
|
+
node.hidden = true
|
|
6534
|
+
node.style.setProperty('display', 'none', 'important')
|
|
6535
|
+
}
|
|
6536
|
+
}
|
|
6537
|
+
|
|
6538
|
+
const insertNotice = () => {
|
|
6539
|
+
if (disposed || !active) return
|
|
6540
|
+
if (doc.getElementById(NOTICE_ID)) return
|
|
6541
|
+
const notice = doc.createElement('div')
|
|
6542
|
+
notice.id = NOTICE_ID
|
|
6543
|
+
notice.setAttribute('data-fang-essence-notice', '1')
|
|
6544
|
+
notice.setAttribute('role', 'status')
|
|
6545
|
+
notice.textContent = '元主 Web:仅插件安装/设置与系统设置可用;会话、任务与指令请在母体或分身中执行。'
|
|
6546
|
+
notice.style.cssText = 'position:fixed;left:16px;bottom:16px;z-index:2147483000;max-width:min(520px,60vw);' +
|
|
6547
|
+
'padding:8px 12px;border-radius:10px;border:1px solid rgba(10,107,224,.25);background:rgba(232,241,253,.96);' +
|
|
6548
|
+
'color:#0B3E8E;font:12px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;box-shadow:0 2px 8px rgba(16,17,20,.08)'
|
|
6549
|
+
doc.body.appendChild(notice)
|
|
6550
|
+
}
|
|
6551
|
+
|
|
6552
|
+
/** 默认落地页 = 插件设置页(点一次侧栏「插件」,只做一次)。 */
|
|
6553
|
+
let landed = false
|
|
6554
|
+
const landOnPlugins = () => {
|
|
6555
|
+
if (disposed || !active || landed) return
|
|
6556
|
+
const button = [...doc.querySelectorAll('button')].find((node) => isPanelRow(node) && isPluginNav(clean(node.textContent)))
|
|
6557
|
+
if (!button) return
|
|
6558
|
+
landed = true
|
|
6559
|
+
try { button.click() } catch { /* ignore */ }
|
|
6560
|
+
doc.documentElement?.setAttribute?.('data-fang-essence-landing', 'plugins')
|
|
6561
|
+
}
|
|
6562
|
+
|
|
6563
|
+
const onClickCapture = (event) => {
|
|
6564
|
+
if (!active || disposed) return
|
|
6565
|
+
const button = event.target && typeof event.target.closest === 'function' ? event.target.closest('button') : null
|
|
6566
|
+
if (!button) return
|
|
6567
|
+
const text = clean(button.textContent)
|
|
6568
|
+
if (isPanelRow(button) && matchNav(text)) {
|
|
6569
|
+
event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation(); return
|
|
6570
|
+
}
|
|
6571
|
+
const label = clean(button.getAttribute?.('aria-label') || '')
|
|
6572
|
+
if (/^(发送|Send)$/.test(label) || /^(发送|Send)$/.test(text)) {
|
|
6573
|
+
event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation()
|
|
6574
|
+
}
|
|
6575
|
+
}
|
|
6576
|
+
|
|
6577
|
+
const onKeyDown = (event) => {
|
|
6578
|
+
if (!active || disposed) return
|
|
6579
|
+
if (event.key !== 'Enter' || event.shiftKey) return
|
|
6580
|
+
const target = event.target
|
|
6581
|
+
const inComposer = Boolean(target && typeof target.closest === 'function' && target.closest('[class*="composer"],[class*="Composer"],textarea'))
|
|
6582
|
+
if (!inComposer) return
|
|
6583
|
+
event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation()
|
|
6584
|
+
}
|
|
6585
|
+
|
|
6586
|
+
const apply = () => {
|
|
6587
|
+
if (disposed) return
|
|
6588
|
+
hideNavRows()
|
|
6589
|
+
hideWorkspaceBlock()
|
|
6590
|
+
hideComposer()
|
|
6591
|
+
insertNotice()
|
|
6592
|
+
landOnPlugins()
|
|
6593
|
+
}
|
|
6594
|
+
const start = () => {
|
|
6595
|
+
if (disposed || active) return
|
|
6596
|
+
active = true
|
|
6597
|
+
apply()
|
|
6598
|
+
try {
|
|
6599
|
+
observer = new MutationObserver(() => apply())
|
|
6600
|
+
observer.observe(doc.body, { childList: true, subtree: true })
|
|
6601
|
+
} catch { /* ignore */ }
|
|
6602
|
+
doc.addEventListener('click', onClickCapture, true)
|
|
6603
|
+
doc.addEventListener('keydown', onKeyDown, true)
|
|
6604
|
+
// 宿主首屏渲染有先后:分几次重试落地页与隐藏
|
|
6605
|
+
for (const delay of [300, 800, 1500, 3000]) setTimeout(apply, delay)
|
|
6606
|
+
doc.documentElement?.setAttribute?.('data-fang-essence-locks', 'applied')
|
|
6607
|
+
}
|
|
6608
|
+
|
|
6609
|
+
void detectWebRole().then((role) => {
|
|
6610
|
+
if (disposed) return
|
|
6611
|
+
if (role === 'essence') start()
|
|
6612
|
+
}).catch(() => { /* 识别失败则不启用 */ })
|
|
6613
|
+
|
|
6614
|
+
return () => {
|
|
6615
|
+
disposed = true
|
|
6616
|
+
active = false
|
|
6617
|
+
try { observer?.disconnect() } catch { /* ignore */ }
|
|
6618
|
+
try { doc.removeEventListener('click', onClickCapture, true) } catch { /* ignore */ }
|
|
6619
|
+
try { doc.removeEventListener('keydown', onKeyDown, true) } catch { /* ignore */ }
|
|
6620
|
+
try { doc.getElementById(NOTICE_ID)?.remove() } catch { /* ignore */ }
|
|
6621
|
+
for (const node of doc.querySelectorAll('[data-fang-essence-hidden="1"]')) {
|
|
6622
|
+
try { node.hidden = false; node.style.removeProperty('display'); node.removeAttribute('aria-hidden'); delete node.dataset.fangEssenceHidden } catch { /* ignore */ }
|
|
6623
|
+
}
|
|
6624
|
+
doc.documentElement?.removeAttribute?.('data-fang-essence-locks')
|
|
6625
|
+
}
|
|
6626
|
+
}
|
|
6627
|
+
|
|
6414
6628
|
function mountForkUiLocks() {
|
|
6415
6629
|
if (typeof document === 'undefined' || !document.body) return () => {}
|
|
6416
6630
|
const doc = document
|
|
@@ -6418,7 +6632,7 @@ window.__ModuleLoader__.load({
|
|
|
6418
6632
|
let active = false
|
|
6419
6633
|
let timer = 0
|
|
6420
6634
|
let observer = null
|
|
6421
|
-
const NAV_TEXTS = ['插件']
|
|
6635
|
+
const NAV_TEXTS = ['插件', '新会话', '新建会话']
|
|
6422
6636
|
const ACTION_TEXTS = ['启动', '启动插件', '开始使用', '启用']
|
|
6423
6637
|
|
|
6424
6638
|
/** v3.1.20:宿主侧栏行类名会随版本变化,不再只认 panelRow。 */
|
|
@@ -6445,7 +6659,8 @@ window.__ModuleLoader__.load({
|
|
|
6445
6659
|
if (disposed || !active) return
|
|
6446
6660
|
for (const node of doc.querySelectorAll('button')) {
|
|
6447
6661
|
if (!isPanelRow(node)) continue
|
|
6448
|
-
|
|
6662
|
+
const navText = String(node.textContent || '').trim()
|
|
6663
|
+
if (!isPluginNavText(navText) && !/^新会话|^新建会话/.test(navText)) continue
|
|
6449
6664
|
if (node.dataset.fangForkHidden === '1' && node.hidden) continue
|
|
6450
6665
|
node.dataset.fangForkHidden = '1'
|
|
6451
6666
|
node.hidden = true
|
|
@@ -6585,9 +6800,20 @@ window.__ModuleLoader__.load({
|
|
|
6585
6800
|
}
|
|
6586
6801
|
|
|
6587
6802
|
// ── 插件入口 ──────────────────────────────────────────────────────────
|
|
6803
|
+
// v3.1.23:jsdom 回归用钩子桥(只在测试模式挂到 window,正常运行时不存在)
|
|
6804
|
+
if (typeof window !== 'undefined' && window.__FANG_TEST_HOOK__) {
|
|
6805
|
+
window.__fangTestHooks = window.__fangTestHooks || {}
|
|
6806
|
+
Object.assign(window.__fangTestHooks, {
|
|
6807
|
+
__mountEssenceUiLocks: mountEssenceUiLocks,
|
|
6808
|
+
__mountForkUiLocks: mountForkUiLocks,
|
|
6809
|
+
__mountCloseConfirm: mountCloseConfirm,
|
|
6810
|
+
__detectWebRole: detectWebRole,
|
|
6811
|
+
})
|
|
6812
|
+
}
|
|
6813
|
+
|
|
6588
6814
|
return {
|
|
6589
6815
|
mountPanel,
|
|
6590
|
-
...(typeof window !== 'undefined' && window.__FANG_TEST_HOOK__ ? { __renderDecisionMini: renderDecisionMini, __mountWebRoleBadge: mountWebRoleBadge, __detectWebRole: detectWebRole, __mountForkUiLocks: mountForkUiLocks, __mountCloseConfirm: mountCloseConfirm, __mountDecisionRelay: mountDecisionRelay } : {}),
|
|
6816
|
+
...(typeof window !== 'undefined' && window.__FANG_TEST_HOOK__ ? { __renderDecisionMini: renderDecisionMini, __mountWebRoleBadge: mountWebRoleBadge, __detectWebRole: detectWebRole, __mountForkUiLocks: mountForkUiLocks, __mountEssenceUiLocks: mountEssenceUiLocks, __mountCloseConfirm: mountCloseConfirm, __mountDecisionRelay: mountDecisionRelay } : {}),
|
|
6591
6817
|
inject: ['slots'],
|
|
6592
6818
|
apply(ctx) {
|
|
6593
6819
|
const disposers = []
|
|
@@ -6595,6 +6821,8 @@ window.__ModuleLoader__.load({
|
|
|
6595
6821
|
disposers.push(mountWebRoleBadge())
|
|
6596
6822
|
// v3.1.19:分身 Web 界面收敛(隐藏「插件」入口 + 「启动」无操作)。
|
|
6597
6823
|
disposers.push(mountForkUiLocks())
|
|
6824
|
+
// v3.1.23:元主 Web 界面收敛(隐藏工作区/新会话、只留插件与系统设置、默认落地插件页)。
|
|
6825
|
+
disposers.push(mountEssenceUiLocks())
|
|
6598
6826
|
// v3.1.19:元主 / 分身 Web 关闭前二次确认(防误触)。
|
|
6599
6827
|
disposers.push(mountCloseConfirm())
|
|
6600
6828
|
// 母体 Web = DSH 主会话视图;Web 端直接切回 conversation 面板。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@twinsearth/dsh-fang",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.23",
|
|
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.",
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"node": ">=22"
|
|
51
51
|
},
|
|
52
52
|
"optionalDependencies": {
|
|
53
|
-
"@twinsearth/dsh-fang-queue-journal": "^0.1.
|
|
53
|
+
"@twinsearth/dsh-fang-queue-journal": "^0.1.6",
|
|
54
54
|
"@twinsearth/dsh-fang-web-entry": "0.1.1"
|
|
55
55
|
},
|
|
56
56
|
"devDependencies": {
|
package/src/kernel/types.mjs
CHANGED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// tools/recover-queue.mjs — 从瓮城的 composer journal 里找回草稿与排队消息。
|
|
4
|
+
//
|
|
5
|
+
// 用法:
|
|
6
|
+
// node tools/recover-queue.mjs # 扫描默认目录,列出可恢复内容
|
|
7
|
+
// node tools/recover-queue.mjs --data-dir <dir> # 指定 fang dataDir(可多次)
|
|
8
|
+
// node tools/recover-queue.mjs --scan-all # 扫描 ~/.dsh/fang 下所有 dataDir
|
|
9
|
+
// node tools/recover-queue.mjs --json # 输出 JSON(便于脚本处理)
|
|
10
|
+
// node tools/recover-queue.mjs --restore <url> --token <token> --session <sessionId> --index <n>
|
|
11
|
+
// 把第 n 条快照(默认最新)的队列写回官方队列:POST <url>/fang/api/composer/queue
|
|
12
|
+
// --dry-run 与 --restore 搭配,只打印将要发送的内容
|
|
13
|
+
//
|
|
14
|
+
// 设计原则:只读扫描 + 显式恢复;默认不发送任何消息。
|
|
15
|
+
import fs from 'node:fs'
|
|
16
|
+
import os from 'node:os'
|
|
17
|
+
import path from 'node:path'
|
|
18
|
+
|
|
19
|
+
const args = process.argv.slice(2)
|
|
20
|
+
const readFlag = (name) => {
|
|
21
|
+
const index = args.indexOf(name)
|
|
22
|
+
return index >= 0 ? String(args[index + 1] ?? '') : ''
|
|
23
|
+
}
|
|
24
|
+
const has = (name) => args.includes(name)
|
|
25
|
+
|
|
26
|
+
const jsonOut = has('--json')
|
|
27
|
+
const scanAll = has('--scan-all')
|
|
28
|
+
const dryRun = has('--dry-run')
|
|
29
|
+
const dataDirs = []
|
|
30
|
+
for (let i = 0; i < args.length; i += 1) if (args[i] === '--data-dir' && args[i + 1]) dataDirs.push(args[i + 1])
|
|
31
|
+
if (scanAll || dataDirs.length === 0) {
|
|
32
|
+
const roots = [path.join(os.homedir(), '.dsh', 'fang')]
|
|
33
|
+
for (const root of roots) {
|
|
34
|
+
try {
|
|
35
|
+
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
|
36
|
+
if (!entry.isDirectory()) continue
|
|
37
|
+
const candidate = path.join(root, entry.name)
|
|
38
|
+
// fang dataDir 里应有 endpoint.json / audit.jsonl / composer-journal.json 之一
|
|
39
|
+
const markers = ['composer-journal.json', 'composer-journal-history.jsonl', 'audit.jsonl', 'endpoint.json']
|
|
40
|
+
if (markers.some((marker) => fs.existsSync(path.join(candidate, marker)))) dataDirs.push(candidate)
|
|
41
|
+
}
|
|
42
|
+
} catch { /* 没有 fang 目录 */ }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const readJson = (file) => {
|
|
47
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
|
|
48
|
+
}
|
|
49
|
+
const readLines = (file) => {
|
|
50
|
+
try {
|
|
51
|
+
return fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).map((line) => {
|
|
52
|
+
try { return JSON.parse(line) } catch { return null }
|
|
53
|
+
}).filter(Boolean)
|
|
54
|
+
} catch { return [] }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const report = []
|
|
58
|
+
for (const dir of dataDirs) {
|
|
59
|
+
const journalFile = path.join(dir, 'composer-journal.json')
|
|
60
|
+
const historyFile = path.join(dir, 'composer-journal-history.jsonl')
|
|
61
|
+
const journal = readJson(journalFile)
|
|
62
|
+
const entries = []
|
|
63
|
+
if (journal && typeof journal === 'object') {
|
|
64
|
+
for (const [key, entry] of Object.entries(journal)) {
|
|
65
|
+
const queue = Array.isArray(entry?.queue) ? entry.queue : []
|
|
66
|
+
if (!entry?.draft && queue.length === 0) continue
|
|
67
|
+
entries.push({ key, draft: String(entry?.draft || ''), queue, updatedAt: entry?.updatedAt || '', source: 'journal' })
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
for (const snapshot of readLines(historyFile)) {
|
|
71
|
+
const queue = Array.isArray(snapshot?.queue) ? snapshot.queue : []
|
|
72
|
+
if (queue.length === 0) continue
|
|
73
|
+
entries.push({
|
|
74
|
+
key: String(snapshot?.key || ''),
|
|
75
|
+
draft: String(snapshot?.draft || ''),
|
|
76
|
+
queue,
|
|
77
|
+
updatedAt: String(snapshot?.updatedAt || ''),
|
|
78
|
+
sessionKey: String(snapshot?.sessionKey || ''),
|
|
79
|
+
source: 'history',
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
entries.sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)))
|
|
83
|
+
report.push({ dataDir: dir, journalFile, historyFile, entries })
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const restoreUrl = readFlag('--restore').replace(/\/+$/, '')
|
|
87
|
+
const restoreToken = readFlag('--token') || String(process.env.FANG_TOKEN ?? '')
|
|
88
|
+
const restoreSession = readFlag('--session')
|
|
89
|
+
const indexFlag = Number(readFlag('--index') || 0)
|
|
90
|
+
|
|
91
|
+
if (!jsonOut) {
|
|
92
|
+
console.log(`扫描目录 ${dataDirs.length} 个`)
|
|
93
|
+
for (const item of report) {
|
|
94
|
+
console.log(`\n=== ${item.dataDir}`)
|
|
95
|
+
console.log(` journal: ${fs.existsSync(item.journalFile) ? item.journalFile : '(none)'}`)
|
|
96
|
+
console.log(` history: ${fs.existsSync(item.historyFile) ? item.historyFile : '(none)'}`)
|
|
97
|
+
if (item.entries.length === 0) { console.log(' 可恢复条目: 0'); continue }
|
|
98
|
+
item.entries.forEach((entry, index) => {
|
|
99
|
+
console.log(` [${index}] ${entry.source} · key=${JSON.stringify(entry.key)} · ${entry.updatedAt} · queue=${entry.queue.length}${entry.draft ? ' · draft=' + JSON.stringify(entry.draft.slice(0, 40)) : ''}`)
|
|
100
|
+
for (const queueItem of entry.queue.slice(0, 6)) {
|
|
101
|
+
const text = String(queueItem?.text ?? '')
|
|
102
|
+
const broken = /\?{3,}/.test(text)
|
|
103
|
+
console.log(` • ${JSON.stringify(text.slice(0, 120))}${broken ? ' ⚠ 疑似乱码(原文已丢失)' : ''}`)
|
|
104
|
+
}
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (jsonOut) {
|
|
110
|
+
console.log(JSON.stringify({ at: new Date().toISOString(), dataDirs, report }, null, 2))
|
|
111
|
+
if (!restoreUrl) process.exit(0)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (restoreUrl) {
|
|
115
|
+
const flattened = report.flatMap((item) => item.entries.map((entry) => ({ ...entry, dataDir: item.dataDir })))
|
|
116
|
+
const target = flattened[indexFlag]
|
|
117
|
+
if (!target) { console.error(`没有第 ${indexFlag} 条可恢复记录(共 ${flattened.length} 条)`); process.exit(1) }
|
|
118
|
+
if (!restoreSession) { console.error('恢复需要 --session <sessionId>(官方队列按会话恢复)'); process.exit(1) }
|
|
119
|
+
const items = target.queue.map((queueItem) => ({ text: String(queueItem?.text ?? '').slice(0, 4000) })).filter((item) => item.text.trim())
|
|
120
|
+
if (items.length === 0) { console.error('该快照没有可恢复的队列内容'); process.exit(1) }
|
|
121
|
+
const payload = { sessionId: restoreSession, items }
|
|
122
|
+
console.log(`\n准备恢复 ${items.length} 条 → ${restoreUrl}/fang/api/composer/queue(session=${restoreSession})`)
|
|
123
|
+
if (dryRun) { console.log('--dry-run:未发送'); process.exit(0) }
|
|
124
|
+
if (!restoreToken) { console.error('恢复需要 --token 或环境变量 FANG_TOKEN'); process.exit(1) }
|
|
125
|
+
const res = await fetch(`${restoreUrl}/fang/api/composer/queue`, {
|
|
126
|
+
method: 'POST',
|
|
127
|
+
headers: { 'content-type': 'application/json', 'x-fang-auth': restoreToken },
|
|
128
|
+
body: JSON.stringify(payload),
|
|
129
|
+
})
|
|
130
|
+
const text = await res.text()
|
|
131
|
+
console.log(`HTTP ${res.status} ${text.slice(0, 200)}`)
|
|
132
|
+
process.exit(res.ok ? 0 : 1)
|
|
133
|
+
}
|