@morozinc/opencode-tencentdb-plugin 0.0.0-stage → 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/LICENSE +661 -0
- package/LICENSE-MIT +24 -0
- package/NOTICE.md +14 -0
- package/README.md +207 -2
- package/dist/gui-experimental.cjs +64 -0
- package/dist/integration.mjs +1986 -0
- package/docs/screenshots/code-indexes.png +0 -0
- package/package.json +61 -4
- package/scripts/prepare-runtime.mjs +298 -0
- package/src/binding.ts +33 -0
- package/src/bmad-artifact-preview.tsx +111 -0
- package/src/embedding-settings.tsx +191 -0
- package/src/gui.tsx +388 -0
- package/src/index.ts +484 -0
- package/src/integration.d.ts +75 -0
- package/src/rpc.ts +195 -0
- package/src/rule-document.ts +44 -0
- package/src/rules-contract.ts +77 -0
- package/src/rules.ts +237 -0
- package/src/runtime.ts +436 -0
- package/vendor/TENCENT-LICENSE +27 -0
- package/vendor/integration/native/config.ts +253 -0
- package/vendor/integration/native/embedding.ts +270 -0
- package/vendor/integration/native/index.ts +265 -0
- package/vendor/integration/project/index.ts +151 -0
- package/vendor/integration/project/knowledge.ts +283 -0
- package/vendor/integration/server.ts +154 -0
- package/vendor/integration/tencentChatRules.ts +84 -0
- package/vendor/integration/tencentGenerationContext.ts +4 -0
- package/vendor/integration/tencentKnowledgeClient.ts +512 -0
- package/vendor/integration/tencentMemoryClient.ts +391 -0
- package/vendor/integration/tencentUserQuestion.ts +51 -0
- package/vendor/locks/MemoryCore.json +4776 -0
- package/vendor/locks/MemoryKnowledge.json +3761 -0
- package/vendor/locks/MemoryPanel.json +467 -0
- package/vendor/locks/web.json +6418 -0
- package/vendor/provenance.json +21 -0
- package/vendor/runner.mjs +12 -0
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
copyFileSync,
|
|
4
|
+
existsSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
readFileSync,
|
|
7
|
+
renameSync,
|
|
8
|
+
rmSync,
|
|
9
|
+
writeFileSync,
|
|
10
|
+
} from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
|
|
13
|
+
export function savePrivate(file: string, value: unknown): void {
|
|
14
|
+
mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
15
|
+
const temporary = `${file}.tmp`;
|
|
16
|
+
writeFileSync(
|
|
17
|
+
temporary,
|
|
18
|
+
typeof value === "string" ? value : JSON.stringify(value, null, 2),
|
|
19
|
+
{ mode: 0o600 },
|
|
20
|
+
);
|
|
21
|
+
renameSync(temporary, file);
|
|
22
|
+
}
|
|
23
|
+
export function readJson<T>(file: string, fallback: T): T {
|
|
24
|
+
return existsSync(file)
|
|
25
|
+
? (JSON.parse(readFileSync(file, "utf8")) as T)
|
|
26
|
+
: fallback;
|
|
27
|
+
}
|
|
28
|
+
export function nativeConfig(userData: string) {
|
|
29
|
+
const root = path.join(userData, "tencentdb");
|
|
30
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
31
|
+
const secretsFile = path.join(root, "runtime-secrets.json");
|
|
32
|
+
const secrets = readJson(secretsFile, {
|
|
33
|
+
gateway: randomBytes(32).toString("hex"),
|
|
34
|
+
knowledge: randomBytes(32).toString("hex"),
|
|
35
|
+
});
|
|
36
|
+
if (!existsSync(secretsFile)) savePrivate(secretsFile, secrets);
|
|
37
|
+
const settingsFile = path.join(root, "runtime-settings.json");
|
|
38
|
+
const settings = readJson(settingsFile, {
|
|
39
|
+
corePort: 8420,
|
|
40
|
+
knowledgePort: 8424,
|
|
41
|
+
panelPort: 8125,
|
|
42
|
+
embedding: {
|
|
43
|
+
provider: "openai",
|
|
44
|
+
baseUrl: "http://127.0.0.1:11434/v1",
|
|
45
|
+
apiKey: "ollama",
|
|
46
|
+
model: "bge-m3",
|
|
47
|
+
dimensions: 1024,
|
|
48
|
+
sendDimensions: false,
|
|
49
|
+
maxInputChars: 8192,
|
|
50
|
+
timeoutMs: 60000,
|
|
51
|
+
},
|
|
52
|
+
knowledgeWorkspaces: [] as Array<{ hostPath: string; servicePath: string }>,
|
|
53
|
+
});
|
|
54
|
+
for (const port of [
|
|
55
|
+
settings.corePort,
|
|
56
|
+
settings.knowledgePort,
|
|
57
|
+
settings.panelPort,
|
|
58
|
+
]) {
|
|
59
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65535)
|
|
60
|
+
throw new Error("Invalid local memory port");
|
|
61
|
+
}
|
|
62
|
+
if (!existsSync(settingsFile)) savePrivate(settingsFile, settings);
|
|
63
|
+
const coreUrl = `http://127.0.0.1:${settings.corePort}`;
|
|
64
|
+
const knowledgeUrl = `http://127.0.0.1:${settings.knowledgePort}`;
|
|
65
|
+
const panelUrl = `http://127.0.0.1:${settings.panelPort}`;
|
|
66
|
+
const gatewayFile = path.join(root, "gateway.json");
|
|
67
|
+
savePrivate(gatewayFile, {
|
|
68
|
+
deployMode: "standalone",
|
|
69
|
+
stateBackend: "local",
|
|
70
|
+
server: { host: "127.0.0.1", port: settings.corePort },
|
|
71
|
+
data: { baseDir: path.join(root, "core") },
|
|
72
|
+
llm: { maxTokens: 32000, timeoutMs: 300000 },
|
|
73
|
+
memory: {
|
|
74
|
+
promptMode: "code",
|
|
75
|
+
capture: { enabled: true },
|
|
76
|
+
extraction: {
|
|
77
|
+
enabled: true,
|
|
78
|
+
enableDedup: true,
|
|
79
|
+
maxMemoriesPerSession: 20,
|
|
80
|
+
},
|
|
81
|
+
persona: { triggerEveryN: 50, maxScenes: 15 },
|
|
82
|
+
pipeline: {
|
|
83
|
+
everyNConversations: 5,
|
|
84
|
+
enableWarmup: true,
|
|
85
|
+
l1IdleTimeoutSeconds: 600,
|
|
86
|
+
l2DelayAfterL1Seconds: 90,
|
|
87
|
+
l2MinIntervalSeconds: 900,
|
|
88
|
+
l2MaxIntervalSeconds: 3600,
|
|
89
|
+
},
|
|
90
|
+
recall: {
|
|
91
|
+
enabled: true,
|
|
92
|
+
maxResults: 5,
|
|
93
|
+
scoreThreshold: 0.3,
|
|
94
|
+
strategy: "hybrid",
|
|
95
|
+
timeoutMs: 5000,
|
|
96
|
+
},
|
|
97
|
+
storeBackend: "sqlite",
|
|
98
|
+
embedding: settings.embedding,
|
|
99
|
+
},
|
|
100
|
+
skill: { enabled: true, routing: { mode: "bm25", searchTopK: 20 } },
|
|
101
|
+
});
|
|
102
|
+
const instancesFile = path.join(root, "instances.json");
|
|
103
|
+
savePrivate(instancesFile, {
|
|
104
|
+
instances: [
|
|
105
|
+
{
|
|
106
|
+
id: "default",
|
|
107
|
+
name: "OpenCode",
|
|
108
|
+
gateway_endpoint: coreUrl,
|
|
109
|
+
api_key: secrets.gateway,
|
|
110
|
+
},
|
|
111
|
+
],
|
|
112
|
+
});
|
|
113
|
+
return {
|
|
114
|
+
root,
|
|
115
|
+
settings,
|
|
116
|
+
secrets,
|
|
117
|
+
coreUrl,
|
|
118
|
+
knowledgeUrl,
|
|
119
|
+
panelUrl,
|
|
120
|
+
gatewayFile,
|
|
121
|
+
instancesFile,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Provision once; on updates reuse and verify existing credentials and identity. */
|
|
126
|
+
export async function provision(
|
|
127
|
+
config: ReturnType<typeof nativeConfig>,
|
|
128
|
+
): Promise<string> {
|
|
129
|
+
const { root, coreUrl, knowledgeUrl, secrets, settings } = config;
|
|
130
|
+
const request = async (
|
|
131
|
+
route: string,
|
|
132
|
+
body: Record<string, unknown>,
|
|
133
|
+
key?: string,
|
|
134
|
+
) => {
|
|
135
|
+
const response = await fetch(`${coreUrl}/v3/${route}`, {
|
|
136
|
+
method: "POST",
|
|
137
|
+
headers: {
|
|
138
|
+
"Content-Type": "application/json",
|
|
139
|
+
"x-tdai-service-id": "default",
|
|
140
|
+
Authorization: `Bearer ${secrets.gateway}`,
|
|
141
|
+
...(key ? { "x-tdai-user-key": key } : {}),
|
|
142
|
+
},
|
|
143
|
+
body: JSON.stringify(body),
|
|
144
|
+
signal: AbortSignal.timeout(15000),
|
|
145
|
+
});
|
|
146
|
+
if (route === "internal/meta/user/init-admin" && response.status === 409)
|
|
147
|
+
return {};
|
|
148
|
+
if (!response.ok)
|
|
149
|
+
throw new Error(`Local memory ${route}: HTTP ${response.status}`);
|
|
150
|
+
const result = await response.json();
|
|
151
|
+
if (result.code !== 0)
|
|
152
|
+
throw new Error(`Local memory ${route} rejected the request`);
|
|
153
|
+
return result.data;
|
|
154
|
+
};
|
|
155
|
+
const adminFile = path.join(root, "admin-key");
|
|
156
|
+
const adminKey = existsSync(adminFile)
|
|
157
|
+
? readFileSync(adminFile, "utf8").trim()
|
|
158
|
+
: `sk-mem-${randomBytes(24).toString("hex")}`;
|
|
159
|
+
if (!existsSync(adminFile)) savePrivate(adminFile, adminKey);
|
|
160
|
+
await request("internal/meta/user/init-admin", {
|
|
161
|
+
username: "admin",
|
|
162
|
+
user_key: adminKey,
|
|
163
|
+
});
|
|
164
|
+
const keyFile = path.join(root, "business-key");
|
|
165
|
+
const key = existsSync(keyFile)
|
|
166
|
+
? readFileSync(keyFile, "utf8").trim()
|
|
167
|
+
: `sk-mem-${randomBytes(24).toString("hex")}`;
|
|
168
|
+
if (!existsSync(keyFile)) savePrivate(keyFile, key);
|
|
169
|
+
let identity = await request("meta/auth/verify", { user_key: key });
|
|
170
|
+
if (!identity.valid) {
|
|
171
|
+
const users = await request(
|
|
172
|
+
"meta/user/list",
|
|
173
|
+
{ username: "opencode" },
|
|
174
|
+
adminKey,
|
|
175
|
+
);
|
|
176
|
+
if (users.items?.length)
|
|
177
|
+
throw new Error(
|
|
178
|
+
"Saved memory key does not match the existing user; recover the key, do not reset data",
|
|
179
|
+
);
|
|
180
|
+
await request(
|
|
181
|
+
"meta/user/create-with-key",
|
|
182
|
+
{ username: "opencode", user_key: key },
|
|
183
|
+
adminKey,
|
|
184
|
+
);
|
|
185
|
+
identity = await request("meta/auth/verify", { user_key: key });
|
|
186
|
+
}
|
|
187
|
+
if (!identity.valid || !identity.user)
|
|
188
|
+
throw new Error(
|
|
189
|
+
"Saved memory identity is invalid; do not reset its database",
|
|
190
|
+
);
|
|
191
|
+
const userId = identity.user.user_id;
|
|
192
|
+
const teams = await request(
|
|
193
|
+
"meta/team/list",
|
|
194
|
+
{ user_id: userId, limit: 100 },
|
|
195
|
+
key,
|
|
196
|
+
);
|
|
197
|
+
const team =
|
|
198
|
+
teams.items?.find((item: { name: string }) => item.name === "OpenCode") ||
|
|
199
|
+
(await request(
|
|
200
|
+
"meta/team/create",
|
|
201
|
+
{ name: "OpenCode", owner_user_id: userId },
|
|
202
|
+
key,
|
|
203
|
+
));
|
|
204
|
+
const agents = await request(
|
|
205
|
+
"meta/agent/list",
|
|
206
|
+
{ team_id: team.team_id, limit: 100 },
|
|
207
|
+
key,
|
|
208
|
+
);
|
|
209
|
+
const agent =
|
|
210
|
+
agents.items?.find((item: { name: string }) => item.name === "General") ||
|
|
211
|
+
(await request(
|
|
212
|
+
"meta/agent/create",
|
|
213
|
+
{ team_id: team.team_id, owner_user_id: userId, name: "General" },
|
|
214
|
+
key,
|
|
215
|
+
));
|
|
216
|
+
const file = path.join(root, "aionui-memory.json");
|
|
217
|
+
savePrivate(file, {
|
|
218
|
+
gatewayUrl: coreUrl,
|
|
219
|
+
knowledgeUrl,
|
|
220
|
+
serviceId: "default",
|
|
221
|
+
userId,
|
|
222
|
+
teamId: team.team_id,
|
|
223
|
+
agentId: agent.agent_id,
|
|
224
|
+
gatewayApiKey: secrets.gateway,
|
|
225
|
+
knowledgeServiceKey: secrets.knowledge,
|
|
226
|
+
knowledgeWorkspaces: settings.knowledgeWorkspaces,
|
|
227
|
+
nativeKnowledgeProjectsDir: path.join(root, "knowledge-projects"),
|
|
228
|
+
});
|
|
229
|
+
return file;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Recover the previous index/configuration after an interrupted offline rebuild. */
|
|
233
|
+
export function recoverEmbeddingChange(userData: string): void {
|
|
234
|
+
const root = path.join(userData, "tencentdb");
|
|
235
|
+
const marker = path.join(root, "embedding-change.pending");
|
|
236
|
+
if (!existsSync(marker)) return;
|
|
237
|
+
const work = path.join(root, "embedding-change");
|
|
238
|
+
const previous = readJson(path.join(work, "previous-settings.json"), null);
|
|
239
|
+
if (!previous || !existsSync(path.join(work, "backup/vectors.db")))
|
|
240
|
+
throw new Error("Embedding recovery backup is missing");
|
|
241
|
+
for (const suffix of ["", "-wal", "-shm"]) {
|
|
242
|
+
const file = `vectors.db${suffix}`;
|
|
243
|
+
rmSync(path.join(root, "core", file), { force: true });
|
|
244
|
+
if (existsSync(path.join(work, "backup", file)))
|
|
245
|
+
copyFileSync(
|
|
246
|
+
path.join(work, "backup", file),
|
|
247
|
+
path.join(root, "core", file),
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
savePrivate(path.join(root, "runtime-settings.json"), previous);
|
|
251
|
+
rmSync(path.join(work, "embedding.json"), { force: true });
|
|
252
|
+
rmSync(marker);
|
|
253
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
2
|
+
import {
|
|
3
|
+
copyFileSync,
|
|
4
|
+
existsSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
readFileSync,
|
|
7
|
+
renameSync,
|
|
8
|
+
rmSync,
|
|
9
|
+
} from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { createInterface } from "node:readline";
|
|
12
|
+
import {
|
|
13
|
+
type nativeConfig,
|
|
14
|
+
readJson,
|
|
15
|
+
recoverEmbeddingChange,
|
|
16
|
+
savePrivate,
|
|
17
|
+
} from "./config";
|
|
18
|
+
import { startNativeMemory, stopNativeMemory } from "./index";
|
|
19
|
+
|
|
20
|
+
export type EmbeddingInput = {
|
|
21
|
+
baseUrl: string;
|
|
22
|
+
model: string;
|
|
23
|
+
apiKey?: string;
|
|
24
|
+
};
|
|
25
|
+
let job: {
|
|
26
|
+
phase: string;
|
|
27
|
+
done: number;
|
|
28
|
+
total: number;
|
|
29
|
+
layer?: string;
|
|
30
|
+
error?: string;
|
|
31
|
+
} = { phase: "idle", done: 0, total: 0 };
|
|
32
|
+
let worker: ChildProcess | undefined;
|
|
33
|
+
let quitting = false;
|
|
34
|
+
let completion: Promise<void> | undefined;
|
|
35
|
+
let runtime: { bundle: string; userData: string } | undefined;
|
|
36
|
+
export function configureEmbeddingRuntime(
|
|
37
|
+
bundle: string,
|
|
38
|
+
userData: string,
|
|
39
|
+
): void {
|
|
40
|
+
runtime = { bundle, userData };
|
|
41
|
+
quitting = false;
|
|
42
|
+
}
|
|
43
|
+
export async function stopEmbeddingJob(): Promise<void> {
|
|
44
|
+
quitting = true;
|
|
45
|
+
worker?.kill("SIGTERM");
|
|
46
|
+
await completion;
|
|
47
|
+
}
|
|
48
|
+
export function embeddingStatus() {
|
|
49
|
+
if (!runtime) return { available: false, ...job };
|
|
50
|
+
const { embedding } = JSON.parse(
|
|
51
|
+
readFileSync(
|
|
52
|
+
path.join(runtime.userData, "tencentdb/runtime-settings.json"),
|
|
53
|
+
"utf8",
|
|
54
|
+
),
|
|
55
|
+
) as ReturnType<typeof nativeConfig>["settings"];
|
|
56
|
+
return {
|
|
57
|
+
available: true,
|
|
58
|
+
...job,
|
|
59
|
+
current: {
|
|
60
|
+
baseUrl: embedding.baseUrl,
|
|
61
|
+
model: embedding.model,
|
|
62
|
+
dimensions: embedding.dimensions,
|
|
63
|
+
hasApiKey: !!embedding.apiKey,
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function inputConfig(input: unknown) {
|
|
68
|
+
if (!runtime) throw new Error("Native memory is unavailable");
|
|
69
|
+
const value = input as EmbeddingInput;
|
|
70
|
+
if (
|
|
71
|
+
!value ||
|
|
72
|
+
typeof value.baseUrl !== "string" ||
|
|
73
|
+
typeof value.model !== "string" ||
|
|
74
|
+
!value.model.trim() ||
|
|
75
|
+
value.model.length > 200 ||
|
|
76
|
+
(value.apiKey !== undefined && typeof value.apiKey !== "string")
|
|
77
|
+
)
|
|
78
|
+
throw new Error("Invalid embedding configuration");
|
|
79
|
+
const url = new URL(value.baseUrl);
|
|
80
|
+
if (
|
|
81
|
+
!["http:", "https:"].includes(url.protocol) ||
|
|
82
|
+
url.username ||
|
|
83
|
+
url.password ||
|
|
84
|
+
url.search ||
|
|
85
|
+
url.hash
|
|
86
|
+
)
|
|
87
|
+
throw new Error("Invalid embedding endpoint");
|
|
88
|
+
const previous = (
|
|
89
|
+
JSON.parse(
|
|
90
|
+
readFileSync(
|
|
91
|
+
path.join(runtime.userData, "tencentdb/runtime-settings.json"),
|
|
92
|
+
"utf8",
|
|
93
|
+
),
|
|
94
|
+
) as ReturnType<typeof nativeConfig>["settings"]
|
|
95
|
+
).embedding;
|
|
96
|
+
const baseUrl = value.baseUrl.replace(/\/+$/, "");
|
|
97
|
+
const isSameEndpoint = baseUrl === previous.baseUrl.replace(/\/+$/, "");
|
|
98
|
+
const isLocalEndpoint = ["127.0.0.1", "localhost", "[::1]"].includes(
|
|
99
|
+
url.hostname,
|
|
100
|
+
);
|
|
101
|
+
const apiKey =
|
|
102
|
+
value.apiKey ||
|
|
103
|
+
(isSameEndpoint ? previous.apiKey : "") ||
|
|
104
|
+
(isLocalEndpoint ? "ollama" : "");
|
|
105
|
+
if (!apiKey)
|
|
106
|
+
throw new Error(
|
|
107
|
+
"An API key is required for a new remote embedding endpoint",
|
|
108
|
+
);
|
|
109
|
+
return {
|
|
110
|
+
...previous,
|
|
111
|
+
provider: "openai_compatible",
|
|
112
|
+
baseUrl,
|
|
113
|
+
model: value.model.trim(),
|
|
114
|
+
apiKey,
|
|
115
|
+
sendDimensions: false,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
export async function probeEmbedding(
|
|
119
|
+
input: unknown,
|
|
120
|
+
): Promise<{ dimensions: number }> {
|
|
121
|
+
const config = inputConfig(input);
|
|
122
|
+
const response = await fetch(`${config.baseUrl}/embeddings`, {
|
|
123
|
+
method: "POST",
|
|
124
|
+
headers: {
|
|
125
|
+
"Content-Type": "application/json",
|
|
126
|
+
Authorization: `Bearer ${config.apiKey}`,
|
|
127
|
+
},
|
|
128
|
+
body: JSON.stringify({
|
|
129
|
+
model: config.model,
|
|
130
|
+
input: "Embedding connection test",
|
|
131
|
+
}),
|
|
132
|
+
signal: AbortSignal.timeout(60000),
|
|
133
|
+
redirect: "error",
|
|
134
|
+
});
|
|
135
|
+
if (!response.ok)
|
|
136
|
+
throw new Error(`Embedding endpoint returned HTTP ${response.status}`);
|
|
137
|
+
const data = (await response.json()) as {
|
|
138
|
+
data?: Array<{ embedding?: number[] }>;
|
|
139
|
+
};
|
|
140
|
+
const vector = data.data?.[0]?.embedding;
|
|
141
|
+
if (
|
|
142
|
+
!Array.isArray(vector) ||
|
|
143
|
+
vector.length < 1 ||
|
|
144
|
+
vector.length > 65536 ||
|
|
145
|
+
vector.some((n) => typeof n !== "number" || !Number.isFinite(n))
|
|
146
|
+
)
|
|
147
|
+
throw new Error("Endpoint did not return a valid embedding");
|
|
148
|
+
return { dimensions: vector.length };
|
|
149
|
+
}
|
|
150
|
+
export function applyEmbedding(input: unknown): void {
|
|
151
|
+
if (completion && !["complete", "failed"].includes(job.phase))
|
|
152
|
+
throw new Error("Embedding change is already running");
|
|
153
|
+
const config = inputConfig(input);
|
|
154
|
+
const active = runtime!;
|
|
155
|
+
job = { phase: "checking", done: 0, total: 0 };
|
|
156
|
+
completion = (async () => {
|
|
157
|
+
let paused = false;
|
|
158
|
+
const root = path.join(active.userData, "tencentdb");
|
|
159
|
+
const work = path.join(root, "embedding-change");
|
|
160
|
+
try {
|
|
161
|
+
const { dimensions } = await probeEmbedding(input);
|
|
162
|
+
if (quitting) throw new Error("Application is closing");
|
|
163
|
+
config.dimensions = dimensions;
|
|
164
|
+
job.phase = "reindexing";
|
|
165
|
+
await stopNativeMemory();
|
|
166
|
+
paused = true;
|
|
167
|
+
rmSync(work, { recursive: true, force: true });
|
|
168
|
+
mkdirSync(path.join(work, "backup"), { recursive: true, mode: 0o700 });
|
|
169
|
+
mkdirSync(path.join(work, "stage"), { recursive: true });
|
|
170
|
+
for (const suffix of ["", "-wal", "-shm"]) {
|
|
171
|
+
const source = path.join(root, "core", `vectors.db${suffix}`);
|
|
172
|
+
if (existsSync(source))
|
|
173
|
+
for (const dest of ["backup", "stage"])
|
|
174
|
+
copyFileSync(source, path.join(work, dest, `vectors.db${suffix}`));
|
|
175
|
+
}
|
|
176
|
+
const settings = readJson(path.join(root, "runtime-settings.json"), {});
|
|
177
|
+
savePrivate(path.join(work, "previous-settings.json"), settings);
|
|
178
|
+
savePrivate(path.join(work, "embedding.json"), config);
|
|
179
|
+
// Startup rolls back an interrupted switch before any service opens the database.
|
|
180
|
+
savePrivate(path.join(root, "embedding-change.pending"), true);
|
|
181
|
+
await new Promise<void>((resolve, reject) => {
|
|
182
|
+
worker = spawn(
|
|
183
|
+
path.join(
|
|
184
|
+
active.bundle,
|
|
185
|
+
"bin",
|
|
186
|
+
process.platform === "win32" ? "node.exe" : "node",
|
|
187
|
+
),
|
|
188
|
+
[
|
|
189
|
+
"--import",
|
|
190
|
+
"tsx",
|
|
191
|
+
path.join(active.bundle, "runner.mjs"),
|
|
192
|
+
path.join(active.bundle, "MemoryCore/src/desktop-reindex.ts"),
|
|
193
|
+
path.join(work, "embedding.json"),
|
|
194
|
+
path.join(work, "stage/vectors.db"),
|
|
195
|
+
],
|
|
196
|
+
{
|
|
197
|
+
cwd: path.join(active.bundle, "MemoryCore"),
|
|
198
|
+
stdio: ["ignore", "pipe", "ignore", "ipc"],
|
|
199
|
+
detached: process.platform !== "win32",
|
|
200
|
+
windowsHide: true,
|
|
201
|
+
},
|
|
202
|
+
);
|
|
203
|
+
createInterface({ input: worker.stdout! }).on("line", (line) => {
|
|
204
|
+
try {
|
|
205
|
+
const progress = JSON.parse(line);
|
|
206
|
+
if (
|
|
207
|
+
Number.isInteger(progress.done) &&
|
|
208
|
+
Number.isInteger(progress.total)
|
|
209
|
+
)
|
|
210
|
+
job = {
|
|
211
|
+
phase: "reindexing",
|
|
212
|
+
done: progress.done,
|
|
213
|
+
total: progress.total,
|
|
214
|
+
layer: progress.layer,
|
|
215
|
+
};
|
|
216
|
+
} catch {
|
|
217
|
+
/* Not a progress event. */
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
worker.once("error", reject);
|
|
221
|
+
worker.once("exit", (code) => {
|
|
222
|
+
worker = undefined;
|
|
223
|
+
if (code === 0) resolve();
|
|
224
|
+
else reject(new Error("Embedding indexing failed"));
|
|
225
|
+
});
|
|
226
|
+
});
|
|
227
|
+
if (quitting) throw new Error("Application is closing");
|
|
228
|
+
for (const suffix of ["", "-wal", "-shm"])
|
|
229
|
+
rmSync(path.join(root, "core", `vectors.db${suffix}`), { force: true });
|
|
230
|
+
copyFileSync(
|
|
231
|
+
path.join(work, "stage/vectors.db"),
|
|
232
|
+
path.join(root, "core/vectors.db"),
|
|
233
|
+
);
|
|
234
|
+
savePrivate(path.join(root, "runtime-settings.json"), {
|
|
235
|
+
...settings,
|
|
236
|
+
embedding: config,
|
|
237
|
+
});
|
|
238
|
+
await startNativeMemory(active.bundle, active.userData, false);
|
|
239
|
+
rmSync(path.join(root, "embedding-change.pending"));
|
|
240
|
+
rmSync(path.join(work, "embedding.json"), { force: true });
|
|
241
|
+
try {
|
|
242
|
+
renameSync(work, path.join(root, `embedding-backup-${Date.now()}`));
|
|
243
|
+
} catch {
|
|
244
|
+
/* Backup remains in embedding-change. */
|
|
245
|
+
}
|
|
246
|
+
job.phase = "complete";
|
|
247
|
+
} catch (error) {
|
|
248
|
+
console.error("[Memory embeddings] Index switch failed", error);
|
|
249
|
+
job.error = error instanceof Error ? error.message : String(error);
|
|
250
|
+
if (paused) {
|
|
251
|
+
try {
|
|
252
|
+
await stopNativeMemory();
|
|
253
|
+
recoverEmbeddingChange(active.userData);
|
|
254
|
+
rmSync(path.join(work, "embedding.json"), { force: true });
|
|
255
|
+
if (!quitting)
|
|
256
|
+
await startNativeMemory(active.bundle, active.userData);
|
|
257
|
+
} catch (recoveryError) {
|
|
258
|
+
console.error("[Memory embeddings] Recovery failed", recoveryError);
|
|
259
|
+
job.phase = "unavailable";
|
|
260
|
+
job.error =
|
|
261
|
+
recoveryError instanceof Error
|
|
262
|
+
? recoveryError.message
|
|
263
|
+
: String(recoveryError);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
job.phase = "failed";
|
|
268
|
+
}
|
|
269
|
+
})();
|
|
270
|
+
}
|