Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/design/2026-12-04-context-claim-recovery.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Agent 上下文证据引用纠错

适用于执行态的上下文声明。证据不存在、已失效,或依赖声明已失效时,运行时拒绝本批声明,可以在同一次任务里重新确认依据。

## 行为

- 首次拒绝后,整次运行最多再请求模型两轮。普通工具调用、空声明和无进展的回答都会占用这两轮,成功登记修正后的声明也不会返还已用额度。调用者配置不限轮数时,此额度仍然生效。
- 取消、新输入和实际并发或存储故障走既有处理路径。常规任务预算先耗尽时保留原有停止原因。纠错不能使用为普通工具回执预留的追加轮次。
- 引用被拒绝就撤回当轮草稿,清掉待拼接正文,保留已经确认的证据和已经执行的工具结果。同批被拦下的工具只产生内部回执。
- 后续模型请求携带配对的工具调用与拒绝回执,工具入参使用空声明,错误回执包含原因和最多三个相关编号。纠错消息只在当前运行有待修正时存在。
- 改正后恢复正常完成校验。额度用尽时由运行时结束,用户只看到「没能确认完成任务所需的依据」,没有未经校验的回答。只读路径沿用原有处理方式。

## 验收

| 场景 | 预期 |
| -------------------------------- | ------------------------------------------------------ |
| 首次登记或修正成功 | 已执行工具只跑一次,最终回复仍经过完成校验 |
| 连续三次提交无效引用 | 第三次失败后停止,失败正文和被拦操作的回执没有公开输出 |
| 穿插工具结果、空声明或无进展回复 | 已完成结果保留,两轮额度继续累计 |
| 上下文窗口接近上限 | 回执保持配对,省去原声明,下一轮可准备 |
| 常规任务预算提前触顶 | 保留原停止原因,结果给出通用说明 |
| 取消、新请求、真实存储或并发错误 | 优先沿用原有处理路径 |
9 changes: 6 additions & 3 deletions packages/core/src/agent/moss-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2649,9 +2649,12 @@ ${result.stderr ?? ''}`.trim();
{ sessionKey, runId: `${runId}:compact` },
(usage) => versionedStore.recordSummaryUsage(sessionKey, runId, usage)
),
...(extraContext
? { ephemeral: [{ role: 'user', timestamp: Date.now(), content: extraContext }] }
: {}),
ephemeral: [
...(input.ephemeral ?? []),
...(extraContext
? [{ role: 'user' as const, timestamp: Date.now(), content: extraContext }]
: []),
],
});
input.repairSignal?.throwIfAborted();
contextGeneration = projection.revision;
Expand Down
92 changes: 25 additions & 67 deletions packages/core/src/loop/agent-loop-compaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
runWithCompactionPrepareTimeout,
} from './compaction-timeout.js';
import { notifyReadContextDropped } from '@rdk-moss/context/read-context-events.js';
import type { AgentLoopLlmUsage } from './agent-loop-types.js';
import type { AgentLoopDeps } from './agent-loop-types.js';

/** Distinct tool names across tool_use blocks (summary quality signal). */
function countDistinctToolNames(messages: Message[]): number {
Expand All @@ -32,25 +32,7 @@ function countDistinctToolNames(messages: Message[]): number {
return names.size;
}

export interface AgentLoopPrepareCompaction {
(params: {
messages: Message[];
sessionKey: string;
runId: string;
forceCompaction?: boolean;
includeThinking?: boolean;
/** Retry path only: skip the LLM summarizer and use the local deterministic one. */
skipLlmCompaction?: boolean;
abortSignal?: AbortSignal;
}): Promise<{
summary?: string;
summaryMessage?: Message;
messages?: Message[];
droppedMessages?: number;
checkpointOutline?: string[];
usage?: AgentLoopLlmUsage[];
}>;
}
export type AgentLoopPrepareCompaction = AgentLoopDeps['prepareCompaction'];

export interface AgentLoopCompactionOutcome {
attempted: boolean;
Expand All @@ -61,7 +43,7 @@ export interface AgentLoopCompactionOutcome {
degraded?: boolean;
}

interface CompactionCoreParams {
interface CompactionInput {
sessionKey: string;
runId: string;
currentMessages: Message[];
Expand All @@ -71,11 +53,12 @@ interface CompactionCoreParams {
push: (event: MiniAgentEvent) => void;
onWarn?: (message: string, meta: Record<string, unknown>) => void;
abortSignal?: AbortSignal;
includeThinking?: boolean;
}

interface CompactionCoreParams extends CompactionInput {
forceCompaction?: boolean;

includeThinking?: boolean;

hookReason: 'proactive' | 'overflow';

computeStats: (prep: { summary: string; summaryMessage: Message; droppedMessages?: number }) => {
Expand Down Expand Up @@ -125,20 +108,23 @@ async function runCompactionCore(
// as degraded so the transcript says the summary is not the LLM's.
let degraded = false;
const prepareStartedAt = Date.now();
let prep: Awaited<ReturnType<AgentLoopPrepareCompaction>>;
try {
prep = await runWithCompactionPrepareTimeout(
const prepare = (skipLlmCompaction?: true) =>
runWithCompactionPrepareTimeout(
(prepareAbortSignal) =>
prepareCompaction({
messages: currentMessages,
sessionKey,
runId,
forceCompaction,
includeThinking,
...(skipLlmCompaction ? { skipLlmCompaction } : {}),
abortSignal: prepareAbortSignal,
}),
{ abortSignal, label: errorLabel }
{ abortSignal, label: skipLlmCompaction ? `${errorLabel}-deterministic` : errorLabel }
);
let prep: Awaited<ReturnType<AgentLoopPrepareCompaction>>;
try {
prep = await prepare();
} catch (error) {
if (!isCompactionPrepareTimeout(error) || abortSignal?.aborted) throw error;
const timeoutMs = resolveCompactionPrepareTimeoutMs();
Expand All @@ -151,19 +137,7 @@ async function runCompactionCore(
sessionKey,
});
degraded = true;
prep = await runWithCompactionPrepareTimeout(
(prepareAbortSignal) =>
prepareCompaction({
messages: currentMessages,
sessionKey,
runId,
forceCompaction,
includeThinking,
skipLlmCompaction: true,
abortSignal: prepareAbortSignal,
}),
{ abortSignal, label: `${errorLabel}-deterministic` }
);
prep = await prepare(true);
}

const checkpointOutline =
Expand Down Expand Up @@ -278,20 +252,12 @@ async function runCompactionCore(
}
}

export async function runProactiveWindowCompaction(params: {
sessionKey: string;
runId: string;
currentMessages: Message[];
rawTotalChars: number;
promptUnitsForWindow: number;
prepareCompaction: AgentLoopPrepareCompaction;
compactHooks?: CompactHookRegistry;
persistCurrentMessages: (messages?: Message[]) => Promise<void>;
push: (event: MiniAgentEvent) => void;
onWarn?: (message: string, meta: Record<string, unknown>) => void;
abortSignal?: AbortSignal;
includeThinking?: boolean;
}): Promise<AgentLoopCompactionOutcome> {
export async function runProactiveWindowCompaction(
params: CompactionInput & {
rawTotalChars: number;
promptUnitsForWindow: number;
}
): Promise<AgentLoopCompactionOutcome> {
const { rawTotalChars, promptUnitsForWindow } = params;
return runCompactionCore({
...params,
Expand All @@ -313,19 +279,11 @@ export async function runProactiveWindowCompaction(params: {
});
}

export async function runPromptPruneCompaction(params: {
sessionKey: string;
runId: string;
currentMessages: Message[];
droppedMessagesForStats: Message[];
prepareCompaction: AgentLoopPrepareCompaction;
compactHooks?: CompactHookRegistry;
persistCurrentMessages: (messages?: Message[]) => Promise<void>;
push: (event: MiniAgentEvent) => void;
onWarn?: (message: string, meta: Record<string, unknown>) => void;
abortSignal?: AbortSignal;
includeThinking?: boolean;
}): Promise<AgentLoopCompactionOutcome> {
export async function runPromptPruneCompaction(
params: CompactionInput & {
droppedMessagesForStats: Message[];
}
): Promise<AgentLoopCompactionOutcome> {
const { droppedMessagesForStats } = params;
return runCompactionCore({
...params,
Expand Down
23 changes: 4 additions & 19 deletions packages/core/src/loop/agent-loop-context-prep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type { CompactHookRegistry } from './compact-hooks.js';
import type { ContextPruningSettings, PruneResult } from '@rdk-moss/context/pruning.js';
import type { AgentLoopMutableState } from './agent-loop-state.js';
import type { AgentLoopCompactionOutcome } from './agent-loop-compaction.js';
import type { AgentLoopLlmUsage } from './agent-loop-types.js';
import type { AgentLoopDeps } from './agent-loop-types.js';
import {
estimateMessageChars,
estimateMessageTokens,
Expand Down Expand Up @@ -214,22 +214,7 @@ export interface PrepareTurnContextParams {
getToolsForRun: () => Tool[];
sessionKey: string;
runId: string;
prepareCompaction: (params: {
messages: Message[];
sessionKey: string;
runId: string;
forceCompaction?: boolean;
includeThinking?: boolean;
skipLlmCompaction?: boolean;
abortSignal?: AbortSignal;
}) => Promise<{
summary?: string;
summaryMessage?: Message;
messages?: Message[];
droppedMessages?: number;
checkpointOutline?: string[];
usage?: AgentLoopLlmUsage[];
}>;
prepareCompaction: AgentLoopDeps['prepareCompaction'];
compactHooks?: CompactHookRegistry;
persistCurrentMessages: (messages?: Message[]) => Promise<void>;
push: (event: MiniAgentEvent) => void;
Expand Down Expand Up @@ -299,7 +284,7 @@ export async function prepareTurnContext(
toolOrderChecks: 0,
toolOrderChanges: 0,
};
const pendingToolResultFollowUp = lastMessageEndsWithToolResult(currentMessages);
const pendingToolResultFollowUp = lastMessageNeedsToolFollowUpLlm(currentMessages);
const includeThinkingInBudget = shouldIncludeThinkingInBudget(currentMessages, modelDef);

let estPromptTokens = estimatePromptUnitsForContextWindow({
Expand Down Expand Up @@ -564,7 +549,7 @@ export async function prepareTurnContext(
};
}

function lastMessageEndsWithToolResult(messages: Message[]): boolean {
export function lastMessageNeedsToolFollowUpLlm(messages: Message[]): boolean {
const last = messages[messages.length - 1];
if (!last || last.role !== 'user') return false;
const c = last.content;
Expand Down
19 changes: 2 additions & 17 deletions packages/core/src/loop/agent-loop-llm-call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { totalPromptTokens } from '@rdk-moss/ai/llm/usage.js';
import { runAgentLoopLlmTurn } from './agent-loop-stream-helpers.js';
import { runOverflowRecovery } from './overflow-recovery.js';
import type { LoopControlSignal } from './agent-loop-context-prep.js';
import type { AgentLoopLlmUsage } from './agent-loop-types.js';
import type { AgentLoopDeps } from './agent-loop-types.js';

export interface ExecuteLlmTurnParams {
state: AgentLoopMutableState;
Expand All @@ -39,22 +39,7 @@ export interface ExecuteLlmTurnParams {
runStartMs: number;
push: (event: MiniAgentEvent) => void;
currentMessages: Message[];
prepareCompaction: (params: {
messages: Message[];
sessionKey: string;
runId: string;
forceCompaction?: boolean;
includeThinking?: boolean;
skipLlmCompaction?: boolean;
abortSignal?: AbortSignal;
}) => Promise<{
summary?: string;
summaryMessage?: Message;
messages?: Message[];
droppedMessages?: number;
checkpointOutline?: string[];
usage?: AgentLoopLlmUsage[];
}>;
prepareCompaction: AgentLoopDeps['prepareCompaction'];
replaceMessages?: (sessionKey: string, messages: Message[]) => Promise<void>;
compactHooks?: CompactHookRegistry;
lastMessageNeedsToolFollowUpLlm: (messages: Message[]) => boolean;
Expand Down
Loading
Loading