A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(coding-agent): bundle default websearch skill (#86)
rasdanid773015ba9b1
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex 8905864d68..6cd68727da 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -2,6 +2,10 @@## [Unreleased]+### Added++- Added a bundled `websearch` skill (Google search via the Serper API) that loads by default. Add a Serper key via `/login` ("Serper (web search)"); it is stored with your other credentials and supplied to the skill automatically. The skill can be disabled with `bundledSkills.websearch: false` and overridden by a same-named skill in any user, project, package, or `--skill` location.+## [0.2.1] - 2026-06-23### Fixeddiff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.mdindex d7f9489e45..42f978011b 100644--- a/packages/coding-agent/README.md+++ b/packages/coding-agent/README.md@@ -303,6 +303,8 @@ Skills can also be Python-backed. A Python skill is a normal skill directory witPlace in `~/.prime/agent/skills/`, `~/.agents/skills/`, `.prime/agent/skills/`, or `.agents/skills/` (from `cwd` up through parent directories) or a [Prime Agent package](#prime-agent-packages) to share with others. See [docs/skills.md](docs/skills.md).+Prime Agent ships with a built-in `websearch` skill (Google search via the [Serper](https://serper.dev) API). It loads by default; run `/login` and choose "Serper (web search)" to add your key, disable it with `bundledSkills.websearch: false`, or override it with your own `websearch` skill in any location above. See [docs/skills.md#built-in-skills](docs/skills.md#built-in-skills).+### Extensions<p align="center"><img src="docs/images/doom-extension.png" alt="Doom Extension" width="600"></p>diff --git a/packages/coding-agent/docs/settings.md b/packages/coding-agent/docs/settings.mdindex a22246638a..49a2b5c602 100644--- a/packages/coding-agent/docs/settings.md+++ b/packages/coding-agent/docs/settings.md@@ -212,9 +212,20 @@ Paths in `~/.pi/agent/settings.json` resolve relative to `~/.pi/agent`. Paths in| `themes` | string[] | `[]` | Local theme file paths or directories || `enableSkillCommands` | boolean | `true` | Register skills as `/skill:name` commands || `enableBuiltinSkills` | boolean | `true` | Load built-in skills shipped with prime-agent |+| `bundledSkills.websearch` | boolean | `true` | Load the built-in `websearch` skill |Arrays support glob patterns and exclusions. Use `!pattern` to exclude. Use `+path` to force-include an exact path and `-path` to force-exclude an exact path.+Disable the built-in `websearch` skill while keeping normal skill discovery enabled:++```json+{+ "bundledSkills": {+ "websearch": false+ }+}+```+#### packagesString form loads all resources from a package:diff --git a/packages/coding-agent/docs/skills.md b/packages/coding-agent/docs/skills.mdindex 03ca1e2301..893c980d36 100644--- a/packages/coding-agent/docs/skills.md+++ b/packages/coding-agent/docs/skills.md@@ -45,12 +45,49 @@ Disable discovery with `--no-skills` (explicit `--skill` paths still load).## Built-in Skills-Prime Agent ships with built-in skills that teach the agent the Prime Intellect ecosystem:+Prime Agent ships with built-in skills that load by default:- `prime-intellect` - Prime Intellect products and workflows via the prime CLI: verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, sandboxes, tunnels, Prime Inference, GPU compute, and storage. Reference docs for each area load on demand from the skill's `references/` directory.- `skill-creator` - teaches the agent to create new skills: markdown skill layout, frontmatter rules, placement and precedence, and the full Python-backed skill contract (package layout, `run()` convention, optional CLI, kernel venv behavior) with a working template in `references/python-skills.md`.+- `websearch` - a Python-backed Google search skill using the [Serper](https://serper.dev) API.-Built-in skills behave like any other skill but have the lowest precedence: a user, project, or package skill with the same name overrides the built-in one.+Built-in skills behave like any other skill but have the lowest precedence: a user, project, package, or `--skill` skill with the same name overrides the built-in one.++### websearch++Setup: get a free API key at [serper.dev](https://serper.dev), then run `/login`,+switch to the **Services** tab (left/right arrows), and choose **Serper (web+search)** to paste it. The key is stored alongside your other credentials (in+`auth.json`) and read by the skill on each call — no environment variables+required, and it works even if you add the key mid-session.++Optional overrides (environment variables):++```bash+export PRIME_AGENT_WEBSEARCH_TIMEOUT=45+export PRIME_AGENT_WEBSEARCH_NUM_RESULTS=5+```++A `SERPER_API_KEY` in the environment, if set, takes precedence over the stored key.++Once loaded, the model can call it directly in the IPython kernel by import name:++```python+print(await websearch("latest Prime Agent release"))+```++Until a key is configured, web search returns a clear message telling the agent+to walk you through `/login`.++Disable only the built-in `websearch` skill in settings:++```json+{+ "bundledSkills": {+ "websearch": false+ }+}+```To disable all built-in skills, set `enableBuiltinSkills` to `false` in `settings.json` (or toggle "Built-in skills" in `/settings`):@@ -60,7 +97,7 @@ To disable all built-in skills, set `enableBuiltinSkills` to `false` in `setting}```-`--no-skills` also excludes them. To disable a single built-in skill, force-exclude it in the global `skills` array (patterns resolve against the built-in skills directory):+`--no-skills` also excludes built-in skills. To disable a single built-in skill without a dedicated setting, force-exclude it in the global `skills` array (patterns resolve against the built-in skills directory):```json{diff --git a/packages/coding-agent/package.json b/packages/coding-agent/package.jsonindex e3e8c8a932..5b99ce7c91 100644--- a/packages/coding-agent/package.json+++ b/packages/coding-agent/package.json@@ -36,7 +36,7 @@"build": "tsgo -p tsconfig.build.json && shx chmod +x dist/cli.js && npm run copy-assets && npm run bundle","build:binary": "npm --prefix ../tui run build && npm --prefix ../ai run build && npm --prefix ../agent run build && npm run build && bun build --compile ./dist/bun/cli.js --outfile dist/pi && npm run copy-binary-assets","copy-assets": "shx mkdir -p dist/modes/interactive/theme && shx cp src/modes/interactive/theme/*.json dist/modes/interactive/theme/ && shx mkdir -p dist/modes/interactive/assets && shx cp src/modes/interactive/assets/*.png dist/modes/interactive/assets/ && shx mkdir -p dist/core/export-html/vendor && shx cp src/core/export-html/template.html src/core/export-html/template.css src/core/export-html/template.js dist/core/export-html/ && shx cp src/core/export-html/vendor/*.js dist/core/export-html/vendor/ && shx rm -rf dist/prime-agent-runtime && shx cp -r ../../prime-agent-runtime dist/prime-agent-runtime && shx rm -rf dist/skills && shx cp -r skills dist/skills",- "copy-binary-assets": "shx cp package.json dist/ && shx cp README.md dist/ && shx cp CHANGELOG.md dist/ && shx mkdir -p dist/theme && shx cp src/modes/interactive/theme/*.json dist/theme/ && shx mkdir -p dist/assets && shx cp src/modes/interactive/assets/*.png dist/assets/ && shx mkdir -p dist/export-html/vendor && shx cp src/core/export-html/template.html dist/export-html/ && shx cp src/core/export-html/vendor/*.js dist/export-html/vendor/ && shx cp -r docs dist/ && shx cp -r examples dist/ && shx cp ../../node_modules/@silvia-odwyer/photon-node/photon_rs_bg.wasm dist/",+ "copy-binary-assets": "shx cp package.json dist/ && shx cp README.md dist/ && shx cp CHANGELOG.md dist/ && shx mkdir -p dist/theme && shx cp src/modes/interactive/theme/*.json dist/theme/ && shx mkdir -p dist/assets && shx cp src/modes/interactive/assets/*.png dist/assets/ && shx mkdir -p dist/export-html/vendor && shx cp src/core/export-html/template.html dist/export-html/ && shx cp src/core/export-html/vendor/*.js dist/export-html/vendor/ && shx cp -r docs dist/ && shx cp -r examples dist/ && shx cp ../../node_modules/@silvia-odwyer/photon-node/photon_rs_bg.wasm dist/ && shx rm -rf dist/skills && shx cp -r skills dist/skills","test": "vitest --run","postinstall": "node postinstall.cjs","prepublishOnly": "npm run clean && npm run build",diff --git a/packages/coding-agent/skills/.gitignore b/packages/coding-agent/skills/.gitignorenew file mode 100644index 0000000000..7a60b85e14--- /dev/null+++ b/packages/coding-agent/skills/.gitignore@@ -0,0 +1,2 @@+__pycache__/+*.pycdiff --git a/packages/coding-agent/skills/websearch/SKILL.md b/packages/coding-agent/skills/websearch/SKILL.mdnew file mode 100644index 0000000000..fa678a261d--- /dev/null+++ b/packages/coding-agent/skills/websearch/SKILL.md@@ -0,0 +1,30 @@+---+name: websearch+description: Search Google via the Serper API. Takes a single query. Returns titles, URLs, snippets, and knowledge-graph data.+---++# Web Search++Search the web via the Serper Google Search API.++## Setup++Get a free API key at https://serper.dev, then run `/login` in Prime Agent and+choose "Serper (web search)" to paste it. The key is stored in Prime Agent and+made available to this skill automatically.++If web search reports a missing key, walk the user through those two steps;+don't ask them to set environment variables.++Optional overrides (environment variables):++- `PRIME_AGENT_WEBSEARCH_TIMEOUT` - HTTP timeout in seconds (default 45).+- `PRIME_AGENT_WEBSEARCH_NUM_RESULTS` - number of organic results to return (default 5).++## Usage++Call the prepared `websearch` import directly in the IPython kernel:++```python+print(await websearch("latest Prime Agent release"))+```diff --git a/packages/coding-agent/skills/websearch/pyproject.toml b/packages/coding-agent/skills/websearch/pyproject.tomlnew file mode 100644index 0000000000..0082d6a3e7--- /dev/null+++ b/packages/coding-agent/skills/websearch/pyproject.toml@@ -0,0 +1,16 @@+[project]+name = "prime-agent-skill-websearch"+version = "0.1.0"+description = "Web search skill for Prime Agent (Google search via Serper API)."+requires-python = ">=3.10"+dependencies = ["httpx", "prime-agent-runtime"]++[project.scripts]+websearch = "rlm.skill:cli"++[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["src/websearch"]diff --git a/packages/coding-agent/skills/websearch/src/websearch/__init__.py b/packages/coding-agent/skills/websearch/src/websearch/__init__.pynew file mode 100644index 0000000000..b30746f33e--- /dev/null+++ b/packages/coding-agent/skills/websearch/src/websearch/__init__.py@@ -0,0 +1,5 @@+"""Web search skill."""++from .websearch import run++__all__ = ["run"]diff --git a/packages/coding-agent/skills/websearch/src/websearch/websearch.py b/packages/coding-agent/skills/websearch/src/websearch/websearch.pynew file mode 100644index 0000000000..8f0a899825--- /dev/null+++ b/packages/coding-agent/skills/websearch/src/websearch/websearch.py@@ -0,0 +1,178 @@+"""Websearch skill implementation."""++from __future__ import annotations++import json+import os+from pathlib import Path++import httpx+++def _env_int(name: str, default: int) -> int:+ """Read an int from the environment, falling back to default on bad values."""+ try:+ return int(os.environ[name])+ except (KeyError, ValueError):+ return default+++def _agent_dir() -> Path:+ """Resolve the Prime Agent config dir the same way the runtime does."""+ raw = (+ os.environ.get("PRIME_AGENT_CODING_AGENT_DIR")+ or os.environ.get("PI_CODING_AGENT_DIR")+ or str(Path.home() / ".prime" / "agent")+ )+ return Path(raw).expanduser()+++def _resolve_api_key() -> str:+ # Read auth.json on each call (not just the injected env var) so a key added+ # via /login after the kernel started is still picked up. Env var wins.+ env_key = os.environ.get("SERPER_API_KEY", "").strip()+ if env_key:+ return env_key++ try:+ auth = json.loads((_agent_dir() / "auth.json").read_text())+ cred = auth.get("serper") if isinstance(auth, dict) else None+ if isinstance(cred, dict) and cred.get("type") == "api_key":+ return _resolve_config_value(str(cred.get("key") or ""))+ except (OSError, ValueError):+ pass+ return ""+++def _resolve_config_value(value: str) -> str:+ # Stored keys may be a literal or an env-var name; "!command" refs can't be run+ # safely here, so skip them (the agent injects those resolved at build time).+ value = value.strip()+ if not value or value.startswith("!"):+ return ""+ return (os.environ.get(value) or value).strip()+++def _format_serper_results(data: dict, query: str, num_results: int = 5) -> str:+ """Format a Serper API response into readable text."""+ sections: list[str] = []++ kg = data.get("knowledgeGraph")+ if kg:+ kg_lines: list[str] = []+ title = (kg.get("title") or "").strip()+ if title:+ kg_lines.append(f"Knowledge Graph: {title}")+ description = (kg.get("description") or "").strip()+ if description:+ kg_lines.append(description)+ for key, value in (kg.get("attributes") or {}).items():+ text = str(value).strip()+ if text:+ kg_lines.append(f"{key}: {text}")+ if kg_lines:+ sections.append("\n".join(kg_lines))++ for i, result in enumerate((data.get("organic") or [])[:num_results]):+ title = (result.get("title") or "").strip() or "Untitled"+ lines = [f"Result {i}: {title}"]+ link = (result.get("link") or "").strip()+ if link:+ lines.append(f"URL: {link}")+ snippet = (result.get("snippet") or "").strip()+ if snippet:+ lines.append(snippet)+ sections.append("\n".join(lines))++ people_also_ask = data.get("peopleAlsoAsk") or []+ if people_also_ask:+ max_q = max(1, min(3, len(people_also_ask)))+ questions: list[str] = []+ for item in people_also_ask[:max_q]:+ question = (item.get("question") or "").strip()+ if not question:+ continue+ entry = f"Q: {question}"+ answer = (item.get("snippet") or "").strip()+ if answer:+ entry += f"\nA: {answer}"+ questions.append(entry)+ if questions:+ sections.append("People Also Ask:\n" + "\n".join(questions))++ if not sections:+ return f"No results returned for query: {query}"++ return "\n\n---\n\n".join(sections)+++async def _fetch_serper(query: str, api_key: str, timeout: int = 45, num_results: int = 5) -> str:+ """Execute a single Serper API search."""+ try:+ async with httpx.AsyncClient(timeout=timeout) as client:+ resp = await client.post(+ "https://google.serper.dev/search",+ json={"q": query},+ headers={+ "X-API-KEY": api_key,+ "Content-Type": "application/json",+ },+ )+ resp.raise_for_status()+ data = resp.json()+ except httpx.HTTPStatusError as e:+ body = e.response.text if e.response is not None else ""+ raise RuntimeError(f"Serper search error ({e.response.status_code}): {body}") from e++ return _format_serper_results(data, query, num_results=num_results)+++async def run(+ query: str,+ *,+ max_output: int = 8192,+ timeout: int | None = None,+ num_results: int | None = None,+) -> str:+ """Run a Google search via Serper and return formatted results.++ Args:+ query: Google search query.+ max_output: Truncate output to this many chars.+ timeout: HTTP timeout in seconds.+ num_results: Organic results to return.++ Returns:+ Formatted search results.+ """+ api_key = _resolve_api_key()+ if not api_key:+ return (+ "Web search is not set up yet: no Serper API key is configured.\n"+ "Tell the user how to enable it:\n"+ " 1. Get a free API key at https://serper.dev (sign up, copy the key).\n"+ " 2. In Prime Agent, run /login and choose \"Serper (web search)\", then paste the key.\n"+ "Do not ask the user to set environment variables. Once the key is saved, web search works automatically."+ )++ if timeout is None:+ timeout = _env_int("PRIME_AGENT_WEBSEARCH_TIMEOUT", 45)+ if num_results is None:+ num_results = _env_int("PRIME_AGENT_WEBSEARCH_NUM_RESULTS", 5)++ try:+ result = await _fetch_serper(query, api_key, timeout=timeout, num_results=num_results)+ except Exception as e:+ result = f"Error searching for '{query}': {e}"+ output = f'Results for query "{query}":\n\n{result}'++ if len(output) > max_output:+ total = len(output)+ marker = f"\n... [output truncated, {total} chars total] ...\n"+ # Reserve room for the marker so the result stays within max_output.+ half = max(0, (max_output - len(marker)) // 2)+ output = output[:half] + marker + output[len(output) - half:]+ if len(output) > max_output: # marker alone exceeds the budget+ output = output[:max_output]++ return outputdiff --git a/packages/coding-agent/src/cli/args.ts b/packages/coding-agent/src/cli/args.tsindex d156c06a23..1aa7268c53 100644--- a/packages/coding-agent/src/cli/args.ts+++ b/packages/coding-agent/src/cli/args.ts@@ -365,6 +365,9 @@ ${chalk.bold("Environment Variables:")}PI_OFFLINE - Disable startup network operations when set to 1/true/yesPRIME_AGENT_DOWNLOAD_BASE_URL - Override the Prime Agent release manifest and tarball base URLPI_SHARE_VIEWER_URL - Base URL for /share command (default: https://pi.dev/session/)+ SERPER_API_KEY - Overrides the stored Serper key for the websearch skill (use /login to store one)+ PRIME_AGENT_WEBSEARCH_TIMEOUT - websearch HTTP timeout in seconds (default: 45)+ PRIME_AGENT_WEBSEARCH_NUM_RESULTS - websearch organic results to return (default: 5)${chalk.bold("Built-in Tool Names:")}ipython - Execute Python in a persistent IPython kerneldiff --git a/packages/coding-agent/src/config.ts b/packages/coding-agent/src/config.tsindex e487ca3095..4913b84b81 100644--- a/packages/coding-agent/src/config.ts+++ b/packages/coding-agent/src/config.ts@@ -448,11 +448,20 @@ export function getBundledInteractiveAssetPath(name: string): string {/*** Get the directory containing built-in skills shipped with the package.- * - For Bun binary: skills/ next to executable (copied by copy-binary-assets)- * - For Node.js (dist/) and tsx (src/): <package root>/skills+ * - For Bun binary: skills/ next to executable+ * - For Node.js (dist/): dist/skills/+ * - For tsx (src/): skills/ at the package root*/export function getBundledSkillsDir(): string {- return join(getPackageDir(), "skills");+ if (isBunBinary) {+ return join(getPackageDir(), "skills");+ }+ const packageDir = getPackageDir();+ // Source checkouts (tsx) keep built-in skills at the package root; built+ // packages copy them to dist/skills. Decide by whether src/ is present so a+ // stale dist/ from a prior build never shadows live source edits.+ const isSourceCheckout = existsSync(join(packageDir, "src"));+ return isSourceCheckout ? join(packageDir, "skills") : join(packageDir, "dist", "skills");}// =============================================================================diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 01affb8ac9..fa422c80c9 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -131,6 +131,7 @@ import {type RefinementResult,saveHarnessState,} from "./refinement/index.js";+import { resolveConfigValue } from "./resolve-config-value.js";import type { ResourceExtensionPaths, ResourceLoader } from "./resource-loader.js";import {type CreateRlmSubagentRuntimeOptions,@@ -159,6 +160,7 @@ import { createAllToolDefinitions } from "./tools/index.js";import { IpythonKernelProvisioner } from "./tools/ipython.js";import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";import { addAssistantUsage, cloneUsage, emptyUsage } from "./usage.js";+import { SERPER_CREDENTIAL_ID, SERPER_ENV_VAR, WEBSEARCH_SKILL_NAME } from "./websearch-credential.js";export type { GoalState, GoalStatus } from "./goals.js";export type { SessionStats } from "./session-stats.js";@@ -282,6 +284,8 @@ export interface AgentSessionConfig {sessionManager: SessionManager;settingsManager: SettingsManager;cwd: string;+ /** Config dir backing credentials (auth.json); exported to the kernel for skills. */+ agentDir?: string;/** Models to cycle through with Ctrl+P (from --models flag) */scopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;/** Resource loader for skills, prompts, themes, context files, system prompt */@@ -702,6 +706,7 @@ export class AgentSession {private _customTools: ToolDefinition[];private _baseToolDefinitions: Map<string, ToolDefinition> = new Map();private _cwd: string;+ private _agentDir?: string;private _extensionRunnerRef?: { current?: ExtensionRunner };private _initialActiveToolNames?: string[];private _allowedToolNames?: Set<string>;@@ -749,6 +754,7 @@ export class AgentSession {this._resourceLoader = config.resourceLoader;this._customTools = config.customTools ?? [];this._cwd = config.cwd;+ this._agentDir = config.agentDir;this._modelRegistry = config.modelRegistry;this._extensionRunnerRef = config.extensionRunnerRef;this._initialActiveToolNames = config.initialActiveToolNames;@@ -3740,9 +3746,33 @@ export class AgentSession {if (rlmSessionDir) {env.RLM_SESSION_DIR = rlmSessionDir;}+ this._addWebsearchKeyEnv(env);return env;}+ private _addWebsearchKeyEnv(env: Record<string, string>): void {+ if (this._agentDir) {+ env.PRIME_AGENT_CODING_AGENT_DIR = this._agentDir;+ }++ if (process.env[SERPER_ENV_VAR]?.trim()) {+ return;+ }+ // Inject only when a websearch skill (bundled or custom) is actually loaded,+ // so the key isn't exposed to kernels that can't use it.+ if (!this._resourceLoader.getSkills().skills.some((skill) => skill.name === WEBSEARCH_SKILL_NAME)) {+ return;+ }+ const cred = this._modelRegistry.authStorage.get(SERPER_CREDENTIAL_ID);+ if (cred?.type !== "api_key") {+ return;+ }+ const resolved = resolveConfigValue(cred.key)?.trim();+ if (resolved) {+ env[SERPER_ENV_VAR] = resolved;+ }+ }+// Undefined when there's no persistent artifact dir (e.g. the viewer client):// don't mkdtemp here, since this runs on every kernel build but a viewer never// does RLM work. The temp dir is created lazily in _createChildRlmSessionDir.@@ -3909,6 +3939,7 @@ export class AgentSession {sessionManager: childSessionManager,settingsManager: this.settingsManager,cwd: this._cwd,+ agentDir: this._agentDir,scopedModels: options.scopedModels,resourceLoader: this._resourceLoader,customTools: options.customTools,diff --git a/packages/coding-agent/src/core/package-manager.ts b/packages/coding-agent/src/core/package-manager.tsindex db4e9d2059..729ad52d99 100644--- a/packages/coding-agent/src/core/package-manager.ts+++ b/packages/coding-agent/src/core/package-manager.ts@@ -2258,7 +2258,10 @@ export class DefaultPackageManager implements PackageManager {path: this.bundledSkillsDir,});}- addResources("skills", builtinEntries, builtinMetadata, userOverrides.skills, this.bundledSkillsDir);+ const builtinSkillOverrides = this.settingsManager.getBundledWebsearchEnabled()+ ? userOverrides.skills+ : [...userOverrides.skills, "-websearch/SKILL.md"];+ addResources("skills", builtinEntries, builtinMetadata, builtinSkillOverrides, this.bundledSkillsDir);}addResources("prompts",diff --git a/packages/coding-agent/src/core/resource-loader.ts b/packages/coding-agent/src/core/resource-loader.tsindex 7ccc896e47..565d7b0c18 100644--- a/packages/coding-agent/src/core/resource-loader.ts+++ b/packages/coding-agent/src/core/resource-loader.ts@@ -2,7 +2,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";import { homedir } from "node:os";import { join, resolve, sep } from "node:path";import chalk from "chalk";-import { CONFIG_DIR_NAME } from "../config.js";+import { CONFIG_DIR_NAME, getBundledSkillsDir } from "../config.js";import { loadThemeFromPath, type Theme } from "../modes/interactive/theme/theme.js";import type { ResourceDiagnostic } from "./diagnostics.js";@@ -158,6 +158,7 @@ export class DefaultResourceLoader implements ResourceLoader {private settingsManager: SettingsManager;private eventBus: EventBus;private packageManager: DefaultPackageManager;+ private bundledSkillsDir: string | null;private additionalExtensionPaths: string[];private additionalSkillPaths: string[];private additionalPromptTemplatePaths: string[];@@ -211,11 +212,12 @@ export class DefaultResourceLoader implements ResourceLoader {this.agentDir = options.agentDir;this.settingsManager = options.settingsManager ?? SettingsManager.create(this.cwd, this.agentDir);this.eventBus = options.eventBus ?? createEventBus();+ this.bundledSkillsDir = options.bundledSkillsDir === undefined ? getBundledSkillsDir() : options.bundledSkillsDir;this.packageManager = new DefaultPackageManager({cwd: this.cwd,agentDir: this.agentDir,settingsManager: this.settingsManager,- bundledSkillsDir: options.bundledSkillsDir,+ bundledSkillsDir: this.bundledSkillsDir,});this.additionalExtensionPaths = options.additionalExtensionPaths ?? [];this.additionalSkillPaths = options.additionalSkillPaths ?? [];@@ -421,7 +423,7 @@ export class DefaultResourceLoader implements ResourceLoader {const skillPaths = this.noSkills? this.mergePaths(cliEnabledSkills, this.additionalSkillPaths)- : this.mergePaths([...cliEnabledSkills, ...enabledSkills], this.additionalSkillPaths);+ : this.mergePaths([...cliEnabledSkills, ...this.additionalSkillPaths], enabledSkills);this.lastSkillPaths = skillPaths;this.updateSkillsFromPaths(skillPaths, metadataByPath);diff --git a/packages/coding-agent/src/core/sdk.ts b/packages/coding-agent/src/core/sdk.tsindex 2695f8e06a..0e556cd96b 100644--- a/packages/coding-agent/src/core/sdk.ts+++ b/packages/coding-agent/src/core/sdk.ts@@ -342,6 +342,8 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}sessionManager,settingsManager,cwd,+ // Only the explicit dir — the default may not match injected custom storage.+ agentDir: options.agentDir,scopedModels: options.scopedModels,resourceLoader,customTools: options.customTools,diff --git a/packages/coding-agent/src/core/settings-manager.ts b/packages/coding-agent/src/core/settings-manager.tsindex 567b417ff9..fdfed50a38 100644--- a/packages/coding-agent/src/core/settings-manager.ts+++ b/packages/coding-agent/src/core/settings-manager.ts@@ -54,6 +54,10 @@ export interface MarkdownSettings {codeBlockIndent?: string; // default: " "}+export interface BundledSkillsSettings {+ websearch?: boolean; // default: true+}+export interface WarningSettings {anthropicExtraUsage?: boolean; // default: true}@@ -100,6 +104,7 @@ export interface Settings {prompts?: string[]; // Array of local prompt template paths or directoriesthemes?: string[]; // Array of local theme file paths or directoriesenableSkillCommands?: boolean; // default: true - register skills as /skill:name commands+ bundledSkills?: BundledSkillsSettings; // Configure built-in skills shipped with Prime AgentenableBuiltinSkills?: boolean; // default: true - load built-in skills shipped with prime-agentterminal?: TerminalSettings;images?: ImageSettings;@@ -910,6 +915,16 @@ export class SettingsManager {this.save();}+ getBundledSkills(): { websearch: boolean } {+ return {+ websearch: this.settings.bundledSkills?.websearch ?? true,+ };+ }++ getBundledWebsearchEnabled(): boolean {+ return this.getBundledSkills().websearch;+ }+getEnableBuiltinSkills(): boolean {return this.settings.enableBuiltinSkills ?? true;}diff --git a/packages/coding-agent/src/core/websearch-credential.ts b/packages/coding-agent/src/core/websearch-credential.tsnew file mode 100644index 0000000000..11ebe2fd46--- /dev/null+++ b/packages/coding-agent/src/core/websearch-credential.ts@@ -0,0 +1,6 @@+// Shared identifiers for the bundled websearch skill's Serper credential, used by+// the /login UI (auth.json key) and the kernel env injection.+export const WEBSEARCH_SKILL_NAME = "websearch";+export const SERPER_CREDENTIAL_ID = "serper";+export const SERPER_CREDENTIAL_NAME = "Serper (web search)";+export const SERPER_ENV_VAR = "SERPER_API_KEY";diff --git a/packages/coding-agent/src/modes/interactive/auth-flows.ts b/packages/coding-agent/src/modes/interactive/auth-flows.tsindex 2dc7ed481e..6249288df3 100644--- a/packages/coding-agent/src/modes/interactive/auth-flows.ts+++ b/packages/coding-agent/src/modes/interactive/auth-flows.ts@@ -27,6 +27,7 @@ import {resolvePrimeAgentTracesBaseUrl,} from "../../core/prime-inference-auth.js";import { BUILT_IN_PROVIDER_DISPLAY_NAMES } from "../../core/provider-display-names.js";+import { SERPER_CREDENTIAL_ID, SERPER_CREDENTIAL_NAME } from "../../core/websearch-credential.js";import { showFullPaneOverlay } from "./components/centered-overlay.js";import { ExtensionSelectorComponent } from "./components/extension-selector.js";import { LoginDialogComponent } from "./components/login-dialog.js";@@ -44,6 +45,8 @@ export type AuthenticationResult =providerId: string;providerName: string;authType: "oauth" | "api_key";+ /** "service" credentials (e.g. web search) don't affect model selection. */+ kind?: "provider" | "service";}| { status: "cancelled" }| { status: "failed" };@@ -148,7 +151,8 @@ export class ProviderAuthFlows {} else if (providerOption.id === BEDROCK_PROVIDER_ID) {resolve(await this.showBedrockSetupDialog(providerOption.id, providerOption.name));} else {- resolve(await this.showApiKeyLoginDialog(providerOption.id, providerOption.name));+ const kind = providerOption.id === SERPER_CREDENTIAL_ID ? "service" : "provider";+ resolve(await this.showApiKeyLoginDialog(providerOption.id, providerOption.name, kind));}},() => {@@ -232,6 +236,14 @@ export class ProviderAuthFlows {});}+ // Serper is a skill credential, not a model provider, so add it manually.+ options.push({+ id: SERPER_CREDENTIAL_ID,+ name: SERPER_CREDENTIAL_NAME,+ authType: "api_key",+ category: "service",+ });+const filteredOptions = authType ? options.filter((option) => option.authType === authType) : options;return filteredOptions.sort(compareAuthSelectorProviders);}@@ -245,10 +257,12 @@ export class ProviderAuthFlows {if (!credential) {continue;}+ const isSerper = providerId === SERPER_CREDENTIAL_ID;options.push({id: providerId,- name: this.host.modelRegistry.getProviderDisplayName(providerId),+ name: isSerper ? SERPER_CREDENTIAL_NAME : this.host.modelRegistry.getProviderDisplayName(providerId),authType: credential.type,+ category: isSerper ? "service" : "provider",});}@@ -260,6 +274,7 @@ export class ProviderAuthFlows {providerName: string,authType: "oauth" | "api_key",statusSuffix?: string,+ kind: "provider" | "service" = "provider",): Promise<AuthenticationResult> {this.host.modelRegistry.refresh();@@ -274,6 +289,7 @@ export class ProviderAuthFlows {providerId,providerName,authType,+ kind,};}@@ -677,7 +693,11 @@ export class ProviderAuthFlows {}}- private async showApiKeyLoginDialog(providerId: string, providerName: string): Promise<AuthenticationResult> {+ private async showApiKeyLoginDialog(+ providerId: string,+ providerName: string,+ kind: "provider" | "service" = "provider",+ ): Promise<AuthenticationResult> {const dialog = new LoginDialogComponent(this.host.ui,providerId,@@ -703,7 +723,7 @@ export class ProviderAuthFlows {this.host.modelRegistry.authStorage.set(providerId, { type: "api_key", key: apiKey });closeDialog();- return await this.completeProviderAuthentication(providerId, providerName, "api_key");+ return await this.completeProviderAuthentication(providerId, providerName, "api_key", undefined, kind);} catch (error: unknown) {closeDialog();const errorMsg = error instanceof Error ? error.message : String(error);diff --git a/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts b/packages/coding-agent/src/modes/interactive/components/oauth-selector.tsindex 296612d1a2..858adde607 100644--- a/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts+++ b/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts@@ -10,10 +10,14 @@ import {type MenuViewportProvider,} from "./menu-panel.js";+export type AuthSelectorCategory = "provider" | "service";+export type AuthSelectorProvider = {id: string;name: string;authType: "oauth" | "api_key";+ /** Which tab the entry belongs to. Defaults to "provider" when omitted. */+ category?: AuthSelectorCategory;};export function compareAuthSelectorProviders(a: AuthSelectorProvider, b: AuthSelectorProvider): number {@@ -25,6 +29,8 @@ export function compareAuthSelectorProviders(a: AuthSelectorProvider, b: AuthSelconst PREFERRED_VISIBLE_PROVIDERS = 8;const PROVIDER_LIST_RESERVED_ROWS = 7;+/** Extra fixed rows the Providers/Services tab bar (text + spacer) consumes. */+const TAB_BAR_RESERVED_ROWS = 2;const PROVIDER_SCROLL_INDICATOR_ROWS = 1;/**@@ -44,10 +50,14 @@ export class OAuthSelectorComponent extends Container implements Focusable {}private listContainer: Container;+ private tabBar?: TruncatedText;private allProviders: AuthSelectorProvider[];private filteredProviders: AuthSelectorProvider[];private selectedIndex: number = 0;private mode: "login" | "logout";+ /** Tabs present in the data, in display order. Empty/single → no tab bar. */+ private categories: AuthSelectorCategory[] = [];+ private activeCategory: AuthSelectorCategory = "provider";private authStorage: AuthStorage;private getAuthStatus: (providerId: string) => AuthStatus;private onSelectCallback: (provider: AuthSelectorProvider) => void;@@ -80,12 +90,22 @@ export class OAuthSelectorComponent extends Container implements Focusable {this.onSelectCallback = onSelect;this.onCancelCallback = onCancel;+ const present = new Set(providers.map((p) => p.category ?? "provider"));+ this.categories = (["provider", "service"] as const).filter((c) => present.has(c));+ this.activeCategory = this.categories[0] ?? "provider";+const panel = new MenuPanel({title: mode === "login" ? "Providers" : "Saved Credentials",subtitle: mode === "login" ? "Connect with a subscription or API key." : "Choose a credential to remove.",});this.addChild(panel);+ if (this.categories.length > 1) {+ this.tabBar = new TruncatedText("");+ panel.addChild(this.tabBar);+ panel.addChild(new Spacer(1));+ }+this.searchInput = new MenuSearchInput("Search providers");this.searchInput.onSubmit = () => {const selectedProvider = this.filteredProviders[this.selectedIndex];@@ -104,11 +124,40 @@ export class OAuthSelectorComponent extends Container implements Focusable {this.filterProviders("");}+ private inActiveCategory(provider: AuthSelectorProvider): boolean {+ return (provider.category ?? "provider") === this.activeCategory;+ }++ private switchCategory(direction: 1 | -1): void {+ if (this.categories.length < 2) return;+ const current = this.categories.indexOf(this.activeCategory);+ const next = (current + direction + this.categories.length) % this.categories.length;+ this.activeCategory = this.categories[next];+ this.selectedIndex = 0;+ this.searchInput.setValue("");+ this.filterProviders("");+ }++ private updateTabBar(): void {+ if (!this.tabBar) return;+ const labels: Record<AuthSelectorCategory, string> = { provider: "Providers", service: "Services" };+ const rendered = this.categories+ .map((category) =>+ category === this.activeCategory+ ? theme.bold(theme.fg("accent", labels[category]))+ : theme.fg("muted", labels[category]),+ )+ .join(theme.fg("muted", " · "));+ this.tabBar.setText(`${rendered} ${theme.fg("muted", "←/→ switch")}`);+ }+private filterProviders(query: string): void {+ const inCategory = this.allProviders.filter((p) => this.inActiveCategory(p));this.filteredProviders = query- ? fuzzyFilter(this.allProviders, query, (provider) => `${provider.name} ${provider.id} ${provider.authType}`)- : this.allProviders;+ ? fuzzyFilter(inCategory, query, (provider) => `${provider.name} ${provider.id} ${provider.authType}`)+ : inCategory;this.selectedIndex = Math.max(0, Math.min(this.selectedIndex, Math.max(0, this.filteredProviders.length - 1)));+ this.updateTabBar();this.updateList();}@@ -231,6 +280,21 @@ export class OAuthSelectorComponent extends Container implements Focusable {this.selectedIndex = Math.min(this.filteredProviders.length - 1, this.selectedIndex + 1);this.updateList();}+ // Only steal left/right for tabs when the search field is empty, so cursor+ // editing still works while filtering.+ else if (+ this.categories.length > 1 &&+ this.searchInput.getValue() === "" &&+ kb.matches(keyData, "tui.editor.cursorLeft")+ ) {+ this.switchCategory(-1);+ } else if (+ this.categories.length > 1 &&+ this.searchInput.getValue() === "" &&+ kb.matches(keyData, "tui.editor.cursorRight")+ ) {+ this.switchCategory(1);+ }// Enterelse if (kb.matches(keyData, "tui.select.confirm")) {const selectedProvider = this.filteredProviders[this.selectedIndex];@@ -249,12 +313,16 @@ export class OAuthSelectorComponent extends Container implements Focusable {}}+ private get reservedRows(): number {+ return this.tabBar ? PROVIDER_LIST_RESERVED_ROWS + TAB_BAR_RESERVED_ROWS : PROVIDER_LIST_RESERVED_ROWS;+ }+private updateLayout(): void {this.listLayout = getMenuListLayout({getRows: this.viewport.getRows,preferredVisibleItems: PREFERRED_VISIBLE_PROVIDERS,totalItems: this.filteredProviders.length,- reservedRows: PROVIDER_LIST_RESERVED_ROWS,+ reservedRows: this.reservedRows,comfortableItemRows: 3,compactItemRows: 2,scrollIndicatorRows: PROVIDER_SCROLL_INDICATOR_ROWS,diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 084c595520..cb9f9d8071 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -1653,13 +1653,19 @@ export class InteractiveMode {}}+ const formatMessageLines = (diagnostic: AgentConnectionResourceDiagnostic, indent: number): string[] => {+ const color = diagnostic.type === "error" ? "error" : "warning";+ const prefix = " ".repeat(indent);+ return diagnostic.message.split("\n").map((line) => theme.fg(color, `${prefix}${line}`));+ };+for (const d of otherDiagnostics) {if (d.path) {const formattedPath = this.formatPathWithSource(d.path, this.findSourceInfoForPath(d.path, sourceInfos));lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${formattedPath}`));- lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${d.message}`));+ lines.push(...formatMessageLines(d, 4));} else {- lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${d.message}`));+ lines.push(...formatMessageLines(d, 2));}}@@ -1678,6 +1684,25 @@ export class InteractiveMode {}const sectionHeader = (name: string, color: ThemeColor = "mdHeading") => theme.fg(color, `[${name}]`);+ const diagnosticsHeader = (name: string, diagnostics: readonly AgentConnectionResourceDiagnostic[]): string => {+ if (diagnostics.some((diagnostic) => diagnostic.type === "collision")) {+ return `${name} conflicts`;+ }++ const errorCount = diagnostics.filter((diagnostic) => diagnostic.type === "error").length;+ const warningCount = diagnostics.filter((diagnostic) => diagnostic.type === "warning").length;+ if (errorCount > 0 && warningCount > 0) {+ return `${name} diagnostics`;+ }+ if (errorCount > 0) {+ return `${name} error${errorCount === 1 ? "" : "s"}`;+ }+ if (warningCount > 0) {+ return `${name} warning${warningCount === 1 ? "" : "s"}`;+ }++ return `${name} diagnostics`;+ };const formatCompactList = (items: string[], options?: { sort?: boolean }): string => {const labels = items.map((item) => item.trim()).filter((item) => item.length > 0);if (options?.sort !== false) {@@ -1812,7 +1837,13 @@ export class InteractiveMode {const skillDiagnostics = resourceSnapshot?.diagnostics.skills ?? [];if (skillDiagnostics.length > 0) {const warningLines = this.formatDiagnostics(skillDiagnostics, sourceInfos);- this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Skill conflicts]")}\n${warningLines}`, 0, 0));+ this.chatContainer.addChild(+ new Text(+ `${sectionHeader(diagnosticsHeader("Skill", skillDiagnostics), "warning")}\n${warningLines}`,+ 0,+ 0,+ ),+ );this.chatContainer.addChild(new Spacer(1));}@@ -1820,7 +1851,11 @@ export class InteractiveMode {if (promptDiagnostics.length > 0) {const warningLines = this.formatDiagnostics(promptDiagnostics, sourceInfos);this.chatContainer.addChild(- new Text(`${theme.fg("warning", "[Prompt conflicts]")}\n${warningLines}`, 0, 0),+ new Text(+ `${sectionHeader(diagnosticsHeader("Prompt", promptDiagnostics), "warning")}\n${warningLines}`,+ 0,+ 0,+ ),);this.chatContainer.addChild(new Spacer(1));}@@ -1843,7 +1878,11 @@ export class InteractiveMode {if (extensionDiagnostics.length > 0) {const warningLines = this.formatDiagnostics(extensionDiagnostics, sourceInfos);this.chatContainer.addChild(- new Text(`${theme.fg("warning", "[Extension issues]")}\n${warningLines}`, 0, 0),+ new Text(+ `${sectionHeader(diagnosticsHeader("Extension", extensionDiagnostics), "warning")}\n${warningLines}`,+ 0,+ 0,+ ),);this.chatContainer.addChild(new Spacer(1));}@@ -1851,7 +1890,13 @@ export class InteractiveMode {const themeDiagnostics = resourceSnapshot?.diagnostics.themes ?? [];if (themeDiagnostics.length > 0) {const warningLines = this.formatDiagnostics(themeDiagnostics, sourceInfos);- this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Theme conflicts]")}\n${warningLines}`, 0, 0));+ this.chatContainer.addChild(+ new Text(+ `${sectionHeader(diagnosticsHeader("Theme", themeDiagnostics), "warning")}\n${warningLines}`,+ 0,+ 0,+ ),+ );this.chatContainer.addChild(new Spacer(1));}}@@ -6436,7 +6481,8 @@ export class InteractiveMode {private async showOAuthSelector(mode: "login" | "logout"): Promise<void> {if (mode === "login") {const authResult = await this.showLoginProviderSelector();- if (authResult.status === "success") {+ // Service credentials don't change the model, so skip the model picker.+ if (authResult.status === "success" && authResult.kind !== "service") {await this.promptForModelSelection();}return;diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex ed02b4ce04..aa31f52e7c 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -20,6 +20,8 @@ import { ModelRegistry } from "../src/core/model-registry.js";import { createRlmRunHostHandler } from "../src/core/rlm-runtime.js";import { SessionManager } from "../src/core/session-manager.js";import { SettingsManager } from "../src/core/settings-manager.js";+import type { Skill } from "../src/core/skills.js";+import { createSyntheticSourceInfo } from "../src/core/source-info.js";import { MISSING_RIPGREP_MESSAGE } from "../src/utils/tools-manager.js";import { createTestResourceLoader } from "./utilities.js";@@ -857,22 +859,44 @@ describe("AgentSession RLM session dir", () => {rmSync(tempDir, { recursive: true, force: true });});- function createSession(sessionManager: SessionManager): AgentSession {+ function createSession(+ sessionManager: SessionManager,+ agentDir?: string,+ serperKey?: string,+ loadWebsearchSkill = false,+ ): AgentSession {const authStorage = AuthStorage.create(join(tempDir, "auth.json"));authStorage.setRuntimeApiKey("anthropic", "test-key");+ if (serperKey !== undefined) {+ authStorage.set("serper", { type: "api_key", key: serperKey });+ }const agent = new Agent({convertToLlm,getApiKey: () => "test-key",initialState: { model, systemPrompt: "", tools: [], thinkingLevel: "off" },streamFn: () => streamAnswer("ignored"),});+ const skills: Skill[] = loadWebsearchSkill+ ? [+ {+ kind: "markdown",+ name: "websearch",+ description: "",+ filePath: "/x/websearch/SKILL.md",+ baseDir: "/x/websearch",+ sourceInfo: createSyntheticSourceInfo("/x/websearch/SKILL.md", { source: "package" }),+ disableModelInvocation: false,+ },+ ]+ : [];session = new AgentSession({agent,sessionManager,settingsManager: SettingsManager.create(tempDir, tempDir),cwd: tempDir,+ agentDir,modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models.json")),- resourceLoader: createTestResourceLoader(),+ resourceLoader: createTestResourceLoader({ skills }),});return session;}@@ -902,4 +926,70 @@ describe("AgentSession RLM session dir", () => {expect(inspectable._ensureRlmSessionDir()).toBe(artifactDir);expect(inspectable._rlmKernelEnv().RLM_SESSION_DIR).toBe(artifactDir);});++ it("exports the configured agentDir to the kernel so skills find auth.json", () => {+ const agentDir = join(tempDir, "custom-agent-dir");+ const root = createSession(SessionManager.inMemory(tempDir), agentDir);+ const env = (root as unknown as InspectableRlmDirSession)._rlmKernelEnv();+ expect(env.PRIME_AGENT_CODING_AGENT_DIR).toBe(agentDir);+ });++ it("omits the agentDir env var when none is configured", () => {+ const root = createSession(SessionManager.inMemory(tempDir));+ const env = (root as unknown as InspectableRlmDirSession)._rlmKernelEnv();+ expect(env.PRIME_AGENT_CODING_AGENT_DIR).toBeUndefined();+ });++ it("exports agentDir but skips key injection when no websearch skill is loaded", () => {+ const agentDir = join(tempDir, "custom-agent-dir");+ const root = createSession(SessionManager.inMemory(tempDir), agentDir, "stored-key", false);+ const env = (root as unknown as InspectableRlmDirSession)._rlmKernelEnv();+ expect(env.PRIME_AGENT_CODING_AGENT_DIR).toBe(agentDir);+ expect(env.SERPER_API_KEY).toBeUndefined();+ });++ it("injects the key for a custom websearch skill even when bundled is off", () => {+ const previous = process.env.SERPER_API_KEY;+ delete process.env.SERPER_API_KEY;+ try {+ // loadWebsearchSkill=true models a --skill/project websearch; the bundled+ // setting is irrelevant because the gate checks the loaded skill, not settings.+ const root = createSession(SessionManager.inMemory(tempDir), undefined, "custom-key", true);+ const env = (root as unknown as InspectableRlmDirSession)._rlmKernelEnv();+ expect(env.SERPER_API_KEY).toBe("custom-key");+ } finally {+ if (previous === undefined) delete process.env.SERPER_API_KEY;+ else process.env.SERPER_API_KEY = previous;+ }+ });++ it("injects a literal stored Serper key into the kernel", () => {+ const previous = process.env.SERPER_API_KEY;+ delete process.env.SERPER_API_KEY;+ try {+ const root = createSession(SessionManager.inMemory(tempDir), undefined, "literal-serper-key", true);+ const env = (root as unknown as InspectableRlmDirSession)._rlmKernelEnv();+ expect(env.SERPER_API_KEY).toBe("literal-serper-key");+ } finally {+ if (previous === undefined) delete process.env.SERPER_API_KEY;+ else process.env.SERPER_API_KEY = previous;+ }+ });++ it("resolves an env-var-reference Serper key before injecting it", () => {+ const previousKey = process.env.SERPER_API_KEY;+ const previousRef = process.env.MY_SERPER_REF;+ delete process.env.SERPER_API_KEY;+ process.env.MY_SERPER_REF = "resolved-secret";+ try {+ const root = createSession(SessionManager.inMemory(tempDir), undefined, "MY_SERPER_REF", true);+ const env = (root as unknown as InspectableRlmDirSession)._rlmKernelEnv();+ expect(env.SERPER_API_KEY).toBe("resolved-secret");+ } finally {+ if (previousKey === undefined) delete process.env.SERPER_API_KEY;+ else process.env.SERPER_API_KEY = previousKey;+ if (previousRef === undefined) delete process.env.MY_SERPER_REF;+ else process.env.MY_SERPER_REF = previousRef;+ }+ });});diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.tsindex 9df35ee047..8e53a2824a 100644--- a/packages/coding-agent/test/interactive-mode-status.test.ts+++ b/packages/coding-agent/test/interactive-mode-status.test.ts@@ -16,6 +16,7 @@ import type {AgentConnectionExtensionUiRequest,AgentConnectionExtensionUiResponse,AgentConnectionModel,+ AgentConnectionResourceDiagnostic,AgentConnectionResourceSnapshot,AgentConnectionSessionEvent,AgentConnectionSourceInfo,@@ -1422,8 +1423,9 @@ describe("InteractiveMode.showLoadedResources", () => {contextFiles?: Array<{ path: string; content?: string }>;extensions?: ExtensionFixture[];skills?: Array<{ filePath: string; name: string }>;- skillDiagnostics?: AgentConnectionResourceSnapshot["diagnostics"]["skills"];+ skillDiagnostics?: AgentConnectionResourceDiagnostic[];useRealScopeGroups?: boolean;+ useRealDiagnostics?: boolean;}) {const connectionResourceSnapshot: AgentConnectionResourceSnapshot = {contextFiles: (options.contextFiles ?? []).map((contextFile) => ({ path: contextFile.path })),@@ -1485,6 +1487,13 @@ describe("InteractiveMode.showLoadedResources", () => {getBuiltInCommandConflictDiagnostics: () => [],};+ if (options.useRealDiagnostics) {+ fakeThis.formatDiagnostics = (+ diagnostics: readonly AgentConnectionResourceDiagnostic[],+ sourceInfos: Map<string, AgentConnectionSourceInfo>,+ ) => (InteractiveMode as any).prototype.formatDiagnostics.call(fakeThis, diagnostics, sourceInfos);+ }+if (options.useRealScopeGroups) {fakeThis.getScopeGroup = (sourceInfo?: AgentConnectionSourceInfo) =>(InteractiveMode as any).prototype.getScopeGroup.call(fakeThis, sourceInfo);@@ -2060,7 +2069,35 @@ describe("InteractiveMode.showLoadedResources", () => {});const output = renderAll(fakeThis.chatContainer);- expect(output).toContain("[Skill conflicts]");+ expect(output).toContain("[Skill warning]");expect(output).not.toContain("[Skills]");});++ test("formats a multi-line skill warning without path noise", () => {+ const fakeThis = createShowLoadedResourcesThis({+ quietStartup: true,+ skillDiagnostics: [+ {+ type: "warning",+ message: "first line of the warning.\nsecond line with guidance.\n\n indented detail",+ },+ ],+ useRealDiagnostics: true,+ });++ (InteractiveMode as any).prototype.showLoadedResources.call(fakeThis, {+ force: false,+ showDiagnosticsWhenQuiet: true,+ });++ const output = normalizeRenderedOutput(fakeThis.chatContainer, 100);+ expect(output).toMatchInlineSnapshot(`+"[Skill warning]+ first line of the warning.+ second line with guidance.++ indented detail"+`);+ expect(output).not.toContain("[Skill conflicts]");+ });});diff --git a/packages/coding-agent/test/oauth-selector.test.ts b/packages/coding-agent/test/oauth-selector.test.tsindex 3a083f06b0..c677ec5f68 100644--- a/packages/coding-agent/test/oauth-selector.test.ts+++ b/packages/coding-agent/test/oauth-selector.test.ts@@ -224,4 +224,63 @@ describe("OAuthSelectorComponent", () => {expect(output).toContain("Provider 3");expect(output).toContain("(6/12)");});++ it("shows Providers/Services tabs and switches with left/right arrows", () => {+ const selector = new OAuthSelectorComponent(+ "login",+ AuthStorage.inMemory(),+ [+ { id: "anthropic", name: "Anthropic", authType: "oauth", category: "provider" },+ { id: "serper", name: "Serper (web search)", authType: "api_key", category: "service" },+ ],+ () => {},+ () => {},+ );++ // Providers tab active first: provider shown, service hidden.+ let output = stripAnsi(selector.render(120).join("\n"));+ expect(output).toContain("Providers");+ expect(output).toContain("Services");+ expect(output).toContain("Anthropic");+ expect(output).not.toContain("Serper");++ // Right arrow switches to the Services tab.+ selector.handleInput("\x1b[C");+ output = stripAnsi(selector.render(120).join("\n"));+ expect(output).toContain("Serper (web search)");+ expect(output).not.toContain("Anthropic");+ });++ it("selecting on the Services tab returns the service entry", () => {+ let chosen: string | undefined;+ const selector = new OAuthSelectorComponent(+ "login",+ AuthStorage.inMemory(),+ [+ { id: "anthropic", name: "Anthropic", authType: "oauth", category: "provider" },+ { id: "serper", name: "Serper (web search)", authType: "api_key", category: "service" },+ ],+ (provider) => {+ chosen = provider.id;+ },+ () => {},+ );++ selector.handleInput("\x1b[C"); // -> Services tab+ selector.handleInput("\r"); // confirm+ expect(chosen).toBe("serper");+ });++ it("shows no tab bar when only one category is present", () => {+ const selector = new OAuthSelectorComponent(+ "login",+ AuthStorage.inMemory(),+ [{ id: "anthropic", name: "Anthropic", authType: "oauth", category: "provider" }],+ () => {},+ () => {},+ );++ const output = stripAnsi(selector.render(120).join("\n"));+ expect(output).not.toContain("←/→ switch");+ });});diff --git a/packages/coding-agent/test/resource-loader.test.ts b/packages/coding-agent/test/resource-loader.test.tsindex 84e6539300..4daf8436b0 100644--- a/packages/coding-agent/test/resource-loader.test.ts+++ b/packages/coding-agent/test/resource-loader.test.ts@@ -15,16 +15,24 @@ describe("DefaultResourceLoader", () => {let tempDir: string;let agentDir: string;let cwd: string;+ let previousSerperApiKey: string | undefined;beforeEach(() => {tempDir = join(tmpdir(), `rl-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);agentDir = join(tempDir, "agent");cwd = join(tempDir, "project");+ previousSerperApiKey = process.env.SERPER_API_KEY;+ delete process.env.SERPER_API_KEY;mkdirSync(agentDir, { recursive: true });mkdirSync(cwd, { recursive: true });});afterEach(() => {+ if (previousSerperApiKey === undefined) {+ delete process.env.SERPER_API_KEY;+ } else {+ process.env.SERPER_API_KEY = previousSerperApiKey;+ }rmSync(tempDir, { recursive: true, force: true });});@@ -452,6 +460,102 @@ Content`,});});+ describe("bundled skills", () => {+ it("should load the bundled websearch skill by default", async () => {+ const loader = new DefaultResourceLoader({ cwd, agentDir });+ await loader.reload();++ const { skills } = loader.getSkills();+ const websearch = skills.find((s) => s.name === "websearch");+ expect(websearch).toBeDefined();+ expect(websearch?.kind).toBe("python");+ if (websearch?.kind === "python") {+ expect(websearch.python.importName).toBe("websearch");+ expect(websearch.python.pyprojectPath.endsWith("pyproject.toml")).toBe(true);+ }+ });++ it("should not emit a SERPER_API_KEY warning when the key is unset", async () => {+ const loader = new DefaultResourceLoader({ cwd, agentDir });+ await loader.reload();++ const { diagnostics } = loader.getSkills();+ expect(diagnostics.some((d) => d.type === "warning" && d.message.includes("SERPER_API_KEY"))).toBe(false);+ });++ it("should not load the bundled websearch skill when disabled in settings", async () => {+ const settingsManager = SettingsManager.inMemory({ bundledSkills: { websearch: false } });+ const loader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });+ await loader.reload();++ const { skills, diagnostics } = loader.getSkills();+ expect(skills.some((s) => s.name === "websearch")).toBe(false);+ expect(diagnostics.some((d) => d.type === "warning" && d.message.includes("SERPER_API_KEY is not set"))).toBe(+ false,+ );+ });++ it("should not load bundled skills when noSkills is true", async () => {+ const loader = new DefaultResourceLoader({ cwd, agentDir, noSkills: true });+ await loader.reload();++ const { skills } = loader.getSkills();+ expect(skills.some((s) => s.name === "websearch")).toBe(false);+ });++ it("should let a project skill override the bundled websearch skill", async () => {+ const projectSkillDir = join(cwd, ".prime", "agent", "skills", "websearch");+ mkdirSync(projectSkillDir, { recursive: true });+ writeFileSync(+ join(projectSkillDir, "SKILL.md"),+ `---+name: websearch+description: Project-specific web search override.+---+Project override.`,+ );++ const loader = new DefaultResourceLoader({ cwd, agentDir });+ await loader.reload();++ const { skills, diagnostics } = loader.getSkills();+ const websearch = skills.find((s) => s.name === "websearch");+ expect(websearch).toBeDefined();+ expect(websearch?.filePath).toBe(join(projectSkillDir, "SKILL.md"));+ expect(websearch?.kind).toBe("markdown");+ expect(diagnostics.some((d) => d.type === "collision" && d.collision?.name === "websearch")).toBe(true);+ expect(diagnostics.some((d) => d.type === "warning" && d.message.includes("SERPER_API_KEY is not set"))).toBe(+ false,+ );+ });++ it("should let an explicit --skill path override the bundled websearch skill", async () => {+ const customSkillDir = join(tempDir, "custom-websearch", "websearch");+ mkdirSync(customSkillDir, { recursive: true });+ writeFileSync(+ join(customSkillDir, "SKILL.md"),+ `---+name: websearch+description: Explicit web search override.+---+Explicit override.`,+ );++ const loader = new DefaultResourceLoader({+ cwd,+ agentDir,+ additionalSkillPaths: [customSkillDir],+ });+ await loader.reload();++ const { skills } = loader.getSkills();+ const websearch = skills.find((s) => s.name === "websearch");+ expect(websearch).toBeDefined();+ expect(websearch?.filePath).toBe(join(customSkillDir, "SKILL.md"));+ expect(websearch?.kind).toBe("markdown");+ });+ });+describe("override functions", () => {it("should apply skillsOverride", async () => {const injectedSkill: Skill = {diff --git a/packages/coding-agent/test/utilities.ts b/packages/coding-agent/test/utilities.tsindex ed55dbe776..f4a0bfc532 100644--- a/packages/coding-agent/test/utilities.ts+++ b/packages/coding-agent/test/utilities.ts@@ -17,6 +17,7 @@ import { ModelRegistry } from "../src/core/model-registry.js";import type { ResourceLoader } from "../src/core/resource-loader.js";import { SessionManager } from "../src/core/session-manager.js";import { SettingsManager } from "../src/core/settings-manager.js";+import type { Skill } from "../src/core/skills.js";import { createIpythonTool } from "../src/index.js";/**@@ -205,6 +206,7 @@ export async function createTestExtensionsResult(export interface CreateTestResourceLoaderOptions {extensionsResult?: LoadExtensionsResult;+ skills?: Skill[];}export function createTestResourceLoader(options: CreateTestResourceLoaderOptions = {}): ResourceLoader {@@ -216,7 +218,7 @@ export function createTestResourceLoader(options: CreateTestResourceLoaderOptionreturn {getExtensions: () => extensionsResult,- getSkills: () => ({ skills: [], diagnostics: [] }),+ getSkills: () => ({ skills: options.skills ?? [], diagnostics: [] }),getPrompts: () => ({ prompts: [], diagnostics: [] }),getThemes: () => ({ themes: [], diagnostics: [] }),getAgentsFiles: () => ({ agentsFiles: [] }),diff --git a/packages/tui/src/components/truncated-text.ts b/packages/tui/src/components/truncated-text.tsindex 12eac558d1..d0efc64b9e 100644--- a/packages/tui/src/components/truncated-text.ts+++ b/packages/tui/src/components/truncated-text.ts@@ -15,6 +15,10 @@ export class TruncatedText implements Component {this.paddingY = paddingY;}+ setText(text: string): void {+ this.text = text;+ }+invalidate(): void {// No cached state to invalidate currently}