feat: add CLI settings export/import functionality

- Implemented exportSettings and importSettings APIs for CLI settings.
- Added hooks useExportSettings and useImportSettings for managing export/import operations in the frontend.
- Updated SettingsPage to include buttons for exporting and importing CLI settings.
- Enhanced backend to handle export and import requests, including validation and conflict resolution.
- Introduced new data structures for exported settings and import options.
- Updated localization files to support new export/import features.
- Refactored CLI tool configurations to remove hardcoded model defaults, allowing dynamic model retrieval.
This commit is contained in:
catlog22
2026-02-25 21:40:24 +08:00
parent 4c2bf31525
commit b2b8688d26
24 changed files with 1287 additions and 651 deletions

View File

@@ -16,6 +16,9 @@ import {
SettingsListResponse,
SettingsOperationResult,
SaveEndpointRequest,
ExportedSettings,
ImportOptions,
ImportResult,
validateSettings,
createDefaultSettings
} from '../types/cli-settings.js';
@@ -471,3 +474,152 @@ export function validateEndpointName(name: string): { valid: boolean; error?: st
return { valid: true };
}
/**
* Export all CLI endpoint settings
* Returns an ExportedSettings object with version, timestamp, and all endpoints
*/
export function exportAllSettings(): ExportedSettings {
const { endpoints } = listAllSettings();
return {
version: '1.0.0',
timestamp: new Date().toISOString(),
endpoints
};
}
/**
* Import settings from an ExportedSettings object
* Validates and applies imported settings with configurable conflict resolution
*/
export function importSettings(
exportedData: unknown,
options: ImportOptions = {}
): ImportResult {
const {
conflictStrategy = 'skip',
skipInvalid = true,
disableImported = false
} = options;
const result: ImportResult = {
success: false,
imported: 0,
skipped: 0,
errors: [],
importedIds: []
};
// Validate exported data structure
if (!exportedData || typeof exportedData !== 'object') {
result.errors.push('Invalid export data: must be an object');
return result;
}
const data = exportedData as Record<string, unknown>;
// Check for required fields
if (!('endpoints' in data) || !Array.isArray(data.endpoints)) {
result.errors.push('Invalid export data: missing or invalid endpoints array');
return result;
}
// Validate version (for future migration support)
if ('version' in data && typeof data.version !== 'string') {
result.errors.push('Invalid export data: version must be a string');
return result;
}
const endpoints = data.endpoints as unknown[];
const existingIndex = loadIndex();
for (let i = 0; i < endpoints.length; i++) {
const ep = endpoints[i];
// Validate endpoint structure
if (!ep || typeof ep !== 'object') {
if (!skipInvalid) {
result.errors.push(`Endpoint at index ${i}: invalid structure`);
}
result.skipped++;
continue;
}
const endpoint = ep as Record<string, unknown>;
// Check required fields
if (!endpoint.name || typeof endpoint.name !== 'string') {
if (!skipInvalid) {
result.errors.push(`Endpoint at index ${i}: missing or invalid name`);
}
result.skipped++;
continue;
}
if (!endpoint.settings || typeof endpoint.settings !== 'object') {
if (!skipInvalid) {
result.errors.push(`Endpoint at index ${i}: missing or invalid settings`);
}
result.skipped++;
continue;
}
// Validate settings using provider-aware validation
const provider: CliProvider = (endpoint.provider as CliProvider) || 'claude';
if (!validateSettings(endpoint.settings, provider)) {
if (!skipInvalid) {
result.errors.push(`Endpoint "${endpoint.name}": invalid settings format`);
}
result.skipped++;
continue;
}
// Determine endpoint ID
const endpointId = (endpoint.id as string) || generateEndpointId();
const exists = existingIndex.has(endpointId);
// Handle conflicts
if (exists && conflictStrategy === 'skip') {
result.skipped++;
continue;
}
// Prepare import request
const importRequest: SaveEndpointRequest = {
id: endpointId,
name: endpoint.name as string,
description: endpoint.description as string | undefined,
provider,
settings: endpoint.settings as CliSettings,
enabled: disableImported ? false : (endpoint.enabled as boolean) ?? true
};
// For merge strategy, combine with existing if applicable
if (exists && conflictStrategy === 'merge') {
const existing = loadEndpointSettings(endpointId);
if (existing) {
importRequest.settings = {
...existing.settings,
...(endpoint.settings as CliSettings)
} as CliSettings;
importRequest.name = (endpoint.name as string) || existing.name;
importRequest.description = (endpoint.description as string) ?? existing.description;
}
}
// Save the endpoint
const saveResult = saveEndpointSettings(importRequest);
if (saveResult.success) {
result.imported++;
result.importedIds!.push(endpointId);
} else {
result.errors.push(`Endpoint "${endpoint.name}": ${saveResult.message || 'Failed to save'}`);
result.skipped++;
}
}
result.success = result.imported > 0;
return result;
}

View File

@@ -12,9 +12,11 @@ import {
toggleEndpointEnabled,
getSettingsFilePath,
ensureSettingsDir,
sanitizeEndpointId
sanitizeEndpointId,
exportAllSettings,
importSettings
} from '../../config/cli-settings-manager.js';
import type { SaveEndpointRequest } from '../../types/cli-settings.js';
import type { SaveEndpointRequest, ImportOptions } from '../../types/cli-settings.js';
import { validateSettings } from '../../types/cli-settings.js';
import { syncBuiltinToolsAvailability, getBuiltinToolsSyncReport } from '../../tools/claude-cli-tools.js';
@@ -275,5 +277,62 @@ export async function handleCliSettingsRoutes(ctx: RouteContext): Promise<boolea
return true;
}
// ========== EXPORT SETTINGS ==========
// GET /api/cli/settings/export
if (pathname === '/api/cli/settings/export' && req.method === 'GET') {
try {
const exportData = exportAllSettings();
const jsonContent = JSON.stringify(exportData, null, 2);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').substring(0, 19);
const filename = `cli-settings-export-${timestamp}.json`;
res.writeHead(200, {
'Content-Type': 'application/json',
'Content-Disposition': `attachment; filename="${filename}"`,
'Content-Length': Buffer.byteLength(jsonContent, 'utf-8')
});
res.end(jsonContent);
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: (err as Error).message }));
}
return true;
}
// ========== IMPORT SETTINGS ==========
// POST /api/cli/settings/import
if (pathname === '/api/cli/settings/import' && req.method === 'POST') {
handlePostRequest(req, res, async (body: unknown) => {
try {
// Extract import options and data from request
const request = body as { data?: unknown; options?: ImportOptions };
if (!request.data) {
return { error: 'Missing export data in request body', status: 400 };
}
const result = importSettings(request.data, request.options);
if (result.success) {
// Broadcast import event
broadcastToClients({
type: 'CLI_SETTINGS_IMPORTED',
payload: {
imported: result.imported,
skipped: result.skipped,
importedIds: result.importedIds,
timestamp: new Date().toISOString()
}
});
}
return result;
} catch (err) {
return { error: (err as Error).message, status: 500 };
}
});
return true;
}
return false;
}

View File

@@ -335,11 +335,15 @@ export class CliSessionManager {
}
// Merge endpoint env vars with process.env (endpoint overrides process.env)
const spawnEnv: Record<string, string> = {
const spawnEnv: Record<string, string | undefined> = {
...(process.env as Record<string, string>),
...endpointEnv,
};
// Unset CLAUDECODE to allow nested Claude Code sessions (SDK/subagent use case)
// See: https://github.com/anthropics/claude-agent-sdk-python/issues/573
delete spawnEnv.CLAUDECODE;
let pty: nodePty.IPty;
try {
pty = nodePty.spawn(file, args, {

View File

@@ -136,46 +136,32 @@ export interface ClaudeCliCombinedConfig extends ClaudeCliToolsConfig {
// ========== Default Config ==========
// Default tools config - no model defaults, models come from user's cli-tools.json
const DEFAULT_TOOLS_CONFIG: ClaudeCliToolsConfig = {
version: '3.4.0',
tools: {
gemini: {
enabled: true,
primaryModel: 'gemini-2.5-pro',
secondaryModel: 'gemini-2.5-flash',
availableModels: ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-2.0-flash', 'gemini-2.0-flash-thinking', 'gemini-1.5-pro'],
tags: [],
type: 'builtin'
},
qwen: {
enabled: true,
primaryModel: 'coder-model',
secondaryModel: 'coder-model',
availableModels: ['coder-model', 'vision-model', 'qwen-2.5-coder', 'qwen-2.5-72b'],
tags: [],
type: 'builtin'
},
codex: {
enabled: true,
primaryModel: 'gpt-5.2',
secondaryModel: 'gpt-5.2',
availableModels: ['gpt-5.2', 'gpt-5', 'gpt5-codex', 'o3', 'o1'],
tags: [],
type: 'builtin'
},
claude: {
enabled: true,
primaryModel: 'sonnet',
secondaryModel: 'haiku',
availableModels: ['opus', 'sonnet', 'haiku'],
tags: [],
type: 'builtin'
},
opencode: {
enabled: true,
primaryModel: 'opencode/glm-4.7-free',
secondaryModel: 'opencode/glm-4.7-free',
availableModels: ['opencode/glm-4.7-free', 'opencode/deepseek-v3-free'],
tags: [],
type: 'builtin'
}

View File

@@ -958,12 +958,16 @@ async function executeCliTool(
// Merge custom env with process.env (custom env takes precedence)
// Also include rulesEnv for $PROTO and $TMPL template variables
const spawnEnv = {
const spawnEnv: Record<string, string | undefined> = {
...process.env,
...customEnv,
...(rulesEnv || {})
};
// Unset CLAUDECODE to allow nested Claude Code sessions (SDK/subagent use case)
// See: https://github.com/anthropics/claude-agent-sdk-python/issues/573
delete spawnEnv.CLAUDECODE;
debugLog('SPAWN', `Spawning process`, {
command,
args,

View File

@@ -23,13 +23,6 @@ const CODE_EXTENSIONS = [
'.ts', '.tsx', '.js', '.jsx', '.py', '.sh', '.go', '.rs'
];
// Default models for each tool
const DEFAULT_MODELS: Record<string, string> = {
gemini: 'gemini-2.5-flash',
qwen: 'coder-model',
codex: 'gpt5-codex'
};
// Template paths (relative to user home directory)
const TEMPLATE_BASE = '~/.ccw/workflows/cli-templates/prompts/documentation';
@@ -141,20 +134,21 @@ function buildCliCommand(tool: string, promptFile: string, model: string): strin
// Build the cat/read command based on platform
const catCmd = isWindows ? `Get-Content -Raw "${normalizedPath}" | ` : `cat "${normalizedPath}" | `;
// Build model flag only if model is specified
const modelFlag = model ? ` -m "${model}"` : '';
switch (tool) {
case 'qwen':
return model === 'coder-model'
? `${catCmd}qwen --yolo`
: `${catCmd}qwen -m "${model}" --yolo`;
return `${catCmd}qwen${modelFlag} --yolo`;
case 'codex':
// codex uses different syntax - prompt as exec argument
if (isWindows) {
return `codex --full-auto exec (Get-Content -Raw "${normalizedPath}") -m "${model}" --skip-git-repo-check -s danger-full-access`;
return `codex --full-auto exec (Get-Content -Raw "${normalizedPath}")${modelFlag} --skip-git-repo-check -s danger-full-access`;
}
return `codex --full-auto exec "$(cat "${normalizedPath}")" -m "${model}" --skip-git-repo-check -s danger-full-access`;
return `codex --full-auto exec "$(cat "${normalizedPath}")"${modelFlag} --skip-git-repo-check -s danger-full-access`;
case 'gemini':
default:
return `${catCmd}gemini -m "${model}" --yolo`;
return `${catCmd}gemini${modelFlag} --yolo`;
}
}
@@ -273,7 +267,8 @@ export async function handler(params: Record<string, unknown>): Promise<ToolResu
try {
actualModel = getSecondaryModel(process.cwd(), tool);
} catch {
actualModel = DEFAULT_MODELS[tool] || DEFAULT_MODELS.gemini;
// If config not available, don't specify model - let CLI decide
actualModel = '';
}
}

View File

@@ -258,3 +258,43 @@ export function validateSettings(settings: unknown, provider?: CliProvider): set
return true;
}
/**
* Exported settings format for backup/restore
*/
export interface ExportedSettings {
/** Export format version for future migrations */
version: string;
/** Export timestamp (ISO 8601) */
timestamp: string;
/** All endpoint settings */
endpoints: EndpointSettings[];
}
/**
* Import options for conflict resolution
*/
export interface ImportOptions {
/** How to handle conflicts: 'skip' keeps existing, 'overwrite' replaces, 'merge' combines */
conflictStrategy?: 'skip' | 'overwrite' | 'merge';
/** Whether to skip invalid endpoints (default: true) */
skipInvalid?: boolean;
/** Whether to disable all imported endpoints (default: false) */
disableImported?: boolean;
}
/**
* Import result summary
*/
export interface ImportResult {
/** Whether import was successful overall */
success: boolean;
/** Number of endpoints imported successfully */
imported: number;
/** Number of endpoints skipped (conflicts or validation errors) */
skipped: number;
/** Detailed error messages for failed imports */
errors: string[];
/** List of imported endpoint IDs */
importedIds?: string[];
}