pi-knowledge 0.15.0 → 0.16.1

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 (61) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +61 -23
  3. package/dist/index.d.ts +10 -4
  4. package/dist/index.js +145 -166
  5. package/dist/src/coverage-snapshot.d.ts +23 -0
  6. package/dist/src/coverage-snapshot.js +53 -0
  7. package/dist/src/daemon/client.d.ts +60 -0
  8. package/dist/src/daemon/client.js +360 -0
  9. package/dist/src/daemon/main.d.ts +2 -0
  10. package/dist/src/daemon/main.js +109 -0
  11. package/dist/src/daemon/protocol.d.ts +71 -0
  12. package/dist/src/daemon/protocol.js +170 -0
  13. package/dist/src/daemon/runtime.d.ts +26 -0
  14. package/dist/src/daemon/runtime.js +192 -0
  15. package/dist/src/daemon/server.d.ts +46 -0
  16. package/dist/src/daemon/server.js +500 -0
  17. package/dist/src/daemon/service.d.ts +49 -0
  18. package/dist/src/daemon/service.js +527 -0
  19. package/dist/src/diagnostics/health.d.ts +6 -0
  20. package/dist/src/diagnostics/health.js +135 -2
  21. package/dist/src/engine.d.ts +13 -8
  22. package/dist/src/engine.js +569 -100
  23. package/dist/src/filesystem-access.d.ts +9 -0
  24. package/dist/src/filesystem-access.js +100 -0
  25. package/dist/src/indexer/chunker.d.ts +12 -0
  26. package/dist/src/indexer/chunker.js +307 -9
  27. package/dist/src/mcp/http.d.ts +47 -0
  28. package/dist/src/mcp/http.js +564 -0
  29. package/dist/src/mcp/main.d.ts +2 -0
  30. package/dist/src/mcp/main.js +97 -0
  31. package/dist/src/mcp/protocol.d.ts +81 -0
  32. package/dist/src/mcp/protocol.js +444 -0
  33. package/dist/src/mcp/server.d.ts +42 -0
  34. package/dist/src/mcp/server.js +378 -0
  35. package/dist/src/model-worker-client.js +9 -0
  36. package/dist/src/model-worker-contract.d.ts +3 -0
  37. package/dist/src/model-worker-contract.js +8 -0
  38. package/dist/src/model-worker.js +76 -4
  39. package/dist/src/network/safe-fetch.d.ts +7 -0
  40. package/dist/src/network/safe-fetch.js +199 -0
  41. package/dist/src/node-runtime.d.ts +3 -0
  42. package/dist/src/node-runtime.js +78 -0
  43. package/dist/src/profiles.d.ts +15 -0
  44. package/dist/src/profiles.js +160 -0
  45. package/dist/src/runtime-config.js +5 -6
  46. package/dist/src/secure-files.d.ts +17 -0
  47. package/dist/src/secure-files.js +183 -0
  48. package/dist/src/status.js +12 -7
  49. package/dist/src/storage/sqlite.d.ts +4 -1
  50. package/dist/src/storage/sqlite.js +46 -3
  51. package/dist/src/type-guards.d.ts +1 -0
  52. package/dist/src/type-guards.js +3 -0
  53. package/dist/src/watcher/file-watcher.d.ts +3 -1
  54. package/dist/src/watcher/file-watcher.js +166 -32
  55. package/dist/src/windows-security.d.ts +4 -0
  56. package/dist/src/windows-security.js +67 -0
  57. package/docs/configuration.md +40 -9
  58. package/docs/daemon-profiles.md +302 -0
  59. package/docs/mcp-clients.md +266 -0
  60. package/docs/offline-mode.md +6 -6
  61. package/package.json +28 -2
@@ -0,0 +1,500 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createConnection, createServer } from "node:net";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+ import { DAEMON_PROTOCOL_VERSION, DAEMON_SHUTDOWN_GRACE_MS, DAEMON_SHUTDOWN_SETTLE_MS, MAX_PROGRESS_FRAMES, MAX_RPC_CONNECTIONS, MAX_RPC_FRAME_BYTES, MAX_RPC_IN_FLIGHT, packageBuildIdentity, packageVersion, parseDaemonClientFrame, } from "./protocol.js";
5
+ import { acquireDaemonOwnership, DaemonLockExistsError, processIsAlive, publishDaemonManifest, readDaemonOwner, releaseDaemonOwnership, removeStaleOwnership, } from "./runtime.js";
6
+ import { KnowledgeDaemonService } from "./service.js";
7
+ const MAX_RPC_CONTROL_CONNECTIONS = 4;
8
+ export class DaemonAlreadyRunningError extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "DaemonAlreadyRunningError";
12
+ }
13
+ }
14
+ export class DaemonStartupCancelledError extends Error {
15
+ constructor() {
16
+ super("Profile daemon startup was cancelled by shutdown");
17
+ this.name = "DaemonStartupCancelledError";
18
+ }
19
+ }
20
+ function errorFrame(id, code, message) {
21
+ const boundedMessage = message.length > 4_096 ? `${message.slice(0, 4_096)}…` : message;
22
+ return { type: "error", id, code, message: boundedMessage };
23
+ }
24
+ function endpointAcceptsConnections(endpoint, timeoutMs = 500) {
25
+ const { promise, resolve } = Promise.withResolvers();
26
+ const socket = createConnection(endpoint);
27
+ let settled = false;
28
+ const finish = (result) => {
29
+ if (settled)
30
+ return;
31
+ settled = true;
32
+ clearTimeout(timer);
33
+ socket.destroy();
34
+ resolve(result);
35
+ };
36
+ const timer = setTimeout(() => finish(false), timeoutMs);
37
+ socket.once("connect", () => finish(true));
38
+ socket.once("error", () => finish(false));
39
+ return promise;
40
+ }
41
+ function closeServer(server) {
42
+ const { promise, resolve, reject } = Promise.withResolvers();
43
+ try {
44
+ server.close((error) => {
45
+ if (error)
46
+ reject(error);
47
+ else
48
+ resolve();
49
+ });
50
+ }
51
+ catch (error) {
52
+ reject(error);
53
+ }
54
+ return promise;
55
+ }
56
+ async function acquireWithRecovery(profile) {
57
+ try {
58
+ return acquireDaemonOwnership(profile);
59
+ }
60
+ catch (error) {
61
+ if (!(error instanceof DaemonLockExistsError))
62
+ throw error;
63
+ }
64
+ const owner = readDaemonOwner(profile);
65
+ if (!owner)
66
+ throw new DaemonAlreadyRunningError("Daemon lock exists without a readable owner record");
67
+ if (await endpointAcceptsConnections(owner.endpoint)) {
68
+ throw new DaemonAlreadyRunningError(`Knowledge profile daemon is already listening (PID ${owner.pid})`);
69
+ }
70
+ if (processIsAlive(owner.pid)) {
71
+ throw new DaemonAlreadyRunningError(`Knowledge profile daemon PID ${owner.pid} is alive but unresponsive; refusing unsafe takeover`);
72
+ }
73
+ removeStaleOwnership(profile, owner);
74
+ return acquireDaemonOwnership(profile);
75
+ }
76
+ export class ProfileDaemonServer {
77
+ controlCandidates = new Set();
78
+ sockets = new Set();
79
+ requestControllers = new Map();
80
+ inFlight = new Set();
81
+ service;
82
+ failStop;
83
+ profile;
84
+ options;
85
+ server;
86
+ ownership;
87
+ manifest;
88
+ accepting = false;
89
+ connectionCount = 0;
90
+ shutdownPromise;
91
+ startingPromise;
92
+ stopping = false;
93
+ startFailed = false;
94
+ controlTrimScheduled = false;
95
+ stopped = Promise.withResolvers();
96
+ constructor(profile, options = {}) {
97
+ this.profile = profile;
98
+ this.options = options;
99
+ this.service = new KnowledgeDaemonService(profile, undefined, () => {
100
+ this.refreshManifestDiagnostics(this.manifest?.watcher_enabled ?? this.options.watchersEnabled === true);
101
+ });
102
+ this.failStop =
103
+ options.failStop ??
104
+ ((message) => {
105
+ console.error(message);
106
+ process.exit(1);
107
+ });
108
+ }
109
+ start() {
110
+ if (this.startFailed)
111
+ return Promise.reject(new Error("Profile daemon server cannot restart after failed startup"));
112
+ if (this.startingPromise || this.server || this.ownership) {
113
+ return Promise.reject(new Error("Profile daemon server is already started"));
114
+ }
115
+ if (this.stopping)
116
+ return Promise.reject(new Error("Profile daemon server is stopping"));
117
+ const run = this.startInternal();
118
+ this.startingPromise = run;
119
+ const clearStarting = () => {
120
+ if (this.startingPromise === run)
121
+ this.startingPromise = undefined;
122
+ };
123
+ void run.then(clearStarting, clearStarting);
124
+ return run;
125
+ }
126
+ assertStartupActive() {
127
+ if (this.stopping)
128
+ throw new DaemonStartupCancelledError();
129
+ }
130
+ async startInternal() {
131
+ let ownership;
132
+ let boundEndpoint = false;
133
+ let server;
134
+ try {
135
+ ownership = await acquireWithRecovery(this.profile);
136
+ this.assertStartupActive();
137
+ this.ownership = ownership;
138
+ server = createServer((socket) => this.acceptConnection(socket));
139
+ this.server = server;
140
+ const { promise, resolve, reject } = Promise.withResolvers();
141
+ const onError = (error) => {
142
+ server?.off("listening", onListening);
143
+ reject(error);
144
+ };
145
+ const onListening = () => {
146
+ server?.off("error", onError);
147
+ boundEndpoint = true;
148
+ resolve();
149
+ };
150
+ server.once("error", onError);
151
+ server.once("listening", onListening);
152
+ server.listen(ownership.owner.endpoint);
153
+ await promise;
154
+ this.assertStartupActive();
155
+ this.manifest = publishDaemonManifest(this.profile, ownership, {
156
+ ready: false,
157
+ watcherEnabled: false,
158
+ });
159
+ this.assertStartupActive();
160
+ process.env.PI_KNOWLEDGE_DIR = this.profile.storageDir;
161
+ await this.service.initialize(this.options.watchersEnabled === true);
162
+ this.assertStartupActive();
163
+ this.accepting = true;
164
+ this.manifest = publishDaemonManifest(this.profile, ownership, {
165
+ ready: true,
166
+ watcherEnabled: this.options.watchersEnabled === true,
167
+ lastSnapshotError: this.service.coverageSnapshotError(),
168
+ });
169
+ return this.manifest;
170
+ }
171
+ catch (error) {
172
+ this.startFailed = true;
173
+ this.accepting = false;
174
+ this.service.abortOperations();
175
+ for (const socket of this.sockets)
176
+ socket.destroy();
177
+ let cleanupError;
178
+ try {
179
+ if (server?.listening)
180
+ await closeServer(server);
181
+ }
182
+ catch (candidate) {
183
+ cleanupError = candidate;
184
+ }
185
+ try {
186
+ await this.service.dispose();
187
+ }
188
+ catch (candidate) {
189
+ cleanupError ??= candidate;
190
+ }
191
+ if (cleanupError) {
192
+ this.failStop(`Profile daemon startup cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`);
193
+ }
194
+ if (ownership)
195
+ releaseDaemonOwnership(this.profile, ownership, { removeEndpoint: boundEndpoint });
196
+ this.ownership = undefined;
197
+ this.server = undefined;
198
+ this.manifest = undefined;
199
+ throw error;
200
+ }
201
+ }
202
+ writeFrame(socket, frame) {
203
+ let line = `${JSON.stringify(frame)}\n`;
204
+ let bytes = Buffer.byteLength(line);
205
+ if (bytes > MAX_RPC_FRAME_BYTES) {
206
+ if (frame.type !== "result") {
207
+ socket.destroy(new Error("Daemon response exceeds the configured frame limit"));
208
+ return false;
209
+ }
210
+ line = `${JSON.stringify(errorFrame(frame.id, "response_too_large", "Daemon result exceeds the configured response limit"))}\n`;
211
+ bytes = Buffer.byteLength(line);
212
+ }
213
+ if (socket.writableLength + bytes > MAX_RPC_FRAME_BYTES) {
214
+ socket.destroy(new Error("Daemon outbound buffer exceeds the configured limit"));
215
+ return false;
216
+ }
217
+ return socket.write(line);
218
+ }
219
+ scheduleControlCandidateTrim() {
220
+ if (this.controlTrimScheduled)
221
+ return;
222
+ this.controlTrimScheduled = true;
223
+ setImmediate(() => {
224
+ this.controlTrimScheduled = false;
225
+ while (this.controlCandidates.size > MAX_RPC_CONTROL_CONNECTIONS) {
226
+ const oldest = this.controlCandidates.values().next().value;
227
+ if (!oldest)
228
+ break;
229
+ this.controlCandidates.delete(oldest);
230
+ if (this.sockets.delete(oldest))
231
+ this.connectionCount--;
232
+ oldest.destroy(new Error("Reserved daemon control connection was superseded"));
233
+ }
234
+ });
235
+ }
236
+ acceptConnection(socket) {
237
+ socket.on("error", () => {
238
+ /* connection-local framing and peer errors must not terminate the daemon */
239
+ });
240
+ this.connectionCount++;
241
+ this.sockets.add(socket);
242
+ const controlOnly = this.connectionCount > MAX_RPC_CONNECTIONS;
243
+ let inputBuffer;
244
+ let inputBytes = 0;
245
+ let requestId;
246
+ const requestKey = randomUUID();
247
+ let progressFrames = 0;
248
+ const authenticationDeadline = setTimeout(() => socket.destroy(), 5_000);
249
+ authenticationDeadline.unref();
250
+ const close = () => {
251
+ if (!this.sockets.delete(socket))
252
+ return;
253
+ clearTimeout(authenticationDeadline);
254
+ this.requestControllers.get(requestKey)?.abort();
255
+ this.controlCandidates.delete(socket);
256
+ this.connectionCount--;
257
+ };
258
+ socket.once("close", close);
259
+ if (controlOnly) {
260
+ this.controlCandidates.add(socket);
261
+ this.scheduleControlCandidateTrim();
262
+ }
263
+ const acceptLine = (lineBuffer) => {
264
+ const line = lineBuffer.toString("utf8").trim();
265
+ if (!line)
266
+ return;
267
+ try {
268
+ const frame = parseDaemonClientFrame(JSON.parse(line));
269
+ if (frame.type === "cancel") {
270
+ if (requestId === frame.id && this.manifest && frame.token === this.manifest.auth_token) {
271
+ this.requestControllers.get(requestKey)?.abort();
272
+ }
273
+ }
274
+ else if (requestId) {
275
+ this.writeFrame(socket, errorFrame(frame.id, "invalid_request", "One request is allowed per connection"));
276
+ }
277
+ else {
278
+ clearTimeout(authenticationDeadline);
279
+ requestId = frame.id;
280
+ if (controlOnly &&
281
+ frame.type === "request" &&
282
+ frame.method === "shutdown" &&
283
+ this.manifest &&
284
+ frame.token === this.manifest.auth_token) {
285
+ this.controlCandidates.delete(socket);
286
+ }
287
+ const run = this.handleRequest(socket, requestKey, frame, controlOnly, () => {
288
+ progressFrames++;
289
+ return progressFrames <= MAX_PROGRESS_FRAMES;
290
+ });
291
+ this.inFlight.add(run);
292
+ void run.finally(() => this.inFlight.delete(run));
293
+ }
294
+ }
295
+ catch (error) {
296
+ this.writeFrame(socket, errorFrame(requestId ?? "", "invalid_request", error instanceof Error ? error.message : "Invalid request"));
297
+ socket.end();
298
+ }
299
+ };
300
+ socket.on("data", (chunk) => {
301
+ let offset = 0;
302
+ while (offset < chunk.byteLength) {
303
+ const newline = chunk.indexOf(0x0a, offset);
304
+ const end = newline < 0 ? chunk.byteLength : newline;
305
+ const part = chunk.subarray(offset, end);
306
+ const requiredBytes = inputBytes + part.byteLength;
307
+ if (requiredBytes > MAX_RPC_FRAME_BYTES) {
308
+ socket.destroy(new Error("Daemon request exceeds the configured frame limit"));
309
+ return;
310
+ }
311
+ if (part.byteLength > 0) {
312
+ if (!inputBuffer || inputBuffer.byteLength < requiredBytes) {
313
+ const capacity = Math.min(MAX_RPC_FRAME_BYTES, Math.max(requiredBytes, inputBuffer ? inputBuffer.byteLength * 2 : 4_096));
314
+ const grown = Buffer.allocUnsafe(capacity);
315
+ inputBuffer?.copy(grown, 0, 0, inputBytes);
316
+ inputBuffer = grown;
317
+ }
318
+ part.copy(inputBuffer, inputBytes);
319
+ inputBytes = requiredBytes;
320
+ }
321
+ if (newline < 0)
322
+ return;
323
+ if (inputBuffer && inputBytes > 0)
324
+ acceptLine(inputBuffer.subarray(0, inputBytes));
325
+ inputBuffer = undefined;
326
+ inputBytes = 0;
327
+ offset = newline + 1;
328
+ }
329
+ });
330
+ }
331
+ refreshManifestDiagnostics(watchersEnabled) {
332
+ if (!this.ownership || !this.manifest)
333
+ return;
334
+ const snapshotError = this.service.coverageSnapshotError();
335
+ if (this.manifest.watcher_enabled === watchersEnabled && this.manifest.last_snapshot_error === snapshotError) {
336
+ return;
337
+ }
338
+ try {
339
+ this.manifest = publishDaemonManifest(this.profile, this.ownership, {
340
+ ready: this.accepting,
341
+ watcherEnabled: watchersEnabled,
342
+ lastSnapshotError: snapshotError,
343
+ });
344
+ }
345
+ catch {
346
+ console.error("Failed to publish daemon runtime diagnostics");
347
+ }
348
+ }
349
+ async handleRequest(socket, requestKey, frame, controlOnly, allowProgress) {
350
+ const manifest = this.manifest;
351
+ if (!manifest || frame.token !== manifest.auth_token) {
352
+ this.writeFrame(socket, errorFrame(frame.id, "unauthorized", "Invalid daemon credential"));
353
+ socket.end();
354
+ return;
355
+ }
356
+ if (frame.method === "shutdown") {
357
+ this.writeFrame(socket, { type: "result", id: frame.id, result: { accepted: true } });
358
+ socket.end();
359
+ void this.shutdown().catch((error) => this.failStop(error instanceof Error ? error.message : "Profile daemon shutdown failed"));
360
+ return;
361
+ }
362
+ if (frame.package_version !== packageVersion()) {
363
+ this.writeFrame(socket, errorFrame(frame.id, "version_mismatch", "Daemon and client package versions differ"));
364
+ socket.end();
365
+ return;
366
+ }
367
+ if (frame.build_identity !== packageBuildIdentity()) {
368
+ this.writeFrame(socket, errorFrame(frame.id, "build_mismatch", "Daemon and client builds differ"));
369
+ socket.end();
370
+ return;
371
+ }
372
+ if (controlOnly) {
373
+ this.writeFrame(socket, errorFrame(frame.id, "overloaded", "Normal daemon connection capacity is exhausted"));
374
+ socket.end();
375
+ return;
376
+ }
377
+ if (frame.method === "ping") {
378
+ this.writeFrame(socket, {
379
+ type: "result",
380
+ id: frame.id,
381
+ result: {
382
+ ready: manifest.ready && this.accepting,
383
+ protocol_version: DAEMON_PROTOCOL_VERSION,
384
+ profile: { name: this.profile.name, id: this.profile.id },
385
+ storage_dir: this.profile.storageDir,
386
+ instance_id: manifest.instance_id,
387
+ pid: manifest.pid,
388
+ package_version: manifest.package_version,
389
+ runtime_configuration_signature: manifest.runtime_configuration_signature,
390
+ build_identity: manifest.build_identity,
391
+ },
392
+ });
393
+ socket.end();
394
+ return;
395
+ }
396
+ if (!this.accepting || !manifest.ready) {
397
+ this.writeFrame(socket, errorFrame(frame.id, "not_ready", "Knowledge profile daemon is initializing"));
398
+ socket.end();
399
+ return;
400
+ }
401
+ if (this.inFlight.size >= MAX_RPC_IN_FLIGHT) {
402
+ this.writeFrame(socket, errorFrame(frame.id, "overloaded", "Too many in-flight daemon requests"));
403
+ socket.end();
404
+ return;
405
+ }
406
+ const controller = new AbortController();
407
+ this.requestControllers.set(requestKey, controller);
408
+ try {
409
+ const result = await this.service.dispatch(frame.method, frame.params, {
410
+ requestId: requestKey,
411
+ signal: controller.signal,
412
+ onProgress: (message) => {
413
+ if (allowProgress())
414
+ this.writeFrame(socket, { type: "progress", id: frame.id, message });
415
+ },
416
+ });
417
+ const watchersEnabled = frame.method === "enable_watchers" || this.manifest?.watcher_enabled === true;
418
+ this.refreshManifestDiagnostics(watchersEnabled);
419
+ if (!controller.signal.aborted)
420
+ this.writeFrame(socket, { type: "result", id: frame.id, result });
421
+ }
422
+ catch (error) {
423
+ if (!controller.signal.aborted) {
424
+ this.writeFrame(socket, errorFrame(frame.id, "operation_failed", error instanceof Error ? error.message : String(error)));
425
+ }
426
+ }
427
+ finally {
428
+ this.requestControllers.delete(requestKey);
429
+ socket.end();
430
+ }
431
+ }
432
+ async waitForQuiescence(timeoutMs) {
433
+ const deadline = Date.now() + timeoutMs;
434
+ while (this.inFlight.size > 0 || this.service.activeUpdateCount() > 0) {
435
+ if (Date.now() >= deadline)
436
+ return false;
437
+ await delay(20);
438
+ }
439
+ return true;
440
+ }
441
+ waitUntilStopped() {
442
+ return this.stopped.promise;
443
+ }
444
+ publishStoppingState() {
445
+ if (!this.ownership)
446
+ return;
447
+ try {
448
+ this.manifest = publishDaemonManifest(this.profile, this.ownership, {
449
+ ready: false,
450
+ watcherEnabled: this.manifest?.watcher_enabled === true,
451
+ lastSnapshotError: this.service.coverageSnapshotError(),
452
+ });
453
+ }
454
+ catch (error) {
455
+ console.error(`Failed to publish daemon shutdown state: ${error instanceof Error ? error.message : String(error)}`);
456
+ }
457
+ }
458
+ shutdown() {
459
+ if (this.shutdownPromise)
460
+ return this.shutdownPromise;
461
+ this.stopping = true;
462
+ this.accepting = false;
463
+ if (this.manifest)
464
+ this.manifest = { ...this.manifest, ready: false };
465
+ const ownershipAtShutdown = this.ownership;
466
+ this.publishStoppingState();
467
+ for (const controller of this.requestControllers.values())
468
+ controller.abort();
469
+ this.service.abortOperations();
470
+ const startup = this.startingPromise;
471
+ this.shutdownPromise = (async () => {
472
+ await startup?.catch(() => { });
473
+ if (!this.server && !this.ownership) {
474
+ this.stopped.resolve();
475
+ return;
476
+ }
477
+ if (this.ownership !== ownershipAtShutdown)
478
+ this.publishStoppingState();
479
+ const serverClosed = this.server?.listening ? closeServer(this.server) : Promise.resolve();
480
+ const quiesced = await this.waitForQuiescence(DAEMON_SHUTDOWN_GRACE_MS);
481
+ if (!quiesced) {
482
+ this.service.forceTerminateModelWorker();
483
+ const settled = await this.waitForQuiescence(DAEMON_SHUTDOWN_SETTLE_MS);
484
+ if (!settled)
485
+ this.failStop("Profile daemon could not safely settle active operations during shutdown");
486
+ }
487
+ await this.service.dispose();
488
+ for (const socket of this.sockets)
489
+ socket.destroy();
490
+ await serverClosed;
491
+ if (this.ownership)
492
+ releaseDaemonOwnership(this.profile, this.ownership);
493
+ this.server = undefined;
494
+ this.ownership = undefined;
495
+ this.manifest = undefined;
496
+ this.stopped.resolve();
497
+ })();
498
+ return this.shutdownPromise;
499
+ }
500
+ }
@@ -0,0 +1,49 @@
1
+ import { type CoverageSnapshotWriter } from "../coverage-snapshot.ts";
2
+ import type { DoctorReport, IndexPlan, KnowledgeStatusSnapshot, SearchResponse, SymbolSearchResponse } from "../engine.ts";
3
+ import type { KnowledgeProfile } from "../profiles.ts";
4
+ import type { KnowledgeBase } from "../storage/sqlite.ts";
5
+ import type { DaemonMethod } from "./protocol.ts";
6
+ export interface DaemonServiceStatus {
7
+ profile: {
8
+ name: string;
9
+ id: string;
10
+ };
11
+ storage_path: string;
12
+ watch_count: number;
13
+ snapshot_error?: string;
14
+ snapshot: KnowledgeStatusSnapshot;
15
+ }
16
+ export interface DaemonServiceDispatchContext {
17
+ requestId: string;
18
+ signal: AbortSignal;
19
+ onProgress: (message: string) => void;
20
+ }
21
+ export declare class KnowledgeDaemonService {
22
+ private readonly engine;
23
+ private readonly updates;
24
+ private readonly watcherDirty;
25
+ private readonly watcherRetryTimers;
26
+ private readonly profile;
27
+ private readonly snapshotWriter;
28
+ private readonly onSnapshotStateChange;
29
+ private initialized;
30
+ private watchersEnabled;
31
+ private shuttingDown;
32
+ private lastSnapshotError;
33
+ constructor(profile: KnowledgeProfile, snapshotWriter?: CoverageSnapshotWriter | undefined, onSnapshotStateChange?: (() => void) | undefined);
34
+ initialize(watchersEnabled: boolean): Promise<void>;
35
+ private refreshCoverageSnapshot;
36
+ coverageSnapshotError(): string | undefined;
37
+ private assertReady;
38
+ private triggerWatcherUpdate;
39
+ private startWatcherFor;
40
+ enableWatchers(): number;
41
+ private resolveKnowledgeBase;
42
+ private coordinateUpdate;
43
+ dispatch(method: DaemonMethod, params: Record<string, unknown>, context: DaemonServiceDispatchContext): Promise<unknown>;
44
+ abortOperations(): void;
45
+ forceTerminateModelWorker(): void;
46
+ activeUpdateCount(): number;
47
+ dispose(): Promise<void>;
48
+ }
49
+ export type { DoctorReport, IndexPlan, KnowledgeBase, KnowledgeStatusSnapshot, SearchResponse, SymbolSearchResponse };