dsh-xlock 0.0.0-stage → 0.2.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 +125 -3
- package/cli/xlock.mjs +359 -0
- package/client.js +307 -0
- package/config.json +10 -0
- package/cordis.patch.yml +10 -0
- package/core/archive.mjs +195 -0
- package/core/archivesync.mjs +170 -0
- package/core/audit.mjs +226 -0
- package/core/classify.mjs +123 -0
- package/core/config.mjs +139 -0
- package/core/frames.mjs +216 -0
- package/core/identity.mjs +44 -0
- package/core/intercept.mjs +364 -0
- package/core/live.mjs +173 -0
- package/core/marker.mjs +234 -0
- package/core/origin.mjs +267 -0
- package/core/quarantine.mjs +240 -0
- package/core/repair.mjs +105 -0
- package/core/sessionfs.mjs +128 -0
- package/core/uistate.mjs +141 -0
- package/core/util.mjs +168 -0
- package/core/xlocktool.mjs +112 -0
- package/dsh-xlock.ps1 +50 -0
- package/index.js +255 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +48 -3
package/core/util.mjs
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-xlock — 基础工具:原子写、fsync、UTC 时间戳、JSON 读写。
|
|
3
|
+
*
|
|
4
|
+
* 零依赖(node: 内置 only)。所有落盘操作都假设同目录同卷:
|
|
5
|
+
* 标记文件在会话目录内(temp+rename 原子),隔离区在 %LOCALAPPDATA%
|
|
6
|
+
* (跨卷移动走 copy+unlink 兜底)。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
appendFileSync,
|
|
11
|
+
closeSync,
|
|
12
|
+
copyFileSync,
|
|
13
|
+
existsSync,
|
|
14
|
+
fsyncSync,
|
|
15
|
+
mkdirSync,
|
|
16
|
+
openSync,
|
|
17
|
+
readFileSync,
|
|
18
|
+
renameSync,
|
|
19
|
+
statSync,
|
|
20
|
+
unlinkSync,
|
|
21
|
+
writeFileSync,
|
|
22
|
+
writeSync,
|
|
23
|
+
} from 'node:fs'
|
|
24
|
+
import { dirname, join } from 'node:path'
|
|
25
|
+
import { fileURLToPath } from 'node:url'
|
|
26
|
+
import { randomBytes } from 'node:crypto'
|
|
27
|
+
|
|
28
|
+
/** 包根目录(core/ 的上一级)。CLI 与宿主半共用同一份 config.json / machines.json。 */
|
|
29
|
+
export const PKG_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 原子写一个 UTF-8 文件:同目录 temp + rename。
|
|
33
|
+
* @param {string} path 目标路径
|
|
34
|
+
* @param {string} text 内容
|
|
35
|
+
* @returns {void}
|
|
36
|
+
*/
|
|
37
|
+
export function atomicWriteText(path, text) {
|
|
38
|
+
const tmp = `${path}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`
|
|
39
|
+
const fd = openSync(tmp, 'w')
|
|
40
|
+
try {
|
|
41
|
+
writeSync(fd, text, 0, 'utf8')
|
|
42
|
+
fsyncSync(fd)
|
|
43
|
+
} finally {
|
|
44
|
+
closeSync(fd)
|
|
45
|
+
}
|
|
46
|
+
renameSync(tmp, path)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 读取 JSON 文件;不存在或解析失败返回 fallback。
|
|
51
|
+
* @param {string} path 文件路径
|
|
52
|
+
* @param {any} fallback 解析失败时的兜底值
|
|
53
|
+
* @returns {any}
|
|
54
|
+
*/
|
|
55
|
+
export function readJsonSafe(path, fallback) {
|
|
56
|
+
try {
|
|
57
|
+
return JSON.parse(readFileSync(path, 'utf8'))
|
|
58
|
+
} catch {
|
|
59
|
+
return fallback
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** fsync 一个已写完的文件(按路径打开-同步-关闭)。 */
|
|
64
|
+
export function fsyncFile(path) {
|
|
65
|
+
const fd = openSync(path, 'r+')
|
|
66
|
+
try {
|
|
67
|
+
fsyncSync(fd)
|
|
68
|
+
} finally {
|
|
69
|
+
closeSync(fd)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 跨卷安全移动:先 rename,失败(EXDEV/EPERM)退 copy+unlink。
|
|
75
|
+
* @param {string} src 源文件
|
|
76
|
+
* @param {string} dst 目标文件
|
|
77
|
+
*/
|
|
78
|
+
export function moveFile(src, dst) {
|
|
79
|
+
try {
|
|
80
|
+
renameSync(src, dst)
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (error?.code !== 'EXDEV') throw error
|
|
83
|
+
copyFileSync(src, dst)
|
|
84
|
+
unlinkSync(src)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* UTC 时间戳,用于隔离区目录名:yyyyMMdd-HHmmss。
|
|
90
|
+
* @param {Date} [date]
|
|
91
|
+
* @returns {string}
|
|
92
|
+
*/
|
|
93
|
+
export function utcStamp(date = new Date()) {
|
|
94
|
+
const p = (n, w = 2) => String(n).padStart(w, '0')
|
|
95
|
+
return (
|
|
96
|
+
`${date.getUTCFullYear()}${p(date.getUTCMonth() + 1)}${p(date.getUTCDate())}` +
|
|
97
|
+
`-${p(date.getUTCHours())}${p(date.getUTCMinutes())}${p(date.getUTCSeconds())}`
|
|
98
|
+
)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** ISO UTC 时间(meta/ledger 用)。 */
|
|
102
|
+
export function isoUtc(date = new Date()) {
|
|
103
|
+
return date.toISOString()
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 从文件名提取 Syncthing 冲突副本信息。
|
|
108
|
+
* 命名规律:`<base>.sync-conflict-<yyyyMMdd>-<HHmmss>-<设备短ID>.<ext>`
|
|
109
|
+
* (Syncthing 在最后一个点前插入冲突标记)。
|
|
110
|
+
* @param {string} name 文件名
|
|
111
|
+
* @returns {{date:string,time:string,shortId:string}|undefined}
|
|
112
|
+
*/
|
|
113
|
+
export function parseSyncConflictName(name) {
|
|
114
|
+
const match = /\.sync-conflict-(\d{8})-(\d{6})-([A-Za-z0-9]+)\./.exec(name)
|
|
115
|
+
if (!match) return undefined
|
|
116
|
+
return { date: match[1], time: match[2], shortId: match[3] }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 确保目录存在(recursive)。 */
|
|
120
|
+
export function ensureDir(path) {
|
|
121
|
+
if (!existsSync(path)) mkdirSync(path, { recursive: true })
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* 会话短名(报告显示用):session-55d2ae62-… → 55d2ae62。
|
|
126
|
+
* @param {string} sessionId
|
|
127
|
+
* @returns {string}
|
|
128
|
+
*/
|
|
129
|
+
export function shortSessionId(sessionId) {
|
|
130
|
+
return String(sessionId).replace(/^session-/, '').slice(0, 8)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* 把任意文本压成单行摘要(报告里嵌 JSON 用)。
|
|
135
|
+
* @param {string} text
|
|
136
|
+
* @param {number} [max]
|
|
137
|
+
*/
|
|
138
|
+
export function oneLine(text, max = 160) {
|
|
139
|
+
const flat = String(text).replace(/[\r\n]+/g, ' ⏎ ')
|
|
140
|
+
return flat.length > max ? `${flat.slice(0, max)}…` : flat
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export { writeFileSync, readFileSync, existsSync, join }
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 宿主半文件日志:%LOCALAPPDATA%\dsh-xlock\host.log。
|
|
147
|
+
* cordis logger 在桌面端不可见(stdout 吞掉),文件日志是激活/门禁排障的
|
|
148
|
+
* 唯一可靠观测面。>2MB 时轮转为 host.log.1。任何失败都静默(日志不许弄崩宿主)。
|
|
149
|
+
* @param {string} line 单行内容
|
|
150
|
+
*/
|
|
151
|
+
export function fileLog(line) {
|
|
152
|
+
try {
|
|
153
|
+
const localApp = process.env.LOCALAPPDATA
|
|
154
|
+
|| (process.env.USERPROFILE ? join(process.env.USERPROFILE, 'AppData', 'Local') : undefined)
|
|
155
|
+
if (!localApp) return
|
|
156
|
+
const root = join(localApp, 'dsh-xlock')
|
|
157
|
+
ensureDir(root)
|
|
158
|
+
const path = join(root, 'host.log')
|
|
159
|
+
try {
|
|
160
|
+
if (statSync(path).size > 2 * 1024 * 1024) renameSync(path, `${path}.1`)
|
|
161
|
+
} catch {
|
|
162
|
+
/* 不存在则不轮转 */
|
|
163
|
+
}
|
|
164
|
+
appendFileSync(path, `${new Date().toISOString()} ${line}\n`, 'utf8')
|
|
165
|
+
} catch {
|
|
166
|
+
/* 日志失败永不外溢 */
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-xlock — DSH 原生工具注册(工程化:模型只做触发与参数搬运,全部判定走 core/*)。
|
|
3
|
+
*
|
|
4
|
+
* 动机(用户要求 m01580):跨机接管逃生门 reset 不能依赖 dsh-xlock.ps1 ——
|
|
5
|
+
* mobile / 无 shell 环境下用户只能与助手对话。注册为 DSH 原生工具后,
|
|
6
|
+
* 任何会话里一句话即可触发;错误消息里的指引同步指向本工具。
|
|
7
|
+
*
|
|
8
|
+
* 注册形态对齐 dsh-plugin-market/src/tools.ts:66-71(普通 bundle 直接注册):
|
|
9
|
+
* ctx.inject(['tools'], (toolCtx) => { toolCtx.tools.register(definition) })
|
|
10
|
+
* 校验规则见 dsh-tools/src/index.ts:128(output.schema/render、timeoutMs、
|
|
11
|
+
* name!==保留名 'run_code')。
|
|
12
|
+
*/
|
|
13
|
+
import { cmdAudit, cmdResolve, cmdReset, cmdStatus, cmdGc } from '../cli/xlock.mjs'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* cmd* 函数全部同步并向 process.stdout 写结果;宿主进程(GUI 子系统)stdout
|
|
17
|
+
* 不可见,工具需把结果作为字符串返回 → 临时接管 stdout.write 捕获输出。
|
|
18
|
+
* 同步代码单线程执行,finally 保证恢复;异常向调用方(execute)传播。
|
|
19
|
+
*/
|
|
20
|
+
function captureStdout(fn) {
|
|
21
|
+
const chunks = []
|
|
22
|
+
if (!process.stdout || typeof process.stdout.write !== 'function') {
|
|
23
|
+
fn()
|
|
24
|
+
return '(output not capturable: no stdout)'
|
|
25
|
+
}
|
|
26
|
+
const orig = process.stdout.write
|
|
27
|
+
process.stdout.write = function (chunk) {
|
|
28
|
+
chunks.push(typeof chunk === 'string' ? chunk : String(chunk))
|
|
29
|
+
return true
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
fn()
|
|
33
|
+
} finally {
|
|
34
|
+
process.stdout.write = orig
|
|
35
|
+
}
|
|
36
|
+
return chunks.join('')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function defineXlockTool() {
|
|
40
|
+
return {
|
|
41
|
+
name: 'xlock',
|
|
42
|
+
description: [
|
|
43
|
+
'dsh-xlock 跨机会话粘锁与同步冲突副本管理(纯工程工具,不含智能判断)。',
|
|
44
|
+
'status=全部会话的锁标记/冲突副本概览+隔离区统计;',
|
|
45
|
+
'audit=会话目录双边画像走查报告(只读不改文件);',
|
|
46
|
+
'reset=删除会话粘锁标记(跨机接管唯一逃生门)——仅当确认持有方机器已停写(已崩溃或放弃该会话)时使用;',
|
|
47
|
+
'resolve=裁决同步冲突副本(keep=primary 以主文件为准 / copy 以副本换正,换正前自动修复 torn 末行);',
|
|
48
|
+
'gc=清理过期/超限隔离区(ledger 留痕)。',
|
|
49
|
+
'session 参数支持 session id 片段模糊匹配(必须唯一命中)。',
|
|
50
|
+
].join(''),
|
|
51
|
+
parameters: {
|
|
52
|
+
action: {
|
|
53
|
+
type: 'string',
|
|
54
|
+
required: true,
|
|
55
|
+
enum: ['status', 'audit', 'reset', 'resolve', 'gc'],
|
|
56
|
+
description: '子命令',
|
|
57
|
+
},
|
|
58
|
+
session: {
|
|
59
|
+
type: 'string',
|
|
60
|
+
description: 'session id 或唯一前缀(audit/reset/resolve 必填)',
|
|
61
|
+
},
|
|
62
|
+
keep: {
|
|
63
|
+
type: 'string',
|
|
64
|
+
enum: ['primary', 'copy'],
|
|
65
|
+
description: 'resolve 裁决方向(resolve 必填):primary=以主文件为准,copy=以副本换正',
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
output: {
|
|
69
|
+
schema: { type: 'string' },
|
|
70
|
+
render: (_args, value) => [{ type: 'text', text: value }],
|
|
71
|
+
},
|
|
72
|
+
async execute(args, exec) {
|
|
73
|
+
if (exec?.signal?.throwIfAborted) exec.signal.throwIfAborted()
|
|
74
|
+
const action = args?.action
|
|
75
|
+
const session = args?.session
|
|
76
|
+
try {
|
|
77
|
+
switch (action) {
|
|
78
|
+
case 'status':
|
|
79
|
+
return captureStdout(() => cmdStatus()) || '(no output)'
|
|
80
|
+
case 'audit': {
|
|
81
|
+
if (!session) return 'ERROR: audit 需要 session 参数(全量概览请用 action=status)'
|
|
82
|
+
return captureStdout(() => cmdAudit([session])) || '(no output)'
|
|
83
|
+
}
|
|
84
|
+
case 'reset': {
|
|
85
|
+
if (!session) return 'ERROR: reset 需要 session 参数'
|
|
86
|
+
return captureStdout(() => cmdReset([session])) || '(no output)'
|
|
87
|
+
}
|
|
88
|
+
case 'resolve': {
|
|
89
|
+
if (!session) return 'ERROR: resolve 需要 session 参数'
|
|
90
|
+
if (args.keep !== 'primary' && args.keep !== 'copy') return 'ERROR: resolve 需要 keep=primary|copy'
|
|
91
|
+
return captureStdout(() => cmdResolve([session, '--keep', args.keep])) || '(no output)'
|
|
92
|
+
}
|
|
93
|
+
case 'gc':
|
|
94
|
+
return captureStdout(() => cmdGc()) || '(no output)'
|
|
95
|
+
default:
|
|
96
|
+
return `ERROR: unknown action "${action}"(status|audit|reset|resolve|gc)`
|
|
97
|
+
}
|
|
98
|
+
} catch (error) {
|
|
99
|
+
return `ERROR: ${error?.message || String(error)}`
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 注册工具。tools = tools 服务实例(toolCtx.tools)。
|
|
107
|
+
* @returns 注册 disposer(失败/无服务返回 undefined,绝不抛——插件 bug 不得弄哑会话)。
|
|
108
|
+
*/
|
|
109
|
+
export function registerXlockTool(tools) {
|
|
110
|
+
if (!tools || typeof tools.register !== 'function') return undefined
|
|
111
|
+
return tools.register(defineXlockTool())
|
|
112
|
+
}
|
package/dsh-xlock.ps1
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
***REMOVED*** dsh-xlock.ps1 — 跨机会话粘锁插件 CLI 包装
|
|
2
|
+
***REMOVED***
|
|
3
|
+
***REMOVED*** 用法(PowerShell 7+):
|
|
4
|
+
***REMOVED*** dsh-xlock.ps1 audit <session|all>
|
|
5
|
+
***REMOVED*** dsh-xlock.ps1 resolve <session> --keep primary|copy
|
|
6
|
+
***REMOVED*** dsh-xlock.ps1 reset <session>
|
|
7
|
+
***REMOVED*** dsh-xlock.ps1 status
|
|
8
|
+
***REMOVED*** dsh-xlock.ps1 gc
|
|
9
|
+
***REMOVED***
|
|
10
|
+
***REMOVED*** 前置:DSH 已安装(或手动指定 $env:DSH_NODE_EXECUTABLE);
|
|
11
|
+
***REMOVED*** 本脚本用 DSH 自带 Node(ELECTRON_RUN_AS_NODE=1)跑插件 CLI,零额外依赖。
|
|
12
|
+
***REMOVED*** 规则:本文件 UTF-8 BOM + CRLF;不要用会改行尾的编辑器保存。
|
|
13
|
+
|
|
14
|
+
[CmdletBinding()]
|
|
15
|
+
param(
|
|
16
|
+
[Parameter(Position = 0, ValueFromRemainingArguments = $true)]
|
|
17
|
+
[string[]]$Rest
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
$ErrorActionPreference = 'Stop'
|
|
21
|
+
|
|
22
|
+
***REMOVED*** ── 定位 DSH Node ────────────────────────────────────────────────────────
|
|
23
|
+
$node = $env:DSH_NODE_EXECUTABLE
|
|
24
|
+
if (-not $node -or -not (Test-Path -LiteralPath $node)) {
|
|
25
|
+
$node = $null
|
|
26
|
+
$candidates = @(
|
|
27
|
+
(Join-Path $env:ProgramFiles 'DeepSeek Harness\DeepSeek Harness.exe'),
|
|
28
|
+
(Join-Path ${env:ProgramFiles(x86)} 'DeepSeek Harness\DeepSeek Harness.exe'),
|
|
29
|
+
(Join-Path $env:LOCALAPPDATA 'Programs\DeepSeek Harness\DeepSeek Harness.exe')
|
|
30
|
+
)
|
|
31
|
+
foreach ($c in $candidates) {
|
|
32
|
+
if ($c -and (Test-Path -LiteralPath $c)) { $node = $c; break }
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (-not $node -or -not (Test-Path -LiteralPath $node)) {
|
|
36
|
+
Write-Error 'DSH_NODE_EXECUTABLE 未设置且找不到 DeepSeek Harness.exe;请先启动 DSH 或手动指定环境变量'
|
|
37
|
+
exit 2
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
***REMOVED*** ── 定位插件 CLI ────────────────────────────────────────────────────────
|
|
41
|
+
$cli = Join-Path $PSScriptRoot 'cli\xlock.mjs'
|
|
42
|
+
if (-not (Test-Path -LiteralPath $cli)) {
|
|
43
|
+
***REMOVED*** 本脚本与 cli/ 同目录(源码态 dsh-plugins/dsh-xlock、安装态 node_modules/dsh-xlock 均成立)
|
|
44
|
+
Write-Error "找不到 CLI:$cli"
|
|
45
|
+
exit 2
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
$env:ELECTRON_RUN_AS_NODE = '1'
|
|
49
|
+
& $node $cli @Rest
|
|
50
|
+
exit $LASTEXITCODE
|
package/index.js
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-xlock — 宿主半入口。
|
|
3
|
+
*
|
|
4
|
+
* apply(ctx, config):
|
|
5
|
+
* 1) loadIdentity() → 本机指纹(%LOCALAPPDATA%\dsh-xlock\machineId.json)
|
|
6
|
+
* 2) loadConfig(config) → 包内 config.json ← 注入配置(cordis.patch.yml)
|
|
7
|
+
* 3) startupGc → 隔离区按保留期/限额清理(不改任何会话文件)
|
|
8
|
+
* 4) ctx.inject(['sessionPersistence'], sp =>
|
|
9
|
+
* ctx.effect(wrapPersistence(sp, identity, cfg, log)))
|
|
10
|
+
*
|
|
11
|
+
* 拦截点唯一可行形态:实例级方法赋值(inst.open/inst.create)。
|
|
12
|
+
* 原因:cordis ctx.provide 禁止重提供既有服务;Service 实例经 createTraceable
|
|
13
|
+
* 代理,set 陷阱把赋值透传到原始实例、get 自有属性优先——对所有读者生效。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import z from '@deepseek-ai/schemastery'
|
|
17
|
+
import { loadIdentity } from './core/identity.mjs'
|
|
18
|
+
import { loadConfig, loadMachines, learnRegistry } from './core/config.mjs'
|
|
19
|
+
import { wrapPersistence } from './core/intercept.mjs'
|
|
20
|
+
import { gcQuarantine } from './core/quarantine.mjs'
|
|
21
|
+
import { registerXlockTool } from './core/xlocktool.mjs'
|
|
22
|
+
import { createArchiveSync } from './core/archivesync.mjs'
|
|
23
|
+
import { getSessionLockState, listSessionLockStates, listSessionIds, resetSessionLock } from './core/uistate.mjs'
|
|
24
|
+
import { fileLog } from './core/util.mjs'
|
|
25
|
+
|
|
26
|
+
export const name = 'dsh-xlock'
|
|
27
|
+
|
|
28
|
+
// 说明(UI 不展示 description 就看这里):
|
|
29
|
+
// divergentGate 分叉副本写打开时 'block'(默认,拦截) | 'warn'(放行+日志)
|
|
30
|
+
// acquireQuiesceMs 取得标记后的静默复检毫秒数(0=关,默认)
|
|
31
|
+
// startupGc 启动顺带清理过期隔离区(默认 true)
|
|
32
|
+
// archiveSyncRoute 归档状态跨机同步:写侧落标记 + 读侧收敛归档集(默认 true)
|
|
33
|
+
// sessionActiveMs 判定「对端真在写」的日志活跃窗口(毫秒,默认 180000)
|
|
34
|
+
// retentionDays / exportRetentionDays / maxQuarantineBytes 隔离区保留策略
|
|
35
|
+
export const Config = z.object({
|
|
36
|
+
divergentGate: z.union([z.const('block'), z.const('warn')]).default('block'),
|
|
37
|
+
acquireQuiesceMs: z.number().default(0),
|
|
38
|
+
startupGc: z.boolean().default(true),
|
|
39
|
+
archiveSyncRoute: z.boolean().default(true),
|
|
40
|
+
sessionActiveMs: z.number().default(180000),
|
|
41
|
+
retentionDays: z.number().default(30),
|
|
42
|
+
exportRetentionDays: z.number().default(180),
|
|
43
|
+
maxQuarantineBytes: z.number().default(536870912),
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
export function apply(ctx, config) {
|
|
47
|
+
const cfg = loadConfig(config)
|
|
48
|
+
const identity = loadIdentity()
|
|
49
|
+
// 双通道日志:cordis logger(桌面端吞 stdout,聊胜于无)+ 文件
|
|
50
|
+
// (%LOCALAPPDATA%\dsh-xlock\host.log,排障真凭据)。
|
|
51
|
+
const log = (line, extra) => {
|
|
52
|
+
const text = extra === undefined ? line : `${line} ${JSON.stringify(extra)}`
|
|
53
|
+
fileLog(text)
|
|
54
|
+
if (ctx.logger && typeof ctx.logger.info === 'function') ctx.logger.info(`[dsh-xlock] ${text}`)
|
|
55
|
+
else console.error(`[dsh-xlock] ${text}`)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
fileLog(`apply entered: pid=${process.pid} host=${identity.host} gate=${cfg.divergentGate} quiesce=${cfg.acquireQuiesceMs}ms`)
|
|
59
|
+
log(`active: host=${identity.host} machineId=${identity.uuid.slice(0, 8)}… gate=${cfg.divergentGate} quiesce=${cfg.acquireQuiesceMs}ms`)
|
|
60
|
+
|
|
61
|
+
if (cfg.startupGc) {
|
|
62
|
+
try {
|
|
63
|
+
const gc = gcQuarantine(cfg)
|
|
64
|
+
if (gc.deleted > 0) {
|
|
65
|
+
log(`startup gc: deleted=${gc.deleted} bytesFreed=${gc.freedBytes} entries=${gc.entries}`)
|
|
66
|
+
}
|
|
67
|
+
} catch (error) {
|
|
68
|
+
log(`startup gc failed (ignored): ${error?.message || error}`)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// registry 自动学习:把本机 host 与本地工作区路径登记进 machines.json,
|
|
73
|
+
// 让「桶名 → 机器」的历史归属推断在别的机器上也成立。
|
|
74
|
+
// 只增不改、内容不变则不写盘(免得每次启动都触发一次跨机同步)。
|
|
75
|
+
// 一次性副作用,无需 effect 清理。
|
|
76
|
+
ctx.inject(['workspaceRegistry'], (wsCtx) => {
|
|
77
|
+
try {
|
|
78
|
+
const registry = wsCtx?.workspaceRegistry
|
|
79
|
+
if (!registry || typeof registry.list !== 'function') {
|
|
80
|
+
fileLog('registry learn: workspaceRegistry unavailable — skipped')
|
|
81
|
+
return
|
|
82
|
+
}
|
|
83
|
+
const cwds = []
|
|
84
|
+
for (const ws of registry.list()) {
|
|
85
|
+
if (ws && typeof ws.path === 'string' && ws.path !== '') cwds.push(ws.path)
|
|
86
|
+
}
|
|
87
|
+
learnRegistry(identity, cwds, log)
|
|
88
|
+
} catch (error) {
|
|
89
|
+
log(`registry learn skipped (ignored): ${error?.message || error}`)
|
|
90
|
+
}
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
// 归档状态跨机同步(从 dsh-tweaks 迁入):本机归档集变化 → 落标记随会话目录
|
|
94
|
+
// 同步给对端;对端标记 → 收敛到本机归档集。archiveCtx 就是 childCtx,
|
|
95
|
+
// workspaceRegistry 从其属性取(同 registry learn 的注入形态)。
|
|
96
|
+
if (cfg.archiveSyncRoute) {
|
|
97
|
+
try {
|
|
98
|
+
ctx.inject(['sessionPersistence', 'workspaceRegistry'], (archiveCtx) => {
|
|
99
|
+
const wsCtx = archiveCtx?.workspaceRegistry
|
|
100
|
+
if (!wsCtx || typeof wsCtx.archiveSession !== 'function') {
|
|
101
|
+
fileLog('archive sync: workspaceRegistry unavailable — skipped')
|
|
102
|
+
return
|
|
103
|
+
}
|
|
104
|
+
archiveCtx.effect(() => {
|
|
105
|
+
log('archive sync: starting (write markers + read converge)')
|
|
106
|
+
const dispose = createArchiveSync(archiveCtx)
|
|
107
|
+
return () => {
|
|
108
|
+
try { dispose() } catch { /* 服务已卸载 */ }
|
|
109
|
+
}
|
|
110
|
+
}, 'dsh-xlock:archive-sync')
|
|
111
|
+
})
|
|
112
|
+
} catch (error) {
|
|
113
|
+
try { ctx.logger?.warn?.(`dsh-xlock archive sync could not start: ${String(error?.message ?? error)}`) } catch {}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// cordis inject 语义(dsh-agent-loop/src/index.ts:358 同款实证):回调参数是
|
|
118
|
+
// **Context(childCtx)**,服务要 childCtx.sessionPersistence 属性取——不是
|
|
119
|
+
// 直接把回调参数当服务。effect 也挂在 childCtx 上(dsh-tweaks 同款),
|
|
120
|
+
// 插件卸载时随该 fiber 一起清理。
|
|
121
|
+
ctx.inject(['sessionPersistence'], (childCtx) => {
|
|
122
|
+
const sp = childCtx?.sessionPersistence
|
|
123
|
+
fileLog(`inject fired: childCtx=${typeof childCtx} sp=${typeof sp} open=${typeof sp?.open} create=${typeof sp?.create}`)
|
|
124
|
+
if (!sp || typeof sp.open !== 'function' || typeof sp.create !== 'function') {
|
|
125
|
+
log(`ERROR: inject delivered ${typeof childCtx} without usable sessionPersistence — NOT wrapping (sessions unprotected)`)
|
|
126
|
+
return
|
|
127
|
+
}
|
|
128
|
+
childCtx.effect(() => {
|
|
129
|
+
log('wrapping sessionPersistence (sticky cross-machine lock + repair gates)')
|
|
130
|
+
const restore = wrapPersistence(sp, identity, cfg, log)
|
|
131
|
+
// 诊断+双保险:ctx.get 直读路径(agent-loop createStoredSession 走的就是
|
|
132
|
+
// runtime.ctx.get,不是 inject)若解析到另一实例(服务替换/多 provide),
|
|
133
|
+
// 一并包装;wrapPersistence 幂等守卫(WRAP_TAG+函数名)保证同实例不重入。
|
|
134
|
+
try {
|
|
135
|
+
const got = ctx.get?.('sessionPersistence')
|
|
136
|
+
if (got && typeof got.open === 'function' && typeof got.create === 'function' && got !== sp) {
|
|
137
|
+
const before = got.create?.name
|
|
138
|
+
wrapPersistence(got, identity, cfg, log)
|
|
139
|
+
log(`post-wrap probe: ctx.get resolved a different object (create was ${before}) — wrapped it too`)
|
|
140
|
+
} else {
|
|
141
|
+
log(`post-wrap probe: ctx.get same=${got === sp} type=${typeof got} create=${typeof got?.create}`)
|
|
142
|
+
}
|
|
143
|
+
} catch (error) {
|
|
144
|
+
log(`post-wrap probe failed (ignored): ${error?.message || error}`)
|
|
145
|
+
}
|
|
146
|
+
// cordis effect 回调返回裸函数 = 卸载/禁用时的清理回调(dsh-tweaks 同款)。
|
|
147
|
+
return () => {
|
|
148
|
+
try {
|
|
149
|
+
restore()
|
|
150
|
+
} catch {
|
|
151
|
+
/* 实例已被替换 */
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}, 'dsh-xlock:wrap')
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
// 会话锁/归档状态查询 + 显式解锁:给 client 半的徽标/解锁按钮用(PLAN 步骤5)。
|
|
158
|
+
// 纯读本机磁盘标记 + 显式删锁标记,与 xlock 工具的 reset 同语义;归档标记一概不碰。
|
|
159
|
+
ctx.inject(['webServer'], (wsCtx) => {
|
|
160
|
+
const web = wsCtx?.webServer
|
|
161
|
+
if (!web || typeof web.register !== 'function') {
|
|
162
|
+
fileLog('inject webServer: no usable webServer — session-state routes NOT registered')
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
const sendJson = (response, status, payload) => {
|
|
166
|
+
response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
167
|
+
response.end(JSON.stringify(payload))
|
|
168
|
+
}
|
|
169
|
+
const readBody = async (request) => {
|
|
170
|
+
const chunks = []
|
|
171
|
+
for await (const chunk of request) chunks.push(chunk)
|
|
172
|
+
const text = Buffer.concat(chunks).toString('utf8')
|
|
173
|
+
return text ? JSON.parse(text) : {}
|
|
174
|
+
}
|
|
175
|
+
wsCtx.effect(() => {
|
|
176
|
+
const offs = []
|
|
177
|
+
offs.push(web.register({
|
|
178
|
+
kind: 'exact',
|
|
179
|
+
path: '/dsh-xlock/session-state',
|
|
180
|
+
handler: async (_request, response) => {
|
|
181
|
+
try {
|
|
182
|
+
sendJson(response, 200, {
|
|
183
|
+
sessions: listSessionLockStates({
|
|
184
|
+
identity,
|
|
185
|
+
registry: loadMachines(),
|
|
186
|
+
activeMs: cfg.sessionActiveMs,
|
|
187
|
+
}),
|
|
188
|
+
refreshedAt: Date.now(),
|
|
189
|
+
})
|
|
190
|
+
} catch (error) {
|
|
191
|
+
log(`session-state route failed: ${error?.message || error}`)
|
|
192
|
+
sendJson(response, 500, { error: String(error?.message ?? error) })
|
|
193
|
+
}
|
|
194
|
+
},
|
|
195
|
+
}))
|
|
196
|
+
offs.push(web.register({
|
|
197
|
+
kind: 'exact',
|
|
198
|
+
path: '/dsh-xlock/session-state/reset',
|
|
199
|
+
handler: async (request, response) => {
|
|
200
|
+
let body = {}
|
|
201
|
+
try { body = await readBody(request) } catch { }
|
|
202
|
+
const result = resetSessionLock(body?.sessionId)
|
|
203
|
+
sendJson(response, result.ok ? 200 : 400, result)
|
|
204
|
+
if (result.ok) log(`session-state reset: ${result.sessionId} removed=${result.removed.join(',')}`)
|
|
205
|
+
},
|
|
206
|
+
}))
|
|
207
|
+
// 全量会话 id 集合:客户端比对集合变化 → 让平台重拉权威基线(异机删会话后
|
|
208
|
+
// 本机不会产生 session/disposed,列表不会自己变)。纯读取。
|
|
209
|
+
offs.push(web.register({
|
|
210
|
+
kind: 'exact',
|
|
211
|
+
path: '/dsh-xlock/session-ids',
|
|
212
|
+
handler: async (_request, response) => {
|
|
213
|
+
try {
|
|
214
|
+
sendJson(response, 200, { ids: listSessionIds(), refreshedAt: Date.now() })
|
|
215
|
+
} catch (error) {
|
|
216
|
+
log(`session-ids route failed: ${error?.message || error}`)
|
|
217
|
+
sendJson(response, 500, { error: String(error?.message ?? error) })
|
|
218
|
+
}
|
|
219
|
+
},
|
|
220
|
+
}))
|
|
221
|
+
log('session-state routes registered: /dsh-xlock/session-state[/reset] + /dsh-xlock/session-ids')
|
|
222
|
+
return () => { for (const off of offs) { try { off() } catch { /* 服务已卸载 */ } } }
|
|
223
|
+
}, 'dsh-xlock:session-state-routes')
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
// DSH 原生工具(用户要求 m01580:reset 逃生门必须 GUI/mobile 可达,不依赖 ps1)。
|
|
227
|
+
// 注册形态 = dsh-plugin-market/src/tools.ts:66-71 同款(普通 bundle 直接注册)。
|
|
228
|
+
ctx.inject(['tools'], (toolCtx) => {
|
|
229
|
+
const tools = toolCtx?.tools
|
|
230
|
+
if (!tools || typeof tools.register !== 'function') {
|
|
231
|
+
fileLog('inject tools: no usable tools service — xlock tool NOT registered')
|
|
232
|
+
return
|
|
233
|
+
}
|
|
234
|
+
toolCtx.effect(() => {
|
|
235
|
+
try {
|
|
236
|
+
const unregister = registerXlockTool(tools)
|
|
237
|
+
if (!unregister) {
|
|
238
|
+
fileLog('xlock tool register returned no disposer (tools service unavailable?)')
|
|
239
|
+
return undefined
|
|
240
|
+
}
|
|
241
|
+
log('xlock tool registered: status/audit/reset/resolve/gc')
|
|
242
|
+
return () => {
|
|
243
|
+
try {
|
|
244
|
+
unregister()
|
|
245
|
+
} catch {
|
|
246
|
+
/* 服务已卸载 */
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
} catch (error) {
|
|
250
|
+
log(`xlock tool register failed: ${error?.message || error}`)
|
|
251
|
+
return undefined
|
|
252
|
+
}
|
|
253
|
+
}, 'dsh-xlock:tool')
|
|
254
|
+
})
|
|
255
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Cross-machine Lock",
|
|
4
|
+
"description": "Sticky cross-machine session lock plus sync-conflict audit and repair for DSH sessions: a held marker stops another machine from writing a session that is in use, and the pre-write gate walks zstd frames, repairs a torn last line in place, and triages Syncthing conflict copies. Sessions also get a creation-origin record so you can tell which machine built them."
|
|
5
|
+
}
|
|
6
|
+
}
|
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-xlock",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.9",
|
|
4
|
+
"description": "Sticky cross-machine session lock, sync-conflict audit/repair, and session creation-origin records for DSH sessions",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/jalousiex/dsh-xlock.git"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public",
|
|
14
|
+
"registry": "https://registry.npmjs.org/"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"index.js",
|
|
18
|
+
"client.js",
|
|
19
|
+
"core",
|
|
20
|
+
"cli",
|
|
21
|
+
"locale",
|
|
22
|
+
"config.json",
|
|
23
|
+
"dsh-xlock.ps1",
|
|
24
|
+
"cordis.patch.yml",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=22"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"@deepseek-ai/schemastery": "^3.18.2"
|
|
32
|
+
},
|
|
33
|
+
"dsh": {
|
|
34
|
+
"bundle": {
|
|
35
|
+
"patch": "./cordis.patch.yml"
|
|
36
|
+
},
|
|
37
|
+
"client": {
|
|
38
|
+
"platform": "web",
|
|
39
|
+
"immediately": true,
|
|
40
|
+
"inject": [
|
|
41
|
+
"@deepseek-ai/dsh-client-ui-slots"
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"exports": {
|
|
46
|
+
".": "./index.js",
|
|
47
|
+
"./client": "./client.js",
|
|
48
|
+
"./locale/*.json": "./locale/*.json",
|
|
49
|
+
"./package.json": "./package.json"
|
|
50
|
+
}
|
|
6
51
|
}
|