Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
RequestPermissionResponse,
} from "@agentclientprotocol/sdk";
import type {
PermissionMode,
PermissionRuleValue,
PermissionUpdate,
} from "@anthropic-ai/claude-agent-sdk";
Expand Down Expand Up @@ -31,6 +32,7 @@ import type { Session } from "../types";
import {
buildExitPlanModePermissionOptions,
buildPermissionOptions,
CLEAR_AND_CONTINUE_OPTION_ID,
} from "./permission-options";
import {
extractPostHogSubTool,
Expand Down Expand Up @@ -252,32 +254,72 @@ async function requestPlanApproval(
});
}

const PLAN_APPROVAL_MODE_OPTION_IDS = [
"auto",
"default",
"acceptEdits",
"bypassPermissions",
] as const satisfies readonly PermissionMode[];

function isPlanApprovalMode(value: string): value is PermissionMode {
return (PLAN_APPROVAL_MODE_OPTION_IDS as readonly string[]).includes(value);
}

function resolvePlanApprovalMode(
optionId: string,
response: RequestPermissionResponse,
previousMode?: string,
): PermissionMode | null {
if (isPlanApprovalMode(optionId)) {
return optionId;
}

// Opt-in clear-and-continue: honor the ModeSelector choice when present,
// otherwise fall back to the mode the session was in before plan mode.
if (optionId === CLEAR_AND_CONTINUE_OPTION_ID) {
const answers = response._meta?.answers as
| Record<string, string>
| undefined;
const fromAnswers = answers?.executionMode;
if (typeof fromAnswers === "string" && isPlanApprovalMode(fromAnswers)) {
return fromAnswers;
}
if (previousMode && isPlanApprovalMode(previousMode)) {
return previousMode;
}
return "default";
}

return null;
}

async function applyPlanApproval(
response: RequestPermissionResponse,
context: ToolHandlerContext,
updatedInput: Record<string, unknown>,
): Promise<ToolPermissionResult> {
if (
response.outcome?.outcome === "selected" &&
(response.outcome.optionId === "auto" ||
response.outcome.optionId === "default" ||
response.outcome.optionId === "acceptEdits" ||
response.outcome.optionId === "bypassPermissions")
) {
await context.applySessionMode(response.outcome.optionId);
await context.updateConfigOption("mode", response.outcome.optionId);
if (response.outcome?.outcome === "selected") {
const mode = resolvePlanApprovalMode(
response.outcome.optionId,
response,
context.session.modeBeforePlan,
);
if (mode) {
await context.applySessionMode(mode);
await context.updateConfigOption("mode", mode);

return {
behavior: "allow",
updatedInput,
updatedPermissions: context.suggestions ?? [
{
type: "setMode",
mode: response.outcome.optionId,
destination: "localSettings",
},
],
};
return {
behavior: "allow",
updatedInput,
updatedPermissions: context.suggestions ?? [
{
type: "setMode",
mode,
destination: "localSettings",
},
],
};
}
}

const customInput = (response._meta as Record<string, unknown> | undefined)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,20 @@ describe("buildExitPlanModePermissionOptions", () => {
expect(options[options.length - 1].optionId).toBe("reject_with_feedback");
});

it("includes an opt-in clear-and-continue option before reject", () => {
const options = buildExitPlanModePermissionOptions();
const clearIndex = options.findIndex(
(opt) => opt.optionId === "clearAndContinue",
);
expect(clearIndex).toBeGreaterThanOrEqual(0);
expect(options[clearIndex]).toMatchObject({
optionId: "clearAndContinue",
kind: "allow_once",
name: "Yes, clear history and continue from plan",
});
expect(options[clearIndex + 1]?.optionId).toBe("reject_with_feedback");
});

it.each([
{
previousMode: "default",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ const CONTINUE_LABELS: Record<string, string> = {
bypassPermissions: "Yes, continue bypassing all permissions",
};

/** Opt-in plan approval: clear planning context, then continue from the plan. */
export const CLEAR_AND_CONTINUE_OPTION_ID = "clearAndContinue";

export function buildExitPlanModePermissionOptions(
previousMode?: string,
): PermissionOption[] {
Expand Down Expand Up @@ -151,6 +154,16 @@ export function buildExitPlanModePermissionOptions(
}
}

options.push({
kind: "allow_once",
name: "Yes, clear history and continue from plan",
optionId: CLEAR_AND_CONTINUE_OPTION_ID,
_meta: {
description:
"Discard planning conversation tokens and start implementation with a fresh context seeded by this plan",
},
});

options.push({
kind: "reject_once",
name: "No, and tell the agent what to do differently",
Expand Down
103 changes: 103 additions & 0 deletions packages/core/src/sessions/planContinuation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import type { PermissionRequest } from "@posthog/shared";
import { describe, expect, it } from "vitest";
import {
buildApprovedPlanContinuationPrompt,
CLEAR_AND_CONTINUE_OPTION_ID,
extractPlanMarkdownFromPermission,
isClearAndContinueOption,
isPlanApprovalAcceptOption,
isPlanApprovalPermission,
resolveClearAndContinueExecutionMode,
shouldContinueFromApprovedPlan,
toApprovedExecutionMode,
} from "./planContinuation";

function makePermission(
overrides: Partial<PermissionRequest> & {
toolCall?: PermissionRequest["toolCall"];
} = {},
): PermissionRequest {
return {
taskRunId: "run-1",
receivedAt: 0,
options: [],
...overrides,
} as PermissionRequest;
}

describe("planContinuation", () => {
it("detects plan approval permissions", () => {
expect(
isPlanApprovalPermission(
makePermission({ toolCall: { kind: "switch_mode" } as never }),
),
).toBe(true);
expect(
isPlanApprovalPermission(
makePermission({ toolCall: { kind: "execute" } as never }),
),
).toBe(false);
});

it("recognizes approve option ids", () => {
expect(isPlanApprovalAcceptOption("auto")).toBe(true);
expect(isPlanApprovalAcceptOption("reject_with_feedback")).toBe(false);
expect(isClearAndContinueOption(CLEAR_AND_CONTINUE_OPTION_ID)).toBe(true);
expect(isClearAndContinueOption("auto")).toBe(false);
});

it("only continues for the explicit clear-and-continue option", () => {
const permission = makePermission({
toolCall: { kind: "switch_mode" } as never,
});
expect(shouldContinueFromApprovedPlan(permission, "auto")).toBe(false);
expect(
shouldContinueFromApprovedPlan(permission, CLEAR_AND_CONTINUE_OPTION_ID),
).toBe(true);
expect(
shouldContinueFromApprovedPlan(permission, "reject_with_feedback"),
).toBe(false);
});

it("extracts trimmed plan markdown from rawInput", () => {
const permission = makePermission({
toolCall: {
kind: "switch_mode",
rawInput: { plan: " ## Steps\n- one " },
} as never,
});
expect(extractPlanMarkdownFromPermission(permission)).toBe(
"## Steps\n- one",
);
expect(
extractPlanMarkdownFromPermission(
makePermission({ toolCall: { kind: "switch_mode" } as never }),
),
).toBeNull();
});

it("maps approve option to execution mode", () => {
expect(toApprovedExecutionMode("auto")).toBe("auto");
expect(toApprovedExecutionMode("acceptEdits")).toBe("acceptEdits");
});

it("resolves clear-and-continue execution mode from answers", () => {
expect(
resolveClearAndContinueExecutionMode({ executionMode: "acceptEdits" }),
).toBe("acceptEdits");
expect(resolveClearAndContinueExecutionMode({})).toBe("default");
expect(resolveClearAndContinueExecutionMode()).toBe("default");
});

it("builds a continuation prompt that embeds the plan", () => {
const blocks = buildApprovedPlanContinuationPrompt("## Fix\n- patch auth");
expect(blocks).toHaveLength(1);
expect(blocks[0]?.type).toBe("text");
const textBlock = blocks[0];
if (textBlock?.type !== "text") {
throw new Error("expected text block");
}
expect(textBlock.text).toContain("## Fix\n- patch auth");
expect(textBlock.text).toContain("execute this plan directly");
});
});
94 changes: 94 additions & 0 deletions packages/core/src/sessions/planContinuation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import type { ContentBlock } from "@agentclientprotocol/sdk";
import type { ExecutionMode, PermissionRequest } from "@posthog/shared";

/** Option ids offered when approving ExitPlanMode (see buildExitPlanModePermissionOptions). */
export const PLAN_APPROVAL_ACCEPT_OPTION_IDS = [
"auto",
"default",
"acceptEdits",
"bypassPermissions",
] as const;

export type PlanApprovalAcceptOptionId =
(typeof PLAN_APPROVAL_ACCEPT_OPTION_IDS)[number];

/**
* Opt-in plan-approval option: clear planning context, then continue from the
* approved plan. Kept in sync with `CLEAR_AND_CONTINUE_OPTION_ID` in the Claude
* permission-options module (agent cannot import core).
*/
export const CLEAR_AND_CONTINUE_OPTION_ID = "clearAndContinue";

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The option id is duplicated here and in the Claude permission-options module on purpose — @posthog/agent can't import @posthog/core (import-direction rule), so there's no shared home. The doc comment above flags they must stay in sync. Open to a better spot (e.g. @posthog/shared).

/** Answers key used by the plan UI to carry the ModeSelector choice. */
export const CLEAR_AND_CONTINUE_EXECUTION_MODE_KEY = "executionMode";

export function isPlanApprovalPermission(
permission: PermissionRequest,
): boolean {
return permission.toolCall?.kind === "switch_mode";
}

export function isPlanApprovalAcceptOption(
optionId: string,
): optionId is PlanApprovalAcceptOptionId {
return (PLAN_APPROVAL_ACCEPT_OPTION_IDS as readonly string[]).includes(
optionId,
);
}

export function isClearAndContinueOption(optionId: string): boolean {
return optionId === CLEAR_AND_CONTINUE_OPTION_ID;
}

/**
* Only the explicit "clear history and continue from plan" option triggers a
* fresh implementation session — normal approve keeps the planning context.
*/
export function shouldContinueFromApprovedPlan(
permission: PermissionRequest,
optionId: string,
): boolean {
return (
isPlanApprovalPermission(permission) && isClearAndContinueOption(optionId)
);
}

export function extractPlanMarkdownFromPermission(
permission: PermissionRequest,
): string | null {
const rawInput = permission.toolCall?.rawInput as
| { plan?: unknown }
| undefined;
const plan = rawInput?.plan;
if (typeof plan !== "string") return null;
const trimmed = plan.trim();
return trimmed.length > 0 ? trimmed : null;
}

export function toApprovedExecutionMode(
optionId: PlanApprovalAcceptOptionId,
): ExecutionMode {
return optionId;
}

export function resolveClearAndContinueExecutionMode(
answers?: Record<string, string>,
): ExecutionMode {
const mode = answers?.[CLEAR_AND_CONTINUE_EXECUTION_MODE_KEY];
if (mode && isPlanApprovalAcceptOption(mode)) {
return toApprovedExecutionMode(mode);
}
return "default";
}

export function buildApprovedPlanContinuationPrompt(
planMarkdown: string,
): ContentBlock[] {
const text = [
"The user approved the implementation plan below. Planning is complete — execute this plan directly.",
"Do not re-enter plan mode unless the user asks for a significant change in direction.",
"",
planMarkdown,
].join("\n");
return [{ type: "text", text }];
}
Loading