mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-17 22:05:50 +00:00
* fix: bound agent communication memory growth UDS messaging now uses private local capabilities instead of exposing auth tokens through SDK metadata, environment variables, session registry, peer listing, or tool output. The receive path bounds NDJSON frames, response buffers, active clients, and pending inbox bytes, and strips auth metadata before messages enter the prompt queue. Teammate mailboxes now validate file and message sizes, fail closed on corrupt mutation inputs, compact by count and retained bytes, and use stable message identity for in-process acknowledgements. Agent summaries now fork only a bounded recent context using lazy size estimation and content fingerprints instead of retaining or serializing unbounded histories. Constraint: PR #361 was already merged; this branch is based on upstream/main@c2ac9a74. Rejected: Default-disabling COORDINATOR_MODE/TEAMMEM only | explicit feature enablement still hit unbounded paths. Rejected: Persisting UDS auth in SDK/env/session registry | bridge/remote metadata can leak local capability secrets. Rejected: Inline uds #token addresses | observable/tool/classifier paths can reflect raw addresses outside the UDS request frame. Rejected: Positional mailbox marking after compaction | compaction can shift indices across the lock boundary. Confidence: high Scope-risk: moderate Directive: Do not expose UDS capability tokens through SDK messages, environment variables, session registry, peer-list output, or SendMessage result/classifier surfaces. Directive: Do not reintroduce positional mailbox acknowledgements unless compaction is removed or read+mark is atomic under one lock. Tested: bun test src/utils/__tests__/ndjsonFramer.test.ts src/utils/__tests__/udsMessaging.test.ts packages/builtin-tools/src/tools/SendMessageTool/__tests__/udsRecipientSanitization.test.ts Tested: bunx tsc --noEmit --pretty false Tested: bun run lint Tested: bunx biome lint modified src/package files Tested: bun run test:all (3704 pass, 0 fail, 6734 expects) Tested: bun audit (No vulnerabilities found) Tested: bun run build Tested: bun run build:vite Tested: git diff --check Not-tested: End-to-end external UDS client driving a full production headless model turn. * fix: harden bounded agent communication review fixes CodeRabbit and Codecov surfaced real gaps in UDS framing, peer discovery, mailbox retention, and summary context coverage. This tightens those paths without suppressing review or coverage signals. Constraint: PR #369 must address CodeRabbit and Codecov findings without warning suppression or fake fallbacks Rejected: Suppress Codecov or CodeRabbit warnings | leaves real receive-path and test-isolation gaps Rejected: Add unreachable feature-gated tests | bun:bundle keeps those branches compile-time gated in local tests Confidence: high Scope-risk: moderate Directive: Keep UDS auth-token rejection outside feature flags; do not reintroduce inline token fallbacks Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage; bun run test:all; bun run lint; bun run build; bun run build:vite; bun audit; git diff --cached --check Not-tested: Remote Codecov/CodeRabbit refreshed reports until pushed * fix: prevent agent communication bounds from hiding CI regressions Tighten the UDS auth, framing, and response-reader boundaries while keeping the AgentSummary lifecycle covered so Codecov and CI fail on real regressions instead of missing coverage. The poorMode settings mock mirrors unrelated real settings defaults to avoid Bun mock retention changing later permission tests. Constraint: PR #369 must fix Codecov/CI precisely without warning suppression, fallback masking, or mock pollution Rejected: Delete AgentSummary lifecycle coverage | would hide Codecov loss and stale-summary behavior Rejected: Store inline UDS rejection in a hidden input sentinel | cloned observable inputs can drop it and bypass rejection Rejected: Ignore malformed UDS frames until timeout | leaves client slots and SendMessage calls open to exhaustion Confidence: high Scope-risk: moderate Directive: Keep empty #token= markers rejected; do not require a non-empty token value in hasInlineUdsToken Tested: bun test packages/builtin-tools/src/tools/SendMessageTool/__tests__/udsRecipientSanitization.test.ts src/utils/__tests__/udsMessaging.test.ts src/utils/__tests__/udsResponseReader.test.ts src/utils/__tests__/ndjsonFramer.test.ts Tested: bunx tsc --noEmit --pretty false Tested: bun run lint Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage Tested: bun run test:all Tested: bun audit Tested: bun run build Tested: bun run build:vite Not-tested: GitHub-hosted Codecov upload until pushed PR checks rerun --------- Co-authored-by: unraid <local@unraid.local>
215 lines
7.5 KiB
TypeScript
215 lines
7.5 KiB
TypeScript
/**
|
|
* Periodic background summarization for coordinator mode sub-agents.
|
|
*
|
|
* Forks the sub-agent's conversation every ~30s using runForkedAgent()
|
|
* to generate a 1-2 sentence progress summary. The summary is stored
|
|
* on AgentProgress for UI display.
|
|
*
|
|
* Cache sharing: uses the same CacheSafeParams as the parent agent
|
|
* to share the prompt cache. Tools are kept in the request for cache
|
|
* key matching but denied via canUseTool callback.
|
|
*/
|
|
|
|
import type { TaskContext } from '../../Task.js'
|
|
import { isPoorModeActive } from '../../commands/poor/poorMode.js'
|
|
import { updateAgentSummary } from '../../tasks/LocalAgentTask/LocalAgentTask.js'
|
|
import type { AgentId } from '../../types/ids.js'
|
|
import { logForDebugging } from '../../utils/debug.js'
|
|
import {
|
|
type CacheSafeParams,
|
|
runForkedAgent,
|
|
} from '../../utils/forkedAgent.js'
|
|
import { logError } from '../../utils/log.js'
|
|
import { getAgentTranscript } from '../../utils/sessionStorage.js'
|
|
import { buildSummaryContext } from './summaryContext.js'
|
|
import {
|
|
buildSummaryPrompt,
|
|
createSummaryPromptMessage,
|
|
} from './summaryPrompt.js'
|
|
|
|
const SUMMARY_INTERVAL_MS = 30_000
|
|
|
|
export type AgentSummaryDependencies = Partial<{
|
|
clearTimeout: typeof clearTimeout
|
|
getAgentTranscript: typeof getAgentTranscript
|
|
isPoorModeActive: typeof isPoorModeActive
|
|
logError: typeof logError
|
|
logForDebugging: typeof logForDebugging
|
|
runForkedAgent: typeof runForkedAgent
|
|
setTimeout: typeof setTimeout
|
|
updateAgentSummary: typeof updateAgentSummary
|
|
}>
|
|
|
|
export function startAgentSummarization(
|
|
taskId: string,
|
|
agentId: AgentId,
|
|
cacheSafeParams: CacheSafeParams,
|
|
setAppState: TaskContext['setAppState'],
|
|
dependencies: AgentSummaryDependencies = {},
|
|
): { stop: () => void } {
|
|
// Drop forkContextMessages from the closure — runSummary rebuilds it each
|
|
// tick from getAgentTranscript(). Without this, the original fork messages
|
|
// (passed from AgentTool.tsx) are pinned for the lifetime of the timer.
|
|
const { forkContextMessages: _drop, ...baseParams } = cacheSafeParams
|
|
let summaryAbortController: AbortController | null = null
|
|
let timeoutId: ReturnType<typeof setTimeout> | null = null
|
|
let stopped = false
|
|
let previousSummary: string | null = null
|
|
let lastHandledTranscriptFingerprint: string | null = null
|
|
const clearTimeoutImpl = dependencies.clearTimeout ?? clearTimeout
|
|
const getAgentTranscriptImpl =
|
|
dependencies.getAgentTranscript ?? getAgentTranscript
|
|
const isPoorModeActiveImpl =
|
|
dependencies.isPoorModeActive ?? isPoorModeActive
|
|
const logErrorImpl = dependencies.logError ?? logError
|
|
const logForDebuggingImpl =
|
|
dependencies.logForDebugging ?? logForDebugging
|
|
const runForkedAgentImpl = dependencies.runForkedAgent ?? runForkedAgent
|
|
const setTimeoutImpl = dependencies.setTimeout ?? setTimeout
|
|
const updateAgentSummaryImpl =
|
|
dependencies.updateAgentSummary ?? updateAgentSummary
|
|
|
|
async function runSummary(): Promise<void> {
|
|
if (stopped) return
|
|
if (isPoorModeActiveImpl()) {
|
|
logForDebuggingImpl('[AgentSummary] Skipping summary — poor mode active')
|
|
scheduleNext()
|
|
return
|
|
}
|
|
|
|
logForDebuggingImpl(`[AgentSummary] Timer fired for agent ${agentId}`)
|
|
|
|
try {
|
|
// Read current messages from transcript
|
|
const transcript = await getAgentTranscriptImpl(agentId)
|
|
if (!transcript || transcript.messages.length < 3) {
|
|
// Not enough context yet — finally block will schedule next attempt
|
|
logForDebuggingImpl(
|
|
`[AgentSummary] Skipping summary for ${taskId}: not enough messages (${transcript?.messages.length ?? 0})`,
|
|
)
|
|
return
|
|
}
|
|
|
|
const summaryContext = buildSummaryContext(
|
|
transcript.messages,
|
|
lastHandledTranscriptFingerprint,
|
|
)
|
|
if (summaryContext.skipReason === 'unchanged') {
|
|
logForDebuggingImpl(
|
|
`[AgentSummary] Skipping summary for ${taskId}: transcript unchanged`,
|
|
)
|
|
return
|
|
}
|
|
|
|
if (summaryContext.skipReason === 'too_small') {
|
|
logForDebuggingImpl(
|
|
`[AgentSummary] Skipping summary for ${taskId}: no bounded context available`,
|
|
)
|
|
return
|
|
}
|
|
|
|
// Build fork params with current messages
|
|
const forkParams: CacheSafeParams = {
|
|
...baseParams,
|
|
forkContextMessages: summaryContext.messages,
|
|
}
|
|
|
|
logForDebuggingImpl(
|
|
`[AgentSummary] Forking for summary, ${summaryContext.messages.length} messages in context`,
|
|
)
|
|
|
|
// Create abort controller for this summary
|
|
summaryAbortController = new AbortController()
|
|
|
|
// Deny tools via callback, NOT by passing tools:[] - that busts cache
|
|
const canUseTool = async () => ({
|
|
behavior: 'deny' as const,
|
|
message: 'No tools needed for summary',
|
|
decisionReason: { type: 'other' as const, reason: 'summary only' },
|
|
})
|
|
|
|
// DO NOT set maxOutputTokens here. The fork piggybacks on the main
|
|
// thread's prompt cache by sending identical cache-key params (system,
|
|
// tools, model, messages prefix, thinking config). Setting maxOutputTokens
|
|
// would clamp budget_tokens, creating a thinking config mismatch that
|
|
// invalidates the cache.
|
|
//
|
|
// ContentReplacementState is cloned by default in createSubagentContext
|
|
// from forkParams.toolUseContext (the subagent's LIVE state captured at
|
|
// onCacheSafeParams time). No explicit override needed.
|
|
const result = await runForkedAgentImpl({
|
|
promptMessages: [
|
|
createSummaryPromptMessage(buildSummaryPrompt(previousSummary)),
|
|
],
|
|
cacheSafeParams: forkParams,
|
|
canUseTool,
|
|
querySource: 'agent_summary',
|
|
forkLabel: 'agent_summary',
|
|
overrides: { abortController: summaryAbortController },
|
|
skipTranscript: true,
|
|
})
|
|
|
|
if (stopped) return
|
|
|
|
// Extract summary text from result
|
|
for (const msg of result.messages) {
|
|
if (msg.type !== 'assistant') continue
|
|
// Skip API error messages
|
|
if (msg.isApiErrorMessage) {
|
|
logForDebugging(
|
|
`[AgentSummary] Skipping API error message for ${taskId}`,
|
|
)
|
|
continue
|
|
}
|
|
const contentArr = Array.isArray(msg.message!.content)
|
|
? msg.message!.content
|
|
: []
|
|
const textBlock = contentArr.find(b => b.type === 'text')
|
|
if (textBlock?.type === 'text' && textBlock.text.trim()) {
|
|
const summaryText = textBlock.text.trim()
|
|
logForDebuggingImpl(
|
|
`[AgentSummary] Summary result for ${taskId}: ${summaryText}`,
|
|
)
|
|
lastHandledTranscriptFingerprint = summaryContext.fingerprint
|
|
previousSummary = summaryText
|
|
updateAgentSummaryImpl(taskId, summaryText, setAppState)
|
|
break
|
|
}
|
|
}
|
|
} catch (e) {
|
|
if (!stopped && e instanceof Error) {
|
|
logErrorImpl(e)
|
|
}
|
|
} finally {
|
|
summaryAbortController = null
|
|
// Reset timer on completion (not initiation) to prevent overlapping summaries
|
|
if (!stopped) {
|
|
scheduleNext()
|
|
}
|
|
}
|
|
}
|
|
|
|
function scheduleNext(): void {
|
|
if (stopped) return
|
|
timeoutId = setTimeoutImpl(runSummary, SUMMARY_INTERVAL_MS)
|
|
}
|
|
|
|
function stop(): void {
|
|
logForDebuggingImpl(`[AgentSummary] Stopping summarization for ${taskId}`)
|
|
stopped = true
|
|
if (timeoutId) {
|
|
clearTimeoutImpl(timeoutId)
|
|
timeoutId = null
|
|
}
|
|
if (summaryAbortController) {
|
|
summaryAbortController.abort()
|
|
summaryAbortController = null
|
|
}
|
|
}
|
|
|
|
// Start the first timer
|
|
scheduleNext()
|
|
|
|
return { stop }
|
|
}
|