dsh-workbench-host 0.0.0-stage → 0.7.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/LICENSE +21 -0
- package/README.md +26 -2
- package/client/client.js +2177 -0
- package/cordis.patch.yml +5 -0
- package/lib/actions/action-output.js +25 -0
- package/lib/actions/actions.js +499 -0
- package/lib/actions/capabilities.js +299 -0
- package/lib/actions/task-targets.js +75 -0
- package/lib/core/db.d.ts +6 -0
- package/lib/core/db.js +72 -0
- package/lib/core/index.d.ts +4 -0
- package/lib/core/index.js +4 -0
- package/lib/core/repo.d.ts +43 -0
- package/lib/core/repo.js +116 -0
- package/lib/core/schema.d.ts +7 -0
- package/lib/core/schema.js +65 -0
- package/lib/index.js +411 -0
- package/lib/infra/audit.js +373 -0
- package/lib/infra/backup.js +263 -0
- package/lib/infra/network.js +466 -0
- package/lib/infra/search.js +83 -0
- package/lib/infra/zip.js +217 -0
- package/lib/sync/sync-conflicts.js +37 -0
- package/lib/sync/sync-incoming.js +56 -0
- package/lib/sync/sync-types.js +1 -0
- package/lib/sync/sync-values.js +22 -0
- package/lib/sync/sync.js +550 -0
- package/lib/types/host-types.js +1 -0
- package/package.json +61 -4
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import { renderTaskTarget } from "./task-targets.js";
|
|
2
|
+
export function createCapabilities({ domains, SHELL_VERSION, actionEntry, taskTargets }) {
|
|
3
|
+
function findDomain(raw) {
|
|
4
|
+
const key = String(raw ?? "").trim();
|
|
5
|
+
if (!key)
|
|
6
|
+
return null;
|
|
7
|
+
for (const rec of domains.values()) {
|
|
8
|
+
if (rec.def.id === key ||
|
|
9
|
+
rec.def.id === "wb-addon-" + key ||
|
|
10
|
+
rec.def.id.replace(/^wb-addon-/, "") === key) {
|
|
11
|
+
return rec;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
/** 归一化能力依赖:声明了 requires 却没装对应域时,能力清单必须说出来,否则 agent 会照描述传参。 */
|
|
17
|
+
function normalizeRequires(declared, warnings) {
|
|
18
|
+
const requires = [];
|
|
19
|
+
for (const raw of Array.isArray(declared?.requires) ? declared.requires : []) {
|
|
20
|
+
const id = String(raw ?? "").trim();
|
|
21
|
+
if (!id)
|
|
22
|
+
continue;
|
|
23
|
+
if (requires.indexOf(id) >= 0)
|
|
24
|
+
continue;
|
|
25
|
+
requires.push(id);
|
|
26
|
+
}
|
|
27
|
+
const missing = requires.filter((id) => !domains.has(id) && !domains.has("wb-addon-" + id));
|
|
28
|
+
if (missing.length) {
|
|
29
|
+
warnings.push("依赖未安装:" + missing.join("、") + ";相关参数(如 tagIds/tags)会报错,其余功能正常");
|
|
30
|
+
}
|
|
31
|
+
return { requires, missing };
|
|
32
|
+
}
|
|
33
|
+
/** 取业务域的能力清单;未声明时回退到域描述,保留 action 列表供 agent 自行判断。 */
|
|
34
|
+
function capabilityOf(rec) {
|
|
35
|
+
const declared = rec.def.capability;
|
|
36
|
+
if (!declared) {
|
|
37
|
+
return {
|
|
38
|
+
summary: rec.def.description ?? rec.def.title,
|
|
39
|
+
records: [],
|
|
40
|
+
notFor: [],
|
|
41
|
+
notes: [],
|
|
42
|
+
fields: [],
|
|
43
|
+
requires: [],
|
|
44
|
+
missingRequires: [],
|
|
45
|
+
source: "fallback",
|
|
46
|
+
warnings: [],
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
const warnings = [];
|
|
50
|
+
const seen = new Set();
|
|
51
|
+
const records = [];
|
|
52
|
+
for (const raw of Array.isArray(declared.records) ? declared.records : []) {
|
|
53
|
+
if (!raw || typeof raw !== "object")
|
|
54
|
+
continue;
|
|
55
|
+
const kind = String(raw.kind ?? "").trim();
|
|
56
|
+
if (!kind) {
|
|
57
|
+
warnings.push("存在缺少 kind 的记录声明,已忽略");
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (seen.has(kind)) {
|
|
61
|
+
warnings.push("记录类型重复:" + kind + "(只保留第一条)");
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
seen.add(kind);
|
|
65
|
+
const primaryAction = String(raw.primaryAction ?? "").trim();
|
|
66
|
+
if (!primaryAction) {
|
|
67
|
+
warnings.push(kind + ":缺少 primaryAction");
|
|
68
|
+
}
|
|
69
|
+
else if (!rec.actions.has(primaryAction)) {
|
|
70
|
+
warnings.push(kind + ":primaryAction 未注册:" + primaryAction);
|
|
71
|
+
}
|
|
72
|
+
records.push({
|
|
73
|
+
kind,
|
|
74
|
+
title: String(raw.title ?? kind),
|
|
75
|
+
description: String(raw.description ?? ""),
|
|
76
|
+
when: Array.isArray(raw.when)
|
|
77
|
+
? raw.when.filter((x) => typeof x === "string" && x.trim())
|
|
78
|
+
: [],
|
|
79
|
+
notFor: Array.isArray(raw.notFor) ? raw.notFor : [],
|
|
80
|
+
primaryAction,
|
|
81
|
+
keyArgs: Array.isArray(raw.keyArgs) ? raw.keyArgs : [],
|
|
82
|
+
dedupe: String(raw.dedupe ?? ""),
|
|
83
|
+
relations: Array.isArray(raw.relations) ? raw.relations : [],
|
|
84
|
+
examples: Array.isArray(raw.examples) ? raw.examples : [],
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
// 字段字典:agent 最容易踩的坑是「方向/枚举/默认值」看不见(例如把 priority 当成越小越紧急)。
|
|
88
|
+
const fields = [];
|
|
89
|
+
const fieldNames = new Set();
|
|
90
|
+
for (const raw of Array.isArray(declared.fields) ? declared.fields : []) {
|
|
91
|
+
if (!raw || typeof raw !== "object")
|
|
92
|
+
continue;
|
|
93
|
+
const name = String(raw.name ?? "").trim();
|
|
94
|
+
if (!name) {
|
|
95
|
+
warnings.push("存在缺少 name 的字段声明,已忽略");
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (fieldNames.has(name)) {
|
|
99
|
+
warnings.push("字段重复:" + name + "(只保留第一条)");
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
fieldNames.add(name);
|
|
103
|
+
fields.push({
|
|
104
|
+
name,
|
|
105
|
+
type: String(raw.type ?? ""),
|
|
106
|
+
description: String(raw.description ?? ""),
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
if (!fields.length) {
|
|
110
|
+
warnings.push("未声明字段字典(capability.fields);agent 只能看到字段名,容易误解方向与枚举");
|
|
111
|
+
}
|
|
112
|
+
const deps = normalizeRequires(declared, warnings);
|
|
113
|
+
return {
|
|
114
|
+
summary: String(declared.summary ?? "").trim() || rec.def.description || rec.def.title,
|
|
115
|
+
records,
|
|
116
|
+
notFor: Array.isArray(declared.notFor) ? declared.notFor : [],
|
|
117
|
+
notes: Array.isArray(declared.notes) ? declared.notes : [],
|
|
118
|
+
fields,
|
|
119
|
+
requires: deps.requires,
|
|
120
|
+
missingRequires: deps.missing,
|
|
121
|
+
source: "declared",
|
|
122
|
+
warnings,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/** capabilities.list:聚合各插件“记录什么、首选哪个 action”,给 agent 做统一发现。 */
|
|
126
|
+
async function capabilityListMeta(args) {
|
|
127
|
+
const kind = args.kind === undefined || args.kind === null ? "" : String(args.kind).trim();
|
|
128
|
+
const out = [];
|
|
129
|
+
for (const rec of domains.values()) {
|
|
130
|
+
const cap = capabilityOf(rec);
|
|
131
|
+
if (kind && !cap.records.some((r) => r.kind === kind))
|
|
132
|
+
continue;
|
|
133
|
+
out.push({
|
|
134
|
+
id: rec.def.id,
|
|
135
|
+
title: rec.def.title,
|
|
136
|
+
version: rec.def.version,
|
|
137
|
+
enabled: rec.error === null,
|
|
138
|
+
error: rec.error,
|
|
139
|
+
summary: cap.summary,
|
|
140
|
+
source: cap.source,
|
|
141
|
+
actionCount: rec.actions.size,
|
|
142
|
+
requires: cap.requires ?? [],
|
|
143
|
+
missingRequires: cap.missingRequires ?? [],
|
|
144
|
+
records: cap.records.map((r) => ({
|
|
145
|
+
kind: r.kind,
|
|
146
|
+
title: r.title,
|
|
147
|
+
description: r.description,
|
|
148
|
+
primaryAction: r.primaryAction,
|
|
149
|
+
})),
|
|
150
|
+
taskOwnership: await taskTargets.get(rec),
|
|
151
|
+
warnings: cap.warnings,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
return { shellVersion: SHELL_VERSION, kind, domains: out };
|
|
155
|
+
}
|
|
156
|
+
function renderCapabilityList(meta) {
|
|
157
|
+
const lines = [
|
|
158
|
+
"工作台 " + meta.shellVersion + " · " + meta.domains.length + " 个域" + (meta.kind ? "(kind=" + meta.kind + ")" : ""),
|
|
159
|
+
];
|
|
160
|
+
for (const d of meta.domains) {
|
|
161
|
+
lines.push("", "[" + d.id + "] " + d.title + " v" + d.version + (d.enabled ? "" : "(未启用:" + d.error + ")"));
|
|
162
|
+
lines.push(" " + d.summary);
|
|
163
|
+
if (d.taskOwnership)
|
|
164
|
+
lines.push(renderTaskTarget(d.taskOwnership));
|
|
165
|
+
if (!d.records.length) {
|
|
166
|
+
lines.push(" (未声明能力清单;可用 action 见 actions.list)");
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
for (const r of d.records) {
|
|
170
|
+
lines.push(" " + r.kind + " → " + r.primaryAction + ":" + r.description);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
for (const w of d.warnings ?? [])
|
|
174
|
+
lines.push(" ⚠ " + w);
|
|
175
|
+
}
|
|
176
|
+
lines.push("", '查看单个域的完整能力与 action 列表:Workbench({ action: "capabilities.get", args: { domain: "tasks" } })');
|
|
177
|
+
return lines.join("\n");
|
|
178
|
+
}
|
|
179
|
+
/** capabilities.get:单个业务域的完整能力清单 + action 摘要(字段细节仍走 actions.help)。 */
|
|
180
|
+
async function capabilityGetMeta(args) {
|
|
181
|
+
const name = String(args.domain ?? args.id ?? "").trim();
|
|
182
|
+
if (!name)
|
|
183
|
+
throw new Error("缺少 domain;先用 capabilities.list 查看可用业务域");
|
|
184
|
+
const rec = findDomain(name);
|
|
185
|
+
if (!rec)
|
|
186
|
+
throw new Error("没有该业务域:" + name + ";先用 capabilities.list 查看");
|
|
187
|
+
const cap = capabilityOf(rec);
|
|
188
|
+
return {
|
|
189
|
+
shellVersion: SHELL_VERSION,
|
|
190
|
+
domain: {
|
|
191
|
+
id: rec.def.id,
|
|
192
|
+
title: rec.def.title,
|
|
193
|
+
description: rec.def.description ?? "",
|
|
194
|
+
version: rec.def.version,
|
|
195
|
+
enabled: rec.error === null,
|
|
196
|
+
error: rec.error,
|
|
197
|
+
},
|
|
198
|
+
capability: {
|
|
199
|
+
summary: cap.summary,
|
|
200
|
+
taskOwnership: await taskTargets.get(rec),
|
|
201
|
+
records: cap.records,
|
|
202
|
+
notFor: cap.notFor,
|
|
203
|
+
notes: cap.notes,
|
|
204
|
+
fields: cap.fields ?? [],
|
|
205
|
+
requires: cap.requires ?? [],
|
|
206
|
+
missingRequires: cap.missingRequires ?? [],
|
|
207
|
+
},
|
|
208
|
+
source: cap.source,
|
|
209
|
+
actions: [...rec.actions].map(([action, def]) => actionEntry(action, rec.def.id, def)),
|
|
210
|
+
warnings: cap.warnings,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
function renderCapability(meta) {
|
|
214
|
+
const d = meta.domain;
|
|
215
|
+
const cap = meta.capability;
|
|
216
|
+
const lines = [
|
|
217
|
+
"[" + d.id + "] " + d.title + " v" + d.version + (d.enabled ? "" : "(未启用:" + d.error + ")"),
|
|
218
|
+
cap.summary,
|
|
219
|
+
];
|
|
220
|
+
if (cap.taskOwnership)
|
|
221
|
+
lines.push(renderTaskTarget(cap.taskOwnership));
|
|
222
|
+
if (Array.isArray(cap.requires) && cap.requires.length) {
|
|
223
|
+
const missing = Array.isArray(cap.missingRequires) ? cap.missingRequires : [];
|
|
224
|
+
lines.push("依赖:" +
|
|
225
|
+
cap.requires
|
|
226
|
+
.map((id) => id + (missing.indexOf(id) >= 0 ? "(未安装)" : ""))
|
|
227
|
+
.join("、"));
|
|
228
|
+
}
|
|
229
|
+
if (meta.source === "fallback") {
|
|
230
|
+
lines.push("", "该域未声明能力清单;以下 action 仍可直接调用。");
|
|
231
|
+
}
|
|
232
|
+
if (!cap.records.length) {
|
|
233
|
+
lines.push("", "记录类型:未声明");
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
lines.push("", "记录类型:");
|
|
237
|
+
for (const r of cap.records) {
|
|
238
|
+
lines.push("- " + r.kind + " · " + r.title + " → " + r.primaryAction);
|
|
239
|
+
if (r.description)
|
|
240
|
+
lines.push(" " + r.description);
|
|
241
|
+
if (r.when.length) {
|
|
242
|
+
lines.push(" 何时记录:");
|
|
243
|
+
for (const w of r.when)
|
|
244
|
+
lines.push(" - " + w);
|
|
245
|
+
}
|
|
246
|
+
if (r.notFor.length) {
|
|
247
|
+
lines.push(" 不要记录:");
|
|
248
|
+
for (const w of r.notFor)
|
|
249
|
+
lines.push(" - " + w);
|
|
250
|
+
}
|
|
251
|
+
if (r.keyArgs.length)
|
|
252
|
+
lines.push(" 常用参数:" + r.keyArgs.join(", "));
|
|
253
|
+
if (r.dedupe)
|
|
254
|
+
lines.push(" 去重:" + r.dedupe);
|
|
255
|
+
if (r.relations.length) {
|
|
256
|
+
lines.push(" 关系:");
|
|
257
|
+
for (const rel of r.relations) {
|
|
258
|
+
lines.push(" - " + rel.kind + " via " + rel.via + ":" + rel.description);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
if (r.examples.length) {
|
|
262
|
+
lines.push(" 示例:");
|
|
263
|
+
for (const ex of r.examples) {
|
|
264
|
+
const example = JSON.stringify({ action: r.primaryAction, args: ex.args ?? ex });
|
|
265
|
+
lines.push(" Workbench(" + example + ")" + (ex.purpose ? " // " + ex.purpose : ""));
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
if (cap.notFor.length) {
|
|
271
|
+
lines.push("", "这个域不适合:");
|
|
272
|
+
for (const w of cap.notFor)
|
|
273
|
+
lines.push(" - " + w);
|
|
274
|
+
}
|
|
275
|
+
if (cap.notes.length) {
|
|
276
|
+
lines.push("", "约束:");
|
|
277
|
+
for (const w of cap.notes)
|
|
278
|
+
lines.push(" - " + w);
|
|
279
|
+
}
|
|
280
|
+
const capFields = cap.fields ?? [];
|
|
281
|
+
if (capFields.length) {
|
|
282
|
+
lines.push("", "字段字典(方向/范围/默认值以此为准):");
|
|
283
|
+
for (const f of capFields) {
|
|
284
|
+
lines.push(" " + f.name + (f.type ? " · " + f.type : "") + (f.description ? " — " + f.description : ""));
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
lines.push("", "可用 action(" + meta.actions.length + "):");
|
|
288
|
+
for (const a of meta.actions)
|
|
289
|
+
lines.push(" " + a.name + (a.description ? " — " + a.description : ""));
|
|
290
|
+
lines.push("", '字段细节:Workbench({ action: "actions.help", args: { action: "<name>" } })');
|
|
291
|
+
if (meta.warnings.length) {
|
|
292
|
+
lines.push("", "⚠ 校验提示:");
|
|
293
|
+
for (const w of meta.warnings)
|
|
294
|
+
lines.push(" - " + w);
|
|
295
|
+
}
|
|
296
|
+
return lines.join("\n");
|
|
297
|
+
}
|
|
298
|
+
return { capabilityListMeta, renderCapabilityList, capabilityGetMeta, renderCapability };
|
|
299
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { getSyncStateText, setSyncStateText } from "../core/index.js";
|
|
2
|
+
import { actionErrorText } from "./action-output.js";
|
|
3
|
+
const PREFIX = "capability.taskTarget:";
|
|
4
|
+
/** Environment-local explicit mapping. No task schema or business rows are written here. */
|
|
5
|
+
export function createTaskTargets(db, domains, invoke) {
|
|
6
|
+
function domainOf(raw) {
|
|
7
|
+
const name = String(raw ?? "").trim();
|
|
8
|
+
const domain = domains.get(name) || domains.get("wb-addon-" + name);
|
|
9
|
+
if (!domain)
|
|
10
|
+
throw new Error("DOMAIN_NOT_FOUND:没有该业务域;先调用 capabilities.list");
|
|
11
|
+
return domain;
|
|
12
|
+
}
|
|
13
|
+
async function target(tableId) {
|
|
14
|
+
const tasks = domains.get("wb-addon-tasks");
|
|
15
|
+
if (!tasks || tasks.error || !tasks.actions.has("tasks.capabilities"))
|
|
16
|
+
throw new Error("TASKS_UNAVAILABLE:任务发现能力不可用");
|
|
17
|
+
const { result } = await invoke("tasks.capabilities", { tableId }, "agent");
|
|
18
|
+
const table = result?.tables?.find((t) => String(t.id) === tableId);
|
|
19
|
+
if (!table || !table.tablePath || !Array.isArray(table.pathSegments) || !table.pathSegments.length) {
|
|
20
|
+
throw new Error("TABLE_NOT_FOUND:目标表不存在或路径无效");
|
|
21
|
+
}
|
|
22
|
+
return table;
|
|
23
|
+
}
|
|
24
|
+
async function get(rec) {
|
|
25
|
+
const guidance = rec.def.capability?.taskOwnership;
|
|
26
|
+
const tableId = getSyncStateText(db, PREFIX + rec.def.id) || null;
|
|
27
|
+
const nextActions = [{ action: "tasks.resolveTable", args: { query: guidance?.query || rec.def.title } }];
|
|
28
|
+
const base = { boundary: guidance?.boundary || "业务记录使用本域 action;开发/修复工作项使用 tasks.create。一次性问答与临时查询不建任务。", nextActions,
|
|
29
|
+
configureAction: "capabilities.setTaskTarget", domain: rec.def.id };
|
|
30
|
+
if (!tableId)
|
|
31
|
+
return { ...base, configured: false, status: "unconfigured", message: "未配置任务归属;先 resolve 候选,由用户明确选择后配置。", tableId: null };
|
|
32
|
+
try {
|
|
33
|
+
const table = await target(tableId);
|
|
34
|
+
return { ...base, configured: true, status: "configured", tableId, path: table.path, tablePath: table.tablePath,
|
|
35
|
+
pathSegments: table.pathSegments, description: table.description, message: "显式配置优先;创建任务仍须传 tableId。" };
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
return { ...base, configured: false, status: "invalid", tableId: null, configuredTableId: tableId,
|
|
39
|
+
message: "未配置有效任务归属;原映射失效,不使用同名表替代。", reason: actionErrorText(error) };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const setAction = {
|
|
43
|
+
description: "显式保存 domain→任务 tableId 映射,仅配置开发工作项归属,不改变业务记录职责、不创建表、不移动任务。tableId=null 清除;目标必须是存活且完整路径的任务表。配置保存在本机宿主 storage,不随业务数据同步。",
|
|
44
|
+
input: { type: "object", properties: {
|
|
45
|
+
domain: { type: "string", description: "已安装域 id 或简称,如 storage" },
|
|
46
|
+
tableId: { type: ["string", "number", "null"], description: "tasks.capabilities/resolveTable 返回且经明确选择的目标表 id;null 清除配置" },
|
|
47
|
+
}, required: ["domain", "tableId"] },
|
|
48
|
+
examples: [{ domain: "storage", tableId: null }],
|
|
49
|
+
async execute(args) {
|
|
50
|
+
const rec = domainOf(args.domain);
|
|
51
|
+
if (!Object.prototype.hasOwnProperty.call(args, "tableId"))
|
|
52
|
+
throw new Error("TABLE_REQUIRED:必须显式提供 tableId;清除用 null");
|
|
53
|
+
if (args.tableId !== null) {
|
|
54
|
+
if (!["string", "number"].includes(typeof args.tableId) || !String(args.tableId).trim())
|
|
55
|
+
throw new Error("INVALID_TABLE_ID:tableId 必须是非空 string/number,清除用 null");
|
|
56
|
+
await target(String(args.tableId).trim());
|
|
57
|
+
}
|
|
58
|
+
setSyncStateText(db, PREFIX + rec.def.id, args.tableId === null ? "" : String(args.tableId).trim());
|
|
59
|
+
return get(rec);
|
|
60
|
+
},
|
|
61
|
+
render: (result) => renderTaskTarget(result),
|
|
62
|
+
};
|
|
63
|
+
return { get, setAction };
|
|
64
|
+
}
|
|
65
|
+
export function renderTaskTarget(value) {
|
|
66
|
+
const lines = ["任务归属指引:" + value.boundary, value.message];
|
|
67
|
+
if (value.configured)
|
|
68
|
+
lines.push("目标:" + (value.pathSegments || []).map((p) => p.name).join(" / ") + "(tableId=" + value.tableId + ");职责:" + (value.description || "未填写"));
|
|
69
|
+
if (value.reason)
|
|
70
|
+
lines.push("原因:" + value.reason);
|
|
71
|
+
for (const action of value.nextActions || [])
|
|
72
|
+
lines.push("下一步:Workbench(" + JSON.stringify(action) + ")");
|
|
73
|
+
lines.push("配置入口:capabilities.setTaskTarget({domain:" + JSON.stringify(value.domain) + ",tableId:<明确选择的表id>});null 可清除。");
|
|
74
|
+
return lines.join("\n");
|
|
75
|
+
}
|
package/lib/core/db.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
/** 打开(或创建)工作台本地库并跑基线 schema。单进程权威,WAL。 */
|
|
3
|
+
export declare function openDb(file: string): DatabaseSync;
|
|
4
|
+
/** UUIDv7:时间有序主键。demo 简化实现(48bit ms + rand)。 */
|
|
5
|
+
export declare function uuidv7(): string;
|
|
6
|
+
export declare function monoNow(): number;
|
package/lib/core/db.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import { mkdirSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { SCHEMA_SQL } from "./schema.js";
|
|
5
|
+
function hasColumn(db, table, column) {
|
|
6
|
+
try {
|
|
7
|
+
const rows = db.prepare("PRAGMA table_info(" + table + ")").all();
|
|
8
|
+
return rows.some((row) => row.name === column);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** 旧库增量迁移(CREATE TABLE IF NOT EXISTS 不会补列)。 */
|
|
15
|
+
function migrateLocalDb(db) {
|
|
16
|
+
db.exec("BEGIN IMMEDIATE");
|
|
17
|
+
try {
|
|
18
|
+
if (!hasColumn(db, "conflict_shadow", "kind")) {
|
|
19
|
+
db.exec("ALTER TABLE conflict_shadow ADD COLUMN kind TEXT NOT NULL DEFAULT 'pull'");
|
|
20
|
+
}
|
|
21
|
+
if (!hasColumn(db, "conflict_shadow", "resolution")) {
|
|
22
|
+
db.exec("ALTER TABLE conflict_shadow ADD COLUMN resolution TEXT NOT NULL DEFAULT 'server'");
|
|
23
|
+
}
|
|
24
|
+
if (!hasColumn(db, "conflict_shadow", "server_updated_at")) {
|
|
25
|
+
db.exec("ALTER TABLE conflict_shadow ADD COLUMN server_updated_at INTEGER");
|
|
26
|
+
}
|
|
27
|
+
if (!hasColumn(db, "conflict_shadow", "local_updated_at")) {
|
|
28
|
+
db.exec("ALTER TABLE conflict_shadow ADD COLUMN local_updated_at INTEGER");
|
|
29
|
+
}
|
|
30
|
+
db.exec("COMMIT");
|
|
31
|
+
}
|
|
32
|
+
catch (e) {
|
|
33
|
+
try {
|
|
34
|
+
db.exec("ROLLBACK");
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
/* ignore */
|
|
38
|
+
}
|
|
39
|
+
throw e;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** 打开(或创建)工作台本地库并跑基线 schema。单进程权威,WAL。 */
|
|
43
|
+
export function openDb(file) {
|
|
44
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
45
|
+
const db = new DatabaseSync(file);
|
|
46
|
+
db.exec(SCHEMA_SQL);
|
|
47
|
+
migrateLocalDb(db);
|
|
48
|
+
return db;
|
|
49
|
+
}
|
|
50
|
+
/** UUIDv7:时间有序主键。demo 简化实现(48bit ms + rand)。 */
|
|
51
|
+
export function uuidv7() {
|
|
52
|
+
const bytes = new Uint8Array(16);
|
|
53
|
+
crypto.getRandomValues(bytes);
|
|
54
|
+
const ms = Date.now();
|
|
55
|
+
bytes[0] = (ms / 2 ** 40) & 0xff;
|
|
56
|
+
bytes[1] = (ms / 2 ** 32) & 0xff;
|
|
57
|
+
bytes[2] = (ms / 2 ** 24) & 0xff;
|
|
58
|
+
bytes[3] = (ms / 2 ** 16) & 0xff;
|
|
59
|
+
bytes[4] = (ms / 2 ** 8) & 0xff;
|
|
60
|
+
bytes[5] = ms & 0xff;
|
|
61
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x70;
|
|
62
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
63
|
+
const h = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
64
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
65
|
+
}
|
|
66
|
+
/** 单调化时间戳:防时钟回拨导致的乱序覆盖(07 失败模式清单)。 */
|
|
67
|
+
let lastTs = 0;
|
|
68
|
+
export function monoNow() {
|
|
69
|
+
const wall = Date.now();
|
|
70
|
+
lastTs = Math.max(wall, lastTs + 1);
|
|
71
|
+
return lastTs;
|
|
72
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { DatabaseSync } from "node:sqlite";
|
|
2
|
+
/** 变更来源:ui/agent 本地写要进 change log;sync 回写不进(循环防护,05 文档)。 */
|
|
3
|
+
export type WriteOrigin = "ui" | "agent" | "sync";
|
|
4
|
+
/**
|
|
5
|
+
* 平台同步层:只做「表无关」的事情。
|
|
6
|
+
* 具体业务(任务增删改查)属于子插件,壳不 import、不硬编码。
|
|
7
|
+
*/
|
|
8
|
+
declare function tableExists(db: DatabaseSync, tableName: string): boolean;
|
|
9
|
+
export declare function writeConflict(db: DatabaseSync, tableName: string, rowId: string, kind: string, resolution: string, local: Record<string, unknown> | null, server: Record<string, unknown> | null, serverUpdatedAt: number | null, localUpdatedAt: number | null): void;
|
|
10
|
+
/**
|
|
11
|
+
* 应用一条远端 upsert(pull 路径):严格行级 LWW。
|
|
12
|
+
* - 本地 updated_at 更大:保留本地,写 conflict_shadow;
|
|
13
|
+
* - 相等:payload 相同则幂等,不同则以服务端为准并写 shadow;
|
|
14
|
+
* - 远端更大:整行替换。
|
|
15
|
+
* 表不存在(对应插件未安装)时直接跳过:数据仍在云端,安装后 snapshot 补回。
|
|
16
|
+
*/
|
|
17
|
+
export declare function applyRemoteUpsert(db: DatabaseSync, tableName: string, remote: Record<string, unknown>, serverUpdatedAt: number): boolean;
|
|
18
|
+
/**
|
|
19
|
+
* 应用一条远端墓碑。v2 的 delete 事件带完整行 payload,走同一套 LWW;
|
|
20
|
+
* 旧协议没有 payload 时退化为本地打墓碑(仍用远端事件时间,而不是本机时间)。
|
|
21
|
+
*/
|
|
22
|
+
export declare function applyRemoteDelete(db: DatabaseSync, tableName: string, rowId: string, remote?: Record<string, unknown> | null, serverUpdatedAt?: number): boolean;
|
|
23
|
+
/** 记录一条死信(单行/单表失败,不阻塞其他表)。 */
|
|
24
|
+
export declare function recordDeadLetter(db: DatabaseSync, tableName: string, rowId: string, op: string, payload: string | null, error: string): void;
|
|
25
|
+
/** 读取待推送的变更尾部(seq > afterSeq),按 seq 升序。 */
|
|
26
|
+
export declare function pendingChanges(db: DatabaseSync, afterSeq: number, limit?: number): {
|
|
27
|
+
seq: number;
|
|
28
|
+
table_name: string;
|
|
29
|
+
row_id: string;
|
|
30
|
+
op: string;
|
|
31
|
+
payload: string | null;
|
|
32
|
+
origin: string;
|
|
33
|
+
updated_at: number;
|
|
34
|
+
}[];
|
|
35
|
+
/** 记录已同步水位(数字;v1 兼容)。 */
|
|
36
|
+
export declare function setSyncState(db: DatabaseSync, key: string, value: number): void;
|
|
37
|
+
export declare function getSyncState(db: DatabaseSync, key: string): number;
|
|
38
|
+
/** 文本水位:账号 id / epoch / 时间戳等统一入口。 */
|
|
39
|
+
export declare function setSyncStateText(db: DatabaseSync, key: string, value: string): void;
|
|
40
|
+
export declare function getSyncStateText(db: DatabaseSync, key: string): string;
|
|
41
|
+
export declare function deleteSyncState(db: DatabaseSync, key: string): void;
|
|
42
|
+
/** 供子插件宿主 API 复用:判断表是否存在。 */
|
|
43
|
+
export { tableExists };
|
package/lib/core/repo.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { monoNow } from "./db.js";
|
|
2
|
+
/**
|
|
3
|
+
* 平台同步层:只做「表无关」的事情。
|
|
4
|
+
* 具体业务(任务增删改查)属于子插件,壳不 import、不硬编码。
|
|
5
|
+
*/
|
|
6
|
+
function tableExists(db, tableName) {
|
|
7
|
+
return Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(tableName));
|
|
8
|
+
}
|
|
9
|
+
function stableStringify(value) {
|
|
10
|
+
if (value === null)
|
|
11
|
+
return "null";
|
|
12
|
+
if (Array.isArray(value))
|
|
13
|
+
return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
|
|
14
|
+
if (typeof value === "object") {
|
|
15
|
+
const obj = value;
|
|
16
|
+
return "{" + Object.keys(obj).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k])).join(",") + "}";
|
|
17
|
+
}
|
|
18
|
+
return JSON.stringify(value);
|
|
19
|
+
}
|
|
20
|
+
export function writeConflict(db, tableName, rowId, kind, resolution, local, server, serverUpdatedAt, localUpdatedAt) {
|
|
21
|
+
db.prepare("INSERT INTO conflict_shadow(table_name,row_id,kind,resolution,local_payload,server_payload,server_updated_at,local_updated_at,resolved_at) " +
|
|
22
|
+
"VALUES(?,?,?,?,?,?,?,?,?)").run(tableName, rowId, kind, resolution, local ? JSON.stringify(local) : null, server ? JSON.stringify(server) : null, serverUpdatedAt, localUpdatedAt, monoNow());
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* 应用一条远端 upsert(pull 路径):严格行级 LWW。
|
|
26
|
+
* - 本地 updated_at 更大:保留本地,写 conflict_shadow;
|
|
27
|
+
* - 相等:payload 相同则幂等,不同则以服务端为准并写 shadow;
|
|
28
|
+
* - 远端更大:整行替换。
|
|
29
|
+
* 表不存在(对应插件未安装)时直接跳过:数据仍在云端,安装后 snapshot 补回。
|
|
30
|
+
*/
|
|
31
|
+
export function applyRemoteUpsert(db, tableName, remote, serverUpdatedAt) {
|
|
32
|
+
if (!tableExists(db, tableName))
|
|
33
|
+
return false;
|
|
34
|
+
const rowId = String(remote.id ?? "");
|
|
35
|
+
if (!rowId)
|
|
36
|
+
return false;
|
|
37
|
+
const cur = db.prepare("SELECT * FROM " + tableName + " WHERE id=?").get(rowId);
|
|
38
|
+
if (cur) {
|
|
39
|
+
const localUpdatedAt = Number(cur.updated_at) || 0;
|
|
40
|
+
if (localUpdatedAt > serverUpdatedAt) {
|
|
41
|
+
writeConflict(db, tableName, rowId, "pull", "local", cur, remote, serverUpdatedAt, localUpdatedAt);
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
if (localUpdatedAt === serverUpdatedAt && stableStringify(cur) !== stableStringify(remote)) {
|
|
45
|
+
writeConflict(db, tableName, rowId, "pull-equal", "server", cur, remote, serverUpdatedAt, localUpdatedAt);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const cols = Object.keys(remote);
|
|
49
|
+
// 通用整行替换:先删后插保证列集合与服务端一致(列由业务插件建表,同步方不感知)。
|
|
50
|
+
db.exec("SAVEPOINT core_remote_row");
|
|
51
|
+
try {
|
|
52
|
+
db.prepare("DELETE FROM " + tableName + " WHERE id=?").run(rowId);
|
|
53
|
+
const placeholders = cols.map(() => "?").join(",");
|
|
54
|
+
db.prepare("INSERT INTO " + tableName + " (" + cols.join(",") + ") VALUES(" + placeholders + ")").run(...cols.map((c) => remote[c]));
|
|
55
|
+
db.exec("RELEASE core_remote_row");
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
db.exec("ROLLBACK TO core_remote_row; RELEASE core_remote_row");
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* 应用一条远端墓碑。v2 的 delete 事件带完整行 payload,走同一套 LWW;
|
|
65
|
+
* 旧协议没有 payload 时退化为本地打墓碑(仍用远端事件时间,而不是本机时间)。
|
|
66
|
+
*/
|
|
67
|
+
export function applyRemoteDelete(db, tableName, rowId, remote, serverUpdatedAt) {
|
|
68
|
+
if (!tableExists(db, tableName))
|
|
69
|
+
return false;
|
|
70
|
+
if (remote && remote.id !== undefined) {
|
|
71
|
+
return applyRemoteUpsert(db, tableName, remote, Number(serverUpdatedAt ?? remote.updated_at ?? Date.now()));
|
|
72
|
+
}
|
|
73
|
+
const ts = Number(serverUpdatedAt ?? Date.now());
|
|
74
|
+
db.prepare("UPDATE " + tableName + " SET deleted_at=?, updated_at=? WHERE id=? AND updated_at<=?").run(ts, ts, rowId, ts);
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
/** 记录一条死信(单行/单表失败,不阻塞其他表)。 */
|
|
78
|
+
export function recordDeadLetter(db, tableName, rowId, op, payload, error) {
|
|
79
|
+
const now = monoNow();
|
|
80
|
+
const existing = db
|
|
81
|
+
.prepare("SELECT id,attempts FROM sync_dead_letter WHERE table_name=? AND row_id=? AND op=?")
|
|
82
|
+
.get(tableName, rowId, op);
|
|
83
|
+
if (existing) {
|
|
84
|
+
db.prepare("UPDATE sync_dead_letter SET payload=?,error=?,attempts=?,updated_at=? WHERE id=?").run(payload, error, existing.attempts + 1, now, existing.id);
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
db.prepare("INSERT INTO sync_dead_letter(table_name,row_id,op,payload,error,attempts,created_at,updated_at) VALUES(?,?,?,?,?,1,?,?)").run(tableName, rowId, op, payload, error, now, now);
|
|
88
|
+
}
|
|
89
|
+
db.exec("DELETE FROM sync_dead_letter WHERE id NOT IN (SELECT id FROM sync_dead_letter ORDER BY id DESC LIMIT 1000)");
|
|
90
|
+
}
|
|
91
|
+
/** 读取待推送的变更尾部(seq > afterSeq),按 seq 升序。 */
|
|
92
|
+
export function pendingChanges(db, afterSeq, limit = 200) {
|
|
93
|
+
return db.prepare("SELECT * FROM sync_change_log WHERE seq>? ORDER BY seq ASC LIMIT ?").all(afterSeq, limit);
|
|
94
|
+
}
|
|
95
|
+
/** 记录已同步水位(数字;v1 兼容)。 */
|
|
96
|
+
export function setSyncState(db, key, value) {
|
|
97
|
+
setSyncStateText(db, key, String(value));
|
|
98
|
+
}
|
|
99
|
+
export function getSyncState(db, key) {
|
|
100
|
+
const raw = getSyncStateText(db, key);
|
|
101
|
+
const n = Number(raw);
|
|
102
|
+
return Number.isFinite(n) ? n : 0;
|
|
103
|
+
}
|
|
104
|
+
/** 文本水位:账号 id / epoch / 时间戳等统一入口。 */
|
|
105
|
+
export function setSyncStateText(db, key, value) {
|
|
106
|
+
db.prepare("INSERT INTO sync_state(k,v) VALUES(?,?) ON CONFLICT(k) DO UPDATE SET v=excluded.v").run(key, value);
|
|
107
|
+
}
|
|
108
|
+
export function getSyncStateText(db, key) {
|
|
109
|
+
const row = db.prepare("SELECT v FROM sync_state WHERE k=?").get(key);
|
|
110
|
+
return row && row.v !== null && row.v !== undefined ? String(row.v) : "";
|
|
111
|
+
}
|
|
112
|
+
export function deleteSyncState(db, key) {
|
|
113
|
+
db.prepare("DELETE FROM sync_state WHERE k=?").run(key);
|
|
114
|
+
}
|
|
115
|
+
/** 供子插件宿主 API 复用:判断表是否存在。 */
|
|
116
|
+
export { tableExists };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 工作台本地库 schema(平台级表)。
|
|
3
|
+
*
|
|
4
|
+
* 业务表(task / tag / site 等)不在这里:它们由子插件的 migrations 创建/演进,
|
|
5
|
+
* 壳本身不感知任何具体业务。这样「任务记录」才能真正装/卸。
|
|
6
|
+
*/
|
|
7
|
+
export declare const SCHEMA_SQL = "\nPRAGMA journal_mode=WAL;\n\nCREATE TABLE IF NOT EXISTS meta (\n k TEXT PRIMARY KEY, v TEXT NOT NULL\n);\n\n-- \u901A\u7528\u53D8\u66F4\u65E5\u5FD7\uFF1A\u5199\u4E8B\u52A1\u5185\u8FFD\u52A0\uFF1B\u672A\u63A8\u9001\u5C3E\u90E8\u5373\u5F85\u540C\u6B65\u961F\u5217\nCREATE TABLE IF NOT EXISTS sync_change_log (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n table_name TEXT NOT NULL,\n row_id TEXT NOT NULL,\n op TEXT NOT NULL,\n payload TEXT,\n origin TEXT NOT NULL,\n updated_at INTEGER NOT NULL\n);\n\n-- \u51B2\u7A81\u5C55\u793A\uFF08LWW \u8F93\u65B9\u7684\u7248\u672C\u7559\u6863\uFF0C\u7EDD\u4E0D\u9759\u9ED8\u541E\u6570\u636E\uFF09\nCREATE TABLE IF NOT EXISTS conflict_shadow (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n table_name TEXT NOT NULL,\n row_id TEXT NOT NULL,\n kind TEXT NOT NULL DEFAULT 'pull',\n resolution TEXT NOT NULL DEFAULT 'server',\n local_payload TEXT,\n server_payload TEXT,\n server_updated_at INTEGER,\n local_updated_at INTEGER,\n resolved_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_conflict_resolved ON conflict_shadow(resolved_at);\n\n-- \u5355\u884C/\u5355\u8868\u8FDE\u7EED\u5931\u8D25\u7684\u6B7B\u4FE1\uFF1B\u4E0D\u963B\u585E\u5176\u4ED6\u8868\u540C\u6B65\nCREATE TABLE IF NOT EXISTS sync_dead_letter (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n table_name TEXT NOT NULL,\n row_id TEXT NOT NULL,\n op TEXT NOT NULL,\n payload TEXT,\n error TEXT NOT NULL,\n attempts INTEGER NOT NULL DEFAULT 1,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_dead_letter_table ON sync_dead_letter(table_name, row_id);\n\n-- \u540C\u6B65\u6C34\u4F4D/\u8D26\u53F7\u7ED1\u5B9A/\u65F6\u949F/\u6700\u540E\u72B6\u6001\u3002v \u7528 TEXT \u5B58\u50A8\uFF0C\u517C\u5BB9\u65E7\u5E93\u7684 INTEGER \u4EB2\u548C\u6027\u3002\nCREATE TABLE IF NOT EXISTS sync_state (\n k TEXT PRIMARY KEY, v TEXT NOT NULL\n);\n\n-- \u4F1A\u8BDD\u7EA7\u8BB0\u5F55\u6A21\u5F0F\uFF1A\u53EA\u5F71\u54CD\u672C\u673A\u5F53\u524D\u4F1A\u8BDD\uFF0C\u4E0D\u53C2\u4E0E\u540C\u6B65/\u5907\u4EFD\u3002\nCREATE TABLE IF NOT EXISTS session_mode (\n session_id TEXT PRIMARY KEY,\n enabled INTEGER NOT NULL DEFAULT 0,\n updated_at INTEGER NOT NULL\n);\n";
|