@curio-data/mcp-intelli-search 0.15.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +199 -0
- package/NOTICE +41 -0
- package/README.md +260 -0
- package/dist/chunk-5I6PWQPA.js +254 -0
- package/dist/chunk-V6E7CJEW.js +2505 -0
- package/dist/chunk-ZTHYRKI2.js +23 -0
- package/dist/cli.js +88 -0
- package/dist/runtime.js +16 -0
- package/dist/server.js +281 -0
- package/package.json +44 -0
|
@@ -0,0 +1,2505 @@
|
|
|
1
|
+
import {
|
|
2
|
+
identity,
|
|
3
|
+
validateCacheDir,
|
|
4
|
+
validateDomains
|
|
5
|
+
} from "./chunk-5I6PWQPA.js";
|
|
6
|
+
|
|
7
|
+
// packages/mcp/src/runtime.ts
|
|
8
|
+
import { Check } from "typebox/value";
|
|
9
|
+
|
|
10
|
+
// src/core/paths.ts
|
|
11
|
+
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
12
|
+
function resolveWorkspacePaths(workspaceRoot, cacheDir, display = "configured") {
|
|
13
|
+
if (!isAbsolute(workspaceRoot)) throw new Error("Workspace root must be absolute");
|
|
14
|
+
const root = resolve(workspaceRoot);
|
|
15
|
+
const cacheRoot = resolve(root, cacheDir);
|
|
16
|
+
return Object.freeze({
|
|
17
|
+
workspaceRoot: root,
|
|
18
|
+
cacheRoot,
|
|
19
|
+
stagingRoot: join(cacheRoot, ".staging"),
|
|
20
|
+
cacheDisplayRoot: display === "absolute" ? cacheRoot : cacheDir
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
function displayCachePath(paths, physicalPath) {
|
|
24
|
+
return join(paths.cacheDisplayRoot, relative(paths.cacheRoot, physicalPath));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// src/core/annotations.ts
|
|
28
|
+
function citationsFromChunk(parsed) {
|
|
29
|
+
if (typeof parsed !== "object" || parsed === null) return [];
|
|
30
|
+
const choices = parsed.choices;
|
|
31
|
+
if (!Array.isArray(choices)) return [];
|
|
32
|
+
const out = [];
|
|
33
|
+
for (const choice of choices) {
|
|
34
|
+
if (typeof choice !== "object" || choice === null) continue;
|
|
35
|
+
const holder = choice;
|
|
36
|
+
const annotationLists = [holder.delta?.annotations, holder.message?.annotations];
|
|
37
|
+
for (const list of annotationLists) {
|
|
38
|
+
if (!Array.isArray(list)) continue;
|
|
39
|
+
for (const entry of list) {
|
|
40
|
+
const ann = entry;
|
|
41
|
+
if (ann?.type !== "url_citation" && !ann?.url_citation) continue;
|
|
42
|
+
const url = ann.url_citation?.url;
|
|
43
|
+
if (typeof url !== "string" || url.length === 0) continue;
|
|
44
|
+
if (!/^https?:\/\//.test(url)) continue;
|
|
45
|
+
const title = ann.url_citation?.title;
|
|
46
|
+
out.push(typeof title === "string" && title.length > 0 ? { url, title } : { url });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
function parseCitations(bodyText2) {
|
|
53
|
+
const out = [];
|
|
54
|
+
const seen = /* @__PURE__ */ new Set();
|
|
55
|
+
const add = (list) => {
|
|
56
|
+
for (const c of list) {
|
|
57
|
+
if (!seen.has(c.url)) {
|
|
58
|
+
seen.add(c.url);
|
|
59
|
+
out.push(c);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const trimmed = bodyText2.trim();
|
|
64
|
+
if (trimmed.startsWith("{")) {
|
|
65
|
+
try {
|
|
66
|
+
add(citationsFromChunk(JSON.parse(trimmed)));
|
|
67
|
+
} catch {
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
for (const line of bodyText2.split("\n")) {
|
|
72
|
+
const trimmedLine = line.trim();
|
|
73
|
+
if (!trimmedLine.startsWith("data:")) continue;
|
|
74
|
+
const payload = trimmedLine.slice(5).trim();
|
|
75
|
+
if (payload.length === 0 || payload === "[DONE]") continue;
|
|
76
|
+
try {
|
|
77
|
+
add(citationsFromChunk(JSON.parse(payload)));
|
|
78
|
+
} catch {
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
function mergeCitations(textUrls, sink) {
|
|
84
|
+
const merged = [];
|
|
85
|
+
const seen = /* @__PURE__ */ new Set();
|
|
86
|
+
for (const { url, title } of textUrls) {
|
|
87
|
+
if (seen.has(url)) continue;
|
|
88
|
+
seen.add(url);
|
|
89
|
+
merged.push({ url, title });
|
|
90
|
+
}
|
|
91
|
+
for (const { url, title } of sink.citations) {
|
|
92
|
+
if (seen.has(url)) continue;
|
|
93
|
+
seen.add(url);
|
|
94
|
+
merged.push({ url, title: title && title.length > 0 ? title : url });
|
|
95
|
+
}
|
|
96
|
+
return merged;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// src/core/console.ts
|
|
100
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
101
|
+
var scopes = new AsyncLocalStorage();
|
|
102
|
+
var activeCalls = 0;
|
|
103
|
+
var restore;
|
|
104
|
+
function acquireConsole() {
|
|
105
|
+
if (activeCalls++ !== 0) return;
|
|
106
|
+
const originalError = console.error;
|
|
107
|
+
const originalWarn = console.warn;
|
|
108
|
+
const dispatch = (channel, original) => (...args) => {
|
|
109
|
+
const stack = scopes.getStore() ?? [];
|
|
110
|
+
for (let i = stack.length - 1; i >= 0; i--) {
|
|
111
|
+
const scope = stack[i];
|
|
112
|
+
if (scope.active && scope[channel].includes(args[0])) {
|
|
113
|
+
if (channel === "error") scope.muzzled = true;
|
|
114
|
+
else scope.warned = true;
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
original(...args);
|
|
119
|
+
};
|
|
120
|
+
const errorDispatcher = dispatch("error", originalError);
|
|
121
|
+
const warnDispatcher = dispatch("warn", originalWarn);
|
|
122
|
+
console.error = errorDispatcher;
|
|
123
|
+
console.warn = warnDispatcher;
|
|
124
|
+
restore = () => {
|
|
125
|
+
if (console.error === errorDispatcher) console.error = originalError;
|
|
126
|
+
if (console.warn === warnDispatcher) console.warn = originalWarn;
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
async function withMuzzledConsole(fn, muzzleTags) {
|
|
130
|
+
const error = muzzleTags.error ?? [];
|
|
131
|
+
const warn = muzzleTags.warn ?? [];
|
|
132
|
+
if (error.length === 0 && warn.length === 0) {
|
|
133
|
+
return { value: await fn(), muzzled: false, warned: false };
|
|
134
|
+
}
|
|
135
|
+
const scope = { error, warn, muzzled: false, warned: false, active: true };
|
|
136
|
+
acquireConsole();
|
|
137
|
+
try {
|
|
138
|
+
const value = await scopes.run([...scopes.getStore() ?? [], scope], fn);
|
|
139
|
+
return { value, muzzled: scope.muzzled, warned: scope.warned };
|
|
140
|
+
} finally {
|
|
141
|
+
scope.active = false;
|
|
142
|
+
if (--activeCalls === 0) {
|
|
143
|
+
restore?.();
|
|
144
|
+
restore = void 0;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/core/util.ts
|
|
150
|
+
function throwIfAborted(signal) {
|
|
151
|
+
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
|
|
152
|
+
}
|
|
153
|
+
function errMsg(err) {
|
|
154
|
+
return err instanceof Error ? err.message : String(err);
|
|
155
|
+
}
|
|
156
|
+
var TRUNCATED_MARKER = "\n\n[TRUNCATED]";
|
|
157
|
+
function truncateContent(content, maxChars) {
|
|
158
|
+
if (content.length <= maxChars) return content;
|
|
159
|
+
return content.slice(0, maxChars) + TRUNCATED_MARKER;
|
|
160
|
+
}
|
|
161
|
+
async function mapWithConcurrency(items, concurrency, fn, opts) {
|
|
162
|
+
const results = new Array(items.length).fill(void 0);
|
|
163
|
+
let nextIndex = 0;
|
|
164
|
+
const limit = Math.max(1, Math.min(concurrency, items.length));
|
|
165
|
+
const worker = async () => {
|
|
166
|
+
while (nextIndex < items.length) {
|
|
167
|
+
if (opts?.signal?.aborted) return;
|
|
168
|
+
const index = nextIndex++;
|
|
169
|
+
const result = await fn(items[index], index);
|
|
170
|
+
results[index] = result;
|
|
171
|
+
opts?.onSettled?.(items[index], index, result);
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
const settled = await Promise.allSettled(Array.from({ length: limit }, () => worker()));
|
|
175
|
+
const failed = settled.find((r) => r.status === "rejected");
|
|
176
|
+
if (failed?.status === "rejected") throw failed.reason;
|
|
177
|
+
return results;
|
|
178
|
+
}
|
|
179
|
+
function sleep(ms, signal) {
|
|
180
|
+
return new Promise((resolve2, reject) => {
|
|
181
|
+
if (signal?.aborted) {
|
|
182
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
const timer = setTimeout(() => {
|
|
186
|
+
signal?.removeEventListener("abort", onAbort);
|
|
187
|
+
resolve2();
|
|
188
|
+
}, ms);
|
|
189
|
+
const onAbort = () => {
|
|
190
|
+
clearTimeout(timer);
|
|
191
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
192
|
+
};
|
|
193
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
async function callWithAbortTimeout(run, timeoutMs, userSignal) {
|
|
197
|
+
if (!timeoutMs || timeoutMs <= 0) {
|
|
198
|
+
return { value: await run(userSignal), timedOut: false };
|
|
199
|
+
}
|
|
200
|
+
const ac = new AbortController();
|
|
201
|
+
let timedOut = false;
|
|
202
|
+
const timer = setTimeout(() => {
|
|
203
|
+
timedOut = true;
|
|
204
|
+
ac.abort();
|
|
205
|
+
}, timeoutMs);
|
|
206
|
+
const signal = userSignal ? AbortSignal.any([userSignal, ac.signal]) : ac.signal;
|
|
207
|
+
try {
|
|
208
|
+
const value = await run(signal);
|
|
209
|
+
return { value, timedOut };
|
|
210
|
+
} catch (error) {
|
|
211
|
+
if (timedOut && !userSignal?.aborted) throw new AttemptTimeoutError({ cause: error });
|
|
212
|
+
throw error;
|
|
213
|
+
} finally {
|
|
214
|
+
clearTimeout(timer);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
var AttemptTimeoutError = class extends Error {
|
|
218
|
+
constructor(options) {
|
|
219
|
+
super("Model attempt timed out", options);
|
|
220
|
+
this.name = "AttemptTimeoutError";
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
async function withRetry(fn, classify, opts) {
|
|
224
|
+
const sleepFn = opts.sleep ?? sleep;
|
|
225
|
+
const rand = opts.random ?? Math.random;
|
|
226
|
+
const attempts = Math.max(1, opts.attempts);
|
|
227
|
+
let lastResult;
|
|
228
|
+
let lastError;
|
|
229
|
+
let threw = false;
|
|
230
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
231
|
+
throwIfAborted(opts.signal);
|
|
232
|
+
threw = false;
|
|
233
|
+
try {
|
|
234
|
+
lastResult = await fn(attempt);
|
|
235
|
+
} catch (err) {
|
|
236
|
+
threw = true;
|
|
237
|
+
lastError = err;
|
|
238
|
+
}
|
|
239
|
+
if (opts.signal?.aborted) break;
|
|
240
|
+
const decision = classify(threw ? void 0 : lastResult, threw ? lastError : void 0);
|
|
241
|
+
if (!decision.retry || attempt === attempts) break;
|
|
242
|
+
const exp = Math.min(opts.maxDelayMs, opts.baseDelayMs * 2 ** (attempt - 1));
|
|
243
|
+
let delayMs = rand() * exp;
|
|
244
|
+
if (decision.retryAfterMs != null) {
|
|
245
|
+
delayMs = Math.min(Math.max(delayMs, decision.retryAfterMs), opts.maxDelayMs);
|
|
246
|
+
}
|
|
247
|
+
opts.onRetry?.({ attempt, delayMs, reason: threw ? "error" : "degraded" });
|
|
248
|
+
await sleepFn(delayMs, opts.signal);
|
|
249
|
+
}
|
|
250
|
+
if (threw) throw lastError;
|
|
251
|
+
return lastResult;
|
|
252
|
+
}
|
|
253
|
+
var RETRYABLE_RE = /\b(429|rate[ _-]?limited?|too many requests|overloaded|server error|service unavailable|temporarily unavailable|500|502|503|504|timed? ?out|timeout|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN)\b/i;
|
|
254
|
+
function isRetryableMessage(msg) {
|
|
255
|
+
return !!msg && RETRYABLE_RE.test(msg);
|
|
256
|
+
}
|
|
257
|
+
function parseRetryAfterMs(msg) {
|
|
258
|
+
if (!msg) return void 0;
|
|
259
|
+
const m = msg.match(/retry[\s-]?after[:\s]*?(\d+(?:\.\d+)?)\s*(ms|s|sec|secs|seconds)?/i) ?? msg.match(/(?:try again|retry) in\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|secs|seconds)?/i);
|
|
260
|
+
if (!m) return void 0;
|
|
261
|
+
const n = parseFloat(m[1]);
|
|
262
|
+
if (!Number.isFinite(n)) return void 0;
|
|
263
|
+
return /^ms$/i.test(m[2] ?? "") ? n : n * 1e3;
|
|
264
|
+
}
|
|
265
|
+
function createRateLimiter(minIntervalMs) {
|
|
266
|
+
let next = 0;
|
|
267
|
+
return async (signal) => {
|
|
268
|
+
if (minIntervalMs <= 0) return;
|
|
269
|
+
const now = Date.now();
|
|
270
|
+
const wait = Math.max(0, next - now);
|
|
271
|
+
next = Math.max(now, next) + minIntervalMs;
|
|
272
|
+
if (wait > 0) await sleep(wait, signal);
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
function extractSourceUrls(text) {
|
|
276
|
+
const urls = [];
|
|
277
|
+
const seen = /* @__PURE__ */ new Set();
|
|
278
|
+
const linkPattern = /\[([^\]]*)\]\((https?:\/\/(?:[^()\s]|\([^()\s]*\))*)\)/g;
|
|
279
|
+
for (const m of text.matchAll(linkPattern)) {
|
|
280
|
+
const url = m[2];
|
|
281
|
+
if (!seen.has(url)) {
|
|
282
|
+
seen.add(url);
|
|
283
|
+
urls.push({ url, title: m[1] });
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
const barePattern = /(https?:\/\/(?:[^\s<>"{}*()|\\^`\[\]]|\([^()\s]*\))+)/g;
|
|
287
|
+
for (const m of text.matchAll(barePattern)) {
|
|
288
|
+
const url = m[1].replace(/[.,;:!]+$/, "");
|
|
289
|
+
if (!seen.has(url)) {
|
|
290
|
+
seen.add(url);
|
|
291
|
+
try {
|
|
292
|
+
const u = new URL(url);
|
|
293
|
+
const parts = u.pathname.split("/").filter(Boolean);
|
|
294
|
+
const title = parts.length > 0 ? parts[parts.length - 1].replace(/\.[^.]+$/, "") : u.hostname;
|
|
295
|
+
urls.push({ url, title });
|
|
296
|
+
} catch {
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
const absoluteSpans = [];
|
|
301
|
+
const absoluteSpanPattern = /https?:\/\/\S+/g;
|
|
302
|
+
for (const m of text.matchAll(absoluteSpanPattern)) {
|
|
303
|
+
absoluteSpans.push({ start: m.index, end: m.index + m[0].length });
|
|
304
|
+
}
|
|
305
|
+
const domainPattern = /(?<!:\/\/)(?<![A-Za-z0-9@._-])((?:www\.)?(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}(?:\/[^\s<>"{}*()|\\`\[\]]*)?)/g;
|
|
306
|
+
for (const m of text.matchAll(domainPattern)) {
|
|
307
|
+
if (absoluteSpans.some(({ start, end }) => m.index >= start && m.index < end)) continue;
|
|
308
|
+
const domainReference = m[1].replace(/[.,;:!]+$/, "");
|
|
309
|
+
const url = `https://${domainReference}`;
|
|
310
|
+
if (seen.has(url)) continue;
|
|
311
|
+
try {
|
|
312
|
+
const u = new URL(url);
|
|
313
|
+
seen.add(url);
|
|
314
|
+
const parts = u.pathname.split("/").filter(Boolean);
|
|
315
|
+
const title = parts.length > 0 ? parts[parts.length - 1].replace(/\.[^.]+$/, "") : u.hostname;
|
|
316
|
+
urls.push({ url, title });
|
|
317
|
+
} catch {
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return urls;
|
|
321
|
+
}
|
|
322
|
+
function inferSourceType(line) {
|
|
323
|
+
const lower = line.toLowerCase();
|
|
324
|
+
if (lower.includes("official doc")) return "official docs";
|
|
325
|
+
if (lower.includes("api reference")) return "API reference";
|
|
326
|
+
if (lower.includes("tutorial")) return "tutorial";
|
|
327
|
+
if (lower.includes("blog")) return "blog post";
|
|
328
|
+
if (lower.includes("forum") || lower.includes("stackoverflow")) return "forum";
|
|
329
|
+
return "unknown";
|
|
330
|
+
}
|
|
331
|
+
function inferCurrentness(line) {
|
|
332
|
+
const lower = line.toLowerCase();
|
|
333
|
+
if (lower.includes("current") || lower.includes("up to date")) return "current";
|
|
334
|
+
if (lower.includes("outdated") || lower.includes("old")) return "possibly outdated";
|
|
335
|
+
return "undated";
|
|
336
|
+
}
|
|
337
|
+
function stripTrailingSourcesSection(text) {
|
|
338
|
+
const trimmedEnd = text.replace(/[ \t]+$/g, "");
|
|
339
|
+
const match = trimmedEnd.match(
|
|
340
|
+
/\n[ \t]*(?:#{1,6}[ \t]*)?\*{0,2}Sources\*{0,2}[ \t]*:?[ \t]*\n[\s\S]*$/i
|
|
341
|
+
);
|
|
342
|
+
if (!match) return text;
|
|
343
|
+
if (!/https?:\/\/|\bwww\./.test(match[0])) return text;
|
|
344
|
+
const cut = trimmedEnd.slice(0, match.index).replace(/\s+$/g, "");
|
|
345
|
+
return cut + "\n";
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// src/core/llm.ts
|
|
349
|
+
async function runModelWithPolicy(attempt, request, logger, testing) {
|
|
350
|
+
const { model, signal, retry, timeoutMs } = request;
|
|
351
|
+
const label = `${model.provider}/${model.model}`;
|
|
352
|
+
let timedOut = false;
|
|
353
|
+
let hints = {};
|
|
354
|
+
const timeoutError = () => new Error(
|
|
355
|
+
`LLM call timed out (${label}) after ${timeoutMs}ms per attempt across ${retry?.attempts ?? 1} attempt(s). The provider may be rate limiting or overloaded.`
|
|
356
|
+
);
|
|
357
|
+
let response;
|
|
358
|
+
try {
|
|
359
|
+
response = await withRetry(
|
|
360
|
+
async () => {
|
|
361
|
+
timedOut = false;
|
|
362
|
+
hints = {};
|
|
363
|
+
try {
|
|
364
|
+
const result = await callWithAbortTimeout(
|
|
365
|
+
(attemptSignal) => attempt(attemptSignal, hints),
|
|
366
|
+
timeoutMs,
|
|
367
|
+
signal
|
|
368
|
+
);
|
|
369
|
+
timedOut = result.timedOut;
|
|
370
|
+
return result.value;
|
|
371
|
+
} catch (error) {
|
|
372
|
+
timedOut = error instanceof AttemptTimeoutError;
|
|
373
|
+
throw error;
|
|
374
|
+
}
|
|
375
|
+
},
|
|
376
|
+
(result, error) => {
|
|
377
|
+
if (signal?.aborted) return { retry: false };
|
|
378
|
+
if (timedOut) return { retry: true };
|
|
379
|
+
const message = error ? errMsg(error) : result?.error;
|
|
380
|
+
return isRetryableMessage(message) ? { retry: true, retryAfterMs: parseRetryAfterMs(message) ?? hints.retryAfterMs } : { retry: false };
|
|
381
|
+
},
|
|
382
|
+
{
|
|
383
|
+
attempts: retry?.attempts ?? 1,
|
|
384
|
+
baseDelayMs: retry?.baseDelayMs ?? 1e3,
|
|
385
|
+
maxDelayMs: retry?.maxDelayMs ?? 2e4,
|
|
386
|
+
signal,
|
|
387
|
+
...testing,
|
|
388
|
+
onRetry: ({ attempt: attempt2, delayMs, reason }) => {
|
|
389
|
+
const message = `${label}: ${timedOut ? "timeout" : reason} on attempt ${attempt2}, retrying in ${Math.round(delayMs)}ms`;
|
|
390
|
+
if (request.onRetryNotice) request.onRetryNotice(message);
|
|
391
|
+
else logger.error(message);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
);
|
|
395
|
+
} catch (error) {
|
|
396
|
+
throwIfAborted(signal);
|
|
397
|
+
if (timedOut) throw timeoutError();
|
|
398
|
+
throw error;
|
|
399
|
+
}
|
|
400
|
+
throwIfAborted(signal);
|
|
401
|
+
if (timedOut) throw timeoutError();
|
|
402
|
+
if (response.error !== void 0)
|
|
403
|
+
throw new Error(`LLM call failed (${label}): ${response.error}`);
|
|
404
|
+
return response.value;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// src/core/prompts.ts
|
|
408
|
+
var SEARCH_SYSTEM_PROMPT = "You are a web search assistant. Answer the query with cited sources. Always include source URLs in markdown link format: [title](url). End your response with a Sources section that lists every source you used, one markdown link per line. Include as many relevant source URLs as possible (aim for 6 or more).";
|
|
409
|
+
var EXTRACTION_SYSTEM_PROMPT = `You are a technical content extraction assistant. Your job is to
|
|
410
|
+
extract relevant information from a web page for a software developer.
|
|
411
|
+
|
|
412
|
+
Rules:
|
|
413
|
+
- Extract ONLY the content relevant to the query. Discard unrelated sections.
|
|
414
|
+
- Preserve complete code blocks, function signatures, API examples, and
|
|
415
|
+
configuration snippets verbatim. These are high-value content.
|
|
416
|
+
- Preserve version numbers, dependency requirements, and compatibility notes.
|
|
417
|
+
- Summarise narrative prose concisely but do not truncate technical detail.
|
|
418
|
+
- If the page is primarily a blog post paraphrasing official documentation,
|
|
419
|
+
note this and identify the upstream source if visible.
|
|
420
|
+
- Structure your extraction with clear headings.
|
|
421
|
+
- Begin with a one-line assessment: what type of source this is
|
|
422
|
+
(official docs / tutorial / blog post / forum thread / API reference)
|
|
423
|
+
and how current it appears to be.
|
|
424
|
+
- Adapt extraction to the source type:
|
|
425
|
+
- Official docs/API reference: preserve exact signatures, parameter types,
|
|
426
|
+
return types, and version annotations. These are canonical.
|
|
427
|
+
- Blog posts/tutorials: extract practical patterns, gotchas, and real-world
|
|
428
|
+
examples that aren't in the docs. Note if the author is paraphrasing docs.
|
|
429
|
+
- Forum threads (Reddit, StackOverflow, Discourse): extract the actual problem,
|
|
430
|
+
the accepted or most-upvoted solution, and any caveats. Discard tangents.
|
|
431
|
+
- Aim for 3,000-5,000 characters of output. Shorter for thin pages,
|
|
432
|
+
longer if the page is densely relevant.`;
|
|
433
|
+
var COLLATION_SYSTEM_PROMPT = `You are a research collation assistant for a software developer.
|
|
434
|
+
You receive multiple per-page extractions on the same topic. Each extraction
|
|
435
|
+
has already been filtered for relevance \u2014 your job is to synthesise, not extract.
|
|
436
|
+
|
|
437
|
+
Your job:
|
|
438
|
+
1. Identify overlapping content. If multiple sources describe the same concept,
|
|
439
|
+
keep the best version using this priority:
|
|
440
|
+
- Official documentation > API reference > tutorial > blog post > forum thread
|
|
441
|
+
- When contradicting, prefer official docs. Flag the contradiction.
|
|
442
|
+
- Blog posts may have better practical examples than docs \u2014 keep those.
|
|
443
|
+
- Forum threads may have real-world fixes not in docs \u2014 keep those.
|
|
444
|
+
2. Flag contradictions explicitly: "Source A says X, Source B says Y."
|
|
445
|
+
3. Preserve the single best code example for each concept \u2014 do not include
|
|
446
|
+
multiple versions of the same snippet. Prefer complete, runnable examples.
|
|
447
|
+
4. Note version-specific information and any deprecation warnings.
|
|
448
|
+
5. Include cache paths and source file references for follow-up.
|
|
449
|
+
|
|
450
|
+
Output exactly two sections:
|
|
451
|
+
|
|
452
|
+
## Summary
|
|
453
|
+
A concise, deduplicated synthesis (under 2000 tokens).
|
|
454
|
+
Include the cache path and source file paths so the agent can drill deeper.
|
|
455
|
+
Preserve complete code blocks and API signatures verbatim.
|
|
456
|
+
|
|
457
|
+
## Source assessment
|
|
458
|
+
For each source: URL, type, relevance (high/medium/low), what unique information
|
|
459
|
+
it contributed that wasn't available in other sources.`;
|
|
460
|
+
var CACHE_SUGGEST_PROMPT = `You judge search query relevance. Given the current query and a list of
|
|
461
|
+
previous searches, identify which are semantically related \u2014 even if the
|
|
462
|
+
wording differs. Consider paraphrases, broader/narrower scope, and topic overlap.
|
|
463
|
+
|
|
464
|
+
Return a JSON array of matching entries, each with "index" (1-based from the
|
|
465
|
+
list) and "relevance" (a brief note on why it's related). Return an empty
|
|
466
|
+
array [] if none are related.
|
|
467
|
+
|
|
468
|
+
Important: only include genuinely related searches. A query about "Rust
|
|
469
|
+
installation" is NOT related to "Rust vs Go performance" even though both
|
|
470
|
+
mention Rust. Focus on whether reading the previous results would actually
|
|
471
|
+
help someone researching the current query.
|
|
472
|
+
|
|
473
|
+
Response format:
|
|
474
|
+
[{"index": 1, "relevance": "one-line note"}]`;
|
|
475
|
+
|
|
476
|
+
// src/core/cache.ts
|
|
477
|
+
import { mkdir, writeFile, readFile, rename, rm, stat, readdir } from "node:fs/promises";
|
|
478
|
+
import { dirname, join as join2 } from "node:path";
|
|
479
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
480
|
+
var MAX_JUDGE_ENTRIES = 20;
|
|
481
|
+
var DEFAULT_STALE_MS = 3e4;
|
|
482
|
+
var DEFAULT_POLL_MS = 50;
|
|
483
|
+
var DEFAULT_LOCK_TIMEOUT_MS = 1e4;
|
|
484
|
+
function cacheLockDir(cachePath) {
|
|
485
|
+
return join2(cachePath, ".lock");
|
|
486
|
+
}
|
|
487
|
+
function indexLockDir(cacheDir) {
|
|
488
|
+
return join2(cacheDir, ".index.lock");
|
|
489
|
+
}
|
|
490
|
+
async function acquireLock(lockDir, opts) {
|
|
491
|
+
const timeoutMs = opts?.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS;
|
|
492
|
+
const staleMs = opts?.staleMs ?? DEFAULT_STALE_MS;
|
|
493
|
+
const pollMs = opts?.pollMs ?? DEFAULT_POLL_MS;
|
|
494
|
+
const deadline = Date.now() + timeoutMs;
|
|
495
|
+
throwIfAborted(opts?.signal);
|
|
496
|
+
await mkdir(dirname(lockDir), { recursive: true });
|
|
497
|
+
while (true) {
|
|
498
|
+
throwIfAborted(opts?.signal);
|
|
499
|
+
try {
|
|
500
|
+
await mkdir(lockDir);
|
|
501
|
+
await writeFile(join2(lockDir, "pid"), String(process.pid), "utf-8");
|
|
502
|
+
return async () => {
|
|
503
|
+
try {
|
|
504
|
+
await rm(lockDir, { recursive: true, force: true });
|
|
505
|
+
} catch {
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
} catch (err) {
|
|
509
|
+
if (err?.code !== "EEXIST") throw err;
|
|
510
|
+
if (await isLockStale(lockDir, staleMs)) {
|
|
511
|
+
await rm(lockDir, { recursive: true, force: true });
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
514
|
+
if (Date.now() >= deadline) {
|
|
515
|
+
throw new Error(`Lock timeout: could not acquire ${lockDir} within ${timeoutMs}ms`);
|
|
516
|
+
}
|
|
517
|
+
const delay = pollMs + Math.floor(Math.random() * pollMs);
|
|
518
|
+
await sleep(delay, opts?.signal);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
async function isLockStale(lockDir, staleMs) {
|
|
523
|
+
try {
|
|
524
|
+
const s = await stat(lockDir);
|
|
525
|
+
return Date.now() - s.birthtimeMs > staleMs;
|
|
526
|
+
} catch {
|
|
527
|
+
return false;
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
async function withLock(lockDir, fn, signal) {
|
|
531
|
+
const release = await acquireLock(lockDir, { signal });
|
|
532
|
+
try {
|
|
533
|
+
throwIfAborted(signal);
|
|
534
|
+
return await fn();
|
|
535
|
+
} finally {
|
|
536
|
+
await release();
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
async function atomicWriteFile(filePath, content) {
|
|
540
|
+
const tmp = filePath + "." + process.pid + "." + randomBytes(4).toString("hex") + ".tmp";
|
|
541
|
+
await writeFile(tmp, content, "utf-8");
|
|
542
|
+
await rename(tmp, filePath);
|
|
543
|
+
}
|
|
544
|
+
async function createStagingDir(parent) {
|
|
545
|
+
const name = `.staging.${process.pid}.${randomBytes(4).toString("hex")}`;
|
|
546
|
+
const staging = join2(parent, name);
|
|
547
|
+
await mkdir(staging, { recursive: true });
|
|
548
|
+
return staging;
|
|
549
|
+
}
|
|
550
|
+
function makeCachePath(query, cwd, cacheDir) {
|
|
551
|
+
const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
552
|
+
const words = query.toLowerCase().replace(/[^a-z0-9\s]/g, "").split(/\s+/).filter(Boolean).slice(0, 5).join("-");
|
|
553
|
+
const hash = createHash("sha1").update(query).digest("hex").slice(0, 6);
|
|
554
|
+
const stem = words ? `${words}-${hash}` : hash;
|
|
555
|
+
return join2(resolveWorkspacePaths(cwd, cacheDir).cacheRoot, `${date}-${stem}`);
|
|
556
|
+
}
|
|
557
|
+
function domainSlug(url) {
|
|
558
|
+
try {
|
|
559
|
+
return new URL(url).hostname.replace(/^www\./, "").replace(/\./g, "-");
|
|
560
|
+
} catch {
|
|
561
|
+
return "unknown";
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
function sourceFilename(index, url) {
|
|
565
|
+
return `${String(index + 1).padStart(2, "0")}-${domainSlug(url)}.md`;
|
|
566
|
+
}
|
|
567
|
+
async function writeCacheFiles(cachePath, extractions, pages, searchSummary, query) {
|
|
568
|
+
await mkdir(cachePath, { recursive: true });
|
|
569
|
+
const staging = await createStagingDir(cachePath);
|
|
570
|
+
try {
|
|
571
|
+
const stagingExtractions = join2(staging, "extractions");
|
|
572
|
+
const stagingSources = join2(staging, "sources");
|
|
573
|
+
await mkdir(stagingExtractions, { recursive: true });
|
|
574
|
+
await mkdir(stagingSources, { recursive: true });
|
|
575
|
+
await writeFile(join2(staging, "query.txt"), query, "utf-8");
|
|
576
|
+
for (const [i, ext] of extractions.entries()) {
|
|
577
|
+
if (ext.status !== "success" || !ext.extraction) continue;
|
|
578
|
+
const filename = sourceFilename(i, ext.url);
|
|
579
|
+
const header = `# ${ext.title}
|
|
580
|
+
|
|
581
|
+
> Source: ${ext.url}
|
|
582
|
+
> Type: ${ext.sourceType}
|
|
583
|
+
|
|
584
|
+
---
|
|
585
|
+
|
|
586
|
+
`;
|
|
587
|
+
await writeFile(join2(stagingExtractions, filename), header + ext.extraction, "utf-8");
|
|
588
|
+
}
|
|
589
|
+
for (const [i, page] of pages.entries()) {
|
|
590
|
+
if (page.status !== "success") continue;
|
|
591
|
+
const filename = sourceFilename(i, page.url);
|
|
592
|
+
const header = `# ${page.title}
|
|
593
|
+
|
|
594
|
+
> Source: ${page.url}
|
|
595
|
+
|
|
596
|
+
---
|
|
597
|
+
|
|
598
|
+
`;
|
|
599
|
+
await writeFile(join2(stagingSources, filename), header + page.content, "utf-8");
|
|
600
|
+
}
|
|
601
|
+
await moveStagedFiles(staging, cachePath);
|
|
602
|
+
} finally {
|
|
603
|
+
await rm(staging, { recursive: true, force: true }).catch(() => {
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
async function moveStagedFiles(staging, target) {
|
|
608
|
+
const entries = await readdir(staging, { withFileTypes: true });
|
|
609
|
+
for (const entry of entries) {
|
|
610
|
+
const src = join2(staging, entry.name);
|
|
611
|
+
const dst = join2(target, entry.name);
|
|
612
|
+
if (entry.isDirectory()) {
|
|
613
|
+
await mkdir(dst, { recursive: true });
|
|
614
|
+
await moveStagedFiles(src, dst);
|
|
615
|
+
} else {
|
|
616
|
+
await rm(dst, { force: true }).catch(() => {
|
|
617
|
+
});
|
|
618
|
+
await rename(src, dst);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
async function writeReportFile(cachePath, query, collation, extractions, pages, displayPath = cachePath) {
|
|
623
|
+
await mkdir(cachePath, { recursive: true });
|
|
624
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
625
|
+
const succeeded = extractions.filter((e) => e.status === "success");
|
|
626
|
+
const blocked = extractions.filter((e) => e.status !== "success");
|
|
627
|
+
let report = `# ${query}
|
|
628
|
+
|
|
629
|
+
`;
|
|
630
|
+
report += `> Searched: ${now}
|
|
631
|
+
`;
|
|
632
|
+
report += `> Cache: ${displayPath}/
|
|
633
|
+
`;
|
|
634
|
+
report += `> Sources: ${succeeded.length} succeeded, ${blocked.length} blocked
|
|
635
|
+
|
|
636
|
+
`;
|
|
637
|
+
report += collation + "\n\n";
|
|
638
|
+
report += `## Source index
|
|
639
|
+
|
|
640
|
+
`;
|
|
641
|
+
report += `| # | Source | Type | Extraction | Full page |
|
|
642
|
+
`;
|
|
643
|
+
report += `|---|--------|------|------------|----------|
|
|
644
|
+
`;
|
|
645
|
+
for (const [i, ext] of succeeded.entries()) {
|
|
646
|
+
const filename = sourceFilename(i, ext.url);
|
|
647
|
+
report += `| ${i + 1} | ${ext.url} | ${ext.sourceType} | extractions/${filename} | sources/${filename} |
|
|
648
|
+
`;
|
|
649
|
+
}
|
|
650
|
+
if (blocked.length > 0) {
|
|
651
|
+
report += `
|
|
652
|
+
## Blocked/Failed URLs
|
|
653
|
+
|
|
654
|
+
`;
|
|
655
|
+
for (const page of pages.filter((p) => p.status !== "success")) {
|
|
656
|
+
report += `- ${page.url}${page.error ? ` \u2014 ${page.error}` : ""}
|
|
657
|
+
`;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
await atomicWriteFile(join2(cachePath, "report.md"), report);
|
|
661
|
+
}
|
|
662
|
+
async function updateIndex(cacheDir, slug, query) {
|
|
663
|
+
await mkdir(cacheDir, { recursive: true });
|
|
664
|
+
const indexPath = join2(cacheDir, ".index.json");
|
|
665
|
+
let index;
|
|
666
|
+
try {
|
|
667
|
+
const raw = await readFile(indexPath, "utf-8");
|
|
668
|
+
index = JSON.parse(raw);
|
|
669
|
+
} catch {
|
|
670
|
+
index = { searches: [] };
|
|
671
|
+
}
|
|
672
|
+
index.searches = index.searches.filter((e) => e.slug !== slug);
|
|
673
|
+
index.searches.push({ slug, query, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
674
|
+
await atomicWriteFile(indexPath, JSON.stringify(index, null, 2) + "\n");
|
|
675
|
+
}
|
|
676
|
+
async function readIndex(cacheDir) {
|
|
677
|
+
const indexPath = join2(cacheDir, ".index.json");
|
|
678
|
+
try {
|
|
679
|
+
const raw = await readFile(indexPath, "utf-8");
|
|
680
|
+
return JSON.parse(raw);
|
|
681
|
+
} catch {
|
|
682
|
+
return { searches: [] };
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
function formatIndexForJudge(index, excludeSlug) {
|
|
686
|
+
const entries = index.searches.filter((e) => e.slug !== excludeSlug).slice(-MAX_JUDGE_ENTRIES);
|
|
687
|
+
if (entries.length === 0) return "No previous searches.";
|
|
688
|
+
return entries.map((e, i) => `${i + 1}. "${e.query}" (slug: ${e.slug}, searched: ${e.timestamp})`).join("\n");
|
|
689
|
+
}
|
|
690
|
+
function parseJudgeResponse(response, index, excludeSlug) {
|
|
691
|
+
const eligible = index.searches.filter((e) => e.slug !== excludeSlug);
|
|
692
|
+
const jsonMatch = response.match(/\[[\s\S]*\]/);
|
|
693
|
+
if (!jsonMatch) return [];
|
|
694
|
+
let parsed;
|
|
695
|
+
try {
|
|
696
|
+
parsed = JSON.parse(jsonMatch[0]);
|
|
697
|
+
} catch {
|
|
698
|
+
return [];
|
|
699
|
+
}
|
|
700
|
+
if (!Array.isArray(parsed)) return [];
|
|
701
|
+
const results = [];
|
|
702
|
+
for (const item of parsed) {
|
|
703
|
+
if (typeof item.index !== "number" || item.index < 1) continue;
|
|
704
|
+
const entry = eligible[item.index - 1];
|
|
705
|
+
if (!entry) continue;
|
|
706
|
+
results.push({ entry, relevance: item.relevance ?? "" });
|
|
707
|
+
}
|
|
708
|
+
return results;
|
|
709
|
+
}
|
|
710
|
+
function formatCacheSuggestions(matches, cacheDir) {
|
|
711
|
+
if (matches.length === 0) return "";
|
|
712
|
+
const now = Date.now();
|
|
713
|
+
const age = (ts) => {
|
|
714
|
+
const hours = Math.floor((now - new Date(ts).getTime()) / 36e5);
|
|
715
|
+
if (hours < 1) return "just now";
|
|
716
|
+
if (hours < 24) return `${hours}h ago`;
|
|
717
|
+
const days = Math.floor(hours / 24);
|
|
718
|
+
return `${days}d ago`;
|
|
719
|
+
};
|
|
720
|
+
let out = "\n---\n\n## \u{1F4DA} Related cached searches\n\n";
|
|
721
|
+
out += "The following previous searches may contain relevant supplementary information. ";
|
|
722
|
+
out += `Read a report with \`read ${cacheDir}/<slug>/report.md\` if the live results are insufficient.
|
|
723
|
+
|
|
724
|
+
`;
|
|
725
|
+
out += "| # | Query | Age | Why related |\n";
|
|
726
|
+
out += "|---|-------|-----|-------------|\n";
|
|
727
|
+
for (const [i, m] of matches.entries()) {
|
|
728
|
+
const queryTrunc = m.entry.query.length > 60 ? m.entry.query.slice(0, 57) + "..." : m.entry.query;
|
|
729
|
+
out += `| ${i + 1} | \`${queryTrunc}\` | ${age(m.entry.timestamp)} | ${m.relevance} |
|
|
730
|
+
`;
|
|
731
|
+
}
|
|
732
|
+
out += `
|
|
733
|
+
Cache directory: \`${cacheDir}/\`
|
|
734
|
+
`;
|
|
735
|
+
return out;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
// src/core/messages.ts
|
|
739
|
+
function appendDomainFilter(query, domains) {
|
|
740
|
+
if (!domains?.length) return query;
|
|
741
|
+
return query + " site:" + domains.join(" OR site:");
|
|
742
|
+
}
|
|
743
|
+
var WEB_SEARCH_ENGINES = /* @__PURE__ */ new Set([
|
|
744
|
+
"auto",
|
|
745
|
+
"native",
|
|
746
|
+
"exa",
|
|
747
|
+
"parallel",
|
|
748
|
+
"perplexity",
|
|
749
|
+
"firecrawl"
|
|
750
|
+
]);
|
|
751
|
+
function buildSearchPayloadPatch(settings, provider, domains) {
|
|
752
|
+
const ws = settings.searchWebSearch;
|
|
753
|
+
if (!ws?.enabled || provider !== "openrouter") return void 0;
|
|
754
|
+
const parameters = {};
|
|
755
|
+
if (ws.engine && ws.engine !== "auto" && WEB_SEARCH_ENGINES.has(ws.engine)) {
|
|
756
|
+
parameters.engine = ws.engine;
|
|
757
|
+
}
|
|
758
|
+
if (typeof ws.maxResults === "number" && Number.isFinite(ws.maxResults)) {
|
|
759
|
+
parameters.max_results = Math.min(25, Math.max(1, Math.round(ws.maxResults)));
|
|
760
|
+
}
|
|
761
|
+
if (ws.searchContextSize) parameters.search_context_size = ws.searchContextSize;
|
|
762
|
+
const allowed = [...ws.allowedDomains ?? [], ...domains ?? []].filter(
|
|
763
|
+
(d, i, arr) => arr.indexOf(d) === i
|
|
764
|
+
);
|
|
765
|
+
if (allowed.length > 0) parameters.allowed_domains = allowed;
|
|
766
|
+
if (ws.excludedDomains?.length) parameters.excluded_domains = [...ws.excludedDomains];
|
|
767
|
+
const serverTool = { type: "openrouter:web_search", parameters };
|
|
768
|
+
return (payload) => {
|
|
769
|
+
if (payload.tools) return payload;
|
|
770
|
+
return { ...payload, tools: [serverTool] };
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
function buildExtractionMessage(content, query, focusPrompt, maxChars) {
|
|
774
|
+
let msg = `Web page content:
|
|
775
|
+
---
|
|
776
|
+
${truncateContent(content, maxChars)}
|
|
777
|
+
---
|
|
778
|
+
|
|
779
|
+
`;
|
|
780
|
+
msg += `Extract information relevant to: ${query}
|
|
781
|
+
`;
|
|
782
|
+
if (focusPrompt) {
|
|
783
|
+
msg += `
|
|
784
|
+
Focus: ${focusPrompt}
|
|
785
|
+
`;
|
|
786
|
+
}
|
|
787
|
+
return msg;
|
|
788
|
+
}
|
|
789
|
+
function buildCollationMessage(query, cachePath, searchSummary, succeededExtractions) {
|
|
790
|
+
let msg = `Original query: ${query}
|
|
791
|
+
`;
|
|
792
|
+
msg += `Cache path: ${cachePath}/
|
|
793
|
+
|
|
794
|
+
`;
|
|
795
|
+
if (searchSummary) {
|
|
796
|
+
msg += `Search summary (from the search model):
|
|
797
|
+
${searchSummary}
|
|
798
|
+
|
|
799
|
+
`;
|
|
800
|
+
}
|
|
801
|
+
for (const [i, ext] of succeededExtractions.entries()) {
|
|
802
|
+
const filename = sourceFilename(i, ext.url);
|
|
803
|
+
msg += `--- Source ${i + 1}: ${ext.url} ---
|
|
804
|
+
`;
|
|
805
|
+
msg += `Title: ${ext.title}
|
|
806
|
+
`;
|
|
807
|
+
msg += `Type: ${ext.sourceType}
|
|
808
|
+
`;
|
|
809
|
+
msg += `Extraction file: ${cachePath}/extractions/${filename}
|
|
810
|
+
`;
|
|
811
|
+
msg += `Full page file: ${cachePath}/sources/${filename}
|
|
812
|
+
`;
|
|
813
|
+
msg += `
|
|
814
|
+
${ext.extraction}
|
|
815
|
+
|
|
816
|
+
`;
|
|
817
|
+
}
|
|
818
|
+
return msg;
|
|
819
|
+
}
|
|
820
|
+
function formatCacheAppendix(cachePath, succeeded, failed) {
|
|
821
|
+
let out = `
|
|
822
|
+
|
|
823
|
+
---
|
|
824
|
+
`;
|
|
825
|
+
out += `**Cache**: \`${cachePath}/\`
|
|
826
|
+
`;
|
|
827
|
+
out += `**Report**: \`${cachePath}/report.md\`
|
|
828
|
+
`;
|
|
829
|
+
out += `**Sources**: ${succeeded} succeeded, ${failed} failed
|
|
830
|
+
`;
|
|
831
|
+
out += `
|
|
832
|
+
To explore a specific source:
|
|
833
|
+
`;
|
|
834
|
+
out += `- Read the extraction: \`read ${cachePath}/extractions/01-*.md\`
|
|
835
|
+
`;
|
|
836
|
+
out += `- Read the full page: \`read ${cachePath}/sources/01-*.md\`
|
|
837
|
+
`;
|
|
838
|
+
return out;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
// src/core/operations/search.ts
|
|
842
|
+
async function search(params, context) {
|
|
843
|
+
const { settings, models, signal } = context;
|
|
844
|
+
throwIfAborted(signal);
|
|
845
|
+
const searchConfig = settings.searchModel;
|
|
846
|
+
const searchQuery = appendDomainFilter(params.query, params.domains);
|
|
847
|
+
const payloadPatch = buildSearchPayloadPatch(settings, searchConfig.provider, params.domains);
|
|
848
|
+
try {
|
|
849
|
+
const { text: responseText, citations } = await models.complete({
|
|
850
|
+
model: searchConfig,
|
|
851
|
+
systemPrompt: SEARCH_SYSTEM_PROMPT,
|
|
852
|
+
userMessage: searchQuery,
|
|
853
|
+
maxTokens: 2e3,
|
|
854
|
+
signal,
|
|
855
|
+
collectCitations: true,
|
|
856
|
+
payloadPatch,
|
|
857
|
+
reasoning: payloadPatch ? settings.searchWebSearch.reasoning ?? "low" : void 0
|
|
858
|
+
});
|
|
859
|
+
throwIfAborted(signal);
|
|
860
|
+
const sources = mergeCitations(extractSourceUrls(responseText), { citations }).slice(
|
|
861
|
+
0,
|
|
862
|
+
Math.max(1, settings.defaultUrls)
|
|
863
|
+
);
|
|
864
|
+
const result = {
|
|
865
|
+
summary: stripTrailingSourcesSection(responseText),
|
|
866
|
+
sources,
|
|
867
|
+
query: params.query,
|
|
868
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
869
|
+
};
|
|
870
|
+
return {
|
|
871
|
+
text: formatSearchResult(result),
|
|
872
|
+
outcome: "completed",
|
|
873
|
+
details: { sources, query: params.query }
|
|
874
|
+
};
|
|
875
|
+
} catch (err) {
|
|
876
|
+
throwIfAborted(signal);
|
|
877
|
+
throw new Error(`Search failed: ${err?.message ?? String(err)}`);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
function formatSearchResult(result) {
|
|
881
|
+
let output = `## Search results for: "${result.query}"
|
|
882
|
+
|
|
883
|
+
`;
|
|
884
|
+
output += result.summary + "\n\n";
|
|
885
|
+
output += `### Sources (${result.sources.length})
|
|
886
|
+
|
|
887
|
+
`;
|
|
888
|
+
for (const [i, source] of result.sources.entries()) {
|
|
889
|
+
output += `${i + 1}. [${source.title || source.url}](${source.url})
|
|
890
|
+
`;
|
|
891
|
+
}
|
|
892
|
+
return output;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
// src/core/operations/extract.ts
|
|
896
|
+
async function extract(params, context) {
|
|
897
|
+
const { settings, models, signal } = context;
|
|
898
|
+
throwIfAborted(signal);
|
|
899
|
+
const extractConfig = settings.extractModel;
|
|
900
|
+
const userMessage = buildExtractionMessage(
|
|
901
|
+
params.content,
|
|
902
|
+
params.query,
|
|
903
|
+
params.focusPrompt,
|
|
904
|
+
settings.extractMaxChars
|
|
905
|
+
);
|
|
906
|
+
const { text: extraction } = await models.complete({
|
|
907
|
+
model: extractConfig,
|
|
908
|
+
systemPrompt: EXTRACTION_SYSTEM_PROMPT,
|
|
909
|
+
userMessage,
|
|
910
|
+
maxTokens: settings.extractionMaxTokens,
|
|
911
|
+
signal
|
|
912
|
+
});
|
|
913
|
+
throwIfAborted(signal);
|
|
914
|
+
const firstLine = extraction.split("\n")[0] ?? "";
|
|
915
|
+
const sourceType = inferSourceType(firstLine);
|
|
916
|
+
const currentness = inferCurrentness(firstLine);
|
|
917
|
+
return {
|
|
918
|
+
text: `### Extraction: ${params.title}
|
|
919
|
+
|
|
920
|
+
${extraction}`,
|
|
921
|
+
outcome: "completed",
|
|
922
|
+
details: { url: params.url, extraction, sourceType, currentness }
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
// src/core/operations/collate.ts
|
|
927
|
+
async function collate(params, context) {
|
|
928
|
+
const { settings, models, signal } = context;
|
|
929
|
+
throwIfAborted(signal);
|
|
930
|
+
const collateConfig = settings.collateModel;
|
|
931
|
+
const paths = context.paths;
|
|
932
|
+
const physicalPath = makeCachePath(params.query, paths.workspaceRoot, paths.cacheRoot);
|
|
933
|
+
const cachePath = displayCachePath(paths, physicalPath);
|
|
934
|
+
const succeeded = params.extractions.filter((e) => e.status === "success");
|
|
935
|
+
const blocked = params.extractions.filter((e) => e.status !== "success");
|
|
936
|
+
const extractResults = params.extractions.map((e) => ({
|
|
937
|
+
url: e.url,
|
|
938
|
+
title: e.title,
|
|
939
|
+
extraction: e.extraction,
|
|
940
|
+
sourceType: e.sourceType,
|
|
941
|
+
currentness: "undated",
|
|
942
|
+
status: e.status
|
|
943
|
+
}));
|
|
944
|
+
const fetchedPages = (params.fullPages ?? []).map((p) => ({
|
|
945
|
+
url: p.url,
|
|
946
|
+
title: p.title,
|
|
947
|
+
content: p.content,
|
|
948
|
+
status: "success"
|
|
949
|
+
}));
|
|
950
|
+
const userMessage = buildCollationMessage(
|
|
951
|
+
params.query,
|
|
952
|
+
cachePath,
|
|
953
|
+
params.searchSummary,
|
|
954
|
+
extractResults.filter((e) => e.status === "success")
|
|
955
|
+
);
|
|
956
|
+
const { text: collation } = await models.complete({
|
|
957
|
+
model: collateConfig,
|
|
958
|
+
systemPrompt: COLLATION_SYSTEM_PROMPT,
|
|
959
|
+
userMessage,
|
|
960
|
+
maxTokens: settings.collationMaxTokens,
|
|
961
|
+
signal
|
|
962
|
+
});
|
|
963
|
+
await withLock(
|
|
964
|
+
cacheLockDir(physicalPath),
|
|
965
|
+
async () => {
|
|
966
|
+
await writeCacheFiles(
|
|
967
|
+
physicalPath,
|
|
968
|
+
extractResults,
|
|
969
|
+
fetchedPages,
|
|
970
|
+
params.searchSummary ?? "",
|
|
971
|
+
params.query
|
|
972
|
+
);
|
|
973
|
+
await writeReportFile(
|
|
974
|
+
physicalPath,
|
|
975
|
+
params.query,
|
|
976
|
+
collation,
|
|
977
|
+
extractResults,
|
|
978
|
+
fetchedPages,
|
|
979
|
+
cachePath
|
|
980
|
+
);
|
|
981
|
+
await withLock(
|
|
982
|
+
indexLockDir(paths.cacheRoot),
|
|
983
|
+
async () => {
|
|
984
|
+
const slug = physicalPath.split("/").pop() ?? physicalPath;
|
|
985
|
+
await updateIndex(paths.cacheRoot, slug, params.query);
|
|
986
|
+
},
|
|
987
|
+
signal
|
|
988
|
+
);
|
|
989
|
+
},
|
|
990
|
+
signal
|
|
991
|
+
);
|
|
992
|
+
return {
|
|
993
|
+
text: collation + formatCacheAppendix(cachePath, succeeded.length, blocked.length),
|
|
994
|
+
outcome: "completed",
|
|
995
|
+
details: { cachePath, sourcesFetched: succeeded.length + blocked.length }
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
// src/core/fetch.ts
|
|
1000
|
+
import { fetch as wreqFetch } from "wreq-js";
|
|
1001
|
+
import { Defuddle } from "defuddle/node";
|
|
1002
|
+
import { parseHTML } from "linkedom";
|
|
1003
|
+
import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
|
|
1004
|
+
import { join as join3 } from "node:path";
|
|
1005
|
+
var DEFAULT_FETCH_OPTIONS = {
|
|
1006
|
+
maxChars: 5e5,
|
|
1007
|
+
timeoutMs: 2e4,
|
|
1008
|
+
browser: "chrome_145",
|
|
1009
|
+
concurrency: 4
|
|
1010
|
+
};
|
|
1011
|
+
async function fetchSingle(url, opts, signal) {
|
|
1012
|
+
try {
|
|
1013
|
+
return await fetchWithComparison(url, opts, signal);
|
|
1014
|
+
} catch (err) {
|
|
1015
|
+
return {
|
|
1016
|
+
url,
|
|
1017
|
+
title: "",
|
|
1018
|
+
content: "",
|
|
1019
|
+
status: "error",
|
|
1020
|
+
error: errMsg(err)
|
|
1021
|
+
};
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
async function fetchWithComparison(url, opts, signal) {
|
|
1025
|
+
const [defuddleRes, markdownRes] = await Promise.allSettled([
|
|
1026
|
+
fetchViaDefuddle(url, opts, signal),
|
|
1027
|
+
fetchMarkdownVariant(url, opts, signal)
|
|
1028
|
+
]);
|
|
1029
|
+
const defuddlePage = defuddleRes.status === "fulfilled" ? defuddleRes.value : null;
|
|
1030
|
+
const markdownPage = markdownRes.status === "fulfilled" ? markdownRes.value : null;
|
|
1031
|
+
if (defuddlePage && markdownPage) {
|
|
1032
|
+
return compareAndPick(defuddlePage, markdownPage);
|
|
1033
|
+
}
|
|
1034
|
+
const onlyPage = defuddlePage ?? markdownPage;
|
|
1035
|
+
if (onlyPage) return onlyPage;
|
|
1036
|
+
const reason = (defuddleRes.status === "rejected" ? defuddleRes.reason : null) ?? (markdownRes.status === "rejected" ? markdownRes.reason : null) ?? new Error("Both fetch pipelines failed");
|
|
1037
|
+
throw reason;
|
|
1038
|
+
}
|
|
1039
|
+
function compareAndPick(a, b) {
|
|
1040
|
+
const aScore = scoreContent(a.content);
|
|
1041
|
+
const bScore = scoreContent(b.content);
|
|
1042
|
+
if (bScore > aScore) {
|
|
1043
|
+
return { ...b, status: "success", source: "markdown" };
|
|
1044
|
+
}
|
|
1045
|
+
return { ...a, status: "success", source: "defuddle" };
|
|
1046
|
+
}
|
|
1047
|
+
function scoreContent(content) {
|
|
1048
|
+
let score = content.length;
|
|
1049
|
+
score += (content.match(/```/g) ?? []).length * 100;
|
|
1050
|
+
score += (content.match(/^#{1,6}\s/gm) ?? []).length * 50;
|
|
1051
|
+
score += (content.match(/^\|/gm) ?? []).length * 20;
|
|
1052
|
+
score -= (content.match(/Skip to content|Was this helpful|Edit page|Report issue|Copy page/g) ?? []).length * 500;
|
|
1053
|
+
if (content.startsWith("---")) score -= 1e3;
|
|
1054
|
+
return score;
|
|
1055
|
+
}
|
|
1056
|
+
var DEFUDDLE_MUZZLE_TAGS = {
|
|
1057
|
+
error: ["Defuddle"],
|
|
1058
|
+
warn: ["Failed to parse URL:", "Failed to parse base URL:"]
|
|
1059
|
+
};
|
|
1060
|
+
async function fetchViaDefuddle(url, opts, signal) {
|
|
1061
|
+
const response = await rawFetch(url, opts, signal);
|
|
1062
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
1063
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
1064
|
+
if (!contentType.includes("text/html") && !contentType.includes("application/xhtml")) {
|
|
1065
|
+
throw new Error(`Not HTML: ${contentType}`);
|
|
1066
|
+
}
|
|
1067
|
+
const body = await response.text();
|
|
1068
|
+
const { document } = parseHTML(body);
|
|
1069
|
+
cleanBrokenMetadata(document, url);
|
|
1070
|
+
let extracted;
|
|
1071
|
+
let degraded = false;
|
|
1072
|
+
try {
|
|
1073
|
+
const out = await withMuzzledConsole(
|
|
1074
|
+
() => Defuddle(document, url, { markdown: true }),
|
|
1075
|
+
DEFUDDLE_MUZZLE_TAGS
|
|
1076
|
+
);
|
|
1077
|
+
extracted = out.value;
|
|
1078
|
+
degraded = out.muzzled;
|
|
1079
|
+
} catch {
|
|
1080
|
+
degraded = true;
|
|
1081
|
+
}
|
|
1082
|
+
if (degraded || !extracted) {
|
|
1083
|
+
const title2 = document.querySelector("title")?.textContent?.trim() ?? "";
|
|
1084
|
+
const metaDesc = document.querySelector('meta[name="description"]')?.getAttribute("content")?.trim() ?? "";
|
|
1085
|
+
const bodyText2 = document.body?.textContent?.replace(/\s+/g, " ").trim() ?? "";
|
|
1086
|
+
const content2 = [
|
|
1087
|
+
`# ${title2}`,
|
|
1088
|
+
metaDesc ? `> ${metaDesc}` : "",
|
|
1089
|
+
bodyText2.length > 0 ? bodyText2 : "(No parseable text content)"
|
|
1090
|
+
].filter(Boolean).join("\n\n");
|
|
1091
|
+
return {
|
|
1092
|
+
url,
|
|
1093
|
+
title: title2,
|
|
1094
|
+
content: truncateContent(content2, opts.maxChars),
|
|
1095
|
+
status: "success",
|
|
1096
|
+
source: "defuddle-fallback"
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
const title = extracted.title ?? "";
|
|
1100
|
+
const content = extracted.contentMarkdown ?? extracted.content ?? body;
|
|
1101
|
+
return {
|
|
1102
|
+
url,
|
|
1103
|
+
title,
|
|
1104
|
+
content: truncateContent(content, opts.maxChars),
|
|
1105
|
+
status: "success",
|
|
1106
|
+
source: "defuddle"
|
|
1107
|
+
};
|
|
1108
|
+
}
|
|
1109
|
+
async function fetchMarkdownVariant(url, opts, signal) {
|
|
1110
|
+
const acceptResult = await fetchWithAcceptHeader(url, opts, signal);
|
|
1111
|
+
if (acceptResult) return acceptResult;
|
|
1112
|
+
const mdUrl = await findMarkdownAlternate(url, opts, signal);
|
|
1113
|
+
if (mdUrl) return await fetchMarkdown(mdUrl, opts, signal);
|
|
1114
|
+
return null;
|
|
1115
|
+
}
|
|
1116
|
+
async function fetchWithAcceptHeader(url, opts, signal) {
|
|
1117
|
+
try {
|
|
1118
|
+
const combinedSignal = combineSignal(signal, opts.timeoutMs);
|
|
1119
|
+
const response = await wreqFetch(url, {
|
|
1120
|
+
browser: opts.browser,
|
|
1121
|
+
os: "windows",
|
|
1122
|
+
headers: { Accept: "text/markdown" },
|
|
1123
|
+
proxy: opts.proxy,
|
|
1124
|
+
signal: combinedSignal
|
|
1125
|
+
});
|
|
1126
|
+
if (!response.ok) return null;
|
|
1127
|
+
if (!response.headers.get("content-type")?.includes("text/markdown")) return null;
|
|
1128
|
+
return processMarkdownResponse(url, response, opts);
|
|
1129
|
+
} catch {
|
|
1130
|
+
return null;
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
async function findMarkdownAlternate(url, opts, signal) {
|
|
1134
|
+
try {
|
|
1135
|
+
const response = await rawFetch(url, opts, signal);
|
|
1136
|
+
if (!response.ok) return null;
|
|
1137
|
+
if (!response.headers.get("content-type")?.includes("text/html")) return null;
|
|
1138
|
+
const html = await response.text();
|
|
1139
|
+
const { document } = parseHTML(html);
|
|
1140
|
+
const links = document.querySelectorAll('link[rel="alternate"][type="text/markdown"]');
|
|
1141
|
+
for (const link of Array.from(links)) {
|
|
1142
|
+
const href = link.getAttribute("href");
|
|
1143
|
+
if (href) return new URL(href, url).href;
|
|
1144
|
+
}
|
|
1145
|
+
return null;
|
|
1146
|
+
} catch {
|
|
1147
|
+
return null;
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
async function fetchMarkdown(mdUrl, opts, signal) {
|
|
1151
|
+
const response = await rawFetch(mdUrl, opts, signal);
|
|
1152
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
1153
|
+
return processMarkdownResponse(mdUrl, response, opts);
|
|
1154
|
+
}
|
|
1155
|
+
async function processMarkdownResponse(url, response, opts) {
|
|
1156
|
+
let content = await response.text();
|
|
1157
|
+
content = sanitizeMarkdown(content);
|
|
1158
|
+
return {
|
|
1159
|
+
url,
|
|
1160
|
+
title: guessTitleFromMarkdown(content) || "",
|
|
1161
|
+
content: truncateContent(content, opts.maxChars),
|
|
1162
|
+
status: "success",
|
|
1163
|
+
source: "markdown"
|
|
1164
|
+
};
|
|
1165
|
+
}
|
|
1166
|
+
var LLMS_FULL_TIMEOUT_MS = 1e4;
|
|
1167
|
+
var BUILTIN_LLMS_FULL_SITES = {
|
|
1168
|
+
"developers.cloudflare.com": (url) => {
|
|
1169
|
+
const match = new URL(url).pathname.match(/^\/([^/]+)\//);
|
|
1170
|
+
if (match) {
|
|
1171
|
+
return `https://developers.cloudflare.com/${match[1]}/llms-full.txt`;
|
|
1172
|
+
}
|
|
1173
|
+
return null;
|
|
1174
|
+
},
|
|
1175
|
+
"nextjs.org": () => `https://nextjs.org/docs/llms-full.txt`,
|
|
1176
|
+
"vite.dev": () => `https://vite.dev/llms-full.txt`
|
|
1177
|
+
};
|
|
1178
|
+
async function downloadLlmsFullToCache(url, cachePath, signal, timeoutMs = LLMS_FULL_TIMEOUT_MS, proxy) {
|
|
1179
|
+
if (signal?.aborted) return null;
|
|
1180
|
+
const hostname = safeHostname(url);
|
|
1181
|
+
if (!hostname) return null;
|
|
1182
|
+
const builder = BUILTIN_LLMS_FULL_SITES[hostname];
|
|
1183
|
+
let llmsFullUrl = builder ? builder(url) : null;
|
|
1184
|
+
if (!llmsFullUrl) {
|
|
1185
|
+
llmsFullUrl = `https://${hostname}/llms-full.txt`;
|
|
1186
|
+
}
|
|
1187
|
+
return downloadLlmsFullFile(llmsFullUrl, hostname, cachePath, timeoutMs, signal, proxy);
|
|
1188
|
+
}
|
|
1189
|
+
async function downloadLlmsFullFile(llmsFullUrl, hostname, cachePath, timeoutMs, signal, proxy) {
|
|
1190
|
+
try {
|
|
1191
|
+
const response = await wreqFetch(llmsFullUrl, {
|
|
1192
|
+
browser: "chrome_145",
|
|
1193
|
+
os: "windows",
|
|
1194
|
+
proxy,
|
|
1195
|
+
signal: combineSignal(signal, timeoutMs)
|
|
1196
|
+
});
|
|
1197
|
+
if (!response.ok) return null;
|
|
1198
|
+
const content = await response.text();
|
|
1199
|
+
if (content.length === 0) return null;
|
|
1200
|
+
const fullCachePath = join3(cachePath, "sources");
|
|
1201
|
+
await mkdir2(fullCachePath, { recursive: true });
|
|
1202
|
+
const filename = `llms-full-${hostname}.md`;
|
|
1203
|
+
const filepath = join3(fullCachePath, filename);
|
|
1204
|
+
await writeFile2(filepath, content);
|
|
1205
|
+
return filepath;
|
|
1206
|
+
} catch {
|
|
1207
|
+
return null;
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
function combineSignal(external, timeoutMs) {
|
|
1211
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
1212
|
+
if (external) {
|
|
1213
|
+
return AbortSignal.any([external, timeout]);
|
|
1214
|
+
}
|
|
1215
|
+
return timeout;
|
|
1216
|
+
}
|
|
1217
|
+
async function rawFetch(url, opts, signal) {
|
|
1218
|
+
return wreqFetch(url, {
|
|
1219
|
+
browser: opts.browser,
|
|
1220
|
+
os: "windows",
|
|
1221
|
+
proxy: opts.proxy,
|
|
1222
|
+
signal: combineSignal(signal, opts.timeoutMs)
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
function guessTitleFromMarkdown(content) {
|
|
1226
|
+
const frontmatter = content.match(/^---\n([\s\S]*?)\n---/);
|
|
1227
|
+
if (frontmatter) {
|
|
1228
|
+
const titleMatch = frontmatter[1].match(/^title:\s*(.+)$/m);
|
|
1229
|
+
if (titleMatch) return titleMatch[1].trim().replace(/^["']|["']$/g, "");
|
|
1230
|
+
}
|
|
1231
|
+
const headingMatch = content.match(/^#\s+(.+)$/m);
|
|
1232
|
+
if (headingMatch) return headingMatch[1].trim();
|
|
1233
|
+
return "";
|
|
1234
|
+
}
|
|
1235
|
+
function sanitizeMarkdown(content) {
|
|
1236
|
+
content = content.replace(/^---\n[\s\S]*?\n---\s*\n/, "");
|
|
1237
|
+
content = content.replace(/\[Skip to content\].*?\n/g, "");
|
|
1238
|
+
content = content.replace(/Was this helpful\?\s*\n\s*YesNo\s*\n/g, "");
|
|
1239
|
+
content = content.replace(/^Copy (?:page|for LLM|for AI)\n/gm, "");
|
|
1240
|
+
content = content.replace(/\[\s*Edit page\s*\]\([^)]*\)/g, "");
|
|
1241
|
+
content = content.replace(/\[\s*Report issue\s*\]\([^)]*\)/g, "");
|
|
1242
|
+
content = content.replace(/^Edit on GitHub\s*\n/gm, "");
|
|
1243
|
+
content = content.replace(/\n{3,}/g, "\n\n");
|
|
1244
|
+
return content.trim();
|
|
1245
|
+
}
|
|
1246
|
+
function cleanBrokenMetadata(document, pageUrl) {
|
|
1247
|
+
const elements = document.querySelectorAll("meta[content], link[href], a[href]");
|
|
1248
|
+
for (const el of Array.from(elements)) {
|
|
1249
|
+
const tag = el.tagName.toLowerCase();
|
|
1250
|
+
for (const attr of tag === "meta" ? ["content"] : ["href"]) {
|
|
1251
|
+
const val = el.getAttribute(attr);
|
|
1252
|
+
if (!val) continue;
|
|
1253
|
+
if (/^(undefined|null)$/i.test(val)) {
|
|
1254
|
+
el.remove();
|
|
1255
|
+
break;
|
|
1256
|
+
}
|
|
1257
|
+
try {
|
|
1258
|
+
new URL(val);
|
|
1259
|
+
} catch {
|
|
1260
|
+
try {
|
|
1261
|
+
const resolved = new URL(val, pageUrl).href;
|
|
1262
|
+
el.setAttribute(attr, resolved);
|
|
1263
|
+
} catch {
|
|
1264
|
+
el.remove();
|
|
1265
|
+
break;
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
const ldJsonScripts = document.querySelectorAll('script[type="application/ld+json"]');
|
|
1271
|
+
for (const script of Array.from(ldJsonScripts)) {
|
|
1272
|
+
const text = script.textContent?.trim();
|
|
1273
|
+
if (!text) {
|
|
1274
|
+
script.remove();
|
|
1275
|
+
continue;
|
|
1276
|
+
}
|
|
1277
|
+
try {
|
|
1278
|
+
JSON.parse(text);
|
|
1279
|
+
} catch {
|
|
1280
|
+
script.remove();
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
function safeHostname(url) {
|
|
1285
|
+
try {
|
|
1286
|
+
return new URL(url).hostname;
|
|
1287
|
+
} catch {
|
|
1288
|
+
return null;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
async function fetchPages(urls, signal, opts) {
|
|
1292
|
+
const fullOpts = { ...DEFAULT_FETCH_OPTIONS, ...opts };
|
|
1293
|
+
const results = await mapWithConcurrency(
|
|
1294
|
+
urls,
|
|
1295
|
+
fullOpts.concurrency,
|
|
1296
|
+
(url) => fetchSingle(url, fullOpts, signal),
|
|
1297
|
+
{ signal }
|
|
1298
|
+
);
|
|
1299
|
+
return results.map(
|
|
1300
|
+
(r, i) => r ?? {
|
|
1301
|
+
url: urls[i],
|
|
1302
|
+
title: "",
|
|
1303
|
+
content: "",
|
|
1304
|
+
status: "error",
|
|
1305
|
+
error: "Worker did not complete"
|
|
1306
|
+
}
|
|
1307
|
+
);
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
// src/core/telemetry.ts
|
|
1311
|
+
import { writeFile as writeFile3, rename as rename2, readdir as readdir2, unlink } from "node:fs/promises";
|
|
1312
|
+
import { join as join4 } from "node:path";
|
|
1313
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
1314
|
+
var SCHEMA_VERSION = 1;
|
|
1315
|
+
var TelemetryBuilder = class _TelemetryBuilder {
|
|
1316
|
+
constructor(identity2, query, now) {
|
|
1317
|
+
this.now = now;
|
|
1318
|
+
this.start = now();
|
|
1319
|
+
this.meta = {
|
|
1320
|
+
schemaVersion: SCHEMA_VERSION,
|
|
1321
|
+
extensionVersion: identity2.version,
|
|
1322
|
+
...identity2.adapter === "pi" ? {} : { packageName: identity2.name, adapter: identity2.adapter },
|
|
1323
|
+
query,
|
|
1324
|
+
timestamp: new Date(this.start).toISOString(),
|
|
1325
|
+
durationMs: 0,
|
|
1326
|
+
outcome: "completed",
|
|
1327
|
+
stages: {
|
|
1328
|
+
search: { model: "", linksReturned: 0, retryFired: false, attempts: 0, degraded: false },
|
|
1329
|
+
fetch: { requested: 0, succeeded: 0, failed: 0, winners: {} },
|
|
1330
|
+
extract: {
|
|
1331
|
+
model: "",
|
|
1332
|
+
succeeded: 0,
|
|
1333
|
+
failed: 0,
|
|
1334
|
+
totalInputCharsApprox: 0,
|
|
1335
|
+
totalOutputChars: 0
|
|
1336
|
+
},
|
|
1337
|
+
collate: { model: "", summaryChars: 0 },
|
|
1338
|
+
cacheSuggest: { ran: false, surfaced: 0, slugs: [] }
|
|
1339
|
+
}
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
now;
|
|
1343
|
+
start;
|
|
1344
|
+
meta;
|
|
1345
|
+
/** Identity is supplied by the emitting adapter, never discovered from core paths. */
|
|
1346
|
+
static async create(query, identity2, now = Date.now) {
|
|
1347
|
+
return new _TelemetryBuilder(identity2, query, now);
|
|
1348
|
+
}
|
|
1349
|
+
recordSearch(input) {
|
|
1350
|
+
this.meta.stages.search = { degraded: false, ...input };
|
|
1351
|
+
}
|
|
1352
|
+
recordFetch(input) {
|
|
1353
|
+
this.meta.stages.fetch = { ...input };
|
|
1354
|
+
}
|
|
1355
|
+
recordExtract(input) {
|
|
1356
|
+
this.meta.stages.extract = { ...input };
|
|
1357
|
+
}
|
|
1358
|
+
recordCollate(input) {
|
|
1359
|
+
this.meta.stages.collate = { ...input };
|
|
1360
|
+
}
|
|
1361
|
+
recordCacheSuggest(input) {
|
|
1362
|
+
this.meta.stages.cacheSuggest = { ...input };
|
|
1363
|
+
}
|
|
1364
|
+
/** Record which exit path produced this sidecar. Call at every return
|
|
1365
|
+
* point so the analysis script can bucket degraded runs. */
|
|
1366
|
+
setOutcome(outcome) {
|
|
1367
|
+
this.meta.outcome = outcome;
|
|
1368
|
+
}
|
|
1369
|
+
/** Stamp duration and return the immutable payload. */
|
|
1370
|
+
finalize() {
|
|
1371
|
+
this.meta.durationMs = this.now() - this.start;
|
|
1372
|
+
return this.meta;
|
|
1373
|
+
}
|
|
1374
|
+
};
|
|
1375
|
+
async function writeTelemetry(cachePath, meta) {
|
|
1376
|
+
await sweepStaleTempFiles(cachePath);
|
|
1377
|
+
const target = join4(cachePath, "meta.json");
|
|
1378
|
+
const tmp = join4(cachePath, `.meta.json.${process.pid}.${randomBytes2(4).toString("hex")}.tmp`);
|
|
1379
|
+
await writeFile3(tmp, JSON.stringify(meta, null, 2) + "\n", "utf-8");
|
|
1380
|
+
await rename2(tmp, target);
|
|
1381
|
+
}
|
|
1382
|
+
async function sweepStaleTempFiles(cachePath) {
|
|
1383
|
+
let entries;
|
|
1384
|
+
try {
|
|
1385
|
+
entries = await readdir2(cachePath);
|
|
1386
|
+
} catch {
|
|
1387
|
+
return;
|
|
1388
|
+
}
|
|
1389
|
+
await Promise.all(
|
|
1390
|
+
entries.filter((e) => /^\.meta\.json\..*\.tmp$/.test(e)).map((e) => unlink(join4(cachePath, e)).catch(() => {
|
|
1391
|
+
}))
|
|
1392
|
+
);
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
// src/core/operations/research.ts
|
|
1396
|
+
import { mkdir as mkdir3, writeFile as writeFile4, rm as rm2, readdir as readdir3, readFile as readFile2, mkdtemp } from "node:fs/promises";
|
|
1397
|
+
import { join as join5 } from "node:path";
|
|
1398
|
+
|
|
1399
|
+
// src/core/progress.ts
|
|
1400
|
+
var STAGES = ["search", "fetch", "extract", "collate", "cache"];
|
|
1401
|
+
function progress(stage, message, subProgress) {
|
|
1402
|
+
const stageIdx = STAGES.indexOf(stage);
|
|
1403
|
+
return {
|
|
1404
|
+
stage,
|
|
1405
|
+
stageIdx,
|
|
1406
|
+
totalStages: STAGES.length,
|
|
1407
|
+
message,
|
|
1408
|
+
pct: Math.round((stageIdx + 1) / STAGES.length * 100),
|
|
1409
|
+
...subProgress ? { subProgress } : {}
|
|
1410
|
+
};
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
// src/core/operations/research.ts
|
|
1414
|
+
var MissingModelsError = class extends Error {
|
|
1415
|
+
constructor(bindings) {
|
|
1416
|
+
super(
|
|
1417
|
+
`Configured model(s) not found: ${bindings.map(({ role, config }) => `${role}: ${config.provider}/${config.model}`).join(", ")}`
|
|
1418
|
+
);
|
|
1419
|
+
this.bindings = bindings;
|
|
1420
|
+
}
|
|
1421
|
+
bindings;
|
|
1422
|
+
};
|
|
1423
|
+
async function preflightResearch(context) {
|
|
1424
|
+
const missing = await context.models.preflight([
|
|
1425
|
+
{ role: "search", config: context.settings.searchModel },
|
|
1426
|
+
{ role: "extract", config: context.settings.extractModel },
|
|
1427
|
+
{ role: "collate", config: context.settings.collateModel }
|
|
1428
|
+
]);
|
|
1429
|
+
if (missing.length) throw new MissingModelsError(missing);
|
|
1430
|
+
}
|
|
1431
|
+
async function research(params, context, dependencies = { fetchPages, downloadLlmsFullToCache }) {
|
|
1432
|
+
throwIfAborted(context.signal);
|
|
1433
|
+
await preflightResearch(context);
|
|
1434
|
+
throwIfAborted(context.signal);
|
|
1435
|
+
const { settings, paths } = context;
|
|
1436
|
+
const physicalCachePath = makeCachePath(params.query, paths.workspaceRoot, paths.cacheRoot);
|
|
1437
|
+
return executePipeline({
|
|
1438
|
+
...context,
|
|
1439
|
+
signal: context.signal,
|
|
1440
|
+
dependencies,
|
|
1441
|
+
params,
|
|
1442
|
+
physicalCachePath,
|
|
1443
|
+
cachePath: displayCachePath(paths, physicalCachePath),
|
|
1444
|
+
maxUrls: Math.min(params.maxUrls ?? settings.defaultUrls, settings.maxUrls),
|
|
1445
|
+
retry: {
|
|
1446
|
+
attempts: settings.llmRetryAttempts,
|
|
1447
|
+
baseDelayMs: settings.retryBaseDelayMs,
|
|
1448
|
+
maxDelayMs: settings.retryMaxDelayMs
|
|
1449
|
+
},
|
|
1450
|
+
gate: createRateLimiter(settings.minRequestIntervalMs),
|
|
1451
|
+
tel: settings.disableTelemetry ? null : await TelemetryBuilder.create(params.query, context.identity, context.now),
|
|
1452
|
+
searchConfig: settings.searchModel,
|
|
1453
|
+
extractConfig: settings.extractModel,
|
|
1454
|
+
collateConfig: settings.collateModel
|
|
1455
|
+
});
|
|
1456
|
+
}
|
|
1457
|
+
async function executePipeline(p) {
|
|
1458
|
+
const search2 = await runSearchStage(p);
|
|
1459
|
+
if (search2.urls.length === 0) {
|
|
1460
|
+
return degradedReturn(
|
|
1461
|
+
p,
|
|
1462
|
+
"no-links",
|
|
1463
|
+
`Search returned no links for query: "${p.params.query}" after ${search2.maxAttempts} attempt(s). This is a degraded search response (the model replied without markdown links), not a fetch or extraction failure.
|
|
1464
|
+
|
|
1465
|
+
Search summary:
|
|
1466
|
+
${search2.searchResult}`,
|
|
1467
|
+
{ cachePath: "", urlsSearched: 0, pagesFetched: 0, pagesFailed: 0 }
|
|
1468
|
+
);
|
|
1469
|
+
}
|
|
1470
|
+
const fetched = await runFetchStage(p, search2.urls);
|
|
1471
|
+
throwIfAborted(p.signal);
|
|
1472
|
+
if (fetched.successPages.length === 0) {
|
|
1473
|
+
return degradedReturn(
|
|
1474
|
+
p,
|
|
1475
|
+
"fetch-failed",
|
|
1476
|
+
`All ${search2.urls.length} pages failed to fetch.
|
|
1477
|
+
|
|
1478
|
+
Search summary:
|
|
1479
|
+
${search2.searchResult}`,
|
|
1480
|
+
{
|
|
1481
|
+
cachePath: "",
|
|
1482
|
+
urlsSearched: search2.urls.length,
|
|
1483
|
+
pagesFetched: 0,
|
|
1484
|
+
pagesFailed: search2.urls.length
|
|
1485
|
+
}
|
|
1486
|
+
);
|
|
1487
|
+
}
|
|
1488
|
+
const extracted = await runExtractStage(p, fetched.successPages, fetched.pages);
|
|
1489
|
+
throwIfAborted(p.signal);
|
|
1490
|
+
p.onProgress?.(progress("collate", "Synthesising results..."));
|
|
1491
|
+
const allExtractions = [...extracted.extractions, ...extracted.blockedExtractions];
|
|
1492
|
+
const succeededExtractions = allExtractions.filter((e) => e.status === "success");
|
|
1493
|
+
if (succeededExtractions.length === 0) {
|
|
1494
|
+
const fetchFailed = extracted.blockedExtractions.length;
|
|
1495
|
+
const extractFailed = extracted.extractions.filter((e) => e.status === "failed").length;
|
|
1496
|
+
const reason = fetchFailed > 0 ? `${fetchFailed} page(s) failed to fetch` : `${extractFailed} extraction(s) failed`;
|
|
1497
|
+
return degradedReturn(
|
|
1498
|
+
p,
|
|
1499
|
+
"extraction-failed",
|
|
1500
|
+
`${reason}. No content was extracted.
|
|
1501
|
+
|
|
1502
|
+
Search summary:
|
|
1503
|
+
${search2.searchResult}`,
|
|
1504
|
+
{
|
|
1505
|
+
cachePath: "",
|
|
1506
|
+
urlsSearched: search2.urls.length,
|
|
1507
|
+
pagesFetched: fetched.successPages.length,
|
|
1508
|
+
pagesFailed: fetched.pages.length - fetched.successPages.length
|
|
1509
|
+
}
|
|
1510
|
+
);
|
|
1511
|
+
}
|
|
1512
|
+
const collation = await runCollateStage(p, search2.searchResult, succeededExtractions);
|
|
1513
|
+
throwIfAborted(p.signal);
|
|
1514
|
+
const llms = await startLlmsFullDownloads(p, fetched.successPages);
|
|
1515
|
+
try {
|
|
1516
|
+
await writeCacheArtifacts(p, allExtractions, fetched, search2.searchResult, collation, llms);
|
|
1517
|
+
} finally {
|
|
1518
|
+
llms.abort.abort();
|
|
1519
|
+
await Promise.allSettled(llms.futures);
|
|
1520
|
+
if (llms.staging) {
|
|
1521
|
+
try {
|
|
1522
|
+
if (p.dependencies.removeStaging) await p.dependencies.removeStaging(llms.staging);
|
|
1523
|
+
else await rm2(llms.staging, { recursive: true, force: true });
|
|
1524
|
+
} catch (error) {
|
|
1525
|
+
p.logger.error(`Documentation staging cleanup failed: ${errMsg(error)}`);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
const suggestionsAppendix = await runCacheSuggestStage(p);
|
|
1530
|
+
throwIfAborted(p.signal);
|
|
1531
|
+
await writeLockedTelemetry(p, "completed");
|
|
1532
|
+
const failedCount = fetched.pages.length - fetched.successPages.length;
|
|
1533
|
+
const result = collation + formatCacheAppendix(p.cachePath, fetched.successPages.length, failedCount) + suggestionsAppendix;
|
|
1534
|
+
return {
|
|
1535
|
+
text: result,
|
|
1536
|
+
outcome: "completed",
|
|
1537
|
+
details: {
|
|
1538
|
+
cachePath: p.cachePath,
|
|
1539
|
+
urlsSearched: search2.urls.length,
|
|
1540
|
+
pagesFetched: fetched.successPages.length,
|
|
1541
|
+
pagesFailed: failedCount
|
|
1542
|
+
}
|
|
1543
|
+
};
|
|
1544
|
+
}
|
|
1545
|
+
async function runSearchStage(p) {
|
|
1546
|
+
p.onProgress?.(
|
|
1547
|
+
progress("search", `Querying ${p.searchConfig.provider}/${p.searchConfig.model}...`)
|
|
1548
|
+
);
|
|
1549
|
+
const searchQuery = appendDomainFilter(p.params.query, p.params.domains);
|
|
1550
|
+
let searchResult = "";
|
|
1551
|
+
let urls = [];
|
|
1552
|
+
const maxAttempts = Math.max(1, p.settings.searchRetryAttempts);
|
|
1553
|
+
let attemptsUsed = 0;
|
|
1554
|
+
let annotationsHarvested = 0;
|
|
1555
|
+
const payloadPatch = buildSearchPayloadPatch(
|
|
1556
|
+
p.settings,
|
|
1557
|
+
p.searchConfig.provider,
|
|
1558
|
+
p.params.domains
|
|
1559
|
+
);
|
|
1560
|
+
const searchReasoning = payloadPatch ? p.settings.searchWebSearch.reasoning ?? "low" : void 0;
|
|
1561
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
1562
|
+
throwIfAborted(p.signal);
|
|
1563
|
+
attemptsUsed = attempt;
|
|
1564
|
+
const completion = await p.models.complete({
|
|
1565
|
+
model: p.searchConfig,
|
|
1566
|
+
systemPrompt: SEARCH_SYSTEM_PROMPT,
|
|
1567
|
+
userMessage: searchQuery,
|
|
1568
|
+
maxTokens: 2e3,
|
|
1569
|
+
signal: p.signal,
|
|
1570
|
+
retry: p.retry,
|
|
1571
|
+
timeoutMs: p.settings.llmTimeoutMs,
|
|
1572
|
+
collectCitations: true,
|
|
1573
|
+
payloadPatch,
|
|
1574
|
+
reasoning: searchReasoning,
|
|
1575
|
+
onRetryNotice: (msg) => p.onProgress?.(progress("search", msg))
|
|
1576
|
+
});
|
|
1577
|
+
searchResult = completion.text;
|
|
1578
|
+
annotationsHarvested = completion.citations.length;
|
|
1579
|
+
urls = mergeCitations(extractSourceUrls(searchResult), completion).slice(0, p.maxUrls);
|
|
1580
|
+
if (urls.length > 0 || p.signal?.aborted || attempt === maxAttempts) break;
|
|
1581
|
+
p.onProgress?.(
|
|
1582
|
+
progress("search", `Search returned no links \u2014 retrying (${attempt}/${maxAttempts - 1})...`)
|
|
1583
|
+
);
|
|
1584
|
+
await sleep(p.settings.retryBaseDelayMs, p.signal);
|
|
1585
|
+
}
|
|
1586
|
+
if (p.signal?.aborted) {
|
|
1587
|
+
throw new DOMException("Aborted", "AbortError");
|
|
1588
|
+
}
|
|
1589
|
+
searchResult = stripTrailingSourcesSection(searchResult);
|
|
1590
|
+
p.tel?.recordSearch({
|
|
1591
|
+
model: `${p.searchConfig.provider}/${p.searchConfig.model}`,
|
|
1592
|
+
linksReturned: urls.length,
|
|
1593
|
+
retryFired: attemptsUsed > 1,
|
|
1594
|
+
attempts: attemptsUsed,
|
|
1595
|
+
degraded: urls.length === 0,
|
|
1596
|
+
annotationsHarvested
|
|
1597
|
+
});
|
|
1598
|
+
return { searchResult, urls, attemptsUsed, maxAttempts };
|
|
1599
|
+
}
|
|
1600
|
+
async function runFetchStage(p, urls) {
|
|
1601
|
+
p.onProgress?.(progress("fetch", `Fetching ${urls.length} pages...`));
|
|
1602
|
+
throwIfAborted(p.signal);
|
|
1603
|
+
const pages = await p.dependencies.fetchPages(
|
|
1604
|
+
urls.map((u) => u.url),
|
|
1605
|
+
p.signal,
|
|
1606
|
+
{
|
|
1607
|
+
timeoutMs: p.settings.fetchTimeoutMs,
|
|
1608
|
+
browser: p.settings.browserFingerprint,
|
|
1609
|
+
concurrency: p.settings.fetchConcurrency,
|
|
1610
|
+
proxy: p.settings.httpProxy
|
|
1611
|
+
}
|
|
1612
|
+
);
|
|
1613
|
+
const successPages = pages.filter((pg) => pg.status === "success");
|
|
1614
|
+
const fetchWinners = {};
|
|
1615
|
+
for (const pg of successPages) {
|
|
1616
|
+
const variant = pg.source ?? "unknown";
|
|
1617
|
+
fetchWinners[variant] = (fetchWinners[variant] ?? 0) + 1;
|
|
1618
|
+
}
|
|
1619
|
+
p.tel?.recordFetch({
|
|
1620
|
+
requested: urls.length,
|
|
1621
|
+
succeeded: successPages.length,
|
|
1622
|
+
failed: pages.length - successPages.length,
|
|
1623
|
+
winners: fetchWinners
|
|
1624
|
+
});
|
|
1625
|
+
return { pages, successPages };
|
|
1626
|
+
}
|
|
1627
|
+
async function runExtractStage(p, successPages, pages) {
|
|
1628
|
+
p.onProgress?.(
|
|
1629
|
+
progress("extract", `Extracting from ${successPages.length} pages...`, {
|
|
1630
|
+
current: 0,
|
|
1631
|
+
total: successPages.length
|
|
1632
|
+
})
|
|
1633
|
+
);
|
|
1634
|
+
let extractDone = 0;
|
|
1635
|
+
const rawExtractions = await mapWithConcurrency(
|
|
1636
|
+
successPages,
|
|
1637
|
+
p.settings.extractionConcurrency,
|
|
1638
|
+
async (page) => {
|
|
1639
|
+
await p.gate(p.signal);
|
|
1640
|
+
return extractPage(p, page);
|
|
1641
|
+
},
|
|
1642
|
+
{
|
|
1643
|
+
signal: p.signal,
|
|
1644
|
+
onSettled: (page) => {
|
|
1645
|
+
extractDone++;
|
|
1646
|
+
p.onProgress?.(
|
|
1647
|
+
progress(
|
|
1648
|
+
"extract",
|
|
1649
|
+
`Page ${extractDone}/${successPages.length}: ${(page.title || page.url).slice(0, 40)}...`,
|
|
1650
|
+
{ current: extractDone, total: successPages.length }
|
|
1651
|
+
)
|
|
1652
|
+
);
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
);
|
|
1656
|
+
const extractions = rawExtractions.map(
|
|
1657
|
+
(e, i) => e ?? {
|
|
1658
|
+
url: successPages[i].url,
|
|
1659
|
+
title: successPages[i].title,
|
|
1660
|
+
extraction: "",
|
|
1661
|
+
sourceType: "unknown",
|
|
1662
|
+
currentness: "unknown",
|
|
1663
|
+
status: "failed"
|
|
1664
|
+
}
|
|
1665
|
+
);
|
|
1666
|
+
const blockedExtractions = pages.filter((pg) => pg.status !== "success").map((pg) => ({
|
|
1667
|
+
url: pg.url,
|
|
1668
|
+
title: "",
|
|
1669
|
+
extraction: "",
|
|
1670
|
+
sourceType: "unknown",
|
|
1671
|
+
currentness: "unknown",
|
|
1672
|
+
status: "blocked"
|
|
1673
|
+
}));
|
|
1674
|
+
const succeededExtr = extractions.filter((e) => e.status === "success");
|
|
1675
|
+
const failedExtr = extractions.length - succeededExtr.length;
|
|
1676
|
+
const totalIn = successPages.reduce(
|
|
1677
|
+
(sum, pg) => sum + Math.min(pg.content.length, p.settings.extractMaxChars),
|
|
1678
|
+
0
|
|
1679
|
+
);
|
|
1680
|
+
const totalOut = succeededExtr.reduce((sum, e) => sum + e.extraction.length, 0);
|
|
1681
|
+
p.tel?.recordExtract({
|
|
1682
|
+
model: `${p.extractConfig.provider}/${p.extractConfig.model}`,
|
|
1683
|
+
succeeded: succeededExtr.length,
|
|
1684
|
+
failed: failedExtr,
|
|
1685
|
+
totalInputCharsApprox: totalIn,
|
|
1686
|
+
totalOutputChars: totalOut
|
|
1687
|
+
});
|
|
1688
|
+
return { extractions, blockedExtractions };
|
|
1689
|
+
}
|
|
1690
|
+
async function runCollateStage(p, searchResult, succeededExtractions) {
|
|
1691
|
+
const collationUserMsg = buildCollationMessage(
|
|
1692
|
+
p.params.query,
|
|
1693
|
+
p.cachePath,
|
|
1694
|
+
searchResult,
|
|
1695
|
+
succeededExtractions
|
|
1696
|
+
);
|
|
1697
|
+
throwIfAborted(p.signal);
|
|
1698
|
+
const { text: collation } = await p.models.complete({
|
|
1699
|
+
model: p.collateConfig,
|
|
1700
|
+
systemPrompt: COLLATION_SYSTEM_PROMPT,
|
|
1701
|
+
userMessage: collationUserMsg,
|
|
1702
|
+
maxTokens: p.settings.collationMaxTokens,
|
|
1703
|
+
signal: p.signal,
|
|
1704
|
+
retry: p.retry,
|
|
1705
|
+
timeoutMs: p.settings.llmTimeoutMs,
|
|
1706
|
+
onRetryNotice: (msg) => p.onProgress?.(progress("collate", msg))
|
|
1707
|
+
});
|
|
1708
|
+
p.tel?.recordCollate({
|
|
1709
|
+
model: `${p.collateConfig.provider}/${p.collateConfig.model}`,
|
|
1710
|
+
summaryChars: collation.length
|
|
1711
|
+
});
|
|
1712
|
+
return collation;
|
|
1713
|
+
}
|
|
1714
|
+
async function startLlmsFullDownloads(p, successPages) {
|
|
1715
|
+
const abort = new AbortController();
|
|
1716
|
+
if (p.settings.disableLlmsFullDiscovery) return { abort, futures: [] };
|
|
1717
|
+
throwIfAborted(p.signal);
|
|
1718
|
+
let staging;
|
|
1719
|
+
try {
|
|
1720
|
+
await mkdir3(p.paths.stagingRoot, { recursive: true });
|
|
1721
|
+
staging = await mkdtemp(join5(p.paths.stagingRoot, "llms-"));
|
|
1722
|
+
} catch (error) {
|
|
1723
|
+
throwIfAborted(p.signal);
|
|
1724
|
+
p.logger.error(`Documentation staging setup failed: ${errMsg(error)}`);
|
|
1725
|
+
return { abort, futures: [] };
|
|
1726
|
+
}
|
|
1727
|
+
const signal = p.signal ? AbortSignal.any([p.signal, abort.signal]) : abort.signal;
|
|
1728
|
+
let futures = [];
|
|
1729
|
+
{
|
|
1730
|
+
const sampleUrlByHost = /* @__PURE__ */ new Map();
|
|
1731
|
+
for (const pg of successPages) {
|
|
1732
|
+
try {
|
|
1733
|
+
const h = new URL(pg.url).hostname;
|
|
1734
|
+
if (!sampleUrlByHost.has(h)) sampleUrlByHost.set(h, pg.url);
|
|
1735
|
+
} catch {
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
futures = [...sampleUrlByHost.values()].map(
|
|
1739
|
+
(sampleUrl) => Promise.resolve().then(
|
|
1740
|
+
() => p.dependencies.downloadLlmsFullToCache(
|
|
1741
|
+
sampleUrl,
|
|
1742
|
+
staging,
|
|
1743
|
+
signal,
|
|
1744
|
+
void 0,
|
|
1745
|
+
p.settings.httpProxy
|
|
1746
|
+
)
|
|
1747
|
+
).catch(() => null)
|
|
1748
|
+
);
|
|
1749
|
+
}
|
|
1750
|
+
return { staging, abort, futures };
|
|
1751
|
+
}
|
|
1752
|
+
async function writeCacheArtifacts(p, allExtractions, fetched, searchResult, collation, llms) {
|
|
1753
|
+
await withLock(
|
|
1754
|
+
cacheLockDir(p.physicalCachePath),
|
|
1755
|
+
async () => {
|
|
1756
|
+
await writeCacheFiles(
|
|
1757
|
+
p.physicalCachePath,
|
|
1758
|
+
allExtractions,
|
|
1759
|
+
fetched.successPages,
|
|
1760
|
+
searchResult,
|
|
1761
|
+
p.params.query
|
|
1762
|
+
);
|
|
1763
|
+
await writeReportFile(
|
|
1764
|
+
p.physicalCachePath,
|
|
1765
|
+
p.params.query,
|
|
1766
|
+
collation,
|
|
1767
|
+
allExtractions,
|
|
1768
|
+
fetched.pages,
|
|
1769
|
+
p.cachePath
|
|
1770
|
+
);
|
|
1771
|
+
await writeTelemetrySidecar(p.logger, p.tel, p.physicalCachePath, "completed");
|
|
1772
|
+
await withLock(
|
|
1773
|
+
indexLockDir(p.paths.cacheRoot),
|
|
1774
|
+
async () => {
|
|
1775
|
+
const slug = p.physicalCachePath.split("/").pop() ?? p.physicalCachePath;
|
|
1776
|
+
await updateIndex(p.paths.cacheRoot, slug, p.params.query);
|
|
1777
|
+
},
|
|
1778
|
+
p.signal
|
|
1779
|
+
);
|
|
1780
|
+
},
|
|
1781
|
+
p.signal
|
|
1782
|
+
);
|
|
1783
|
+
await Promise.all(llms.futures);
|
|
1784
|
+
throwIfAborted(p.signal);
|
|
1785
|
+
if (llms.staging) {
|
|
1786
|
+
const staging = llms.staging;
|
|
1787
|
+
await withLock(
|
|
1788
|
+
cacheLockDir(p.physicalCachePath),
|
|
1789
|
+
() => flushLlmsStaging(staging, join5(p.physicalCachePath, "sources")),
|
|
1790
|
+
p.signal
|
|
1791
|
+
);
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
async function runCacheSuggestStage(p) {
|
|
1795
|
+
p.onProgress?.(progress("cache", "Checking related cached research..."));
|
|
1796
|
+
throwIfAborted(p.signal);
|
|
1797
|
+
const currentSlug = p.cachePath.split("/").pop() ?? "";
|
|
1798
|
+
let suggestionsAppendix = "";
|
|
1799
|
+
let cacheSuggestRan = false;
|
|
1800
|
+
let cacheSuggestSurfaced = 0;
|
|
1801
|
+
let cacheSuggestSlugs = [];
|
|
1802
|
+
try {
|
|
1803
|
+
const index = await readIndex(p.paths.cacheRoot);
|
|
1804
|
+
if (index.searches.some((e) => e.slug !== currentSlug)) {
|
|
1805
|
+
const indexText = formatIndexForJudge(index, currentSlug);
|
|
1806
|
+
const judgeUserMsg = `Current query: "${p.params.query}"
|
|
1807
|
+
|
|
1808
|
+
Previous searches:
|
|
1809
|
+
${indexText}`;
|
|
1810
|
+
const { text: judgeResponse } = await p.models.complete({
|
|
1811
|
+
model: p.extractConfig,
|
|
1812
|
+
systemPrompt: CACHE_SUGGEST_PROMPT,
|
|
1813
|
+
userMessage: judgeUserMsg,
|
|
1814
|
+
maxTokens: 500,
|
|
1815
|
+
signal: p.signal,
|
|
1816
|
+
retry: p.retry,
|
|
1817
|
+
timeoutMs: p.settings.llmTimeoutMs,
|
|
1818
|
+
onRetryNotice: (msg) => p.onProgress?.(progress("cache", msg))
|
|
1819
|
+
});
|
|
1820
|
+
const matches = parseJudgeResponse(judgeResponse, index, currentSlug);
|
|
1821
|
+
cacheSuggestRan = true;
|
|
1822
|
+
cacheSuggestSurfaced = matches.length;
|
|
1823
|
+
cacheSuggestSlugs = matches.map((m) => m.entry.slug);
|
|
1824
|
+
suggestionsAppendix = formatCacheSuggestions(matches, p.paths.cacheDisplayRoot);
|
|
1825
|
+
}
|
|
1826
|
+
} catch (err) {
|
|
1827
|
+
throwIfAborted(p.signal);
|
|
1828
|
+
p.logger.error(`Cache suggest failed: ${errMsg(err)}`);
|
|
1829
|
+
}
|
|
1830
|
+
p.tel?.recordCacheSuggest({
|
|
1831
|
+
ran: cacheSuggestRan,
|
|
1832
|
+
surfaced: cacheSuggestSurfaced,
|
|
1833
|
+
slugs: cacheSuggestSlugs
|
|
1834
|
+
});
|
|
1835
|
+
return suggestionsAppendix;
|
|
1836
|
+
}
|
|
1837
|
+
async function degradedReturn(p, outcome, message, details) {
|
|
1838
|
+
throwIfAborted(p.signal);
|
|
1839
|
+
await writeLockedTelemetry(p, outcome);
|
|
1840
|
+
return { text: message, details, outcome };
|
|
1841
|
+
}
|
|
1842
|
+
async function flushLlmsStaging(staging, targetDir) {
|
|
1843
|
+
const stagingSources = join5(staging, "sources");
|
|
1844
|
+
let entries;
|
|
1845
|
+
try {
|
|
1846
|
+
entries = await readdir3(stagingSources);
|
|
1847
|
+
} catch {
|
|
1848
|
+
return;
|
|
1849
|
+
}
|
|
1850
|
+
await mkdir3(targetDir, { recursive: true });
|
|
1851
|
+
for (const name of entries) {
|
|
1852
|
+
if (!name.startsWith("llms-full-")) continue;
|
|
1853
|
+
const src = join5(stagingSources, name);
|
|
1854
|
+
const dst = join5(targetDir, name);
|
|
1855
|
+
try {
|
|
1856
|
+
const data = await readFile2(src, "utf-8");
|
|
1857
|
+
await writeFile4(dst, data);
|
|
1858
|
+
} catch {
|
|
1859
|
+
}
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
async function writeLockedTelemetry(p, outcome) {
|
|
1863
|
+
if (!p.tel) return;
|
|
1864
|
+
try {
|
|
1865
|
+
await withLock(
|
|
1866
|
+
cacheLockDir(p.physicalCachePath),
|
|
1867
|
+
() => writeTelemetrySidecar(p.logger, p.tel, p.physicalCachePath, outcome),
|
|
1868
|
+
p.signal
|
|
1869
|
+
);
|
|
1870
|
+
} catch (error) {
|
|
1871
|
+
throwIfAborted(p.signal);
|
|
1872
|
+
p.logger.error(`Telemetry write failed: ${errMsg(error)}`);
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
async function writeTelemetrySidecar(logger, tel, cachePath, outcome) {
|
|
1876
|
+
if (!tel) return;
|
|
1877
|
+
tel.setOutcome(outcome);
|
|
1878
|
+
try {
|
|
1879
|
+
await mkdir3(cachePath, { recursive: true });
|
|
1880
|
+
await writeTelemetry(cachePath, tel.finalize());
|
|
1881
|
+
} catch (err) {
|
|
1882
|
+
logger.error(`Telemetry write failed: ${errMsg(err)}`);
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
async function extractPage(p, page) {
|
|
1886
|
+
throwIfAborted(p.signal);
|
|
1887
|
+
try {
|
|
1888
|
+
const userMessage = buildExtractionMessage(
|
|
1889
|
+
page.content,
|
|
1890
|
+
p.params.query,
|
|
1891
|
+
p.params.focusPrompt,
|
|
1892
|
+
p.settings.extractMaxChars
|
|
1893
|
+
);
|
|
1894
|
+
const { text: extraction } = await p.models.complete({
|
|
1895
|
+
model: p.extractConfig,
|
|
1896
|
+
systemPrompt: EXTRACTION_SYSTEM_PROMPT,
|
|
1897
|
+
userMessage,
|
|
1898
|
+
maxTokens: p.settings.extractionMaxTokens,
|
|
1899
|
+
signal: p.signal,
|
|
1900
|
+
retry: p.retry,
|
|
1901
|
+
timeoutMs: p.settings.llmTimeoutMs,
|
|
1902
|
+
onRetryNotice: (msg) => p.onProgress?.(progress("extract", msg))
|
|
1903
|
+
});
|
|
1904
|
+
const firstLine = extraction.split("\n")[0] ?? "";
|
|
1905
|
+
return {
|
|
1906
|
+
url: page.url,
|
|
1907
|
+
title: page.title,
|
|
1908
|
+
extraction,
|
|
1909
|
+
sourceType: inferSourceType(firstLine),
|
|
1910
|
+
currentness: inferCurrentness(firstLine),
|
|
1911
|
+
status: "success"
|
|
1912
|
+
};
|
|
1913
|
+
} catch (err) {
|
|
1914
|
+
throwIfAborted(p.signal);
|
|
1915
|
+
p.logger.error(`Extraction failed for ${page.url}: ${errMsg(err)}`);
|
|
1916
|
+
return {
|
|
1917
|
+
url: page.url,
|
|
1918
|
+
title: page.title,
|
|
1919
|
+
extraction: "",
|
|
1920
|
+
sourceType: "unknown",
|
|
1921
|
+
currentness: "unknown",
|
|
1922
|
+
status: "failed"
|
|
1923
|
+
};
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
|
|
1927
|
+
// src/core/schemas.ts
|
|
1928
|
+
import { Type } from "typebox";
|
|
1929
|
+
var extractionSchema = Type.Object({
|
|
1930
|
+
url: Type.String(),
|
|
1931
|
+
title: Type.String(),
|
|
1932
|
+
extraction: Type.String(),
|
|
1933
|
+
sourceType: Type.String(),
|
|
1934
|
+
status: Type.String()
|
|
1935
|
+
});
|
|
1936
|
+
var fullPageSchema = Type.Object({
|
|
1937
|
+
url: Type.String(),
|
|
1938
|
+
title: Type.String(),
|
|
1939
|
+
content: Type.String()
|
|
1940
|
+
});
|
|
1941
|
+
var searchSchema = Type.Object({
|
|
1942
|
+
query: Type.String({ description: "Search query" }),
|
|
1943
|
+
domains: Type.Optional(Type.Array(Type.String(), { description: "Restrict to these domains" }))
|
|
1944
|
+
});
|
|
1945
|
+
var extractSchema = Type.Object({
|
|
1946
|
+
url: Type.String({ description: "URL of the page to extract from" }),
|
|
1947
|
+
title: Type.String({ description: "Page title" }),
|
|
1948
|
+
content: Type.String({ description: "Full page content in markdown" }),
|
|
1949
|
+
query: Type.String({ description: "The original search query" }),
|
|
1950
|
+
focusPrompt: Type.Optional(
|
|
1951
|
+
Type.String({ description: "Optional focus guidance for extraction" })
|
|
1952
|
+
)
|
|
1953
|
+
});
|
|
1954
|
+
var collateSchema = Type.Object({
|
|
1955
|
+
extractions: Type.Array(extractionSchema, {
|
|
1956
|
+
description: "Array of per-page extraction results from intelli_extract"
|
|
1957
|
+
}),
|
|
1958
|
+
query: Type.String({ description: "The original search query" }),
|
|
1959
|
+
searchSummary: Type.Optional(
|
|
1960
|
+
Type.String({
|
|
1961
|
+
description: "Summary from the initial search step"
|
|
1962
|
+
})
|
|
1963
|
+
),
|
|
1964
|
+
fullPages: Type.Optional(
|
|
1965
|
+
Type.Array(fullPageSchema, {
|
|
1966
|
+
description: "Full page content for caching (not sent to LLM)"
|
|
1967
|
+
})
|
|
1968
|
+
)
|
|
1969
|
+
});
|
|
1970
|
+
var researchSchema = Type.Object({
|
|
1971
|
+
query: Type.String({ description: "What to research" }),
|
|
1972
|
+
maxUrls: Type.Optional(
|
|
1973
|
+
Type.Number({ description: "Max URLs to fetch (default: 8, capped by settings.maxUrls)" })
|
|
1974
|
+
),
|
|
1975
|
+
domains: Type.Optional(
|
|
1976
|
+
Type.Array(Type.String(), { description: "Restrict search to these domains" })
|
|
1977
|
+
),
|
|
1978
|
+
focusPrompt: Type.Optional(Type.String({ description: "Focus guidance for all extractions" }))
|
|
1979
|
+
});
|
|
1980
|
+
|
|
1981
|
+
// packages/mcp/src/errors.ts
|
|
1982
|
+
var StandaloneError = class extends Error {
|
|
1983
|
+
constructor(code, message) {
|
|
1984
|
+
super(message);
|
|
1985
|
+
this.code = code;
|
|
1986
|
+
this.name = code === "CANCELLED" ? "AbortError" : "StandaloneError";
|
|
1987
|
+
}
|
|
1988
|
+
code;
|
|
1989
|
+
};
|
|
1990
|
+
|
|
1991
|
+
// packages/mcp/src/providers/openrouter.ts
|
|
1992
|
+
var endpoint = "https://openrouter.ai/api/v1";
|
|
1993
|
+
var record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1994
|
+
var numeric = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
1995
|
+
function statusError(status, hints) {
|
|
1996
|
+
if (status === 402 && hints?.retryAfterMs !== void 0)
|
|
1997
|
+
return new StandaloneError(
|
|
1998
|
+
"PROVIDER",
|
|
1999
|
+
"OpenRouter HTTP 402: temporarily unavailable (in-flight spending budget)"
|
|
2000
|
+
);
|
|
2001
|
+
const hint = status === 401 ? "check the configured API key" : status === 402 ? "check account credits" : status === 403 ? "check account permissions and provider policy" : status === 404 ? "check the exact model identifier" : status === 429 ? "rate limited" : status === 408 ? "request timed out" : status >= 500 ? "server error" : "provider request failed";
|
|
2002
|
+
return new StandaloneError("PROVIDER", `OpenRouter HTTP ${status}: ${hint}`);
|
|
2003
|
+
}
|
|
2004
|
+
function responseError(value, hints) {
|
|
2005
|
+
const error = record(value);
|
|
2006
|
+
const types = {
|
|
2007
|
+
rate_limit_exceeded: 429,
|
|
2008
|
+
provider_overloaded: 503,
|
|
2009
|
+
provider_unavailable: 502,
|
|
2010
|
+
server: 500,
|
|
2011
|
+
timeout: 408,
|
|
2012
|
+
authentication: 401,
|
|
2013
|
+
payment_required: 402,
|
|
2014
|
+
permission_denied: 403,
|
|
2015
|
+
content_policy_violation: 403,
|
|
2016
|
+
refusal: 403,
|
|
2017
|
+
invalid_request: 400,
|
|
2018
|
+
invalid_prompt: 400,
|
|
2019
|
+
not_found: 404,
|
|
2020
|
+
context_length_exceeded: 400,
|
|
2021
|
+
max_tokens_exceeded: 400
|
|
2022
|
+
};
|
|
2023
|
+
const type = record(error.metadata).error_type;
|
|
2024
|
+
const code = Number(error.code);
|
|
2025
|
+
const status = typeof type === "string" && Object.hasOwn(types, type) ? types[type] : Number.isInteger(code) && code >= 400 && code <= 599 ? code : 400;
|
|
2026
|
+
return statusError(status, hints);
|
|
2027
|
+
}
|
|
2028
|
+
async function bodyText(response, signal, limit) {
|
|
2029
|
+
if (!response.body) throw new Error("OpenRouter returned an empty response body");
|
|
2030
|
+
const reader = response.body.getReader();
|
|
2031
|
+
const abort = () => {
|
|
2032
|
+
void reader.cancel().catch(() => {
|
|
2033
|
+
});
|
|
2034
|
+
};
|
|
2035
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
2036
|
+
const chunks = [];
|
|
2037
|
+
let bytes = 0;
|
|
2038
|
+
try {
|
|
2039
|
+
throwIfAborted(signal);
|
|
2040
|
+
for (; ; ) {
|
|
2041
|
+
const { value, done } = await reader.read();
|
|
2042
|
+
throwIfAborted(signal);
|
|
2043
|
+
if (done) break;
|
|
2044
|
+
bytes += value.byteLength;
|
|
2045
|
+
if (bytes > limit)
|
|
2046
|
+
throw new Error("OpenRouter response exceeds the configured transport safety limit");
|
|
2047
|
+
chunks.push(value);
|
|
2048
|
+
}
|
|
2049
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
2050
|
+
} finally {
|
|
2051
|
+
signal?.removeEventListener("abort", abort);
|
|
2052
|
+
await reader.cancel().catch(() => {
|
|
2053
|
+
});
|
|
2054
|
+
reader.releaseLock();
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
function usage(value) {
|
|
2058
|
+
const raw = record(value);
|
|
2059
|
+
const out = {};
|
|
2060
|
+
for (const [key, val] of Object.entries({
|
|
2061
|
+
input: raw.prompt_tokens,
|
|
2062
|
+
output: raw.completion_tokens,
|
|
2063
|
+
totalTokens: raw.total_tokens,
|
|
2064
|
+
totalCost: raw.cost,
|
|
2065
|
+
cacheRead: record(raw.prompt_tokens_details).cached_tokens,
|
|
2066
|
+
reasoning: record(raw.completion_tokens_details).reasoning_tokens
|
|
2067
|
+
})) {
|
|
2068
|
+
const n = numeric(val);
|
|
2069
|
+
if (n !== void 0) Object.assign(out, { [key]: n });
|
|
2070
|
+
}
|
|
2071
|
+
return Object.keys(out).length ? out : void 0;
|
|
2072
|
+
}
|
|
2073
|
+
function createOpenRouterClient(config, options) {
|
|
2074
|
+
const transport = options.fetch ?? globalThis.fetch;
|
|
2075
|
+
const env = { ...options.env ?? process.env };
|
|
2076
|
+
const settings = config.settings;
|
|
2077
|
+
const configured = [settings.searchModel, settings.extractModel, settings.collateModel];
|
|
2078
|
+
let catalogue;
|
|
2079
|
+
function key() {
|
|
2080
|
+
const value = env[config.apiKeyEnv];
|
|
2081
|
+
if (!value || !value.trim() || /\s/.test(value))
|
|
2082
|
+
throw new StandaloneError(
|
|
2083
|
+
"CONFIGURATION",
|
|
2084
|
+
`Set the credential environment variable ${config.apiKeyEnv} before creating the runtime; restart it after changing credentials`
|
|
2085
|
+
);
|
|
2086
|
+
return value;
|
|
2087
|
+
}
|
|
2088
|
+
function policy(request) {
|
|
2089
|
+
return {
|
|
2090
|
+
...request,
|
|
2091
|
+
timeoutMs: request.timeoutMs ?? settings.llmTimeoutMs,
|
|
2092
|
+
retry: request.retry ?? {
|
|
2093
|
+
attempts: settings.llmRetryAttempts,
|
|
2094
|
+
baseDelayMs: settings.retryBaseDelayMs,
|
|
2095
|
+
maxDelayMs: settings.retryMaxDelayMs
|
|
2096
|
+
}
|
|
2097
|
+
};
|
|
2098
|
+
}
|
|
2099
|
+
async function send(path, init, signal, hints) {
|
|
2100
|
+
let response;
|
|
2101
|
+
try {
|
|
2102
|
+
response = await transport(`${endpoint}${path}`, {
|
|
2103
|
+
...init,
|
|
2104
|
+
signal,
|
|
2105
|
+
redirect: "error",
|
|
2106
|
+
headers: { Authorization: `Bearer ${key()}`, "Content-Type": "application/json" }
|
|
2107
|
+
});
|
|
2108
|
+
} catch {
|
|
2109
|
+
throwIfAborted(signal);
|
|
2110
|
+
throw new Error("OpenRouter service unavailable; check connectivity");
|
|
2111
|
+
}
|
|
2112
|
+
const retryAfter = response.headers.get("retry-after");
|
|
2113
|
+
if (retryAfter !== null) {
|
|
2114
|
+
const seconds = Number(retryAfter);
|
|
2115
|
+
const delay = Number.isFinite(seconds) ? seconds * 1e3 : Date.parse(retryAfter) - Date.now();
|
|
2116
|
+
if (Number.isFinite(delay) && delay >= 0) hints.retryAfterMs = delay;
|
|
2117
|
+
}
|
|
2118
|
+
if (!response.ok) {
|
|
2119
|
+
void response.body?.cancel().catch(() => {
|
|
2120
|
+
});
|
|
2121
|
+
throw statusError(response.status, hints);
|
|
2122
|
+
}
|
|
2123
|
+
let raw;
|
|
2124
|
+
try {
|
|
2125
|
+
raw = await bodyText(response, signal, path === "/models" ? 16e6 : 8e6);
|
|
2126
|
+
} catch (error) {
|
|
2127
|
+
throwIfAborted(signal);
|
|
2128
|
+
if (error instanceof Error && error.message.startsWith("OpenRouter response exceeds"))
|
|
2129
|
+
throw error;
|
|
2130
|
+
throw new Error("OpenRouter server error: response body failed");
|
|
2131
|
+
}
|
|
2132
|
+
let data;
|
|
2133
|
+
try {
|
|
2134
|
+
data = record(JSON.parse(raw));
|
|
2135
|
+
} catch {
|
|
2136
|
+
throw new Error("OpenRouter returned malformed JSON");
|
|
2137
|
+
}
|
|
2138
|
+
if (data.error !== void 0) throw responseError(data.error, hints);
|
|
2139
|
+
return { raw, data };
|
|
2140
|
+
}
|
|
2141
|
+
function capabilities(binding) {
|
|
2142
|
+
if (binding.config.provider !== "openrouter" || !configured.some((item) => item.model === binding.config.model))
|
|
2143
|
+
return false;
|
|
2144
|
+
const entry = catalogue?.find((item) => item.id === binding.config.model);
|
|
2145
|
+
if (!entry) return false;
|
|
2146
|
+
const architecture = record(entry.architecture);
|
|
2147
|
+
if (!Array.isArray(architecture.input_modalities) || !architecture.input_modalities.includes("text") || !Array.isArray(architecture.output_modalities) || !architecture.output_modalities.includes("text"))
|
|
2148
|
+
throw new Error(`Configured ${binding.role} model does not advertise text input/output`);
|
|
2149
|
+
const search2 = binding.role === "search";
|
|
2150
|
+
const effort = search2 && settings.searchWebSearch.enabled ? settings.searchWebSearch.reasoning ?? "low" : "low";
|
|
2151
|
+
const efforts = record(entry.reasoning).supported_efforts;
|
|
2152
|
+
if (Array.isArray(efforts) && !efforts.includes(effort))
|
|
2153
|
+
throw new Error(
|
|
2154
|
+
`Configured ${binding.role} model does not support the requested reasoning effort`
|
|
2155
|
+
);
|
|
2156
|
+
if (search2 && settings.searchWebSearch.enabled && (!Array.isArray(entry.supported_parameters) || !entry.supported_parameters.includes("tools")))
|
|
2157
|
+
throw new Error("Configured search model does not advertise tool support");
|
|
2158
|
+
return true;
|
|
2159
|
+
}
|
|
2160
|
+
const client = {
|
|
2161
|
+
async preflight(bindings) {
|
|
2162
|
+
key();
|
|
2163
|
+
if (!catalogue) {
|
|
2164
|
+
const data = await runModelWithPolicy(
|
|
2165
|
+
async (signal, hints) => {
|
|
2166
|
+
const { data: data2 } = await send("/models", { method: "GET" }, signal, hints);
|
|
2167
|
+
if (!Array.isArray(data2.data))
|
|
2168
|
+
throw new Error("OpenRouter returned an invalid model catalogue");
|
|
2169
|
+
return { value: data2.data.map(record) };
|
|
2170
|
+
},
|
|
2171
|
+
policy({
|
|
2172
|
+
model: settings.searchModel,
|
|
2173
|
+
systemPrompt: "",
|
|
2174
|
+
userMessage: "",
|
|
2175
|
+
signal: options.signal
|
|
2176
|
+
}),
|
|
2177
|
+
options.logger,
|
|
2178
|
+
options.policyTesting
|
|
2179
|
+
);
|
|
2180
|
+
catalogue = data;
|
|
2181
|
+
}
|
|
2182
|
+
return bindings.filter((binding) => !capabilities(binding));
|
|
2183
|
+
},
|
|
2184
|
+
async complete(request) {
|
|
2185
|
+
throwIfAborted(request.signal);
|
|
2186
|
+
key();
|
|
2187
|
+
if (request.model.provider !== "openrouter" || !configured.some((item) => item.model === request.model.model))
|
|
2188
|
+
throw new Error("Model is not explicitly configured for this provider");
|
|
2189
|
+
if (!catalogue) throw new Error("Run provider preflight before model completion");
|
|
2190
|
+
const entry = catalogue.find((item) => item.id === request.model.model);
|
|
2191
|
+
if (!entry) throw new Error("Configured model is absent from the provider catalogue");
|
|
2192
|
+
const supportsReasoning = Array.isArray(entry.supported_parameters) && entry.supported_parameters.includes("reasoning") || Object.keys(record(entry.reasoning)).length > 0;
|
|
2193
|
+
return runModelWithPolicy(
|
|
2194
|
+
async (signal, hints) => {
|
|
2195
|
+
const base = {
|
|
2196
|
+
model: request.model.model,
|
|
2197
|
+
stream: false,
|
|
2198
|
+
messages: [
|
|
2199
|
+
{ role: "system", content: request.systemPrompt },
|
|
2200
|
+
{ role: "user", content: request.userMessage }
|
|
2201
|
+
]
|
|
2202
|
+
};
|
|
2203
|
+
if (supportsReasoning)
|
|
2204
|
+
base.reasoning = { effort: request.reasoning ?? "low", exclude: true };
|
|
2205
|
+
if (request.maxTokens !== void 0) base.max_completion_tokens = request.maxTokens;
|
|
2206
|
+
const payload = request.payloadPatch ? request.payloadPatch(base) : base;
|
|
2207
|
+
if (payload.model !== base.model || payload.stream !== false || payload.messages !== base.messages || "models" in payload || "route" in payload)
|
|
2208
|
+
throw new Error("Payload patch cannot change model routing or message ownership");
|
|
2209
|
+
const { data, raw } = await send(
|
|
2210
|
+
"/chat/completions",
|
|
2211
|
+
{ method: "POST", body: JSON.stringify(payload) },
|
|
2212
|
+
signal,
|
|
2213
|
+
hints
|
|
2214
|
+
);
|
|
2215
|
+
const choices = data.choices;
|
|
2216
|
+
if (!Array.isArray(choices) || choices.length !== 1)
|
|
2217
|
+
throw new Error("OpenRouter returned invalid completion choices");
|
|
2218
|
+
const choice = record(choices[0]);
|
|
2219
|
+
if (choice.error !== void 0) throw responseError(choice.error, hints);
|
|
2220
|
+
if (choice.finish_reason === "error")
|
|
2221
|
+
throw new StandaloneError(
|
|
2222
|
+
"PROVIDER",
|
|
2223
|
+
"OpenRouter returned a failed completion without an error classification"
|
|
2224
|
+
);
|
|
2225
|
+
const message = record(choice.message);
|
|
2226
|
+
if (message.refusal || choice.finish_reason === "content_filter")
|
|
2227
|
+
throw new Error("OpenRouter declined the request under provider policy");
|
|
2228
|
+
if (typeof message.content !== "string")
|
|
2229
|
+
throw new Error("OpenRouter returned no text completion");
|
|
2230
|
+
if (!message.content.trim() && choice.finish_reason === "length")
|
|
2231
|
+
throw new Error(
|
|
2232
|
+
"OpenRouter exhausted the output budget without visible text; increase token limits or lower reasoning effort"
|
|
2233
|
+
);
|
|
2234
|
+
return {
|
|
2235
|
+
value: {
|
|
2236
|
+
text: message.content,
|
|
2237
|
+
citations: request.collectCitations ? parseCitations(raw) : [],
|
|
2238
|
+
usage: usage(data.usage)
|
|
2239
|
+
}
|
|
2240
|
+
};
|
|
2241
|
+
},
|
|
2242
|
+
policy(request),
|
|
2243
|
+
options.logger,
|
|
2244
|
+
options.policyTesting
|
|
2245
|
+
);
|
|
2246
|
+
}
|
|
2247
|
+
};
|
|
2248
|
+
async function safe(call) {
|
|
2249
|
+
try {
|
|
2250
|
+
return await call;
|
|
2251
|
+
} catch (error) {
|
|
2252
|
+
if (error instanceof StandaloneError) throw error;
|
|
2253
|
+
throw new StandaloneError(
|
|
2254
|
+
"PROVIDER",
|
|
2255
|
+
error instanceof Error ? error.message : "OpenRouter request failed"
|
|
2256
|
+
);
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
2259
|
+
return {
|
|
2260
|
+
preflight: (bindings) => safe(client.preflight(bindings)),
|
|
2261
|
+
complete: (request) => safe(client.complete(request))
|
|
2262
|
+
};
|
|
2263
|
+
}
|
|
2264
|
+
|
|
2265
|
+
// packages/mcp/src/workspace.ts
|
|
2266
|
+
import { lstat, readdir as readdir4, realpath } from "node:fs/promises";
|
|
2267
|
+
import { join as join6, relative as relative2, sep } from "node:path";
|
|
2268
|
+
async function assertWorkspaceSafe(paths, signal) {
|
|
2269
|
+
throwIfAborted(signal);
|
|
2270
|
+
if (await realpath(paths.workspaceRoot) !== paths.workspaceRoot)
|
|
2271
|
+
throw new Error("Workspace identity changed");
|
|
2272
|
+
const parts = relative2(paths.workspaceRoot, paths.cacheRoot).split(sep);
|
|
2273
|
+
if (!parts.length || parts.some((part) => !part || part === ".."))
|
|
2274
|
+
throw new Error("Cache must remain inside the workspace");
|
|
2275
|
+
let count = 0;
|
|
2276
|
+
async function inspect(path2, descend) {
|
|
2277
|
+
throwIfAborted(signal);
|
|
2278
|
+
if (++count > 1e5)
|
|
2279
|
+
throw new Error("Cache safety scan exceeds 100000 entries; use a smaller cache directory");
|
|
2280
|
+
let entry;
|
|
2281
|
+
try {
|
|
2282
|
+
entry = await lstat(path2);
|
|
2283
|
+
} catch (error) {
|
|
2284
|
+
if (error.code === "ENOENT") return;
|
|
2285
|
+
throw new Error("Cannot inspect workspace cache");
|
|
2286
|
+
}
|
|
2287
|
+
if (entry.isSymbolicLink() || entry.isFile() && entry.nlink > 1)
|
|
2288
|
+
throw new Error("Cache links are not allowed; select an unlinked workspace-local cache");
|
|
2289
|
+
if (!entry.isFile() && !entry.isDirectory())
|
|
2290
|
+
throw new Error("Cache contains an unsupported filesystem entry");
|
|
2291
|
+
if ((!descend || path2 === paths.cacheRoot || path2 === paths.stagingRoot) && !entry.isDirectory())
|
|
2292
|
+
throw new Error("Cache and staging roots and their ancestors must be directories");
|
|
2293
|
+
if (descend && entry.isDirectory())
|
|
2294
|
+
for (const name of await readdir4(path2)) await inspect(join6(path2, name), true);
|
|
2295
|
+
}
|
|
2296
|
+
let path = paths.workspaceRoot;
|
|
2297
|
+
for (const part of parts) {
|
|
2298
|
+
path = join6(path, part);
|
|
2299
|
+
await inspect(path, path === paths.cacheRoot);
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
async function workspacePaths(workspace, cacheDir) {
|
|
2303
|
+
validateCacheDir(cacheDir);
|
|
2304
|
+
const paths = resolveWorkspacePaths(workspace, cacheDir, "absolute");
|
|
2305
|
+
await assertWorkspaceSafe(paths);
|
|
2306
|
+
return paths;
|
|
2307
|
+
}
|
|
2308
|
+
|
|
2309
|
+
// packages/mcp/src/console.ts
|
|
2310
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
2311
|
+
var scopes2 = new AsyncLocalStorage2();
|
|
2312
|
+
var activeCalls2 = 0;
|
|
2313
|
+
var restore2;
|
|
2314
|
+
var channels = ["log", "info", "debug", "dir", "table"];
|
|
2315
|
+
async function withStandaloneStdout(logger, operation) {
|
|
2316
|
+
if (activeCalls2++ === 0) {
|
|
2317
|
+
const restores = [];
|
|
2318
|
+
for (const channel of channels) {
|
|
2319
|
+
const original = console[channel];
|
|
2320
|
+
const dispatch = (...args) => {
|
|
2321
|
+
const scope2 = scopes2.getStore();
|
|
2322
|
+
if (scope2?.active) {
|
|
2323
|
+
scopes2.exit(
|
|
2324
|
+
() => scope2.logger.warn("Suppressed dependency console output during standalone execution")
|
|
2325
|
+
);
|
|
2326
|
+
} else original(...args);
|
|
2327
|
+
};
|
|
2328
|
+
console[channel] = dispatch;
|
|
2329
|
+
restores.push(() => {
|
|
2330
|
+
if (console[channel] === dispatch) console[channel] = original;
|
|
2331
|
+
});
|
|
2332
|
+
}
|
|
2333
|
+
restore2 = () => {
|
|
2334
|
+
for (const undo of restores) undo();
|
|
2335
|
+
};
|
|
2336
|
+
}
|
|
2337
|
+
const scope = { active: true, logger };
|
|
2338
|
+
try {
|
|
2339
|
+
return await scopes2.run(scope, operation);
|
|
2340
|
+
} finally {
|
|
2341
|
+
scope.active = false;
|
|
2342
|
+
if (--activeCalls2 === 0) {
|
|
2343
|
+
restore2?.();
|
|
2344
|
+
restore2 = void 0;
|
|
2345
|
+
}
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
// packages/mcp/src/runtime.ts
|
|
2350
|
+
var schemas = {
|
|
2351
|
+
intelli_search: searchSchema,
|
|
2352
|
+
intelli_extract: extractSchema,
|
|
2353
|
+
intelli_collate: collateSchema,
|
|
2354
|
+
intelli_research: researchSchema
|
|
2355
|
+
};
|
|
2356
|
+
function strict(schema) {
|
|
2357
|
+
const clone = { ...schema };
|
|
2358
|
+
if (clone.type === "object") {
|
|
2359
|
+
clone.additionalProperties = false;
|
|
2360
|
+
clone.properties = Object.fromEntries(
|
|
2361
|
+
Object.entries(clone.properties ?? {}).map(([key, value]) => [key, strict(value)])
|
|
2362
|
+
);
|
|
2363
|
+
}
|
|
2364
|
+
if (clone.type === "array") {
|
|
2365
|
+
clone.maxItems = 100;
|
|
2366
|
+
clone.items = strict(clone.items);
|
|
2367
|
+
}
|
|
2368
|
+
if (clone.type === "string") clone.maxLength = 2e6;
|
|
2369
|
+
return clone;
|
|
2370
|
+
}
|
|
2371
|
+
var inputSchemas = Object.fromEntries(
|
|
2372
|
+
Object.entries(schemas).map(([key, schema]) => [key, strict(schema)])
|
|
2373
|
+
);
|
|
2374
|
+
function validate(name, params) {
|
|
2375
|
+
if (!Object.hasOwn(inputSchemas, name)) throw new Error("Unknown operation");
|
|
2376
|
+
if (!Check(inputSchemas[name], params)) throw new Error("Invalid operation arguments");
|
|
2377
|
+
const input = params;
|
|
2378
|
+
if (!input.query.trim()) throw new Error("query must not be empty");
|
|
2379
|
+
if ("maxUrls" in input && input.maxUrls !== void 0 && (!Number.isSafeInteger(input.maxUrls) || input.maxUrls < 1))
|
|
2380
|
+
throw new Error("maxUrls must be a positive integer");
|
|
2381
|
+
if ("extractions" in input && input.extractions.some((item) => !["success", "failed", "blocked"].includes(item.status)))
|
|
2382
|
+
throw new Error("extraction status must be success, failed or blocked");
|
|
2383
|
+
}
|
|
2384
|
+
var stderrLogger = {
|
|
2385
|
+
error: (message) => {
|
|
2386
|
+
process.stderr.write(`[mcp-intelli-search] ${message}
|
|
2387
|
+
`);
|
|
2388
|
+
},
|
|
2389
|
+
warn: (message) => {
|
|
2390
|
+
process.stderr.write(`[mcp-intelli-search] ${message}
|
|
2391
|
+
`);
|
|
2392
|
+
}
|
|
2393
|
+
};
|
|
2394
|
+
async function createRuntime(config, options = {}) {
|
|
2395
|
+
const paths = await workspacePaths(config.workspace, config.settings.cacheDir);
|
|
2396
|
+
const env = { ...options.env ?? process.env };
|
|
2397
|
+
const secret = env[config.apiKeyEnv];
|
|
2398
|
+
const redact = (message) => secret ? message.split(secret).join("[REDACTED]") : message;
|
|
2399
|
+
const sink = options.logger ?? stderrLogger;
|
|
2400
|
+
const logger = {
|
|
2401
|
+
error: (message) => sink.error(redact(message)),
|
|
2402
|
+
warn: (message) => sink.warn(redact(message))
|
|
2403
|
+
};
|
|
2404
|
+
return {
|
|
2405
|
+
identity,
|
|
2406
|
+
paths,
|
|
2407
|
+
async execute(name, params, execution = {}) {
|
|
2408
|
+
let category = "INVALID_ARGUMENTS";
|
|
2409
|
+
try {
|
|
2410
|
+
validate(name, params);
|
|
2411
|
+
if ("domains" in params && params.domains !== void 0) {
|
|
2412
|
+
validateDomains(params.domains, "domains");
|
|
2413
|
+
const search2 = config.settings.searchWebSearch;
|
|
2414
|
+
if (search2.enabled && ["perplexity", "firecrawl"].includes(search2.engine ?? "") && search2.excludedDomains?.length && params.domains.length)
|
|
2415
|
+
throw new Error(
|
|
2416
|
+
"This search engine cannot combine per-call domains and excludedDomains"
|
|
2417
|
+
);
|
|
2418
|
+
}
|
|
2419
|
+
throwIfAborted(execution.signal);
|
|
2420
|
+
category = "WORKSPACE";
|
|
2421
|
+
await assertWorkspaceSafe(paths, execution.signal);
|
|
2422
|
+
const models = createOpenRouterClient(config, {
|
|
2423
|
+
fetch: options.fetch,
|
|
2424
|
+
env,
|
|
2425
|
+
logger,
|
|
2426
|
+
signal: execution.signal
|
|
2427
|
+
});
|
|
2428
|
+
const settings = config.settings;
|
|
2429
|
+
const bindings = name === "intelli_research" ? [
|
|
2430
|
+
{ role: "search", config: settings.searchModel },
|
|
2431
|
+
{ role: "extract", config: settings.extractModel },
|
|
2432
|
+
{ role: "collate", config: settings.collateModel }
|
|
2433
|
+
] : [
|
|
2434
|
+
{
|
|
2435
|
+
role: name.slice("intelli_".length),
|
|
2436
|
+
config: name === "intelli_search" ? settings.searchModel : name === "intelli_extract" ? settings.extractModel : settings.collateModel
|
|
2437
|
+
}
|
|
2438
|
+
];
|
|
2439
|
+
category = "CONFIGURATION";
|
|
2440
|
+
const missing = await models.preflight(bindings);
|
|
2441
|
+
if (missing.length)
|
|
2442
|
+
throw new Error(
|
|
2443
|
+
`Configured model unavailable for role(s): ${missing.map((item) => item.role).join(", ")}`
|
|
2444
|
+
);
|
|
2445
|
+
throwIfAborted(execution.signal);
|
|
2446
|
+
category = "WORKSPACE";
|
|
2447
|
+
await assertWorkspaceSafe(paths, execution.signal);
|
|
2448
|
+
category = "OPERATION";
|
|
2449
|
+
const context = {
|
|
2450
|
+
settings,
|
|
2451
|
+
models,
|
|
2452
|
+
paths,
|
|
2453
|
+
identity,
|
|
2454
|
+
logger,
|
|
2455
|
+
...execution
|
|
2456
|
+
};
|
|
2457
|
+
const result = await withStandaloneStdout(logger, async () => {
|
|
2458
|
+
switch (name) {
|
|
2459
|
+
case "intelli_search":
|
|
2460
|
+
return search(params, context);
|
|
2461
|
+
case "intelli_extract":
|
|
2462
|
+
return extract(params, context);
|
|
2463
|
+
case "intelli_collate":
|
|
2464
|
+
return collate(params, context);
|
|
2465
|
+
case "intelli_research":
|
|
2466
|
+
return research(
|
|
2467
|
+
params,
|
|
2468
|
+
context,
|
|
2469
|
+
options.researchDependencies
|
|
2470
|
+
);
|
|
2471
|
+
default:
|
|
2472
|
+
throw new Error("Unknown operation");
|
|
2473
|
+
}
|
|
2474
|
+
});
|
|
2475
|
+
return {
|
|
2476
|
+
...result,
|
|
2477
|
+
text: redact(
|
|
2478
|
+
result.text.replace(
|
|
2479
|
+
/(^- Read (?:the extraction|the full page): )`read ([^`]+)`/gm,
|
|
2480
|
+
"$1`$2` (use the host's file-reading capability)"
|
|
2481
|
+
).replace(
|
|
2482
|
+
/Read a report with `read ([^`]+)`/g,
|
|
2483
|
+
"Read `$1` with the host's file-reading capability"
|
|
2484
|
+
)
|
|
2485
|
+
)
|
|
2486
|
+
};
|
|
2487
|
+
} catch (error) {
|
|
2488
|
+
if (execution.signal?.aborted) throw new StandaloneError("CANCELLED", "Operation aborted");
|
|
2489
|
+
throw new StandaloneError(
|
|
2490
|
+
error instanceof StandaloneError ? error.code : category,
|
|
2491
|
+
redact(error instanceof Error ? error.message : "Standalone operation failed")
|
|
2492
|
+
);
|
|
2493
|
+
}
|
|
2494
|
+
}
|
|
2495
|
+
};
|
|
2496
|
+
}
|
|
2497
|
+
|
|
2498
|
+
export {
|
|
2499
|
+
searchSchema,
|
|
2500
|
+
extractSchema,
|
|
2501
|
+
collateSchema,
|
|
2502
|
+
researchSchema,
|
|
2503
|
+
StandaloneError,
|
|
2504
|
+
createRuntime
|
|
2505
|
+
};
|