Skip to content

feat: add optional You.com search integration - #24

Open
mouse-value-add wants to merge 5 commits into
framerslab:masterfrom
mouse-value-add:feat/youcom-mcp-integration
Open

feat: add optional You.com search integration#24
mouse-value-add wants to merge 5 commits into
framerslab:masterfrom
mouse-value-add:feat/youcom-mcp-integration

Conversation

@mouse-value-add

@mouse-value-add mouse-value-add commented Jul 26, 2026

Copy link
Copy Markdown

Summary

This PR adds You.com as an optional search provider to AgentOS, enabling agents to access real-time web search and research capabilities through You.com's APIs.

Changes

  • YouComProvider: New provider implementing IProvider interface focused on search tools rather than LLM generation
  • Search API Integration: Direct integration with You.com Search API supporting both keyless (100 searches/day) and authenticated modes
  • Provider Registration: Added YouCom to AIModelProviderManager with auto-detection via YDC_API_KEY/YOUCOM_API_KEY
  • Comprehensive Documentation: Usage examples, configuration options, and integration guide
  • Test Coverage: Unit tests for core functionality and error handling

Key Features

  • Keyless Operation: 100 free searches per day per IP, no API key required for evaluation
  • Authenticated Access: Higher quotas and enhanced features with YDC_API_KEY
  • Two Search Models: youcom-search for web search, youcom-news for news search
  • Error Handling: Graceful handling of rate limits, network issues, and quota limits
  • Health Monitoring: Built-in connectivity testing and configuration validation

Usage Example

import { agent } from '@framers/agentos';

const researcher = agent({
  provider: 'youcom',
  instructions: 'You are a research assistant with access to current web information.'
});

const session = researcher.session('research-1');
await session.send('What are the latest developments in AI agent frameworks?');

Integration Approach

YouCom follows AgentOS provider patterns but focuses on search capabilities rather than text generation. This allows agents to augment LLM responses with current web information while maintaining compatibility with existing provider systems.

Environment Variables

  • YDC_API_KEY: Optional You.com API key (recommended for production)
  • YOUCOM_API_KEY: Legacy fallback environment variable
  • No configuration required for keyless operation

Testing

  • TypeScript compilation passes
  • Comprehensive unit test coverage
  • Example integration in examples/youcom-search-example.mjs
  • Health checks and error handling validated

This integration provides AgentOS agents with access to real-time web information while maintaining the framework's provider-agnostic architecture. The keyless tier enables immediate evaluation, while API key authentication unlocks higher quotas for production use.

Summary by Sourcery

Integrate You.com as an optional search-focused provider within AgentOS, including model registration, auto-detection, documentation, examples, and tests.

New Features:

  • Add YouComProvider implementing the IProvider interface to expose You.com web and news search capabilities as tools.
  • Register the youcom provider and its youcom-search and youcom-news models in the AIModelProviderManager and provider defaults for use by agents.
  • Support keyless and API-key-based operation for You.com via environment-based auto-detection (YDC_API_KEY/YOUCOM_API_KEY).

Enhancements:

  • Introduce health checking, connectivity testing, and informative completion behavior for the YouComProvider to fit into the existing provider ecosystem.

Build:

  • Add a pnpm-workspace.yaml skeleton for configuring native build allowances in the workspace.

Documentation:

  • Add a dedicated You.com provider documentation page covering configuration, authentication modes, available models, error handling, and best practices.

Tests:

  • Add integration-style tests validating YouComProvider initialization, model listing, search behavior, health checks, and unsupported operations handling.
  • Add an example script demonstrating practical usage of the YouCom provider with AgentOS agents and direct search API access.

Summary by CodeRabbit

  • New Features
    • Added You.com provider integration for web/news search with model discovery, connectivity checks, and rate-limit-aware errors.
    • Enabled automatic credential detection (including legacy fallback handling) and improved probe-based provider selection; You.com works in keyless mode for search.
    • Exposed YouComProvider from the main package.
  • Documentation
    • Added a full You.com provider guide (configuration, response formats, and troubleshooting).
  • Examples
    • Added a Node.js CLI search example for web and news.
  • Tests
    • Added integration coverage for provider lifecycle, request/response normalization, defaults, and unsupported operations.
  • Chores
    • Updated workspace build permissions configuration.

- Add YouComProvider implementing IProvider interface
- Integration with You.com Search API and MCP server
- Support for keyless (100 searches/day) and authenticated modes
- Expose search capabilities through youcom-search and youcom-news models
- Auto-detection via YDC_API_KEY and YOUCOM_API_KEY environment variables
- Comprehensive error handling and health monitoring
- Documentation and examples for integration
- Test coverage for core functionality

The YouCom provider focuses on search and research tools rather than LLM generation,
making current web information available to AgentOS agents through You.com's APIs.
@sourcery-ai

sourcery-ai Bot commented Jul 26, 2026

Copy link
Copy Markdown

🧙 Sourcery is reviewing your pull request!


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai

coderabbitai Bot commented Jul 26, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a YouCom provider with web/news search, health checks, model metadata, runtime autodetection, AgentOS manager wiring, integration tests, a CLI example, documentation, and workspace build configuration.

Changes

YouCom provider integration

Layer / File(s) Summary
Provider implementation
src/core/llm/providers/implementations/YouComProvider.ts
Adds configurable initialization, API-key detection, connectivity checks, web/news search, health reporting, model metadata, shutdown, and explicit unsupported-operation responses.
Runtime registration and manager wiring
src/api/model.ts, src/api/runtime/provider-defaults.ts, src/core/llm/providers/AIModelProviderManager.ts, src/index.ts
Adds keyless resolution, multi-key environment autodetection, provider configuration typing, manager initialization, and a top-level provider export.
Integration validation and example
tests/youcom-integration.test.ts, src/api/runtime/__tests__/provider-defaults.test.ts, examples/youcom-search-example.mjs
Tests lifecycle, search normalization, models, health, validation, unsupported operations, autodetection, and discoverability; adds a direct CLI search example.
Documentation and workspace configuration
docs/providers/youcom-provider.md, pnpm-workspace.yaml
Documents setup, response formats, limitations, integrations, troubleshooting, and standards; adds workspace build-approval entries.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant AgentOS
  participant AIModelProviderManager
  participant YouComProvider
  participant YouComSearchAPI
  AgentOS->>AIModelProviderManager: initialize youcom provider
  AIModelProviderManager->>YouComProvider: initialize configuration
  YouComProvider->>YouComSearchAPI: test connectivity
  AgentOS->>YouComProvider: search query
  YouComProvider->>YouComSearchAPI: request web or news results
  YouComSearchAPI-->>YouComProvider: search response
  YouComProvider-->>AgentOS: formatted search result
Loading

Possibly related PRs

  • framerslab/agentos#21: Extends the same provider manager wiring, defaults, and autodetection patterns for another provider.

Suggested reviewers: victor-evogor, jddunn

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main change: adding an optional You.com search integration.
Description check ✅ Passed The PR has the required Summary and substantial details, but it omits the template's Checklist and Related sections.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Add optional You.com (YouCom) provider for web/news search tools

✨ Enhancement 📝 Documentation 🧪 Tests ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Introduce a YouCom provider exposing You.com search as AgentOS “models” and tools.
• Register YouCom for defaults and env-based auto-detection (YDC_API_KEY / YOUCOM_API_KEY).
• Add docs, runnable example, and basic integration/unit tests for initialization and errors.
Diagram

graph TD
  A["Agent / Session"] --> B["AIModelProviderManager"] --> C["YouComProvider"] --> D{{"You.com Search API"}}
  E("Env vars") --> B --> F["provider-defaults"]
  C --> G["Docs & Example"]

  subgraph Legend
    direction LR
    _mod["Module/Component"] ~~~ _cfg("Configuration") ~~~ _ext{{"External service"}}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Implement You.com search as a Tool/Plugin (not an IProvider)
  • ➕ Matches semantics: search is a tool, not a completion/embedding model
  • ➕ Avoids stubbed generateCompletion()/streaming/embedding methods
  • ➕ Simplifies provider registry and model-default mapping
  • ➖ Requires introducing/standardizing a tool/plugin registration pathway
  • ➖ May be a larger refactor if AgentOS assumes providers own tool access
2. Use MCP client integration first (rather than direct Search API fetch)
  • ➕ Aligns with stated MCP roadmap and could unlock richer toolset (contents/research)
  • ➕ Centralizes auth and tool invocation patterns
  • ➖ Higher implementation complexity and dependency surface area
  • ➖ MCP endpoint/tooling stability may be less predictable than the search API

Recommendation: The PR’s approach is reasonable for an incremental integration: it fits existing provider discovery/selection and delivers immediate value via keyless/authenticated Search API access. Consider evolving toward a first-class tool/plugin abstraction (or MCP-based tool invocation) to better represent “search-only provider” semantics and reduce the need for placeholder completion/embedding methods.

Files changed (7) +806 / -1

Enhancement (4) +437 / -1
youcom-search-example.mjsAdd runnable example demonstrating AgentOS + YouCom search usage +119/-0

Add runnable example demonstrating AgentOS + YouCom search usage

• Adds a CLI example that creates an agent using the youcom provider and runs multiple queries using the search tool path. Also demonstrates direct provider.search() access and prints configuration snippets for keyless/authenticated modes.

examples/youcom-search-example.mjs

provider-defaults.tsAdd youcom defaults and env auto-detection probes +6/-0

Add youcom defaults and env auto-detection probes

• Registers youcom default ‘text/cheap’ model IDs as youcom-search (treating search as the primary capability). Adds YDC_API_KEY and YOUCOM_API_KEY probes to the provider auto-detect order, with the legacy key as fallback.

src/api/runtime/provider-defaults.ts

AIModelProviderManager.tsRegister YouComProvider in provider manager factory and config typing +5/-1

Register YouComProvider in provider manager factory and config typing

• Imports YouComProvider/YouComProviderConfig, expands the ProviderConfigEntry union type, and adds a switch case to instantiate the provider when providerId is 'youcom'.

src/core/llm/providers/AIModelProviderManager.ts

YouComProvider.tsIntroduce YouComProvider implementing IProvider with You.com Search API +307/-0

Introduce YouComProvider implementing IProvider with You.com Search API

• Adds a new IProvider implementation focused on search: initialize() configures endpoints and auto-detects API keys, search() calls You.com’s Search API with rate-limit handling, and checkHealth() performs a connectivity probe. listAvailableModels() exposes youcom-search and youcom-news as model-like capabilities, while embeddings/streaming are explicitly unsupported and completion returns an informative placeholder response.

src/core/llm/providers/implementations/YouComProvider.ts

Tests (1) +110 / -0
youcom-integration.test.tsAdd integration/unit tests for YouComProvider behavior +110/-0

Add integration/unit tests for YouComProvider behavior

• Covers initialization, available-model listing, health checks, configuration with API key, and unsupported embeddings behavior. Includes a best-effort search test that tolerates network/quota limits.

tests/youcom-integration.test.ts

Documentation (1) +246 / -0
youcom-provider.mdAdd YouCom provider integration guide and configuration reference +246/-0

Add YouCom provider integration guide and configuration reference

• Introduces end-to-end documentation for the YouCom provider, including keyless vs API-key auth, models, direct API usage, health checks, and troubleshooting. Includes best practices and points to an example script.

docs/providers/youcom-provider.md

Other (1) +13 / -0
pnpm-workspace.yamlAdd pnpm workspace allowBuilds configuration stub +13/-0

Add pnpm workspace allowBuilds configuration stub

• Adds an allowBuilds section listing native/binary packages with placeholder values. This appears intended as a workspace-level build policy template.

pnpm-workspace.yaml

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7d43387975

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +138 to +139
{ envKey: 'YDC_API_KEY', provider: 'youcom' },
{ envKey: 'YOUCOM_API_KEY', provider: 'youcom' }, // Fallback for legacy env var

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve You.com credentials before auto-detecting it

When agent() or generateText() is used with the documented YDC_API_KEY/YOUCOM_API_KEY environment setup, these probes select youcom, but resolveProvider() has neither variable in ENV_KEY_MAP and does not list You.com in KEYLESS_PROVIDER_IDS (src/api/model.ts:40-62). It therefore throws at src/api/model.ts:158-160 before YouComProvider.initialize() can read the key; keyless calls with an explicit provider: 'youcom' fail at the same point. Add the credential mappings and keyless handling to the high-level resolver.

Useful? React with 👍 / 👎.

Comment on lines +198 to +210
// For now, YouComProvider focuses on tool integration rather than LLM generation
// This could be enhanced to provide search-augmented responses
return {
id: `youcom-${Date.now()}`,
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
modelId: modelId,
choices: [{
index: 0,
message: {
role: 'assistant',
content: 'YouComProvider is optimized for search and research tools. Please use the search() method or integrate with AgentOS tools for web search capabilities.',
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Back agent calls with an actual search implementation

When a caller bypasses credential resolution with an explicit key and uses the documented agent({ provider: 'youcom' }).session().send(...) flow, generateText() invokes this method, which ignores the prompt and returns the same canned message without calling search(). The advertised tools: ['search'] does not bridge the gap either: the provider registers no ITool, and adaptTools() discards string arrays. Consequently the primary agent integration never performs a search; expose an executable search tool or implement search-backed/fallback completion behavior instead of reporting a successful completion.

Useful? React with 👍 / 👎.

Comment on lines +159 to +164
const { count = 10, type = 'web' } = options;

try {
const url = new URL(this.config.searchApiUrl!);
url.searchParams.set('query', query);
url.searchParams.set('count', count.toString());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply the requested search type

For calls such as the documented search(query, { type: 'news' }), type is destructured but never added to the request or used to transform the response, so the wire request is identical to the default web search. This makes the news option—and effectively the advertised youcom-news capability—unable to select news results; forward the type through the API's supported parameter/endpoint or implement the corresponding filtering.

Useful? React with 👍 / 👎.

Comment on lines +286 to +290
public async checkHealth(): Promise<{ isHealthy: boolean; details?: unknown }> {
try {
await this.testSearchConnectivity();
return { isHealthy: true, details: { apiKeyConfigured: Boolean(this.config.apiKey) } };
} catch (error) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate connectivity failures into health checks

When the endpoint is unreachable or responds with an error such as 401 or 500, testSearchConnectivity() catches and suppresses that failure, so this try always reaches the isHealthy: true return and the unhealthy branch is unreachable. Monitoring will therefore report a broken provider as healthy; use a non-swallowing connectivity probe for checkHealth() while retaining best-effort behavior only during initialization.

Useful? React with 👍 / 👎.

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 26, 2026

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Broken pnpm-workspace.yaml ✓ Resolved 🐞 Bug ☼ Reliability
Description
pnpm-workspace.yaml was added with placeholder string values under allowBuilds, which is not a
valid boolean allowlist and can break pnpm install/build behavior. This is a repo-wide build
reliability risk.
Code

pnpm-workspace.yaml[R1-13]

+allowBuilds:
+  '@matrix-org/matrix-sdk-crypto-nodejs': set this to true or false
+  '@whiskeysockets/baileys': set this to true or false
+  bcrypt: set this to true or false
+  better-sqlite3: set this to true or false
+  esbuild: set this to true or false
+  ffi-napi: set this to true or false
+  hnswlib-node: set this to true or false
+  onnxruntime-node: set this to true or false
+  protobufjs: set this to true or false
+  ref-napi: set this to true or false
+  sharp: set this to true or false
+  tesseract.js: set this to true or false
Evidence
The file content is placeholder text values rather than boolean configuration entries, so it is not
a valid allowlist as written.

pnpm-workspace.yaml[1-13]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`pnpm-workspace.yaml` contains placeholder string values (e.g. `set this to true or false`) under `allowBuilds`. This is not valid configuration for a build allowlist and can cause pnpm to misbehave or fail installs.
### Issue Context
This file is newly introduced in the PR, so any config error affects all contributors/CI immediately.
### Fix Focus Areas
- pnpm-workspace.yaml[1-13]
### Suggested fix
- Replace each placeholder value with an actual boolean (`true`/`false`) or convert to the correct pnpm configuration shape your repo uses (and remove `allowBuilds` entirely if it’s not supported/needed).
- If this repository expects workspace package globs, add the appropriate `packages:` section (only if applicable to this repo layout).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. YouCom auto-detect fails ✓ Resolved 🐞 Bug ≡ Correctness
Description
autoDetectProvider() can select youcom based on YDC_API_KEY, but resolveProvider() does not
read YDC_API_KEY (and will throw unless an API key is provided via YOUCOM_API_KEY or an explicit
override). This makes env-based auto-detection fail unexpectedly for text calls.
Code

src/api/runtime/provider-defaults.ts[R138-139]

+  { envKey: 'YDC_API_KEY', provider: 'youcom' },
+  { envKey: 'YOUCOM_API_KEY', provider: 'youcom' }, // Fallback for legacy env var
Evidence
The PR adds YDC_API_KEY/YOUCOM_API_KEY probes for auto-detection and a default text model for
youcom, but resolveProvider() only reads keys from ENV_KEY_MAP and otherwise throws when no
key is found—ENV_KEY_MAP has no youcom entry, so YDC_API_KEY won’t be used.

src/api/runtime/provider-defaults.ts[101-105]
src/api/runtime/provider-defaults.ts[123-139]
src/api/model.ts[40-63]
src/api/model.ts[120-164]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Provider auto-detection includes `YDC_API_KEY`/`YOUCOM_API_KEY` for `youcom`, but the credential resolver path used by `generateText()`/`agent()` (`resolveProvider`) only consults `ENV_KEY_MAP` and otherwise requires `${PROVIDER}_API_KEY`. Since `ENV_KEY_MAP` has no `youcom` entry, `YDC_API_KEY` is ignored and resolution can throw.
### Issue Context
- `autoDetectProvider('text')` can return `youcom` because `PROVIDER_DEFAULTS.youcom.text` exists.
- `generateText()` then calls `resolveProvider(providerId, modelId, ...)`, which throws when it can’t resolve an API key.
### Fix Focus Areas
- src/api/runtime/provider-defaults.ts[101-105]
- src/api/runtime/provider-defaults.ts[123-139]
- src/api/model.ts[40-63]
- src/api/model.ts[120-164]
### Suggested fix
- Teach `resolveProvider()` how to resolve You.com credentials:
- Add `youcom` to `ENV_KEY_MAP` (prefer `YDC_API_KEY`) and explicitly fall back to `YOUCOM_API_KEY`.
- If keyless mode is truly supported for the high-level API, also allow `providerId === 'youcom'` to proceed without an API key (similar to `KEYLESS_PROVIDER_IDS`), instead of throwing.
- Ensure behavior matches docs: if keyless is supported, don’t hard-require an API key in `resolveProvider()` for `youcom`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Completion returns static text ✓ Resolved 🐞 Bug ≡ Correctness
Description
YouComProvider.generateCompletion() returns a fixed instructional message instead of performing
model completion or delegating to a fallback provider. Because AgentOS’s generateText()/agent()
paths call provider.generateCompletion(), a youcom-selected text call will return incorrect
output for every request.
Code

src/core/llm/providers/implementations/YouComProvider.ts[R189-219]

+  public async generateCompletion(
+    modelId: string,
+    messages: ChatMessage[],
+    options: ModelCompletionOptions
+  ): Promise<ModelCompletionResponse> {
+    if (!this._isInitialized) {
+      throw new Error('YouComProvider is not initialized. Call initialize() first.');
+    }
+
+    // For now, YouComProvider focuses on tool integration rather than LLM generation
+    // This could be enhanced to provide search-augmented responses
+    return {
+      id: `youcom-${Date.now()}`,
+      object: 'chat.completion',
+      created: Math.floor(Date.now() / 1000),
+      modelId: modelId,
+      choices: [{
+        index: 0,
+        message: {
+          role: 'assistant',
+          content: 'YouComProvider is optimized for search and research tools. Please use the search() method or integrate with AgentOS tools for web search capabilities.',
+        },
+        finishReason: 'stop'
+      }],
+      usage: {
+        totalTokens: 50,
+        promptTokens: 25,
+        completionTokens: 25
+      }
+    };
+  }
Evidence
generateText() builds tools/messages and calls provider.generateCompletion(...) for actual text
output, while YouComProvider.generateCompletion() returns a constant message regardless of input,
and youcom is registered with a default text model.

src/api/runtime/provider-defaults.ts[101-105]
src/api/generateText.ts[1472-1493]
src/api/generateText.ts[1607-1651]
src/core/llm/providers/implementations/YouComProvider.ts[189-219]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`YouComProvider` is wired into the LLM provider manager and is given a default `text` model, but its `generateCompletion()` implementation does not generate text. This breaks normal usage paths (`agent()`, `generateText()`) that assume a provider will perform an actual completion.
### Issue Context
- The high-level API uses `provider.generateCompletion(...)` for text generation.
- `YouComProvider.generateCompletion(...)` always returns a canned response.
### Fix Focus Areas
- src/core/llm/providers/implementations/YouComProvider.ts[189-219]
- src/api/runtime/provider-defaults.ts[101-105]
- src/api/generateText.ts[1472-1493]
- src/api/generateText.ts[1607-1651]
### Suggested fix
Choose one consistent approach:
1) **Tool-only integration (recommended if You.com is search-only):**
- Remove `youcom` from `PROVIDER_DEFAULTS.text` so it can’t be selected for text generation.
- Make `generateCompletion()` throw a clear “unsupported” error (or route users to the dedicated search tool/service).
2) **Hybrid provider:**
- Implement `generateCompletion()` by performing `search()` and then delegating to a real LLM provider (configurable `fallbackProvider`) with the search results injected into the prompt.
- Ensure the provider advertises proper `capabilities` and behaves like other text providers.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (1)
4. Streaming method throws ✓ Resolved 🐞 Bug ☼ Reliability
Description
YouComProvider.generateCompletionStream() throws immediately, but streamText() expects to
iterate an async generator for streaming providers. Calling streaming APIs with provider: 'youcom'
will fail at runtime instead of yielding a terminal chunk or a clean error result.
Code

src/core/llm/providers/implementations/YouComProvider.ts[R224-230]

+  public async *generateCompletionStream(
+    modelId: string,
+    messages: ChatMessage[],
+    options: ModelCompletionOptions
+  ): AsyncGenerator<ModelCompletionResponse, void, undefined> {
+    throw new Error('Streaming completion is not implemented for YouComProvider. Use search tools instead.');
+  }
Evidence
streamText() directly calls provider.generateCompletionStream(...) and iterates chunks;
YouComProvider.generateCompletionStream() throws immediately; and the provider contract describes
streaming behavior expectations.

src/api/streamText.ts[639-713]
src/core/llm/providers/IProvider.ts[513-527]
src/core/llm/providers/implementations/YouComProvider.ts[224-230]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`generateCompletionStream()` is implemented as an async generator but throws before yielding anything. `streamText()` consumes provider streams via `for await (...)`, so this causes immediate rejection and no structured stream result.
### Issue Context
- `streamText()` calls `provider.generateCompletionStream(...)` and processes `responseTextDelta` chunks.
- The IProvider contract documents streaming invariants including a final chunk (`isFinal: true`) on completion/error.
### Fix Focus Areas
- src/core/llm/providers/implementations/YouComProvider.ts[224-230]
- src/api/streamText.ts[647-713]
- src/core/llm/providers/IProvider.ts[513-527]
### Suggested fix
Implement a non-streaming-compatible stream instead of throwing:
- Option A: Call `generateCompletion()` internally and yield a single chunk with:
- `responseTextDelta` set to the full assistant message content
- `isFinal: true`
- `usage` populated
- Option B: Yield a single `isFinal: true` chunk with `error: { message, type }` when streaming is unsupported.
Either approach prevents hard crashes and lets `streamText()` return a deterministic result.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

5. Search type ignored ✓ Resolved 🐞 Bug ≡ Correctness
Description
YouComProvider.search() accepts type: 'web' | 'news' but never uses it in the request, so
callers cannot actually select the news search behavior. This contradicts the advertised
youcom-news model and the docs’ news-search examples.
Code

src/core/llm/providers/implementations/YouComProvider.ts[R154-165]

+  public async search(query: string, options: { count?: number; type?: 'web' | 'news' } = {}): Promise<YouComSearchResult> {
+    if (!this._isInitialized) {
+      throw new Error('YouComProvider is not initialized. Call initialize() first.');
+    }
+
+    const { count = 10, type = 'web' } = options;
+    
+    try {
+      const url = new URL(this.config.searchApiUrl!);
+      url.searchParams.set('query', query);
+      url.searchParams.set('count', count.toString());
+      
Evidence
The method reads type but only sends query and count; meanwhile, the provider claims to
support a separate news model and the docs show calling search(..., { type: 'news' }).

src/core/llm/providers/implementations/YouComProvider.ts[154-165]
src/core/llm/providers/implementations/YouComProvider.ts[246-272]
docs/providers/youcom-provider.md[87-91]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`search()` destructures `type` but does not translate it into any API parameter or endpoint selection. As a result, `{ type: 'news' }` behaves the same as web search.
### Issue Context
The provider also advertises a `youcom-news` model in `listAvailableModels()`, implying a distinct behavior.
### Fix Focus Areas
- src/core/llm/providers/implementations/YouComProvider.ts[154-180]
- src/core/llm/providers/implementations/YouComProvider.ts[246-272]
### Suggested fix
- Map `type` (or `modelId === 'youcom-news'`) to the You.com API’s supported request shape (query param or path) so news searches are actually requested.
- Add a small unit test asserting that `type: 'news'` changes the outgoing request URL (e.g., includes a `type=news` param or hits a news endpoint).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

6. Example tools ignored ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
The example config passes tools: ['search'], but the runtime tool adapter drops arrays that aren’t
proper tool definitions, so no tools are actually available to the agent. Users copying the example
will not get any functional search tool access.
Code

examples/youcom-search-example.mjs[R23-31]

+    const searchAgent = agent({
+      provider: 'youcom',
+      instructions: `You are a research assistant with access to current web information through You.com search.
+      
+When users ask questions that require current information, use your search capabilities to find relevant results.
+Always cite your sources with URLs and provide a balanced view from multiple sources when possible.`,
+      tools: ['search'], // YouCom provider exposes search as a core capability
+      memory: { types: ['episodic'], working: { enabled: true } },
+    });
Evidence
The example uses a string array for tools; agent() forwards tools to generateText(), and
adaptTools() explicitly returns [] for arrays that don’t match the supported tool entry shapes.

examples/youcom-search-example.mjs[23-31]
src/api/agent.ts[750-755]
src/api/generateText.ts[1479-1482]
src/api/runtime/toolAdapter.ts[294-307]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The example passes a string array for `tools`, but `adaptTools()` returns `[]` for arrays that are not `ToolDefinitionForLLM[]` or named external tool entries. This means the example’s `tools: ['search']` is a no-op.
### Issue Context
`agent()` forwards `opts.tools` into `generateText()`, which calls `adaptTools(opts.tools)`.
### Fix Focus Areas
- examples/youcom-search-example.mjs[23-31]
- src/api/agent.ts[750-755]
- src/api/generateText.ts[1479-1482]
- src/api/runtime/toolAdapter.ts[294-307]
### Suggested fix
- Replace `tools: ['search']` with one of the supported tool input shapes:
- A tool map `{ search: { description, parameters, execute } }`, or
- A proper `ToolDefinitionForLLM[]` entry (name/description/inputSchema), or
- A named external tool registry entry.
- Alternatively, remove the `tools` line from the example and demonstrate direct `provider.search()` only (since that API exists).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Comment thread pnpm-workspace.yaml Outdated
Comment thread src/api/runtime/provider-defaults.ts
Comment thread src/core/llm/providers/implementations/YouComProvider.ts
Comment thread src/core/llm/providers/implementations/YouComProvider.ts
Comment thread src/core/llm/providers/implementations/YouComProvider.ts Outdated
Comment thread examples/youcom-search-example.mjs Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 12

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/providers/youcom-provider.md`:
- Around line 73-80: Update the Direct Search API example to import
YouComProvider from its public package path and use keyless initialization by
omitting apiKey, or conditionally reading process.env.YDC_API_KEY without
passing the literal string "optional".
- Around line 55-63: Fix both examples in the youcom provider documentation by
eliminating the self-shadowing `const agent = agent(...)` declaration. Rename
the local instance variable or alias the imported `agent` factory, and apply the
same correction to the additional snippet while preserving the existing
configuration and usage.
- Around line 20-28: Update the quick-start example around the researcher agent
and session.send call to configure a text-generation-capable fallback LLM
alongside the YouCom provider, or replace the completion-style prompt with an
explicit YouCom search/tool invocation. Ensure the copy-paste example can
execute successfully while preserving the current research-assistant intent.
- Around line 7-11: Update the introductory capability list in the YouCom
provider documentation to describe only the currently exposed youcom-search and
youcom-news functionality. Move the content extraction and research synthesis
bullets to the MCP section, or clearly label them as planned future MCP tools.

In `@pnpm-workspace.yaml`:
- Around line 1-13: Replace every placeholder value under allowBuilds with an
audited boolean approval decision, using true or false for each listed package.
Preserve the existing package keys and ensure no placeholder text remains.

In `@src/api/runtime/provider-defaults.ts`:
- Around line 138-139: Update the youcom probe construction and
PROBE_BY_PROVIDER handling in the provider defaults so a custom priority
containing youcom retains both YDC_API_KEY and YOUCOM_API_KEY probes, checking
the primary variable as well as the legacy fallback. Ensure deduplication does
not discard the YDC_API_KEY entry when retaining the last youcom probe.

In `@src/core/llm/providers/implementations/YouComProvider.ts`:
- Around line 154-165: Update the `YouComProvider.search` method to apply the
destructured `type` value when constructing the request and handling its
response, so `type: 'news'` uses the news-specific behavior while `type: 'web'`
preserves the existing web search behavior. Ensure the advertised `youcom-news`
capability routes through this implemented news path.
- Around line 116-131: Update testSearchConnectivity and its callers so failed
HTTP responses or network errors produce an unsuccessful health result instead
of being treated as healthy. Preserve offline-tolerant initialization by
explicitly ignoring or handling the failure only during initialization, while
checkHealth propagates or consumes the probe status and returns isHealthy:
false.
- Around line 189-218: The YouComProvider.generateCompletion method must reject
unsupported text generation instead of returning boilerplate content and
fabricated usage; throw the established unsupported-operation error until real
fallback delegation exists. In
src/core/llm/providers/implementations/YouComProvider.ts lines 189-218, replace
the hard-coded completion response; in src/api/runtime/provider-defaults.ts
lines 101-104, remove text/cheap defaults unless backed by a real completion
provider; in tests/youcom-integration.test.ts lines 88-99, assert the
unsupported-operation error; and in examples/youcom-search-example.mjs lines
23-31, demonstrate direct search or configure a real completion provider.
- Around line 52-64: Update YouComProvider’s searchApiUrl default and request
authentication to use the documented https://ydc-index.io/v1/search endpoint
with X-API-Key instead of bearer auth. In search(), normalize authenticated
responses from data.results into YouComSearchResult, and update that interface’s
web/news fields to represent description and snippets while preserving title,
url, and published_at where applicable.

In `@tests/youcom-integration.test.ts`:
- Around line 102-109: Replace the literal self-comparison in the “should be
discoverable in provider registry” test with an actual AIModelProviderManager
integration. Initialize the manager using an enabled youcom provider
configuration, then call getProvider('youcom') and assert that the provider is
returned.
- Around line 39-59: Replace the broad catch in “should perform basic search
functionality” with a mocked fetch-based test that asserts the request endpoint,
parameters, and normalized search response. Remove unconditional success on
search errors; only skip explicitly recognized network or quota failures, while
propagating authentication, endpoint, parsing, and parameter errors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: adebb081-6aea-4a56-85cf-ca76cc47d8e6

📥 Commits

Reviewing files that changed from the base of the PR and between 5aeb630 and 7d43387.

📒 Files selected for processing (7)
  • docs/providers/youcom-provider.md
  • examples/youcom-search-example.mjs
  • pnpm-workspace.yaml
  • src/api/runtime/provider-defaults.ts
  • src/core/llm/providers/AIModelProviderManager.ts
  • src/core/llm/providers/implementations/YouComProvider.ts
  • tests/youcom-integration.test.ts

Comment thread docs/providers/youcom-provider.md Outdated
Comment thread docs/providers/youcom-provider.md Outdated
Comment thread docs/providers/youcom-provider.md Outdated
Comment thread docs/providers/youcom-provider.md
Comment thread pnpm-workspace.yaml Outdated
Comment thread src/core/llm/providers/implementations/YouComProvider.ts Outdated
Comment thread src/core/llm/providers/implementations/YouComProvider.ts Outdated
Comment on lines +189 to +218
public async generateCompletion(
modelId: string,
messages: ChatMessage[],
options: ModelCompletionOptions
): Promise<ModelCompletionResponse> {
if (!this._isInitialized) {
throw new Error('YouComProvider is not initialized. Call initialize() first.');
}

// For now, YouComProvider focuses on tool integration rather than LLM generation
// This could be enhanced to provide search-augmented responses
return {
id: `youcom-${Date.now()}`,
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
modelId: modelId,
choices: [{
index: 0,
message: {
role: 'assistant',
content: 'YouComProvider is optimized for search and research tools. Please use the search() method or integrate with AgentOS tools for web search capabilities.',
},
finishReason: 'stop'
}],
usage: {
totalTokens: 50,
promptTokens: 25,
completionTokens: 25
}
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Do not route text generation to a provider that returns boilerplate.

YouComProvider.generateCompletion() returns a successful hard-coded response and invented token usage, while runtime defaults route text requests to it. Consequently, auto-detected and example session.send() requests return boilerplate rather than search-backed output or an explicit unsupported-operation error.

  • src/core/llm/providers/implementations/YouComProvider.ts#L189-L218: reject completions as unsupported until real fallback delegation is implemented; do not fabricate a successful completion.
  • src/api/runtime/provider-defaults.ts#L101-L104: remove text/cheap defaults, or register them only when an actual fallback completion provider is wired.
  • tests/youcom-integration.test.ts#L88-L99: assert the intended unsupported-operation error rather than the placeholder response.
  • examples/youcom-search-example.mjs#L23-L31: demonstrate direct search or configure a real completion provider alongside the search integration.
📍 Affects 4 files
  • src/core/llm/providers/implementations/YouComProvider.ts#L189-L218 (this comment)
  • src/api/runtime/provider-defaults.ts#L101-L104
  • tests/youcom-integration.test.ts#L88-L99
  • examples/youcom-search-example.mjs#L23-L31
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/llm/providers/implementations/YouComProvider.ts` around lines 189 -
218, The YouComProvider.generateCompletion method must reject unsupported text
generation instead of returning boilerplate content and fabricated usage; throw
the established unsupported-operation error until real fallback delegation
exists. In src/core/llm/providers/implementations/YouComProvider.ts lines
189-218, replace the hard-coded completion response; in
src/api/runtime/provider-defaults.ts lines 101-104, remove text/cheap defaults
unless backed by a real completion provider; in tests/youcom-integration.test.ts
lines 88-99, assert the unsupported-operation error; and in
examples/youcom-search-example.mjs lines 23-31, demonstrate direct search or
configure a real completion provider.

Comment thread tests/youcom-integration.test.ts Outdated
Comment thread tests/youcom-integration.test.ts Outdated
- Replace placeholder values in pnpm-workspace.yaml with proper boolean configuration
- Add youcom to ENV_KEY_MAP for proper environment key resolution
- Add youcom to KEYLESS_PROVIDER_IDS to support keyless operation
- Remove youcom from PROVIDER_DEFAULTS text models since it's search-only
- Fix generateCompletion to throw error instead of returning static response
- Fix generateCompletionStream to yield proper error response instead of throwing
- Fix search method to actually use the 'type' parameter for news vs web search

This addresses the main issues raised by CodeRabbit and other reviewers:
- Broken pnpm workspace configuration
- Auto-detection failure due to missing ENV_KEY mapping
- Incorrect completion behavior for search-only provider
- Search type parameter being ignored
@mouse-value-add

Copy link
Copy Markdown
Author

Good catch on the key issues raised by the automated reviews! I've addressed the main problems:

Fixed pnpm-workspace.yaml:

  • Replaced all placeholder string values with proper boolean configuration ( for all listed packages)

Fixed YouCom auto-detection:

  • Added to ENV_KEY_MAP in model.ts for proper environment key resolution
  • Added to KEYLESS_PROVIDER_IDS to support keyless operation
  • Removed youcom from PROVIDER_DEFAULTS text models since it's search-only, not an LLM provider

Fixed provider behavior:

  • Changed to throw a clear error instead of returning static text
  • Fixed to yield a proper error response instead of throwing immediately
  • Fixed method to actually use the parameter (news vs web search)

These changes align the implementation with the intended design: YouComProvider as a search tool provider, not a text completion provider. The provider registry and auto-detection should now work properly while making it clear that this provider is for search capabilities.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
src/core/llm/providers/implementations/YouComProvider.ts (4)

181-182: 🎯 Functional Correctness | 🟠 Major

Normalize the API response before returning it.

This remains the previously reported contract issue: return data exposes the raw { results, metadata } envelope as YouComSearchResult without validation or normalization. Ensure the declared type matches the documented results.web/results.news entries, including description and snippets, and add coverage for both result sections. (you.com)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/llm/providers/implementations/YouComProvider.ts` around lines 181 -
182, Update the response handling in YouComProvider so the parsed API envelope
is validated and normalized into the declared YouComSearchResult shape before
returning, rather than returning raw data. Ensure results.web and results.news
entries include the documented description and snippets fields, and add coverage
for both sections.

87-87: 🎯 Functional Correctness | 🟠 Major

Align the endpoint and authentication with You.com’s Search API contract.

This remains the previously reported mismatch: Line 87 uses api.you.com/v1/agents/search, while Lines 144-146 send Authorization: Bearer. The current Search API documents GET /v1/search with X-API-Key; authenticated requests will fail unless this integration is updated or the custom endpoint is explicitly supported separately. (you.com)

Also applies to: 144-146

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/llm/providers/implementations/YouComProvider.ts` at line 87, Update
YouComProvider’s searchApiUrl to the documented GET /v1/search endpoint and
change the request authentication from Authorization: Bearer to the X-API-Key
header, ensuring the configured API key is sent under that header consistently.

118-121: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Add timeouts to the You.com outbound fetches.

initialize() and search() both call fetch() directly, so slow/unreachable You.com API traffic can leave startup, health checks, or user searches stalled. Use bounded timeout signals for both requests at lines 117-169 and keep the existing network-error handling in the catch blocks.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/llm/providers/implementations/YouComProvider.ts` around lines 118 -
121, Update the outbound fetch calls in YouComProvider.initialize() and search()
to use bounded timeout signals, including the existing fetch at the
initialization health check and the search request. Preserve the current request
behavior and network-error handling in their catch blocks while ensuring both
requests abort when their timeout expires.

159-164: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reject invalid count values before building the You.com request.

The Search API uses 10 as the default when count is omitted; accept only an explicit integer in a supported range and throw before url.searchParams.set('count', ...).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/llm/providers/implementations/YouComProvider.ts` around lines 159 -
164, Validate the explicit count value in the YouComProvider request flow before
constructing the URL or calling url.searchParams.set('count', ...). Preserve 10
only when count is omitted, and otherwise require an integer within the Search
API’s supported range, throwing for invalid values.
♻️ Duplicate comments (2)
src/core/llm/providers/implementations/YouComProvider.ts (2)

165-167: 🎯 Functional Correctness | 🟠 Major

Do not rely on the undocumented type=news parameter.

This is similar to the previous search-type finding, but the current public API contract does not list type as a query parameter. The API returns unified web/news results based on query intent; news workflows use supported controls such as freshness, then consume results.news. As written, youcom-news is not guaranteed to perform news-specific searches. (you.com)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/llm/providers/implementations/YouComProvider.ts` around lines 165 -
167, Remove the undocumented type=news query parameter handling from the search
URL construction in YouComProvider. Preserve supported controls such as
freshness for news requests and continue consuming news results through the
existing results.news workflow.

116-131: 🎯 Functional Correctness | 🟠 Major

Make health checks report failed probes.

This remains unresolved: testSearchConnectivity() catches failures and returns normally, so checkHealth() always returns isHealthy: true. Preserve offline-tolerant initialization if required, but return the probe result as unhealthy from checkHealth().

Also applies to: 284-287

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/llm/providers/implementations/YouComProvider.ts` around lines 116 -
131, Update YouComProvider.testSearchConnectivity and its checkHealth caller so
probe failures are reported as unhealthy instead of being swallowed as
successful completion. Preserve the current non-throwing behavior during
initialization, but return or propagate an explicit success/failure result from
testSearchConnectivity and use it to set checkHealth’s isHealthy value.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/core/llm/providers/implementations/YouComProvider.ts`:
- Around line 181-182: Update the response handling in YouComProvider so the
parsed API envelope is validated and normalized into the declared
YouComSearchResult shape before returning, rather than returning raw data.
Ensure results.web and results.news entries include the documented description
and snippets fields, and add coverage for both sections.
- Line 87: Update YouComProvider’s searchApiUrl to the documented GET /v1/search
endpoint and change the request authentication from Authorization: Bearer to the
X-API-Key header, ensuring the configured API key is sent under that header
consistently.
- Around line 118-121: Update the outbound fetch calls in
YouComProvider.initialize() and search() to use bounded timeout signals,
including the existing fetch at the initialization health check and the search
request. Preserve the current request behavior and network-error handling in
their catch blocks while ensuring both requests abort when their timeout
expires.
- Around line 159-164: Validate the explicit count value in the YouComProvider
request flow before constructing the URL or calling
url.searchParams.set('count', ...). Preserve 10 only when count is omitted, and
otherwise require an integer within the Search API’s supported range, throwing
for invalid values.

---

Duplicate comments:
In `@src/core/llm/providers/implementations/YouComProvider.ts`:
- Around line 165-167: Remove the undocumented type=news query parameter
handling from the search URL construction in YouComProvider. Preserve supported
controls such as freshness for news requests and continue consuming news results
through the existing results.news workflow.
- Around line 116-131: Update YouComProvider.testSearchConnectivity and its
checkHealth caller so probe failures are reported as unhealthy instead of being
swallowed as successful completion. Preserve the current non-throwing behavior
during initialization, but return or propagate an explicit success/failure
result from testSearchConnectivity and use it to set checkHealth’s isHealthy
value.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7cef24e2-27e4-4116-8441-99ac54388622

📥 Commits

Reviewing files that changed from the base of the PR and between 7d43387 and 6095ba7.

📒 Files selected for processing (4)
  • pnpm-workspace.yaml
  • src/api/model.ts
  • src/api/runtime/provider-defaults.ts
  • src/core/llm/providers/implementations/YouComProvider.ts
💤 Files with no reviewable changes (1)
  • src/api/runtime/provider-defaults.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • pnpm-workspace.yaml

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
tests/youcom-integration.test.ts (1)

27-38: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Stub YDC_API_KEY/YOUCOM_API_KEY to avoid host-environment leakage.

Several tests call provider.initialize({}) with no explicit apiKey and then assert unauthenticated behavior (e.g. apiKeyConfigured: false at Line 154, no X-API-Key header expectations). YouComProvider.initialize auto-detects the key from process.env.YDC_API_KEY || process.env.YOUCOM_API_KEY. Since this PR introduces these exact env vars as first-class provider-detection keys (see provider-defaults.ts), any CI runner or local shell that happens to export them will silently flip these tests into authenticated mode and break the assertions.

🧪 Suggested fix: isolate env in beforeEach/afterEach
   beforeEach(() => {
     provider = new YouComProvider();
     fetchMock = vi.fn();
     vi.stubGlobal('fetch', fetchMock);
+    vi.stubEnv('YDC_API_KEY', '');
+    vi.stubEnv('YOUCOM_API_KEY', '');
   });

   afterEach(async () => {
     if (provider.isInitialized) {
       await provider.shutdown();
     }
     vi.unstubAllGlobals();
+    vi.unstubAllEnvs();
   });

Also applies to: 40-166

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/youcom-integration.test.ts` around lines 27 - 38, Isolate the YouCom
integration tests from host authentication settings by stubbing YDC_API_KEY and
YOUCOM_API_KEY to an absent value in beforeEach and restoring the original
environment in afterEach. Update the setup around provider initialization so
tests calling YouComProvider.initialize({}) consistently exercise
unauthenticated behavior while preserving environment cleanup.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@tests/youcom-integration.test.ts`:
- Around line 27-38: Isolate the YouCom integration tests from host
authentication settings by stubbing YDC_API_KEY and YOUCOM_API_KEY to an absent
value in beforeEach and restoring the original environment in afterEach. Update
the setup around provider initialization so tests calling
YouComProvider.initialize({}) consistently exercise unauthenticated behavior
while preserving environment cleanup.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 560c7aa5-3cfd-43b0-81c9-d79d8b4d8c50

📥 Commits

Reviewing files that changed from the base of the PR and between 6095ba7 and 668312b.

📒 Files selected for processing (6)
  • docs/providers/youcom-provider.md
  • examples/youcom-search-example.mjs
  • src/api/runtime/provider-defaults.ts
  • src/core/llm/providers/implementations/YouComProvider.ts
  • src/index.ts
  • tests/youcom-integration.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • docs/providers/youcom-provider.md
  • src/core/llm/providers/implementations/YouComProvider.ts

Stub YDC_API_KEY and YOUCOM_API_KEY to ensure tests consistently exercise
unauthenticated behavior without interference from host environment settings.
@mouse-value-add

Copy link
Copy Markdown
Author

Fixed the environment isolation issue in tests. Added proper stubbing of YDC_API_KEY and YOUCOM_API_KEY environment variables to ensure tests consistently exercise unauthenticated behavior without interference from host environment settings.

This addresses the test reliability concern where CI runners or local environments with these keys would break test assertions.

@mouse-value-add

Copy link
Copy Markdown
Author

Follow-up fixes are in on feat/youcom-mcp-integration.

This keeps YouCom keyless by default in the quick start/example and isolates the tests from host YDC_API_KEY / YOUCOM_API_KEY settings.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/api/runtime/__tests__/provider-defaults.test.ts`:
- Around line 130-145: Revise the autoDetectProvider tests around the “detects
youcom from YDC_API_KEY” case to separate YDC-only and YOUCOM_API_KEY-only
detection scenarios, removing the ambiguity caused by setting both variables. If
YDC_API_KEY precedence is part of the contract, add a separate assertion against
the resolved credential rather than inferring precedence from the provider
result.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 3d184b2a-50d8-417b-9da0-63077766bb14

📥 Commits

Reviewing files that changed from the base of the PR and between 81e7dbe and 8c26ad1.

📒 Files selected for processing (3)
  • docs/providers/youcom-provider.md
  • examples/youcom-search-example.mjs
  • src/api/runtime/__tests__/provider-defaults.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/providers/youcom-provider.md

Comment on lines +130 to +145
it('detects youcom from YDC_API_KEY before the legacy fallback', () => {
delete process.env.OPENAI_API_KEY;
delete process.env.OPENROUTER_API_KEY;
delete process.env.ANTHROPIC_API_KEY;
delete process.env.GEMINI_API_KEY;
delete process.env.GROQ_API_KEY;
delete process.env.TOGETHER_API_KEY;
delete process.env.MISTRAL_API_KEY;
delete process.env.XAI_API_KEY;
delete process.env.OLLAMA_BASE_URL;
delete process.env.STABILITY_API_KEY;
delete process.env.REPLICATE_API_TOKEN;
process.env.YDC_API_KEY = 'new-key';
process.env.YOUCOM_API_KEY = 'legacy-key';

expect(autoDetectProvider()).toBe('youcom');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

This assertion does not verify key precedence.

With both environment variables set, autoDetectProvider() returns youcom regardless of probe order. Split this into YDC-only and legacy-only detection tests, and assert the resolved credential separately if YDC_API_KEY precedence is part of the contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/api/runtime/__tests__/provider-defaults.test.ts` around lines 130 - 145,
Revise the autoDetectProvider tests around the “detects youcom from YDC_API_KEY”
case to separate YDC-only and YOUCOM_API_KEY-only detection scenarios, removing
the ambiguity caused by setting both variables. If YDC_API_KEY precedence is
part of the contract, add a separate assertion against the resolved credential
rather than inferring precedence from the provider result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant