Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(agent): support /compact in codex sessions (#125586)

Shy Altera91d2a30665e
diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts
index 65d063146108..5211adfc7a3e 100644
--- a/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts
+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts
@@ -28,6 +28,7 @@ vi.mock("node:fs", async (importOriginal) => {
// Required-field invariants the native codex app-server enforces on each request.
const REQUIRED_FIELDS: Record<string, string[]> = {
+ "thread/compact/start": ["threadId"],
"thread/goal/clear": ["threadId"],
"thread/goal/get": ["threadId"],
"thread/goal/set": ["threadId"],
@@ -708,6 +709,194 @@ describe("CodexAppServerAgent", () => {
}
});
+ it.each([
+ {
+ label: "completes",
+ prompt: "/compact keep the test plan",
+ status: "completed",
+ stopReason: "end_turn",
+ boundaries: 1,
+ expectedStatus: undefined,
+ },
+ {
+ label: "fails",
+ prompt: "/compact",
+ status: "failed",
+ stopReason: "refusal",
+ boundaries: 0,
+ expectedStatus: { sessionId: "thr_1", status: "compacting_failed" },
+ },
+ {
+ label: "hits a fatal model error",
+ prompt: "/compact",
+ status: "error",
+ stopReason: "end_turn",
+ boundaries: 0,
+ expectedStatus: {
+ sessionId: "thr_1",
+ status: "compacting_failed",
+ error: "The model could not summarize this conversation.",
+ },
+ },
+ {
+ label: "is cancelled",
+ prompt: "/compact",
+ status: "cancel",
+ stopReason: "cancelled",
+ boundaries: 0,
+ expectedStatus: {
+ sessionId: "thr_1",
+ status: "compacting",
+ isComplete: true,
+ },
+ },
+ ])(
+ "/compact owns the native compaction turn when it $label",
+ async (testCase) => {
+ vi.useFakeTimers();
+ try {
+ const stub = makeStubRpc({
+ "thread/start": { thread: { id: "thr_1" } },
+ "thread/compact/start": {},
+ "turn/interrupt": {},
+ });
+ const { client, extNotifications } = makeFakeClient();
+ const agent = new CodexAppServerAgent(client, {
+ processOptions: { binaryPath: "/bundle/codex" },
+ rpcFactory: stub.factory,
+ });
+
+ await agent.newSession({
+ cwd: "/repo",
+ } as unknown as NewSessionRequest);
+ const done = agent.prompt({
+ sessionId: "thr_1",
+ prompt: [{ type: "text", text: testCase.prompt }],
+ } as unknown as PromptRequest);
+ await vi.advanceTimersByTimeAsync(0);
+ stub.emit("turn/started", {
+ threadId: "thr_1",
+ turn: { id: "turn_c" },
+ });
+ stub.emit("item/started", {
+ threadId: "thr_1",
+ item: { type: "contextCompaction", id: "c1" },
+ });
+ if (testCase.status === "error") {
+ stub.emit("error", {
+ threadId: "thr_1",
+ turnId: "turn_c",
+ willRetry: false,
+ error: {
+ message: JSON.stringify({
+ error: {
+ message: "The model could not summarize this conversation.",
+ type: "invalid_request_error",
+ },
+ }),
+ },
+ });
+ } else if (testCase.status === "cancel") {
+ await agent.cancel({ sessionId: "thr_1" });
+ expect(stub.requests).toContainEqual({
+ method: "turn/interrupt",
+ params: { threadId: "thr_1", turnId: "turn_c" },
+ });
+ } else {
+ if (testCase.status === "completed") {
+ stub.emit("item/completed", {
+ threadId: "thr_1",
+ item: { type: "contextCompaction", id: "c1" },
+ });
+ }
+ stub.emit("turn/completed", {
+ threadId: "thr_1",
+ turn: { id: "turn_c", status: testCase.status },
+ });
+ await vi.advanceTimersByTimeAsync(250);
+ }
+
+ await expect(done).resolves.toMatchObject({
+ stopReason: testCase.stopReason,
+ ...(testCase.status === "error"
+ ? { _meta: { compactionFailed: true } }
+ : {}),
+ });
+ expect(stub.requests).toContainEqual({
+ method: "thread/compact/start",
+ params: { threadId: "thr_1" },
+ });
+ expect(
+ stub.requests.some((request) => request.method === "turn/start"),
+ ).toBe(false);
+ expect(
+ extNotifications.filter(
+ (n) => n.method === "_posthog/compact_boundary",
+ ),
+ ).toHaveLength(testCase.boundaries);
+ if (testCase.expectedStatus) {
+ expect(extNotifications).toContainEqual({
+ method: "_posthog/status",
+ params: testCase.expectedStatus,
+ });
+ }
+ expect(
+ extNotifications.some(
+ (n) => n.method === "_posthog/background_turn_started",
+ ),
+ ).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ },
+ );
+
+ it.each([
+ { label: "steered into a running turn", steer: true },
+ { label: "sent during a background goal turn", steer: false },
+ ])(
+ "declines /compact $label without interrupting the turn",
+ async (testCase) => {
+ const stub = makeStubRpc({
+ "thread/start": { thread: { id: "thr_1" } },
+ "turn/start": { turn: { id: "turn_1", status: "inProgress" } },
+ });
+ const { client, sessionUpdates } = makeFakeClient();
+ const agent = new CodexAppServerAgent(client, {
+ processOptions: { binaryPath: "/bundle/codex" },
+ rpcFactory: stub.factory,
+ });
+ await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
+ if (testCase.steer) {
+ void agent.prompt({
+ sessionId: "thr_1",
+ prompt: [{ type: "text", text: "long task" }],
+ } as unknown as PromptRequest);
+ }
+ stub.emit("turn/started", { threadId: "thr_1", turn: { id: "turn_1" } });
+
+ const result = await agent.prompt({
+ sessionId: "thr_1",
+ prompt: [{ type: "text", text: "/compact" }],
+ ...(testCase.steer ? { _meta: { steer: true } } : {}),
+ } as unknown as PromptRequest);
+
+ expect(result).toMatchObject(
+ testCase.steer
+ ? { _meta: { steer: false, steerDeclineCause: "turn_not_steerable" } }
+ : { stopReason: "end_turn" },
+ );
+ expect(
+ stub.requests.some(
+ (request) => request.method === "thread/compact/start",
+ ),
+ ).toBe(false);
+ expect(JSON.stringify(sessionUpdates)).toContain(
+ "Run /compact again when this turn ends.",
+ );
+ },
+ );
+
it("handles a goal command wrapped in hidden cold-resume context", async () => {
const stub = makeStubRpc({
"thread/start": { thread: { id: "thr_1" } },
@@ -3971,6 +4160,7 @@ describe("CodexAppServerAgent", () => {
description: "Set or view the goal for a long-running task",
input: { hint: "[<objective>|clear|pause|resume]" },
},
+ { name: "compact", description: "Compact the conversation context" },
{ name: "deploy", description: "Deploy" },
]);
});
@@ -4252,7 +4442,7 @@ describe("CodexAppServerAgent", () => {
).toHaveLength(1);
});
- it("still emits compact_boundary when the turn dies mid-compaction (no stuck isCompacting)", async () => {
+ it("reports a failed compaction when the turn dies mid-compaction (no stuck isCompacting)", async () => {
const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });
const { client, extNotifications } = makeFakeClient();
const agent = new CodexAppServerAgent(client, {
@@ -4268,7 +4458,7 @@ describe("CodexAppServerAgent", () => {
sessionId: "t",
prompt: [{ type: "text", text: "go" }],
} as unknown as PromptRequest);
- // A fatal error ends the turn before item/completed; failure recovery still fires the boundary.
+ // A fatal error ends the turn before item/completed; failure recovery clears isCompacting.
stub.emit("item/started", {
item: { type: "contextCompaction", id: "c1" },
});
@@ -4277,10 +4467,13 @@ describe("CodexAppServerAgent", () => {
"The agent stopped before completing this request: boom",
);
+ expect(extNotifications).toContainEqual({
+ method: "_posthog/status",
+ params: { sessionId: "t", status: "compacting_failed", error: "boom" },
+ });
expect(
- extNotifications.find((n) => n.method === "_posthog/compact_boundary")
- ?.params,
- ).toMatchObject({ sessionId: "t" });
+ extNotifications.some((n) => n.method === "_posthog/compact_boundary"),
+ ).toBe(false);
});
it("loadSession resumes the thread and returns configOptions", async () => {
diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts
index 1d6206174e80..10b75e3c55c8 100644
--- a/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts
+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts
@@ -66,6 +66,7 @@ import {
import {
classifyAgentError,
isRetryableUpstreamErrorClassification,
+ rejectedRequestMessage,
sanitizeAgentErrorCause,
} from "../error-classification";
import { isLocalSkillCommandChunk } from "../local-skill";
@@ -236,13 +237,31 @@ const GOAL_COMMAND = {
input: { hint: "[<objective>|clear|pause|resume]" },
};
-function parseGoalCommand(prompt: PromptRequest["prompt"]): GoalCommand | null {
+const COMPACT_COMMAND = {
+ name: "compact",
+ description: "Compact the conversation context",
+};
+
+const COMPACT_BUSY_MESSAGE =
+ "\n\nCouldn't compact while the agent is working. Run /compact again when this turn ends.";
+
+function visiblePromptText(prompt: PromptRequest["prompt"]): string | null {
const visible = visiblePromptBlocks(prompt);
if (visible.some((block) => block.type !== "text")) return null;
- const text = visible
+ return visible
.map((block) => (block.type === "text" ? block.text : ""))
.join("\n")
.trim();
+}
+
+function isCompactCommand(prompt: PromptRequest["prompt"]): boolean {
+ const text = visiblePromptText(prompt);
+ return text !== null && /^\/compact(?:\s|$)/.test(text);
+}
+
+function parseGoalCommand(prompt: PromptRequest["prompt"]): GoalCommand | null {
+ const text = visiblePromptText(prompt);
+ if (text === null) return null;
const match = text.match(/^\/goal(?:\s+([\s\S]*))?$/);
if (!match) return null;
const argument = match[1]?.trim();
@@ -869,7 +888,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {
name: string;
description: string;
input?: { hint: string };
- }> = [GOAL_COMMAND];
+ }> = [GOAL_COMMAND, COMPACT_COMMAND];
try {
const res = await this.rpc.request<{
data?: Array<{ skills?: CodexSkill[] }>;
@@ -881,13 +900,14 @@ export class CodexAppServerAgent extends BaseAcpAgent {
(skill): skill is CodexSkill & { name: string } =>
!!skill.name &&
skill.name !== GOAL_COMMAND.name &&
+ skill.name !== COMPACT_COMMAND.name &&
skill.enabled !== false,
)
.map((skill) => ({
name: skill.name,
description: skill.description ?? "",
}));
- commands = [GOAL_COMMAND, ...skills];
+ commands = [GOAL_COMMAND, COMPACT_COMMAND, ...skills];
} catch (err) {
this.logger.warn("skills/list failed", { error: String(err) });
}
@@ -919,11 +939,43 @@ export class CodexAppServerAgent extends BaseAcpAgent {
? { stopReason: "end_turn", _meta: { steer: true } }
: { stopReason: "end_turn" };
}
+ const compactCommand = isCompactCommand(params.prompt);
+ if (
+ compactCommand &&
+ (isSteer || this.turns.isPending || this.nativeGoalTurnId)
+ ) {
+ this.broadcastAgentText(COMPACT_BUSY_MESSAGE);
+ return isSteer
+ ? steerDeclined("turn_not_steerable")
+ : { stopReason: "end_turn" };
+ }
this.cancelNextGoalTurn = false;
// Reopen the notification gate (a prior interrupt may have left session.cancelled set).
if (!isSteer) {
this.session.cancelled = false;
}
+ if (compactCommand) {
+ this.planHandoffCancel?.();
+ this.broadcastUserInput(visiblePromptBlocks(params.prompt));
+ try {
+ return await this.runOwnedTurn(
+ APP_SERVER_METHODS.THREAD_COMPACT_START,
+ { threadId: this.threadId },
+ );
+ } catch (error) {
+ if (
+ classifyGatewayLimitError(
+ error instanceof Error ? error.message : String(error),
+ ) !== null
+ ) {
+ throw error;
+ }
+ this.logger.warn("Codex manual compaction failed", {
+ error: String(error),
+ });
+ return { stopReason: "end_turn", _meta: { compactionFailed: true } };
+ }
+ }
// A new prompt while the plan handoff awaits approval implicitly declines it:
// settle the race so the previous prompt() returns and this one owns the turn.
this.planHandoffCancel?.();
@@ -1225,7 +1277,17 @@ export class CodexAppServerAgent extends BaseAcpAgent {
}
/** Start one codex turn and await its completion. */
- private async runTurn(input: CodexUserInput[]): Promise<PromptResponse> {
+ private runTurn(input: CodexUserInput[]): Promise<PromptResponse> {
+ return this.runOwnedTurn(
+ APP_SERVER_METHODS.TURN_START,
+ this.turnStartParams(input),
+ );
+ }
+
+ private async runOwnedTurn(
+ method: string,
+ params: Record<string, unknown>,
+ ): Promise<PromptResponse> {
this.lastAgentMessage = "";
this.lastTurnError = undefined;
this.resetUsage();
@@ -1236,10 +1298,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {
this.deferredTurnComplete = undefined;
const { completion, turn } = this.turns.begin();
try {
- await this.rpc.request(
- APP_SERVER_METHODS.TURN_START,
- this.turnStartParams(input),
- );
+ await this.rpc.request(method, params);
return await completion;
} finally {
this.turns.finishPrompt(turn);
@@ -1755,6 +1814,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {
const completedNativeGoalTurn = turn?.id === this.nativeGoalTurnId;
if (completedNativeGoalTurn) {
this.nativeGoalTurnId = undefined;
+ this.endCompaction(mapTurnStopReason(turn?.status));
void this.client
.extNotification(POSTHOG_NOTIFICATIONS.BACKGROUND_TURN_COMPLETE, {
sessionId: this.sessionId,
@@ -2125,6 +2185,32 @@ export class CodexAppServerAgent extends BaseAcpAgent {
.catch(() => undefined);
}
+ private endCompaction(reason: StopReason, error?: string): void {
+ if (!this.compactionActive) return;
+ this.compactionActive = false;
+ if (reason === "end_turn") {
+ this.emitCompactionBoundary();
+ return;
+ }
+ if (!this.sessionId) return;
+ void this.client
+ .extNotification(
+ POSTHOG_NOTIFICATIONS.STATUS,
+ reason === "cancelled"
+ ? {
+ sessionId: this.sessionId,
+ status: "compacting",
+ isComplete: true,
+ }
+ : {
+ sessionId: this.sessionId,
+ status: "compacting_failed",
+ ...(error ? { error } : {}),
+ },
+ )
+ .catch(() => undefined);
+ }
+
/** Emit `_posthog/usage_update` so the host's token/cost UI fills. */
private emitUsageExtNotification(params: unknown): void {
if (!this.sessionId) return;
@@ -2146,10 +2232,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {
if (!pending) return;
// If the turn dies mid-compaction the boundary never fires, leaving isCompacting stuck
// true (silently queuing later messages). Recover here.
- if (this.compactionActive) {
- this.compactionActive = false;
- this.emitCompactionBoundary();
- }
+ this.endCompaction(reason);
const message = this.lastAgentMessage;
// Per-turn usage is codex's own `tokenUsage.last` (not a reconstructed delta).
const usage = this.usage.perTurnUsage();
@@ -2200,10 +2283,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {
this.turns.markInterrupted();
const pending = this.turns.claim();
if (!pending) return;
- if (this.compactionActive) {
- this.compactionActive = false;
- this.emitCompactionBoundary();
- }
+ this.endCompaction("refusal", compactionFailureDetail(this.lastTurnError));
const usage = this.usage.perTurnUsage();
pending.reject(error);
if (emitTurnComplete) {
@@ -2268,10 +2348,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {
const pending = this.turns.claim();
if (!pending) return;
this.broadcastAgentText(message);
- if (this.compactionActive) {
- this.compactionActive = false;
- this.emitCompactionBoundary();
- }
+ this.endCompaction("refusal");
const usage = this.usage.perTurnUsage();
void this.emitTurnCompleteSignal("refusal", usage);
void this.emitUsageBreakdown(this.usage.contextTokens());
@@ -2607,6 +2684,14 @@ const CODEX_BASELINE_TOKENS = 12000;
const IMPLEMENT_PLAN_MESSAGE = "Implement the plan.";
/** codex `TurnStatus` → ACP `StopReason`: interrupted → cancel, failed → refusal, else end. */
+function compactionFailureDetail(
+ cause: { message: string } | undefined,
+): string | undefined {
+ const raw = cause?.message.trim();
+ if (!raw) return undefined;
+ return (rejectedRequestMessage(raw) ?? raw).slice(0, MAX_FATAL_CAUSE_LENGTH);
+}
+
function mapTurnStopReason(status: string | undefined): StopReason {
if (status === "interrupted") return "cancelled";
if (status === "failed") return "refusal";
diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/protocol.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/protocol.ts
index 01febc90e9c0..3802c06b6640 100644
--- a/packages/agent/packages/agent/src/adapters/codex-app-server/protocol.ts
+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/protocol.ts
@@ -29,6 +29,7 @@ export const APP_SERVER_METHODS = {
THREAD_GOAL_GET: "thread/goal/get",
THREAD_GOAL_CLEAR: "thread/goal/clear",
THREAD_LIST: "thread/list",
+ THREAD_COMPACT_START: "thread/compact/start",
} as const;
export const APP_SERVER_NOTIFICATIONS = {
diff --git a/packages/agent/packages/agent/src/adapters/error-classification.ts b/packages/agent/packages/agent/src/adapters/error-classification.ts
index 3dbadc8b0e0f..1c07b0bedf1d 100644
--- a/packages/agent/packages/agent/src/adapters/error-classification.ts
+++ b/packages/agent/packages/agent/src/adapters/error-classification.ts
@@ -142,7 +142,7 @@ export function sanitizeAgentErrorCause(
return text.slice(0, 400);
}
-function rejectedRequestMessage(body: string): string | undefined {
+export function rejectedRequestMessage(body: string): string | undefined {
try {
const message = JSON.parse(body)?.error?.message;
return typeof message === "string" ? message : undefined;
diff --git a/packages/agent/packages/agent/src/server/agent-server.test.ts b/packages/agent/packages/agent/src/server/agent-server.test.ts
index 1af9176604d6..26660cace27a 100644
--- a/packages/agent/packages/agent/src/server/agent-server.test.ts
+++ b/packages/agent/packages/agent/src/server/agent-server.test.ts
@@ -4233,71 +4233,86 @@ describe("AgentServer HTTP Mode", () => {
expect(body.error).toBe("No active session for this run");
}, 20000);
- it("continues a cloud task after a manual compact command", async () => {
- const s = createServer();
- await s.start();
- const broadcastEvent = vi.fn();
- let serverInternals!: {
- session: { clientConnection: { prompt: typeof prompt } };
- broadcastEvent: typeof broadcastEvent;
- handleAcpTransportMessage(message: unknown): void;
- };
- const prompt = vi.fn(async (_params: { prompt: ContentBlock[] }) => {
- serverInternals.handleAcpTransportMessage({
- jsonrpc: "2.0",
- method: POSTHOG_NOTIFICATIONS.TURN_COMPLETE,
- params: { sessionId: "session-1", stopReason: "end_turn" },
+ it.each([
+ { label: "continues a cloud task after", meta: undefined, prompts: 2 },
+ {
+ label: "does not continue a cloud task after a failed",
+ meta: { compactionFailed: true },
+ prompts: 1,
+ },
+ ])(
+ "$label manual compact command",
+ async ({ meta, prompts }) => {
+ const s = createServer();
+ await s.start();
+ const broadcastEvent = vi.fn();
+ let serverInternals!: {
+ session: { clientConnection: { prompt: typeof prompt } };
+ broadcastEvent: typeof broadcastEvent;
+ handleAcpTransportMessage(message: unknown): void;
+ };
+ const prompt = vi.fn(async (_params: { prompt: ContentBlock[] }) => {
+ serverInternals.handleAcpTransportMessage({
+ jsonrpc: "2.0",
+ method: POSTHOG_NOTIFICATIONS.TURN_COMPLETE,
+ params: { sessionId: "session-1", stopReason: "end_turn" },
+ });
+ return prompt.mock.calls.length === 1 && meta
+ ? { stopReason: "end_turn", _meta: meta }
+ : { stopReason: "end_turn" };
});
- return { stopReason: "end_turn" };
- });
- serverInternals = s as unknown as typeof serverInternals;
- serverInternals.session.clientConnection.prompt = prompt;
- serverInternals.broadcastEvent = broadcastEvent;
+ serverInternals = s as unknown as typeof serverInternals;
+ serverInternals.session.clientConnection.prompt = prompt;
+ serverInternals.broadcastEvent = broadcastEvent;
- const token = createToken();
- const response = await fetch(`http://localhost:${port}/command`, {
- method: "POST",
- headers: {
- Authorization: `Bearer ${token}`,
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- jsonrpc: "2.0",
- id: "compact-and-continue",
- method: "user_message",
- params: {
- content:
- "/compact Continue with the task using the question tool and plan.",
+ const token = createToken();
+ const response = await fetch(`http://localhost:${port}/command`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": "application/json",
},
- }),
- });
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id: "compact-and-continue",
+ method: "user_message",
+ params: {
+ content:
+ "/compact Continue with the task using the question tool and plan.",
+ },
+ }),
+ });
- expect(response.status).toBe(200);
- const body = (await response.json()) as {
- result?: { stopReason?: string };
- };
- expect(body.result?.stopReason).toBe("end_turn");
- expect(prompt).toHaveBeenCalledTimes(2);
- expect(prompt.mock.calls[0]?.[0].prompt).toEqual([
- {
- type: "text",
- text: "/compact Continue with the task using the question tool and plan.",
- },
- ]);
- expect(prompt.mock.calls[1]?.[0].prompt).toEqual([
- {
- type: "text",
- text: expect.stringContaining("Continue working on the task"),
- _meta: { ui: { hidden: true } },
- },
- ]);
- const turnCompleteEvents = broadcastEvent.mock.calls.filter(
- ([event]) =>
- (event as { notification?: { method?: string } }).notification
- ?.method === POSTHOG_NOTIFICATIONS.TURN_COMPLETE,
- );
- expect(turnCompleteEvents).toHaveLength(1);
- }, 20000);
+ expect(response.status).toBe(200);
+ const body = (await response.json()) as {
+ result?: { stopReason?: string };
+ };
+ expect(body.result?.stopReason).toBe("end_turn");
+ expect(prompt).toHaveBeenCalledTimes(prompts);
+ expect(prompt.mock.calls[0]?.[0].prompt).toEqual([
+ {
+ type: "text",
+ text: "/compact Continue with the task using the question tool and plan.",
+ },
+ ]);
+ if (prompts === 2) {
+ expect(prompt.mock.calls[1]?.[0].prompt).toEqual([
+ {
+ type: "text",
+ text: expect.stringContaining("Continue working on the task"),
+ _meta: { ui: { hidden: true } },
+ },
+ ]);
+ }
+ const turnCompleteEvents = broadcastEvent.mock.calls.filter(
+ ([event]) =>
+ (event as { notification?: { method?: string } }).notification
+ ?.method === POSTHOG_NOTIFICATIONS.TURN_COMPLETE,
+ );
+ expect(turnCompleteEvents).toHaveLength(1);
+ },
+ 20000,
+ );
it("honors cancellation while preparing a human follow-up", async () => {
const s = createServer();
diff --git a/packages/agent/packages/agent/src/server/agent-server.ts b/packages/agent/packages/agent/src/server/agent-server.ts
index 645e454e262e..5ba02b243b60 100644
--- a/packages/agent/packages/agent/src/server/agent-server.ts
+++ b/packages/agent/packages/agent/src/server/agent-server.ts
@@ -409,6 +409,13 @@ function hiddenPromptBlock(block: ContentBlock): ContentBlock {
} as ContentBlock;
}
+function compactionFailed(result: PromptResponse): boolean {
+ return (
+ (result._meta as { compactionFailed?: unknown } | undefined)
+ ?.compactionFailed === true
+ );
+}
+
function isManualCompactPrompt(prompt: ContentBlock[]): boolean {
return /^\/compact(?:\s|$)/.test(promptBlocksToText(prompt).trimStart());
}
@@ -1658,7 +1665,11 @@ export class AgentServer {
result = await runTurn();
}
- if (result.stopReason === "end_turn" && manualCompactPrompt) {
+ if (
+ result.stopReason === "end_turn" &&
+ manualCompactPrompt &&
+ !compactionFailed(result)
+ ) {
commitDelivery();
if (messageId) {
this.pendingCompactContinuationMessageIds.add(messageId);