@xdarkicex/openclaw-memory-libravdb 1.4.5 → 1.4.7

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.
Files changed (75) hide show
  1. package/HOOK.md +14 -0
  2. package/README.md +32 -2
  3. package/dist/cli.d.ts +39 -0
  4. package/dist/cli.js +208 -0
  5. package/dist/context-engine.d.ts +56 -0
  6. package/dist/context-engine.js +125 -0
  7. package/dist/dream-promotion.d.ts +47 -0
  8. package/dist/dream-promotion.js +363 -0
  9. package/dist/dream-routing.d.ts +6 -0
  10. package/dist/dream-routing.js +31 -0
  11. package/dist/durable-namespace.d.ts +6 -0
  12. package/dist/durable-namespace.js +24 -0
  13. package/dist/grpc-client.d.ts +23 -0
  14. package/dist/grpc-client.js +104 -0
  15. package/dist/index.d.ts +10 -0
  16. package/dist/index.js +40 -0
  17. package/dist/lifecycle-hooks.d.ts +4 -0
  18. package/dist/lifecycle-hooks.js +64 -0
  19. package/dist/markdown-hash.d.ts +3 -0
  20. package/dist/markdown-hash.js +82 -0
  21. package/dist/markdown-ingest.d.ts +43 -0
  22. package/dist/markdown-ingest.js +464 -0
  23. package/dist/memory-provider.d.ts +4 -0
  24. package/dist/memory-provider.js +13 -0
  25. package/dist/memory-runtime.d.ts +118 -0
  26. package/dist/memory-runtime.js +217 -0
  27. package/dist/plugin-runtime.d.ts +28 -0
  28. package/dist/plugin-runtime.js +127 -0
  29. package/dist/proto/intelligence_kernel/v1/kernel.proto +378 -0
  30. package/dist/recall-cache.d.ts +2 -0
  31. package/dist/recall-cache.js +30 -0
  32. package/dist/rpc-protobuf-codecs.d.ts +70 -0
  33. package/dist/rpc-protobuf-codecs.js +77 -0
  34. package/dist/rpc.d.ts +14 -0
  35. package/dist/rpc.js +121 -0
  36. package/dist/sidecar.d.ts +34 -0
  37. package/dist/sidecar.js +535 -0
  38. package/dist/types.d.ts +163 -0
  39. package/dist/types.js +1 -0
  40. package/docs/contributing.md +14 -13
  41. package/docs/install.md +7 -9
  42. package/docs/installation.md +23 -16
  43. package/docs/uninstall.md +1 -1
  44. package/index.js +2 -0
  45. package/openclaw.plugin.json +2 -2
  46. package/package.json +39 -16
  47. package/packaging/README.md +0 -71
  48. package/packaging/homebrew/libravdbd.rb.tmpl +0 -224
  49. package/packaging/launchd/com.xdarkicex.libravdbd.plist +0 -32
  50. package/packaging/systemd/libravdbd.service +0 -12
  51. package/src/cli.ts +0 -299
  52. package/src/comparison-experiments.ts +0 -128
  53. package/src/context-engine.ts +0 -1451
  54. package/src/continuity.ts +0 -93
  55. package/src/dream-promotion.ts +0 -492
  56. package/src/dream-routing.ts +0 -40
  57. package/src/durable-namespace.ts +0 -34
  58. package/src/index.ts +0 -47
  59. package/src/lifecycle-hooks.ts +0 -96
  60. package/src/markdown-hash.ts +0 -104
  61. package/src/markdown-ingest.ts +0 -627
  62. package/src/memory-provider.ts +0 -25
  63. package/src/memory-runtime.ts +0 -283
  64. package/src/openclaw-plugin-sdk.d.ts +0 -59
  65. package/src/plugin-runtime.ts +0 -116
  66. package/src/recall-cache.ts +0 -34
  67. package/src/recall-utils.ts +0 -131
  68. package/src/rpc.ts +0 -84
  69. package/src/scoring.ts +0 -632
  70. package/src/sidecar.ts +0 -486
  71. package/src/temporal.ts +0 -1010
  72. package/src/tokens.ts +0 -52
  73. package/src/types.ts +0 -277
  74. package/tsconfig.json +0 -20
  75. package/tsconfig.tests.json +0 -12
@@ -0,0 +1,34 @@
1
+ import type { LoggerLike, PluginConfig, SidecarHandle, SidecarSocket } from "./types.js";
2
+ type CloseHandler = () => void;
3
+ type DataHandler = (chunk: Buffer) => void;
4
+ type ErrorHandler = (error: Error) => void;
5
+ export interface SidecarRuntime {
6
+ resolveEndpoint(cfg: PluginConfig): string | Promise<string>;
7
+ createSocket(endpoint: string): SidecarSocket;
8
+ scheduleRestart(delayMs: number, restart: () => void): void;
9
+ }
10
+ declare class PlaceholderSocket implements SidecarSocket {
11
+ private readonly onData;
12
+ private readonly onClose;
13
+ private readonly onError;
14
+ private readonly connectOnce;
15
+ private readonly errorOnce;
16
+ constructor();
17
+ setEncoding(_encoding: string): void;
18
+ on(event: "data" | "close" | "error", handler: DataHandler | CloseHandler | ErrorHandler): void;
19
+ once(event: "connect" | "error", handler: CloseHandler | ErrorHandler): void;
20
+ write(chunk: Buffer | string): void;
21
+ destroy(): void;
22
+ private emitError;
23
+ }
24
+ export declare function startSidecar(cfg: PluginConfig, logger?: LoggerLike, runtime?: SidecarRuntime): Promise<SidecarHandle>;
25
+ export declare function computeBackoffMs(retries: number): number;
26
+ export declare function computeStartupConnectRetryDelay(attempt: number, waitedMs?: number): number;
27
+ export declare function isTcpEndpoint(endpoint: string): boolean;
28
+ export declare function resolveEndpoint(cfg: PluginConfig): string;
29
+ export declare function resolveConfiguredEndpoint(cfg: PluginConfig): string;
30
+ export declare function daemonProvisioningHint(): string;
31
+ export declare function defaultEndpoint(platform?: NodeJS.Platform, homeDir?: string): string;
32
+ export declare function buildSidecarEnv(cfg: PluginConfig): Record<string, string>;
33
+ export { PlaceholderSocket };
34
+ export declare function probeSidecarEndpoint(cfg: PluginConfig): Promise<string | null>;
@@ -0,0 +1,535 @@
1
+ import fs from "node:fs";
2
+ import net from "node:net";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ const STARTUP_CONNECT_MAX_RETRIES = 5;
6
+ const STARTUP_CONNECT_BASE_DELAY_MS = 100;
7
+ const STARTUP_CONNECT_MAX_TOTAL_WAIT_MS = 2000;
8
+ class PlaceholderSocket {
9
+ onData = new Set();
10
+ onClose = new Set();
11
+ onError = new Set();
12
+ connectOnce = new Set();
13
+ errorOnce = new Set();
14
+ constructor() {
15
+ queueMicrotask(() => {
16
+ for (const handler of this.connectOnce) {
17
+ handler();
18
+ }
19
+ this.connectOnce.clear();
20
+ });
21
+ }
22
+ setEncoding(_encoding) { }
23
+ on(event, handler) {
24
+ if (event === "data") {
25
+ this.onData.add(handler);
26
+ return;
27
+ }
28
+ if (event === "error") {
29
+ this.onError.add(handler);
30
+ return;
31
+ }
32
+ this.onClose.add(handler);
33
+ }
34
+ once(event, handler) {
35
+ if (event === "connect") {
36
+ this.connectOnce.add(handler);
37
+ return;
38
+ }
39
+ this.errorOnce.add(handler);
40
+ }
41
+ write(chunk) {
42
+ try {
43
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8");
44
+ let offset = 0;
45
+ // Consume the one-time magic byte if present
46
+ if (buf.byteLength > 0 && buf[0] === 0x02)
47
+ offset = 1;
48
+ // Parse length-prefixed frames
49
+ while (offset + 4 <= buf.byteLength) {
50
+ const len = buf.readUInt32BE(offset);
51
+ offset += 4;
52
+ if (offset + len > buf.byteLength)
53
+ break;
54
+ const msg = JSON.parse(buf.subarray(offset, offset + len).toString("utf8"));
55
+ offset += len;
56
+ const responseJson = JSON.stringify({
57
+ jsonrpc: "2.0",
58
+ id: msg.id,
59
+ result: msg.method === "health" ? { ok: true } : {},
60
+ });
61
+ // Emit as a properly framed binary response
62
+ const payload = Buffer.from(responseJson, "utf8");
63
+ const header = Buffer.alloc(4);
64
+ header.writeUInt32BE(payload.byteLength, 0);
65
+ const frame = Buffer.concat([header, payload]);
66
+ for (const handler of this.onData) {
67
+ handler(frame);
68
+ }
69
+ }
70
+ }
71
+ catch (error) {
72
+ const err = error instanceof Error ? error : new Error(String(error));
73
+ this.emitError(err);
74
+ }
75
+ }
76
+ destroy() {
77
+ for (const handler of this.onClose) {
78
+ handler();
79
+ }
80
+ }
81
+ emitError(error) {
82
+ for (const handler of this.onError) {
83
+ handler(error);
84
+ }
85
+ for (const handler of this.errorOnce) {
86
+ handler(error);
87
+ }
88
+ this.errorOnce.clear();
89
+ }
90
+ }
91
+ class SupervisorSocket {
92
+ onData = new Set();
93
+ onClose = new Set();
94
+ onError = new Set();
95
+ connectOnce = new Set();
96
+ errorOnce = new Set();
97
+ current;
98
+ encoding = "utf8";
99
+ generation = 0;
100
+ bind(socket) {
101
+ this.current = socket;
102
+ this.generation += 1;
103
+ const generation = this.generation;
104
+ socket.setEncoding(this.encoding);
105
+ socket.on("data", (chunk) => {
106
+ if (generation !== this.generation) {
107
+ return;
108
+ }
109
+ for (const handler of this.onData) {
110
+ handler(chunk);
111
+ }
112
+ });
113
+ socket.on("close", () => {
114
+ if (generation !== this.generation) {
115
+ return;
116
+ }
117
+ this.current = undefined;
118
+ for (const handler of this.onClose) {
119
+ handler();
120
+ }
121
+ });
122
+ socket.on("error", (error) => {
123
+ if (generation !== this.generation) {
124
+ return;
125
+ }
126
+ this.current = undefined;
127
+ for (const handler of this.onError) {
128
+ handler(error);
129
+ }
130
+ for (const handler of this.errorOnce) {
131
+ handler(error);
132
+ }
133
+ this.errorOnce.clear();
134
+ });
135
+ for (const handler of this.connectOnce) {
136
+ handler();
137
+ }
138
+ this.connectOnce.clear();
139
+ }
140
+ setEncoding(encoding) {
141
+ this.encoding = encoding;
142
+ this.current?.setEncoding(encoding);
143
+ }
144
+ on(event, handler) {
145
+ if (event === "data") {
146
+ this.onData.add(handler);
147
+ return;
148
+ }
149
+ if (event === "error") {
150
+ this.onError.add(handler);
151
+ return;
152
+ }
153
+ this.onClose.add(handler);
154
+ }
155
+ once(event, handler) {
156
+ if (event === "connect") {
157
+ if (this.current) {
158
+ handler();
159
+ return;
160
+ }
161
+ this.connectOnce.add(handler);
162
+ return;
163
+ }
164
+ this.errorOnce.add(handler);
165
+ }
166
+ write(chunk) {
167
+ if (!this.current) {
168
+ throw new Error("Sidecar socket unavailable");
169
+ }
170
+ this.current.write(chunk); // Cast/pass down safely
171
+ }
172
+ destroy() {
173
+ this.current?.destroy();
174
+ }
175
+ }
176
+ class SidecarSupervisor {
177
+ cfg;
178
+ logger;
179
+ runtime;
180
+ retries = 0;
181
+ degraded = false;
182
+ shuttingDown = false;
183
+ reconnectScheduled = false;
184
+ socket;
185
+ constructor(cfg, logger, runtime) {
186
+ this.cfg = cfg;
187
+ this.logger = logger;
188
+ this.runtime = runtime;
189
+ this.socket = new SupervisorSocket();
190
+ }
191
+ async start() {
192
+ const endpoint = await this.runtime.resolveEndpoint(this.cfg);
193
+ const socket = await this.connectEndpointWithRetry(endpoint);
194
+ this.reconnectScheduled = false;
195
+ if (this.socket instanceof SupervisorSocket) {
196
+ this.socket.bind(socket);
197
+ }
198
+ else {
199
+ this.socket = socket;
200
+ }
201
+ return socket;
202
+ }
203
+ isDegraded() {
204
+ return this.degraded;
205
+ }
206
+ async shutdown() {
207
+ this.shuttingDown = true;
208
+ this.socket.destroy();
209
+ }
210
+ async connectEndpointWithRetry(endpoint) {
211
+ if (isTcpEndpoint(endpoint)) {
212
+ this.logger.info?.(`[libravdb] using TCP endpoint ${endpoint}`);
213
+ }
214
+ else {
215
+ this.logger.info?.(`[libravdb] using Unix socket ${endpoint}`);
216
+ }
217
+ let waitedMs = 0;
218
+ for (let attempt = 0;; attempt += 1) {
219
+ try {
220
+ return await this.connectEndpoint(endpoint);
221
+ }
222
+ catch (error) {
223
+ if (!isStartupConnectRetryableError(error) || attempt >= STARTUP_CONNECT_MAX_RETRIES - 1) {
224
+ throw error;
225
+ }
226
+ const delayMs = computeStartupConnectRetryDelay(attempt, waitedMs);
227
+ if (delayMs <= 0) {
228
+ throw error;
229
+ }
230
+ waitedMs += delayMs;
231
+ this.logger.info?.(`[libravdb] Daemon not ready, retrying connection (attempt ${attempt + 1}/${STARTUP_CONNECT_MAX_RETRIES})...`);
232
+ await sleep(delayMs);
233
+ }
234
+ }
235
+ }
236
+ async connectEndpoint(endpoint) {
237
+ const socket = this.runtime.createSocket(endpoint);
238
+ return await new Promise((resolve, reject) => {
239
+ socket.once("connect", () => {
240
+ socket.on("close", () => {
241
+ void this.handleExit(1);
242
+ });
243
+ resolve(socket);
244
+ });
245
+ socket.once("error", (error) => {
246
+ socket.destroy();
247
+ reject(formatConnectionError(endpoint, error));
248
+ });
249
+ });
250
+ }
251
+ async handleExit(code) {
252
+ if (this.shuttingDown) {
253
+ return;
254
+ }
255
+ if (code === 0) {
256
+ return;
257
+ }
258
+ if (this.reconnectScheduled) {
259
+ return;
260
+ }
261
+ const maxRetries = this.cfg.maxRetries ?? 3;
262
+ if (this.retries >= maxRetries) {
263
+ this.logger.error("[libravdb] sidecar retries exhausted; degraded mode");
264
+ this.degraded = true;
265
+ return;
266
+ }
267
+ const backoffMs = computeBackoffMs(this.retries);
268
+ this.retries += 1;
269
+ this.reconnectScheduled = true;
270
+ this.runtime.scheduleRestart(backoffMs, () => {
271
+ void this.start().catch((error) => {
272
+ this.reconnectScheduled = false;
273
+ const message = error instanceof Error ? error.message : String(error);
274
+ this.logger.error(`[libravdb] sidecar reconnect failed: ${message}`);
275
+ });
276
+ });
277
+ }
278
+ }
279
+ export async function startSidecar(cfg, logger = console, runtime = createDefaultRuntime()) {
280
+ const supervisor = new SidecarSupervisor(cfg, logger, runtime);
281
+ await supervisor.start();
282
+ return supervisor;
283
+ }
284
+ export function computeBackoffMs(retries) {
285
+ return Math.min(500 * Math.pow(2, retries), 16000);
286
+ }
287
+ export function computeStartupConnectRetryDelay(attempt, waitedMs = 0) {
288
+ if (attempt < 0) {
289
+ return 0;
290
+ }
291
+ const remainingMs = STARTUP_CONNECT_MAX_TOTAL_WAIT_MS - waitedMs;
292
+ if (remainingMs <= 0) {
293
+ return 0;
294
+ }
295
+ return Math.min(STARTUP_CONNECT_BASE_DELAY_MS * Math.pow(2, attempt), remainingMs);
296
+ }
297
+ export function isTcpEndpoint(endpoint) {
298
+ return endpoint.startsWith("tcp:");
299
+ }
300
+ export function resolveEndpoint(cfg) {
301
+ const endpoint = resolveConfiguredEndpoint(cfg);
302
+ return endpoint.replace(/^unix:/, "");
303
+ }
304
+ export function resolveConfiguredEndpoint(cfg) {
305
+ const value = cfg.sidecarPath?.trim();
306
+ if (!value || value === "auto") {
307
+ return defaultEndpoint();
308
+ }
309
+ if (!isConfiguredEndpoint(value)) {
310
+ throw new Error(`LibraVDB sidecarPath must be a daemon endpoint like unix:/path/to/libravdb.sock or tcp:127.0.0.1:37421. Executable paths are no longer supported.`);
311
+ }
312
+ return value;
313
+ }
314
+ export function daemonProvisioningHint() {
315
+ return "If you installed the npm package, install and start libravdbd separately; the package does not provision the daemon binary, ONNX Runtime, or model assets.";
316
+ }
317
+ export function defaultEndpoint(platform = process.platform, homeDir = os.homedir()) {
318
+ // Honour the daemon's own env var first (set by Homebrew LaunchAgent / systemd unit).
319
+ const envEndpoint = process.env.LIBRAVDB_RPC_ENDPOINT?.trim();
320
+ if (envEndpoint && isConfiguredEndpoint(envEndpoint)) {
321
+ return envEndpoint;
322
+ }
323
+ if (platform === "win32") {
324
+ return "tcp:127.0.0.1:37421";
325
+ }
326
+ const sockName = "libravdb.sock";
327
+ const candidateDirs = [
328
+ // User-local (npm plugin convention)
329
+ homeDir?.trim() ? path.join(homeDir, ".clawdb", "run") : null,
330
+ // Homebrew (Apple Silicon) — matches the Homebrew formula LaunchAgent
331
+ "/opt/homebrew/var/clawdb/run",
332
+ // Homebrew (Intel Mac) / manual Linux installs
333
+ "/usr/local/var/clawdb/run",
334
+ ].filter((d) => d !== null);
335
+ for (const dir of candidateDirs) {
336
+ const sockPath = path.join(dir, sockName);
337
+ try {
338
+ if (fs.existsSync(sockPath)) {
339
+ return `unix:${sockPath}`;
340
+ }
341
+ }
342
+ catch {
343
+ // Permission error or similar — skip this candidate.
344
+ }
345
+ }
346
+ // Fallback to the original user-local path so error messages stay familiar.
347
+ const baseDir = homeDir?.trim()
348
+ ? path.join(homeDir, ".clawdb", "run")
349
+ : path.join(".", ".clawdb", "run");
350
+ return `unix:${path.join(baseDir, sockName)}`;
351
+ }
352
+ export function buildSidecarEnv(cfg) {
353
+ const env = {};
354
+ if (cfg.dbPath) {
355
+ env.LIBRAVDB_DB_PATH = cfg.dbPath;
356
+ }
357
+ if (cfg.embeddingRuntimePath) {
358
+ env.LIBRAVDB_ONNX_RUNTIME = cfg.embeddingRuntimePath;
359
+ }
360
+ if (cfg.embeddingBackend) {
361
+ env.LIBRAVDB_EMBEDDING_BACKEND = cfg.embeddingBackend;
362
+ }
363
+ if (cfg.embeddingProfile) {
364
+ env.LIBRAVDB_EMBEDDING_PROFILE = cfg.embeddingProfile;
365
+ }
366
+ if (cfg.fallbackProfile) {
367
+ env.LIBRAVDB_FALLBACK_PROFILE = cfg.fallbackProfile;
368
+ }
369
+ if (cfg.embeddingModelPath) {
370
+ env.LIBRAVDB_EMBEDDING_MODEL = cfg.embeddingModelPath;
371
+ }
372
+ if (cfg.embeddingTokenizerPath) {
373
+ env.LIBRAVDB_EMBEDDING_TOKENIZER = cfg.embeddingTokenizerPath;
374
+ }
375
+ if (typeof cfg.embeddingDimensions === "number" && cfg.embeddingDimensions > 0) {
376
+ env.LIBRAVDB_EMBEDDING_DIMENSIONS = String(cfg.embeddingDimensions);
377
+ }
378
+ if (typeof cfg.embeddingNormalize === "boolean") {
379
+ env.LIBRAVDB_EMBEDDING_NORMALIZE = String(cfg.embeddingNormalize);
380
+ }
381
+ if (cfg.summarizerBackend) {
382
+ env.LIBRAVDB_SUMMARIZER_BACKEND = cfg.summarizerBackend;
383
+ }
384
+ if (cfg.summarizerProfile) {
385
+ env.LIBRAVDB_SUMMARIZER_PROFILE = cfg.summarizerProfile;
386
+ }
387
+ if (cfg.summarizerRuntimePath) {
388
+ env.LIBRAVDB_SUMMARIZER_RUNTIME = cfg.summarizerRuntimePath;
389
+ }
390
+ if (cfg.summarizerModelPath) {
391
+ env.LIBRAVDB_SUMMARIZER_MODEL_PATH = cfg.summarizerModelPath;
392
+ }
393
+ if (cfg.summarizerTokenizerPath) {
394
+ env.LIBRAVDB_SUMMARIZER_TOKENIZER = cfg.summarizerTokenizerPath;
395
+ }
396
+ if (cfg.summarizerModel) {
397
+ env.LIBRAVDB_SUMMARIZER_MODEL = cfg.summarizerModel;
398
+ }
399
+ if (cfg.summarizerEndpoint) {
400
+ env.LIBRAVDB_SUMMARIZER_ENDPOINT = cfg.summarizerEndpoint;
401
+ }
402
+ if (cfg.ollamaUrl && !env.LIBRAVDB_SUMMARIZER_ENDPOINT) {
403
+ env.LIBRAVDB_SUMMARIZER_ENDPOINT = cfg.ollamaUrl;
404
+ }
405
+ if (cfg.compactModel && !env.LIBRAVDB_SUMMARIZER_MODEL) {
406
+ env.LIBRAVDB_SUMMARIZER_MODEL = cfg.compactModel;
407
+ }
408
+ if (cfg.gatingWeights?.w1c != null) {
409
+ env.LIBRAVDB_GATING_W1C = String(cfg.gatingWeights.w1c);
410
+ }
411
+ if (cfg.gatingWeights?.w2c != null) {
412
+ env.LIBRAVDB_GATING_W2C = String(cfg.gatingWeights.w2c);
413
+ }
414
+ if (cfg.gatingWeights?.w3c != null) {
415
+ env.LIBRAVDB_GATING_W3C = String(cfg.gatingWeights.w3c);
416
+ }
417
+ if (cfg.gatingWeights?.w1t != null) {
418
+ env.LIBRAVDB_GATING_W1T = String(cfg.gatingWeights.w1t);
419
+ }
420
+ if (cfg.gatingWeights?.w2t != null) {
421
+ env.LIBRAVDB_GATING_W2T = String(cfg.gatingWeights.w2t);
422
+ }
423
+ if (cfg.gatingWeights?.w3t != null) {
424
+ env.LIBRAVDB_GATING_W3T = String(cfg.gatingWeights.w3t);
425
+ }
426
+ if (typeof cfg.gatingTechNorm === "number" && cfg.gatingTechNorm > 0) {
427
+ env.LIBRAVDB_GATING_TECH_NORM = String(cfg.gatingTechNorm);
428
+ }
429
+ if (typeof cfg.ingestionGateThreshold === "number" && cfg.ingestionGateThreshold >= 0) {
430
+ env.LIBRAVDB_GATING_THRESHOLD = String(cfg.ingestionGateThreshold);
431
+ }
432
+ if (typeof cfg.gatingCentroidK === "number" && cfg.gatingCentroidK > 0) {
433
+ env.LIBRAVDB_GATING_CENTROID_K = String(cfg.gatingCentroidK);
434
+ }
435
+ if (typeof cfg.lifecycleJournalMaxEntries === "number" && cfg.lifecycleJournalMaxEntries > 0) {
436
+ env.LIBRAVDB_LIFECYCLE_JOURNAL_MAX_ENTRIES = String(cfg.lifecycleJournalMaxEntries);
437
+ }
438
+ return env;
439
+ }
440
+ function createDefaultRuntime() {
441
+ return {
442
+ resolveEndpoint(cfg) {
443
+ return resolveEndpoint(cfg);
444
+ },
445
+ createSocket(endpoint) {
446
+ if (isTcpEndpoint(endpoint)) {
447
+ const address = endpoint.slice("tcp:".length);
448
+ const separator = address.lastIndexOf(":");
449
+ if (separator <= 0) {
450
+ throw new Error(`Invalid TCP sidecar endpoint: ${endpoint}`);
451
+ }
452
+ return net.connect({
453
+ host: address.slice(0, separator),
454
+ port: Number(address.slice(separator + 1)),
455
+ });
456
+ }
457
+ return net.connect(endpoint);
458
+ },
459
+ scheduleRestart(delayMs, restart) {
460
+ setTimeout(restart, delayMs);
461
+ },
462
+ };
463
+ }
464
+ function isStartupConnectRetryableError(error) {
465
+ const code = typeof error?.code === "string"
466
+ ? error.code
467
+ : "";
468
+ return code === "ENOENT" || code === "ECONNREFUSED";
469
+ }
470
+ function formatConnectionError(endpoint, error) {
471
+ const code = typeof error.code === "string"
472
+ ? error.code
473
+ : "";
474
+ const annotated = error instanceof Error ? error : new Error(String(error));
475
+ if (code) {
476
+ annotated.code = code;
477
+ }
478
+ if (code === "ENOENT" || code === "ECONNREFUSED") {
479
+ const unavailable = new Error(`LibraVDB daemon unavailable at ${describeEndpoint(endpoint)}. ${daemonProvisioningHint()} Or set sidecarPath to a running daemon endpoint.`);
480
+ unavailable.code = code;
481
+ return unavailable;
482
+ }
483
+ return annotated;
484
+ }
485
+ function describeEndpoint(endpoint) {
486
+ if (isTcpEndpoint(endpoint)) {
487
+ return endpoint;
488
+ }
489
+ return `unix:${endpoint}`;
490
+ }
491
+ function isConfiguredEndpoint(value) {
492
+ return value?.startsWith("tcp:") === true || value?.startsWith("unix:") === true;
493
+ }
494
+ export { PlaceholderSocket };
495
+ function sleep(delayMs) {
496
+ return new Promise((resolve) => setTimeout(resolve, delayMs));
497
+ }
498
+ export async function probeSidecarEndpoint(cfg) {
499
+ const endpoint = resolveConfiguredEndpoint(cfg);
500
+ try {
501
+ await new Promise((resolve, reject) => {
502
+ if (isTcpEndpoint(endpoint)) {
503
+ const address = endpoint.slice("tcp:".length);
504
+ const separator = address.lastIndexOf(":");
505
+ if (separator <= 0) {
506
+ reject(new Error("invalid tcp endpoint"));
507
+ return;
508
+ }
509
+ const host = address.slice(0, separator);
510
+ const port = Number(address.slice(separator + 1));
511
+ const socket = net.connect({ host, port }, () => {
512
+ socket.destroy();
513
+ resolve();
514
+ });
515
+ socket.setTimeout(500);
516
+ socket.on("error", reject);
517
+ socket.on("timeout", reject);
518
+ }
519
+ else {
520
+ const socketPath = endpoint.replace(/^unix:/, "");
521
+ const socket = net.connect(socketPath, () => {
522
+ socket.destroy();
523
+ resolve();
524
+ });
525
+ socket.setTimeout(500);
526
+ socket.on("error", reject);
527
+ socket.on("timeout", reject);
528
+ }
529
+ });
530
+ return endpoint;
531
+ }
532
+ catch {
533
+ return null;
534
+ }
535
+ }