sage-mem 3.0.0 → 3.1.0
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.en.md +15 -1
- package/README.md +15 -1
- package/lib/client.js +701 -0
- package/lib/index.js +95 -1
- package/lib/sync/devices.js +237 -0
- package/lib/sync/panel.js +143 -0
- package/lib/typert/schemas.js +69 -0
- package/lib/typert.host.js +31 -0
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -35,10 +35,12 @@ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
|
|
|
35
35
|
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
36
36
|
import { join } from 'node:path'
|
|
37
37
|
import { checkUpdate as checkUpdateImpl } from './update.js'
|
|
38
|
-
import { applySettingsPatch, MAX_RAW_BYTES, parseExperimentalPatch, parseUiPatch, pendingExperimental, pendingUi, rawName, readExternalSettings, readReservedFile, readSettingsFileDetailed, readSettingsSnapshot, RESERVED_FILE, SETTINGS_FILE } from './settings.js'
|
|
38
|
+
import { applySettingsPatch, MAX_RAW_BYTES, parseExperimentalPatch, parseUiPatch, pendingExperimental, pendingUi, rawName, readExternalSettings, readReservedFile, readSettingsFileDetailed, readSettingsSnapshot, readSyncSettings, RESERVED_FILE, SETTINGS_FILE } from './settings.js'
|
|
39
39
|
import { createRecallInjector, createSessionInjectState, readRecallDebug } from './recall/index.js'
|
|
40
40
|
import { mountAutodream, mountMemoryTools, mountMirror, mountObserve, mountPreCompact, mountWriteGate } from './assembly/index.js'
|
|
41
41
|
import { ensureLocalInstance } from './sync/instance.js'
|
|
42
|
+
import { listDevices } from './sync/devices.js'
|
|
43
|
+
import { runSyncAction } from './sync/panel.js'
|
|
42
44
|
// 3.0.0:跨设备冲突的裁决实现(`conflict/applyResolution` 背后的那一步)。
|
|
43
45
|
import { resolveSyncConflict } from './sync/resolve.js'
|
|
44
46
|
|
|
@@ -52,6 +54,14 @@ import { resolveSyncConflict } from './sync/resolve.js'
|
|
|
52
54
|
function readReject(code, message) {
|
|
53
55
|
return Object.assign(new Error(message), { code })
|
|
54
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* 非空字符串才认(`code` / `error` 这类「有才带」的字段用它)。
|
|
59
|
+
* 单独起名字的另一个理由见 SyncGateway.run:直接写 `typeof x.code === 'string'`
|
|
60
|
+
* 会被错误码登记守卫当成「用了 `string` 这个业务码」。
|
|
61
|
+
*/
|
|
62
|
+
function textOf(value) {
|
|
63
|
+
return typeof value === 'string' && value !== '' ? value : ''
|
|
64
|
+
}
|
|
55
65
|
/**
|
|
56
66
|
* 手动 @Remote marker 注册(Node 24 不解析装饰器语法,手写 decorator context)。
|
|
57
67
|
*/
|
|
@@ -83,6 +93,10 @@ export class MemoryGateway extends TypertRemoteService {
|
|
|
83
93
|
// 也不许在 lib/sync/ 里另写一份带 `expectedRevision` 的写盘:一条记忆的落盘口径只该有一处。
|
|
84
94
|
new ConflictGateway(ctx, (name, content, opts) => this.writeFile(name, content, opts))
|
|
85
95
|
|
|
96
|
+
// 3.1.0:跨设备同步的面板入口(设备候选 + 一次动作)—— `sync.*` 服务。
|
|
97
|
+
// 与 conflict 分开成独立 namespace:那边裁的是「本机两条记忆谁算数」,这边动的是网线与远端库。
|
|
98
|
+
new SyncGateway(ctx)
|
|
99
|
+
|
|
86
100
|
// 四块挂载(1.2.0 从构造函数里搬出的四段)。顺序保持原样:
|
|
87
101
|
// autodream → 检索工具 → 观测 → 写入门。
|
|
88
102
|
mountAutodream(ctx, {
|
|
@@ -840,6 +854,86 @@ markRemote(ConflictGateway, 'applyResolution', 'applyResolution')
|
|
|
840
854
|
// 两次并发点击若各自读到 open,就会各写一次正文(远端那一条甚至会被推两次)。
|
|
841
855
|
serializeByKey(ConflictGateway, ['invalidate', 'dismiss', 'undo', 'removeRecord', 'applyResolution'])
|
|
842
856
|
|
|
857
|
+
/**
|
|
858
|
+
* 3.1.0:跨设备同步的面板面(`sync.*`)。业务全在 `lib/sync/`,这一层只做三件事:
|
|
859
|
+
* 把参数收成字符串、把**设置的兜底**接上、把回来的收据补齐成结果 schema 的形状
|
|
860
|
+
* (`runSyncAction` 的 `invalid` 分支不带 action/applied/report,`gateVerdict` 的
|
|
861
|
+
* deviceId 可能是 null —— schema 不该替下游造值,归一化就落在这里)。
|
|
862
|
+
*/
|
|
863
|
+
export class SyncGateway extends TypertRemoteService {
|
|
864
|
+
constructor(ctx) {
|
|
865
|
+
super(ctx, 'sync')
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/**
|
|
869
|
+
* 设备候选(`tailscale status --json`)。`listDevices` 自己**不抛** ——
|
|
870
|
+
* 没装 / 没登录 / JSON 坏都是值(`available:false` + 一句人话)。这里的 catch
|
|
871
|
+
* 兜的是它之外的意外:面板拿到 `ok:false` 就知道该看日志,而不是去手打 host。
|
|
872
|
+
*/
|
|
873
|
+
async devices() {
|
|
874
|
+
try {
|
|
875
|
+
const { available, devices, reason } = await listDevices()
|
|
876
|
+
return { ok: true, available, devices, ...(typeof reason === 'string' && reason !== '' ? { reason } : {}) }
|
|
877
|
+
} catch (err) {
|
|
878
|
+
return { ok: false, available: false, devices: [], code: 'sync_failed', error: `错误:sync_failed — ${err?.message ?? err}` }
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/**
|
|
883
|
+
* 一次同步动作。`host` / `remotePath` 的兜底顺序与工具面(`lib/tools/sync-tool.js`)一致:
|
|
884
|
+
* **传了就用传的**(去空白后非空),否则读设置里「外部访问 → 跨设备」那两项。
|
|
885
|
+
* 面板平时不传,只有用户临时改了没保存时才传 —— 所以这里不能反过来(设置优先)。
|
|
886
|
+
*/
|
|
887
|
+
async run(opts) {
|
|
888
|
+
const action = String(opts?.action ?? '')
|
|
889
|
+
const configured = await readSyncSettings().catch(() => ({ sync: { host: '', remotePath: '' } }))
|
|
890
|
+
const host = String(opts?.host ?? '').trim() || configured.sync.host
|
|
891
|
+
const remotePath = String(opts?.remotePath ?? '').trim() || configured.sync.remotePath
|
|
892
|
+
|
|
893
|
+
let out
|
|
894
|
+
try {
|
|
895
|
+
out = await runSyncAction({
|
|
896
|
+
action,
|
|
897
|
+
host,
|
|
898
|
+
remotePath,
|
|
899
|
+
apply: opts?.apply === true,
|
|
900
|
+
confirm: opts?.confirm === true,
|
|
901
|
+
memoryDir: MEMORY_DIR,
|
|
902
|
+
stateRoot: STATE_ROOT,
|
|
903
|
+
})
|
|
904
|
+
} catch (err) {
|
|
905
|
+
out = { ok: false, code: 'sync_failed', error: `错误:sync_failed — ${err?.message ?? err}` }
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
const gate = out?.gate
|
|
909
|
+
return {
|
|
910
|
+
ok: out?.ok === true,
|
|
911
|
+
action: typeof out?.action === 'string' && out.action !== '' ? out.action : action,
|
|
912
|
+
applied: out?.applied === true,
|
|
913
|
+
report: typeof out?.report === 'string' ? out.report : '',
|
|
914
|
+
...(gate !== null && typeof gate === 'object'
|
|
915
|
+
? {
|
|
916
|
+
gate: {
|
|
917
|
+
allow: gate.allow === true,
|
|
918
|
+
reason: String(gate.reason ?? ''),
|
|
919
|
+
needConfirm: gate.needConfirm === true,
|
|
920
|
+
deviceId: String(gate.deviceId ?? ''),
|
|
921
|
+
deviceLabel: String(gate.deviceLabel ?? ''),
|
|
922
|
+
},
|
|
923
|
+
}
|
|
924
|
+
: {}),
|
|
925
|
+
// `code` / `error` 只在是字符串时才带上。**不用 `typeof x === 'string'` 的字面写法**:
|
|
926
|
+
// `test/code-registry-test.mjs` 的第二个模式会把 `.code === '<任意文本>'` 当成
|
|
927
|
+
// 「用了这个业务码」,于是 `'string'` 会被报成未登记的码(3.1.0 真踩过一次)。
|
|
928
|
+
...(textOf(out?.code) ? { code: out.code } : {}),
|
|
929
|
+
...(textOf(out?.error) ? { error: out.error } : {}),
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
markRemote(SyncGateway, 'devices', 'devices')
|
|
935
|
+
markRemote(SyncGateway, 'run', 'run')
|
|
936
|
+
|
|
843
937
|
/**
|
|
844
938
|
* autodream 的 remote 面:设置页「自动做梦」标签页唯一的数据通道。
|
|
845
939
|
*
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* sync 层 —— **设备候选**(`tailscale status --json` → 面板上的一排按钮)。
|
|
3
|
+
*
|
|
4
|
+
* 分工:`parseTailscaleStatus` 是**纯函数**(字符串进、结构出),测试靠它做逐条断言;
|
|
5
|
+
* `listDevices` 才碰 IO,而且**一律不抛** —— 设备发现是体验层,没有它同步照样能做(手打 host)。
|
|
6
|
+
*
|
|
7
|
+
* ⚠️ **鉴权边界(这段注释别删)**:能列出候选,只说明「这个节点过了 Tailscale 的 ACL」,
|
|
8
|
+
* 不说明「那一定是我的机器」—— 共享节点、退出前的旧设备都还留在网里。
|
|
9
|
+
* 真正的写入门是 `gate.js`(远端 `.sage-mem/` + 读得懂的 `instance.json` + 首次 / 换库时的人点头)。
|
|
10
|
+
* 所以这里只做**候选展示,不做鉴权**,也不把任何结果写进信任状态。
|
|
11
|
+
* 出处:`docs/3.0.0-push-plan.md` §1.3、`docs/decisions.md` D64 ②。
|
|
12
|
+
*
|
|
13
|
+
* 同样按那份决定:**不做 mDNS / 广播**(§7)。降级路径就是让人手打 SSH 别名,
|
|
14
|
+
* 所以每一种失败都翻成一句人话,而不是抛异常。
|
|
15
|
+
*/
|
|
16
|
+
import { execFile } from 'node:child_process'
|
|
17
|
+
import { DEFAULT_TIMEOUT_MS } from './remote.js'
|
|
18
|
+
|
|
19
|
+
/** 要跑的命令。`--json` 是唯一的机器可读面(人类格式会随版本变)。 */
|
|
20
|
+
export const TAILSCALE_BIN = 'tailscale'
|
|
21
|
+
export const TAILSCALE_ARGS = Object.freeze(['status', '--json'])
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* `tailscale status --json` 的输出上限。百来个节点的状态大约几十 KB,
|
|
25
|
+
* 8 MB 是「万一它把什么东西都倒出来」的封顶,不是预期值。
|
|
26
|
+
*/
|
|
27
|
+
const MAX_OUTPUT_BYTES = 8 * 1024 * 1024
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 超时的 errno 拼写。单独起名字只为一个理由:`code === '…'` 的字面量会被
|
|
31
|
+
* `test/code-registry-test.mjs` 当成「业务码没登记」,而这是 **Node errno**,
|
|
32
|
+
* 按 `lib/shared/codes.js` 头部的约定**不该**进清单(它不是我们的命名空间)。
|
|
33
|
+
*/
|
|
34
|
+
const E_TIMEOUT = 'ETIMEDOUT'
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 去掉 `DNSName` 的尾点。
|
|
38
|
+
*
|
|
39
|
+
* Tailscale 给的是**绝对** DNS 名(`xxx.tailxxxx.ts.net.`),尾点表示「这是完整名字」。
|
|
40
|
+
* 留着它在面板上看着像笔误,拼进 `ssh` 里也容易被当成域名的一部分。
|
|
41
|
+
*
|
|
42
|
+
* @param {unknown} value
|
|
43
|
+
* @returns {string} 非字符串一律空串(缺字段不是错误,只是没这个信息)
|
|
44
|
+
*/
|
|
45
|
+
function withoutTrailingDot(value) {
|
|
46
|
+
if (typeof value !== 'string') return ''
|
|
47
|
+
return value.endsWith('.') ? value.slice(0, -1) : value
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 解析 `tailscale status --json` 的文本。**纯函数**:不读盘、不跑命令、不看环境。
|
|
52
|
+
*
|
|
53
|
+
* 只收 **`Online === true` 且 `HostName` 非空** 的 `Peer`。两条理由:
|
|
54
|
+
* - 离线节点的按钮点下去只会等一次 ssh 超时(`spawnSsh` 的 ConnectTimeout 是 10 s);
|
|
55
|
+
* - 没有 `HostName` 就没法 `ssh <host>`,列出来只是噪音。
|
|
56
|
+
*
|
|
57
|
+
* **`Self` 不算候选**:本机不需要同步到自己(真要自测用本机路径,不经过 ssh)。
|
|
58
|
+
* 实现上只遍历 `Peer`,所以 `Self` 天然不在结果里 —— 这条靠结构保证,不靠过滤。
|
|
59
|
+
*
|
|
60
|
+
* @param {unknown} text — 命令的原样 stdout
|
|
61
|
+
* @returns {{devices: Array<{host: string, dnsName: string, ips: string[], os: string, online: boolean}>, reason: string|null}}
|
|
62
|
+
* `reason` 为 `null` 表示「拿到了候选」;否则是一句给人看的话,`devices` 必为空数组。
|
|
63
|
+
*/
|
|
64
|
+
export function parseTailscaleStatus(text) {
|
|
65
|
+
if (typeof text !== 'string' || text.trim() === '') {
|
|
66
|
+
return {
|
|
67
|
+
devices: [],
|
|
68
|
+
reason: '`tailscale status --json` 没有任何输出(命令没跑起来?)—— 手打 SSH 别名即可,同步不依赖它',
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
let data
|
|
73
|
+
try {
|
|
74
|
+
data = JSON.parse(text)
|
|
75
|
+
} catch {
|
|
76
|
+
return {
|
|
77
|
+
devices: [],
|
|
78
|
+
reason: '`tailscale status --json` 的输出不是合法 JSON(Tailscale 版本不匹配?)—— 手打 SSH 别名即可',
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
|
|
83
|
+
return {
|
|
84
|
+
devices: [],
|
|
85
|
+
reason: '`tailscale status --json` 的输出不是一个 JSON 对象 —— 手打 SSH 别名即可',
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const peers = data.Peer
|
|
90
|
+
const nodes = peers !== null && typeof peers === 'object' && !Array.isArray(peers) ? Object.values(peers) : []
|
|
91
|
+
if (nodes.length === 0) {
|
|
92
|
+
return {
|
|
93
|
+
devices: [],
|
|
94
|
+
reason: 'Tailscale 没报告任何 peer(没登录,或这个网络里只有本机)—— 手打 SSH 别名即可',
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const devices = []
|
|
99
|
+
for (const node of nodes) {
|
|
100
|
+
if (node === null || typeof node !== 'object') continue
|
|
101
|
+
if (node.Online !== true) continue
|
|
102
|
+
const host = typeof node.HostName === 'string' ? node.HostName.trim() : ''
|
|
103
|
+
if (host === '') continue
|
|
104
|
+
devices.push({
|
|
105
|
+
host,
|
|
106
|
+
dnsName: withoutTrailingDot(node.DNSName),
|
|
107
|
+
ips: Array.isArray(node.TailscaleIPs)
|
|
108
|
+
? node.TailscaleIPs.filter((ip) => typeof ip === 'string' && ip.trim() !== '')
|
|
109
|
+
: [],
|
|
110
|
+
os: typeof node.OS === 'string' ? node.OS : '', // 原样透出:这是给人认机器的线索,不做翻译
|
|
111
|
+
online: true,
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (devices.length === 0) {
|
|
116
|
+
return {
|
|
117
|
+
devices: [],
|
|
118
|
+
reason: `Tailscale 里有 ${nodes.length} 个节点,但没有一个在线且带 HostName —— 手打 SSH 别名即可`,
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// 顺序沿用 JSON 里 peer 的顺序(Tailscale 按节点 ID 稳定输出),不在这里重排 ——
|
|
123
|
+
// 面板的排序是 UI 的事,后端擅自排序只会让两处各有一套顺序。
|
|
124
|
+
return { devices, reason: null }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** 取错误 / stdout 的第一行,用来把长 stderr 压成一句话。 */
|
|
128
|
+
function firstLine(value) {
|
|
129
|
+
if (Buffer.isBuffer(value)) return firstLine(value.toString('utf8'))
|
|
130
|
+
if (typeof value !== 'string') return ''
|
|
131
|
+
const line = value.split('\n').map((s) => s.trim()).filter(Boolean)[0]
|
|
132
|
+
return line ?? ''
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* 把一次失败翻成一句人话。四种失败各有各的处置建议,但**结论都一样**:
|
|
137
|
+
* 回退手打 host,同步不受影响。
|
|
138
|
+
*
|
|
139
|
+
* @param {any} err
|
|
140
|
+
* @param {number} timeoutMs
|
|
141
|
+
* @returns {string}
|
|
142
|
+
*/
|
|
143
|
+
function reasonOfFailure(err, timeoutMs) {
|
|
144
|
+
const code = err?.code
|
|
145
|
+
const detail = firstLine(err?.stderr) || firstLine(err?.message)
|
|
146
|
+
if (err?.timedOut === true || code === E_TIMEOUT) {
|
|
147
|
+
return `tailscale status 超时(超过 ${timeoutMs} ms 没返回)—— 手打 SSH 别名即可,同步不依赖它`
|
|
148
|
+
}
|
|
149
|
+
if (code === 'ENOENT') {
|
|
150
|
+
return '没找到 tailscale 命令(没装或不在 PATH 里)—— 手打 SSH 别名即可,同步不依赖它'
|
|
151
|
+
}
|
|
152
|
+
if (Number.isInteger(code)) {
|
|
153
|
+
return `tailscale status 退出码 ${code}(可能未登录或 tailscaled 没起来):${detail || '没有更多信息'}`
|
|
154
|
+
}
|
|
155
|
+
return `tailscale status 没跑起来:${detail || '没有更多信息'}`
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** 从注入点 / 默认实现的返回值里取出文本;取不出就是 `null`(交给失败处理)。 */
|
|
159
|
+
function stdoutOf(value) {
|
|
160
|
+
if (typeof value === 'string') return value
|
|
161
|
+
if (Buffer.isBuffer(value)) return value.toString('utf8')
|
|
162
|
+
if (value !== null && typeof value === 'object') {
|
|
163
|
+
if (typeof value.stdout === 'string') return value.stdout
|
|
164
|
+
if (Buffer.isBuffer(value.stdout)) return value.stdout.toString('utf8')
|
|
165
|
+
}
|
|
166
|
+
return null
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* 默认执行器:真跑 `tailscale status --json`。
|
|
171
|
+
*
|
|
172
|
+
* **给数组参数、不设 `shell: true`** —— 这条路不需要 shell(没有管道、没有通配),
|
|
173
|
+
* 而一旦经过 shell,主机名 / 输出里的任何引号都成了语法的一部分。`execFile` 天然就是这条路。
|
|
174
|
+
*
|
|
175
|
+
* @param {{command: string, args: string[], timeoutMs: number}} input
|
|
176
|
+
* @returns {Promise<{stdout: string, stderr: string}>}
|
|
177
|
+
*/
|
|
178
|
+
function runTailscale({ command, args, timeoutMs }) {
|
|
179
|
+
return new Promise((resolve, reject) => {
|
|
180
|
+
const child = execFile(
|
|
181
|
+
command,
|
|
182
|
+
args,
|
|
183
|
+
{ timeout: timeoutMs, maxBuffer: MAX_OUTPUT_BYTES, windowsHide: true, encoding: 'utf8' },
|
|
184
|
+
(err, stdout, stderr) => {
|
|
185
|
+
if (err) {
|
|
186
|
+
const e = new Error(err.message)
|
|
187
|
+
e.stderr = stderr
|
|
188
|
+
e.code = err.code
|
|
189
|
+
// 与 `remote.js` 同一条判据:被 timeout 杀掉时 `code` 是 null,只有 signal。
|
|
190
|
+
e.timedOut = err.killed === true || err.signal === 'SIGTERM'
|
|
191
|
+
reject(e)
|
|
192
|
+
return
|
|
193
|
+
}
|
|
194
|
+
resolve({ stdout, stderr })
|
|
195
|
+
},
|
|
196
|
+
)
|
|
197
|
+
// 与 `spawnSsh` 同一条理由(那边有真机实测的详述):`execFile` 默认开的 stdin 管道
|
|
198
|
+
// 从不关闭,某些时序下 CLI 会等一个永远不会来的 EOF。tailscale 是本地进程,
|
|
199
|
+
// 但给一个 EOF 的成本是零。
|
|
200
|
+
try {
|
|
201
|
+
child?.stdin?.end()
|
|
202
|
+
} catch {
|
|
203
|
+
// 子进程已经退出、管道已销毁:结论仍由回调决定。
|
|
204
|
+
}
|
|
205
|
+
})
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* 列出 Tailscale 里**可作候选**的设备。
|
|
210
|
+
*
|
|
211
|
+
* 失败是值,不是异常(与检索工具同一条纪律):没装 / 未登录 / 非零退出 / JSON 坏 /
|
|
212
|
+
* `Peer` 为空,一律返回 `available: false` 加一句人话,调用方(面板)据此回退手打 host。
|
|
213
|
+
*
|
|
214
|
+
* @param {object} [input]
|
|
215
|
+
* @param {number} [input.timeoutMs] — 整体超时(默认 `remote.js` 的 `DEFAULT_TIMEOUT_MS`;
|
|
216
|
+
* 本地命令通常远快于此,这个上限只是兜底)
|
|
217
|
+
* @param {(input: {command: string, args: string[], timeoutMs: number}) => Promise<{stdout: string, stderr: string}|string>|{stdout: string}|string} [input.run]
|
|
218
|
+
* — 注入点(测试用)。可以是 async 也可以同步返回;抛错或返回 `{ code }` / `{ error }` 都算失败。
|
|
219
|
+
* @returns {Promise<{available: boolean, devices: Array<object>, reason: string|null}>}
|
|
220
|
+
*/
|
|
221
|
+
export async function listDevices({ timeoutMs = DEFAULT_TIMEOUT_MS, run = runTailscale } = {}) {
|
|
222
|
+
let raw
|
|
223
|
+
try {
|
|
224
|
+
raw = await run({ command: TAILSCALE_BIN, args: [...TAILSCALE_ARGS], timeoutMs })
|
|
225
|
+
} catch (err) {
|
|
226
|
+
return { available: false, devices: [], reason: reasonOfFailure(err, timeoutMs) }
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// 注入点也可能用「返回值告诉我失败」的方式(`{ code: 'ENOENT' }` / `{ error }`),
|
|
230
|
+
// 而默认执行器只会抛 —— 两种都收,免得测试和实现各说一套。
|
|
231
|
+
if (stdoutOf(raw) === null) {
|
|
232
|
+
return { available: false, devices: [], reason: reasonOfFailure(raw, timeoutMs) }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const parsed = parseTailscaleStatus(stdoutOf(raw))
|
|
236
|
+
return { available: parsed.reason === null, devices: parsed.devices, reason: parsed.reason }
|
|
237
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* sync 层 —— **面板的一个入口**:一次调用,三种动作。
|
|
3
|
+
*
|
|
4
|
+
* 这个文件只做三件事:**校验参数、分派、补字段**。fetch / sha / 门禁 / 计划 / 报告
|
|
5
|
+
* 全在各自的模块里(`check.js` / `pull.js` / `push.js`),这里**不许**再写一遍 ——
|
|
6
|
+
* 面板与工具必须走同一条链路,否则「面板上看到的」与「工具里跑出来的」会各说各话,
|
|
7
|
+
* 而同步出错时最贵的成本就是「不知道看的和跑的是不是同一件事」。
|
|
8
|
+
*
|
|
9
|
+
* 为什么 `check` 不给 `updateBase`:面板上**不放**「重建基线」这种按钮。
|
|
10
|
+
* 那个开关会把差异一键抹平成「没有差异」,而差异恰恰是面板存在的理由。
|
|
11
|
+
* 要重建基线就明确去调工具(`memory_sync_check` 的 `updateBase: true`),
|
|
12
|
+
* 那里至少还要求人自己写下这个参数。
|
|
13
|
+
*/
|
|
14
|
+
import { resolveSync } from './policy.js'
|
|
15
|
+
import { runSyncCheck } from './check.js'
|
|
16
|
+
import { runSyncPull } from './pull.js'
|
|
17
|
+
import { runSyncPush } from './push.js'
|
|
18
|
+
|
|
19
|
+
/** 面板能发起的三种动作。顺序即 UI 上的顺序:先看清楚,再搬。 */
|
|
20
|
+
export const PANEL_ACTIONS = ['check', 'pull', 'push']
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* 这两句文案**抄自 `lib/tools/sync-tool.js`**(`no_host` / `no_remote_path` 两个分支),
|
|
24
|
+
* 一个字都没改:同一个失败在工具里和面板里读出两套说法,是最容易让人以为「这里的东西坏了」的那种。
|
|
25
|
+
* 改文案请两边一起改。
|
|
26
|
+
*/
|
|
27
|
+
const NO_HOST_ERROR = '错误:no_host — 还没配置远端主机。在「外部访问 → 跨设备」里填 SSH 别名,或这次直接传 host 参数。'
|
|
28
|
+
const NO_REMOTE_PATH_ERROR = '错误:no_remote_path — 还没配置远端记忆目录。在设置里填,或这次直接传 remotePath 参数。'
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 剥掉本层自己的注入点,其余原样交给下游。
|
|
32
|
+
*
|
|
33
|
+
* 三个桩名(`runSyncCheck` / `runSyncPull` / `runSyncPush`)只有这一层认识;
|
|
34
|
+
* 混进下游的 `deps` 里虽然不会有人读,但「一个层的开关在下下一层也看得见」迟早会被误用。
|
|
35
|
+
*
|
|
36
|
+
* @param {object} deps
|
|
37
|
+
* @returns {object}
|
|
38
|
+
*/
|
|
39
|
+
function downstreamDeps(deps) {
|
|
40
|
+
const {
|
|
41
|
+
runSyncCheck: _check,
|
|
42
|
+
runSyncPull: _pull,
|
|
43
|
+
runSyncPush: _push,
|
|
44
|
+
...rest
|
|
45
|
+
} = deps
|
|
46
|
+
return rest
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 跑一次同步动作。**返回下游的返回**,只补三个字段:`action` / `applied` / `report`。
|
|
51
|
+
*
|
|
52
|
+
* 补字段的理由:
|
|
53
|
+
* - `action`:三种动作共用一张卡片,UI 得知道刚才点的是哪个;
|
|
54
|
+
* - `applied`:`check` 永远是 `false`(它一个字节都不写),拉取 / 推送取下游的 `applied` ——
|
|
55
|
+
* 于是 UI 只要看这一个布尔就知道「这次是真做了还是只是预演」;
|
|
56
|
+
* - `report`:下游给的是 markdown,缺了就补空串,免得 UI 渲染出 `undefined`。
|
|
57
|
+
*
|
|
58
|
+
* `apply` **原样传给三个动作**(`check` 忽略它 —— 它没有写盘的路),`confirm` 只给 `push`。
|
|
59
|
+
* 这两条不在这里加工:预演与确认都是下游的判据,这一层越权改写等于偷偷替人点了头。
|
|
60
|
+
*
|
|
61
|
+
* @param {object} [input]
|
|
62
|
+
* @param {'check'|'pull'|'push'} input.action — 动作名(必须是 `PANEL_ACTIONS` 之一)
|
|
63
|
+
* @param {string} [input.host] — ssh 主机别名
|
|
64
|
+
* @param {string} [input.remotePath] — 远端记忆目录
|
|
65
|
+
* @param {string} input.memoryDir — 本地记忆目录
|
|
66
|
+
* @param {string} input.stateRoot — 状态根(基线 / 备份 / 冲突 / 身份)
|
|
67
|
+
* @param {boolean} [input.apply=false] — 默认预演
|
|
68
|
+
* @param {boolean} [input.confirm=false] — 首次 / 换库时的人点头(只有 `push` 用)
|
|
69
|
+
* @param {number} [input.now]
|
|
70
|
+
* @param {number} [input.timeoutMs]
|
|
71
|
+
* @param {object} [input.deps] — 注入点。除下游自己的键外,本层认识
|
|
72
|
+
* `runSyncCheck` / `runSyncPull` / `runSyncPush`(测试用来断言「真的被调用了、参数对不对」)
|
|
73
|
+
* @returns {Promise<object>}
|
|
74
|
+
*/
|
|
75
|
+
export async function runSyncAction({
|
|
76
|
+
action,
|
|
77
|
+
host,
|
|
78
|
+
remotePath,
|
|
79
|
+
memoryDir,
|
|
80
|
+
stateRoot,
|
|
81
|
+
apply = false,
|
|
82
|
+
confirm = false,
|
|
83
|
+
now = Date.now(),
|
|
84
|
+
timeoutMs,
|
|
85
|
+
deps = {},
|
|
86
|
+
} = {}) {
|
|
87
|
+
if (!PANEL_ACTIONS.includes(action)) {
|
|
88
|
+
return { ok: false, code: 'invalid', error: '错误:invalid — 未知的同步动作' }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// host / remotePath 的判据只有一处:`policy.js` 的 `resolveSync`(去空白、拒控制字符)。
|
|
92
|
+
// 这里不再自己 `trim()` —— 两套判据意味着「工具里能过、面板里过不去」这类只在一条腿上发作的毛病。
|
|
93
|
+
const target = resolveSync({ host, remotePath }).sync
|
|
94
|
+
if (target.host === '') return { ok: false, code: 'no_host', error: NO_HOST_ERROR }
|
|
95
|
+
if (target.remotePath === '') return { ok: false, code: 'no_remote_path', error: NO_REMOTE_PATH_ERROR }
|
|
96
|
+
|
|
97
|
+
const inject = deps !== null && typeof deps === 'object' ? deps : {}
|
|
98
|
+
const call = {
|
|
99
|
+
memoryDir,
|
|
100
|
+
stateRoot,
|
|
101
|
+
host: target.host,
|
|
102
|
+
remotePath: target.remotePath,
|
|
103
|
+
apply,
|
|
104
|
+
now,
|
|
105
|
+
deps: downstreamDeps(inject),
|
|
106
|
+
...(Number.isFinite(timeoutMs) ? { timeoutMs } : {}),
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
let out
|
|
110
|
+
try {
|
|
111
|
+
if (action === 'check') {
|
|
112
|
+
const fn = inject.runSyncCheck ?? runSyncCheck
|
|
113
|
+
// `updateBase: false` 写死 —— 见文件头:面板不提供「重建基线」。
|
|
114
|
+
out = await fn({ ...call, updateBase: false })
|
|
115
|
+
} else if (action === 'pull') {
|
|
116
|
+
const fn = inject.runSyncPull ?? runSyncPull
|
|
117
|
+
out = await fn(call)
|
|
118
|
+
} else {
|
|
119
|
+
const fn = inject.runSyncPush ?? runSyncPush
|
|
120
|
+
out = await fn({ ...call, confirm: confirm === true })
|
|
121
|
+
}
|
|
122
|
+
} catch (err) {
|
|
123
|
+
// 连不上 / 配置错误在下游是抛(与 `check.js` / `push.js` 同口径:那是异常,不是结论)。
|
|
124
|
+
// 面板不能把异常递给 UI —— 翻成一个码,形状与工具那边一致。
|
|
125
|
+
const message = String(err?.message ?? err)
|
|
126
|
+
return {
|
|
127
|
+
ok: false,
|
|
128
|
+
code: 'sync_failed',
|
|
129
|
+
error: `错误:sync_failed — ${message}`,
|
|
130
|
+
action,
|
|
131
|
+
applied: false,
|
|
132
|
+
report: '',
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return {
|
|
137
|
+
...out,
|
|
138
|
+
action,
|
|
139
|
+
// check 永远 false(它没有写盘的路);拉取 / 推送只看下游怎么说。
|
|
140
|
+
applied: action === 'check' ? false : out?.applied === true,
|
|
141
|
+
report: typeof out?.report === 'string' ? out.report : '',
|
|
142
|
+
}
|
|
143
|
+
}
|
package/lib/typert/schemas.js
CHANGED
|
@@ -19,6 +19,9 @@ import { MAX_FILE_BYTES, MAX_RAW_BYTES } from '../shared/limits.js'
|
|
|
19
19
|
// 在 schema 里重抄一份 `['local','remote','manual']` 的代价是:那边加一种裁法,这里静默把它判成坏入参
|
|
20
20
|
// —— 面板传得出去、宿主一律 `invalid`,症状是「按钮点了没反应」而不是报错。
|
|
21
21
|
import { RESOLVE_CHOICES } from '../sync/resolve.js'
|
|
22
|
+
// 3.1.0:面板能发起的同步动作也只有一份取值来源(`sync/panel.js` 的 PANEL_ACTIONS)。
|
|
23
|
+
// 与上面 RESOLVE_CHOICES 同一条理由:重抄一遍 = 那边加动作、这里静默判成坏入参。
|
|
24
|
+
import { PANEL_ACTIONS } from '../sync/panel.js'
|
|
22
25
|
|
|
23
26
|
// 文件名:与 host 侧 safeName 同一套底线 —— 非空、无路径分隔符与 Windows 非法字符、
|
|
24
27
|
// 以 .md 结尾、长度有界。(真正的目录逃逸防护仍在 host 侧 safeName。)
|
|
@@ -853,3 +856,69 @@ export const conflictApplyResultSchema = z.object({
|
|
|
853
856
|
'recordId': z.string().readonly(),
|
|
854
857
|
}).readonly()
|
|
855
858
|
|
|
859
|
+
// ── 3.1.0:面板的同步面(sync/devices · sync/run)────────────────────────────
|
|
860
|
+
// 这两个方法是「面板能自己做的事」与「面板只能转达的事」的分界:
|
|
861
|
+
// · devices —— 一次 `tailscale status --json` 的候选列表,**纯展示**,失败也是值;
|
|
862
|
+
// · run —— 一次同步动作,判据 / 门禁 / 报告全在 `lib/sync/` 里,这里只给形状。
|
|
863
|
+
//
|
|
864
|
+
// `available` 与 `ok` 是两件事:`ok` 说的是「这次调用有没有走通」(异常 → false),
|
|
865
|
+
// `available` 说的是「设备发现能不能用」(没装 tailscale / 没登录 → false 但 `ok` 仍是 true)。
|
|
866
|
+
// 合成一个布尔会让面板分不清「工具坏了」与「这台机器没装 tailscale」——
|
|
867
|
+
// 后者要提示「手打 SSH 别名」,前者要提示「看日志」。
|
|
868
|
+
export const syncDevicesResultSchema = z.object({
|
|
869
|
+
'ok': z.boolean().readonly(),
|
|
870
|
+
'available': z.boolean().readonly(),
|
|
871
|
+
'devices': z.array(z.object({
|
|
872
|
+
'host': z.string().readonly(),
|
|
873
|
+
'dnsName': z.string().readonly(),
|
|
874
|
+
'ips': z.array(z.string()).readonly(),
|
|
875
|
+
'os': z.string().readonly(),
|
|
876
|
+
'online': z.boolean().readonly(),
|
|
877
|
+
}).readonly()).readonly(),
|
|
878
|
+
// 成功拿到候选时**没有** reason(`listDevices` 用 null 表示「没事可报」,这里就不出现这个键)。
|
|
879
|
+
'reason': z.string().readonly().optional(),
|
|
880
|
+
'code': z.string().readonly().optional(),
|
|
881
|
+
'error': z.string().readonly().optional(),
|
|
882
|
+
}).readonly()
|
|
883
|
+
|
|
884
|
+
// 入参:动作名 + 三个可选覆盖。
|
|
885
|
+
// `action` 的三个取值**只有一个来源**(`lib/sync/panel.js` 的 PANEL_ACTIONS,`runSyncAction`
|
|
886
|
+
// 自己也拿它当判据)—— 在 schema 里重抄一份,那边加一种动作时这里会静默判成坏入参。
|
|
887
|
+
// `host` / `remotePath` 可选:面板平时不传,走设置里的「跨设备」配置;只有用户临时改了
|
|
888
|
+
// 又没保存时才传(兜底在 `lib/index.js` 的 SyncGateway,不在 schema 这一层)。
|
|
889
|
+
export const syncRunArgsSchema = z.object({
|
|
890
|
+
'action': z.enum(PANEL_ACTIONS),
|
|
891
|
+
'host': z.string().readonly().optional(),
|
|
892
|
+
'remotePath': z.string().readonly().optional(),
|
|
893
|
+
'apply': z.boolean().readonly().optional(),
|
|
894
|
+
'confirm': z.boolean().readonly().optional(),
|
|
895
|
+
}).readonly()
|
|
896
|
+
|
|
897
|
+
// 结果:**只声明三种动作都成立的那几个字段**。
|
|
898
|
+
//
|
|
899
|
+
// ⚠️ 这里刻意**没有** `summary` / `plan` / `results`:三个动作的 summary 形状各不相同
|
|
900
|
+
// (pull 是 import/overwrite/…,push 是 upload/overwrite/…,check 连 summary 都没有),
|
|
901
|
+
// 声明一份「对所有动作都成立」的合并形状只有两条路 —— 要么放宽成 z.any()(等于没校验,
|
|
902
|
+
// 还会把下游形状当契约冻住),要么逼下游每个动作都造齐所有键(假字段)。两条都不划算:
|
|
903
|
+
// 面板只渲染 `report`(markdown),要细看就读那份 report。
|
|
904
|
+
//
|
|
905
|
+
// `action` / `applied` / `report` **必填**:它们是三种动作共同的回声,失败收据也带着
|
|
906
|
+
// (见 `runSyncAction` 的 catch 分支)。`gate` 只有 push 会给(写入门),其余动作没有。
|
|
907
|
+
export const syncRunResultSchema = z.object({
|
|
908
|
+
'ok': z.boolean().readonly(),
|
|
909
|
+
'action': z.string().readonly(),
|
|
910
|
+
'applied': z.boolean().readonly(),
|
|
911
|
+
'report': z.string().readonly(),
|
|
912
|
+
'gate': z.object({
|
|
913
|
+
'allow': z.boolean().readonly(),
|
|
914
|
+
'reason': z.string().readonly(),
|
|
915
|
+
'needConfirm': z.boolean().readonly(),
|
|
916
|
+
// `gateVerdict` 在「远端状态目录读不到 / 没有 instance.json」时会回 null。
|
|
917
|
+
// 这里声明成 string,归一化放在网关那一层(null → 空串)—— schema 不替下游造值。
|
|
918
|
+
'deviceId': z.string().readonly(),
|
|
919
|
+
'deviceLabel': z.string().readonly(),
|
|
920
|
+
}).readonly().optional(),
|
|
921
|
+
'code': z.string().readonly().optional(),
|
|
922
|
+
'error': z.string().readonly().optional(),
|
|
923
|
+
}).readonly()
|
|
924
|
+
|
package/lib/typert.host.js
CHANGED
|
@@ -26,6 +26,7 @@ import {
|
|
|
26
26
|
conflictItemSchema, conflictRecordSchema, conflictCountsSchema, conflictWroteSchema, conflictListSchema, conflictReadResultSchema,
|
|
27
27
|
conflictInvalidateResultSchema, conflictDismissResultSchema, conflictUndoResultSchema, conflictRemoveResultSchema,
|
|
28
28
|
conflictApplyArgsSchema, conflictApplyResultSchema,
|
|
29
|
+
syncDevicesResultSchema, syncRunArgsSchema, syncRunResultSchema,
|
|
29
30
|
} from './typert/schemas.js'
|
|
30
31
|
export const TYPERT = {
|
|
31
32
|
package: 'sage-mem',
|
|
@@ -582,6 +583,36 @@ export const TYPERT = {
|
|
|
582
583
|
result: { mode: 'strict', typeSymbol: 'sage-mem/types#ConflictApplyResult', schema: conflictApplyResultSchema, create: () => conflictApplyResultSchema },
|
|
583
584
|
sourceLocation: { "file": "lib/index.js", "line": 1, "column": 1 },
|
|
584
585
|
},
|
|
586
|
+
// ── 3.1.0:跨设备同步的面板入口(`sync.*` 服务)──
|
|
587
|
+
// 与 `conflict.*` 同一套写法:业务判断全在 `lib/sync/`(devices.js / panel.js),
|
|
588
|
+
// 这里只声明传输形状。`sourceLocation` 同样硬编码 lib/index.js(见 D21)。
|
|
589
|
+
{
|
|
590
|
+
// 设备候选(`tailscale status --json` → 面板上的一排按钮)。无入参:超时 / 注入点
|
|
591
|
+
// 都是测试用的,不值得占一个 wire 参数。
|
|
592
|
+
id: 'sage-mem#sync/devices',
|
|
593
|
+
service: 'sync',
|
|
594
|
+
namespace: 'sync',
|
|
595
|
+
method: 'devices',
|
|
596
|
+
invocation: { kind: 'direct' },
|
|
597
|
+
parameters: [],
|
|
598
|
+
result: { mode: 'strict', typeSymbol: 'sage-mem/types#SyncDevicesResult', schema: syncDevicesResultSchema, create: () => syncDevicesResultSchema },
|
|
599
|
+
sourceLocation: { "file": "lib/index.js", "line": 1, "column": 1 },
|
|
600
|
+
},
|
|
601
|
+
{
|
|
602
|
+
// 一次同步动作:check(看清楚)/ pull(搬回来)/ push(推上去)。
|
|
603
|
+
// 入参是**一个** opts 对象 —— 与 conflict 那七条同一个姿势,面板只传它认识的那几个键。
|
|
604
|
+
// 结果 schema 刻意不含 summary / plan / results(三个动作形状各异,见 schemas.js 的注释)。
|
|
605
|
+
id: 'sage-mem#sync/run',
|
|
606
|
+
service: 'sync',
|
|
607
|
+
namespace: 'sync',
|
|
608
|
+
method: 'run',
|
|
609
|
+
invocation: { kind: 'direct' },
|
|
610
|
+
parameters: [
|
|
611
|
+
{ name: 'opts', wire: 'opts', source: 'json', codec: { mode: 'strict', typeSymbol: 'sage-mem/types#SyncRunArgs', schema: syncRunArgsSchema, create: () => syncRunArgsSchema } },
|
|
612
|
+
],
|
|
613
|
+
result: { mode: 'strict', typeSymbol: 'sage-mem/types#SyncRunResult', schema: syncRunResultSchema, create: () => syncRunResultSchema },
|
|
614
|
+
sourceLocation: { "file": "lib/index.js", "line": 1, "column": 1 },
|
|
615
|
+
},
|
|
585
616
|
],
|
|
586
617
|
model: {
|
|
587
618
|
"services": [],
|
package/package.json
CHANGED