diff --git a/src/core/assistant-message/presentAssistantMessage.ts b/src/core/assistant-message/presentAssistantMessage.ts index d14239d97e..ab2b404536 100644 --- a/src/core/assistant-message/presentAssistantMessage.ts +++ b/src/core/assistant-message/presentAssistantMessage.ts @@ -42,13 +42,16 @@ import { codebaseSearchTool } from "../tools/CodebaseSearchTool" import { formatResponse } from "../prompts/responses" import { sanitizeToolUseId } from "../../utils/tool-id" +import { MiddlewareChain } from "../middlewares/MiddlewareChain" +import { IntentValidationMiddleware } from "../middlewares/IntentValidationMiddleware" +import { ScopeEnforcementMiddleware } from "../middlewares/ScopeEnforcementMiddleware" /** * Processes and presents assistant message content to the user interface. * * This function is the core message handling system that: * - Sequentially processes content blocks from the assistant's response. - * - Displays text content to the user. + * - Displays text content to the user * - Executes tool use requests with appropriate user approval. * - Manages the flow of conversation by determining when to proceed to the next content block. * - Coordinates file system checkpointing for modified files. @@ -681,20 +684,16 @@ export async function presentAssistantMessage(cline: Task) { } } - // TODO: requiresIntent check should be based on tool definition, not hardcoded list - const requiresIntent: ToolName[] = [ - "apply_diff", - "write_to_file", - "edit_file", - "apply_patch", - "execute_command", - "search_replace", - "edit", - ] + const middlewareChain = new MiddlewareChain() + middlewareChain.add(new IntentValidationMiddleware()) + middlewareChain.add(new ScopeEnforcementMiddleware()) - if (requiresIntent.includes(block.name as ToolName) && !cline.getHasSelectedIntent()) { - const errorMsg = "You must call select_active_intent before using modification tools." - pushToolResult(formatResponse.toolError(errorMsg)) + const middlewareResult = await middlewareChain.executeBefore(block.params, cline, block.name) + if (!middlewareResult.allow) { + pushToolResult(middlewareResult.error || "Middleware validation failed") + cline.consecutiveMistakeCount++ + cline.didToolFailInCurrentTurn = true + cline.recordToolError(block.name as ToolName, middlewareResult.error || "Middleware validation failed") break } diff --git a/src/core/middlewares/IntentValidationMiddleware.ts b/src/core/middlewares/IntentValidationMiddleware.ts new file mode 100644 index 0000000000..0404f17426 --- /dev/null +++ b/src/core/middlewares/IntentValidationMiddleware.ts @@ -0,0 +1,23 @@ +import { ToolName } from "@roo-code/types" +import { Task } from "../task/Task" +import { ToolMiddleware, MiddlewareResult } from "./ToolMiddleware" + +export class IntentValidationMiddleware implements ToolMiddleware { + name = "intentValidation" + + async beforeExecute(_params: any, task: Task, toolName: ToolName): Promise { + if (toolName === "select_active_intent" || toolName === "list_active_intents") { + return { allow: true } + } + + const selectedIntentId = task.getSelectedIntentId() + if (!selectedIntentId) { + return { + allow: false, + error: "No active intent selected. Use select_active_intent first.", + } + } + + return { allow: true } + } +} diff --git a/src/core/middlewares/MiddlewareChain.ts b/src/core/middlewares/MiddlewareChain.ts new file mode 100644 index 0000000000..c3c85a88c3 --- /dev/null +++ b/src/core/middlewares/MiddlewareChain.ts @@ -0,0 +1,25 @@ +import { ToolName } from "@roo-code/types" +import { Task } from "../task/Task" +import { ToolMiddleware, MiddlewareResult } from "./ToolMiddleware" + +export class MiddlewareChain { + private middlewares: ToolMiddleware[] = [] + + add(middleware: ToolMiddleware): void { + this.middlewares.push(middleware) + } + + async executeBefore(params: any, task: Task, toolName: ToolName): Promise { + for (const middleware of this.middlewares) { + const result = await middleware.beforeExecute?.(params, task, toolName) + if (result?.allow === false) { + return result + } + + if (result?.modifiedParams) { + params = result.modifiedParams + } + } + return { allow: true } + } +} diff --git a/src/core/middlewares/ScopeEnforcementMiddleware.ts b/src/core/middlewares/ScopeEnforcementMiddleware.ts new file mode 100644 index 0000000000..14419952e0 --- /dev/null +++ b/src/core/middlewares/ScopeEnforcementMiddleware.ts @@ -0,0 +1,56 @@ +import { ToolName } from "@roo-code/types" +import { Task } from "../task/Task" +import { ToolMiddleware, MiddlewareResult } from "./ToolMiddleware" + +export class ScopeEnforcementMiddleware implements ToolMiddleware { + name = "scopeEnforcement" + + async beforeExecute(params: any, task: Task, toolName: ToolName): Promise { + const destructiveTools: Array = ["write_to_file", "edit", "apply_diff", "execute_command"] + if (!destructiveTools.includes(toolName)) { + return { allow: true } + } + + const selectedIntentId = task.getSelectedIntentId() + if (!selectedIntentId) { + return { allow: false, error: "No active intent selected" } + } + + const provider = task.providerRef.deref() + if (!provider) { + return { allow: false, error: "Provider unavailable" } + } + + try { + const intentLoader = provider.getIntentLoader() + await intentLoader.ensureLoaded() + const intent = intentLoader.getIntent(selectedIntentId) + + if (!intent) { + return { allow: false, error: `Intent '${selectedIntentId}' not found` } + } + + if (toolName === "write_to_file" && params.path) { + if (intent.owned_scopes?.length) { + const isAuthorized = intent.owned_scopes.some( + (scope) => params.path.startsWith(scope) || params.path === scope, + ) + + if (!isAuthorized) { + return { + allow: false, + error: `Scope Violation: ${selectedIntentId} not authorized to edit ${params.path}`, + } + } + } + } + + return { allow: true } + } catch (error) { + return { + allow: false, + error: `Error validating scope: ${error instanceof Error ? error.message : String(error)}`, + } + } + } +} diff --git a/src/core/middlewares/ToolMiddleware.ts b/src/core/middlewares/ToolMiddleware.ts new file mode 100644 index 0000000000..02063e1626 --- /dev/null +++ b/src/core/middlewares/ToolMiddleware.ts @@ -0,0 +1,13 @@ +import { Task } from "../task/Task" + +export interface MiddlewareResult { + allow: boolean + error?: string + modifiedParams?: any +} + +export interface ToolMiddleware { + name: string + beforeExecute?(params: any, task: Task, toolName: string): Promise + afterExecute?(result: any, task: Task, toolName: string): Promise +} diff --git a/src/core/prompts/sections/intent-protocol.ts b/src/core/prompts/sections/intent-protocol.ts index ba18a9b767..360e1b5dfe 100644 --- a/src/core/prompts/sections/intent-protocol.ts +++ b/src/core/prompts/sections/intent-protocol.ts @@ -2,13 +2,18 @@ export function intentProtocolSection(): string { return ` === -INTENT-DRIVEN PROTOCOL +INTENT-DRIVEN PROTOCOL + +You are an Intent-Driven Architect. You MUST follow this two-step process before making any changes: -1. You MUST call the tool "select_active_intent" before making any code edits or running destructive commands. -2. You may call read-only tools before selecting an intent, but you must select an intent before: +You CANNOT write code or modify files until you have successfully selected an intent. The intent context will provide you with the scope, constraints, and acceptance criteria for your work.1. You MUST call the tool "select_active_intent" before making any code edits or running destructive commands. + +1. First, call list_active_intents to discover all available intents +2. Then, call select_active_intent(intent_id) with the appropriate intent ID +3. You may call read-only tools before selecting an intent, but you must select an intent before: - apply_diff / write_to_file / edit_file / apply_patch - execute_command that changes the repo (git commit, installs, deletions, etc.) -3. If you are unsure which intent applies, request the list of intents from the user or consult the intent index below. -4. After selecting an intent, you must keep all actions within owned_scope and obey constraints. +4. If you are unsure which intent applies, request the list of intents from the user or consult the intent index below. +5. After selecting an intent, you must keep all actions within owned_scope and obey constraints. `.trim() } diff --git a/src/core/prompts/tools/native-tools/list_active_intents.ts b/src/core/prompts/tools/native-tools/list_active_intents.ts index 37e8fd5b4f..bfbc35bd7b 100644 --- a/src/core/prompts/tools/native-tools/list_active_intents.ts +++ b/src/core/prompts/tools/native-tools/list_active_intents.ts @@ -1,12 +1,33 @@ import type OpenAI from "openai" -const LIST_ACTIVE_INTENT_DESCRIPTION = `` -// TODO: add params here later for the list active intents +const LIST_ACTIVE_INTENTS_DESCRIPTION = `List all currently active intents available for selection. Use this tool when you need to choose which intent to work on before making any code changes. + +This tool reads the workspace intent registry (typically .orchestration/active_intents.json) and returns a compact list of intents with: +- id +- name +- status +- owned_scope (high-level scope paths) +- constraints (short summary) +- acceptance_criteria (short summary) + +When to use: +- At the start of a task, before calling select_active_intent +- When you are unsure which intent ID applies +- When select_active_intent fails due to an invalid ID + +Example: List all available active intents +{}` export default { type: "function", function: { name: "list_active_intents", - description: LIST_ACTIVE_INTENT_DESCRIPTION, + description: LIST_ACTIVE_INTENTS_DESCRIPTION, + parameters: { + type: "object", + properties: {}, + additionalProperties: false, + required: [], + }, }, } satisfies OpenAI.Chat.ChatCompletionTool diff --git a/src/core/prompts/tools/native-tools/select_active_intent.ts b/src/core/prompts/tools/native-tools/select_active_intent.ts index 506a36be36..62c79e105c 100644 --- a/src/core/prompts/tools/native-tools/select_active_intent.ts +++ b/src/core/prompts/tools/native-tools/select_active_intent.ts @@ -1,10 +1,20 @@ import type OpenAI from "openai" -const SELECT_ACTIVE_INTENT_DESCRIPTION = ` -Select and activate an intent from active_intents.json.\n -This must be called before making any changes to understand what changes are intended.\n -` -const INTENT_ID_DESCRIPTION = `The intent_id for the currently selected intent by the LLM and will be activated by LLM` +const SELECT_ACTIVE_INTENT_DESCRIPTION = `Select and activate a specific intent by ID. This MUST be called before making any code changes. + +After selecting an intent, all subsequent work should stay within the intent's owned_scope and obey its constraints. The tool returns an block containing the intent details for prompt injection. + +When to use: +- Immediately after list_active_intents, once you choose the correct ID +- At the start of a new task or when switching to a different intent + +Parameters: +- intent_id: (required) The ID of the intent to activate (e.g., "INT-001") + +Example: Activate intent INT-001 +{ "intent_id": "INT-001" }` + +const INTENT_ID_DESCRIPTION = `Intent ID to activate (e.g., "INT-001"). Choose from list_active_intents results.` export default { type: "function", @@ -15,11 +25,13 @@ export default { parameters: { type: "object", properties: { - path: { + intent_id: { type: "string", description: INTENT_ID_DESCRIPTION, }, }, + required: ["intent_id"], + additionalProperties: false, }, }, } satisfies OpenAI.Chat.ChatCompletionTool diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index eb24ec3196..61c6760977 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -863,6 +863,31 @@ export class Task extends EventEmitter implements TaskLike { return [instance, promise] } + private async validateIntentGate(): Promise { + const lastMessage = this.apiConversationHistory[this.apiConversationHistory.length - 1] + const lastMessageContent = lastMessage?.content + + if (Array.isArray(lastMessageContent)) { + const hasIntentSection = lastMessageContent.some((block) => { + return ( + block.type === "tool_use" && + (block.name === "select_active_intent" || block.name === "list_active_intents") + ) + }) + + if (!hasIntentSection && !this.selectedIntentId) { + await this.say( + "error", + "You must cite a valid Intent ID. Use select_active_intent or list_active_intents first.", + ) + return false + } + return true + } + + return false + } + // API Messages private async getSavedApiConversationHistory(): Promise { @@ -2793,6 +2818,11 @@ export class Task extends EventEmitter implements TaskLike { const streamModelInfo = this.cachedStreamingModel.info const cachedModelId = this.cachedStreamingModel.id + const hasValidIntent = await this.validateIntentGate() + if (!hasValidIntent) { + return true + } + // Yields only if the first chunk is successful, otherwise will // allow the user to retry the request (most likely due to rate // limit error, which gets thrown on the first chunk). diff --git a/src/core/tools/ListActiveIntents.ts b/src/core/tools/ListActiveIntents.ts index f1ce9aa2fb..93939ef07f 100644 --- a/src/core/tools/ListActiveIntents.ts +++ b/src/core/tools/ListActiveIntents.ts @@ -1,12 +1,46 @@ import { Task } from "../task/Task" +import type { Intent } from "../intents/types" import { BaseTool, ToolCallbacks } from "./BaseTool" +import { ToolUse } from "../../shared/tools" export class ListActiveIntents extends BaseTool<"list_active_intents"> { readonly name = "list_active_intents" as const - override execute(_params: any, _task: Task, _callbacks: ToolCallbacks): Promise { - throw new Error("Method not implemented.") + async execute(_params: any, task: Task, callbacks: ToolCallbacks): Promise { + const { pushToolResult, handleError } = callbacks + + try { + const provider = task.providerRef.deref() + if (!provider) { + // TODO: Figure out what to do when provider becomes undefined + return + } + + const intentLoader = provider.getIntentLoader() + await intentLoader.ensureLoaded() + + const intents = intentLoader.getAllIntents() + if (intents.length === 0) { + pushToolResult("No active intents found in .orchestration/active_intents.json") + return + } + + pushToolResult(`Available intents:\n\n${this.formatIntentList(intents)}`) + } catch (error) { + handleError("list active intents", error) + } } + + private formatIntentList(intents: Array) { + return intents + .map( + (intent) => + `- ${intent.id}: ${intent.name} (${intent.status})\n Scope: ${intent.owned_scopes?.join(", ") || "None"}\n Constraints: ${intent.constraints?.join(", ") || "None"}`, + ) + .join("\n\n") + } + + override async handlePartial(_task: Task, _block: ToolUse<"list_active_intents">): Promise {} } export const listActiveIntentsTool = new ListActiveIntents() diff --git a/src/core/tools/SelectActiveIntent.ts b/src/core/tools/SelectActiveIntent.ts index 35421c953b..deb5f570b2 100644 --- a/src/core/tools/SelectActiveIntent.ts +++ b/src/core/tools/SelectActiveIntent.ts @@ -2,6 +2,7 @@ import { Task } from "../task/Task" import { BaseTool, ToolCallbacks } from "./BaseTool" import { Intent } from "../intents/types" import { formatResponse } from "../prompts/responses" +import { ToolUse } from "../../shared/tools" interface SelectActiveIntentParams { intent_id: string @@ -25,6 +26,7 @@ export class SelectActiveIntentTool extends BaseTool<"select_active_intent"> { const provider = task.providerRef.deref() if (!provider) { + // TODO: Figure out what to do when the provider becomes undefined return } @@ -77,6 +79,8 @@ export class SelectActiveIntentTool extends BaseTool<"select_active_intent"> { ``, ].join("\n") } + + override async handlePartial(_task: Task, _block: ToolUse<"select_active_intent">): Promise {} } export const selectActiveIntentTool = new SelectActiveIntentTool() diff --git a/src/shared/tools.ts b/src/shared/tools.ts index 6b9c676861..2b1b9e2e3e 100644 --- a/src/shared/tools.ts +++ b/src/shared/tools.ts @@ -115,6 +115,8 @@ export type NativeToolArgs = { update_todo_list: { todos: string } use_mcp_tool: { server_name: string; tool_name: string; arguments?: Record } write_to_file: { path: string; content: string } + select_active_intent: { intent_id: string } + list_active_intents: {} // Add more tools as they are migrated to native protocol } @@ -296,7 +298,14 @@ export const TOOL_DISPLAY_NAMES: Record = { // Define available tool groups. export const TOOL_GROUPS: Record = { read: { - tools: ["read_file", "search_files", "list_files", "codebase_search", "select_active_intent"], + tools: [ + "read_file", + "search_files", + "list_files", + "codebase_search", + "select_active_intent", + "list_active_intents", + ], }, edit: { tools: ["apply_diff", "write_to_file", "generate_image"], @@ -323,6 +332,8 @@ export const ALWAYS_AVAILABLE_TOOLS: ToolName[] = [ "update_todo_list", "run_slash_command", "skill", + "select_active_intent", + "list_active_intents", ] as const /**