dsh-session-sync 0.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/ARCHITECTURE.md +86 -0
- package/CHANGELOG.md +18 -0
- package/LICENSE +201 -0
- package/README.es.md +181 -0
- package/README.hi.md +181 -0
- package/README.md +181 -0
- package/README.pt.md +181 -0
- package/README.zh.md +181 -0
- package/SECURITY.md +39 -0
- package/THIRD_PARTY_NOTICES.md +25 -0
- package/cordis.patch.yml +41 -0
- package/index.mjs +775 -0
- package/lib/constants.mjs +109 -0
- package/lib/domain.mjs +29 -0
- package/lib/engine.mjs +289 -0
- package/lib/errors.mjs +99 -0
- package/lib/gate.mjs +152 -0
- package/lib/git.mjs +377 -0
- package/lib/merge.mjs +96 -0
- package/lib/mirror.mjs +120 -0
- package/lib/paths.mjs +107 -0
- package/lib/render.mjs +107 -0
- package/lib/sanitize.mjs +105 -0
- package/lib/status.mjs +69 -0
- package/package.json +144 -0
- package/types.d.ts +132 -0
package/index.mjs
ADDED
|
@@ -0,0 +1,775 @@
|
|
|
1
|
+
// index.mjs — dsh-session-sync 插件入口(唯一 host 面文件)。
|
|
2
|
+
//
|
|
3
|
+
// 功能:把 DSH 会话存储目录(默认 $DSH_HOME/sessions)作为不透明字节镜像进
|
|
4
|
+
// 一个专用 git 工作树并同步到自定义 remote:
|
|
5
|
+
// - 默认 git 后端(ctx.subprocess 跑 git;动词白名单 + 绝不强推);backend 词汇
|
|
6
|
+
// 预留端到端加密后端(age/GPG 类),密钥不入仓库(当前配置即响亮失败)。
|
|
7
|
+
// - /sync 命令(status|pull|push|diff|log|help;pull/push 走确认门)与
|
|
8
|
+
// sync_pull / sync_push / sync_status 模型工具(操作走审批,轮次内可用)。
|
|
9
|
+
// - 冲突裁决:会话日志 append-only —— 双边纯追加/真实分歧一律"本地保留 +
|
|
10
|
+
// 远端留存 fork 文件",绝不静默覆盖(lib/merge.mjs 语义 + 测试)。
|
|
11
|
+
// - 自动模式:autoPullOnStart / autoPushOnTurnEnd(turn/end 会话事件)/
|
|
12
|
+
// pullIntervalMinutes(周期拉取;定时与事件全部走 ctx.effect 可逆)。
|
|
13
|
+
// - 同步元数据(设备 id、最近推/拉、最近错误)存 ctx.storageDomain 领域
|
|
14
|
+
// 'session-sync'。
|
|
15
|
+
//
|
|
16
|
+
// 只消费公开服务:sessions / commands / storageDomain / subprocess(inject
|
|
17
|
+
// 声明),tools 经 ctx.inject 可选注册;userQuestions / approval 可选查找
|
|
18
|
+
// (缺失 = 失败关闭)。lib/ 零 DSH 依赖,服务只在边界接线。
|
|
19
|
+
|
|
20
|
+
import { randomUUID } from 'node:crypto'
|
|
21
|
+
import { Context } from '@deepseek-ai/cordis'
|
|
22
|
+
import Schema from '@deepseek-ai/schemastery'
|
|
23
|
+
import SessionStore, { KNOWN_SESSION_EVENT_TYPES } from '@deepseek-ai/dsh-session'
|
|
24
|
+
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
25
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
26
|
+
import {
|
|
27
|
+
BACKENDS,
|
|
28
|
+
COMMAND_NAME,
|
|
29
|
+
CONFIRM_CHANNELS,
|
|
30
|
+
DEFAULTS,
|
|
31
|
+
LIMITS,
|
|
32
|
+
PLUGIN_NAME,
|
|
33
|
+
SESSION_EVENTS,
|
|
34
|
+
STATE_KEY,
|
|
35
|
+
TOOL_PULL,
|
|
36
|
+
TOOL_PUSH,
|
|
37
|
+
TOOL_STATUS,
|
|
38
|
+
} from './lib/constants.mjs'
|
|
39
|
+
import {
|
|
40
|
+
badConfig,
|
|
41
|
+
backendUnsupported,
|
|
42
|
+
messageOf,
|
|
43
|
+
registryUnavailable,
|
|
44
|
+
} from './lib/errors.mjs'
|
|
45
|
+
import { assertNestingSafe, resolveRepoDir, resolveSessionRoot } from './lib/paths.mjs'
|
|
46
|
+
import { GitBackend } from './lib/git.mjs'
|
|
47
|
+
import { SyncEngine } from './lib/engine.mjs'
|
|
48
|
+
import { collectStatus } from './lib/status.mjs'
|
|
49
|
+
import { renderDiff, renderPull, renderPush, renderStatus, errorValue } from './lib/render.mjs'
|
|
50
|
+
import { confirmSync, hasOpenTurn, makeEventGate, maybeAppendSessionEvent } from './lib/gate.mjs'
|
|
51
|
+
import { sessionSyncDomainSpec } from './lib/domain.mjs'
|
|
52
|
+
|
|
53
|
+
export const name = PLUGIN_NAME
|
|
54
|
+
|
|
55
|
+
/** 必需服务:缺失即加载失败(响亮)。 */
|
|
56
|
+
export const inject = ['sessions', 'commands', 'storageDomain', 'subprocess']
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 宿主 append 是否盖章 ignorable 信封(运行时能力探测)。
|
|
60
|
+
* 在全新 detached Context 上构造 SessionStore(绝不接入宿主持久化,探测
|
|
61
|
+
* 会话不落盘):追加一条带 { ignorable: true } 的探测事件并回读信封标记。
|
|
62
|
+
* rc.6 的 append 静默丢弃未知选项键 → 标记缺失 → false(门保持关闭);
|
|
63
|
+
* 支持 ignorable 信封的宿主 → true(sync/* 以 ignorable 落盘)。
|
|
64
|
+
* @returns {boolean} 宿主支持 ignorable 信封。
|
|
65
|
+
*/
|
|
66
|
+
export function probeIgnorableAppend() {
|
|
67
|
+
try {
|
|
68
|
+
const store = new SessionStore(new Context())
|
|
69
|
+
const session = store.create()
|
|
70
|
+
const event = session.append(SESSION_EVENTS.PUSH, {
|
|
71
|
+
sessionId: 'probe',
|
|
72
|
+
ok: true,
|
|
73
|
+
pushed: true,
|
|
74
|
+
head: 'probe',
|
|
75
|
+
// @ts-ignore rc.6 append has no envelope option — probing it is the point.
|
|
76
|
+
}, /** @type {any} */ ({ ignorable: true }))
|
|
77
|
+
return event?.ignorable === true
|
|
78
|
+
} catch {
|
|
79
|
+
return false
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* 插件配置(Schemastery,全部可 cordis.yml 覆盖;无硬编码 tunable)。
|
|
85
|
+
* @typedef {object} Config
|
|
86
|
+
* @property {boolean} [enabled] 整体开关;false 时不注册任何东西。
|
|
87
|
+
* @property {string} [backend] 同步后端词汇;只有 'git' 实现,其余(加密后端)预留并响亮失败。
|
|
88
|
+
* @property {string} [sessionRoot] 会话存储根;空 = $DSH_HOME/sessions(两者皆缺响亮失败)。
|
|
89
|
+
* @property {string} [repoDir] 同步 git 工作树根;空 = $DSH_HOME/dsh-session-sync/repo。
|
|
90
|
+
* @property {string} [remote] 远端地址(自定义 remote;pull/push 前必须非空,status/diff 不需要)。
|
|
91
|
+
* @property {string} [branch] 远端分支名(默认 main)。
|
|
92
|
+
* @property {string} [gitBin] git 可执行路径(默认 'git')。
|
|
93
|
+
* @property {boolean} [autoPullOnStart] 挂载时自动拉取一次(配置即授权,不再确认)。
|
|
94
|
+
* @property {boolean} [autoPushOnTurnEnd] 每个 turn/end 后自动推送(配置即授权)。
|
|
95
|
+
* @property {number} [pullIntervalMinutes] 周期自动拉取间隔分钟(0 = 关闭)。
|
|
96
|
+
* @property {'auto'|'userQuestions'|'approval'} [confirmVia] 确认通道(auto 优先 userQuestions)。
|
|
97
|
+
* @property {number} [graceMs] git 子进程终止宽限(ms)。
|
|
98
|
+
* @property {number} [commandTimeoutMs] 单条 git 命令超时(ms)。
|
|
99
|
+
* @property {number} [maxOutputBytes] git 输出单流收集上限(字节)。
|
|
100
|
+
* @property {string} [commitName] 插件提交者名。
|
|
101
|
+
* @property {string} [commitEmail] 插件提交者邮箱。
|
|
102
|
+
* @property {boolean} [registerCommand] 注册 /sync 命令。
|
|
103
|
+
* @property {boolean} [registerTools] tools 服务存在时注册 sync_* 工具。
|
|
104
|
+
*/
|
|
105
|
+
export const Config = Schema.object({
|
|
106
|
+
enabled: Schema.boolean().default(DEFAULTS.ENABLED),
|
|
107
|
+
backend: Schema.union(Object.values(BACKENDS)).default(DEFAULTS.BACKEND),
|
|
108
|
+
sessionRoot: Schema.string().default(DEFAULTS.SESSION_ROOT),
|
|
109
|
+
repoDir: Schema.string().default(DEFAULTS.REPO_DIR),
|
|
110
|
+
remote: Schema.string().default(DEFAULTS.REMOTE),
|
|
111
|
+
branch: Schema.string().default(DEFAULTS.BRANCH),
|
|
112
|
+
gitBin: Schema.string().default(DEFAULTS.GIT_BIN),
|
|
113
|
+
autoPullOnStart: Schema.boolean().default(DEFAULTS.AUTO_PULL_ON_START),
|
|
114
|
+
autoPushOnTurnEnd: Schema.boolean().default(DEFAULTS.AUTO_PUSH_ON_TURN_END),
|
|
115
|
+
pullIntervalMinutes: Schema.number().default(DEFAULTS.PULL_INTERVAL_MINUTES),
|
|
116
|
+
confirmVia: Schema.union(Object.values(CONFIRM_CHANNELS)).default(DEFAULTS.CONFIRM_VIA),
|
|
117
|
+
graceMs: Schema.number().default(DEFAULTS.GRACE_MS),
|
|
118
|
+
commandTimeoutMs: Schema.number().default(DEFAULTS.COMMAND_TIMEOUT_MS),
|
|
119
|
+
maxOutputBytes: Schema.number().default(DEFAULTS.MAX_OUTPUT_BYTES),
|
|
120
|
+
commitName: Schema.string().default(DEFAULTS.COMMIT_NAME),
|
|
121
|
+
commitEmail: Schema.string().default(DEFAULTS.COMMIT_EMAIL),
|
|
122
|
+
registerCommand: Schema.boolean().default(DEFAULTS.REGISTER_COMMAND),
|
|
123
|
+
registerTools: Schema.boolean().default(DEFAULTS.REGISTER_TOOLS),
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* 显式补齐默认 + 加载期校验(非法配置响亮失败)。
|
|
128
|
+
* @param {Partial<Config>|undefined} config - cordis loader 传入的配置。
|
|
129
|
+
* @returns {Required<Config>} 校验后的配置。
|
|
130
|
+
*/
|
|
131
|
+
export function resolveConfig(config = {}) {
|
|
132
|
+
const resolved = {
|
|
133
|
+
enabled: config.enabled ?? DEFAULTS.ENABLED,
|
|
134
|
+
backend: config.backend ?? DEFAULTS.BACKEND,
|
|
135
|
+
sessionRoot: config.sessionRoot ?? DEFAULTS.SESSION_ROOT,
|
|
136
|
+
repoDir: config.repoDir ?? DEFAULTS.REPO_DIR,
|
|
137
|
+
remote: config.remote ?? DEFAULTS.REMOTE,
|
|
138
|
+
branch: config.branch ?? DEFAULTS.BRANCH,
|
|
139
|
+
gitBin: config.gitBin ?? DEFAULTS.GIT_BIN,
|
|
140
|
+
autoPullOnStart: config.autoPullOnStart ?? DEFAULTS.AUTO_PULL_ON_START,
|
|
141
|
+
autoPushOnTurnEnd: config.autoPushOnTurnEnd ?? DEFAULTS.AUTO_PUSH_ON_TURN_END,
|
|
142
|
+
pullIntervalMinutes: config.pullIntervalMinutes ?? DEFAULTS.PULL_INTERVAL_MINUTES,
|
|
143
|
+
confirmVia: config.confirmVia ?? DEFAULTS.CONFIRM_VIA,
|
|
144
|
+
graceMs: config.graceMs ?? DEFAULTS.GRACE_MS,
|
|
145
|
+
commandTimeoutMs: config.commandTimeoutMs ?? DEFAULTS.COMMAND_TIMEOUT_MS,
|
|
146
|
+
maxOutputBytes: config.maxOutputBytes ?? DEFAULTS.MAX_OUTPUT_BYTES,
|
|
147
|
+
commitName: config.commitName ?? DEFAULTS.COMMIT_NAME,
|
|
148
|
+
commitEmail: config.commitEmail ?? DEFAULTS.COMMIT_EMAIL,
|
|
149
|
+
registerCommand: config.registerCommand ?? DEFAULTS.REGISTER_COMMAND,
|
|
150
|
+
registerTools: config.registerTools ?? DEFAULTS.REGISTER_TOOLS,
|
|
151
|
+
}
|
|
152
|
+
if (resolved.enabled === false) return resolved
|
|
153
|
+
if (!Object.values(BACKENDS).includes(/** @type {any} */ (resolved.backend))) {
|
|
154
|
+
throw backendUnsupported(/** @type {any} */ (resolved.backend))
|
|
155
|
+
}
|
|
156
|
+
if (!Object.values(CONFIRM_CHANNELS).includes(resolved.confirmVia)) {
|
|
157
|
+
throw badConfig(`confirmVia ${JSON.stringify(resolved.confirmVia)} must be one of auto|userQuestions|approval`)
|
|
158
|
+
}
|
|
159
|
+
if (typeof resolved.gitBin !== 'string' || resolved.gitBin.length === 0) {
|
|
160
|
+
throw badConfig('gitBin must be a non-empty string')
|
|
161
|
+
}
|
|
162
|
+
if (typeof resolved.branch !== 'string' || resolved.branch.length === 0 || !/^[A-Za-z0-9._/-]+$/u.test(resolved.branch)) {
|
|
163
|
+
throw badConfig('branch must be a non-empty ref-safe string')
|
|
164
|
+
}
|
|
165
|
+
if (!Number.isFinite(resolved.graceMs) || resolved.graceMs < LIMITS.MIN_GRACE_MS || resolved.graceMs > LIMITS.MAX_GRACE_MS) {
|
|
166
|
+
throw badConfig(`graceMs must be an integer in [${LIMITS.MIN_GRACE_MS}, ${LIMITS.MAX_GRACE_MS}]`)
|
|
167
|
+
}
|
|
168
|
+
if (!Number.isFinite(resolved.commandTimeoutMs) || resolved.commandTimeoutMs < LIMITS.MIN_COMMAND_TIMEOUT_MS || resolved.commandTimeoutMs > LIMITS.MAX_COMMAND_TIMEOUT_MS) {
|
|
169
|
+
throw badConfig(`commandTimeoutMs must be an integer in [${LIMITS.MIN_COMMAND_TIMEOUT_MS}, ${LIMITS.MAX_COMMAND_TIMEOUT_MS}]`)
|
|
170
|
+
}
|
|
171
|
+
if (!Number.isFinite(resolved.maxOutputBytes) || resolved.maxOutputBytes < LIMITS.MIN_MAX_OUTPUT_BYTES || resolved.maxOutputBytes > LIMITS.MAX_MAX_OUTPUT_BYTES) {
|
|
172
|
+
throw badConfig(`maxOutputBytes must be an integer in [${LIMITS.MIN_MAX_OUTPUT_BYTES}, ${LIMITS.MAX_MAX_OUTPUT_BYTES}]`)
|
|
173
|
+
}
|
|
174
|
+
if (!Number.isInteger(resolved.pullIntervalMinutes) || resolved.pullIntervalMinutes < LIMITS.MIN_PULL_INTERVAL_MINUTES || resolved.pullIntervalMinutes > LIMITS.MAX_PULL_INTERVAL_MINUTES) {
|
|
175
|
+
throw badConfig(`pullIntervalMinutes must be an integer in [${LIMITS.MIN_PULL_INTERVAL_MINUTES}, ${LIMITS.MAX_PULL_INTERVAL_MINUTES}]`)
|
|
176
|
+
}
|
|
177
|
+
if (typeof resolved.commitName !== 'string' || resolved.commitName.trim().length === 0) {
|
|
178
|
+
throw badConfig('commitName must be a non-empty string')
|
|
179
|
+
}
|
|
180
|
+
if (typeof resolved.commitEmail !== 'string' || resolved.commitEmail.trim().length === 0) {
|
|
181
|
+
throw badConfig('commitEmail must be a non-empty string')
|
|
182
|
+
}
|
|
183
|
+
if (resolved.sessionRoot === '' && process.env.DSH_HOME === undefined) {
|
|
184
|
+
throw badConfig('sessionRoot is empty and $DSH_HOME is not set; run under dsh or set sessionRoot explicitly')
|
|
185
|
+
}
|
|
186
|
+
if (resolved.repoDir === '' && process.env.DSH_HOME === undefined) {
|
|
187
|
+
throw badConfig('repoDir is empty and $DSH_HOME is not set; run under dsh or set repoDir explicitly')
|
|
188
|
+
}
|
|
189
|
+
return resolved
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* git runner:ctx.subprocess 上的 collect/pipe 封装。
|
|
194
|
+
* binary=true 时 stdout 走原始字节管道(读 blob 必需),否则 collect 文本。
|
|
195
|
+
* @param {import('@deepseek-ai/dsh-subprocess').SubprocessRuntime} subprocess - 宿主子进程服务。
|
|
196
|
+
* @param {object} opts - {gitBin, graceMs, commandTimeoutMs, maxOutputBytes}。
|
|
197
|
+
* @returns {(args: string[], runOpts?: object) => Promise<{code: number, stdout: string|Buffer, stderr: string}>}
|
|
198
|
+
*/
|
|
199
|
+
export function makeRunGit(subprocess, opts) {
|
|
200
|
+
return async (args, runOpts = {}) => {
|
|
201
|
+
const controller = new AbortController()
|
|
202
|
+
let timedOut = false
|
|
203
|
+
const timer = setTimeout(() => {
|
|
204
|
+
timedOut = true
|
|
205
|
+
controller.abort(new Error(`git ${args[0] ?? ''} timed out after ${opts.commandTimeoutMs}ms`))
|
|
206
|
+
}, opts.commandTimeoutMs)
|
|
207
|
+
const onAbort = () => {
|
|
208
|
+
controller.abort(runOpts.signal?.reason instanceof Error ? runOpts.signal.reason : new Error('sync operation aborted'))
|
|
209
|
+
}
|
|
210
|
+
if (runOpts.signal !== undefined) {
|
|
211
|
+
runOpts.signal.addEventListener('abort', onAbort, { once: true })
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
const executable = await subprocess.resolveExecutable(opts.gitBin, undefined, controller.signal)
|
|
215
|
+
const handle = subprocess.spawn({
|
|
216
|
+
argv: [executable, ...args],
|
|
217
|
+
cwd: runOpts.cwd,
|
|
218
|
+
stdio: {
|
|
219
|
+
stdin: 'ignore',
|
|
220
|
+
stdout: runOpts.binary === true ? 'pipe' : { maxBytes: opts.maxOutputBytes },
|
|
221
|
+
stderr: { maxBytes: opts.maxOutputBytes },
|
|
222
|
+
},
|
|
223
|
+
graceMs: opts.graceMs,
|
|
224
|
+
signal: controller.signal,
|
|
225
|
+
env: {
|
|
226
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
227
|
+
GIT_OPTIONAL_LOCKS: '0',
|
|
228
|
+
},
|
|
229
|
+
})
|
|
230
|
+
let raw
|
|
231
|
+
if (runOpts.binary === true) {
|
|
232
|
+
const chunks = []
|
|
233
|
+
for await (const chunk of handle.stdout) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)))
|
|
234
|
+
raw = Buffer.concat(chunks)
|
|
235
|
+
}
|
|
236
|
+
const outcome = await handle.done
|
|
237
|
+
if (timedOut) {
|
|
238
|
+
throw new Error(`git ${args[0] ?? ''} timed out after ${opts.commandTimeoutMs}ms`)
|
|
239
|
+
}
|
|
240
|
+
if (runOpts.signal?.aborted === true) {
|
|
241
|
+
throw runOpts.signal.reason instanceof Error ? runOpts.signal.reason : new Error('sync operation aborted')
|
|
242
|
+
}
|
|
243
|
+
const stdout = raw ?? handle.collected.stdout.readFrom(0).text
|
|
244
|
+
const stderr = handle.collected.stderr.readFrom(0).text
|
|
245
|
+
return { code: outcome.exitCode ?? (outcome.signal !== null ? 128 : 0), stdout, stderr }
|
|
246
|
+
} finally {
|
|
247
|
+
clearTimeout(timer)
|
|
248
|
+
if (runOpts.signal !== undefined) {
|
|
249
|
+
runOpts.signal.removeEventListener('abort', onAbort)
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* 工具参数/输出描述(双语)。
|
|
257
|
+
*/
|
|
258
|
+
const TOOL_TEXT = {
|
|
259
|
+
en: {
|
|
260
|
+
statusDescription: 'Show the session-sync git mirror state: branch, sanitized remote, ahead/behind counts, uncommitted files, fork files from conflicts, and the last pull/push times. Read-only: never confirms, never touches the network.',
|
|
261
|
+
pullDescription: 'Pull remote session changes into the local sync mirror with append-only keep-both merge semantics (local version kept, remote version preserved as fork files — never silently overwritten). Requires user confirmation.',
|
|
262
|
+
pushDescription: 'Mirror local session files into the sync repo, commit, and push to the configured remote. Never force-pushes; a rejected push reconciles by pulling first and retries once. Requires user confirmation.',
|
|
263
|
+
},
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** sync_status 工具规范结果(与工具 schema 同构)。 */
|
|
267
|
+
/** @typedef {{ok: boolean, branch: string, remote: string, head?: string, remoteHead?: string, ahead: number, behind: number, dirty: string[], forks: string[], diffStat: string, mergeInProgress: boolean, lastCommits: string[], lastPullAt?: number, lastPushAt?: number, lastError?: string, error?: string}} StatusValue */
|
|
268
|
+
/** @typedef {{ok: boolean, pulled?: boolean, merged?: boolean, adopted?: number, appended?: number, diverged?: number, forks?: string[], head?: string, error?: string}} PullValue */
|
|
269
|
+
/** @typedef {{ok: boolean, pushed?: boolean, head?: string, mirrored?: number, deleted?: number, remote?: string, error?: string}} PushValue */
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* sync_status 工具定义(read-only:不确认、不触网)。
|
|
273
|
+
* @param {SyncEngine} engine - 同步引擎。
|
|
274
|
+
* @param {() => Promise<object>} readMeta - 元数据读取。
|
|
275
|
+
* @returns {object} 工具定义。
|
|
276
|
+
*/
|
|
277
|
+
export function makeSyncStatusTool(engine, readMeta) {
|
|
278
|
+
return defineTool({
|
|
279
|
+
name: TOOL_STATUS,
|
|
280
|
+
description: TOOL_TEXT.en.statusDescription,
|
|
281
|
+
parameters: {},
|
|
282
|
+
output: {
|
|
283
|
+
schema: {
|
|
284
|
+
type: 'object',
|
|
285
|
+
additionalProperties: false,
|
|
286
|
+
properties: {
|
|
287
|
+
ok: { type: 'boolean', required: true },
|
|
288
|
+
branch: { type: 'string' },
|
|
289
|
+
remote: { type: 'string' },
|
|
290
|
+
head: { type: 'string' },
|
|
291
|
+
remoteHead: { type: 'string' },
|
|
292
|
+
ahead: { type: 'integer' },
|
|
293
|
+
behind: { type: 'integer' },
|
|
294
|
+
dirty: { type: 'array', items: { type: 'string' } },
|
|
295
|
+
forks: { type: 'array', items: { type: 'string' } },
|
|
296
|
+
diffStat: { type: 'string' },
|
|
297
|
+
mergeInProgress: { type: 'boolean' },
|
|
298
|
+
lastCommits: { type: 'array', items: { type: 'string' } },
|
|
299
|
+
lastPullAt: { type: 'integer' },
|
|
300
|
+
lastPushAt: { type: 'integer' },
|
|
301
|
+
lastError: { type: 'string' },
|
|
302
|
+
error: { type: 'string' },
|
|
303
|
+
},
|
|
304
|
+
},
|
|
305
|
+
render(_args, value) {
|
|
306
|
+
return [{ type: 'text', text: renderStatus(value) }]
|
|
307
|
+
},
|
|
308
|
+
},
|
|
309
|
+
async execute(_args, exec) {
|
|
310
|
+
exec.signal?.throwIfAborted()
|
|
311
|
+
const status = await engine.status()
|
|
312
|
+
try {
|
|
313
|
+
const meta = await readMeta()
|
|
314
|
+
return { ...status, lastPullAt: meta.lastPullAt, lastPushAt: meta.lastPushAt, lastError: meta.lastError }
|
|
315
|
+
} catch {
|
|
316
|
+
return status
|
|
317
|
+
}
|
|
318
|
+
},
|
|
319
|
+
})
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* sync_pull 工具定义(操作走确认门;execute 尊重 exec.signal)。
|
|
324
|
+
* @param {object} deps - {engine, ctx, confirmVia}。
|
|
325
|
+
* @returns {object} 工具定义。
|
|
326
|
+
*/
|
|
327
|
+
export function makeSyncPullTool(deps) {
|
|
328
|
+
return defineTool({
|
|
329
|
+
name: TOOL_PULL,
|
|
330
|
+
description: TOOL_TEXT.en.pullDescription,
|
|
331
|
+
parameters: {},
|
|
332
|
+
output: {
|
|
333
|
+
schema: {
|
|
334
|
+
type: 'object',
|
|
335
|
+
additionalProperties: false,
|
|
336
|
+
properties: {
|
|
337
|
+
ok: { type: 'boolean', required: true },
|
|
338
|
+
pulled: { type: 'boolean' },
|
|
339
|
+
merged: { type: 'boolean' },
|
|
340
|
+
adopted: { type: 'integer' },
|
|
341
|
+
appended: { type: 'integer' },
|
|
342
|
+
diverged: { type: 'integer' },
|
|
343
|
+
forks: { type: 'array', items: { type: 'string' } },
|
|
344
|
+
head: { type: 'string' },
|
|
345
|
+
error: { type: 'string' },
|
|
346
|
+
},
|
|
347
|
+
},
|
|
348
|
+
render(_args, value) {
|
|
349
|
+
return [{ type: 'text', text: renderPull(value) }]
|
|
350
|
+
},
|
|
351
|
+
},
|
|
352
|
+
async execute(_args, exec) {
|
|
353
|
+
exec.signal?.throwIfAborted()
|
|
354
|
+
const verdict = await confirmSync(
|
|
355
|
+
{ ctx: deps.ctx, confirmVia: deps.confirmVia, action: 'pull', summary: 'Download remote session changes into the local sync mirror (keep-both merge; never overwrites).' },
|
|
356
|
+
exec.agent,
|
|
357
|
+
exec.signal,
|
|
358
|
+
)
|
|
359
|
+
if (!verdict.allowed) {
|
|
360
|
+
return errorValue(verdict.reason ?? 'confirmation failed (fail closed)')
|
|
361
|
+
}
|
|
362
|
+
const result = await deps.engine.pull({ signal: exec.signal })
|
|
363
|
+
if (exec.agent?.session !== null && exec.agent?.session !== undefined) {
|
|
364
|
+
maybeAppendSessionEvent(exec.agent.session, SESSION_EVENTS.PULL, {
|
|
365
|
+
sessionId: exec.agent.session.id,
|
|
366
|
+
ok: result.ok,
|
|
367
|
+
error: result.error,
|
|
368
|
+
pulled: result.pulled,
|
|
369
|
+
merged: result.merged,
|
|
370
|
+
adopted: result.adopted,
|
|
371
|
+
appended: result.appended,
|
|
372
|
+
diverged: result.diverged,
|
|
373
|
+
forks: result.forks,
|
|
374
|
+
head: result.head,
|
|
375
|
+
}, deps.eventGate, (message) => deps.logger.warn(message))
|
|
376
|
+
}
|
|
377
|
+
return result
|
|
378
|
+
},
|
|
379
|
+
})
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* sync_push 工具定义(操作走确认门;execute 尊重 exec.signal)。
|
|
384
|
+
* @param {object} deps - {engine, ctx, confirmVia, eventGate, logger}。
|
|
385
|
+
* @returns {object} 工具定义。
|
|
386
|
+
*/
|
|
387
|
+
export function makeSyncPushTool(deps) {
|
|
388
|
+
return defineTool({
|
|
389
|
+
name: TOOL_PUSH,
|
|
390
|
+
description: TOOL_TEXT.en.pushDescription,
|
|
391
|
+
parameters: {},
|
|
392
|
+
output: {
|
|
393
|
+
schema: {
|
|
394
|
+
type: 'object',
|
|
395
|
+
additionalProperties: false,
|
|
396
|
+
properties: {
|
|
397
|
+
ok: { type: 'boolean', required: true },
|
|
398
|
+
pushed: { type: 'boolean' },
|
|
399
|
+
head: { type: 'string' },
|
|
400
|
+
mirrored: { type: 'integer' },
|
|
401
|
+
deleted: { type: 'integer' },
|
|
402
|
+
remote: { type: 'string' },
|
|
403
|
+
error: { type: 'string' },
|
|
404
|
+
},
|
|
405
|
+
},
|
|
406
|
+
render(_args, value) {
|
|
407
|
+
return [{ type: 'text', text: renderPush(value) }]
|
|
408
|
+
},
|
|
409
|
+
},
|
|
410
|
+
async execute(_args, exec) {
|
|
411
|
+
exec.signal?.throwIfAborted()
|
|
412
|
+
const verdict = await confirmSync(
|
|
413
|
+
{ ctx: deps.ctx, confirmVia: deps.confirmVia, action: 'push', summary: 'Upload local session changes to the sync remote (commit + push; never force-pushes).' },
|
|
414
|
+
exec.agent,
|
|
415
|
+
exec.signal,
|
|
416
|
+
)
|
|
417
|
+
if (!verdict.allowed) {
|
|
418
|
+
return errorValue(verdict.reason ?? 'confirmation failed (fail closed)')
|
|
419
|
+
}
|
|
420
|
+
const result = await deps.engine.push({ signal: exec.signal })
|
|
421
|
+
if (exec.agent?.session !== null && exec.agent?.session !== undefined) {
|
|
422
|
+
maybeAppendSessionEvent(exec.agent.session, SESSION_EVENTS.PUSH, {
|
|
423
|
+
sessionId: exec.agent.session.id,
|
|
424
|
+
ok: result.ok,
|
|
425
|
+
error: result.error,
|
|
426
|
+
pushed: result.pushed,
|
|
427
|
+
mirrored: result.mirrored,
|
|
428
|
+
deleted: result.deleted,
|
|
429
|
+
head: result.head,
|
|
430
|
+
}, deps.eventGate, (message) => deps.logger.warn(message))
|
|
431
|
+
}
|
|
432
|
+
return result
|
|
433
|
+
},
|
|
434
|
+
})
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* 向 fork 子会话注入冲突通知:说明远端版本已留存为 fork 文件、两边历史
|
|
439
|
+
* 都完整。通知是持久的 user/message(plugin source),派生历史会投影它。
|
|
440
|
+
* @param {import('@deepseek-ai/dsh-session').Session} child - fork 子会话。
|
|
441
|
+
* @param {string[]} forkPaths - 本会话相关 fork 文件路径。
|
|
442
|
+
* @param {string} parentId - 原会话 id。
|
|
443
|
+
*/
|
|
444
|
+
export function injectForkNotice(child, forkPaths, parentId) {
|
|
445
|
+
const text = [
|
|
446
|
+
'session-sync resolved a cross-device conflict by keeping both sides:',
|
|
447
|
+
`the local lineage of session ${parentId} continues here (this forked session);`,
|
|
448
|
+
'the remote version was preserved as fork file(s):',
|
|
449
|
+
...forkPaths.slice(0, 10).map(path => ` ${path}`),
|
|
450
|
+
forkPaths.length > 10 ? ` … ${forkPaths.length - 10} more` : '',
|
|
451
|
+
'Both histories are intact in the sync repository; nothing was overwritten.',
|
|
452
|
+
].filter(line => line.length > 0).join('\n')
|
|
453
|
+
try {
|
|
454
|
+
child.append('user/message', createUserMessage({
|
|
455
|
+
content: [{ type: 'text', text }],
|
|
456
|
+
source: { kind: 'plugin', plugin: PLUGIN_NAME, form: 'notice', summary: 'session-sync conflict fork' },
|
|
457
|
+
}), { surfaceOp: 'append' })
|
|
458
|
+
} catch (error) {
|
|
459
|
+
// 通知是锦上添花:append 失败绝不能把一次成功的拉取变成失败。
|
|
460
|
+
return
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* 插件挂载。enabled:false 时不注册任何东西;非法配置在加载期响亮抛错。
|
|
466
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx - Cordis 上下文。
|
|
467
|
+
* @param {Partial<Config>} [config] - 插件配置。
|
|
468
|
+
*/
|
|
469
|
+
export function apply(ctx, config = {}) {
|
|
470
|
+
const resolved = resolveConfig(config)
|
|
471
|
+
if (resolved.enabled === false) return
|
|
472
|
+
|
|
473
|
+
const logger = ctx.logger(PLUGIN_NAME)
|
|
474
|
+
const warn = (message) => logger.warn(message)
|
|
475
|
+
const eventGate = makeEventGate(KNOWN_SESSION_EVENT_TYPES, probeIgnorableAppend())
|
|
476
|
+
|
|
477
|
+
const sessionRoot = resolveSessionRoot(resolved.sessionRoot)
|
|
478
|
+
const repoDir = resolveRepoDir(resolved.repoDir)
|
|
479
|
+
assertNestingSafe(sessionRoot, repoDir)
|
|
480
|
+
|
|
481
|
+
// --- 同步元数据:ctx.storageDomain 领域 'session-sync'(异步打开,操作路径 await)。
|
|
482
|
+
/** @type {Promise<object>} 打开后的领域 state 表。 */
|
|
483
|
+
const tablePromise = ctx.storageDomain.open(sessionSyncDomainSpec).then((domain) => {
|
|
484
|
+
ctx.effect(() => () => { void domain.close() }, `${PLUGIN_NAME}.domain.close`)
|
|
485
|
+
return domain.table('state')
|
|
486
|
+
})
|
|
487
|
+
tablePromise.catch(() => {}) // 消费方各自处理拒绝;此处仅避免未处理拒绝告警。
|
|
488
|
+
|
|
489
|
+
/** @type {{deviceId: string, lastPullAt?: number, lastPushAt?: number, lastPushHead?: string, lastError?: string}|undefined} 元数据缓存。 */
|
|
490
|
+
let metaCache
|
|
491
|
+
let metaOps = Promise.resolve()
|
|
492
|
+
const withMeta = (fn) => {
|
|
493
|
+
const run = metaOps.then(fn, fn)
|
|
494
|
+
metaOps = run.then(() => undefined, () => undefined)
|
|
495
|
+
return run
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** 确保设备 id 已持久化并读入缓存。 */
|
|
499
|
+
async function ensureMeta() {
|
|
500
|
+
if (metaCache !== undefined) return metaCache
|
|
501
|
+
const table = await tablePromise
|
|
502
|
+
let state = await table.get(STATE_KEY)
|
|
503
|
+
if (state === undefined) {
|
|
504
|
+
state = { deviceId: randomUUID() }
|
|
505
|
+
await table.put(STATE_KEY, state)
|
|
506
|
+
}
|
|
507
|
+
metaCache = state
|
|
508
|
+
return state
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** 元数据补丁(引擎回调;串行写领域)。 */
|
|
512
|
+
function reportMeta(patch) {
|
|
513
|
+
void withMeta(async () => {
|
|
514
|
+
try {
|
|
515
|
+
const current = await ensureMeta()
|
|
516
|
+
const next = { ...current, ...patch }
|
|
517
|
+
const table = await tablePromise
|
|
518
|
+
await table.put(STATE_KEY, next)
|
|
519
|
+
metaCache = next
|
|
520
|
+
} catch (error) {
|
|
521
|
+
warn(`sync metadata write failed: ${messageOf(error)}`)
|
|
522
|
+
}
|
|
523
|
+
})
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** 最近错误(引擎回调;串行写领域)。 */
|
|
527
|
+
function reportError(message) {
|
|
528
|
+
reportMeta({ lastError: message.slice(0, 500) })
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// --- git 后端 + 引擎。
|
|
532
|
+
const git = new GitBackend({
|
|
533
|
+
repoDir,
|
|
534
|
+
remote: resolved.remote,
|
|
535
|
+
branch: resolved.branch,
|
|
536
|
+
commitName: resolved.commitName,
|
|
537
|
+
commitEmail: resolved.commitEmail,
|
|
538
|
+
run: makeRunGit(ctx.subprocess, {
|
|
539
|
+
gitBin: resolved.gitBin,
|
|
540
|
+
graceMs: resolved.graceMs,
|
|
541
|
+
commandTimeoutMs: resolved.commandTimeoutMs,
|
|
542
|
+
maxOutputBytes: resolved.maxOutputBytes,
|
|
543
|
+
}),
|
|
544
|
+
timeoutMs: resolved.commandTimeoutMs,
|
|
545
|
+
})
|
|
546
|
+
|
|
547
|
+
const engine = new SyncEngine({
|
|
548
|
+
git,
|
|
549
|
+
sessionRoot,
|
|
550
|
+
repoDir,
|
|
551
|
+
remote: resolved.remote,
|
|
552
|
+
branch: resolved.branch,
|
|
553
|
+
deviceId: 'pending',
|
|
554
|
+
reportMeta,
|
|
555
|
+
reportError,
|
|
556
|
+
logger,
|
|
557
|
+
onForks: (forkPaths) => handleForks(forkPaths),
|
|
558
|
+
})
|
|
559
|
+
// 设备 id 来自元数据领域;在领域就绪后补齐(fork 命名/设备文件用)。
|
|
560
|
+
void ensureMeta().then((meta) => {
|
|
561
|
+
engine.deviceId = meta.deviceId
|
|
562
|
+
}).catch(error => warn(`sync metadata open failed: ${messageOf(error)}`))
|
|
563
|
+
|
|
564
|
+
/** fork 文件产生回调:尝试把冲突会话在会话层面 fork(安全时)。 */
|
|
565
|
+
function handleForks(forkPaths) {
|
|
566
|
+
const bySession = new Map()
|
|
567
|
+
for (const forkPath of forkPaths) {
|
|
568
|
+
const parts = forkPath.split('/')
|
|
569
|
+
if (parts.length >= 2 && parts[0] === 'sessions') {
|
|
570
|
+
const list = bySession.get(parts[1]) ?? []
|
|
571
|
+
list.push(forkPath)
|
|
572
|
+
bySession.set(parts[1], list)
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
for (const [sessionId, paths] of bySession) {
|
|
576
|
+
const session = ctx.sessions.get(sessionId)
|
|
577
|
+
if (session === undefined) continue
|
|
578
|
+
maybeAppendSessionEvent(session, SESSION_EVENTS.CONFLICT, {
|
|
579
|
+
sessionId: session.id,
|
|
580
|
+
forkPaths: paths,
|
|
581
|
+
diverged: paths.length,
|
|
582
|
+
}, eventGate, warn)
|
|
583
|
+
if (hasOpenTurn(session.events)) {
|
|
584
|
+
logger.info(`sync conflict on live session ${sessionId}: turn open, session-level fork skipped (files preserved as forks)`)
|
|
585
|
+
continue
|
|
586
|
+
}
|
|
587
|
+
try {
|
|
588
|
+
const child = ctx.sessions.fork(session)
|
|
589
|
+
injectForkNotice(child, paths, session.id)
|
|
590
|
+
maybeAppendSessionEvent(session, SESSION_EVENTS.CONFLICT, {
|
|
591
|
+
sessionId: session.id,
|
|
592
|
+
forkPaths: paths,
|
|
593
|
+
childSessionId: child.id,
|
|
594
|
+
}, eventGate, warn)
|
|
595
|
+
logger.info(`sync conflict on session ${sessionId}: forked → ${child.id} (both lineages kept)`)
|
|
596
|
+
} catch (error) {
|
|
597
|
+
logger.warn(`sync conflict session fork failed for ${sessionId}: ${messageOf(error)} (fork files preserved)`)
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// --- /sync 命令(Consumer)。
|
|
603
|
+
if (resolved.registerCommand) {
|
|
604
|
+
ctx.commands.register({
|
|
605
|
+
name: COMMAND_NAME,
|
|
606
|
+
description: 'Cross-device session sync: status, pull/push the git mirror with keep-both conflict resolution, or diff against the last-fetched remote.',
|
|
607
|
+
input: { hint: '[status | pull | push | diff | log | help]' },
|
|
608
|
+
async handler(invocation) {
|
|
609
|
+
return handleSyncCommand(invocation)
|
|
610
|
+
},
|
|
611
|
+
})
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* /sync 命令处理器。
|
|
616
|
+
* @param {import('@deepseek-ai/dsh-commands').CommandInvocation} invocation - 命令调用。
|
|
617
|
+
* @returns {Promise<import('@deepseek-ai/dsh-commands').CommandResult>} 命令结果。
|
|
618
|
+
*/
|
|
619
|
+
async function handleSyncCommand(invocation) {
|
|
620
|
+
const { agent, rawInput, signal } = invocation
|
|
621
|
+
const session = agent?.session
|
|
622
|
+
const action = rawInput.trim().split(/\s+/u)[0]?.toLowerCase() || 'status'
|
|
623
|
+
try {
|
|
624
|
+
if (action === 'help' || (action !== 'status' && action !== 'pull' && action !== 'push' && action !== 'diff' && action !== 'log')) {
|
|
625
|
+
return {
|
|
626
|
+
kind: 'success',
|
|
627
|
+
text: [
|
|
628
|
+
'sync: usage — /sync [status | pull | push | diff | log | help]',
|
|
629
|
+
' status show mirror state (default): branch, remote, ahead/behind, dirty, forks',
|
|
630
|
+
' pull fetch + merge remote changes (keep-both; confirms first)',
|
|
631
|
+
' push mirror + commit + push local changes (confirms first)',
|
|
632
|
+
' diff uncommitted changes + HEAD..remote stat (read-only)',
|
|
633
|
+
' log last commits in the sync repository',
|
|
634
|
+
].join('\n'),
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
if (action === 'status') {
|
|
638
|
+
const status = await engine.status()
|
|
639
|
+
let meta = {}
|
|
640
|
+
try {
|
|
641
|
+
meta = await ensureMeta()
|
|
642
|
+
} catch {
|
|
643
|
+
// 元数据只读失败不阻断状态展示。
|
|
644
|
+
}
|
|
645
|
+
return { kind: status.ok ? 'success' : 'error', text: renderStatus({ ...status, lastPullAt: meta.lastPullAt, lastPushAt: meta.lastPushAt }) }
|
|
646
|
+
}
|
|
647
|
+
if (action === 'diff') {
|
|
648
|
+
const status = await engine.status()
|
|
649
|
+
return { kind: status.ok ? 'success' : 'error', text: renderDiff(status) }
|
|
650
|
+
}
|
|
651
|
+
if (action === 'log') {
|
|
652
|
+
const status = await engine.status()
|
|
653
|
+
const lines = status.lastCommits.length > 0 ? status.lastCommits : ['(no commits yet)']
|
|
654
|
+
return { kind: 'success', text: `sync: last commits in ${repoDir}:\n${lines.map(line => ` ${line}`).join('\n')}` }
|
|
655
|
+
}
|
|
656
|
+
// pull / push:覆盖性操作必须经确认门(无回答者失败关闭)。
|
|
657
|
+
const summary = action === 'push'
|
|
658
|
+
? 'Local session files will be mirrored, committed, and pushed to the sync remote (never force-pushed).'
|
|
659
|
+
: 'Remote session changes will be merged into the local mirror with keep-both semantics (local kept, remote preserved as fork files).'
|
|
660
|
+
const verdict = await confirmSync({ ctx, confirmVia: resolved.confirmVia, action, summary }, agent, signal)
|
|
661
|
+
if (!verdict.allowed) {
|
|
662
|
+
const reason = verdict.reason ?? 'no confirmation answerer (fail closed)'
|
|
663
|
+
logger.info(`sync ${action} denied (${verdict.channel}: ${reason})`)
|
|
664
|
+
return { kind: 'error', text: `sync: cancelled: ${reason}` }
|
|
665
|
+
}
|
|
666
|
+
if (action === 'push') {
|
|
667
|
+
const result = await engine.push({ signal })
|
|
668
|
+
if (session !== null && session !== undefined) {
|
|
669
|
+
maybeAppendSessionEvent(session, SESSION_EVENTS.PUSH, {
|
|
670
|
+
sessionId: session.id,
|
|
671
|
+
ok: result.ok,
|
|
672
|
+
error: result.error,
|
|
673
|
+
pushed: result.pushed,
|
|
674
|
+
mirrored: result.mirrored,
|
|
675
|
+
deleted: result.deleted,
|
|
676
|
+
head: result.head,
|
|
677
|
+
}, eventGate, warn)
|
|
678
|
+
}
|
|
679
|
+
return { kind: result.ok ? 'success' : 'error', text: renderPush(result) }
|
|
680
|
+
}
|
|
681
|
+
const result = await engine.pull({ signal })
|
|
682
|
+
if (session !== null && session !== undefined) {
|
|
683
|
+
maybeAppendSessionEvent(session, SESSION_EVENTS.PULL, {
|
|
684
|
+
sessionId: session.id,
|
|
685
|
+
ok: result.ok,
|
|
686
|
+
error: result.error,
|
|
687
|
+
pulled: result.pulled,
|
|
688
|
+
merged: result.merged,
|
|
689
|
+
adopted: result.adopted,
|
|
690
|
+
appended: result.appended,
|
|
691
|
+
diverged: result.diverged,
|
|
692
|
+
forks: result.forks,
|
|
693
|
+
head: result.head,
|
|
694
|
+
}, eventGate, warn)
|
|
695
|
+
}
|
|
696
|
+
return { kind: result.ok ? 'success' : 'error', text: renderPull(result) }
|
|
697
|
+
} catch (error) {
|
|
698
|
+
const message = `sync: ${action || 'status'} failed: ${messageOf(error)}`
|
|
699
|
+
logger.error(message)
|
|
700
|
+
return { kind: 'error', text: message }
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// --- sync_* 模型工具(Consumer;tools 服务存在时才注册,随 fiber 卸载撤销)。
|
|
705
|
+
if (resolved.registerTools) {
|
|
706
|
+
ctx.inject(['tools'], (toolCtx) => {
|
|
707
|
+
toolCtx.tools.register(makeSyncStatusTool(engine, ensureMeta))
|
|
708
|
+
toolCtx.tools.register(makeSyncPullTool({ engine, ctx, confirmVia: resolved.confirmVia, eventGate, logger }))
|
|
709
|
+
toolCtx.tools.register(makeSyncPushTool({ engine, ctx, confirmVia: resolved.confirmVia, eventGate, logger }))
|
|
710
|
+
})
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// --- 自动模式(全部 effect:事件/定时随插件卸载自动撤销)。
|
|
714
|
+
// 挂载时自动拉取(配置即授权;失败只记日志,绝不阻断启动)。
|
|
715
|
+
if (resolved.autoPullOnStart) {
|
|
716
|
+
ctx.effect(() => {
|
|
717
|
+
void engine.pull().then(result => {
|
|
718
|
+
if (!result.ok) warn(`auto pull failed: ${result.error ?? 'unknown error'}`)
|
|
719
|
+
})
|
|
720
|
+
return () => {}
|
|
721
|
+
}, `${PLUGIN_NAME}.auto-pull-on-start`)
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
// turn/end 自动推送(配置即授权;每轮结束拉一次快照并推送)。
|
|
725
|
+
if (resolved.autoPushOnTurnEnd) {
|
|
726
|
+
ctx.on('session/event', (session, event) => {
|
|
727
|
+
if (event.type !== 'turn/end') return
|
|
728
|
+
void engine.push().then(result => {
|
|
729
|
+
maybeAppendSessionEvent(session, SESSION_EVENTS.PUSH, {
|
|
730
|
+
sessionId: session.id,
|
|
731
|
+
ok: result.ok,
|
|
732
|
+
error: result.error,
|
|
733
|
+
pushed: result.pushed,
|
|
734
|
+
mirrored: result.mirrored,
|
|
735
|
+
deleted: result.deleted,
|
|
736
|
+
head: result.head,
|
|
737
|
+
}, eventGate, warn)
|
|
738
|
+
if (!result.ok) warn(`auto push failed: ${result.error ?? 'unknown error'}`)
|
|
739
|
+
})
|
|
740
|
+
})
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// 周期拉取(pullIntervalMinutes > 0 时;定时器随 fiber 自动撤销)。
|
|
744
|
+
if (resolved.pullIntervalMinutes > 0) {
|
|
745
|
+
ctx.effect(() => {
|
|
746
|
+
const timer = setInterval(() => {
|
|
747
|
+
void engine.pull().then(result => {
|
|
748
|
+
if (!result.ok) warn(`periodic pull failed: ${result.error ?? 'unknown error'}`)
|
|
749
|
+
})
|
|
750
|
+
}, resolved.pullIntervalMinutes * 60_000)
|
|
751
|
+
return () => clearInterval(timer)
|
|
752
|
+
}, `${PLUGIN_NAME}.periodic-pull`)
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
export {
|
|
757
|
+
// 复用/测试面:引擎、后端、纯函数与词汇。
|
|
758
|
+
GitBackend,
|
|
759
|
+
SyncEngine,
|
|
760
|
+
collectStatus,
|
|
761
|
+
renderStatus,
|
|
762
|
+
renderDiff,
|
|
763
|
+
renderPull,
|
|
764
|
+
renderPush,
|
|
765
|
+
confirmSync,
|
|
766
|
+
makeEventGate,
|
|
767
|
+
maybeAppendSessionEvent,
|
|
768
|
+
hasOpenTurn,
|
|
769
|
+
resolveSessionRoot,
|
|
770
|
+
resolveRepoDir,
|
|
771
|
+
assertNestingSafe,
|
|
772
|
+
sessionSyncDomainSpec,
|
|
773
|
+
registryUnavailable,
|
|
774
|
+
errorValue,
|
|
775
|
+
}
|