Merge pull request #8069 from continuedev/dallin/workflow-files

CLI workflows
This commit is contained in:
Dallin Romney 2025-10-05 23:44:39 -07:00 • committed by GitHub
commit fec051027b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
61 changed files with 3024 additions and 1854 deletions

View file

@ -57,8 +57,7 @@ Users can switch modes during chat sessions using:
Modes are implemented through the permission system:
- **ModeService**: Singleton service managing the current mode and initialization
- **ToolPermissionService**: Extended to support mode-specific policies with highest priority
- **ToolPermissionService**: Rectifies current mode and tool policies
- **ModeIndicator**: UI component showing current mode (hidden for normal mode)
- **Keyboard shortcuts**: Shift+Tab cycles through modes instantly
- **Backward compatibility**: Existing `--readonly` flag maps to plan mode

View file

@ -1,5 +0,0 @@
import { vi } from "vitest";
export const processPromptOrRule = vi.fn<(spec: string) => Promise<string>>();
export const processPrompt = vi.fn<(prompt: string) => Promise<string>>();

View file

@ -1,3 +1,4 @@
import { ToolPermissionService } from "src/services/ToolPermissionService.js";
import { vi } from "vitest";
export const services = {
@ -7,14 +8,23 @@ export const services = {
switchOrganization: vi.fn(() => Promise.resolve({})),
getAvailableOrganizations: vi.fn(() => Promise.resolve([])),
},
toolPermissions: vi.mocked(new ToolPermissionService()),
};
export const reloadService = vi.fn(() => Promise.resolve(undefined));
export const SERVICE_NAMES = {
AUTH: "auth",
API_CLIENT: "apiClient",
CONFIG: "config",
MODEL: "model",
MCP: "mcp",
};
API_CLIENT: "apiClient",
TOOL_PERMISSIONS: "toolPermissions",
FILE_INDEX: "fileIndex",
RESOURCE_MONITORING: "resourceMonitoring",
SYSTEM_MESSAGE: "systemMessage",
CHAT_HISTORY: "chatHistory",
UPDATE: "update",
STORAGE_SYNC: "storageSync",
WORKFLOW: "workflow",
} as const;

View file

@ -1,75 +0,0 @@
import { beforeEach, describe, expect, it } from "vitest";
import { parseArgs } from "./args.js";
describe("parseArgs --mcp flag", () => {
beforeEach(() => {
// Clear process.argv before each test
process.argv = ["node", "test"];
});
it("should parse single MCP from --mcp flag", () => {
process.argv = ["node", "test", "--mcp", "my-org/my-mcp"];
const result = parseArgs();
expect(result.mcps).toEqual(["my-org/my-mcp"]);
});
it("should parse multiple MCPs from multiple --mcp flags", () => {
process.argv = ["node", "test", "--mcp", "org1/mcp1", "--mcp", "org2/mcp2"];
const result = parseArgs();
expect(result.mcps).toEqual(["org1/mcp1", "org2/mcp2"]);
});
it("should handle MCP flag with other flags", () => {
process.argv = [
"node",
"test",
"--config",
"my-config.yaml",
"--mcp",
"my-org/my-mcp",
"--org",
"test-org",
];
const result = parseArgs();
expect(result.configPath).toBe("my-config.yaml");
expect(result.mcps).toEqual(["my-org/my-mcp"]);
expect(result.organizationSlug).toBe("test-org");
});
it("should handle MCP flag with prompt", () => {
process.argv = ["node", "test", "--mcp", "my-org/my-mcp", "hello world"];
const result = parseArgs();
expect(result.mcps).toEqual(["my-org/my-mcp"]);
expect(result.prompt).toBe("hello world");
});
it("should ignore MCP and rule flag values when extracting prompt", () => {
process.argv = [
"node",
"test",
"actual prompt",
"--rule",
"my-rule",
"--mcp",
"my-org/my-mcp",
];
const result = parseArgs();
expect(result.prompt).toBe("actual prompt");
expect(result.rules).toEqual(["my-rule"]);
expect(result.mcps).toEqual(["my-org/my-mcp"]);
});
it("should handle MCP flag without value", () => {
process.argv = ["node", "test", "--mcp"];
const result = parseArgs();
expect(result.mcps).toEqual([]);
});
it("should handle MCP flag at the end without value", () => {
process.argv = ["node", "test", "my prompt", "--mcp"];
const result = parseArgs();
expect(result.prompt).toBe("my prompt");
expect(result.mcps).toEqual([]);
});
});

View file

@ -1,84 +0,0 @@
import { describe, it, expect, beforeEach, afterAll } from "vitest";
import { parseArgs, processPromptOrRule } from "./args.js";
describe("args --prompt flag", () => {
const originalArgv = process.argv;
beforeEach(() => {
// Reset process.argv for each test
process.argv = ["node", "script.js"];
});
afterAll(() => {
// Restore original process.argv after all tests
process.argv = originalArgv;
});
it("should parse single prompt from --prompt flag", () => {
process.argv = ["node", "script.js", "--prompt", "my-prompt"];
const result = parseArgs();
expect(result.prompts).toEqual(["my-prompt"]);
});
it("should parse multiple prompts from multiple --prompt flags", () => {
process.argv = [
"node",
"script.js",
"--prompt",
"prompt1",
"--prompt",
"prompt2",
];
const result = parseArgs();
expect(result.prompts).toEqual(["prompt1", "prompt2"]);
});
it("should handle mixed flags including --prompt", () => {
process.argv = [
"node",
"script.js",
"--config",
"myconfig",
"--prompt",
"myprompt",
"--resume",
];
const result = parseArgs();
expect(result.configPath).toBe("myconfig");
expect(result.prompts).toEqual(["myprompt"]);
expect(result.resume).toBe(true);
});
it("should not include --prompt value in non-flag arguments", () => {
process.argv = [
"node",
"script.js",
"--prompt",
"prompt-value",
"actual-prompt",
];
const result = parseArgs();
expect(result.prompts).toEqual(["prompt-value"]);
expect(result.prompt).toBe("actual-prompt");
});
it("should handle both --rule and --prompt flags", () => {
process.argv = [
"node",
"script.js",
"--rule",
"my-rule",
"--prompt",
"my-prompt",
];
const result = parseArgs();
expect(result.rules).toEqual(["my-rule"]);
expect(result.prompts).toEqual(["my-prompt"]);
});
it("should process direct string content", async () => {
const result = await processPromptOrRule("This is a direct prompt");
expect(result).toBe("This is a direct prompt");
});
});

View file

@ -1,222 +1,6 @@
import { vi } from "vitest";
import { parseArgs, processPromptOrRule } from "./args.js";
describe("parseArgs", () => {
const originalArgv = process.argv;
beforeEach(() => {
// Reset process.argv before each test
process.argv = ["node", "script.js"];
});
afterAll(() => {
// Restore original argv
process.argv = originalArgv;
});
it("should return default values when no arguments provided", () => {
const result = parseArgs();
expect(result).toEqual({});
});
it("should set resume to true when --resume flag is present", () => {
process.argv = ["node", "script.js", "--resume"];
const result = parseArgs();
expect(result.resume).toBe(true);
});
it("should set readonly to true when --readonly flag is present", () => {
process.argv = ["node", "script.js", "--readonly"];
const result = parseArgs();
expect(result.readonly).toBe(true);
});
it("should parse config path from --config flag", () => {
process.argv = ["node", "script.js", "--config", "/path/to/config.yaml"];
const result = parseArgs();
expect(result.configPath).toBe("/path/to/config.yaml");
});
it("should parse single rule from --rule flag", () => {
process.argv = ["node", "script.js", "--rule", "my-rule"];
const result = parseArgs();
expect(result.rules).toEqual(["my-rule"]);
});
it("should parse multiple rules from multiple --rule flags", () => {
process.argv = ["node", "script.js", "--rule", "rule1", "--rule", "rule2"];
const result = parseArgs();
expect(result.rules).toEqual(["rule1", "rule2"]);
});
it("should parse prompt from last non-flag argument", () => {
process.argv = ["node", "script.js", "Hello world"];
const result = parseArgs();
expect(result.prompt).toBe("Hello world");
});
it("should handle multiple flags together", () => {
process.argv = ["node", "script.js", "--print", "--readonly", "--resume"];
const result = parseArgs();
expect(result).toEqual({
readonly: true,
resume: true,
});
});
it("should handle config flag with other flags", () => {
process.argv = ["node", "script.js", "--config", "config.yaml", "--print"];
const result = parseArgs();
expect(result).toEqual({
configPath: "config.yaml",
});
});
it("should handle rule flag with other flags", () => {
process.argv = ["node", "script.js", "--rule", "my-rule", "--print"];
const result = parseArgs();
expect(result).toEqual({
rules: ["my-rule"],
});
});
it("should handle prompt with flags", () => {
process.argv = ["node", "script.js", "--print", "What is the weather?"];
const result = parseArgs();
expect(result).toEqual({
prompt: "What is the weather?",
});
});
it("should handle config flag with prompt", () => {
process.argv = [
"node",
"script.js",
"--config",
"config.yaml",
"Test prompt",
];
const result = parseArgs();
expect(result).toEqual({
configPath: "config.yaml",
prompt: "Test prompt",
});
});
it("should handle rule flag with prompt", () => {
process.argv = ["node", "script.js", "--rule", "my-rule", "Test prompt"];
const result = parseArgs();
expect(result).toEqual({
rules: ["my-rule"],
prompt: "Test prompt",
});
});
it("should ignore config and rule flag values when extracting prompt", () => {
process.argv = [
"node",
"script.js",
"--config",
"config.yaml",
"--rule",
"my-rule",
"actual-prompt",
];
const result = parseArgs();
expect(result.prompt).toBe("actual-prompt");
expect(result.configPath).toBe("config.yaml");
expect(result.rules).toEqual(["my-rule"]);
});
it("should handle multiple non-flag arguments and use the last one as prompt", () => {
process.argv = ["node", "script.js", "first", "second", "third"];
const result = parseArgs();
expect(result.prompt).toBe("third");
});
it("should handle complex argument combinations", () => {
process.argv = [
"node",
"script.js",
"--print",
"--config",
"my-config.yaml",
"--rule",
"rule1",
"--rule",
"rule2",
"--readonly",
"--resume",
"Complex prompt with spaces",
];
const result = parseArgs();
expect(result).toEqual({
configPath: "my-config.yaml",
rules: ["rule1", "rule2"],
readonly: true,
resume: true,
prompt: "Complex prompt with spaces",
});
});
it("should handle config flag without value", () => {
process.argv = ["node", "script.js", "--config"];
const result = parseArgs();
expect(result.configPath).toBeUndefined();
});
it("should handle rule flag without value", () => {
process.argv = ["node", "script.js", "--rule"];
const result = parseArgs();
expect(result.rules).toEqual([]);
});
it("should handle config flag at the end without value", () => {
process.argv = ["node", "script.js", "--print", "--config"];
const result = parseArgs();
expect(result.configPath).toBeUndefined();
});
it("should handle rule flag at the end without value", () => {
process.argv = ["node", "script.js", "--print", "--rule"];
const result = parseArgs();
expect(result.rules).toEqual([]);
});
it("should handle empty arguments array", () => {
process.argv = ["node", "script.js"];
const result = parseArgs();
expect(result).toEqual({});
});
it("should handle multiple boolean flags", () => {
process.argv = ["node", "script.js", "--readonly", "--resume"];
const result = parseArgs();
expect(result.readonly).toBe(true);
expect(result.resume).toBe(true);
});
it("should handle multiple rules with complex combinations", () => {
process.argv = [
"node",
"script.js",
"--rule",
"file.txt",
"--rule",
"owner/package",
"--rule",
"direct string rule",
];
const result = parseArgs();
expect(result.rules).toEqual([
"file.txt",
"owner/package",
"direct string rule",
]);
});
});
import { processRule as processPromptOrRule } from "./hubLoader.js";
describe("processPromptOrRule (loadRuleFromHub integration)", () => {
// Mock fetch for hub tests
const originalFetch = global.fetch;

View file

@ -1,147 +0,0 @@
export interface CommandLineArgs {
configPath?: string;
organizationSlug?: string; // Organization slug to use for this session
prompt?: string; // Optional prompt argument
resume?: boolean; // Resume from last session
fork?: string; // Fork from an existing session ID
readonly?: boolean; // Start in plan mode (backward compatibility)
rules?: string[]; // Array of rule specifications
mcps?: string[]; // Array of MCP server slugs from the hub
models?: string[]; // Array of model slugs from the hub
prompts?: string[]; // Array of prompt slugs from the hub
format?: "json"; // Output format for headless mode
}
// Re-export hub loader functions for backward compatibility
export { loadMcpFromHub, processRule } from "./hubLoader.js";
// Alias processRule as processPromptOrRule for backward compatibility
export { processRule as processPromptOrRule } from "./hubLoader.js";
/**
* Extract values for a specific flag that can appear multiple times
*/
function extractMultipleFlags(args: string[], flagName: string): string[] {
const indices: number[] = [];
for (let i = 0; i < args.length; i++) {
if (args[i] === flagName) {
indices.push(i);
}
}
const values: string[] = [];
for (const index of indices) {
if (index + 1 < args.length && !args[index + 1].startsWith("--")) {
values.push(args[index + 1]);
}
}
return values;
}
/**
* Extract value for a single-value flag
*/
function extractSingleFlag(
args: string[],
flagName: string,
): string | undefined {
const index = args.indexOf(flagName);
if (
index !== -1 &&
index + 1 < args.length &&
!args[index + 1].startsWith("--")
) {
return args[index + 1];
}
return undefined;
}
/**
* Parse command line arguments for non-permission related flags
* @deprecated Most functionality has been moved to services. This is only kept for backward compatibility.
* @returns Parsed command line arguments
*/
export function parseArgs(): CommandLineArgs {
const args = process.argv.slice(2);
const result: CommandLineArgs = {};
// Parse boolean flags
if (args.includes("--resume")) {
result.resume = true;
}
if (args.includes("--readonly")) {
result.readonly = true;
}
// Parse fork flag
const forkValue = extractSingleFlag(args, "--fork");
if (forkValue) {
result.fork = forkValue;
}
// Parse single-value flags
const formatValue = extractSingleFlag(args, "--format");
if (formatValue === "json") {
result.format = "json";
}
result.configPath = extractSingleFlag(args, "--config");
const orgValue = extractSingleFlag(args, "--org");
if (orgValue) {
result.organizationSlug =
orgValue.toLowerCase() === "personal" ? undefined : orgValue;
}
// Parse multi-value flags
const rules = extractMultipleFlags(args, "--rule");
if (rules.length > 0) {
result.rules = rules;
} else if (args.includes("--rule")) {
result.rules = [];
}
const mcps = extractMultipleFlags(args, "--mcp");
if (mcps.length > 0) {
result.mcps = mcps;
} else if (args.includes("--mcp")) {
// Ensure we have an empty array if --mcp flag is present but has no values
result.mcps = [];
}
const models = extractMultipleFlags(args, "--model");
if (models.length > 0) {
result.models = models;
} else if (args.includes("--model")) {
result.models = [];
}
const prompts = extractMultipleFlags(args, "--prompt");
if (prompts.length > 0) {
result.prompts = prompts;
} else if (args.includes("--prompt")) {
result.prompts = [];
}
// Extract prompt from non-flag arguments
const flagsWithValues = [
"--config",
"--org",
"--rule",
"--mcp",
"--model",
"--prompt",
"--format",
"--fork",
];
const nonFlagArgs = args.filter((arg, index) => {
if (arg.startsWith("--") || arg === "-p") return false;
const prevArg = index > 0 ? args[index - 1] : "";
return !flagsWithValues.includes(prevArg);
});
if (nonFlagArgs.length > 0) {
result.prompt = nonFlagArgs[nonFlagArgs.length - 1];
}
return result;
}

View file

@ -21,6 +21,8 @@ export interface BaseCommandOptions {
ask?: string[];
/** Array of tools to exclude from use (--exclude) */
exclude?: string[];
/** Workflow slug from the hub (--workflow) */
workflow?: string;
}
/**

View file

@ -12,7 +12,11 @@ import * as logging from "../logging.js";
import { sentryService } from "../sentry.js";
import { initializeServices, services } from "../services/index.js";
import { serviceContainer } from "../services/ServiceContainer.js";
import { ModelServiceState, SERVICE_NAMES } from "../services/types.js";
import {
ModelServiceState,
SERVICE_NAMES,
WorkflowServiceState,
} from "../services/types.js";
import {
loadSession,
updateSessionHistory,
@ -474,9 +478,15 @@ async function runHeadlessMode(
const { processAndCombinePrompts } = await import(
"../util/promptProcessor.js"
);
const workflowState = await serviceContainer.get<WorkflowServiceState>(
SERVICE_NAMES.WORKFLOW,
);
const initialPrompt =
`${workflowState?.workflowFile?.prompt ?? ""}\n\n${prompt ?? ""}`.trim() ||
undefined;
const initialUserInput = await processAndCombinePrompts(
options.prompt,
prompt,
initialPrompt,
);
let isFirstMessage = true;
@ -532,7 +542,6 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
if (!options.headless) {
// Process flags for TUI mode
const { permissionOverrides } = processCommandFlags(options);
// Initialize services with onboarding handled internally
await initializeServices({
options,
@ -540,9 +549,17 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
toolPermissionOverrides: permissionOverrides,
});
const workflowState = await serviceContainer.get<WorkflowServiceState>(
SERVICE_NAMES.WORKFLOW,
);
const initialPrompt =
`${workflowState?.workflowFile?.prompt ?? ""}\n\n${prompt ?? ""}`.trim() ||
undefined;
// Start TUI with skipOnboarding since we already handled it
const tuiOptions: any = {
initialPrompt: prompt,
initialPrompt,
resume: options.resume,
fork: options.fork,
config: options.config,

View file

@ -2,6 +2,7 @@ import chalk from "chalk";
import type { ChatHistoryItem } from "core/index.js";
import express, { Request, Response } from "express";
import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js";
import { posthogService } from "src/telemetry/posthogService.js";
import { getAccessToken, getAssistantSlug } from "../auth/workos.js";
@ -72,9 +73,10 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
});
// Get initialized services from the service container
const [configState, modelState] = await Promise.all([
const [configState, modelState, permissionsState] = await Promise.all([
getService<ConfigServiceState>(SERVICE_NAMES.CONFIG),
getService<ModelServiceState>(SERVICE_NAMES.MODEL),
getService<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS),
]);
if (!configState.config || !modelState.llmApi || !modelState.model) {
@ -117,6 +119,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
// Initialize session with system message
const systemMessage = await constructSystemMessage(
permissionsState.currentMode,
options.rule,
undefined,
true,

View file

@ -13,11 +13,34 @@ vi.mock("./hubLoader.js", () => ({
// 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 workflow state
vi.mock("./services/ServiceContainer.js", () => ({
serviceContainer: {
get: vi.fn(() =>
Promise.resolve({
workflowService: null,
workflowModelName: null,
workflowFile: null,
workflow: null,
}),
),
},
}));
vi.mock("./services/types.js", () => ({
SERVICE_NAMES: {
WORKFLOW: "workflow",
},
}));
describe("ConfigEnhancer", () => {
let enhancer: ConfigEnhancer;
let mockConfig: any;
@ -199,4 +222,42 @@ describe("ConfigEnhancer", () => {
command: "existing-mcp",
});
});
it("should handle workflow integration gracefully when no workflow", async () => {
// The mocked service container returns null workflow state
const options: BaseCommandOptions = {
rule: ["test-rule"],
};
const config = await enhancer.enhanceConfig(mockConfig, options);
// Should work normally when no workflow is active
expect(config.rules).toEqual(["test-rule"]);
});
it("should handle workflow integration when workflow is active", async () => {
// Mock service container to return active workflow
const options: BaseCommandOptions = {
rule: ["user-rule"],
prompt: ["user-prompt"],
};
const config = await enhancer.enhanceConfig(mockConfig, options, {
workflowFile: {
name: "Test Workflow",
prompt: "You are a test assistant",
rules: "Always be helpful",
model: "gpt-4",
tools: "bash,read",
},
slug: "owner/test-workflow",
workflowModelName: null,
workflowService: null,
});
// Should have both workflow and user rules
expect(config.rules).toHaveLength(2);
expect(config.rules?.[0]).toBe("Always be helpful"); // Workflow rule first
expect(config.rules?.[1]).toBe("user-rule"); // User rule second
});
});

View file

@ -1,43 +1,115 @@
import { AssistantUnrolled, Rule } from "@continuedev/config-yaml";
import {
AssistantUnrolled,
parseWorkflowTools,
Rule,
} from "@continuedev/config-yaml";
import { BaseCommandOptions } from "./commands/BaseCommandOptions.js";
import {
loadPackageFromHub,
loadPackagesFromHub,
mcpProcessor,
modelProcessor,
processRule,
} from "./hubLoader.js";
import { WorkflowServiceState } 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 enhanceConfigFromWorkflow(
config: AssistantUnrolled,
_options: BaseCommandOptions | undefined,
workflowState?: WorkflowServiceState,
) {
const enhancedConfig = { ...config };
const options = { ..._options };
if (workflowState?.workflowFile) {
const { rules, model, tools, prompt } = workflowState?.workflowFile;
if (rules) {
options.rule = [
...rules
.split(",")
.filter(Boolean)
.map((r) => r.trim()),
...(options.rule || []),
];
}
if (tools) {
try {
const parsedTools = parseWorkflowTools(tools);
if (parsedTools.mcpServers.length > 0) {
options.mcp = [...parsedTools.mcpServers, ...(options.mcp || [])];
}
} catch (e) {
logger.error("Failed to parse workflow tools", e);
}
}
// --model takes precedence over workflow model
if (model) {
try {
const workflowModel = await loadPackageFromHub(model, modelProcessor);
enhancedConfig.models = [
workflowModel,
...(enhancedConfig.models ?? []),
];
workflowState?.workflowService?.setWorkflowModelName(
workflowModel.name,
);
} catch (e) {
logger.error("Failed to load workflow model", e);
}
}
// Workflow prompt is included as a slash command, initial kickoff is handled elsewhere
if (prompt) {
enhancedConfig.prompts = [
{
name: `Workflow prompt (${workflowState.workflowFile.name})`,
prompt,
description: workflowState.workflowFile.description,
},
...(enhancedConfig.prompts ?? []),
];
}
}
return { options, enhancedConfig };
}
/**
* Apply all enhancements to a configuration
*/
async enhanceConfig(
config: AssistantUnrolled,
options: BaseCommandOptions,
_options?: BaseCommandOptions,
workflowState?: WorkflowServiceState,
): Promise<AssistantUnrolled> {
let enhancedConfig = { ...config };
const enhanced = await this.enhanceConfigFromWorkflow(
config,
_options,
workflowState,
);
let { enhancedConfig } = enhanced;
const { options } = enhanced;
// Apply rules
// Inject resolved items into config
if (options.rule && options.rule.length > 0) {
enhancedConfig = await this.injectRules(enhancedConfig, options.rule);
}
// Apply MCPs
if (options.mcp && options.mcp.length > 0) {
enhancedConfig = await this.injectMcps(enhancedConfig, options.mcp);
}
// Apply models
if (options.model && options.model.length > 0) {
enhancedConfig = await this.injectModels(enhancedConfig, options.model);
}
// Apply prompts
if (options.prompt && options.prompt.length > 0) {
enhancedConfig = await this.injectPrompts(enhancedConfig, options.prompt);
}
@ -105,11 +177,8 @@ export class ConfigEnhancer {
const modifiedConfig = { ...config };
// Prepend processed MCPs to existing mcpServers array for consistency
const existingMcpServers = (modifiedConfig as any).mcpServers || [];
(modifiedConfig as any).mcpServers = [
...processedMcps,
...existingMcpServers,
];
const existingMcpServers = modifiedConfig.mcpServers || [];
modifiedConfig.mcpServers = [...processedMcps, ...existingMcpServers];
return modifiedConfig;
}
@ -123,26 +192,28 @@ export class ConfigEnhancer {
): Promise<AssistantUnrolled> {
const processedModels = await loadPackagesFromHub(models, modelProcessor);
// Clone the config to avoid mutating the original
const modifiedConfig = { ...config };
// Prepend processed models to existing models array so they become the default
const existingModels = (modifiedConfig as any).models || [];
(modifiedConfig as any).models = [...processedModels, ...existingModels];
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<AssistantUnrolled> {
// For prompts, we'll need a different approach since they become slash commands
// This is a placeholder implementation
logger.debug("Prompt injection not yet implemented", { prompts });
// 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;
}
}

View file

@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import { useServiceContainer } from "../services/ServiceContainerContext.js";
import { ServiceResult } from "../services/types.js";
@ -96,47 +96,54 @@ export function useServices<T extends Record<string, any>>(
allReady: boolean;
} {
const container = useServiceContainer();
const [services, setServices] = useState<Partial<T>>({});
const getServiceStates = useCallback(() => {
const services: Partial<T> = {};
let hasLoading = false;
let hasError: Error | null = null;
for (const serviceName of serviceNames) {
const result = container.getSync(serviceName as string);
if (result.state === "loading") {
hasLoading = true;
} else if (result.state === "error") {
hasError = result.error;
} else if (result.state === "idle") {
// Auto-load idle services
container.load(serviceName as string).catch(() => {});
} else if (result.state === "ready" && result.value !== null) {
services[serviceName] = result.value as T[keyof T];
} else {
}
}
return {
hasLoading,
hasError,
services,
};
}, [serviceNames, container]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const [services, setServices] = useState<Partial<T>>(
getServiceStates().services,
);
useEffect(() => {
const updateState = () => {
const newServices: Partial<T> = {};
let hasLoading = false;
let hasError: Error | null = null;
for (const serviceName of serviceNames) {
const result = container.getSync(serviceName as string);
if (result.state === "loading") {
hasLoading = true;
} else if (result.state === "error") {
hasError = result.error;
} else if (result.state === "idle") {
// Auto-load idle services
container.load(serviceName as string).catch(() => {});
} else if (result.state === "ready" && result.value !== null) {
newServices[serviceName] = result.value as T[keyof T];
} else {
}
}
setServices(newServices);
setLoading(hasLoading);
setError(hasError);
};
// Initial state
updateState();
// Set up listeners for all services
const listeners: Array<() => void> = [];
for (const serviceName of serviceNames) {
const name = serviceName as string;
const onAnyChange = () => updateState();
const onAnyChange = () => {
const { hasLoading, hasError, services } = getServiceStates();
setLoading(hasLoading);
setError(hasError);
setServices(services);
};
container.on(`${name}:loading`, onAnyChange);
container.on(`${name}:ready`, onAnyChange);
@ -155,7 +162,7 @@ export function useServices<T extends Record<string, any>>(
return () => {
listeners.forEach((cleanup) => cleanup());
};
}, [serviceNames.join(","), container]);
}, [serviceNames.join(","), container, getServiceStates]);
const allReady = serviceNames.every((name) =>
container.isReady(name as string),

View file

@ -1,3 +1,4 @@
import { parseWorkflowFile, WorkflowFile } from "@continuedev/config-yaml";
import JSZip from "jszip";
import { env } from "./env.js";
@ -11,7 +12,7 @@ const HUB_SLUG_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
/**
* Hub package type definitions
*/
export type HubPackageType = "rule" | "mcp" | "model" | "prompt";
export type HubPackageType = "rule" | "mcp" | "model" | "prompt" | "workflow";
/**
* Hub package processor interface
@ -99,6 +100,15 @@ export const promptProcessor: HubPackageProcessor<string> = {
parseContent: (content: string) => content,
};
export const workflowProcessor: HubPackageProcessor<WorkflowFile> = {
type: "workflow",
expectedFileExtensions: [".md"],
parseContent: (content: string) => parseWorkflowFile(content),
validateContent: (workflowFile: WorkflowFile) => {
return !!workflowFile.name;
},
};
/**
* Generic hub package loader
*/

View file

@ -5,6 +5,8 @@ import * as path from "path";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { AuthService } from "src/services/AuthService.js";
import {
AuthenticatedConfig,
getModelName,
@ -12,7 +14,6 @@ import {
saveAuthConfig,
} from "../auth/workos.js";
import * as config from "../config.js";
import { AuthService } from "../services/AuthService.js";
import { ModelService } from "../services/ModelService.js";
// Mock the config module
@ -25,7 +26,7 @@ describe("Model Persistence User Flow", () => {
let mockAuthConfig: AuthenticatedConfig;
const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
beforeEach(() => {
beforeEach(async () => {
vi.clearAllMocks();
// Create a temporary directory for testing
@ -68,6 +69,7 @@ describe("Model Persistence User Flow", () => {
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000, // 1 hour from now
organizationId: "test-org",
modelName: "GPT-4",
};
// Setup default mock behavior

View file

@ -19,6 +19,24 @@ vi.mock("../hubLoader.js", () => ({
modelProcessor: {},
}));
// Mock the service container to provide empty workflow state
vi.mock("../services/ServiceContainer.js", () => ({
serviceContainer: {
get: vi.fn(() =>
Promise.resolve({
workflowFile: null,
slug: null,
}),
),
},
}));
vi.mock("../services/types.js", () => ({
SERVICE_NAMES: {
WORKFLOW: "workflow",
},
}));
describe("Rule duplication integration test", () => {
it("should not duplicate rules when using --rule flag", async () => {
const enhancer = new ConfigEnhancer();

View file

@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { loadMcpFromHub } from "./args.js";
import { loadMcpFromHub } from "./hubLoader.js";
// Store original fetch to restore later
const originalFetch = global.fetch;

View file

@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { parseArgs, loadMcpFromHub } from "./args.js";
import { loadMcpFromHub } from "./hubLoader.js";
// Integration test to demonstrate the --mcp flag functionality
describe("--mcp flag integration", () => {
@ -10,35 +10,6 @@ describe("--mcp flag integration", () => {
vi.clearAllMocks();
});
it("should demonstrate the complete --mcp flag functionality", () => {
// Test command line parsing
process.argv = [
"node",
"test",
"--config",
"my-config.yaml",
"--mcp",
"continuedev/filesystem",
"--mcp",
"continuedev/github",
"hello world",
];
const args = parseArgs();
// Verify the parsed command line arguments
expect(args).toEqual({
configPath: "my-config.yaml",
mcps: ["continuedev/filesystem", "continuedev/github"],
prompt: "hello world",
});
// Verify MCP slugs are properly captured
expect(args.mcps).toHaveLength(2);
expect(args.mcps).toContain("continuedev/filesystem");
expect(args.mcps).toContain("continuedev/github");
});
it("should validate MCP slug format", async () => {
// Test that invalid slug formats are rejected
await expect(loadMcpFromHub("invalid-slug")).rejects.toThrow(
@ -58,35 +29,4 @@ describe("--mcp flag integration", () => {
'Failed to load mcp from hub "valid/slug": HTTP 404: Not Found',
);
});
it("should demonstrate MCP flag with other command line options", () => {
process.argv = [
"node",
"test",
"--config",
"test-config.yaml",
"--org",
"my-org",
"--rule",
"my-rule",
"--mcp",
"continuedev/filesystem",
"--allow",
"readFile",
"--readonly",
"analyze this code",
];
const args = parseArgs();
// Verify all flags are parsed correctly together
expect(args).toEqual({
configPath: "test-config.yaml",
organizationSlug: "my-org",
rules: ["my-rule"],
mcps: ["continuedev/filesystem"],
readonly: true,
prompt: "analyze this code",
});
});
});

View file

@ -6,10 +6,10 @@ import { BaseLlmApi } from "@continuedev/openai-adapters";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import { processPromptOrRule } from "./args.js";
import { AuthConfig, isAuthenticated, login } from "./auth/workos.js";
import { initialize } from "./config.js";
import { env } from "./env.js";
import { processRule } from "./hubLoader.js";
import { MCPService } from "./services/MCPService.js";
import {
getApiKeyValidationError,
@ -250,7 +250,7 @@ async function injectRulesIntoConfig(
const processedRules: string[] = [];
for (const ruleSpec of rules) {
try {
const processedRule = await processPromptOrRule(ruleSpec);
const processedRule = await processRule(ruleSpec);
processedRules.push(processedRule);
} catch (error: any) {
console.warn(

View file

@ -1,7 +1,8 @@
import type { ToolPolicy } from "@continuedev/terminal-security";
import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js";
import { getServiceSync } from "../services/index.js";
import type { ToolPermissionServiceState } from "../services/types.js";
import { SERVICE_NAMES } from "../services/types.js";
import { getAllBuiltinTools } from "../tools/index.js";

View file

@ -1,205 +1,206 @@
import {
AuthenticatedConfig,
login as doLogin,
logout as doLogout,
ensureOrganization,
isAuthenticated,
listUserOrganizations,
loadAuthConfig,
saveAuthConfig,
} from "../auth/workos.js";
import { logger } from "../util/logger.js";
// 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";
// 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<AuthServiceState> {
constructor() {
super("AuthService", {
authConfig: null,
isAuthenticated: false,
});
}
// /**
// * Service for managing authentication state and operations
// * Now extends BaseService for common functionality
// */
// export class AuthService extends BaseService<AuthServiceState> {
// constructor() {
// super("AuthService", {
// authConfig: null,
// isAuthenticated: false,
// });
// }
/**
* Initialize the auth service by loading current config
*/
async doInitialize(): Promise<AuthServiceState> {
const authConfig = loadAuthConfig();
const authenticated = isAuthenticated();
// /**
// * Initialize the auth service by loading current config
// */
// async doInitialize(): Promise<AuthServiceState> {
// const authConfig = loadAuthConfig();
// const authenticated = isAuthenticated();
const state: AuthServiceState = {
authConfig,
isAuthenticated: authenticated,
organizationId: authConfig?.organizationId || undefined,
};
// const state: AuthServiceState = {
// authConfig,
// isAuthenticated: authenticated,
// organizationId: authConfig?.organizationId || undefined,
// };
logger.debug("AuthService initialized", {
authenticated,
hasConfig: !!authConfig,
orgId: state.organizationId,
});
// logger.debug("AuthService initialized", {
// authenticated,
// hasConfig: !!authConfig,
// orgId: state.organizationId,
// });
return state;
}
// return state;
// }
/**
* Perform login flow
*/
async login(): Promise<AuthServiceState> {
logger.debug("Starting login flow");
// /**
// * Perform login flow
// */
// async login(): Promise<AuthServiceState> {
// logger.debug("Starting login flow");
try {
const newAuthConfig = await doLogin();
// try {
// const newAuthConfig = await doLogin();
this.setState({
authConfig: newAuthConfig,
isAuthenticated: true,
organizationId: newAuthConfig?.organizationId || undefined,
});
// this.setState({
// authConfig: newAuthConfig,
// isAuthenticated: true,
// organizationId: newAuthConfig?.organizationId || undefined,
// });
logger.debug("Login successful", {
orgId: this.currentState.organizationId,
});
// 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;
}
}
// return this.getState();
// } catch (error: any) {
// logger.error("Login failed:", error);
// this.emit("error", error);
// throw error;
// }
// }
/**
* Perform logout
*/
async logout(): Promise<AuthServiceState> {
logger.debug("Logging out");
// /**
// * Perform logout
// */
// async logout(): Promise<AuthServiceState> {
// logger.debug("Logging out");
doLogout();
// doLogout();
this.setState({
authConfig: null,
isAuthenticated: false,
organizationId: undefined,
});
// this.setState({
// authConfig: null,
// isAuthenticated: false,
// organizationId: undefined,
// });
logger.debug("Logout complete");
return this.getState();
}
// logger.debug("Logout complete");
// return this.getState();
// }
/**
* Ensure organization is selected, prompting if necessary
*/
async ensureOrganization(
isHeadless: boolean = false,
): Promise<AuthServiceState> {
if (!this.currentState.authConfig) {
throw new Error("Not authenticated - cannot ensure organization");
}
// /**
// * Ensure organization is selected, prompting if necessary
// */
// async ensureOrganization(
// isHeadless: boolean = false,
// ): Promise<AuthServiceState> {
// if (!this.currentState.authConfig) {
// throw new Error("Not authenticated - cannot ensure organization");
// }
logger.debug("Ensuring organization is selected", {
currentOrgId: this.currentState.organizationId,
isHeadless,
});
// logger.debug("Ensuring organization is selected", {
// currentOrgId: this.currentState.organizationId,
// isHeadless,
// });
const updatedConfig = await ensureOrganization(
this.currentState.authConfig,
isHeadless,
);
// const updatedConfig = await ensureOrganization(
// this.currentState.authConfig,
// isHeadless,
// );
this.setState({
authConfig: updatedConfig,
isAuthenticated: true,
organizationId: updatedConfig?.organizationId || undefined,
});
// this.setState({
// authConfig: updatedConfig,
// isAuthenticated: true,
// organizationId: updatedConfig?.organizationId || undefined,
// });
logger.debug("Organization ensured", {
orgId: this.currentState.organizationId,
});
// logger.debug("Organization ensured", {
// orgId: this.currentState.organizationId,
// });
return this.getState();
}
// return this.getState();
// }
/**
* Switch to a different organization
*/
async switchOrganization(
organizationId: string | null,
): Promise<AuthServiceState> {
if (
!this.currentState.authConfig ||
!("userId" in this.currentState.authConfig)
) {
throw new Error(
"Not authenticated with file-based auth - cannot switch organizations",
);
}
// /**
// * Switch to a different organization
// */
// async switchOrganization(
// organizationId: string | null,
// ): Promise<AuthServiceState> {
// 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,
});
// logger.debug("Switching organization", {
// from: this.currentState.organizationId,
// to: organizationId,
// });
const authenticatedConfig = this.currentState
.authConfig as AuthenticatedConfig;
// const authenticatedConfig = this.currentState
// .authConfig as AuthenticatedConfig;
const updatedConfig: AuthenticatedConfig = {
...authenticatedConfig,
organizationId,
};
// const updatedConfig: AuthenticatedConfig = {
// ...authenticatedConfig,
// organizationId,
// };
saveAuthConfig(updatedConfig);
// saveAuthConfig(updatedConfig);
this.setState({
authConfig: updatedConfig,
isAuthenticated: true,
organizationId: organizationId || undefined,
});
// this.setState({
// authConfig: updatedConfig,
// isAuthenticated: true,
// organizationId: organizationId || undefined,
// });
logger.debug("Organization switched", {
newOrgId: this.currentState.organizationId,
});
// logger.debug("Organization switched", {
// newOrgId: this.currentState.organizationId,
// });
return this.getState();
}
// return this.getState();
// }
/**
* Get available organizations for the current user
*/
async getAvailableOrganizations(): Promise<
{ id: string; name: string }[] | null
> {
if (!this.currentState.isAuthenticated) {
return null;
}
// /**
// * 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;
}
}
// 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<boolean> {
const orgs = await this.getAvailableOrganizations();
return orgs !== null && orgs.length > 0;
}
// /**
// * Check if the current user has multiple organizations available
// */
// async hasMultipleOrganizations(): Promise<boolean> {
// const orgs = await this.getAvailableOrganizations();
// return orgs !== null && orgs.length > 0;
// }
/**
* Refresh auth state from disk (useful after external changes)
*/
async refresh(): Promise<AuthServiceState> {
logger.debug("Refreshing auth state from disk");
return this.reload();
}
}
// /**
// * Refresh auth state from disk (useful after external changes)
// */
// async refresh(): Promise<AuthServiceState> {
// logger.debug("Refreshing auth state from disk");
// return this.reload();
// }
// }
export {};

View file

@ -12,7 +12,7 @@ import * as configLoader from "../configLoader.js";
import { ConfigService } from "./ConfigService.js";
import { serviceContainer } from "./ServiceContainer.js";
import { SERVICE_NAMES } from "./types.js";
import { SERVICE_NAMES, WorkflowServiceState } from "./types.js";
describe("ConfigService", () => {
let service: ConfigService;
@ -23,7 +23,12 @@ describe("ConfigService", () => {
systemMessage: "Test system message",
} as any;
const mockApiClient = { get: vi.fn(), post: vi.fn() };
const mockWorkflowState: WorkflowServiceState = {
slug: null,
workflowFile: null,
workflowModelName: null,
workflowService: null,
};
beforeEach(() => {
vi.clearAllMocks();
service = new ConfigService();
@ -36,12 +41,13 @@ describe("ConfigService", () => {
source: { type: "cli-flag", path: "/path/to/config.yaml" } as any,
});
const state = await service.initialize(
{ accessToken: "token" } as any,
"/path/to/config.yaml",
"org-123",
mockApiClient as any,
);
const state = await service.initialize({
authConfig: { accessToken: "token" } as any,
configPath: "/path/to/config.yaml",
_organizationId: "org-123",
apiClient: mockApiClient as any,
workflowState: mockWorkflowState,
});
expect(state).toEqual({
config: mockConfig as any,
@ -55,12 +61,13 @@ describe("ConfigService", () => {
source: { type: "default-agent" } as any,
});
const state = await service.initialize(
{ accessToken: "token" } as any,
undefined,
"org-123",
mockApiClient as any,
);
const state = await service.initialize({
authConfig: { accessToken: "token" } as any,
configPath: undefined,
_organizationId: "org-123",
apiClient: mockApiClient as any,
workflowState: mockWorkflowState,
});
expect(state).toEqual({
config: mockConfig as any,
@ -82,18 +89,20 @@ describe("ConfigService", () => {
vi.mocked(configEnhancer.enhanceConfig).mockResolvedValue(expectedConfig);
const state = await service.initialize(
{ accessToken: "token" } as any,
"/config.yaml",
"org-123",
mockApiClient as any,
{ rule: ["rule1", "rule2"] },
);
const state = await service.initialize({
authConfig: { accessToken: "token" } as any,
configPath: "/config.yaml",
_organizationId: "org-123",
apiClient: mockApiClient as any,
workflowState: mockWorkflowState,
injectedConfigOptions: { rule: ["rule1", "rule2"] },
});
// Verify configEnhancer was called with the right parameters
expect(vi.mocked(configEnhancer.enhanceConfig)).toHaveBeenCalledWith(
mockConfig,
{ rule: ["rule1", "rule2"] },
mockWorkflowState,
);
expect(state.config).toEqual(expectedConfig);
@ -107,12 +116,13 @@ describe("ConfigService", () => {
config: mockConfig as any,
source: { type: "cli-flag", path: "/old.yaml" } as any,
});
await service.initialize(
{ accessToken: "token" } as any,
"/old.yaml",
"org-123",
mockApiClient as any,
);
await service.initialize({
authConfig: { accessToken: "token" } as any,
configPath: "/old.yaml",
_organizationId: "org-123",
apiClient: mockApiClient as any,
workflowState: mockWorkflowState,
});
// Switch to new config
const newConfig = { ...mockConfig, name: "new-assistant" } as any;
@ -136,12 +146,13 @@ describe("ConfigService", () => {
});
test("should handle switch config errors", async () => {
await service.initialize(
{ accessToken: "token" } as any,
"/old.yaml",
"org-123",
mockApiClient as any,
);
await service.initialize({
authConfig: { accessToken: "token" } as any,
configPath: "/old.yaml",
_organizationId: "org-123",
apiClient: mockApiClient as any,
workflowState: mockWorkflowState,
});
vi.mocked(configLoader.loadConfiguration).mockRejectedValue(
new Error("Config not found"),
@ -165,12 +176,13 @@ describe("ConfigService", () => {
config: mockConfig as any,
source: { type: "cli-flag", path: "/config.yaml" } as any,
});
await service.initialize(
{ accessToken: "token" } as any,
"/config.yaml",
"org-123",
mockApiClient as any,
);
await service.initialize({
authConfig: { accessToken: "token" } as any,
configPath: "/config.yaml",
_organizationId: "org-123",
apiClient: mockApiClient as any,
workflowState: mockWorkflowState,
});
// Modify mock to return updated config
const updatedConfig = { ...mockConfig, name: "updated-assistant" } as any;
@ -197,12 +209,13 @@ describe("ConfigService", () => {
config: mockConfig as any,
source: { type: "default-agent" } as any,
});
await service.initialize(
{ accessToken: "token" } as any,
undefined,
"org-123",
mockApiClient as any,
);
await service.initialize({
authConfig: { accessToken: "token" } as any,
configPath: undefined,
_organizationId: "org-123",
apiClient: mockApiClient as any,
workflowState: mockWorkflowState,
});
await expect(
service.reload(
@ -221,12 +234,13 @@ describe("ConfigService", () => {
config: mockConfig as any,
source: { type: "cli-flag", path: "/old.yaml" } as any,
});
await service.initialize(
{ accessToken: "token" } as any,
"/old.yaml",
"org-123",
mockApiClient as any,
);
await service.initialize({
authConfig: { accessToken: "token" } as any,
configPath: "/old.yaml",
_organizationId: "org-123",
apiClient: mockApiClient as any,
workflowState: mockWorkflowState,
});
// Mock service container
vi.mocked(workos.loadAuthConfig).mockReturnValue({
@ -263,12 +277,13 @@ describe("ConfigService", () => {
});
test("should handle missing API client", async () => {
await service.initialize(
{ accessToken: "token" } as any,
"/old.yaml",
"org-123",
mockApiClient as any,
);
await service.initialize({
authConfig: { accessToken: "token" } as any,
configPath: "/old.yaml",
_organizationId: "org-123",
apiClient: mockApiClient as any,
workflowState: mockWorkflowState,
});
vi.mocked(workos.loadAuthConfig).mockReturnValue({
accessToken: "token",
@ -286,7 +301,11 @@ describe("ConfigService", () => {
describe("getDependencies()", () => {
test("should declare auth and apiClient dependencies", () => {
expect(service.getDependencies()).toEqual(["auth", "apiClient"]);
expect(service.getDependencies()).toEqual([
"auth",
"apiClient",
"workflow",
]);
});
});
@ -296,12 +315,13 @@ describe("ConfigService", () => {
config: mockConfig as any,
source: { type: "cli-flag", path: "/old.yaml" } as any,
});
await service.initialize(
{ accessToken: "token" } as any,
"/old.yaml",
"org-123",
mockApiClient as any,
);
await service.initialize({
authConfig: { accessToken: "token" } as any,
configPath: "/old.yaml",
_organizationId: "org-123",
apiClient: mockApiClient as any,
workflowState: mockWorkflowState,
});
const listener = vi.fn();
service.on("stateChanged", listener);
@ -329,12 +349,13 @@ describe("ConfigService", () => {
});
test("should emit error on switch failure", async () => {
await service.initialize(
{ accessToken: "token" } as any,
"/old.yaml",
"org-123",
mockApiClient as any,
);
await service.initialize({
authConfig: { accessToken: "token" } as any,
configPath: "/old.yaml",
_organizationId: "org-123",
apiClient: mockApiClient as any,
workflowState: mockWorkflowState,
});
const errorListener = vi.fn();
service.on("error", errorListener);

View file

@ -11,8 +11,17 @@ import {
ApiClientServiceState,
ConfigServiceState,
SERVICE_NAMES,
WorkflowServiceState,
} from "./types.js";
interface ConfigServiceInit {
authConfig: AuthConfig;
configPath: string | undefined;
_organizationId: string | null;
apiClient: DefaultApiInterface;
workflowState: WorkflowServiceState;
injectedConfigOptions?: BaseCommandOptions;
}
/**
* Service for managing configuration state and operations
* Handles loading configs from files or assistant slugs
@ -32,19 +41,23 @@ export class ConfigService
* Declare dependencies on other services
*/
getDependencies(): string[] {
return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT];
return [
SERVICE_NAMES.AUTH,
SERVICE_NAMES.API_CLIENT,
SERVICE_NAMES.WORKFLOW,
];
}
/**
* Initialize the config service
*/
async doInitialize(
authConfig: AuthConfig,
configPath: string | undefined,
_organizationId: string | null,
apiClient: DefaultApiInterface,
injectedConfigOptions?: BaseCommandOptions,
): Promise<ConfigServiceState> {
async doInitialize({
apiClient,
authConfig,
configPath,
workflowState,
injectedConfigOptions,
}: ConfigServiceInit): Promise<ConfigServiceState> {
// Use the new streamlined config loader
const { loadConfiguration } = await import("../configLoader.js");
const result = await loadConfiguration(authConfig, configPath, apiClient);
@ -53,12 +66,13 @@ export class ConfigService
// Apply injected config if provided
if (
injectedConfigOptions &&
this.hasInjectedConfig(injectedConfigOptions)
workflowState?.workflowFile ||
(injectedConfigOptions && this.hasInjectedConfig(injectedConfigOptions))
) {
config = await configEnhancer.enhanceConfig(
config,
injectedConfigOptions,
workflowState,
);
logger.debug("Applied injected configuration");

View file

@ -1,259 +0,0 @@
import { beforeEach, afterEach, describe, expect, vi, test } from "vitest";
import { ModeService } from "./ModeService.js";
describe("ModeService", () => {
let modeService: ModeService;
beforeEach(() => {
// Reset singleton instance for each test
(ModeService as any).instance = undefined;
modeService = ModeService.getInstance();
});
afterEach(() => {
// Clean up singleton instance
(ModeService as any).instance = undefined;
});
describe("State Management", () => {
test("should initialize with normal mode by default", async () => {
const state = await modeService.initialize({});
expect(state).toEqual({
mode: "normal",
toolPermissionService: expect.any(Object),
});
expect(modeService.getCurrentMode()).toBe("normal");
});
test("should convert readonly flag to plan mode", async () => {
const state = await modeService.initialize({ readonly: true });
expect(state.mode).toBe("plan");
expect(modeService.getCurrentMode()).toBe("plan");
});
test("should convert auto flag to auto mode", async () => {
const state = await modeService.initialize({ auto: true });
expect(state.mode).toBe("auto");
expect(modeService.getCurrentMode()).toBe("auto");
});
test("should initialize tool permission service with flags", async () => {
const state = await modeService.initialize({
allow: ["testTool"],
exclude: ["badTool"],
});
const toolPermissionService = state.toolPermissionService;
expect(toolPermissionService).toBeDefined();
expect(toolPermissionService.getState()).toBeDefined();
expect(toolPermissionService.getCurrentMode()).toBe("normal");
});
});
describe("switchMode()", () => {
beforeEach(async () => {
await modeService.initialize({});
});
test("should switch from normal to plan mode", () => {
expect(modeService.getCurrentMode()).toBe("normal");
modeService.switchMode("plan");
expect(modeService.getCurrentMode()).toBe("plan");
expect(modeService.getState().mode).toBe("plan");
});
test("should switch from plan to auto mode", () => {
modeService.switchMode("plan");
expect(modeService.getCurrentMode()).toBe("plan");
modeService.switchMode("auto");
expect(modeService.getCurrentMode()).toBe("auto");
expect(modeService.getState().mode).toBe("auto");
});
test("should switch back to normal mode", () => {
modeService.switchMode("plan");
modeService.switchMode("normal");
expect(modeService.getCurrentMode()).toBe("normal");
expect(modeService.getState().mode).toBe("normal");
});
test("should update tool permission service when switching modes", () => {
const toolPermissionService = modeService.getToolPermissionService();
const initialState = toolPermissionService.getState();
modeService.switchMode("auto");
const newState = toolPermissionService.getState();
expect(newState.currentMode).toBe("auto");
expect(newState.permissions.policies.length).toBeGreaterThan(0);
expect(newState.permissions.policies[0]).toEqual({
tool: "*",
permission: "allow",
});
});
test("should handle multiple mode switches correctly", () => {
// Start in normal
expect(modeService.getCurrentMode()).toBe("normal");
// Switch to plan
modeService.switchMode("plan");
const planState = modeService.getToolPermissionService().getState();
expect(planState.permissions.policies).toContainEqual({
tool: "Write",
permission: "exclude",
});
// Switch to auto
modeService.switchMode("auto");
const autoState = modeService.getToolPermissionService().getState();
expect(autoState.permissions.policies).toHaveLength(1);
expect(autoState.permissions.policies[0]).toEqual({
tool: "*",
permission: "allow",
});
// Back to normal
modeService.switchMode("normal");
const normalState = modeService.getToolPermissionService().getState();
expect(normalState.currentMode).toBe("normal");
});
});
describe("getAvailableModes()", () => {
beforeEach(async () => {
await modeService.initialize({});
});
test("should return all available modes with descriptions", () => {
const modes = modeService.getAvailableModes();
expect(modes).toHaveLength(3);
const modeNames = modes.map((m) => m.mode);
expect(modeNames).toContain("normal");
expect(modeNames).toContain("plan");
expect(modeNames).toContain("auto");
// Check that all modes have descriptions
modes.forEach((mode) => {
expect(mode.description).toBeDefined();
expect(mode.description.length).toBeGreaterThan(0);
});
});
});
describe("Singleton Behavior", () => {
test("should return the same instance", () => {
const instance1 = ModeService.getInstance();
const instance2 = ModeService.getInstance();
expect(instance1).toBe(instance2);
});
test("should maintain state across getInstance calls", async () => {
const instance1 = ModeService.getInstance();
await instance1.initialize({});
instance1.switchMode("plan");
const instance2 = ModeService.getInstance();
expect(instance2.getCurrentMode()).toBe("plan");
});
});
describe("isReady()", () => {
test("should always return true for ModeService", () => {
// ModeService is always ready since it's a singleton
expect(modeService.isReady()).toBe(true);
});
});
describe("Event Emission", () => {
let modeChangeListener: ReturnType<typeof vi.fn>;
let stateChangeListener: ReturnType<typeof vi.fn>;
beforeEach(async () => {
await modeService.initialize({});
modeChangeListener = vi.fn();
stateChangeListener = vi.fn();
modeService.on("modeChanged", modeChangeListener);
modeService.on("stateChanged", stateChangeListener);
});
afterEach(() => {
modeService.off("modeChanged", modeChangeListener);
modeService.off("stateChanged", stateChangeListener);
});
test("should emit modeChanged event when mode switches", () => {
modeService.switchMode("plan");
expect(modeChangeListener).toHaveBeenCalledWith("plan", "normal");
expect(modeChangeListener).toHaveBeenCalledTimes(1);
});
test("should emit stateChanged event when mode switches", () => {
modeService.switchMode("plan");
expect(stateChangeListener).toHaveBeenCalledWith(
expect.objectContaining({ mode: "plan" }),
expect.objectContaining({ mode: "normal" }),
);
});
test("should emit event with correct previous and new modes", () => {
modeService.switchMode("plan");
modeChangeListener.mockClear();
stateChangeListener.mockClear();
modeService.switchMode("auto");
expect(modeChangeListener).toHaveBeenCalledWith("auto", "plan");
expect(modeChangeListener).toHaveBeenCalledTimes(1);
expect(stateChangeListener).toHaveBeenCalledTimes(1);
});
test("should not emit event when switching to same mode", () => {
modeService.switchMode("plan");
modeChangeListener.mockClear();
stateChangeListener.mockClear();
modeService.switchMode("plan");
expect(modeChangeListener).not.toHaveBeenCalled();
// stateChanged might still be called due to setState, but modeChanged should not
});
});
describe("Integration with ToolPermissionService", () => {
beforeEach(async () => {
await modeService.initialize({
allow: ["Read"],
exclude: ["dangerous_tool"],
});
});
test("should pass initialization args to ToolPermissionService", () => {
const toolService = modeService.getToolPermissionService();
const state = toolService.getState();
// The state should have processed the allow/exclude rules
expect(state.permissions.policies).toBeDefined();
expect(state.currentMode).toBe("normal");
});
test("should maintain ToolPermissionService reference", () => {
const toolService1 = modeService.getToolPermissionService();
const toolService2 = modeService.getToolPermissionService();
expect(toolService1).toBe(toolService2);
});
});
});

View file

@ -1,144 +0,0 @@
import { PermissionMode } from "../permissions/types.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
import { ToolPermissionService } from "./ToolPermissionService.js";
export interface ModeServiceState {
mode: PermissionMode;
toolPermissionService: ToolPermissionService;
}
/**
* Global service for managing permission modes
* Provides a singleton interface for mode switching
*/
export class ModeService extends BaseService<ModeServiceState> {
private static instance: ModeService;
private constructor() {
const toolPermissionService = new ToolPermissionService();
super("ModeService", {
mode: "normal",
toolPermissionService,
});
// Increase max listeners since ModeService is a singleton that can have
// multiple subscribers (UI components, tests, etc.)
this.setMaxListeners(100);
}
public static getInstance(): ModeService {
if (!ModeService.instance) {
ModeService.instance = new ModeService();
}
return ModeService.instance;
}
/**
* Initialize the mode service with command line arguments
*/
async doInitialize(args: {
readonly?: boolean;
auto?: boolean;
allow?: string[];
ask?: string[];
exclude?: string[];
isHeadless?: boolean;
}): Promise<ModeServiceState> {
// Convert legacy flags to mode
let mode: PermissionMode = "normal";
if (args.readonly) {
mode = "plan"; // Legacy flag maps directly to plan mode
} else if (args.auto) {
mode = "auto"; // Auto flag maps to auto mode
}
this.currentState.toolPermissionService.initializeSync({
allow: args.allow,
ask: args.ask,
exclude: args.exclude,
mode,
isHeadless: args.isHeadless,
});
logger.debug(`ModeService initialized with mode: ${mode}`);
return {
mode,
toolPermissionService: this.currentState.toolPermissionService,
};
}
/**
* Switch to a different mode
*/
public switchMode(mode: PermissionMode): void {
const previousMode = this.currentState.mode;
this.currentState.toolPermissionService.switchMode(mode);
this.setState({ mode });
logger.info(`Switched to ${mode} mode`);
// Emit mode change event for immediate UI updates
if (previousMode !== mode) {
this.emit("modeChanged", mode, previousMode);
}
}
/**
* Get the current mode
*/
public getCurrentMode(): PermissionMode {
return this.currentState.mode;
}
/**
* Get the tool permission service instance
*/
public getToolPermissionService(): ToolPermissionService {
return this.currentState.toolPermissionService;
}
/**
* Get available modes with descriptions
*/
public getAvailableModes(): Array<{
mode: PermissionMode;
description: string;
}> {
return [
{
mode: "normal",
description: "Default mode - follows configured permission policies",
},
{
mode: "plan",
description: "Planning mode - only allow read-only tools for analysis",
},
{
mode: "auto",
description: "Automatically allow all tools without asking",
},
];
}
/**
* Override cleanup to properly clean up nested ToolPermissionService
*/
override async cleanup(): Promise<void> {
await this.currentState.toolPermissionService.cleanup();
await super.cleanup();
}
/**
* Override isReady since this is a singleton with immediate availability
*/
override isReady(): boolean {
return true;
}
}
// Export singleton instance
export const modeService = ModeService.getInstance();

View file

@ -1,12 +1,12 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { describe, expect, beforeEach, vi, test } from "vitest";
import { beforeEach, describe, expect, test, vi } from "vitest";
// Mock dependencies before imports
vi.mock("../config.js");
vi.mock("../auth/workos.js");
import { AuthConfig } from "../auth/workos.js";
import * as workos from "../auth/workos.js";
import { AuthConfig } from "../auth/workos.js";
import * as config from "../config.js";
import { ModelService } from "./ModelService.js";
@ -357,8 +357,8 @@ describe("ModelService", () => {
});
describe("getDependencies()", () => {
test("should declare auth and config dependencies", () => {
expect(service.getDependencies()).toEqual(["auth", "config"]);
test("should declare auth, config, and workflow dependencies", () => {
expect(service.getDependencies()).toEqual(["auth", "config", "workflow"]);
});
});

View file

@ -5,7 +5,7 @@ import { createLlmApi, getLlmApi } from "../config.js";
import { logger } from "../util/logger.js";
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
import { ModelServiceState } from "./types.js";
import { ModelServiceState, WorkflowServiceState } from "./types.js";
/**
* Service for managing LLM and model state
@ -32,7 +32,7 @@ export class ModelService
* Declare dependencies on other services
*/
getDependencies(): string[] {
return ["auth", "config"];
return ["auth", "config", "workflow"];
}
/**
@ -41,6 +41,7 @@ export class ModelService
async doInitialize(
assistant: AssistantUnrolled,
authConfig: AuthConfig,
workflowServiceState?: WorkflowServiceState,
): Promise<ModelServiceState> {
logger.debug("ModelService.doInitialize called", {
hasAssistant: !!assistant,
@ -55,16 +56,29 @@ export class ModelService
model && (model.roles?.includes("chat") || model.roles === undefined),
) || []) as ModelConfig[];
// Check if we have a persisted model name and use it if valid
const persistedModelName = getModelName(authConfig);
if (persistedModelName) {
let preferredModelName: string | null | undefined = null;
let modelSource = "default";
// Priority = workflow -> last selected model
if (workflowServiceState?.workflowModelName) {
preferredModelName = workflowServiceState.workflowModelName;
modelSource = "workflow";
} else {
preferredModelName = getModelName(authConfig);
if (preferredModelName) {
modelSource = "persisted";
}
}
// Try to use the preferred model (workflow or persisted)
if (preferredModelName) {
// During initialization, we need to check against availableModels directly
const modelIndex = this.availableModels.findIndex((model) => {
const name = (model as any).name || (model as any).model;
return name === persistedModelName;
return name === preferredModelName;
});
if (modelIndex === -1) {
// Model name not found, use default model selection
// Preferred model not found, use default model selection
const [llmApi, model] = getLlmApi(assistant, authConfig);
return {
llmApi,
@ -73,20 +87,20 @@ export class ModelService
authConfig,
};
} else {
// Use the persisted model - but we need to handle initialization specially
// Use the preferred model - but we need to handle initialization specially
// During init, currentState isn't set yet, so switchModel would fail
// Instead, we'll manually switch here
const selectedModel = this.availableModels[modelIndex];
logger.debug("Using persisted model during initialization", {
logger.debug(`Using ${modelSource} model during initialization`, {
modelIndex,
provider: selectedModel.provider,
name: (selectedModel as any).name || "unnamed",
modelSource,
});
const llmApi = createLlmApi(selectedModel, authConfig);
if (!llmApi) {
throw new Error("Failed to initialize LLM with persisted model");
throw new Error(`Failed to initialize LLM with ${modelSource} model`);
}
return {

View file

@ -0,0 +1,254 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AuthConfig } from "../auth/workos.js";
import * as config from "../config.js";
import { ModelService } from "./ModelService.js";
import { WorkflowServiceState } from "./types.js";
// Mock the dependencies
vi.mock("../auth/workos.js", () => ({
getModelName: vi.fn(() => null),
}));
vi.mock("../config.js", () => ({
createLlmApi: vi.fn(() => ({ provider: "test" })),
getLlmApi: vi.fn(() => [
{ provider: "test" },
{ provider: "test", name: "default-model" },
]),
}));
vi.mock("../util/logger.js", () => ({
logger: {
debug: vi.fn(),
error: vi.fn(),
},
}));
describe("ModelService workflow model prioritization", () => {
let modelService: ModelService;
let mockAssistant: AssistantUnrolled;
let mockAuthConfig: AuthConfig;
let mockModels: ModelConfig[];
beforeEach(() => {
modelService = new ModelService();
mockModels = [
{ provider: "anthropic", name: "claude-3-sonnet" } as ModelConfig,
{ provider: "openai", name: "gpt-4" } as ModelConfig,
{ provider: "anthropic", name: "claude-3-haiku" } as ModelConfig,
];
mockAssistant = {
models: mockModels,
} as AssistantUnrolled;
mockAuthConfig = {} as AuthConfig;
// Reset mocks
vi.clearAllMocks();
});
it("should prioritize workflow model over default when workflow file has model specified", async () => {
const workflowServiceState: WorkflowServiceState = {
workflowFile: {
name: "test-workflow",
model: "gpt-4",
prompt: "Test workflow",
},
slug: "test/workflow",
workflowModelName: "gpt-4",
workflowService: null,
};
// Mock createLlmApi to return different models based on the selected model
const createLlmApiMock = vi.mocked(config.createLlmApi);
createLlmApiMock.mockImplementation(
(model: ModelConfig) =>
({
provider: model.provider,
name: (model as any).name,
}) as any,
);
const result = await modelService.doInitialize(
mockAssistant,
mockAuthConfig,
workflowServiceState,
);
expect(result.model).toEqual(
expect.objectContaining({
name: "gpt-4",
provider: "openai",
}),
);
// Should have called createLlmApi with the workflow-specified model
expect(createLlmApiMock).toHaveBeenCalledWith(
expect.objectContaining({ name: "gpt-4" }),
mockAuthConfig,
);
});
it("should fall back to persisted model when no workflow model is specified", async () => {
const workflowServiceState: WorkflowServiceState = {
workflowFile: {
name: "test-workflow",
prompt: "Test workflow",
// No model specified
},
slug: "test/workflow",
workflowModelName: null,
workflowService: null,
};
// Mock getModelName to return a persisted model
const { getModelName } = await import("../auth/workos.js");
vi.mocked(getModelName).mockReturnValue("claude-3-sonnet");
const createLlmApiMock = vi.mocked(config.createLlmApi);
createLlmApiMock.mockImplementation(
(model: ModelConfig) =>
({
provider: model.provider,
name: (model as any).name,
}) as any,
);
const result = await modelService.doInitialize(
mockAssistant,
mockAuthConfig,
workflowServiceState,
);
expect(result.model).toEqual(
expect.objectContaining({
name: "claude-3-sonnet",
provider: "anthropic",
}),
);
expect(createLlmApiMock).toHaveBeenCalledWith(
expect.objectContaining({ name: "claude-3-sonnet" }),
mockAuthConfig,
);
});
it("should fall back to default model when workflow model is not available", async () => {
const workflowServiceState: WorkflowServiceState = {
workflowFile: {
name: "test-workflow",
model: "non-existent-model", // Model not in available models
prompt: "Test workflow",
},
slug: "test/workflow",
workflowModelName: "non-existent-model",
workflowService: null,
};
const getLlmApiMock = vi.mocked(config.getLlmApi);
getLlmApiMock.mockReturnValue([
{ provider: "default" } as any,
{ provider: "anthropic", name: "claude-3-sonnet" } as ModelConfig,
]);
const result = await modelService.doInitialize(
mockAssistant,
mockAuthConfig,
workflowServiceState,
);
expect(result.model).toEqual(
expect.objectContaining({
name: "claude-3-sonnet",
provider: "anthropic",
}),
);
// Should have fallen back to getLlmApi
expect(getLlmApiMock).toHaveBeenCalledWith(mockAssistant, mockAuthConfig);
});
it("should use default model when no workflow file exists", async () => {
const workflowServiceState: WorkflowServiceState = {
workflowFile: null,
slug: null,
workflowModelName: null,
workflowService: null,
};
// Make sure getModelName returns null (no persisted model)
const { getModelName } = await import("../auth/workos.js");
vi.mocked(getModelName).mockReturnValue(null);
const getLlmApiMock = vi.mocked(config.getLlmApi);
getLlmApiMock.mockReturnValue([
{ provider: "default" } as any,
{ provider: "anthropic", name: "claude-3-sonnet" } as ModelConfig,
]);
const result = await modelService.doInitialize(
mockAssistant,
mockAuthConfig,
workflowServiceState,
);
expect(result.model).toEqual(
expect.objectContaining({
name: "claude-3-sonnet",
provider: "anthropic",
}),
);
expect(getLlmApiMock).toHaveBeenCalledWith(mockAssistant, mockAuthConfig);
});
it("should prioritize workflow model over persisted model", async () => {
const workflowServiceState: WorkflowServiceState = {
workflowFile: {
name: "test-workflow",
model: "gpt-4", // Workflow specifies gpt-4
prompt: "Test workflow",
},
slug: "test/workflow",
workflowModelName: "gpt-4",
workflowService: null,
};
// Mock getModelName to return a different persisted model
const { getModelName } = await import("../auth/workos.js");
vi.mocked(getModelName).mockReturnValue("claude-3-haiku");
const createLlmApiMock = vi.mocked(config.createLlmApi);
createLlmApiMock.mockImplementation(
(model: ModelConfig) =>
({
provider: model.provider,
name: (model as any).name,
}) as any,
);
const result = await modelService.doInitialize(
mockAssistant,
mockAuthConfig,
workflowServiceState,
);
// Should use workflow model (gpt-4), not persisted model (claude-3-haiku)
expect(result.model).toEqual(
expect.objectContaining({
name: "gpt-4",
provider: "openai",
}),
);
expect(createLlmApiMock).toHaveBeenCalledWith(
expect.objectContaining({ name: "gpt-4" }),
mockAuthConfig,
);
});
});

View file

@ -2,7 +2,7 @@ import { EventEmitter } from "events";
import { logger } from "../util/logger.js";
import { ServiceResult, ServiceState } from "./types.js";
import { type ServiceResult, type ServiceState } from "./types.js";
/**
* Central service container that manages service lifecycle and dependencies

View file

@ -1,8 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { modeService } from "./ModeService.js";
import { SystemMessageService } from "./SystemMessageService.js";
import { services } from "./index.js";
const toolPermissionService = services.toolPermissions;
// Mock the systemMessage module
vi.mock("../systemMessage.js", () => ({
constructSystemMessage: vi.fn(),
@ -71,35 +73,16 @@ describe("SystemMessageService", () => {
constructSystemMessageMock.mockResolvedValue("Test system message");
await service.initialize(config);
const message = await service.getSystemMessage();
const message = await service.getSystemMessage("normal");
expect(constructSystemMessageMock).toHaveBeenCalledWith(
"normal", // Default mode
["rule1"],
"json",
true,
"normal", // Default mode
);
expect(message).toBe("Test system message");
});
it("should use updated mode when mode changes", async () => {
constructSystemMessageMock.mockResolvedValue("Updated system message");
await service.initialize({});
// Simulate mode change
modeService.emit("modeChanged", "plan", "normal");
const message = await service.getSystemMessage();
expect(constructSystemMessageMock).toHaveBeenCalledWith(
undefined,
undefined,
undefined,
"plan",
);
expect(message).toBe("Updated system message");
});
});
describe("updateConfig", () => {
@ -114,13 +97,13 @@ describe("SystemMessageService", () => {
});
constructSystemMessageMock.mockResolvedValue("Updated message");
await service.getSystemMessage();
await service.getSystemMessage("normal");
expect(constructSystemMessageMock).toHaveBeenCalledWith(
"normal",
["rule1"],
"json",
false,
"normal",
);
});
@ -135,42 +118,17 @@ describe("SystemMessageService", () => {
});
constructSystemMessageMock.mockResolvedValue("Updated message");
await service.getSystemMessage();
await service.getSystemMessage("normal");
expect(constructSystemMessageMock).toHaveBeenCalledWith(
"normal",
["rule2", "rule3"],
"json",
undefined,
"normal",
);
});
});
describe("mode tracking", () => {
it("should track current mode from ModeService", async () => {
await service.initialize({});
expect(service.getCurrentMode()).toBe("normal");
// Simulate mode change
modeService.emit("modeChanged", "auto", "normal");
expect(service.getCurrentMode()).toBe("auto");
});
it("should initialize with current mode from ModeService", async () => {
// Mock modeService.getCurrentMode
vi.spyOn(modeService, "getCurrentMode").mockReturnValue("plan");
const newService = new SystemMessageService();
await newService.initialize({});
expect(newService.getCurrentMode()).toBe("plan");
await newService.cleanup();
});
});
describe("error handling", () => {
it("should handle constructSystemMessage errors gracefully", async () => {
constructSystemMessageMock.mockRejectedValue(
@ -179,7 +137,7 @@ describe("SystemMessageService", () => {
await service.initialize({});
await expect(service.getSystemMessage()).rejects.toThrow(
await expect(service.getSystemMessage("normal")).rejects.toThrow(
"Failed to construct",
);
});

View file

@ -3,7 +3,7 @@ import { constructSystemMessage } from "../systemMessage.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
import { modeService } from "./ModeService.js";
import { SERVICE_NAMES } from "./types.js";
export interface SystemMessageServiceState {
additionalRules?: string[];
@ -16,26 +16,8 @@ export interface SystemMessageServiceState {
* Provides fresh system messages that reflect current mode and configuration
*/
export class SystemMessageService extends BaseService<SystemMessageServiceState> {
private currentMode: PermissionMode = "normal";
constructor() {
super("SystemMessageService", {});
// Listen to mode changes from ModeService
this.setupModeListener();
}
/**
* Set up listener for mode changes
*/
private setupModeListener(): void {
modeService.on("modeChanged", (newMode: PermissionMode) => {
logger.debug(`SystemMessageService: Mode changed to ${newMode}`);
this.currentMode = newMode;
});
// Initialize current mode
this.currentMode = modeService.getCurrentMode();
}
/**
@ -64,24 +46,28 @@ export class SystemMessageService extends BaseService<SystemMessageServiceState>
/**
* Get a fresh system message with current mode and configuration
*/
public async getSystemMessage(): Promise<string> {
public async getSystemMessage(currentMode: PermissionMode): Promise<string> {
const { additionalRules, format, headless } = this.currentState;
const systemMessage = await constructSystemMessage(
currentMode,
additionalRules,
format,
headless,
this.currentMode,
);
logger.debug("Generated fresh system message", {
mode: this.currentMode,
mode: currentMode,
messageLength: systemMessage.length,
});
return systemMessage;
}
getDependencies(): string[] {
return [SERVICE_NAMES.TOOL_PERMISSIONS];
}
/**
* Update configuration that affects system message
*/
@ -93,14 +79,4 @@ export class SystemMessageService extends BaseService<SystemMessageServiceState>
logger.debug("SystemMessageService config updated", config);
}
/**
* Get the current mode being used for system messages
*/
public getCurrentMode(): PermissionMode {
return this.currentMode;
}
}
// Export singleton instance
export const systemMessageService = new SystemMessageService();

View file

@ -1,4 +1,4 @@
import { describe, expect, test, beforeEach, vi } from "vitest";
import { beforeEach, describe, expect, test, vi } from "vitest";
// Mock modules
vi.mock("../permissions/permissionsYamlLoader.js");
@ -30,6 +30,7 @@ describe("ToolPermissionService", () => {
currentMode: "normal",
isHeadless: false,
modePolicyCount: 0,
workflowPolicyCount: 0,
});
});

View file

@ -1,3 +1,5 @@
import { parseWorkflowTools } from "@continuedev/config-yaml";
import { ensurePermissionsYamlExists } from "../permissions/permissionsYamlLoader.js";
import { resolvePermissionPrecedence } from "../permissions/precedenceResolver.js";
import {
@ -7,20 +9,34 @@ import {
} from "../permissions/types.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
import { serviceContainer } from "./ServiceContainer.js";
import { SERVICE_NAMES, WorkflowServiceState } from "./types.js";
export interface InitializeToolServiceOverrides {
allow?: string[];
ask?: string[];
exclude?: string[];
mode?: PermissionMode;
isHeadless?: boolean;
}
export interface ToolPermissionServiceState {
permissions: ToolPermissions;
currentMode: PermissionMode;
isHeadless: boolean;
modePolicyCount?: number; // Track how many policies are from mode vs other sources
workflowPolicyCount?: number;
originalPolicies?: ToolPermissions; // Store original policies when switching modes
}
/**
* Service for managing tool permissions with a single source of truth
*/
export class ToolPermissionService extends BaseService<ToolPermissionServiceState> {
export class ToolPermissionService
extends BaseService<ToolPermissionServiceState>
implements ServiceWithDependencies
{
constructor() {
super("ToolPermissionService", {
permissions: { policies: [] },
@ -30,6 +46,74 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
});
}
/**
* Override setState to notify the ServiceContainer
* This ensures reactive UI components get updated when mode changes
*/
protected override setState(
newState: Partial<ToolPermissionServiceState>,
): void {
super.setState(newState);
serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, this.currentState);
}
/**
* Declare dependencies on other services
*/
getDependencies(): string[] {
return [SERVICE_NAMES.WORKFLOW];
}
/**
* Generate workflow-specific policies if a workflow is active
*/
private generateWorkflowPolicies(
workflowServiceState?: WorkflowServiceState,
): undefined | ToolPermissionPolicy[] {
if (!workflowServiceState?.workflowFile?.tools) {
return undefined;
}
const parsedTools = parseWorkflowTools(
workflowServiceState.workflowFile.tools,
);
if (parsedTools.tools.length === 0) {
return undefined;
}
const policies: ToolPermissionPolicy[] = [];
for (const toolRef of parsedTools.tools) {
if (toolRef.mcpServer) {
if (toolRef.toolName) {
policies.push({
tool: `mcp:${toolRef.mcpServer}:${toolRef.toolName}`,
permission: "allow",
});
} else {
policies.push({
tool: `mcp:${toolRef.mcpServer}:*`,
permission: "allow",
});
}
} else if (toolRef.toolName) {
policies.push({ tool: toolRef.toolName, permission: "allow" });
}
}
if (policies.length > 0) {
logger.debug(`Generated ${policies.length} workflow tool policies`);
}
if (parsedTools.allBuiltIn) {
policies.push({ tool: "*", permission: "allow" });
policies.push({ tool: "mcp:*", permission: "exclude" });
} else {
policies.push({ tool: "*", permission: "exclude" });
}
return policies;
}
/**
* Generate mode-specific policies based on the current mode
*/
@ -57,7 +141,7 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
{ tool: "Grep", permission: "allow" },
{ tool: "WebFetch", permission: "allow" },
{ tool: "WebSearch", permission: "allow" },
// Allow MCP tools (assume they're read-only by nature)
// Allow MCP tools (no way to know if they're read only but shouldn't disable mcp usage in plan)
{ tool: "mcp:*", permission: "allow" },
// Default: exclude everything else to ensure no writes
{ tool: "*", permission: "exclude" },
@ -78,13 +162,10 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
* Synchronously initialize with runtime overrides
* Used for immediate availability of command-line permission overrides
*/
initializeSync(runtimeOverrides?: {
allow?: string[];
ask?: string[];
exclude?: string[];
mode?: PermissionMode;
isHeadless?: boolean;
}): ToolPermissionServiceState {
initializeSync(
runtimeOverrides?: InitializeToolServiceOverrides,
workflowServiceState?: WorkflowServiceState,
): ToolPermissionServiceState {
logger.debug("Synchronously initializing ToolPermissionService");
// Set mode from overrides or default
@ -97,13 +178,17 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
this.setState({ isHeadless: runtimeOverrides.isHeadless });
}
// Generate mode-specific policies first (highest priority)
const workflowPolicies =
this.generateWorkflowPolicies(workflowServiceState);
const modePolicies = this.generateModePolicies();
// For plan and auto modes, use ONLY mode policies (absolute override)
// For normal mode, combine with user configuration
let allPolicies: ToolPermissionPolicy[];
if (
if (workflowPolicies) {
// Workflow policies take full precedence on init
allPolicies = workflowPolicies;
} else if (
this.currentState.currentMode === "plan" ||
this.currentState.currentMode === "auto"
) {
@ -124,9 +209,9 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
currentMode: this.currentState.currentMode,
isHeadless: this.currentState.isHeadless,
modePolicyCount: modePolicies.length,
workflowPolicyCount: (workflowPolicies ?? []).length,
});
// Mark as initialized since we're bypassing the async initialize flow
(this as any).isInitialized = true;
return this.getState();
@ -135,18 +220,14 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
/**
* Initialize the tool permission service with runtime overrides (async version)
*/
async doInitialize(runtimeOverrides?: {
allow?: string[];
ask?: string[];
exclude?: string[];
mode?: PermissionMode;
isHeadless?: boolean;
}): Promise<ToolPermissionServiceState> {
// Ensure permissions.yaml exists before loading
async doInitialize(
runtimeOverrides?: InitializeToolServiceOverrides,
workflowServiceState?: WorkflowServiceState,
): Promise<ToolPermissionServiceState> {
await ensurePermissionsYamlExists();
// Use the synchronous version after ensuring the file exists
return this.initializeSync(runtimeOverrides);
return this.initializeSync(runtimeOverrides, workflowServiceState);
}
/**
@ -173,13 +254,12 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
* Switch to a different permission mode
*/
switchMode(newMode: PermissionMode): ToolPermissionServiceState {
logger.debug(
`Switching from mode '${this.currentState.currentMode}' to '${newMode}'`,
);
const currentMode = this.currentState.currentMode;
logger.debug(`Switching from mode '${currentMode}' to '${newMode}'`);
// Store original policies when leaving normal mode for the first time
if (
this.currentState.currentMode === "normal" &&
currentMode === "normal" &&
newMode !== "normal" &&
!this.currentState.originalPolicies
) {
@ -194,7 +274,10 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
);
}
this.currentState.currentMode = newMode;
this.setState({
currentMode: newMode,
});
this.emit("modeChanged", newMode, currentMode);
// Regenerate policies with the new mode
const modePolicies = this.generateModePolicies();
@ -291,20 +374,6 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
logger.debug(
`Reloaded permissions: ${freshPolicies.length} user policies, ${modePolicies.length} mode policies`,
);
// Update the service container with the new state
// Import here to avoid circular dependencies
try {
const { serviceContainer } = await import("./ServiceContainer.js");
const { SERVICE_NAMES } = await import("./types.js");
serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, this.getState());
logger.debug("Updated service container with reloaded permissions");
} catch (error) {
logger.error(
"Failed to update service container after permission reload",
{ error },
);
}
}
/**
@ -313,4 +382,24 @@ export class ToolPermissionService extends BaseService<ToolPermissionServiceStat
override isReady(): boolean {
return true;
}
public getAvailableModes(): Array<{
mode: PermissionMode;
description: string;
}> {
return [
{
mode: "normal",
description: "Default mode - follows configured permission policies",
},
{
mode: "plan",
description: "Planning mode - only allow read-only tools for analysis",
},
{
mode: "auto",
description: "Automatically allow all tools without asking",
},
];
}
}

View file

@ -0,0 +1,292 @@
import { Mock, vi } from "vitest";
import { workflowProcessor } from "../hubLoader.js";
import { WorkflowService } from "./WorkflowService.js";
// Mock the hubLoader module
vi.mock("../hubLoader.js", () => ({
loadPackageFromHub: vi.fn(),
HubPackageProcessor: vi.fn(),
workflowProcessor: {
type: "workflow",
expectedFileExtensions: [".md"],
parseContent: vi.fn(),
validateContent: vi.fn(),
},
}));
// Mock the logger
vi.mock("../util/logger.js", () => ({
logger: {
debug: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
},
}));
describe("WorkflowService", () => {
let service: WorkflowService;
let mockLoadPackageFromHub: any;
beforeEach(async () => {
vi.clearAllMocks();
service = new WorkflowService();
// Get the mock function
const hubLoaderModule = await import("../hubLoader.js");
mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any;
});
describe("initialization", () => {
it("should initialize with inactive state when no workflow provided", async () => {
const state = await service.initialize();
expect(state).toEqual({
workflowFile: null,
slug: null,
workflowModelName: null,
workflowService: service,
});
});
it("should initialize with inactive state when workflow is empty string", async () => {
const state = await service.initialize("");
expect(state).toEqual({
workflowFile: null,
slug: null,
workflowModelName: null,
workflowService: service,
});
});
it("should reject invalid workflow slug format", async () => {
const state = await service.initialize("invalid-slug");
expect(state).toEqual({
workflowFile: null,
slug: null,
workflowModelName: null,
workflowService: service,
});
// Should not call loadPackageFromHub with invalid slug
expect(mockLoadPackageFromHub).not.toHaveBeenCalled();
});
it("should reject workflow slug with too many parts", async () => {
const state = await service.initialize("owner/package/extra");
expect(state).toEqual({
workflowFile: null,
slug: null,
workflowModelName: null,
workflowService: service,
});
expect(mockLoadPackageFromHub).not.toHaveBeenCalled();
});
it("should load valid workflow successfully", async () => {
const mockWorkflowFile = {
name: "Test Workflow",
description: "A test workflow",
model: "gpt-4",
tools: "bash,read,write",
rules: "Be helpful",
prompt: "You are a helpful assistant.",
};
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
const state = await service.initialize("owner/package");
expect(state).toEqual({
workflowFile: mockWorkflowFile,
slug: "owner/package",
workflowModelName: null,
workflowService: service,
});
expect(mockLoadPackageFromHub).toHaveBeenCalledWith(
"owner/package",
workflowProcessor,
);
});
it("should handle loading errors gracefully", async () => {
mockLoadPackageFromHub.mockRejectedValue(new Error("Network error"));
const state = await service.initialize("owner/package");
expect(state).toEqual({
workflowFile: null,
slug: null,
workflowModelName: null,
workflowService: service,
});
expect(mockLoadPackageFromHub).toHaveBeenCalledWith(
"owner/package",
workflowProcessor,
);
});
it("should handle minimal workflow file", async () => {
const mockWorkflowFile = {
name: "Minimal Workflow",
prompt: "",
};
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
const state = await service.initialize("owner/minimal");
expect(state).toEqual({
workflowFile: mockWorkflowFile,
slug: "owner/minimal",
workflowModelName: null,
workflowService: service,
});
});
});
describe("state getters", () => {
beforeEach(async () => {
const mockWorkflowFile = {
name: "Test Workflow",
description: "A test workflow",
model: "gpt-4",
tools: "bash,read,write",
rules: "Be helpful",
prompt: "You are a helpful assistant.",
};
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
await service.initialize("owner/package");
});
it("should return workflow state", () => {
const state = service.getState();
expect(state.workflowFile?.name).toBe("Test Workflow");
expect(state.slug).toBe("owner/package");
expect(state.workflowFile?.model).toBe("gpt-4");
expect(state.workflowFile?.tools).toBe("bash,read,write");
expect(state.workflowFile?.rules).toBe("Be helpful");
expect(state.workflowFile?.prompt).toBe("You are a helpful assistant.");
});
});
describe("inactive workflow state", () => {
beforeEach(() => {
service.initialize();
});
it("should return inactive state when no workflow", () => {
const state = service.getState();
expect(state.workflowFile).toBeNull();
expect(state.slug).toBeNull();
});
});
describe("partial workflow data", () => {
it("should handle workflow with only name and prompt", async () => {
const mockWorkflowFile = {
name: "Simple Workflow",
prompt: "Simple prompt",
};
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
await service.initialize("owner/simple");
const state = service.getState();
expect(state.workflowFile?.model).toBeUndefined();
expect(state.workflowFile?.tools).toBeUndefined();
expect(state.workflowFile?.rules).toBeUndefined();
expect(state.workflowFile?.prompt).toBe("Simple prompt");
});
it("should handle workflow with empty prompt", async () => {
const mockWorkflowFile = {
name: "Empty Prompt Workflow",
model: "gpt-3.5-turbo",
prompt: "",
};
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
await service.initialize("owner/empty");
const state = service.getState();
expect(state.workflowFile?.model).toBe("gpt-3.5-turbo");
expect(state.workflowFile?.prompt).toBe("");
});
});
});
describe("workflowProcessor", () => {
it("should have correct type and extensions", () => {
expect(workflowProcessor.type).toBe("workflow");
expect(workflowProcessor.expectedFileExtensions).toEqual([".md"]);
});
it("should parse workflow content correctly", () => {
const content = `---
name: Test Workflow
model: gpt-4
tools: bash,read
---
You are a helpful assistant.`;
// Set up the mock to return expected result
const expectedResult = {
name: "Test Workflow",
model: "gpt-4",
tools: "bash,read",
prompt: "You are a helpful assistant.",
};
(workflowProcessor.parseContent as Mock).mockReturnValue(expectedResult);
const result = workflowProcessor.parseContent(content, "test.md");
expect(result).toEqual({
name: "Test Workflow",
model: "gpt-4",
tools: "bash,read",
prompt: "You are a helpful assistant.",
});
});
it("should validate workflow content", () => {
const validWorkflow = {
name: "Valid Workflow",
prompt: "Test prompt",
};
const invalidWorkflow = {
prompt: "Test prompt",
// Missing name
};
// Set up mock validation responses
(workflowProcessor.validateContent as Mock)
.mockReturnValueOnce(true) // For valid workflow
.mockReturnValueOnce(false); // For invalid workflow
expect(workflowProcessor.validateContent?.(validWorkflow)).toBe(true);
expect(workflowProcessor.validateContent?.(invalidWorkflow as any)).toBe(
false,
);
});
it("should validate workflow with empty name as invalid", () => {
const invalidWorkflow = {
name: "",
prompt: "Test prompt",
};
// Mock validation to return false for empty name
(workflowProcessor.validateContent as Mock).mockReturnValue(false);
expect(workflowProcessor.validateContent?.(invalidWorkflow)).toBe(false);
});
});

View file

@ -0,0 +1,78 @@
import { loadPackageFromHub, workflowProcessor } from "../hubLoader.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
import { serviceContainer } from "./ServiceContainer.js";
import { WorkflowServiceState } from "./types.js";
/**
* Service for managing workflow state
* Loads workflows from the hub and extracts model, tools, and prompt information
*/
export class WorkflowService extends BaseService<WorkflowServiceState> {
/**
* Set the resolved workflow model name after it's been processed
* Called by ConfigEnhancer after resolving the model slug
*/
setWorkflowModelName(modelName: string): void {
this.setState({
workflowModelName: modelName,
});
}
constructor() {
super("WorkflowService", {
workflowService: null,
workflowFile: null,
slug: null,
workflowModelName: null,
});
}
/**
* Initialize the workflow service with a workflow slug
*/
async doInitialize(workflowSlug?: string): Promise<WorkflowServiceState> {
if (!workflowSlug) {
return {
workflowService: this,
workflowFile: null,
slug: null,
workflowModelName: null,
};
}
try {
const parts = workflowSlug.split("/");
if (parts.length !== 2) {
throw new Error(
`Invalid workflow slug format. Expected "owner/package", got: ${workflowSlug}`,
);
}
const workflowFile = await loadPackageFromHub(
workflowSlug,
workflowProcessor,
);
return {
workflowService: this,
workflowFile,
slug: workflowSlug,
workflowModelName: null, // Will be set by ConfigEnhancer after model resolution
};
} catch (error: any) {
logger.error("Failed to initialize WorkflowService:", error);
return {
workflowService: this,
workflowFile: null,
slug: null,
workflowModelName: null,
};
}
}
protected override setState(newState: Partial<WorkflowServiceState>): void {
super.setState(newState);
serviceContainer.set("update", this.currentState);
}
}

View file

@ -3,21 +3,13 @@ import { beforeEach, describe, expect, it } from "vitest";
import { serviceContainer } from "./ServiceContainer.js";
import type { ToolPermissionServiceState } from "./ToolPermissionService.js";
import { initializeServices, getServiceSync, SERVICE_NAMES } from "./index.js";
import { getServiceSync, initializeServices, SERVICE_NAMES } from "./index.js";
describe("Service Initialization", () => {
beforeEach(() => {
// Clean up service container state
const services = [
SERVICE_NAMES.TOOL_PERMISSIONS,
SERVICE_NAMES.AUTH,
SERVICE_NAMES.API_CLIENT,
SERVICE_NAMES.CONFIG,
SERVICE_NAMES.MODEL,
SERVICE_NAMES.MCP,
];
services.forEach((service) => {
Object.keys(SERVICE_NAMES).forEach((service) => {
// Reset service state
(serviceContainer as any).services.delete(service);
(serviceContainer as any).factories.delete(service);

View file

@ -1,9 +1,8 @@
import { vi } from "vitest";
import { modeService } from "./ModeService.js";
import { serviceContainer } from "./ServiceContainer.js";
import { WorkflowService } from "./WorkflowService.js";
import { initializeServices } from "./index.js";
import { initializeServices, services } from "./index.js";
// Mock the onboarding module
vi.mock("../onboarding.js", () => ({
@ -17,45 +16,11 @@ vi.mock("../auth/workos.js", () => ({
}));
describe("initializeServices", () => {
let mockModeService: any;
let mockServiceContainer: any;
// let mockToolPermissionsService: any;
beforeEach(() => {
// Reset all mocks
vi.clearAllMocks();
// Create mock mode service
mockModeService = {
initialize: vi.fn(),
getCurrentMode: vi.fn(),
getToolPermissionService: vi.fn().mockReturnValue({
getState: vi.fn().mockReturnValue({
currentMode: "normal",
isHeadless: false,
permissions: { policies: [] },
}),
}),
};
// Create mock service container
mockServiceContainer = {
registerValue: vi.fn(),
register: vi.fn(),
initializeAll: vi.fn().mockResolvedValue(undefined),
};
// Set up mocks
(modeService as any).initialize = mockModeService.initialize;
(modeService as any).getCurrentMode = mockModeService.getCurrentMode;
(modeService as any).getToolPermissionService =
mockModeService.getToolPermissionService;
// Mock serviceContainer methods
(serviceContainer as any).registerValue =
mockServiceContainer.registerValue;
(serviceContainer as any).register = mockServiceContainer.register;
(serviceContainer as any).initializeAll =
mockServiceContainer.initializeAll;
});
afterEach(() => {
@ -63,28 +28,8 @@ describe("initializeServices", () => {
});
describe("mode conversion", () => {
it("should pass only readonly flag for plan mode", async () => {
await initializeServices({
headless: true, // Skip onboarding
toolPermissionOverrides: {
mode: "plan",
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
},
});
expect(mockModeService.initialize).toHaveBeenCalledWith({
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
readonly: true,
isHeadless: true,
// auto should NOT be set
});
});
it("should pass only auto flag for auto mode", async () => {
const spy = vi.spyOn(services.toolPermissions, "initialize");
await initializeServices({
headless: true, // Skip onboarding
toolPermissionOverrides: {
@ -95,63 +40,21 @@ describe("initializeServices", () => {
},
});
expect(mockModeService.initialize).toHaveBeenCalledWith({
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
auto: true,
isHeadless: true,
// readonly should NOT be set
});
});
it("should pass no mode flags for normal mode", async () => {
await initializeServices({
headless: true, // Skip onboarding
toolPermissionOverrides: {
mode: "normal",
expect(spy).toHaveBeenCalledWith(
{
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
mode: "auto",
isHeadless: true,
},
});
expect(mockModeService.initialize).toHaveBeenCalledWith({
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
isHeadless: true,
// Neither readonly nor auto should be set
});
});
it("should pass no mode flags when mode is undefined", async () => {
await initializeServices({
headless: true, // Skip onboarding
toolPermissionOverrides: {
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
{
slug: null,
workflowFile: null,
workflowModelName: null,
workflowService: expect.any(WorkflowService),
},
});
expect(mockModeService.initialize).toHaveBeenCalledWith({
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
isHeadless: true,
// Neither readonly nor auto should be set
});
});
it("should call initialize with defaults when no toolPermissionOverrides provided", async () => {
await initializeServices({
headless: true, // Skip onboarding
});
expect(mockModeService.initialize).toHaveBeenCalledWith({
isHeadless: true,
});
);
});
});
});

View file

@ -9,11 +9,14 @@ import { ConfigService } from "./ConfigService.js";
import { FileIndexService } from "./FileIndexService.js";
import { MCPService } from "./MCPService.js";
import { ModelService } from "./ModelService.js";
import { modeService } from "./ModeService.js";
import { ResourceMonitoringService } from "./ResourceMonitoringService.js";
import { serviceContainer } from "./ServiceContainer.js";
import { StorageSyncService } from "./StorageSyncService.js";
import { systemMessageService } from "./SystemMessageService.js";
import { SystemMessageService } from "./SystemMessageService.js";
import {
InitializeToolServiceOverrides,
ToolPermissionService,
} from "./ToolPermissionService.js";
import {
ApiClientServiceState,
AuthServiceState,
@ -21,8 +24,10 @@ import {
SERVICE_NAMES,
ServiceInitOptions,
ServiceInitResult,
WorkflowServiceState,
} from "./types.js";
import { UpdateService } from "./UpdateService.js";
import { WorkflowService } from "./WorkflowService.js";
// Service instances
const authService = new AuthService();
@ -35,6 +40,9 @@ const resourceMonitoringService = new ResourceMonitoringService();
const chatHistoryService = new ChatHistoryService();
const updateService = new UpdateService();
const storageSyncService = new StorageSyncService();
const workflowService = new WorkflowService();
const toolPermissionService = new ToolPermissionService();
const systemMessageService = new SystemMessageService();
/**
* Initialize all services and register them with the service container
@ -76,46 +84,48 @@ export async function initializeServices(
commandOptions.config = CONFIG_PATH;
}
// Initialize mode service with tool permission overrides
if (initOptions.toolPermissionOverrides) {
const overrides = { ...initOptions.toolPermissionOverrides };
serviceContainer.register(
SERVICE_NAMES.WORKFLOW,
() => workflowService.initialize(commandOptions.workflow),
[],
);
// Convert mode to boolean flags for ModeService
const initArgs: Parameters<typeof modeService.initialize>[0] = {
allow: overrides.allow,
ask: overrides.ask,
exclude: overrides.exclude,
isHeadless: initOptions.headless,
};
// Only set the boolean flag that corresponds to the mode
if (overrides.mode === "plan") {
initArgs.readonly = true;
} else if (overrides.mode === "auto") {
initArgs.auto = true;
}
// If mode is "normal" or undefined, no flags are set
await modeService.initialize(initArgs);
} else {
// Even if no overrides, we need to initialize with defaults
await modeService.initialize({
isHeadless: initOptions.headless,
});
}
// Register the TOOL_PERMISSIONS service with immediate value
// Since ToolPermissionService is already initialized synchronously in ModeService,
// we can register it as a ready value instead of a factory
const toolPermissionState = modeService.getToolPermissionService().getState();
logger.debug("Registering TOOL_PERMISSIONS with state:", {
currentMode: toolPermissionState.currentMode,
isHeadless: toolPermissionState.isHeadless,
policyCount: toolPermissionState.permissions.policies.length,
});
serviceContainer.registerValue(
serviceContainer.register(
SERVICE_NAMES.TOOL_PERMISSIONS,
toolPermissionState,
async () => {
const workflowState = await serviceContainer.get<WorkflowServiceState>(
SERVICE_NAMES.WORKFLOW,
);
// Initialize mode service with tool permission overrides
if (initOptions.toolPermissionOverrides) {
const overrides = { ...initOptions.toolPermissionOverrides };
// Convert mode to boolean flags for ModeService
const initArgs: InitializeToolServiceOverrides = {
allow: overrides.allow,
ask: overrides.ask,
exclude: overrides.exclude,
isHeadless: initOptions.headless,
};
// Only set the boolean flag that corresponds to the mode
if (overrides.mode) {
initArgs.mode = overrides.mode;
}
// If mode is "normal" or undefined, no flags are set
return await toolPermissionService.initialize(initArgs, workflowState);
} else {
// Even if no overrides, we need to initialize with defaults
return await toolPermissionService.initialize(
{
isHeadless: initOptions.headless,
},
workflowState,
);
}
},
[SERVICE_NAMES.WORKFLOW],
);
// Initialize SystemMessageService with command options
@ -127,7 +137,7 @@ export async function initializeServices(
format: (commandOptions as any).format, // format option from CLI
headless: initOptions.headless,
}),
[], // No dependencies
[SERVICE_NAMES.TOOL_PERMISSIONS],
);
serviceContainer.register(
@ -156,9 +166,10 @@ export async function initializeServices(
serviceContainer.register(
SERVICE_NAMES.CONFIG,
async () => {
const [authState, apiClientState] = await Promise.all([
const [authState, apiClientState, workflowState] = await Promise.all([
serviceContainer.get<AuthServiceState>(SERVICE_NAMES.AUTH),
serviceContainer.get<ApiClientServiceState>(SERVICE_NAMES.API_CLIENT),
serviceContainer.get<WorkflowServiceState>(SERVICE_NAMES.WORKFLOW),
]);
// Ensure organization is selected if authenticated
@ -198,32 +209,38 @@ export async function initializeServices(
}
}
return configService.initialize(
finalAuthState.authConfig,
return configService.initialize({
authConfig: finalAuthState.authConfig,
configPath,
finalAuthState.organizationId || null,
apiClientState.apiClient,
commandOptions,
);
// organizationId: finalAuthState.organizationId || null,
apiClient: apiClientState.apiClient,
workflowState,
injectedConfigOptions: commandOptions,
});
},
[SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT], // Depends on auth and API client
[SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.WORKFLOW], // Dependencies
);
serviceContainer.register(
SERVICE_NAMES.MODEL,
async () => {
const [configState, authState] = await Promise.all([
const [configState, authState, workflowState] = await Promise.all([
serviceContainer.get<ConfigServiceState>(SERVICE_NAMES.CONFIG),
serviceContainer.get<AuthServiceState>(SERVICE_NAMES.AUTH),
serviceContainer.get<WorkflowServiceState>(SERVICE_NAMES.WORKFLOW),
]);
if (!configState.config) {
throw new Error("Config not available");
}
return modelService.initialize(configState.config, authState.authConfig);
return modelService.initialize(
configState.config,
authState.authConfig,
workflowState,
);
},
[SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH], // Depends on config and auth
[SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH, SERVICE_NAMES.WORKFLOW], // Depends on config, auth, and workflow
);
serviceContainer.register(
@ -321,12 +338,13 @@ export const services = {
apiClient: apiClientService,
mcp: mcpService,
fileIndex: fileIndexService,
mode: modeService,
resourceMonitoring: resourceMonitoringService,
systemMessage: systemMessageService,
chatHistory: chatHistoryService,
updateService: updateService,
storageSync: storageSyncService,
workflow: workflowService,
toolPermissions: toolPermissionService,
} as const;
// Export the service container for advanced usage

View file

@ -1,4 +1,8 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import {
AssistantUnrolled,
ModelConfig,
WorkflowFile,
} from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { AssistantConfig } from "@continuedev/sdk";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
@ -6,9 +10,10 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { AuthConfig } from "../auth/workos.js";
import { BaseCommandOptions } from "../commands/BaseCommandOptions.js";
import { PermissionMode, ToolPermissions } from "../permissions/types.js";
import { PermissionMode } from "../permissions/types.js";
import { MCPService } from "./MCPService.js";
import { type MCPService } from "./MCPService.js";
import { WorkflowService } from "./WorkflowService.js";
/**
* Service lifecycle states
@ -104,13 +109,6 @@ export interface ApiClientServiceState {
apiClient: DefaultApiInterface | null;
}
export interface ToolPermissionServiceState {
permissions: ToolPermissions;
currentMode: PermissionMode;
modePolicyCount?: number;
originalPolicies?: ToolPermissions;
}
export interface StorageSyncServiceState {
isEnabled: boolean;
storageId?: string;
@ -118,6 +116,13 @@ export interface StorageSyncServiceState {
lastError?: string | null;
}
export interface WorkflowServiceState {
workflowFile: WorkflowFile | null;
slug: string | null;
workflowModelName: string | null;
workflowService: WorkflowService | null;
}
export type { ChatHistoryState } from "./ChatHistoryService.js";
export type { FileIndexServiceState } from "./FileIndexService.js";
@ -137,6 +142,7 @@ export const SERVICE_NAMES = {
CHAT_HISTORY: "chatHistory",
UPDATE: "update",
STORAGE_SYNC: "storageSync",
WORKFLOW: "workflow",
} as const;
/**

View file

@ -0,0 +1,631 @@
import { vi } from "vitest";
import { ConfigEnhancer } from "../configEnhancer.js";
import { ModelService } from "./ModelService.js";
import { WorkflowService } from "./WorkflowService.js";
// Mock the hubLoader module
vi.mock("../hubLoader.js", () => ({
loadPackageFromHub: vi.fn(),
loadPackagesFromHub: vi.fn(),
mcpProcessor: {},
modelProcessor: {},
processRule: vi.fn(),
workflowProcessor: {
type: "workflow",
expectedFileExtensions: [".md"],
parseContent: vi.fn(),
validateContent: vi.fn(),
},
}));
// Mock the logger
vi.mock("../util/logger.js", () => ({
logger: {
debug: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
},
}));
// Mock config module
vi.mock("../config.js", () => ({
createLlmApi: vi.fn(),
getLlmApi: vi.fn(),
}));
// Mock auth module
vi.mock("../auth/workos.js", () => ({
getModelName: vi.fn(),
}));
describe("Workflow Integration Tests", () => {
let workflowService: WorkflowService;
let modelService: ModelService;
let configEnhancer: ConfigEnhancer;
let mockLoadPackageFromHub: any;
let mockLoadPackagesFromHub: any;
let mockProcessRule: any;
let mockCreateLlmApi: any;
let mockGetLlmApi: any;
let mockModelProcessor: any;
const mockWorkflowFile = {
name: "Test Workflow",
description: "A test workflow for integration testing",
model: "gpt-4-workflow",
tools: "bash,read,write",
rules: "Always be helpful and concise",
prompt: "You are a workflow 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();
// Get mock functions
const hubLoaderModule = await import("../hubLoader.js");
const configModule = await import("../config.js");
mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any;
mockLoadPackagesFromHub = hubLoaderModule.loadPackagesFromHub as any;
mockProcessRule = hubLoaderModule.processRule as any;
mockModelProcessor = hubLoaderModule.modelProcessor;
mockCreateLlmApi = configModule.createLlmApi as any;
mockGetLlmApi = configModule.getLlmApi as any;
// Create service instances
workflowService = new WorkflowService();
modelService = new ModelService();
configEnhancer = new ConfigEnhancer();
// Setup default mocks
mockProcessRule.mockResolvedValue("Processed rule content");
mockLoadPackagesFromHub.mockResolvedValue([{ name: "test-mcp" }]);
mockLoadPackageFromHub.mockResolvedValue({
name: "test-model",
provider: "openai",
});
mockCreateLlmApi.mockReturnValue({ mock: "llmApi" });
mockGetLlmApi.mockReturnValue([
{ mock: "llmApi" },
mockAssistant.models[0],
]);
});
describe("Workflow models are injected via ConfigEnhancer", () => {
it("should add workflow model to options when workflow is active", async () => {
// Setup workflow service with active workflow
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
await workflowService.initialize("owner/workflow");
const workflowState = workflowService.getState();
expect(workflowState.workflowFile?.model).toBe("gpt-4-workflow");
// Mock loadPackageFromHub to return a model for the workflow model
mockLoadPackageFromHub.mockResolvedValueOnce({
name: "gpt-4-workflow",
provider: "openai",
});
// Test that ConfigEnhancer adds the workflow model to options
const baseConfig = { models: [] };
const baseOptions = {}; // No --model flag
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
baseOptions,
workflowState,
);
// Should have loaded the workflow model directly via loadPackageFromHub
expect(mockLoadPackageFromHub).toHaveBeenCalledWith(
"gpt-4-workflow",
mockModelProcessor,
);
// The workflow model should be prepended to the models array
expect(enhancedConfig.models).toHaveLength(1);
expect(enhancedConfig.models?.[0]).toEqual({
name: "gpt-4-workflow",
provider: "openai",
});
});
it("should not add workflow model when no workflow is active", async () => {
// Initialize workflow service without workflow
await workflowService.initialize();
const workflowState = workflowService.getState();
expect(workflowState.workflowFile).toBeNull();
// Test that ConfigEnhancer doesn't add any workflow models
const baseConfig = { models: [] };
const baseOptions = {};
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
baseOptions,
workflowState,
);
// Should not have enhanced with any models
expect(enhancedConfig.models).toEqual([]);
});
it("should respect --model flag priority over workflow model", async () => {
// Setup workflow service with active workflow
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
await workflowService.initialize("owner/workflow");
// Mock loadPackageFromHub for workflow model and loadPackagesFromHub for user models
mockLoadPackageFromHub.mockResolvedValueOnce({
name: "gpt-4-workflow",
provider: "openai",
});
mockLoadPackagesFromHub.mockResolvedValueOnce([
{
name: "user-specified-model",
provider: "anthropic",
},
]);
// Test that --model flag takes precedence
const baseConfig = { models: [] };
const baseOptions = { model: ["user-specified-model"] }; // User specified --model
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
baseOptions,
workflowService.getState(),
);
// Should process the user model via loadPackagesFromHub
expect(mockLoadPackagesFromHub).toHaveBeenCalledWith(
["user-specified-model"],
mockModelProcessor,
);
// Should also load the workflow model
expect(mockLoadPackageFromHub).toHaveBeenCalledWith(
"gpt-4-workflow",
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-workflow",
provider: "openai",
});
});
});
describe("WorkflowService affects ConfigEnhancer", () => {
it("should inject workflow rules when workflow is active", async () => {
// Setup workflow service with active workflow
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
await workflowService.initialize("owner/workflow");
const baseConfig = {
rules: ["existing rule"],
};
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
{},
workflowService.getState(),
);
// Rules should be processed normally since workflow rules are now added to options.rule
expect(mockProcessRule).toHaveBeenCalledWith(mockWorkflowFile.rules);
expect(enhancedConfig.rules).toHaveLength(2);
// The workflow rule is processed first, then existing rules
expect(mockProcessRule).toHaveBeenNthCalledWith(
1,
mockWorkflowFile.rules,
);
});
it("should not inject workflow rules when workflow is inactive", async () => {
// Initialize workflow service without workflow
await workflowService.initialize();
const baseConfig = {
rules: ["existing rule"],
};
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
{},
workflowService.getState(),
);
expect(mockProcessRule).not.toHaveBeenCalled();
expect(enhancedConfig.rules).toHaveLength(1);
expect(enhancedConfig?.rules?.[0]).toBe("existing rule");
});
it("should not inject workflow rules when workflow has no rules", async () => {
const workflowWithoutRules = {
...mockWorkflowFile,
rules: undefined,
};
mockLoadPackageFromHub.mockResolvedValue(workflowWithoutRules);
await workflowService.initialize("owner/workflow");
const baseConfig = {
rules: ["existing rule"],
};
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
{},
workflowService.getState(),
);
expect(mockProcessRule).not.toHaveBeenCalled();
expect(enhancedConfig.rules).toHaveLength(1);
expect(enhancedConfig.rules?.[0]).toBe("existing rule");
});
});
describe("Workflow model constraints", () => {
it("should filter available models to only workflow model when specified", async () => {
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
await workflowService.initialize("owner/workflow");
await modelService.initialize(
mockAssistant as any,
mockAuthConfig as any,
);
// Verify that available models include all original models
// (we removed the filtering logic)
const availableModels = modelService.getAvailableChatModels();
expect(availableModels).toHaveLength(2); // Should include both original models
expect(availableModels.map((m) => m.name)).toEqual([
"gpt-3.5-turbo",
"gpt-4",
]);
});
it("should allow all models when no workflow is active", async () => {
await workflowService.initialize();
await modelService.initialize(
mockAssistant as any,
mockAuthConfig as any,
);
const availableModels = modelService.getAvailableChatModels();
expect(availableModels).toHaveLength(2);
expect(availableModels.map((m) => m.name)).toEqual([
"gpt-3.5-turbo",
"gpt-4",
]);
});
});
describe("Error handling", () => {
it("should handle workflow loading errors gracefully", async () => {
mockLoadPackageFromHub.mockRejectedValue(new Error("Network error"));
await workflowService.initialize("owner/workflow");
const workflowState = workflowService.getState();
expect(workflowState.workflowFile).toBeNull();
// Model service should work normally
await modelService.initialize(
mockAssistant as any,
mockAuthConfig as any,
);
expect(mockGetLlmApi).toHaveBeenCalled();
});
it("should handle workflow rule processing errors gracefully", async () => {
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
mockProcessRule.mockRejectedValue(new Error("Rule processing failed"));
await workflowService.initialize("owner/workflow");
const baseConfig = {
rules: ["existing rule"],
};
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
{},
workflowService.getState(),
);
// Should not inject workflow rule but should preserve existing rules
expect(enhancedConfig.rules).toHaveLength(1);
expect(enhancedConfig.rules?.[0]).toBe("existing rule");
});
// Removed test for missing service container since workflow service
// should always be initialized before ConfigEnhancer is called
it("should inject workflow prompt when workflow is active", async () => {
// Setup workflow service with active workflow
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
await workflowService.initialize("owner/workflow");
const baseConfig = {
rules: ["existing rule"],
prompts: [],
};
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
{},
workflowService.getState(),
);
// Workflow prompt should be added to config.prompts
expect(enhancedConfig.prompts).toBeDefined();
expect(enhancedConfig.prompts?.length).toBeGreaterThan(0);
expect(enhancedConfig.prompts?.[0]).toMatchObject({
prompt: "You are a workflow assistant.",
name: expect.stringContaining("Test Workflow"),
});
expect(enhancedConfig.rules).toHaveLength(2);
});
it("should add workflow prompt to config alongside other prompts", async () => {
// Setup workflow service with active workflow
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
await workflowService.initialize("owner/workflow");
const baseConfig = {
prompts: [{ name: "Existing", prompt: "existing-prompt" }],
};
const baseOptions = {};
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
baseOptions,
workflowService.getState(),
);
// Workflow prompt should be prepended to existing prompts
expect(enhancedConfig.prompts).toHaveLength(2);
expect(enhancedConfig.prompts?.[0]).toMatchObject({
name: expect.stringContaining("Test Workflow"),
prompt: "You are a workflow assistant.",
});
expect(enhancedConfig.prompts?.[1]).toMatchObject({
name: "Existing",
prompt: "existing-prompt",
});
});
it("should not add workflow prompt when workflow has no prompt", async () => {
const workflowWithoutPrompt = {
...mockWorkflowFile,
prompt: undefined,
};
mockLoadPackageFromHub.mockResolvedValue(workflowWithoutPrompt);
await workflowService.initialize("owner/workflow");
const baseConfig = {
prompts: [{ name: "Existing", prompt: "existing-prompt" }],
};
const baseOptions = {};
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
baseOptions,
workflowService.getState(),
);
// Should only have the existing prompt, no workflow prompt added
expect(enhancedConfig.prompts).toHaveLength(1);
expect(enhancedConfig.prompts?.[0]).toMatchObject({
name: "Existing",
prompt: "existing-prompt",
});
});
});
describe("ConfigEnhancer prompt integration", () => {
it("should add workflow prompt to config.prompts when workflow is active", async () => {
// Setup workflow service with active workflow
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
await workflowService.initialize("owner/workflow");
const baseOptions = { prompt: ["user-prompt"] };
const baseConfig = { prompts: [] };
// Enhance config with workflow state
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
baseOptions,
workflowService.getState(),
);
// Verify that the workflow prompt was added to config.prompts
expect(enhancedConfig.prompts).toBeDefined();
expect(enhancedConfig.prompts).toHaveLength(1);
expect(enhancedConfig.prompts?.[0]).toMatchObject({
name: expect.stringContaining("Test Workflow"),
prompt: "You are a workflow assistant.",
description: "A test workflow for integration testing",
});
});
it("should work end-to-end with workflow prompt in config", async () => {
// Setup workflow service with active workflow
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
await workflowService.initialize("owner/workflow");
const workflowState = workflowService.getState();
expect(workflowState.workflowFile?.prompt).toBe(
"You are a workflow assistant.",
);
const baseConfig = { prompts: [] };
const baseOptions = { prompt: ["Tell me about TypeScript"] };
// Enhance config with workflow
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
baseOptions,
workflowState,
);
// Verify workflow prompt is added to config.prompts
expect(enhancedConfig.prompts).toBeDefined();
expect(enhancedConfig.prompts?.length).toBeGreaterThan(0);
expect(enhancedConfig.prompts?.[0]?.prompt).toBe(
"You are a workflow assistant.",
);
expect(enhancedConfig.prompts?.[0]?.name).toContain("Test Workflow");
});
});
describe("Workflow data extraction", () => {
it("should correctly extract all workflow properties", async () => {
mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile);
await workflowService.initialize("owner/workflow");
const workflowState = workflowService.getState();
expect(workflowState.workflowFile?.model).toBe("gpt-4-workflow");
expect(workflowState.workflowFile?.tools).toBe("bash,read,write");
expect(workflowState.workflowFile?.rules).toBe(
"Always be helpful and concise",
);
expect(workflowState.workflowFile?.prompt).toBe(
"You are a workflow assistant.",
);
expect(workflowState.slug).toBe("owner/workflow");
});
it("should handle partial workflow data", async () => {
const partialWorkflow = {
name: "Partial Workflow",
model: "gpt-3.5-turbo",
prompt: "Partial prompt",
// No tools or rules
};
mockLoadPackageFromHub.mockResolvedValue(partialWorkflow);
await workflowService.initialize("owner/partial");
const workflowState = workflowService.getState();
expect(workflowState.workflowFile?.model).toBe("gpt-3.5-turbo");
expect(workflowState.workflowFile?.tools).toBeUndefined();
expect(workflowState.workflowFile?.rules).toBeUndefined();
expect(workflowState.workflowFile?.prompt).toBe("Partial prompt");
});
});
describe("Workflow tools integration", () => {
it("should inject MCP servers from workflow tools", async () => {
const workflowWithTools = {
...mockWorkflowFile,
tools: "owner/mcp1, another/mcp2:specific_tool",
};
mockLoadPackageFromHub.mockResolvedValue(workflowWithTools);
mockLoadPackagesFromHub.mockResolvedValue([
{ name: "mcp1" },
{ name: "mcp2" },
]);
await workflowService.initialize("owner/workflow");
const baseConfig = {
mcpServers: [{ name: "existing-mcp" }],
};
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
{},
workflowService.getState(),
);
expect(enhancedConfig.mcpServers).toHaveLength(3);
expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "mcp1" });
expect(enhancedConfig.mcpServers?.[1]).toEqual({ name: "mcp2" });
expect(enhancedConfig.mcpServers?.[2]).toEqual({ name: "existing-mcp" });
});
it("should not inject MCP servers when workflow has no tools", async () => {
const workflowWithoutTools = {
...mockWorkflowFile,
tools: undefined,
};
mockLoadPackageFromHub.mockResolvedValue(workflowWithoutTools);
await workflowService.initialize("owner/workflow");
const baseConfig = {
mcpServers: [{ name: "existing-mcp" }],
};
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
{},
workflowService.getState(),
);
expect(enhancedConfig.mcpServers).toHaveLength(1);
expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "existing-mcp" });
});
it("should deduplicate MCP servers", async () => {
const workflowWithDuplicateTools = {
...mockWorkflowFile,
tools: "owner/mcp1, owner/mcp1:tool1, owner/mcp1:tool2",
};
mockLoadPackageFromHub.mockResolvedValue(workflowWithDuplicateTools);
mockLoadPackagesFromHub.mockResolvedValue([{ name: "mcp1" }]);
await workflowService.initialize("owner/workflow");
const baseConfig = {
mcpServers: [{ name: "mcp1" }], // Already exists
};
const enhancedConfig = await configEnhancer.enhanceConfig(
baseConfig as any,
{},
workflowService.getState(),
);
// Should not deduplicate since we simplified the logic
expect(enhancedConfig.mcpServers).toHaveLength(2);
expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "mcp1" });
expect(enhancedConfig.mcpServers?.[1]).toEqual({ name: "mcp1" });
});
});
});

View file

@ -84,6 +84,10 @@ export function addCommonOptions(command: Command): Command {
return array;
},
[] as string[],
)
.option(
"--workflow <slug>",
"Load workflow from the hub (slug in format 'owner/package')",
);
}
@ -107,6 +111,7 @@ export function mergeParentOptions(parentCommand: Command, options: any): any {
"allow",
"ask",
"exclude",
"workflow",
];
for (const optName of inheritableOptions) {

View file

@ -13,16 +13,7 @@ import { getAllTools } from "./streamChatResponse.js";
describe("getAllTools - Tool Filtering", () => {
beforeEach(() => {
// Clean up service container state before each test
const services = [
SERVICE_NAMES.TOOL_PERMISSIONS,
SERVICE_NAMES.AUTH,
SERVICE_NAMES.API_CLIENT,
SERVICE_NAMES.CONFIG,
SERVICE_NAMES.MODEL,
SERVICE_NAMES.MCP,
];
services.forEach((service) => {
Object.values(SERVICE_NAMES).forEach((service) => {
// Reset service state
(serviceContainer as any).services.delete(service);
(serviceContainer as any).factories.delete(service);

View file

@ -4,24 +4,16 @@ import {
SERVICE_NAMES,
initializeServices,
serviceContainer,
services,
} from "../services/index.js";
import { modeService } from "../services/ModeService.js";
import { getAllTools } from "./handleToolCalls.js";
describe("streamChatResponse - Mode Switch During Streaming", () => {
const toolPermissionService = services.toolPermissions;
beforeEach(async () => {
// Clean up service container state before each test
const services = [
SERVICE_NAMES.TOOL_PERMISSIONS,
SERVICE_NAMES.AUTH,
SERVICE_NAMES.API_CLIENT,
SERVICE_NAMES.CONFIG,
SERVICE_NAMES.MODEL,
SERVICE_NAMES.MCP,
];
services.forEach((service) => {
Object.values(SERVICE_NAMES).forEach((service) => {
(serviceContainer as any).services.delete(service);
(serviceContainer as any).factories.delete(service);
(serviceContainer as any).dependencies.delete(service);
@ -46,10 +38,10 @@ describe("streamChatResponse - Mode Switch During Streaming", () => {
expect(toolNames).toContain("Edit");
// Switch to plan mode (simulating Shift+Tab during streaming)
modeService.switchMode("plan");
toolPermissionService.switchMode("plan");
// Update the service container (this is what UserInput.tsx does)
const updatedState = modeService.getToolPermissionService().getState();
const updatedState = toolPermissionService.getState();
serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState);
// Recompute tools - should now exclude write tools
@ -68,25 +60,25 @@ describe("streamChatResponse - Mode Switch During Streaming", () => {
test("getAllTools reflects current mode immediately", async () => {
// Start in normal mode
expect(modeService.getCurrentMode()).toBe("normal");
expect(toolPermissionService.getCurrentMode()).toBe("normal");
let tools = await getAllTools();
expect(tools.map((t) => t.function.name)).toContain("Write");
// Switch to plan mode
modeService.switchMode("plan");
let updatedState = modeService.getToolPermissionService().getState();
toolPermissionService.switchMode("plan");
let updatedState = toolPermissionService.getState();
serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState);
expect(modeService.getCurrentMode()).toBe("plan");
expect(toolPermissionService.getCurrentMode()).toBe("plan");
// getAllTools should immediately reflect the new mode
tools = await getAllTools();
expect(tools.map((t) => t.function.name)).not.toContain("Write");
// Switch to auto mode
modeService.switchMode("auto");
updatedState = modeService.getToolPermissionService().getState();
toolPermissionService.switchMode("auto");
updatedState = toolPermissionService.getState();
serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState);
expect(modeService.getCurrentMode()).toBe("auto");
expect(toolPermissionService.getCurrentMode()).toBe("auto");
// getAllTools should immediately reflect auto mode (all tools allowed)
tools = await getAllTools();

View file

@ -8,9 +8,7 @@ import type {
ChatCompletionTool,
} from "openai/resources.mjs";
import { getServiceSync, SERVICE_NAMES, services } from "../services/index.js";
import { systemMessageService } from "../services/SystemMessageService.js";
import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
import { services } from "../services/index.js";
import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { ToolCall } from "../tools/index.js";
@ -157,7 +155,9 @@ export async function processStreamingResponse(
}
// Get fresh system message and inject it
const systemMessage = await systemMessageService.getSystemMessage();
const systemMessage = await services.systemMessage.getSystemMessage(
services.toolPermissions.getState().currentMode,
);
const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage(
chatHistory,
systemMessage,
@ -337,10 +337,7 @@ export async function streamChatResponse(
hasCallbacks: !!callbacks,
});
const serviceResult = getServiceSync<ToolPermissionServiceState>(
SERVICE_NAMES.TOOL_PERMISSIONS,
);
const isHeadless = serviceResult.value?.isHeadless ?? false;
const isHeadless = services.toolPermissions.isHeadless();
let fullResponse = "";
let finalResponse = "";
@ -394,12 +391,12 @@ export async function streamChatResponse(
// Get response from LLM
const { content, toolCalls, shouldContinue } =
await processStreamingResponse({
isHeadless,
chatHistory,
model,
llmApi,
abortController,
callbacks,
isHeadless,
tools,
});

View file

@ -8,12 +8,13 @@ const { constructSystemMessage } = await import("./systemMessage.js");
vi.mock("./services/ServiceContainer.js", () => ({
serviceContainer: {
get: vi.fn().mockResolvedValue({ config: { rules: [] } }),
set: vi.fn(),
},
}));
// Mock processPromptOrRule to avoid file system operations in tests
vi.mock("./args.js", () => ({
processPromptOrRule: vi
// Mock processRule to avoid file system operations in tests
vi.mock("./hubLoader.js", () => ({
processRule: vi
.fn()
.mockImplementation((spec: string) => Promise.resolve(spec)),
}));
@ -23,7 +24,7 @@ const PLAN_MODE_STRING = "You are operating in _Plan Mode_";
describe("constructSystemMessage", () => {
it("should return base system message with rules when additionalRules is provided", async () => {
const rules = ["These are the rules for the assistant."];
const result = await constructSystemMessage(rules);
const result = await constructSystemMessage("normal", rules);
expect(result).toContain("You are an agent in the Continue CLI");
expect(result).toContain('<context name="userRules">');
@ -33,7 +34,7 @@ describe("constructSystemMessage", () => {
it("should return base system message with agent content when no rules but agent file exists", async () => {
// The implementation checks for agent files like AGENTS.md which exists in this project
const result = await constructSystemMessage();
const result = await constructSystemMessage("normal");
expect(result).toContain("You are an agent in the Continue CLI");
expect(result).toContain('<context name="userRules">');
@ -41,7 +42,7 @@ describe("constructSystemMessage", () => {
});
it("should include base system message components", async () => {
const result = await constructSystemMessage();
const result = await constructSystemMessage("normal");
expect(result).toContain("You are an agent in the Continue CLI");
expect(result).toContain("<env>");
@ -50,27 +51,27 @@ describe("constructSystemMessage", () => {
});
it("should handle whitespace-only rules message", async () => {
const result = await constructSystemMessage([" "]);
const result = await constructSystemMessage("normal", [" "]);
expect(result).toContain("You are an agent in the Continue CLI");
expect(result).toContain('<context name="userRules">');
});
it("should include working directory information", async () => {
const result = await constructSystemMessage();
const result = await constructSystemMessage("normal");
expect(result).toContain("Working directory:");
expect(result).toContain("<env>");
});
it("should include platform information", async () => {
const result = await constructSystemMessage();
const result = await constructSystemMessage("normal");
expect(result).toContain("Platform:");
});
it("should include current date", async () => {
const result = await constructSystemMessage();
const result = await constructSystemMessage("normal");
expect(result).toContain("Today's date:");
expect(result).toContain(new Date().toISOString().split("T")[0]);
@ -78,7 +79,7 @@ describe("constructSystemMessage", () => {
it("should format rules section correctly", async () => {
const rulesMessage = "Rule 1: Do this\nRule 2: Do that";
const result = await constructSystemMessage([rulesMessage]);
const result = await constructSystemMessage("normal", [rulesMessage]);
expect(result).toContain('<context name="userRules">');
expect(result).toContain(rulesMessage);
@ -89,7 +90,7 @@ describe("constructSystemMessage", () => {
const rulesMessage = `Rule 1: First rule
Rule 2: Second rule
Rule 3: Third rule`;
const result = await constructSystemMessage([rulesMessage]);
const result = await constructSystemMessage("normal", [rulesMessage]);
expect(result).toContain(rulesMessage);
expect(result).toContain('<context name="userRules">');
@ -98,7 +99,7 @@ Rule 3: Third rule`;
it("should handle special characters in rules message", async () => {
const rulesMessage = "Rule with <special> characters & symbols!";
const result = await constructSystemMessage([rulesMessage]);
const result = await constructSystemMessage("normal", [rulesMessage]);
expect(result).toContain(rulesMessage);
expect(result).toContain('<context name="userRules">');
@ -106,7 +107,7 @@ Rule 3: Third rule`;
it("should handle very long rules message", async () => {
const rulesMessage = "A".repeat(1000);
const result = await constructSystemMessage([rulesMessage]);
const result = await constructSystemMessage("normal", [rulesMessage]);
expect(result).toContain(rulesMessage);
expect(result).toContain('<context name="userRules">');
@ -114,7 +115,7 @@ Rule 3: Third rule`;
it("should combine rules and agent content when both are present", async () => {
const rulesMessage = "These are the rules.";
const result = await constructSystemMessage([rulesMessage]);
const result = await constructSystemMessage("normal", [rulesMessage]);
expect(result).toContain('<context name="userRules">');
expect(result).toContain(rulesMessage);
@ -123,7 +124,12 @@ Rule 3: Third rule`;
});
it("should add headless mode instructions when headless is true", async () => {
const result = await constructSystemMessage(undefined, undefined, true);
const result = await constructSystemMessage(
"normal",
undefined,
undefined,
true,
);
expect(result).toContain("You are an agent in the Continue CLI");
expect(result).toContain("IMPORTANT: You are running in headless mode");
@ -134,7 +140,12 @@ Rule 3: Third rule`;
});
it("should not add headless mode instructions when headless is false", async () => {
const result = await constructSystemMessage(undefined, undefined, false);
const result = await constructSystemMessage(
"normal",
undefined,
undefined,
false,
);
expect(result).toContain("You are an agent in the Continue CLI");
expect(result).not.toContain("IMPORTANT: You are running in headless mode");
@ -142,7 +153,7 @@ Rule 3: Third rule`;
});
it("should not add headless mode instructions when headless is undefined", async () => {
const result = await constructSystemMessage();
const result = await constructSystemMessage("normal");
expect(result).toContain("You are an agent in the Continue CLI");
expect(result).not.toContain("IMPORTANT: You are running in headless mode");
@ -150,7 +161,7 @@ Rule 3: Third rule`;
});
it("should add JSON format instructions when format is json", async () => {
const result = await constructSystemMessage(undefined, "json");
const result = await constructSystemMessage("normal", undefined, "json");
expect(result).toContain("You are an agent in the Continue CLI");
expect(result).toContain(
@ -162,10 +173,10 @@ Rule 3: Third rule`;
it("should add plan mode instructions when mode is plan", async () => {
const result = await constructSystemMessage(
"plan",
undefined,
undefined,
false,
"plan",
);
expect(result).toContain("You are an agent in the Continue CLI");
@ -182,10 +193,10 @@ Rule 3: Third rule`;
it("should not add plan mode instructions when mode is not plan", async () => {
const result = await constructSystemMessage(
"normal",
undefined,
undefined,
false,
"normal",
);
expect(result).toContain("You are an agent in the Continue CLI");
@ -195,8 +206,8 @@ Rule 3: Third rule`;
);
});
it("should not add plan mode instructions when mode is undefined", async () => {
const result = await constructSystemMessage();
it("should not add plan mode instructions when mode is normal", async () => {
const result = await constructSystemMessage("normal");
expect(result).toContain("You are an agent in the Continue CLI");
expect(result).not.toContain(PLAN_MODE_STRING);
@ -207,10 +218,10 @@ Rule 3: Third rule`;
it("should include basic plan mode description", async () => {
const result = await constructSystemMessage(
"plan",
undefined,
undefined,
false,
"plan",
);
expect(result).toContain(PLAN_MODE_STRING);
@ -220,10 +231,10 @@ Rule 3: Third rule`;
it("should combine plan mode with headless mode instructions", async () => {
const result = await constructSystemMessage(
"plan",
undefined,
undefined,
true,
"plan",
);
expect(result).toContain("IMPORTANT: You are running in headless mode");
@ -235,10 +246,10 @@ Rule 3: Third rule`;
it("should combine plan mode with JSON format instructions", async () => {
const result = await constructSystemMessage(
"plan",
undefined,
"json",
false,
"plan",
);
expect(result).toContain(

View file

@ -5,9 +5,8 @@ import * as path from "path";
import pkg from "ignore-walk";
import { Minimatch } from "minimatch";
import { processPromptOrRule } from "./args.js";
import { processRule } from "./hubLoader.js";
import { PermissionMode } from "./permissions/types.js";
import { modeService } from "./services/ModeService.js";
import { serviceContainer } from "./services/ServiceContainer.js";
import { ConfigServiceState, SERVICE_NAMES } from "./services/types.js";
const { WalkerSync } = pkg;
@ -125,10 +124,10 @@ async function getConfigYamlRules(): Promise<string[]> {
* @returns The comprehensive system message with base message and rules section
*/
export async function constructSystemMessage(
mode: PermissionMode,
additionalRules?: string[],
format?: "json",
headless?: boolean,
mode?: PermissionMode,
): Promise<string> {
const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"];
@ -153,7 +152,7 @@ export async function constructSystemMessage(
if (additionalRules && additionalRules.length > 0) {
for (const ruleSpec of additionalRules) {
try {
const processedRule = await processPromptOrRule(ruleSpec);
const processedRule = await processRule(ruleSpec);
processedRules.push(processedRule);
} catch (error: any) {
console.warn(
@ -166,14 +165,11 @@ export async function constructSystemMessage(
const configYamlRules = await getConfigYamlRules();
processedRules.push(...configYamlRules);
// Get current mode if not provided
const currentMode = mode ?? modeService.getCurrentMode();
// Construct the comprehensive system message
let systemMessage = baseSystemMessage;
// Add plan mode specific instructions if in plan mode
if (currentMode === "plan") {
if (mode === "plan") {
systemMessage +=
'\n<context name="planMode">You are operating in _Plan Mode_, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files. For example, it is not acceptable to use the Bash tool to write to files.</context>\n';
} else {

View file

@ -8,8 +8,8 @@ import {
MCPServiceState,
SERVICE_NAMES,
serviceContainer,
services,
} from "../services/index.js";
import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
import type { ModelServiceState } from "../services/types.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { logger } from "../util/logger.js";
@ -58,17 +58,8 @@ export const BUILTIN_TOOLS: Tool[] = BASE_BUILTIN_TOOLS;
function getDynamicTools(): Tool[] {
const dynamicTools: Tool[] = [];
// Add headless-specific tools if in headless mode
try {
const serviceResult = getServiceSync<ToolPermissionServiceState>(
SERVICE_NAMES.TOOL_PERMISSIONS,
);
const isHeadless = serviceResult.value?.isHeadless ?? false;
if (isHeadless) {
dynamicTools.push(exitTool);
}
} catch {
// Service not ready yet, no dynamic tools
if (services.toolPermissions.isHeadless()) {
dynamicTools.push(exitTool);
}
// Add beta status tool if --beta-status-tool flag is present

View file

@ -7,6 +7,8 @@ import React, {
useState,
} from "react";
import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js";
import { useServices } from "../hooks/useService.js";
import {
ApiClientServiceState,
@ -28,7 +30,6 @@ import { useChat } from "./hooks/useChat.js";
import { useContextPercentage } from "./hooks/useContextPercentage.js";
import { useMessageRenderer } from "./hooks/useMessageRenderer.js";
import {
useCurrentMode,
useIntroMessage,
useLoginHandlers,
useSelectors,
@ -95,7 +96,16 @@ function useTUIChatServices(remoteUrl?: string) {
mcp: MCPServiceState;
apiClient: ApiClientServiceState;
update: UpdateServiceState;
}>(["auth", "config", "model", "mcp", "apiClient", "update"]);
toolPermissions: ToolPermissionServiceState;
}>([
"auth",
"config",
"model",
"mcp",
"apiClient",
"update",
"toolPermissions",
]);
return { services, allServicesReady, isRemoteMode };
}
@ -162,9 +172,6 @@ const TUIChat: React.FC<TUIChatProps> = ({
allServicesReady,
);
// State for current mode (for hiding cwd in plan/auto modes)
const currentMode = useCurrentMode();
// Use login handlers
const { handleLoginPrompt, handleLoginTokenSubmit } = useLoginHandlers(
navigateTo,
@ -379,7 +386,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
{/* Free trial status and Continue CLI info - always show */}
<BottomStatusBar
currentMode={currentMode}
currentMode={services?.toolPermissions?.currentMode ?? "normal"}
remoteUrl={remoteUrl}
isRemoteMode={isRemoteMode}
services={services}

View file

@ -1,29 +1,29 @@
import { describe, expect, it, beforeEach } from "vitest";
import { modeService } from "../services/ModeService.js";
import { beforeEach, describe, expect, it } from "vitest";
import { services } from "../services/index.js";
const toolPermissionService = services.toolPermissions;
describe("UserInput Keyboard Shortcuts", () => {
beforeEach(() => {
// Reset to normal mode for each test
modeService.initialize({});
toolPermissionService.initialize({});
});
describe("mode cycling logic", () => {
it("should cycle through modes in correct order", () => {
// Initially should be normal mode
expect(modeService.getCurrentMode()).toBe("normal");
expect(toolPermissionService.getCurrentMode()).toBe("normal");
// Cycle to plan
modeService.switchMode("plan");
expect(modeService.getCurrentMode()).toBe("plan");
toolPermissionService.switchMode("plan");
expect(toolPermissionService.getCurrentMode()).toBe("plan");
// Cycle to auto
modeService.switchMode("auto");
expect(modeService.getCurrentMode()).toBe("auto");
toolPermissionService.switchMode("auto");
expect(toolPermissionService.getCurrentMode()).toBe("auto");
// Cycle back to normal
modeService.switchMode("normal");
expect(modeService.getCurrentMode()).toBe("normal");
toolPermissionService.switchMode("normal");
expect(toolPermissionService.getCurrentMode()).toBe("normal");
});
it("should cycle through all modes sequentially", () => {
@ -32,8 +32,8 @@ describe("UserInput Keyboard Shortcuts", () => {
// Test cycling through all modes
for (let i = 0; i < modes.length * 2; i++) {
const expectedMode = modes[i % modes.length];
modeService.switchMode(expectedMode);
expect(modeService.getCurrentMode()).toBe(expectedMode);
toolPermissionService.switchMode(expectedMode);
expect(toolPermissionService.getCurrentMode()).toBe(expectedMode);
}
});
});

View file

@ -7,8 +7,11 @@ import { getAllSlashCommands } from "../commands/commands.js";
import { useServices } from "../hooks/useService.js";
import type { PermissionMode } from "../permissions/types.js";
import type { FileIndexServiceState } from "../services/FileIndexService.js";
import { SERVICE_NAMES, serviceContainer } from "../services/index.js";
import { modeService } from "../services/ModeService.js";
import {
SERVICE_NAMES,
serviceContainer,
services,
} from "../services/index.js";
import { messageQueue } from "../stream/messageQueue.js";
import { InputHistory } from "../util/inputHistory.js";
@ -190,17 +193,17 @@ const UserInput: React.FC<UserInputProps> = ({
// Cycle through permission modes
const cycleModes = async () => {
const modes: PermissionMode[] = ["normal", "plan", "auto"];
const currentMode = modeService.getCurrentMode();
const currentMode = services.toolPermissions.getCurrentMode();
const currentIndex = modes.indexOf(currentMode);
const nextIndex = (currentIndex + 1) % modes.length;
const nextMode = modes[nextIndex];
modeService.switchMode(nextMode);
services.toolPermissions.switchMode(nextMode);
// Update the service container with the new tool permissions state
// Since TOOL_PERMISSIONS was registered with registerValue(), we need to
// update its value directly rather than reloading from a factory
const updatedState = modeService.getToolPermissionService().getState();
const updatedState = services.toolPermissions.getState();
serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState);
// Show a brief indicator of the mode change

View file

@ -1,21 +1,7 @@
import { vi, beforeEach, describe, it, expect } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
// Mock the services
const mockToolPermissionService = {
reloadPermissions: vi.fn(),
getState: vi.fn(),
getCurrentMode: vi.fn(() => "normal"),
};
const mockServices = {
mode: {
getToolPermissionService: vi.fn(() => mockToolPermissionService),
},
};
vi.mock("../../services/index.js", () => ({
services: mockServices,
}));
import { services } from "../../services/index.js";
vi.mock("../../services/index.js");
// Mock the permission system
vi.mock("../../permissions/policyWriter.js", () => ({
@ -63,7 +49,7 @@ describe("Permission Policy Reload Workflow", () => {
await addPolicyToYaml(policyRule);
// This is the key part we're testing - reload should be called
await services.mode.getToolPermissionService().reloadPermissions();
await services.toolPermissions.reloadPermissions();
} catch (error) {
// Handle errors gracefully
}
@ -76,7 +62,7 @@ describe("Permission Policy Reload Workflow", () => {
expect(addPolicyToYaml).toHaveBeenCalledWith(
"tool: Edit\npermission: allow",
);
expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled();
expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled();
});
it("should handle permission reload failure gracefully", async () => {
@ -90,7 +76,7 @@ describe("Permission Policy Reload Workflow", () => {
vi.mocked(addPolicyToYaml).mockResolvedValue(undefined);
// Mock reloadPermissions to fail
mockToolPermissionService.reloadPermissions.mockRejectedValue(
vi.mocked(services.toolPermissions.reloadPermissions).mockRejectedValue(
new Error("Reload failed"),
);
@ -118,7 +104,7 @@ describe("Permission Policy Reload Workflow", () => {
await addPolicyToYaml(policyRule);
// This should fail but not break the flow
await services.mode.getToolPermissionService().reloadPermissions();
await services.toolPermissions.reloadPermissions();
} catch (error) {
// Error should be caught and handled gracefully
errorCaught = true;
@ -127,7 +113,7 @@ describe("Permission Policy Reload Workflow", () => {
// Verify that despite the reload failure, the policy was still created
expect(addPolicyToYaml).toHaveBeenCalled();
expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled();
expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled();
expect(errorCaught).toBe(true);
});
@ -142,7 +128,9 @@ describe("Permission Policy Reload Workflow", () => {
vi.mocked(addPolicyToYaml).mockResolvedValue(undefined);
// Mock successful reload
mockToolPermissionService.reloadPermissions.mockResolvedValue(undefined);
vi.mocked(services.toolPermissions.reloadPermissions).mockResolvedValue(
undefined,
);
const mockActiveRequest = {
toolName: "Edit",
@ -167,13 +155,13 @@ describe("Permission Policy Reload Workflow", () => {
);
await addPolicyToYaml(policyRule);
await services.mode.getToolPermissionService().reloadPermissions();
await services.toolPermissions.reloadPermissions();
}
// AFTER: Policy is now active without restart
// Next time user tries to edit a file, it should be automatically allowed
expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled();
expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled();
// This represents the improvement: the new policy takes effect immediately
// without requiring the user to restart the Continue CLI

View file

@ -4,11 +4,14 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { getAllTools } from "src/stream/handleToolCalls.js";
import { SERVICE_NAMES, serviceContainer } from "../../services/index.js";
import { modeService } from "../../services/ModeService.js";
import {
SERVICE_NAMES,
serviceContainer,
services,
} from "../../services/index.js";
import { createUITestContext } from "../../test-helpers/ui-test-context.js";
import { AppRoot } from "../AppRoot.js";
const toolPermissionService = services.toolPermissions;
describe("TUIChat - Plan Mode Bug Reproduction", () => {
let context: any;
@ -20,7 +23,9 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => {
});
// Ensure mode service is properly initialized in normal mode
await modeService.initialize({});
await toolPermissionService.doInitialize({
mode: "normal",
});
});
afterEach(() => {
@ -142,10 +147,10 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => {
// that causes the actual bug in production
// First, set up a realistic service state (not mocked)
await modeService.initialize({ isHeadless: false });
await toolPermissionService.initialize({ isHeadless: false });
// Register the tool permissions service like the real app does
const initialState = modeService.getToolPermissionService().getState();
const initialState = toolPermissionService.getState();
serviceContainer.registerValue(
SERVICE_NAMES.TOOL_PERMISSIONS,
initialState,
@ -155,7 +160,7 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => {
expect(() => getAllTools()).not.toThrow();
// Switch modes WITHOUT updating the service container (this simulates the bug)
modeService.switchMode("plan");
toolPermissionService.switchMode("plan");
// The service container still has the old state, so getAllTools() should not find
// the updated state with plan mode permissions. However, since the ToolPermissionService
@ -172,9 +177,5 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => {
const tools = getAllTools();
expect(tools).toBeDefined();
expect(Array.isArray(tools)).toBe(true);
// But the tools returned will be for "normal" mode, not "plan" mode
// In plan mode, many tools should be excluded, but with stale normal state, all tools are available
const planModeState = modeService.getToolPermissionService().getState();
});
});

View file

@ -1,15 +1,21 @@
import { render } from "ink-testing-library";
import React from "react";
import { describe, expect, it, beforeEach } from "vitest";
import { beforeEach, describe, expect, it } from "vitest";
import { modeService } from "../../services/ModeService.js";
import { initializeServices, services } from "src/services/index.js";
import { ModeIndicator } from "./ModeIndicator.js";
describe("ModeIndicator", () => {
beforeEach(() => {
const toolPermissionService = services.toolPermissions;
beforeEach(async () => {
// Reset to normal mode for each test
modeService.initialize({});
await initializeServices({
headless: true,
toolPermissionOverrides: {
mode: "normal",
},
});
});
describe("mode display", () => {
@ -29,13 +35,13 @@ describe("ModeIndicator", () => {
});
it("should use current mode from service when no mode prop provided", () => {
modeService.switchMode("plan");
toolPermissionService.switchMode("plan");
const { lastFrame } = render(<ModeIndicator />);
expect(lastFrame()).toContain("plan]");
});
it("should prioritize mode prop over service mode", () => {
modeService.switchMode("plan");
toolPermissionService.switchMode("plan");
const { lastFrame } = render(<ModeIndicator mode="auto" />);
expect(lastFrame()).toContain("auto]");
});
@ -49,17 +55,17 @@ describe("ModeIndicator", () => {
expect(lastFrame()).toBe("");
// Switch to plan
modeService.switchMode("plan");
toolPermissionService.switchMode("plan");
rerender(<ModeIndicator />);
expect(lastFrame()).toContain("plan]");
// Switch to auto
modeService.switchMode("auto");
toolPermissionService.switchMode("auto");
rerender(<ModeIndicator />);
expect(lastFrame()).toContain("auto]");
// Switch back to normal
modeService.switchMode("normal");
toolPermissionService.switchMode("normal");
rerender(<ModeIndicator />);
expect(lastFrame()).toBe("");
});

View file

@ -1,38 +1,21 @@
import { Text } from "ink";
import React, { useEffect, useState } from "react";
import React from "react";
import { useServices } from "src/hooks/useService.js";
import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js";
import { SERVICE_NAMES } from "src/services/types.js";
import type { PermissionMode } from "../../permissions/types.js";
import { modeService } from "../../services/ModeService.js";
interface ModeIndicatorProps {
mode?: PermissionMode;
}
const ModeIndicator: React.FC<ModeIndicatorProps> = ({ mode }) => {
const [currentMode, setCurrentMode] = useState<PermissionMode>(
mode || modeService.getCurrentMode(),
);
// Update mode when it changes (for cases where mode prop is not provided)
useEffect(() => {
if (!mode) {
// Listen for immediate mode changes
const handleModeChange = (newMode: PermissionMode) => {
setCurrentMode(newMode);
};
modeService.on("modeChanged", handleModeChange);
// Set initial mode
setCurrentMode(modeService.getCurrentMode());
return () => {
modeService.off("modeChanged", handleModeChange);
};
} else if (mode !== currentMode) {
setCurrentMode(mode);
}
}, [mode]);
const { services } = useServices<{
toolPermissions: ToolPermissionServiceState;
}>([SERVICE_NAMES.TOOL_PERMISSIONS]);
const currentMode = mode ?? services.toolPermissions?.currentMode ?? "normal";
// Don't show indicator for normal mode to keep it clean
if (currentMode === "normal") {

View file

@ -749,7 +749,7 @@ export function useChat({
logger.debug(`Policy created: ${policyRule}`);
// Reload permissions to pick up the new policy without requiring restart
await services.mode.getToolPermissionService().reloadPermissions();
await services.toolPermissions.reloadPermissions();
} catch (error) {
logger.error("Failed to create policy or reload permissions", {
error,

View file

@ -1,7 +1,5 @@
import { useCallback, useEffect, useState } from "react";
import type { PermissionMode } from "../../permissions/types.js";
import { modeService } from "../../services/ModeService.js";
import { getGitBranch, getGitRemoteUrl, isGitRepo } from "../../util/git.js";
import type { ConfigOption, ModelOption } from "../types/selectorTypes.js";
@ -150,26 +148,6 @@ export function useLoginHandlers(
return { handleLoginPrompt, handleLoginTokenSubmit };
}
// Custom hook for mode tracking
export function useCurrentMode() {
const [currentMode, setCurrentMode] = useState<PermissionMode>(
modeService.getCurrentMode(),
);
useEffect(() => {
const handleModeChange = (newMode: PermissionMode) => {
setCurrentMode(newMode);
};
modeService.on("modeChanged", handleModeChange);
return () => {
modeService.off("modeChanged", handleModeChange);
};
}, []);
return currentMode;
}
// Custom hook to combine all selector logic
export function useSelectors(
configPath: string | undefined,

View file

@ -1,12 +1,12 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import * as args from "../args.js";
import { processRule } from "../hubLoader.js";
import { processAndCombinePrompts } from "./promptProcessor.js";
// Mock the args module
vi.mock("../args.js", () => ({
processPromptOrRule: vi.fn(),
vi.mock("../hubLoader.js", () => ({
processRule: vi.fn(),
}));
// Mock the logger
@ -38,7 +38,7 @@ describe("promptProcessor", () => {
});
it("should process single additional prompt without initial", async () => {
const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
const mockProcessPromptOrRule = vi.mocked(processRule);
mockProcessPromptOrRule.mockResolvedValue("processed prompt");
const result = await processAndCombinePrompts(["prompt1"]);
@ -48,7 +48,7 @@ describe("promptProcessor", () => {
});
it("should combine multiple processed prompts", async () => {
const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
const mockProcessPromptOrRule = vi.mocked(processRule);
mockProcessPromptOrRule
.mockResolvedValueOnce("first prompt")
.mockResolvedValueOnce("second prompt");
@ -62,7 +62,7 @@ describe("promptProcessor", () => {
});
it("should combine processed prompts with initial prompt", async () => {
const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
const mockProcessPromptOrRule = vi.mocked(processRule);
mockProcessPromptOrRule
.mockResolvedValueOnce("processed1")
.mockResolvedValueOnce("processed2");
@ -76,7 +76,7 @@ describe("promptProcessor", () => {
});
it("should handle processing errors and continue with successful ones", async () => {
const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
const mockProcessPromptOrRule = vi.mocked(processRule);
mockProcessPromptOrRule
.mockResolvedValueOnce("success1")
.mockRejectedValueOnce(new Error("processing failed"))
@ -89,7 +89,7 @@ describe("promptProcessor", () => {
});
it("should return initial prompt when all processing fails", async () => {
const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
const mockProcessPromptOrRule = vi.mocked(processRule);
mockProcessPromptOrRule
.mockRejectedValueOnce(new Error("fail1"))
.mockRejectedValueOnce(new Error("fail2"));
@ -103,7 +103,7 @@ describe("promptProcessor", () => {
});
it("should return undefined when all processing fails and no initial", async () => {
const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
const mockProcessPromptOrRule = vi.mocked(processRule);
mockProcessPromptOrRule.mockRejectedValue(new Error("processing failed"));
const result = await processAndCombinePrompts(["bad"]);
@ -112,7 +112,7 @@ describe("promptProcessor", () => {
});
it("should warn when processing fails", async () => {
const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
const mockProcessPromptOrRule = vi.mocked(processRule);
mockProcessPromptOrRule.mockRejectedValue(new Error("test error"));
const { logger } = await import("./logger.js");

View file

@ -1,4 +1,4 @@
import { processPromptOrRule } from "../args.js";
import { processRule } from "../hubLoader.js";
import { logger } from "./logger.js";
@ -20,7 +20,7 @@ export async function processAndCombinePrompts(
for (const promptSpec of additionalPrompts) {
try {
const processed = await processPromptOrRule(promptSpec);
const processed = await processRule(promptSpec);
processedPrompts.push(processed);
} catch (error: any) {
logger.warn(`Failed to process prompt "${promptSpec}": ${error.message}`);

View file

@ -1,4 +1,5 @@
export * from "./createMarkdownRule.js";
export * from "./createMarkdownPrompt.js";
export * from "./createMarkdownRule.js";
export * from "./getRuleType.js";
export * from "./markdownToRule.js";
export * from "./workflowFiles.js";

View file

@ -0,0 +1,604 @@
import {
parseWorkflowFile,
parseWorkflowTools,
serializeWorkflowFile,
type WorkflowFile,
} from "./workflowFiles.js";
const example = `
---
name: Example Agent / Workflow
description: Trying to wrap my head around what are these files
model: anthropic/claude-sonnet-4
tools: linear-mcp, sentry-mcp:read-alerts, Read, Glob, Bash(git diff:*)
rules: org/rule1, org/rule2
---
This is the prompt
`.trim();
const minimalExample = `
---
name: Minimal Workflow
---
Just a simple prompt
`.trim();
const invalidExample = `
---
description: Missing name field
---
This should fail
`.trim();
const noFrontmatterExample = `This is just markdown without frontmatter`;
const invalidYamlExample = `
---
name: [invalid: yaml: syntax
---
This should fail
`.trim();
describe("parseWorkflowFile", () => {
test("parses complete workflow file correctly", () => {
const result = parseWorkflowFile(example);
expect(result).toEqual({
name: "Example Agent / Workflow",
description: "Trying to wrap my head around what are these files",
model: "anthropic/claude-sonnet-4",
tools: "linear-mcp, sentry-mcp:read-alerts, Read, Glob, Bash(git diff:*)",
rules: "org/rule1, org/rule2",
prompt: "This is the prompt",
});
});
test("parses minimal workflow file with only name", () => {
const result = parseWorkflowFile(minimalExample);
expect(result).toEqual({
name: "Minimal Workflow",
prompt: "Just a simple prompt",
});
// Optional fields should be undefined
expect(result.description).toBeUndefined();
expect(result.model).toBeUndefined();
expect(result.tools).toBeUndefined();
expect(result.rules).toBeUndefined();
});
test("throws error when name field is missing", () => {
expect(() => parseWorkflowFile(invalidExample)).toThrow(
"Workflow file must contain YAML frontmatter with a 'name' field",
);
});
test("throws error when no frontmatter is present", () => {
expect(() => parseWorkflowFile(noFrontmatterExample)).toThrow(
"Workflow file must contain YAML frontmatter with a 'name' field",
);
});
test("throws error with invalid YAML syntax", () => {
expect(() => parseWorkflowFile(invalidYamlExample)).toThrow();
});
test("handles empty frontmatter with name", () => {
const emptyFrontmatter = `
---
name: Empty Test
---
`.trim();
const result = parseWorkflowFile(emptyFrontmatter);
expect(result).toEqual({
name: "Empty Test",
prompt: "",
});
});
test("handles multiline prompts", () => {
const multilineExample = `
---
name: Multiline Test
---
Line 1
Line 2
Line 4 with gap
`.trim();
const result = parseWorkflowFile(multilineExample);
expect(result.prompt).toBe("Line 1\nLine 2\n\nLine 4 with gap");
});
test("handles prompts with --- in content", () => {
const dashedContentExample = `
---
name: Dashed Content
---
This has --- in the middle
And more content after
`.trim();
const result = parseWorkflowFile(dashedContentExample);
expect(result.prompt).toBe(
"This has --- in the middle\nAnd more content after",
);
});
test("validates unknown frontmatter fields are allowed", () => {
const extraFieldsExample = `
---
name: Extra Fields Test
extraField: should be ignored by schema
---
Prompt content
`.trim();
const result = parseWorkflowFile(extraFieldsExample);
expect(result.name).toBe("Extra Fields Test");
expect(result.prompt).toBe("Prompt content");
// Extra fields should not be in the result
expect("extraField" in result).toBe(false);
});
test("parses workflow with tools but no rules", () => {
const toolsOnlyExample = `
---
name: Tools Only Workflow
description: A workflow that uses tools but no rules
tools: git, filesystem, search
---
This workflow uses tools but doesn't define any rules.
`.trim();
const result = parseWorkflowFile(toolsOnlyExample);
expect(result).toEqual({
name: "Tools Only Workflow",
description: "A workflow that uses tools but no rules",
tools: "git, filesystem, search",
prompt: "This workflow uses tools but doesn't define any rules.",
});
// Rules should be undefined
expect(result.rules).toBeUndefined();
});
test("validates required name field type", () => {
const invalidNameType = `
---
name: 123
---
Prompt
`.trim();
expect(() => parseWorkflowFile(invalidNameType)).toThrow(
"Invalid workflow file frontmatter",
);
});
});
describe("serializeWorkflowFile", () => {
test("serializes complete workflow file correctly", () => {
const workflowFile: WorkflowFile = {
name: "Test Workflow",
description: "A test workflow",
model: "anthropic/claude-3-sonnet",
tools: "tool1, tool2",
rules: "rule1, rule2",
prompt: "This is the test prompt",
};
const result = serializeWorkflowFile(workflowFile);
// Parse it back to verify round-trip consistency
const parsed = parseWorkflowFile(result);
expect(parsed).toEqual(workflowFile);
});
test("serializes minimal workflow file", () => {
const workflowFile: WorkflowFile = {
name: "Minimal",
prompt: "Simple prompt",
};
const result = serializeWorkflowFile(workflowFile);
const parsed = parseWorkflowFile(result);
expect(parsed).toEqual(workflowFile);
});
test("filters out undefined values from frontmatter", () => {
const workflowFile: WorkflowFile = {
name: "Test",
description: undefined,
model: "gpt-4",
tools: undefined,
rules: undefined,
prompt: "Test prompt",
};
const result = serializeWorkflowFile(workflowFile);
// Should not contain undefined fields in YAML
expect(result).not.toContain("description");
expect(result).not.toContain("tools");
expect(result).not.toContain("rules");
expect(result).toContain("model: gpt-4");
// Verify round-trip
const parsed = parseWorkflowFile(result);
expect(parsed.name).toBe("Test");
expect(parsed.model).toBe("gpt-4");
expect(parsed.description).toBeUndefined();
expect(parsed.tools).toBeUndefined();
expect(parsed.rules).toBeUndefined();
});
test("handles empty prompt", () => {
const workflowFile: WorkflowFile = {
name: "Empty Prompt",
prompt: "",
};
const result = serializeWorkflowFile(workflowFile);
const parsed = parseWorkflowFile(result);
expect(parsed.prompt).toBe("");
});
test("preserves multiline prompts", () => {
const workflowFile: WorkflowFile = {
name: "Multiline",
prompt: "Line 1\nLine 2\n\nLine 4",
};
const result = serializeWorkflowFile(workflowFile);
const parsed = parseWorkflowFile(result);
expect(parsed.prompt).toBe(workflowFile.prompt);
});
});
describe("round-trip consistency", () => {
test("example workflow maintains consistency", () => {
const parsed = parseWorkflowFile(example);
const serialized = serializeWorkflowFile(parsed);
const reparsed = parseWorkflowFile(serialized);
expect(reparsed).toEqual(parsed);
});
test("minimal workflow maintains consistency", () => {
const parsed = parseWorkflowFile(minimalExample);
const serialized = serializeWorkflowFile(parsed);
const reparsed = parseWorkflowFile(serialized);
expect(reparsed).toEqual(parsed);
});
});
describe("edge cases", () => {
test("handles Windows line endings", () => {
const windowsExample = example.replace(/\n/g, "\r\n");
const result = parseWorkflowFile(windowsExample);
expect(result.name).toBe("Example Agent / Workflow");
expect(result.prompt).toBe("This is the prompt");
});
test("handles mixed line endings", () => {
const mixedExample = `---\r\nname: Mixed\n---\r\nPrompt content\n`;
const result = parseWorkflowFile(mixedExample);
expect(result.name).toBe("Mixed");
expect(result.prompt).toBe("Prompt content");
});
test("handles empty name string", () => {
const emptyNameExample = `
---
name: ""
---
Prompt
`.trim();
expect(() => parseWorkflowFile(emptyNameExample)).toThrow(
"Workflow file must contain YAML frontmatter with a 'name' field",
);
});
test("handles null name", () => {
const nullNameExample = `
---
name: null
---
Prompt
`.trim();
expect(() => parseWorkflowFile(nullNameExample)).toThrow(
"Workflow file must contain YAML frontmatter with a 'name' field",
);
});
});
describe("parseWorkflowTools", () => {
it("should return empty arrays for undefined tools", () => {
const result = parseWorkflowTools(undefined);
expect(result).toEqual({ tools: [], mcpServers: [], allBuiltIn: false });
});
it("should return empty arrays for empty tools string", () => {
const result = parseWorkflowTools("");
expect(result).toEqual({ tools: [], mcpServers: [], allBuiltIn: false });
const result2 = parseWorkflowTools(" ");
expect(result2).toEqual({ tools: [], mcpServers: [], allBuiltIn: false });
});
it("should parse built-in tools", () => {
const result = parseWorkflowTools("bash, read, edit");
expect(result).toEqual({
tools: [{ toolName: "bash" }, { toolName: "read" }, { toolName: "edit" }],
mcpServers: [],
allBuiltIn: false,
});
});
it("should parse built_in keyword", () => {
const result = parseWorkflowTools("built_in");
expect(result).toEqual({
tools: [],
mcpServers: [],
allBuiltIn: true,
});
});
it("should parse built_in with other tools", () => {
const result = parseWorkflowTools("built_in, owner/package");
expect(result).toEqual({
tools: [{ mcpServer: "owner/package" }],
mcpServers: ["owner/package"],
allBuiltIn: true,
});
});
it("should parse MCP server (all tools)", () => {
const result = parseWorkflowTools("owner/package, another/server");
expect(result).toEqual({
tools: [{ mcpServer: "owner/package" }, { mcpServer: "another/server" }],
mcpServers: ["owner/package", "another/server"],
allBuiltIn: false,
});
});
it("should parse specific MCP tools", () => {
const result = parseWorkflowTools(
"owner/package:tool1, owner/package:tool2",
);
expect(result).toEqual({
tools: [
{ mcpServer: "owner/package", toolName: "tool1" },
{ mcpServer: "owner/package", toolName: "tool2" },
],
mcpServers: ["owner/package"],
allBuiltIn: false,
});
});
it("should parse mixed tool types", () => {
const result = parseWorkflowTools(
"anmcp/serverslug:a_tool, anmcp/serverslug:another_tool, asecond/mcpserver, bash, read, edit",
);
expect(result).toEqual({
tools: [
{ mcpServer: "anmcp/serverslug", toolName: "a_tool" },
{ mcpServer: "anmcp/serverslug", toolName: "another_tool" },
{ mcpServer: "asecond/mcpserver" },
{ toolName: "bash" },
{ toolName: "read" },
{ toolName: "edit" },
],
mcpServers: ["anmcp/serverslug", "asecond/mcpserver"],
allBuiltIn: false,
});
});
it("should parse mixed tools with built_in keyword", () => {
const result = parseWorkflowTools(
"built_in, anmcp/serverslug:a_tool, asecond/mcpserver",
);
expect(result).toEqual({
tools: [
{ mcpServer: "anmcp/serverslug", toolName: "a_tool" },
{ mcpServer: "asecond/mcpserver" },
],
mcpServers: ["anmcp/serverslug", "asecond/mcpserver"],
allBuiltIn: true,
});
});
it("should deduplicate MCP servers", () => {
const result = parseWorkflowTools(
"owner/package:tool1, owner/package:tool2, owner/package, other/server",
);
expect(result).toEqual({
tools: [
{ mcpServer: "owner/package", toolName: "tool1" },
{ mcpServer: "owner/package", toolName: "tool2" },
{ mcpServer: "owner/package" },
{ mcpServer: "other/server" },
],
mcpServers: ["owner/package", "other/server"],
allBuiltIn: false,
});
});
it("should handle extra whitespace", () => {
const result = parseWorkflowTools(
" owner/package:tool1 , bash , other/server ",
);
expect(result).toEqual({
tools: [
{ mcpServer: "owner/package", toolName: "tool1" },
{ toolName: "bash" },
{ mcpServer: "other/server" },
],
mcpServers: ["owner/package", "other/server"],
allBuiltIn: false,
});
});
it("should handle any MCP server slug format", () => {
expect(() => parseWorkflowTools("invalid-slug")).not.toThrow();
expect(() => parseWorkflowTools("invalid/slug/extra")).not.toThrow();
expect(() =>
parseWorkflowTools("owner/package:tool, invalid/slug/extra:tool"),
).not.toThrow();
});
it("should handle valid MCP server slug formats", () => {
const validSlugs = [
"owner/package",
"owner-name/package-name",
"owner.name/package.name",
"owner_name/package_name",
"owner123/package456",
];
for (const slug of validSlugs) {
expect(() => parseWorkflowTools(slug)).not.toThrow();
expect(() => parseWorkflowTools(`${slug}:tool`)).not.toThrow();
}
});
it("should handle empty tool names and empty entries", () => {
const result = parseWorkflowTools(
"owner/package:tool1, , owner/package:, bash",
);
expect(result).toEqual({
tools: [
{ mcpServer: "owner/package", toolName: "tool1" },
{ mcpServer: "owner/package", toolName: "" },
{ toolName: "bash" },
],
mcpServers: ["owner/package"],
allBuiltIn: false,
});
});
describe("whitespace validation in colon-separated MCP tool references", () => {
it("should reject MCP tool reference with space after colon", () => {
expect(() => parseWorkflowTools("owner/slug: tool")).toThrow(
'Invalid MCP tool reference "owner/slug: tool": colon-separated tool references cannot contain whitespace',
);
});
it("should reject MCP tool reference with space before colon", () => {
expect(() => parseWorkflowTools("owner/slug :tool")).toThrow(
'Invalid MCP tool reference "owner/slug :tool": colon-separated tool references cannot contain whitespace',
);
});
it("should reject MCP tool reference with spaces around colon", () => {
expect(() => parseWorkflowTools("owner/slug : tool")).toThrow(
'Invalid MCP tool reference "owner/slug : tool": colon-separated tool references cannot contain whitespace',
);
});
it("should reject MCP tool reference with space in tool name", () => {
expect(() => parseWorkflowTools("owner/slug:my tool")).toThrow(
'Invalid MCP tool reference "owner/slug:my tool": colon-separated tool references cannot contain whitespace',
);
});
it("should reject MCP tool reference with space in server slug", () => {
expect(() => parseWorkflowTools("owner /slug:tool")).toThrow(
'Invalid MCP tool reference "owner /slug:tool": colon-separated tool references cannot contain whitespace',
);
});
it("should reject MCP tool reference with tab character", () => {
expect(() => parseWorkflowTools("owner/slug:\ttool")).toThrow(
'Invalid MCP tool reference "owner/slug:\ttool": colon-separated tool references cannot contain whitespace',
);
});
it("should reject MCP tool reference with newline character", () => {
expect(() => parseWorkflowTools("owner/slug:\ntool")).toThrow(
'Invalid MCP tool reference "owner/slug:\ntool": colon-separated tool references cannot contain whitespace',
);
});
it("should reject MCP tool reference with multiple spaces", () => {
expect(() => parseWorkflowTools("owner/slug: tool ")).toThrow(
'Invalid MCP tool reference "owner/slug: tool": colon-separated tool references cannot contain whitespace',
);
});
it("should reject MCP tool reference with leading spaces in tool name", () => {
expect(() => parseWorkflowTools("owner/slug: tool")).toThrow(
'Invalid MCP tool reference "owner/slug: tool": colon-separated tool references cannot contain whitespace',
);
});
it("should accept valid colon-separated MCP tool reference without whitespace", () => {
const result = parseWorkflowTools("owner/package:tool_name");
expect(result).toEqual({
tools: [{ mcpServer: "owner/package", toolName: "tool_name" }],
mcpServers: ["owner/package"],
allBuiltIn: false,
});
});
it("should accept valid MCP tool references with hyphens and underscores", () => {
const result = parseWorkflowTools(
"owner-name/package_name:tool-name_123",
);
expect(result).toEqual({
tools: [
{
mcpServer: "owner-name/package_name",
toolName: "tool-name_123",
},
],
mcpServers: ["owner-name/package_name"],
allBuiltIn: false,
});
});
it("should allow whitespace between comma-separated items", () => {
const result = parseWorkflowTools(
"owner/package:tool1, owner/package:tool2 , bash",
);
expect(result).toEqual({
tools: [
{ mcpServer: "owner/package", toolName: "tool1" },
{ mcpServer: "owner/package", toolName: "tool2" },
{ toolName: "bash" },
],
mcpServers: ["owner/package"],
allBuiltIn: false,
});
});
it("should reject whitespace in one reference but accept valid references in same string", () => {
expect(() =>
parseWorkflowTools("owner/package:tool1, owner/package: tool2, bash"),
).toThrow(
'Invalid MCP tool reference "owner/package: tool2": colon-separated tool references cannot contain whitespace',
);
});
it("should not reject whitespace in MCP server references without colon", () => {
// Note: This behavior may or may not be desired, but documents current behavior
// Server-only references (no colon) don't trigger the whitespace check
expect(() => parseWorkflowTools("owner /package")).not.toThrow();
});
it("should not reject whitespace in built-in tool names", () => {
// Note: This behavior may or may not be desired, but documents current behavior
// Built-in tools (no slash) don't trigger the whitespace check
expect(() => parseWorkflowTools("my tool")).not.toThrow();
});
});
});

View file

@ -0,0 +1,157 @@
import * as YAML from "yaml";
import z from "zod";
import { parseMarkdownRule } from "./markdownToRule.js";
/*
Experimental/internal config format for workflows
*/
const workflowFileFrontmatterSchema = z.object({
name: z.string().min(1, "Name cannot be empty"),
description: z.string().optional(),
model: z.string().optional(),
tools: z.string().optional(), // TODO also accept yaml array
rules: z.string().optional(), // TODO also accept yaml array
});
export type WorkflowFileFrontmatter = z.infer<
typeof workflowFileFrontmatterSchema
>;
const workflowFileSchema = workflowFileFrontmatterSchema.extend({
prompt: z.string(),
});
export type WorkflowFile = z.infer<typeof workflowFileSchema>;
/**
* Parsed workflow tool reference
*/
export interface WorkflowToolReference {
/** MCP server slug (owner/package) if this is an MCP tool */
mcpServer?: string;
/** Specific tool name - either MCP tool name or built-in tool name */
toolName?: string;
}
/**
* Parsed workflow tools configuration
*/
export interface ParsedWorkflowTools {
/** All tool references */
tools: WorkflowToolReference[];
/** Unique MCP server slugs that need to be added to config */
mcpServers: string[];
/** Whether all built-in tools are allowed */
allBuiltIn: boolean;
}
/**
* Parses and validates a workflow file from markdown content
* Workflow files must have frontmatter with at least a name
*/
export function parseWorkflowFile(content: string): WorkflowFile {
const { frontmatter, markdown } = parseMarkdownRule(content);
if (!frontmatter.name) {
throw new Error(
"Workflow file must contain YAML frontmatter with a 'name' field",
);
}
const validationResult = workflowFileFrontmatterSchema.safeParse(frontmatter);
if (!validationResult.success) {
const errorDetails = validationResult.error.issues
.map((issue) => `${issue.path.join(".")}: ${issue.message}`)
.join(", ");
throw new Error(`Invalid workflow file frontmatter: ${errorDetails}`);
}
return {
...validationResult.data,
prompt: markdown,
};
}
/**
* Serializes a Workflow file back to markdown with YAML frontmatter
*/
export function serializeWorkflowFile(workflowFile: WorkflowFile): string {
const { prompt, ...frontmatter } = workflowFile;
// Filter out undefined values from frontmatter
const cleanFrontmatter = Object.fromEntries(
Object.entries(frontmatter).filter(([, value]) => value !== undefined),
);
const yamlFrontmatter = YAML.stringify(cleanFrontmatter).trim();
return `---\n${yamlFrontmatter}\n---\n${prompt}`;
}
/**
* Parse workflow tools string into structured format
*
* Supports formats:
* - owner/package - all tools from MCP server
* - owner/package:tool_name - specific tool from MCP server
* - ToolName or tool_name - built-in tool
* - built_in - all built-in tools
*
* @param toolsString Comma-separated tools string
* @returns Parsed tools configuration
*/
export function parseWorkflowTools(toolsString?: string): ParsedWorkflowTools {
if (!toolsString?.trim()) {
return { tools: [], mcpServers: [], allBuiltIn: false };
}
const tools: WorkflowToolReference[] = [];
const mcpServerSet = new Set<string>();
let allBuiltIn = false;
const toolRefs = toolsString
.split(",")
.map((t) => t.trim())
.filter(Boolean);
for (const toolRef of toolRefs) {
if (toolRef === "built_in") {
// Special keyword for all built-in tools
allBuiltIn = true;
} else if (toolRef.includes("/")) {
// MCP tool reference: "owner/package" or "owner/package:tool_name"
const colonIndex = toolRef.indexOf(":");
if (colonIndex > 0) {
// Specific tool: "owner/package:tool_name"
// Reject references with whitespace to prevent silent misconfigurations
if (/\s/.test(toolRef)) {
throw new Error(
`Invalid MCP tool reference "${toolRef}": colon-separated tool references cannot contain whitespace. ` +
`Use format "owner/slug:tool_name" without spaces.`,
);
}
const mcpServer = toolRef.substring(0, colonIndex);
const toolName = toolRef.substring(colonIndex + 1);
tools.push({ mcpServer, toolName });
mcpServerSet.add(mcpServer);
} else {
// All tools from server: "owner/package"
const mcpServer = toolRef;
tools.push({ mcpServer });
mcpServerSet.add(mcpServer);
}
} else {
// Built-in tool
tools.push({ toolName: toolRef });
}
}
return {
tools,
mcpServers: Array.from(mcpServerSet),
allBuiltIn,
};
}