|
| 1 | +import type { PluginInput } from "@opencode-ai/plugin" |
| 2 | + |
| 3 | +export function createPulseMonitorHook(ctx: PluginInput) { |
| 4 | + const STANDARD_TIMEOUT = 5 * 60 * 1000 // 5 minutes |
| 5 | + const THINKING_TIMEOUT = 5 * 60 * 1000 // 5 minutes |
| 6 | + const CHECK_INTERVAL = 5 * 1000 // 5 seconds |
| 7 | + |
| 8 | + let lastHeartbeat = Date.now() |
| 9 | + let isMonitoring = false |
| 10 | + let currentSessionID: string | null = null |
| 11 | + let monitorTimer: ReturnType<typeof setInterval> | null = null |
| 12 | + let isThinking = false |
| 13 | + |
| 14 | + const startMonitoring = (sessionID: string) => { |
| 15 | + if (currentSessionID !== sessionID) { |
| 16 | + currentSessionID = sessionID |
| 17 | + // Reset thinking state when switching sessions or starting new |
| 18 | + isThinking = false |
| 19 | + } |
| 20 | + |
| 21 | + lastHeartbeat = Date.now() |
| 22 | + |
| 23 | + if (!isMonitoring) { |
| 24 | + isMonitoring = true |
| 25 | + if (monitorTimer) clearInterval(monitorTimer) |
| 26 | + |
| 27 | + monitorTimer = setInterval(async () => { |
| 28 | + if (!isMonitoring || !currentSessionID) return |
| 29 | + |
| 30 | + const timeSinceLastHeartbeat = Date.now() - lastHeartbeat |
| 31 | + const currentTimeout = isThinking ? THINKING_TIMEOUT : STANDARD_TIMEOUT |
| 32 | + |
| 33 | + if (timeSinceLastHeartbeat > currentTimeout) { |
| 34 | + await recoverStalledSession(currentSessionID, timeSinceLastHeartbeat, isThinking) |
| 35 | + } |
| 36 | + }, CHECK_INTERVAL) |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + const stopMonitoring = () => { |
| 41 | + isMonitoring = false |
| 42 | + if (monitorTimer) { |
| 43 | + clearInterval(monitorTimer) |
| 44 | + monitorTimer = null |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + const updateHeartbeat = (isThinkingUpdate?: boolean) => { |
| 49 | + if (isMonitoring) { |
| 50 | + lastHeartbeat = Date.now() |
| 51 | + if (isThinkingUpdate !== undefined) { |
| 52 | + isThinking = isThinkingUpdate |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + const recoverStalledSession = async (sessionID: string, stalledDuration: number, wasThinking: boolean) => { |
| 58 | + stopMonitoring() |
| 59 | + |
| 60 | + try { |
| 61 | + const durationSec = Math.round(stalledDuration/1000) |
| 62 | + const typeStr = wasThinking ? "Thinking" : "Standard" |
| 63 | + |
| 64 | + // 1. Notify User |
| 65 | + await ctx.client.tui.showToast({ |
| 66 | + body: { |
| 67 | + title: "Pulse Monitor: Cardiac Arrest", |
| 68 | + message: `Session stalled (${typeStr}) for ${durationSec}s. Defibrillating...`, |
| 69 | + variant: "error", |
| 70 | + duration: 5000 |
| 71 | + } |
| 72 | + }).catch(() => {}) |
| 73 | + |
| 74 | + // 2. Abort current generation (Defibrillation shock) |
| 75 | + await ctx.client.session.abort({ path: { id: sessionID } }).catch(() => {}) |
| 76 | + |
| 77 | + // 3. Wait a bit for state to settle |
| 78 | + await new Promise(resolve => setTimeout(resolve, 1500)) |
| 79 | + |
| 80 | + // 4. Prompt "continue" to kickstart (CPR) |
| 81 | + await ctx.client.session.prompt({ |
| 82 | + path: { id: sessionID }, |
| 83 | + body: { parts: [{ type: "text", text: "The connection was unstable and stalled. Please continue from where you left off." }] }, |
| 84 | + query: { directory: ctx.directory } |
| 85 | + }) |
| 86 | + |
| 87 | + // Resume monitoring |
| 88 | + startMonitoring(sessionID) |
| 89 | + |
| 90 | + } catch (err) { |
| 91 | + console.error("[PulseMonitor] Recovery failed:", err) |
| 92 | + // If recovery fails, we stop monitoring to avoid loops |
| 93 | + stopMonitoring() |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + return { |
| 98 | + event: async (input: { event: any }) => { |
| 99 | + const { event } = input |
| 100 | + const props = event.properties as Record<string, any> | undefined |
| 101 | + |
| 102 | + // Monitor both session updates and part updates to capture token flow |
| 103 | + if (event.type === "session.updated" || event.type === "message.part.updated") { |
| 104 | + // Try to get sessionID from various common locations |
| 105 | + const sessionID = props?.info?.id || props?.sessionID |
| 106 | + |
| 107 | + if (sessionID) { |
| 108 | + if (!isMonitoring) startMonitoring(sessionID) |
| 109 | + |
| 110 | + // Check for thinking indicators in the payload |
| 111 | + let thinkingUpdate: boolean | undefined = undefined |
| 112 | + |
| 113 | + if (event.type === "message.part.updated") { |
| 114 | + const part = props?.part |
| 115 | + if (part) { |
| 116 | + const THINKING_TYPES = ["thinking", "redacted_thinking", "reasoning"] |
| 117 | + if (THINKING_TYPES.includes(part.type)) { |
| 118 | + thinkingUpdate = true |
| 119 | + } else if (part.type === "text" || part.type === "tool_use") { |
| 120 | + thinkingUpdate = false |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + updateHeartbeat(thinkingUpdate) |
| 126 | + } |
| 127 | + } else if (event.type === "session.idle" || event.type === "session.error" || event.type === "session.stopped") { |
| 128 | + stopMonitoring() |
| 129 | + } |
| 130 | + }, |
| 131 | + "tool.execute.before": async () => { |
| 132 | + // Pause monitoring while tool runs locally (tools can take time) |
| 133 | + stopMonitoring() |
| 134 | + }, |
| 135 | + "tool.execute.after": async (input: { sessionID: string }) => { |
| 136 | + // Resume monitoring after tool finishes |
| 137 | + if (input.sessionID) { |
| 138 | + startMonitoring(input.sessionID) |
| 139 | + } |
| 140 | + } |
| 141 | + } |
| 142 | +} |
0 commit comments