2026-02-13 17:40:29 +09:00
|
|
|
import type { BackgroundManager } from "../../features/background-agent"
|
2026-03-08 02:23:22 +09:00
|
|
|
import { updateSessionAgent } from "../../features/claude-code-session-state"
|
|
|
|
|
import {
|
|
|
|
|
clearCompactionAgentConfigCheckpoint,
|
|
|
|
|
getCompactionAgentConfigCheckpoint,
|
|
|
|
|
setCompactionAgentConfigCheckpoint,
|
|
|
|
|
} from "../../shared/compaction-agent-config-checkpoint"
|
|
|
|
|
import { createInternalAgentTextPart } from "../../shared/internal-initiator-marker"
|
|
|
|
|
import { log } from "../../shared/logger"
|
|
|
|
|
import { setSessionModel } from "../../shared/session-model-state"
|
|
|
|
|
import { setSessionTools } from "../../shared/session-tools-store"
|
2026-03-11 18:23:59 +09:00
|
|
|
import { COMPACTION_CONTEXT_PROMPT } from "./compaction-context-prompt"
|
2026-02-08 13:57:26 +09:00
|
|
|
import {
|
2026-03-11 18:23:59 +09:00
|
|
|
createExpectedRecoveryPromptConfig,
|
|
|
|
|
isPromptConfigRecovered,
|
|
|
|
|
} from "./recovery-prompt-config"
|
2026-03-08 02:23:22 +09:00
|
|
|
import {
|
|
|
|
|
resolveLatestSessionPromptConfig,
|
|
|
|
|
resolveSessionPromptConfig,
|
|
|
|
|
} from "./session-prompt-config-resolver"
|
2026-03-11 18:23:59 +09:00
|
|
|
import {
|
|
|
|
|
finalizeTrackedAssistantMessage,
|
|
|
|
|
shouldTreatAssistantPartAsOutput,
|
|
|
|
|
trackAssistantOutput,
|
|
|
|
|
type TailMonitorState,
|
|
|
|
|
} from "./tail-monitor"
|
2026-03-08 02:23:22 +09:00
|
|
|
|
|
|
|
|
const HOOK_NAME = "compaction-context-injector"
|
|
|
|
|
const AGENT_RECOVERY_PROMPT = "[restore checkpointed session agent configuration after compaction]"
|
|
|
|
|
const NO_TEXT_TAIL_THRESHOLD = 5
|
|
|
|
|
const RECOVERY_COOLDOWN_MS = 60_000
|
|
|
|
|
const RECENT_COMPACTION_WINDOW_MS = 10 * 60 * 1000
|
|
|
|
|
|
|
|
|
|
type CompactionContextClient = {
|
|
|
|
|
client: {
|
|
|
|
|
session: {
|
|
|
|
|
messages: (input: { path: { id: string } }) => Promise<unknown>
|
|
|
|
|
promptAsync: (input: {
|
|
|
|
|
path: { id: string }
|
|
|
|
|
body: {
|
|
|
|
|
noReply?: boolean
|
|
|
|
|
agent?: string
|
|
|
|
|
model?: { providerID: string; modelID: string }
|
|
|
|
|
tools?: Record<string, boolean>
|
|
|
|
|
parts: Array<{ type: "text"; text: string }>
|
|
|
|
|
}
|
|
|
|
|
query?: { directory: string }
|
|
|
|
|
}) => Promise<unknown>
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
directory: string
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface CompactionContextInjector {
|
|
|
|
|
capture: (sessionID: string) => Promise<void>
|
|
|
|
|
inject: (sessionID?: string) => string
|
|
|
|
|
event: (input: { event: { type: string; properties?: unknown } }) => Promise<void>
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function isCompactionAgent(agent: string | undefined): boolean {
|
|
|
|
|
return agent?.trim().toLowerCase() === "compaction"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function resolveSessionID(props?: Record<string, unknown>): string | undefined {
|
|
|
|
|
return (props?.sessionID ??
|
|
|
|
|
(props?.info as { id?: string } | undefined)?.id) as string | undefined
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function createCompactionContextInjector(options?: {
|
|
|
|
|
ctx?: CompactionContextClient
|
|
|
|
|
backgroundManager?: BackgroundManager
|
|
|
|
|
}): CompactionContextInjector {
|
|
|
|
|
const ctx = options?.ctx
|
|
|
|
|
const backgroundManager = options?.backgroundManager
|
|
|
|
|
const tailStates = new Map<string, TailMonitorState>()
|
|
|
|
|
|
|
|
|
|
const getTailState = (sessionID: string): TailMonitorState => {
|
|
|
|
|
const existing = tailStates.get(sessionID)
|
|
|
|
|
if (existing) {
|
|
|
|
|
return existing
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const created: TailMonitorState = {
|
2026-03-11 18:23:59 +09:00
|
|
|
currentHasOutput: false,
|
2026-03-08 02:23:22 +09:00
|
|
|
consecutiveNoTextMessages: 0,
|
|
|
|
|
}
|
|
|
|
|
tailStates.set(sessionID, created)
|
|
|
|
|
return created
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const recoverCheckpointedAgentConfig = async (
|
|
|
|
|
sessionID: string,
|
|
|
|
|
reason: "session.compacted" | "no-text-tail",
|
|
|
|
|
): Promise<boolean> => {
|
|
|
|
|
if (!ctx) {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const checkpoint = getCompactionAgentConfigCheckpoint(sessionID)
|
|
|
|
|
if (!checkpoint?.agent) {
|
|
|
|
|
return false
|
|
|
|
|
}
|
2026-03-11 18:23:59 +09:00
|
|
|
const checkpointWithAgent = {
|
|
|
|
|
...checkpoint,
|
|
|
|
|
agent: checkpoint.agent,
|
|
|
|
|
}
|
2026-03-08 02:23:22 +09:00
|
|
|
|
|
|
|
|
const tailState = getTailState(sessionID)
|
|
|
|
|
const now = Date.now()
|
|
|
|
|
if (tailState.lastRecoveryAt && now - tailState.lastRecoveryAt < RECOVERY_COOLDOWN_MS) {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-11 18:23:59 +09:00
|
|
|
const currentPromptConfig = await resolveSessionPromptConfig(ctx, sessionID)
|
|
|
|
|
const expectedPromptConfig = createExpectedRecoveryPromptConfig(
|
|
|
|
|
checkpointWithAgent,
|
|
|
|
|
currentPromptConfig,
|
|
|
|
|
)
|
|
|
|
|
const model = expectedPromptConfig.model
|
|
|
|
|
const tools = expectedPromptConfig.tools
|
|
|
|
|
|
2026-03-08 02:23:22 +09:00
|
|
|
if (reason === "session.compacted") {
|
|
|
|
|
const latestPromptConfig = await resolveLatestSessionPromptConfig(ctx, sessionID)
|
2026-03-11 18:23:59 +09:00
|
|
|
if (isPromptConfigRecovered(latestPromptConfig, expectedPromptConfig)) {
|
2026-03-08 02:23:22 +09:00
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await ctx.client.session.promptAsync({
|
|
|
|
|
path: { id: sessionID },
|
|
|
|
|
body: {
|
|
|
|
|
noReply: true,
|
2026-03-11 18:23:59 +09:00
|
|
|
agent: expectedPromptConfig.agent,
|
2026-03-08 02:23:22 +09:00
|
|
|
...(model ? { model } : {}),
|
|
|
|
|
...(tools ? { tools } : {}),
|
|
|
|
|
parts: [createInternalAgentTextPart(AGENT_RECOVERY_PROMPT)],
|
|
|
|
|
},
|
|
|
|
|
query: { directory: ctx.directory },
|
|
|
|
|
})
|
|
|
|
|
|
2026-03-11 18:23:59 +09:00
|
|
|
const recoveredPromptConfig = await resolveLatestSessionPromptConfig(ctx, sessionID)
|
|
|
|
|
if (!isPromptConfigRecovered(recoveredPromptConfig, expectedPromptConfig)) {
|
|
|
|
|
log(`[${HOOK_NAME}] Re-injected agent config but recovery is still incomplete`, {
|
|
|
|
|
sessionID,
|
|
|
|
|
reason,
|
|
|
|
|
agent: expectedPromptConfig.agent,
|
|
|
|
|
model,
|
|
|
|
|
hasTools: !!tools,
|
|
|
|
|
recoveredPromptConfig,
|
|
|
|
|
})
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
updateSessionAgent(sessionID, expectedPromptConfig.agent)
|
2026-03-08 02:23:22 +09:00
|
|
|
if (model) {
|
|
|
|
|
setSessionModel(sessionID, model)
|
|
|
|
|
}
|
|
|
|
|
if (tools) {
|
|
|
|
|
setSessionTools(sessionID, tools)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
tailState.lastRecoveryAt = now
|
|
|
|
|
tailState.consecutiveNoTextMessages = 0
|
|
|
|
|
|
|
|
|
|
log(`[${HOOK_NAME}] Re-injected checkpointed agent config`, {
|
|
|
|
|
sessionID,
|
|
|
|
|
reason,
|
2026-03-11 18:23:59 +09:00
|
|
|
agent: expectedPromptConfig.agent,
|
2026-03-08 02:23:22 +09:00
|
|
|
model,
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return true
|
|
|
|
|
} catch (error) {
|
|
|
|
|
log(`[${HOOK_NAME}] Failed to re-inject checkpointed agent config`, {
|
|
|
|
|
sessionID,
|
|
|
|
|
reason,
|
|
|
|
|
error: String(error),
|
|
|
|
|
})
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const maybeWarnAboutNoTextTail = async (sessionID: string): Promise<void> => {
|
|
|
|
|
const tailState = getTailState(sessionID)
|
|
|
|
|
if (tailState.consecutiveNoTextMessages < NO_TEXT_TAIL_THRESHOLD) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const recentlyCompacted =
|
|
|
|
|
tailState.lastCompactedAt !== undefined &&
|
|
|
|
|
Date.now() - tailState.lastCompactedAt < RECENT_COMPACTION_WINDOW_MS
|
|
|
|
|
|
|
|
|
|
log(`[${HOOK_NAME}] Detected consecutive assistant messages with no text`, {
|
|
|
|
|
sessionID,
|
|
|
|
|
consecutiveNoTextMessages: tailState.consecutiveNoTextMessages,
|
|
|
|
|
recentlyCompacted,
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if (recentlyCompacted) {
|
|
|
|
|
await recoverCheckpointedAgentConfig(sessionID, "no-text-tail")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const capture = async (sessionID: string): Promise<void> => {
|
|
|
|
|
if (!ctx || !sessionID) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const promptConfig = await resolveSessionPromptConfig(ctx, sessionID)
|
|
|
|
|
if (!promptConfig.agent && !promptConfig.model && !promptConfig.tools) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
setCompactionAgentConfigCheckpoint(sessionID, promptConfig)
|
|
|
|
|
log(`[${HOOK_NAME}] Captured agent checkpoint before compaction`, {
|
|
|
|
|
sessionID,
|
|
|
|
|
agent: promptConfig.agent,
|
|
|
|
|
model: promptConfig.model,
|
|
|
|
|
hasTools: !!promptConfig.tools,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const inject = (sessionID?: string): string => {
|
2026-02-13 17:40:29 +09:00
|
|
|
let prompt = COMPACTION_CONTEXT_PROMPT
|
|
|
|
|
|
|
|
|
|
if (backgroundManager && sessionID) {
|
|
|
|
|
const history = backgroundManager.taskHistory.formatForCompaction(sessionID)
|
|
|
|
|
if (history) {
|
|
|
|
|
prompt += `\n### Active/Recent Delegated Sessions\n${history}\n`
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return prompt
|
|
|
|
|
}
|
2026-03-08 02:23:22 +09:00
|
|
|
|
|
|
|
|
const event = async ({ event }: { event: { type: string; properties?: unknown } }): Promise<void> => {
|
|
|
|
|
const props = event.properties as Record<string, unknown> | undefined
|
|
|
|
|
|
|
|
|
|
if (event.type === "session.deleted") {
|
|
|
|
|
const sessionID = resolveSessionID(props)
|
|
|
|
|
if (sessionID) {
|
|
|
|
|
clearCompactionAgentConfigCheckpoint(sessionID)
|
|
|
|
|
tailStates.delete(sessionID)
|
|
|
|
|
}
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (event.type === "session.idle") {
|
|
|
|
|
const sessionID = resolveSessionID(props)
|
|
|
|
|
if (!sessionID) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const noTextCount = finalizeTrackedAssistantMessage(getTailState(sessionID))
|
|
|
|
|
if (noTextCount > 0) {
|
|
|
|
|
await maybeWarnAboutNoTextTail(sessionID)
|
|
|
|
|
}
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (event.type === "session.compacted") {
|
|
|
|
|
const sessionID = resolveSessionID(props)
|
|
|
|
|
if (!sessionID) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const tailState = getTailState(sessionID)
|
|
|
|
|
finalizeTrackedAssistantMessage(tailState)
|
|
|
|
|
tailState.lastCompactedAt = Date.now()
|
|
|
|
|
await maybeWarnAboutNoTextTail(sessionID)
|
|
|
|
|
await recoverCheckpointedAgentConfig(sessionID, "session.compacted")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (event.type === "message.updated") {
|
|
|
|
|
const info = props?.info as {
|
|
|
|
|
id?: string
|
|
|
|
|
role?: string
|
|
|
|
|
sessionID?: string
|
|
|
|
|
} | undefined
|
|
|
|
|
|
|
|
|
|
if (!info?.sessionID || info.role !== "assistant" || !info.id) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const tailState = getTailState(info.sessionID)
|
|
|
|
|
if (tailState.currentMessageID && tailState.currentMessageID !== info.id) {
|
|
|
|
|
finalizeTrackedAssistantMessage(tailState)
|
|
|
|
|
await maybeWarnAboutNoTextTail(info.sessionID)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (tailState.currentMessageID !== info.id) {
|
|
|
|
|
tailState.currentMessageID = info.id
|
2026-03-11 18:23:59 +09:00
|
|
|
tailState.currentHasOutput = false
|
2026-03-08 02:23:22 +09:00
|
|
|
}
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (event.type === "message.part.delta") {
|
|
|
|
|
const sessionID = props?.sessionID as string | undefined
|
|
|
|
|
const messageID = props?.messageID as string | undefined
|
|
|
|
|
const field = props?.field as string | undefined
|
|
|
|
|
const delta = props?.delta as string | undefined
|
|
|
|
|
|
|
|
|
|
if (!sessionID || field !== "text" || !delta?.trim()) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-11 18:23:59 +09:00
|
|
|
trackAssistantOutput(getTailState(sessionID), messageID)
|
2026-03-08 02:23:22 +09:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (event.type === "message.part.updated") {
|
|
|
|
|
const part = props?.part as {
|
|
|
|
|
messageID?: string
|
|
|
|
|
sessionID?: string
|
|
|
|
|
type?: string
|
|
|
|
|
text?: string
|
|
|
|
|
} | undefined
|
|
|
|
|
|
2026-03-11 18:23:59 +09:00
|
|
|
if (!part?.sessionID || !shouldTreatAssistantPartAsOutput(part)) {
|
2026-03-08 02:23:22 +09:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-11 18:23:59 +09:00
|
|
|
trackAssistantOutput(getTailState(part.sessionID), part.messageID)
|
2026-03-08 02:23:22 +09:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { capture, inject, event }
|
2026-02-08 13:57:26 +09:00
|
|
|
}
|