@curio-data/mcp-intelli-search 0.19.0 → 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-653%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
 
@@ -43,7 +43,7 @@ Choose the installation route for the host:
43
43
 
44
44
  The install branches: [`Pi` Native Extension](https://github.com/Curio-Data/pi-intelli-search/blob/main/README.md#pi-native-extension) and [MCP Server](#mcp-server), with host instructions for [Claude Code](#claude-code), [Codex](#codex) and any [Generic MCP Host](#generic-mcp-host).
45
45
 
46
- The native extension uses `Pi` settings and authentication. The MCP server requires explicit configuration, a per-folder workspace and an environment-supplied inference key; it does not read `Pi` settings or credentials.
46
+ The native extension uses `Pi` settings and authentication. Generic MCP registration requires explicit configuration and a workspace; the Codex launcher supplies project and model defaults. Inference uses an OpenRouter key supplied through the configured environment variable or credential file. The MCP server does not read `Pi` settings or credentials.
47
47
 
48
48
  ## Contents
49
49
 
@@ -59,6 +59,7 @@ The native extension uses `Pi` settings and authentication. The MCP server requi
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)
@@ -100,7 +101,7 @@ The native extension uses `Pi` settings and authentication. The MCP server requi
100
101
  - An [OpenRouter API key](https://openrouter.ai/keys) with credit for inference. One key covers all three model roles; charges are separate from the host subscription.
101
102
  - An existing project folder for the research cache. The server and host must be able to read the same filesystem.
102
103
 
103
- The server requires an explicit JavaScript Object Notation (JSON) configuration and absolute workspace path. It reads no host credential stores, `Pi` settings or discovered project configuration. Native fetch assets are verified on _Linux_ x86-64; _macOS_ and _Windows_ are not verified. See [Compatibility](#mcp-server-compatibility) for the recorded scope.
104
+ Generic registration requires an explicit JavaScript Object Notation (JSON) configuration and absolute workspace path. The Codex launcher supplies its working root as the workspace and uses documented model defaults when no per-user configuration exists. The server reads no host credential stores, `Pi` settings or discovered project configuration. Native fetch assets are verified on _Linux_ x86-64; _macOS_ and _Windows_ are not verified. See [Compatibility](#mcp-server-compatibility) for the recorded scope.
104
105
 
105
106
  #### Claude Code
106
107
 
@@ -219,17 +220,27 @@ 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
- Save the [minimal configuration](#create-the-configuration) as `.intelli-search.json` in the project folder and [supply the API key](#supply-the-api-key). From that folder, export the paths before launching Codex:
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
- export INTELLI_SEARCH_CONFIG="$PWD/.intelli-search.json"
226
- export INTELLI_SEARCH_WORKSPACE="$PWD"
226
+ read -r -s -p 'OpenRouter API key: ' OPENROUTER_API_KEY
227
+ printf '\n'
228
+ printf '%s\n' "$OPENROUTER_API_KEY" | \
229
+ npx -y --package @curio-data/mcp-intelli-search \
230
+ mcp-intelli-search setup
231
+ unset OPENROUTER_API_KEY
227
232
  codex
228
233
  ```
229
234
 
230
- In the session, ask: “Use intelli_search to find the current TypeScript release and cite the official source.” Confirm a successful MCP tool call and an answer with sources. `codex mcp list` alone does not start the server or prove inference. If the tools are unavailable, the setup is incomplete: an answer from the host's own web search does not show that this server ran.
235
+ Setup creates `${XDG_CONFIG_HOME:-$HOME/.config}/mcp-intelli-search/config.json` when absent and stores the key separately as `openrouter.key` with user-only permissions. Existing model and tuning selections are preserved. Setup adds a missing `apiKeyFile` selection and honours an existing custom credential path.
236
+
237
+ The next tool call reads a new or replacement key without a restart when the loaded configuration selects that path. Restart after changing loaded configuration. An exported `OPENROUTER_API_KEY` remains an alternative and takes precedence over the file. Confirm that setup prints `Setup complete.` before starting or using Codex.
231
238
 
232
- Codex filters the server environment; the plugin forwards `OPENROUTER_API_KEY`, `INTELLI_SEARCH_CONFIG` and `INTELLI_SEARCH_WORKSPACE` explicitly. Set all three before each launch. The installed `intelli-search` skill covers persistent configuration and unattended tool approval; see the [compatibility matrix](https://github.com/Curio-Data/pi-intelli-search/blob/main/docs/COMPATIBILITY.md#host-plugins) for verified host behaviour.
239
+ The plugin starts with `--host codex`, uses the Codex working root as its workspace and needs no path or credential exports. Legacy `INTELLI_SEARCH_CONFIG` and `INTELLI_SEARCH_WORKSPACE` exports are ignored in this mode; explicit command-line selections remain available. A home or filesystem-root working directory produces an actionable `WORKSPACE` tool error instead of an accidental shared cache; restart Codex from the project or with `--cd <project>`. Its four tools appear even before setup. A missing key produces an actionable `CONFIGURATION` tool error rather than a server startup failure. Customise the per-user `config.json` to override the documented default models or tuning, then restart Codex.
240
+
241
+ In the session, ask: “Use intelli_search to find the current TypeScript release and cite the official source.” Confirm a successful MCP tool call and an answer with sources. `codex mcp list` alone does not start the server or prove inference. The `/mcp` status `Auth: Unsupported` is expected because this stdio server does not use the OAuth authorization framework; it does not describe the OpenRouter credential.
242
+
243
+ The installed `intelli-search` skill covers configuration and unattended tool approval; see the [compatibility matrix](https://github.com/Curio-Data/pi-intelli-search/blob/main/docs/COMPATIBILITY.md#host-plugins) for verified host behaviour.
233
244
 
234
245
  <a id="route-a-direct-mcp-configuration"></a>
235
246
  #### Generic MCP Host
@@ -277,6 +288,18 @@ Research collation receives only successful, non-empty page extractions, not the
277
288
 
278
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.
279
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
+
280
303
  <a id="quick-start"></a>
281
304
  ## Usage Examples
282
305
 
@@ -331,7 +354,7 @@ The illustration shows the native pipeline with the model configuration at its c
331
354
 
332
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).
333
356
 
334
- 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.
335
358
 
336
359
  See [docs/ARCHITECTURE.md](https://github.com/Curio-Data/pi-intelli-search/blob/main/docs/ARCHITECTURE.md) for detailed design decisions.
337
360
 
@@ -358,12 +381,11 @@ This reference applies to `@curio-data/mcp-intelli-search` only. Installation ro
358
381
  ### Requirements
359
382
 
360
383
  - [_Node.js_](https://nodejs.org/) satisfying the `engines` range in the [standalone manifest](https://github.com/Curio-Data/pi-intelli-search/blob/main/packages/mcp/package.json).
361
- - An existing, explicitly selected absolute workspace directory.
362
- - An explicitly selected JSON configuration file.
363
- - A separately billed OpenRouter API key supplied through a named environment variable before constructing the runtime. Restart the runtime after changing credentials; it snapshots the environment.
384
+ - An existing absolute workspace directory and JSON configuration file for generic registration or direct runtime use. Codex mode supplies its workspace and model defaults.
385
+ - A separately billed OpenRouter API key supplied through a named environment variable before constructing the runtime, or through `setup` and a user-only credential file. Environment changes require a runtime restart; each operation rereads the selected credential file, so a new or replacement key takes effect on the next operation.
364
386
  - A platform supported by [_wreq-js_](https://github.com/sqdshguy/wreq-js), the browser-fingerprint fetch dependency. The installation gate exercises its native assets on the running platform; it does not establish support for other platforms.
365
387
 
366
- The package neither reads host credential stores nor loads project configuration automatically. Native `Pi` settings, authentication, providers and defaults remain independent.
388
+ The package neither reads host credential stores nor loads project configuration automatically. Codex mode reads only its documented per-user configuration and credential paths. Native `Pi` settings, authentication, providers and defaults remain independent.
367
389
 
368
390
  ### Verification
369
391
 
@@ -379,7 +401,7 @@ Use the same configuration and workspace as the registered server. If a project-
379
401
 
380
402
  ### Serving the Protocol
381
403
 
382
- An invocation without `--check-config` validates the explicit workspace, then serves the four canonical tools (`intelli_search`, `intelli_extract`, `intelli_collate`, `intelli_research`) over stdio until the input stream closes. An explicitly selected missing, unreadable or invalid configuration file does not prevent connection: each tool call returns an actionable `CONFIGURATION` error, and the server rereads the file on each call until it loads. Repair the file and call again. Once loaded, configuration remains fixed until restart. Missing launcher arguments and invalid workspaces still fail at startup; `--check-config` remains strict. Serving performs no inference at startup; credentials are only required when an operation runs.
404
+ An invocation without `--check-config` validates the selected workspace, then serves the four canonical tools (`intelli_search`, `intelli_extract`, `intelli_collate`, `intelli_research`) over stdio until the input stream closes. An explicitly selected missing, unreadable or invalid configuration file does not prevent connection: each tool call returns an actionable `CONFIGURATION` error, and the server rereads the file on each call until it loads. Repair the file and call again. Once loaded, configuration remains fixed until restart. Generic registration rejects missing launcher arguments and invalid workspaces at startup; `--check-config` remains strict. Codex mode selects its working root and built-in defaults when its per-user configuration is absent. Serving performs no inference at startup; credentials are only required when an operation runs.
383
405
 
384
406
  - **Registration and Schemas.** Tool names and JSON input schemas mirror the native `Pi` tools verbatim; descriptions adapt the native guidance for protocol clients (host-neutral cache wording, embedded `focusPrompt` and breadth guidance), because the protocol offers no separate guidance channel. Invalid tool arguments are reported as tool errors (`isError` results), matching the software development kit (SDK) distinction between malformed protocol requests and invalid arguments.
385
407
  - **Results.** Successful calls return the complete operation text both as text content and as `structuredContent.text`, alongside `outcome` and `details`. Hosts that prefer the structured representation receive the same answer, sources and cache suggestions. The duplication is intentional for host compatibility; a host that forwards both representations can consume extra context. Degraded research (`no-links`, `fetch-failed`, `extraction-failed`) remains a normal result. Execution failures return `isError` results tagged with the safe `StandaloneError` category rather than raw provider causes.
@@ -393,11 +415,11 @@ Startup diagnostics go to standard error. The SDK version range is declared in `
393
415
 
394
416
  ### Configuration
395
417
 
396
- Select the configuration with `--config FILE` or `INTELLI_SEARCH_CONFIG`. Select the workspace with `--workspace ABSOLUTE_DIRECTORY` or `INTELLI_SEARCH_WORKSPACE`. Command-line values take precedence. Relative workspace paths are rejected; existing workspace symlinks are canonicalised.
418
+ Select the configuration with `--config FILE` or `INTELLI_SEARCH_CONFIG`. Select the workspace with `--workspace ABSOLUTE_DIRECTORY` or `INTELLI_SEARCH_WORKSPACE`. Command-line values take precedence. Relative workspace paths are rejected; existing workspace symlinks are canonicalised. `--host codex` instead selects the working root and `${XDG_CONFIG_HOME:-$HOME/.config}/mcp-intelli-search/config.json`; explicit selections still take precedence.
397
419
 
398
- The [minimal configuration](#create-the-configuration) explicitly selects OpenRouter for every role; add an optional `tuning` object (for example `"cacheDir": ".search"`) beside `providers` and `models`. These are example selections, not standalone defaults.
420
+ The [minimal configuration](#create-the-configuration) explicitly selects OpenRouter for every role; add an optional `tuning` object (for example `"cacheDir": ".search"`) beside `providers` and `models`. Generic registration has no model defaults. Codex mode uses `perplexity/sonar` for search and `minimax/minimax-m3` for extraction and collation when no per-user file exists.
399
421
 
400
- Only `providers`, `models` and optional `tuning` are accepted at the top level. All three model roles are required. The provider object accepts only `apiKeyEnv`, an environment-variable name rather than a key value. The initial provider scope is OpenRouter at its fixed `https://openrouter.ai/api/v1` endpoint; custom endpoints, proxy settings, provider fallback and dynamic router model identifiers are not accepted.
422
+ Only `providers`, `models` and optional `tuning` are accepted at the top level. All three model roles are required in a configuration file. The provider object accepts `apiKeyEnv`, an environment-variable name rather than a key value, and optional `apiKeyFile`, an absolute path to a separately stored key. The environment variable takes precedence. Setup writes the key with user-only permissions; each file read rejects symbolic links, hard links, other owners and group or world access on platforms with POSIX permissions. Setup manages the default per-user configuration. For a separately selected generic configuration, set `providers.openrouter.apiKeyFile` to the credential path printed by setup and restart after changing loaded configuration. The initial provider scope is OpenRouter at its fixed `https://openrouter.ai/api/v1` endpoint; custom endpoints, proxy settings, provider fallback and dynamic router model identifiers are not accepted.
401
423
 
402
424
  Configuration loading does not require working credentials. Each operation validates its required model roles against OpenRouter's model catalogue before inference. Full research validates all three roles first. Validation checks exact identifiers, text input/output, advertised reasoning efforts when supplied, and tool support for an enabled search tool. Catalogue lookup is bounded and cancellable. It establishes advertised capabilities, not account credit, per-key model access or future provider availability; inference errors remain possible.
403
425
 
@@ -413,10 +435,10 @@ Unspecified tuning comes from the canonical [shared defaults](https://github.com
413
435
  | `maxUrls` | `20`: hard cap on research pages | Integer from 1 to 100 |
414
436
  | `extractMaxChars` | `150000`: per-page extraction input character limit | Integer from 1 to 2,000,000 |
415
437
  | `fetchTimeoutMs` | `20000`: page-fetch timeout in milliseconds | Integer from 1 to 600,000 |
416
- | `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 |
417
439
  | `fetchConcurrency` | `4`: simultaneous page fetches | Integer from 1 to 32 |
418
440
  | `extractionConcurrency` | `4`: simultaneous per-page extractions | Integer from 1 to 32 |
419
- | `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 |
420
442
  | `collationMaxTokens` | `4000`: synthesis output-token limit | Integer from 16 to 128,000 |
421
443
  | `llmRetryAttempts` | `3`: model-call attempts, including the first | Integer from 1 to 10 |
422
444
  | `searchRetryAttempts` | `2`: search attempts after a valid response with no usable links, including the first | Integer from 1 to 10 |
@@ -437,7 +459,7 @@ Unspecified tuning comes from the canonical [shared defaults](https://github.com
437
459
 
438
460
  **Reasoning:** The adapter sends reasoning fields only when the catalogue advertises reasoning support; non-reasoning models receive neither effort nor exclusion fields.
439
461
 
440
- **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.
441
463
 
442
464
  ### Direct Engine Verification
443
465
 
@@ -478,7 +500,7 @@ This example incurs inference and search charges when run with a real credential
478
500
 
479
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.
480
502
 
481
- 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.
482
504
 
483
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.
484
506
 
@@ -508,9 +530,9 @@ Every startup failure is diagnostic-only and lands on standard error; standard o
508
530
  | Configuration rejected with an unknown-key or range error | The loader is strict: unknown keys, invalid types and out-of-range values fail validation. Correct the configuration and call again if it has not yet loaded. The [Tuning](#tuning) table lists accepted keys and ranges. |
509
531
  | Tools never appear in the host | Check absent launcher arguments, an unusable workspace or an unsafe cache. Read the host's MCP server logs for the standard-error diagnostic. Claude Code can cache a startup failure from an older server: try `/mcp` reconnect, then restart ([evidence and limits](https://github.com/Curio-Data/pi-intelli-search/blob/main/docs/COMPATIBILITY.md#claude-code-evidence-and-limits)). A connected server still needs a successful tool call to verify inference. |
510
532
  | `CONFIGURATION` persists after the file is repaired | A file that has not yet loaded is reread on the next call; once loaded, configuration changes require a restart. |
511
- | Diagnostic names a missing credential environment variable | Supply the named variable through the host's supported credential mechanism and restart. The server snapshots credentials at startup. |
533
+ | Diagnostic names a missing credential environment variable | Supply the named variable before host launch. Codex users can instead run `mcp-intelli-search setup` with the key on standard input. For a separately selected configuration, set `providers.openrouter.apiKeyFile` to the printed credential path. Environment or loaded-configuration changes require restart; file credentials are reread on each call. |
512
534
  | Catalogue preflight names a model role or capability | Correct the model identifier or required capabilities using [Configuration](#configuration). Read the diagnostic; catalogue lookup failures are not proof of invalid credentials. Restart after changing loaded model selections. |
513
- | `PROVIDER` reports authentication, access, credit or transport failure | Follow the specific diagnostic: check credentials, model access, account credit or connectivity. Restart after changing credentials. The category alone does not identify a rejected key. |
535
+ | `PROVIDER` reports authentication, access, credit or transport failure | Follow the specific diagnostic: check credentials, model access, account credit or connectivity. Restart after changing an environment credential. For the default Codex configuration, replace a stored key with `setup` and call again. For a separately selected configuration, replace the file named by `providers.openrouter.apiKeyFile`, or select setup's printed path and restart. The category alone does not identify a rejected key. |
514
536
  | Repeated `429` retries | Tune pacing to observed account/provider limits. For an observed limit of approximately 0.33 requests per second, try `minRequestIntervalMs: 3000` and `extractionConcurrency: 2`; adjust retry attempts as needed. Raise `llmTimeoutMs` only when its model-call timer expires. |
515
537
  | Cache paths unreadable from the host | The host must share the server's filesystem. Sandboxed or remote hosts cannot read local cache paths; run the server where the host can read the workspace. |
516
538
 
@@ -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,
@@ -223,8 +233,8 @@ async function resolveWorkspace(workspace) {
223
233
  return canonical;
224
234
  }
225
235
  async function parseConfig(value, workspace) {
226
- const { apiKeyEnv, settings } = parseDocument(value);
227
- return freeze({ workspace: await resolveWorkspace(workspace), apiKeyEnv, settings });
236
+ const { apiKeyEnv, apiKeyFile, settings } = parseDocument(value);
237
+ return freeze({ workspace: await resolveWorkspace(workspace), apiKeyEnv, apiKeyFile, settings });
228
238
  }
229
239
  function parseDocument(value) {
230
240
  const root = object(value, "configuration");
@@ -232,10 +242,13 @@ function parseDocument(value) {
232
242
  const providers = object(root.providers, "providers");
233
243
  keys(providers, ["openrouter"], "providers");
234
244
  const provider = object(providers.openrouter, "providers.openrouter");
235
- keys(provider, ["apiKeyEnv"], "providers.openrouter");
245
+ keys(provider, ["apiKeyEnv", "apiKeyFile"], "providers.openrouter");
236
246
  const apiKeyEnv = text(provider.apiKeyEnv, "providers.openrouter.apiKeyEnv");
237
247
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(apiKeyEnv))
238
248
  throw new Error("apiKeyEnv must name an environment variable, not contain a credential");
249
+ const apiKeyFile = provider.apiKeyFile === void 0 ? void 0 : text(provider.apiKeyFile, "providers.openrouter.apiKeyFile");
250
+ if (apiKeyFile !== void 0 && !isAbsolute(apiKeyFile))
251
+ throw new Error("apiKeyFile must be an absolute path, not contain a credential");
239
252
  const models = object(root.models, "models");
240
253
  keys(models, ["search", "extract", "collate"], "models");
241
254
  const tuning = root.tuning === void 0 ? {} : object(root.tuning, "tuning");
@@ -283,7 +296,7 @@ function parseDocument(value) {
283
296
  throw new Error(
284
297
  "Search requires an explicitly enabled searchWebSearch tool or a supported Sonar search model"
285
298
  );
286
- return { apiKeyEnv, settings };
299
+ return { apiKeyEnv, apiKeyFile, settings };
287
300
  }
288
301
  async function loadConfig(file, workspace) {
289
302
  const path = resolve(file).replace(/[\x00-\x1f\x7f]/g, "?");
@@ -323,10 +336,161 @@ async function loadConfig(file, workspace) {
323
336
  return freeze({
324
337
  workspace: await resolveWorkspace(workspace),
325
338
  apiKeyEnv: parsed.apiKeyEnv,
339
+ apiKeyFile: parsed.apiKeyFile,
326
340
  settings: parsed.settings
327
341
  });
328
342
  }
329
343
 
344
+ // packages/mcp/src/errors.ts
345
+ var StandaloneError = class extends Error {
346
+ constructor(code, message) {
347
+ super(message);
348
+ this.code = code;
349
+ this.name = code === "CANCELLED" ? "AbortError" : "StandaloneError";
350
+ }
351
+ code;
352
+ };
353
+
354
+ // packages/mcp/src/host.ts
355
+ import { lstat, mkdir, readFile as readFile2, rename, rm, writeFile } from "node:fs/promises";
356
+ import { randomUUID } from "node:crypto";
357
+ import { homedir } from "node:os";
358
+ import { dirname, isAbsolute as isAbsolute2, join } from "node:path";
359
+ function hostPaths(env = process.env) {
360
+ const home = env.HOME || homedir();
361
+ if (!home || !isAbsolute2(home)) throw new Error("A home directory is required");
362
+ const base = env.XDG_CONFIG_HOME && isAbsolute2(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join(home, ".config");
363
+ const directory = join(base, "mcp-intelli-search");
364
+ return {
365
+ directory,
366
+ config: join(directory, "config.json"),
367
+ credential: join(directory, "openrouter.key")
368
+ };
369
+ }
370
+ function defaultDocument(credential) {
371
+ return {
372
+ providers: {
373
+ openrouter: {
374
+ apiKeyEnv: "OPENROUTER_API_KEY",
375
+ apiKeyFile: credential
376
+ }
377
+ },
378
+ models: {
379
+ search: { provider: "openrouter", model: "perplexity/sonar" },
380
+ extract: { provider: "openrouter", model: "minimax/minimax-m3" },
381
+ collate: { provider: "openrouter", model: "minimax/minimax-m3" }
382
+ }
383
+ };
384
+ }
385
+ function defaultCodexConfig(workspace, paths) {
386
+ return parseConfig(defaultDocument(paths.credential), workspace);
387
+ }
388
+ function credentialText(source) {
389
+ const value = source.replace(/\r?\n$/, "");
390
+ if (!value || value.length > 4096 || /\s/.test(value))
391
+ throw new Error("OpenRouter credential must be one nonempty line without whitespace");
392
+ return value;
393
+ }
394
+ async function resolveCredential(config, env) {
395
+ const fromEnvironment = env[config.apiKeyEnv];
396
+ if (fromEnvironment) return fromEnvironment;
397
+ if (!config.apiKeyFile) return void 0;
398
+ let source;
399
+ try {
400
+ const metadata = await lstat(config.apiKeyFile);
401
+ if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1)
402
+ throw new StandaloneError(
403
+ "CONFIGURATION",
404
+ "OpenRouter credential file must be one regular, non-linked file"
405
+ );
406
+ if (process.platform !== "win32") {
407
+ if (metadata.uid !== process.getuid?.() || (metadata.mode & 63) !== 0)
408
+ throw new StandaloneError(
409
+ "CONFIGURATION",
410
+ "OpenRouter credential file must be owned by the current user and inaccessible to group and other users; repair it or run mcp-intelli-search setup for the default configuration"
411
+ );
412
+ }
413
+ source = await readFile2(config.apiKeyFile, "utf8");
414
+ } catch (error) {
415
+ if (error instanceof StandaloneError) throw error;
416
+ if (error.code === "ENOENT") return void 0;
417
+ throw new StandaloneError(
418
+ "CONFIGURATION",
419
+ "OpenRouter credential file is not readable; repair the configured path or run mcp-intelli-search setup for the default configuration"
420
+ );
421
+ }
422
+ try {
423
+ return credentialText(source);
424
+ } catch (error) {
425
+ throw new StandaloneError(
426
+ "CONFIGURATION",
427
+ `${error instanceof Error ? error.message : "Invalid OpenRouter credential"}; replace it or run mcp-intelli-search setup for the default configuration`
428
+ );
429
+ }
430
+ }
431
+ async function writePrivateAtomic(file, source) {
432
+ const directory = dirname(file);
433
+ await mkdir(directory, { recursive: true, mode: 448 });
434
+ const temporary = join(directory, `.${process.pid}.${randomUUID()}.tmp`);
435
+ try {
436
+ await writeFile(temporary, source, { encoding: "utf8", flag: "wx", mode: 384 });
437
+ await rename(temporary, file);
438
+ } finally {
439
+ await rm(temporary, { force: true }).catch(() => {
440
+ });
441
+ }
442
+ }
443
+ async function prepareConfig(paths) {
444
+ let source;
445
+ try {
446
+ source = await readFile2(paths.config, "utf8");
447
+ } catch (error) {
448
+ if (error.code !== "ENOENT") throw error;
449
+ await writePrivateAtomic(
450
+ paths.config,
451
+ `${JSON.stringify(defaultDocument(paths.credential), null, 2)}
452
+ `
453
+ );
454
+ return paths;
455
+ }
456
+ if (source.startsWith("\uFEFF")) source = source.slice(1);
457
+ let value;
458
+ try {
459
+ value = JSON.parse(source);
460
+ } catch {
461
+ throw new ConfigurationError(
462
+ "invalid-json",
463
+ `Configuration file is not valid JSON: ${paths.config}`
464
+ );
465
+ }
466
+ let parsed;
467
+ try {
468
+ parsed = await parseConfig(value, process.cwd());
469
+ } catch (error) {
470
+ if (error instanceof ConfigurationError) throw error;
471
+ throw new ConfigurationError(
472
+ "invalid",
473
+ `Invalid configuration in ${paths.config}: ${error instanceof Error ? error.message : "unknown defect"}`
474
+ );
475
+ }
476
+ if (parsed.apiKeyFile) return { ...paths, credential: parsed.apiKeyFile };
477
+ const metadata = await lstat(paths.config);
478
+ if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1)
479
+ throw new Error("Configuration must be one regular, non-linked file before setup can update it");
480
+ const document = value;
481
+ document.providers.openrouter.apiKeyFile = paths.credential;
482
+ await writePrivateAtomic(paths.config, `${JSON.stringify(document, null, 2)}
483
+ `);
484
+ return paths;
485
+ }
486
+ async function setupHost(source, env = process.env) {
487
+ const credential = credentialText(source);
488
+ const paths = await prepareConfig(hostPaths(env));
489
+ await writePrivateAtomic(paths.credential, `${credential}
490
+ `);
491
+ return paths;
492
+ }
493
+
330
494
  export {
331
495
  identity,
332
496
  validateCacheDir,
@@ -334,5 +498,10 @@ export {
334
498
  ConfigurationError,
335
499
  resolveWorkspace,
336
500
  parseConfig,
337
- loadConfig
501
+ loadConfig,
502
+ StandaloneError,
503
+ hostPaths,
504
+ defaultCodexConfig,
505
+ resolveCredential,
506
+ setupHost
338
507
  };
@@ -1,8 +1,10 @@
1
1
  import {
2
+ StandaloneError,
2
3
  identity,
4
+ resolveCredential,
3
5
  validateCacheDir,
4
6
  validateDomains
5
- } from "./chunk-EHXBTGSE.js";
7
+ } from "./chunk-LXLEWIYT.js";
6
8
 
7
9
  // packages/mcp/src/runtime.ts
8
10
  import { Check } from "typebox/value";
@@ -147,6 +149,10 @@ async function withMuzzledConsole(fn, muzzleTags) {
147
149
  }
148
150
 
149
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
+ }
150
156
  function throwIfAborted(signal) {
151
157
  if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
152
158
  }
@@ -691,7 +697,7 @@ ${summary}
691
697
  const extractionFile = identity2.extractionFileFor(source.url);
692
698
  if (!extractionFile) invalid("an evidence source has no extraction file");
693
699
  const fullPage = identity2.sourceFileFor(source.url);
694
- 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"} |
695
701
  `;
696
702
  }
697
703
  return result.trimEnd();
@@ -760,7 +766,7 @@ function buildCollationMessage(query, _cachePath, _searchSummary, succeededExtra
760
766
  }))
761
767
  }, null, 2);
762
768
  }
763
- function formatCacheAppendix(cachePath, succeeded, failed) {
769
+ function formatCacheAppendix(cachePath, succeeded, failed, failedEntries = [], truncatedCount = 0) {
764
770
  let out = `
765
771
 
766
772
  ---
@@ -769,13 +775,25 @@ function formatCacheAppendix(cachePath, succeeded, failed) {
769
775
  `;
770
776
  out += `**Report**: \`${cachePath}/report.md\`
771
777
  `;
772
- out += `**Sources**: ${succeeded} succeeded, ${failed} failed
778
+ out += `**Sources**: ${succeeded} succeeded${truncatedCount > 0 ? ` (${truncatedCount} truncated at the output cap)` : ""}, ${failed} failed
773
779
  `;
774
780
  out += `
775
781
  - Read the report: \`read ${cachePath}/report.md\`
776
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
+ }
777
795
  out += `
778
- 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.
779
797
  `;
780
798
  return out;
781
799
  }
@@ -845,7 +863,7 @@ async function extract(params, context) {
845
863
  params.focusPrompt,
846
864
  settings.extractMaxChars
847
865
  );
848
- const { text: extraction } = await models.complete({
866
+ const { text: extraction, usage: usage2 } = await models.complete({
849
867
  model: extractConfig,
850
868
  systemPrompt: EXTRACTION_SYSTEM_PROMPT,
851
869
  userMessage,
@@ -853,15 +871,26 @@ async function extract(params, context) {
853
871
  signal
854
872
  });
855
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
+ }
856
881
  const firstLine = extraction.split("\n")[0] ?? "";
857
882
  const sourceType = inferSourceType(firstLine);
858
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.` : "";
859
888
  return {
860
889
  text: `### Extraction: ${params.title}
861
890
 
862
- ${extraction}`,
891
+ ${extraction}${truncationNote}`,
863
892
  outcome: "completed",
864
- details: { url: params.url, extraction, sourceType, currentness }
893
+ details: { url: params.url, extraction, sourceType, currentness, ...truncated ? { truncated: true } : {} }
865
894
  };
866
895
  }
867
896
 
@@ -1147,7 +1176,7 @@ async function writeReportFile(cachePath, query, collation, extractions, pages,
1147
1176
  for (const [i, ext] of succeeded.entries()) {
1148
1177
  const extractionFile = identity2.extractionFileFor(ext.url);
1149
1178
  const sourceFile = identity2.sourceFileFor(ext.url);
1150
- 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"} |
1151
1180
  `;
1152
1181
  }
1153
1182
  }
@@ -1157,8 +1186,10 @@ async function writeReportFile(cachePath, query, collation, extractions, pages,
1157
1186
 
1158
1187
  `;
1159
1188
  for (const entry of blocked) {
1160
- const error = pages.find((page) => page.url === entry.url)?.error;
1161
- 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})` : ""}
1162
1193
  `;
1163
1194
  }
1164
1195
  }
@@ -1207,6 +1238,15 @@ function formatIndexForJudge(index, excludeSlug) {
1207
1238
  if (entries.length === 0) return "No previous searches.";
1208
1239
  return entries.map((e, i) => `${i + 1}. "${e.query}" (slug: ${e.slug}, searched: ${e.timestamp})`).join("\n");
1209
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
+ }
1210
1250
  function parseJudgeResponse(response, index, excludeSlug) {
1211
1251
  const candidates = judgeCandidates(index, excludeSlug);
1212
1252
  const jsonMatch = response.match(/\[[\s\S]*\]/);
@@ -1268,7 +1308,9 @@ async function collate(params, context) {
1268
1308
  extraction: e.extraction,
1269
1309
  sourceType: e.sourceType,
1270
1310
  currentness: "undated",
1271
- 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 } : {}
1272
1314
  }));
1273
1315
  const succeeded = evidenceExtractions(extractResults);
1274
1316
  const blocked = extractResults.filter((e) => e.status !== "success");
@@ -1287,14 +1329,19 @@ async function collate(params, context) {
1287
1329
  succeeded,
1288
1330
  identity2
1289
1331
  );
1290
- const { text } = await models.complete({
1332
+ const { text, usage: usage2 } = await models.complete({
1291
1333
  model: collateConfig,
1292
1334
  systemPrompt: COLLATION_SYSTEM_PROMPT,
1293
1335
  userMessage,
1294
1336
  maxTokens: settings.collationMaxTokens,
1295
1337
  signal
1296
1338
  });
1297
- 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
+ }
1298
1345
  await withLock(
1299
1346
  cacheLockDir(physicalPath),
1300
1347
  async () => {
@@ -1330,8 +1377,14 @@ async function collate(params, context) {
1330
1377
  },
1331
1378
  signal
1332
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;
1333
1386
  return {
1334
- text: collation + formatCacheAppendix(cachePath, succeeded.length, blocked.length),
1387
+ text: collation + formatCacheAppendix(cachePath, succeeded.length, blocked.length, failedEntries, truncatedCount),
1335
1388
  outcome: "completed",
1336
1389
  details: { cachePath, sourcesFetched: succeeded.length + blocked.length }
1337
1390
  };
@@ -1836,10 +1889,18 @@ ${search2.searchResult}`,
1836
1889
  const fetchFailed = extracted.blockedExtractions.length;
1837
1890
  const extractFailed = extracted.extractions.filter((e) => e.status === "failed").length;
1838
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}` : "";
1839
1900
  return degradedReturn(
1840
1901
  p,
1841
1902
  "extraction-failed",
1842
- `${reason}. No content was extracted.
1903
+ `${reason}. No content was extracted.${failureBlock}
1843
1904
 
1844
1905
  Search summary:
1845
1906
  ${search2.searchResult}`,
@@ -1847,7 +1908,8 @@ ${search2.searchResult}`,
1847
1908
  cachePath: "",
1848
1909
  urlsSearched: search2.urls.length,
1849
1910
  pagesFetched: fetched.successPages.length,
1850
- pagesFailed: fetched.pages.length - fetched.successPages.length
1911
+ pagesFailed: fetched.pages.length - fetched.successPages.length,
1912
+ extractionFailed: extractFailed
1851
1913
  }
1852
1914
  );
1853
1915
  }
@@ -1872,7 +1934,28 @@ ${search2.searchResult}`,
1872
1934
  throwIfAborted(p.signal);
1873
1935
  await writeLockedTelemetry(p, "completed");
1874
1936
  const failedCount = fetched.pages.length - fetched.successPages.length;
1875
- 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;
1876
1959
  return {
1877
1960
  text: result,
1878
1961
  outcome: "completed",
@@ -1880,7 +1963,10 @@ ${search2.searchResult}`,
1880
1963
  cachePath: p.cachePath,
1881
1964
  urlsSearched: search2.urls.length,
1882
1965
  pagesFetched: fetched.successPages.length,
1883
- 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
1884
1970
  }
1885
1971
  };
1886
1972
  }
@@ -2015,6 +2101,14 @@ async function runExtractStage(p, successPages, pages) {
2015
2101
  }));
2016
2102
  const succeededExtr = extractions.filter((e) => e.status === "success");
2017
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
+ );
2018
2112
  const totalIn = successPages.reduce(
2019
2113
  (sum, pg) => sum + Math.min(pg.content.length, p.settings.extractMaxChars),
2020
2114
  0
@@ -2025,7 +2119,15 @@ async function runExtractStage(p, successPages, pages) {
2025
2119
  succeeded: succeededExtr.length,
2026
2120
  failed: failedExtr,
2027
2121
  totalInputCharsApprox: totalIn,
2028
- 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] } : {}
2029
2131
  });
2030
2132
  return { extractions, blockedExtractions };
2031
2133
  }
@@ -2038,7 +2140,7 @@ async function runCollateStage(p, searchResult, succeededExtractions, identity2)
2038
2140
  identity2
2039
2141
  );
2040
2142
  throwIfAborted(p.signal);
2041
- const { text } = await p.models.complete({
2143
+ const { text, usage: usage2, routeProvider } = await p.models.complete({
2042
2144
  model: p.collateConfig,
2043
2145
  systemPrompt: COLLATION_SYSTEM_PROMPT,
2044
2146
  userMessage: collationUserMsg,
@@ -2048,10 +2150,18 @@ async function runCollateStage(p, searchResult, succeededExtractions, identity2)
2048
2150
  timeoutMs: p.settings.llmTimeoutMs,
2049
2151
  onRetryNotice: (msg) => p.onProgress?.(progress("collate", msg))
2050
2152
  });
2051
- 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
+ }
2052
2160
  p.tel?.recordCollate({
2053
2161
  model: `${p.collateConfig.provider}/${p.collateConfig.model}`,
2054
- summaryChars: text.trim().length
2162
+ summaryChars: text.trim().length,
2163
+ ...collateTruncated ? { truncated: true } : {},
2164
+ ...routeProvider ? { provider: routeProvider } : {}
2055
2165
  });
2056
2166
  return collation;
2057
2167
  }
@@ -2149,9 +2259,12 @@ async function runCacheSuggestStage(p) {
2149
2259
  let cacheSuggestRan = false;
2150
2260
  let cacheSuggestSurfaced = 0;
2151
2261
  let cacheSuggestSlugs = [];
2262
+ let cacheSuggestDegraded;
2263
+ let judgeAttempted = false;
2152
2264
  try {
2153
2265
  const index = await readIndex(p.paths.cacheRoot);
2154
2266
  if (index.searches.some((e) => e.slug !== currentSlug)) {
2267
+ judgeAttempted = true;
2155
2268
  const indexText = formatIndexForJudge(index, currentSlug);
2156
2269
  const judgeUserMsg = `Current query: "${p.params.query}"
2157
2270
 
@@ -2161,12 +2274,18 @@ ${indexText}`;
2161
2274
  model: p.extractConfig,
2162
2275
  systemPrompt: CACHE_SUGGEST_PROMPT,
2163
2276
  userMessage: judgeUserMsg,
2164
- maxTokens: 500,
2277
+ maxTokens: 2e3,
2165
2278
  signal: p.signal,
2166
2279
  retry: p.retry,
2167
2280
  timeoutMs: p.settings.llmTimeoutMs,
2168
2281
  onRetryNotice: (msg) => p.onProgress?.(progress("cache", msg))
2169
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
+ }
2170
2289
  const matches = parseJudgeResponse(judgeResponse, index, currentSlug);
2171
2290
  cacheSuggestRan = true;
2172
2291
  cacheSuggestSurfaced = matches.length;
@@ -2175,12 +2294,14 @@ ${indexText}`;
2175
2294
  }
2176
2295
  } catch (err) {
2177
2296
  throwIfAborted(p.signal);
2297
+ if (judgeAttempted) cacheSuggestDegraded = true;
2178
2298
  p.logger.error(`Cache suggest failed: ${errMsg(err)}`);
2179
2299
  }
2180
2300
  p.tel?.recordCacheSuggest({
2181
2301
  ran: cacheSuggestRan,
2182
2302
  surfaced: cacheSuggestSurfaced,
2183
- slugs: cacheSuggestSlugs
2303
+ slugs: cacheSuggestSlugs,
2304
+ ...cacheSuggestDegraded ? { degraded: true } : {}
2184
2305
  });
2185
2306
  return suggestionsAppendix;
2186
2307
  }
@@ -2261,6 +2382,8 @@ async function writeTelemetrySidecar(logger, tel, cachePath, outcome) {
2261
2382
  }
2262
2383
  async function extractPage(p, page) {
2263
2384
  throwIfAborted(p.signal);
2385
+ let exhausted;
2386
+ let routeProvider;
2264
2387
  try {
2265
2388
  const userMessage = buildExtractionMessage(
2266
2389
  page.content,
@@ -2268,7 +2391,7 @@ async function extractPage(p, page) {
2268
2391
  p.params.focusPrompt,
2269
2392
  p.settings.extractMaxChars
2270
2393
  );
2271
- const { text: extraction } = await p.models.complete({
2394
+ const completion = await p.models.complete({
2272
2395
  model: p.extractConfig,
2273
2396
  systemPrompt: EXTRACTION_SYSTEM_PROMPT,
2274
2397
  userMessage,
@@ -2278,7 +2401,15 @@ async function extractPage(p, page) {
2278
2401
  timeoutMs: p.settings.llmTimeoutMs,
2279
2402
  onRetryNotice: (msg) => p.onProgress?.(progress("extract", msg))
2280
2403
  });
2281
- 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
+ }
2282
2413
  const firstLine = extraction.split("\n")[0] ?? "";
2283
2414
  return {
2284
2415
  url: page.url,
@@ -2286,18 +2417,28 @@ async function extractPage(p, page) {
2286
2417
  extraction,
2287
2418
  sourceType: inferSourceType(firstLine),
2288
2419
  currentness: inferCurrentness(firstLine),
2289
- 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 } : {}
2290
2425
  };
2291
2426
  } catch (err) {
2292
2427
  throwIfAborted(p.signal);
2293
- 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}`);
2294
2430
  return {
2295
2431
  url: page.url,
2296
2432
  title: page.title,
2297
2433
  extraction: "",
2298
2434
  sourceType: "unknown",
2299
2435
  currentness: "unknown",
2300
- 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 } : {}
2301
2442
  };
2302
2443
  }
2303
2444
  }
@@ -2309,7 +2450,12 @@ var extractionSchema = Type.Object({
2309
2450
  title: Type.String(),
2310
2451
  extraction: Type.String(),
2311
2452
  sourceType: Type.String(),
2312
- 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())
2313
2459
  });
2314
2460
  var fullPageSchema = Type.Object({
2315
2461
  url: Type.String(),
@@ -2365,16 +2511,6 @@ var researchSchema = Type.Object({
2365
2511
  focusPrompt: Type.Optional(Type.String({ description: "Focus guidance for all extractions" }))
2366
2512
  });
2367
2513
 
2368
- // packages/mcp/src/errors.ts
2369
- var StandaloneError = class extends Error {
2370
- constructor(code, message) {
2371
- super(message);
2372
- this.code = code;
2373
- this.name = code === "CANCELLED" ? "AbortError" : "StandaloneError";
2374
- }
2375
- code;
2376
- };
2377
-
2378
2514
  // packages/mcp/src/providers/openrouter.ts
2379
2515
  var endpoint = "https://openrouter.ai/api/v1";
2380
2516
  var record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
@@ -2468,7 +2604,7 @@ function createOpenRouterClient(config, options) {
2468
2604
  if (!value || !value.trim() || /\s/.test(value))
2469
2605
  throw new StandaloneError(
2470
2606
  "CONFIGURATION",
2471
- `Set the credential environment variable ${config.apiKeyEnv} before creating the runtime; restart it after changing credentials`
2607
+ config.apiKeyFile ? `Set ${config.apiKeyEnv} before launch or supply the key at ${config.apiKeyFile}. mcp-intelli-search setup manages the default per-user configuration; restart after changing loaded configuration` : `Set the credential environment variable ${config.apiKeyEnv} before creating the runtime; restart it after changing credentials`
2472
2608
  );
2473
2609
  return value;
2474
2610
  }
@@ -2612,17 +2748,23 @@ function createOpenRouterClient(config, options) {
2612
2748
  const message = record(choice.message);
2613
2749
  if (message.refusal || choice.finish_reason === "content_filter")
2614
2750
  throw new Error("OpenRouter declined the request under provider policy");
2615
- if (typeof message.content !== "string")
2616
- throw new Error("OpenRouter returned no text completion");
2617
- 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` : "") + ")" : "";
2618
2756
  throw new Error(
2619
- "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."
2620
2758
  );
2759
+ }
2760
+ if (typeof content !== "string")
2761
+ throw new Error("OpenRouter returned no text completion");
2621
2762
  return {
2622
2763
  value: {
2623
- text: message.content,
2764
+ text: content,
2624
2765
  citations: request.collectCitations ? parseCitations(raw) : [],
2625
- usage: usage(data.usage)
2766
+ usage: usage(data.usage),
2767
+ ...typeof data.provider === "string" && data.provider ? { routeProvider: data.provider } : {}
2626
2768
  }
2627
2769
  };
2628
2770
  },
@@ -2781,8 +2923,13 @@ var stderrLogger = {
2781
2923
  async function createRuntime(config, options = {}) {
2782
2924
  const paths = await workspacePaths(config.workspace, config.settings.cacheDir);
2783
2925
  const env = { ...options.env ?? process.env };
2784
- const secret = env[config.apiKeyEnv];
2785
- const redact = (message) => secret ? message.split(secret).join("[REDACTED]") : message;
2926
+ const secrets = /* @__PURE__ */ new Set();
2927
+ if (env[config.apiKeyEnv]) secrets.add(env[config.apiKeyEnv]);
2928
+ const redact = (message) => {
2929
+ let redacted = message;
2930
+ for (const secret of secrets) if (secret) redacted = redacted.split(secret).join("[REDACTED]");
2931
+ return redacted;
2932
+ };
2786
2933
  const sink = options.logger ?? stderrLogger;
2787
2934
  const logger = {
2788
2935
  error: (message) => sink.error(redact(message)),
@@ -2806,9 +2953,16 @@ async function createRuntime(config, options = {}) {
2806
2953
  throwIfAborted(execution.signal);
2807
2954
  category = "WORKSPACE";
2808
2955
  await assertWorkspaceSafe(paths, execution.signal);
2956
+ category = "CONFIGURATION";
2957
+ const operationEnv = { ...env };
2958
+ const credential = await resolveCredential(config, operationEnv);
2959
+ if (credential) {
2960
+ operationEnv[config.apiKeyEnv] = credential;
2961
+ secrets.add(credential);
2962
+ }
2809
2963
  const models = createOpenRouterClient(config, {
2810
2964
  fetch: options.fetch,
2811
- env,
2965
+ env: operationEnv,
2812
2966
  logger,
2813
2967
  signal: execution.signal
2814
2968
  });
@@ -2887,6 +3041,5 @@ export {
2887
3041
  extractSchema,
2888
3042
  collateSchema,
2889
3043
  researchSchema,
2890
- StandaloneError,
2891
3044
  createRuntime
2892
3045
  };
package/dist/cli.js CHANGED
@@ -4,54 +4,88 @@ import {
4
4
  } from "./chunk-ZTHYRKI2.js";
5
5
  import {
6
6
  ConfigurationError,
7
+ defaultCodexConfig,
8
+ hostPaths,
7
9
  identity,
8
10
  loadConfig,
9
- resolveWorkspace
10
- } from "./chunk-EHXBTGSE.js";
11
+ resolveWorkspace,
12
+ setupHost
13
+ } from "./chunk-LXLEWIYT.js";
11
14
 
12
15
  // packages/mcp/src/cli.ts
13
16
  import { parseArgs } from "node:util";
17
+ import { homedir } from "node:os";
18
+ import { realpath } from "node:fs/promises";
19
+ import { parse as parsePath } from "node:path";
14
20
  function cliOptions(argv, env = process.env) {
15
- const { values } = parseArgs({
21
+ const { values, positionals } = parseArgs({
16
22
  args: argv,
17
23
  strict: true,
18
- allowPositionals: false,
24
+ allowPositionals: true,
19
25
  options: {
20
26
  config: { type: "string" },
21
27
  workspace: { type: "string" },
28
+ host: { type: "string" },
22
29
  help: { type: "boolean" },
23
30
  version: { type: "boolean" },
24
31
  "check-config": { type: "boolean" }
25
32
  }
26
33
  });
34
+ if (values.host !== void 0 && values.host !== "codex")
35
+ throw new Error("Unsupported host");
36
+ if (positionals.length > 1 || positionals.length === 1 && positionals[0] !== "setup")
37
+ throw new Error("Unsupported command");
38
+ const setup = positionals[0] === "setup";
27
39
  return {
28
40
  ...values,
29
- config: values.config ?? env.INTELLI_SEARCH_CONFIG,
30
- workspace: values.workspace ?? env.INTELLI_SEARCH_WORKSPACE
41
+ setup,
42
+ config: values.config ?? (setup || values.host === "codex" ? void 0 : env.INTELLI_SEARCH_CONFIG),
43
+ workspace: values.workspace ?? (setup || values.host === "codex" ? void 0 : env.INTELLI_SEARCH_WORKSPACE)
31
44
  };
32
45
  }
46
+ async function credentialInput() {
47
+ if (process.stdin.isTTY)
48
+ throw new Error(
49
+ "Setup requires the key on standard input; use the hidden-prompt pipeline from the installation guide"
50
+ );
51
+ const chunks = [];
52
+ let length = 0;
53
+ for await (const chunk of process.stdin) {
54
+ const buffer = Buffer.from(chunk);
55
+ length += buffer.length;
56
+ if (length > 4098)
57
+ throw new Error("Credential input exceeds the 4096-byte limit plus its line ending");
58
+ chunks.push(buffer);
59
+ }
60
+ return Buffer.concat(chunks).toString("utf8");
61
+ }
33
62
  async function main() {
34
63
  let args;
35
64
  try {
36
65
  args = cliOptions(process.argv.slice(2));
37
- } catch {
38
- throw new Error("Invalid arguments. Run mcp-intelli-search --help");
66
+ } catch (error) {
67
+ throw new Error(error instanceof Error ? error.message : "Invalid arguments");
39
68
  }
40
69
  if (args.help) {
41
70
  process.stdout.write(
42
- `Usage: mcp-intelli-search --config FILE --workspace ABSOLUTE_DIRECTORY
71
+ `Usage: mcp-intelli-search setup
72
+ mcp-intelli-search --host codex [--config FILE] [--workspace ABSOLUTE_DIRECTORY]
73
+ mcp-intelli-search --config FILE --workspace ABSOLUTE_DIRECTORY
74
+
75
+ Commands:
76
+ setup Store an OpenRouter key read from standard input and create or connect per-user configuration; accepts no path selections
43
77
 
44
78
  Options:
45
- --config FILE Explicit JSON configuration (or INTELLI_SEARCH_CONFIG)
46
- --workspace DIR Existing absolute workspace (or INTELLI_SEARCH_WORKSPACE)
79
+ --host codex Use the Codex working root and per-user defaults
80
+ --config FILE Explicit generic configuration (or INTELLI_SEARCH_CONFIG)
81
+ --workspace DIR Existing absolute generic workspace (or INTELLI_SEARCH_WORKSPACE)
47
82
  --check-config Validate configuration without inference or serving
48
83
  --help Show this help
49
84
  --version Show package version
50
85
 
51
- Command-line values take precedence over environment values.
52
- Without --check-config the executable serves the four intelli_* research tools
53
- as a Model Context Protocol server over standard input/output. Diagnostics go
54
- to standard error; standard output carries protocol messages only.
86
+ Generic MCP serving requires explicit configuration and workspace paths.
87
+ Codex mode supplies both from its launcher and works without path exports.
88
+ Standard output carries protocol messages only while serving.
55
89
  `
56
90
  );
57
91
  return;
@@ -61,27 +95,83 @@ to standard error; standard output carries protocol messages only.
61
95
  `);
62
96
  return;
63
97
  }
64
- if (!args.config || !args.workspace)
98
+ if (args.setup) {
99
+ if (args.config || args.workspace || args.host || args["check-config"])
100
+ throw new Error(
101
+ "Setup accepts no path selections. Remove --config, --workspace, --host and --check-config"
102
+ );
103
+ const paths2 = await setupHost(await credentialInput());
104
+ await loadConfig(paths2.config, process.cwd());
105
+ process.stdout.write(
106
+ `Setup complete.
107
+ Configuration: ${paths2.config}
108
+ Credential: ${paths2.credential}
109
+ The next tool call can use this credential when the selected configuration names its path.
110
+ Restart after changing loaded configuration.
111
+ `
112
+ );
113
+ if (process.env.OPENROUTER_API_KEY)
114
+ process.stderr.write(
115
+ "OPENROUTER_API_KEY is set and takes precedence over the stored credential\n"
116
+ );
117
+ return;
118
+ }
119
+ const paths = args.host === "codex" ? hostPaths() : void 0;
120
+ const file = args.config ?? paths?.config;
121
+ const workspace = args.workspace ?? (args.host === "codex" ? process.cwd() : void 0);
122
+ if (!file || !workspace)
65
123
  throw new Error(
66
124
  "Explicit --config and --workspace are required (or their INTELLI_SEARCH_* environment equivalents)"
67
125
  );
68
- const { config: file, workspace } = args;
126
+ const canonicalWorkspace = await resolveWorkspace(workspace);
127
+ let workspaceDefect;
128
+ if (args.host === "codex" && !args.workspace) {
129
+ const home = await realpath(homedir()).catch(() => homedir());
130
+ if (canonicalWorkspace === parsePath(canonicalWorkspace).root || canonicalWorkspace === home)
131
+ workspaceDefect = "Codex working root must be a project directory, not the home or filesystem root; restart Codex from the project or with --cd <project>";
132
+ }
69
133
  if (args["check-config"]) {
70
- await loadConfig(file, workspace);
71
- process.stdout.write("Configuration is valid.\n");
134
+ if (workspaceDefect) throw new Error(workspaceDefect);
135
+ let builtInDefaults = false;
136
+ if (paths && !args.config) {
137
+ try {
138
+ await loadConfig(file, workspace);
139
+ } catch (error) {
140
+ if (!(error instanceof ConfigurationError) || error.reason !== "missing") throw error;
141
+ await defaultCodexConfig(workspace, paths);
142
+ builtInDefaults = true;
143
+ }
144
+ } else {
145
+ await loadConfig(file, workspace);
146
+ }
147
+ process.stdout.write(
148
+ builtInDefaults ? "Configuration is valid (built-in Codex defaults; no per-user file found).\n" : "Configuration is valid.\n"
149
+ );
72
150
  return;
73
151
  }
74
- await resolveWorkspace(workspace);
152
+ const loadSelected = async () => {
153
+ const loaded = await loadConfig(file, workspace);
154
+ return paths && !args.config && !loaded.apiKeyFile ? { ...loaded, apiKeyFile: paths.credential } : loaded;
155
+ };
75
156
  let config;
76
- try {
77
- config = await loadConfig(file, workspace);
78
- } catch (error) {
79
- if (!(error instanceof ConfigurationError)) throw error;
80
- process.stderr.write(
81
- `[mcp-intelli-search] ${error.message}. Serving anyway: each tool call reports this and rereads the file until it loads
157
+ if (workspaceDefect) {
158
+ const defect = workspaceDefect;
159
+ config = () => Promise.reject(new Error(defect));
160
+ } else {
161
+ try {
162
+ config = await loadSelected();
163
+ } catch (error) {
164
+ if (!(error instanceof ConfigurationError)) throw error;
165
+ if (paths && !args.config && error.reason === "missing") {
166
+ config = await defaultCodexConfig(workspace, paths);
167
+ } else {
168
+ process.stderr.write(
169
+ `[mcp-intelli-search] ${error.message}. Serving anyway: each tool call reports this and rereads the file until it loads
82
170
  `
83
- );
84
- config = () => loadConfig(file, workspace);
171
+ );
172
+ config = loadSelected;
173
+ }
174
+ }
85
175
  }
86
176
  installStdoutGuard();
87
177
  const { startServer } = await import("./server.js");
package/dist/runtime.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import {
2
- StandaloneError,
3
2
  createRuntime
4
- } from "./chunk-XGQZ3IDP.js";
3
+ } from "./chunk-NLULRY33.js";
5
4
  import {
6
5
  ConfigurationError,
6
+ StandaloneError,
7
7
  identity,
8
8
  loadConfig,
9
9
  parseConfig
10
- } from "./chunk-EHXBTGSE.js";
10
+ } from "./chunk-LXLEWIYT.js";
11
11
  export {
12
12
  ConfigurationError,
13
13
  StandaloneError,
package/dist/server.js CHANGED
@@ -2,17 +2,17 @@ import {
2
2
  installStdoutGuard
3
3
  } from "./chunk-ZTHYRKI2.js";
4
4
  import {
5
- StandaloneError,
6
5
  collateSchema,
7
6
  createRuntime,
8
7
  extractSchema,
9
8
  researchSchema,
10
9
  searchSchema
11
- } from "./chunk-XGQZ3IDP.js";
10
+ } from "./chunk-NLULRY33.js";
12
11
  import {
13
12
  ConfigurationError,
13
+ StandaloneError,
14
14
  identity
15
- } from "./chunk-EHXBTGSE.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.0",
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",