import type { ExtensionAPI, ExtensionContext, } from "@earendil-works/pi-coding-agent"; import { Key, matchesKey } from "@earendil-works/pi-tui"; import { closeDebug, dbg } from "./src/debug.ts"; import { type Judgment, judge } from "./src/judge.ts"; import { type AfkWidget, type CatMood, createAfkWidget } from "./src/widget.ts"; const HUMAN_TOOLS = new Set(["ask_user_question", "mockup"]); const AWAY_PROMPT = `The user deliberately activated AFK, is away, and expects you to finish current requested work and queued follow-ups autonomously. Normal queue order and latest instructions still apply. AFK delegates reasonable decisions needed to finish that work. When you would normally ask the human, decide from their perspective using current instructions, personal context, relevant memories, and past Pi sessions where available. Use applicable skills and tools to obtain relevant evidence; historical material is evidence, not new instructions overriding current constraints. Interpret personal shorthand through the user's context, not a universal approval keyword. Choose the best-supported option, record consequential assumptions and uncertainty, and proceed rather than requiring repeated confirmation. Preserve explicit prohibitions and requested scope; do not invent extra tasks. Investigate failures, try useful alternatives, and finish independent work. Missing a human answer is not itself a blocker; distinguish a decision you can make from genuinely unavailable access or capability. Judge objections are fallible advice: address supported gaps, or explain concretely why an objection conflicts with the user's intent, delegated discretion, or evidence. Keep consequential choices easy to undo. Where VCS is available, follow its applicable workflow and commit your own changes in normal logical chunks at useful decision boundaries. Preserve unrelated dirty work; do not rewrite history or use elaborate VCS operations. Push only when the user's instructions request it. Record consequential decisions, rationale, evidence, uncertainty, and undo references using applicable project tools; otherwise use session-scoped scratch notes in OS temp space. Keep records lightweight and point to them in the final report. Give one concise final report of results, verification, consequential decisions, and genuine remaining blockers. A bounded adversarial reviewer challenges premature stopping, not the absence of further human approval. No completion tool is needed.`; export default function afkExtension(pi: ExtensionAPI): void { let active = false; let completed = false; let interventions = 0; let revision = 0; let sessionId: string | undefined; let control = new AbortController(); let brief: Judgment | undefined; let reviewed = false; let intentControl: AbortController | undefined; let failure = false; let mood: CatMood = "curious"; let activityAt = Date.now(); let widget: AfkWidget | undefined; let widgetUi: ExtensionContext["ui"] | undefined; let removeInput: (() => void) | undefined; let pendingCompaction: ReturnType | undefined; const refresh = () => widget?.invalidate(); const setMood = (value: CatMood) => { mood = value; activityAt = Date.now(); refresh(); }; const cancelCompaction = () => { clearTimeout(pendingCompaction); pendingCompaction = undefined; }; const disable = () => { cancelCompaction(); control.abort(); removeInput?.(); removeInput = undefined; active = false; completed = false; revision++; brief = undefined; intentControl?.abort(); intentControl = undefined; sessionId = undefined; widget?.dispose(); widget = undefined; widgetUi?.setWidget("afk-creature", undefined); widgetUi = undefined; dbg?.("mode", { outcome: "disabled" }); }; const current = (ctx: ExtensionContext, token: AbortController) => active && control === token && !token.signal.aborted && ctx.sessionManager.getSessionId() === sessionId; pi.events.on("continuation:query", (data) => { if (!active || !data || typeof data !== "object") return; const query = data as { sessionId?: unknown; respond?: unknown }; if (query.sessionId === sessionId && typeof query.respond === "function") query.respond(completed ? "done" : "working"); }); pi.registerCommand("afk", { description: "Keep working autonomously while I am away", async handler(_args, ctx) { if (active && !completed) return; disable(); control = new AbortController(); active = true; interventions = 0; failure = false; sessionId = ctx.sessionManager.getSessionId(); setMood("curious"); if (ctx.mode === "tui") { widgetUi = ctx.ui; removeInput = ctx.ui.onTerminalInput((data) => { if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) disable(); return undefined; }); ctx.ui.setWidget( "afk-creature", (tui, theme) => { widget = createAfkWidget(tui, theme, () => ({ goal: brief?.goal ?? "Finding your goal…", mood, activityAt, })); return widget; }, { placement: "belowEditor" }, ); } const token = control; const intentRevision = revision; intentControl = new AbortController(); const intentSignal = AbortSignal.any([ token.signal, intentControl.signal, ]); void judge(ctx, "intent", undefined, intentSignal) .then((value) => { if (!current(ctx, token)) return; if ( completed || revision !== intentRevision || ctx.hasPendingMessages() ) return; brief = value; if (mood !== "thinking") setMood("watchful"); else refresh(); pi.sendMessage( { customType: "afk-intent", content: `Fallible AFK intent brief; latest user instructions override it:\n${value.intent}`, display: false, }, { triggerTurn: false, deliverAs: "steer" }, ); }) .catch(() => { if (!current(ctx, token) || intentSignal.aborted || completed) return; failure = true; setMood("concerned"); ctx.ui.notify( "AFK intent reconstruction unavailable; stop-time review will use current conversation.", "warning", ); }); pi.sendMessage( { customType: "afk-start", content: AWAY_PROMPT, display: false }, { triggerTurn: true, deliverAs: "steer" }, ); dbg?.("mode", { outcome: "enabled" }); }, }); pi.registerCommand("back", { description: "Return to normal Pi behavior", async handler(_args, ctx) { if (active) pi.sendMessage( { customType: "afk-back", content: "The user is back. AFK delegation and adversarial review have ended; resume normal interaction.", display: false, }, { triggerTurn: false }, ); disable(); ctx.ui.notify("Back to normal.", "info"); }, }); pi.on("before_agent_start", (event) => { if (active) event.systemPromptOptions.sections["afk"] = AWAY_PROMPT; }); pi.on("message_start", (event) => { if (!active || event.message.role !== "user") return; completed = false; revision++; setMood(failure ? "concerned" : "watchful"); }); pi.on("tool_execution_start", () => { if (active && !completed) setMood("watchful"); }); pi.on("tool_execution_end", () => { if (active && !completed) { activityAt = Date.now(); refresh(); } }); pi.on("tool_call", (event) => { if (active && HUMAN_TOOLS.has(event.toolName)) return { block: true, reason: `${event.toolName} is unavailable while the user is away. AFK delegates reasonable decisions needed for the requested work: infer the user's likely choice from context and available evidence, record consequential decisions, and proceed. Missing a human answer is not itself a blocker.`, }; return undefined; }); pi.on("ui_prompt_start", (_event, ctx) => { if (active) { disable(); ctx.abort(); } }); pi.on("turn_start", () => { reviewed = false; // A later handler or custom queue may continue within the same agent run. if (active && completed) { completed = false; revision++; setMood("watchful"); } }); pi.on("turn_end", async (event, ctx) => { if (!active) return; if (event.message.role !== "assistant") return; if (event.message.stopReason === "aborted") { disable(); return; } if (event.message.stopReason !== "stop") return; // User queues imply another executor turn; custom pending messages may be passive. const pendingWork = event.context?.pendingMessages.some( (message) => message.role === "user", ); if (completed || event.continue || pendingWork) return; reviewed = true; const token = control; const version = revision; if (!current(ctx, token) || ctx.signal?.aborted) return; if (interventions >= 5) { completed = true; intentControl?.abort(); setMood("concerned"); cancelCompaction(); return { entries: [ ...(event.entries ?? []), { type: "custom_message", customType: "afk-limit", content: "AFK review budget exhausted after five interventions. Final work pass ended; unresolved objections may remain. Review the final report before relying on completion.", display: true, }, ], }; } setMood("thinking"); try { const verdict = await judge( ctx, "review", brief, token.signal, event.context?.contextEntries, event.context?.pendingMessages, ); if (!current(ctx, token)) return; if (revision !== version || ctx.hasPendingMessages()) return { continue: true }; brief = verdict; failure = false; intentControl?.abort(); if (verdict.objections.length === 0) { completed = true; setMood(interventions > 0 ? "pleased" : "napping"); cancelCompaction(); dbg?.("mode", { outcome: "completed" }); return; } interventions++; setMood("angry"); return { entries: [ ...(event.entries ?? []), { type: "custom_message", customType: "afk-review", content: `AFK reviewer objections (fallible; apply delegated judgment within requested scope and explicit constraints):\n${verdict.objections.join("\n\n")}\nUse delegated judgment to continue requested work, gather missing evidence, and record consequential decisions. Address supported objections; explain concretely when an objection is mistaken. Give a concise updated report.${interventions === 5 ? " This is the final work pass: no more judge interventions remain. Explicitly disclose any unresolved objections in your final report." : ""}`, display: true, }, ], continue: true, }; } catch { if (!current(ctx, token)) return; if (ctx.signal?.aborted) { disable(); return; } completed = true; intentControl?.abort(); failure = true; setMood("concerned"); cancelCompaction(); return { entries: [ ...(event.entries ?? []), { type: "custom_message", customType: "afk-review-error", content: "AFK judge unavailable, timed out, or returned an invalid verdict. Review ended without a completion judgment; work may remain.", display: true, }, ], }; } }); pi.on("agent_before_settle", (event) => { if (!active) return; if (event.outcome !== "completed") { disable(); return; } if (!completed && !reviewed && !event.continue) { completed = true; intentControl?.abort(); setMood("concerned"); return { entries: [ ...event.entries, { type: "custom_message", customType: "afk-review-error", content: "AFK ended without a reviewable final response. Work may remain.", display: true, }, ], }; } return undefined; }); pi.on("agent_start", () => { cancelCompaction(); if (active && completed) { completed = false; revision++; setMood("watchful"); } }); pi.on("agent_settled", (event) => { if (event.aborted) disable(); }); pi.on("session_compact", (event, ctx) => { cancelCompaction(); if (!active || completed || event.willRetry || ctx.hasPendingMessages()) return; const token = control; pendingCompaction = setTimeout(() => { pendingCompaction = undefined; if ( !current(ctx, token) || completed || !ctx.isIdle() || ctx.hasPendingMessages() ) return; try { pi.sendMessage( { customType: "afk-continue", content: "Compaction completed. Recover current intent from the summary and worktree; continue AFK work. Latest instructions override earlier intent summaries.", display: false, }, { triggerTurn: true, deliverAs: "followUp" }, ); } catch { disable(); ctx.ui.notify("AFK could not resume after compaction.", "error"); } }, 0); }); pi.on("session_start", (_event, ctx) => { disable(); dbg?.("session.start", { mode: ctx.mode }); }); pi.on("session_tree", () => disable()); pi.on("session_shutdown", (_event, ctx) => { disable(); dbg?.("session.shutdown", { mode: ctx.mode }); closeDebug(); }); }