repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(goal): defer retries and abort on ctrl-c

db68a6544e538bad04dc74726417399f7da34165

Review <review@example.invalid> ·

unsigned

Browse filesCompare with HEAD

Changed files (4)

CHANGELOG.md

Modified
13 13 `×N` so one notice shows distinct secrets, not every occurrence
14 14 - Classify goal extension API errors into kinds (context_overflow, transport,
15 15 server, rate_limit, stream, parse, auth, quota, bad_request, unknown) with
16 - human-readable short/detail/hint and retryability, and retry retryable errors
17 - indefinitely with exponential backoff capped at 60s instead of pausing after a
18 - retry cap
19 -- Let Pi core handle `context_length_exceeded` auto-compaction/retry; goal records
20 - context-overflow event/UI state without starting a duplicate `ctx.compact` flow
21 -- Defer goal-owned retries while Pi core auto-retry attempts remain, then pause
22 - after Pi retry exhaustion instead of starting another continuation loop
16 + human-readable short/detail/hint and retryability
17 +- Let Pi core own retry/compaction for goal errors: defer while Pi retry is
18 + pending, pause after retry exhaustion, and pause immediately when Pi retry is
19 + disabled or unavailable
20 +- Avoid mutating goal state for context-overflow errors while Pi core retry is
21 + pending
22 +- Make Ctrl+C cancel an active goal and abort the current Pi run like Escape
23 23 - Prune goal transcript rows and persisted assistant failure messages from active
24 24 goal LLM context so reload/resume cannot resurrect failed retry payloads
25 25 - Pause the goal loop on terminal errors (auth 401/403, quota,

extensions/goal/__tests__/integration-full.test.ts

Modified
585 - it("retries WebSocket 1006 transport errors instead of pausing", async () => {
585 + it("pauses on transport errors when Pi retry is disabled", async () => {
586 586 t = await createGoalSession();
587 587 mkdirSync(join(t.cwd, ".pi"), { recursive: true });
588 588 writeFileSync(
592 592 installSaysErrorStream(t, "WebSocket closed 1006 Connection ended");
594 594 await t.session.prompt("/goal survive websocket drop");
595 - await waitFor(() => latestGoal()?.lastReason?.startsWith("retry 1"));
595 + await waitFor(() => latestGoal()?.status === "paused");
597 597 expect(latestGoal()).toMatchObject({
598 598 objective: "survive websocket drop",
599 - status: "active",
599 + status: "paused",
600 600 lastVerdict: "error",
601 + lastReason:
602 + "transport error: network or connection failure. reconnecting.",
602 - expect(latestGoal()?.lastReason).toContain("transport error");
605 606 it("does not dispatch goal retry while Pi auto-retry delay is pending", async () => {

extensions/goal/__tests__/unit.test.ts

Modified
1480 1480 describe("cancelGoalRun", () => {
1481 + it("aborts and pauses active goal on ctrl-c terminal input", async () => {
1482 + const handlers = new Map<
1483 + string,
1484 + Array<(event: unknown, ctx: unknown) => unknown>
1485 + >();
1486 + let terminalInput: ((data: string) => unknown) | undefined;
1487 + let abortCalls = 0;
1488 + let activeTools: string[] = ["update_goal"];
1489 + const entries: Array<{
1490 + type: string;
1491 + customType: string;
1492 + data: unknown;
1493 + }> = [
1495 + type: "custom",
1496 + customType: GOAL_STATE_CUSTOM_TYPE,
1497 + data: goal({ sessionId: "session-1" }),
1498 + },
1499 + ];
1500 + const pi = {
1501 + events: { emit: () => {} },
1502 + on: (
1503 + event: string,
1504 + handler: (event: unknown, ctx: unknown) => unknown,
1505 + ) => {
1506 + handlers.set(event, [...(handlers.get(event) ?? []), handler]);
1507 + },
1508 + registerMessageRenderer: () => {},
1509 + registerShortcut: () => {},
1510 + registerTool: () => {},
1511 + registerCommand: () => {},
1512 + appendEntry: (customType: string, data: unknown) => {
1513 + entries.push({ type: "custom", customType, data });
1514 + },
1515 + sendMessage: () => {},
1516 + sendUserMessage: () => {},
1517 + getActiveTools: () => activeTools,
1518 + setActiveTools: (names: string[]) => {
1519 + activeTools = names;
1520 + },
1521 + } as never;
1522 + const ctx = {
1523 + hasUI: true,
1524 + cwd: process.cwd(),
1525 + isIdle: () => false,
1526 + abort: () => {
1527 + abortCalls++;
1528 + },
1529 + ui: {
1530 + notify: () => {},
1531 + setStatus: () => {},
1532 + setWidget: () => {},
1533 + setWorkingMessage: () => {},
1534 + setWorkingIndicator: () => {},
1535 + onTerminalInput: (handler: (data: string) => unknown) => {
1536 + terminalInput = handler;
1537 + return () => {};
1538 + },
1539 + },
1540 + sessionManager: {
1541 + getSessionId: () => "session-1",
1542 + getEntries: () => entries,
1543 + appendCustomMessageEntry: () => {},
1544 + },
1545 + } as never;
1547 + goalExtension(pi);
1548 + await handlers.get("session_start")?.[0]?.({}, ctx);
1549 + terminalInput?.("\u0003");
1551 + expect(abortCalls).toBe(1);
1552 + expect(replay(entries.map((entry) => entry.data))).toMatchObject({
1553 + status: "paused",
1554 + lastReason: "cancelled by user",
1555 + });
1556 + expect(activeTools).toEqual([]);
1557 + });
1481 1559 it("returns undefined and appends tombstone", () => {
1482 1560 const entries: unknown[] = [];
1483 1561 const pi = {
1599 1677 describe("agent_end context overflow recovery", () => {
1600 - it("leaves compaction to Pi core instead of calling ctx.compact", async () => {
1678 + it("defers context overflow to Pi core instead of mutating goal state", async () => {
1601 1679 const handlers = new Map<
1602 1680 string,
1603 1681 Array<(event: unknown, ctx: unknown) => unknown>
1676 1754 await handlers.get("agent_end")?.[0]?.({ messages: [] }, ctx);
1678 1756 expect(compactCalls).toBe(0);
1679 - expect(replay(entries.map((entry) => entry.data))?.lastReason).toBe(
1680 - "retry 1: context overflow",
1681 - );
1757 + expect(
1758 + replay(entries.map((entry) => entry.data))?.lastReason,
1759 + ).toBeUndefined();

extensions/goal/index.ts

Modified
192 192 const JUDGE_ATTEMPTS = 2;
193 193 const JUDGE_PARSE_FAILURE_LIMIT = 3;
194 194 const BLOCKED_STREAK_LIMIT = 3;
195 -const ERROR_BACKOFF_BASE_MS = 2000;
196 -const ERROR_BACKOFF_MAX_MS = 60_000;
197 195 const ANSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]/g;
198 196 const CONTROL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g;
199 197 const GOAL_WIDGET_LABEL_WIDTH = 11;
917 915 return classifyError(message).retryable;
920 -function errorBackoffMs(retries: number): number {
921 - return Math.min(
922 - ERROR_BACKOFF_MAX_MS,
923 - ERROR_BACKOFF_BASE_MS * 2 ** Math.min(retries, 10),
924 - );
927 -function errorRetryLabel(retries: number, classified: ClassifiedError): string {
928 - return `retry ${retries}: ${classified.short}`;
931 918 function errorPauseLabel(classified: ClassifiedError): string {
932 919 return `${classified.short}: ${classified.detail}.${classified.hint ? ` ${classified.hint}.` : ""}`;
946 933 ).getRetrySettings();
947 934 if (!retry.enabled || retry.maxRetries <= 0) return "none";
948 935 const classified = classifyError(evidence.errorMessage);
949 - if (!classified.retryable || classified.kind === "context_overflow")
950 - return "none";
936 + if (!classified.retryable) return "none";
951 937 return deferredRetries < retry.maxRetries ? "pending" : "exhausted";
2635 2621 removeTerminalInput?.();
2636 2622 removeTerminalInput = ctx.hasUI
2637 2623 ? ctx.ui.onTerminalInput((data) => {
2638 - if (matchesKey(data, "escape")) {
2624 + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
2625 + const abortActiveRun =
2626 + state?.status === "active" &&
2627 + ownsGoal(ctx, state) &&
2628 + !ctx.isIdle();
2639 2629 state = cancelGoalRun(pi, ctx, state);
2640 2630 continuation.queued = false;
2641 2631 continuation.scheduled = false;
2632 + if (abortActiveRun) ctx.abort();
2643 2634 return undefined;
2812 2803 if (evidence?.stopReason === "error") {
2813 2804 const errorMessage = evidence.errorMessage || "assistant error";
2814 2805 const classified = classifyError(errorMessage);
2815 - const retries = (state.errorRetries ?? 0) + 1;
2817 - if (classified.kind === "context_overflow") {
2818 - state = updateGoal(pi, state, {
2819 - errorRetries: retries,
2820 - lastVerdict: "error",
2821 - lastReason: errorRetryLabel(retries, classified),
2822 - timeUsedSeconds: currentElapsedSeconds(state),
2823 - });
2824 - appendGoalEvent(pi, ctx, "context-overflow", state, {
2825 - reason: errorMessage,
2826 - retries,
2827 - });
2828 - renderGoalUi(ctx, state);
2829 - syncUpdateGoalTool();
2830 - if (ctx.hasUI)
2831 - ctx.ui.notify(
2832 - `Goal: ${classified.short} — waiting for Pi compaction retry`,
2833 - "info",
2834 - );
2835 - return;
2838 - if (piRetry === "exhausted") {
2839 - state = updateGoal(pi, state, {
2840 - status: "paused",
2841 - lastVerdict: "error",
2842 - lastReason: `retry exhausted: ${classified.short}`,
2843 - timeUsedSeconds: currentElapsedSeconds(state),
2844 - });
2845 - appendGoalEvent(pi, ctx, "paused", state, {
2846 - reason: state.lastReason,
2847 - raw: errorMessage,
2848 - kind: classified.kind,
2849 - });
2850 - renderGoalUi(ctx, state);
2851 - syncUpdateGoalTool();
2852 - if (ctx.hasUI)
2853 - ctx.ui.notify(`Goal paused — ${state.lastReason}`, "warning");
2854 - return;
2857 - if (classified.retryable) {
2858 - state = updateGoal(pi, state, {
2859 - errorRetries: retries,
2860 - lastVerdict: "error",
2861 - lastReason: errorRetryLabel(retries, classified),
2862 - timeUsedSeconds: currentElapsedSeconds(state),
2863 - });
2864 - appendGoalEvent(pi, ctx, "error-retry", state, {
2865 - reason: errorMessage,
2866 - kind: classified.kind,
2867 - retries,
2868 - });
2869 - renderGoalUi(ctx, state);
2870 - syncUpdateGoalTool();
2871 - if (ctx.hasUI)
2872 - ctx.ui.notify(
2873 - `Goal ${classified.short} — ${errorRetryLabel(retries, classified)}`,
2874 - "warning",
2875 - );
2876 - const retryState = state;
2877 - setTimeout(
2878 - () => scheduleContinuation(pi, ctx, retryState, continuation),
2879 - errorBackoffMs(retries),
2880 - );
2881 - return;
2884 2807 state = updateGoal(pi, state, {
2885 2808 status: "paused",
2886 2809 lastVerdict: "error",
2887 - lastReason: errorPauseLabel(classified),
2810 + lastReason:
2811 + piRetry === "exhausted"
2812 + ? `retry exhausted: ${classified.short}`
2813 + : errorPauseLabel(classified),
2888 2814 timeUsedSeconds: currentElapsedSeconds(state),
2890 2816 appendGoalEvent(pi, ctx, "paused", state, {