diff --git a/extensions/cli/src/commands/remote.test.ts b/extensions/cli/src/commands/remote.test.ts index a8025a4d7..9a9c9f3f5 100644 --- a/extensions/cli/src/commands/remote.test.ts +++ b/extensions/cli/src/commands/remote.test.ts @@ -353,7 +353,32 @@ describe("remote command", () => { expect(mockFetch).toHaveBeenCalledWith( new URL("agents", mockEnv.env.apiBase), expect.objectContaining({ - body: expect.stringContaining(`"agent":"${testConfig}"`), + body: expect.stringContaining(`"config":"${testConfig}"`), + }), + ); + }); + + it("should include agent in request body when agent option is provided", async () => { + const testAgent = "test-agent"; + + await remote("test prompt", { agent: testAgent }); + + expect(mockFetch).toHaveBeenCalledWith( + new URL("agents", mockEnv.env.apiBase), + expect.objectContaining({ + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-token", + }, + body: expect.stringContaining(`"agent":"${testAgent}"`), + }), + ); + + expect(mockFetch).toHaveBeenCalledWith( + new URL("agents", mockEnv.env.apiBase), + expect.objectContaining({ + body: expect.stringContaining(`"agent":"${testAgent}"`), }), ); }); @@ -375,11 +400,31 @@ describe("remote command", () => { name: expect.stringMatching(/^devbox-\d+$/), prompt: "test prompt", idempotencyKey: testIdempotencyKey, - agent: testConfig, config: testConfig, }); }); + it("should handle proper request body structure with agent field", async () => { + const testAgent = "my-agent"; + const testIdempotencyKey = "test-with-config"; + + await remote("test prompt", { + agent: testAgent, + idempotencyKey: testIdempotencyKey, + }); + + const fetchCall = mockFetch.mock.calls[0]; + const requestBody = JSON.parse(fetchCall[1].body); + + expect(requestBody).toEqual({ + repoUrl: "https://github.com/user/test-repo.git", + name: expect.stringMatching(/^devbox-\d+$/), + prompt: "test prompt", + idempotencyKey: testIdempotencyKey, + agent: testAgent, + }); + }); + it("should not include config in request body when config option is not provided", async () => { await remote("test prompt", {}); diff --git a/extensions/cli/src/commands/remote.ts b/extensions/cli/src/commands/remote.ts index 919c720fd..040afa1b1 100644 --- a/extensions/cli/src/commands/remote.ts +++ b/extensions/cli/src/commands/remote.ts @@ -21,6 +21,7 @@ type RemoteCommandOptions = { branch?: string; repo?: string; config?: string; + agent?: string; }; type TunnelResponse = { @@ -169,7 +170,7 @@ function buildAgentRequestBody( repoUrl: options.repo ?? getRepoUrl(), name: `devbox-${Date.now()}`, prompt, - agent: options.config, + agent: options.agent, config: options.config, }; diff --git a/extensions/cli/src/configEnhancer.test.ts b/extensions/cli/src/configEnhancer.test.ts deleted file mode 100644 index 75fc33a85..000000000 --- a/extensions/cli/src/configEnhancer.test.ts +++ /dev/null @@ -1,328 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; - -import { BaseCommandOptions } from "./commands/BaseCommandOptions.js"; -import { ConfigEnhancer } from "./configEnhancer.js"; - -// Mock processRule to simulate hub loading -vi.mock("./hubLoader.js", () => ({ - processRule: vi.fn((rule: string) => { - // Simulate hub slug loading - if (rule.includes("/") && !rule.startsWith(".") && !rule.startsWith("/")) { - return Promise.resolve(`Content for ${rule}`); - } - // Return as-is for direct content - return Promise.resolve(rule); - }), - loadPackageFromHub: vi.fn(() => - Promise.resolve({ name: "test", provider: "test" }), - ), - loadPackagesFromHub: vi.fn(() => Promise.resolve([])), - mcpProcessor: {}, - modelProcessor: {}, -})); - -// Mock the service container to provide empty agent file state -vi.mock("./services/ServiceContainer.js", () => ({ - serviceContainer: { - get: vi.fn(() => - Promise.resolve({ - agentFileService: null, - agentFileModelName: null, - agentFile: null, - slug: null, - }), - ), - }, -})); - -vi.mock("./services/types.js", () => ({ - SERVICE_NAMES: { - AGENT_FILE: "agentFile", - }, -})); - -describe("ConfigEnhancer", () => { - let enhancer: ConfigEnhancer; - let mockConfig: any; - - beforeEach(() => { - enhancer = new ConfigEnhancer(); - mockConfig = { - name: "test-config", - version: "1.0.0", - models: [], - mcpServers: [], - } as any; - vi.clearAllMocks(); - }); - - it("should return unchanged config when no enhancements provided", async () => { - const config = await enhancer.enhanceConfig(mockConfig, {}); - - expect(config).toEqual(mockConfig); - }); - - it("should apply rules enhancement", async () => { - const options: BaseCommandOptions = { - rule: ["test-rule"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toEqual(["test-rule"]); - }); - - it("should apply multiple enhancements", async () => { - const options: BaseCommandOptions = { - rule: ["rule1", "rule2"], - mcp: [], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toEqual(["rule1", "rule2"]); - }); - - it("should preserve existing rules when adding new ones", async () => { - mockConfig.rules = ["existing rule"]; - const options: BaseCommandOptions = { - rule: ["new rule"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toEqual(["existing rule", "new rule"]); - }); - - it("should not mutate original config", async () => { - const originalConfig = { ...mockConfig }; - const options: BaseCommandOptions = { - rule: ["test-rule"], - }; - - await enhancer.enhanceConfig(mockConfig, options); - - expect(mockConfig).toEqual(originalConfig); - }); - - it("should preserve hub slug as rule name", async () => { - const options: BaseCommandOptions = { - rule: ["nate/spanish"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toHaveLength(1); - expect(config.rules?.[0]).toEqual({ - name: "nate/spanish", - rule: "Content for nate/spanish", - }); - }); - - it("should handle mix of hub slugs and direct content", async () => { - const options: BaseCommandOptions = { - rule: ["nate/spanish", "Always be helpful", "org/another-rule"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toHaveLength(3); - expect(config.rules?.[0]).toEqual({ - name: "nate/spanish", - rule: "Content for nate/spanish", - }); - expect(config.rules?.[1]).toBe("Always be helpful"); - expect(config.rules?.[2]).toEqual({ - name: "org/another-rule", - rule: "Content for org/another-rule", - }); - }); - - it("should treat file paths as plain strings", async () => { - const options: BaseCommandOptions = { - rule: ["./rules/my-rule.md", "/absolute/path/rule.txt"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.rules).toHaveLength(2); - // File paths should be stored as plain strings - expect(config.rules?.[0]).toBe("./rules/my-rule.md"); - expect(config.rules?.[1]).toBe("/absolute/path/rule.txt"); - }); - - it("should prepend models from --model flag to make them default", async () => { - // Mock loadPackagesFromHub to return test models - const { loadPackagesFromHub } = await import("./hubLoader.js"); - (loadPackagesFromHub as any).mockResolvedValueOnce([ - { name: "GPT-5", provider: "openai", model: "gpt-5" }, - { name: "Claude-3", provider: "anthropic", model: "claude-3" }, - ]); - - // Set up existing models in config - mockConfig.models = [ - { name: "GPT-4", provider: "openai", model: "gpt-4" }, - { name: "Claude-2", provider: "anthropic", model: "claude-2" }, - ]; - - const options: BaseCommandOptions = { - model: ["openai/gpt-5", "anthropic/claude-3"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - // Models from --model flag should be prepended (at the start) - expect(config.models).toHaveLength(4); - expect(config.models?.[0]).toEqual({ - name: "GPT-5", - provider: "openai", - model: "gpt-5", - }); - expect(config.models?.[1]).toEqual({ - name: "Claude-3", - provider: "anthropic", - model: "claude-3", - }); - expect(config.models?.[2]).toEqual({ - name: "GPT-4", - provider: "openai", - model: "gpt-4", - }); - expect(config.models?.[3]).toEqual({ - name: "Claude-2", - provider: "anthropic", - model: "claude-2", - }); - }); - - it("should prepend MCPs from --mcp flag", async () => { - // Mock loadPackageFromHub to return test MCP (singular call for each MCP) - const { loadPackageFromHub } = await import("./hubLoader.js"); - (loadPackageFromHub as any).mockResolvedValueOnce({ - name: "New-MCP", - command: "new-mcp", - }); - - // Set up existing MCPs in config - mockConfig.mcpServers = [{ name: "Existing-MCP", command: "existing-mcp" }]; - - const options: BaseCommandOptions = { - mcp: ["test/new-mcp"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - // MCPs from --mcp flag should be prepended (at the start) - expect(config.mcpServers).toHaveLength(2); - expect(config.mcpServers?.[0]).toEqual({ - name: "New-MCP", - command: "new-mcp", - }); - expect(config.mcpServers?.[1]).toEqual({ - name: "Existing-MCP", - command: "existing-mcp", - }); - }); - - it("should handle URLs in --mcp flag as streamable-http servers", async () => { - // Set up existing MCPs in config - mockConfig.mcpServers = [{ name: "Existing-MCP", command: "existing-mcp" }]; - - const options: BaseCommandOptions = { - mcp: ["https://docs.continue.dev/mcp"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - // URL should be converted to streamable-http MCP configuration - expect(config.mcpServers).toHaveLength(2); - expect(config.mcpServers?.[0]).toEqual({ - name: "docs.continue.dev", - type: "streamable-http", - url: "https://docs.continue.dev/mcp", - }); - expect(config.mcpServers?.[1]).toEqual({ - name: "Existing-MCP", - command: "existing-mcp", - }); - }); - - it("should handle mix of URLs and hub slugs in --mcp flag", async () => { - // Mock loadPackageFromHub to return test MCP for hub slug - const { loadPackageFromHub } = await import("./hubLoader.js"); - (loadPackageFromHub as any).mockResolvedValueOnce({ - name: "Hub-MCP", - command: "hub-mcp", - }); - - const options: BaseCommandOptions = { - mcp: ["https://example.com/mcp", "test/hub-mcp"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.mcpServers).toHaveLength(2); - expect(config.mcpServers?.[0]).toEqual({ - name: "example.com", - type: "streamable-http", - url: "https://example.com/mcp", - }); - expect(config.mcpServers?.[1]).toEqual({ - name: "Hub-MCP", - command: "hub-mcp", - }); - }); - - it("should handle http:// URLs in --mcp flag", async () => { - const options: BaseCommandOptions = { - mcp: ["http://localhost:8080/mcp"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - expect(config.mcpServers).toHaveLength(1); - expect(config.mcpServers?.[0]).toEqual({ - name: "localhost", - type: "streamable-http", - url: "http://localhost:8080/mcp", - }); - }); - - it("should handle agent file integration gracefully when no agent file", async () => { - // The mocked service container returns null agent file state - const options: BaseCommandOptions = { - rule: ["test-rule"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - - // Should work normally when no agent file is active - expect(config.rules).toEqual(["test-rule"]); - }); - - it("should handle agent file integration when agent file is active", async () => { - // Mock service container to return active agent file - const options: BaseCommandOptions = { - rule: ["user-rule"], - prompt: ["user-prompt"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options, { - agentFile: { - name: "Test Agent", - prompt: "You are a test assistant", - rules: "Always be helpful", - model: "gpt-4", - tools: "bash,read", - }, - slug: "owner/test-agent", - agentFileModelName: null, - agentFileService: null, - }); - - // Should have both agent file and user rules - expect(config.rules).toHaveLength(2); - expect(config.rules?.[0]).toBe("Always be helpful"); // Agent file rule first - expect(config.rules?.[1]).toBe("user-rule"); // User rule second - }); -}); diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts deleted file mode 100644 index 106023b75..000000000 --- a/extensions/cli/src/configEnhancer.ts +++ /dev/null @@ -1,248 +0,0 @@ -import { - AssistantUnrolled, - parseAgentFileTools, - Rule, -} from "@continuedev/config-yaml"; - -import { BaseCommandOptions } from "./commands/BaseCommandOptions.js"; -import { - loadPackageFromHub, - loadPackagesFromHub, - mcpProcessor, - modelProcessor, - processRule, -} from "./hubLoader.js"; -import { AgentFileServiceState } from "./services/types.js"; -import { logger } from "./util/logger.js"; - -/** - * Enhances a configuration by injecting additional components from CLI flags - */ -export class ConfigEnhancer { - // added this for lint complexity rule - private async enhanceConfigFromAgentFile( - config: AssistantUnrolled, - _options: BaseCommandOptions | undefined, - agentFileState?: AgentFileServiceState, - ) { - const enhancedConfig = { ...config }; - const options = { ..._options }; - - if (agentFileState?.agentFile) { - const { rules, model, tools, prompt } = agentFileState?.agentFile; - if (rules) { - options.rule = [ - ...rules - .split(",") - .filter(Boolean) - .map((r) => r.trim()), - ...(options.rule || []), - ]; - } - - if (tools) { - try { - const parsedTools = parseAgentFileTools(tools); - if (parsedTools.mcpServers.length > 0) { - options.mcp = [...parsedTools.mcpServers, ...(options.mcp || [])]; - } - } catch (e) { - logger.error("Failed to parse agent file tools", e); - } - } - - // --model takes precedence over agent file model - if (model) { - try { - const agentFileModel = await loadPackageFromHub( - model, - modelProcessor, - ); - enhancedConfig.models = [ - agentFileModel, - ...(enhancedConfig.models ?? []), - ]; - agentFileState?.agentFileService?.setagentFileModelName( - agentFileModel.name, - ); - } catch (e) { - logger.error("Failed to load agent model", e); - } - } - - // Agent file prompt is included as a slash command, initial kickoff is handled elsewhere - if (prompt) { - enhancedConfig.prompts = [ - { - name: `Agent prompt (${agentFileState.agentFile.name})`, - prompt, - description: agentFileState.agentFile.description, - }, - ...(enhancedConfig.prompts ?? []), - ]; - } - } - return { options, enhancedConfig }; - } - /** - * Apply all enhancements to a configuration - */ - async enhanceConfig( - config: AssistantUnrolled, - _options?: BaseCommandOptions, - agentFileState?: AgentFileServiceState, - ): Promise { - const enhanced = await this.enhanceConfigFromAgentFile( - config, - _options, - agentFileState, - ); - let { enhancedConfig } = enhanced; - const { options } = enhanced; - - // Inject resolved items into config - if (options.rule && options.rule.length > 0) { - enhancedConfig = await this.injectRules(enhancedConfig, options.rule); - } - - if (options.mcp && options.mcp.length > 0) { - enhancedConfig = await this.injectMcps(enhancedConfig, options.mcp); - } - - if (options.model && options.model.length > 0) { - enhancedConfig = await this.injectModels(enhancedConfig, options.model); - } - - if (options.prompt && options.prompt.length > 0) { - enhancedConfig = await this.injectPrompts(enhancedConfig, options.prompt); - } - - return enhancedConfig; - } - - /** - * Inject rules into the system message - */ - private async injectRules( - config: AssistantUnrolled, - rules: string[], - ): Promise { - const processedRules: Rule[] = []; - - for (const ruleSpec of rules) { - try { - const processedContent = await processRule(ruleSpec); - - // Check if this is a hub slug (contains / but doesn't start with . or /) - const isHubSlug = - ruleSpec.includes("/") && - !ruleSpec.startsWith(".") && - !ruleSpec.startsWith("/"); - - if (isHubSlug) { - // Store as RuleObject with name (slug) and rule (content) - processedRules.push({ - name: ruleSpec, - rule: processedContent, - }); - } else { - // Store as plain string for file paths or direct content - processedRules.push(processedContent); - } - } catch (error: any) { - logger.warn(`Failed to process rule "${ruleSpec}": ${error.message}`); - } - } - - // Clone the config to avoid mutating the original - const modifiedConfig = { ...config }; - - // Add processed rules to the config's rules array - if (processedRules.length > 0) { - // Combine with existing rules if any - const existingRules = modifiedConfig.rules || []; - modifiedConfig.rules = [...existingRules, ...processedRules]; - } - - return modifiedConfig; - } - - /** - * Inject MCP servers into the configuration - */ - private async injectMcps( - config: AssistantUnrolled, - mcps: string[], - ): Promise { - const processedMcps: any[] = []; - - // Process each MCP spec - check if it's a URL or hub slug - for (const mcpSpec of mcps) { - try { - // Check if it's a URL (starts with http:// or https://) - if (mcpSpec.startsWith("http://") || mcpSpec.startsWith("https://")) { - // Create a streamable-http MCP configuration - processedMcps.push({ - name: new URL(mcpSpec).hostname, - type: "streamable-http", - url: mcpSpec, - }); - } else { - // Otherwise, treat it as a hub slug - const hubMcp = await loadPackageFromHub(mcpSpec, mcpProcessor); - processedMcps.push(hubMcp); - } - } catch (error: any) { - logger.warn(`Failed to load MCP "${mcpSpec}": ${error.message}`); - } - } - - // Clone the config to avoid mutating the original - const modifiedConfig = { ...config }; - - // Prepend processed MCPs to existing mcpServers array for consistency - const existingMcpServers = modifiedConfig.mcpServers || []; - modifiedConfig.mcpServers = [...processedMcps, ...existingMcpServers]; - - return modifiedConfig; - } - - /** - * Inject models into the configuration - */ - private async injectModels( - config: AssistantUnrolled, - models: string[], - ): Promise { - const processedModels = await loadPackagesFromHub(models, modelProcessor); - - const modifiedConfig = { ...config }; - - // Prepend processed models to existing models array so they become the default - const existingModels = modifiedConfig.models || []; - modifiedConfig.models = [...processedModels, ...existingModels]; - - return modifiedConfig; - } - - /** - * Inject prompts into the configuration - * Note: Prompts are processed at runtime via processAndCombinePrompts(), - * not injected into the config. This method exists for consistency with - * other injection methods but doesn't modify the config. - */ - private async injectPrompts( - config: AssistantUnrolled, - prompts: string[], - ): Promise { - // Prompts are handled at runtime by processAndCombinePrompts in chat.ts - // They don't need to be injected into the configuration - logger.debug("Prompts will be processed at runtime", { prompts }); - return config; - } -} - -/** - * Global config enhancer instance - */ -export const configEnhancer = new ConfigEnhancer(); diff --git a/extensions/cli/src/configLoader.ts b/extensions/cli/src/configLoader.ts index 423875312..c3ccd6296 100644 --- a/extensions/cli/src/configLoader.ts +++ b/extensions/cli/src/configLoader.ts @@ -4,9 +4,11 @@ import * as path from "path"; import { AssistantUnrolled, + mergeUnrolledAssistants, PackageIdentifier, RegistryClient, unrollAssistant, + unrollAssistantFromContent, } from "@continuedev/config-yaml"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; @@ -18,7 +20,6 @@ import { getConfigUri, getOrganizationId, isEnvironmentAuthConfig, - loadAuthConfig, updateConfigUri, } from "./auth/workos.js"; import { CLIPlatformClient } from "./CLIPlatformClient.js"; @@ -34,7 +35,8 @@ export type ConfigSource = | { type: "saved-uri"; uri: string } | { type: "user-assistant"; slug: string } | { type: "default-config-yaml" } - | { type: "default-agent" }; + | { type: "default-agent" } + | { type: "no-config" }; /** * Streamlined configuration loader that implements the specification @@ -44,12 +46,18 @@ export async function loadConfiguration( authConfig: AuthConfig, cliConfigPath: string | undefined, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], + isHeadless: boolean | undefined, ): Promise { const organizationId = getOrganizationId(authConfig); const accessToken = getAccessToken(authConfig); // Step 1: Determine config source using precedence rules - const configSource = determineConfigSource(authConfig, cliConfigPath); + const configSource = determineConfigSource( + authConfig, + cliConfigPath, + isHeadless, + ); // Step 2: Load configuration from the determined source const config = await loadFromSource( @@ -57,6 +65,7 @@ export async function loadConfiguration( accessToken, organizationId ?? null, apiClient, + injectBlocks, ); // Step 3: Save config URI for session continuity (only for file-based auth) @@ -79,12 +88,18 @@ export async function loadConfiguration( function determineConfigSource( authConfig: AuthConfig, cliConfigPath: string | undefined, + isHeadless: boolean | undefined, ): ConfigSource { // Priority 1: CLI --config flag if (cliConfigPath) { return { type: "cli-flag", path: cliConfigPath }; } + // In headless, config fallback behavior isn't supported + if (isHeadless) { + return { type: "no-config" }; + } + // Priority 2: Saved config URI (only for file-based auth) if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) { const savedUri = getConfigUri(authConfig); @@ -115,6 +130,7 @@ async function loadFromSource( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { try { switch (source.type) { @@ -124,6 +140,7 @@ async function loadFromSource( accessToken, organizationId, apiClient, + injectBlocks, ); case "saved-uri": @@ -132,20 +149,38 @@ async function loadFromSource( accessToken, organizationId, apiClient, + injectBlocks, ); case "user-assistant": - return await loadUserAssistantWithFallback(organizationId, apiClient); + return await loadUserAssistantWithFallback( + organizationId, + apiClient, + accessToken, + injectBlocks, + ); case "default-config-yaml": return await loadDefaultConfigYaml( accessToken, organizationId, apiClient, + injectBlocks, ); case "default-agent": - return await loadDefaultAgent(organizationId, apiClient); + return await loadDefaultAgent( + organizationId, + apiClient, + accessToken, + injectBlocks, + ); + + case "no-config": + return { + name: "No Config Specified", + version: "1.0.0", + }; default: throw new Error(`Unknown config source type: ${(source as any).type}`); @@ -158,7 +193,12 @@ async function loadFromSource( "Failed to load user assistants, falling back to default agent", ), ); - return await loadDefaultAgent(organizationId, apiClient); + return await loadDefaultAgent( + organizationId, + apiClient, + accessToken, + injectBlocks, + ); } throw error; } @@ -173,6 +213,7 @@ async function loadFromCliFlag( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { if (isFilePath(configPath)) { // Load local YAML file @@ -181,10 +222,17 @@ async function loadFromCliFlag( accessToken, organizationId, apiClient, + injectBlocks, ); } else { // Load assistant slug - return await loadAssistantSlug(configPath, organizationId, apiClient); + return await loadAssistantSlug( + configPath, + accessToken, + organizationId, + apiClient, + injectBlocks, + ); } } @@ -196,6 +244,7 @@ async function loadFromSavedUri( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { const filePath = uriToPath(uri); if (filePath) { @@ -204,12 +253,19 @@ async function loadFromSavedUri( accessToken, organizationId, apiClient, + injectBlocks, ); } const slug = uriToSlug(uri); if (slug) { - return await loadAssistantSlug(slug, organizationId, apiClient); + return await loadAssistantSlug( + slug, + accessToken, + organizationId, + apiClient, + injectBlocks, + ); } throw new Error(`Invalid saved config URI: ${uri}`); @@ -221,6 +277,8 @@ async function loadFromSavedUri( async function loadUserAssistantWithFallback( organizationId: string | null, apiClient: DefaultApiInterface, + accessToken: string | null, + injectBlocks: PackageIdentifier[], ): Promise { const assistants = await apiClient.listAssistants({ alwaysUseProxy: "false", @@ -240,12 +298,29 @@ async function loadUserAssistantWithFallback( "Failed to load assistant.", ); } + let apiConfig = result.config as AssistantUnrolled; + if (injectBlocks.length > 0) { + const injectedConfig = await unrollPackageIdentifiersAsConfigYaml( + injectBlocks, + accessToken, + organizationId, + apiClient, + ); + if (injectedConfig?.block) { + apiConfig = mergeUnrolledAssistants(apiConfig, injectedConfig.block); + } + } - return result.config as AssistantUnrolled; + return apiConfig; } // No user assistants, fall back to default agent - return await loadDefaultAgent(organizationId, apiClient); + return await loadDefaultAgent( + organizationId, + apiClient, + accessToken, + injectBlocks, + ); } /** @@ -255,6 +330,7 @@ async function loadDefaultConfigYaml( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { const defaultConfigPath = path.join(env.continueHome, "config.yaml"); return await loadConfigYaml( @@ -262,6 +338,7 @@ async function loadDefaultConfigYaml( accessToken, organizationId, apiClient, + injectBlocks, ); } @@ -271,6 +348,8 @@ async function loadDefaultConfigYaml( async function loadDefaultAgent( organizationId: string | null, apiClient: DefaultApiInterface, + accessToken: string | null, + injectBlocks: PackageIdentifier[], ): Promise { const resp = await apiClient.getAssistant({ ownerSlug: "continuedev", @@ -281,18 +360,66 @@ async function loadDefaultAgent( if (!resp.configResult.config) { throw new Error("Failed to load default agent."); } + let apiConfig = resp.configResult.config as AssistantUnrolled; + if (injectBlocks.length > 0) { + const injectedConfig = await unrollPackageIdentifiersAsConfigYaml( + injectBlocks, + accessToken, + organizationId, + apiClient, + ); + if (injectedConfig?.block) { + apiConfig = mergeUnrolledAssistants(apiConfig, injectedConfig.block); + } + } - return resp.configResult.config as AssistantUnrolled; + return apiConfig; +} + +export async function unrollPackageIdentifiersAsConfigYaml( + packageIdentifiers: PackageIdentifier[], + accessToken: string | null, + organizationId: string | null, + apiClient: DefaultApiInterface, +): Promise<{ block: AssistantUnrolled | undefined } | null> { + const unrollResult = await unrollAssistantFromContent( + { + uriType: "file", + fileUri: "", + }, + "name: FILLER\nschema: v1\nversion: 0.0.1", + new RegistryClient({ + accessToken: accessToken ?? undefined, + apiBase: env.apiBase, + rootPath: undefined, // TODO verify this doesn't cause issues with file blocks + }), + { + currentUserSlug: "", + onPremProxyUrl: null, + orgScopeId: organizationId, + platformClient: new CLIPlatformClient(organizationId, apiClient), + renderSecrets: true, + injectBlocks: packageIdentifiers, + }, + ); + if (!unrollResult?.config) { + const fatalError = unrollResult.errors?.find((e) => e.fatal); + if (fatalError) { + throw new Error(`Error(s) unrolling package: ${fatalError.message}`); + } + } + + return { + block: unrollResult?.config, + }; } -/** - * Common function to unroll an assistant with consistent configuration - */ async function unrollAssistantWithConfig( packageIdentifier: PackageIdentifier, accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { const unrollResult = await unrollAssistant( packageIdentifier, @@ -311,7 +438,7 @@ async function unrollAssistantWithConfig( renderSecrets: true, platformClient: new CLIPlatformClient(organizationId, apiClient), onPremProxyUrl: null, - injectBlocks: [], + injectBlocks, }, ); @@ -337,12 +464,14 @@ async function loadConfigYaml( accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { return await unrollAssistantWithConfig( { fileUri: filePath, uriType: "file" }, accessToken, organizationId, apiClient, + injectBlocks, ); } @@ -351,8 +480,10 @@ async function loadConfigYaml( */ async function loadAssistantSlug( slug: string, + accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, + injectBlocks: PackageIdentifier[], ): Promise { const [ownerSlug, packageSlug] = slug.split("/"); if (!ownerSlug || !packageSlug) { @@ -360,7 +491,6 @@ async function loadAssistantSlug( `Invalid assistant slug format. Expected "owner/package", got: ${slug}`, ); } - // Unroll locally if not logged in if (!(apiClient as any).configuration.accessToken) { return await unrollAssistantWithConfig( @@ -368,9 +498,10 @@ async function loadAssistantSlug( uriType: "slug", fullSlug: { ownerSlug, packageSlug, versionSlug: "latest" }, }, - getAccessToken(loadAuthConfig()), + accessToken ?? null, organizationId, apiClient, + injectBlocks, ); } @@ -389,8 +520,20 @@ async function loadAssistantSlug( "Failed to load assistant.", ); } + let apiConfig = result.config as AssistantUnrolled; + if (injectBlocks.length > 0) { + const injectedConfig = await unrollPackageIdentifiersAsConfigYaml( + injectBlocks, + accessToken, + organizationId, + apiClient, + ); + if (injectedConfig?.block) { + apiConfig = mergeUnrolledAssistants(apiConfig, injectedConfig.block); + } + } - return result.config as AssistantUnrolled; + return apiConfig; } /** diff --git a/extensions/cli/src/hubLoader.ts b/extensions/cli/src/hubLoader.ts index 3e7bf384a..412f80208 100644 --- a/extensions/cli/src/hubLoader.ts +++ b/extensions/cli/src/hubLoader.ts @@ -1,4 +1,8 @@ -import { AgentFile, parseAgentFile } from "@continuedev/config-yaml"; +import { + AgentFile, + ModelConfig, + parseAgentFile, +} from "@continuedev/config-yaml"; import JSZip from "jszip"; import { getAccessToken, loadAuthConfig } from "./auth/workos.js"; @@ -8,7 +12,7 @@ import { logger } from "./util/logger.js"; /** * Pattern to match valid hub slugs (owner/package format) */ -const HUB_SLUG_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; +export const HUB_SLUG_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; /** * Hub package type definitions @@ -66,7 +70,7 @@ export const mcpProcessor: HubPackageProcessor = { /** * Model processor - handles JSON/YAML configuration files */ -export const modelProcessor: HubPackageProcessor = { +export const modelProcessor: HubPackageProcessor = { type: "model", expectedFileExtensions: [".json", ".yaml", ".yml"], parseContent: async (content: string, filename: string) => { @@ -241,9 +245,6 @@ export const loadMcpFromHub = (slug: string) => export const loadModelFromHub = (slug: string) => loadPackageFromHub(slug, modelProcessor); -export const loadPromptFromHub = (slug: string) => - loadPackageFromHub(slug, promptProcessor); - /** * Process a rule specification - supports file paths, hub slugs, or direct content */ @@ -297,6 +298,22 @@ export async function processRule(ruleSpec: string): Promise { return ruleSpec; } +export function isStringRule(rule: string) { + if (rule.includes(" ") || rule.includes("\n")) { + return true; + } + if ( + ["file:/", ".", "/", "~"].some((prefix) => rule.startsWith(prefix)) || + rule.includes("\\") + ) { + return false; + } + if (HUB_SLUG_PATTERN.test(rule)) { + return false; + } + return true; +} + /** * Batch load multiple packages with error handling */ diff --git a/extensions/cli/src/integration/rule-duplication.test.ts b/extensions/cli/src/integration/rule-duplication.test.ts index d58d11df3..3a713170d 100644 --- a/extensions/cli/src/integration/rule-duplication.test.ts +++ b/extensions/cli/src/integration/rule-duplication.test.ts @@ -1,125 +1,130 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; -import { describe, expect, it, vi } from "vitest"; +import { decodePackageIdentifier } from "@continuedev/config-yaml"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { isStringRule } from "src/hubLoader.js"; import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; -import { ConfigEnhancer } from "../configEnhancer.js"; +import { ConfigService } from "../services/ConfigService.js"; -// Mock the processRule function to avoid network calls -vi.mock("../hubLoader.js", () => ({ - processRule: vi.fn((rule: string) => { - // Simulate hub slug loading - return content for hub slugs - if (rule.includes("/") && !rule.startsWith(".") && !rule.startsWith("/")) { - return Promise.resolve(`Content for ${rule}`); - } - // Return as-is for direct content - return Promise.resolve(rule); - }), - loadPackagesFromHub: vi.fn(() => Promise.resolve([])), - mcpProcessor: {}, - modelProcessor: {}, +// Mock the required functions - need to match the import path used by ConfigService +vi.mock("src/hubLoader.js", () => ({ + isStringRule: vi.fn(), })); -// Mock the service container to provide empty agent file state -vi.mock("../services/ServiceContainer.js", () => ({ - serviceContainer: { - get: vi.fn(() => - Promise.resolve({ - agentFile: null, - slug: null, - }), - ), - }, +vi.mock("@continuedev/config-yaml", async (importOriginal) => ({ + ...(await importOriginal()), + decodePackageIdentifier: vi.fn((id) => ({ + type: "slug" as const, + slug: id, + version: undefined, + })), })); -vi.mock("../services/types.js", () => ({ - SERVICE_NAMES: { - AGENT_FILE: "agentFile", +vi.mock("../configLoader.js", () => ({ + loadConfiguration: vi.fn(), +})); + +vi.mock("../auth/workos.js", () => ({ + loadAuthConfig: vi.fn(), +})); + +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + warn: vi.fn(), }, })); describe("Rule duplication integration test", () => { - it("should not duplicate rules when using --rule flag", async () => { - const enhancer = new ConfigEnhancer(); + let configService: ConfigService; - // Initial config without any rules - const initialConfig: AssistantUnrolled = { - name: "Test Assistant", - rules: [], - } as any; + beforeEach(() => { + vi.clearAllMocks(); + configService = new ConfigService(); + + // Reset mocks to their default behavior + vi.mocked(decodePackageIdentifier).mockImplementation((id) => ({ + uriType: "slug", + fullSlug: { + ownerSlug: "owner", + packageSlug: "package", + versionSlug: "version", + }, + })); + + // Reset isStringRule mock + vi.mocked(isStringRule).mockImplementation((rule: string) => { + // Default implementation - string rules contain spaces/newlines or are local paths + return ( + rule.includes(" ") || + rule.includes("\n") || + rule.startsWith(".") || + rule.startsWith("/") || + !rule.includes("/") + ); + }); + }); + + it("should not duplicate rules when using --rule flag", () => { + // Setup mocks + vi.mocked(isStringRule).mockReturnValue(false); // "nate/spanish" is a package identifier // Simulate command-line options with --rule flag const options: BaseCommandOptions = { rule: ["nate/spanish"], }; - // Enhance config with command-line rules - const enhancedConfig = await enhancer.enhanceConfig(initialConfig, options); + // Process the options through the config service + const { injected, additional } = + configService.getAdditionalBlocksFromOptions(options, undefined); - // Verify the rule was added exactly once as a RuleObject - expect(enhancedConfig.rules).toHaveLength(1); - expect(enhancedConfig.rules).toEqual([ - { name: "nate/spanish", rule: "Content for nate/spanish" }, - ]); + // The rule should be processed as a package identifier + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "nate/spanish", + ); + expect(injected).toHaveLength(1); + expect(additional.rules).toHaveLength(0); // Package identifier rules go into injected }); - it("should merge command-line rules with existing config rules", async () => { - const enhancer = new ConfigEnhancer(); - - // Initial config with existing rules - const initialConfig: AssistantUnrolled = { - name: "Test Assistant", - rules: ["existing-rule"], - } as any; + it("should merge command-line rules with existing config rules", () => { + // Setup mocks for different rule types + vi.mocked(isStringRule) + .mockReturnValueOnce(false) // "nate/spanish" is a package identifier + .mockReturnValueOnce(true); // "direct-rule" is a string rule // Simulate command-line options with --rule flag const options: BaseCommandOptions = { rule: ["nate/spanish", "direct-rule"], }; - // Enhance config with command-line rules - const enhancedConfig = await enhancer.enhanceConfig(initialConfig, options); + // Process the options through the config service + const { injected, additional } = + configService.getAdditionalBlocksFromOptions(options, undefined); - // Verify all rules are present without duplication - expect(enhancedConfig.rules).toHaveLength(3); - expect(enhancedConfig.rules).toEqual([ - "existing-rule", - { name: "nate/spanish", rule: "Content for nate/spanish" }, - "direct-rule", - ]); + // "nate/spanish" should be a package identifier, "direct-rule" should be a string rule + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "nate/spanish", + ); + expect(injected).toHaveLength(1); // nate/spanish + expect(additional.rules).toEqual(["direct-rule"]); // direct-rule as string }); - it("should handle rule content with frontmatter", async () => { - const enhancer = new ConfigEnhancer(); - - // Mock processRule to return content with frontmatter - const { processRule } = await import("../hubLoader.js"); - (processRule as any).mockImplementation((rule: string) => { - if (rule === "nate/spanish") { - return Promise.resolve(`--- -alwaysApply: true ---- - -Always respond in Spanish.`); - } - return Promise.resolve(rule); - }); - - const initialConfig: AssistantUnrolled = { - name: "Test Assistant", - rules: [], - } as any; + it("should process package identifiers for hub rules", () => { + // Setup mock - all rules are package identifiers + vi.mocked(isStringRule).mockReturnValue(false); const options: BaseCommandOptions = { rule: ["nate/spanish"], }; - const enhancedConfig = await enhancer.enhanceConfig(initialConfig, options); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions(options, undefined); - // Hub rules should be stored as RuleObject with name and content - expect(enhancedConfig.rules).toHaveLength(1); - const ruleObj = enhancedConfig.rules?.[0] as any; - expect(ruleObj.name).toBe("nate/spanish"); - expect(ruleObj.rule).toContain("Always respond in Spanish."); - expect(ruleObj.rule).toContain("alwaysApply: true"); + // Hub rules should be processed as package identifiers, not string rules + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "nate/spanish", + ); + expect(injected).toHaveLength(1); + expect(additional.rules).toHaveLength(0); // Package identifier rules don't go into additional.rules }); }); diff --git a/extensions/cli/src/onboarding.ts b/extensions/cli/src/onboarding.ts index fe090ed1a..2a8162284 100644 --- a/extensions/cli/src/onboarding.ts +++ b/extensions/cli/src/onboarding.ts @@ -148,6 +148,8 @@ export async function initializeWithOnboarding( authConfig, configPath, getApiClient(authConfig?.accessToken), + [], + false, ); } catch (errorMessage) { throw new Error( diff --git a/extensions/cli/src/services/AgentFileService.test.ts b/extensions/cli/src/services/AgentFileService.test.ts index 13e1eb9bd..1100095c1 100644 --- a/extensions/cli/src/services/AgentFileService.test.ts +++ b/extensions/cli/src/services/AgentFileService.test.ts @@ -1,13 +1,19 @@ -import { Mock, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; -import { agentFileProcessor } from "../hubLoader.js"; - -import { AgentFileService } from "./AgentFileService.js"; +import { + AgentFileService, + EMPTY_AGENT_FILE_STATE, +} from "./AgentFileService.js"; // Mock the hubLoader module vi.mock("../hubLoader.js", () => ({ loadPackageFromHub: vi.fn(), - HubPackageProcessor: vi.fn(), + loadPackagesFromHub: vi.fn(), + loadModelFromHub: vi.fn(), + mcpProcessor: {}, + modelProcessor: {}, + processRule: vi.fn(), + isStringRule: vi.fn(), agentFileProcessor: { type: "agentFile", expectedFileExtensions: [".md"], @@ -25,268 +31,401 @@ vi.mock("../util/logger.js", () => ({ }, })); +// Mock config module +vi.mock("../config.js", () => ({ + createLlmApi: vi.fn(), + getLlmApi: vi.fn(), +})); + +// Mock auth module +vi.mock("../auth/workos.js", () => ({ + getModelName: vi.fn(), + loadAuthConfig: vi.fn(), +})); + +// Mock the config-yaml package +vi.mock("@continuedev/config-yaml", async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + }; +}); + +// Mock service container +vi.mock("./ServiceContainer.js", () => ({ + serviceContainer: { + get: vi.fn(), + set: vi.fn(), + reload: vi.fn(), + }, +})); + describe("AgentFileService", () => { - let service: AgentFileService; + let agentFileService: AgentFileService; let mockLoadPackageFromHub: any; + let mockLoadModelFromHub: any; + + const mockAgentFile = { + name: "Test Agent File", + description: "A test agent for integration testing", + model: "gpt-4-agent", + tools: "bash,read,write", + rules: "Always be helpful and concise", + prompt: "You are an assistant.", + }; + + const mockAssistant = { + models: [ + { + provider: "openai", + name: "gpt-3.5-turbo", + roles: ["chat"], + }, + { + provider: "openai", + name: "gpt-4", + roles: ["chat"], + }, + ], + }; + + const mockAuthConfig = { + apiKey: "test-key", + }; beforeEach(async () => { vi.clearAllMocks(); - service = new AgentFileService(); - // Get the mock function + // Get mock functions const hubLoaderModule = await import("../hubLoader.js"); mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any; + mockLoadModelFromHub = hubLoaderModule.loadModelFromHub as any; + + // Create service instance + agentFileService = new AgentFileService(); + + // Setup default mocks + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + mockLoadModelFromHub.mockResolvedValue({ + name: "gpt-4-agent", + provider: "openai", + }); }); describe("initialization", () => { - it("should initialize with inactive state when no agent file provided", async () => { - const state = await service.initialize(); - - expect(state).toEqual({ - agentFile: null, - slug: null, - agentFileModelName: null, - agentFileService: service, - }); - }); - - it("should initialize with inactive state when agent slug is empty string", async () => { - const state = await service.initialize(""); - - expect(state).toEqual({ - agentFile: null, - slug: null, - agentFileModelName: null, - agentFileService: service, - }); - }); - - it("should reject invalid agent slug format", async () => { - const state = await service.initialize("invalid-slug"); - - expect(state).toEqual({ - agentFile: null, - slug: null, - agentFileModelName: null, - agentFileService: service, - }); - - // Should not call loadPackageFromHub with invalid slug - expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); - }); - - it("should reject agent slug with too many parts", async () => { - const state = await service.initialize("owner/package/extra"); - - expect(state).toEqual({ - agentFile: null, - slug: null, - agentFileModelName: null, - agentFileService: service, - }); - - expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); - }); - - it("should load valid agent file successfully", async () => { - const mockAgentFile = { - name: "Test Agent", - description: "A test agent", - model: "gpt-4", - tools: "bash,read,write", - rules: "Be helpful", - prompt: "You are a helpful assistant.", + it("should initialize with empty state when no agent slug provided", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + const result = await agentFileService.initialize( + undefined, + authServiceState, + apiClientState, + ); - const state = await service.initialize("owner/package"); + expect(result).toEqual(EMPTY_AGENT_FILE_STATE); + expect(agentFileService.getState()).toEqual(EMPTY_AGENT_FILE_STATE); + expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); + }); - expect(state).toEqual({ - agentFile: mockAgentFile, - slug: "owner/package", - agentFileModelName: null, - agentFileService: service, - }); + it("should load and parse agent file when slug is provided", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); expect(mockLoadPackageFromHub).toHaveBeenCalledWith( - "owner/package", - agentFileProcessor, + "owner/agent", + expect.objectContaining({ + type: "agentFile", + expectedFileExtensions: [".md"], + }), ); + + const state = agentFileService.getState(); + expect(state.agentFile).toEqual(mockAgentFile); + expect(state.slug).toBe("owner/agent"); }); - it("should handle loading errors gracefully", async () => { + it("should load agent file model when model is specified", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + expect(mockLoadModelFromHub).toHaveBeenCalledWith("gpt-4-agent"); + + const state = agentFileService.getState(); + expect(state.agentFileModel).toEqual({ + name: "gpt-4-agent", + provider: "openai", + }); + }); + }); + + describe("rules parsing", () => { + it("should parse rules when agent file has rules", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.parsedRules).toBeDefined(); + expect(state.parsedRules).toEqual(["Always be helpful and concise"]); + }); + + it("should not parse rules when agent file has no rules", async () => { + const agentFileWithoutRules = { ...mockAgentFile, rules: undefined }; + mockLoadPackageFromHub.mockResolvedValue(agentFileWithoutRules); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.parsedRules).toBeNull(); + }); + }); + + describe("tools parsing", () => { + it("should parse tools when agent file has tools", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.parsedTools).toBeDefined(); + expect(state.parsedTools?.mcpServers).toBeDefined(); + expect(Array.isArray(state.parsedTools?.mcpServers)).toBe(true); + }); + + it("should not parse tools when agent file has no tools", async () => { + const agentFileWithoutTools = { ...mockAgentFile, tools: undefined }; + mockLoadPackageFromHub.mockResolvedValue(agentFileWithoutTools); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.parsedTools).toBeNull(); + }); + }); + + describe("model loading", () => { + it("should not load model when agent file has no model", async () => { + const agentFileWithoutModel = { ...mockAgentFile, model: undefined }; + mockLoadPackageFromHub.mockResolvedValue(agentFileWithoutModel); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + expect(mockLoadModelFromHub).not.toHaveBeenCalled(); + + const state = agentFileService.getState(); + expect(state.agentFileModel).toBeNull(); + }); + + it("should throw error when API client is not available for model loading", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: null }; + + await expect( + agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ), + ).rejects.toThrow( + "Cannot load agent model, failed to load api client service", + ); + }); + }); + + describe("error handling", () => { + it("should throw error when agent loading fails", async () => { mockLoadPackageFromHub.mockRejectedValue(new Error("Network error")); - const state = await service.initialize("owner/package"); + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - expect(state).toEqual({ - agentFile: null, - slug: null, - agentFileModelName: null, - agentFileService: service, - }); + await expect( + agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ), + ).rejects.toThrow("Network error"); - expect(mockLoadPackageFromHub).toHaveBeenCalledWith( - "owner/package", - agentFileProcessor, + const state = agentFileService.getState(); + expect(state.agentFile).toBeNull(); + }); + + it("should throw error for invalid agent slug format", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await expect( + agentFileService.initialize( + "invalid-slug", + authServiceState, + apiClientState, + ), + ).rejects.toThrow( + 'Invalid agent slug format. Expected "owner/package", got: invalid-slug', ); }); - it("should handle minimal agent file", async () => { - const mockAgentFile = { - name: "Minimal Agent File", - prompt: "", + it("should throw error when model loading fails", async () => { + mockLoadModelFromHub.mockRejectedValue(new Error("Model load error")); + + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + await expect( + agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ), + ).rejects.toThrow("Model load error"); + }); + }); - const state = await service.initialize("owner/minimal"); + describe("state management", () => { + it("should return correct state after initialization", async () => { + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - expect(state).toEqual({ - agentFile: mockAgentFile, - slug: "owner/minimal", - agentFileModelName: null, - agentFileService: service, + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + const state = agentFileService.getState(); + expect(state.agentFile).toEqual(mockAgentFile); + expect(state.slug).toBe("owner/agent"); + expect(state.parsedRules).toEqual(["Always be helpful and concise"]); + expect(state.parsedTools?.mcpServers).toBeDefined(); + expect(Array.isArray(state.parsedTools?.mcpServers)).toBe(true); + expect(state.agentFileModel).toEqual({ + name: "gpt-4-agent", + provider: "openai", }); }); + + it("should have correct dependencies", () => { + const dependencies = agentFileService.getDependencies(); + expect(dependencies).toEqual(["auth", "apiClient"]); + }); }); - describe("state getters", () => { - beforeEach(async () => { - const mockAgentFile = { - name: "Test Agent", - description: "A test Agent", - model: "gpt-4", - tools: "bash,read,write", - rules: "Be helpful", - prompt: "You are a helpful assistant.", + describe("partial data handling", () => { + it("should handle agent file with missing optional properties", async () => { + const partialAgentFile = { + name: "Partial Agent File", + model: "gpt-3.5-turbo", + prompt: "Partial prompt", + // No tools or rules }; - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await service.initialize("owner/package"); - }); + mockLoadPackageFromHub.mockResolvedValue(partialAgentFile); - it("should return agent file state", () => { - const state = service.getState(); - expect(state.agentFile?.name).toBe("Test Agent"); - expect(state.slug).toBe("owner/package"); - expect(state.agentFile?.model).toBe("gpt-4"); - expect(state.agentFile?.tools).toBe("bash,read,write"); - expect(state.agentFile?.rules).toBe("Be helpful"); - expect(state.agentFile?.prompt).toBe("You are a helpful assistant."); - }); - }); - - describe("inactive agent file state", () => { - beforeEach(() => { - service.initialize(); - }); - - it("should return inactive state when no agent file", () => { - const state = service.getState(); - expect(state.agentFile).toBeNull(); - expect(state.slug).toBeNull(); - }); - }); - - describe("partial agent file data", () => { - it("should handle agent file with only name and prompt", async () => { - const mockAgentFile = { - name: "Simple Agent", - prompt: "Simple prompt", + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await service.initialize("owner/simple"); + await agentFileService.initialize( + "owner/partial", + authServiceState, + apiClientState, + ); - const state = service.getState(); - expect(state.agentFile?.model).toBeUndefined(); + const state = agentFileService.getState(); + expect(state.agentFile?.name).toBe("Partial Agent File"); + expect(state.agentFile?.model).toBe("gpt-3.5-turbo"); + expect(state.agentFile?.prompt).toBe("Partial prompt"); expect(state.agentFile?.tools).toBeUndefined(); expect(state.agentFile?.rules).toBeUndefined(); - expect(state.agentFile?.prompt).toBe("Simple prompt"); - }); - - it("should handle agent file with empty prompt", async () => { - const mockAgentFile = { - name: "Empty Prompt Agent", - model: "gpt-3.5-turbo", - prompt: "", - }; - - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await service.initialize("owner/empty"); - - const state = service.getState(); - expect(state.agentFile?.model).toBe("gpt-3.5-turbo"); - expect(state.agentFile?.prompt).toBe(""); + expect(state.parsedRules).toBeNull(); + expect(state.parsedTools).toBeNull(); }); }); }); - -describe("agentFileProcessor", () => { - it("should have correct type and extensions", () => { - expect(agentFileProcessor.type).toBe("agentFile"); - expect(agentFileProcessor.expectedFileExtensions).toEqual([".md"]); - }); - - it("should parse agent file content correctly", () => { - const content = `--- -name: Test Agent -model: gpt-4 -tools: bash,read ---- -You are a helpful assistant.`; - - // Set up the mock to return expected result - const expectedResult = { - name: "Test Agent", - model: "gpt-4", - tools: "bash,read", - prompt: "You are a helpful assistant.", - }; - (agentFileProcessor.parseContent as Mock).mockReturnValue(expectedResult); - - const result = agentFileProcessor.parseContent(content, "test.md"); - expect(result).toEqual({ - name: "Test Agent", - model: "gpt-4", - tools: "bash,read", - prompt: "You are a helpful assistant.", - }); - }); - - it("should validate agent file content", () => { - const validAgentFile = { - name: "Valid Agent", - prompt: "Test prompt", - }; - - const invalidAgentFile = { - prompt: "Test prompt", - // Missing name - }; - - // Set up mock validation responses - (agentFileProcessor.validateContent as Mock) - .mockReturnValueOnce(true) // For valid agent file - .mockReturnValueOnce(false); // For invalid agent file - - expect(agentFileProcessor.validateContent?.(validAgentFile)).toBe(true); - expect(agentFileProcessor.validateContent?.(invalidAgentFile as any)).toBe( - false, - ); - }); - - it("should validate agent file with empty name as invalid", () => { - const invalidAgentFile = { - name: "", - prompt: "Test prompt", - }; - - // Mock validation to return false for empty name - (agentFileProcessor.validateContent as Mock).mockReturnValue(false); - - expect(agentFileProcessor.validateContent?.(invalidAgentFile)).toBe(false); - }); -}); diff --git a/extensions/cli/src/services/AgentFileService.ts b/extensions/cli/src/services/AgentFileService.ts index 8220e34f5..81dd0e4df 100644 --- a/extensions/cli/src/services/AgentFileService.ts +++ b/extensions/cli/src/services/AgentFileService.ts @@ -1,43 +1,60 @@ -import { agentFileProcessor, loadPackageFromHub } from "../hubLoader.js"; +import { + parseAgentFileRules, + parseAgentFileTools, +} from "@continuedev/config-yaml"; + +import { + agentFileProcessor, + loadModelFromHub, + loadPackageFromHub, +} from "../hubLoader.js"; import { logger } from "../util/logger.js"; -import { BaseService } from "./BaseService.js"; +import { BaseService, ServiceWithDependencies } from "./BaseService.js"; import { serviceContainer } from "./ServiceContainer.js"; -import { AgentFileServiceState } from "./types.js"; +import { + AgentFileServiceState, + ApiClientServiceState, + AuthServiceState, + SERVICE_NAMES, +} from "./types.js"; +export const EMPTY_AGENT_FILE_STATE: AgentFileServiceState = { + agentFile: null, + slug: null, + parsedRules: null, + parsedTools: null, + agentFileModel: null, +}; /** * Service for managing agent file state * Loads agent files from the hub and extracts model, tools, and prompt information */ -export class AgentFileService extends BaseService { - /** - * Set the resolved agent file model name after it's been processed - * Called by ConfigEnhancer after resolving the model slug - */ - setagentFileModelName(modelName: string): void { - this.setState({ - agentFileModelName: modelName, - }); - } +export class AgentFileService + extends BaseService + implements ServiceWithDependencies +{ constructor() { super("AgentFileService", { - agentFileService: null, - agentFile: null, - slug: null, - agentFileModelName: null, + ...EMPTY_AGENT_FILE_STATE, }); } + getDependencies(): string[] { + return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT]; + } + /** * Initialize the agent file service with a hub slug */ - async doInitialize(agentFileSlug?: string): Promise { + async doInitialize( + agentFileSlug: string | undefined, + authServiceState: AuthServiceState, + apiClientState: ApiClientServiceState, + ): Promise { if (!agentFileSlug) { return { - agentFileService: this, - agentFile: null, - slug: null, - agentFileModelName: null, + ...EMPTY_AGENT_FILE_STATE, }; } @@ -54,20 +71,40 @@ export class AgentFileService extends BaseService { agentFileProcessor, ); - return { - agentFileService: this, + // Set the basic agent file state + this.setState({ agentFile, slug: agentFileSlug, - agentFileModelName: null, // Will be set by ConfigEnhancer after model resolution - }; + }); + + if (agentFile.model) { + if (!apiClientState.apiClient) { + throw new Error( + "Cannot load agent model, failed to load api client service", + ); + } + const model = await loadModelFromHub(agentFile.model); + this.setState({ + agentFileModel: model, + }); + } + + if (agentFile.rules) { + this.setState({ + parsedRules: parseAgentFileRules(agentFile.rules), + }); + } + + if (agentFile.tools) { + this.setState({ + parsedTools: parseAgentFileTools(agentFile.tools), + }); + } + + return this.getState(); } catch (error: any) { logger.error("Failed to initialize AgentFileService:", error); - return { - agentFileService: this, - agentFile: null, - slug: null, - agentFileModelName: null, - }; + throw error; } } diff --git a/extensions/cli/src/services/AuthService.refactored.ts b/extensions/cli/src/services/AuthService.refactored.ts deleted file mode 100644 index c79d563d2..000000000 --- a/extensions/cli/src/services/AuthService.refactored.ts +++ /dev/null @@ -1,206 +0,0 @@ -// import { -// AuthenticatedConfig, -// login as doLogin, -// logout as doLogout, -// ensureOrganization, -// isAuthenticated, -// listUserOrganizations, -// loadAuthConfig, -// saveAuthConfig, -// } from "../auth/workos.js"; -// import { logger } from "../util/logger.js"; - -// import { BaseService } from "./BaseService.js"; -// import { AuthServiceState } from "./types.js"; - -// /** -// * Service for managing authentication state and operations -// * Now extends BaseService for common functionality -// */ -// export class AuthService extends BaseService { -// constructor() { -// super("AuthService", { -// authConfig: null, -// isAuthenticated: false, -// }); -// } - -// /** -// * Initialize the auth service by loading current config -// */ -// async doInitialize(): Promise { -// const authConfig = loadAuthConfig(); -// const authenticated = isAuthenticated(); - -// const state: AuthServiceState = { -// authConfig, -// isAuthenticated: authenticated, -// organizationId: authConfig?.organizationId || undefined, -// }; - -// logger.debug("AuthService initialized", { -// authenticated, -// hasConfig: !!authConfig, -// orgId: state.organizationId, -// }); - -// return state; -// } - -// /** -// * Perform login flow -// */ -// async login(): Promise { -// logger.debug("Starting login flow"); - -// try { -// const newAuthConfig = await doLogin(); - -// this.setState({ -// authConfig: newAuthConfig, -// isAuthenticated: true, -// organizationId: newAuthConfig?.organizationId || undefined, -// }); - -// logger.debug("Login successful", { -// orgId: this.currentState.organizationId, -// }); - -// return this.getState(); -// } catch (error: any) { -// logger.error("Login failed:", error); -// this.emit("error", error); -// throw error; -// } -// } - -// /** -// * Perform logout -// */ -// async logout(): Promise { -// logger.debug("Logging out"); - -// doLogout(); - -// this.setState({ -// authConfig: null, -// isAuthenticated: false, -// organizationId: undefined, -// }); - -// logger.debug("Logout complete"); -// return this.getState(); -// } - -// /** -// * Ensure organization is selected, prompting if necessary -// */ -// async ensureOrganization( -// isHeadless: boolean = false, -// ): Promise { -// if (!this.currentState.authConfig) { -// throw new Error("Not authenticated - cannot ensure organization"); -// } - -// logger.debug("Ensuring organization is selected", { -// currentOrgId: this.currentState.organizationId, -// isHeadless, -// }); - -// const updatedConfig = await ensureOrganization( -// this.currentState.authConfig, -// isHeadless, -// ); - -// this.setState({ -// authConfig: updatedConfig, -// isAuthenticated: true, -// organizationId: updatedConfig?.organizationId || undefined, -// }); - -// logger.debug("Organization ensured", { -// orgId: this.currentState.organizationId, -// }); - -// return this.getState(); -// } - -// /** -// * Switch to a different organization -// */ -// async switchOrganization( -// organizationId: string | null, -// ): Promise { -// if ( -// !this.currentState.authConfig || -// !("userId" in this.currentState.authConfig) -// ) { -// throw new Error( -// "Not authenticated with file-based auth - cannot switch organizations", -// ); -// } - -// logger.debug("Switching organization", { -// from: this.currentState.organizationId, -// to: organizationId, -// }); - -// const authenticatedConfig = this.currentState -// .authConfig as AuthenticatedConfig; - -// const updatedConfig: AuthenticatedConfig = { -// ...authenticatedConfig, -// organizationId, -// }; - -// saveAuthConfig(updatedConfig); - -// this.setState({ -// authConfig: updatedConfig, -// isAuthenticated: true, -// organizationId: organizationId || undefined, -// }); - -// logger.debug("Organization switched", { -// newOrgId: this.currentState.organizationId, -// }); - -// return this.getState(); -// } - -// /** -// * Get available organizations for the current user -// */ -// async getAvailableOrganizations(): Promise< -// { id: string; name: string }[] | null -// > { -// if (!this.currentState.isAuthenticated) { -// return null; -// } - -// try { -// return await listUserOrganizations(); -// } catch (error: any) { -// logger.error("Failed to list organizations:", error); -// this.emit("error", error); -// return null; -// } -// } - -// /** -// * Check if the current user has multiple organizations available -// */ -// async hasMultipleOrganizations(): Promise { -// const orgs = await this.getAvailableOrganizations(); -// return orgs !== null && orgs.length > 0; -// } - -// /** -// * Refresh auth state from disk (useful after external changes) -// */ -// async refresh(): Promise { -// logger.debug("Refreshing auth state from disk"); -// return this.reload(); -// } -// } -export {}; diff --git a/extensions/cli/src/services/ConfigService.test.ts b/extensions/cli/src/services/ConfigService.test.ts index 2ca7b9146..6a4820553 100644 --- a/extensions/cli/src/services/ConfigService.test.ts +++ b/extensions/cli/src/services/ConfigService.test.ts @@ -1,37 +1,79 @@ +import { + decodePackageIdentifier, + mergeUnrolledAssistants, + ModelRole, +} from "@continuedev/config-yaml"; import { beforeEach, describe, expect, test, vi } from "vitest"; -// Mock modules -vi.mock("../auth/workos.js"); -vi.mock("../configLoader.js"); -vi.mock("../configEnhancer.js"); -vi.mock("./ServiceContainer.js"); - import * as workos from "../auth/workos.js"; -import { configEnhancer } from "../configEnhancer.js"; import * as configLoader from "../configLoader.js"; import { ConfigService } from "./ConfigService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { AgentFileServiceState, SERVICE_NAMES } from "./types.js"; +vi.mock("../auth/workos.js"); +vi.mock("../configLoader.js", () => ({ + loadConfiguration: vi.fn(), + unrollPackageIdentifiersAsConfigYaml: vi.fn(), +})); +vi.mock("../util/logger.js"); +vi.mock("./ServiceContainer.js"); +vi.mock("@continuedev/config-yaml"); + +const defaultModel = { + provider: "anthropic", + name: "claude-sonnet-4.5", + model: "claude-3-5-sonnet-20241022", + roles: ["chat"] as ModelRole[], +}; describe("ConfigService", () => { let service: ConfigService; const mockConfig = { name: "test-assistant", version: "1.0.0", - models: [], + models: [ + { + name: "existing-model", + model: "gpt-4", + roles: ["chat"], + }, + ], systemMessage: "Test system message", } as any; const mockApiClient = { get: vi.fn(), post: vi.fn() }; const mockAgentFileState: AgentFileServiceState = { slug: null, agentFile: null, - agentFileModelName: null, - agentFileService: null, + agentFileModel: null, + parsedRules: null, + parsedTools: null, }; beforeEach(() => { vi.clearAllMocks(); service = new ConfigService(); + + // Setup mocks + vi.mocked(mergeUnrolledAssistants).mockReturnValue(mockConfig as any); + vi.mocked(decodePackageIdentifier).mockImplementation((id) => ({ + uriType: "slug", + fullSlug: { + ownerSlug: "owner", + packageSlug: "package", + versionSlug: "version", + }, + })); + + // Mock the default model loading function + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + block: { + name: "default-chat-model", + version: "1.0.0", + models: [defaultModel], + }, + }); }); describe("State Management", () => { @@ -41,10 +83,9 @@ describe("ConfigService", () => { source: { type: "cli-flag", path: "/path/to/config.yaml" } as any, }); - const state = await service.initialize({ + const state = await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/path/to/config.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -53,6 +94,16 @@ describe("ConfigService", () => { config: mockConfig as any, configPath: "/path/to/config.yaml", }); + expect(vi.mocked(mergeUnrolledAssistants)).toHaveBeenCalledWith( + mockConfig, + expect.objectContaining({ + name: "hidden", + version: "1.0.0", + rules: [], + mcpServers: [], + prompts: [], + }), + ); }); test("should initialize with undefined config path", async () => { @@ -61,10 +112,9 @@ describe("ConfigService", () => { source: { type: "default-agent" } as any, }); - const state = await service.initialize({ + const state = await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: undefined, - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -75,7 +125,7 @@ describe("ConfigService", () => { }); }); - test("should inject rules into config", async () => { + test("should inject rules into config using mergeUnrolledAssistants", async () => { vi.mocked(configLoader.loadConfiguration).mockResolvedValue({ config: mockConfig as any, source: { type: "cli-flag", path: "/config.yaml" } as any, @@ -83,26 +133,29 @@ describe("ConfigService", () => { const expectedConfig = { ...mockConfig, - systemMessage: - "Test system message\n\nProcessed: rule1\n\nProcessed: rule2", + rules: ["rule1", "rule2"], }; - vi.mocked(configEnhancer.enhanceConfig).mockResolvedValue(expectedConfig); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(expectedConfig); - const state = await service.initialize({ + const state = await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/config.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, injectedConfigOptions: { rule: ["rule1", "rule2"] }, }); - // Verify configEnhancer was called with the right parameters - expect(vi.mocked(configEnhancer.enhanceConfig)).toHaveBeenCalledWith( + // Verify mergeUnrolledAssistants was called with the right parameters + expect(vi.mocked(mergeUnrolledAssistants)).toHaveBeenCalledWith( mockConfig, - { rule: ["rule1", "rule2"] }, - mockAgentFileState, + expect.objectContaining({ + name: "hidden", + version: "1.0.0", + rules: ["rule1", "rule2"], + mcpServers: [], + prompts: [], + }), ); expect(state.config).toEqual(expectedConfig); @@ -116,10 +169,9 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/old.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -130,13 +182,14 @@ describe("ConfigService", () => { config: newConfig, source: { type: "cli-flag", path: "/new.yaml" } as any, }); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(newConfig); - const state = await service.switchConfig( - "/new.yaml", - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ); + const state = await service.switchConfig({ + authConfig: { accessToken: "token" } as any, + configPath: "/new.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); expect(state).toEqual({ config: newConfig, @@ -146,10 +199,9 @@ describe("ConfigService", () => { }); test("should handle switch config errors", async () => { - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/old.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -159,12 +211,12 @@ describe("ConfigService", () => { ); await expect( - service.switchConfig( - "/bad.yaml", - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ), + service.switchConfig({ + authConfig: { accessToken: "token" } as any, + configPath: "/bad.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }), ).rejects.toThrow("Config not found"); }); }); @@ -176,10 +228,9 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/config.yaml" } as any, }); - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/config.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -190,12 +241,13 @@ describe("ConfigService", () => { config: updatedConfig, source: { type: "cli-flag", path: "/config.yaml" } as any, }); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(updatedConfig); - const state = await service.reload( - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ); + const state = await service.reload({ + authConfig: { accessToken: "token" } as any, + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); expect(state).toEqual({ config: updatedConfig, @@ -209,20 +261,19 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "default-agent" } as any, }); - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: undefined, - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); await expect( - service.reload( - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ), + service.reload({ + authConfig: { accessToken: "token" } as any, + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }), ).rejects.toThrow("No configuration path available for reload"); }); }); @@ -234,10 +285,9 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/old.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -247,9 +297,10 @@ describe("ConfigService", () => { accessToken: "token", organizationId: "org-123", } as any); - vi.mocked(serviceContainer.get).mockResolvedValue({ - apiClient: mockApiClient, - }); + vi.mocked(serviceContainer.get) + .mockResolvedValueOnce({ apiClient: mockApiClient }) + .mockResolvedValueOnce(mockAgentFileState) + .mockResolvedValueOnce({ isHeadless: false }); // Mock new config load const newConfig = { ...mockConfig, name: "new-assistant" } as any; @@ -257,6 +308,7 @@ describe("ConfigService", () => { config: newConfig, source: { type: "cli-flag", path: "/new.yaml" } as any, }); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(newConfig); await service.updateConfigPath("/new.yaml"); @@ -277,10 +329,9 @@ describe("ConfigService", () => { }); test("should handle missing API client", async () => { - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/old.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -299,12 +350,89 @@ describe("ConfigService", () => { }); }); + describe("getAdditionalBlocksFromOptions()", () => { + test("should process command line options correctly", () => { + const options = { + rule: ["rule1", "owner/package-rule"], + prompt: ["prompt1"], + model: ["gpt-4"], + mcp: ["owner/mcp-server", "https://example.com/mcp"], + }; + const agentFileState = { + agentFile: { + name: "test-agent", + model: "agent-model", + prompt: "Agent prompt", + }, + parsedRules: ["agent/rule"], + parsedTools: { + mcpServers: ["agent/mcp"], + }, + } as any; + + const result = service.getAdditionalBlocksFromOptions( + options, + agentFileState, + ); + + // Should have package identifiers from models, MCPs, and non-string rules + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith("gpt-4"); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "agent-model", + ); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "owner/package-rule", + ); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "owner/mcp-server", + ); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "agent/rule", + ); + expect(vi.mocked(decodePackageIdentifier)).toHaveBeenCalledWith( + "agent/mcp", + ); + + // Should have additional blocks with string rules and URL MCPs + expect(result.additional.rules).toContain("rule1"); + expect(result.additional.rules).toContain("prompt1"); + expect(result.additional.mcpServers).toEqual([ + expect.objectContaining({ + name: "example.com", + url: "https://example.com/mcp", + }), + ]); + expect(result.additional.prompts).toEqual([ + expect.objectContaining({ + name: "Agent prompt (test-agent)", + prompt: "Agent prompt", + }), + ]); + }); + + test("should handle empty options", () => { + const result = service.getAdditionalBlocksFromOptions( + undefined, + undefined, + ); + + expect(result.injected).toEqual([]); + expect(result.additional).toEqual({ + name: "hidden", + version: "1.0.0", + rules: [], + mcpServers: [], + prompts: [], + }); + }); + }); + describe("getDependencies()", () => { - test("should declare auth and apiClient dependencies", () => { + test("should declare auth, apiClient, and agentFile dependencies", () => { expect(service.getDependencies()).toEqual([ - "auth", - "apiClient", - "agentFile", + SERVICE_NAMES.AUTH, + SERVICE_NAMES.API_CLIENT, + SERVICE_NAMES.AGENT_FILE, ]); }); }); @@ -315,10 +443,9 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/old.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -331,13 +458,14 @@ describe("ConfigService", () => { config: newConfig, source: { type: "cli-flag", path: "/new.yaml" } as any, }); + vi.mocked(mergeUnrolledAssistants).mockReturnValue(newConfig); - await service.switchConfig( - "/new.yaml", - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ); + await service.switchConfig({ + authConfig: { accessToken: "token" } as any, + configPath: "/new.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }); expect(listener).toHaveBeenCalledWith( expect.objectContaining({ config: newConfig, configPath: "/new.yaml" }), @@ -349,10 +477,9 @@ describe("ConfigService", () => { }); test("should emit error on switch failure", async () => { - await service.initialize({ + await service.doInitialize({ authConfig: { accessToken: "token" } as any, configPath: "/old.yaml", - _organizationId: "org-123", apiClient: mockApiClient as any, agentFileState: mockAgentFileState, }); @@ -364,17 +491,260 @@ describe("ConfigService", () => { vi.mocked(configLoader.loadConfiguration).mockRejectedValue(error); await expect( - service.switchConfig( - "/bad.yaml", - { accessToken: "token" } as any, - "org-123", - mockApiClient as any, - ), + service.switchConfig({ + authConfig: { accessToken: "token" } as any, + configPath: "/bad.yaml", + apiClient: mockApiClient as any, + agentFileState: mockAgentFileState, + }), ).rejects.toThrow(); expect(errorListener).toHaveBeenCalledWith(error); }); }); + describe("addDefaultChatModelIfNone()", () => { + test("should add default model when no chat models exist", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [ + { + name: "non-chat-model", + model: "test-model", + roles: ["embed", "rerank"], // No "chat" role + }, + ], + } as any; + + // Mock the default model loading + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + block: { + name: "default", + version: "1.0.0", + models: [defaultModel], + }, + }); + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + expect( + vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml), + ).toHaveBeenCalledWith( + [ + { + uriType: "slug", + fullSlug: { + ownerSlug: "anthropic", + packageSlug: "claude-sonnet-4-5", + versionSlug: "1.0.0", + }, + }, + ], + "token", + null, + mockApiClient, + ); + + expect(result.models).toHaveLength(2); + expect(result.models![1]).toEqual(defaultModel); + }); + + test("should not add default model when chat model already exists", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [ + { + name: "existing-chat-model", + model: "gpt-4", + roles: ["chat"], + }, + ], + } as any; + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + // Should not call the unroll function since chat model exists + expect( + vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml), + ).not.toHaveBeenCalled(); + expect(result).toBe(config); // Should return unchanged config + }); + + test("should not add default model when model with no roles exists (defaults to chat)", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [ + { + name: "model-with-no-roles", + model: "gpt-4", + // No roles specified, defaults to including chat + }, + ], + } as any; + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + expect( + vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml), + ).not.toHaveBeenCalled(); + expect(result).toBe(config); + }); + + test("should handle empty models array by adding default model", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [], + } as any; + + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + block: { + name: "default", + version: "1.0.0", + models: [defaultModel], + }, + }); + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + expect(result.models).toHaveLength(1); + expect(result.models![0]).toEqual(defaultModel); + }); + + test("should handle undefined models by adding default model", async () => { + const config = { + name: "test-config", + version: "1.0.0", + // models is undefined + } as any; + + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + block: { + name: "default", + version: "1.0.0", + models: [defaultModel], + }, + }); + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ); + + expect(result.models).toHaveLength(1); + expect(result.models![0]).toEqual(defaultModel); + }); + + test("should throw error when default model fails to load", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [], + } as any; + + const error = new Error("Failed to load default model"); + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockRejectedValue(error); + + await expect( + service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ), + ).rejects.toThrow("No model specified and failed to load default model"); + }); + + test("should throw error when loaded default model is empty", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [], + } as any; + + // Mock empty model config + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + block: { + name: "default", + version: "1.0.0", + models: [], // Empty models array + }, + }); + + await expect( + service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + { accessToken: "token" } as any, + ), + ).rejects.toThrow("No model specified and failed to load default model"); + }); + + test("should work with null access token", async () => { + const config = { + name: "test-config", + version: "1.0.0", + models: [], + } as any; + + vi.mocked( + configLoader.unrollPackageIdentifiersAsConfigYaml, + ).mockResolvedValue({ + block: { + name: "default", + version: "1.0.0", + models: [defaultModel], + }, + }); + + const result = await service.addDefaultChatModelIfNone( + config, + mockApiClient as any, + undefined, // No auth config + ); + + expect( + vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml), + ).toHaveBeenCalledWith( + expect.any(Array), + null, // Should pass null for access token + null, // Should pass null for organization ID + mockApiClient, + ); + + expect(result.models).toHaveLength(1); + expect(result.models![0]).toEqual(defaultModel); + }); + }); + describe("Legacy Compatibility", () => { test("updateConfigPath method exists and has correct signature", () => { // Test that the updateConfigPath method exists and is a function diff --git a/extensions/cli/src/services/ConfigService.ts b/extensions/cli/src/services/ConfigService.ts index 391215399..864c84cc9 100644 --- a/extensions/cli/src/services/ConfigService.ts +++ b/extensions/cli/src/services/ConfigService.ts @@ -1,12 +1,25 @@ +import { + AssistantUnrolled, + decodePackageIdentifier, + mergeUnrolledAssistants, + PackageIdentifier, +} from "@continuedev/config-yaml"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; +import { isStringRule } from "src/hubLoader.js"; +import { getErrorString } from "src/util/error.js"; + import { AuthConfig, loadAuthConfig } from "../auth/workos.js"; import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; -import { configEnhancer } from "../configEnhancer.js"; +import { + loadConfiguration, + unrollPackageIdentifiersAsConfigYaml, +} from "../configLoader.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; import { serviceContainer } from "./ServiceContainer.js"; +import { ToolPermissionServiceState } from "./ToolPermissionService.js"; import { AgentFileServiceState, ApiClientServiceState, @@ -14,13 +27,22 @@ import { SERVICE_NAMES, } from "./types.js"; +const DEFAULT_MODEL_IDENTIFIER: PackageIdentifier = { + uriType: "slug", + fullSlug: { + ownerSlug: "anthropic", + packageSlug: "claude-sonnet-4-5", + versionSlug: "1.0.0", + }, +}; + interface ConfigServiceInit { authConfig: AuthConfig; configPath: string | undefined; - _organizationId: string | null; apiClient: DefaultApiInterface; agentFileState: AgentFileServiceState; injectedConfigOptions?: BaseCommandOptions; + isHeadless?: boolean; } /** * Service for managing configuration state and operations @@ -48,97 +70,248 @@ export class ConfigService ]; } + getAdditionalBlocksFromOptions( + injectedConfigOptions: BaseCommandOptions | undefined, + agentFileState: AgentFileServiceState | undefined, + ): { + injected: PackageIdentifier[]; + additional: AssistantUnrolled; + } { + const packageIdentifiers: PackageIdentifier[] = []; + const additional: AssistantUnrolled = { + name: "hidden", + version: "1.0.0", + rules: [], + mcpServers: [], + prompts: [], + }; + + const options = injectedConfigOptions || {}; + + this.processModels(options.model || [], agentFileState, packageIdentifiers); + this.processMcpServers( + options.mcp || [], + agentFileState, + packageIdentifiers, + additional, + ); + this.processAgentFileRules(agentFileState, packageIdentifiers); + this.processRulesAndPrompts( + options.rule || [], + options.prompt || [], + packageIdentifiers, + additional, + ); + this.processAgentFilePrompt(agentFileState, additional); + + return { + injected: packageIdentifiers, + additional, + }; + } + + private processModels( + models: string[], + agentFileState: AgentFileServiceState | undefined, + packageIdentifiers: PackageIdentifier[], + ): void { + const allModels = [...models]; + if (agentFileState?.agentFile?.model) { + allModels.push(agentFileState.agentFile.model); + } + + for (const model of allModels) { + try { + packageIdentifiers.push(decodePackageIdentifier(model)); + } catch (e) { + logger.warn(`Failed to add model "${model}": ${getErrorString(e)}`); + } + } + } + + private processMcpServers( + mcps: string[], + agentFileState: AgentFileServiceState | undefined, + packageIdentifiers: PackageIdentifier[], + additional: AssistantUnrolled, + ): void { + const allMcps = [ + ...mcps, + ...(agentFileState?.parsedTools?.mcpServers || []), + ]; + + for (const mcp of allMcps) { + try { + if (this.isUrl(mcp)) { + additional.mcpServers!.push({ + name: new URL(mcp).hostname, + url: mcp, + }); + } else { + packageIdentifiers.push(decodePackageIdentifier(mcp)); + } + } catch (e) { + logger.warn(`Failed to add MCP server "${mcp}": ${getErrorString(e)}`); + } + } + } + + private processAgentFileRules( + agentFileState: AgentFileServiceState | undefined, + packageIdentifiers: PackageIdentifier[], + ): void { + for (const rule of agentFileState?.parsedRules || []) { + try { + packageIdentifiers.push(decodePackageIdentifier(rule)); + } catch (e) { + logger.warn( + `Failed to get rule "${rule} (from agent file)": ${getErrorString(e)}`, + ); + } + } + } + + private processRulesAndPrompts( + rules: string[], + prompts: string[], + packageIdentifiers: PackageIdentifier[], + additional: AssistantUnrolled, + ): void { + const allRulesAndPrompts = [...rules, ...prompts]; + + for (const item of allRulesAndPrompts) { + try { + if (isStringRule(item)) { + additional.rules!.push(item); + } else { + packageIdentifiers.push(decodePackageIdentifier(item)); + } + } catch (e) { + logger.warn( + `Failed to load rule or prompt "${item}": ${getErrorString(e)}`, + ); + } + } + } + + private processAgentFilePrompt( + agentFileState: AgentFileServiceState | undefined, + additional: AssistantUnrolled, + ): void { + if (agentFileState?.agentFile?.prompt) { + additional.prompts!.push({ + name: `Agent prompt (${agentFileState.agentFile.name})`, + prompt: agentFileState.agentFile.prompt, + description: agentFileState.agentFile.description, + }); + } + } + + private isUrl(value: string): boolean { + return value.startsWith("http://") || value.startsWith("https://"); + } + + async addDefaultChatModelIfNone( + config: AssistantUnrolled, + apiClient: DefaultApiInterface, + authConfig: AuthConfig | undefined, + ): Promise { + const hasChatModel = !!config.models?.find( + (m) => !!m && (!m.roles || m.roles.includes("chat")), + ); + if (!hasChatModel) { + try { + const modelConfig = await unrollPackageIdentifiersAsConfigYaml( + [DEFAULT_MODEL_IDENTIFIER], + authConfig?.accessToken ?? null, + authConfig?.organizationId ?? null, + apiClient, + ); + const defaultModel = modelConfig?.block?.models?.[0]; + if (!defaultModel) { + throw new Error("Loaded default model contained no model block"); + } + config.models = [...(config.models || []), defaultModel]; + } catch (e) { + logger.error("Failed to load default model with no model specified", e); + throw new Error("No model specified and failed to load default model"); + } + } + return config; + } + + private async loadConfig( + init: ConfigServiceInit, + ): Promise { + const { + authConfig, + configPath, + apiClient, + injectedConfigOptions, + agentFileState, + } = init; + const { injected, additional } = this.getAdditionalBlocksFromOptions( + injectedConfigOptions, + agentFileState, + ); + + const result = await loadConfiguration( + authConfig, + configPath, + apiClient, + injected, + init.isHeadless, + ); + + const loadedConfig = result.config; + const merged = mergeUnrolledAssistants(loadedConfig, additional); + + const withModel = await this.addDefaultChatModelIfNone( + merged, + apiClient, + authConfig, + ); + + // Config URI persistence is now handled by the streamlined loader + logger.debug("ConfigService initialized successfully"); + + const state = { + config: withModel, + configPath, + }; + this.setState(state); + + return state; + } + /** * Initialize the config service */ - async doInitialize({ - apiClient, - authConfig, - configPath, - agentFileState, - injectedConfigOptions, - }: ConfigServiceInit): Promise { - // Use the new streamlined config loader - const { loadConfiguration } = await import("../configLoader.js"); - const result = await loadConfiguration(authConfig, configPath, apiClient); - - let config = result.config; - - // Apply injected config if provided - if ( - agentFileState?.agentFile || - (injectedConfigOptions && this.hasInjectedConfig(injectedConfigOptions)) - ) { - config = await configEnhancer.enhanceConfig( - config, - injectedConfigOptions, - agentFileState, - ); - - logger.debug("Applied injected configuration"); - } + async doInitialize(init: ConfigServiceInit): Promise { + const result = await this.loadConfig(init); // Config URI persistence is now handled by the streamlined loader - logger.debug("ConfigService initialized successfully"); - return { - config, - configPath, - }; + return result; } /** * Switch to a new configuration */ - async switchConfig( - newConfigPath: string, - authConfig: AuthConfig, - _organizationId: string | null, - apiClient: DefaultApiInterface, - injectedConfigOptions?: BaseCommandOptions, - ): Promise { + async switchConfig(init: ConfigServiceInit): Promise { logger.debug("Switching configuration", { from: this.currentState.configPath, - to: newConfigPath, + to: init.configPath, }); try { - // Use the new streamlined config loader - const { loadConfiguration } = await import("../configLoader.js"); - const result = await loadConfiguration( - authConfig, - newConfigPath, - apiClient, - ); - - let config = result.config; - - // Apply injected config if provided - if ( - injectedConfigOptions && - this.hasInjectedConfig(injectedConfigOptions) - ) { - config = await configEnhancer.enhanceConfig( - config, - injectedConfigOptions, - ); - - logger.debug("Applied injected configuration"); - } - - this.setState({ - config, - configPath: newConfigPath, - }); - - // Config URI persistence is now handled by the streamlined loader - + const state = await this.loadConfig(init); logger.debug("Configuration switched successfully", { - newConfigPath, + newConfigPath: init.configPath, }); - return this.getState(); + return state; } catch (error: any) { logger.error("Failed to switch configuration:", error); this.emit("error", error); @@ -150,10 +323,7 @@ export class ConfigService * Reload the current configuration */ async reload( - authConfig: AuthConfig, - _organizationId: string | null, - apiClient: DefaultApiInterface, - injectedConfigOptions?: BaseCommandOptions, + init: Omit, ): Promise { if (!this.currentState.configPath) { throw new Error("No configuration path available for reload"); @@ -161,25 +331,10 @@ export class ConfigService logger.debug("Reloading current configuration"); - return this.switchConfig( - this.currentState.configPath, - authConfig, - _organizationId, - apiClient, - injectedConfigOptions, - ); - } - - /** - * Check if injected config options contain any config to inject - */ - private hasInjectedConfig(options: BaseCommandOptions): boolean { - return !!( - (options.rule && options.rule.length > 0) || - (options.mcp && options.mcp.length > 0) || - (options.model && options.model.length > 0) || - (options.prompt && options.prompt.length > 0) - ); + return this.switchConfig({ + ...init, + configPath: this.currentState.configPath, + }); } /** @@ -195,40 +350,39 @@ export class ConfigService try { // Get current auth and API client state needed for config loading const authConfig = loadAuthConfig(); - const apiClientState = await serviceContainer.get( + const { apiClient } = await serviceContainer.get( SERVICE_NAMES.API_CLIENT, ); - if (!apiClientState.apiClient) { + if (!apiClient) { throw new Error("API client not available"); } - // Load the new configuration using streamlined loader - const { loadConfiguration } = await import("../configLoader.js"); - const result = await loadConfiguration( - authConfig, - newConfigPath, - apiClientState.apiClient, + const agentFileState = await serviceContainer.get( + SERVICE_NAMES.AGENT_FILE, ); - // Update internal state - this.setState({ - config: result.config, + const toolPermissionsState = + await serviceContainer.get( + SERVICE_NAMES.TOOL_PERMISSIONS, + ); + + const result = await this.loadConfig({ + agentFileState, + apiClient, + authConfig, configPath: newConfigPath, + injectedConfigOptions: {}, + isHeadless: toolPermissionsState.isHeadless, }); - // Config URI persistence is now handled by the streamlined loader - - // Update the CONFIG service in the container - serviceContainer.set(SERVICE_NAMES.CONFIG, this.getState()); - // Manually reload dependent services (MODEL, MCP) to pick up the new config await serviceContainer.reload(SERVICE_NAMES.MODEL); await serviceContainer.reload(SERVICE_NAMES.MCP); logger.debug("Configuration path updated successfully", { newConfigPath, - configName: result.config.name, + configName: result.config?.name, }); } catch (error: any) { logger.error("Failed to update configuration path:", error); @@ -236,4 +390,9 @@ export class ConfigService throw error; } } + + setState(newState: Partial): void { + super.setState(newState); + serviceContainer.set(SERVICE_NAMES.CONFIG, this.currentState); + } } diff --git a/extensions/cli/src/services/ModelService.test.ts b/extensions/cli/src/services/ModelService.test.ts index bcc797780..1ce83b540 100644 --- a/extensions/cli/src/services/ModelService.test.ts +++ b/extensions/cli/src/services/ModelService.test.ts @@ -100,45 +100,6 @@ describe("ModelService", () => { }); }); - describe("update()", () => { - test("should update model with new assistant config", async () => { - // Initialize first - vi.mocked(config.getLlmApi).mockReturnValue([ - mockLlmApi as any, - mockAssistant.models![0] as ModelConfig, - ]); - await service.initialize(mockAssistant, mockAuthConfig); - - // Update with new assistant - const newAssistant = { - ...mockAssistant, - models: [ - { - provider: "openai", - model: "gpt-4-turbo", - name: "GPT-4 Turbo", - apiKey: "new-key", - roles: ["chat"], - } as ModelConfig, - ], - }; - const newLlmApi = { complete: vi.fn(), stream: vi.fn() }; - vi.mocked(config.getLlmApi).mockReturnValue([ - newLlmApi as any, - newAssistant.models![0] as ModelConfig, - ]); - - const state = await service.update(newAssistant, mockAuthConfig); - - expect(state).toEqual({ - llmApi: newLlmApi, - model: newAssistant.models![0], - assistant: newAssistant, - authConfig: mockAuthConfig, - }); - }); - }); - describe("switchModel()", () => { test("should switch to a different model by index", async () => { vi.mocked(config.getLlmApi).mockReturnValue([ diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index f4e0a18b8..0c36e1971 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -41,7 +41,7 @@ export class ModelService async doInitialize( assistant: AssistantUnrolled, authConfig: AuthConfig, - agentFileServiceState?: AgentFileServiceState, + agentFileServiceState: AgentFileServiceState | undefined, ): Promise { logger.debug("ModelService.doInitialize called", { hasAssistant: !!assistant, @@ -60,8 +60,8 @@ export class ModelService let modelSource = "default"; // Priority = agentFile -> last selected model - if (agentFileServiceState?.agentFileModelName) { - preferredModelName = agentFileServiceState.agentFileModelName; + if (agentFileServiceState?.agentFileModel?.name) { + preferredModelName = agentFileServiceState.agentFileModel?.name; modelSource = "agentFile"; } else { preferredModelName = getModelName(authConfig); @@ -122,48 +122,6 @@ export class ModelService } } - /** - * Update the model based on new config or auth changes - */ - async update( - assistant: AssistantUnrolled, - authConfig: AuthConfig, - ): Promise { - logger.debug("Updating ModelService"); - - try { - // Update instance properties for backward compatibility - this.assistant = assistant; - this.authConfig = authConfig; - this.availableModels = (assistant.models?.filter( - (model) => - model && (model.roles?.includes("chat") || model.roles === undefined), - ) || []) as ModelConfig[]; - - const [llmApi, model] = getLlmApi(assistant, authConfig); - - // Ensure state has all necessary data - this.setState({ - llmApi, - model, - assistant, - authConfig, - }); - - logger.debug("ModelService updated successfully", { - modelProvider: model.provider, - modelName: (model as any).name || "unnamed", - availableModels: this.availableModels.length, - }); - - return this.getState(); - } catch (error: any) { - logger.error("Failed to update ModelService:", error); - this.emit("error", error); - throw error; - } - } - /** * Override isReady to check for required state */ diff --git a/extensions/cli/src/services/ModelService.workflow-priority.test.ts b/extensions/cli/src/services/ModelService.workflow-priority.test.ts index e683a86d2..8706a1150 100644 --- a/extensions/cli/src/services/ModelService.workflow-priority.test.ts +++ b/extensions/cli/src/services/ModelService.workflow-priority.test.ts @@ -60,8 +60,13 @@ describe("ModelService agent file model prioritization", () => { prompt: "Test agent", }, slug: "test/agent", - agentFileModelName: "gpt-4", - agentFileService: null, + agentFileModel: { + name: "gpt-4", + model: "gpt-4", + provider: "openai", + }, + parsedRules: null, + parsedTools: null, }; // Mock createLlmApi to return different models based on the selected model @@ -102,8 +107,9 @@ describe("ModelService agent file model prioritization", () => { // No model specified }, slug: "test/agent", - agentFileModelName: null, - agentFileService: null, + agentFileModel: null, + parsedRules: null, + parsedTools: null, }; // Mock getModelName to return a persisted model @@ -146,8 +152,13 @@ describe("ModelService agent file model prioritization", () => { prompt: "Test agent", }, slug: "test/agent", - agentFileModelName: "non-existent-model", - agentFileService: null, + agentFileModel: { + name: "non-existent-model", + model: "non-existent", + provider: "nonexistent", + }, + parsedRules: null, + parsedTools: null, }; const getLlmApiMock = vi.mocked(config.getLlmApi); @@ -177,8 +188,9 @@ describe("ModelService agent file model prioritization", () => { const agentFileServiceState: AgentFileServiceState = { agentFile: null, slug: null, - agentFileModelName: null, - agentFileService: null, + agentFileModel: null, + parsedRules: null, + parsedTools: null, }; // Make sure getModelName returns null (no persisted model) @@ -215,8 +227,13 @@ describe("ModelService agent file model prioritization", () => { prompt: "Test agent", }, slug: "test/agent", - agentFileModelName: "gpt-4", - agentFileService: null, + agentFileModel: { + name: "gpt-4", + model: "gpt-4", + provider: "openai", + }, + parsedRules: null, + parsedTools: null, }; // Mock getModelName to return a different persisted model diff --git a/extensions/cli/src/services/agent-file-integration.test.ts b/extensions/cli/src/services/agent-file-integration.test.ts index 905f7a683..080f9e40d 100644 --- a/extensions/cli/src/services/agent-file-integration.test.ts +++ b/extensions/cli/src/services/agent-file-integration.test.ts @@ -1,17 +1,18 @@ -import { vi } from "vitest"; - -import { ConfigEnhancer } from "../configEnhancer.js"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { AgentFileService } from "./AgentFileService.js"; +import { ConfigService } from "./ConfigService.js"; import { ModelService } from "./ModelService.js"; // Mock the hubLoader module vi.mock("../hubLoader.js", () => ({ loadPackageFromHub: vi.fn(), loadPackagesFromHub: vi.fn(), + loadModelFromHub: vi.fn(), mcpProcessor: {}, modelProcessor: {}, processRule: vi.fn(), + isStringRule: vi.fn(), agentFileProcessor: { type: "agentFile", expectedFileExtensions: [".md"], @@ -38,18 +39,50 @@ vi.mock("../config.js", () => ({ // Mock auth module vi.mock("../auth/workos.js", () => ({ getModelName: vi.fn(), + loadAuthConfig: vi.fn(), +})); + +// Mock the config-yaml package +vi.mock("@continuedev/config-yaml", async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + decodePackageIdentifier: vi.fn((id) => ({ + type: "slug", + slug: id, + version: undefined, + })), + }; +}); + +// Mock configLoader +vi.mock("../configLoader.js", () => ({ + loadConfiguration: vi.fn(), +})); + +// Mock service container +vi.mock("./ServiceContainer.js", () => ({ + serviceContainer: { + get: vi.fn(), + set: vi.fn(), + reload: vi.fn(), + }, })); describe("Agent file Integration Tests", () => { let agentFileService: AgentFileService; let modelService: ModelService; - let configEnhancer: ConfigEnhancer; + let configService: ConfigService; let mockLoadPackageFromHub: any; let mockLoadPackagesFromHub: any; let mockProcessRule: any; let mockCreateLlmApi: any; let mockGetLlmApi: any; let mockModelProcessor: any; + let mockDecodePackageIdentifier: any; + let mockLoadModelFromHub: any; + let mockIsStringRule: any; const mockAgentFile = { name: "Test Agent File", @@ -90,21 +123,32 @@ describe("Agent file Integration Tests", () => { mockLoadPackagesFromHub = hubLoaderModule.loadPackagesFromHub as any; mockProcessRule = hubLoaderModule.processRule as any; mockModelProcessor = hubLoaderModule.modelProcessor; + mockLoadModelFromHub = hubLoaderModule.loadModelFromHub as any; + mockIsStringRule = hubLoaderModule.isStringRule as any; mockCreateLlmApi = configModule.createLlmApi as any; mockGetLlmApi = configModule.getLlmApi as any; + // Get mock functions from config-yaml + const configYaml = await import("@continuedev/config-yaml"); + mockDecodePackageIdentifier = configYaml.decodePackageIdentifier as any; + // Create service instances agentFileService = new AgentFileService(); modelService = new ModelService(); - configEnhancer = new ConfigEnhancer(); + configService = new ConfigService(); // Setup default mocks mockProcessRule.mockResolvedValue("Processed rule content"); mockLoadPackagesFromHub.mockResolvedValue([{ name: "test-mcp" }]); - mockLoadPackageFromHub.mockResolvedValue({ - name: "test-model", + mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); + mockLoadModelFromHub.mockResolvedValue({ + name: "gpt-4-agent", provider: "openai", }); + mockIsStringRule.mockImplementation((rule: string) => { + // String rules are those that don't look like package identifiers + return rule.includes(" ") || rule.includes("\n") || !rule.includes("/"); + }); mockCreateLlmApi.mockReturnValue({ mock: "llmApi" }); mockGetLlmApi.mockReturnValue([ { mock: "llmApi" }, @@ -112,158 +156,157 @@ describe("Agent file Integration Tests", () => { ]); }); - describe("Agent file models are injected via ConfigEnhancer", () => { - it("should add agent file model to options when agent file active", async () => { + describe("Agent file models are injected via ConfigService", () => { + it("should add agent file model when agent file is active", async () => { // Setup agent file service with active agent file mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); const agentFileState = agentFileService.getState(); expect(agentFileState.agentFile?.model).toBe("gpt-4-agent"); - // Mock loadPackageFromHub to return a model for the agent file model - mockLoadPackageFromHub.mockResolvedValueOnce({ - name: "gpt-4-agent", - provider: "openai", - }); - - // Test that ConfigEnhancer adds the agent file model to options - const baseConfig = { models: [] }; + // Test that ConfigService processes the agent file model const baseOptions = {}; // No --model flag - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileState, - ); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); - // Should have loaded the agent file model directly via loadPackageFromHub - expect(mockLoadPackageFromHub).toHaveBeenCalledWith( - "gpt-4-agent", - mockModelProcessor, - ); - - // The agent file model should be prepended to the models array - expect(enhancedConfig.models).toHaveLength(1); - expect(enhancedConfig.models?.[0]).toEqual({ - name: "gpt-4-agent", - provider: "openai", - }); + // Should have processed the agent file model as a package identifier + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("gpt-4-agent"); + expect(injected).toHaveLength(2); // Agent file model + parsed rules become package identifiers }); it("should not add agent file model when no agent file active", async () => { // Initialize agent file service without agent - await agentFileService.initialize(); + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + undefined, + authServiceState, + apiClientState, + ); const agentFileState = agentFileService.getState(); expect(agentFileState.agentFile).toBeNull(); - // Test that ConfigEnhancer doesn't add any agent file models - const baseConfig = { models: [] }; + // Test that ConfigService doesn't add any agent file models const baseOptions = {}; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileState, - ); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); - // Should not have enhanced with any models - expect(enhancedConfig.models).toEqual([]); + // Should not have processed any models + expect(injected).toHaveLength(0); + expect(additional.models || []).toHaveLength(0); }); - it("should respect --model flag priority over agent file model", async () => { + it("should process both --model flag and agent file model", async () => { // Setup agent file service with active agent file mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); - // Mock loadPackageFromHub for agent file model and loadPackagesFromHub for user models - mockLoadPackageFromHub.mockResolvedValueOnce({ - name: "gpt-4-agent", - provider: "openai", - }); - mockLoadPackagesFromHub.mockResolvedValueOnce([ - { - name: "user-specified-model", - provider: "anthropic", - }, - ]); + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - // Test that --model flag takes precedence - const baseConfig = { models: [] }; + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); + + // Test that --model flag and agent file model are both processed const baseOptions = { model: ["user-specified-model"] }; // User specified --model - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileService.getState(), - ); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileService.getState(), + ); - // Should process the user model via loadPackagesFromHub - expect(mockLoadPackagesFromHub).toHaveBeenCalledWith( - ["user-specified-model"], - mockModelProcessor, + // Should process both the user model and agent file model as package identifiers + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith( + "user-specified-model", ); - - // Should also load the agent file model - expect(mockLoadPackageFromHub).toHaveBeenCalledWith( - "gpt-4-agent", - mockModelProcessor, - ); - - // Both models should be in the config, with user model first (takes precedence) - expect(enhancedConfig.models).toHaveLength(2); - expect(enhancedConfig.models?.[0]).toEqual({ - name: "user-specified-model", - provider: "anthropic", - }); - expect(enhancedConfig.models?.[1]).toEqual({ - name: "gpt-4-agent", - provider: "openai", - }); + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("gpt-4-agent"); + expect(injected).toHaveLength(3); // User model + agent file model + parsed rules as package identifiers }); }); - describe("AgentFileService affects ConfigEnhancer", () => { + describe("AgentFileService affects ConfigService", () => { it("should inject agent file rules when agent file active", async () => { - // Setup agent file service with active agent file - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); - - const baseConfig = { - rules: ["existing rule"], + // Mock the agent file with parsed rules + const agentFileStateWithRules = { + agentFile: mockAgentFile, + parsedRules: ["agent/rule1"], // Parsed rules from agent file + parsedTools: null, + slug: null, + agentFileModel: null, }; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), - ); + const baseOptions = {}; - // Rules should be processed normally since agent file rules are now added to options.rule - expect(mockProcessRule).toHaveBeenCalledWith(mockAgentFile.rules); - expect(enhancedConfig.rules).toHaveLength(2); - // The agent file rule is processed first, then existing rules - expect(mockProcessRule).toHaveBeenNthCalledWith(1, mockAgentFile.rules); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithRules, + ); + + // Agent file rules should be processed as package identifiers + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("agent/rule1"); + expect(injected).toHaveLength(2); // Model + rule }); it("should not inject agent file rules when agent file inactive", async () => { // Initialize agent file service without agent file - await agentFileService.initialize(); - - const baseConfig = { - rules: ["existing rule"], + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), + await agentFileService.initialize( + undefined, + authServiceState, + apiClientState, ); - expect(mockProcessRule).not.toHaveBeenCalled(); - expect(enhancedConfig.rules).toHaveLength(1); - expect(enhancedConfig?.rules?.[0]).toBe("existing rule"); + const baseOptions = {}; + const agentFileState = agentFileService.getState(); + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Should not process any rules since no agent file is active + expect(injected).toHaveLength(0); + expect(additional.rules).toHaveLength(0); }); it("should not inject agent file rules when agent file has no rules", async () => { @@ -272,29 +315,46 @@ describe("Agent file Integration Tests", () => { rules: undefined, }; - mockLoadPackageFromHub.mockResolvedValue(agentFileWithoutRules); - await agentFileService.initialize("owner/agent"); - - const baseConfig = { - rules: ["existing rule"], + // Mock agent file state with no parsed rules + const agentFileStateWithoutRules = { + agentFile: agentFileWithoutRules, + parsedRules: [], // No parsed rules + parsedTools: null, + slug: null, + agentFileModel: null, }; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), - ); + const baseOptions = {}; - expect(mockProcessRule).not.toHaveBeenCalled(); - expect(enhancedConfig.rules).toHaveLength(1); - expect(enhancedConfig.rules?.[0]).toBe("existing rule"); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithoutRules, + ); + + // Should only have the model, no rules + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("gpt-4-agent"); // Only the model + expect(injected).toHaveLength(1); // Only the model + expect(additional.rules).toHaveLength(0); }); }); describe("Agent file model constraints", () => { it("should filter available models to only agent file model when specified", async () => { mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); await modelService.initialize( mockAssistant as any, @@ -312,7 +372,18 @@ describe("Agent file Integration Tests", () => { }); it("should allow all models when no agent file active", async () => { - await agentFileService.initialize(); + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + undefined, + authServiceState, + apiClientState, + ); await modelService.initialize( mockAssistant as any, @@ -332,7 +403,21 @@ describe("Agent file Integration Tests", () => { it("should handle agent loading errors gracefully", async () => { mockLoadPackageFromHub.mockRejectedValue(new Error("Network error")); - await agentFileService.initialize("owner/agent"); + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + // The service should throw the error, not handle it gracefully + await expect( + agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ), + ).rejects.toThrow("Network error"); const agentFileState = agentFileService.getState(); expect(agentFileState.agentFile).toBeNull(); @@ -345,25 +430,34 @@ describe("Agent file Integration Tests", () => { expect(mockGetLlmApi).toHaveBeenCalled(); }); - it("should handle agent rule processing errors gracefully", async () => { - mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - mockProcessRule.mockRejectedValue(new Error("Rule processing failed")); + it("should handle package identifier decoding errors gracefully", async () => { + // Mock decoding to throw an error + mockDecodePackageIdentifier.mockImplementation((id: string) => { + if (id === "invalid-rule") { + throw new Error("Invalid package identifier"); + } + return { type: "slug", slug: id, version: undefined }; + }); - await agentFileService.initialize("owner/agent"); - - const baseConfig = { - rules: ["existing rule"], + const agentFileStateWithInvalidRules = { + agentFile: mockAgentFile, + parsedRules: ["invalid-rule"], // This will throw an error when decoded + parsedTools: null, + slug: null, + agentFileModel: null, }; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), - ); + const baseOptions = {}; - // Should not inject agent file rule but should preserve existing rules - expect(enhancedConfig.rules).toHaveLength(1); - expect(enhancedConfig.rules?.[0]).toBe("existing rule"); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithInvalidRules, + ); + + // Should handle the error gracefully and only include valid package identifiers + expect(injected).toHaveLength(1); // Only the model should be included + expect(additional.rules).toHaveLength(0); }); // Removed test for missing service container since agent file service @@ -372,142 +466,209 @@ describe("Agent file Integration Tests", () => { it("should inject agent file prompt when agent file active", async () => { // Setup agent file service with active agent file mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); - const baseConfig = { - rules: ["existing rule"], - prompts: [], + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, ); - // Agent file prompt should be added to config.prompts - expect(enhancedConfig.prompts).toBeDefined(); - expect(enhancedConfig.prompts?.length).toBeGreaterThan(0); - expect(enhancedConfig.prompts?.[0]).toMatchObject({ + const baseOptions = {}; + const agentFileState = agentFileService.getState(); + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Agent file prompt should be added to additional.prompts + expect(additional.prompts).toBeDefined(); + expect(additional.prompts?.length).toBeGreaterThan(0); + expect(additional.prompts?.[0]).toMatchObject({ prompt: "You are an assistant.", name: expect.stringContaining("Test Agent"), }); - expect(enhancedConfig.rules).toHaveLength(2); }); - it("should add agent file prompt to config alongside other prompts", async () => { + it("should prepare agent file prompt for merging with other prompts", async () => { // Setup agent file service with active agent file mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); - const baseConfig = { - prompts: [{ name: "Existing", prompt: "existing-prompt" }], + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, }; - const baseOptions = {}; + const apiClientState = { apiClient: { mock: "apiClient" } }; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileService.getState(), + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, ); - // Agent file prompt should be prepended to existing prompts - expect(enhancedConfig.prompts).toHaveLength(2); - expect(enhancedConfig.prompts?.[0]).toMatchObject({ + const baseOptions = {}; + const agentFileState = agentFileService.getState(); + + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Agent file prompt should be in additional block ready for merging + expect(additional.prompts).toHaveLength(1); + expect(additional.prompts?.[0]).toMatchObject({ name: expect.stringContaining("Test Agent"), prompt: "You are an assistant.", }); - expect(enhancedConfig.prompts?.[1]).toMatchObject({ - name: "Existing", - prompt: "existing-prompt", - }); + + // mergeUnrolledAssistants would combine this with base config prompts + const { mergeUnrolledAssistants } = await import( + "@continuedev/config-yaml" + ); + const baseConfig = { + name: "original", + version: "1.0.0", + prompts: [{ name: "Existing", prompt: "existing-prompt" }], + }; + + const merged = mergeUnrolledAssistants(baseConfig, additional); + expect(merged.prompts).toHaveLength(2); }); it("should not add agent file prompt when agent file has no prompt", async () => { const agentFileWithoutPrompt = { ...mockAgentFile, - prompt: undefined, + prompt: "", }; - mockLoadPackageFromHub.mockResolvedValue(agentFileWithoutPrompt); - await agentFileService.initialize("owner/agent"); - - const baseConfig = { - prompts: [{ name: "Existing", prompt: "existing-prompt" }], + const agentFileStateWithoutPrompt = { + agentFile: agentFileWithoutPrompt, + parsedRules: [], + parsedTools: null, + slug: null, + agentFileModel: null, }; + const baseOptions = {}; - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileService.getState(), - ); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithoutPrompt, + ); - // Should only have the existing prompt, no agent file prompt added - expect(enhancedConfig.prompts).toHaveLength(1); - expect(enhancedConfig.prompts?.[0]).toMatchObject({ - name: "Existing", - prompt: "existing-prompt", - }); + // Should not have any prompts in additional block + expect(additional.prompts).toHaveLength(0); }); }); - describe("ConfigEnhancer prompt integration", () => { - it("should add agent file prompt to config.prompts when agent file active", async () => { + describe("ConfigService prompt integration", () => { + it("should process agent file prompt and user prompts together", async () => { // Setup agent file service with active agent file mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); - const baseOptions = { prompt: ["user-prompt"] }; - const baseConfig = { prompts: [] }; + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; - // Enhance config with agent file state - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileService.getState(), + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, ); - // Verify that the agent file prompt was added to config.prompts - expect(enhancedConfig.prompts).toBeDefined(); - expect(enhancedConfig.prompts).toHaveLength(1); - expect(enhancedConfig.prompts?.[0]).toMatchObject({ + const baseOptions = { prompt: ["user-prompt"] }; + const agentFileState = agentFileService.getState(); + + // Process options with ConfigService + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); + + // Verify that the agent file prompt was added to additional block + expect(additional.prompts).toBeDefined(); + expect(additional.prompts).toHaveLength(1); + expect(additional.prompts?.[0]).toMatchObject({ name: expect.stringContaining("Test Agent"), prompt: "You are an assistant.", description: "A test agent for integration testing", }); + + // User prompts should be in additional.rules as string rules + expect(additional.rules).toContain("user-prompt"); }); - it("should work end-to-end with agent file prompt in config", async () => { + it("should work end-to-end with agent file prompt processing", async () => { // Setup agent file service with active agent file mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); const agentFileState = agentFileService.getState(); expect(agentFileState.agentFile?.prompt).toBe("You are an assistant."); - const baseConfig = { prompts: [] }; const baseOptions = { prompt: ["Tell me about TypeScript"] }; - // Enhance config with agent file - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - baseOptions, - agentFileState, - ); + // Process with ConfigService + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileState, + ); - // Verify agent file prompt is added to config.prompts - expect(enhancedConfig.prompts).toBeDefined(); - expect(enhancedConfig.prompts?.length).toBeGreaterThan(0); - expect(enhancedConfig.prompts?.[0]?.prompt).toBe("You are an assistant."); - expect(enhancedConfig.prompts?.[0]?.name).toContain("Test Agent"); + // Verify agent file prompt is prepared for merging + expect(additional.prompts).toBeDefined(); + expect(additional.prompts?.length).toBeGreaterThan(0); + expect(additional.prompts?.[0]?.prompt).toBe("You are an assistant."); + expect(additional.prompts?.[0]?.name).toContain("Test Agent"); + + // User prompt should be a string rule + expect(additional.rules).toContain("Tell me about TypeScript"); }); }); describe("Agent file data extraction", () => { it("should correctly extract all agent file properties", async () => { mockLoadPackageFromHub.mockResolvedValue(mockAgentFile); - await agentFileService.initialize("owner/agent"); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/agent", + authServiceState, + apiClientState, + ); const agentFileState = agentFileService.getState(); expect(agentFileState.agentFile?.model).toBe("gpt-4-agent"); @@ -528,7 +689,19 @@ describe("Agent file Integration Tests", () => { }; mockLoadPackageFromHub.mockResolvedValue(partialAgentFile); - await agentFileService.initialize("owner/partial"); + + // Mock the required service states + const authServiceState = { + authConfig: mockAuthConfig, + isAuthenticated: true, + }; + const apiClientState = { apiClient: { mock: "apiClient" } }; + + await agentFileService.initialize( + "owner/partial", + authServiceState, + apiClientState, + ); const agentFileState = agentFileService.getState(); expect(agentFileState.agentFile?.model).toBe("gpt-3.5-turbo"); @@ -540,102 +713,88 @@ describe("Agent file Integration Tests", () => { describe("Agent file tools integration", () => { it("should inject MCP servers from agent file tools", async () => { - const agentFileWithTools = { - ...mockAgentFile, - tools: "owner/mcp1, another/mcp2:specific_tool", + const agentFileStateWithTools = { + agentFile: { + ...mockAgentFile, + tools: "owner/mcp1, another/mcp2:specific_tool", + }, + parsedRules: [], + parsedTools: { + mcpServers: ["owner/mcp1", "another/mcp2"], // Parsed MCP servers + tools: [], + allBuiltIn: false, + }, + slug: null, + agentFileModel: null, }; - // Clear the default mock and setup specific mocks - mockLoadPackageFromHub.mockReset(); - // First call loads the agent file - mockLoadPackageFromHub.mockResolvedValueOnce(agentFileWithTools); - // Second call loads the agent file model - mockLoadPackageFromHub.mockResolvedValueOnce({ - name: "gpt-4-agent", - provider: "openai", - }); - // Third call loads mcp1 - mockLoadPackageFromHub.mockResolvedValueOnce({ name: "mcp1" }); - // Fourth call loads mcp2 - mockLoadPackageFromHub.mockResolvedValueOnce({ name: "mcp2" }); + const baseOptions = {}; - await agentFileService.initialize("owner/agent"); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithTools, + ); - const baseConfig = { - mcpServers: [{ name: "existing-mcp" }], - }; - - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), - ); - - expect(enhancedConfig.mcpServers).toHaveLength(3); - // MCPs are prepended in the order they are loaded - expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "mcp1" }); - expect(enhancedConfig.mcpServers?.[1]).toEqual({ name: "mcp2" }); - expect(enhancedConfig.mcpServers?.[2]).toEqual({ name: "existing-mcp" }); + // MCP servers should be processed as package identifiers + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("owner/mcp1"); + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("another/mcp2"); + expect(injected).toHaveLength(3); // model + 2 MCP servers }); it("should not inject MCP servers when agent file has no tools", async () => { - const agentWithoutTools = { - ...mockAgentFile, - tools: undefined, + const agentFileStateWithoutTools = { + agentFile: { + ...mockAgentFile, + tools: undefined, + }, + parsedRules: [], + parsedTools: null, + slug: null, + agentFileModel: null, }; - mockLoadPackageFromHub.mockReset(); - mockLoadPackageFromHub.mockResolvedValueOnce(agentWithoutTools); - await agentFileService.initialize("owner/agent"); + const baseOptions = {}; - const baseConfig = { - mcpServers: [{ name: "existing-mcp" }], - }; + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithoutTools, + ); - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), - ); - - expect(enhancedConfig.mcpServers).toHaveLength(1); - expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "existing-mcp" }); + // Should only have the model, no MCP servers + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("gpt-4-agent"); // Only model + expect(injected).toHaveLength(1); // Only model + expect(additional.mcpServers).toHaveLength(0); }); - it("should deduplicate MCP servers", async () => { - const agentFileWithDuplicateTools = { - ...mockAgentFile, - tools: "owner/mcp1, owner/mcp1:tool1, owner/mcp1:tool2", + it("should handle deduplicated MCP servers from parsing", async () => { + const agentFileStateWithDuplicateTools = { + agentFile: { + ...mockAgentFile, + tools: "owner/mcp1, owner/mcp1:tool1, owner/mcp1:tool2", + }, + parsedRules: [], + parsedTools: { + mcpServers: ["owner/mcp1"], // parseAgentFileTools already deduplicated + tools: [], + allBuiltIn: false, + }, + slug: null, + agentFileModel: null, }; - // Clear the default mock and setup specific mocks - mockLoadPackageFromHub.mockReset(); - // First call loads the agent file - mockLoadPackageFromHub.mockResolvedValueOnce(agentFileWithDuplicateTools); - // Second call loads the agent file model - mockLoadPackageFromHub.mockResolvedValueOnce({ - name: "gpt-4-agent", - provider: "openai", - }); - // Third call: The parseAgentFileTools will extract only unique MCP servers, so only one loadPackageFromHub call - mockLoadPackageFromHub.mockResolvedValueOnce({ name: "mcp1" }); + const baseOptions = {}; - await agentFileService.initialize("owner/agent"); + const { injected, additional } = + configService.getAdditionalBlocksFromOptions( + baseOptions, + agentFileStateWithDuplicateTools, + ); - const baseConfig = { - mcpServers: [{ name: "existing-mcp" }], // Changed to avoid confusion - }; - - const enhancedConfig = await configEnhancer.enhanceConfig( - baseConfig as any, - {}, - agentFileService.getState(), - ); - - // parseAgentFileTools deduplicates, so we only get mcp1 once - expect(enhancedConfig.mcpServers).toHaveLength(2); - expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "mcp1" }); - expect(enhancedConfig.mcpServers?.[1]).toEqual({ name: "existing-mcp" }); + // Should only process the deduplicated MCP server once + expect(mockDecodePackageIdentifier).toHaveBeenCalledWith("owner/mcp1"); + expect(injected).toHaveLength(2); // model + deduplicated MCP server }); }); }); diff --git a/extensions/cli/src/services/index.test.ts b/extensions/cli/src/services/index.test.ts index 07145f705..7450476a6 100644 --- a/extensions/cli/src/services/index.test.ts +++ b/extensions/cli/src/services/index.test.ts @@ -1,7 +1,6 @@ +import { Configuration, DefaultApi } from "@continuedev/sdk/dist/api"; import { vi } from "vitest"; -import { AgentFileService } from "./AgentFileService.js"; - import { initializeServices, services } from "./index.js"; // Mock the onboarding module @@ -13,6 +12,15 @@ vi.mock("../onboarding.js", () => ({ // Mock auth module vi.mock("../auth/workos.js", () => ({ loadAuthConfig: vi.fn().mockReturnValue({}), + getConfigUri: vi.fn().mockReturnValue(null), +})); + +// Mock the config loader +vi.mock("../configLoader.js", () => ({ + loadConfiguration: vi.fn().mockResolvedValue({ + config: { name: "test", version: "1.0.0" }, + source: { type: "test" }, + }), })); describe("initializeServices", () => { @@ -21,6 +29,37 @@ describe("initializeServices", () => { beforeEach(() => { // Reset all mocks vi.clearAllMocks(); + + // Mock service methods to avoid actual initialization + vi.spyOn(services.auth, "initialize").mockResolvedValue({ + authConfig: { + accessToken: "", + expiresAt: 123, + organizationId: "", + refreshToken: "", + userEmail: "", + }, + isAuthenticated: false, + }); + vi.spyOn(services.apiClient, "initialize").mockResolvedValue({ + apiClient: new DefaultApi( + new Configuration({ + basePath: "", + accessToken: "", + }), + ), + }); + vi.spyOn(services.agentFile, "initialize").mockResolvedValue({ + slug: null, + agentFile: null, + agentFileModel: null, + parsedRules: null, + parsedTools: null, + }); + vi.spyOn(services.config, "initialize").mockResolvedValue({ + config: { name: "test", version: "1.0.0" }, + configPath: undefined, + }); }); afterEach(() => { @@ -51,8 +90,9 @@ describe("initializeServices", () => { { slug: null, agentFile: null, - agentFileModelName: null, - agentFileService: expect.any(AgentFileService), + agentFileModel: null, + parsedRules: null, + parsedTools: null, }, ); }); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index 79b0b4269..bb3a50df6 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -51,7 +51,6 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { logger.debug("Initializing service registry"); const commandOptions = initOptions.options || {}; - // Handle onboarding for TUI mode (headless: false) unless explicitly skipped if (!initOptions.headless && !initOptions.skipOnboarding) { const authConfig = loadAuthConfig(); @@ -75,10 +74,40 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { commandOptions.config = CONFIG_PATH; } + serviceContainer.register( + SERVICE_NAMES.AUTH, + async () => { + return await authService.initialize(); + }, + [], // No dependencies + ); + + serviceContainer.register( + SERVICE_NAMES.API_CLIENT, + async () => { + const authState = await serviceContainer.get( + SERVICE_NAMES.AUTH, + ); + return apiClientService.initialize(authState.authConfig); + }, + [SERVICE_NAMES.AUTH], // Depends on auth + ); + serviceContainer.register( SERVICE_NAMES.AGENT_FILE, - () => agentFileService.initialize(commandOptions.agent), - [], + async () => { + const [authState, apiClientState] = await Promise.all([ + serviceContainer.get(SERVICE_NAMES.AUTH), + serviceContainer.get(SERVICE_NAMES.API_CLIENT), + ]); + + return await agentFileService.initialize( + commandOptions.agent, + authState, + apiClientState, + ); + }, + [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT], ); serviceContainer.register( @@ -131,29 +160,12 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { [SERVICE_NAMES.TOOL_PERMISSIONS], ); - serviceContainer.register( - SERVICE_NAMES.AUTH, - () => authService.initialize(), - [], // No dependencies - ); - serviceContainer.register( SERVICE_NAMES.UPDATE, () => updateService.initialize(), [], // No dependencies ); - serviceContainer.register( - SERVICE_NAMES.API_CLIENT, - async () => { - const authState = await serviceContainer.get( - SERVICE_NAMES.AUTH, - ); - return apiClientService.initialize(authState.authConfig); - }, - [SERVICE_NAMES.AUTH], // Depends on auth - ); - serviceContainer.register( SERVICE_NAMES.CONFIG, async () => { @@ -200,13 +212,14 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { } } - return configService.initialize({ + return await configService.initialize({ authConfig: finalAuthState.authConfig, configPath, // organizationId: finalAuthState.organizationId || null, apiClient: apiClientState.apiClient, agentFileState, injectedConfigOptions: commandOptions, + isHeadless: initOptions.headless, }); }, [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.AGENT_FILE], // Dependencies diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index cbe4121d4..8de9f26d9 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -2,6 +2,8 @@ import { AgentFile, AssistantUnrolled, ModelConfig, + parseAgentFileRules, + parseAgentFileTools, } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { AssistantConfig } from "@continuedev/sdk"; @@ -12,7 +14,6 @@ import { AuthConfig } from "../auth/workos.js"; import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; import { PermissionMode } from "../permissions/types.js"; -import { AgentFileService } from "./AgentFileService.js"; import { type MCPService } from "./MCPService.js"; /** @@ -119,8 +120,9 @@ export interface StorageSyncServiceState { export interface AgentFileServiceState { agentFile: AgentFile | null; slug: string | null; - agentFileModelName: string | null; - agentFileService: AgentFileService | null; + agentFileModel: ModelConfig | null; + parsedTools: ReturnType | null; + parsedRules: ReturnType | null; } export type { ChatHistoryState } from "./ChatHistoryService.js"; diff --git a/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts index 4564d20a9..24b83ee04 100644 --- a/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts @@ -80,7 +80,7 @@ describe("getAllTools - Tool Filtering", () => { expect(toolNames).toContain("Bash"); expect(toolNames).toContain("Read"); expect(toolNames).toContain("Write"); - expect(toolNames).toContain("Edit"); + expect(toolNames).toContain("MultiEdit"); }); test("should include all tools in auto mode", async () => { @@ -107,7 +107,7 @@ describe("getAllTools - Tool Filtering", () => { expect(toolNames).toContain("Bash"); expect(toolNames).toContain("Read"); expect(toolNames).toContain("Write"); - expect(toolNames).toContain("Edit"); + expect(toolNames).toContain("MultiEdit"); }); test("should respect explicit exclude in normal mode", async () => { diff --git a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts index b3af7eb65..6f97f9872 100644 --- a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts @@ -35,7 +35,7 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { // Should include write tools in normal mode expect(toolNames).toContain("Write"); - expect(toolNames).toContain("Edit"); + expect(toolNames).toContain("MultiEdit"); // Switch to plan mode (simulating Shift+Tab during streaming) toolPermissionService.switchMode("plan"); @@ -50,7 +50,7 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { // Should exclude write tools in plan mode expect(toolNames).not.toContain("Write"); - expect(toolNames).not.toContain("Edit"); + expect(toolNames).not.toContain("MultiEdit"); // Should still include read-only tools expect(toolNames).toContain("Read"); @@ -83,7 +83,7 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { // getAllTools should immediately reflect auto mode (all tools allowed) tools = await getAllTools(); expect(tools.map((t) => t.function.name)).toContain("Write"); - expect(tools.map((t) => t.function.name)).toContain("Edit"); + expect(tools.map((t) => t.function.name)).toContain("MultiEdit"); expect(tools.map((t) => t.function.name)).toContain("Read"); }); diff --git a/extensions/cli/src/ui/hooks/useConfigSelector.test.ts b/extensions/cli/src/ui/hooks/useConfigSelector.test.ts deleted file mode 100644 index 9272cdbc0..000000000 --- a/extensions/cli/src/ui/hooks/useConfigSelector.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, test } from "vitest"; - -describe("useConfigSelector", () => { - test("hook updated to use reactive service pattern", () => { - // This test documents that useConfigSelector has been updated - - // Changes made: - // 1. Removed manual onAssistantChange callback - // 2. Now calls services.config.updateConfigPath() - // 3. Lets ServiceContainer handle dependency management - // 4. Allows automatic UI updates via reactive system - - // The hook now properly: - // - Handles local config selection - // - Handles assistant config selection - // - Handles create config option - // - Provides error handling - // - Triggers reactive updates - - expect("hook").toBe("hook"); - }); - - test("integrates with reactive service system", () => { - // The hook integration follows the correct pattern: - // - User interaction → service method call - // - Service handles state update and notification - // - ServiceContainer manages dependency cascade - // - UI components re-render automatically - - expect("integration").toBe("integration"); - }); -}); diff --git a/packages/config-yaml/src/load/injectBlocks.test.ts b/packages/config-yaml/src/load/injectBlocks.test.ts new file mode 100644 index 000000000..14feb97dc --- /dev/null +++ b/packages/config-yaml/src/load/injectBlocks.test.ts @@ -0,0 +1,538 @@ +import { Registry } from "../interfaces/index.js"; +import { PackageIdentifier } from "../interfaces/slugs.js"; +import { ConfigYaml } from "../schemas/index.js"; +import { unrollBlocks } from "./unroll.js"; + +// Mock Registry for testing +class MockRegistry implements Registry { + private content: Record = {}; + + setContent(id: string, content: string) { + this.content[id] = content; + } + + async getContent(id: PackageIdentifier): Promise { + const key = + id.uriType === "file" + ? id.fileUri + : `${id.fullSlug.ownerSlug}/${id.fullSlug.packageSlug}`; + if (this.content[key]) { + return this.content[key]; + } + throw new Error(`Content not found for ${key}`); + } +} + +describe("injectBlocks with input-to-secret conversion", () => { + let mockRegistry: MockRegistry; + + beforeEach(() => { + mockRegistry = new MockRegistry(); + }); + + it("converts inputs to secrets in injected model blocks", async () => { + // Set up a basic assistant config + const assistant: ConfigYaml = { + name: "Test Assistant", + version: "1.0.0", + }; + + // Set up an injected block with input template variables in model + // Note: Block schema requires exactly 1 element in arrays + const injectedBlockContent = ` +name: OpenAI Block +version: 1.0.0 +schema: v1 +models: + - name: gpt-4 + provider: openai + model: gpt-4 + apiKey: \${{ inputs.openaiKey }} + apiBase: \${{ inputs.customEndpoint }} +`; + + const injectedBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/openai-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/openai-block.yaml", + injectedBlockContent, + ); + + // Unroll with injected blocks + const result = await unrollBlocks( + assistant, + mockRegistry, + [injectedBlockId], // inject the block + undefined, // no allowlist + undefined, // no blocklist + undefined, // no request options + ); + + expect(result.config).toBeDefined(); + expect(result.config!.models).toBeDefined(); + expect(result.config!.models!.length).toBe(1); + + // Check that inputs were converted to secrets in the model + const model = result.config!.models![0]!; + expect(model.apiKey).toBe("${{ secrets.openaiKey }}"); + expect(model.apiBase).toBe("${{ secrets.customEndpoint }}"); + expect(model.name).toBe("gpt-4"); + expect(model.provider).toBe("openai"); + expect(model.model).toBe("gpt-4"); + + // Check that no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.openaiKey"); + expect(configStr).not.toContain("inputs.customEndpoint"); + }); + + it("converts inputs to secrets in injected rule blocks", async () => { + const assistant: ConfigYaml = { + name: "Rule Test Assistant", + version: "1.0.0", + }; + + const injectedBlockContent = ` +name: Style Rules Block +version: 1.0.0 +schema: v1 +rules: + - "Use \${{ inputs.codeStyle }} formatting consistently" +`; + + const injectedBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/rules-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/rules-block.yaml", + injectedBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [injectedBlockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + + // Check that input was converted to secret in the rule + // Note: string rules get wrapped in objects with sourceFile when injected + const rule = result.config!.rules![0]!; + if (typeof rule === "string") { + expect(rule).toBe("Use ${{ secrets.codeStyle }} formatting consistently"); + } else { + expect(rule.rule).toBe( + "Use ${{ secrets.codeStyle }} formatting consistently", + ); + } + + // Check that no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.codeStyle"); + }); + + it("converts inputs to secrets in injected docs blocks", async () => { + const assistant: ConfigYaml = { + name: "Docs Test Assistant", + version: "1.0.0", + }; + + const injectedBlockContent = ` +name: Dynamic Docs Block +version: 1.0.0 +schema: v1 +docs: + - name: project-docs + startUrl: \${{ inputs.docsBaseUrl }}/api + rootUrl: \${{ inputs.docsBaseUrl }} + faviconUrl: \${{ inputs.docsBaseUrl }}/favicon.ico +`; + + const injectedBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/docs-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/docs-block.yaml", + injectedBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [injectedBlockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.docs).toBeDefined(); + expect(result.config!.docs!.length).toBe(1); + + // Check that inputs were converted to secrets in the doc config + const doc = result.config!.docs![0]!; + expect(doc.startUrl).toBe("${{ secrets.docsBaseUrl }}/api"); + expect(doc.rootUrl).toBe("${{ secrets.docsBaseUrl }}"); + expect(doc.faviconUrl).toBe("${{ secrets.docsBaseUrl }}/favicon.ico"); + expect(doc.name).toBe("project-docs"); + + // Check that no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.docsBaseUrl"); + }); + + it("converts inputs to secrets in injected prompt blocks", async () => { + const assistant: ConfigYaml = { + name: "Prompt Test Assistant", + version: "1.0.0", + }; + + const injectedBlockContent = ` +name: Dynamic Prompt Block +version: 1.0.0 +schema: v1 +prompts: + - name: custom-prompt + description: "A customizable prompt" + prompt: "You are a \${{ inputs.roleType }} assistant. Use \${{ inputs.responseStyle }} responses." +`; + + const injectedBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/prompt-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/prompt-block.yaml", + injectedBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [injectedBlockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.prompts).toBeDefined(); + expect(result.config!.prompts!.length).toBe(1); + + // Check that inputs were converted to secrets in the prompt + const prompt = result.config!.prompts![0]!; + expect(prompt.prompt).toBe( + "You are a ${{ secrets.roleType }} assistant. Use ${{ secrets.responseStyle }} responses.", + ); + expect(prompt.name).toBe("custom-prompt"); + expect(prompt.description).toBe("A customizable prompt"); + + // Check that no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.roleType"); + expect(configStr).not.toContain("inputs.responseStyle"); + }); + + it("handles multiple injected blocks of different types", async () => { + const assistant: ConfigYaml = { + name: "Multi-Block Assistant", + version: "1.0.0", + }; + + // Model block with inputs + const modelBlockContent = ` +name: API Model Block +version: 1.0.0 +schema: v1 +models: + - name: custom-api + provider: openai + model: \${{ inputs.modelName }} + apiKey: \${{ inputs.apiKey }} +`; + + // Rules block with inputs + const rulesBlockContent = ` +name: Dynamic Rules Block +version: 1.0.0 +schema: v1 +rules: + - "Follow \${{ inputs.codingStandard }} conventions" +`; + + const modelBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/model-block.yaml", + }; + + const rulesBlockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/rules-block.yaml", + }; + + mockRegistry.setContent("file:///test/model-block.yaml", modelBlockContent); + mockRegistry.setContent("file:///test/rules-block.yaml", rulesBlockContent); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [modelBlockId, rulesBlockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + + // Check model block conversion + expect(result.config!.models).toBeDefined(); + expect(result.config!.models!.length).toBe(1); + const model = result.config!.models![0]!; + expect(model.model).toBe("${{ secrets.modelName }}"); + expect(model.apiKey).toBe("${{ secrets.apiKey }}"); + + // Check rules block conversion + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + const rule = result.config!.rules![0]!; + if (typeof rule === "string") { + expect(rule).toBe("Follow ${{ secrets.codingStandard }} conventions"); + } else { + expect(rule.rule).toBe( + "Follow ${{ secrets.codingStandard }} conventions", + ); + } + + // Verify no input variables remain + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.modelName"); + expect(configStr).not.toContain("inputs.apiKey"); + expect(configStr).not.toContain("inputs.codingStandard"); + }); + + it("handles blocks with no template variables", async () => { + const assistant: ConfigYaml = { + name: "Static Assistant", + version: "1.0.0", + }; + + const staticBlockContent = ` +name: Static Block +version: 1.0.0 +schema: v1 +models: + - name: static-model + provider: ollama + model: llama3.1 + defaultCompletionOptions: + temperature: 0.5 + stream: false +`; + + const blockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/static-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/static-block.yaml", + staticBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [blockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + + // Check that static content is preserved as-is + expect(result.config!.models).toBeDefined(); + expect(result.config!.models!.length).toBe(1); + const model = result.config!.models![0]!; + expect(model.name).toBe("static-model"); + expect(model.provider).toBe("ollama"); + expect(model.model).toBe("llama3.1"); + expect(model.defaultCompletionOptions?.temperature).toBe(0.5); + expect(model.defaultCompletionOptions?.stream).toBe(false); + }); + + it("preserves non-input template variables", async () => { + const assistant: ConfigYaml = { + name: "Mixed Variables Assistant", + version: "1.0.0", + }; + + const mixedBlockContent = ` +name: Mixed Variables Block +version: 1.0.0 +schema: v1 +rules: + - "Input: \${{ inputs.userSetting }} | Secret: \${{ secrets.apiKey }} | Continue: \${{ continue.workspaceRoot }}" +`; + + const blockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/mixed-block.yaml", + }; + + mockRegistry.setContent("file:///test/mixed-block.yaml", mixedBlockContent); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [blockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + + const rule = result.config!.rules![0]!; + let ruleText: string; + if (typeof rule === "string") { + ruleText = rule; + } else { + ruleText = rule.rule; + } + + // Input should be converted to secret, others should remain unchanged + expect(ruleText).toBe( + "Input: ${{ secrets.userSetting }} | Secret: ${{ secrets.apiKey }} | Continue: ${{ continue.workspaceRoot }}", + ); + + // Verify only inputs were converted + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.userSetting"); + expect(configStr).toContain("secrets.apiKey"); + expect(configStr).toContain("continue.workspaceRoot"); + }); + + it("adds source file information to injected blocks", async () => { + const assistant: ConfigYaml = { + name: "Source Test Assistant", + version: "1.0.0", + }; + + const blockContent = ` +name: Source Block +version: 1.0.0 +schema: v1 +rules: + - name: custom-rule + rule: "Always add type hints with \${{ inputs.typeStyle }}" + description: "Enforce type hints for better code clarity" +`; + + const blockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/source-block.yaml", + }; + + mockRegistry.setContent("file:///test/source-block.yaml", blockContent); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [blockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + + // Check that rules have source file information + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + const rule = result.config!.rules![0]; + expect(rule).toMatchObject({ + name: "custom-rule", + rule: "Always add type hints with ${{ secrets.typeStyle }}", + description: "Enforce type hints for better code clarity", + sourceFile: "file:///test/source-block.yaml", + }); + + // Verify input was converted + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.typeStyle"); + }); + + it("handles complex nested input variables", async () => { + const assistant: ConfigYaml = { + name: "Nested Variables Assistant", + version: "1.0.0", + }; + + const nestedBlockContent = ` +name: Nested Variables Block +version: 1.0.0 +schema: v1 +rules: + - "Database config: host=\${{ inputs.db.host }};port=\${{ inputs.db.port }};user=\${{ inputs.db.user }}" +`; + + const blockId: PackageIdentifier = { + uriType: "file", + fileUri: "file:///test/nested-block.yaml", + }; + + mockRegistry.setContent( + "file:///test/nested-block.yaml", + nestedBlockContent, + ); + + const result = await unrollBlocks( + assistant, + mockRegistry, + [blockId], + undefined, + undefined, + undefined, + ); + + expect(result.config).toBeDefined(); + expect(result.config!.rules).toBeDefined(); + expect(result.config!.rules!.length).toBe(1); + + const rule = result.config!.rules![0]!; + let ruleText: string; + if (typeof rule === "string") { + ruleText = rule; + } else { + ruleText = rule.rule; + } + + // All nested inputs should be converted to secrets + expect(ruleText).toBe( + "Database config: host=${{ secrets.db.host }};port=${{ secrets.db.port }};user=${{ secrets.db.user }}", + ); + + // Verify all nested inputs were converted + const configStr = JSON.stringify(result.config); + expect(configStr).not.toContain("inputs.db.host"); + expect(configStr).not.toContain("inputs.db.port"); + expect(configStr).not.toContain("inputs.db.user"); + }); +}); diff --git a/packages/config-yaml/src/load/unroll.test.ts b/packages/config-yaml/src/load/unroll.test.ts index fb94017b1..9a308dd9b 100644 --- a/packages/config-yaml/src/load/unroll.test.ts +++ b/packages/config-yaml/src/load/unroll.test.ts @@ -1,5 +1,8 @@ import { PackageIdentifier } from "../interfaces/slugs.js"; -import { parseMarkdownRuleOrAssistantUnrolled } from "./unroll.js"; +import { + parseMarkdownRuleOrAssistantUnrolled, + replaceInputsWithSecrets, +} from "./unroll.js"; describe("parseMarkdownRuleOrAssistantUnrolled tests", () => { it("parses valid YAML content as AssistantUnrolled", () => { @@ -88,3 +91,186 @@ model: # should be models expect(rule).toHaveProperty("rule", dubiousContent); }); }); + +describe("replaceInputsWithSecrets tests", () => { + it("replaces single input with secret", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + value: \${{ inputs.apiKey }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.apiKey }}"); + expect(result).not.toContain("\${{ inputs.apiKey }}"); + }); + + it("replaces multiple inputs with secrets", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + apiKey: \${{ inputs.apiKey }} + dbPassword: \${{ inputs.dbPassword }} + endpoint: \${{ inputs.endpoint }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.apiKey }}"); + expect(result).toContain("\${{ secrets.dbPassword }}"); + expect(result).toContain("\${{ secrets.endpoint }}"); + expect(result).not.toContain("\${{ inputs.apiKey }}"); + expect(result).not.toContain("\${{ inputs.dbPassword }}"); + expect(result).not.toContain("\${{ inputs.endpoint }}"); + }); + + it("leaves secrets template variables unchanged", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + apiKey: \${{ secrets.existingSecret }} + dbPassword: \${{ inputs.dbPassword }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.existingSecret }}"); + expect(result).toContain("\${{ secrets.dbPassword }}"); + expect(result).not.toContain("\${{ inputs.dbPassword }}"); + }); + + it("leaves other template variables unchanged", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + apiKey: \${{ inputs.apiKey }} + environment: \${{ continue.environment }} + customVar: \${{ other.variable }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.apiKey }}"); + expect(result).toContain("\${{ continue.environment }}"); + expect(result).toContain("\${{ other.variable }}"); + expect(result).not.toContain("\${{ inputs.apiKey }}"); + }); + + it("handles yaml with no input template variables", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + staticValue: "hello world" + secretValue: \${{ secrets.mySecret }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toBe(yamlContent); // Should remain unchanged + expect(result).toContain("\${{ secrets.mySecret }}"); + }); + + it("handles empty string", () => { + const yamlContent = ""; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toBe(""); + }); + + it("handles inputs with whitespace in template variables", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + value1: \${{ inputs.apiKey }} + value2: \${{\tinputs.tabbed\t}} + value3: \${{\n inputs.multiline \n}} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.apiKey }}"); + expect(result).toContain("\${{ secrets.tabbed }}"); + expect(result).toContain("\${{ secrets.multiline }}"); + expect(result).not.toContain("inputs.apiKey"); + expect(result).not.toContain("inputs.tabbed"); + expect(result).not.toContain("inputs.multiline"); + }); + + it("handles nested input keys", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + config: \${{ inputs.database.host }} + port: \${{ inputs.database.port }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.database.host }}"); + expect(result).toContain("\${{ secrets.database.port }}"); + expect(result).not.toContain("inputs.database.host"); + expect(result).not.toContain("inputs.database.port"); + }); + + it("handles multiple inputs on same line", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + connectionString: "host=\${{ inputs.host }};port=\${{ inputs.port }};user=\${{ inputs.user }}" +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.host }}"); + expect(result).toContain("\${{ secrets.port }}"); + expect(result).toContain("\${{ secrets.user }}"); + expect(result).not.toContain("inputs.host"); + expect(result).not.toContain("inputs.port"); + expect(result).not.toContain("inputs.user"); + }); + + it("preserves malformed template variables that don't start with inputs", () => { + const yamlContent = ` +name: Test +version: 1.0.0 +data: + value1: \${{ inputs.valid }} + value2: \${{ malformed.inputs.something }} + value3: \${{ input.typo }} +`; + const result = replaceInputsWithSecrets(yamlContent); + expect(result).toContain("\${{ secrets.valid }}"); + expect(result).toContain("\${{ malformed.inputs.something }}"); // Should remain unchanged + expect(result).toContain("\${{ input.typo }}"); // Should remain unchanged (typo in 'input') + expect(result).not.toContain("inputs.valid"); + }); + + it("handles YAML with complex structure", () => { + const yamlContent = ` +name: Complex Test +version: 1.0.0 +models: + - name: gpt-4 + apiKey: \${{ inputs.openaiKey }} +prompts: + - name: system + content: "You are a helpful assistant. API key: \${{ inputs.openaiKey }}" +rules: + - "Use \${{ inputs.style }} formatting" +data: + config: + database: + host: \${{ inputs.dbHost }} + password: \${{ inputs.dbPassword }} + external: + secret: \${{ secrets.external }} + other: \${{ other.variable }} +`; + const result = replaceInputsWithSecrets(yamlContent); + // Check all inputs were replaced with secrets + expect(result).toContain("\${{ secrets.openaiKey }}"); + expect(result).toContain("\${{ secrets.style }}"); + expect(result).toContain("\${{ secrets.dbHost }}"); + expect(result).toContain("\${{ secrets.dbPassword }}"); + // Check that non-input variables remain unchanged + expect(result).toContain("\${{ secrets.external }}"); + expect(result).toContain("\${{ other.variable }}"); + // Check that no input variables remain + expect(result).not.toContain("inputs.openaiKey"); + expect(result).not.toContain("inputs.style"); + expect(result).not.toContain("inputs.dbHost"); + expect(result).not.toContain("inputs.dbPassword"); + }); +}); diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index bc8aa3785..cc05ccaf0 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -239,6 +239,18 @@ export async function unrollAssistant( return result; } +export function replaceInputsWithSecrets(yamlContent: string): string { + const inputsToSecretsMap: Record = {}; + + getTemplateVariables(yamlContent) + .filter((v) => v.startsWith("inputs.")) + .forEach((v) => { + inputsToSecretsMap[v] = `\${{ ${v.replace("inputs.", "secrets.")} }}`; + }); + + return fillTemplateVariables(yamlContent, inputsToSecretsMap); +} + function renderTemplateData( rawYaml: string, templateData: Partial, @@ -284,7 +296,7 @@ export async function unrollAssistantFromContent( // Convert all of the template variables to FQSNs // Secrets from the block will have the assistant slug prepended to the FQSN - const templatedYaml = renderTemplateData(rawUnrolledYaml, { + let templatedYaml = renderTemplateData(rawUnrolledYaml, { secrets: extractFQSNMap(rawUnrolledYaml, [id]), }); @@ -529,16 +541,13 @@ export async function unrollBlocks( const injectedBlockPromises = injectBlocks.map(async (injectBlock) => { try { const blockConfigYaml = await registry.getContent(injectBlock); - const parsedBlock = parseMarkdownRuleOrConfigYaml( - blockConfigYaml, + const blockConfigYamlWithSecrets = + replaceInputsWithSecrets(blockConfigYaml); + const resolvedBlock = parseMarkdownRuleOrConfigYaml( + blockConfigYamlWithSecrets, injectBlock, ); - const blockType = getBlockType(parsedBlock); - const resolvedBlock = await resolveBlock( - injectBlock, - undefined, - registry, - ); + const blockType = getBlockType(resolvedBlock); return { blockType, diff --git a/packages/config-yaml/src/markdown/agentFiles.ts b/packages/config-yaml/src/markdown/agentFiles.ts index 5f072c4ac..4450cda0c 100644 --- a/packages/config-yaml/src/markdown/agentFiles.ts +++ b/packages/config-yaml/src/markdown/agentFiles.ts @@ -153,3 +153,10 @@ export function parseAgentFileTools(toolsString?: string): ParsedAgentTools { allBuiltIn, }; } + +export function parseAgentFileRules(rules: string) { + return rules + .split(",") + .map((r) => r.trim()) + .filter(Boolean); +}