import { approvalId, type ConfirmPrompt, renderPlan } from '@agentic-kit/harness'; import { canceled, layerError } from './input'; import { type ChangeCommand, CliError, type CommandContext, type CommandErrorCode, type CommandResult, ExitCode, type NextWord } from './types'; /** What the layer does with a planned change, from the flags and the terminal of the run alone. */ export type Approval = 'show-plan' | 'apply' | 'apply-if-same' | 'ask' | 'approval-required'; /** The condition on every --approve step: an agent must not run it on its own. */ export const APPROVAL_WHEN = 'Only after a person approves this plan'; /** * --dry-run shows the plan, --approve applies it only if it is still that plan, and --yes approves any plan. A * run that cannot prompt stops before the change. At a terminal, the person's own ordinary write applies at once, and * a destructive change, or any change made for an agent, asks first. */ export function decideApproval(run: { dryRun: boolean; yes: boolean; interactive: boolean; approve?: string; destructive: boolean; forAgent: boolean }): Approval { if (run.dryRun) return 'show-plan'; if (run.approve !== undefined) return 'apply-if-same'; if (run.yes) return 'apply'; if (!run.interactive) return 'approval-required'; return run.destructive || run.forAgent ? 'ask' : 'apply'; } /** The data of a `--dry-run`: nothing was changed, this is what would be, and the id that approves exactly this. */ export interface PlanData { applied: false; plan: ConfirmPrompt; planId: string; } /** * The run a plan was made for besides its input: the global flags, and the JSON Schema of both, which marks what only * says how a secret arrives; why prompts are off, if they are; and whether the run acts for an agent. */ export interface PlanRun { globals: Record; schema: { input?: object; globals?: object }; blocker?: string; forAgent: boolean; inputFromStdin?: boolean; } /** The plan in plain text, then its title as the question: "Delete 3 rows from tasks? (y/n) [n]". */ async function confirmed(ctx: CommandContext, plan: ConfirmPrompt): Promise { ctx.stderr.write(`${renderPlan(plan)}\n\n`); const question = plan.title.endsWith('?') ? plan.title : `${plan.title}?`; const answers = await ctx.prompter.prompt<{ yes?: boolean }>({}, [{ type: 'confirm', name: 'yes', message: question, default: false }]); return answers.yes === true; } /** Plans the change, and applies it only when the run approves that plan: the one approval step of every change. */ export async function runChange( command: ChangeCommand, input: Record, ctx: CommandContext, dryRun: boolean, run: PlanRun ): Promise> { const planned = await command.plan(input, ctx); const { plan } = planned; // The id binds the command, its input and global flags (but no x-delivery part), the directory and the plan. const planId = approvalId({ action: command.name, input: { input, globals: run.globals }, schema: { type: 'object', properties: { input: run.schema.input ?? {}, globals: run.schema.globals ?? {} } }, cwd: ctx.cwd, plan }); const needs = ctx.interactive ? [] : planned.needs ?? []; const approve: NextWord[] = [...needs, '--approve', planId]; if (run.inputFromStdin) approve.unshift('--input', { placeholder: '@file-with-original-json' }); // A flag the step adds replaces the value the run gave it (--from-stdin=false), so the step names it once. const replaced = needs.map((flag) => flag.replace(/^--/, '').split('=')[0]); const shown = (): string => renderPlan(plan); // A change interrupted while it was planned is not applied: the interrupt is reported whatever the plan was. const apply = (): Promise> | CommandResult => { if (ctx.signal?.aborted) throw layerError({ code: 'interrupted', message: 'The command was interrupted (SIGINT). Nothing changed.', exitCode: ExitCode.interrupted }); return command.apply(input, planned, ctx); }; const approveStep = (drop: string[]) => ({ ...ctx.followUp(approve, { drop: [...drop, 'yes', 'approve', ...replaced, ...(run.inputFromStdin ? ['input'] : [])], why: run.inputFromStdin ? 'Apply the plan with the original JSON input in an @file' : 'Apply the plan' }), when: APPROVAL_WHEN }); const stop = (code: CommandErrorCode, message: string): CliError => { if (ctx.format === 'text') ctx.stderr.write(`${shown()}\n\n`); return new CliError({ code, message, hint: 'Show the plan to the person, then run the --approve step.', next: [approveStep([])], exitCode: ExitCode.approvalRequired, details: { plan, planId } }); }; const decided = decideApproval({ dryRun, yes: ctx.yes, interactive: ctx.interactive, approve: ctx.approve, destructive: command.effect === 'destructive', forAgent: run.forAgent }); switch (decided) { case 'show-plan': { const data: PlanData = { applied: false, plan, planId }; return { data, text: renderPlan(plan), next: [approveStep(['dry-run'])] }; } case 'apply-if-same': if (ctx.approve === planId) return apply(); throw stop('plan-changed', 'Nothing changed. The plan is no longer the one that was approved.'); case 'apply': return apply(); case 'ask': if (await confirmed(ctx, plan)) return apply(); throw canceled(); case 'approval-required': throw stop('approval-required', `Nothing changed. The plan needs a person's approval, and no prompt can ask: ${run.blocker}.`); } }