@unblocklabs/unblock-memory 0.12.3 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -18
- package/defaults.json +162 -0
- package/dist/src/analysis.js +1 -1
- package/dist/src/cluster-review.d.ts +2 -0
- package/dist/src/cluster-review.js +9 -8
- package/dist/src/config.d.ts +9 -6
- package/dist/src/config.js +59 -45
- package/dist/src/curation.d.ts +1 -1
- package/dist/src/decision-client.d.ts +45 -0
- package/dist/src/decision-client.js +87 -0
- package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
- package/dist/src/decision-ranking.js +155 -0
- package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
- package/dist/src/decision-review.js +193 -0
- package/dist/src/defaults.d.ts +8 -0
- package/dist/src/defaults.js +128 -0
- package/dist/src/diagnostics.d.ts +5 -5
- package/dist/src/emotion-baselines.d.ts +28 -3
- package/dist/src/emotion-baselines.js +312 -115
- package/dist/src/evidence-review.d.ts +22 -8
- package/dist/src/evidence-review.js +11 -8
- package/dist/src/extraction-chunk.d.ts +3 -0
- package/dist/src/extraction-chunk.js +25 -6
- package/dist/src/extraction-config.js +4 -2
- package/dist/src/extraction-model.d.ts +25 -17
- package/dist/src/extraction-model.js +232 -104
- package/dist/src/extraction-runtime.d.ts +3 -1
- package/dist/src/extraction-runtime.js +48 -20
- package/dist/src/extraction-source.d.ts +1 -1
- package/dist/src/extraction-source.js +21 -12
- package/dist/src/extraction-store.d.ts +29 -3
- package/dist/src/extraction-store.js +149 -25
- package/dist/src/extraction-worker.d.ts +3 -3
- package/dist/src/extraction-worker.js +250 -95
- package/dist/src/inside-out-runtime.js +43 -30
- package/dist/src/inside-out-sources.js +2 -1
- package/dist/src/inside-out-store.d.ts +2 -2
- package/dist/src/inside-out-store.js +111 -69
- package/dist/src/inside-out.d.ts +10 -9
- package/dist/src/inside-out.js +194 -106
- package/dist/src/manager.d.ts +22 -9
- package/dist/src/manager.js +279 -172
- package/dist/src/memory-database.js +3 -2
- package/dist/src/memory-passage.d.ts +2 -2
- package/dist/src/memory-passage.js +3 -2
- package/dist/src/memory-search.d.ts +4 -2
- package/dist/src/memory-search.js +5 -5
- package/dist/src/memory-whisperer.d.ts +1 -1
- package/dist/src/memory-whisperer.js +195 -129
- package/dist/src/my-turn.d.ts +1 -1
- package/dist/src/my-turn.js +90 -70
- package/dist/src/people-background.d.ts +5 -1
- package/dist/src/people-background.js +31 -7
- package/dist/src/people-dossier-review.d.ts +20 -8
- package/dist/src/people-dossier-review.js +15 -11
- package/dist/src/people-hooks.js +127 -22
- package/dist/src/people-learning-cron.d.ts +1 -1
- package/dist/src/people-learning-cron.js +107 -57
- package/dist/src/people-learning-inventory.d.ts +1 -0
- package/dist/src/people-learning-inventory.js +283 -172
- package/dist/src/people-learning-prompt.js +1 -1
- package/dist/src/people-learning-runtime.d.ts +1 -1
- package/dist/src/people-learning-runtime.js +360 -203
- package/dist/src/people-learning-store.d.ts +27 -4
- package/dist/src/people-learning-store.js +312 -96
- package/dist/src/people-primer-tool.js +13 -10
- package/dist/src/people-primer.d.ts +3 -1
- package/dist/src/people-primer.js +66 -48
- package/dist/src/people-store.d.ts +18 -21
- package/dist/src/people-store.js +188 -64
- package/dist/src/people-tools.js +138 -93
- package/dist/src/plugin.js +19 -18
- package/dist/src/quality-audit.d.ts +2 -0
- package/dist/src/quality-audit.js +11 -9
- package/dist/src/quality-triage.js +4 -3
- package/dist/src/query-generator.js +5 -2
- package/dist/src/response-audit.d.ts +1 -1
- package/dist/src/response-audit.js +78 -44
- package/dist/src/response-config.js +3 -1
- package/dist/src/response-episodes.d.ts +1 -1
- package/dist/src/response-episodes.js +15 -19
- package/dist/src/response-identity.js +2 -1
- package/dist/src/response-judge.d.ts +151 -145
- package/dist/src/response-judge.js +535 -204
- package/dist/src/response-memory.js +2 -1
- package/dist/src/response-outcome.js +9 -8
- package/dist/src/response-reviews.d.ts +29 -1
- package/dist/src/response-reviews.js +113 -15
- package/dist/src/response-runtime.js +10 -9
- package/dist/src/response-stages.d.ts +50 -53
- package/dist/src/response-stages.js +10 -4
- package/dist/src/response-store.d.ts +7 -6
- package/dist/src/response-store.js +335 -212
- package/dist/src/review-tools.d.ts +8 -2
- package/dist/src/review-tools.js +22 -21
- package/dist/src/runtime.d.ts +7 -4
- package/dist/src/runtime.js +625 -98
- package/dist/src/safety-config.js +3 -2
- package/dist/src/safety-whisperer.d.ts +2 -2
- package/dist/src/safety-whisperer.js +90 -73
- package/dist/src/session-sync.d.ts +3 -1
- package/dist/src/session-sync.js +202 -96
- package/dist/src/skill-whisperer.d.ts +2 -2
- package/dist/src/skill-whisperer.js +55 -32
- package/dist/src/slack-directory.js +3 -2
- package/dist/src/training-gate.d.ts +9 -22
- package/dist/src/training-gate.js +34 -36
- package/dist/src/training-input.js +4 -3
- package/dist/src/training-judge.d.ts +9 -16
- package/dist/src/training-judge.js +6 -5
- package/dist/src/training-models.d.ts +1 -1
- package/dist/src/training-models.js +9 -7
- package/dist/src/training-queries.d.ts +14 -9
- package/dist/src/training-queries.js +374 -231
- package/dist/src/training-retrieval.d.ts +17 -27
- package/dist/src/training-retrieval.js +186 -139
- package/dist/src/training-runtime.d.ts +3 -0
- package/dist/src/training-runtime.js +76 -18
- package/dist/src/training-store.d.ts +18 -3
- package/dist/src/training-store.js +141 -52
- package/dist/src/training.js +9 -11
- package/dist/src/whisperer-context.d.ts +13 -0
- package/dist/src/whisperer-context.js +22 -1
- package/docs/configuration.md +83 -64
- package/docs/extraction.md +26 -35
- package/docs/memory-training.md +7 -6
- package/docs/people-learning.md +2 -2
- package/docs/peoplesql.md +6 -6
- package/docs/response-audit.md +10 -8
- package/docs/retrieval.md +43 -47
- package/openclaw.plugin.json +76 -75
- package/package.json +5 -2
- package/skills/memory-curator/SKILL.md +1 -1
- package/skills/people-whisperer/SKILL.md +1 -1
- package/dist/src/typesafe-client.d.ts +0 -30
- package/dist/src/typesafe-client.js +0 -92
- package/dist/src/typesafe-review.js +0 -154
- package/dist/src/typesafe.js +0 -147
package/dist/src/runtime.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import { DEFAULTS } from "./defaults.js";
|
|
1
2
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import {
|
|
3
|
+
import { closeSync, constants, fchmodSync, lstatSync, openSync, readFileSync } from "node:fs";
|
|
4
|
+
import fs from "node:fs/promises";
|
|
3
5
|
import { MEMORY_DATABASE } from "./memory-database.js";
|
|
4
6
|
import { join } from "node:path";
|
|
7
|
+
import { DatabaseSync } from "node:sqlite";
|
|
5
8
|
import { resolveAgentWorkspaceDir, resolveStateDir, } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
|
|
6
9
|
import { listAgentIds, resolveAgentIdentity } from "openclaw/plugin-sdk/agent-runtime";
|
|
7
10
|
import { QmdMemoryManager } from "./manager.js";
|
|
@@ -10,10 +13,64 @@ import { unchangedSessionSync } from "./session-sync.js";
|
|
|
10
13
|
import { resolveConfiguredSkillPath, resolveSessionSource, resolveSources } from "./sources.js";
|
|
11
14
|
import { classifyWorkspaceMemoryPaths } from "./workspace-path-classifier.js";
|
|
12
15
|
import { agentStateDir, agentTranscriptDatabase } from "./agent-paths.js";
|
|
13
|
-
const
|
|
16
|
+
const SESSION_SYNC_LOCK_FILE = "session-sync.lock.sqlite";
|
|
17
|
+
const LEGACY_SESSION_SYNC_LOCK_FILE = "session-sync.lock";
|
|
18
|
+
const SESSION_SYNC_STATUS_FILE = "session-sync-status.json";
|
|
19
|
+
const LEASE_BUSY_TIMEOUT_MS = DEFAULTS.sqlite.mainBusyTimeoutMs;
|
|
20
|
+
const MAX_LEASE_BUSY_RETRIES = 6;
|
|
21
|
+
const heldSessionSyncLeaseTokens = new Set();
|
|
22
|
+
const LEASE_SCHEMA_SQL = `
|
|
23
|
+
CREATE TABLE IF NOT EXISTS session_sync_lease (
|
|
24
|
+
id INTEGER PRIMARY KEY CHECK(id = 1),
|
|
25
|
+
pid INTEGER NOT NULL,
|
|
26
|
+
token TEXT NOT NULL,
|
|
27
|
+
started_at TEXT NOT NULL
|
|
28
|
+
)
|
|
29
|
+
`;
|
|
30
|
+
function heldLeaseKey(lockPath, token) {
|
|
31
|
+
return `${lockPath}\0${token}`;
|
|
32
|
+
}
|
|
33
|
+
function isLeaseHeldInProcess(lockPath, token) {
|
|
34
|
+
return heldSessionSyncLeaseTokens.has(heldLeaseKey(lockPath, token));
|
|
35
|
+
}
|
|
36
|
+
function isLeaseActive(lockPath, lease) {
|
|
37
|
+
if (!isProcessAlive(lease.pid))
|
|
38
|
+
return false;
|
|
39
|
+
if (lease.pid === process.pid && !isLeaseHeldInProcess(lockPath, lease.token)) {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
function parseLegacySessionSyncLock(value) {
|
|
45
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
46
|
+
return undefined;
|
|
47
|
+
const { pid, token, startedAt } = value;
|
|
48
|
+
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0 ||
|
|
49
|
+
typeof token !== "string" || token.length === 0 ||
|
|
50
|
+
typeof startedAt !== "string" || startedAt.length === 0) {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
return { pid, token, startedAt };
|
|
54
|
+
}
|
|
55
|
+
function readLiveLegacySessionSyncLock(directory) {
|
|
56
|
+
const legacyPath = join(directory, LEGACY_SESSION_SYNC_LOCK_FILE);
|
|
57
|
+
try {
|
|
58
|
+
const stat = lstatSync(legacyPath, { throwIfNoEntry: false });
|
|
59
|
+
if (!stat || !stat.isFile())
|
|
60
|
+
return undefined;
|
|
61
|
+
const parsed = parseLegacySessionSyncLock(JSON.parse(readFileSync(legacyPath, "utf8")));
|
|
62
|
+
if (!parsed || !isProcessAlive(parsed.pid))
|
|
63
|
+
return undefined;
|
|
64
|
+
return parsed;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
// Missing, unreadable, or invalid legacy lock file does not block SQLite lease acquisition.
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
14
71
|
async function readJson(path) {
|
|
15
72
|
try {
|
|
16
|
-
return JSON.parse(await readFile(path, "utf8"));
|
|
73
|
+
return JSON.parse(await fs.readFile(path, "utf8"));
|
|
17
74
|
}
|
|
18
75
|
catch (error) {
|
|
19
76
|
if (error.code === "ENOENT")
|
|
@@ -23,7 +80,7 @@ async function readJson(path) {
|
|
|
23
80
|
}
|
|
24
81
|
async function removeIfPresent(path) {
|
|
25
82
|
try {
|
|
26
|
-
await unlink(path);
|
|
83
|
+
await fs.unlink(path);
|
|
27
84
|
}
|
|
28
85
|
catch (error) {
|
|
29
86
|
if (error.code !== "ENOENT")
|
|
@@ -33,27 +90,219 @@ async function removeIfPresent(path) {
|
|
|
33
90
|
async function atomicWriteJson(path, value) {
|
|
34
91
|
const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
35
92
|
try {
|
|
36
|
-
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
37
|
-
await
|
|
93
|
+
await fs.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
94
|
+
await fs.chmod(temporary, 0o600);
|
|
95
|
+
await fs.rename(temporary, path);
|
|
38
96
|
}
|
|
39
97
|
finally {
|
|
40
98
|
await removeIfPresent(temporary);
|
|
41
99
|
}
|
|
42
100
|
}
|
|
43
|
-
|
|
44
|
-
|
|
101
|
+
function isProcessAlive(pid) {
|
|
102
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
103
|
+
return false;
|
|
104
|
+
try {
|
|
105
|
+
process.kill(pid, 0);
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
const code = error.code;
|
|
110
|
+
if (code === "EPERM")
|
|
111
|
+
return true;
|
|
112
|
+
if (code === "ESRCH")
|
|
113
|
+
return false;
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function parseLeaseRow(value) {
|
|
118
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
119
|
+
return undefined;
|
|
120
|
+
const { pid, token, started_at: startedAt } = value;
|
|
121
|
+
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0 ||
|
|
122
|
+
typeof token !== "string" || token.length === 0 ||
|
|
123
|
+
typeof startedAt !== "string" || startedAt.length === 0) {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
return { pid, token, startedAt };
|
|
127
|
+
}
|
|
128
|
+
function isSqliteBusy(error) {
|
|
129
|
+
if (!(error instanceof Error))
|
|
130
|
+
return false;
|
|
131
|
+
const errcode = "errcode" in error && typeof error.errcode === "number" ? error.errcode : undefined;
|
|
132
|
+
return errcode !== undefined && (errcode & 0xff) === 5;
|
|
133
|
+
}
|
|
134
|
+
async function withLeaseBusyRetry(operation) {
|
|
135
|
+
for (let attempt = 0;; attempt += 1) {
|
|
136
|
+
try {
|
|
137
|
+
return operation();
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (!isSqliteBusy(error) || attempt >= MAX_LEASE_BUSY_RETRIES)
|
|
141
|
+
throw error;
|
|
142
|
+
const backoffMs = Math.min(200, 20 * (attempt + 1));
|
|
143
|
+
await new Promise((resolve) => setTimeout(resolve, backoffMs));
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function ensurePrivateLeaseFile(lockPath) {
|
|
148
|
+
const existing = lstatSync(lockPath, { throwIfNoEntry: false });
|
|
149
|
+
if (existing && !existing.isFile()) {
|
|
150
|
+
throw new Error("Session sync lock database must be a regular file, not a symlink");
|
|
151
|
+
}
|
|
152
|
+
const descriptor = openSync(lockPath, constants.O_CREAT | constants.O_APPEND | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
|
|
153
|
+
try {
|
|
154
|
+
fchmodSync(descriptor, 0o600);
|
|
155
|
+
}
|
|
156
|
+
finally {
|
|
157
|
+
closeSync(descriptor);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
async function withImmediateLeaseTransaction(lockPath, fn) {
|
|
161
|
+
return await withLeaseBusyRetry(() => {
|
|
162
|
+
ensurePrivateLeaseFile(lockPath);
|
|
163
|
+
const db = new DatabaseSync(lockPath);
|
|
164
|
+
let inTransaction = false;
|
|
165
|
+
try {
|
|
166
|
+
db.exec(`PRAGMA busy_timeout = ${LEASE_BUSY_TIMEOUT_MS}; PRAGMA trusted_schema = OFF;`);
|
|
167
|
+
db.exec("BEGIN IMMEDIATE");
|
|
168
|
+
inTransaction = true;
|
|
169
|
+
db.exec(LEASE_SCHEMA_SQL);
|
|
170
|
+
const { commit, value, onCommit } = fn(db);
|
|
171
|
+
db.exec(commit ? "COMMIT" : "ROLLBACK");
|
|
172
|
+
inTransaction = false;
|
|
173
|
+
if (commit)
|
|
174
|
+
onCommit?.();
|
|
175
|
+
return value;
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
if (inTransaction) {
|
|
179
|
+
try {
|
|
180
|
+
db.exec("ROLLBACK");
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
// Transaction may already be rolled back by SQLite.
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
db.close();
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
async function readSessionSyncLock(lockPath) {
|
|
194
|
+
const stat = lstatSync(lockPath, { throwIfNoEntry: false });
|
|
195
|
+
if (!stat)
|
|
196
|
+
return { exists: false };
|
|
197
|
+
if (!stat.isFile()) {
|
|
198
|
+
throw new Error("Session sync lock database must be a regular file, not a symlink");
|
|
199
|
+
}
|
|
200
|
+
return await withLeaseBusyRetry(() => {
|
|
201
|
+
const db = new DatabaseSync(lockPath, { readOnly: true });
|
|
202
|
+
try {
|
|
203
|
+
db.exec(`PRAGMA busy_timeout = ${LEASE_BUSY_TIMEOUT_MS}; PRAGMA query_only = ON; PRAGMA trusted_schema = OFF;`);
|
|
204
|
+
const table = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'session_sync_lease'").get();
|
|
205
|
+
if (!table)
|
|
206
|
+
return { exists: false };
|
|
207
|
+
const row = db.prepare("SELECT pid, token, started_at FROM session_sync_lease WHERE id = 1").get();
|
|
208
|
+
if (!row)
|
|
209
|
+
return { exists: false };
|
|
210
|
+
return { exists: true, lock: parseLeaseRow(row) };
|
|
211
|
+
}
|
|
212
|
+
finally {
|
|
213
|
+
db.close();
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
async function releaseSessionSyncLock(lockPath, token) {
|
|
218
|
+
heldSessionSyncLeaseTokens.delete(heldLeaseKey(lockPath, token));
|
|
219
|
+
const existing = lstatSync(lockPath, { throwIfNoEntry: false });
|
|
220
|
+
if (!existing)
|
|
221
|
+
return;
|
|
222
|
+
await withImmediateLeaseTransaction(lockPath, (db) => {
|
|
223
|
+
db.prepare("DELETE FROM session_sync_lease WHERE id = 1 AND token = ?").run(token);
|
|
224
|
+
return { commit: true, value: undefined };
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
async function releaseSessionSyncLockSafely(lockPath, token, onError) {
|
|
228
|
+
try {
|
|
229
|
+
await releaseSessionSyncLock(lockPath, token);
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
if (onError)
|
|
233
|
+
onError(error);
|
|
234
|
+
else
|
|
235
|
+
console.warn(`unblock-memory failed to release session sync lease (${lockPath}): ${String(error)}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
async function clearStaleSessionSyncLease(lockPath) {
|
|
239
|
+
const existing = lstatSync(lockPath, { throwIfNoEntry: false });
|
|
240
|
+
if (!existing)
|
|
241
|
+
return undefined;
|
|
242
|
+
return await withImmediateLeaseTransaction(lockPath, (db) => {
|
|
243
|
+
const row = db.prepare("SELECT pid, token, started_at FROM session_sync_lease WHERE id = 1").get();
|
|
244
|
+
if (!row)
|
|
245
|
+
return { commit: false, value: undefined };
|
|
246
|
+
const current = parseLeaseRow(row);
|
|
247
|
+
if (current && isLeaseActive(lockPath, current)) {
|
|
248
|
+
return { commit: false, value: current };
|
|
249
|
+
}
|
|
250
|
+
db.prepare("DELETE FROM session_sync_lease WHERE id = 1").run();
|
|
251
|
+
return { commit: true, value: undefined };
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
async function acquireSessionSyncLock(directory, startedAt) {
|
|
255
|
+
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
256
|
+
const liveLegacyBefore = readLiveLegacySessionSyncLock(directory);
|
|
257
|
+
if (liveLegacyBefore) {
|
|
258
|
+
return { acquired: false, owner: liveLegacyBefore };
|
|
259
|
+
}
|
|
260
|
+
const lockPath = join(directory, SESSION_SYNC_LOCK_FILE);
|
|
261
|
+
const candidate = {
|
|
262
|
+
pid: process.pid,
|
|
263
|
+
token: randomUUID(),
|
|
264
|
+
startedAt,
|
|
265
|
+
};
|
|
266
|
+
return await withImmediateLeaseTransaction(lockPath, (db) => {
|
|
267
|
+
const row = db.prepare("SELECT pid, token, started_at FROM session_sync_lease WHERE id = 1").get();
|
|
268
|
+
const existing = parseLeaseRow(row);
|
|
269
|
+
if (existing && isLeaseActive(lockPath, existing)) {
|
|
270
|
+
return { commit: false, value: { acquired: false, owner: existing } };
|
|
271
|
+
}
|
|
272
|
+
const liveLegacy = readLiveLegacySessionSyncLock(directory);
|
|
273
|
+
if (liveLegacy) {
|
|
274
|
+
return { commit: false, value: { acquired: false, owner: liveLegacy } };
|
|
275
|
+
}
|
|
276
|
+
db.prepare("INSERT OR REPLACE INTO session_sync_lease (id, pid, token, started_at) VALUES (1, ?, ?, ?)").run(candidate.pid, candidate.token, candidate.startedAt);
|
|
277
|
+
return {
|
|
278
|
+
commit: true,
|
|
279
|
+
value: { acquired: true, lock: candidate, lockPath },
|
|
280
|
+
onCommit: () => {
|
|
281
|
+
heldSessionSyncLeaseTokens.add(heldLeaseKey(lockPath, candidate.token));
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
function runningStatusFromReceipt(status, startedAt) {
|
|
287
|
+
return status?.status === "running" && status.startedAt === startedAt
|
|
288
|
+
? { status: "running", phase: status.phase, startedAt }
|
|
289
|
+
: { status: "running", phase: "queued", startedAt };
|
|
290
|
+
}
|
|
291
|
+
export async function recoverInterruptedSessionSync(directory, statusPath, stale, onError) {
|
|
292
|
+
const acquired = await acquireSessionSyncLock(directory, stale.startedAt);
|
|
293
|
+
if (!acquired.acquired) {
|
|
294
|
+
const current = await readJson(statusPath);
|
|
295
|
+
return runningStatusFromReceipt(current, acquired.owner.startedAt);
|
|
296
|
+
}
|
|
45
297
|
try {
|
|
46
298
|
const current = await readJson(statusPath);
|
|
47
299
|
if (!current)
|
|
48
300
|
return { status: "idle" };
|
|
49
301
|
if (current.status !== "running")
|
|
50
302
|
return current;
|
|
51
|
-
if (current.startedAt !== stale.startedAt) {
|
|
52
|
-
return { status: "running", phase: current.phase, startedAt: current.startedAt };
|
|
53
|
-
}
|
|
54
303
|
const failed = {
|
|
55
304
|
status: "failed",
|
|
56
|
-
startedAt:
|
|
305
|
+
startedAt: current.startedAt,
|
|
57
306
|
completedAt: new Date().toISOString(),
|
|
58
307
|
error: "session sync interrupted by Gateway restart",
|
|
59
308
|
};
|
|
@@ -61,8 +310,7 @@ export async function recoverInterruptedSessionSync(directory, statusPath, stale
|
|
|
61
310
|
return failed;
|
|
62
311
|
}
|
|
63
312
|
finally {
|
|
64
|
-
|
|
65
|
-
activeSessionSyncs.delete(directory);
|
|
313
|
+
await releaseSessionSyncLockSafely(acquired.lockPath, acquired.lock.token, onError);
|
|
66
314
|
}
|
|
67
315
|
}
|
|
68
316
|
export class QmdMemoryRuntime {
|
|
@@ -71,24 +319,72 @@ export class QmdMemoryRuntime {
|
|
|
71
319
|
#analysisExecutable;
|
|
72
320
|
#keepEmbeddingModelWarm;
|
|
73
321
|
#stateRoot;
|
|
322
|
+
#onError;
|
|
74
323
|
#managers = new Map();
|
|
324
|
+
#closingManagers = new Map();
|
|
325
|
+
#activeSessionSyncs = new Map();
|
|
326
|
+
#pendingSessionSyncStarts = new Set();
|
|
327
|
+
#closing = false;
|
|
328
|
+
#closed = false;
|
|
329
|
+
#reloadFences = 0;
|
|
330
|
+
#closeAllFences = 0;
|
|
331
|
+
#closePromise;
|
|
75
332
|
#sessionSyncTimer;
|
|
333
|
+
#schedule;
|
|
76
334
|
startSessionSyncSchedule(cfg, onError) {
|
|
77
335
|
this.stopSessionSyncSchedule();
|
|
336
|
+
if (this.#closing || this.#closed)
|
|
337
|
+
return;
|
|
338
|
+
const sessions = this.#corpora.find((corpus) => corpus.kind === "sessions");
|
|
339
|
+
if (!sessions?.syncIntervalMinutes)
|
|
340
|
+
return;
|
|
341
|
+
this.#schedule = { cfg, onError };
|
|
342
|
+
if (this.#reloadFences === 0 && this.#closeAllFences === 0) {
|
|
343
|
+
this.#startSessionSyncTimer(sessions.syncIntervalMinutes, cfg, onError);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
stopSessionSyncSchedule() {
|
|
347
|
+
this.#schedule = undefined;
|
|
348
|
+
this.#pauseSessionSyncSchedule();
|
|
349
|
+
}
|
|
350
|
+
#pauseSessionSyncSchedule() {
|
|
351
|
+
if (this.#sessionSyncTimer)
|
|
352
|
+
clearInterval(this.#sessionSyncTimer);
|
|
353
|
+
this.#sessionSyncTimer = undefined;
|
|
354
|
+
}
|
|
355
|
+
#maybeResumeSessionSyncSchedule() {
|
|
356
|
+
if (this.#closing ||
|
|
357
|
+
this.#closed ||
|
|
358
|
+
this.#reloadFences > 0 ||
|
|
359
|
+
this.#closeAllFences > 0 ||
|
|
360
|
+
this.#sessionSyncTimer ||
|
|
361
|
+
!this.#schedule) {
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
78
364
|
const sessions = this.#corpora.find((corpus) => corpus.kind === "sessions");
|
|
79
365
|
if (!sessions?.syncIntervalMinutes)
|
|
80
366
|
return;
|
|
367
|
+
this.#startSessionSyncTimer(sessions.syncIntervalMinutes, this.#schedule.cfg, this.#schedule.onError);
|
|
368
|
+
}
|
|
369
|
+
#startSessionSyncTimer(syncIntervalMinutes, cfg, onError) {
|
|
81
370
|
this.#sessionSyncTimer = setInterval(() => {
|
|
82
371
|
for (const agentId of listAgentIds(cfg)) {
|
|
83
372
|
void this.startSessionSync({ cfg, agentId }).catch(onError);
|
|
84
373
|
}
|
|
85
|
-
},
|
|
374
|
+
}, syncIntervalMinutes * 60_000);
|
|
86
375
|
this.#sessionSyncTimer.unref();
|
|
87
376
|
}
|
|
88
|
-
|
|
89
|
-
if (this.#
|
|
90
|
-
|
|
91
|
-
this.#
|
|
377
|
+
#admissionBlockedReason() {
|
|
378
|
+
if (this.#closing || this.#closed)
|
|
379
|
+
return "memory runtime is closing";
|
|
380
|
+
if (this.#reloadFences > 0)
|
|
381
|
+
return "memory runtime is reloading";
|
|
382
|
+
if (this.#closeAllFences > 0)
|
|
383
|
+
return "memory runtime is closing";
|
|
384
|
+
return undefined;
|
|
385
|
+
}
|
|
386
|
+
async #releaseLease(lockPath, token) {
|
|
387
|
+
await releaseSessionSyncLockSafely(lockPath, token, this.#onError ?? this.#schedule?.onError);
|
|
92
388
|
}
|
|
93
389
|
constructor(corpora, options = {}) {
|
|
94
390
|
this.#corpora = corpora;
|
|
@@ -96,42 +392,82 @@ export class QmdMemoryRuntime {
|
|
|
96
392
|
this.#analysisExecutable = options.analysisExecutable;
|
|
97
393
|
this.#keepEmbeddingModelWarm = options.keepEmbeddingModelWarm ?? true;
|
|
98
394
|
this.#stateRoot = options.stateRoot ?? resolveStateDir();
|
|
395
|
+
this.#onError = options.onError;
|
|
99
396
|
}
|
|
100
397
|
async getMemorySearchManager(params) {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
398
|
+
while (true) {
|
|
399
|
+
const blocked = this.#admissionBlockedReason();
|
|
400
|
+
if (blocked) {
|
|
401
|
+
return { manager: null, error: blocked };
|
|
402
|
+
}
|
|
403
|
+
const closing = this.#closingManagers.get(params.agentId);
|
|
404
|
+
if (closing) {
|
|
405
|
+
await closing.catch(() => undefined);
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
let pending = this.#managers.get(params.agentId);
|
|
409
|
+
if (!pending) {
|
|
410
|
+
pending = this.#createManager(params.cfg, params.agentId);
|
|
411
|
+
this.#managers.set(params.agentId, pending);
|
|
412
|
+
}
|
|
413
|
+
try {
|
|
414
|
+
const manager = await pending;
|
|
415
|
+
const blockedAfter = this.#admissionBlockedReason();
|
|
416
|
+
if (blockedAfter) {
|
|
417
|
+
return { manager: null, error: blockedAfter };
|
|
418
|
+
}
|
|
419
|
+
if (this.#managers.get(params.agentId) !== pending) {
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
return { manager };
|
|
423
|
+
}
|
|
424
|
+
catch (error) {
|
|
425
|
+
if (this.#managers.get(params.agentId) === pending)
|
|
426
|
+
this.#managers.delete(params.agentId);
|
|
427
|
+
return { manager: null, error: error instanceof Error ? error.message : String(error) };
|
|
428
|
+
}
|
|
113
429
|
}
|
|
114
430
|
}
|
|
115
431
|
resolveMemoryBackendConfig() {
|
|
116
432
|
return { backend: "builtin" };
|
|
117
433
|
}
|
|
118
434
|
classifyWorkspaceMemoryPaths = classifyWorkspaceMemoryPaths;
|
|
119
|
-
|
|
435
|
+
startSessionSync(params, force = false) {
|
|
436
|
+
const blocked = this.#admissionBlockedReason();
|
|
437
|
+
if (blocked) {
|
|
438
|
+
return Promise.resolve({
|
|
439
|
+
status: "unavailable",
|
|
440
|
+
error: blocked,
|
|
441
|
+
});
|
|
442
|
+
}
|
|
120
443
|
if (!this.#corpora.some((corpus) => corpus.kind === "sessions")) {
|
|
121
|
-
return {
|
|
444
|
+
return Promise.resolve({
|
|
122
445
|
status: "unavailable",
|
|
123
446
|
error: 'memory session sync requires a configured "sessions" corpus',
|
|
124
|
-
};
|
|
447
|
+
});
|
|
125
448
|
}
|
|
449
|
+
const pending = this.#startSessionSync(params, force);
|
|
450
|
+
this.#pendingSessionSyncStarts.add(pending);
|
|
451
|
+
const cleanup = () => {
|
|
452
|
+
this.#pendingSessionSyncStarts.delete(pending);
|
|
453
|
+
};
|
|
454
|
+
pending.then(cleanup, cleanup);
|
|
455
|
+
return pending;
|
|
456
|
+
}
|
|
457
|
+
async #startSessionSync(params, force) {
|
|
126
458
|
const directory = this.#stateDir(params.agentId);
|
|
127
|
-
const statusPath = join(directory,
|
|
128
|
-
const running = activeSessionSyncs.get(directory);
|
|
129
|
-
if (running)
|
|
130
|
-
return { status: "already_running", startedAt: running };
|
|
459
|
+
const statusPath = join(directory, SESSION_SYNC_STATUS_FILE);
|
|
131
460
|
const startedAt = new Date().toISOString();
|
|
132
|
-
|
|
461
|
+
const acquired = await acquireSessionSyncLock(directory, startedAt);
|
|
462
|
+
if (!acquired.acquired) {
|
|
463
|
+
return { status: "already_running", startedAt: acquired.owner.startedAt };
|
|
464
|
+
}
|
|
465
|
+
const blockedAfterAcquire = this.#admissionBlockedReason();
|
|
466
|
+
if (blockedAfterAcquire) {
|
|
467
|
+
await this.#releaseLease(acquired.lockPath, acquired.lock.token);
|
|
468
|
+
return { status: "unavailable", error: blockedAfterAcquire };
|
|
469
|
+
}
|
|
133
470
|
try {
|
|
134
|
-
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
135
471
|
await atomicWriteJson(statusPath, {
|
|
136
472
|
status: "running",
|
|
137
473
|
phase: "queued",
|
|
@@ -140,85 +476,276 @@ export class QmdMemoryRuntime {
|
|
|
140
476
|
});
|
|
141
477
|
}
|
|
142
478
|
catch (error) {
|
|
143
|
-
|
|
144
|
-
activeSessionSyncs.delete(directory);
|
|
479
|
+
await this.#releaseLease(acquired.lockPath, acquired.lock.token);
|
|
145
480
|
throw error;
|
|
146
481
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
const writePhase = (phase) => {
|
|
150
|
-
statusWrites = statusWrites.then(() => atomicWriteJson(statusPath, {
|
|
151
|
-
status: "running",
|
|
152
|
-
phase,
|
|
153
|
-
pid: process.pid,
|
|
154
|
-
startedAt,
|
|
155
|
-
}));
|
|
156
|
-
};
|
|
482
|
+
const blockedAfterWrite = this.#admissionBlockedReason();
|
|
483
|
+
if (blockedAfterWrite) {
|
|
157
484
|
try {
|
|
158
|
-
const sessions = this.#sessionConfig(params.cfg, params.agentId);
|
|
159
|
-
let result = !force && sessions
|
|
160
|
-
? await unchangedSessionSync(sessions, join(directory, "index.sqlite")) : undefined;
|
|
161
|
-
if (!result) {
|
|
162
|
-
const { manager, error } = await this.getMemorySearchManager(params);
|
|
163
|
-
if (!manager)
|
|
164
|
-
throw new Error(error ?? "memory unavailable");
|
|
165
|
-
result = await manager.syncSessions(force, writePhase);
|
|
166
|
-
}
|
|
167
|
-
await statusWrites;
|
|
168
485
|
await atomicWriteJson(statusPath, {
|
|
169
|
-
status: "
|
|
486
|
+
status: "failed",
|
|
170
487
|
startedAt,
|
|
171
488
|
completedAt: new Date().toISOString(),
|
|
172
|
-
|
|
489
|
+
error: blockedAfterWrite,
|
|
173
490
|
});
|
|
174
491
|
}
|
|
175
|
-
catch
|
|
176
|
-
|
|
177
|
-
try {
|
|
178
|
-
await atomicWriteJson(statusPath, {
|
|
179
|
-
status: "failed",
|
|
180
|
-
startedAt,
|
|
181
|
-
completedAt: new Date().toISOString(),
|
|
182
|
-
error: error instanceof Error ? error.message : String(error),
|
|
183
|
-
});
|
|
184
|
-
}
|
|
185
|
-
catch {
|
|
186
|
-
// The next status read converts the persisted running state to interrupted.
|
|
187
|
-
}
|
|
492
|
+
catch {
|
|
493
|
+
// Best effort: the next status read recovers any remaining running receipt.
|
|
188
494
|
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
495
|
+
await this.#releaseLease(acquired.lockPath, acquired.lock.token);
|
|
496
|
+
return { status: "unavailable", error: blockedAfterWrite };
|
|
497
|
+
}
|
|
498
|
+
const run = this.#runSessionSync(params, force, {
|
|
499
|
+
directory,
|
|
500
|
+
statusPath,
|
|
501
|
+
lockPath: acquired.lockPath,
|
|
502
|
+
token: acquired.lock.token,
|
|
503
|
+
startedAt,
|
|
504
|
+
});
|
|
505
|
+
this.#activeSessionSyncs.set(directory, run);
|
|
506
|
+
const cleanupRun = () => {
|
|
507
|
+
if (this.#activeSessionSyncs.get(directory) === run) {
|
|
508
|
+
this.#activeSessionSyncs.delete(directory);
|
|
192
509
|
}
|
|
193
|
-
}
|
|
510
|
+
};
|
|
511
|
+
run.then(cleanupRun, cleanupRun);
|
|
194
512
|
return { status: "started", startedAt };
|
|
195
513
|
}
|
|
514
|
+
async #runSessionSync(params, force, run) {
|
|
515
|
+
let statusWrites = Promise.resolve();
|
|
516
|
+
const writePhase = (phase) => {
|
|
517
|
+
statusWrites = statusWrites.then(() => atomicWriteJson(run.statusPath, {
|
|
518
|
+
status: "running",
|
|
519
|
+
phase,
|
|
520
|
+
pid: process.pid,
|
|
521
|
+
startedAt: run.startedAt,
|
|
522
|
+
}));
|
|
523
|
+
};
|
|
524
|
+
try {
|
|
525
|
+
const sessions = this.#sessionConfig(params.cfg, params.agentId);
|
|
526
|
+
let result = !force && sessions
|
|
527
|
+
? await unchangedSessionSync(sessions, join(run.directory, "index.sqlite"))
|
|
528
|
+
: undefined;
|
|
529
|
+
if (!result) {
|
|
530
|
+
const { manager, error } = await this.getMemorySearchManager(params);
|
|
531
|
+
if (!manager)
|
|
532
|
+
throw new Error(error ?? "memory unavailable");
|
|
533
|
+
result = await manager.syncSessions(force, writePhase);
|
|
534
|
+
}
|
|
535
|
+
await statusWrites;
|
|
536
|
+
await atomicWriteJson(run.statusPath, {
|
|
537
|
+
status: "completed",
|
|
538
|
+
startedAt: run.startedAt,
|
|
539
|
+
completedAt: new Date().toISOString(),
|
|
540
|
+
...result,
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
catch (error) {
|
|
544
|
+
await statusWrites.catch(() => { });
|
|
545
|
+
try {
|
|
546
|
+
await atomicWriteJson(run.statusPath, {
|
|
547
|
+
status: "failed",
|
|
548
|
+
startedAt: run.startedAt,
|
|
549
|
+
completedAt: new Date().toISOString(),
|
|
550
|
+
error: error instanceof Error ? error.message : String(error),
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
catch {
|
|
554
|
+
// The next status read converts the persisted running state to interrupted.
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
finally {
|
|
558
|
+
await this.#releaseLease(run.lockPath, run.token);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
196
561
|
async sessionSyncStatus(agentId) {
|
|
197
562
|
const directory = this.#stateDir(agentId);
|
|
198
|
-
const
|
|
563
|
+
const lockPath = join(directory, SESSION_SYNC_LOCK_FILE);
|
|
564
|
+
const statusPath = join(directory, SESSION_SYNC_STATUS_FILE);
|
|
565
|
+
const onError = this.#onError ?? this.#schedule?.onError;
|
|
566
|
+
const lockState = await readSessionSyncLock(lockPath);
|
|
567
|
+
if (lockState.exists && lockState.lock && isLeaseActive(lockPath, lockState.lock)) {
|
|
568
|
+
const status = await readJson(statusPath);
|
|
569
|
+
return runningStatusFromReceipt(status, lockState.lock.startedAt);
|
|
570
|
+
}
|
|
571
|
+
const legacyOwner = readLiveLegacySessionSyncLock(directory);
|
|
572
|
+
if (legacyOwner) {
|
|
573
|
+
const status = await readJson(statusPath);
|
|
574
|
+
return runningStatusFromReceipt(status, legacyOwner.startedAt);
|
|
575
|
+
}
|
|
199
576
|
const status = await readJson(statusPath);
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
577
|
+
if (status?.status === "running") {
|
|
578
|
+
return await recoverInterruptedSessionSync(directory, statusPath, status, onError);
|
|
579
|
+
}
|
|
580
|
+
if (lockState.exists) {
|
|
581
|
+
const liveOwner = await clearStaleSessionSyncLease(lockPath);
|
|
582
|
+
if (liveOwner) {
|
|
583
|
+
const refreshedStatus = await readJson(statusPath);
|
|
584
|
+
return runningStatusFromReceipt(refreshedStatus, liveOwner.startedAt);
|
|
585
|
+
}
|
|
586
|
+
const refreshedStatus = await readJson(statusPath);
|
|
587
|
+
if (refreshedStatus?.status === "running") {
|
|
588
|
+
return await recoverInterruptedSessionSync(directory, statusPath, refreshedStatus, onError);
|
|
589
|
+
}
|
|
590
|
+
return refreshedStatus ?? { status: "idle" };
|
|
591
|
+
}
|
|
592
|
+
return status ?? { status: "idle" };
|
|
593
|
+
}
|
|
594
|
+
async #drainSessionSyncs() {
|
|
595
|
+
while (this.#pendingSessionSyncStarts.size > 0 || this.#activeSessionSyncs.size > 0) {
|
|
596
|
+
await Promise.allSettled([
|
|
597
|
+
...this.#pendingSessionSyncStarts,
|
|
598
|
+
...this.#activeSessionSyncs.values(),
|
|
599
|
+
]);
|
|
205
600
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
601
|
+
}
|
|
602
|
+
prepareReload(change) {
|
|
603
|
+
// QMD embeds locally rather than via host MemoryEmbeddingProviderAdapter instances,
|
|
604
|
+
// so only retiring this runtime affects its managers and session syncs.
|
|
605
|
+
if (!change.retireRuntime) {
|
|
606
|
+
return {
|
|
607
|
+
drain: async () => ({ errors: [] }),
|
|
608
|
+
resume() { },
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
this.#reloadFences += 1;
|
|
612
|
+
this.#pauseSessionSyncSchedule();
|
|
613
|
+
let resumed = false;
|
|
614
|
+
let drainPromise;
|
|
615
|
+
return {
|
|
616
|
+
drain: () => {
|
|
617
|
+
if (!drainPromise) {
|
|
618
|
+
drainPromise = (async () => {
|
|
619
|
+
const errors = [];
|
|
620
|
+
if (resumed)
|
|
621
|
+
return { errors };
|
|
622
|
+
let ranOnce = false;
|
|
623
|
+
while (!ranOnce ||
|
|
624
|
+
(!resumed && (this.#pendingSessionSyncStarts.size > 0 ||
|
|
625
|
+
this.#activeSessionSyncs.size > 0 ||
|
|
626
|
+
this.#managers.size > 0 ||
|
|
627
|
+
this.#closingManagers.size > 0))) {
|
|
628
|
+
ranOnce = true;
|
|
629
|
+
await this.#drainSessionSyncs();
|
|
630
|
+
if (resumed)
|
|
631
|
+
break;
|
|
632
|
+
const agentIds = new Set([...this.#managers.keys(), ...this.#closingManagers.keys()]);
|
|
633
|
+
if (agentIds.size > 0) {
|
|
634
|
+
const settled = await Promise.allSettled([...agentIds].map((agentId) => this.closeMemorySearchManager({ agentId })));
|
|
635
|
+
for (const outcome of settled) {
|
|
636
|
+
if (outcome.status === "rejected")
|
|
637
|
+
errors.push(outcome.reason);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
return { errors };
|
|
642
|
+
})();
|
|
643
|
+
}
|
|
644
|
+
return drainPromise;
|
|
645
|
+
},
|
|
646
|
+
resume: () => {
|
|
647
|
+
if (resumed)
|
|
648
|
+
return;
|
|
649
|
+
resumed = true;
|
|
650
|
+
this.#reloadFences = Math.max(0, this.#reloadFences - 1);
|
|
651
|
+
this.#maybeResumeSessionSyncSchedule();
|
|
652
|
+
},
|
|
653
|
+
};
|
|
211
654
|
}
|
|
212
655
|
async closeMemorySearchManager(params) {
|
|
213
|
-
const
|
|
214
|
-
this.#
|
|
215
|
-
|
|
656
|
+
const { agentId } = params;
|
|
657
|
+
const activeSync = this.#activeSessionSyncs.get(this.#stateDir(agentId));
|
|
658
|
+
if (activeSync)
|
|
659
|
+
await activeSync.catch(() => undefined);
|
|
660
|
+
const previousClose = this.#closingManagers.get(agentId);
|
|
661
|
+
const pending = this.#managers.get(agentId);
|
|
662
|
+
this.#managers.delete(agentId);
|
|
663
|
+
if (!previousClose && !pending)
|
|
664
|
+
return;
|
|
665
|
+
const closing = (async () => {
|
|
666
|
+
let closeError;
|
|
667
|
+
if (previousClose) {
|
|
668
|
+
try {
|
|
669
|
+
await previousClose;
|
|
670
|
+
}
|
|
671
|
+
catch (error) {
|
|
672
|
+
closeError = error;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
if (pending) {
|
|
676
|
+
let manager;
|
|
677
|
+
try {
|
|
678
|
+
manager = await pending;
|
|
679
|
+
}
|
|
680
|
+
catch {
|
|
681
|
+
// Failed startup already cleaned up its own manager inside #createManager.
|
|
682
|
+
}
|
|
683
|
+
if (manager) {
|
|
684
|
+
try {
|
|
685
|
+
await manager.close();
|
|
686
|
+
}
|
|
687
|
+
catch (error) {
|
|
688
|
+
closeError ??= error;
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
if (closeError !== undefined)
|
|
693
|
+
throw closeError;
|
|
694
|
+
})();
|
|
695
|
+
this.#closingManagers.set(agentId, closing);
|
|
696
|
+
try {
|
|
697
|
+
await closing;
|
|
698
|
+
}
|
|
699
|
+
finally {
|
|
700
|
+
if (this.#closingManagers.get(agentId) === closing) {
|
|
701
|
+
this.#closingManagers.delete(agentId);
|
|
702
|
+
}
|
|
703
|
+
}
|
|
216
704
|
}
|
|
217
705
|
async closeAllMemorySearchManagers() {
|
|
706
|
+
this.#closeAllFences += 1;
|
|
218
707
|
this.stopSessionSyncSchedule();
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
708
|
+
let firstError;
|
|
709
|
+
let hasError = false;
|
|
710
|
+
try {
|
|
711
|
+
while (this.#pendingSessionSyncStarts.size > 0 ||
|
|
712
|
+
this.#activeSessionSyncs.size > 0 ||
|
|
713
|
+
this.#managers.size > 0 ||
|
|
714
|
+
this.#closingManagers.size > 0) {
|
|
715
|
+
await this.#drainSessionSyncs();
|
|
716
|
+
const agentIds = new Set([...this.#managers.keys(), ...this.#closingManagers.keys()]);
|
|
717
|
+
if (agentIds.size > 0) {
|
|
718
|
+
const settled = await Promise.allSettled([...agentIds].map((agentId) => this.closeMemorySearchManager({ agentId })));
|
|
719
|
+
for (const outcome of settled) {
|
|
720
|
+
if (outcome.status === "rejected" && !hasError) {
|
|
721
|
+
hasError = true;
|
|
722
|
+
firstError = outcome.reason;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
finally {
|
|
729
|
+
this.#closeAllFences = Math.max(0, this.#closeAllFences - 1);
|
|
730
|
+
}
|
|
731
|
+
if (hasError)
|
|
732
|
+
throw firstError;
|
|
733
|
+
}
|
|
734
|
+
async close() {
|
|
735
|
+
if (this.#closePromise)
|
|
736
|
+
return this.#closePromise;
|
|
737
|
+
this.#closing = true;
|
|
738
|
+
const closing = (async () => {
|
|
739
|
+
try {
|
|
740
|
+
await this.closeAllMemorySearchManagers();
|
|
741
|
+
}
|
|
742
|
+
finally {
|
|
743
|
+
this.#closed = true;
|
|
744
|
+
this.#closing = false;
|
|
745
|
+
}
|
|
746
|
+
})();
|
|
747
|
+
this.#closePromise = closing;
|
|
748
|
+
return closing;
|
|
222
749
|
}
|
|
223
750
|
async searchSkills(params, query, minScore, limit) {
|
|
224
751
|
const { manager, error } = await this.getMemorySearchManager(params);
|