File size: 8,020 Bytes
7a1ad33 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | /**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
BaseDeclarativeTool,
BaseToolInvocation,
Kind,
ToolConfirmationOutcome,
type ToolConfirmationPayload,
type ToolExitPlanModeConfirmationDetails,
type ToolExitPlanModeConfirmationPayload,
type ToolResult,
type ExecuteOptions,
} from './tools.js';
import type { MessageBus } from '../confirmation-bus/message-bus.js';
import path from 'node:path';
import type { Config } from '../config/config.js';
import { EXIT_PLAN_MODE_TOOL_NAME } from './tool-names.js';
import {
validatePlanPath,
validatePlanContent,
resolveAndValidatePlanPath,
} from '../utils/planUtils.js';
import { ApprovalMode } from '../policy/types.js';
import { logPlanExecution } from '../telemetry/loggers.js';
import { PlanExecutionEvent } from '../telemetry/types.js';
import { getExitPlanModeDefinition } from './definitions/coreTools.js';
import { resolveToolDeclaration } from './definitions/resolver.js';
import { getPlanModeExitMessage } from '../utils/approvalModeUtils.js';
export interface ExitPlanModeParams {
plan_filename: string;
}
export class ExitPlanModeTool extends BaseDeclarativeTool<
ExitPlanModeParams,
ToolResult
> {
static readonly Name = EXIT_PLAN_MODE_TOOL_NAME;
constructor(
private config: Config,
messageBus: MessageBus,
) {
const definition = getExitPlanModeDefinition();
super(
ExitPlanModeTool.Name,
'Exit Plan Mode',
definition.base.description!,
Kind.Plan,
definition.base.parametersJsonSchema,
messageBus,
);
}
protected override validateToolParamValues(
params: ExitPlanModeParams,
): string | null {
if (!params.plan_filename || params.plan_filename.trim() === '') {
return 'plan_filename is required.';
}
try {
resolveAndValidatePlanPath(
params.plan_filename,
this.config.storage.getPlansDir(),
this.config.getProjectRoot(),
);
} catch (e) {
return e instanceof Error ? e.message : String(e);
}
return null;
}
protected createInvocation(
params: ExitPlanModeParams,
messageBus: MessageBus,
toolName: string,
toolDisplayName: string,
): ExitPlanModeInvocation {
return new ExitPlanModeInvocation(
params,
messageBus,
toolName,
toolDisplayName,
this.config,
);
}
override getSchema(modelId?: string) {
return resolveToolDeclaration(getExitPlanModeDefinition(), modelId);
}
}
export class ExitPlanModeInvocation extends BaseToolInvocation<
ExitPlanModeParams,
ToolResult
> {
private confirmationOutcome: ToolConfirmationOutcome | null = null;
private approvalPayload: ToolExitPlanModeConfirmationPayload | null = null;
private planValidationError: string | null = null;
constructor(
params: ExitPlanModeParams,
messageBus: MessageBus,
toolName: string,
toolDisplayName: string,
private config: Config,
) {
super(params, messageBus, toolName, toolDisplayName);
}
override async shouldConfirmExecute(
abortSignal: AbortSignal,
): Promise<ToolExitPlanModeConfirmationDetails | false> {
const resolvedPlanPath = this.getResolvedPlanPath();
const pathError = await validatePlanPath(
this.params.plan_filename,
this.config.storage.getPlansDir(),
this.config.getProjectRoot(),
);
if (pathError) {
this.planValidationError = pathError;
return false;
}
const contentError = await validatePlanContent(resolvedPlanPath);
if (contentError) {
this.planValidationError = contentError;
return false;
}
const decision = await this.getMessageBusDecision(abortSignal);
if (decision === 'deny') {
throw new Error(
`Tool execution for "${
this._toolDisplayName || this._toolName
}" denied by policy.`,
);
}
if (decision === 'allow') {
// If policy is allow, auto-approve with default settings and execute.
this.confirmationOutcome = ToolConfirmationOutcome.ProceedOnce;
this.approvalPayload = {
approved: true,
approvalMode: this.getAllowApprovalMode(),
};
return false;
}
// decision is 'ask_user'
return {
type: 'exit_plan_mode',
title: 'Plan Approval',
planPath: resolvedPlanPath,
onConfirm: async (
outcome: ToolConfirmationOutcome,
payload?: ToolConfirmationPayload,
) => {
this.confirmationOutcome = outcome;
if (payload && 'approved' in payload) {
this.approvalPayload = payload;
}
},
};
}
getDescription(): string {
return `Requesting plan approval for: ${path.join(this.config.storage.getPlansDir(), this.params.plan_filename)}`;
}
/**
* Returns the resolved plan path.
* Note: Validation is done in validateToolParamValues, so this assumes the path is valid.
*/
private getResolvedPlanPath(): string {
return resolveAndValidatePlanPath(
this.params.plan_filename,
this.config.storage.getPlansDir(),
this.config.getProjectRoot(),
);
}
async execute({ abortSignal: _signal }: ExecuteOptions): Promise<ToolResult> {
const resolvedPlanPath = this.getResolvedPlanPath();
if (this.planValidationError) {
return {
llmContent: this.planValidationError,
returnDisplay: 'Error: Invalid plan',
};
}
if (this.confirmationOutcome === ToolConfirmationOutcome.Cancel) {
return {
llmContent:
'User cancelled the plan approval dialog. The plan was not approved and you are still in Plan Mode.',
returnDisplay: 'Cancelled',
};
}
// When a user policy grants `allow` for exit_plan_mode, the scheduler
// skips the confirmation phase entirely and shouldConfirmExecute is never
// called, leaving approvalPayload null.
const payload = this.approvalPayload ?? {
approved: true,
approvalMode: this.getAllowApprovalMode(),
};
if (payload.approved) {
const newMode = payload.approvalMode ?? ApprovalMode.DEFAULT;
if (newMode === ApprovalMode.PLAN) {
throw new Error(`Unexpected approval mode: ${newMode}`);
}
this.config.setApprovalMode(newMode);
this.config.setApprovedPlanPath(resolvedPlanPath);
logPlanExecution(this.config, new PlanExecutionEvent(newMode));
const exitMessage = getPlanModeExitMessage(newMode);
return {
llmContent: `${exitMessage}
The approved implementation plan is stored at: ${resolvedPlanPath}
Read and follow the plan strictly during implementation.`,
returnDisplay: `Plan approved: ${resolvedPlanPath}`,
};
} else {
const feedback = payload?.feedback?.trim();
if (feedback) {
return {
llmContent: `Plan rejected. User feedback: ${feedback}
The plan is stored at: ${resolvedPlanPath}
Revise the plan based on the feedback.`,
returnDisplay: `Feedback: ${feedback}`,
};
} else {
return {
llmContent: `Plan rejected. No feedback provided.
The plan is stored at: ${resolvedPlanPath}
Ask the user for specific feedback on how to improve the plan.`,
returnDisplay: 'Rejected (no feedback)',
};
}
}
}
/**
* Determines the approval mode to switch to when plan mode is exited via a policy ALLOW.
* In non-interactive environments, this defaults to YOLO to allow automated execution.
*/
private getAllowApprovalMode(): ApprovalMode {
if (!this.config.isInteractive()) {
// For non-interactive environment requires minimal user action, exit as YOLO mode for plan implementation.
return ApprovalMode.YOLO;
}
// By default, YOLO mode in interactive environment cannot enter/exit plan mode.
// Always exit plan mode and move to default approval mode if exit_plan_mode tool is configured with allow decision.
return ApprovalMode.DEFAULT;
}
}
|