-
Notifications
You must be signed in to change notification settings - Fork 2.9k
feat(hooks): add reliability stack hooks for memory gating and crash recovery #2329
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
inwardwellbeing
wants to merge
6
commits into
code-yeongyu:dev
Choose a base branch
from
inwardwellbeing:ck/reliability-stack
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
91bf532
feat(hooks): add correction-detector hook
inwardwellbeing 3549a7b
feat(hooks): add resource-gate hook for OOM prevention
inwardwellbeing f5b098d
feat(hooks): add execution-gate, learning-bus-injector, and auto-chec…
inwardwellbeing 6c8a51e
feat(hooks): register new hooks in schema and add barrel exports
inwardwellbeing 9453ad6
chore: bump version to 3.10.0
inwardwellbeing 3905a7b
chore: ignore platform binary sourcemaps in packages/*/bin/
inwardwellbeing File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| export const HOOK_NAME = "auto-checkpoint" | ||
| export const CHECKPOINT_MESSAGE_THRESHOLD = 20 | ||
| export const CHECKPOINT_TIME_THRESHOLD_MS = 15 * 60 * 1000 // 15 minutes | ||
| export const CHECKPOINT_NAME = "auto-idle" | ||
| export const DEFAULT_SKIP_AGENTS = ["explore", "librarian", "multimodal-looker", "oracle", "metis", "momus"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| import type { PluginInput } from "@opencode-ai/plugin" | ||
|
|
||
| import { createInternalAgentTextPart, normalizeSDKResponse } from "../../shared" | ||
| import { getAgentConfigKey } from "../../shared/agent-display-names" | ||
| import { log } from "../../shared/logger" | ||
|
|
||
| import { | ||
| CHECKPOINT_MESSAGE_THRESHOLD, | ||
| CHECKPOINT_TIME_THRESHOLD_MS, | ||
| DEFAULT_SKIP_AGENTS, | ||
| HOOK_NAME, | ||
| } from "./constants" | ||
| import { buildCheckpointPrompt, buildRestorePrompt } from "./prompt-templates" | ||
|
|
||
| const COOLDOWN_MS = 5 * 60 * 1000 | ||
| const MAX_INJECTION_CHARS = 2000 | ||
|
|
||
| type SessionState = { | ||
| idleCount: number | ||
| lastInjectionAt: number | ||
| restoreInjected: boolean | ||
| isSubagent: boolean | null | ||
| } | ||
|
|
||
| export type AutoCheckpointHook = ReturnType<typeof createAutoCheckpointHook> | ||
|
|
||
| export function createAutoCheckpointHook( | ||
| ctx: PluginInput, | ||
| options: { skipAgents?: string[] } = {}, | ||
| ) { | ||
| const { skipAgents = DEFAULT_SKIP_AGENTS } = options | ||
| const sessions = new Map<string, SessionState>() | ||
|
|
||
| async function resolveAgent(sessionID: string): Promise<string | undefined> { | ||
| try { | ||
| const messagesResp = await ctx.client.session.messages({ | ||
| path: { id: sessionID }, | ||
| }) | ||
| const messages = normalizeSDKResponse(messagesResp, [] as Array<{ info?: { agent?: string } }>) | ||
| for (const msg of messages) { | ||
| if (msg.info?.agent) return msg.info.agent | ||
| } | ||
| } catch (error) { | ||
| log(`[${HOOK_NAME}] Failed to resolve agent`, { sessionID, error: String(error) }) | ||
| } | ||
| return undefined | ||
| } | ||
|
|
||
| function getOrCreateSession(sessionID: string): SessionState { | ||
| let state = sessions.get(sessionID) | ||
| if (!state) { | ||
| state = { idleCount: 0, lastInjectionAt: 0, restoreInjected: false, isSubagent: null } | ||
| sessions.set(sessionID, state) | ||
| } | ||
| return state | ||
| } | ||
|
|
||
| async function isSkippedAgent(sessionID: string, state: SessionState): Promise<boolean> { | ||
| if (state.isSubagent !== null) return state.isSubagent | ||
| const agentName = await resolveAgent(sessionID) | ||
| if (agentName && skipAgents.some((s) => getAgentConfigKey(s) === getAgentConfigKey(agentName))) { | ||
| state.isSubagent = true | ||
| log(`[${HOOK_NAME}] Skipped: sub-agent session`, { sessionID, agent: agentName }) | ||
| return true | ||
| } | ||
| state.isSubagent = false | ||
| return false | ||
| } | ||
|
|
||
| const event = async (input: { event: { type: string; properties?: unknown } }): Promise<void> => { | ||
| if (input.event.type === "session.deleted") { | ||
| const props = input.event.properties as Record<string, unknown> | undefined | ||
| const sessionInfo = props?.info as { id?: string } | undefined | ||
| if (sessionInfo?.id) { | ||
| sessions.delete(sessionInfo.id) | ||
| } | ||
| return | ||
| } | ||
|
|
||
| if (input.event.type !== "session.idle") return | ||
|
|
||
| const props = input.event.properties as Record<string, unknown> | undefined | ||
| const sessionID = props?.sessionID as string | undefined | ||
| if (!sessionID) return | ||
|
|
||
| const state = getOrCreateSession(sessionID) | ||
| state.idleCount++ | ||
| const now = Date.now() | ||
|
|
||
| // First idle of a fresh session: inject restore prompt | ||
| if (state.idleCount === 1 && !state.restoreInjected) { | ||
| if (await isSkippedAgent(sessionID, state)) return | ||
|
|
||
| state.restoreInjected = true | ||
| try { | ||
| const prompt = buildRestorePrompt() | ||
| await ctx.client.session.promptAsync({ | ||
| path: { id: sessionID }, | ||
| body: { parts: [createInternalAgentTextPart(prompt)] }, | ||
| query: { directory: ctx.directory }, | ||
| }) | ||
| state.lastInjectionAt = now | ||
| log(`[${HOOK_NAME}] Injected restore prompt`, { sessionID }) | ||
| } catch (error) { | ||
| log(`[${HOOK_NAME}] Failed to inject restore prompt`, { sessionID, error: String(error) }) | ||
| state.restoreInjected = false | ||
| } | ||
| return | ||
| } | ||
|
|
||
| // Cooldown: skip if last injection was less than 5min ago | ||
| if (now - state.lastInjectionAt < COOLDOWN_MS) return | ||
|
|
||
| // Check thresholds: idle count (proxy for messages) or time since last injection | ||
| const idlesSinceLastInjection = state.idleCount | ||
| const timeSinceLastInjection = state.lastInjectionAt === 0 ? now : now - state.lastInjectionAt | ||
|
|
||
| const messageThresholdMet = idlesSinceLastInjection >= CHECKPOINT_MESSAGE_THRESHOLD | ||
| const timeThresholdMet = timeSinceLastInjection >= CHECKPOINT_TIME_THRESHOLD_MS | ||
|
|
||
| if (!messageThresholdMet && !timeThresholdMet) return | ||
|
|
||
| if (await isSkippedAgent(sessionID, state)) return | ||
|
|
||
| try { | ||
| const minutesSince = Math.round(timeSinceLastInjection / 60_000) | ||
| let prompt = buildCheckpointPrompt({ | ||
| messagesSinceCheckpoint: idlesSinceLastInjection, | ||
| minutesSinceCheckpoint: minutesSince, | ||
| }) | ||
|
|
||
| if (prompt.length > MAX_INJECTION_CHARS) { | ||
| prompt = prompt.slice(0, MAX_INJECTION_CHARS) + "\n\n(Truncated)" | ||
| } | ||
|
|
||
| await ctx.client.session.promptAsync({ | ||
| path: { id: sessionID }, | ||
| body: { parts: [createInternalAgentTextPart(prompt)] }, | ||
| query: { directory: ctx.directory }, | ||
| }) | ||
|
|
||
| state.lastInjectionAt = now | ||
| state.idleCount = 0 | ||
|
|
||
| log(`[${HOOK_NAME}] Injected checkpoint prompt`, { | ||
| sessionID, | ||
| idleCount: idlesSinceLastInjection, | ||
| minutesSinceCheckpoint: minutesSince, | ||
| trigger: messageThresholdMet ? "message-threshold" : "time-threshold", | ||
| }) | ||
| } catch (error) { | ||
| log(`[${HOOK_NAME}] Failed to inject checkpoint prompt`, { sessionID, error: String(error) }) | ||
| } | ||
| } | ||
|
|
||
| return { event } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P1: When
lastInjectionAtis 0 (initial state or failed injection),timeSinceLastInjectionincorrectly falls back tonow(current timestamp), causingminutesSinceto calculate as ~28 million minutes. The checkpoint prompt then displays an absurd duration. The fallback should be0instead ofnowto correctly indicate no time has passed since injection.Prompt for AI agents