/** * Shared stop handlers - runs all stop event logic. * Used by StopOrchestrator.ts (Claude Code) and opencode plugin. */ import { randomUUID } from "node:crypto"; import { existsSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs"; import { writeFile } from "node:fs/promises"; import { resolve } from "node:path"; import { autoBackup } from "../handlers/backup"; import { writeContextDigests } from "../handlers/context-digests"; import { notifyDesktop } from "../handlers/desktop-notify"; import { persistLastExchange } from "../handlers/persist-last-exchange"; import { projectTouch } from "../handlers/project-touch"; import { runSynthesis } from "../handlers/synthesis"; import { resetTab } from "../handlers/tab"; import { updateCounts } from "../handlers/update-counts"; import { captureWorkSession } from "../handlers/work-session"; import { spawnCollectIfDue } from "./collect-trigger"; import { acknowledgeMentioned } from "./daily-nudge"; import { spawnDetachedInference } from "./detached-inference"; import { startHookTiming } from "./hook-timing"; import { fileFinalReply, type HookTurnPayload, hookFinalReply, hookSessionId, } from "./hook-turn"; import { recordReply } from "./interaction"; import { logDebug, logError } from "./log"; import { assets, ensureDir, paths } from "./paths"; import { extractContent, extractLastAssistant, type Message, recentMessages, withFinalReply, } from "./transcript"; export interface StopTurnPayload extends HookTurnPayload { transcript_path?: string | null; transcriptPath?: string | null; stop_hook_active?: boolean; loop_count?: number; executionNum?: number; } type Transcript = Message[]; /** Session-intelligence reads the last 10 user messages; nothing else reads further back. */ const STOP_USER_MESSAGES = 10; interface ReplyWait { timeoutMs: number; intervalMs: number; } const REPLY_WAIT: ReplyWait = { timeoutMs: 15_000, intervalMs: 200 }; function transcriptOf(payload: StopTurnPayload | null): Transcript { const transcriptPath = payload?.transcript_path ?? payload?.transcriptPath; return transcriptPath ? recentMessages(transcriptPath, STOP_USER_MESSAGES) : []; } /** The Copilot CLI writes the reply to its transcript only after agentStop returns. */ function replyNotWrittenYet(payload: StopTurnPayload | null, messages: Transcript) { return messages.at(-1)?.role === "user" && !hookFinalReply(payload); } async function transcriptOnceReplied( payload: StopTurnPayload, wait: ReplyWait ): Promise { const deadline = Date.now() + wait.timeoutMs; for (;;) { const messages = transcriptOf(payload); if (!replyNotWrittenYet(payload, messages)) return messages; if (Date.now() >= deadline) return null; await Bun.sleep(wait.intervalMs); } } function deferStopTurn(payload: StopTurnPayload): void { try { const deferId: string = randomUUID(); const payloadPath = resolve(paths.state(), `stop-deferred.${deferId}.json`); writeFileSync(payloadPath, JSON.stringify(payload), "utf-8"); const scriptPath = resolve(assets.hooks(), "StopDeferred.ts"); spawnDetachedInference(scriptPath, [payloadPath], "stop-deferred"); } catch (err) { logError("deferStopTurn", err); } } function takeDeferredPayload(payloadPath: string): StopTurnPayload | null { try { return JSON.parse(readFileSync(payloadPath, "utf-8")); } catch { return null; } finally { rmSync(payloadPath, { force: true }); } } /** Runs the stop a hook deferred, once the reply it was waiting for is in the transcript. */ export async function finishDeferredStop( payloadPath: string, wait: ReplyWait = REPLY_WAIT ): Promise { const payload = takeDeferredPayload(payloadPath); if (!payload) return; const messages = await transcriptOnceReplied(payload, wait); if (!messages) { logDebug("finishDeferredStop", "The reply never reached the transcript"); return; } await runTurnStop(payload, messages); } /** Everything a stop hook does once the agent's payload is read. */ export async function stopTurn(payload: StopTurnPayload | null): Promise { const messages = transcriptOf(payload); if (payload && replyNotWrittenYet(payload, messages)) { deferStopTurn(payload); return; } await runTurnStop(payload, messages); } async function runTurnStop( payload: StopTurnPayload | null, messages: Transcript ): Promise { if (messages.length >= 2) { await runStopHandlers(messages, { lastAssistantMessage: hookFinalReply(payload), sessionId: hookSessionId(payload), }); return; } logDebug("stopTurn", "No readable transcript; filing only the final reply"); fileFinalReply(payload); } interface RunStopHandlersOptions { lastAssistantMessage?: string; sessionId?: string; } /** Run all stop handlers on the newest messages of the transcript */ export async function runStopHandlers( fileMessages: Message[], options: RunStopHandlersOptions = {} ): Promise { const timing = startHookTiming("stop"); if (fileMessages.length < 2) return; const messages = withFinalReply(fileMessages, options.lastAssistantMessage); const transcript = JSON.stringify(messages); logDebug("runStopHandlers", `Running handlers (${messages.length} messages)`); // Cache last assistant response (session-scoped) cacheLastResponse(messages, options.lastAssistantMessage, options.sessionId); if (options.sessionId) recordFinalReply(messages, options.sessionId); // Always persist last exchange — drives CompactRecover + "Pick Up Where You Left Off" if (options.sessionId) persistLastExchange(messages, options.sessionId); // Detach inference-bearing handlers — claude --print cold-start can exceed // any in-hook budget. These spawn detached bun subprocesses that run the // inference and write results to disk; they don't block this hook. await timing.time("detach-inference", async () => { sweepStaleHandoffs(); await detachSessionIntelligence(transcript, options.sessionId); await detachEntityExtraction(transcript, options.sessionId); detachAgenda(options.sessionId); }); // Run remaining (non-inference) handlers concurrently. // project-touch only fires when cwd resolves to an active registered project. const handlers: Record = { "work-session": captureWorkSession(transcript, options.sessionId), tab: resetTab(), "update-counts": updateCounts(), backup: autoBackup(), synthesis: runSynthesis(), "project-touch": projectTouch(), "desktop-notify": notifyDesktop(options.sessionId), "context-digests": Promise.resolve(writeContextDigests()), "collect-events": Promise.resolve(spawnCollectIfDue()), }; const names = Object.keys(handlers); const results = await Promise.allSettled( names.map((name) => timing.time(name, Promise.resolve(handlers[name]))) ); for (let i = 0; i < results.length; i++) { const r = results[i]; if (r?.status === "rejected") { logError(`runStopHandlers:${names[i]}`, r.reason); } } timing.log(options.sessionId); } /** * Cache the last assistant response per session for RatingCapture. * Stores a map of session_id → { response, ts } in last-responses.json. * Keeps at most MAX_CACHED_SESSIONS entries (evicts oldest by ts). */ const MAX_CACHED_SESSIONS = 20; interface CachedResponse { response: string; ts: string; } function cacheLastResponse( msgs: Message[], lastAssistantMessage?: string, sessionId?: string ): void { if (!sessionId) return; // Can't cache without a session key try { let lastResponse = lastAssistantMessage; if (!lastResponse) { const lastAssistant = extractLastAssistant(msgs); lastResponse = extractContent(lastAssistant); } if (!lastResponse) return; const cachePath = resolve(ensureDir(paths.state()), "last-responses.json"); // Read existing cache let cache: Record = {}; if (existsSync(cachePath)) { try { cache = JSON.parse(readFileSync(cachePath, "utf-8")); } catch { cache = {}; } } // Upsert this session cache[sessionId] = { response: lastResponse.slice(0, 2000), ts: new Date().toISOString(), }; // Evict oldest if over limit const keys = Object.keys(cache); if (keys.length > MAX_CACHED_SESSIONS) { const sorted = keys.sort((a, b) => (cache[a].ts ?? "").localeCompare(cache[b].ts ?? "") ); for (const key of sorted.slice(0, keys.length - MAX_CACHED_SESSIONS)) { delete cache[key]; } } writeFileSync(cachePath, JSON.stringify(cache), "utf-8"); logDebug("runStopHandlers", "Cached last response for RatingCapture"); } catch (err) { logError("runStopHandlers:cacheLastResponse", err); } } function recordFinalReply(messages: Message[], sessionId: string): void { try { const reply = extractContent(extractLastAssistant(messages)); recordReply(sessionId, reply); acknowledgeMentioned(reply); } catch (err) { logError("runStopHandlers:recordReply", err); } } const HANDOFF_MAX_AGE_MS = 24 * 60 * 60_000; /** Write transcript to a uniquely named hand-off file and return the path. Child unlinks it. */ async function writeTranscriptHandoff(transcript: string): Promise { const id: string = randomUUID(); const file = resolve(paths.transcriptHandoff(), `${id}.txt`); await writeFile(file, transcript, "utf-8"); return file; } /** Delete hand-off files a child never got to remove. */ export function sweepStaleHandoffs(now: number = Date.now()): void { try { const dir = paths.transcriptHandoff(); for (const name of readdirSync(dir)) { const file = resolve(dir, name); try { if (now - statSync(file).mtimeMs <= HANDOFF_MAX_AGE_MS) continue; unlinkSync(file); } catch (err) { if ((err as NodeJS.ErrnoException).code !== "ENOENT") { logError("sweepStaleHandoffs", err); } } } } catch (err) { logError("sweepStaleHandoffs", err); } } /** * The agenda reads files, not the transcript, so it needs no tmp copy — but it * calls a model, so it detaches like the others. It no-ops on a fresh agenda. */ function detachAgenda(sessionId?: string): void { try { const scriptPath = resolve(assets.hooks(), "handlers", "agenda.ts"); spawnDetachedInference(scriptPath, ["--run", sessionId ?? ""], "agenda"); } catch (err) { logError("detachAgenda", err); } } /** Spawn a detached child to run session-intelligence on a hand-off copy of the transcript. */ async function detachSessionIntelligence( transcript: string, sessionId?: string ): Promise { try { const transcriptPath = await writeTranscriptHandoff(transcript); const scriptPath = resolve(assets.hooks(), "handlers", "session-intelligence.ts"); spawnDetachedInference( scriptPath, ["--run", sessionId ?? "", transcriptPath], "session-intelligence" ); } catch (err) { logError("detachSessionIntelligence", err); } } async function detachEntityExtraction( transcript: string, sessionId?: string ): Promise { if (!sessionId) return; try { const transcriptPath = await writeTranscriptHandoff(transcript); const scriptPath = resolve(assets.hooks(), "handlers", "entity-extraction.ts"); spawnDetachedInference( scriptPath, ["--run", sessionId, transcriptPath], "entity-extraction" ); } catch (err) { logError("detachEntityExtraction", err); } }