@autorag/librarian 2.10.2 → 2.10.4
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 +23 -3
- package/dist/agent/agent.d.ts +1 -1
- package/dist/agent/answer-guidelines.d.ts +17 -0
- package/dist/agent/search-documents.d.ts +1 -1
- package/dist/cli/commands/types.d.ts +2 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +925 -592
- package/dist/core.js +1641 -1327
- package/dist/datasource/sidecar/descriptors.d.ts +1 -0
- package/dist/datasource/skills/lazykatok/skill.d.ts +13 -0
- package/dist/everything/client.d.ts +5 -0
- package/dist/filesystem/path-exclusions.d.ts +2 -0
- package/dist/fsearch/client.d.ts +3 -2
- package/dist/fsearch/walk.d.ts +2 -0
- package/dist/index.js +1642 -1328
- package/dist/mcp/index.js +1642 -1328
- package/dist/minsync/index.d.ts +1 -1
- package/dist/minsync/installer.d.ts +1 -1
- package/dist/minsync/types.d.ts +7 -0
- package/package.json +1 -1
- package/skills/autorag-doctor/SKILL.md +1 -0
- package/skills/autorag-lite-setup/SKILL.md +1 -1
- package/skills/autorag-setup/SKILL.md +1 -1
package/dist/index.js
CHANGED
|
@@ -2109,6 +2109,25 @@ function errorMessage(error) {
|
|
|
2109
2109
|
var MANIFEST_FILENAME = "manifest.json";
|
|
2110
2110
|
var init_bundle = () => {};
|
|
2111
2111
|
|
|
2112
|
+
// src/filesystem/path-exclusions.ts
|
|
2113
|
+
import { posix as posix2, win32 as win322 } from "node:path";
|
|
2114
|
+
function createPathExclusionMatcher(excludedPaths, platform = process.platform) {
|
|
2115
|
+
const paths = platform === "win32" ? win322 : posix2;
|
|
2116
|
+
const normalize = (path) => {
|
|
2117
|
+
const absolute = paths.resolve(path);
|
|
2118
|
+
return platform === "win32" ? absolute.toLowerCase() : absolute;
|
|
2119
|
+
};
|
|
2120
|
+
const excluded = excludedPaths.map((path) => {
|
|
2121
|
+
const absolute = normalize(path);
|
|
2122
|
+
return { absolute, prefix: absolute.endsWith(paths.sep) ? absolute : `${absolute}${paths.sep}` };
|
|
2123
|
+
});
|
|
2124
|
+
return (path) => {
|
|
2125
|
+
const absolute = normalize(path);
|
|
2126
|
+
return excluded.some((entry) => absolute === entry.absolute || absolute.startsWith(entry.prefix));
|
|
2127
|
+
};
|
|
2128
|
+
}
|
|
2129
|
+
var init_path_exclusions = () => {};
|
|
2130
|
+
|
|
2112
2131
|
// src/everything/client.ts
|
|
2113
2132
|
import { spawn as spawn2 } from "node:child_process";
|
|
2114
2133
|
import { createHash as createHash4 } from "node:crypto";
|
|
@@ -2226,6 +2245,7 @@ class EverythingClient {
|
|
|
2226
2245
|
run;
|
|
2227
2246
|
launch;
|
|
2228
2247
|
stateDir;
|
|
2248
|
+
isExcludedPath;
|
|
2229
2249
|
binaries;
|
|
2230
2250
|
operation = Promise.resolve();
|
|
2231
2251
|
constructor(options) {
|
|
@@ -2235,6 +2255,7 @@ class EverythingClient {
|
|
|
2235
2255
|
this.run = options.run ?? runProcess;
|
|
2236
2256
|
this.launch = options.launch ?? launchDetached;
|
|
2237
2257
|
this.stateDir = join6(options.root, ".autorag", "everything");
|
|
2258
|
+
this.isExcludedPath = createPathExclusionMatcher(options.excludeFolders ?? [], "win32");
|
|
2238
2259
|
}
|
|
2239
2260
|
isSupported() {
|
|
2240
2261
|
return this.platform === "win32";
|
|
@@ -2254,6 +2275,9 @@ class EverythingClient {
|
|
|
2254
2275
|
}
|
|
2255
2276
|
const es = { ok: true, esPath: binaries.esPath };
|
|
2256
2277
|
const timeoutMs = this.options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
2278
|
+
if ((this.options.excludeFolders?.length ?? 0) > 0) {
|
|
2279
|
+
return this.searchWithExclusions(es.esPath, request, timeoutMs);
|
|
2280
|
+
}
|
|
2257
2281
|
const args = buildEverythingSearchArgs(this.instanceName, request, timeoutMs);
|
|
2258
2282
|
const result = await this.run(es.esPath, args, timeoutMs + 5000);
|
|
2259
2283
|
if (result.code !== 0)
|
|
@@ -2265,6 +2289,50 @@ class EverythingClient {
|
|
|
2265
2289
|
}
|
|
2266
2290
|
});
|
|
2267
2291
|
}
|
|
2292
|
+
async searchWithExclusions(esPath, request, timeoutMs) {
|
|
2293
|
+
const deadline = Date.now() + timeoutMs;
|
|
2294
|
+
const offset = request.offset ?? 0;
|
|
2295
|
+
const maxResults = request.maxResults ?? DEFAULT_MAX_RESULTS;
|
|
2296
|
+
const results = [];
|
|
2297
|
+
let skipped = 0;
|
|
2298
|
+
let nativeOffset = 0;
|
|
2299
|
+
const timedOut = () => ({
|
|
2300
|
+
ok: false,
|
|
2301
|
+
reason: "search-failed",
|
|
2302
|
+
message: `Everything search exceeded ${timeoutMs}ms while filtering excluded paths; narrow the query or increase the Everything timeout.`
|
|
2303
|
+
});
|
|
2304
|
+
for (;; ) {
|
|
2305
|
+
const remainingMs = deadline - Date.now();
|
|
2306
|
+
if (remainingMs <= 0)
|
|
2307
|
+
return timedOut();
|
|
2308
|
+
const args = buildEverythingSearchArgs(this.instanceName, { ...request, offset: nativeOffset, maxResults: MAX_FILTER_CANDIDATES }, remainingMs);
|
|
2309
|
+
const response = await this.run(esPath, args, remainingMs + 5000);
|
|
2310
|
+
if (response.code !== 0)
|
|
2311
|
+
return this.failure("search-failed", esPath, args, response);
|
|
2312
|
+
if (Date.now() >= deadline)
|
|
2313
|
+
return timedOut();
|
|
2314
|
+
let entries;
|
|
2315
|
+
try {
|
|
2316
|
+
entries = parseEverythingJson(response.stdout);
|
|
2317
|
+
} catch (error) {
|
|
2318
|
+
return { ok: false, reason: "search-failed", message: error.message };
|
|
2319
|
+
}
|
|
2320
|
+
for (const entry of entries) {
|
|
2321
|
+
if (this.isExcludedPath(entry.path))
|
|
2322
|
+
continue;
|
|
2323
|
+
if (skipped < offset) {
|
|
2324
|
+
skipped += 1;
|
|
2325
|
+
continue;
|
|
2326
|
+
}
|
|
2327
|
+
results.push(entry);
|
|
2328
|
+
if (results.length >= maxResults)
|
|
2329
|
+
return { ok: true, results };
|
|
2330
|
+
}
|
|
2331
|
+
if (entries.length < MAX_FILTER_CANDIDATES)
|
|
2332
|
+
return { ok: true, results };
|
|
2333
|
+
nativeOffset += entries.length;
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2268
2336
|
index() {
|
|
2269
2337
|
return this.serialize(async () => {
|
|
2270
2338
|
const es = await this.ensureRunning(true);
|
|
@@ -2338,7 +2406,8 @@ class EverythingClient {
|
|
|
2338
2406
|
excludeFolders: [
|
|
2339
2407
|
...new Set([
|
|
2340
2408
|
join6(this.options.root, ".autorag"),
|
|
2341
|
-
...this.options.folders.map((folder) => join6(folder, ".autorag"))
|
|
2409
|
+
...this.options.folders.map((folder) => join6(folder, ".autorag")),
|
|
2410
|
+
...this.options.excludeFolders ?? []
|
|
2342
2411
|
])
|
|
2343
2412
|
]
|
|
2344
2413
|
}));
|
|
@@ -2432,8 +2501,9 @@ function launchDetached(command, args) {
|
|
|
2432
2501
|
child.on("error", () => {});
|
|
2433
2502
|
child.unref();
|
|
2434
2503
|
}
|
|
2435
|
-
var DEFAULT_TIMEOUT_MS2 = 30000, DEFAULT_STARTUP_TIMEOUT_MS = 20000, DEFAULT_INDEX_TIMEOUT_MS, DEFAULT_POLL_INTERVAL_MS = 250, DEFAULT_MAX_RESULTS = 100, MAX_OUTPUT_BYTES, VERSION_PATTERN;
|
|
2504
|
+
var DEFAULT_TIMEOUT_MS2 = 30000, DEFAULT_STARTUP_TIMEOUT_MS = 20000, DEFAULT_INDEX_TIMEOUT_MS, DEFAULT_POLL_INTERVAL_MS = 250, DEFAULT_MAX_RESULTS = 100, MAX_FILTER_CANDIDATES = 1000, MAX_OUTPUT_BYTES, VERSION_PATTERN;
|
|
2436
2505
|
var init_client = __esm(() => {
|
|
2506
|
+
init_path_exclusions();
|
|
2437
2507
|
init_bundle();
|
|
2438
2508
|
DEFAULT_INDEX_TIMEOUT_MS = 10 * 60000;
|
|
2439
2509
|
MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
|
|
@@ -2453,6 +2523,7 @@ function compare(a, b) {
|
|
|
2453
2523
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
2454
2524
|
}
|
|
2455
2525
|
async function walkFileSearch(folders, request, options = {}) {
|
|
2526
|
+
const isExcluded = createPathExclusionMatcher(options.excludeFolders ?? []);
|
|
2456
2527
|
const maxVisited = options.maxVisited ?? DEFAULT_MAX_VISITED;
|
|
2457
2528
|
const maxMatches = options.maxMatches ?? DEFAULT_MAX_MATCHES;
|
|
2458
2529
|
const deadline = Date.now() + (options.deadlineMs ?? DEFAULT_DEADLINE_MS);
|
|
@@ -2475,6 +2546,8 @@ async function walkFileSearch(folders, request, options = {}) {
|
|
|
2475
2546
|
outer:
|
|
2476
2547
|
while (pending.length > 0) {
|
|
2477
2548
|
const dir = pending.pop();
|
|
2549
|
+
if (isExcluded(dir))
|
|
2550
|
+
continue;
|
|
2478
2551
|
if (Date.now() >= deadline) {
|
|
2479
2552
|
truncated = true;
|
|
2480
2553
|
break;
|
|
@@ -2492,6 +2565,8 @@ async function walkFileSearch(folders, request, options = {}) {
|
|
|
2492
2565
|
}
|
|
2493
2566
|
visited += 1;
|
|
2494
2567
|
const path = join7(dir, dirent.name);
|
|
2568
|
+
if (isExcluded(path))
|
|
2569
|
+
continue;
|
|
2495
2570
|
if (dirent.isDirectory()) {
|
|
2496
2571
|
if (dirent.name === ".autorag")
|
|
2497
2572
|
continue;
|
|
@@ -2526,6 +2601,8 @@ async function walkFileSearch(folders, request, options = {}) {
|
|
|
2526
2601
|
}
|
|
2527
2602
|
}
|
|
2528
2603
|
for (const folder of folders) {
|
|
2604
|
+
if (isExcluded(folder))
|
|
2605
|
+
continue;
|
|
2529
2606
|
if (!underPath(folder) || !matches(folder))
|
|
2530
2607
|
continue;
|
|
2531
2608
|
if (request.kind === "files")
|
|
@@ -2552,6 +2629,7 @@ async function walkFileSearch(folders, request, options = {}) {
|
|
|
2552
2629
|
}
|
|
2553
2630
|
var DEFAULT_MAX_VISITED = 500000, DEFAULT_DEADLINE_MS = 20000, DEFAULT_MAX_MATCHES = 1e4, SORT_ORDERS;
|
|
2554
2631
|
var init_walk = __esm(() => {
|
|
2632
|
+
init_path_exclusions();
|
|
2555
2633
|
SORT_ORDERS = {
|
|
2556
2634
|
"name-ascending": (a, b) => compare(a.name, b.name),
|
|
2557
2635
|
"name-descending": (a, b) => compare(b.name, a.name),
|
|
@@ -2661,6 +2739,7 @@ class FSearchClient {
|
|
|
2661
2739
|
launch;
|
|
2662
2740
|
isAlive;
|
|
2663
2741
|
kill;
|
|
2742
|
+
isExcludedPath;
|
|
2664
2743
|
stateDir;
|
|
2665
2744
|
dbPath;
|
|
2666
2745
|
pidPath;
|
|
@@ -2673,6 +2752,7 @@ class FSearchClient {
|
|
|
2673
2752
|
this.launch = options.launch ?? launchDetached2;
|
|
2674
2753
|
this.isAlive = options.isProcessAlive ?? defaultIsProcessAlive;
|
|
2675
2754
|
this.kill = options.killProcess ?? ((pid) => process.kill(pid, "SIGTERM"));
|
|
2755
|
+
this.isExcludedPath = createPathExclusionMatcher(options.excludeFolders ?? []);
|
|
2676
2756
|
this.stateDir = join8(options.root, ".autorag", "fsearch");
|
|
2677
2757
|
this.dbPath = join8(this.stateDir, "fsearch.db");
|
|
2678
2758
|
this.pidPath = join8(this.stateDir, "watch.pid");
|
|
@@ -2690,6 +2770,7 @@ class FSearchClient {
|
|
|
2690
2770
|
if (unavailable !== undefined || !binary.ok) {
|
|
2691
2771
|
try {
|
|
2692
2772
|
const walked = await walkFileSearch(this.options.folders, request, {
|
|
2773
|
+
excludeFolders: this.options.excludeFolders,
|
|
2693
2774
|
maxVisited: this.options.walkMaxVisited,
|
|
2694
2775
|
deadlineMs: this.options.walkDeadlineMs
|
|
2695
2776
|
});
|
|
@@ -2704,7 +2785,9 @@ class FSearchClient {
|
|
|
2704
2785
|
return { ok: false, reason: "search-failed", message: error.message };
|
|
2705
2786
|
}
|
|
2706
2787
|
}
|
|
2707
|
-
const
|
|
2788
|
+
const hasExclusions = (this.options.excludeFolders?.length ?? 0) > 0;
|
|
2789
|
+
const nativeRequest = hasExclusions ? { ...request, offset: 0, maxResults: MAX_RESULTS_CAP } : request;
|
|
2790
|
+
const args = buildFSearchSearchArgs(this.dbPath, this.socketPath(), nativeRequest);
|
|
2708
2791
|
const result = await this.run(binary.path, args, this.options.timeoutMs ?? DEFAULT_TIMEOUT_MS3);
|
|
2709
2792
|
if (result.code !== 0)
|
|
2710
2793
|
return this.failure("search-failed", binary.path, args, result);
|
|
@@ -2715,6 +2798,10 @@ class FSearchClient {
|
|
|
2715
2798
|
return { ok: false, reason: "search-failed", message: error.message };
|
|
2716
2799
|
}
|
|
2717
2800
|
let entries = parsed.entries;
|
|
2801
|
+
if (hasExclusions) {
|
|
2802
|
+
const isExcluded = this.isExcludedPath;
|
|
2803
|
+
entries = entries.filter((entry) => !isExcluded(entry.path));
|
|
2804
|
+
}
|
|
2718
2805
|
if (request.path !== undefined) {
|
|
2719
2806
|
const prefix = request.path.endsWith(sep3) ? request.path : `${request.path}${sep3}`;
|
|
2720
2807
|
entries = entries.filter((entry) => entry.path === request.path || entry.path.startsWith(prefix));
|
|
@@ -2724,7 +2811,16 @@ class FSearchClient {
|
|
|
2724
2811
|
const maxResults = Math.min(request.maxResults ?? DEFAULT_MAX_RESULTS2, MAX_RESULTS_CAP);
|
|
2725
2812
|
if (entries.length > maxResults)
|
|
2726
2813
|
entries = entries.slice(0, maxResults);
|
|
2727
|
-
return {
|
|
2814
|
+
return {
|
|
2815
|
+
ok: true,
|
|
2816
|
+
backend: "fsearch-cli",
|
|
2817
|
+
results: entries,
|
|
2818
|
+
total: parsed.total,
|
|
2819
|
+
...hasExclusions && parsed.total !== undefined && parsed.total > parsed.entries.length && entries.length < maxResults ? {
|
|
2820
|
+
truncated: true,
|
|
2821
|
+
note: `FSearch checked ${parsed.entries.length} of ${parsed.total} native matches before exclusions (candidate limit ${MAX_RESULTS_CAP}); results may be incomplete. Narrow the query.`
|
|
2822
|
+
} : {}
|
|
2823
|
+
};
|
|
2728
2824
|
});
|
|
2729
2825
|
}
|
|
2730
2826
|
index() {
|
|
@@ -2918,6 +3014,7 @@ function defaultIsProcessAlive(pid) {
|
|
|
2918
3014
|
}
|
|
2919
3015
|
var DEFAULT_TIMEOUT_MS3 = 30000, DEFAULT_STARTUP_TIMEOUT_MS2 = 1e4, STOP_TIMEOUT_MS = 2000, DEFAULT_INDEX_TIMEOUT_MS2, DEFAULT_POLL_INTERVAL_MS2 = 250, DEFAULT_MAX_RESULTS2 = 100, MAX_RESULTS_CAP = 1000, MAX_OUTPUT_BYTES2, SORT_KEYS;
|
|
2920
3016
|
var init_client2 = __esm(() => {
|
|
3017
|
+
init_path_exclusions();
|
|
2921
3018
|
init_walk();
|
|
2922
3019
|
DEFAULT_INDEX_TIMEOUT_MS2 = 10 * 60000;
|
|
2923
3020
|
MAX_OUTPUT_BYTES2 = 8 * 1024 * 1024;
|
|
@@ -5513,7 +5610,8 @@ class MinSyncClient {
|
|
|
5513
5610
|
restoreConfig();
|
|
5514
5611
|
return this.lockHeldResult(result.stderr);
|
|
5515
5612
|
}
|
|
5516
|
-
|
|
5613
|
+
const partial = !result.ok && result.code === MINSYNC_PARTIAL_SYNC_EXIT_CODE ? readPartialSync(result.stdout) : undefined;
|
|
5614
|
+
if (!result.ok && partial === undefined) {
|
|
5517
5615
|
restoreConfig();
|
|
5518
5616
|
return {
|
|
5519
5617
|
ok: false,
|
|
@@ -5533,10 +5631,12 @@ class MinSyncClient {
|
|
|
5533
5631
|
}
|
|
5534
5632
|
if (effective.identity)
|
|
5535
5633
|
this.writeIdentity(effective.identity);
|
|
5634
|
+
const filesFailed = partial?.filesFailed ?? [];
|
|
5536
5635
|
return {
|
|
5537
5636
|
ok: true,
|
|
5538
5637
|
synced: readSyncedCount(result.stdout),
|
|
5539
5638
|
workspacePath: this.workspacePath,
|
|
5639
|
+
...filesFailed.length > 0 ? { filesFailed } : {},
|
|
5540
5640
|
...identityChanged ? {
|
|
5541
5641
|
diagnostic: {
|
|
5542
5642
|
code: "embedding-identity-mismatch",
|
|
@@ -5568,6 +5668,19 @@ function readConfigSnapshot(configPath) {
|
|
|
5568
5668
|
throw error;
|
|
5569
5669
|
}
|
|
5570
5670
|
}
|
|
5671
|
+
function readPartialSync(stdout) {
|
|
5672
|
+
const parsed = parseJson(stdout);
|
|
5673
|
+
if (!isRecord4(parsed) || parsed.partial !== true)
|
|
5674
|
+
return;
|
|
5675
|
+
const failures = Array.isArray(parsed.files_failed) ? parsed.files_failed : [];
|
|
5676
|
+
return {
|
|
5677
|
+
filesFailed: failures.filter(isRecord4).map((failure) => ({
|
|
5678
|
+
path: typeof failure.path === "string" ? failure.path : "(unknown)",
|
|
5679
|
+
stage: typeof failure.stage === "string" ? failure.stage : "unknown",
|
|
5680
|
+
error: typeof failure.error === "string" ? failure.error : "unknown error"
|
|
5681
|
+
}))
|
|
5682
|
+
};
|
|
5683
|
+
}
|
|
5571
5684
|
function readSyncedCount(stdout) {
|
|
5572
5685
|
const parsed = parseJson(stdout);
|
|
5573
5686
|
if (!isRecord4(parsed))
|
|
@@ -5623,7 +5736,7 @@ function isIdentity(value) {
|
|
|
5623
5736
|
function isRecord4(value) {
|
|
5624
5737
|
return typeof value === "object" && value !== null;
|
|
5625
5738
|
}
|
|
5626
|
-
var MINSYNC_OLLAMA_MIGRATION_MESSAGE = "This workspace uses the legacy 768-dimensional Ollama/TEI embedding path. Reindex explicitly, or pin an explicit Ollama/TEI embedder config before using the new default runtime.", API_KEY_ENV_PATTERN, MINSYNC_LOCK_HELD_EXIT_CODE = 3, MinSyncQueryError;
|
|
5739
|
+
var MINSYNC_OLLAMA_MIGRATION_MESSAGE = "This workspace uses the legacy 768-dimensional Ollama/TEI embedding path. Reindex explicitly, or pin an explicit Ollama/TEI embedder config before using the new default runtime.", API_KEY_ENV_PATTERN, MINSYNC_LOCK_HELD_EXIT_CODE = 3, MINSYNC_PARTIAL_SYNC_EXIT_CODE = 6, MinSyncQueryError;
|
|
5627
5740
|
var init_client4 = __esm(() => {
|
|
5628
5741
|
init_embedder_config();
|
|
5629
5742
|
init_errors();
|
|
@@ -5867,7 +5980,7 @@ function isGitHubAsset(value) {
|
|
|
5867
5980
|
function isRecord5(value) {
|
|
5868
5981
|
return typeof value === "object" && value !== null;
|
|
5869
5982
|
}
|
|
5870
|
-
var LATEST_RELEASE_URL = "https://api.github.com/repos/NomaDamas/MinSync/releases/latest", SHA256_HEX_PATTERN, MINSYNC_VERSION = "0.4.
|
|
5983
|
+
var LATEST_RELEASE_URL = "https://api.github.com/repos/NomaDamas/MinSync/releases/latest", SHA256_HEX_PATTERN, MINSYNC_VERSION = "0.4.8", MINSYNC_CARGO_INSTALL_TIMEOUT_MS, CARGO_PROBE_TIMEOUT_MS = 5000, MinSyncReleaseError;
|
|
5871
5984
|
var init_installer2 = __esm(() => {
|
|
5872
5985
|
init_process();
|
|
5873
5986
|
SHA256_HEX_PATTERN = /^[a-f0-9]{64}$/;
|
|
@@ -9170,12 +9283,43 @@ function digitsEndAt(text, from) {
|
|
|
9170
9283
|
end += 1;
|
|
9171
9284
|
return end;
|
|
9172
9285
|
}
|
|
9173
|
-
function continuesAsProse(answer, from) {
|
|
9174
|
-
|
|
9286
|
+
function continuesAsProse(answer, openIndex, from) {
|
|
9287
|
+
let cursor = from;
|
|
9288
|
+
let leadingEmphasis = 0;
|
|
9289
|
+
while (openIndex - 1 - leadingEmphasis >= 0 && (answer[openIndex - 1 - leadingEmphasis] === "*" || answer[openIndex - 1 - leadingEmphasis] === "_")) {
|
|
9290
|
+
leadingEmphasis += 1;
|
|
9291
|
+
}
|
|
9292
|
+
if (leadingEmphasis > 0) {
|
|
9293
|
+
let trailingEmphasis = 0;
|
|
9294
|
+
while (cursor + trailingEmphasis < answer.length && trailingEmphasis < leadingEmphasis && answer[cursor + trailingEmphasis] === answer[openIndex - 1 - trailingEmphasis]) {
|
|
9295
|
+
trailingEmphasis += 1;
|
|
9296
|
+
}
|
|
9297
|
+
if (trailingEmphasis === leadingEmphasis)
|
|
9298
|
+
cursor += trailingEmphasis;
|
|
9299
|
+
}
|
|
9300
|
+
const tokenStart = openIndex - leadingEmphasis;
|
|
9301
|
+
const linePrefix = answer.slice(answer.lastIndexOf(`
|
|
9302
|
+
`, tokenStart - 1) + 1, tokenStart);
|
|
9303
|
+
const atHeadingStart = /^[ \t>*-]*$/u.test(linePrefix);
|
|
9304
|
+
if (atHeadingStart && answer[cursor] === ":")
|
|
9305
|
+
cursor += 1;
|
|
9306
|
+
if (answer[cursor] !== " " && answer[cursor] !== " ")
|
|
9175
9307
|
return false;
|
|
9176
|
-
|
|
9308
|
+
cursor += 1;
|
|
9309
|
+
while (cursor < answer.length && (answer[cursor] === "*" || answer[cursor] === "_" || answer[cursor] === '"' || answer[cursor] === "'" || answer[cursor] === "“" || answer[cursor] === "‘")) {
|
|
9310
|
+
cursor += 1;
|
|
9311
|
+
}
|
|
9312
|
+
const next = answer.codePointAt(cursor);
|
|
9177
9313
|
return next !== undefined && /[\p{L}\p{N}]/u.test(String.fromCodePoint(next));
|
|
9178
9314
|
}
|
|
9315
|
+
function isLegalPinpoint(answer, openIndex, afterCloseIndex) {
|
|
9316
|
+
if (PINPOINT_RANGE_AHEAD.test(answer.slice(afterCloseIndex, afterCloseIndex + 16)))
|
|
9317
|
+
return true;
|
|
9318
|
+
if (PINPOINT_RANGE_BEHIND.test(answer.slice(Math.max(0, openIndex - 16), openIndex)))
|
|
9319
|
+
return true;
|
|
9320
|
+
const prefixWindow = answer.slice(Math.max(0, openIndex - 120), openIndex);
|
|
9321
|
+
return PARA_PINPOINT_PREFIX.test(prefixWindow) || CLAUSE_START_AT_PREFIX.test(prefixWindow) || CASE_CITATION_AT_PREFIX.test(prefixWindow);
|
|
9322
|
+
}
|
|
9179
9323
|
function evidenceMarkerAt(answer, index) {
|
|
9180
9324
|
const ids = [];
|
|
9181
9325
|
let cursor = index + 1;
|
|
@@ -9241,7 +9385,7 @@ function answerMarkers(answer, isFile = () => false) {
|
|
|
9241
9385
|
}
|
|
9242
9386
|
if (char === "[") {
|
|
9243
9387
|
const digitsEnd = digitsEndAt(answer, index + 1);
|
|
9244
|
-
if (digitsEnd > index + 1 && answer[digitsEnd] === "]" && answer[digitsEnd + 1] !== "(" && !continuesAsProse(answer, digitsEnd + 1)) {
|
|
9388
|
+
if (digitsEnd > index + 1 && answer[digitsEnd] === "]" && answer[digitsEnd + 1] !== "(" && !continuesAsProse(answer, index, digitsEnd + 1) && !isLegalPinpoint(answer, index, digitsEnd + 1)) {
|
|
9245
9389
|
markers.push({
|
|
9246
9390
|
kind: "number",
|
|
9247
9391
|
start: leadingStart(index),
|
|
@@ -9313,7 +9457,14 @@ function assertResultsMappingOneToOne(label, results, mapping) {
|
|
|
9313
9457
|
].filter((note) => note !== undefined);
|
|
9314
9458
|
throw new Error(`${label}: result numbers and mapping numbers must be one-to-one, but results contain ${formatCitationList(resultNumbers)} ` + `and mapping contains ${formatCitationList(mappingNumbers)}` + (duplicateNotes.length > 0 ? ` (${duplicateNotes.join("; ")})` : "") + ". Give every result a unique number with exactly one mapping entry carrying the same number and no mapping entry without a result.");
|
|
9315
9459
|
}
|
|
9316
|
-
var MAX_FILE_MARKER_CLOSERS = 8, FILE_MARKER_PREFIX = "[file:";
|
|
9460
|
+
var MAX_FILE_MARKER_CLOSERS = 8, FILE_MARKER_PREFIX = "[file:", PARA_PINPOINT_PREFIX, CLAUSE_START_AT_PREFIX, CASE_CITATION_AT_PREFIX, PINPOINT_RANGE_AHEAD, PINPOINT_RANGE_BEHIND;
|
|
9461
|
+
var init_citations = __esm(() => {
|
|
9462
|
+
PARA_PINPOINT_PREFIX = /(?:^|[^\p{L}\p{N}])(?:paras?\.?|paragraphs?)(?:[ \t\u00a0]+\[\d+\][ \t\u00a0]*(?:[-–—]|,(?:[ \t\u00a0]*(?:and|or)\b)?|and\b|or\b))*[ \t\u00a0]*$/iu;
|
|
9463
|
+
CLAUSE_START_AT_PREFIX = /(?:^|[\n.!?؛;:()]|[>*-])[ \t\u00a0]*At(?:[ \t\u00a0]+\[\d+\][ \t\u00a0]*(?:[-–—]|,(?:[ \t\u00a0]*(?:and|or)\b)?|and\b|or\b))*[ \t\u00a0]+$/u;
|
|
9464
|
+
CASE_CITATION_AT_PREFIX = /(?:\[\d{4}\][^\n.;]*?|\b(?:v|vs\.?)\s+[^\n.;]{1,60}?|\bs(?:ection)?[ \t\u00a0]+\d+[A-Za-z]?(?:\(\d+\))?[^\n.;]{0,30}?)[ \t\u00a0]+at(?:[ \t\u00a0]+\[\d+\][ \t\u00a0]*(?:[-–—]|,(?:[ \t\u00a0]*(?:and|or)\b)?|and\b|or\b))*[ \t\u00a0]+$/iu;
|
|
9465
|
+
PINPOINT_RANGE_AHEAD = /^[ \t\u00a0]*[-–—][ \t\u00a0]*\[\d+\]/u;
|
|
9466
|
+
PINPOINT_RANGE_BEHIND = /\[\d+\][ \t\u00a0]*[-–—][ \t\u00a0]*$/u;
|
|
9467
|
+
});
|
|
9317
9468
|
|
|
9318
9469
|
// src/agent/evidence-ledger.ts
|
|
9319
9470
|
import { createHash as createHash10 } from "node:crypto";
|
|
@@ -9597,6 +9748,7 @@ function deriveResultsFromAnswer(text, ledger, options) {
|
|
|
9597
9748
|
}
|
|
9598
9749
|
var MAX_EXCERPT_CHARS = 400, MAX_CLAIM_CHARS = 280, CLAIM_LOOKBACK_CHARS = 600, SENTENCE_END, LEADING_LIST_MARK, EVIDENCE_MARKER_TEXT, LEADING_BLANK;
|
|
9599
9750
|
var init_answer_citations = __esm(() => {
|
|
9751
|
+
init_citations();
|
|
9600
9752
|
init_evidence_ledger();
|
|
9601
9753
|
SENTENCE_END = /[.!?。!?]/u;
|
|
9602
9754
|
LEADING_LIST_MARK = /^[\s\-*•>]+/u;
|
|
@@ -9605,7 +9757,7 @@ var init_answer_citations = __esm(() => {
|
|
|
9605
9757
|
});
|
|
9606
9758
|
|
|
9607
9759
|
// src/agent/answer-guidelines.ts
|
|
9608
|
-
var ANSWER_IMAGE_EMBED_RULE = "**Images**: when a retrieved result is itself an image file (png, jpg, jpeg, gif, webp, svg, bmp, avif, heic, tiff) and showing it answers the question, embed it in the answer as a markdown image on its own line: ``, followed by its citation, e.g. ` [e2]`. Use only the real source path of retrieved evidence. Never invent a path, use relative paths, or embed remote URLs. Apart from these image embeds, the no-file-paths rule stands.", ANSWER_IMAGE_DELTA_RULE = "An image already embedded in the first answer must not be embedded again.", ANSWER_CITATION_RULE = "**Citations**: cite supporting evidence inline with the evidence id shown next to each retrieved result, in square brackets (e.g. [e3], or [e3][e7] for two). Copy ids exactly; never invent one. For a local file you opened yourself with `bash`, cite `[file:<absolute path>]`. Cite the evidence that backs a sentence at the end of that sentence. Do not cite numbers, paths, or anything else.";
|
|
9760
|
+
var ANSWER_IMAGE_EMBED_RULE = "**Images**: when a retrieved result is itself an image file (png, jpg, jpeg, gif, webp, svg, bmp, avif, heic, tiff) and showing it answers the question, embed it in the answer as a markdown image on its own line: ``, followed by its citation, e.g. ` [e2]`. Use only the real source path of retrieved evidence. Never invent a path, use relative paths, or embed remote URLs. Apart from these image embeds, the no-file-paths rule stands.", ANSWER_IMAGE_DELTA_RULE = "An image already embedded in the first answer must not be embedded again.", ANSWER_CITATION_RULE = "**Citations**: cite supporting evidence inline with the evidence id shown next to each retrieved result, in square brackets (e.g. [e3], or [e3][e7] for two). Copy ids exactly; never invent one. For a local file you opened yourself with `bash`, cite `[file:<absolute path>]`. Cite the evidence that backs a sentence at the end of that sentence. Do not cite numbers, paths, or anything else.", ANSWER_DELIVERABLE_RULE = '**Deliverables and artifacts**: if the user asks you to draft, write, generate, or prepare a deliverable or artifact (a reply email, letter, legal opinion, summary document, standard-format case citation block, checklist, report, or workflow document — including requests phrased as "how should I reply..." to a specific message), produce the finished, ready-to-use artifact as a file (using `write`, `edit`, or `bash` in local sessions, without overwriting existing source files) in a file format, extension, and structure aligned with the context and domain (e.g. `.eml` or `.md`/`.txt` with headers for an email reply; `.md`, `.txt`, `.docx`, `.hwp`, or `.pdf` matching workspace conventions for a legal opinion, insertable case-citation block, or summary document; `.csv`, `.xlsx`, or `.json` for structured tabular data), containing the complete unabridged artifact (including required headers, precedent passages, pinpoint paragraphs, and standard-format citations) inside the file instead of merely describing how to produce it. Do NOT dump the full artifact text into your reply: unless the user explicitly requests otherwise, keep your reply concise within the at-most-5-bullet direct-answer format, clearly stating the created file\'s exact path/location and briefly summarizing what was generated with inline citations to the underlying source evidence (`[eN]` or `[file:<source path>]`); never cite the newly created deliverable file itself as `[file:...]`.', ANSWER_DELIVERABLE_DELTA_RULE = "If a deliverable or artifact was requested and the first answer could not write the file yet (the fast phase runs without tool calls) or only gave advice about it, create the complete context-aligned deliverable file now during verification and report the created file's location and a brief summary concisely.";
|
|
9609
9761
|
|
|
9610
9762
|
// src/agent/datasource-skill.ts
|
|
9611
9763
|
import { Type as Type3 } from "typebox";
|
|
@@ -13941,6 +14093,7 @@ function recordStructuredResultsSession(sessionId, query, details, memory, compo
|
|
|
13941
14093
|
}
|
|
13942
14094
|
var init_search_documents = __esm(() => {
|
|
13943
14095
|
init_memory();
|
|
14096
|
+
init_citations();
|
|
13944
14097
|
});
|
|
13945
14098
|
|
|
13946
14099
|
// src/agent/search-all-tool.ts
|
|
@@ -14257,6 +14410,10 @@ function buildSystemPrompt(config) {
|
|
|
14257
14410
|
const modelId = config.modelId ?? "the configured model";
|
|
14258
14411
|
const toolLines = [
|
|
14259
14412
|
toolLine(config, "bash", "read and inspect configured document collections with ls, find, grep, cat, and similar tools, and — in local sessions — organize local files when the user asks (rename, move, copy, create folders, move to trash)"),
|
|
14413
|
+
...config.remoteSession ? [] : [
|
|
14414
|
+
toolLine(config, "write", "create a new file in local sessions — use this to produce requested deliverables and artifacts in a file format aligned with the request and context without overwriting existing source files"),
|
|
14415
|
+
toolLine(config, "edit", "surgically update an existing deliverable or config file when the user asks (local sessions only)")
|
|
14416
|
+
],
|
|
14260
14417
|
toolLine(config, "jikji_find", "local discovery through Jikji answer packs"),
|
|
14261
14418
|
toolLine(config, "everything_search", "instant Windows file/folder name search (voidtools Everything) across the configured search folders"),
|
|
14262
14419
|
toolLine(config, "fsearch_search", "instant macOS/Linux file/folder name search (fsearch-cli/FSearch) across the configured search folders, with a slow filesystem-walk fallback"),
|
|
@@ -14273,6 +14430,12 @@ function buildSystemPrompt(config) {
|
|
|
14273
14430
|
...config.toolNames.filter((name) => name.startsWith("search_datasource_")).map((name) => `- **${name}**: search only the ${name.slice("search_datasource_".length).replace(/_/g, "-")} datasource connection, spawning no other datasource CLIs`),
|
|
14274
14431
|
...config.toolNames.filter((name) => ![
|
|
14275
14432
|
"bash",
|
|
14433
|
+
"read",
|
|
14434
|
+
"write",
|
|
14435
|
+
"edit",
|
|
14436
|
+
"grep",
|
|
14437
|
+
"find",
|
|
14438
|
+
"ls",
|
|
14276
14439
|
"jikji_find",
|
|
14277
14440
|
"everything_search",
|
|
14278
14441
|
"fsearch_search",
|
|
@@ -14405,8 +14568,9 @@ Your answer is your final reply, written as plain text, never as a tool call. Ci
|
|
|
14405
14568
|
## Answer Guidelines
|
|
14406
14569
|
|
|
14407
14570
|
- **Complete vs. delta answer**: When no first answer reached the caller, give the complete core answer. When a first answer was already delivered, return only the delta against it — corrections and newly verified findings — and never repeat its unchanged content; if nothing changed, confirm the first answer in one short line.
|
|
14408
|
-
- **Bullet-point core answer**:
|
|
14409
|
-
- **Direct answer only**:
|
|
14571
|
+
- **Bullet-point core answer**: Unless the user explicitly requests a different format or length, provide the core answer to the user's question in at most 5 bullet points. If additional explanation or context is necessary, append it after the bullet points.
|
|
14572
|
+
- **Direct answer only**: Unless the user explicitly requests otherwise, the caller only needs the direct answer to their question. Never include specific file paths, datasource descriptions, or retrieval mechanics/principles in the answer (source paths are attached to each citation from the evidence ids you cite). Do not quote raw chunk text.
|
|
14573
|
+
- ${ANSWER_DELIVERABLE_RULE} ${ANSWER_DELIVERABLE_DELTA_RULE}
|
|
14410
14574
|
- ${ANSWER_CITATION_RULE}
|
|
14411
14575
|
- ${ANSWER_IMAGE_EMBED_RULE} ${ANSWER_IMAGE_DELTA_RULE}
|
|
14412
14576
|
- **No per-source negative reports**: Never report individual negative findings per source (e.g. "no information found in Slack" or "checked Drive but found nothing"). Simply omit unproductive sources from the answer and focus on what was found or provide a concise overall conclusion.
|
|
@@ -20363,7 +20527,8 @@ class AutoRAGAgent {
|
|
|
20363
20527
|
const everythingClient = new EverythingClient({
|
|
20364
20528
|
...options.everything ?? {},
|
|
20365
20529
|
root: this.workspaceProjectRoot,
|
|
20366
|
-
folders: this.searchPaths
|
|
20530
|
+
folders: this.searchPaths,
|
|
20531
|
+
excludeFolders: this.excludePaths
|
|
20367
20532
|
});
|
|
20368
20533
|
if (everythingClient.isSupported())
|
|
20369
20534
|
this.everythingClient = everythingClient;
|
|
@@ -20469,8 +20634,9 @@ class AutoRAGAgent {
|
|
|
20469
20634
|
return true;
|
|
20470
20635
|
});
|
|
20471
20636
|
this.tools = tools;
|
|
20637
|
+
const builtinToolNames = this.remoteSession ? PI_BUILTIN_TOOL_NAMES.filter((name) => name !== "write" && name !== "edit") : PI_BUILTIN_TOOL_NAMES;
|
|
20472
20638
|
const toolNames = [
|
|
20473
|
-
...
|
|
20639
|
+
...builtinToolNames,
|
|
20474
20640
|
...tools.map((tool) => tool.name),
|
|
20475
20641
|
...this.jevExtension !== undefined ? [JEV_TOOL_NAME] : []
|
|
20476
20642
|
];
|
|
@@ -20486,7 +20652,7 @@ class AutoRAGAgent {
|
|
|
20486
20652
|
this.innerAgent = {
|
|
20487
20653
|
state: {
|
|
20488
20654
|
systemPrompt,
|
|
20489
|
-
tools: [...
|
|
20655
|
+
tools: [...builtinToolNames.map((name) => ({ name })), ...tools],
|
|
20490
20656
|
messages: []
|
|
20491
20657
|
},
|
|
20492
20658
|
transformContext: (messages) => this.withMemoryContext(messages)
|
|
@@ -20803,6 +20969,7 @@ ${context.text}
|
|
|
20803
20969
|
...this.jevExtension !== undefined ? [this.jevExtension] : []
|
|
20804
20970
|
],
|
|
20805
20971
|
...this.jevExtension !== undefined ? { extensionToolNames: [JEV_TOOL_NAME] } : {},
|
|
20972
|
+
remoteSession: this.remoteSession,
|
|
20806
20973
|
...this.updateNotice === undefined ? {} : { updateNotice: this.updateNotice }
|
|
20807
20974
|
});
|
|
20808
20975
|
this.boundPiRuntime = runtime.runtime;
|
|
@@ -21729,8 +21896,9 @@ ${baseline}
|
|
|
21729
21896
|
` + `Produce the best complete, self-contained answer you can RIGHT NOW from this evidence. Do NOT call any search, retrieval, or file-reading tools and do NOT wait for more evidence. ` + `If the query is answerable from general knowledge alone, answer directly.
|
|
21730
21897
|
|
|
21731
21898
|
` + `Formatting and content rules for the answer:
|
|
21732
|
-
` + `-
|
|
21733
|
-
` + `-
|
|
21899
|
+
` + `- Unless the user explicitly requests a different format or length, provide the core answer to the user's question in at most 5 bullet points. If additional explanation is necessary, append it after the bullet points.
|
|
21900
|
+
` + `- Unless the user explicitly requests otherwise, answer the question directly. Do not include specific file paths, datasource descriptions, or retrieval mechanics in the answer text.
|
|
21901
|
+
` + `- ${ANSWER_DELIVERABLE_RULE}
|
|
21734
21902
|
` + `- ${ANSWER_CITATION_RULE}
|
|
21735
21903
|
` + `- ${ANSWER_IMAGE_EMBED_RULE}
|
|
21736
21904
|
` + `- Do not report per-source negative findings (e.g. "no information found in Slack" or "checked Drive but found nothing").
|
|
@@ -21769,12 +21937,14 @@ ${baseline}
|
|
|
21769
21937
|
` + `- NEVER restate or re-list first-answer facts that remain correct, and never repeat its bullet list.
|
|
21770
21938
|
` + `- Mark each item clearly as a correction or as a new finding.
|
|
21771
21939
|
` + `- If verification changed nothing and found nothing new, say so in one short line (the first answer is confirmed as-is) instead of restating it.
|
|
21940
|
+
` + `- ${ANSWER_DELIVERABLE_RULE} ${ANSWER_DELIVERABLE_DELTA_RULE}
|
|
21772
21941
|
` + `- ${ANSWER_CITATION_RULE} A correction or new finding that relies on evidence the first answer cited must cite that evidence's id again.
|
|
21773
21942
|
` + `- ${ANSWER_IMAGE_EMBED_RULE} ${ANSWER_IMAGE_DELTA_RULE}
|
|
21774
21943
|
` + `- Do not report per-source negative findings (e.g. "no information found in Slack").
|
|
21775
21944
|
` + `- When evidence conflicts, treat the freshest (most recent) information as the correct source of truth.` : `Formatting and content rules for the final answer (COMPLETE — no first answer reached the caller):
|
|
21776
|
-
` + `-
|
|
21777
|
-
` + `-
|
|
21945
|
+
` + `- Unless the user explicitly requests a different format or length, provide the core answer to the user's question in at most 5 bullet points. If additional explanation is necessary, append it after the bullet points.
|
|
21946
|
+
` + `- Unless the user explicitly requests otherwise, answer the question directly. Do not include specific file paths, datasource descriptions, or retrieval mechanics in the answer text.
|
|
21947
|
+
` + `- ${ANSWER_DELIVERABLE_RULE}${fastAnswer !== undefined ? ` ${ANSWER_DELIVERABLE_DELTA_RULE}` : ""}
|
|
21778
21948
|
` + `- ${ANSWER_CITATION_RULE}
|
|
21779
21949
|
` + `- ${ANSWER_IMAGE_EMBED_RULE}
|
|
21780
21950
|
` + `- Do not report per-source negative findings (e.g. "no information found in Slack").
|
|
@@ -21802,8 +21972,9 @@ ${initialRetrievalContext ?? "Pending; continue only with a brief progress state
|
|
|
21802
21972
|
` + `Treat candidates as unverified evidence, verify important claims against source files when needed, and use additional tools when needed. ` + `Judge relevance, conflicts, freshness, and sufficiency in this agent loop.
|
|
21803
21973
|
|
|
21804
21974
|
` + `Formatting and content rules for the answer:
|
|
21805
|
-
` + `-
|
|
21806
|
-
` + `-
|
|
21975
|
+
` + `- Unless the user explicitly requests a different format or length, provide the core answer to the user's question in at most 5 bullet points. If additional explanation is necessary, append it after the bullet points.
|
|
21976
|
+
` + `- Unless the user explicitly requests otherwise, answer the question directly. Do not include specific file paths, datasource descriptions, or retrieval mechanics in the answer text.
|
|
21977
|
+
` + `- ${ANSWER_DELIVERABLE_RULE}
|
|
21807
21978
|
` + `- ${ANSWER_CITATION_RULE}
|
|
21808
21979
|
` + `- ${ANSWER_IMAGE_EMBED_RULE}
|
|
21809
21980
|
` + `- Do not report per-source negative findings (e.g. "no information found in Slack").
|
|
@@ -21958,6 +22129,7 @@ ${initialRetrievalContext ?? "Pending; continue only with a brief progress state
|
|
|
21958
22129
|
...summary.diagnostics,
|
|
21959
22130
|
...minsyncDiagnostics,
|
|
21960
22131
|
...stagingExcludedDiagnostics(minsync?.stagingExcluded),
|
|
22132
|
+
...fileSkippedDiagnostics(minsync?.filesFailed),
|
|
21961
22133
|
...everythingDiagnostics,
|
|
21962
22134
|
...fsearchDiagnostics
|
|
21963
22135
|
],
|
|
@@ -22594,6 +22766,14 @@ function stagingExcludedDiagnostics(excluded) {
|
|
|
22594
22766
|
source
|
|
22595
22767
|
}));
|
|
22596
22768
|
}
|
|
22769
|
+
function fileSkippedDiagnostics(failed) {
|
|
22770
|
+
return (failed ?? []).map((failure) => ({
|
|
22771
|
+
code: "minsync-file-skipped",
|
|
22772
|
+
severity: "warning",
|
|
22773
|
+
message: `MinSync skipped this file at the ${failure.stage} stage and will retry it on the next sync: ${sanitizeDiagnosticMessage(failure.error)}`,
|
|
22774
|
+
source: failure.path
|
|
22775
|
+
}));
|
|
22776
|
+
}
|
|
22597
22777
|
function toSearchDiagnostic(diagnostic) {
|
|
22598
22778
|
return {
|
|
22599
22779
|
code: diagnostic.code,
|
|
@@ -22812,7 +22992,7 @@ var init_results = __esm(() => {
|
|
|
22812
22992
|
confidence: Type18.Optional(Type18.Number({ description: "Evidence confidence, 0..1", minimum: 0, maximum: 1 }))
|
|
22813
22993
|
});
|
|
22814
22994
|
answerSchema = Type18.String({
|
|
22815
|
-
description: `Answer for the caller.
|
|
22995
|
+
description: `Answer for the caller. Unless the user explicitly requests otherwise, provide at most 5 bullet points (plus optional explanation) and answer directly; reference results by bracketed number (e.g. [1], [2]) without file paths or raw chunk text, except the image-embed exception below. ${ANSWER_DELIVERABLE_RULE} ${ANSWER_CITATION_RULE} ${ANSWER_IMAGE_EMBED_RULE}`
|
|
22816
22996
|
});
|
|
22817
22997
|
warningsSchema = Type18.Optional(Type18.Array(Type18.String(), { description: "Optional warnings about this result set" }));
|
|
22818
22998
|
curatedResultFields = {
|
|
@@ -23110,7 +23290,7 @@ function chatCrawler(id) {
|
|
|
23110
23290
|
hierarchy: (metadata) => ["chats", str(metadata.chatName) ?? str(metadata.chatId) ?? "unknown"]
|
|
23111
23291
|
};
|
|
23112
23292
|
}
|
|
23113
|
-
var str = (value) => typeof value === "string" && value.length > 0 ? value : undefined, slack, CRAWLER_DESCRIPTORS;
|
|
23293
|
+
var str = (value) => typeof value === "string" && value.length > 0 ? value : undefined, slack, kakao, CRAWLER_DESCRIPTORS;
|
|
23114
23294
|
var init_descriptors = __esm(() => {
|
|
23115
23295
|
slack = {
|
|
23116
23296
|
id: "slack",
|
|
@@ -23141,10 +23321,32 @@ var init_descriptors = __esm(() => {
|
|
|
23141
23321
|
str(metadata.channelName) ?? str(metadata.channelId) ?? "unknown"
|
|
23142
23322
|
]
|
|
23143
23323
|
};
|
|
23324
|
+
kakao = {
|
|
23325
|
+
id: "kakao",
|
|
23326
|
+
keyExpression: "m.chunk_id",
|
|
23327
|
+
chunkId: (key) => key,
|
|
23328
|
+
fromClause: "chunks m",
|
|
23329
|
+
liveWhere: "length(trim(coalesce(m.text, ''))) > 0 and not (json_valid(m.text) and (json_extract(m.text, '$.feedType') is not null or json_extract(m.text, '$.csIP') is not null))",
|
|
23330
|
+
textExpression: "coalesce(m.text, '')",
|
|
23331
|
+
titleExpression: "m.chat_name",
|
|
23332
|
+
epochSecondsExpression: "unixepoch(m.started_at)",
|
|
23333
|
+
fts: { table: "chunks_fts", joinOn: "chunks_fts.rowid = m.rowid" },
|
|
23334
|
+
metadata: [
|
|
23335
|
+
{ sql: "m.chat_id", key: "chatId" },
|
|
23336
|
+
{ sql: "m.chat_name", key: "chatName" },
|
|
23337
|
+
{ sql: "m.sender_nickname", key: "senderNickname" },
|
|
23338
|
+
{ sql: "m.started_at", key: "startedAt" },
|
|
23339
|
+
{ sql: "m.ended_at", key: "endedAt" }
|
|
23340
|
+
],
|
|
23341
|
+
channelIdExpression: "m.chat_id",
|
|
23342
|
+
channelNameExpression: "m.chat_name",
|
|
23343
|
+
hierarchy: (metadata) => ["chats", str(metadata.chatName) ?? str(metadata.chatId) ?? "unknown"]
|
|
23344
|
+
};
|
|
23144
23345
|
CRAWLER_DESCRIPTORS = {
|
|
23145
23346
|
slack,
|
|
23146
23347
|
telegram: chatCrawler("telegram"),
|
|
23147
|
-
whatsapp: chatCrawler("whatsapp")
|
|
23348
|
+
whatsapp: chatCrawler("whatsapp"),
|
|
23349
|
+
kakao
|
|
23148
23350
|
};
|
|
23149
23351
|
});
|
|
23150
23352
|
|
|
@@ -27292,1436 +27494,1528 @@ var init_methods3 = __esm(() => {
|
|
|
27292
27494
|
DEFAULT_KAKAO_TAGS = ["kakaotalk", "personal", "pii"];
|
|
27293
27495
|
});
|
|
27294
27496
|
|
|
27295
|
-
// src/datasource/
|
|
27296
|
-
|
|
27297
|
-
|
|
27298
|
-
|
|
27299
|
-
|
|
27300
|
-
|
|
27301
|
-
|
|
27302
|
-
|
|
27303
|
-
|
|
27304
|
-
|
|
27305
|
-
|
|
27306
|
-
|
|
27307
|
-
|
|
27308
|
-
|
|
27309
|
-
|
|
27310
|
-
|
|
27311
|
-
|
|
27312
|
-
|
|
27313
|
-
|
|
27314
|
-
|
|
27315
|
-
|
|
27316
|
-
|
|
27317
|
-
capabilities: ["chat", "external-cli", "polling", "bm25", "semantic"],
|
|
27318
|
-
tags: this.tags,
|
|
27319
|
-
status: "active",
|
|
27320
|
-
requiresExternalCli: true,
|
|
27321
|
-
datasourceId: KAKAO_DATASOURCE_ID2,
|
|
27322
|
-
instanceId: this.instanceId,
|
|
27323
|
-
instances: this.instances
|
|
27324
|
-
};
|
|
27497
|
+
// src/datasource/sidecar/fusion.ts
|
|
27498
|
+
function encodeVector(vector) {
|
|
27499
|
+
const floats = Float32Array.from(vector);
|
|
27500
|
+
return new Uint8Array(floats.buffer, floats.byteOffset, floats.byteLength);
|
|
27501
|
+
}
|
|
27502
|
+
function decodeVector(blob) {
|
|
27503
|
+
if (blob.byteLength % Float32Array.BYTES_PER_ELEMENT !== 0)
|
|
27504
|
+
return;
|
|
27505
|
+
return new Float32Array(new Uint8Array(blob).buffer);
|
|
27506
|
+
}
|
|
27507
|
+
function cosine3(a, b) {
|
|
27508
|
+
if (a.length === 0 || a.length !== b.length)
|
|
27509
|
+
return 0;
|
|
27510
|
+
let dot = 0;
|
|
27511
|
+
let normA = 0;
|
|
27512
|
+
let normB = 0;
|
|
27513
|
+
for (let index = 0;index < a.length; index += 1) {
|
|
27514
|
+
const x = a[index] ?? 0;
|
|
27515
|
+
const y = b[index] ?? 0;
|
|
27516
|
+
dot += x * y;
|
|
27517
|
+
normA += x * x;
|
|
27518
|
+
normB += y * y;
|
|
27325
27519
|
}
|
|
27326
|
-
|
|
27327
|
-
return
|
|
27328
|
-
|
|
27329
|
-
|
|
27330
|
-
|
|
27331
|
-
|
|
27520
|
+
if (normA === 0 || normB === 0)
|
|
27521
|
+
return 0;
|
|
27522
|
+
return dot / Math.sqrt(normA * normB);
|
|
27523
|
+
}
|
|
27524
|
+
function topKByCosine(query, rows, k) {
|
|
27525
|
+
if (k <= 0)
|
|
27526
|
+
return [];
|
|
27527
|
+
const scored = [];
|
|
27528
|
+
for (const row of rows) {
|
|
27529
|
+
const score = cosine3(query, row.vector);
|
|
27530
|
+
if (score > 0)
|
|
27531
|
+
scored.push({ key: row.key, score });
|
|
27332
27532
|
}
|
|
27333
|
-
|
|
27334
|
-
|
|
27335
|
-
|
|
27336
|
-
|
|
27337
|
-
|
|
27338
|
-
|
|
27339
|
-
|
|
27340
|
-
|
|
27341
|
-
|
|
27342
|
-
|
|
27343
|
-
|
|
27344
|
-
|
|
27345
|
-
const chunkCount = "data" in indexResult && typeof indexResult.data === "object" && indexResult.data !== null && "chunkCount" in indexResult.data && typeof indexResult.data.chunkCount === "number" ? indexResult.data.chunkCount : 0;
|
|
27346
|
-
return {
|
|
27347
|
-
ok: true,
|
|
27348
|
-
instanceId: this.instanceId,
|
|
27349
|
-
skill: KAKAO_DATASOURCE_ID2,
|
|
27350
|
-
chunkCount,
|
|
27351
|
-
indexedAt: this.lastIndexedAt,
|
|
27352
|
-
diagnostics: []
|
|
27353
|
-
};
|
|
27354
|
-
} catch (error) {
|
|
27355
|
-
return this.fail("datasource-unavailable", {
|
|
27356
|
-
ok: false,
|
|
27357
|
-
reason: "spawn-error",
|
|
27358
|
-
stdout: "",
|
|
27359
|
-
stderr: describeRetrievalError(error),
|
|
27360
|
-
code: null
|
|
27361
|
-
});
|
|
27533
|
+
scored.sort((a, b) => b.score - a.score || a.key.localeCompare(b.key));
|
|
27534
|
+
return scored.slice(0, k);
|
|
27535
|
+
}
|
|
27536
|
+
function reciprocalRankFusion(lists) {
|
|
27537
|
+
const scores = new Map;
|
|
27538
|
+
for (const list of lists) {
|
|
27539
|
+
const seen = new Set;
|
|
27540
|
+
for (const [index, key] of list.entries()) {
|
|
27541
|
+
if (seen.has(key))
|
|
27542
|
+
continue;
|
|
27543
|
+
seen.add(key);
|
|
27544
|
+
scores.set(key, (scores.get(key) ?? 0) + 1 / (RRF_K2 + index + 1));
|
|
27362
27545
|
}
|
|
27363
27546
|
}
|
|
27364
|
-
|
|
27365
|
-
|
|
27366
|
-
|
|
27367
|
-
|
|
27547
|
+
return [...scores.entries()].map(([key, score]) => ({ key, score })).sort((a, b) => b.score - a.score);
|
|
27548
|
+
}
|
|
27549
|
+
var RRF_K2 = 60;
|
|
27550
|
+
|
|
27551
|
+
// src/datasource/sidecar/index.ts
|
|
27552
|
+
import { createHash as createHash14 } from "node:crypto";
|
|
27553
|
+
import { mkdirSync as mkdirSync22, statSync as statSync3 } from "node:fs";
|
|
27554
|
+
import { dirname as dirname24 } from "node:path";
|
|
27555
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
27556
|
+
import { pathToFileURL as pathToFileURL2 } from "node:url";
|
|
27557
|
+
|
|
27558
|
+
class CrawlerSidecar {
|
|
27559
|
+
descriptor;
|
|
27560
|
+
options;
|
|
27561
|
+
select;
|
|
27562
|
+
where;
|
|
27563
|
+
opened;
|
|
27564
|
+
attached;
|
|
27565
|
+
lastSemantic;
|
|
27566
|
+
constructor(options) {
|
|
27567
|
+
this.options = options;
|
|
27568
|
+
const { descriptor } = options;
|
|
27569
|
+
this.descriptor = descriptor;
|
|
27570
|
+
const metadataColumns = descriptor.metadata.map((column, index) => `${column.sql} as m${index}`);
|
|
27571
|
+
this.select = [
|
|
27572
|
+
`${descriptor.keyExpression} as k`,
|
|
27573
|
+
`${descriptor.textExpression} as content`,
|
|
27574
|
+
`${descriptor.titleExpression ?? "null"} as title`,
|
|
27575
|
+
`${descriptor.epochSecondsExpression ?? "null"} as epoch`,
|
|
27576
|
+
...metadataColumns
|
|
27577
|
+
].join(", ");
|
|
27578
|
+
const scope = descriptor.scopeExpression !== undefined && options.workspaceId !== undefined;
|
|
27579
|
+
const allowlist = [
|
|
27580
|
+
...(options.channelIds?.length ?? 0) > 0 ? [`${descriptor.channelIdExpression} in (${options.channelIds?.map(() => "?").join(", ")})`] : [],
|
|
27581
|
+
...(options.channelNames?.length ?? 0) > 0 ? [`${descriptor.channelNameExpression} in (${options.channelNames?.map(() => "?").join(", ")})`] : []
|
|
27368
27582
|
];
|
|
27583
|
+
this.where = [
|
|
27584
|
+
descriptor.liveWhere,
|
|
27585
|
+
...scope ? [`${descriptor.scopeExpression} = ?`] : [],
|
|
27586
|
+
...allowlist.length > 0 ? [`(${allowlist.join(" or ")})`] : []
|
|
27587
|
+
].join(" and ");
|
|
27369
27588
|
}
|
|
27370
|
-
|
|
27371
|
-
|
|
27372
|
-
|
|
27373
|
-
|
|
27374
|
-
|
|
27375
|
-
|
|
27376
|
-
|
|
27377
|
-
|
|
27378
|
-
|
|
27379
|
-
|
|
27380
|
-
|
|
27381
|
-
|
|
27382
|
-
|
|
27589
|
+
get db() {
|
|
27590
|
+
if (this.opened !== undefined)
|
|
27591
|
+
return this.opened;
|
|
27592
|
+
mkdirSync22(dirname24(this.options.sidecarDbPath), { recursive: true });
|
|
27593
|
+
const db = new DatabaseSync2(this.options.sidecarDbPath);
|
|
27594
|
+
db.exec(`pragma busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
27595
|
+
db.exec("pragma journal_mode = wal");
|
|
27596
|
+
db.exec(`
|
|
27597
|
+
create table if not exists sidecar_meta (k text primary key, v text not null);
|
|
27598
|
+
create table if not exists sidecar_vec (message_key text primary key, hash text not null, vec blob not null);
|
|
27599
|
+
`);
|
|
27600
|
+
this.opened = db;
|
|
27601
|
+
return db;
|
|
27383
27602
|
}
|
|
27384
|
-
|
|
27385
|
-
|
|
27386
|
-
|
|
27387
|
-
|
|
27388
|
-
|
|
27389
|
-
|
|
27390
|
-
|
|
27391
|
-
|
|
27392
|
-
`# KakaoTalk datasource (${KAKAO_SKILL_TYPE})`,
|
|
27393
|
-
"",
|
|
27394
|
-
"This skill searches KakaoTalk chats that are indexed through the external `lazykatok` CLI. AutoRAG never reads KakaoTalk databases directly.",
|
|
27395
|
-
"",
|
|
27396
|
-
"## When to use",
|
|
27397
|
-
"Use this skill when the question is about KakaoTalk conversations, chat participants, or content shared inside chats.",
|
|
27398
|
-
"",
|
|
27399
|
-
"## Indexing",
|
|
27400
|
-
`Indexing is server-managed and refreshed ${cadence}. You do not trigger indexing; just search.`,
|
|
27401
|
-
"",
|
|
27402
|
-
"## How to search",
|
|
27403
|
-
`Call the dedicated \`${datasourceSearchToolName(KAKAO_DATASOURCE_ID2)}\` tool with a natural-language \`query\` and \`topK\`. This datasource does not support per-source scope narrowing. Configured datasource instances:`,
|
|
27404
|
-
instanceSources.length > 0 ? instanceSources : "- (no configured instances)",
|
|
27405
|
-
"",
|
|
27406
|
-
"Chat/channel filtering is owned by lazykatok.",
|
|
27407
|
-
"",
|
|
27408
|
-
"## Native CLI",
|
|
27409
|
-
"The external `lazykatok` CLI owns the archive, index, and credentials. When the dedicated tool cannot express what you need, call lazykatok directly through `bash`:",
|
|
27410
|
-
'- `lazykatok search bm25 "<query>" --json --limit 20` — lexical search (`semantic` mode also available)',
|
|
27411
|
-
"- `lazykatok chunk get <chunkId> --json` — fetch one chunk by id (chunk ids appear in result metadata)",
|
|
27412
|
-
"- `lazykatok chunk context <chunkId> --json` — surrounding messages of a chunk",
|
|
27413
|
-
"Never pass datasource virtual paths (`/kakao/...`) to bash; they are not OS paths.",
|
|
27414
|
-
"",
|
|
27415
|
-
"## Output rules",
|
|
27416
|
-
"Datasource source identifiers such as `/kakao/<instance>/chunks/<id>` are internal and opaque. Never put them, real file paths, account IDs, or phone numbers in the visible answer."
|
|
27417
|
-
].join(`
|
|
27418
|
-
`)
|
|
27419
|
-
};
|
|
27420
|
-
}
|
|
27421
|
-
fail(code, result) {
|
|
27422
|
-
const base = result.stderr.length > 0 ? `${result.reason}: ${result.stderr.trim().slice(0, 4000)}` : result.reason;
|
|
27423
|
-
const message = code === "datasource-index-failed" && result.reason === "timeout" ? `${base} — ${connectorSyncTimeoutHint()}` : base;
|
|
27424
|
-
const diagnostic = {
|
|
27425
|
-
code,
|
|
27426
|
-
severity: code === "datasource-unavailable" ? "warning" : "error",
|
|
27427
|
-
message,
|
|
27428
|
-
instanceId: this.instanceId,
|
|
27429
|
-
source: KAKAO_DATASOURCE_ID2
|
|
27430
|
-
};
|
|
27431
|
-
return {
|
|
27432
|
-
ok: false,
|
|
27433
|
-
instanceId: this.instanceId,
|
|
27434
|
-
skill: KAKAO_DATASOURCE_ID2,
|
|
27435
|
-
indexedAt: Date.now(),
|
|
27436
|
-
diagnostics: [diagnostic],
|
|
27437
|
-
error: result.reason,
|
|
27438
|
-
code,
|
|
27439
|
-
message
|
|
27440
|
-
};
|
|
27441
|
-
}
|
|
27442
|
-
}
|
|
27443
|
-
var KAKAO_DATASOURCE_ID2 = "kakao", KAKAO_SKILL_TYPE = "kakaotalk", DEFAULT_INSTANCE_ID4 = "default", DEFAULT_POLLING_INTERVAL_MS3, DEFAULT_KAKAO_TAGS2;
|
|
27444
|
-
var init_skill7 = __esm(() => {
|
|
27445
|
-
init_skip();
|
|
27446
|
-
init_scope2();
|
|
27447
|
-
init_methods3();
|
|
27448
|
-
DEFAULT_POLLING_INTERVAL_MS3 = 15 * 60 * 1000;
|
|
27449
|
-
DEFAULT_KAKAO_TAGS2 = ["kakaotalk", "personal", "pii"];
|
|
27450
|
-
});
|
|
27451
|
-
|
|
27452
|
-
// src/datasource/skills/lazykatok/index.ts
|
|
27453
|
-
var init_lazykatok = __esm(() => {
|
|
27454
|
-
init_client8();
|
|
27455
|
-
init_methods3();
|
|
27456
|
-
init_skill7();
|
|
27457
|
-
init_types5();
|
|
27458
|
-
});
|
|
27459
|
-
|
|
27460
|
-
// src/datasource/skills/mail-export/connector.ts
|
|
27461
|
-
import { readdir as readdir4, readFile as readFile5, stat as stat6 } from "node:fs/promises";
|
|
27462
|
-
import { basename as basename12, dirname as dirname24, extname as extname6, join as join37 } from "node:path";
|
|
27463
|
-
import { simpleParser as simpleParser2 } from "mailparser";
|
|
27464
|
-
|
|
27465
|
-
class MailExportConnector {
|
|
27466
|
-
options;
|
|
27467
|
-
constructor(options = {}) {
|
|
27468
|
-
this.options = options;
|
|
27469
|
-
}
|
|
27470
|
-
async fetch() {
|
|
27471
|
-
const paths = this.options.paths ?? [];
|
|
27472
|
-
if (paths.length === 0)
|
|
27473
|
-
return { ok: false, reason: "not-configured", message: "no mail export paths configured" };
|
|
27474
|
-
const maxDocuments = this.options.maxDocuments ?? DEFAULT_MAX_DOCUMENTS3;
|
|
27475
|
-
const maxBytes = this.options.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE2;
|
|
27476
|
-
const files = [];
|
|
27477
|
-
let missingPaths = 0;
|
|
27478
|
-
for (const path of paths) {
|
|
27479
|
-
try {
|
|
27480
|
-
const info = await stat6(path);
|
|
27481
|
-
if (info.isDirectory()) {
|
|
27482
|
-
const entries = await readdir4(path, { recursive: true, withFileTypes: true });
|
|
27483
|
-
for (const entry of entries) {
|
|
27484
|
-
if (!entry.isFile())
|
|
27485
|
-
continue;
|
|
27486
|
-
const extension = extname6(entry.name).toLowerCase();
|
|
27487
|
-
if (extension === ".eml" || extension === ".mbox") {
|
|
27488
|
-
files.push(join37(entry.parentPath, entry.name));
|
|
27489
|
-
}
|
|
27490
|
-
}
|
|
27491
|
-
} else if (info.isFile()) {
|
|
27492
|
-
files.push(path);
|
|
27493
|
-
}
|
|
27494
|
-
} catch {
|
|
27495
|
-
missingPaths += 1;
|
|
27496
|
-
}
|
|
27603
|
+
attachCrawler() {
|
|
27604
|
+
let file;
|
|
27605
|
+
try {
|
|
27606
|
+
const { dev, ino } = statSync3(this.options.crawlerDbPath);
|
|
27607
|
+
file = { dev, ino };
|
|
27608
|
+
} catch {
|
|
27609
|
+
this.detachCrawler();
|
|
27610
|
+
return false;
|
|
27497
27611
|
}
|
|
27498
|
-
if (
|
|
27499
|
-
|
|
27612
|
+
if (this.attached !== undefined) {
|
|
27613
|
+
if (this.attached.dev === file.dev && this.attached.ino === file.ino)
|
|
27614
|
+
return true;
|
|
27615
|
+
this.detachCrawler();
|
|
27500
27616
|
}
|
|
27501
|
-
const
|
|
27502
|
-
|
|
27503
|
-
|
|
27504
|
-
|
|
27505
|
-
|
|
27506
|
-
let skippedLarge = 0;
|
|
27507
|
-
for (const file of files.sort()) {
|
|
27508
|
-
if (documents.length >= maxDocuments)
|
|
27509
|
-
break;
|
|
27510
|
-
let bytes;
|
|
27511
|
-
try {
|
|
27512
|
-
const info = await stat6(file);
|
|
27513
|
-
if (info.size > maxBytes) {
|
|
27514
|
-
skippedLarge += 1;
|
|
27515
|
-
continue;
|
|
27516
|
-
}
|
|
27517
|
-
bytes = await readFile5(file);
|
|
27518
|
-
} catch {
|
|
27519
|
-
parseFailures += 1;
|
|
27520
|
-
continue;
|
|
27521
|
-
}
|
|
27522
|
-
const stem = basename12(file, extname6(file));
|
|
27523
|
-
const mailboxDir = basename12(dirname24(file));
|
|
27524
|
-
const hierarchy = ["mailboxes", mailboxDir, stem];
|
|
27525
|
-
const extension = extname6(file).toLowerCase();
|
|
27526
|
-
const rawMessages = extension === ".mbox" ? splitMbox(bytes.toString("utf8")) : [bytes.toString("utf8")];
|
|
27527
|
-
for (const [index, raw] of rawMessages.entries()) {
|
|
27528
|
-
if (documents.length >= maxDocuments)
|
|
27529
|
-
break;
|
|
27530
|
-
try {
|
|
27531
|
-
const parsed = await simpleParser2(raw);
|
|
27532
|
-
const subject = parsed.subject ?? "(no subject)";
|
|
27533
|
-
const from = Array.isArray(parsed.from) ? parsed.from[0]?.text : parsed.from?.text;
|
|
27534
|
-
const to = Array.isArray(parsed.to) ? parsed.to[0]?.text : parsed.to?.text;
|
|
27535
|
-
const body = (parsed.text ?? "").trim().slice(0, MAX_BODY_CHARS);
|
|
27536
|
-
const headerBlock = [
|
|
27537
|
-
`Subject: ${subject}`,
|
|
27538
|
-
...from !== undefined ? [`From: ${from}`] : [],
|
|
27539
|
-
...to !== undefined ? [`To: ${to}`] : [],
|
|
27540
|
-
...parsed.date !== undefined ? [`Date: ${parsed.date.toISOString()}`] : []
|
|
27541
|
-
].join(`
|
|
27542
|
-
`);
|
|
27543
|
-
const content = `${headerBlock}
|
|
27544
|
-
|
|
27545
|
-
${body}`.trim();
|
|
27546
|
-
if (content.length === 0)
|
|
27547
|
-
continue;
|
|
27548
|
-
documents.push({
|
|
27549
|
-
docId: extension === ".mbox" ? `${stem}-${index + 1}` : stem,
|
|
27550
|
-
hierarchy,
|
|
27551
|
-
title: subject,
|
|
27552
|
-
content,
|
|
27553
|
-
...parsed.date !== undefined ? { publishedAt: parsed.date.getTime() } : {},
|
|
27554
|
-
metadata: {
|
|
27555
|
-
path: file,
|
|
27556
|
-
subject,
|
|
27557
|
-
...from !== undefined ? { from } : {},
|
|
27558
|
-
messageIndex: index
|
|
27559
|
-
}
|
|
27560
|
-
});
|
|
27561
|
-
} catch {
|
|
27562
|
-
parseFailures += 1;
|
|
27563
|
-
}
|
|
27564
|
-
}
|
|
27617
|
+
const crawlerUri = `${pathToFileURL2(this.options.crawlerDbPath).href}?mode=ro`.replaceAll("'", "''");
|
|
27618
|
+
try {
|
|
27619
|
+
this.db.exec(`attach database '${crawlerUri}' as crawler`);
|
|
27620
|
+
} catch {
|
|
27621
|
+
return false;
|
|
27565
27622
|
}
|
|
27566
|
-
|
|
27567
|
-
|
|
27568
|
-
|
|
27569
|
-
|
|
27570
|
-
|
|
27571
|
-
|
|
27572
|
-
|
|
27573
|
-
function splitMbox(text) {
|
|
27574
|
-
const lines = text.split(/\r?\n/u);
|
|
27575
|
-
const messages = [];
|
|
27576
|
-
let current = [];
|
|
27577
|
-
for (const line of lines) {
|
|
27578
|
-
if (MBOX_SEPARATOR.test(line) && line.startsWith("From ")) {
|
|
27579
|
-
if (current.length > 0)
|
|
27580
|
-
messages.push(current.join(`
|
|
27581
|
-
`));
|
|
27582
|
-
current = [];
|
|
27583
|
-
continue;
|
|
27623
|
+
const { descriptor } = this.options;
|
|
27624
|
+
try {
|
|
27625
|
+
this.db.prepare(`select ${this.select} from ${descriptor.fromClause} where ${this.where} limit 0`).all(...this.whereParams());
|
|
27626
|
+
this.db.prepare(`select 1 from ${descriptor.fts.table} limit 0`).all();
|
|
27627
|
+
} catch {
|
|
27628
|
+
this.db.exec("detach database crawler");
|
|
27629
|
+
return false;
|
|
27584
27630
|
}
|
|
27585
|
-
|
|
27631
|
+
this.attached = file;
|
|
27632
|
+
this.lastSemantic = undefined;
|
|
27633
|
+
return true;
|
|
27586
27634
|
}
|
|
27587
|
-
|
|
27588
|
-
|
|
27589
|
-
|
|
27590
|
-
|
|
27591
|
-
|
|
27592
|
-
|
|
27593
|
-
|
|
27594
|
-
|
|
27595
|
-
MBOX_SEPARATOR = /^From .*\d{4}$/mu;
|
|
27596
|
-
});
|
|
27597
|
-
|
|
27598
|
-
// src/datasource/skills/mail-export/skill.ts
|
|
27599
|
-
var MAIL_EXPORT_SKILL_DEFINITION, MailExportSkill;
|
|
27600
|
-
var init_skill8 = __esm(() => {
|
|
27601
|
-
init_connector_skill();
|
|
27602
|
-
init_connector4();
|
|
27603
|
-
MAIL_EXPORT_SKILL_DEFINITION = {
|
|
27604
|
-
skillName: "mail-export",
|
|
27605
|
-
skillType: "mail-export",
|
|
27606
|
-
description: "Local mail export datasource",
|
|
27607
|
-
capabilities: ["email", "filesystem"],
|
|
27608
|
-
defaultTags: ["mail-export", "email", "pii"],
|
|
27609
|
-
contentType: "email",
|
|
27610
|
-
manifestDescription: "Search indexed local mail exports (mbox/eml archives). Use for questions about archived email conversations.",
|
|
27611
|
-
manifestNotes: [
|
|
27612
|
-
"Only the server-configured export paths are indexed; archives are read locally and never uploaded."
|
|
27613
|
-
]
|
|
27614
|
-
};
|
|
27615
|
-
MailExportSkill = class MailExportSkill extends ConnectorDatasourceSkill {
|
|
27616
|
-
constructor(options = {}) {
|
|
27617
|
-
const { connector, connectorOptions, ...rest } = options;
|
|
27618
|
-
super(MAIL_EXPORT_SKILL_DEFINITION, {
|
|
27619
|
-
...rest,
|
|
27620
|
-
connector: connector ?? new MailExportConnector(connectorOptions ?? {})
|
|
27621
|
-
});
|
|
27622
|
-
}
|
|
27623
|
-
};
|
|
27624
|
-
});
|
|
27625
|
-
|
|
27626
|
-
// src/datasource/skills/mail-export/index.ts
|
|
27627
|
-
var init_mail_export = __esm(() => {
|
|
27628
|
-
init_connector4();
|
|
27629
|
-
init_skill8();
|
|
27630
|
-
});
|
|
27631
|
-
|
|
27632
|
-
// src/datasource/skills/mailcrawl/config.ts
|
|
27633
|
-
import { chmodSync, mkdirSync as mkdirSync22 } from "node:fs";
|
|
27634
|
-
function validateMailcrawlInstanceId(instanceId) {
|
|
27635
|
-
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(instanceId)) {
|
|
27636
|
-
throw new Error("mailcrawl instanceId must be a safe single path segment");
|
|
27635
|
+
detachCrawler() {
|
|
27636
|
+
if (this.attached === undefined)
|
|
27637
|
+
return;
|
|
27638
|
+
this.attached = undefined;
|
|
27639
|
+
this.lastSemantic = undefined;
|
|
27640
|
+
try {
|
|
27641
|
+
this.opened?.exec("detach database crawler");
|
|
27642
|
+
} catch {}
|
|
27637
27643
|
}
|
|
27638
|
-
|
|
27639
|
-
|
|
27640
|
-
mkdirSync22(path, { recursive: true, mode: 448 });
|
|
27641
|
-
if (process.platform !== "win32")
|
|
27642
|
-
chmodSync(path, 448);
|
|
27643
|
-
}
|
|
27644
|
-
var init_config3 = () => {};
|
|
27645
|
-
|
|
27646
|
-
// src/datasource/skills/mailcrawl/client.ts
|
|
27647
|
-
import { spawn as spawn15 } from "node:child_process";
|
|
27648
|
-
|
|
27649
|
-
class MailcrawlClient {
|
|
27650
|
-
options;
|
|
27651
|
-
constructor(options = {}) {
|
|
27652
|
-
this.options = options;
|
|
27653
|
-
if (options.instanceId !== undefined)
|
|
27654
|
-
validateMailcrawlInstanceId(options.instanceId);
|
|
27644
|
+
get semanticEnabled() {
|
|
27645
|
+
return this.options.embedder !== undefined;
|
|
27655
27646
|
}
|
|
27656
|
-
|
|
27657
|
-
|
|
27658
|
-
|
|
27659
|
-
|
|
27660
|
-
|
|
27661
|
-
...this.options.mailbox === undefined ? [] : ["--mailbox", this.options.mailbox],
|
|
27662
|
-
...this.options.backend === undefined ? [] : ["--backend", this.options.backend],
|
|
27663
|
-
...this.options.source === undefined ? [] : ["--source", this.options.source],
|
|
27664
|
-
...this.options.fixture === undefined ? [] : ["--fixture", this.options.fixture],
|
|
27665
|
-
...this.options.himalayaConfig === undefined ? [] : ["--himalaya-config", this.options.himalayaConfig]
|
|
27666
|
-
];
|
|
27667
|
-
const result = await this.run(args, signal, this.indexTimeoutMs());
|
|
27668
|
-
if (!result.ok)
|
|
27669
|
-
return failure3(result);
|
|
27670
|
-
const parsed = parseObject2(result.stdout);
|
|
27671
|
-
if (parsed === undefined || !hasAnyNumber(parsed, ["added", "updated", "deleted", "unchanged", "chunksAdded"])) {
|
|
27672
|
-
return failure3({ ...result, ok: false, reason: "invalid-output" });
|
|
27673
|
-
}
|
|
27674
|
-
const messages = number(parsed, "added") ?? number(parsed, "updated") ?? number(parsed, "unchanged") ?? 0;
|
|
27675
|
-
return ok4({
|
|
27676
|
-
messages,
|
|
27677
|
-
added: number(parsed, "added"),
|
|
27678
|
-
updated: number(parsed, "updated"),
|
|
27679
|
-
deleted: number(parsed, "deleted"),
|
|
27680
|
-
unchanged: number(parsed, "unchanged"),
|
|
27681
|
-
chunksAdded: number(parsed, "chunksAdded"),
|
|
27682
|
-
archiveRevision: string(parsed, "archiveRevision")
|
|
27683
|
-
}, result);
|
|
27647
|
+
close() {
|
|
27648
|
+
this.opened?.close();
|
|
27649
|
+
this.opened = undefined;
|
|
27650
|
+
this.attached = undefined;
|
|
27651
|
+
this.lastSemantic = undefined;
|
|
27684
27652
|
}
|
|
27685
|
-
|
|
27686
|
-
|
|
27687
|
-
|
|
27688
|
-
|
|
27689
|
-
|
|
27690
|
-
|
|
27691
|
-
mode === "keyword" ? "bm25" : mode,
|
|
27692
|
-
...this.options.account === undefined ? [] : ["--account", this.options.account],
|
|
27693
|
-
...this.options.mailbox === undefined ? [] : ["--mailbox", this.options.mailbox],
|
|
27694
|
-
"--limit",
|
|
27695
|
-
String(options?.topK ?? 20),
|
|
27696
|
-
"--json",
|
|
27697
|
-
query.trim()
|
|
27653
|
+
whereParams() {
|
|
27654
|
+
const { descriptor, workspaceId, channelIds = [], channelNames = [] } = this.options;
|
|
27655
|
+
return [
|
|
27656
|
+
...descriptor.scopeExpression !== undefined && workspaceId !== undefined ? [workspaceId] : [],
|
|
27657
|
+
...channelIds,
|
|
27658
|
+
...channelNames
|
|
27698
27659
|
];
|
|
27699
|
-
const result = await this.run(args, options?.signal, this.options.timeoutMs ?? DEFAULT_SEARCH_TIMEOUT_MS2);
|
|
27700
|
-
if (!result.ok)
|
|
27701
|
-
return failure3(result);
|
|
27702
|
-
const parsed = parseJson3(result.stdout);
|
|
27703
|
-
if (parsed === undefined)
|
|
27704
|
-
return failure3({ ...result, ok: false, reason: "invalid-output" });
|
|
27705
|
-
const rows = Array.isArray(parsed) ? parsed : objectArray(parsed, ["hits", "results", "items"]);
|
|
27706
|
-
if (rows === undefined)
|
|
27707
|
-
return failure3({ ...result, ok: false, reason: "invalid-output" });
|
|
27708
|
-
const hits = rows.map((row, index) => normalizeHit2(row, mode, index));
|
|
27709
|
-
if (hits.some((hit) => hit === undefined)) {
|
|
27710
|
-
return failure3({ ...result, ok: false, reason: "invalid-output" });
|
|
27711
|
-
}
|
|
27712
|
-
return {
|
|
27713
|
-
ok: true,
|
|
27714
|
-
hits,
|
|
27715
|
-
stdout: result.stdout,
|
|
27716
|
-
stderr: result.stderr,
|
|
27717
|
-
code: result.code ?? 0
|
|
27718
|
-
};
|
|
27719
27660
|
}
|
|
27720
|
-
|
|
27721
|
-
|
|
27661
|
+
searchLexical(query, topK) {
|
|
27662
|
+
const match = toMatchQuery(query);
|
|
27663
|
+
if (match === undefined || topK <= 0 || !this.attachCrawler())
|
|
27664
|
+
return [];
|
|
27665
|
+
const { descriptor } = this.options;
|
|
27666
|
+
const rows = this.db.prepare(`select ${this.select}, bm25(${descriptor.fts.table}) as rank
|
|
27667
|
+
from ${descriptor.fromClause} join ${descriptor.fts.table} on ${descriptor.fts.joinOn}
|
|
27668
|
+
where ${descriptor.fts.table} match ? and ${this.where}
|
|
27669
|
+
order by rank limit ?`).all(match, ...this.whereParams(), topK);
|
|
27670
|
+
return rows.map((row) => this.toHit(this.toRow(row), -Number(row.rank)));
|
|
27722
27671
|
}
|
|
27723
|
-
async
|
|
27724
|
-
const
|
|
27725
|
-
if (
|
|
27726
|
-
return
|
|
27672
|
+
async searchSemantic(query, topK) {
|
|
27673
|
+
const trimmed = query.trim();
|
|
27674
|
+
if (this.options.embedder === undefined || trimmed.length === 0 || topK <= 0 || !this.attachCrawler())
|
|
27675
|
+
return [];
|
|
27676
|
+
const ranked = await this.rankSemantic(trimmed, topK * POOL_FACTOR);
|
|
27677
|
+
if (ranked.length === 0)
|
|
27678
|
+
return [];
|
|
27679
|
+
const live = this.hydrate(ranked.map((entry) => entry.key));
|
|
27680
|
+
const hits = [];
|
|
27681
|
+
for (const entry of ranked) {
|
|
27682
|
+
const row = live.get(entry.key);
|
|
27683
|
+
if (row !== undefined)
|
|
27684
|
+
hits.push(this.toHit(row, entry.score));
|
|
27685
|
+
if (hits.length >= topK)
|
|
27686
|
+
break;
|
|
27727
27687
|
}
|
|
27728
|
-
|
|
27729
|
-
|
|
27730
|
-
|
|
27731
|
-
const
|
|
27732
|
-
|
|
27733
|
-
|
|
27734
|
-
|
|
27688
|
+
return hits;
|
|
27689
|
+
}
|
|
27690
|
+
async rankSemantic(query, pool) {
|
|
27691
|
+
const now = Date.now();
|
|
27692
|
+
let cached = this.lastSemantic;
|
|
27693
|
+
if (cached === undefined || cached.query !== query || now - cached.at > SEMANTIC_REUSE_MS) {
|
|
27694
|
+
const embedder = this.options.embedder;
|
|
27695
|
+
if (embedder === undefined)
|
|
27696
|
+
return [];
|
|
27697
|
+
cached = {
|
|
27698
|
+
query,
|
|
27699
|
+
at: now,
|
|
27700
|
+
vector: embedder.embed([query]).then((vectors) => vectors[0], () => {
|
|
27701
|
+
return;
|
|
27702
|
+
}),
|
|
27703
|
+
ranked: undefined
|
|
27704
|
+
};
|
|
27705
|
+
this.lastSemantic = cached;
|
|
27735
27706
|
}
|
|
27736
|
-
|
|
27737
|
-
|
|
27738
|
-
|
|
27739
|
-
|
|
27740
|
-
|
|
27707
|
+
const vector = await cached.vector;
|
|
27708
|
+
if (vector === undefined) {
|
|
27709
|
+
if (this.lastSemantic === cached)
|
|
27710
|
+
this.lastSemantic = undefined;
|
|
27711
|
+
return [];
|
|
27741
27712
|
}
|
|
27742
|
-
if (
|
|
27743
|
-
|
|
27744
|
-
|
|
27713
|
+
if (cached.ranked === undefined || cached.ranked.pool < pool) {
|
|
27714
|
+
const wide = pool * POOL_FACTOR;
|
|
27715
|
+
cached.ranked = { pool: wide, keys: topKByCosine(vector, this.storedVectors(), wide) };
|
|
27716
|
+
}
|
|
27717
|
+
return cached.ranked.keys.slice(0, pool);
|
|
27745
27718
|
}
|
|
27746
|
-
async
|
|
27747
|
-
|
|
27748
|
-
|
|
27749
|
-
|
|
27750
|
-
const
|
|
27751
|
-
|
|
27752
|
-
|
|
27719
|
+
async searchHybrid(query, topK) {
|
|
27720
|
+
if (topK <= 0)
|
|
27721
|
+
return [];
|
|
27722
|
+
const pool = topK * POOL_FACTOR;
|
|
27723
|
+
const lexical = this.searchLexical(query, pool);
|
|
27724
|
+
const semantic = await this.searchSemantic(query, pool);
|
|
27725
|
+
if (semantic.length === 0)
|
|
27726
|
+
return lexical.slice(0, topK);
|
|
27727
|
+
const byKey = new Map;
|
|
27728
|
+
for (const hit of [...semantic, ...lexical])
|
|
27729
|
+
byKey.set(hit.key, hit);
|
|
27730
|
+
const fused = [];
|
|
27731
|
+
for (const entry of reciprocalRankFusion([lexical.map((hit) => hit.key), semantic.map((hit) => hit.key)])) {
|
|
27732
|
+
const hit = byKey.get(entry.key);
|
|
27733
|
+
if (hit !== undefined)
|
|
27734
|
+
fused.push({ ...hit, score: entry.score });
|
|
27735
|
+
if (fused.length >= topK)
|
|
27736
|
+
break;
|
|
27753
27737
|
}
|
|
27754
|
-
return
|
|
27755
|
-
embedded: number(parsed, "embedded"),
|
|
27756
|
-
reused: number(parsed, "reused"),
|
|
27757
|
-
generation: string(parsed, "generation"),
|
|
27758
|
-
archiveRevision: string(parsed, "archiveRevision"),
|
|
27759
|
-
rebuilt: typeof parsed.rebuilt === "boolean" ? parsed.rebuilt : undefined,
|
|
27760
|
-
embedder: string(parsed, "embedder")
|
|
27761
|
-
}, result);
|
|
27738
|
+
return fused;
|
|
27762
27739
|
}
|
|
27763
|
-
|
|
27764
|
-
|
|
27765
|
-
|
|
27766
|
-
|
|
27767
|
-
|
|
27768
|
-
|
|
27769
|
-
|
|
27770
|
-
|
|
27771
|
-
|
|
27772
|
-
|
|
27773
|
-
|
|
27774
|
-
|
|
27775
|
-
|
|
27776
|
-
|
|
27777
|
-
|
|
27778
|
-
const
|
|
27779
|
-
|
|
27780
|
-
|
|
27781
|
-
|
|
27782
|
-
|
|
27783
|
-
|
|
27784
|
-
|
|
27785
|
-
child.stdout.setEncoding("utf8");
|
|
27786
|
-
child.stderr.setEncoding("utf8");
|
|
27787
|
-
child.stdout.on("data", (chunk) => {
|
|
27788
|
-
stdout = appendOutput(stdout, chunk, max);
|
|
27789
|
-
if (stdout.exceeded && reason === undefined) {
|
|
27790
|
-
reason = "stdout-too-large";
|
|
27791
|
-
terminate4(child);
|
|
27740
|
+
async sync() {
|
|
27741
|
+
const { embedder } = this.options;
|
|
27742
|
+
if (embedder === undefined)
|
|
27743
|
+
return { ok: false, message: "no embedder configured" };
|
|
27744
|
+
if (!this.attachCrawler())
|
|
27745
|
+
return { ok: false, message: "crawler archive not available yet" };
|
|
27746
|
+
let identity;
|
|
27747
|
+
try {
|
|
27748
|
+
identity = await embedder.identity();
|
|
27749
|
+
} catch (error) {
|
|
27750
|
+
return { ok: false, message: errorMessage2(error) };
|
|
27751
|
+
}
|
|
27752
|
+
this.adoptIdentity(identity);
|
|
27753
|
+
const pruned = this.prune();
|
|
27754
|
+
const pending = this.pendingKeys();
|
|
27755
|
+
const batchSize = Math.max(1, this.options.batchSize ?? DEFAULT_BATCH_SIZE);
|
|
27756
|
+
const budget = Math.max(1, this.options.maxEmbedPerSync ?? DEFAULT_MAX_EMBED_PER_SYNC);
|
|
27757
|
+
const target = Math.min(pending.length, budget);
|
|
27758
|
+
const embed = async (rows) => {
|
|
27759
|
+
const vectors = await embedder.embed(rows.map((row) => row.input));
|
|
27760
|
+
if (vectors.length !== rows.length) {
|
|
27761
|
+
throw new Error(`embedder returned ${vectors.length} vectors for ${rows.length} messages`);
|
|
27792
27762
|
}
|
|
27793
|
-
|
|
27794
|
-
|
|
27795
|
-
|
|
27796
|
-
|
|
27797
|
-
|
|
27798
|
-
|
|
27763
|
+
const wrong = vectors.find((vector) => vector.length !== identity.dimension);
|
|
27764
|
+
if (wrong !== undefined) {
|
|
27765
|
+
throw new Error(`embedder returned a ${wrong.length}-dimension vector, expected ${identity.dimension}`);
|
|
27766
|
+
}
|
|
27767
|
+
return vectors;
|
|
27768
|
+
};
|
|
27769
|
+
let embedded = 0;
|
|
27770
|
+
let skipped = 0;
|
|
27771
|
+
for (let offset = 0;offset < target; offset += batchSize) {
|
|
27772
|
+
const rows = [...this.hydrate(pending.slice(offset, Math.min(offset + batchSize, target))).values()];
|
|
27773
|
+
if (rows.length === 0)
|
|
27774
|
+
continue;
|
|
27775
|
+
try {
|
|
27776
|
+
this.store(rows, await embed(rows));
|
|
27777
|
+
embedded += rows.length;
|
|
27778
|
+
} catch (batchError) {
|
|
27779
|
+
const rejected = [];
|
|
27780
|
+
let lastError = batchError;
|
|
27781
|
+
for (const row of rows) {
|
|
27782
|
+
try {
|
|
27783
|
+
this.store([row], await embed([row]));
|
|
27784
|
+
embedded += 1;
|
|
27785
|
+
} catch (error) {
|
|
27786
|
+
rejected.push(row);
|
|
27787
|
+
lastError = error;
|
|
27788
|
+
}
|
|
27789
|
+
}
|
|
27790
|
+
if (rejected.length === 0)
|
|
27791
|
+
continue;
|
|
27792
|
+
if (embedded === 0)
|
|
27793
|
+
return { ok: false, message: errorMessage2(lastError) };
|
|
27794
|
+
this.store(rejected, undefined);
|
|
27795
|
+
skipped += rejected.length;
|
|
27799
27796
|
}
|
|
27800
|
-
});
|
|
27801
|
-
child.on("error", (error) => {
|
|
27802
|
-
if (settled)
|
|
27803
|
-
return;
|
|
27804
|
-
settled = true;
|
|
27805
|
-
clearTimeout(timer);
|
|
27806
|
-
signal?.removeEventListener("abort", abort);
|
|
27807
|
-
resolveResult({
|
|
27808
|
-
ok: false,
|
|
27809
|
-
reason: error.code === "ENOENT" ? "binary-missing" : "spawn-error",
|
|
27810
|
-
stdout: stdout.text,
|
|
27811
|
-
stderr: "",
|
|
27812
|
-
code: null
|
|
27813
|
-
});
|
|
27814
|
-
});
|
|
27815
|
-
child.on("close", (code) => {
|
|
27816
|
-
if (settled)
|
|
27817
|
-
return;
|
|
27818
|
-
settled = true;
|
|
27819
|
-
clearTimeout(timer);
|
|
27820
|
-
signal?.removeEventListener("abort", abort);
|
|
27821
|
-
resolveResult({
|
|
27822
|
-
ok: code === 0 && reason === undefined,
|
|
27823
|
-
...reason === undefined ? code === 0 ? {} : { reason: "nonzero-exit" } : { reason },
|
|
27824
|
-
stdout: stdout.text,
|
|
27825
|
-
stderr: stderr.text,
|
|
27826
|
-
code
|
|
27827
|
-
});
|
|
27828
|
-
});
|
|
27829
|
-
});
|
|
27830
|
-
}
|
|
27831
|
-
function terminate4(child) {
|
|
27832
|
-
if (child.killed)
|
|
27833
|
-
return;
|
|
27834
|
-
if (process.platform !== "win32" && child.pid !== undefined) {
|
|
27835
|
-
try {
|
|
27836
|
-
process.kill(-child.pid, "SIGTERM");
|
|
27837
|
-
return;
|
|
27838
|
-
} catch {}
|
|
27839
|
-
}
|
|
27840
|
-
child.kill("SIGTERM");
|
|
27841
|
-
}
|
|
27842
|
-
function parseJson3(text) {
|
|
27843
|
-
try {
|
|
27844
|
-
return JSON.parse(text.trim());
|
|
27845
|
-
} catch {
|
|
27846
|
-
return;
|
|
27847
|
-
}
|
|
27848
|
-
}
|
|
27849
|
-
function parseObject2(text) {
|
|
27850
|
-
const value = parseJson3(text);
|
|
27851
|
-
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
|
|
27852
|
-
}
|
|
27853
|
-
function objectArray(value, keys) {
|
|
27854
|
-
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
27855
|
-
return;
|
|
27856
|
-
for (const key of keys)
|
|
27857
|
-
if (Array.isArray(value[key]))
|
|
27858
|
-
return value[key];
|
|
27859
|
-
return;
|
|
27860
|
-
}
|
|
27861
|
-
function hasAnyNumber(value, keys) {
|
|
27862
|
-
return keys.some((key) => number(value, key) !== undefined);
|
|
27863
|
-
}
|
|
27864
|
-
function normalizeHit2(value, mode, index) {
|
|
27865
|
-
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
27866
|
-
return;
|
|
27867
|
-
const row = value;
|
|
27868
|
-
const text = (key) => typeof row[key] === "string" ? row[key] : "";
|
|
27869
|
-
const chunkId = text("chunkId") || text("chunk_id");
|
|
27870
|
-
const messageId = text("messageId") || text("message_id");
|
|
27871
|
-
const accountId = text("accountId") || text("account_id");
|
|
27872
|
-
const mailbox = text("mailbox");
|
|
27873
|
-
const snippet = text("snippet") || text("content") || text("text");
|
|
27874
|
-
if (!isSafeOpaqueId(chunkId) || !isSafeOpaqueId(messageId) || !snippet)
|
|
27875
|
-
return;
|
|
27876
|
-
const to = Array.isArray(row.to) ? row.to.filter((item) => typeof item === "string") : [];
|
|
27877
|
-
return {
|
|
27878
|
-
chunkId,
|
|
27879
|
-
messageId,
|
|
27880
|
-
threadId: text("threadId") || text("thread_id"),
|
|
27881
|
-
accountId,
|
|
27882
|
-
mailbox,
|
|
27883
|
-
subject: text("subject"),
|
|
27884
|
-
from: text("from"),
|
|
27885
|
-
to,
|
|
27886
|
-
date: text("date"),
|
|
27887
|
-
snippet,
|
|
27888
|
-
score: typeof row.score === "number" ? row.score : 1 / (index + 1),
|
|
27889
|
-
mode
|
|
27890
|
-
};
|
|
27891
|
-
}
|
|
27892
|
-
function number(value, key) {
|
|
27893
|
-
return typeof value[key] === "number" && Number.isFinite(value[key]) ? value[key] : undefined;
|
|
27894
|
-
}
|
|
27895
|
-
function string(value, key) {
|
|
27896
|
-
return typeof value[key] === "string" ? value[key] : undefined;
|
|
27897
|
-
}
|
|
27898
|
-
function ok4(data, result) {
|
|
27899
|
-
return { ok: true, data, stdout: result.stdout, stderr: result.stderr, code: result.code ?? 0 };
|
|
27900
|
-
}
|
|
27901
|
-
function failure3(result) {
|
|
27902
|
-
return {
|
|
27903
|
-
ok: false,
|
|
27904
|
-
reason: result.reason ?? "nonzero-exit",
|
|
27905
|
-
stdout: result.stdout,
|
|
27906
|
-
stderr: boundDiagnosticText6(result.stderr),
|
|
27907
|
-
code: result.code
|
|
27908
|
-
};
|
|
27909
|
-
}
|
|
27910
|
-
function boundDiagnosticText6(value) {
|
|
27911
|
-
if (value.length === 0)
|
|
27912
|
-
return "";
|
|
27913
|
-
return value.trim().slice(0, 4000);
|
|
27914
|
-
}
|
|
27915
|
-
function appendOutput(current, chunk, maxBytes) {
|
|
27916
|
-
if (current.exceeded)
|
|
27917
|
-
return current;
|
|
27918
|
-
const bytes = Buffer.from(chunk, "utf8");
|
|
27919
|
-
const remaining = Math.max(0, maxBytes - current.bytes);
|
|
27920
|
-
const prefix = truncateUtf8(chunk, remaining);
|
|
27921
|
-
const total = current.bytes + bytes.byteLength;
|
|
27922
|
-
return {
|
|
27923
|
-
text: current.text + prefix,
|
|
27924
|
-
bytes: Math.min(total, maxBytes),
|
|
27925
|
-
exceeded: total > maxBytes
|
|
27926
|
-
};
|
|
27927
|
-
}
|
|
27928
|
-
function isSafeOpaqueId(value) {
|
|
27929
|
-
return value.length > 0 && value !== "." && value !== ".." && !/[\\/#\u0000-\u001f\u007f]/u.test(value);
|
|
27930
|
-
}
|
|
27931
|
-
function findRemoteEmbeddingViolation(env) {
|
|
27932
|
-
for (const [key, value] of Object.entries(env)) {
|
|
27933
|
-
if (value === undefined)
|
|
27934
|
-
continue;
|
|
27935
|
-
const lower = key.toLowerCase();
|
|
27936
|
-
if (REMOTE_EMBEDDING_ENV_KEYS.has(lower))
|
|
27937
|
-
return key;
|
|
27938
|
-
if (lower === "mailcrawl_embedder" || lower === "mailcrawl_embed_url") {
|
|
27939
|
-
if (isRemoteHttpEndpoint(value))
|
|
27940
|
-
return key;
|
|
27941
27797
|
}
|
|
27798
|
+
return { ok: true, embedded, skipped, pruned, remaining: pending.length - embedded - skipped };
|
|
27942
27799
|
}
|
|
27943
|
-
|
|
27944
|
-
|
|
27945
|
-
|
|
27946
|
-
|
|
27947
|
-
|
|
27948
|
-
|
|
27949
|
-
|
|
27950
|
-
|
|
27951
|
-
|
|
27952
|
-
|
|
27800
|
+
adoptIdentity(identity) {
|
|
27801
|
+
const serialized = JSON.stringify(identity);
|
|
27802
|
+
const current = this.db.prepare("select v from sidecar_meta where k = ?").get(IDENTITY_KEY);
|
|
27803
|
+
if (current?.v === serialized)
|
|
27804
|
+
return;
|
|
27805
|
+
this.transaction(() => {
|
|
27806
|
+
this.db.exec("delete from sidecar_vec");
|
|
27807
|
+
this.db.prepare("insert or replace into sidecar_meta (k, v) values (?, ?)").run(IDENTITY_KEY, serialized);
|
|
27808
|
+
});
|
|
27809
|
+
this.lastSemantic = undefined;
|
|
27953
27810
|
}
|
|
27954
|
-
|
|
27955
|
-
|
|
27956
|
-
|
|
27957
|
-
|
|
27958
|
-
|
|
27959
|
-
|
|
27960
|
-
|
|
27811
|
+
prune() {
|
|
27812
|
+
const { descriptor } = this.options;
|
|
27813
|
+
const result = this.db.prepare(`delete from sidecar_vec where message_key not in (
|
|
27814
|
+
select ${descriptor.keyExpression} from ${descriptor.fromClause} where ${this.where}
|
|
27815
|
+
)`).run(...this.whereParams());
|
|
27816
|
+
if (Number(result.changes) > 0)
|
|
27817
|
+
this.lastSemantic = undefined;
|
|
27818
|
+
return Number(result.changes);
|
|
27819
|
+
}
|
|
27820
|
+
pendingKeys() {
|
|
27821
|
+
const { descriptor } = this.options;
|
|
27822
|
+
const rows = this.db.prepare(`select ${this.select}, v.hash as stored_hash
|
|
27823
|
+
from ${descriptor.fromClause}
|
|
27824
|
+
left join sidecar_vec v on v.message_key = ${descriptor.keyExpression}
|
|
27825
|
+
where ${this.where}`).iterate(...this.whereParams());
|
|
27826
|
+
const pending = [];
|
|
27827
|
+
for (const row of rows) {
|
|
27828
|
+
if (row.stored_hash !== this.toRow(row).hash)
|
|
27829
|
+
pending.push(String(row.k));
|
|
27830
|
+
}
|
|
27831
|
+
return pending;
|
|
27832
|
+
}
|
|
27833
|
+
hydrate(keys) {
|
|
27834
|
+
const { descriptor } = this.options;
|
|
27835
|
+
const out = new Map;
|
|
27836
|
+
if (keys.length === 0)
|
|
27837
|
+
return out;
|
|
27838
|
+
const rows = this.db.prepare(`select ${this.select} from ${descriptor.fromClause}
|
|
27839
|
+
where ${descriptor.keyExpression} in (${keys.map(() => "?").join(", ")}) and ${this.where}`).all(...keys, ...this.whereParams());
|
|
27840
|
+
const byKey = new Map(rows.map((row) => [String(row.k), this.toRow(row)]));
|
|
27841
|
+
for (const key of keys) {
|
|
27842
|
+
const row = byKey.get(key);
|
|
27843
|
+
if (row !== undefined)
|
|
27844
|
+
out.set(key, row);
|
|
27845
|
+
}
|
|
27846
|
+
return out;
|
|
27847
|
+
}
|
|
27848
|
+
store(rows, vectors) {
|
|
27849
|
+
const upsert = this.db.prepare("insert or replace into sidecar_vec (message_key, hash, vec) values (?, ?, ?)");
|
|
27850
|
+
this.transaction(() => {
|
|
27851
|
+
for (const [index, row] of rows.entries()) {
|
|
27852
|
+
upsert.run(row.key, row.hash, encodeVector(vectors?.[index] ?? []));
|
|
27853
|
+
}
|
|
27854
|
+
});
|
|
27855
|
+
this.lastSemantic = undefined;
|
|
27856
|
+
}
|
|
27857
|
+
*storedVectors() {
|
|
27858
|
+
const rows = this.db.prepare("select message_key, vec from sidecar_vec where length(vec) > 0").iterate();
|
|
27859
|
+
for (const row of rows) {
|
|
27860
|
+
const vector = row.vec instanceof Uint8Array ? decodeVector(row.vec) : undefined;
|
|
27861
|
+
if (vector !== undefined)
|
|
27862
|
+
yield { key: String(row.message_key), vector };
|
|
27863
|
+
}
|
|
27864
|
+
}
|
|
27865
|
+
transaction(work) {
|
|
27866
|
+
this.db.exec("begin immediate");
|
|
27961
27867
|
try {
|
|
27962
|
-
|
|
27963
|
-
|
|
27868
|
+
work();
|
|
27869
|
+
this.db.exec("commit");
|
|
27870
|
+
} catch (error) {
|
|
27871
|
+
this.db.exec("rollback");
|
|
27872
|
+
throw error;
|
|
27873
|
+
}
|
|
27874
|
+
}
|
|
27875
|
+
toRow(row) {
|
|
27876
|
+
const metadata = {};
|
|
27877
|
+
for (const [index, column] of this.options.descriptor.metadata.entries()) {
|
|
27878
|
+
const value = row[`m${index}`];
|
|
27879
|
+
if (typeof value === "string" && value.length > 0 || typeof value === "number")
|
|
27880
|
+
metadata[column.key] = String(value);
|
|
27881
|
+
}
|
|
27882
|
+
const title = typeof row.title === "string" && row.title.length > 0 ? row.title : undefined;
|
|
27883
|
+
const epoch = typeof row.epoch === "number" && Number.isFinite(row.epoch) ? row.epoch : undefined;
|
|
27884
|
+
const content = String(row.content ?? "");
|
|
27885
|
+
const input = `${title ?? ""}
|
|
27886
|
+
${content}`.slice(0, MAX_EMBED_INPUT_CHARS);
|
|
27887
|
+
return {
|
|
27888
|
+
key: String(row.k),
|
|
27889
|
+
content,
|
|
27890
|
+
title,
|
|
27891
|
+
epoch,
|
|
27892
|
+
metadata,
|
|
27893
|
+
input,
|
|
27894
|
+
hash: createHash14("sha1").update(input).digest("hex")
|
|
27895
|
+
};
|
|
27896
|
+
}
|
|
27897
|
+
toHit(row, score) {
|
|
27898
|
+
return {
|
|
27899
|
+
key: row.key,
|
|
27900
|
+
content: row.content,
|
|
27901
|
+
score,
|
|
27902
|
+
...row.title !== undefined ? { title: row.title } : {},
|
|
27903
|
+
...row.epoch !== undefined ? { publishedAt: Math.round(row.epoch * 1000) } : {},
|
|
27904
|
+
metadata: row.metadata
|
|
27905
|
+
};
|
|
27964
27906
|
}
|
|
27965
|
-
return "";
|
|
27966
27907
|
}
|
|
27967
|
-
|
|
27968
|
-
|
|
27969
|
-
|
|
27970
|
-
|
|
27971
|
-
|
|
27972
|
-
|
|
27973
|
-
|
|
27974
|
-
|
|
27975
|
-
|
|
27976
|
-
"MAILCRAWL_EMBEDDER_PROVIDER",
|
|
27977
|
-
"MAILCRAWL_EMBED_URL",
|
|
27978
|
-
"MAILCRAWL_EMBED_MODEL",
|
|
27979
|
-
"MAILCRAWL_EMBED_DIM",
|
|
27980
|
-
"MAILCRAWL_EMBED_TIMEOUT",
|
|
27981
|
-
"MAILCRAWL_EMBED_BATCH_SIZE",
|
|
27982
|
-
"MAILCRAWL_QUERY_PREFIX",
|
|
27983
|
-
"MAILCRAWL_PASSAGE_PREFIX",
|
|
27984
|
-
"MAILCRAWL_NATIVE_MODEL",
|
|
27985
|
-
"MAILCRAWL_NATIVE_DEVICE",
|
|
27986
|
-
"MAILCRAWL_NATIVE_DTYPE",
|
|
27987
|
-
"MAILCRAWL_KIWI_MODEL",
|
|
27988
|
-
"MAILCRAWL_JA_HELPER",
|
|
27989
|
-
"MAILCRAWL_ZH_HELPER"
|
|
27990
|
-
]);
|
|
27991
|
-
REMOTE_EMBEDDING_ENV_KEYS = new Set([
|
|
27992
|
-
"mailcrawl_embedder_base_url",
|
|
27993
|
-
"mailcrawl_embedding_base_url",
|
|
27994
|
-
"mailcrawl_allow_remote_embeddings"
|
|
27995
|
-
]);
|
|
27996
|
-
});
|
|
27908
|
+
function toMatchQuery(text) {
|
|
27909
|
+
const terms = [...new Set(text.match(/[\p{L}\p{N}_]+/gu) ?? [])];
|
|
27910
|
+
return terms.length === 0 ? undefined : terms.map((term) => `"${term}"`).join(" OR ");
|
|
27911
|
+
}
|
|
27912
|
+
function errorMessage2(error) {
|
|
27913
|
+
return error instanceof Error ? error.message : String(error);
|
|
27914
|
+
}
|
|
27915
|
+
var DEFAULT_BATCH_SIZE = 256, DEFAULT_MAX_EMBED_PER_SYNC = 2048, MAX_EMBED_INPUT_CHARS = 8192, BUSY_TIMEOUT_MS = 5000, POOL_FACTOR = 3, SEMANTIC_REUSE_MS = 1e4, IDENTITY_KEY = "identity";
|
|
27916
|
+
var init_sidecar = () => {};
|
|
27997
27917
|
|
|
27998
|
-
// src/datasource/
|
|
27999
|
-
|
|
28000
|
-
|
|
28001
|
-
|
|
28002
|
-
|
|
28003
|
-
|
|
28004
|
-
|
|
28005
|
-
|
|
28006
|
-
|
|
28007
|
-
this.client = client;
|
|
28008
|
-
this.mode = mode;
|
|
28009
|
-
this.instanceId = instanceId;
|
|
28010
|
-
this.tags = tags;
|
|
28011
|
-
this.account = account;
|
|
28012
|
-
this.mailbox = mailbox;
|
|
27918
|
+
// src/datasource/sidecar/methods.ts
|
|
27919
|
+
function sidecarMethodName(datasourceId, mode) {
|
|
27920
|
+
return mode === "bm25" ? `${datasourceId}-sidecar-bm25` : `${datasourceId}-${mode}`;
|
|
27921
|
+
}
|
|
27922
|
+
|
|
27923
|
+
class SidecarRetrievalMethod {
|
|
27924
|
+
options;
|
|
27925
|
+
constructor(options) {
|
|
27926
|
+
this.options = options;
|
|
28013
27927
|
}
|
|
28014
27928
|
describe() {
|
|
27929
|
+
const { datasourceId, skillType, mode, tags } = this.options;
|
|
27930
|
+
const { type, text, capabilities } = DESCRIPTIONS[mode];
|
|
28015
27931
|
return {
|
|
28016
|
-
name:
|
|
28017
|
-
type
|
|
28018
|
-
description: `${
|
|
27932
|
+
name: sidecarMethodName(datasourceId, mode),
|
|
27933
|
+
type,
|
|
27934
|
+
description: `${text} over ${skillType} via a read-only sidecar index`,
|
|
28019
27935
|
status: "active",
|
|
28020
|
-
capabilities: [
|
|
28021
|
-
datasourceId
|
|
28022
|
-
tags
|
|
27936
|
+
capabilities: [...capabilities, "scoped", "path-opaque-sources"],
|
|
27937
|
+
datasourceId,
|
|
27938
|
+
tags
|
|
27939
|
+
};
|
|
27940
|
+
}
|
|
27941
|
+
async retrieve(query, options) {
|
|
27942
|
+
const trimmed = query.trim();
|
|
27943
|
+
if (trimmed.length === 0)
|
|
27944
|
+
return [];
|
|
27945
|
+
const topK = options.topK ?? DEFAULT_TOP_K5;
|
|
27946
|
+
const { sidecar, mode } = this.options;
|
|
27947
|
+
const hits = mode === "bm25" ? sidecar.searchLexical(trimmed, topK) : mode === "semantic" ? await sidecar.searchSemantic(trimmed, topK) : await sidecar.searchHybrid(trimmed, topK);
|
|
27948
|
+
const results = [];
|
|
27949
|
+
for (const hit of hits) {
|
|
27950
|
+
const result = this.toResult(hit, options);
|
|
27951
|
+
if (result !== undefined)
|
|
27952
|
+
results.push(result);
|
|
27953
|
+
}
|
|
27954
|
+
return results;
|
|
27955
|
+
}
|
|
27956
|
+
toResult(hit, options) {
|
|
27957
|
+
const { descriptor, datasourceId, instanceId, mode } = this.options;
|
|
27958
|
+
const chunkId = descriptor.chunkId(hit.key, hit.metadata);
|
|
27959
|
+
const source = datasourceSourcePath(datasourceId, instanceId, chunkId);
|
|
27960
|
+
if (!matchesDatasourceScope(source, options.scope))
|
|
27961
|
+
return;
|
|
27962
|
+
const method = sidecarMethodName(datasourceId, mode);
|
|
27963
|
+
return {
|
|
27964
|
+
id: `${datasourceId}:${instanceId}:${chunkId}`,
|
|
27965
|
+
content: hit.content,
|
|
27966
|
+
source,
|
|
27967
|
+
score: hit.score,
|
|
27968
|
+
metadata: {
|
|
27969
|
+
...hit.metadata,
|
|
27970
|
+
method,
|
|
27971
|
+
datasourceId,
|
|
27972
|
+
instanceId,
|
|
27973
|
+
backend: "sidecar",
|
|
27974
|
+
...hit.title !== undefined ? { title: hit.title } : {},
|
|
27975
|
+
hierarchy: descriptor.hierarchy(hit.metadata).join("/"),
|
|
27976
|
+
...hit.publishedAt !== undefined ? { publishedAt: hit.publishedAt } : {}
|
|
27977
|
+
}
|
|
28023
27978
|
};
|
|
28024
27979
|
}
|
|
28025
|
-
async retrieve(query, options) {
|
|
28026
|
-
if (!query.trim())
|
|
28027
|
-
return [];
|
|
28028
|
-
const result = await this.client.search(this.mode, query, {
|
|
28029
|
-
topK: options.topK,
|
|
28030
|
-
signal: options.signal
|
|
28031
|
-
});
|
|
28032
|
-
if (!result.ok)
|
|
28033
|
-
throw datasourceCliError("mailcrawl", `search --mode ${this.mode}`, result);
|
|
28034
|
-
return result.hits.filter((hit) => {
|
|
28035
|
-
if (this.account !== undefined && hit.accountId !== this.account)
|
|
28036
|
-
return false;
|
|
28037
|
-
if (this.mailbox !== undefined && hit.mailbox !== this.mailbox)
|
|
28038
|
-
return false;
|
|
28039
|
-
const source = datasourceSourcePath("mailcrawl", this.instanceId, hit.chunkId);
|
|
28040
|
-
return matchesDatasourceScope(source, options.scope);
|
|
28041
|
-
}).map((hit) => {
|
|
28042
|
-
const source = datasourceSourcePath("mailcrawl", this.instanceId, hit.chunkId);
|
|
28043
|
-
return {
|
|
28044
|
-
id: `mailcrawl:${this.instanceId}:${hit.chunkId}`,
|
|
28045
|
-
content: hit.snippet,
|
|
28046
|
-
source,
|
|
28047
|
-
score: hit.score,
|
|
28048
|
-
metadata: {
|
|
28049
|
-
method: `mailcrawl-${this.mode}`,
|
|
28050
|
-
datasourceId: "mailcrawl",
|
|
28051
|
-
instanceId: this.instanceId,
|
|
28052
|
-
mode: this.mode,
|
|
28053
|
-
chunkId: hit.chunkId,
|
|
28054
|
-
messageId: hit.messageId,
|
|
28055
|
-
threadId: hit.threadId,
|
|
28056
|
-
accountId: hit.accountId,
|
|
28057
|
-
mailbox: hit.mailbox,
|
|
28058
|
-
subject: hit.subject,
|
|
28059
|
-
from: hit.from,
|
|
28060
|
-
to: hit.to,
|
|
28061
|
-
date: hit.date
|
|
28062
|
-
}
|
|
28063
|
-
};
|
|
28064
|
-
}).slice(0, options.topK ?? 20);
|
|
28065
|
-
}
|
|
28066
27980
|
}
|
|
28067
|
-
var
|
|
27981
|
+
var DEFAULT_TOP_K5 = 20, DESCRIPTIONS;
|
|
28068
27982
|
var init_methods4 = __esm(() => {
|
|
28069
|
-
init_errors4();
|
|
28070
27983
|
init_scope2();
|
|
28071
|
-
|
|
28072
|
-
|
|
27984
|
+
DESCRIPTIONS = {
|
|
27985
|
+
bm25: { type: "bm25", text: "BM25-ranked FTS5 retrieval", capabilities: ["lexical", "fts5", "bm25"] },
|
|
27986
|
+
semantic: { type: "vector", text: "Semantic (embedding) retrieval", capabilities: ["semantic"] },
|
|
27987
|
+
hybrid: {
|
|
27988
|
+
type: "hybrid",
|
|
27989
|
+
text: "Hybrid BM25 + semantic retrieval (reciprocal rank fusion)",
|
|
27990
|
+
capabilities: ["lexical", "semantic", "hybrid"]
|
|
27991
|
+
}
|
|
27992
|
+
};
|
|
28073
27993
|
});
|
|
28074
27994
|
|
|
28075
|
-
// src/datasource/skills/
|
|
28076
|
-
class
|
|
27995
|
+
// src/datasource/skills/lazykatok/skill.ts
|
|
27996
|
+
class LazykatokSkill {
|
|
28077
27997
|
client;
|
|
28078
27998
|
instanceId;
|
|
28079
27999
|
instances;
|
|
28080
|
-
|
|
28000
|
+
pollingIntervalMs;
|
|
28081
28001
|
tags;
|
|
28082
|
-
|
|
28083
|
-
mailbox;
|
|
28002
|
+
sidecar;
|
|
28084
28003
|
lastIndexedAt;
|
|
28085
|
-
constructor(options
|
|
28086
|
-
|
|
28087
|
-
this.instanceId = options.instanceId ??
|
|
28088
|
-
this.instances = options.instances
|
|
28089
|
-
|
|
28090
|
-
|
|
28091
|
-
|
|
28092
|
-
this.
|
|
28093
|
-
|
|
28094
|
-
|
|
28095
|
-
|
|
28096
|
-
|
|
28004
|
+
constructor(options) {
|
|
28005
|
+
this.client = options.client;
|
|
28006
|
+
this.instanceId = options.instanceId ?? DEFAULT_INSTANCE_ID4;
|
|
28007
|
+
this.instances = options.instances !== undefined && options.instances.length > 0 ? options.instances : [this.instanceId];
|
|
28008
|
+
this.pollingIntervalMs = options.pollingIntervalMs ?? DEFAULT_POLLING_INTERVAL_MS3;
|
|
28009
|
+
this.tags = options.tags ?? DEFAULT_KAKAO_TAGS2;
|
|
28010
|
+
this.lastIndexedAt = options.lastIndexedAt;
|
|
28011
|
+
this.sidecar = options.sidecar === undefined ? undefined : new CrawlerSidecar({
|
|
28012
|
+
...options.sidecar,
|
|
28013
|
+
channelIds: options.channelIds ?? options.sidecar.channelIds ?? [],
|
|
28014
|
+
channelNames: options.channelNames ?? options.sidecar.channelNames ?? []
|
|
28015
|
+
});
|
|
28097
28016
|
}
|
|
28098
28017
|
describe() {
|
|
28099
28018
|
return {
|
|
28100
|
-
name:
|
|
28101
|
-
id:
|
|
28102
|
-
type:
|
|
28103
|
-
description: "
|
|
28104
|
-
capabilities: ["
|
|
28019
|
+
name: KAKAO_DATASOURCE_ID2,
|
|
28020
|
+
id: KAKAO_DATASOURCE_ID2,
|
|
28021
|
+
type: KAKAO_SKILL_TYPE,
|
|
28022
|
+
description: "KakaoTalk datasource via the external lazykatok CLI",
|
|
28023
|
+
capabilities: ["chat", "external-cli", "polling", "bm25", "semantic"],
|
|
28105
28024
|
tags: this.tags,
|
|
28106
28025
|
status: "active",
|
|
28107
28026
|
requiresExternalCli: true,
|
|
28108
|
-
datasourceId:
|
|
28027
|
+
datasourceId: KAKAO_DATASOURCE_ID2,
|
|
28109
28028
|
instanceId: this.instanceId,
|
|
28110
28029
|
instances: this.instances
|
|
28111
28030
|
};
|
|
28112
28031
|
}
|
|
28113
28032
|
polling() {
|
|
28114
28033
|
return {
|
|
28115
|
-
mode:
|
|
28116
|
-
|
|
28034
|
+
mode: "poll",
|
|
28035
|
+
intervalMs: this.pollingIntervalMs,
|
|
28117
28036
|
lastIndexedAt: this.lastIndexedAt
|
|
28118
28037
|
};
|
|
28119
28038
|
}
|
|
28120
28039
|
async index(options) {
|
|
28121
28040
|
try {
|
|
28122
|
-
const
|
|
28123
|
-
if (!
|
|
28124
|
-
return this.fail(
|
|
28125
|
-
|
|
28126
|
-
|
|
28127
|
-
|
|
28128
|
-
if (
|
|
28129
|
-
|
|
28130
|
-
|
|
28131
|
-
|
|
28132
|
-
message: `mailcrawl semantic index unavailable (${indexed.reason}); BM25 remains available`,
|
|
28041
|
+
const doctor = await this.client.doctor(options?.signal);
|
|
28042
|
+
if (!doctor.ok)
|
|
28043
|
+
return this.fail("datasource-unavailable", doctor);
|
|
28044
|
+
const sync = await this.client.sync(options?.signal);
|
|
28045
|
+
if (!sync.ok)
|
|
28046
|
+
return this.fail("datasource-index-failed", sync);
|
|
28047
|
+
if (this.sidecar !== undefined) {
|
|
28048
|
+
this.lastIndexedAt = Date.now();
|
|
28049
|
+
return {
|
|
28050
|
+
ok: true,
|
|
28133
28051
|
instanceId: this.instanceId,
|
|
28134
|
-
|
|
28135
|
-
|
|
28052
|
+
skill: KAKAO_DATASOURCE_ID2,
|
|
28053
|
+
chunkCount: syncChunkCount(sync),
|
|
28054
|
+
indexedAt: this.lastIndexedAt,
|
|
28055
|
+
diagnostics: await this.syncSidecar()
|
|
28056
|
+
};
|
|
28136
28057
|
}
|
|
28058
|
+
const indexResult = await this.client.index(options?.signal);
|
|
28059
|
+
if (!indexResult.ok)
|
|
28060
|
+
return this.fail("datasource-index-failed", indexResult);
|
|
28137
28061
|
this.lastIndexedAt = Date.now();
|
|
28062
|
+
const chunkCount = "data" in indexResult && typeof indexResult.data === "object" && indexResult.data !== null && "chunkCount" in indexResult.data && typeof indexResult.data.chunkCount === "number" ? indexResult.data.chunkCount : 0;
|
|
28138
28063
|
return {
|
|
28139
28064
|
ok: true,
|
|
28140
28065
|
instanceId: this.instanceId,
|
|
28141
|
-
skill:
|
|
28142
|
-
chunkCount
|
|
28066
|
+
skill: KAKAO_DATASOURCE_ID2,
|
|
28067
|
+
chunkCount,
|
|
28143
28068
|
indexedAt: this.lastIndexedAt,
|
|
28144
|
-
diagnostics
|
|
28069
|
+
diagnostics: []
|
|
28145
28070
|
};
|
|
28146
|
-
} catch {
|
|
28147
|
-
return this.fail("datasource-unavailable",
|
|
28071
|
+
} catch (error) {
|
|
28072
|
+
return this.fail("datasource-unavailable", {
|
|
28073
|
+
ok: false,
|
|
28074
|
+
reason: "spawn-error",
|
|
28075
|
+
stdout: "",
|
|
28076
|
+
stderr: describeRetrievalError(error),
|
|
28077
|
+
code: null
|
|
28078
|
+
});
|
|
28148
28079
|
}
|
|
28149
28080
|
}
|
|
28081
|
+
close() {
|
|
28082
|
+
this.sidecar?.close();
|
|
28083
|
+
}
|
|
28150
28084
|
retrievalMethods() {
|
|
28085
|
+
const cliBm25 = new LazykatokBm25Method({ client: this.client, instanceId: this.instanceId, tags: this.tags });
|
|
28086
|
+
const { sidecar } = this;
|
|
28087
|
+
if (sidecar === undefined) {
|
|
28088
|
+
return [
|
|
28089
|
+
cliBm25,
|
|
28090
|
+
new LazykatokSemanticMethod({ client: this.client, instanceId: this.instanceId, tags: this.tags })
|
|
28091
|
+
];
|
|
28092
|
+
}
|
|
28093
|
+
const shared = {
|
|
28094
|
+
sidecar,
|
|
28095
|
+
descriptor: sidecar.descriptor,
|
|
28096
|
+
datasourceId: KAKAO_DATASOURCE_ID2,
|
|
28097
|
+
skillType: KAKAO_SKILL_TYPE,
|
|
28098
|
+
instanceId: this.instanceId,
|
|
28099
|
+
tags: this.tags
|
|
28100
|
+
};
|
|
28101
|
+
const bm25 = new SidecarRetrievalMethod({ ...shared, mode: "bm25" });
|
|
28102
|
+
if (!sidecar.semanticEnabled)
|
|
28103
|
+
return [cliBm25, bm25];
|
|
28151
28104
|
return [
|
|
28152
|
-
|
|
28153
|
-
|
|
28154
|
-
new
|
|
28105
|
+
cliBm25,
|
|
28106
|
+
bm25,
|
|
28107
|
+
new SidecarRetrievalMethod({ ...shared, mode: "semantic" }),
|
|
28108
|
+
new SidecarRetrievalMethod({ ...shared, mode: "hybrid" })
|
|
28155
28109
|
];
|
|
28156
28110
|
}
|
|
28111
|
+
async syncSidecar() {
|
|
28112
|
+
if (this.sidecar === undefined || !this.sidecar.semanticEnabled)
|
|
28113
|
+
return [];
|
|
28114
|
+
const base = { instanceId: this.instanceId, source: KAKAO_DATASOURCE_ID2 };
|
|
28115
|
+
let result;
|
|
28116
|
+
try {
|
|
28117
|
+
result = await this.sidecar.sync();
|
|
28118
|
+
} catch (error) {
|
|
28119
|
+
result = { ok: false, message: error instanceof Error ? error.message : String(error) };
|
|
28120
|
+
}
|
|
28121
|
+
if (!result.ok) {
|
|
28122
|
+
return [
|
|
28123
|
+
{
|
|
28124
|
+
code: "datasource-index-failed",
|
|
28125
|
+
severity: "warning",
|
|
28126
|
+
message: `semantic-unavailable: ${result.message}`.slice(0, 300),
|
|
28127
|
+
...base
|
|
28128
|
+
}
|
|
28129
|
+
];
|
|
28130
|
+
}
|
|
28131
|
+
const diagnostics = [];
|
|
28132
|
+
if (result.skipped > 0) {
|
|
28133
|
+
diagnostics.push({
|
|
28134
|
+
code: "datasource-index-partial",
|
|
28135
|
+
severity: "warning",
|
|
28136
|
+
message: `semantic index skipped ${result.skipped} message(s) the embedder rejected; they stay searchable by BM25 and are retried when edited`,
|
|
28137
|
+
...base
|
|
28138
|
+
});
|
|
28139
|
+
}
|
|
28140
|
+
if (result.remaining > 0) {
|
|
28141
|
+
diagnostics.push({
|
|
28142
|
+
code: "datasource-index-partial",
|
|
28143
|
+
severity: "info",
|
|
28144
|
+
message: `semantic index catching up: ${result.embedded} embedded this refresh, ${result.remaining} remaining; hybrid search uses BM25 for the rest until a later refresh`,
|
|
28145
|
+
...base
|
|
28146
|
+
});
|
|
28147
|
+
}
|
|
28148
|
+
return diagnostics;
|
|
28149
|
+
}
|
|
28157
28150
|
describeSources() {
|
|
28158
28151
|
return this.instances.map((instanceId) => ({
|
|
28159
|
-
source: datasourceSourcePath(
|
|
28160
|
-
datasourceId:
|
|
28161
|
-
skill:
|
|
28152
|
+
source: datasourceSourcePath(KAKAO_DATASOURCE_ID2, instanceId),
|
|
28153
|
+
datasourceId: KAKAO_DATASOURCE_ID2,
|
|
28154
|
+
skill: KAKAO_DATASOURCE_ID2,
|
|
28162
28155
|
instanceId,
|
|
28163
|
-
contentType: "
|
|
28164
|
-
metadata: {
|
|
28165
|
-
|
|
28166
|
-
|
|
28167
|
-
|
|
28168
|
-
|
|
28169
|
-
|
|
28170
|
-
|
|
28171
|
-
|
|
28172
|
-
|
|
28173
|
-
|
|
28174
|
-
|
|
28175
|
-
|
|
28176
|
-
|
|
28177
|
-
|
|
28178
|
-
|
|
28179
|
-
|
|
28180
|
-
|
|
28181
|
-
|
|
28182
|
-
|
|
28183
|
-
|
|
28184
|
-
|
|
28185
|
-
|
|
28186
|
-
##
|
|
28187
|
-
|
|
28188
|
-
|
|
28189
|
-
|
|
28156
|
+
contentType: "chat",
|
|
28157
|
+
metadata: {
|
|
28158
|
+
datasourceId: KAKAO_DATASOURCE_ID2,
|
|
28159
|
+
instanceId,
|
|
28160
|
+
tags: this.tags
|
|
28161
|
+
}
|
|
28162
|
+
}));
|
|
28163
|
+
}
|
|
28164
|
+
skillManifest() {
|
|
28165
|
+
const instanceSources = this.instances.map((instanceId) => `- \`${datasourceSourcePath(KAKAO_DATASOURCE_ID2, instanceId)}\``).join(`
|
|
28166
|
+
`);
|
|
28167
|
+
const cadence = this.pollingIntervalMs > 0 ? `roughly every ${Math.round(this.pollingIntervalMs / 60000)} minute(s) when auto-refresh runs` : "on manual refresh only";
|
|
28168
|
+
return {
|
|
28169
|
+
name: `datasource-${KAKAO_DATASOURCE_ID2}`,
|
|
28170
|
+
description: "Search indexed KakaoTalk chat history (messages, senders, room context). Use for questions about KakaoTalk conversations, decisions made in chats, or who said what.",
|
|
28171
|
+
content: [
|
|
28172
|
+
`# KakaoTalk datasource (${KAKAO_SKILL_TYPE})`,
|
|
28173
|
+
"",
|
|
28174
|
+
"This skill searches KakaoTalk chats that are indexed through the external `lazykatok` CLI. AutoRAG never reads KakaoTalk databases directly.",
|
|
28175
|
+
"",
|
|
28176
|
+
"## When to use",
|
|
28177
|
+
"Use this skill when the question is about KakaoTalk conversations, chat participants, or content shared inside chats.",
|
|
28178
|
+
"",
|
|
28179
|
+
"## Indexing",
|
|
28180
|
+
`Indexing is server-managed and refreshed ${cadence}. You do not trigger indexing; just search.`,
|
|
28181
|
+
"",
|
|
28182
|
+
"## How to search",
|
|
28183
|
+
`Call the dedicated \`${datasourceSearchToolName(KAKAO_DATASOURCE_ID2)}\` tool with a natural-language \`query\` and \`topK\`. This datasource does not support per-source scope narrowing. Configured datasource instances:`,
|
|
28184
|
+
instanceSources.length > 0 ? instanceSources : "- (no configured instances)",
|
|
28185
|
+
"",
|
|
28186
|
+
"Chat/channel filtering is owned by lazykatok.",
|
|
28187
|
+
"",
|
|
28188
|
+
"## Native CLI",
|
|
28189
|
+
"The external `lazykatok` CLI owns the archive, index, and credentials. When the dedicated tool cannot express what you need, call lazykatok directly through `bash`:",
|
|
28190
|
+
'- `lazykatok search bm25 "<query>" --json --limit 20` — lexical search (`semantic` mode also available)',
|
|
28191
|
+
"- `lazykatok chunk get <chunkId> --json` — fetch one chunk by id (chunk ids appear in result metadata)",
|
|
28192
|
+
"- `lazykatok chunk context <chunkId> --json` — surrounding messages of a chunk",
|
|
28193
|
+
"Never pass datasource virtual paths (`/kakao/...`) to bash; they are not OS paths.",
|
|
28194
|
+
"",
|
|
28195
|
+
"## Output rules",
|
|
28196
|
+
"Datasource source identifiers such as `/kakao/<instance>/chunks/<id>` are internal and opaque. Never put them, real file paths, account IDs, or phone numbers in the visible answer."
|
|
28197
|
+
].join(`
|
|
28198
|
+
`)
|
|
28190
28199
|
};
|
|
28191
28200
|
}
|
|
28192
|
-
fail(code,
|
|
28201
|
+
fail(code, result) {
|
|
28202
|
+
const base = result.stderr.length > 0 ? `${result.reason}: ${result.stderr.trim().slice(0, 4000)}` : result.reason;
|
|
28203
|
+
const message = code === "datasource-index-failed" && result.reason === "timeout" ? `${base} — ${connectorSyncTimeoutHint()}` : base;
|
|
28204
|
+
const diagnostic = {
|
|
28205
|
+
code,
|
|
28206
|
+
severity: code === "datasource-unavailable" ? "warning" : "error",
|
|
28207
|
+
message,
|
|
28208
|
+
instanceId: this.instanceId,
|
|
28209
|
+
source: KAKAO_DATASOURCE_ID2
|
|
28210
|
+
};
|
|
28193
28211
|
return {
|
|
28194
28212
|
ok: false,
|
|
28195
28213
|
instanceId: this.instanceId,
|
|
28196
|
-
skill:
|
|
28214
|
+
skill: KAKAO_DATASOURCE_ID2,
|
|
28197
28215
|
indexedAt: Date.now(),
|
|
28198
|
-
diagnostics: [
|
|
28199
|
-
|
|
28200
|
-
code,
|
|
28201
|
-
severity: code === "datasource-unavailable" ? "warning" : "error",
|
|
28202
|
-
message: `mailcrawl ${message}`,
|
|
28203
|
-
instanceId: this.instanceId,
|
|
28204
|
-
source: "mailcrawl"
|
|
28205
|
-
}
|
|
28206
|
-
],
|
|
28207
|
-
error: message,
|
|
28216
|
+
diagnostics: [diagnostic],
|
|
28217
|
+
error: result.reason,
|
|
28208
28218
|
code,
|
|
28209
28219
|
message
|
|
28210
28220
|
};
|
|
28211
28221
|
}
|
|
28212
28222
|
}
|
|
28213
|
-
|
|
28214
|
-
|
|
28223
|
+
function syncChunkCount(sync) {
|
|
28224
|
+
if (!("data" in sync) || typeof sync.data !== "object" || sync.data === null)
|
|
28225
|
+
return 0;
|
|
28226
|
+
const meta = "metadata" in sync.data && typeof sync.data.metadata === "object" && sync.data.metadata !== null ? sync.data.metadata : undefined;
|
|
28227
|
+
if (typeof meta?.chunks === "number")
|
|
28228
|
+
return meta.chunks;
|
|
28229
|
+
if ("messageCount" in sync.data && typeof sync.data.messageCount === "number")
|
|
28230
|
+
return sync.data.messageCount;
|
|
28231
|
+
return 0;
|
|
28232
|
+
}
|
|
28233
|
+
var KAKAO_DATASOURCE_ID2 = "kakao", KAKAO_SKILL_TYPE = "kakaotalk", DEFAULT_INSTANCE_ID4 = "default", DEFAULT_POLLING_INTERVAL_MS3, DEFAULT_KAKAO_TAGS2;
|
|
28234
|
+
var init_skill7 = __esm(() => {
|
|
28235
|
+
init_skip();
|
|
28215
28236
|
init_scope2();
|
|
28216
|
-
|
|
28217
|
-
init_config3();
|
|
28237
|
+
init_sidecar();
|
|
28218
28238
|
init_methods4();
|
|
28219
|
-
|
|
28239
|
+
init_methods3();
|
|
28240
|
+
DEFAULT_POLLING_INTERVAL_MS3 = 15 * 60 * 1000;
|
|
28241
|
+
DEFAULT_KAKAO_TAGS2 = ["kakaotalk", "personal", "pii"];
|
|
28220
28242
|
});
|
|
28221
28243
|
|
|
28222
|
-
// src/datasource/skills/
|
|
28223
|
-
var
|
|
28224
|
-
|
|
28225
|
-
|
|
28226
|
-
|
|
28244
|
+
// src/datasource/skills/lazykatok/index.ts
|
|
28245
|
+
var init_lazykatok = __esm(() => {
|
|
28246
|
+
init_client8();
|
|
28247
|
+
init_methods3();
|
|
28248
|
+
init_skill7();
|
|
28249
|
+
init_types5();
|
|
28250
|
+
});
|
|
28251
|
+
|
|
28252
|
+
// src/datasource/skills/mail-export/connector.ts
|
|
28253
|
+
import { readdir as readdir4, readFile as readFile5, stat as stat6 } from "node:fs/promises";
|
|
28254
|
+
import { basename as basename12, dirname as dirname25, extname as extname6, join as join37 } from "node:path";
|
|
28255
|
+
import { simpleParser as simpleParser2 } from "mailparser";
|
|
28256
|
+
|
|
28257
|
+
class MailExportConnector {
|
|
28258
|
+
options;
|
|
28259
|
+
constructor(options = {}) {
|
|
28260
|
+
this.options = options;
|
|
28261
|
+
}
|
|
28262
|
+
async fetch() {
|
|
28263
|
+
const paths = this.options.paths ?? [];
|
|
28264
|
+
if (paths.length === 0)
|
|
28265
|
+
return { ok: false, reason: "not-configured", message: "no mail export paths configured" };
|
|
28266
|
+
const maxDocuments = this.options.maxDocuments ?? DEFAULT_MAX_DOCUMENTS3;
|
|
28267
|
+
const maxBytes = this.options.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE2;
|
|
28268
|
+
const files = [];
|
|
28269
|
+
let missingPaths = 0;
|
|
28270
|
+
for (const path of paths) {
|
|
28271
|
+
try {
|
|
28272
|
+
const info = await stat6(path);
|
|
28273
|
+
if (info.isDirectory()) {
|
|
28274
|
+
const entries = await readdir4(path, { recursive: true, withFileTypes: true });
|
|
28275
|
+
for (const entry of entries) {
|
|
28276
|
+
if (!entry.isFile())
|
|
28277
|
+
continue;
|
|
28278
|
+
const extension = extname6(entry.name).toLowerCase();
|
|
28279
|
+
if (extension === ".eml" || extension === ".mbox") {
|
|
28280
|
+
files.push(join37(entry.parentPath, entry.name));
|
|
28281
|
+
}
|
|
28282
|
+
}
|
|
28283
|
+
} else if (info.isFile()) {
|
|
28284
|
+
files.push(path);
|
|
28285
|
+
}
|
|
28286
|
+
} catch {
|
|
28287
|
+
missingPaths += 1;
|
|
28288
|
+
}
|
|
28289
|
+
}
|
|
28290
|
+
if (missingPaths === paths.length) {
|
|
28291
|
+
return { ok: false, reason: "unavailable", message: "no configured mail export paths were readable" };
|
|
28292
|
+
}
|
|
28293
|
+
const documents = [];
|
|
28294
|
+
const warnings = [];
|
|
28295
|
+
if (missingPaths > 0)
|
|
28296
|
+
warnings.push(`${missingPaths} configured path(s) were unreadable`);
|
|
28297
|
+
let parseFailures = 0;
|
|
28298
|
+
let skippedLarge = 0;
|
|
28299
|
+
for (const file of files.sort()) {
|
|
28300
|
+
if (documents.length >= maxDocuments)
|
|
28301
|
+
break;
|
|
28302
|
+
let bytes;
|
|
28303
|
+
try {
|
|
28304
|
+
const info = await stat6(file);
|
|
28305
|
+
if (info.size > maxBytes) {
|
|
28306
|
+
skippedLarge += 1;
|
|
28307
|
+
continue;
|
|
28308
|
+
}
|
|
28309
|
+
bytes = await readFile5(file);
|
|
28310
|
+
} catch {
|
|
28311
|
+
parseFailures += 1;
|
|
28312
|
+
continue;
|
|
28313
|
+
}
|
|
28314
|
+
const stem = basename12(file, extname6(file));
|
|
28315
|
+
const mailboxDir = basename12(dirname25(file));
|
|
28316
|
+
const hierarchy = ["mailboxes", mailboxDir, stem];
|
|
28317
|
+
const extension = extname6(file).toLowerCase();
|
|
28318
|
+
const rawMessages = extension === ".mbox" ? splitMbox(bytes.toString("utf8")) : [bytes.toString("utf8")];
|
|
28319
|
+
for (const [index, raw] of rawMessages.entries()) {
|
|
28320
|
+
if (documents.length >= maxDocuments)
|
|
28321
|
+
break;
|
|
28322
|
+
try {
|
|
28323
|
+
const parsed = await simpleParser2(raw);
|
|
28324
|
+
const subject = parsed.subject ?? "(no subject)";
|
|
28325
|
+
const from = Array.isArray(parsed.from) ? parsed.from[0]?.text : parsed.from?.text;
|
|
28326
|
+
const to = Array.isArray(parsed.to) ? parsed.to[0]?.text : parsed.to?.text;
|
|
28327
|
+
const body = (parsed.text ?? "").trim().slice(0, MAX_BODY_CHARS);
|
|
28328
|
+
const headerBlock = [
|
|
28329
|
+
`Subject: ${subject}`,
|
|
28330
|
+
...from !== undefined ? [`From: ${from}`] : [],
|
|
28331
|
+
...to !== undefined ? [`To: ${to}`] : [],
|
|
28332
|
+
...parsed.date !== undefined ? [`Date: ${parsed.date.toISOString()}`] : []
|
|
28333
|
+
].join(`
|
|
28334
|
+
`);
|
|
28335
|
+
const content = `${headerBlock}
|
|
28336
|
+
|
|
28337
|
+
${body}`.trim();
|
|
28338
|
+
if (content.length === 0)
|
|
28339
|
+
continue;
|
|
28340
|
+
documents.push({
|
|
28341
|
+
docId: extension === ".mbox" ? `${stem}-${index + 1}` : stem,
|
|
28342
|
+
hierarchy,
|
|
28343
|
+
title: subject,
|
|
28344
|
+
content,
|
|
28345
|
+
...parsed.date !== undefined ? { publishedAt: parsed.date.getTime() } : {},
|
|
28346
|
+
metadata: {
|
|
28347
|
+
path: file,
|
|
28348
|
+
subject,
|
|
28349
|
+
...from !== undefined ? { from } : {},
|
|
28350
|
+
messageIndex: index
|
|
28351
|
+
}
|
|
28352
|
+
});
|
|
28353
|
+
} catch {
|
|
28354
|
+
parseFailures += 1;
|
|
28355
|
+
}
|
|
28356
|
+
}
|
|
28357
|
+
}
|
|
28358
|
+
if (skippedLarge > 0)
|
|
28359
|
+
warnings.push(`${skippedLarge} file(s) exceeded the size limit and were skipped`);
|
|
28360
|
+
if (parseFailures > 0)
|
|
28361
|
+
warnings.push(`${parseFailures} message(s) failed to parse`);
|
|
28362
|
+
return { ok: true, documents, ...warnings.length > 0 ? { warnings } : {} };
|
|
28363
|
+
}
|
|
28364
|
+
}
|
|
28365
|
+
function splitMbox(text) {
|
|
28366
|
+
const lines = text.split(/\r?\n/u);
|
|
28367
|
+
const messages = [];
|
|
28368
|
+
let current = [];
|
|
28369
|
+
for (const line of lines) {
|
|
28370
|
+
if (MBOX_SEPARATOR.test(line) && line.startsWith("From ")) {
|
|
28371
|
+
if (current.length > 0)
|
|
28372
|
+
messages.push(current.join(`
|
|
28373
|
+
`));
|
|
28374
|
+
current = [];
|
|
28375
|
+
continue;
|
|
28376
|
+
}
|
|
28377
|
+
current.push(line);
|
|
28378
|
+
}
|
|
28379
|
+
if (current.length > 0)
|
|
28380
|
+
messages.push(current.join(`
|
|
28381
|
+
`));
|
|
28382
|
+
return messages.filter((message) => message.trim().length > 0);
|
|
28383
|
+
}
|
|
28384
|
+
var DEFAULT_MAX_DOCUMENTS3 = 500, DEFAULT_MAX_BYTES_PER_FILE2, MAX_BODY_CHARS = 50000, MBOX_SEPARATOR;
|
|
28385
|
+
var init_connector4 = __esm(() => {
|
|
28386
|
+
DEFAULT_MAX_BYTES_PER_FILE2 = 50 * 1024 * 1024;
|
|
28387
|
+
MBOX_SEPARATOR = /^From .*\d{4}$/mu;
|
|
28388
|
+
});
|
|
28389
|
+
|
|
28390
|
+
// src/datasource/skills/mail-export/skill.ts
|
|
28391
|
+
var MAIL_EXPORT_SKILL_DEFINITION, MailExportSkill;
|
|
28392
|
+
var init_skill8 = __esm(() => {
|
|
28393
|
+
init_connector_skill();
|
|
28394
|
+
init_connector4();
|
|
28395
|
+
MAIL_EXPORT_SKILL_DEFINITION = {
|
|
28396
|
+
skillName: "mail-export",
|
|
28397
|
+
skillType: "mail-export",
|
|
28398
|
+
description: "Local mail export datasource",
|
|
28399
|
+
capabilities: ["email", "filesystem"],
|
|
28400
|
+
defaultTags: ["mail-export", "email", "pii"],
|
|
28401
|
+
contentType: "email",
|
|
28402
|
+
manifestDescription: "Search indexed local mail exports (mbox/eml archives). Use for questions about archived email conversations.",
|
|
28403
|
+
manifestNotes: [
|
|
28404
|
+
"Only the server-configured export paths are indexed; archives are read locally and never uploaded."
|
|
28405
|
+
]
|
|
28406
|
+
};
|
|
28407
|
+
MailExportSkill = class MailExportSkill extends ConnectorDatasourceSkill {
|
|
28408
|
+
constructor(options = {}) {
|
|
28409
|
+
const { connector, connectorOptions, ...rest } = options;
|
|
28410
|
+
super(MAIL_EXPORT_SKILL_DEFINITION, {
|
|
28411
|
+
...rest,
|
|
28412
|
+
connector: connector ?? new MailExportConnector(connectorOptions ?? {})
|
|
28413
|
+
});
|
|
28414
|
+
}
|
|
28415
|
+
};
|
|
28416
|
+
});
|
|
28417
|
+
|
|
28418
|
+
// src/datasource/skills/mail-export/index.ts
|
|
28419
|
+
var init_mail_export = __esm(() => {
|
|
28420
|
+
init_connector4();
|
|
28421
|
+
init_skill8();
|
|
28227
28422
|
});
|
|
28228
28423
|
|
|
28229
|
-
// src/datasource/
|
|
28230
|
-
|
|
28231
|
-
|
|
28232
|
-
|
|
28233
|
-
|
|
28234
|
-
function decodeVector(blob) {
|
|
28235
|
-
if (blob.byteLength % Float32Array.BYTES_PER_ELEMENT !== 0)
|
|
28236
|
-
return;
|
|
28237
|
-
return new Float32Array(new Uint8Array(blob).buffer);
|
|
28238
|
-
}
|
|
28239
|
-
function cosine3(a, b) {
|
|
28240
|
-
if (a.length === 0 || a.length !== b.length)
|
|
28241
|
-
return 0;
|
|
28242
|
-
let dot = 0;
|
|
28243
|
-
let normA = 0;
|
|
28244
|
-
let normB = 0;
|
|
28245
|
-
for (let index = 0;index < a.length; index += 1) {
|
|
28246
|
-
const x = a[index] ?? 0;
|
|
28247
|
-
const y = b[index] ?? 0;
|
|
28248
|
-
dot += x * y;
|
|
28249
|
-
normA += x * x;
|
|
28250
|
-
normB += y * y;
|
|
28251
|
-
}
|
|
28252
|
-
if (normA === 0 || normB === 0)
|
|
28253
|
-
return 0;
|
|
28254
|
-
return dot / Math.sqrt(normA * normB);
|
|
28255
|
-
}
|
|
28256
|
-
function topKByCosine(query, rows, k) {
|
|
28257
|
-
if (k <= 0)
|
|
28258
|
-
return [];
|
|
28259
|
-
const scored = [];
|
|
28260
|
-
for (const row of rows) {
|
|
28261
|
-
const score = cosine3(query, row.vector);
|
|
28262
|
-
if (score > 0)
|
|
28263
|
-
scored.push({ key: row.key, score });
|
|
28424
|
+
// src/datasource/skills/mailcrawl/config.ts
|
|
28425
|
+
import { chmodSync, mkdirSync as mkdirSync23 } from "node:fs";
|
|
28426
|
+
function validateMailcrawlInstanceId(instanceId) {
|
|
28427
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(instanceId)) {
|
|
28428
|
+
throw new Error("mailcrawl instanceId must be a safe single path segment");
|
|
28264
28429
|
}
|
|
28265
|
-
scored.sort((a, b) => b.score - a.score || a.key.localeCompare(b.key));
|
|
28266
|
-
return scored.slice(0, k);
|
|
28267
28430
|
}
|
|
28268
|
-
function
|
|
28269
|
-
|
|
28270
|
-
|
|
28271
|
-
|
|
28272
|
-
for (const [index, key] of list.entries()) {
|
|
28273
|
-
if (seen.has(key))
|
|
28274
|
-
continue;
|
|
28275
|
-
seen.add(key);
|
|
28276
|
-
scores.set(key, (scores.get(key) ?? 0) + 1 / (RRF_K2 + index + 1));
|
|
28277
|
-
}
|
|
28278
|
-
}
|
|
28279
|
-
return [...scores.entries()].map(([key, score]) => ({ key, score })).sort((a, b) => b.score - a.score);
|
|
28431
|
+
function ensurePrivateMailcrawlDataDir(path) {
|
|
28432
|
+
mkdirSync23(path, { recursive: true, mode: 448 });
|
|
28433
|
+
if (process.platform !== "win32")
|
|
28434
|
+
chmodSync(path, 448);
|
|
28280
28435
|
}
|
|
28281
|
-
var
|
|
28436
|
+
var init_config3 = () => {};
|
|
28282
28437
|
|
|
28283
|
-
// src/datasource/
|
|
28284
|
-
import {
|
|
28285
|
-
import { mkdirSync as mkdirSync23, statSync as statSync3 } from "node:fs";
|
|
28286
|
-
import { dirname as dirname25 } from "node:path";
|
|
28287
|
-
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
28288
|
-
import { pathToFileURL as pathToFileURL2 } from "node:url";
|
|
28438
|
+
// src/datasource/skills/mailcrawl/client.ts
|
|
28439
|
+
import { spawn as spawn15 } from "node:child_process";
|
|
28289
28440
|
|
|
28290
|
-
class
|
|
28291
|
-
descriptor;
|
|
28441
|
+
class MailcrawlClient {
|
|
28292
28442
|
options;
|
|
28293
|
-
|
|
28294
|
-
where;
|
|
28295
|
-
opened;
|
|
28296
|
-
attached;
|
|
28297
|
-
lastSemantic;
|
|
28298
|
-
constructor(options) {
|
|
28443
|
+
constructor(options = {}) {
|
|
28299
28444
|
this.options = options;
|
|
28300
|
-
|
|
28301
|
-
|
|
28302
|
-
const metadataColumns = descriptor.metadata.map((column, index) => `${column.sql} as m${index}`);
|
|
28303
|
-
this.select = [
|
|
28304
|
-
`${descriptor.keyExpression} as k`,
|
|
28305
|
-
`${descriptor.textExpression} as content`,
|
|
28306
|
-
`${descriptor.titleExpression ?? "null"} as title`,
|
|
28307
|
-
`${descriptor.epochSecondsExpression ?? "null"} as epoch`,
|
|
28308
|
-
...metadataColumns
|
|
28309
|
-
].join(", ");
|
|
28310
|
-
const scope = descriptor.scopeExpression !== undefined && options.workspaceId !== undefined;
|
|
28311
|
-
const allowlist = [
|
|
28312
|
-
...(options.channelIds?.length ?? 0) > 0 ? [`${descriptor.channelIdExpression} in (${options.channelIds?.map(() => "?").join(", ")})`] : [],
|
|
28313
|
-
...(options.channelNames?.length ?? 0) > 0 ? [`${descriptor.channelNameExpression} in (${options.channelNames?.map(() => "?").join(", ")})`] : []
|
|
28314
|
-
];
|
|
28315
|
-
this.where = [
|
|
28316
|
-
descriptor.liveWhere,
|
|
28317
|
-
...scope ? [`${descriptor.scopeExpression} = ?`] : [],
|
|
28318
|
-
...allowlist.length > 0 ? [`(${allowlist.join(" or ")})`] : []
|
|
28319
|
-
].join(" and ");
|
|
28320
|
-
}
|
|
28321
|
-
get db() {
|
|
28322
|
-
if (this.opened !== undefined)
|
|
28323
|
-
return this.opened;
|
|
28324
|
-
mkdirSync23(dirname25(this.options.sidecarDbPath), { recursive: true });
|
|
28325
|
-
const db = new DatabaseSync2(this.options.sidecarDbPath);
|
|
28326
|
-
db.exec(`pragma busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
28327
|
-
db.exec("pragma journal_mode = wal");
|
|
28328
|
-
db.exec(`
|
|
28329
|
-
create table if not exists sidecar_meta (k text primary key, v text not null);
|
|
28330
|
-
create table if not exists sidecar_vec (message_key text primary key, hash text not null, vec blob not null);
|
|
28331
|
-
`);
|
|
28332
|
-
this.opened = db;
|
|
28333
|
-
return db;
|
|
28334
|
-
}
|
|
28335
|
-
attachCrawler() {
|
|
28336
|
-
let file;
|
|
28337
|
-
try {
|
|
28338
|
-
const { dev, ino } = statSync3(this.options.crawlerDbPath);
|
|
28339
|
-
file = { dev, ino };
|
|
28340
|
-
} catch {
|
|
28341
|
-
this.detachCrawler();
|
|
28342
|
-
return false;
|
|
28343
|
-
}
|
|
28344
|
-
if (this.attached !== undefined) {
|
|
28345
|
-
if (this.attached.dev === file.dev && this.attached.ino === file.ino)
|
|
28346
|
-
return true;
|
|
28347
|
-
this.detachCrawler();
|
|
28348
|
-
}
|
|
28349
|
-
const crawlerUri = `${pathToFileURL2(this.options.crawlerDbPath).href}?mode=ro`.replaceAll("'", "''");
|
|
28350
|
-
try {
|
|
28351
|
-
this.db.exec(`attach database '${crawlerUri}' as crawler`);
|
|
28352
|
-
} catch {
|
|
28353
|
-
return false;
|
|
28354
|
-
}
|
|
28355
|
-
const { descriptor } = this.options;
|
|
28356
|
-
try {
|
|
28357
|
-
this.db.prepare(`select ${this.select} from ${descriptor.fromClause} where ${this.where} limit 0`).all(...this.whereParams());
|
|
28358
|
-
this.db.prepare(`select 1 from ${descriptor.fts.table} limit 0`).all();
|
|
28359
|
-
} catch {
|
|
28360
|
-
this.db.exec("detach database crawler");
|
|
28361
|
-
return false;
|
|
28362
|
-
}
|
|
28363
|
-
this.attached = file;
|
|
28364
|
-
this.lastSemantic = undefined;
|
|
28365
|
-
return true;
|
|
28366
|
-
}
|
|
28367
|
-
detachCrawler() {
|
|
28368
|
-
if (this.attached === undefined)
|
|
28369
|
-
return;
|
|
28370
|
-
this.attached = undefined;
|
|
28371
|
-
this.lastSemantic = undefined;
|
|
28372
|
-
try {
|
|
28373
|
-
this.opened?.exec("detach database crawler");
|
|
28374
|
-
} catch {}
|
|
28375
|
-
}
|
|
28376
|
-
get semanticEnabled() {
|
|
28377
|
-
return this.options.embedder !== undefined;
|
|
28378
|
-
}
|
|
28379
|
-
close() {
|
|
28380
|
-
this.opened?.close();
|
|
28381
|
-
this.opened = undefined;
|
|
28382
|
-
this.attached = undefined;
|
|
28383
|
-
this.lastSemantic = undefined;
|
|
28384
|
-
}
|
|
28385
|
-
whereParams() {
|
|
28386
|
-
const { descriptor, workspaceId, channelIds = [], channelNames = [] } = this.options;
|
|
28387
|
-
return [
|
|
28388
|
-
...descriptor.scopeExpression !== undefined && workspaceId !== undefined ? [workspaceId] : [],
|
|
28389
|
-
...channelIds,
|
|
28390
|
-
...channelNames
|
|
28391
|
-
];
|
|
28392
|
-
}
|
|
28393
|
-
searchLexical(query, topK) {
|
|
28394
|
-
const match = toMatchQuery(query);
|
|
28395
|
-
if (match === undefined || topK <= 0 || !this.attachCrawler())
|
|
28396
|
-
return [];
|
|
28397
|
-
const { descriptor } = this.options;
|
|
28398
|
-
const rows = this.db.prepare(`select ${this.select}, bm25(${descriptor.fts.table}) as rank
|
|
28399
|
-
from ${descriptor.fromClause} join ${descriptor.fts.table} on ${descriptor.fts.joinOn}
|
|
28400
|
-
where ${descriptor.fts.table} match ? and ${this.where}
|
|
28401
|
-
order by rank limit ?`).all(match, ...this.whereParams(), topK);
|
|
28402
|
-
return rows.map((row) => this.toHit(this.toRow(row), -Number(row.rank)));
|
|
28403
|
-
}
|
|
28404
|
-
async searchSemantic(query, topK) {
|
|
28405
|
-
const trimmed = query.trim();
|
|
28406
|
-
if (this.options.embedder === undefined || trimmed.length === 0 || topK <= 0 || !this.attachCrawler())
|
|
28407
|
-
return [];
|
|
28408
|
-
const ranked = await this.rankSemantic(trimmed, topK * POOL_FACTOR);
|
|
28409
|
-
if (ranked.length === 0)
|
|
28410
|
-
return [];
|
|
28411
|
-
const live = this.hydrate(ranked.map((entry) => entry.key));
|
|
28412
|
-
const hits = [];
|
|
28413
|
-
for (const entry of ranked) {
|
|
28414
|
-
const row = live.get(entry.key);
|
|
28415
|
-
if (row !== undefined)
|
|
28416
|
-
hits.push(this.toHit(row, entry.score));
|
|
28417
|
-
if (hits.length >= topK)
|
|
28418
|
-
break;
|
|
28419
|
-
}
|
|
28420
|
-
return hits;
|
|
28421
|
-
}
|
|
28422
|
-
async rankSemantic(query, pool) {
|
|
28423
|
-
const now = Date.now();
|
|
28424
|
-
let cached = this.lastSemantic;
|
|
28425
|
-
if (cached === undefined || cached.query !== query || now - cached.at > SEMANTIC_REUSE_MS) {
|
|
28426
|
-
const embedder = this.options.embedder;
|
|
28427
|
-
if (embedder === undefined)
|
|
28428
|
-
return [];
|
|
28429
|
-
cached = {
|
|
28430
|
-
query,
|
|
28431
|
-
at: now,
|
|
28432
|
-
vector: embedder.embed([query]).then((vectors) => vectors[0], () => {
|
|
28433
|
-
return;
|
|
28434
|
-
}),
|
|
28435
|
-
ranked: undefined
|
|
28436
|
-
};
|
|
28437
|
-
this.lastSemantic = cached;
|
|
28438
|
-
}
|
|
28439
|
-
const vector = await cached.vector;
|
|
28440
|
-
if (vector === undefined) {
|
|
28441
|
-
if (this.lastSemantic === cached)
|
|
28442
|
-
this.lastSemantic = undefined;
|
|
28443
|
-
return [];
|
|
28444
|
-
}
|
|
28445
|
-
if (cached.ranked === undefined || cached.ranked.pool < pool) {
|
|
28446
|
-
const wide = pool * POOL_FACTOR;
|
|
28447
|
-
cached.ranked = { pool: wide, keys: topKByCosine(vector, this.storedVectors(), wide) };
|
|
28448
|
-
}
|
|
28449
|
-
return cached.ranked.keys.slice(0, pool);
|
|
28445
|
+
if (options.instanceId !== undefined)
|
|
28446
|
+
validateMailcrawlInstanceId(options.instanceId);
|
|
28450
28447
|
}
|
|
28451
|
-
async
|
|
28452
|
-
|
|
28453
|
-
|
|
28454
|
-
|
|
28455
|
-
|
|
28456
|
-
|
|
28457
|
-
|
|
28458
|
-
|
|
28459
|
-
|
|
28460
|
-
|
|
28461
|
-
|
|
28462
|
-
const
|
|
28463
|
-
|
|
28464
|
-
|
|
28465
|
-
|
|
28466
|
-
|
|
28467
|
-
|
|
28468
|
-
break;
|
|
28448
|
+
async sync(signal) {
|
|
28449
|
+
const args = [
|
|
28450
|
+
"sync",
|
|
28451
|
+
"--json",
|
|
28452
|
+
...this.options.account === undefined ? [] : ["--account", this.options.account],
|
|
28453
|
+
...this.options.mailbox === undefined ? [] : ["--mailbox", this.options.mailbox],
|
|
28454
|
+
...this.options.backend === undefined ? [] : ["--backend", this.options.backend],
|
|
28455
|
+
...this.options.source === undefined ? [] : ["--source", this.options.source],
|
|
28456
|
+
...this.options.fixture === undefined ? [] : ["--fixture", this.options.fixture],
|
|
28457
|
+
...this.options.himalayaConfig === undefined ? [] : ["--himalaya-config", this.options.himalayaConfig]
|
|
28458
|
+
];
|
|
28459
|
+
const result = await this.run(args, signal, this.indexTimeoutMs());
|
|
28460
|
+
if (!result.ok)
|
|
28461
|
+
return failure3(result);
|
|
28462
|
+
const parsed = parseObject2(result.stdout);
|
|
28463
|
+
if (parsed === undefined || !hasAnyNumber(parsed, ["added", "updated", "deleted", "unchanged", "chunksAdded"])) {
|
|
28464
|
+
return failure3({ ...result, ok: false, reason: "invalid-output" });
|
|
28469
28465
|
}
|
|
28470
|
-
|
|
28466
|
+
const messages = number(parsed, "added") ?? number(parsed, "updated") ?? number(parsed, "unchanged") ?? 0;
|
|
28467
|
+
return ok4({
|
|
28468
|
+
messages,
|
|
28469
|
+
added: number(parsed, "added"),
|
|
28470
|
+
updated: number(parsed, "updated"),
|
|
28471
|
+
deleted: number(parsed, "deleted"),
|
|
28472
|
+
unchanged: number(parsed, "unchanged"),
|
|
28473
|
+
chunksAdded: number(parsed, "chunksAdded"),
|
|
28474
|
+
archiveRevision: string(parsed, "archiveRevision")
|
|
28475
|
+
}, result);
|
|
28471
28476
|
}
|
|
28472
|
-
async
|
|
28473
|
-
|
|
28474
|
-
|
|
28475
|
-
|
|
28476
|
-
|
|
28477
|
-
|
|
28478
|
-
|
|
28479
|
-
|
|
28480
|
-
|
|
28481
|
-
|
|
28482
|
-
|
|
28477
|
+
async search(mode, query, options) {
|
|
28478
|
+
if (query.trim().length === 0)
|
|
28479
|
+
return { ok: true, hits: [], stdout: "", stderr: "", code: 0 };
|
|
28480
|
+
const args = [
|
|
28481
|
+
"search",
|
|
28482
|
+
"--mode",
|
|
28483
|
+
mode === "keyword" ? "bm25" : mode,
|
|
28484
|
+
...this.options.account === undefined ? [] : ["--account", this.options.account],
|
|
28485
|
+
...this.options.mailbox === undefined ? [] : ["--mailbox", this.options.mailbox],
|
|
28486
|
+
"--limit",
|
|
28487
|
+
String(options?.topK ?? 20),
|
|
28488
|
+
"--json",
|
|
28489
|
+
query.trim()
|
|
28490
|
+
];
|
|
28491
|
+
const result = await this.run(args, options?.signal, this.options.timeoutMs ?? DEFAULT_SEARCH_TIMEOUT_MS2);
|
|
28492
|
+
if (!result.ok)
|
|
28493
|
+
return failure3(result);
|
|
28494
|
+
const parsed = parseJson3(result.stdout);
|
|
28495
|
+
if (parsed === undefined)
|
|
28496
|
+
return failure3({ ...result, ok: false, reason: "invalid-output" });
|
|
28497
|
+
const rows = Array.isArray(parsed) ? parsed : objectArray(parsed, ["hits", "results", "items"]);
|
|
28498
|
+
if (rows === undefined)
|
|
28499
|
+
return failure3({ ...result, ok: false, reason: "invalid-output" });
|
|
28500
|
+
const hits = rows.map((row, index) => normalizeHit2(row, mode, index));
|
|
28501
|
+
if (hits.some((hit) => hit === undefined)) {
|
|
28502
|
+
return failure3({ ...result, ok: false, reason: "invalid-output" });
|
|
28483
28503
|
}
|
|
28484
|
-
|
|
28485
|
-
|
|
28486
|
-
|
|
28487
|
-
|
|
28488
|
-
|
|
28489
|
-
|
|
28490
|
-
const embed = async (rows) => {
|
|
28491
|
-
const vectors = await embedder.embed(rows.map((row) => row.input));
|
|
28492
|
-
if (vectors.length !== rows.length) {
|
|
28493
|
-
throw new Error(`embedder returned ${vectors.length} vectors for ${rows.length} messages`);
|
|
28494
|
-
}
|
|
28495
|
-
const wrong = vectors.find((vector) => vector.length !== identity.dimension);
|
|
28496
|
-
if (wrong !== undefined) {
|
|
28497
|
-
throw new Error(`embedder returned a ${wrong.length}-dimension vector, expected ${identity.dimension}`);
|
|
28498
|
-
}
|
|
28499
|
-
return vectors;
|
|
28504
|
+
return {
|
|
28505
|
+
ok: true,
|
|
28506
|
+
hits,
|
|
28507
|
+
stdout: result.stdout,
|
|
28508
|
+
stderr: result.stderr,
|
|
28509
|
+
code: result.code ?? 0
|
|
28500
28510
|
};
|
|
28501
|
-
let embedded = 0;
|
|
28502
|
-
let skipped = 0;
|
|
28503
|
-
for (let offset = 0;offset < target; offset += batchSize) {
|
|
28504
|
-
const rows = [...this.hydrate(pending.slice(offset, Math.min(offset + batchSize, target))).values()];
|
|
28505
|
-
if (rows.length === 0)
|
|
28506
|
-
continue;
|
|
28507
|
-
try {
|
|
28508
|
-
this.store(rows, await embed(rows));
|
|
28509
|
-
embedded += rows.length;
|
|
28510
|
-
} catch (batchError) {
|
|
28511
|
-
const rejected = [];
|
|
28512
|
-
let lastError = batchError;
|
|
28513
|
-
for (const row of rows) {
|
|
28514
|
-
try {
|
|
28515
|
-
this.store([row], await embed([row]));
|
|
28516
|
-
embedded += 1;
|
|
28517
|
-
} catch (error) {
|
|
28518
|
-
rejected.push(row);
|
|
28519
|
-
lastError = error;
|
|
28520
|
-
}
|
|
28521
|
-
}
|
|
28522
|
-
if (rejected.length === 0)
|
|
28523
|
-
continue;
|
|
28524
|
-
if (embedded === 0)
|
|
28525
|
-
return { ok: false, message: errorMessage2(lastError) };
|
|
28526
|
-
this.store(rejected, undefined);
|
|
28527
|
-
skipped += rejected.length;
|
|
28528
|
-
}
|
|
28529
|
-
}
|
|
28530
|
-
return { ok: true, embedded, skipped, pruned, remaining: pending.length - embedded - skipped };
|
|
28531
|
-
}
|
|
28532
|
-
adoptIdentity(identity) {
|
|
28533
|
-
const serialized = JSON.stringify(identity);
|
|
28534
|
-
const current = this.db.prepare("select v from sidecar_meta where k = ?").get(IDENTITY_KEY);
|
|
28535
|
-
if (current?.v === serialized)
|
|
28536
|
-
return;
|
|
28537
|
-
this.transaction(() => {
|
|
28538
|
-
this.db.exec("delete from sidecar_vec");
|
|
28539
|
-
this.db.prepare("insert or replace into sidecar_meta (k, v) values (?, ?)").run(IDENTITY_KEY, serialized);
|
|
28540
|
-
});
|
|
28541
|
-
this.lastSemantic = undefined;
|
|
28542
28511
|
}
|
|
28543
|
-
|
|
28544
|
-
|
|
28545
|
-
const result = this.db.prepare(`delete from sidecar_vec where message_key not in (
|
|
28546
|
-
select ${descriptor.keyExpression} from ${descriptor.fromClause} where ${this.where}
|
|
28547
|
-
)`).run(...this.whereParams());
|
|
28548
|
-
if (Number(result.changes) > 0)
|
|
28549
|
-
this.lastSemantic = undefined;
|
|
28550
|
-
return Number(result.changes);
|
|
28512
|
+
indexTimeoutMs() {
|
|
28513
|
+
return this.options.indexTimeoutMs ?? this.options.timeoutMs ?? DEFAULT_INDEX_TIMEOUT_MS3;
|
|
28551
28514
|
}
|
|
28552
|
-
|
|
28553
|
-
const
|
|
28554
|
-
|
|
28555
|
-
|
|
28556
|
-
left join sidecar_vec v on v.message_key = ${descriptor.keyExpression}
|
|
28557
|
-
where ${this.where}`).iterate(...this.whereParams());
|
|
28558
|
-
const pending = [];
|
|
28559
|
-
for (const row of rows) {
|
|
28560
|
-
if (row.stored_hash !== this.toRow(row).hash)
|
|
28561
|
-
pending.push(String(row.k));
|
|
28515
|
+
async run(args, signal, timeoutMs) {
|
|
28516
|
+
const violation = findRemoteEmbeddingViolation({ ...process.env, ...this.options.env ?? {} });
|
|
28517
|
+
if (violation !== undefined) {
|
|
28518
|
+
return { ok: false, reason: "remote-embedding-rejected", stdout: "", stderr: "", code: null };
|
|
28562
28519
|
}
|
|
28563
|
-
|
|
28520
|
+
const dataDir = this.options.dataDir;
|
|
28521
|
+
if (dataDir !== undefined)
|
|
28522
|
+
ensurePrivateMailcrawlDataDir(dataDir);
|
|
28523
|
+
const env = {};
|
|
28524
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
28525
|
+
if (value !== undefined && (SAFE_ENV_KEYS2.has(key) || SAFE_MAILCRAWL_ENV_KEYS.has(key)))
|
|
28526
|
+
env[key] = value;
|
|
28527
|
+
}
|
|
28528
|
+
for (const [key, value] of Object.entries(this.options.env ?? {})) {
|
|
28529
|
+
if (value === undefined)
|
|
28530
|
+
delete env[key];
|
|
28531
|
+
else if (SAFE_ENV_KEYS2.has(key) || SAFE_MAILCRAWL_ENV_KEYS.has(key))
|
|
28532
|
+
env[key] = value;
|
|
28533
|
+
}
|
|
28534
|
+
if (dataDir !== undefined)
|
|
28535
|
+
env.MAILCRAWL_DATA_DIR = dataDir;
|
|
28536
|
+
return spawnMailcrawl(this.options.binaryPath ?? DEFAULT_BINARY4, args, env, this.options, signal, timeoutMs);
|
|
28564
28537
|
}
|
|
28565
|
-
|
|
28566
|
-
const
|
|
28567
|
-
|
|
28568
|
-
|
|
28569
|
-
|
|
28570
|
-
|
|
28571
|
-
|
|
28572
|
-
const byKey = new Map(rows.map((row) => [String(row.k), this.toRow(row)]));
|
|
28573
|
-
for (const key of keys) {
|
|
28574
|
-
const row = byKey.get(key);
|
|
28575
|
-
if (row !== undefined)
|
|
28576
|
-
out.set(key, row);
|
|
28538
|
+
async index(signal) {
|
|
28539
|
+
const result = await this.run(["index", "--json"], signal, this.indexTimeoutMs());
|
|
28540
|
+
if (!result.ok)
|
|
28541
|
+
return failure3(result);
|
|
28542
|
+
const parsed = parseObject2(result.stdout);
|
|
28543
|
+
if (parsed === undefined || number(parsed, "embedded") === undefined && number(parsed, "reused") === undefined && string(parsed, "generation") === undefined) {
|
|
28544
|
+
return failure3({ ...result, ok: false, reason: "invalid-output" });
|
|
28577
28545
|
}
|
|
28578
|
-
return
|
|
28546
|
+
return ok4({
|
|
28547
|
+
embedded: number(parsed, "embedded"),
|
|
28548
|
+
reused: number(parsed, "reused"),
|
|
28549
|
+
generation: string(parsed, "generation"),
|
|
28550
|
+
archiveRevision: string(parsed, "archiveRevision"),
|
|
28551
|
+
rebuilt: typeof parsed.rebuilt === "boolean" ? parsed.rebuilt : undefined,
|
|
28552
|
+
embedder: string(parsed, "embedder")
|
|
28553
|
+
}, result);
|
|
28579
28554
|
}
|
|
28580
|
-
|
|
28581
|
-
|
|
28582
|
-
|
|
28583
|
-
|
|
28584
|
-
|
|
28555
|
+
}
|
|
28556
|
+
function spawnMailcrawl(binary, args, env, options, signal, timeoutMs) {
|
|
28557
|
+
return new Promise((resolveResult) => {
|
|
28558
|
+
const portable = portableSpawnCommand(binary, args);
|
|
28559
|
+
const child = spawn15(portable.command, portable.args, {
|
|
28560
|
+
env,
|
|
28561
|
+
detached: process.platform !== "win32",
|
|
28562
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
28563
|
+
});
|
|
28564
|
+
let stdout = { text: "", bytes: 0, exceeded: false }, stderr = { text: "", bytes: 0, exceeded: false }, settled = false, reason;
|
|
28565
|
+
const max = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES4;
|
|
28566
|
+
const timer = setTimeout(() => {
|
|
28567
|
+
reason = "timeout";
|
|
28568
|
+
terminate4(child);
|
|
28569
|
+
}, timeoutMs);
|
|
28570
|
+
const abort = () => {
|
|
28571
|
+
reason = "aborted";
|
|
28572
|
+
terminate4(child);
|
|
28573
|
+
};
|
|
28574
|
+
if (signal?.aborted)
|
|
28575
|
+
abort();
|
|
28576
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
28577
|
+
child.stdout.setEncoding("utf8");
|
|
28578
|
+
child.stderr.setEncoding("utf8");
|
|
28579
|
+
child.stdout.on("data", (chunk) => {
|
|
28580
|
+
stdout = appendOutput(stdout, chunk, max);
|
|
28581
|
+
if (stdout.exceeded && reason === undefined) {
|
|
28582
|
+
reason = "stdout-too-large";
|
|
28583
|
+
terminate4(child);
|
|
28584
|
+
}
|
|
28585
|
+
});
|
|
28586
|
+
child.stderr.on("data", (chunk) => {
|
|
28587
|
+
stderr = appendOutput(stderr, chunk, max);
|
|
28588
|
+
if (stderr.exceeded && reason === undefined) {
|
|
28589
|
+
reason = "stderr-too-large";
|
|
28590
|
+
terminate4(child);
|
|
28585
28591
|
}
|
|
28586
28592
|
});
|
|
28587
|
-
|
|
28593
|
+
child.on("error", (error) => {
|
|
28594
|
+
if (settled)
|
|
28595
|
+
return;
|
|
28596
|
+
settled = true;
|
|
28597
|
+
clearTimeout(timer);
|
|
28598
|
+
signal?.removeEventListener("abort", abort);
|
|
28599
|
+
resolveResult({
|
|
28600
|
+
ok: false,
|
|
28601
|
+
reason: error.code === "ENOENT" ? "binary-missing" : "spawn-error",
|
|
28602
|
+
stdout: stdout.text,
|
|
28603
|
+
stderr: "",
|
|
28604
|
+
code: null
|
|
28605
|
+
});
|
|
28606
|
+
});
|
|
28607
|
+
child.on("close", (code) => {
|
|
28608
|
+
if (settled)
|
|
28609
|
+
return;
|
|
28610
|
+
settled = true;
|
|
28611
|
+
clearTimeout(timer);
|
|
28612
|
+
signal?.removeEventListener("abort", abort);
|
|
28613
|
+
resolveResult({
|
|
28614
|
+
ok: code === 0 && reason === undefined,
|
|
28615
|
+
...reason === undefined ? code === 0 ? {} : { reason: "nonzero-exit" } : { reason },
|
|
28616
|
+
stdout: stdout.text,
|
|
28617
|
+
stderr: stderr.text,
|
|
28618
|
+
code
|
|
28619
|
+
});
|
|
28620
|
+
});
|
|
28621
|
+
});
|
|
28622
|
+
}
|
|
28623
|
+
function terminate4(child) {
|
|
28624
|
+
if (child.killed)
|
|
28625
|
+
return;
|
|
28626
|
+
if (process.platform !== "win32" && child.pid !== undefined) {
|
|
28627
|
+
try {
|
|
28628
|
+
process.kill(-child.pid, "SIGTERM");
|
|
28629
|
+
return;
|
|
28630
|
+
} catch {}
|
|
28588
28631
|
}
|
|
28589
|
-
|
|
28590
|
-
|
|
28591
|
-
|
|
28592
|
-
|
|
28593
|
-
|
|
28594
|
-
|
|
28632
|
+
child.kill("SIGTERM");
|
|
28633
|
+
}
|
|
28634
|
+
function parseJson3(text) {
|
|
28635
|
+
try {
|
|
28636
|
+
return JSON.parse(text.trim());
|
|
28637
|
+
} catch {
|
|
28638
|
+
return;
|
|
28639
|
+
}
|
|
28640
|
+
}
|
|
28641
|
+
function parseObject2(text) {
|
|
28642
|
+
const value = parseJson3(text);
|
|
28643
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
|
|
28644
|
+
}
|
|
28645
|
+
function objectArray(value, keys) {
|
|
28646
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
28647
|
+
return;
|
|
28648
|
+
for (const key of keys)
|
|
28649
|
+
if (Array.isArray(value[key]))
|
|
28650
|
+
return value[key];
|
|
28651
|
+
return;
|
|
28652
|
+
}
|
|
28653
|
+
function hasAnyNumber(value, keys) {
|
|
28654
|
+
return keys.some((key) => number(value, key) !== undefined);
|
|
28655
|
+
}
|
|
28656
|
+
function normalizeHit2(value, mode, index) {
|
|
28657
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
28658
|
+
return;
|
|
28659
|
+
const row = value;
|
|
28660
|
+
const text = (key) => typeof row[key] === "string" ? row[key] : "";
|
|
28661
|
+
const chunkId = text("chunkId") || text("chunk_id");
|
|
28662
|
+
const messageId = text("messageId") || text("message_id");
|
|
28663
|
+
const accountId = text("accountId") || text("account_id");
|
|
28664
|
+
const mailbox = text("mailbox");
|
|
28665
|
+
const snippet = text("snippet") || text("content") || text("text");
|
|
28666
|
+
if (!isSafeOpaqueId(chunkId) || !isSafeOpaqueId(messageId) || !snippet)
|
|
28667
|
+
return;
|
|
28668
|
+
const to = Array.isArray(row.to) ? row.to.filter((item) => typeof item === "string") : [];
|
|
28669
|
+
return {
|
|
28670
|
+
chunkId,
|
|
28671
|
+
messageId,
|
|
28672
|
+
threadId: text("threadId") || text("thread_id"),
|
|
28673
|
+
accountId,
|
|
28674
|
+
mailbox,
|
|
28675
|
+
subject: text("subject"),
|
|
28676
|
+
from: text("from"),
|
|
28677
|
+
to,
|
|
28678
|
+
date: text("date"),
|
|
28679
|
+
snippet,
|
|
28680
|
+
score: typeof row.score === "number" ? row.score : 1 / (index + 1),
|
|
28681
|
+
mode
|
|
28682
|
+
};
|
|
28683
|
+
}
|
|
28684
|
+
function number(value, key) {
|
|
28685
|
+
return typeof value[key] === "number" && Number.isFinite(value[key]) ? value[key] : undefined;
|
|
28686
|
+
}
|
|
28687
|
+
function string(value, key) {
|
|
28688
|
+
return typeof value[key] === "string" ? value[key] : undefined;
|
|
28689
|
+
}
|
|
28690
|
+
function ok4(data, result) {
|
|
28691
|
+
return { ok: true, data, stdout: result.stdout, stderr: result.stderr, code: result.code ?? 0 };
|
|
28692
|
+
}
|
|
28693
|
+
function failure3(result) {
|
|
28694
|
+
return {
|
|
28695
|
+
ok: false,
|
|
28696
|
+
reason: result.reason ?? "nonzero-exit",
|
|
28697
|
+
stdout: result.stdout,
|
|
28698
|
+
stderr: boundDiagnosticText6(result.stderr),
|
|
28699
|
+
code: result.code
|
|
28700
|
+
};
|
|
28701
|
+
}
|
|
28702
|
+
function boundDiagnosticText6(value) {
|
|
28703
|
+
if (value.length === 0)
|
|
28704
|
+
return "";
|
|
28705
|
+
return value.trim().slice(0, 4000);
|
|
28706
|
+
}
|
|
28707
|
+
function appendOutput(current, chunk, maxBytes) {
|
|
28708
|
+
if (current.exceeded)
|
|
28709
|
+
return current;
|
|
28710
|
+
const bytes = Buffer.from(chunk, "utf8");
|
|
28711
|
+
const remaining = Math.max(0, maxBytes - current.bytes);
|
|
28712
|
+
const prefix = truncateUtf8(chunk, remaining);
|
|
28713
|
+
const total = current.bytes + bytes.byteLength;
|
|
28714
|
+
return {
|
|
28715
|
+
text: current.text + prefix,
|
|
28716
|
+
bytes: Math.min(total, maxBytes),
|
|
28717
|
+
exceeded: total > maxBytes
|
|
28718
|
+
};
|
|
28719
|
+
}
|
|
28720
|
+
function isSafeOpaqueId(value) {
|
|
28721
|
+
return value.length > 0 && value !== "." && value !== ".." && !/[\\/#\u0000-\u001f\u007f]/u.test(value);
|
|
28722
|
+
}
|
|
28723
|
+
function findRemoteEmbeddingViolation(env) {
|
|
28724
|
+
for (const [key, value] of Object.entries(env)) {
|
|
28725
|
+
if (value === undefined)
|
|
28726
|
+
continue;
|
|
28727
|
+
const lower = key.toLowerCase();
|
|
28728
|
+
if (REMOTE_EMBEDDING_ENV_KEYS.has(lower))
|
|
28729
|
+
return key;
|
|
28730
|
+
if (lower === "mailcrawl_embedder" || lower === "mailcrawl_embed_url") {
|
|
28731
|
+
if (isRemoteHttpEndpoint(value))
|
|
28732
|
+
return key;
|
|
28595
28733
|
}
|
|
28596
28734
|
}
|
|
28597
|
-
|
|
28598
|
-
|
|
28735
|
+
return;
|
|
28736
|
+
}
|
|
28737
|
+
function isRemoteHttpEndpoint(value) {
|
|
28738
|
+
const trimmed = value.trim();
|
|
28739
|
+
if (!/^https?:\/\//iu.test(trimmed))
|
|
28740
|
+
return false;
|
|
28741
|
+
try {
|
|
28742
|
+
return !LOOPBACK_HOSTS2.has(new URL(trimmed).hostname);
|
|
28743
|
+
} catch {
|
|
28744
|
+
return true;
|
|
28745
|
+
}
|
|
28746
|
+
}
|
|
28747
|
+
function truncateUtf8(value, maxBytes) {
|
|
28748
|
+
if (Buffer.byteLength(value) <= maxBytes)
|
|
28749
|
+
return value;
|
|
28750
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
28751
|
+
const bytes = Buffer.from(value, "utf8");
|
|
28752
|
+
for (let end = Math.min(maxBytes, bytes.length);end >= 0; end -= 1) {
|
|
28599
28753
|
try {
|
|
28600
|
-
|
|
28601
|
-
|
|
28602
|
-
} catch (error) {
|
|
28603
|
-
this.db.exec("rollback");
|
|
28604
|
-
throw error;
|
|
28605
|
-
}
|
|
28754
|
+
return decoder.decode(bytes.subarray(0, end));
|
|
28755
|
+
} catch {}
|
|
28606
28756
|
}
|
|
28607
|
-
|
|
28608
|
-
|
|
28609
|
-
|
|
28610
|
-
|
|
28611
|
-
|
|
28612
|
-
|
|
28613
|
-
|
|
28614
|
-
|
|
28615
|
-
|
|
28616
|
-
|
|
28617
|
-
|
|
28618
|
-
|
|
28619
|
-
|
|
28620
|
-
|
|
28621
|
-
|
|
28622
|
-
|
|
28623
|
-
|
|
28624
|
-
|
|
28625
|
-
|
|
28626
|
-
|
|
28627
|
-
|
|
28757
|
+
return "";
|
|
28758
|
+
}
|
|
28759
|
+
var DEFAULT_BINARY4 = "mailcrawl", DEFAULT_SEARCH_TIMEOUT_MS2 = 60000, DEFAULT_INDEX_TIMEOUT_MS3 = 1800000, DEFAULT_MAX_BUFFER_BYTES4 = 1048576, LOOPBACK_HOSTS2, SAFE_ENV_KEYS2, SAFE_MAILCRAWL_ENV_KEYS, REMOTE_EMBEDDING_ENV_KEYS;
|
|
28760
|
+
var init_client9 = __esm(() => {
|
|
28761
|
+
init_portable_spawn();
|
|
28762
|
+
init_config3();
|
|
28763
|
+
LOOPBACK_HOSTS2 = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
|
|
28764
|
+
SAFE_ENV_KEYS2 = new Set(["HOME", "LANG", "LC_ALL", "PATH", "TMPDIR", "TMP", "TEMP", "NO_COLOR"]);
|
|
28765
|
+
SAFE_MAILCRAWL_ENV_KEYS = new Set([
|
|
28766
|
+
"MAILCRAWL_DATA_DIR",
|
|
28767
|
+
"MAILCRAWL_EMBEDDER",
|
|
28768
|
+
"MAILCRAWL_EMBEDDER_PROVIDER",
|
|
28769
|
+
"MAILCRAWL_EMBED_URL",
|
|
28770
|
+
"MAILCRAWL_EMBED_MODEL",
|
|
28771
|
+
"MAILCRAWL_EMBED_DIM",
|
|
28772
|
+
"MAILCRAWL_EMBED_TIMEOUT",
|
|
28773
|
+
"MAILCRAWL_EMBED_BATCH_SIZE",
|
|
28774
|
+
"MAILCRAWL_QUERY_PREFIX",
|
|
28775
|
+
"MAILCRAWL_PASSAGE_PREFIX",
|
|
28776
|
+
"MAILCRAWL_NATIVE_MODEL",
|
|
28777
|
+
"MAILCRAWL_NATIVE_DEVICE",
|
|
28778
|
+
"MAILCRAWL_NATIVE_DTYPE",
|
|
28779
|
+
"MAILCRAWL_KIWI_MODEL",
|
|
28780
|
+
"MAILCRAWL_JA_HELPER",
|
|
28781
|
+
"MAILCRAWL_ZH_HELPER"
|
|
28782
|
+
]);
|
|
28783
|
+
REMOTE_EMBEDDING_ENV_KEYS = new Set([
|
|
28784
|
+
"mailcrawl_embedder_base_url",
|
|
28785
|
+
"mailcrawl_embedding_base_url",
|
|
28786
|
+
"mailcrawl_allow_remote_embeddings"
|
|
28787
|
+
]);
|
|
28788
|
+
});
|
|
28789
|
+
|
|
28790
|
+
// src/datasource/skills/mailcrawl/methods.ts
|
|
28791
|
+
class MailcrawlMethod {
|
|
28792
|
+
client;
|
|
28793
|
+
mode;
|
|
28794
|
+
instanceId;
|
|
28795
|
+
tags;
|
|
28796
|
+
account;
|
|
28797
|
+
mailbox;
|
|
28798
|
+
constructor(client, mode, instanceId, tags, account, mailbox) {
|
|
28799
|
+
this.client = client;
|
|
28800
|
+
this.mode = mode;
|
|
28801
|
+
this.instanceId = instanceId;
|
|
28802
|
+
this.tags = tags;
|
|
28803
|
+
this.account = account;
|
|
28804
|
+
this.mailbox = mailbox;
|
|
28628
28805
|
}
|
|
28629
|
-
|
|
28806
|
+
describe() {
|
|
28630
28807
|
return {
|
|
28631
|
-
|
|
28632
|
-
|
|
28633
|
-
|
|
28634
|
-
|
|
28635
|
-
|
|
28636
|
-
|
|
28808
|
+
name: `mailcrawl-${this.mode}`,
|
|
28809
|
+
type: this.mode === "bm25" ? "bm25" : this.mode === "semantic" ? "vector" : "hybrid",
|
|
28810
|
+
description: `${this.mode} retrieval over archived email via the external mailcrawl CLI`,
|
|
28811
|
+
status: "active",
|
|
28812
|
+
capabilities: ["email", this.mode, "scoped", "external-cli", "path-opaque-sources"],
|
|
28813
|
+
datasourceId: "mailcrawl",
|
|
28814
|
+
tags: this.tags
|
|
28637
28815
|
};
|
|
28638
28816
|
}
|
|
28817
|
+
async retrieve(query, options) {
|
|
28818
|
+
if (!query.trim())
|
|
28819
|
+
return [];
|
|
28820
|
+
const result = await this.client.search(this.mode, query, {
|
|
28821
|
+
topK: options.topK,
|
|
28822
|
+
signal: options.signal
|
|
28823
|
+
});
|
|
28824
|
+
if (!result.ok)
|
|
28825
|
+
throw datasourceCliError("mailcrawl", `search --mode ${this.mode}`, result);
|
|
28826
|
+
return result.hits.filter((hit) => {
|
|
28827
|
+
if (this.account !== undefined && hit.accountId !== this.account)
|
|
28828
|
+
return false;
|
|
28829
|
+
if (this.mailbox !== undefined && hit.mailbox !== this.mailbox)
|
|
28830
|
+
return false;
|
|
28831
|
+
const source = datasourceSourcePath("mailcrawl", this.instanceId, hit.chunkId);
|
|
28832
|
+
return matchesDatasourceScope(source, options.scope);
|
|
28833
|
+
}).map((hit) => {
|
|
28834
|
+
const source = datasourceSourcePath("mailcrawl", this.instanceId, hit.chunkId);
|
|
28835
|
+
return {
|
|
28836
|
+
id: `mailcrawl:${this.instanceId}:${hit.chunkId}`,
|
|
28837
|
+
content: hit.snippet,
|
|
28838
|
+
source,
|
|
28839
|
+
score: hit.score,
|
|
28840
|
+
metadata: {
|
|
28841
|
+
method: `mailcrawl-${this.mode}`,
|
|
28842
|
+
datasourceId: "mailcrawl",
|
|
28843
|
+
instanceId: this.instanceId,
|
|
28844
|
+
mode: this.mode,
|
|
28845
|
+
chunkId: hit.chunkId,
|
|
28846
|
+
messageId: hit.messageId,
|
|
28847
|
+
threadId: hit.threadId,
|
|
28848
|
+
accountId: hit.accountId,
|
|
28849
|
+
mailbox: hit.mailbox,
|
|
28850
|
+
subject: hit.subject,
|
|
28851
|
+
from: hit.from,
|
|
28852
|
+
to: hit.to,
|
|
28853
|
+
date: hit.date
|
|
28854
|
+
}
|
|
28855
|
+
};
|
|
28856
|
+
}).slice(0, options.topK ?? 20);
|
|
28857
|
+
}
|
|
28639
28858
|
}
|
|
28640
|
-
|
|
28641
|
-
|
|
28642
|
-
|
|
28643
|
-
|
|
28644
|
-
|
|
28645
|
-
|
|
28646
|
-
}
|
|
28647
|
-
var DEFAULT_BATCH_SIZE = 256, DEFAULT_MAX_EMBED_PER_SYNC = 2048, MAX_EMBED_INPUT_CHARS = 8192, BUSY_TIMEOUT_MS = 5000, POOL_FACTOR = 3, SEMANTIC_REUSE_MS = 1e4, IDENTITY_KEY = "identity";
|
|
28648
|
-
var init_sidecar = () => {};
|
|
28649
|
-
|
|
28650
|
-
// src/datasource/sidecar/methods.ts
|
|
28651
|
-
function sidecarMethodName(datasourceId, mode) {
|
|
28652
|
-
return mode === "bm25" ? `${datasourceId}-sidecar-bm25` : `${datasourceId}-${mode}`;
|
|
28653
|
-
}
|
|
28859
|
+
var modes, MAILCRAWL_MODES;
|
|
28860
|
+
var init_methods5 = __esm(() => {
|
|
28861
|
+
init_errors4();
|
|
28862
|
+
init_scope2();
|
|
28863
|
+
modes = ["bm25", "semantic", "hybrid"];
|
|
28864
|
+
MAILCRAWL_MODES = modes;
|
|
28865
|
+
});
|
|
28654
28866
|
|
|
28655
|
-
|
|
28656
|
-
|
|
28657
|
-
|
|
28658
|
-
|
|
28867
|
+
// src/datasource/skills/mailcrawl/skill.ts
|
|
28868
|
+
class MailcrawlSkill {
|
|
28869
|
+
client;
|
|
28870
|
+
instanceId;
|
|
28871
|
+
instances;
|
|
28872
|
+
interval;
|
|
28873
|
+
tags;
|
|
28874
|
+
account;
|
|
28875
|
+
mailbox;
|
|
28876
|
+
lastIndexedAt;
|
|
28877
|
+
constructor(options = {}) {
|
|
28878
|
+
const connectorOptions = options.connectorOptions ?? options;
|
|
28879
|
+
this.instanceId = options.instanceId ?? "default";
|
|
28880
|
+
this.instances = options.instances?.length ? options.instances : [this.instanceId];
|
|
28881
|
+
validateMailcrawlInstanceId(this.instanceId);
|
|
28882
|
+
for (const instance of this.instances)
|
|
28883
|
+
validateMailcrawlInstanceId(instance);
|
|
28884
|
+
this.interval = options.pollingIntervalMs ?? 15 * 60 * 1000;
|
|
28885
|
+
this.tags = options.tags ?? TAGS;
|
|
28886
|
+
this.account = connectorOptions.account;
|
|
28887
|
+
this.mailbox = connectorOptions.mailbox;
|
|
28888
|
+
this.client = options.client ?? new MailcrawlClient({ ...connectorOptions, instanceId: this.instanceId });
|
|
28659
28889
|
}
|
|
28660
28890
|
describe() {
|
|
28661
|
-
const { datasourceId, skillType, mode, tags } = this.options;
|
|
28662
|
-
const { type, text, capabilities } = DESCRIPTIONS[mode];
|
|
28663
28891
|
return {
|
|
28664
|
-
name:
|
|
28665
|
-
|
|
28666
|
-
|
|
28892
|
+
name: "mailcrawl",
|
|
28893
|
+
id: "mailcrawl",
|
|
28894
|
+
type: "mailcrawl-archive",
|
|
28895
|
+
description: "Local email archive datasource via the external mailcrawl CLI",
|
|
28896
|
+
capabilities: ["email", "external-cli", "polling", "incremental", "bm25", "semantic", "hybrid"],
|
|
28897
|
+
tags: this.tags,
|
|
28667
28898
|
status: "active",
|
|
28668
|
-
|
|
28669
|
-
datasourceId,
|
|
28670
|
-
|
|
28899
|
+
requiresExternalCli: true,
|
|
28900
|
+
datasourceId: "mailcrawl",
|
|
28901
|
+
instanceId: this.instanceId,
|
|
28902
|
+
instances: this.instances
|
|
28671
28903
|
};
|
|
28672
28904
|
}
|
|
28673
|
-
|
|
28674
|
-
|
|
28675
|
-
|
|
28676
|
-
|
|
28677
|
-
|
|
28678
|
-
|
|
28679
|
-
|
|
28680
|
-
|
|
28681
|
-
|
|
28682
|
-
const result = this.
|
|
28683
|
-
if (result
|
|
28684
|
-
|
|
28905
|
+
polling() {
|
|
28906
|
+
return {
|
|
28907
|
+
mode: this.interval > 0 ? "poll" : "none",
|
|
28908
|
+
...this.interval > 0 ? { intervalMs: this.interval } : {},
|
|
28909
|
+
lastIndexedAt: this.lastIndexedAt
|
|
28910
|
+
};
|
|
28911
|
+
}
|
|
28912
|
+
async index(options) {
|
|
28913
|
+
try {
|
|
28914
|
+
const result = await this.client.sync(options?.signal);
|
|
28915
|
+
if (!result.ok) {
|
|
28916
|
+
return this.fail(result.reason === "binary-missing" || result.reason === "spawn-error" || result.reason === "timeout" ? "datasource-unavailable" : result.reason === "remote-embedding-rejected" ? "datasource-embedding-egress-rejected" : "datasource-index-failed", result.reason);
|
|
28917
|
+
}
|
|
28918
|
+
const indexed = await this.client.index(options?.signal);
|
|
28919
|
+
const diagnostics = [];
|
|
28920
|
+
if (!indexed.ok) {
|
|
28921
|
+
diagnostics.push({
|
|
28922
|
+
code: indexed.reason === "remote-embedding-rejected" ? "datasource-embedding-egress-rejected" : "datasource-index-failed",
|
|
28923
|
+
severity: "warning",
|
|
28924
|
+
message: `mailcrawl semantic index unavailable (${indexed.reason}); BM25 remains available`,
|
|
28925
|
+
instanceId: this.instanceId,
|
|
28926
|
+
source: "mailcrawl"
|
|
28927
|
+
});
|
|
28928
|
+
}
|
|
28929
|
+
this.lastIndexedAt = Date.now();
|
|
28930
|
+
return {
|
|
28931
|
+
ok: true,
|
|
28932
|
+
instanceId: this.instanceId,
|
|
28933
|
+
skill: "mailcrawl",
|
|
28934
|
+
chunkCount: result.data.chunksAdded ?? result.data.messages,
|
|
28935
|
+
indexedAt: this.lastIndexedAt,
|
|
28936
|
+
diagnostics
|
|
28937
|
+
};
|
|
28938
|
+
} catch {
|
|
28939
|
+
return this.fail("datasource-unavailable", "mailcrawl sync failed unexpectedly");
|
|
28685
28940
|
}
|
|
28686
|
-
return results;
|
|
28687
28941
|
}
|
|
28688
|
-
|
|
28689
|
-
|
|
28690
|
-
|
|
28691
|
-
|
|
28692
|
-
|
|
28693
|
-
|
|
28694
|
-
|
|
28942
|
+
retrievalMethods() {
|
|
28943
|
+
return [
|
|
28944
|
+
new MailcrawlMethod(this.client, "bm25", this.instanceId, this.tags, this.account, this.mailbox),
|
|
28945
|
+
new MailcrawlMethod(this.client, "semantic", this.instanceId, this.tags, this.account, this.mailbox),
|
|
28946
|
+
new MailcrawlMethod(this.client, "hybrid", this.instanceId, this.tags, this.account, this.mailbox)
|
|
28947
|
+
];
|
|
28948
|
+
}
|
|
28949
|
+
describeSources() {
|
|
28950
|
+
return this.instances.map((instanceId) => ({
|
|
28951
|
+
source: datasourceSourcePath("mailcrawl", instanceId),
|
|
28952
|
+
datasourceId: "mailcrawl",
|
|
28953
|
+
skill: "mailcrawl",
|
|
28954
|
+
instanceId,
|
|
28955
|
+
contentType: "email",
|
|
28956
|
+
metadata: { datasourceId: "mailcrawl", instanceId, tags: this.tags }
|
|
28957
|
+
}));
|
|
28958
|
+
}
|
|
28959
|
+
skillManifest() {
|
|
28960
|
+
const scopes = this.instances.map((id) => `- \`${datasourceSourcePath("mailcrawl", id)}\``).join(`
|
|
28961
|
+
`);
|
|
28695
28962
|
return {
|
|
28696
|
-
|
|
28697
|
-
|
|
28698
|
-
|
|
28699
|
-
|
|
28700
|
-
|
|
28701
|
-
|
|
28702
|
-
|
|
28703
|
-
|
|
28704
|
-
|
|
28705
|
-
|
|
28706
|
-
|
|
28707
|
-
|
|
28708
|
-
|
|
28709
|
-
|
|
28963
|
+
name: "datasource-mailcrawl",
|
|
28964
|
+
description: "Search local email synchronized and indexed by mailcrawl.",
|
|
28965
|
+
content: `# mailcrawl email datasource
|
|
28966
|
+
|
|
28967
|
+
Use this skill for authorized local email retrieval. AutoRAG invokes the external \`mailcrawl\` CLI and never opens its SQLite archive directly.
|
|
28968
|
+
|
|
28969
|
+
## Indexing
|
|
28970
|
+
Indexing is server-managed and incremental; do not trigger sync yourself.
|
|
28971
|
+
|
|
28972
|
+
## Search
|
|
28973
|
+
Call the dedicated \`${datasourceSearchToolName("mailcrawl")}\` tool with a natural-language query. Available scopes:
|
|
28974
|
+
${scopes}
|
|
28975
|
+
|
|
28976
|
+
The selectable retrieval modes are BM25, semantic, and hybrid. Scope arguments can only narrow trusted access. Source identifiers remain opaque and hierarchical.
|
|
28977
|
+
|
|
28978
|
+
## Native CLI
|
|
28979
|
+
The external \`mailcrawl\` CLI owns the archive and index. When the dedicated tool cannot express what you need, call mailcrawl directly through \`bash\`:
|
|
28980
|
+
- \`mailcrawl search --mode hybrid --limit 20 --json "<query>"\` (\`bm25\` and \`semantic\` modes also available; \`--account\` / \`--mailbox\` narrow the archive)
|
|
28981
|
+
Never pass datasource virtual paths (\`/mailcrawl/...\`) to bash; they are not OS paths.`
|
|
28982
|
+
};
|
|
28983
|
+
}
|
|
28984
|
+
fail(code, message) {
|
|
28985
|
+
return {
|
|
28986
|
+
ok: false,
|
|
28987
|
+
instanceId: this.instanceId,
|
|
28988
|
+
skill: "mailcrawl",
|
|
28989
|
+
indexedAt: Date.now(),
|
|
28990
|
+
diagnostics: [
|
|
28991
|
+
{
|
|
28992
|
+
code,
|
|
28993
|
+
severity: code === "datasource-unavailable" ? "warning" : "error",
|
|
28994
|
+
message: `mailcrawl ${message}`,
|
|
28995
|
+
instanceId: this.instanceId,
|
|
28996
|
+
source: "mailcrawl"
|
|
28997
|
+
}
|
|
28998
|
+
],
|
|
28999
|
+
error: message,
|
|
29000
|
+
code,
|
|
29001
|
+
message
|
|
28710
29002
|
};
|
|
28711
29003
|
}
|
|
28712
29004
|
}
|
|
28713
|
-
var
|
|
28714
|
-
var
|
|
29005
|
+
var TAGS;
|
|
29006
|
+
var init_skill9 = __esm(() => {
|
|
28715
29007
|
init_scope2();
|
|
28716
|
-
|
|
28717
|
-
|
|
28718
|
-
|
|
28719
|
-
|
|
28720
|
-
|
|
28721
|
-
|
|
28722
|
-
|
|
28723
|
-
|
|
28724
|
-
|
|
29008
|
+
init_client9();
|
|
29009
|
+
init_config3();
|
|
29010
|
+
init_methods5();
|
|
29011
|
+
TAGS = ["mailcrawl", "email", "pii"];
|
|
29012
|
+
});
|
|
29013
|
+
|
|
29014
|
+
// src/datasource/skills/mailcrawl/index.ts
|
|
29015
|
+
var init_mailcrawl = __esm(() => {
|
|
29016
|
+
init_client9();
|
|
29017
|
+
init_methods5();
|
|
29018
|
+
init_skill9();
|
|
28725
29019
|
});
|
|
28726
29020
|
|
|
28727
29021
|
// src/datasource/crawler-skill.ts
|
|
@@ -29004,7 +29298,7 @@ var init_crawler_skill = __esm(() => {
|
|
|
29004
29298
|
init_errors4();
|
|
29005
29299
|
init_scope2();
|
|
29006
29300
|
init_sidecar();
|
|
29007
|
-
|
|
29301
|
+
init_methods4();
|
|
29008
29302
|
DEFAULT_POLLING_INTERVAL_MS4 = 15 * 60 * 1000;
|
|
29009
29303
|
});
|
|
29010
29304
|
|
|
@@ -30793,14 +31087,27 @@ var init_factory = __esm(() => {
|
|
|
30793
31087
|
...config.channels?.ids !== undefined ? { chatIds: config.channels.ids } : {},
|
|
30794
31088
|
...larkConnectorOptions(config.connector)
|
|
30795
31089
|
}),
|
|
30796
|
-
kakao: (config,
|
|
30797
|
-
|
|
30798
|
-
|
|
30799
|
-
|
|
30800
|
-
|
|
30801
|
-
|
|
30802
|
-
|
|
30803
|
-
|
|
31090
|
+
kakao: (config, workspaceRoot, registrationName) => {
|
|
31091
|
+
const connector = config.connector ?? {};
|
|
31092
|
+
const dataDir = typeof connector.workspacePath === "string" && connector.workspacePath.length > 0 ? connector.workspacePath : join39(homedir4(), "Library", "Application Support", "katok");
|
|
31093
|
+
const sidecar = resolveSidecarOptions({
|
|
31094
|
+
descriptor: CRAWLER_DESCRIPTORS.kakao,
|
|
31095
|
+
connector: config.connector,
|
|
31096
|
+
workspaceRoot,
|
|
31097
|
+
registrationName,
|
|
31098
|
+
instanceId: config.instanceId ?? "default",
|
|
31099
|
+
defaultCrawlerDb: join39(dataDir, "archive.sqlite3")
|
|
31100
|
+
});
|
|
31101
|
+
return new LazykatokSkill({
|
|
31102
|
+
client: new LazykatokClient(connector),
|
|
31103
|
+
...config.instanceId !== undefined ? { instanceId: config.instanceId } : {},
|
|
31104
|
+
...config.pollingIntervalMs !== undefined ? { pollingIntervalMs: config.pollingIntervalMs } : {},
|
|
31105
|
+
...config.tags !== undefined ? { tags: config.tags } : {},
|
|
31106
|
+
channelIds: config.channels?.ids,
|
|
31107
|
+
channelNames: config.channels?.names,
|
|
31108
|
+
...sidecar === undefined ? {} : { sidecar }
|
|
31109
|
+
});
|
|
31110
|
+
},
|
|
30804
31111
|
github: (config, workspaceRoot, registrationName) => new GitHubSkill({
|
|
30805
31112
|
...common(config, workspaceRoot),
|
|
30806
31113
|
skillName: registrationName,
|
|
@@ -30946,7 +31253,7 @@ function migrateLegacyConfig(configPath, legacyPath) {
|
|
|
30946
31253
|
const legacy = readConfigFile(legacyPath, true);
|
|
30947
31254
|
const legacyBytes = readFileSync25(legacyPath);
|
|
30948
31255
|
const migrated = normalizeLegacyConfigPaths(legacy ?? {}, dirname26(legacyPath));
|
|
30949
|
-
const migratedPathsUnchanged = legacy?.workspacePath === migrated.workspacePath && legacy?.memoryPath === migrated.memoryPath && JSON.stringify(legacy?.searchPaths) === JSON.stringify(migrated.searchPaths);
|
|
31256
|
+
const migratedPathsUnchanged = legacy?.workspacePath === migrated.workspacePath && legacy?.memoryPath === migrated.memoryPath && JSON.stringify(legacy?.searchPaths) === JSON.stringify(migrated.searchPaths) && JSON.stringify(legacy?.excludePaths) === JSON.stringify(migrated.excludePaths);
|
|
30950
31257
|
const migratedBytes = migratedPathsUnchanged ? legacyBytes : `${JSON.stringify(migrated, null, 2)}
|
|
30951
31258
|
`;
|
|
30952
31259
|
mkdirSync25(dirname26(configPath), { recursive: true });
|
|
@@ -30984,15 +31291,25 @@ function resolveConfigFileReadOnly(configPath, explicit, legacyPath) {
|
|
|
30984
31291
|
function resolveSearchPaths(searchPaths, origin) {
|
|
30985
31292
|
return searchPaths.map((searchPath) => resolvePersistedPath(searchPath, origin));
|
|
30986
31293
|
}
|
|
31294
|
+
function resolveExcludePaths(value, origin) {
|
|
31295
|
+
if (value === undefined)
|
|
31296
|
+
return;
|
|
31297
|
+
if (!Array.isArray(value) || value.some((path) => typeof path !== "string" || path.length === 0)) {
|
|
31298
|
+
throw new ConfigError("Config field 'excludePaths' must be a non-empty string array");
|
|
31299
|
+
}
|
|
31300
|
+
return resolveSearchPaths(value, origin);
|
|
31301
|
+
}
|
|
30987
31302
|
function resolvePersistedPath(path, origin) {
|
|
30988
31303
|
return isAbsolute10(path) ? path : resolve16(origin, path);
|
|
30989
31304
|
}
|
|
30990
31305
|
function normalizeLegacyConfigPaths(partial, origin) {
|
|
30991
31306
|
const workspacePath = resolvePersistedPath(partial.workspacePath ?? ".", origin);
|
|
31307
|
+
const excludePaths = resolveExcludePaths(partial.excludePaths, workspacePath);
|
|
30992
31308
|
return {
|
|
30993
31309
|
...partial,
|
|
30994
31310
|
workspacePath,
|
|
30995
31311
|
...partial.searchPaths === undefined ? {} : { searchPaths: resolveSearchPaths(partial.searchPaths, workspacePath) },
|
|
31312
|
+
...excludePaths === undefined ? {} : { excludePaths },
|
|
30996
31313
|
...partial.memoryPath === undefined ? {} : { memoryPath: resolvePersistedPath(partial.memoryPath, workspacePath) }
|
|
30997
31314
|
};
|
|
30998
31315
|
}
|
|
@@ -31447,10 +31764,7 @@ function resolveConfig(input) {
|
|
|
31447
31764
|
const configOrigin = dirname26(resolve16(configPath));
|
|
31448
31765
|
const fileWorkspacePath = typeof file.workspacePath === "string" ? resolvePersistedPath(file.workspacePath, configOrigin) : undefined;
|
|
31449
31766
|
const fileSearchPaths = file.searchPaths ? resolveSearchPaths(file.searchPaths, fileWorkspacePath ?? configOrigin) : undefined;
|
|
31450
|
-
|
|
31451
|
-
throw new ConfigError("Config field 'excludePaths' must be a non-empty string array");
|
|
31452
|
-
}
|
|
31453
|
-
const fileExcludePaths = file.excludePaths ? resolveSearchPaths(file.excludePaths, fileWorkspacePath ?? configOrigin) : undefined;
|
|
31767
|
+
const fileExcludePaths = resolveExcludePaths(file.excludePaths, fileWorkspacePath ?? configOrigin);
|
|
31454
31768
|
const searchPaths = flagSearchPaths ?? envSearchPaths ?? fileSearchPaths ?? defaultSearchPaths;
|
|
31455
31769
|
const flagWorkspacePath = flagString(flags, "workspace");
|
|
31456
31770
|
const envWorkspacePath = envString(env, "AUTORAG_WORKSPACE");
|
|
@@ -32186,7 +32500,7 @@ function writeDefaultConfig(path, partial, opts = {}) {
|
|
|
32186
32500
|
full.dupey = partial.dupey ?? { enabled: true };
|
|
32187
32501
|
full.excludeExactDuplicates = partial.excludeExactDuplicates ?? true;
|
|
32188
32502
|
if (partial.excludePaths !== undefined)
|
|
32189
|
-
full.excludePaths =
|
|
32503
|
+
full.excludePaths = resolveExcludePaths(partial.excludePaths, workspacePath);
|
|
32190
32504
|
if (partial.limits !== undefined)
|
|
32191
32505
|
full.limits = normalizeLimitsConfig(partial.limits);
|
|
32192
32506
|
if (partial.refresh !== undefined)
|