diff --git a/extensions/cli/src/permissions/defaultPolicies.ts b/extensions/cli/src/permissions/defaultPolicies.ts index 4951169a5..0664ae1f6 100644 --- a/extensions/cli/src/permissions/defaultPolicies.ts +++ b/extensions/cli/src/permissions/defaultPolicies.ts @@ -13,6 +13,7 @@ export function getDefaultToolPolicies( { tool: "MultiEdit", permission: "ask" }, { tool: "Write", permission: "ask" }, + { tool: "AskQuestion", permission: "allow" }, { tool: "Checklist", permission: "allow" }, { tool: "Diff", permission: "allow" }, { tool: "Exit", permission: "allow" }, // Exit tool is generally safe (headless mode only) @@ -46,6 +47,7 @@ export const PLAN_MODE_POLICIES: ToolPermissionPolicy[] = [ // TODO address bash read only concerns, maybe make permissions more granular { tool: "Bash", permission: "allow" }, + { tool: "AskQuestion", permission: "allow" }, { tool: "Checklist", permission: "allow" }, { tool: "Diff", permission: "allow" }, { tool: "Exit", permission: "allow" }, diff --git a/extensions/cli/src/services/QuizService.ts b/extensions/cli/src/services/QuizService.ts new file mode 100644 index 000000000..df424d850 --- /dev/null +++ b/extensions/cli/src/services/QuizService.ts @@ -0,0 +1,112 @@ +import { EventEmitter } from "events"; + +/**Types */ +export interface QuizQuestion { + question: string; + options?: string[]; + defaultAnswer?: string; +} + +export interface PendingQuestion extends QuizQuestion { + requestId: string; + timestamp: number; +} + +export interface QuizAnswer { + requestId: string; + answer: string; + isCustomAnswer: boolean; +} + +export interface QuizServiceState { + pendingQuestion: PendingQuestion | null; +} + +export interface QuestionRequestedEvent { + requestId: string; + question: QuizQuestion; +} + +export interface QuestionAnsweredEvent { + requestId: string; + answer: string; + isCustomAnswer: boolean; +} + +/**Quiz service */ +export class QuizService extends EventEmitter { + private pendingRequests = new Map< + string, + { + question: QuizQuestion; + resolve: (answer: string) => void; + } + >(); + + private currentState: QuizServiceState = { + pendingQuestion: null, + }; + + /**set a pending question to be answered and return a promise that resolves when the question is answered */ + async askQuestion(question: QuizQuestion): Promise { + const requestId = `quiz-${Date.now()}`; + + return new Promise((resolve) => { + const pendingQuestion: PendingQuestion = { + ...question, + requestId, + timestamp: Date.now(), + }; + + this.pendingRequests.set(requestId, { + question, + resolve, + }); + + this.currentState.pendingQuestion = pendingQuestion; + + const event: QuestionRequestedEvent = { + requestId, + question, + }; + + this.emit("questionRequested", event); + }); + } + + /**answer the pending question request and resolve the answer */ + answerQuestion( + requestId: string, + answer: string, + isCustomAnswer = false, + ): boolean { + const pending = this.pendingRequests.get(requestId); + if (!pending) { + return false; + } + + this.pendingRequests.delete(requestId); + this.currentState.pendingQuestion = null; + + const event: QuestionAnsweredEvent = { + requestId, + answer, + isCustomAnswer, + }; + + this.emit("questionAnswered", event); + pending.resolve(answer); + + return true; + } + + async initialize(): Promise { + this.currentState = { + pendingQuestion: null, + }; + this.pendingRequests.clear(); + return this.currentState; + } +} + +export const quizService = new QuizService(); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index c1807e55c..ffb7cba2c 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -17,6 +17,7 @@ import { FileIndexService } from "./FileIndexService.js"; import { GitAiIntegrationService } from "./GitAiIntegrationService.js"; import { MCPService } from "./MCPService.js"; import { ModelService } from "./ModelService.js"; +import { quizService } from "./QuizService.js"; import { ResourceMonitoringService } from "./ResourceMonitoringService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { StorageSyncService } from "./StorageSyncService.js"; @@ -325,6 +326,12 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { [], // No dependencies ); + serviceContainer.register( + SERVICE_NAMES.QUIZ, + () => quizService.initialize(), + [], // No dependencies + ); + // Eagerly initialize all services to ensure they're ready when needed // This avoids race conditions and "service not ready" errors await serviceContainer.initializeAll(); @@ -389,6 +396,7 @@ export const services = { artifactUpload: artifactUploadService, gitAiIntegration: gitAiIntegrationService, backgroundJobs: backgroundJobService, + quiz: quizService, } as const; export type ServicesType = typeof services; diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index 6011bbd5c..3b3776883 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -158,6 +158,7 @@ export const SERVICE_NAMES = { ARTIFACT_UPLOAD: "artifactUpload", GIT_AI_INTEGRATION: "gitAiIntegration", BACKGROUND_JOBS: "backgroundJobs", + QUIZ: "quiz", } as const; /** diff --git a/extensions/cli/src/tools/allBuiltIns.ts b/extensions/cli/src/tools/allBuiltIns.ts index c5d054e6f..a7a501c71 100644 --- a/extensions/cli/src/tools/allBuiltIns.ts +++ b/extensions/cli/src/tools/allBuiltIns.ts @@ -1,5 +1,6 @@ import { SUBAGENT_TOOL_META } from "../subagent/index.js"; +import { askQuestionTool } from "./askQuestion.js"; import { editTool } from "./edit.js"; import { exitTool } from "./exit.js"; import { fetchTool } from "./fetch.js"; @@ -18,6 +19,7 @@ import { writeFileTool } from "./writeFile.js"; // putting in here for circular import issue export const ALL_BUILT_IN_TOOLS = [ + askQuestionTool, editTool, exitTool, fetchTool, diff --git a/extensions/cli/src/tools/askQuestion.ts b/extensions/cli/src/tools/askQuestion.ts new file mode 100644 index 000000000..beb3f81fb --- /dev/null +++ b/extensions/cli/src/tools/askQuestion.ts @@ -0,0 +1,61 @@ +import { quizService } from "../services/QuizService.js"; + +import { Tool } from "./types.js"; + +export const askQuestionTool: Tool = { + name: "AskQuestion", + displayName: "Ask Question", + description: `Ask the user a clarifying question to gather requirements, preferences, or implementation details before proceeding. +Guidelines: +- You should use this tool **whenever you want to clarify your assumption or need answers to build your plan**. +- DO NOT supply "other" or "none of the above" or similar as an option. User can always provide a free-form answer when needed. +`, + parameters: { + type: "object", + required: ["question", "options"], + properties: { + question: { + type: "string", + description: "The question to ask the user", + }, + options: { + type: "array", + description: + "The list of choices. Leave as empty array if user should provide a free-form answer.", + items: { + type: "string", + }, + }, + defaultAnswer: { + type: "string", + description: + "Default answer if user presses Enter without providing input", + }, + }, + }, + readonly: true, + isBuiltIn: true, + run: async (args: { + question: string; + options?: string[]; + defaultAnswer?: string; + }): Promise => { + const { question, options, defaultAnswer } = args; + + const answer = await quizService.askQuestion({ + question, + options, + defaultAnswer, + }); + + if (options && options.length > 0) { + const selectedIndex = options.indexOf(answer); + if (selectedIndex !== -1) { + return `User selected option ${selectedIndex + 1}: "${answer}"`; + } + return `User provided custom answer: "${answer}"`; + } + + return `User answered: "${answer}"`; + }, +}; diff --git a/extensions/cli/src/tools/builtInToolNames.ts b/extensions/cli/src/tools/builtInToolNames.ts index 274b19e7f..a19753276 100644 --- a/extensions/cli/src/tools/builtInToolNames.ts +++ b/extensions/cli/src/tools/builtInToolNames.ts @@ -6,6 +6,7 @@ * When adding a new built-in tool, update both this list and ALL_BUILT_IN_TOOLS in allBuiltIns.ts. */ export const BUILT_IN_TOOL_NAMES = [ + "AskQuestion", "Edit", "Exit", "Fetch", diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index eb10d870d..fb43739f8 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -19,6 +19,7 @@ import { telemetryService } from "../telemetry/telemetryService.js"; import { logger } from "../util/logger.js"; import { ALL_BUILT_IN_TOOLS } from "./allBuiltIns.js"; +import { askQuestionTool } from "./askQuestion.js"; import { checkBackgroundJobTool } from "./checkBackgroundJob.js"; import { editTool } from "./edit.js"; import { exitTool } from "./exit.js"; @@ -70,6 +71,7 @@ const BASE_BUILTIN_TOOLS: Tool[] = [ fetchTool, writeChecklistTool, checkBackgroundJobTool, + askQuestionTool, ]; const BUILTIN_SEARCH_TOOLS: Tool[] = [searchCodeTool]; diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index bedad8b38..62174cead 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -184,6 +184,7 @@ function useChatHandlers( }; } +// eslint-disable-next-line complexity const TUIChat: React.FC = ({ remoteUrl, configPath, @@ -261,6 +262,7 @@ const TUIChat: React.FC = ({ compactionStartTime, inputMode, activePermissionRequest, + activeQuizQuestion, wasInterrupted, queuedMessages, handleUserMessage, @@ -269,6 +271,7 @@ const TUIChat: React.FC = ({ resetChatHistory, handleEditMessage, handleToolPermissionResponse, + handleQuizAnswer, } = useChat({ assistant: services.config?.config || undefined, model: services.model?.model || undefined, @@ -332,7 +335,9 @@ const TUIChat: React.FC = ({ // Determine if input should be disabled // Allow input even when services are loading, but disable for UI overlays const isInputDisabled = - navState.currentScreen !== "chat" || !!activePermissionRequest; + navState.currentScreen !== "chat" || + !!activePermissionRequest || + !!activeQuizQuestion; // Check if verbose mode is enabled for resource debugging const isVerboseMode = useMemo(() => process.argv.includes("--verbose"), []); @@ -430,7 +435,9 @@ const TUIChat: React.FC = ({ handleReload={handleReload} closeCurrentScreen={closeCurrentScreen} activePermissionRequest={activePermissionRequest} + activeQuizQuestion={activeQuizQuestion} handleToolPermissionResponse={handleToolPermissionResponse} + handleQuizAnswer={handleQuizAnswer} handleUserMessage={handleUserMessage} isWaitingForResponse={isWaitingForResponse} isCompacting={isCompacting} diff --git a/extensions/cli/src/ui/components/ChatScreenContent.tsx b/extensions/cli/src/ui/components/ChatScreenContent.tsx index 7c3225da6..49eed4058 100644 --- a/extensions/cli/src/ui/components/ChatScreenContent.tsx +++ b/extensions/cli/src/ui/components/ChatScreenContent.tsx @@ -1,19 +1,25 @@ import type { AssistantConfig } from "@continuedev/sdk"; import React from "react"; -import type { ActivePermissionRequest } from "../hooks/useChat.types.js"; +import type { + ActivePermissionRequest, + ActiveQuizQuestion, +} from "../hooks/useChat.types.js"; import { UserInput } from "../UserInput.js"; +import { QuizPrompt } from "./QuizPrompt.js"; import { ToolPermissionSelector } from "./ToolPermissionSelector.js"; interface ChatScreenContentProps { activePermissionRequest: ActivePermissionRequest | null; + activeQuizQuestion: ActiveQuizQuestion | null; handleToolPermissionResponse: ( requestId: string, approved: boolean, createPolicy?: boolean, stopStream?: boolean, ) => void; + handleQuizAnswer: (requestId: string, answer: string) => void; handleUserMessage: (message: string, imageMap?: Map) => void; isWaitingForResponse: boolean; isCompacting: boolean; @@ -30,7 +36,9 @@ interface ChatScreenContentProps { export const ChatScreenContent: React.FC = ({ activePermissionRequest, + activeQuizQuestion, handleToolPermissionResponse, + handleQuizAnswer, handleUserMessage, isWaitingForResponse, isCompacting, @@ -44,6 +52,18 @@ export const ChatScreenContent: React.FC = ({ onImageInClipboardChange, onShowEditSelector, }) => { + if (activeQuizQuestion) { + return ( + + ); + } + if (activePermissionRequest) { return ( void; +} + +/**Quiz prompt component for answering for the AskQuestion tool and QuizService */ +export const QuizPrompt: React.FC = ({ + question, + options: rawOptions, + defaultAnswer, + requestId, + onAnswer, +}) => { + const options = Array.isArray(rawOptions) ? rawOptions : undefined; + const [selectedIndex, setSelectedIndex] = useState(0); + const [isCustomMode, setIsCustomMode] = useState( + !options || options.length === 0, + ); // allows typing out an answer even when there are options + const [customInput, setCustomInput] = useState(""); + const [submitted, setSubmitted] = useState(false); + + const hasOptions = options && options.length > 0; + + useInput((input, key) => { + if (submitted) return; + + if (isCustomMode) { + // submit the typed answer + if (key.return) { + const answer = customInput.trim() || defaultAnswer || ""; + if (answer) { + setSubmitted(true); + onAnswer(requestId, answer, true); + } + return; + } + + if (key.backspace || key.delete) { + setCustomInput((prev) => prev.slice(0, -1)); + return; + } + + if (hasOptions && key.upArrow && customInput === "") { + // exit out of typing a custom answer + setIsCustomMode(false); + setSelectedIndex(options.length - 1); + return; + } + + if (input && !key.ctrl && !key.meta) { + // handle typing a custom answer + setCustomInput((prev) => prev + input); + } + return; + } + + if (key.return) { + // submit the selected option + if (hasOptions && options[selectedIndex]) { + setSubmitted(true); + onAnswer(requestId, options[selectedIndex], false); + } + return; + } + + // navigate between options + if (key.upArrow) { + setSelectedIndex((prev) => + prev === 0 ? (hasOptions ? options.length - 1 : 0) : prev - 1, + ); + } else if (key.downArrow) { + if (hasOptions) { + if (selectedIndex === options.length - 1) { + setIsCustomMode(true); + setSelectedIndex(0); + } else { + setSelectedIndex((prev) => + prev === options.length - 1 ? 0 : prev + 1, + ); + } + } + } + + if (input && !key.ctrl && !key.meta && !key.upArrow && !key.downArrow) { + setIsCustomMode(true); + setCustomInput(input); + } + }); + + if (submitted) { + return null; + } + + return ( + + + + ?{" "} + + {question} + + + {hasOptions && !isCustomMode && ( + + {options.map((option, index) => { + const isSelected = index === selectedIndex; + return ( + + + {isSelected ? "❯ " : " "} + {option} + + + ); + })} + + + {" "}(or start typing for custom answer) + + + + )} + + {isCustomMode && ( + + + ❯ + {customInput} + ▊ + + {defaultAnswer && !customInput && ( + + + (Press Enter for default: {defaultAnswer}) + + + )} + + )} + + + + {hasOptions && !isCustomMode + ? "↑/↓ navigate, Enter select" + : "Type answer, Enter submit"} + + + + ); +}; diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index aff68f1ce..516cb7811 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -9,7 +9,10 @@ import type { NavigationScreen } from "../context/NavigationContext.js"; import { DiffViewer } from "../DiffViewer.js"; import { EditMessageSelector } from "../EditMessageSelector.js"; import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js"; -import type { ActivePermissionRequest } from "../hooks/useChat.types.js"; +import type { + ActivePermissionRequest, + ActiveQuizQuestion, +} from "../hooks/useChat.types.js"; import { JobsSelector } from "../JobsSelector.js"; import { MCPSelector } from "../MCPSelector.js"; import { ModelSelector } from "../ModelSelector.js"; @@ -31,12 +34,14 @@ interface ScreenContentProps { handleReload: () => Promise; closeCurrentScreen: () => void; activePermissionRequest: ActivePermissionRequest | null; + activeQuizQuestion: ActiveQuizQuestion | null; handleToolPermissionResponse: ( requestId: string, approved: boolean, createPolicy?: boolean, stopStream?: boolean, ) => void; + handleQuizAnswer: (requestId: string, answer: string) => void; handleUserMessage: (message: string, imageMap?: Map) => void; isWaitingForResponse: boolean; isCompacting: boolean; @@ -72,7 +77,9 @@ export const ScreenContent: React.FC = ({ handleReload, closeCurrentScreen, activePermissionRequest, + activeQuizQuestion, handleToolPermissionResponse, + handleQuizAnswer, handleUserMessage, isWaitingForResponse, isCompacting, @@ -198,7 +205,9 @@ export const ScreenContent: React.FC = ({ return ( ([]); const [activePermissionRequest, setActivePermissionRequest] = useState(null); + const [activeQuizQuestion, setActiveQuizQuestion] = + useState(null); const [compactionIndex, setCompactionIndex] = useState(() => { // When resuming or forking, check for compaction markers in the loaded history if ((resume || fork) && currentSession.history.length > 0) { @@ -195,6 +198,27 @@ export function useChat({ }; }, []); + // Set up quiz service listeners + useEffect(() => { + const quizSvc = services.quiz; + + const onQuestionRequested = (pending: ActiveQuizQuestion) => { + setActiveQuizQuestion(pending); + }; + + const onQuestionAnswered = () => { + setActiveQuizQuestion(null); + }; + + quizSvc.on("questionRequested", onQuestionRequested); + quizSvc.on("questionAnswered", onQuestionAnswered); + + return () => { + quizSvc.off("questionRequested", onQuestionRequested); + quizSvc.off("questionAnswered", onQuestionAnswered); + }; + }, []); + // Clean up abort controller on unmount useEffect(() => { return () => { @@ -829,6 +853,11 @@ export function useChat({ } }; + const handleQuizAnswer = (requestId: string, answer: string) => { + setActiveQuizQuestion(null); + services.quiz.answerQuestion(requestId, answer); + }; + return { chatHistory, setChatHistory: setChatHistory, @@ -839,6 +868,7 @@ export function useChat({ inputMode, attachedFiles, activePermissionRequest, + activeQuizQuestion, wasInterrupted, queuedMessages, handleUserMessage, @@ -847,5 +877,6 @@ export function useChat({ resetChatHistory, handleEditMessage, handleToolPermissionResponse, + handleQuizAnswer, }; } diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index ac2ecc5c6..0e2887c6a 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -2,6 +2,7 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import type { Session } from "core/index.js"; +import { QuestionRequestedEvent } from "../../services/QuizService.js"; import { ToolCallPreview } from "../../tools/types.js"; export interface UseChatProps { @@ -42,6 +43,8 @@ export interface ActivePermissionRequest { hasDynamicEvaluation?: boolean; } +export type ActiveQuizQuestion = QuestionRequestedEvent; + export interface RemoteServerState { session: Session; isProcessing: boolean;