@curio-data/mcp-intelli-search 0.19.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
  [![npm downloads](https://img.shields.io/npm/dt/@curio-data/mcp-intelli-search?color=blue)](https://www.npmjs.com/package/@curio-data/mcp-intelli-search)
7
7
  [![node](https://img.shields.io/badge/node-%E2%89%A522-blue)](https://nodejs.org/)
8
8
  [![license](https://img.shields.io/badge/license-Apache--2.0-green)](https://github.com/Curio-Data/pi-intelli-search/blob/main/LICENSE)
9
- ![tests](https://img.shields.io/badge/test%3Aall-668%20passing-brightgreen)
9
+ ![tests](https://img.shields.io/badge/test%3Aall-684%20passing-brightgreen)
10
10
 
11
11
  Intelligent web research for coding agents: search, extract, collate, and cache grounded web context in one tool call.
12
12
 
@@ -59,6 +59,7 @@ The native extension uses `Pi` settings and authentication. Generic MCP registra
59
59
  - [Generic MCP Host](#generic-mcp-host)
60
60
  - [Tools](#tools)
61
61
  - [Evidence and Provenance](#evidence-and-provenance)
62
+ - [Extraction Diagnostics](#extraction-diagnostics)
62
63
  - [Usage Examples](#usage-examples)
63
64
  - [Quick Search](#quick-search)
64
65
  - [Deep Research](#deep-research)
@@ -219,13 +220,13 @@ codex plugin marketplace add Curio-Data/pi-intelli-search
219
220
  codex plugin add intelli-search --marketplace curio-data-plugins
220
221
  ```
221
222
 
222
- After installation, open a [_Bash_](https://www.gnu.org/software/bash/) shell in the project folder whose `.search/` directory will hold research results. Store the OpenRouter key with the following commands from the plugin's 0.19 release line. The key travels through standard input, not process arguments or configuration JSON:
223
+ After installation, open a [_Bash_](https://www.gnu.org/software/bash/) shell in the project folder whose `.search/` directory will hold research results. Store the OpenRouter key with the setup command below. The key travels through standard input, not process arguments or configuration JSON:
223
224
 
224
225
  ```bash
225
226
  read -r -s -p 'OpenRouter API key: ' OPENROUTER_API_KEY
226
227
  printf '\n'
227
228
  printf '%s\n' "$OPENROUTER_API_KEY" | \
228
- npx -y --package @curio-data/mcp-intelli-search@0.19 \
229
+ npx -y --package @curio-data/mcp-intelli-search \
229
230
  mcp-intelli-search setup
230
231
  unset OPENROUTER_API_KEY
231
232
  codex
@@ -287,6 +288,18 @@ Research collation receives only successful, non-empty page extractions, not the
287
288
 
288
289
  Manual `intelli_collate` labels its evidence as caller-supplied extractions; it does not claim the server fetched those pages. Empty or duplicate source evidence is rejected. The optional `searchSummary` input remains accepted for compatibility but does not supply synthesis evidence. Per-source relevance and contribution ratings are no longer model-generated. Read exact cache paths from the inventory; `Not cached` means no full-page file was supplied.
289
290
 
291
+ ### Extraction Diagnostics
292
+
293
+ A completed research result can contain failed or incomplete sources. `details.pagesFailed` counts fetch failures; `details.extractionFailed` counts failures after a page was fetched. Inspect the failed-source list before relying on a report's coverage. A saved full-page link is provided only when that page was written to the cache. If pages were fetched but no extraction succeeds, the `extraction-failed` result returns the search summary and up to ten known failure reasons without writing a new report or saved pages. If every fetch fails, the separate `fetch-failed` result returns the search summary without a per-source reason list.
294
+
295
+ Nonempty output whose reported token count reaches the configured cap is kept with a truncation warning. `intelli_extract` returns `details.truncated`; research and manual collation mark affected sources in the Source Assessment inventory. A synthesis warning applies to the summary itself. Missing usage does not establish completeness, and `outcome: "completed"` does not guarantee complete source coverage.
296
+
297
+ For a budget-exhaustion diagnostic, review `extractionMaxTokens` for page extraction or `collationMaxTokens` for synthesis. On reasoning models, the budget includes reasoning as well as visible text. Increase the relevant cap within the model's output and context limits, or select a model with a smaller reasoning requirement. Lowering reasoning effort did not prevent exhaustion on the serving route identified in the investigation; it is not a guaranteed remedy. Read an available saved page before repeating paid research. Raising `llmTimeoutMs` addresses timer expiry, not an exhausted token budget or a host deadline.
298
+
299
+ A higher completion cap can permit more billable output and increase OpenRouter's in-flight credit reservation. The [Cost](#cost) estimate is a planning figure, not a spending limit; raising a cap does not mean every call consumes it.
300
+
301
+ Research sidecars, when enabled, record extraction-budget failures, possible truncation, available serving routes and cache-judge degradation. See [Telemetry Sidecar](https://github.com/Curio-Data/pi-intelli-search/blob/main/docs/ARCHITECTURE.md#telemetry-sidecar) for field definitions and absence semantics. Standalone extraction and collation do not write this sidecar.
302
+
290
303
  <a id="quick-start"></a>
291
304
  ## Usage Examples
292
305
 
@@ -341,7 +354,7 @@ The illustration shows the native pipeline with the model configuration at its c
341
354
 
342
355
  The search stage merges text links with harvested citation annotations before selecting pages (see [Source Harvesting from Citations](https://github.com/Curio-Data/pi-intelli-search/blob/main/README.md#source-harvesting-from-citations)). Each page is dual-fetched (HTML via Defuddle versus Markdown endpoint) and scored for quality. Per-page extraction (guided by `focusPrompt`) compresses ≈50K chars to ≈3-5K of query-relevant content before collation, keeping the total context manageable (≈30-50K for 10 pages).
343
356
 
344
- Completed runs and the degraded exits recorded in `outcome` (`no-links`, `fetch-failed`, `extraction-failed`) attempt to write a local-only `meta.json` telemetry sidecar into the cache directory (see [Cache Structure](#cache-structure)). Set `"disableTelemetry": true` in the native `pi-intelli-search` namespace or the MCP `tuning` object to suppress it.
357
+ Completed runs and the degraded exits recorded in `outcome` (`no-links`, `fetch-failed`, `extraction-failed`) attempt to write a local-only `meta.json` telemetry sidecar into the cache directory (see [Cache Structure](#cache-structure)). Set `"disableTelemetry": true` in the native `pi-intelli-search` namespace or the MCP `tuning` object to suppress it. Budget diagnostics and their absence semantics are defined in [Telemetry Sidecar](https://github.com/Curio-Data/pi-intelli-search/blob/main/docs/ARCHITECTURE.md#telemetry-sidecar); the [script guide](https://github.com/Curio-Data/pi-intelli-search/blob/main/scripts/README.md#reported-metrics) explains the available aggregates.
345
358
 
346
359
  See [docs/ARCHITECTURE.md](https://github.com/Curio-Data/pi-intelli-search/blob/main/docs/ARCHITECTURE.md) for detailed design decisions.
347
360
 
@@ -422,10 +435,10 @@ Unspecified tuning comes from the canonical [shared defaults](https://github.com
422
435
  | `maxUrls` | `20`: hard cap on research pages | Integer from 1 to 100 |
423
436
  | `extractMaxChars` | `150000`: per-page extraction input character limit | Integer from 1 to 2,000,000 |
424
437
  | `fetchTimeoutMs` | `20000`: page-fetch timeout in milliseconds | Integer from 1 to 600,000 |
425
- | `llmTimeoutMs` | `90000`: application timeout per model call in milliseconds | Integer from 1 to 600,000 |
438
+ | `llmTimeoutMs` | `120000`: application timeout per model call in milliseconds | Integer from 1 to 600,000 |
426
439
  | `fetchConcurrency` | `4`: simultaneous page fetches | Integer from 1 to 32 |
427
440
  | `extractionConcurrency` | `4`: simultaneous per-page extractions | Integer from 1 to 32 |
428
- | `extractionMaxTokens` | `3000`: per-page output-token limit | Integer from 16 to 128,000 |
441
+ | `extractionMaxTokens` | `8000`: per-page output-token limit (includes hidden reasoning tokens) | Integer from 16 to 128,000 |
429
442
  | `collationMaxTokens` | `4000`: synthesis output-token limit | Integer from 16 to 128,000 |
430
443
  | `llmRetryAttempts` | `3`: model-call attempts, including the first | Integer from 1 to 10 |
431
444
  | `searchRetryAttempts` | `2`: search attempts after a valid response with no usable links, including the first | Integer from 1 to 10 |
@@ -446,7 +459,7 @@ Unspecified tuning comes from the canonical [shared defaults](https://github.com
446
459
 
447
460
  **Reasoning:** The adapter sends reasoning fields only when the catalogue advertises reasoning support; non-reasoning models receive neither effort nor exclusion fields.
448
461
 
449
- **Output Budget:** Empty output after token-budget exhaustion is an error, not a successful extraction. Empty collation is likewise rejected before a completed report is written. When these diagnostics occur, increase `collationMaxTokens`, lower reasoning effort, or choose a model with a smaller reasoning budget.
462
+ **Output Budget:** Empty extraction output fails instead of becoming successful evidence; empty synthesis is rejected before a completed report is written. When reported output reaches the configured stage cap, nonempty output is retained with a truncation warning. Standalone `intelli_extract` returns `details.truncated`; pass it into manual `intelli_collate` to preserve the warning in its inventory and report. A capped synthesis is warned about in the report and tool result. Only `intelli_research` writes the telemetry sidecar, and only when enabled. Missing usage does not establish completeness. See [Extraction Diagnostics](#extraction-diagnostics) for recovery and the limits of these signals.
450
463
 
451
464
  ### Direct Engine Verification
452
465
 
@@ -487,7 +500,7 @@ This example incurs inference and search charges when run with a real credential
487
500
 
488
501
  Standalone validation rejects unknown argument keys, empty queries, nonpositive or fractional `maxUrls`, arrays exceeding 100 entries, strings exceeding 2,000,000 characters and unsupported extraction statuses. Most of these standalone validation rules are separate from the native tool schemas; the exception is the rejection of `maxUrls` values below 1, which the shared core schema also declares as `minimum: 1`, so it fails schema validation before the runtime's specific message. Positive fractional values at or above 1 still fail the standalone integer check.
489
502
 
490
- For manual extraction followed by collation, construct each collation item from the original `url` and `title`, `result.details.extraction` and `result.details.sourceType`, plus an explicit `status` such as `success`. Do not forward the entire extraction `details` object: its `currentness` field is not a collation input.
503
+ For manual extraction followed by collation, construct each successful collation item from the original `url` and `title`, `result.details.extraction` and `result.details.sourceType`, plus `status: "success"`. Copy `result.details.truncated` into the item's optional `truncated` field when present. If extraction fails, retain that source as a failed item with an empty `extraction`, an explicit `sourceType` such as `unknown`, `status: "failed"` and an optional bounded `error` string describing the failure. Failed items are listed for coverage but do not enter synthesis. Do not forward the entire extraction `details` object: its `currentness` field is not a collation input. Supply actual content in `fullPages` if the full-page file must be cached.
491
504
 
492
505
  `mcp-intelli-search --help` and `--version` need no configuration. `--check-config` validates explicit configuration and workspace syntax without credentials or inference, returning exit status 0 for valid configuration and 1 for invalid input. Neither starts a protocol connection. `loadConfig()` throws an exported `ConfigurationError` for file defects, with a `reason` of `missing`, `unreadable`, `invalid-json` or `invalid`; workspace failures remain separate. JSON syntax diagnostics include a location without echoing file contents. The runtime entrypoint is experimental and has no published TypeScript declaration contract. Execution failures expose a safe `StandaloneError.code`: `INVALID_ARGUMENTS`, `CONFIGURATION`, `WORKSPACE`, `PROVIDER`, `OPERATION` or `CANCELLED`. Cancellation uses the `AbortError` name. Raw provider causes are deliberately not retained. Some shared operations wrap provider exceptions, which become `OPERATION` errors; protocol mapping must not depend on exact diagnostic strings.
493
506
 
@@ -22,12 +22,22 @@ function tuningDefaults() {
22
22
  fetchTimeoutMs: 2e4,
23
23
  fetchConcurrency: 4,
24
24
  extractionConcurrency: 4,
25
- extractionMaxTokens: 3e3,
25
+ // The completion cap covers hidden reasoning tokens on reasoning models
26
+ // (the default MiniMax M3 reasons for thousands of tokens before any
27
+ // visible text, and a budget-exhausted call returns empty output with
28
+ // finish_reason "length"). 8,000 cleared the failure in live probes
29
+ // (2026-11-02 investigation and reviews); the reasoning tail is route-
30
+ // and page-dependent, so telemetry records residual exhaustion
31
+ // (evidence/2026-11-02-extract-failure-agentskills-io).
32
+ extractionMaxTokens: 8e3,
26
33
  collationMaxTokens: 4e3,
27
34
  browserFingerprint: "chrome_145",
28
35
  disableLlmsFullDiscovery: false,
29
36
  disableTelemetry: false,
30
- llmTimeoutMs: 9e4,
37
+ // Scaled with extractionMaxTokens in 0.20.0: an 8,000-token completion at
38
+ // the observed ≈95-104 tokens/s takes 77-84s, so the previous 90s default
39
+ // could abort exactly the calls the raised cap was meant to rescue.
40
+ llmTimeoutMs: 12e4,
31
41
  llmRetryAttempts: 3,
32
42
  retryBaseDelayMs: 1500,
33
43
  retryMaxDelayMs: 2e4,
@@ -4,7 +4,7 @@ import {
4
4
  resolveCredential,
5
5
  validateCacheDir,
6
6
  validateDomains
7
- } from "./chunk-57DS6B3Q.js";
7
+ } from "./chunk-LXLEWIYT.js";
8
8
 
9
9
  // packages/mcp/src/runtime.ts
10
10
  import { Check } from "typebox/value";
@@ -149,6 +149,10 @@ async function withMuzzledConsole(fn, muzzleTags) {
149
149
  }
150
150
 
151
151
  // src/core/util.ts
152
+ function budgetExhausted(usage2, maxTokens) {
153
+ if (usage2?.output == null || maxTokens == null) return false;
154
+ return usage2.output >= maxTokens;
155
+ }
152
156
  function throwIfAborted(signal) {
153
157
  if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
154
158
  }
@@ -693,7 +697,7 @@ ${summary}
693
697
  const extractionFile = identity2.extractionFileFor(source.url);
694
698
  if (!extractionFile) invalid("an evidence source has no extraction file");
695
699
  const fullPage = identity2.sourceFileFor(source.url);
696
- result += `| S${index + 1} | ${cell(source.url)} | ${cell(source.sourceType)} | ${evidence === "fetched" ? "Fetched and extracted" : "Caller-supplied extraction"} | ${cell(`${cachePath}/extractions/${extractionFile}`)} | ${fullPage ? cell(`${cachePath}/sources/${fullPage}`) : "Not cached"} |
700
+ result += `| S${index + 1} | ${cell(source.url)} | ${cell(source.sourceType)}${source.truncated ? " \u26A0 truncated" : ""} | ${evidence === "fetched" ? "Fetched and extracted" : "Caller-supplied extraction"} | ${cell(`${cachePath}/extractions/${extractionFile}`)} | ${fullPage ? cell(`${cachePath}/sources/${fullPage}`) : "Not cached"} |
697
701
  `;
698
702
  }
699
703
  return result.trimEnd();
@@ -762,7 +766,7 @@ function buildCollationMessage(query, _cachePath, _searchSummary, succeededExtra
762
766
  }))
763
767
  }, null, 2);
764
768
  }
765
- function formatCacheAppendix(cachePath, succeeded, failed) {
769
+ function formatCacheAppendix(cachePath, succeeded, failed, failedEntries = [], truncatedCount = 0) {
766
770
  let out = `
767
771
 
768
772
  ---
@@ -771,13 +775,25 @@ function formatCacheAppendix(cachePath, succeeded, failed) {
771
775
  `;
772
776
  out += `**Report**: \`${cachePath}/report.md\`
773
777
  `;
774
- out += `**Sources**: ${succeeded} succeeded, ${failed} failed
778
+ out += `**Sources**: ${succeeded} succeeded${truncatedCount > 0 ? ` (${truncatedCount} truncated at the output cap)` : ""}, ${failed} failed
775
779
  `;
776
780
  out += `
777
781
  - Read the report: \`read ${cachePath}/report.md\`
778
782
  `;
783
+ if (failedEntries.length > 0) {
784
+ out += `
785
+ **Failed Sources**:
786
+ `;
787
+ for (const entry of failedEntries) {
788
+ out += `- ${entry.url}`;
789
+ if (entry.error) out += `: ${entry.error}`;
790
+ if (entry.sourceFile) out += ` (full page saved: \`${cachePath}/${entry.sourceFile}\`)`;
791
+ out += `
792
+ `;
793
+ }
794
+ }
779
795
  out += `
780
- Choose exact extraction and full-page paths from the Source assessment above; Not cached means no full-page file exists for that source.
796
+ Choose exact extraction and full-page paths from the Source Assessment above. Not cached means no full-page file exists for that source.
781
797
  `;
782
798
  return out;
783
799
  }
@@ -847,7 +863,7 @@ async function extract(params, context) {
847
863
  params.focusPrompt,
848
864
  settings.extractMaxChars
849
865
  );
850
- const { text: extraction } = await models.complete({
866
+ const { text: extraction, usage: usage2 } = await models.complete({
851
867
  model: extractConfig,
852
868
  systemPrompt: EXTRACTION_SYSTEM_PROMPT,
853
869
  userMessage,
@@ -855,15 +871,26 @@ async function extract(params, context) {
855
871
  signal
856
872
  });
857
873
  throwIfAborted(signal);
874
+ if (!extraction.trim()) {
875
+ const exhausted = budgetExhausted(usage2, settings.extractionMaxTokens);
876
+ const usageNote = usage2?.output != null ? ` (${usage2.output}/${settings.extractionMaxTokens} output tokens` + (usage2.reasoning ? `, ${usage2.reasoning} hidden reasoning` : "") + ")" : "";
877
+ throw new Error(
878
+ exhausted ? `Extraction returned no visible text${usageNote}; the output budget was exhausted. Review extractionMaxTokens or choose a model with a smaller reasoning requirement.` : `Extraction returned no visible text${usageNote}. The output budget was not reported exhausted; inspect the model response before retrying.`
879
+ );
880
+ }
858
881
  const firstLine = extraction.split("\n")[0] ?? "";
859
882
  const sourceType = inferSourceType(firstLine);
860
883
  const currentness = inferCurrentness(firstLine);
884
+ const truncated = budgetExhausted(usage2, settings.extractionMaxTokens);
885
+ const truncationNote = truncated ? `
886
+
887
+ > \u26A0 Extraction output reached extractionMaxTokens (${settings.extractionMaxTokens}); the text may be cut off mid-sentence.` : "";
861
888
  return {
862
889
  text: `### Extraction: ${params.title}
863
890
 
864
- ${extraction}`,
891
+ ${extraction}${truncationNote}`,
865
892
  outcome: "completed",
866
- details: { url: params.url, extraction, sourceType, currentness }
893
+ details: { url: params.url, extraction, sourceType, currentness, ...truncated ? { truncated: true } : {} }
867
894
  };
868
895
  }
869
896
 
@@ -1149,7 +1176,7 @@ async function writeReportFile(cachePath, query, collation, extractions, pages,
1149
1176
  for (const [i, ext] of succeeded.entries()) {
1150
1177
  const extractionFile = identity2.extractionFileFor(ext.url);
1151
1178
  const sourceFile = identity2.sourceFileFor(ext.url);
1152
- report += `| ${i + 1} | ${ext.url} | ${ext.sourceType} | ${extractionFile ? `extractions/${extractionFile}` : "Not cached"} | ${sourceFile ? `sources/${sourceFile}` : "Not cached"} |
1179
+ report += `| ${i + 1} | ${ext.url} | ${ext.sourceType}${ext.truncated ? " (\u26A0 truncated at the output cap)" : ""} | ${extractionFile ? `extractions/${extractionFile}` : "Not cached"} | ${sourceFile ? `sources/${sourceFile}` : "Not cached"} |
1153
1180
  `;
1154
1181
  }
1155
1182
  }
@@ -1159,8 +1186,10 @@ async function writeReportFile(cachePath, query, collation, extractions, pages,
1159
1186
 
1160
1187
  `;
1161
1188
  for (const entry of blocked) {
1162
- const error = pages.find((page) => page.url === entry.url)?.error;
1163
- report += `- ${entry.url}: ${error ?? (entry.status === "blocked" ? "Source marked blocked" : "Extraction failed")}
1189
+ const fetchError = pages.find((page) => page.url === entry.url)?.error;
1190
+ const reason = entry.error ?? fetchError ?? (entry.status === "blocked" ? "Source marked blocked" : "Extraction failed");
1191
+ const savedSource = identity2.sourceFileFor(entry.url);
1192
+ report += `- ${entry.url}: ${reason}${savedSource ? ` (full page saved: sources/${savedSource})` : ""}
1164
1193
  `;
1165
1194
  }
1166
1195
  }
@@ -1209,6 +1238,15 @@ function formatIndexForJudge(index, excludeSlug) {
1209
1238
  if (entries.length === 0) return "No previous searches.";
1210
1239
  return entries.map((e, i) => `${i + 1}. "${e.query}" (slug: ${e.slug}, searched: ${e.timestamp})`).join("\n");
1211
1240
  }
1241
+ function isWellFormedJudgeResponse(response) {
1242
+ const jsonMatch = response.match(/\[[\s\S]*\]/);
1243
+ if (!jsonMatch) return false;
1244
+ try {
1245
+ return Array.isArray(JSON.parse(jsonMatch[0]));
1246
+ } catch {
1247
+ return false;
1248
+ }
1249
+ }
1212
1250
  function parseJudgeResponse(response, index, excludeSlug) {
1213
1251
  const candidates = judgeCandidates(index, excludeSlug);
1214
1252
  const jsonMatch = response.match(/\[[\s\S]*\]/);
@@ -1270,7 +1308,9 @@ async function collate(params, context) {
1270
1308
  extraction: e.extraction,
1271
1309
  sourceType: e.sourceType,
1272
1310
  currentness: "undated",
1273
- status: e.status === "success" && !e.extraction.trim() ? "failed" : e.status
1311
+ status: e.status === "success" && !e.extraction.trim() ? "failed" : e.status,
1312
+ ...e.truncated ? { truncated: true } : {},
1313
+ ...e.error ? { error: e.error } : {}
1274
1314
  }));
1275
1315
  const succeeded = evidenceExtractions(extractResults);
1276
1316
  const blocked = extractResults.filter((e) => e.status !== "success");
@@ -1289,14 +1329,19 @@ async function collate(params, context) {
1289
1329
  succeeded,
1290
1330
  identity2
1291
1331
  );
1292
- const { text } = await models.complete({
1332
+ const { text, usage: usage2 } = await models.complete({
1293
1333
  model: collateConfig,
1294
1334
  systemPrompt: COLLATION_SYSTEM_PROMPT,
1295
1335
  userMessage,
1296
1336
  maxTokens: settings.collationMaxTokens,
1297
1337
  signal
1298
1338
  });
1299
- const collation = finalizeCollation(text, cachePath, succeeded, identity2, "supplied");
1339
+ let collation = finalizeCollation(text, cachePath, succeeded, identity2, "supplied");
1340
+ if (budgetExhausted(usage2, settings.collationMaxTokens)) {
1341
+ collation += `
1342
+
1343
+ > \u26A0 Collation output reached collationMaxTokens (${settings.collationMaxTokens}); the synthesis may be cut off mid-sentence. Raise collationMaxTokens or re-run if completeness matters.`;
1344
+ }
1300
1345
  await withLock(
1301
1346
  cacheLockDir(physicalPath),
1302
1347
  async () => {
@@ -1332,8 +1377,14 @@ async function collate(params, context) {
1332
1377
  },
1333
1378
  signal
1334
1379
  );
1380
+ const failedEntries = extractResults.filter((e) => e.status !== "success").map((e) => ({
1381
+ url: e.url,
1382
+ ...e.error ? { error: e.error } : {},
1383
+ ...identity2.sourceFileFor(e.url) ? { sourceFile: `sources/${identity2.sourceFileFor(e.url)}` } : {}
1384
+ }));
1385
+ const truncatedCount = succeeded.filter((e) => e.truncated).length;
1335
1386
  return {
1336
- text: collation + formatCacheAppendix(cachePath, succeeded.length, blocked.length),
1387
+ text: collation + formatCacheAppendix(cachePath, succeeded.length, blocked.length, failedEntries, truncatedCount),
1337
1388
  outcome: "completed",
1338
1389
  details: { cachePath, sourcesFetched: succeeded.length + blocked.length }
1339
1390
  };
@@ -1838,10 +1889,18 @@ ${search2.searchResult}`,
1838
1889
  const fetchFailed = extracted.blockedExtractions.length;
1839
1890
  const extractFailed = extracted.extractions.filter((e) => e.status === "failed").length;
1840
1891
  const reason = fetchFailed > 0 ? `${fetchFailed} page(s) failed to fetch` : `${extractFailed} extraction(s) failed`;
1892
+ const failureLines = allExtractions.filter((e) => e.status !== "success" && (e.error || fetched.pages.find((pg) => pg.url === e.url)?.error)).map((e) => {
1893
+ const detail = e.error ?? fetched.pages.find((pg) => pg.url === e.url)?.error;
1894
+ return `- ${e.url}: ${String(detail).replace(/\s+/g, " ").slice(0, 200)}`;
1895
+ }).slice(0, 10).join("\n");
1896
+ const failureBlock = failureLines ? `
1897
+
1898
+ Failed Sources (up to 10 known reasons):
1899
+ ${failureLines}` : "";
1841
1900
  return degradedReturn(
1842
1901
  p,
1843
1902
  "extraction-failed",
1844
- `${reason}. No content was extracted.
1903
+ `${reason}. No content was extracted.${failureBlock}
1845
1904
 
1846
1905
  Search summary:
1847
1906
  ${search2.searchResult}`,
@@ -1849,7 +1908,8 @@ ${search2.searchResult}`,
1849
1908
  cachePath: "",
1850
1909
  urlsSearched: search2.urls.length,
1851
1910
  pagesFetched: fetched.successPages.length,
1852
- pagesFailed: fetched.pages.length - fetched.successPages.length
1911
+ pagesFailed: fetched.pages.length - fetched.successPages.length,
1912
+ extractionFailed: extractFailed
1853
1913
  }
1854
1914
  );
1855
1915
  }
@@ -1874,7 +1934,28 @@ ${search2.searchResult}`,
1874
1934
  throwIfAborted(p.signal);
1875
1935
  await writeLockedTelemetry(p, "completed");
1876
1936
  const failedCount = fetched.pages.length - fetched.successPages.length;
1877
- const result = collation + formatCacheAppendix(p.cachePath, succeededExtractions.length, allExtractions.length - succeededExtractions.length) + suggestionsAppendix;
1937
+ const extractionFailures = allExtractions.filter((e) => e.status === "failed").length;
1938
+ const truncatedCount = succeededExtractions.filter((e) => e.truncated).length;
1939
+ const failedEntries = allExtractions.filter((e) => e.status !== "success").map((e) => {
1940
+ const savedSource = identity2.sourceFileFor(e.url);
1941
+ return {
1942
+ url: e.url,
1943
+ // Extraction reason when the extract call failed; fetch error when
1944
+ // the page never made it that far (blocked entries carry none).
1945
+ ...e.error ? { error: e.error } : {},
1946
+ ...fetched.pages.find((page) => page.url === e.url)?.error ? { error: fetched.pages.find((page) => page.url === e.url).error.slice(0, 300) } : {},
1947
+ // The full page stays on disk even when extraction failed; pointing
1948
+ // the agent at it recovers work that was already paid for.
1949
+ ...savedSource ? { sourceFile: `sources/${savedSource}` } : {}
1950
+ };
1951
+ });
1952
+ const result = collation + formatCacheAppendix(
1953
+ p.cachePath,
1954
+ succeededExtractions.length,
1955
+ allExtractions.length - succeededExtractions.length,
1956
+ failedEntries,
1957
+ truncatedCount
1958
+ ) + suggestionsAppendix;
1878
1959
  return {
1879
1960
  text: result,
1880
1961
  outcome: "completed",
@@ -1882,7 +1963,10 @@ ${search2.searchResult}`,
1882
1963
  cachePath: p.cachePath,
1883
1964
  urlsSearched: search2.urls.length,
1884
1965
  pagesFetched: fetched.successPages.length,
1885
- pagesFailed: failedCount
1966
+ pagesFailed: failedCount,
1967
+ // Extraction failures only (status "failed"); pagesFailed counts fetch
1968
+ // failures (status "blocked"), so the two never double-count a page.
1969
+ extractionFailed: extractionFailures
1886
1970
  }
1887
1971
  };
1888
1972
  }
@@ -2017,6 +2101,14 @@ async function runExtractStage(p, successPages, pages) {
2017
2101
  }));
2018
2102
  const succeededExtr = extractions.filter((e) => e.status === "success");
2019
2103
  const failedExtr = extractions.length - succeededExtr.length;
2104
+ let budgetExhaustedFailures = 0;
2105
+ for (const e of extractions) {
2106
+ if (e.status === "failed" && e.failureKind === "budget") budgetExhaustedFailures += 1;
2107
+ }
2108
+ const truncatedCount = succeededExtr.filter((e) => e.truncated).length;
2109
+ const routeProviders = new Set(
2110
+ extractions.filter((e) => e.routeProvider).map((e) => e.routeProvider)
2111
+ );
2020
2112
  const totalIn = successPages.reduce(
2021
2113
  (sum, pg) => sum + Math.min(pg.content.length, p.settings.extractMaxChars),
2022
2114
  0
@@ -2027,7 +2119,15 @@ async function runExtractStage(p, successPages, pages) {
2027
2119
  succeeded: succeededExtr.length,
2028
2120
  failed: failedExtr,
2029
2121
  totalInputCharsApprox: totalIn,
2030
- totalOutputChars: totalOut
2122
+ totalOutputChars: totalOut,
2123
+ ...truncatedCount > 0 ? { truncated: truncatedCount } : {},
2124
+ ...failedExtr > 0 ? {
2125
+ failureReasons: {
2126
+ budgetExhausted: budgetExhaustedFailures,
2127
+ other: failedExtr - budgetExhaustedFailures
2128
+ }
2129
+ } : {},
2130
+ ...routeProviders.size === 1 ? { provider: [...routeProviders][0] } : {}
2031
2131
  });
2032
2132
  return { extractions, blockedExtractions };
2033
2133
  }
@@ -2040,7 +2140,7 @@ async function runCollateStage(p, searchResult, succeededExtractions, identity2)
2040
2140
  identity2
2041
2141
  );
2042
2142
  throwIfAborted(p.signal);
2043
- const { text } = await p.models.complete({
2143
+ const { text, usage: usage2, routeProvider } = await p.models.complete({
2044
2144
  model: p.collateConfig,
2045
2145
  systemPrompt: COLLATION_SYSTEM_PROMPT,
2046
2146
  userMessage: collationUserMsg,
@@ -2050,10 +2150,18 @@ async function runCollateStage(p, searchResult, succeededExtractions, identity2)
2050
2150
  timeoutMs: p.settings.llmTimeoutMs,
2051
2151
  onRetryNotice: (msg) => p.onProgress?.(progress("collate", msg))
2052
2152
  });
2053
- const collation = finalizeCollation(text, p.cachePath, succeededExtractions, identity2, "fetched");
2153
+ let collation = finalizeCollation(text, p.cachePath, succeededExtractions, identity2, "fetched");
2154
+ const collateTruncated = budgetExhausted(usage2, p.settings.collationMaxTokens);
2155
+ if (collateTruncated) {
2156
+ collation += `
2157
+
2158
+ > \u26A0 Collation output reached collationMaxTokens (${p.settings.collationMaxTokens}); the synthesis may be cut off mid-sentence. Raise collationMaxTokens or re-run if completeness matters.`;
2159
+ }
2054
2160
  p.tel?.recordCollate({
2055
2161
  model: `${p.collateConfig.provider}/${p.collateConfig.model}`,
2056
- summaryChars: text.trim().length
2162
+ summaryChars: text.trim().length,
2163
+ ...collateTruncated ? { truncated: true } : {},
2164
+ ...routeProvider ? { provider: routeProvider } : {}
2057
2165
  });
2058
2166
  return collation;
2059
2167
  }
@@ -2151,9 +2259,12 @@ async function runCacheSuggestStage(p) {
2151
2259
  let cacheSuggestRan = false;
2152
2260
  let cacheSuggestSurfaced = 0;
2153
2261
  let cacheSuggestSlugs = [];
2262
+ let cacheSuggestDegraded;
2263
+ let judgeAttempted = false;
2154
2264
  try {
2155
2265
  const index = await readIndex(p.paths.cacheRoot);
2156
2266
  if (index.searches.some((e) => e.slug !== currentSlug)) {
2267
+ judgeAttempted = true;
2157
2268
  const indexText = formatIndexForJudge(index, currentSlug);
2158
2269
  const judgeUserMsg = `Current query: "${p.params.query}"
2159
2270
 
@@ -2163,12 +2274,18 @@ ${indexText}`;
2163
2274
  model: p.extractConfig,
2164
2275
  systemPrompt: CACHE_SUGGEST_PROMPT,
2165
2276
  userMessage: judgeUserMsg,
2166
- maxTokens: 500,
2277
+ maxTokens: 2e3,
2167
2278
  signal: p.signal,
2168
2279
  retry: p.retry,
2169
2280
  timeoutMs: p.settings.llmTimeoutMs,
2170
2281
  onRetryNotice: (msg) => p.onProgress?.(progress("cache", msg))
2171
2282
  });
2283
+ if (!judgeResponse.trim() || !isWellFormedJudgeResponse(judgeResponse)) {
2284
+ cacheSuggestDegraded = true;
2285
+ p.logger.error(
2286
+ `Cache suggest judge returned ${judgeResponse.trim() ? "an unparseable" : "an empty"} response; treating as zero matches`
2287
+ );
2288
+ }
2172
2289
  const matches = parseJudgeResponse(judgeResponse, index, currentSlug);
2173
2290
  cacheSuggestRan = true;
2174
2291
  cacheSuggestSurfaced = matches.length;
@@ -2177,12 +2294,14 @@ ${indexText}`;
2177
2294
  }
2178
2295
  } catch (err) {
2179
2296
  throwIfAborted(p.signal);
2297
+ if (judgeAttempted) cacheSuggestDegraded = true;
2180
2298
  p.logger.error(`Cache suggest failed: ${errMsg(err)}`);
2181
2299
  }
2182
2300
  p.tel?.recordCacheSuggest({
2183
2301
  ran: cacheSuggestRan,
2184
2302
  surfaced: cacheSuggestSurfaced,
2185
- slugs: cacheSuggestSlugs
2303
+ slugs: cacheSuggestSlugs,
2304
+ ...cacheSuggestDegraded ? { degraded: true } : {}
2186
2305
  });
2187
2306
  return suggestionsAppendix;
2188
2307
  }
@@ -2263,6 +2382,8 @@ async function writeTelemetrySidecar(logger, tel, cachePath, outcome) {
2263
2382
  }
2264
2383
  async function extractPage(p, page) {
2265
2384
  throwIfAborted(p.signal);
2385
+ let exhausted;
2386
+ let routeProvider;
2266
2387
  try {
2267
2388
  const userMessage = buildExtractionMessage(
2268
2389
  page.content,
@@ -2270,7 +2391,7 @@ async function extractPage(p, page) {
2270
2391
  p.params.focusPrompt,
2271
2392
  p.settings.extractMaxChars
2272
2393
  );
2273
- const { text: extraction } = await p.models.complete({
2394
+ const completion = await p.models.complete({
2274
2395
  model: p.extractConfig,
2275
2396
  systemPrompt: EXTRACTION_SYSTEM_PROMPT,
2276
2397
  userMessage,
@@ -2280,7 +2401,15 @@ async function extractPage(p, page) {
2280
2401
  timeoutMs: p.settings.llmTimeoutMs,
2281
2402
  onRetryNotice: (msg) => p.onProgress?.(progress("extract", msg))
2282
2403
  });
2283
- if (!extraction.trim()) throw new Error("Extraction returned no visible evidence");
2404
+ const { text: extraction, usage: usage2 } = completion;
2405
+ routeProvider = completion.routeProvider;
2406
+ exhausted = budgetExhausted(usage2, p.settings.extractionMaxTokens);
2407
+ if (!extraction.trim()) {
2408
+ const usageNote = usage2?.output != null ? ` (${usage2.output}/${p.settings.extractionMaxTokens} output tokens` + (usage2.reasoning ? `, ${usage2.reasoning} hidden reasoning` : "") + ")" : "";
2409
+ throw new Error(
2410
+ exhausted ? `Extraction returned no visible text${usageNote}; the output budget was exhausted. Review extractionMaxTokens or choose a model with a smaller reasoning requirement.` : `Extraction returned no visible text${usageNote}. The output budget was not reported exhausted; inspect the model response before retrying.`
2411
+ );
2412
+ }
2284
2413
  const firstLine = extraction.split("\n")[0] ?? "";
2285
2414
  return {
2286
2415
  url: page.url,
@@ -2288,18 +2417,28 @@ async function extractPage(p, page) {
2288
2417
  extraction,
2289
2418
  sourceType: inferSourceType(firstLine),
2290
2419
  currentness: inferCurrentness(firstLine),
2291
- status: "success"
2420
+ status: "success",
2421
+ // Nonempty output cut off by the cap: kept, but flagged so the report
2422
+ // and telemetry can say so. Missing usage never flags.
2423
+ truncated: exhausted || void 0,
2424
+ ...routeProvider ? { routeProvider } : {}
2292
2425
  };
2293
2426
  } catch (err) {
2294
2427
  throwIfAborted(p.signal);
2295
- p.logger.error(`Extraction failed for ${page.url}: ${errMsg(err)}`);
2428
+ const message = errMsg(err).replace(/\s+/g, " ").trim().slice(0, 300) || "extraction failed";
2429
+ p.logger.error(`Extraction failed for ${page.url}: ${message}`);
2296
2430
  return {
2297
2431
  url: page.url,
2298
2432
  title: page.title,
2299
2433
  extraction: "",
2300
2434
  sourceType: "unknown",
2301
2435
  currentness: "unknown",
2302
- status: "failed"
2436
+ status: "failed",
2437
+ error: message + (errMsg(err).length > 300 ? "\u2026" : ""),
2438
+ // Structured classification: usage-based when the call completed, else
2439
+ // a match against our own adapter messages (never free provider text).
2440
+ failureKind: exhausted === true || /exhausted the output budget/.test(message) ? "budget" : "other",
2441
+ ...routeProvider ? { routeProvider } : {}
2303
2442
  };
2304
2443
  }
2305
2444
  }
@@ -2311,7 +2450,12 @@ var extractionSchema = Type.Object({
2311
2450
  title: Type.String(),
2312
2451
  extraction: Type.String(),
2313
2452
  sourceType: Type.String(),
2314
- status: Type.String()
2453
+ status: Type.String(),
2454
+ // Optional diagnostics carried from intelli_extract results: a truncation
2455
+ // flag and the bounded failure reason. Optional so strict argument sampling
2456
+ // that knows only the five core keys keeps working.
2457
+ truncated: Type.Optional(Type.Boolean()),
2458
+ error: Type.Optional(Type.String())
2315
2459
  });
2316
2460
  var fullPageSchema = Type.Object({
2317
2461
  url: Type.String(),
@@ -2604,17 +2748,23 @@ function createOpenRouterClient(config, options) {
2604
2748
  const message = record(choice.message);
2605
2749
  if (message.refusal || choice.finish_reason === "content_filter")
2606
2750
  throw new Error("OpenRouter declined the request under provider policy");
2607
- if (typeof message.content !== "string")
2608
- throw new Error("OpenRouter returned no text completion");
2609
- if (!message.content.trim() && choice.finish_reason === "length")
2751
+ const content = message.content;
2752
+ const emptyish = content == null || typeof content === "string" && !content.trim();
2753
+ if (emptyish && choice.finish_reason === "length") {
2754
+ const reported = usage(data.usage);
2755
+ const counts = reported?.output != null ? ` (${reported.output} output tokens` + (reported.reasoning ? `, ${reported.reasoning} hidden reasoning` : "") + ")" : "";
2610
2756
  throw new Error(
2611
- "OpenRouter exhausted the output budget without visible text; increase token limits or lower reasoning effort"
2757
+ "OpenRouter exhausted the output budget without visible text" + counts + " (the cap includes any reasoning tokens). For extraction, review extractionMaxTokens; for synthesis, review collationMaxTokens. If this diagnostic came from search or cache suggestions, report the stage because those output caps are not exposed as tuning settings."
2612
2758
  );
2759
+ }
2760
+ if (typeof content !== "string")
2761
+ throw new Error("OpenRouter returned no text completion");
2613
2762
  return {
2614
2763
  value: {
2615
- text: message.content,
2764
+ text: content,
2616
2765
  citations: request.collectCitations ? parseCitations(raw) : [],
2617
- usage: usage(data.usage)
2766
+ usage: usage(data.usage),
2767
+ ...typeof data.provider === "string" && data.provider ? { routeProvider: data.provider } : {}
2618
2768
  }
2619
2769
  };
2620
2770
  },
package/dist/cli.js CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  loadConfig,
11
11
  resolveWorkspace,
12
12
  setupHost
13
- } from "./chunk-57DS6B3Q.js";
13
+ } from "./chunk-LXLEWIYT.js";
14
14
 
15
15
  // packages/mcp/src/cli.ts
16
16
  import { parseArgs } from "node:util";
package/dist/runtime.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  createRuntime
3
- } from "./chunk-V5TY66GM.js";
3
+ } from "./chunk-NLULRY33.js";
4
4
  import {
5
5
  ConfigurationError,
6
6
  StandaloneError,
7
7
  identity,
8
8
  loadConfig,
9
9
  parseConfig
10
- } from "./chunk-57DS6B3Q.js";
10
+ } from "./chunk-LXLEWIYT.js";
11
11
  export {
12
12
  ConfigurationError,
13
13
  StandaloneError,
package/dist/server.js CHANGED
@@ -7,12 +7,12 @@ import {
7
7
  extractSchema,
8
8
  researchSchema,
9
9
  searchSchema
10
- } from "./chunk-V5TY66GM.js";
10
+ } from "./chunk-NLULRY33.js";
11
11
  import {
12
12
  ConfigurationError,
13
13
  StandaloneError,
14
14
  identity
15
- } from "./chunk-57DS6B3Q.js";
15
+ } from "./chunk-LXLEWIYT.js";
16
16
 
17
17
  // packages/mcp/src/server.ts
18
18
  import { McpServer, fromJsonSchema } from "@modelcontextprotocol/server";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@curio-data/mcp-intelli-search",
3
- "version": "0.19.1",
3
+ "version": "0.20.0",
4
4
  "description": "Standalone intelligent web research engine and Model Context Protocol stdio server.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",