mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-18 03:27:08 +00:00
Claude-compatible providers can emit assistant snapshots with an all-zero usage object after long tool runs. Picking one as latestUsage reset the status bar to 0 used / 100% left. Skip zero-context samples and retain the last meaningful turn's context. Co-Authored-By: Claude Code <noreply@anthropic.com> Co-Authored-By: HAPI <noreply@hapi.run>
233 lines
9.2 KiB
TypeScript
233 lines
9.2 KiB
TypeScript
import type { AgentState } from '@/types/api'
|
|
import type { AgentEvent, ChatBlock, NormalizedMessage, UsageData } from '@/chat/types'
|
|
import type { ThreadGoal } from '@/types/api'
|
|
import { traceMessages, type TracedMessage } from '@/chat/tracer'
|
|
import { dedupeAgentEvents, foldApiErrorEvents } from '@/chat/reducerEvents'
|
|
import { collectTitleChanges, ensureToolBlock, getPermissions } from '@/chat/reducerTools'
|
|
import { reduceTimeline } from '@/chat/reducerTimeline'
|
|
import { isRedundantGoalStatusMessageText } from '@hapi/protocol/messages'
|
|
|
|
// Calculate context size from usage data
|
|
function calculateContextSize(usage: UsageData): number {
|
|
if (typeof usage.context_tokens === 'number') {
|
|
return usage.context_tokens
|
|
}
|
|
return (usage.cache_creation_input_tokens || 0) + (usage.cache_read_input_tokens || 0) + usage.input_tokens
|
|
}
|
|
|
|
/**
|
|
* Some Claude-compatible providers emit assistant snapshots with an
|
|
* all-zero usage object (notably after long tool runs). Picking one as the
|
|
* latest usage reset the status bar to "ctx 1.0M (100% left)" even though the
|
|
* last real turn reported a large context. Treat an all-zero sample as "no
|
|
* new context information" and keep scanning backwards.
|
|
*/
|
|
function hasContextUsageSignal(usage: UsageData): boolean {
|
|
return (usage.context_tokens ?? 0) > 0
|
|
|| usage.input_tokens > 0
|
|
|| (usage.cache_creation_input_tokens ?? 0) > 0
|
|
|| (usage.cache_read_input_tokens ?? 0) > 0
|
|
}
|
|
|
|
/**
|
|
* Whether a message's usage describes the *parent* thread's context.
|
|
*
|
|
* A Task subagent runs with its own, much smaller context, so letting its usage
|
|
* through makes the status bar's numerator collapse mid-run and snap back when
|
|
* the parent resumes. `scope_role` alone cannot catch this: Claude never stamps
|
|
* it (see sdkToLogConverter.ts), and Codex drops child `token_count` events in
|
|
* the CLI before they reach us — so the guard never actually fires on any path.
|
|
* `isSidechain` is the signal that survives both.
|
|
*/
|
|
function isUsageVisibleInParentContext(msg: NormalizedMessage): boolean {
|
|
if (msg.isSidechain) return false
|
|
return msg.usage?.scope_role !== 'child'
|
|
}
|
|
|
|
export type LatestUsage = {
|
|
inputTokens: number
|
|
outputTokens: number
|
|
cacheCreation: number
|
|
cacheRead: number
|
|
contextSize: number
|
|
contextWindow: number | null
|
|
/**
|
|
* Model reported by the usage-bearing message itself. Local-mode Claude
|
|
* sessions often have session.model = null (the model is picked inside the
|
|
* TUI), so this is the only model signal available for the context-window
|
|
* heuristic when the usage carries no explicit context_window.
|
|
*/
|
|
model: string | null
|
|
timestamp: number
|
|
}
|
|
|
|
export type ReduceChatBlocksOptions = {
|
|
goalStateMessages?: NormalizedMessage[]
|
|
}
|
|
|
|
function getLatestThreadGoal(normalized: NormalizedMessage[]): ThreadGoal | null {
|
|
let sawNewerNonGoalUserMessage = false
|
|
for (let i = normalized.length - 1; i >= 0; i--) {
|
|
const msg = normalized[i]
|
|
if (msg.role === 'user') {
|
|
if (!/^\s*\/goal(?:\s|$)/i.test(msg.content.text)) {
|
|
sawNewerNonGoalUserMessage = true
|
|
}
|
|
continue
|
|
}
|
|
if (msg.role !== 'event') continue
|
|
const event = msg.content as AgentEvent
|
|
if (event.type === 'thread-goal-cleared') return null
|
|
if (event.type === 'thread-goal-updated') {
|
|
const goal = (event as { goal?: ThreadGoal }).goal ?? null
|
|
if (goal?.status === 'complete' && sawNewerNonGoalUserMessage) {
|
|
return null
|
|
}
|
|
return goal
|
|
}
|
|
}
|
|
return null
|
|
}
|
|
|
|
function isRedundantGoalStatusMessage(event: AgentEvent): boolean {
|
|
if (event.type !== 'message') return false
|
|
return isRedundantGoalStatusMessageText(event.message)
|
|
}
|
|
|
|
function isSilentGoalEventBlock(block: ChatBlock): boolean {
|
|
return block.kind === 'agent-event'
|
|
&& (
|
|
block.event.type === 'thread-goal-updated'
|
|
|| block.event.type === 'thread-goal-cleared'
|
|
|| isRedundantGoalStatusMessage(block.event)
|
|
)
|
|
}
|
|
|
|
function filterSilentGoalBlocks(blocks: ChatBlock[]): ChatBlock[] {
|
|
const filtered: ChatBlock[] = []
|
|
|
|
for (const block of blocks) {
|
|
if (isSilentGoalEventBlock(block)) continue
|
|
if (block.kind === 'tool-call' && block.children.length > 0) {
|
|
filtered.push({
|
|
...block,
|
|
children: filterSilentGoalBlocks(block.children)
|
|
})
|
|
continue
|
|
}
|
|
filtered.push(block)
|
|
}
|
|
|
|
return filtered
|
|
}
|
|
|
|
export function reduceChatBlocks(
|
|
normalized: NormalizedMessage[],
|
|
agentState: AgentState | null | undefined,
|
|
options: ReduceChatBlocksOptions = {}
|
|
): { blocks: ChatBlock[]; hasReadyEvent: boolean; latestUsage: LatestUsage | null; latestGoal: ThreadGoal | null } {
|
|
const permissionsById = getPermissions(agentState)
|
|
const titleChangesByToolUseId = collectTitleChanges(normalized)
|
|
|
|
const traced = traceMessages(normalized)
|
|
const groups = new Map<string, TracedMessage[]>()
|
|
const root: TracedMessage[] = []
|
|
|
|
for (const msg of traced) {
|
|
if (msg.sidechainId) {
|
|
const existing = groups.get(msg.sidechainId) ?? []
|
|
existing.push(msg)
|
|
groups.set(msg.sidechainId, existing)
|
|
} else {
|
|
root.push(msg)
|
|
}
|
|
}
|
|
|
|
const consumedGroupIds = new Set<string>()
|
|
const emittedTitleChangeToolUseIds = new Set<string>()
|
|
const reducerContext = { permissionsById, groups, consumedGroupIds, titleChangesByToolUseId, emittedTitleChangeToolUseIds }
|
|
const rootResult = reduceTimeline(root, reducerContext)
|
|
let hasReadyEvent = rootResult.hasReadyEvent
|
|
|
|
// Synthesize a tool card only for a *pending* permission that is not
|
|
// rendered anywhere in the final block tree — so the user can still
|
|
// answer it when its tool_use message hasn't loaded. A resolved request
|
|
// (approved/denied/canceled) is history: agentState keeps it in
|
|
// completedRequests, but synthesizing it here appends a card to the end
|
|
// of the timeline (there is no chronological re-sort), pinning a stale
|
|
// "answered" card above the composer forever. Resolved requests render
|
|
// only via their own message, when it is in the window.
|
|
// Also skip if the permission is older than the oldest message in the
|
|
// current view, to avoid mixing old tool cards with newer messages when
|
|
// paginating.
|
|
//
|
|
// The check must walk the *rendered* tree (including blocks nested under
|
|
// Task/Agent cards), not raw transcript ids: the tracer drops sidechain
|
|
// messages it cannot attribute to a parent Task (no parentToolUseId and
|
|
// no prompt-holding sidechain root — e.g. background subagents), so a
|
|
// raw-id check suppresses this fallback for a card that was never
|
|
// rendered, leaving the pending permission answerable nowhere
|
|
// (hapi#1073).
|
|
const renderedToolBlockIds = new Set<string>()
|
|
const collectRenderedToolBlockIds = (list: ChatBlock[]): void => {
|
|
for (const block of list) {
|
|
if (block.kind !== 'tool-call') continue
|
|
renderedToolBlockIds.add(block.id)
|
|
collectRenderedToolBlockIds(block.children)
|
|
}
|
|
}
|
|
collectRenderedToolBlockIds(rootResult.blocks)
|
|
|
|
const oldestMessageTime = normalized.length > 0
|
|
? Math.min(...normalized.map(m => m.createdAt))
|
|
: null
|
|
|
|
for (const [id, entry] of permissionsById) {
|
|
if (entry.permission.status !== 'pending') continue
|
|
if (renderedToolBlockIds.has(id)) continue
|
|
|
|
const createdAt = entry.permission.createdAt ?? Date.now()
|
|
|
|
// Skip permissions that are older than the oldest message in the current view.
|
|
// These will be shown when the user loads older messages.
|
|
if (oldestMessageTime !== null && createdAt < oldestMessageTime) {
|
|
continue
|
|
}
|
|
|
|
ensureToolBlock(rootResult.blocks, rootResult.toolBlocksById, id, {
|
|
createdAt,
|
|
localId: null,
|
|
name: entry.toolName,
|
|
input: entry.input,
|
|
description: null,
|
|
permission: entry.permission
|
|
})
|
|
}
|
|
|
|
// Calculate latest usage from messages (find the most recent message with usage data)
|
|
let latestUsage: LatestUsage | null = null
|
|
for (let i = normalized.length - 1; i >= 0; i--) {
|
|
const msg = normalized[i]
|
|
if (msg.usage && isUsageVisibleInParentContext(msg) && hasContextUsageSignal(msg.usage)) {
|
|
latestUsage = {
|
|
inputTokens: msg.usage.input_tokens,
|
|
outputTokens: msg.usage.output_tokens,
|
|
cacheCreation: msg.usage.cache_creation_input_tokens ?? 0,
|
|
cacheRead: msg.usage.cache_read_input_tokens ?? 0,
|
|
contextSize: calculateContextSize(msg.usage),
|
|
contextWindow: msg.usage.context_window ?? null,
|
|
model: msg.model ?? null,
|
|
timestamp: msg.createdAt
|
|
}
|
|
break
|
|
}
|
|
}
|
|
|
|
return {
|
|
blocks: filterSilentGoalBlocks(dedupeAgentEvents(foldApiErrorEvents(rootResult.blocks))),
|
|
hasReadyEvent,
|
|
latestUsage,
|
|
latestGoal: getLatestThreadGoal(options.goalStateMessages ?? normalized)
|
|
}
|
|
}
|