Files
deepseek-harness/packages/compaction/compaction-basic/src/index.ts
T
Kexin Liu da3ba0f245 feat(agent-loop): recover inbox claims before step start (#9145)
* feat(agent-loop): recover inbox claims before step start

* fix(acp): withdraw pending prompts at settlement

* fix(goal): withdraw stale rounds when restoring agents

* refactor(agent-loop): fold inbox claims with the queue

* fix(agent-loop): preserve the inbox wire conversion

* refactor(agent-loop): clarify inbox projection updates

* refactor(agent-loop): keep inbox recovery internal

* refactor(agent-loop): simplify inbox recovery

* refactor(agent-loop): clarify inbox claim recovery

* refactor(agent-loop): clarify when input returns to inbox

* refactor(agent-loop): let the inbox own claim return

The inbox projection groups queues and claims symmetrically and
ReactLoopInbox decides whether a failed turn returns its claim from its
own clear() and claim() calls; the loop's running phase keeps no return
flag. Resume restores the interrupted claim through an unconditional
inbox call after announce. The projection tests become a transition
table and the two Agent Notes merge into one.

* fix(agent-loop): drop inherited claims at a fork's seed cut

A cold read of a crashed parent closes its open turn as interrupted
inside the inherited prefix, so the child projected the parent's claim
and restored it into its own queue. The inbox fold now empties both
claim lists at an inherited session/end-seed; a fork keeps the parent's
queue but never the input the parent had taken out of it.

* test(agent-loop): resume a stored fork of a crashed parent without reviving its claim

* fix(compaction-basic): check model-switch pressure at pre-step so a failed switch returns the input

The switch check ran in agent/request, after step/start had settled the
claimed batch, so a Stop, a failed summary, or an exit during that
summary lost the prompt. The step's route is already fixed at
agent/pre-step, where the inbox still owns the claim; the check now
prices the selected route there and the agent/request listener is gone.

* docs: regenerate the event graph after compaction-basic left agent/request

* fix(agent): keep the model-switch notice ahead of context snapshots

With the switch compaction at pre-step, the runtime-context snapshot is
already part of the admitted batch when the notice is added, so an
appended notice landed after it. The notice now precedes the first
context snapshot, keeping the order the model saw before; the
model-switch-compaction snapshot is refreshed for the compaction events
now preceding step/start.
2026-11-26 18:10:58 +08:00

507 lines
21 KiB
TypeScript

/**
* Basic replay-aware compaction backend.
*
* @module @deepseek-ai/dsh-compaction-basic
*/
import { Context, Service } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import { CompactionEngine, ManualCompactionError } from '@deepseek-ai/dsh-compaction'
import type { CompactionResult, CompactionTrigger } from '@deepseek-ai/dsh-compaction'
import type { EpochHeader, Session, SessionSeq } from '@deepseek-ai/dsh-session'
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
import { CONTEXT_WINDOW_EXCEEDED_CODE, LlmError } from '@deepseek-ai/dsh-llm'
import type { LlmCallConfig } from '@deepseek-ai/dsh-llm'
import { assertNever } from '@deepseek-ai/dsh-util-values'
import type { Agent, ModelSelection, PreStepDecision } from '@deepseek-ai/dsh-agent'
import type { CommandId } from '@deepseek-ai/dsh-commands/types'
// Type-only: makes the optional sibling service available to `ctx.get()`.
import type {} from '@deepseek-ai/dsh-compaction-tool-result-pruner'
import { answeredRouteProjectionDefinition } from './answered-route.ts'
import type { AnsweredRoute } from './answered-route.ts'
import {
resolveCompactSpec,
resolveConfig,
resolveTargetPolicy,
TargetPressureConfigError,
} from './config.ts'
import {
assertNoActiveCompaction,
compactSurfaceRegion,
selectCompactableRange,
} from './region.ts'
import { summarizeWithLlm } from './summarizer.ts'
import type { SummarizationInput, SummaryResult, SummaryRoute } from './summarizer.ts'
import type {
BasicCompactionConfig,
ModelCompactPolicyConfig,
ResolvedConfig,
} from './types.ts'
export type {
BasicCompactionConfig,
CompactionPolicyConfig,
ModelCompactPolicyConfig,
ResolvedCompactSpec,
ResolvedConfig,
ResolvedRetention,
ResolvedTargetPolicy,
} from './types.ts'
/** Detach a route that names both provider and model; any other value is no route. */
function completeRoute(route: { provider?: string; model?: string } | undefined): SummaryRoute | undefined {
if (route?.provider === undefined || route.provider.length === 0
|| route.model === undefined || route.model.length === 0) return undefined
return { provider: route.provider, model: route.model }
}
/**
* The header a step on a newly selected route will request under, or undefined
* when the selection keeps the latest durable route. The previous reasoning
* effort never carries over; a previous output cap carries over only when the
* caller set it, so the destination adapter materializes its own defaults.
*/
function switchedHeader(previous: EpochHeader | undefined, selection: Readonly<ModelSelection>): EpochHeader | undefined {
if (previous === undefined || completeRoute(previous.config) === undefined) return undefined
if (previous.config.provider === selection.provider && previous.config.model === selection.model) return undefined
const config: LlmCallConfig = { ...previous.config, ...selection }
if (selection.reasoningEffort === undefined) delete config.reasoningEffort
if (previous.adapterDefaults?.maxTokens === true) delete config.maxTokens
const header: EpochHeader = { ...previous, config }
delete header.adapterDefaults
return header
}
/** Resolve the exact provider/model durably routed for the latest request. */
function routedTarget(session: Session): SummaryRoute | undefined {
return completeRoute(session.requestHeader()?.config)
}
/**
* Output tokens the routed request reserves, which the provider charges to the
* same window as the prompt. The effective envelope's own cap wins; otherwise
* the adapter's per-request default, which the adapter materializes when that
* envelope omits one. No declared cap means no reservation.
*/
function reservedCompletionTokens(header: EpochHeader, defaultMaxTokens: number | undefined): number {
return header.config.maxTokens ?? defaultMaxTokens ?? 0
}
/**
* Resolve the route that summarizes the conversation and selects its policy
* override. The route that last answered already accepted this history; the
* latest header may name a route whose only request overflowed.
* @param agent - supplies the latest header and the live fallback options.
* @param answered - route recorded on the latest assistant message; `null` before the first one.
* @returns the first complete route among `answered`, the latest header, and the agent options.
*/
function conversationTarget(
agent: Agent,
answered: AnsweredRoute,
): SummaryRoute | undefined {
return completeRoute(answered ?? undefined) ?? routedTarget(agent.session) ?? completeRoute(agent.options)
}
const thresholdRatioSchema = z.number()
const headroomTokensSchema = z.number().step(1).min(0)
const retainRatioSchema = z.number()
const retainTokensSchema = z.number().step(1).min(0)
const summarizationProviderSchema = z.string()
const summarizationModelSchema = z.string()
const maxTokensSchema = z.number().step(1).min(1)
const compactionRetriesSchema = z.number().step(1).min(0)
const maxOverflowRetriesSchema = z.number().step(1).min(0)
const modelPolicy: z<ModelCompactPolicyConfig> = z.object({
provider: z.string().required(),
model: z.string().required(),
thresholdRatio: thresholdRatioSchema,
headroomTokens: headroomTokensSchema,
retainRatio: retainRatioSchema,
retainTokens: retainTokensSchema,
summarizationProvider: summarizationProviderSchema,
summarizationModel: summarizationModelSchema,
maxTokens: maxTokensSchema,
compactionRetries: compactionRetriesSchema,
maxOverflowRetries: maxOverflowRetriesSchema,
})
/**
* Dependency-light compaction backend using `ctx.tokenMeter` for pressure,
* retention, cited source events, and summary-convergence pricing.
*
* `summarize()` is the sole subclass customization hook; the replay and durable
* mutation strategy stays fixed so every pricing decision uses the singleton
* token meter.
*/
export class BasicCompactionEngine extends CompactionEngine {
static inject = ['llm', 'tokenMeter', 'sessions', 'sessionProjections']
static Config: z<BasicCompactionConfig> = z.object({
thresholdRatio: thresholdRatioSchema,
headroomTokens: headroomTokensSchema,
retainRatio: retainRatioSchema,
retainTokens: retainTokensSchema,
summarizationProvider: summarizationProviderSchema,
summarizationModel: summarizationModelSchema,
maxTokens: maxTokensSchema,
compactionRetries: compactionRetriesSchema,
maxOverflowRetries: maxOverflowRetriesSchema,
modelPolicies: z.array(modelPolicy),
auto: z.boolean(),
})
/** Resolved and validated compaction configuration. */
readonly config: ResolvedConfig
private readonly warnedPressureConfigTargets = new Set<string>()
private readonly overflowRetries = new WeakMap<Agent, number>()
private readonly overflowAgents = new WeakMap<Session, Agent>()
/** Registered at construction; `summarize()` awaits it, so no read precedes readiness. */
private readonly answeredRoute: Promise<ProjectionHandle<AnsweredRoute>>
constructor(ctx: Context, config: BasicCompactionConfig = {}) {
super(ctx)
this.config = resolveConfig(config)
this.answeredRoute = this.ctx.sessionProjections.register(answeredRouteProjectionDefinition)
if (this.config.auto) this._registerAutomaticCompaction()
}
/** Fail plugin activation when the answered-route projection cannot register. */
protected async [Service.init](): Promise<void> {
await this.answeredRoute
}
/**
* Register between-step pressure, model-switch pressure, and request-overflow
* recovery. Pressure and overflow dispatch through `compactIfNeeded`; a model
* switch prices the step's selected route at pre-step, before the claimed
* input is committed to the step. All summaries use `summarize`.
*/
private _registerAutomaticCompaction(): void {
const { ctx } = this
const logResult = (result: CompactionResult, trigger: string): void => {
ctx.logger.info(
`compaction (${trigger}): shadowed ${result.shadowedSeqs.length} surface nodes `
+ `(seqs ${result.shadowedRange.start}-${result.shadowedRange.end}, `
+ `~${result.shadowedTokenCount} tokens)`,
)
}
ctx.on('agent/pre-step', async (
{ agent, signal, modelSelection },
next,
): Promise<PreStepDecision> => {
if (signal.aborted) return next()
const switched = switchedHeader(agent.session.requestHeader(), modelSelection)
if (switched !== undefined) {
// The step's route is fixed here, and the claimed input is still
// recoverable: a failure returns it to the queue instead of losing it
// behind `step/start`. The previous route summarizes the history.
try {
const result = await this.compactPressure(agent, switched, signal, true)
if (result !== null) logResult(result, 'model switch')
} catch (error: unknown) {
signal.throwIfAborted()
const message = error instanceof Error ? error.message : String(error)
throw new LlmError(
`Cannot switch to ${modelSelection.provider}/${modelSelection.model}: context compaction failed: ${message}. `
+ 'The previous request model is preserved; retry or select a model with a larger context window.',
'MODEL_SWITCH_COMPACTION_FAILED',
{ cause: error },
)
}
return next()
}
try {
const result = await this.compactIfNeeded(agent, 'pressure', signal)
if (result !== null) logResult(result, 'step pressure')
} catch (error: unknown) {
if (error instanceof TargetPressureConfigError) {
if (this.warnedPressureConfigTargets.has(error.targetKey)) return next()
this.warnedPressureConfigTargets.add(error.targetKey)
}
const message = error instanceof Error ? error.message : String(error)
ctx.logger.warn(`step compaction failed: ${message}; continuing the turn`)
}
return next()
})
ctx.on('agent/status', ({ agent, status }) => {
if (status === 'idle') this.overflowRetries.delete(agent)
})
// A successful response starts a fresh overflow-recovery sequence even
// when tool calls continue the same turn into another request.
ctx.on('session/event', (session, event) => {
if (event.type !== 'assistant/message') return
const agent = this.overflowAgents.get(session)
if (agent !== undefined) this.overflowRetries.delete(agent)
})
ctx.on('agent/request-error', async (
{ agent, failure, signal },
next,
) => {
if (failure.code !== CONTEXT_WINDOW_EXCEEDED_CODE || signal.aborted) return next()
this.overflowAgents.set(agent.session, agent)
const target = routedTarget(agent.session)
if (target === undefined) return next()
const policy = resolveTargetPolicy(this.config, target)
const retries = this.overflowRetries.get(agent) ?? 0
if (retries >= policy.maxOverflowRetries) return next()
const generation = agent.session.surface.replaceGeneration
let result: CompactionResult | null
try {
result = await this.compactIfNeeded(agent, 'context-overflow', signal)
} catch (recoveryError: unknown) {
const message = recoveryError instanceof Error ? recoveryError.message : String(recoveryError)
// A model-free prune can land before later summary work fails. That
// durable reduction is sufficient retry proof; do not discard it just
// because the optional second phase threw. Cancellation still wins.
// oxlint-disable-next-line typescript/no-unnecessary-condition -- the signal can abort while recovery is awaited.
if (!signal.aborted && agent.session.surface.replaceGeneration > generation) {
ctx.logger.warn(
`context-overflow compaction failed after durable surface progress: ${message}; `
+ 'retrying from the replacement surface',
)
this.overflowRetries.set(agent, retries + 1)
return { kind: 'retry' }
}
ctx.logger.warn(
// oxlint-disable-next-line typescript/no-unnecessary-condition -- the signal can abort while recovery is awaited.
`context-overflow compaction failed: ${message}; ${signal.aborted
? 'cancellation prevents retry'
: 'preserving the original request error'}`,
)
return next()
}
// oxlint-disable-next-line typescript/no-unnecessary-condition -- the signal can abort while compaction is awaited.
if (signal.aborted
|| agent.session.surface.replaceGeneration <= generation) return next()
if (result !== null) logResult(result, 'context overflow recovery')
this.overflowRetries.set(agent, retries + 1)
return { kind: 'retry' }
})
}
/**
* Summarize the replayed conversation region through a direct one-shot
* `ctx.llm.stream()` call whose prefix reuses the conversation's own system
* prompt, tools, and messages so the provider's KV cache is not invalidated.
* Without a configured summary target the call goes to the route recorded
* on the latest assistant message, then the latest request header, then the
* agent options. A model selected for a later request is not used.
* Override this sole hook for a template or remote summarizer.
* @param input - replayed conversation prefix (system, tools, and leading messages) to condense.
* @param agent - supplies the session history, fallback model, and session id.
* @param signal - optional cancellation forwarded to the adapter.
* @returns safe text summary blocks and the exact auxiliary call envelope and output.
*/
protected async summarize(
input: SummarizationInput,
agent: Agent,
signal?: AbortSignal,
): Promise<SummaryResult> {
const target = conversationTarget(agent, (await this.answeredRoute).stateOf(agent.session))
const config = target === undefined
? this.config
: resolveTargetPolicy(this.config, target)
return summarizeWithLlm(this.ctx, config, input, agent, target, signal)
}
/**
* Compact for replayed step-boundary pressure or one provider-confirmed context
* overflow. Both triggers price the latest durable routed request envelope;
* overflow bypasses the normal threshold and retained-tail policy so it can
* force one useful balanced reduction.
* @param agent - agent whose latest durable routed request is measured.
* @param trigger - normal step-boundary pressure or context-overflow recovery.
* @param signal - live turn cancellation signal forwarded to summarization.
* @returns the latest summary compaction result, or `null` when no summary ran.
*/
override async compactIfNeeded(
agent: Agent,
trigger: CompactionTrigger,
signal: AbortSignal,
): Promise<CompactionResult | null> {
const header = agent.session.requestHeader()
if (header === undefined || routedTarget(agent.session) === undefined) return null
switch (trigger) {
case 'pressure':
return this.compactPressure(agent, header, signal, false)
case 'context-overflow': {
this.ctx.get('toolResultPruner')?.pruneSession(agent.session)
const measurement = this.ctx.tokenMeter.measure(agent.session)
const range = selectCompactableRange(agent.session, measurement, 0)
if (range === null) return null
return this.compactRegion(range.start, range.end, agent, signal)
}
/* v8 ignore next -- closed-union exhaustiveness guard */
default:
assertNever(trigger, 'compaction trigger')
}
}
/** Price the proposed header; switch checks require history below its threshold. */
private async compactPressure(
agent: Agent,
header: EpochHeader,
signal: AbortSignal,
requireBelowThreshold: boolean,
): Promise<CompactionResult | null> {
const target = header.config
const policy = resolveTargetPolicy(this.config, target)
const meter = this.ctx.tokenMeter
let measurement = meter.measure(agent.session, header)
const prune = this.ctx.get('toolResultPruner')
const info = await this.ctx.llm.resolveModelInfo(target.provider, target.model, signal)
assertNoActiveCompaction(agent.session, 'automatic pressure compaction')
const targetKey = `${target.provider}/${target.model}`
if (info.context === undefined) {
throw new TargetPressureConfigError(
targetKey,
`compaction-basic: no context capacity for ${targetKey}; `
+ 'configure contextWindow on that adapter model',
)
}
const spec = resolveCompactSpec(
policy,
info.context.contextWindow,
reservedCompletionTokens(header, info.defaultMaxTokens),
)
if (measurement.totalTokens < spec.thresholdTokens) return null
// Once pressure qualifies, land the model-free pass before choosing a
// summary range, then remeasure through the singleton replay fold.
if (prune !== undefined) {
prune.pruneSession(agent.session)
measurement = meter.measure(agent.session, header)
}
if (measurement.totalTokens < spec.thresholdTokens) return null
let result: CompactionResult | null = null
for (let attempt = 0; attempt <= spec.compactionRetries; attempt += 1) {
const range = selectCompactableRange(agent.session, measurement, spec.retainTokens)
if (range === null) {
if (result === null && !requireBelowThreshold) return null
throw new Error(
'no safe compaction range can reduce context below threshold '
+ `(${measurement.totalTokens} estimated tokens >= threshold ${spec.thresholdTokens})`,
)
}
result = await this.compactRegion(range.start, range.end, agent, signal)
measurement = meter.measure(agent.session, header)
if (measurement.totalTokens < spec.thresholdTokens) return result
}
throw new Error(
`compaction still above threshold after ${spec.compactionRetries + 1} compaction attempts `
+ `(${measurement.totalTokens} estimated tokens >= threshold ${spec.thresholdTokens})`,
)
}
/**
* Compact one inclusive positional range from the agent-owned surface using
* the effective token meter for all retention and shrink pricing.
* @param start - inclusive first surface-node seq.
* @param end - inclusive last surface-node seq.
* @param agent - owner of the target session, used by the summarizer.
* @param signal - optional summarization cancellation signal.
* @returns the successful durable compaction result.
*/
override async compactRegion(
start: SessionSeq,
end: SessionSeq,
agent: Agent,
signal?: AbortSignal,
): Promise<CompactionResult> {
return compactSurfaceRegion(
this.regionDependencies(),
agent.session,
start,
end,
agent,
{ owner: 'current-turn', stability: 'whole-surface' },
signal,
)
}
/**
* Force one useful idle-session compaction below the pressure threshold, and
* resolve only after its standalone marker pair is durably checkpointed.
* @param agent - idle agent whose next-turn admission this call reserves.
* @param signal - cancellation scoped to this compaction request.
* @param sourceCommandId - initiating command identity for presentation correlation.
* @returns the committed result, or `null` when no safe useful range exists.
*/
override compactNow(
agent: Agent,
signal: AbortSignal,
sourceCommandId?: CommandId,
): Promise<CompactionResult | null> {
signal.throwIfAborted()
try {
return agent.runMaintenance(async (agentSignal) => {
const operationSignal = AbortSignal.any([agentSignal, signal])
try {
operationSignal.throwIfAborted()
const range = selectCompactableRange(
agent.session,
this.ctx.tokenMeter.measure(agent.session),
0,
)
if (range === null) return null
return await compactSurfaceRegion(
this.regionDependencies(),
agent.session,
range.start,
range.end,
agent,
{
owner: null,
stability: 'selected-span',
...sourceCommandId === undefined ? {} : { sourceCommandId },
flush: async () => {
await this.ctx.sessions.flush(agent.session)
},
},
operationSignal,
)
} catch (error: unknown) {
if (agentSignal.aborted && operationSignal.reason === agentSignal.reason) {
throw new ManualCompactionError(
'cancelled',
'manual compaction was cancelled',
{ cause: error },
)
}
operationSignal.throwIfAborted()
throw error
}
})
} catch (error: unknown) {
throw new ManualCompactionError(
'busy',
'manual compaction requires an idle agent with no waking queued work',
{ cause: error },
)
}
}
/** Bind the effective token meter and dynamically dispatched summarizer hook. */
private regionDependencies(): Parameters<typeof compactSurfaceRegion>[0] {
return {
meter: this.ctx.tokenMeter,
summarize: (input, owner, abort) => this.summarize(input, owner, abort),
recover: (error, agent, sourceEventSeqs, signal) => this.ctx.waterfall('compaction/summary-error', {
session: agent.session,
sourceEventSeqs,
error,
...signal === undefined ? {} : { signal },
}, () => false),
}
}
}
export default BasicCompactionEngine