mirror of
https://github.com/tiennm99/ccs.git
synced 2026-10-14 08:18:04 +00:00
feat: add first-class CCS WebSearch runtime
This commit is contained in:
1 parent
c45b2a1138
commit
e260df7178
26 files changed
+1241
-158
No files matched your search
@@ -10,7 +10,7 @@ import type { Config, Settings } from '../../types';
|
||||
import type { TargetType } from '../../targets/target-adapter';
|
||||
import { getPersistedTargetChoices, isPersistedTargetType } from '../../targets/target-metadata';
|
||||
import { getCcsDir, getConfigPath, loadConfigSafe } from '../../utils/config-manager';
|
||||
import { ensureProfileHooksOrThrow } from '../../utils/websearch/profile-hook-injector';
|
||||
import { ensureWebSearchMcpOrThrow } from '../../utils/websearch-manager';
|
||||
import { isSensitiveKey } from '../../utils/sensitive-keys';
|
||||
import { isReservedName } from '../../config/reserved-names';
|
||||
import { isUnifiedMode, mutateUnifiedConfig } from '../../config/unified-config-loader';
|
||||
@@ -218,7 +218,7 @@ export function registerApiProfileOrphans(options?: {
|
||||
|
||||
try {
|
||||
if (orphan.validation.valid) {
|
||||
ensureProfileHooksOrThrow(orphan.name);
|
||||
ensureWebSearchMcpOrThrow();
|
||||
}
|
||||
registerApiProfileInConfig(orphan.name, options?.target || 'claude', options?.force || false);
|
||||
result.registered.push(orphan.name);
|
||||
@@ -268,7 +268,7 @@ export function copyApiProfile(
|
||||
|
||||
writeJsonObjectAtomically(destinationSettingsPath, sourceSettings);
|
||||
try {
|
||||
ensureProfileHooksOrThrow(destination);
|
||||
ensureWebSearchMcpOrThrow();
|
||||
} catch (hookError) {
|
||||
rollbackSettingsFile(destinationSettingsPath, previousDestinationContent, destinationExisted);
|
||||
throw hookError;
|
||||
@@ -393,7 +393,7 @@ export function importApiProfileBundle(
|
||||
|
||||
writeJsonObjectAtomically(settingsPath, settings);
|
||||
try {
|
||||
ensureProfileHooksOrThrow(name);
|
||||
ensureWebSearchMcpOrThrow();
|
||||
} catch (hookError) {
|
||||
rollbackSettingsFile(settingsPath, previousSettingsContent, settingsExisted);
|
||||
throw hookError;
|
||||
|
||||
@@ -8,7 +8,7 @@ import { getCcsDir, getConfigPath, loadConfigSafe } from '../../utils/config-man
|
||||
import { expandPath } from '../../utils/helpers';
|
||||
import { validateApiName } from './validation-service';
|
||||
import { mutateUnifiedConfig, isUnifiedMode } from '../../config/unified-config-loader';
|
||||
import { ensureProfileHooksOrThrow } from '../../utils/websearch/profile-hook-injector';
|
||||
import { ensureWebSearchMcpOrThrow } from '../../utils/websearch-manager';
|
||||
import type { TargetType } from '../../targets/target-adapter';
|
||||
import { resolveDroidProvider } from '../../targets/droid-provider';
|
||||
import { isReservedName } from '../../config/reserved-names';
|
||||
@@ -126,8 +126,7 @@ function createSettingsFile(
|
||||
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n', 'utf8');
|
||||
|
||||
try {
|
||||
// Inject WebSearch hooks into profile settings
|
||||
ensureProfileHooksOrThrow(name);
|
||||
ensureWebSearchMcpOrThrow();
|
||||
} catch (error) {
|
||||
rollbackSettingsFile(settingsPath, previousSettingsContent, settingsExisted);
|
||||
throw error;
|
||||
@@ -216,8 +215,7 @@ function createApiProfileUnified(
|
||||
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n', 'utf8');
|
||||
|
||||
try {
|
||||
// Inject WebSearch hooks into profile settings
|
||||
ensureProfileHooksOrThrow(name);
|
||||
ensureWebSearchMcpOrThrow();
|
||||
} catch (error) {
|
||||
rollbackSettingsFile(settingsPath, previousSettingsContent, settingsExisted);
|
||||
throw error;
|
||||
|
||||
+17
-12
@@ -24,10 +24,11 @@ import {
|
||||
import { getEffectiveEnvVars, getCompositeEnvVars } from './cliproxy/config/env-builder';
|
||||
import { CLIPROXY_DEFAULT_PORT } from './cliproxy/config/port-manager';
|
||||
import {
|
||||
ensureMcpWebSearch,
|
||||
ensureWebSearchMcpOrThrow,
|
||||
displayWebSearchStatus,
|
||||
getWebSearchHookEnv,
|
||||
ensureProfileHooksOrThrow,
|
||||
syncWebSearchMcpToConfigDir,
|
||||
appendThirdPartyWebSearchToolArgs,
|
||||
} from './utils/websearch-manager';
|
||||
import { getGlobalEnvConfig, getOfficialChannelsConfig } from './config/unified-config-loader';
|
||||
import { ensureProfileHooks as ensureImageAnalyzerHooks } from './utils/hooks/image-analyzer-profile-hook-injector';
|
||||
@@ -677,8 +678,9 @@ async function main(): Promise<void> {
|
||||
|
||||
if (profileInfo.type === 'cliproxy') {
|
||||
// CLIPROXY FLOW: OAuth-based profiles (gemini, codex, agy, qwen) or user-defined variants
|
||||
// Inject WebSearch hook into profile settings before launch
|
||||
ensureProfileHooksOrThrow(profileInfo.name);
|
||||
if (resolvedTarget === 'claude') {
|
||||
ensureWebSearchMcpOrThrow();
|
||||
}
|
||||
// Inject Image Analyzer hook into profile settings before launch
|
||||
ensureImageAnalyzerHooks(profileInfo.name);
|
||||
|
||||
@@ -835,8 +837,7 @@ async function main(): Promise<void> {
|
||||
});
|
||||
} else if (profileInfo.type === 'copilot') {
|
||||
// COPILOT FLOW: GitHub Copilot subscription via copilot-api proxy
|
||||
// Inject WebSearch hook into profile settings before launch
|
||||
ensureProfileHooksOrThrow(profileInfo.name);
|
||||
ensureWebSearchMcpOrThrow();
|
||||
// Inject Image Analyzer hook into profile settings before launch
|
||||
ensureImageAnalyzerHooks(profileInfo.name);
|
||||
|
||||
@@ -858,6 +859,7 @@ async function main(): Promise<void> {
|
||||
)
|
||||
);
|
||||
}
|
||||
syncWebSearchMcpToConfigDir(continuityInheritance.claudeConfigDir);
|
||||
const exitCode = await executeCopilotProfile(
|
||||
copilotConfig,
|
||||
remainingArgs,
|
||||
@@ -867,14 +869,12 @@ async function main(): Promise<void> {
|
||||
process.exit(exitCode);
|
||||
} else if (profileInfo.type === 'settings') {
|
||||
// Settings-based profiles (glm, glmt) are third-party providers
|
||||
// WebSearch is server-side tool - third-party providers have no access
|
||||
// Inject WebSearch hook into profile settings before launch
|
||||
ensureProfileHooksOrThrow(profileInfo.name);
|
||||
if (resolvedTarget === 'claude') {
|
||||
ensureWebSearchMcpOrThrow();
|
||||
}
|
||||
// Inject Image Analyzer hook into profile settings before launch
|
||||
ensureImageAnalyzerHooks(profileInfo.name);
|
||||
|
||||
ensureMcpWebSearch();
|
||||
|
||||
// Display WebSearch status (single line, equilibrium UX)
|
||||
displayWebSearchStatus();
|
||||
|
||||
@@ -894,6 +894,7 @@ async function main(): Promise<void> {
|
||||
);
|
||||
}
|
||||
const inheritedClaudeConfigDir = continuityInheritance.claudeConfigDir;
|
||||
syncWebSearchMcpToConfigDir(inheritedClaudeConfigDir);
|
||||
const expandedSettingsPath =
|
||||
resolvedSettingsPath ??
|
||||
(profileInfo.settingsPath
|
||||
@@ -1053,7 +1054,11 @@ async function main(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
execClaude(claudeCli, ['--settings', expandedSettingsPath, ...remainingArgs], envVars);
|
||||
execClaude(
|
||||
claudeCli,
|
||||
['--settings', expandedSettingsPath, ...appendThirdPartyWebSearchToolArgs(remainingArgs)],
|
||||
envVars
|
||||
);
|
||||
} else if (profileInfo.type === 'account') {
|
||||
// NEW FLOW: Account-based profile (work, personal)
|
||||
// All platforms: Use instance isolation with CLAUDE_CONFIG_DIR
|
||||
|
||||
@@ -53,9 +53,9 @@ import {
|
||||
} from '../account-manager';
|
||||
import { formatAccountDisplayName } from '../accounts/email-account-identity';
|
||||
import {
|
||||
ensureMcpWebSearch,
|
||||
installWebSearchHook,
|
||||
ensureWebSearchMcpOrThrow,
|
||||
displayWebSearchStatus,
|
||||
appendThirdPartyWebSearchToolArgs,
|
||||
} from '../../utils/websearch-manager';
|
||||
import { loadOrCreateUnifiedConfig, getThinkingConfig } from '../../config/unified-config-loader';
|
||||
import { installImageAnalyzerHook } from '../../utils/hooks';
|
||||
@@ -197,9 +197,8 @@ export async function execClaudeWithCLIProxy(
|
||||
log(`Remote host: ${proxyConfig.host}:${proxyConfig.port} (${proxyConfig.protocol})`);
|
||||
}
|
||||
|
||||
// Setup WebSearch hooks
|
||||
ensureMcpWebSearch();
|
||||
installWebSearchHook();
|
||||
// Setup first-class CCS WebSearch runtime
|
||||
ensureWebSearchMcpOrThrow();
|
||||
displayWebSearchStatus();
|
||||
|
||||
// Sync image analyzer hook from npm package to ~/.ccs/hooks/
|
||||
@@ -1036,7 +1035,12 @@ export async function execClaudeWithCLIProxy(
|
||||
|
||||
let claude: ChildProcess;
|
||||
if (needsShell) {
|
||||
const cmdString = [claudeCli, '--settings', settingsPath, ...claudeArgs]
|
||||
const cmdString = [
|
||||
claudeCli,
|
||||
'--settings',
|
||||
settingsPath,
|
||||
...appendThirdPartyWebSearchToolArgs(claudeArgs),
|
||||
]
|
||||
.map(escapeShellArg)
|
||||
.join(' ');
|
||||
claude = spawn(cmdString, {
|
||||
@@ -1046,11 +1050,15 @@ export async function execClaudeWithCLIProxy(
|
||||
env,
|
||||
});
|
||||
} else {
|
||||
claude = spawn(claudeCli, ['--settings', settingsPath, ...claudeArgs], {
|
||||
stdio: 'inherit',
|
||||
windowsHide: true,
|
||||
env,
|
||||
});
|
||||
claude = spawn(
|
||||
claudeCli,
|
||||
['--settings', settingsPath, ...appendThirdPartyWebSearchToolArgs(claudeArgs)],
|
||||
{
|
||||
stdio: 'inherit',
|
||||
windowsHide: true,
|
||||
env,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// 12b. Start runtime quota monitor (adaptive polling during session)
|
||||
|
||||
@@ -14,7 +14,7 @@ import { expandPath } from '../../utils/helpers';
|
||||
import { getClaudeEnvVars, CLIPROXY_DEFAULT_PORT } from '../config-generator';
|
||||
import { CLIProxyProvider } from '../types';
|
||||
import { CompositeTierConfig } from '../../config/unified-config-types';
|
||||
import { ensureProfileHooksOrThrow } from '../../utils/websearch/profile-hook-injector';
|
||||
import { ensureWebSearchMcpOrThrow } from '../../utils/websearch-manager';
|
||||
import { ensureProfileHooks as ensureImageAnalyzerHooks } from '../../utils/hooks/image-analyzer-profile-hook-injector';
|
||||
import { getEffectiveApiKey } from '../auth-token-manager';
|
||||
import { warn } from '../../utils/ui';
|
||||
@@ -154,8 +154,7 @@ export function createSettingsFile(
|
||||
writeSettings(settingsPath, settings);
|
||||
|
||||
try {
|
||||
// Inject WebSearch hooks into variant settings
|
||||
ensureProfileHooksOrThrow(`${provider}-${name}`);
|
||||
ensureWebSearchMcpOrThrow();
|
||||
} catch (error) {
|
||||
rollbackSettingsFile(settingsPath, previousSettingsContent, settingsExisted);
|
||||
throw error;
|
||||
@@ -189,8 +188,7 @@ export function createSettingsFileUnified(
|
||||
writeSettings(settingsPath, settings);
|
||||
|
||||
try {
|
||||
// Inject WebSearch hooks into variant settings
|
||||
ensureProfileHooksOrThrow(`${provider}-${name}`);
|
||||
ensureWebSearchMcpOrThrow();
|
||||
} catch (error) {
|
||||
rollbackSettingsFile(settingsPath, previousSettingsContent, settingsExisted);
|
||||
throw error;
|
||||
@@ -289,7 +287,7 @@ export function createCompositeSettingsFile(
|
||||
// Hook injectors target ~/.ccs/<profile>.settings.json; only run for default path.
|
||||
if (path.resolve(settingsPath) === path.resolve(defaultSettingsPath)) {
|
||||
try {
|
||||
ensureProfileHooksOrThrow(`composite-${name}`);
|
||||
ensureWebSearchMcpOrThrow();
|
||||
} catch (error) {
|
||||
rollbackSettingsFile(settingsPath, previousSettingsContent, settingsExisted);
|
||||
throw error;
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
|
||||
import { info, ok, color, box, initUI } from '../utils/ui';
|
||||
import { uninstallWebSearchHook } from '../utils/websearch';
|
||||
import { uninstallWebSearchHook, uninstallWebSearchMcp } from '../utils/websearch';
|
||||
import { ClaudeSymlinkManager } from '../utils/claude-symlink-manager';
|
||||
|
||||
/**
|
||||
@@ -42,12 +42,19 @@ export async function handleUninstallCommand(): Promise<void> {
|
||||
removed += 1; // Count as 1 item (the hook file)
|
||||
}
|
||||
|
||||
// 2. Remove symlinks from ~/.claude/
|
||||
// 2. Remove managed WebSearch MCP runtime/config
|
||||
const mcpRemoved = uninstallWebSearchMcp();
|
||||
if (mcpRemoved) {
|
||||
console.log(ok('Removed WebSearch MCP runtime'));
|
||||
removed += 1;
|
||||
}
|
||||
|
||||
// 3. Remove symlinks from ~/.claude/
|
||||
const symlinkManager = new ClaudeSymlinkManager();
|
||||
const symlinksRemoved = symlinkManager.uninstall();
|
||||
removed += symlinksRemoved; // Add actual count of symlinks removed
|
||||
|
||||
// 3. Summary
|
||||
// 4. Summary
|
||||
console.log('');
|
||||
if (removed > 0) {
|
||||
console.log(ok('Uninstall complete!'));
|
||||
|
||||
@@ -14,7 +14,11 @@ import { ensureCopilotApi } from './copilot-package-manager';
|
||||
import { normalizeCopilotConfigWithWarnings } from './copilot-model-normalizer';
|
||||
import { CopilotStatus } from './types';
|
||||
import { fail, info, ok, warn } from '../utils/ui';
|
||||
import { getWebSearchHookEnv } from '../utils/websearch-manager';
|
||||
import {
|
||||
getWebSearchHookEnv,
|
||||
appendThirdPartyWebSearchToolArgs,
|
||||
syncWebSearchMcpToConfigDir,
|
||||
} from '../utils/websearch-manager';
|
||||
import { getImageAnalysisHookEnv } from '../utils/hooks';
|
||||
import { stripClaudeCodeEnv } from '../utils/shell-executor';
|
||||
|
||||
@@ -173,9 +177,11 @@ export async function executeCopilotProfile(
|
||||
console.log(info(`Using GitHub Copilot proxy (model: ${normalizedConfig.model})`));
|
||||
console.log('');
|
||||
|
||||
syncWebSearchMcpToConfigDir(claudeConfigDir);
|
||||
|
||||
// Spawn Claude CLI
|
||||
return new Promise((resolve) => {
|
||||
const proc = spawn(claudeCliPath, claudeArgs, {
|
||||
const proc = spawn(claudeCliPath, appendThirdPartyWebSearchToolArgs(claudeArgs), {
|
||||
stdio: 'inherit',
|
||||
env,
|
||||
shell: process.platform === 'win32',
|
||||
|
||||
@@ -25,6 +25,11 @@ export function getClaudeConfigDir(): string {
|
||||
return getDefaultClaudeConfigDir();
|
||||
}
|
||||
|
||||
/** Resolve user-scope Claude JSON config path (~/.claude.json). */
|
||||
export function getClaudeUserConfigPath(): string {
|
||||
return path.join(getCcsHome(), '.claude.json');
|
||||
}
|
||||
|
||||
/** Resolve Claude settings.json path. */
|
||||
export function getClaudeSettingsPath(): string {
|
||||
return path.join(getClaudeConfigDir(), 'settings.json');
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
/**
|
||||
* WebSearch Manager - Manages WebSearch hook for CCS
|
||||
* WebSearch Manager - Manages CCS WebSearch runtime
|
||||
*
|
||||
* WebSearch is a server-side tool executed by Anthropic's API.
|
||||
* Third-party providers (gemini, agy, codex, qwen) don't have access.
|
||||
* This manager installs a hook that uses deterministic local search backends,
|
||||
* with legacy AI CLI tools kept only as optional fallback.
|
||||
* CCS exposes a first-class local WebSearch tool for those profiles and keeps
|
||||
* the legacy hook runtime only as a compatibility fallback.
|
||||
*
|
||||
* Simplified Architecture:
|
||||
* - No MCP dependency for the default path
|
||||
* - Uses real search providers first (DuckDuckGo, Brave)
|
||||
* - Keeps Gemini/OpenCode/Grok as compatibility fallback only
|
||||
* Runtime Architecture:
|
||||
* - User-scope MCP server in ~/.claude.json for third-party profiles
|
||||
* - Real search providers first (Exa, Tavily, Brave Search, DuckDuckGo)
|
||||
* - Gemini/OpenCode/Grok retained as optional legacy fallback
|
||||
*
|
||||
* @module utils/websearch-manager
|
||||
*/
|
||||
@@ -53,6 +53,23 @@ export {
|
||||
// Re-export hook environment
|
||||
export { getWebSearchHookEnv } from './websearch/hook-env';
|
||||
|
||||
// Re-export MCP runtime helpers
|
||||
export {
|
||||
getWebSearchMcpServerName,
|
||||
getWebSearchMcpServerPath,
|
||||
installWebSearchMcpServer,
|
||||
ensureWebSearchMcpConfig,
|
||||
ensureWebSearchMcp,
|
||||
uninstallWebSearchMcpServer,
|
||||
removeWebSearchMcpConfig,
|
||||
uninstallWebSearchMcp,
|
||||
syncWebSearchMcpToConfigDir,
|
||||
ensureWebSearchMcpOrThrow,
|
||||
} from './websearch/mcp-installer';
|
||||
|
||||
// Re-export Claude launch arg helpers
|
||||
export { appendThirdPartyWebSearchToolArgs } from './websearch/claude-tool-args';
|
||||
|
||||
// Re-export status and readiness functions
|
||||
export {
|
||||
getWebSearchCliProviders,
|
||||
@@ -62,7 +79,7 @@ export {
|
||||
displayWebSearchStatus,
|
||||
} from './websearch/status';
|
||||
|
||||
// Re-export profile hook injection
|
||||
// Re-export profile compatibility hook injection
|
||||
export { ensureProfileHooks, ensureProfileHooksOrThrow } from './websearch/profile-hook-injector';
|
||||
|
||||
// Import for local use
|
||||
@@ -77,11 +94,4 @@ export function clearAllCliCaches(): void {
|
||||
clearOpenCodeCliCache();
|
||||
}
|
||||
|
||||
// ========== Backward Compatibility Exports ==========
|
||||
|
||||
/**
|
||||
* @deprecated Use installWebSearchHook instead - MCP is no longer used
|
||||
*/
|
||||
export function ensureMcpWebSearch(): boolean {
|
||||
return false;
|
||||
}
|
||||
export { ensureWebSearchMcp as ensureMcpWebSearch } from './websearch/mcp-installer';
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Claude launch argument helpers for third-party WebSearch.
|
||||
*/
|
||||
|
||||
const NATIVE_WEBSEARCH_TOOL = 'WebSearch';
|
||||
const DISALLOWED_TOOLS_FLAG = '--disallowedTools';
|
||||
|
||||
function parseToolValue(rawValue: string): string[] {
|
||||
return rawValue
|
||||
.split(',')
|
||||
.map((value) => value.trim())
|
||||
.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
function hasToolInFlag(args: string[], flag: string, toolName: string): boolean {
|
||||
for (let index = 0; index < args.length; index += 1) {
|
||||
const arg = args[index];
|
||||
|
||||
if (arg === flag) {
|
||||
for (let cursor = index + 1; cursor < args.length; cursor += 1) {
|
||||
const value = args[cursor];
|
||||
if (value.startsWith('--')) {
|
||||
break;
|
||||
}
|
||||
if (parseToolValue(value).includes(toolName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!arg.startsWith(`${flag}=`)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const rawValue = arg.slice(flag.length + 1);
|
||||
if (parseToolValue(rawValue).includes(toolName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function appendThirdPartyWebSearchToolArgs(args: string[]): string[] {
|
||||
if (hasToolInFlag(args, DISALLOWED_TOOLS_FLAG, NATIVE_WEBSEARCH_TOOL)) {
|
||||
return args;
|
||||
}
|
||||
|
||||
return [...args, DISALLOWED_TOOLS_FLAG, NATIVE_WEBSEARCH_TOOL];
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* WebSearch Hook Installer
|
||||
*
|
||||
* Manages installation and uninstallation of the WebSearch hook.
|
||||
* Manages installation and uninstallation of the legacy WebSearch hook runtime.
|
||||
*
|
||||
* @module utils/websearch/hook-installer
|
||||
*/
|
||||
@@ -70,7 +70,8 @@ export function hasWebSearchHook(): boolean {
|
||||
/**
|
||||
* Install WebSearch hook to ~/.ccs/hooks/
|
||||
*
|
||||
* This hook intercepts WebSearch and executes via Gemini CLI.
|
||||
* This hook now serves as a compatibility fallback and a shared provider runtime
|
||||
* for the first-class CCS WebSearch MCP server.
|
||||
*
|
||||
* @returns true if hook installed successfully
|
||||
*/
|
||||
|
||||
@@ -50,6 +50,23 @@ export { removeHookConfig } from './hook-config';
|
||||
// Hook Environment
|
||||
export { getWebSearchHookEnv } from './hook-env';
|
||||
|
||||
// MCP Runtime
|
||||
export {
|
||||
getWebSearchMcpServerName,
|
||||
getWebSearchMcpServerPath,
|
||||
installWebSearchMcpServer,
|
||||
ensureWebSearchMcpConfig,
|
||||
ensureWebSearchMcp,
|
||||
uninstallWebSearchMcpServer,
|
||||
removeWebSearchMcpConfig,
|
||||
uninstallWebSearchMcp,
|
||||
syncWebSearchMcpToConfigDir,
|
||||
ensureWebSearchMcpOrThrow,
|
||||
} from './mcp-installer';
|
||||
|
||||
// Claude launch args
|
||||
export { appendThirdPartyWebSearchToolArgs } from './claude-tool-args';
|
||||
|
||||
// Status and Readiness
|
||||
export {
|
||||
getWebSearchCliProviders,
|
||||
@@ -61,5 +78,5 @@ export {
|
||||
|
||||
export { WEBSEARCH_API_KEY_PROVIDERS, getWebSearchApiKeyStates } from './provider-secrets';
|
||||
|
||||
// Profile Hook Injection
|
||||
// Profile compatibility hook injection
|
||||
export { ensureProfileHooks, ensureProfileHooksOrThrow } from './profile-hook-injector';
|
||||
@@ -0,0 +1,329 @@
|
||||
/**
|
||||
* WebSearch MCP installer and ~/.claude.json provisioning.
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { getWebSearchConfig } from '../../config/unified-config-loader';
|
||||
import { getCcsDir } from '../config-manager';
|
||||
import { getClaudeUserConfigPath } from '../claude-config-path';
|
||||
import { info, warn } from '../ui';
|
||||
import { InstanceManager } from '../../management/instance-manager';
|
||||
import { installWebSearchHook } from './hook-installer';
|
||||
|
||||
const WEBSEARCH_MCP_SERVER = 'ccs-websearch-server.cjs';
|
||||
const WEBSEARCH_MCP_SERVER_NAME = 'ccs-websearch';
|
||||
|
||||
interface ClaudeUserConfig {
|
||||
mcpServers?: Record<string, unknown>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
function getCcsMcpDir(): string {
|
||||
return path.join(getCcsDir(), 'mcp');
|
||||
}
|
||||
|
||||
export function getWebSearchMcpServerName(): string {
|
||||
return WEBSEARCH_MCP_SERVER_NAME;
|
||||
}
|
||||
|
||||
export function getWebSearchMcpServerPath(): string {
|
||||
return path.join(getCcsMcpDir(), WEBSEARCH_MCP_SERVER);
|
||||
}
|
||||
|
||||
function hasMatchingContents(sourcePath: string, destinationPath: string): boolean {
|
||||
if (!fs.existsSync(destinationPath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const source = fs.readFileSync(sourcePath);
|
||||
try {
|
||||
const destination = fs.readFileSync(destinationPath);
|
||||
return source.equals(destination);
|
||||
} catch (error) {
|
||||
if (process.env.CCS_DEBUG) {
|
||||
console.error(
|
||||
warn(`Existing WebSearch MCP server is unreadable: ${(error as Error).message}`)
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function getTempPath(targetPath: string): string {
|
||||
const suffix = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
return `${targetPath}.${suffix}.tmp`;
|
||||
}
|
||||
|
||||
function resolveBundledServerSourcePath(): string | null {
|
||||
const possiblePaths = [
|
||||
path.join(__dirname, '..', '..', '..', 'lib', 'mcp', WEBSEARCH_MCP_SERVER),
|
||||
path.join(__dirname, '..', '..', 'lib', 'mcp', WEBSEARCH_MCP_SERVER),
|
||||
path.join(__dirname, '..', 'lib', 'mcp', WEBSEARCH_MCP_SERVER),
|
||||
];
|
||||
|
||||
for (const candidate of possiblePaths) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function readClaudeUserConfig(configPath: string): ClaudeUserConfig | null {
|
||||
if (!fs.existsSync(configPath)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(configPath, 'utf8');
|
||||
const parsed = JSON.parse(raw);
|
||||
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
||||
return null;
|
||||
}
|
||||
return parsed as ClaudeUserConfig;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeClaudeUserConfig(configPath: string, config: ClaudeUserConfig): boolean {
|
||||
const tempPath = getTempPath(configPath);
|
||||
|
||||
try {
|
||||
fs.writeFileSync(tempPath, JSON.stringify(config, null, 2) + '\n', 'utf8');
|
||||
fs.renameSync(tempPath, configPath);
|
||||
return true;
|
||||
} finally {
|
||||
if (fs.existsSync(tempPath)) {
|
||||
fs.unlinkSync(tempPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function removeManagedServerConfig(configPath: string): boolean {
|
||||
if (!fs.existsSync(configPath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const config = readClaudeUserConfig(configPath);
|
||||
if (config === null) {
|
||||
if (process.env.CCS_DEBUG) {
|
||||
console.error(warn(`Malformed Claude config prevents MCP cleanup: ${configPath}`));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const existingServers =
|
||||
config.mcpServers && typeof config.mcpServers === 'object' && !Array.isArray(config.mcpServers)
|
||||
? { ...(config.mcpServers as Record<string, unknown>) }
|
||||
: {};
|
||||
|
||||
if (!(WEBSEARCH_MCP_SERVER_NAME in existingServers)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
delete existingServers[WEBSEARCH_MCP_SERVER_NAME];
|
||||
|
||||
const nextConfig: ClaudeUserConfig = { ...config };
|
||||
if (Object.keys(existingServers).length === 0) {
|
||||
delete nextConfig.mcpServers;
|
||||
} else {
|
||||
nextConfig.mcpServers = existingServers;
|
||||
}
|
||||
|
||||
try {
|
||||
writeClaudeUserConfig(configPath, nextConfig);
|
||||
if (process.env.CCS_DEBUG) {
|
||||
console.error(info(`Removed WebSearch MCP config from ${configPath}`));
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (process.env.CCS_DEBUG) {
|
||||
console.error(
|
||||
warn(
|
||||
`Failed to remove WebSearch MCP config from ${configPath}: ${(error as Error).message}`
|
||||
)
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function installWebSearchMcpServer(): boolean {
|
||||
const wsConfig = getWebSearchConfig();
|
||||
if (!wsConfig.enabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!installWebSearchHook()) {
|
||||
if (process.env.CCS_DEBUG) {
|
||||
console.error(
|
||||
warn('WebSearch MCP server install skipped because hook runtime is unavailable')
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const sourcePath = resolveBundledServerSourcePath();
|
||||
if (!sourcePath) {
|
||||
if (process.env.CCS_DEBUG) {
|
||||
console.error(warn(`WebSearch MCP server source not found: ${WEBSEARCH_MCP_SERVER}`));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const mcpDir = getCcsMcpDir();
|
||||
if (!fs.existsSync(mcpDir)) {
|
||||
fs.mkdirSync(mcpDir, { recursive: true, mode: 0o700 });
|
||||
}
|
||||
|
||||
const serverPath = getWebSearchMcpServerPath();
|
||||
if (hasMatchingContents(sourcePath, serverPath)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const tempPath = getTempPath(serverPath);
|
||||
|
||||
try {
|
||||
fs.copyFileSync(sourcePath, tempPath);
|
||||
fs.chmodSync(tempPath, 0o755);
|
||||
fs.renameSync(tempPath, serverPath);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (process.env.CCS_DEBUG) {
|
||||
console.error(warn(`Failed to install WebSearch MCP server: ${(error as Error).message}`));
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
if (fs.existsSync(tempPath)) {
|
||||
fs.unlinkSync(tempPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function ensureWebSearchMcpConfig(): boolean {
|
||||
const wsConfig = getWebSearchConfig();
|
||||
if (!wsConfig.enabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const claudeUserConfigPath = getClaudeUserConfigPath();
|
||||
const claudeUserConfigDir = path.dirname(claudeUserConfigPath);
|
||||
const config = readClaudeUserConfig(claudeUserConfigPath);
|
||||
|
||||
if (config === null) {
|
||||
if (process.env.CCS_DEBUG) {
|
||||
console.error(warn('Malformed ~/.claude.json prevents WebSearch MCP provisioning'));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!fs.existsSync(claudeUserConfigDir)) {
|
||||
fs.mkdirSync(claudeUserConfigDir, { recursive: true, mode: 0o700 });
|
||||
}
|
||||
|
||||
const existingServers =
|
||||
config.mcpServers && typeof config.mcpServers === 'object' && !Array.isArray(config.mcpServers)
|
||||
? (config.mcpServers as Record<string, unknown>)
|
||||
: {};
|
||||
const desiredServerConfig = {
|
||||
command: 'node',
|
||||
args: [getWebSearchMcpServerPath()],
|
||||
};
|
||||
|
||||
const currentConfig = existingServers[WEBSEARCH_MCP_SERVER_NAME];
|
||||
if (
|
||||
typeof currentConfig === 'object' &&
|
||||
currentConfig !== null &&
|
||||
JSON.stringify(currentConfig) === JSON.stringify(desiredServerConfig)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const nextConfig: ClaudeUserConfig = {
|
||||
...config,
|
||||
mcpServers: {
|
||||
...existingServers,
|
||||
[WEBSEARCH_MCP_SERVER_NAME]: desiredServerConfig,
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
writeClaudeUserConfig(claudeUserConfigPath, nextConfig);
|
||||
if (process.env.CCS_DEBUG) {
|
||||
console.error(info(`Ensured WebSearch MCP config in ${claudeUserConfigPath}`));
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (process.env.CCS_DEBUG) {
|
||||
console.error(warn(`Failed to update ~/.claude.json: ${(error as Error).message}`));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function ensureWebSearchMcp(): boolean {
|
||||
const wsConfig = getWebSearchConfig();
|
||||
if (!wsConfig.enabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return installWebSearchMcpServer() && ensureWebSearchMcpConfig();
|
||||
}
|
||||
|
||||
export function syncWebSearchMcpToConfigDir(claudeConfigDir: string | undefined): boolean {
|
||||
if (!claudeConfigDir) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return new InstanceManager().syncMcpServers(claudeConfigDir);
|
||||
}
|
||||
|
||||
export function uninstallWebSearchMcpServer(): boolean {
|
||||
const serverPath = getWebSearchMcpServerPath();
|
||||
if (!fs.existsSync(serverPath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
fs.unlinkSync(serverPath);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (process.env.CCS_DEBUG) {
|
||||
console.error(warn(`Failed to remove WebSearch MCP server: ${(error as Error).message}`));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function removeWebSearchMcpConfig(): boolean {
|
||||
let removed = removeManagedServerConfig(getClaudeUserConfigPath());
|
||||
|
||||
const instanceManager = new InstanceManager();
|
||||
for (const instanceName of instanceManager.listInstances()) {
|
||||
const instancePath = instanceManager.getInstancePath(instanceName);
|
||||
const instanceClaudeConfigPath = path.join(instancePath, '.claude.json');
|
||||
removed = removeManagedServerConfig(instanceClaudeConfigPath) || removed;
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
export function uninstallWebSearchMcp(): boolean {
|
||||
const removedConfig = removeWebSearchMcpConfig();
|
||||
const removedServer = uninstallWebSearchMcpServer();
|
||||
return removedConfig || removedServer;
|
||||
}
|
||||
|
||||
export function ensureWebSearchMcpOrThrow(): void {
|
||||
const wsConfig = getWebSearchConfig();
|
||||
if (!wsConfig.enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ensureWebSearchMcp()) {
|
||||
throw new Error('WebSearch is enabled, but CCS could not prepare the local WebSearch tool.');
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
/**
|
||||
* Profile Hook Injector
|
||||
*
|
||||
* Injects WebSearch hooks into per-profile settings files.
|
||||
* This replaces the global ~/.claude/settings.json approach.
|
||||
* Injects the legacy WebSearch compatibility hook into per-profile settings files.
|
||||
* The first-class runtime now uses the CCS-managed MCP server; these hooks remain
|
||||
* for compatibility and migration safety only.
|
||||
*
|
||||
* @module utils/websearch/profile-hook-injector
|
||||
*/
|
||||
@@ -76,7 +77,8 @@ function migrateGlobalHook(): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure WebSearch hook is configured in profile's settings file
|
||||
* Ensure the legacy WebSearch compatibility hook is configured in a profile's
|
||||
* settings file when that path is still needed.
|
||||
*
|
||||
* @param profileName - Name of the profile (e.g., 'agy', 'gemini', 'glm')
|
||||
* @returns true if hook is configured (existing or newly added)
|
||||
|
||||
Reference in new issue
Block a user