@librechat/agents 4.1.1 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/AgentContext.cjs +9 -1
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/constants.cjs +2 -0
- package/dist/cjs/common/constants.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +15 -12
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +1 -1
- package/dist/cjs/hitl/approvalReview.cjs +10 -2
- package/dist/cjs/hitl/approvalReview.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/defaults.cjs +12 -0
- package/dist/cjs/llm/anthropic/defaults.cjs.map +1 -0
- package/dist/cjs/llm/anthropic/index.cjs +6 -0
- package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +1 -1
- package/dist/cjs/llm/google/utils/common.cjs +1 -1
- package/dist/cjs/llm/init.cjs +5 -2
- package/dist/cjs/llm/init.cjs.map +1 -1
- package/dist/cjs/llm/invoke.cjs +17 -15
- package/dist/cjs/llm/invoke.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/llm/request.cjs +13 -0
- package/dist/cjs/llm/request.cjs.map +1 -1
- package/dist/cjs/llm/stream/chunkAdapters.cjs +2 -3
- package/dist/cjs/llm/stream/chunkAdapters.cjs.map +1 -1
- package/dist/cjs/llm/truncation.cjs +12 -2
- package/dist/cjs/llm/truncation.cjs.map +1 -1
- package/dist/cjs/main.cjs +7 -4
- package/dist/cjs/messages/core.cjs +1 -1
- package/dist/cjs/messages/format.cjs +1 -1
- package/dist/cjs/messages/index.cjs +1 -1
- package/dist/cjs/messages/prune.cjs +2 -2
- package/dist/cjs/messages/reasoningTypes.cjs +20 -0
- package/dist/cjs/messages/reasoningTypes.cjs.map +1 -1
- package/dist/cjs/messages/recency.cjs +68 -7
- package/dist/cjs/messages/recency.cjs.map +1 -1
- package/dist/cjs/run.cjs +135 -54
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/session/AgentSession.cjs +7 -10
- package/dist/cjs/session/AgentSession.cjs.map +1 -1
- package/dist/cjs/stream.cjs +3 -2
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/summarization/input.cjs +87 -0
- package/dist/cjs/summarization/input.cjs.map +1 -0
- package/dist/cjs/summarization/node.cjs +470 -135
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/summarization/retry.cjs +172 -0
- package/dist/cjs/summarization/retry.cjs.map +1 -0
- package/dist/cjs/summarization/shared.cjs +6 -2
- package/dist/cjs/summarization/shared.cjs.map +1 -1
- package/dist/cjs/summarization/toolBudget.cjs +45 -0
- package/dist/cjs/summarization/toolBudget.cjs.map +1 -0
- package/dist/cjs/summarization/usage.cjs +70 -0
- package/dist/cjs/summarization/usage.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +46 -16
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/cloudflare/CloudflareBridgeRuntime.cjs.map +1 -1
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +155 -18
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
- package/dist/cjs/tools/subagent/SubagentReplay.cjs +6 -1
- package/dist/cjs/tools/subagent/SubagentReplay.cjs.map +1 -1
- package/dist/cjs/tools/subagent/childGraphConfig.cjs +2 -1
- package/dist/cjs/tools/subagent/childGraphConfig.cjs.map +1 -1
- package/dist/cjs/tools/toolBatchReplay.cjs +182 -6
- package/dist/cjs/tools/toolBatchReplay.cjs.map +1 -1
- package/dist/cjs/utils/errors.cjs +21 -0
- package/dist/cjs/utils/errors.cjs.map +1 -1
- package/dist/cjs/utils/index.cjs +1 -1
- package/dist/cjs/utils/schema.cjs +4 -6
- package/dist/cjs/utils/schema.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +9 -1
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/constants.mjs +2 -1
- package/dist/esm/common/constants.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +16 -13
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +1 -1
- package/dist/esm/hitl/approvalReview.mjs +10 -2
- package/dist/esm/hitl/approvalReview.mjs.map +1 -1
- package/dist/esm/llm/anthropic/defaults.mjs +12 -0
- package/dist/esm/llm/anthropic/defaults.mjs.map +1 -0
- package/dist/esm/llm/anthropic/index.mjs +6 -0
- package/dist/esm/llm/anthropic/index.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +1 -1
- package/dist/esm/llm/google/utils/common.mjs +1 -1
- package/dist/esm/llm/init.mjs +5 -2
- package/dist/esm/llm/init.mjs.map +1 -1
- package/dist/esm/llm/invoke.mjs +18 -16
- package/dist/esm/llm/invoke.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +1 -1
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/llm/request.mjs +13 -1
- package/dist/esm/llm/request.mjs.map +1 -1
- package/dist/esm/llm/stream/chunkAdapters.mjs +2 -3
- package/dist/esm/llm/stream/chunkAdapters.mjs.map +1 -1
- package/dist/esm/llm/truncation.mjs +12 -3
- package/dist/esm/llm/truncation.mjs.map +1 -1
- package/dist/esm/main.mjs +8 -8
- package/dist/esm/messages/core.mjs +1 -1
- package/dist/esm/messages/format.mjs +1 -1
- package/dist/esm/messages/index.mjs +1 -1
- package/dist/esm/messages/prune.mjs +2 -2
- package/dist/esm/messages/reasoningTypes.mjs +19 -1
- package/dist/esm/messages/reasoningTypes.mjs.map +1 -1
- package/dist/esm/messages/recency.mjs +68 -8
- package/dist/esm/messages/recency.mjs.map +1 -1
- package/dist/esm/run.mjs +135 -54
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/session/AgentSession.mjs +7 -10
- package/dist/esm/session/AgentSession.mjs.map +1 -1
- package/dist/esm/stream.mjs +3 -2
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/summarization/input.mjs +84 -0
- package/dist/esm/summarization/input.mjs.map +1 -0
- package/dist/esm/summarization/node.mjs +469 -133
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/summarization/retry.mjs +169 -0
- package/dist/esm/summarization/retry.mjs.map +1 -0
- package/dist/esm/summarization/shared.mjs +6 -2
- package/dist/esm/summarization/shared.mjs.map +1 -1
- package/dist/esm/summarization/toolBudget.mjs +45 -0
- package/dist/esm/summarization/toolBudget.mjs.map +1 -0
- package/dist/esm/summarization/usage.mjs +69 -0
- package/dist/esm/summarization/usage.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +46 -16
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/cloudflare/CloudflareBridgeRuntime.mjs.map +1 -1
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +156 -19
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
- package/dist/esm/tools/subagent/SubagentReplay.mjs +6 -1
- package/dist/esm/tools/subagent/SubagentReplay.mjs.map +1 -1
- package/dist/esm/tools/subagent/childGraphConfig.mjs +2 -1
- package/dist/esm/tools/subagent/childGraphConfig.mjs.map +1 -1
- package/dist/esm/tools/toolBatchReplay.mjs +178 -7
- package/dist/esm/tools/toolBatchReplay.mjs.map +1 -1
- package/dist/esm/utils/errors.mjs +21 -1
- package/dist/esm/utils/errors.mjs.map +1 -1
- package/dist/esm/utils/index.mjs +1 -1
- package/dist/esm/utils/schema.mjs +2 -4
- package/dist/esm/utils/schema.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +2 -0
- package/dist/types/common/constants.d.ts +2 -0
- package/dist/types/hitl/approvalReview.d.ts +1 -1
- package/dist/types/llm/anthropic/defaults.d.ts +11 -0
- package/dist/types/llm/init.d.ts +2 -1
- package/dist/types/llm/invoke.d.ts +8 -1
- package/dist/types/llm/request.d.ts +12 -0
- package/dist/types/llm/stream/chunkAdapters.d.ts +1 -1
- package/dist/types/llm/truncation.d.ts +2 -0
- package/dist/types/messages/reasoningTypes.d.ts +6 -0
- package/dist/types/messages/recency.d.ts +2 -0
- package/dist/types/run.d.ts +3 -0
- package/dist/types/summarization/input.d.ts +16 -0
- package/dist/types/summarization/node.d.ts +2 -1
- package/dist/types/summarization/retry.d.ts +22 -0
- package/dist/types/summarization/shared.d.ts +3 -3
- package/dist/types/summarization/toolBudget.d.ts +8 -0
- package/dist/types/summarization/usage.d.ts +9 -0
- package/dist/types/tools/subagent/SubagentReplay.d.ts +3 -1
- package/dist/types/tools/toolBatchReplay.d.ts +14 -1
- package/dist/types/types/graph.d.ts +2 -1
- package/dist/types/types/hitl.d.ts +2 -0
- package/dist/types/types/llm.d.ts +3 -0
- package/dist/types/types/run.d.ts +1 -1
- package/dist/types/types/summarize.d.ts +15 -3
- package/dist/types/utils/errors.d.ts +2 -0
- package/dist/types/utils/schema.d.ts +1 -1
- package/package.json +12 -6
- package/src/agents/AgentContext.ts +7 -0
- package/src/common/constants.ts +3 -0
- package/src/graphs/Graph.ts +16 -21
- package/src/hitl/approvalReview.ts +10 -2
- package/src/llm/anthropic/defaults.ts +22 -0
- package/src/llm/anthropic/index.ts +15 -2
- package/src/llm/init.ts +16 -2
- package/src/llm/invoke.ts +33 -14
- package/src/llm/openai/utils/index.ts +2 -4
- package/src/llm/request.ts +44 -0
- package/src/llm/stream/chunkAdapters.ts +14 -18
- package/src/llm/truncation.ts +33 -17
- package/src/messages/reasoningTypes.ts +71 -0
- package/src/messages/recency.ts +78 -0
- package/src/run.ts +190 -81
- package/src/session/AgentSession.ts +8 -11
- package/src/stream.ts +1 -0
- package/src/summarization/input.ts +98 -0
- package/src/summarization/node.ts +749 -356
- package/src/summarization/retry.ts +294 -0
- package/src/summarization/shared.ts +9 -2
- package/src/summarization/toolBudget.ts +87 -0
- package/src/summarization/usage.ts +117 -0
- package/src/tools/ToolNode.ts +84 -23
- package/src/tools/cloudflare/CloudflareBridgeRuntime.ts +2 -2
- package/src/tools/subagent/SubagentExecutor.ts +227 -32
- package/src/tools/subagent/SubagentReplay.ts +30 -1
- package/src/tools/subagent/childGraphConfig.ts +9 -2
- package/src/tools/toolBatchReplay.ts +237 -7
- package/src/types/graph.ts +2 -1
- package/src/types/hitl.ts +4 -0
- package/src/types/llm.ts +4 -0
- package/src/types/run.ts +6 -3
- package/src/types/summarize.ts +22 -3
- package/src/utils/errors.ts +45 -0
- package/src/utils/schema.ts +7 -11
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ToolMessage, HumanMessage } from '@langchain/core/messages';
|
|
2
2
|
import type { UsageMetadata, BaseMessage } from '@langchain/core/messages';
|
|
3
3
|
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
4
4
|
import type { RenderedCompactionSemanticIndex } from '@/summarization/semanticIndex';
|
|
@@ -23,27 +23,31 @@ import {
|
|
|
23
23
|
resolveBedrockPromptCacheTtl,
|
|
24
24
|
type PromptCacheTtl,
|
|
25
25
|
} from '@/messages/cache';
|
|
26
|
-
import {
|
|
27
|
-
cloneToolMessageWithContent,
|
|
28
|
-
compactToolContent,
|
|
29
|
-
isComputerCallOutputMessage,
|
|
30
|
-
serializeToolContentBounded,
|
|
31
|
-
} from '@/utils/toolContent';
|
|
32
26
|
import {
|
|
33
27
|
enforceStreamLimitsForWireChunk,
|
|
34
28
|
StreamLimitExceededError,
|
|
35
29
|
STREAM_LIMIT_EPOCH_KEY,
|
|
30
|
+
STREAM_LIMIT_ATTEMPT_KEY,
|
|
36
31
|
} from '@/llm/streamLimits';
|
|
32
|
+
import {
|
|
33
|
+
boundSummarizationInput,
|
|
34
|
+
SummarizationInputTooLargeError,
|
|
35
|
+
DEFAULT_SUMMARY_OUTPUT_TOKENS,
|
|
36
|
+
DEFAULT_RETAIN_RECENT_TOKENS,
|
|
37
|
+
} from './input';
|
|
38
|
+
import { classifySummarizationError, withSummarizationRetry, withSummarizationRetryOwner, ReasoningOnlySummaryError } from './retry';
|
|
37
39
|
import {
|
|
38
40
|
DEFAULT_RETAIN_RECENT_TURNS,
|
|
39
41
|
resolveIntraTurnRetainTokens,
|
|
40
42
|
splitAtRecencyBoundary,
|
|
41
43
|
} from '@/messages/recency';
|
|
44
|
+
import { isReasoningContentBlock, hasMeaningfulReasoningContentBlock } from '@/messages/reasoningTypes';
|
|
42
45
|
import {
|
|
43
46
|
createTokenCounter,
|
|
44
47
|
encodingForModel,
|
|
45
48
|
encodingOfTokenCounter,
|
|
46
49
|
} from '@/utils/tokens';
|
|
50
|
+
import { prepareProviderRequest, resolveServingModelId } from '@/llm/prepareProviderRequest';
|
|
47
51
|
import {
|
|
48
52
|
Constants,
|
|
49
53
|
ContentTypes,
|
|
@@ -56,73 +60,23 @@ import {
|
|
|
56
60
|
resolveClientOptionsModel,
|
|
57
61
|
} from '@/llm/request';
|
|
58
62
|
import { renderCompactionSemanticIndex } from '@/summarization/semanticIndex';
|
|
63
|
+
import { readSummarizationUsage, buildSummarizationStepUsage } from './usage';
|
|
59
64
|
import { ProviderTextProtectionError } from '@/protection/providerText';
|
|
60
65
|
import { safeDispatchCustomEvent, emitAgentLog } from '@/utils/events';
|
|
61
66
|
import { prepareToolsForPromptCache } from '@/llm/promptCacheTools';
|
|
62
67
|
import { attemptInvoke, tryFallbackProviders } from '@/llm/invoke';
|
|
63
|
-
import {
|
|
68
|
+
import { serializeToolContentBounded } from '@/utils/toolContent';
|
|
69
|
+
import { hasReasoningKwargs } from '@/llm/stream/chunkAdapters';
|
|
64
70
|
import { makeIsDeferred } from '@/messages/anthropicToolCache';
|
|
71
|
+
import { countSummarizationToolTokens } from './toolBudget';
|
|
65
72
|
import { createRemoveAllMessage } from '@/messages/reducer';
|
|
66
73
|
import { getProviderFamily } from '@/llm/providerRegistry';
|
|
74
|
+
import { getProviderStopReasons } from '@/llm/truncation';
|
|
75
|
+
import { isProviderCancellation } from '@/utils/errors';
|
|
67
76
|
import { initializeModel } from '@/llm/init';
|
|
68
77
|
import { getChunkContent } from '@/stream';
|
|
69
78
|
import { executeHooks } from '@/hooks';
|
|
70
79
|
|
|
71
|
-
/**
|
|
72
|
-
* Default number of recent user-led turns preserved verbatim during
|
|
73
|
-
* compaction. A turn begins at a HumanMessage and includes every
|
|
74
|
-
* following AIMessage and ToolMessage up to the next HumanMessage.
|
|
75
|
-
* The most recent turn is always retained regardless of this value;
|
|
76
|
-
* the default of `2` additionally keeps the prior exchange so the
|
|
77
|
-
* model has fresh context on what just happened. Setting
|
|
78
|
-
* `retainRecent.turns` to `0` reverts to the legacy "summarize every
|
|
79
|
-
* message" behavior.
|
|
80
|
-
*/
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* Generates a structural metadata summary without making an LLM call.
|
|
84
|
-
* Used as a last-resort fallback when all summarization attempts fail.
|
|
85
|
-
* Preserves tool names and message counts so the agent retains basic context.
|
|
86
|
-
*/
|
|
87
|
-
function generateMetadataStub(messages: BaseMessage[]): string {
|
|
88
|
-
const counts: Record<string, number> = {};
|
|
89
|
-
const toolNames = new Set<string>();
|
|
90
|
-
|
|
91
|
-
for (const msg of messages) {
|
|
92
|
-
const role = msg.getType();
|
|
93
|
-
counts[role] = (counts[role] ?? 0) + 1;
|
|
94
|
-
|
|
95
|
-
if (role === 'tool' && msg.name != null && msg.name !== '') {
|
|
96
|
-
toolNames.add(msg.name);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
if (
|
|
100
|
-
role === 'ai' &&
|
|
101
|
-
msg instanceof AIMessage &&
|
|
102
|
-
msg.tool_calls &&
|
|
103
|
-
msg.tool_calls.length > 0
|
|
104
|
-
) {
|
|
105
|
-
for (const tc of msg.tool_calls) {
|
|
106
|
-
toolNames.add(tc.name);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
const countParts = Object.entries(counts)
|
|
112
|
-
.map(([role, count]) => `${count} ${role}`)
|
|
113
|
-
.join(', ');
|
|
114
|
-
|
|
115
|
-
const lines = [
|
|
116
|
-
`[Metadata summary: ${messages.length} messages (${countParts})]`,
|
|
117
|
-
];
|
|
118
|
-
|
|
119
|
-
if (toolNames.size > 0) {
|
|
120
|
-
lines.push(`[Tools used: ${Array.from(toolNames).join(', ')}]`);
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
return lines.join('\n');
|
|
124
|
-
}
|
|
125
|
-
|
|
126
80
|
/** Maximum number of tool failures to include in the enrichment section. */
|
|
127
81
|
const MAX_TOOL_FAILURES = 8;
|
|
128
82
|
/** Maximum chars per failure summary line. */
|
|
@@ -191,56 +145,6 @@ function enrichSummary(summaryText: string, messages: BaseMessage[]): string {
|
|
|
191
145
|
return summaryText + extractToolFailuresSection(messages);
|
|
192
146
|
}
|
|
193
147
|
|
|
194
|
-
/**
|
|
195
|
-
* Restores pre-masking tool content onto the messages array using
|
|
196
|
-
* `pendingOriginalToolContent` stored on AgentContext. Only allocates
|
|
197
|
-
* a new array when there are entries to restore; otherwise returns the
|
|
198
|
-
* input reference unchanged.
|
|
199
|
-
*/
|
|
200
|
-
function restoreOriginalToolContent(
|
|
201
|
-
messages: BaseMessage[],
|
|
202
|
-
originalToolContent: Map<number, string> | undefined,
|
|
203
|
-
maxContextTokens?: number
|
|
204
|
-
): BaseMessage[] {
|
|
205
|
-
if (originalToolContent == null || originalToolContent.size === 0) {
|
|
206
|
-
return messages;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
const restorable: Array<{
|
|
210
|
-
index: number;
|
|
211
|
-
message: ToolMessage;
|
|
212
|
-
content: string;
|
|
213
|
-
}> = [];
|
|
214
|
-
for (const [index, content] of originalToolContent) {
|
|
215
|
-
const message = messages[index];
|
|
216
|
-
if (
|
|
217
|
-
message instanceof ToolMessage &&
|
|
218
|
-
!isComputerCallOutputMessage(message)
|
|
219
|
-
) {
|
|
220
|
-
restorable.push({ index, message, content });
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
if (restorable.length === 0) {
|
|
224
|
-
return messages;
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* Restored originals improve checkpoint quality, but they still feed a
|
|
229
|
-
* provider call. Share one tool-result budget across every restoration so
|
|
230
|
-
* several previously masked results cannot overflow the summarizer.
|
|
231
|
-
*/
|
|
232
|
-
let remainingChars = calculateMaxToolResultChars(maxContextTokens);
|
|
233
|
-
const restored = [...messages];
|
|
234
|
-
for (let i = 0; i < restorable.length; i++) {
|
|
235
|
-
const { index, message, content } = restorable[i];
|
|
236
|
-
const maxChars = Math.floor(remainingChars / (restorable.length - i));
|
|
237
|
-
const compacted = compactToolContent(content, maxChars).content;
|
|
238
|
-
restored[index] = cloneToolMessageWithContent(message, compacted);
|
|
239
|
-
remainingChars -= serializeToolContentBounded(compacted, maxChars).length;
|
|
240
|
-
}
|
|
241
|
-
return restored;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
148
|
// ---------------------------------------------------------------------------
|
|
245
149
|
// Extracted helpers for createSummarizeNode
|
|
246
150
|
// ---------------------------------------------------------------------------
|
|
@@ -249,7 +153,7 @@ interface SummarizationClientConfig {
|
|
|
249
153
|
provider: string;
|
|
250
154
|
modelName?: string;
|
|
251
155
|
clientOptions: Record<string, unknown>;
|
|
252
|
-
effectiveMaxSummaryTokens
|
|
156
|
+
effectiveMaxSummaryTokens: number | undefined;
|
|
253
157
|
promptText: string;
|
|
254
158
|
updatePromptText: string;
|
|
255
159
|
}
|
|
@@ -272,27 +176,34 @@ function buildSummarizationClientConfig(
|
|
|
272
176
|
separateSummarizationParameters(parameters);
|
|
273
177
|
|
|
274
178
|
const isSelfSummarize = provider === (agentContext.provider as string);
|
|
275
|
-
const baseOptions =
|
|
179
|
+
const baseOptions: Record<string, unknown> =
|
|
276
180
|
isSelfSummarize && agentContext.clientOptions
|
|
277
181
|
? { ...agentContext.clientOptions }
|
|
278
182
|
: {};
|
|
279
183
|
|
|
280
|
-
const clientOptions: Record<string, unknown> = {
|
|
184
|
+
const clientOptions: Record<string, unknown> = withSummarizationRetryOwner(provider, {
|
|
281
185
|
...baseOptions,
|
|
282
186
|
...llmParams,
|
|
283
|
-
};
|
|
187
|
+
});
|
|
284
188
|
|
|
285
189
|
if (modelName != null && modelName !== '') {
|
|
286
190
|
clientOptions.model = modelName;
|
|
287
191
|
clientOptions.modelName = modelName;
|
|
288
192
|
}
|
|
289
193
|
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
194
|
+
const outputKey = getMaxOutputTokensKey(provider);
|
|
195
|
+
const inheritedOutputTokens = readSummaryOutputLimit(provider, baseOptions);
|
|
196
|
+
const explicitOutputTokens = readSummaryOutputLimit(provider, llmParams);
|
|
197
|
+
clearSummaryOutputLimits(provider, clientOptions);
|
|
198
|
+
let effectiveMaxSummaryTokens =
|
|
199
|
+
paramMaxSummaryTokens ?? summarizationConfig?.maxSummaryTokens ?? explicitOutputTokens;
|
|
200
|
+
if (effectiveMaxSummaryTokens == null) {
|
|
201
|
+
effectiveMaxSummaryTokens = resolveSummaryOutputTokens(
|
|
202
|
+
provider, clientOptions, agentContext.maxContextTokens, inheritedOutputTokens
|
|
203
|
+
);
|
|
295
204
|
}
|
|
205
|
+
if (effectiveMaxSummaryTokens === -1 && usesCompletionTokenAlias(provider)) effectiveMaxSummaryTokens = undefined;
|
|
206
|
+
if (effectiveMaxSummaryTokens != null) clientOptions[outputKey] = effectiveMaxSummaryTokens;
|
|
296
207
|
|
|
297
208
|
return {
|
|
298
209
|
provider,
|
|
@@ -304,6 +215,121 @@ function buildSummarizationClientConfig(
|
|
|
304
215
|
};
|
|
305
216
|
}
|
|
306
217
|
|
|
218
|
+
function usesCompletionTokenAlias(provider: t.ProviderName): boolean {
|
|
219
|
+
return getProviderFamily(provider) === 'openai' || provider === Providers.MOONSHOT;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function readSummaryOutputLimit(provider: t.ProviderName, options: Record<string, unknown>): number | undefined {
|
|
223
|
+
const openai = usesCompletionTokenAlias(provider);
|
|
224
|
+
const native = (openai ? options.modelKwargs : options.invocationKwargs) as
|
|
225
|
+
{max_output_tokens?: number; max_tokens?: number} | undefined;
|
|
226
|
+
const anthropic = provider === Providers.ANTHROPIC || getProviderFamily(provider) === 'anthropic';
|
|
227
|
+
// Completions rewrites its active output field after merging modelKwargs.
|
|
228
|
+
let nativeLimit: number | undefined;
|
|
229
|
+
if (openai) nativeLimit = native?.max_output_tokens;
|
|
230
|
+
else if (anthropic) nativeLimit = native?.max_tokens;
|
|
231
|
+
return (nativeLimit ?? (openai ? options.maxCompletionTokens : undefined) ??
|
|
232
|
+
options[getMaxOutputTokensKey(provider)]) as number | undefined;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function clearSummaryOutputLimits(provider: t.ProviderName, options: Record<string, unknown>): void {
|
|
236
|
+
delete options[getMaxOutputTokensKey(provider)];
|
|
237
|
+
const openai = usesCompletionTokenAlias(provider);
|
|
238
|
+
if (openai) delete options.maxCompletionTokens;
|
|
239
|
+
const key = openai ? 'modelKwargs' : 'invocationKwargs';
|
|
240
|
+
if (!openai && provider !== Providers.ANTHROPIC && getProviderFamily(provider) !== 'anthropic') return;
|
|
241
|
+
const native = options[key] as object | undefined;
|
|
242
|
+
if (native == null) return;
|
|
243
|
+
const normalized = {...native};
|
|
244
|
+
for (const field of openai ? ['max_output_tokens', 'max_completion_tokens', 'max_tokens'] : ['max_tokens']) {
|
|
245
|
+
Reflect.deleteProperty(normalized, field);
|
|
246
|
+
}
|
|
247
|
+
options[key] = normalized;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function resolveSummaryReasoning(provider: t.ProviderName, clientOptions: Record<string, unknown>): {enabled: boolean; fixedBudget: number} {
|
|
251
|
+
type ReasoningOptions = {
|
|
252
|
+
reasoningEffort?: string;
|
|
253
|
+
reasoning_effort?: string;
|
|
254
|
+
reasoning?: {effort?: string; enabled?: boolean; max_tokens?: number};
|
|
255
|
+
thinking?: t.AnthropicReasoning['thinking'];
|
|
256
|
+
thinkingBudget?: number;
|
|
257
|
+
thinkingConfig?: t.GoogleThinkingConfig;
|
|
258
|
+
};
|
|
259
|
+
const options = clientOptions as ReasoningOptions & {
|
|
260
|
+
include_reasoning?: boolean;
|
|
261
|
+
modelKwargs?: ReasoningOptions;
|
|
262
|
+
additionalModelRequestFields?: ReasoningOptions;
|
|
263
|
+
invocationKwargs?: ReasoningOptions;
|
|
264
|
+
};
|
|
265
|
+
const family = getProviderFamily(provider);
|
|
266
|
+
const google = options.thinkingConfig;
|
|
267
|
+
if (provider === Providers.GOOGLE || provider === Providers.VERTEXAI || family === 'google') {
|
|
268
|
+
const budget = google?.thinkingBudget ?? options.thinkingBudget;
|
|
269
|
+
const hasLevel = google?.thinkingLevel != null && google.thinkingLevel !== 'THINKING_LEVEL_UNSPECIFIED';
|
|
270
|
+
const fixedBudget = budget != null && Number.isFinite(budget) && budget > 0 ? budget : 0;
|
|
271
|
+
return {
|
|
272
|
+
enabled: hasLevel || (budget != null && (budget > 0 || budget === -1)),
|
|
273
|
+
fixedBudget: provider === Providers.VERTEXAI && hasLevel ? 0 : fixedBudget,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
const thinking = (provider === Providers.ANTHROPIC || family === 'anthropic'
|
|
277
|
+
? options.invocationKwargs?.thinking : undefined) ?? options.thinking ??
|
|
278
|
+
options.additionalModelRequestFields?.thinking ?? options.modelKwargs?.thinking;
|
|
279
|
+
if (thinking != null) {
|
|
280
|
+
const enabled = thinking === true || (typeof thinking === 'object' &&
|
|
281
|
+
(thinking.type === 'enabled' || thinking.type === 'adaptive'));
|
|
282
|
+
let budget = thinking === true ? options.thinkingBudget ?? options.additionalModelRequestFields?.thinkingBudget : 0;
|
|
283
|
+
if (typeof thinking === 'object' && thinking.type === 'enabled') budget = thinking.budget_tokens;
|
|
284
|
+
return {enabled, fixedBudget: enabled && budget != null && Number.isFinite(budget) && budget > 0 ? budget : 0};
|
|
285
|
+
}
|
|
286
|
+
const reasoning = {...options.modelKwargs?.reasoning, ...options.reasoning};
|
|
287
|
+
const effort = reasoning.effort ?? options.reasoningEffort ?? options.reasoning_effort ??
|
|
288
|
+
options.modelKwargs?.reasoning_effort ?? options.modelKwargs?.reasoningEffort;
|
|
289
|
+
return {enabled: reasoning.enabled !== false && (
|
|
290
|
+
(effort != null && effort !== '' && effort !== 'none' && effort !== 'disabled') ||
|
|
291
|
+
reasoning.enabled === true || (reasoning.max_tokens != null && reasoning.max_tokens > 0) ||
|
|
292
|
+
(provider === Providers.OPENROUTER && options.reasoning == null &&
|
|
293
|
+
options.modelKwargs?.reasoning == null && options.include_reasoning === true)
|
|
294
|
+
), fixedBudget: 0};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function resolveSummaryOutputTokens(
|
|
298
|
+
provider: t.ProviderName,
|
|
299
|
+
clientOptions: Record<string, unknown>,
|
|
300
|
+
maxContextTokens?: number,
|
|
301
|
+
inheritedOutputTokens?: number
|
|
302
|
+
): number | undefined {
|
|
303
|
+
const explicit = readSummaryOutputLimit(provider, clientOptions);
|
|
304
|
+
if (explicit != null) return explicit === -1 && usesCompletionTokenAlias(provider) ? undefined : explicit;
|
|
305
|
+
const reasoning = resolveSummaryReasoning(provider, clientOptions);
|
|
306
|
+
if (reasoning.enabled && (inheritedOutputTokens == null || inheritedOutputTokens === -1)) return undefined;
|
|
307
|
+
const defaultOutputTokens = reasoning.fixedBudget + Math.min(
|
|
308
|
+
DEFAULT_SUMMARY_OUTPUT_TOKENS,
|
|
309
|
+
Math.max(1, Math.floor((maxContextTokens ?? 40_960) * 0.1))
|
|
310
|
+
);
|
|
311
|
+
const inherited = reasoning.enabled && inheritedOutputTokens != null &&
|
|
312
|
+
Number.isFinite(inheritedOutputTokens) && inheritedOutputTokens > 0 ? inheritedOutputTokens : 0;
|
|
313
|
+
return Math.max(defaultOutputTokens, inherited);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function resolveSummaryOutputReserve(model: t.ChatModel): number {
|
|
317
|
+
let candidate: object | undefined = model;
|
|
318
|
+
const seen = new Set<object>();
|
|
319
|
+
for (let depth = 0; candidate != null && depth < 20 && !seen.has(candidate); depth++) {
|
|
320
|
+
seen.add(candidate);
|
|
321
|
+
const runnable = candidate as {
|
|
322
|
+
profile?: {maxOutputTokens?: number};
|
|
323
|
+
bound?: object;
|
|
324
|
+
last?: object;
|
|
325
|
+
};
|
|
326
|
+
const maximum = runnable.profile?.maxOutputTokens;
|
|
327
|
+
if (maximum != null && Number.isSafeInteger(maximum) && maximum > 0) return maximum;
|
|
328
|
+
candidate = runnable.bound ?? runnable.last;
|
|
329
|
+
}
|
|
330
|
+
throw new SummarizationInputTooLargeError();
|
|
331
|
+
}
|
|
332
|
+
|
|
307
333
|
/**
|
|
308
334
|
* Sizes a summary from the text that will actually be re-injected, carrier
|
|
309
335
|
* included, so the stored count is a measurement rather than a body count plus
|
|
@@ -394,16 +420,117 @@ async function computeSummaryTokenCount(
|
|
|
394
420
|
* the same rule that rejects another agent's counter.
|
|
395
421
|
*/
|
|
396
422
|
function encodingForReceivingAgent(agentContext: AgentContext): EncodingName {
|
|
397
|
-
|
|
423
|
+
return encodingForSummarizationModel(
|
|
424
|
+
agentContext.provider,
|
|
425
|
+
agentContext.clientOptions
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function encodingForSummarizationModel(
|
|
430
|
+
provider: t.ProviderName,
|
|
431
|
+
clientOptions?: t.ClientOptions
|
|
432
|
+
): EncodingName {
|
|
433
|
+
const model = resolveClientOptionsModel(clientOptions);
|
|
398
434
|
if (model != null && encodingForModel(model) === 'claude') {
|
|
399
435
|
return 'claude';
|
|
400
436
|
}
|
|
401
|
-
return
|
|
402
|
-
getProviderFamily(
|
|
437
|
+
return provider === Providers.ANTHROPIC ||
|
|
438
|
+
getProviderFamily(provider) === 'anthropic'
|
|
403
439
|
? 'claude'
|
|
404
440
|
: 'o200k_base';
|
|
405
441
|
}
|
|
406
442
|
|
|
443
|
+
async function prepareSummarizationBudget({
|
|
444
|
+
agentContext,
|
|
445
|
+
model,
|
|
446
|
+
provider,
|
|
447
|
+
clientOptions,
|
|
448
|
+
maxContextTokens,
|
|
449
|
+
outputTokens,
|
|
450
|
+
contextBudgetMode = 'input',
|
|
451
|
+
instruction,
|
|
452
|
+
tools,
|
|
453
|
+
config,
|
|
454
|
+
}: {
|
|
455
|
+
agentContext: AgentContext;
|
|
456
|
+
model: t.ChatModel;
|
|
457
|
+
provider: t.ProviderName;
|
|
458
|
+
clientOptions?: t.ClientOptions;
|
|
459
|
+
maxContextTokens?: number;
|
|
460
|
+
outputTokens: number | undefined;
|
|
461
|
+
contextBudgetMode?: t.ContextBudgetMode;
|
|
462
|
+
instruction: string;
|
|
463
|
+
tools?: t.GraphTools;
|
|
464
|
+
config?: RunnableConfig;
|
|
465
|
+
}): Promise<{
|
|
466
|
+
count: t.TokenCounter;
|
|
467
|
+
system: AgentContext['systemRunnable'];
|
|
468
|
+
budget: number;
|
|
469
|
+
}> {
|
|
470
|
+
const encoding = encodingForSummarizationModel(provider, clientOptions);
|
|
471
|
+
const hostCounter = agentContext.tokenCounter;
|
|
472
|
+
const hostEncoding =
|
|
473
|
+
hostCounter == null ? undefined : encodingOfTokenCounter(hostCounter);
|
|
474
|
+
const usesAgentCounter =
|
|
475
|
+
provider === agentContext.provider &&
|
|
476
|
+
encoding === encodingForReceivingAgent(agentContext) &&
|
|
477
|
+
hostCounter != null &&
|
|
478
|
+
(hostEncoding == null || hostEncoding === encoding);
|
|
479
|
+
const count = usesAgentCounter
|
|
480
|
+
? (agentContext.contextPressureTokenCounts?.count ?? hostCounter)
|
|
481
|
+
: await createTokenCounter(encoding);
|
|
482
|
+
const system =
|
|
483
|
+
provider === agentContext.provider
|
|
484
|
+
? agentContext.systemRunnable
|
|
485
|
+
: undefined;
|
|
486
|
+
const toolTokens = usesAgentCounter ? agentContext.toolSchemaTokens :
|
|
487
|
+
countSummarizationToolTokens({tools, provider, clientOptions, count});
|
|
488
|
+
let overhead = toolTokens;
|
|
489
|
+
if (system != null) {
|
|
490
|
+
overhead = usesAgentCounter
|
|
491
|
+
? agentContext.instructionTokens
|
|
492
|
+
: (await system.invoke([], config)).reduce(
|
|
493
|
+
(total, message) => total + count(message),
|
|
494
|
+
overhead
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
const ratio = usesAgentCounter
|
|
498
|
+
? Math.max(1, agentContext.calibrationRatio)
|
|
499
|
+
: 1;
|
|
500
|
+
const outputReserve = contextBudgetMode === 'window' && maxContextTokens != null
|
|
501
|
+
? outputTokens ?? resolveSummaryOutputReserve(model) : 0;
|
|
502
|
+
const budget =
|
|
503
|
+
maxContextTokens == null
|
|
504
|
+
? Number.MAX_SAFE_INTEGER
|
|
505
|
+
: Math.floor(
|
|
506
|
+
(maxContextTokens -
|
|
507
|
+
overhead -
|
|
508
|
+
outputReserve -
|
|
509
|
+
count(new HumanMessage(instruction))) /
|
|
510
|
+
ratio
|
|
511
|
+
);
|
|
512
|
+
return { count, system, budget };
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
async function flushSummarizationDeltas(
|
|
516
|
+
deltas: t.SummarizeDeltaEvent[],
|
|
517
|
+
config?: RunnableConfig,
|
|
518
|
+
graph?: { getBreakerSignal?: () => AbortSignal }
|
|
519
|
+
): Promise<void> {
|
|
520
|
+
const signal = withBreakerSignal(config, graph)?.signal;
|
|
521
|
+
signal?.throwIfAborted();
|
|
522
|
+
for (const delta of deltas) {
|
|
523
|
+
signal?.throwIfAborted();
|
|
524
|
+
if (config != null)
|
|
525
|
+
await safeDispatchCustomEvent(
|
|
526
|
+
GraphEvents.ON_SUMMARIZE_DELTA,
|
|
527
|
+
delta,
|
|
528
|
+
config
|
|
529
|
+
);
|
|
530
|
+
}
|
|
531
|
+
signal?.throwIfAborted();
|
|
532
|
+
}
|
|
533
|
+
|
|
407
534
|
/**
|
|
408
535
|
* Names the first retained message so the summary declares its own extent
|
|
409
536
|
* rather than leaving the next run to infer coverage from where the block
|
|
@@ -453,6 +580,28 @@ function isSyntheticContext(message: BaseMessage): boolean {
|
|
|
453
580
|
return kwargs.source != null && kwargs.source !== 'steer';
|
|
454
581
|
}
|
|
455
582
|
|
|
583
|
+
function restoreRetainedMessages(
|
|
584
|
+
retained: BaseMessage[],
|
|
585
|
+
canonical: BaseMessage[]
|
|
586
|
+
): BaseMessage[] {
|
|
587
|
+
if (retained.length === 0) return retained;
|
|
588
|
+
const pending = new Map<string, number>();
|
|
589
|
+
for (let i = 0; i < retained.length; i++) {
|
|
590
|
+
const id = retained[i].id;
|
|
591
|
+
if (id != null) pending.set(id, i);
|
|
592
|
+
}
|
|
593
|
+
const restored = [...retained];
|
|
594
|
+
for (let i = canonical.length - 1; i >= 0 && pending.size > 0; i--) {
|
|
595
|
+
const message = canonical[i];
|
|
596
|
+
if (message.id == null) continue;
|
|
597
|
+
const index = pending.get(message.id);
|
|
598
|
+
if (index == null) continue;
|
|
599
|
+
restored[index] = message;
|
|
600
|
+
pending.delete(message.id);
|
|
601
|
+
}
|
|
602
|
+
return restored;
|
|
603
|
+
}
|
|
604
|
+
|
|
456
605
|
function resolveSummaryCoverage(
|
|
457
606
|
messagesToRetain: BaseMessage[]
|
|
458
607
|
): t.SummaryCoverage | undefined {
|
|
@@ -628,17 +777,20 @@ function describeFallbackError(
|
|
|
628
777
|
|
|
629
778
|
/**
|
|
630
779
|
* Runs the summarization LLM call with primary + fallback providers,
|
|
631
|
-
*
|
|
780
|
+
* preserving history when every provider fails.
|
|
632
781
|
*/
|
|
633
782
|
async function executeSummarizationWithFallback(params: {
|
|
634
783
|
agentContext: AgentContext;
|
|
635
784
|
messages: BaseMessage[];
|
|
785
|
+
requiredHeadLength: number;
|
|
636
786
|
clientConfig: SummarizationClientConfig;
|
|
637
787
|
summarizeConfig?: RunnableConfig;
|
|
638
788
|
stepId: string;
|
|
639
789
|
usePromptCache: boolean;
|
|
790
|
+
shrinkInput?: boolean;
|
|
640
791
|
semanticIndex: RenderedCompactionSemanticIndex;
|
|
641
792
|
log: LogFn;
|
|
793
|
+
onUsage: (attempt: t.SummarizationAttemptUsage) => void;
|
|
642
794
|
/** Carries the run's stream limits so the event cap covers summary streams. */
|
|
643
795
|
graph?: StreamLimitState & {
|
|
644
796
|
getBreakerSignal?: () => AbortSignal;
|
|
@@ -650,30 +802,32 @@ async function executeSummarizationWithFallback(params: {
|
|
|
650
802
|
}): Promise<{
|
|
651
803
|
text: string;
|
|
652
804
|
usage?: Partial<UsageMetadata>;
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
* this need to know it carries none of the original content.
|
|
657
|
-
*/
|
|
658
|
-
usedMetadataStub?: boolean;
|
|
805
|
+
provider: string;
|
|
806
|
+
model?: string;
|
|
807
|
+
errorCode?: t.SummarizationErrorCode;
|
|
659
808
|
}> {
|
|
660
809
|
const {
|
|
661
810
|
agentContext,
|
|
662
811
|
messages,
|
|
812
|
+
requiredHeadLength,
|
|
663
813
|
clientConfig,
|
|
664
814
|
summarizeConfig,
|
|
665
815
|
stepId,
|
|
666
816
|
usePromptCache,
|
|
817
|
+
shrinkInput,
|
|
667
818
|
semanticIndex,
|
|
668
819
|
log,
|
|
669
820
|
graph,
|
|
821
|
+
onUsage,
|
|
670
822
|
} = params;
|
|
671
823
|
|
|
672
824
|
const priorSummaryText = agentContext.getSummaryText()?.trim() ?? '';
|
|
673
825
|
|
|
674
826
|
let summaryText = '';
|
|
827
|
+
let summaryProvider = clientConfig.provider;
|
|
828
|
+
let summaryModel = clientConfig.modelName;
|
|
675
829
|
let summaryUsage: Partial<UsageMetadata> | undefined;
|
|
676
|
-
let
|
|
830
|
+
let errorCode: t.SummarizationErrorCode | undefined;
|
|
677
831
|
|
|
678
832
|
try {
|
|
679
833
|
/**
|
|
@@ -681,7 +835,8 @@ async function executeSummarizationWithFallback(params: {
|
|
|
681
835
|
* (e.g. an unrecognized summarization.provider) surfaces through the
|
|
682
836
|
* `log('error', ...)` path below rather than bubbling up silently.
|
|
683
837
|
*/
|
|
684
|
-
const
|
|
838
|
+
const isSelfSummarize = clientConfig.provider === agentContext.provider;
|
|
839
|
+
const summarizationTools = isSelfSummarize
|
|
685
840
|
? (graph?.getToolsForBinding?.(
|
|
686
841
|
clientConfig.provider as t.ProviderName,
|
|
687
842
|
clientConfig.clientOptions as t.ClientOptions
|
|
@@ -699,22 +854,37 @@ async function executeSummarizationWithFallback(params: {
|
|
|
699
854
|
provider: clientConfig.provider,
|
|
700
855
|
clientOptions: clientConfig.clientOptions as t.ClientOptions,
|
|
701
856
|
tools: summarizationTools,
|
|
857
|
+
disableToolCalling: true,
|
|
702
858
|
}) as t.ChatModel;
|
|
703
859
|
|
|
704
|
-
const
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
860
|
+
const signal = withBreakerSignal(summarizeConfig, graph)?.signal;
|
|
861
|
+
const result = await withSummarizationRetry(
|
|
862
|
+
() =>
|
|
863
|
+
summarizeWithCacheHit({
|
|
864
|
+
agentContext,
|
|
865
|
+
onUsage: usage => onUsage({
|
|
866
|
+
provider: clientConfig.provider as t.ProviderName,
|
|
867
|
+
model: clientConfig.modelName ?? resolveServingModelId(summarizationModel) ?? resolveClientOptionsModel(clientConfig.clientOptions as t.ClientOptions),
|
|
868
|
+
usage,
|
|
869
|
+
}),
|
|
870
|
+
shrinkInput,
|
|
871
|
+
outputTokens: clientConfig.effectiveMaxSummaryTokens,
|
|
872
|
+
clientOptions: clientConfig.clientOptions as t.ClientOptions,
|
|
873
|
+
model: summarizationModel,
|
|
874
|
+
tools: summarizationTools,
|
|
875
|
+
messages,
|
|
876
|
+
requiredHeadLength,
|
|
877
|
+
promptText: clientConfig.promptText,
|
|
878
|
+
updatePromptText: clientConfig.updatePromptText,
|
|
879
|
+
priorSummaryText,
|
|
880
|
+
semanticIndexAppendix: semanticIndex.appendix,
|
|
881
|
+
config: summarizeConfig,
|
|
882
|
+
stepId,
|
|
883
|
+
provider: clientConfig.provider,
|
|
884
|
+
reasoningKey: agentContext.reasoningKey,
|
|
885
|
+
graph,
|
|
886
|
+
usePromptCache,
|
|
887
|
+
promptCacheTtl:
|
|
718
888
|
clientConfig.provider === Providers.ANTHROPIC ||
|
|
719
889
|
clientConfig.provider === Providers.OPENROUTER ||
|
|
720
890
|
clientConfig.provider === Providers.BEDROCK
|
|
@@ -724,7 +894,7 @@ async function executeSummarizationWithFallback(params: {
|
|
|
724
894
|
}
|
|
725
895
|
).promptCacheTtl
|
|
726
896
|
: undefined,
|
|
727
|
-
|
|
897
|
+
bedrockModelId:
|
|
728
898
|
clientConfig.provider === Providers.BEDROCK
|
|
729
899
|
? resolveBedrockCompactionCacheModel(
|
|
730
900
|
clientConfig.clientOptions as
|
|
@@ -735,27 +905,33 @@ async function executeSummarizationWithFallback(params: {
|
|
|
735
905
|
| undefined
|
|
736
906
|
)
|
|
737
907
|
: undefined,
|
|
738
|
-
|
|
739
|
-
|
|
908
|
+
log,
|
|
909
|
+
}),
|
|
910
|
+
{
|
|
911
|
+
signal,
|
|
912
|
+
onRetry: (retry) => log('debug', 'Retrying summarization', retry),
|
|
913
|
+
}
|
|
914
|
+
);
|
|
740
915
|
summaryText = result.text;
|
|
741
916
|
summaryUsage = result.usage;
|
|
742
917
|
} catch (primaryError) {
|
|
743
918
|
/**
|
|
744
919
|
* A tripped stream circuit breaker is a safety abort, not a
|
|
745
920
|
* summarization failure to recover from: retrying on fallback providers
|
|
746
|
-
* would spend more provider work after the limit fired
|
|
747
|
-
*
|
|
748
|
-
* commit the stub) despite the `StreamLimits` contract that a breach
|
|
749
|
-
* rejects the run. Rethrown so the summarize node fails the run with
|
|
921
|
+
* would spend more provider work after the limit fired despite the
|
|
922
|
+
* `StreamLimits` contract that a breach rejects the run. Rethrown so the summarize node fails the run with
|
|
750
923
|
* the actionable limit error, consistent with agent turns and subagents.
|
|
751
924
|
*/
|
|
752
|
-
if (
|
|
925
|
+
if (
|
|
926
|
+
primaryError instanceof StreamLimitExceededError ||
|
|
927
|
+
primaryError instanceof ProviderTextProtectionError ||
|
|
928
|
+
isProviderCancellation(primaryError)
|
|
929
|
+
) {
|
|
753
930
|
throw primaryError;
|
|
754
931
|
}
|
|
755
932
|
/** A parallel branch's trip aborts the composed summarization signal,
|
|
756
933
|
* and a provider can surface that as a generic abort error; entering
|
|
757
|
-
* fallback recovery
|
|
758
|
-
* work after the run-wide safety abort. Checked on BOTH channels: the
|
|
934
|
+
* fallback recovery would continue work after the run-wide safety abort. Checked on BOTH channels: the
|
|
759
935
|
* graph's own breaker, and the composed config signal that carries a
|
|
760
936
|
* parent run's trip into subagent child graphs. */
|
|
761
937
|
{
|
|
@@ -768,6 +944,9 @@ async function executeSummarizationWithFallback(params: {
|
|
|
768
944
|
}
|
|
769
945
|
}
|
|
770
946
|
|
|
947
|
+
withBreakerSignal(summarizeConfig, graph)?.signal?.throwIfAborted();
|
|
948
|
+
errorCode = classifySummarizationError(primaryError);
|
|
949
|
+
|
|
771
950
|
const primaryDescribed = describeProviderError(
|
|
772
951
|
primaryError,
|
|
773
952
|
clientConfig.provider,
|
|
@@ -784,27 +963,89 @@ async function executeSummarizationWithFallback(params: {
|
|
|
784
963
|
const fallbacks = Array.isArray(rawFallbacks) ? rawFallbacks : [];
|
|
785
964
|
if (fallbacks.length > 0) {
|
|
786
965
|
try {
|
|
966
|
+
const boundedFallbacks = fallbacks.map((fallback) => {
|
|
967
|
+
const maxContextTokens =
|
|
968
|
+
fallback.maxContextTokens ?? agentContext.maxContextTokens;
|
|
969
|
+
const outputTokens = resolveSummaryOutputTokens(
|
|
970
|
+
fallback.provider, {...fallback.clientOptions}, maxContextTokens
|
|
971
|
+
);
|
|
972
|
+
const clientOptions: Record<string, unknown> = withSummarizationRetryOwner(fallback.provider, {...fallback.clientOptions});
|
|
973
|
+
clearSummaryOutputLimits(fallback.provider, clientOptions);
|
|
974
|
+
if (outputTokens != null) clientOptions[getMaxOutputTokensKey(fallback.provider)] = outputTokens;
|
|
975
|
+
return {
|
|
976
|
+
...fallback,
|
|
977
|
+
clientOptions,
|
|
978
|
+
maxContextTokens,
|
|
979
|
+
contextBudgetMode: fallback.maxContextTokens == null
|
|
980
|
+
? agentContext.summarizationBudgetMode : fallback.contextBudgetMode ?? 'window',
|
|
981
|
+
} as t.FallbackConfig;
|
|
982
|
+
});
|
|
983
|
+
let fallbackIdentity: {provider: string; model?: string} | undefined;
|
|
984
|
+
const pendingDeltas: t.SummarizeDeltaEvent[] = [];
|
|
787
985
|
const onChunk = createSummarizationChunkHandler({
|
|
986
|
+
pendingDeltas,
|
|
788
987
|
stepId,
|
|
789
988
|
config: traceConfig(summarizeConfig, 'cache_hit_compaction'),
|
|
790
989
|
provider: clientConfig.provider,
|
|
791
990
|
reasoningKey: agentContext.reasoningKey,
|
|
792
991
|
graph,
|
|
793
992
|
});
|
|
993
|
+
const fallbackTools = agentContext.getToolsForBinding();
|
|
794
994
|
const fbResult = await tryFallbackProviders({
|
|
795
|
-
fallbacks,
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
995
|
+
fallbacks: boundedFallbacks,
|
|
996
|
+
disableToolCalling: true,
|
|
997
|
+
tools: fallbackTools,
|
|
998
|
+
messages,
|
|
999
|
+
prepareProviderRequest: async ({
|
|
1000
|
+
model,
|
|
1001
|
+
provider,
|
|
1002
|
+
clientOptions,
|
|
1003
|
+
maxContextTokens,
|
|
1004
|
+
contextBudgetMode,
|
|
1005
|
+
config,
|
|
1006
|
+
}) => {
|
|
1007
|
+
config?.signal?.throwIfAborted();
|
|
1008
|
+
pendingDeltas.length = 0;
|
|
1009
|
+
const instruction = buildSummarizationInstruction(
|
|
1010
|
+
clientConfig.promptText, clientConfig.updatePromptText, priorSummaryText,
|
|
1011
|
+
semanticIndex.appendix,
|
|
1012
|
+
provider === agentContext.provider && agentContext.systemRunnable != null,
|
|
1013
|
+
);
|
|
1014
|
+
const { count, system, budget } = await prepareSummarizationBudget({
|
|
1015
|
+
agentContext,
|
|
1016
|
+
model,
|
|
1017
|
+
provider,
|
|
1018
|
+
clientOptions,
|
|
1019
|
+
maxContextTokens,
|
|
1020
|
+
contextBudgetMode,
|
|
1021
|
+
outputTokens: readSummaryOutputLimit(provider, {...clientOptions}),
|
|
1022
|
+
instruction,
|
|
1023
|
+
tools: fallbackTools,
|
|
1024
|
+
config,
|
|
1025
|
+
});
|
|
1026
|
+
const bounded = boundSummarizationInput({
|
|
1027
|
+
messages,
|
|
1028
|
+
requiredHeadLength,
|
|
1029
|
+
tokenCounter: count,
|
|
1030
|
+
budget,
|
|
1031
|
+
provider,
|
|
1032
|
+
});
|
|
1033
|
+
const bedrock = clientOptions as t.BedrockAnthropicInput | undefined;
|
|
1034
|
+
const windowWithCache = provider === Providers.BEDROCK
|
|
1035
|
+
? applySummarizationHistoryCache({messages: bounded, provider,
|
|
1036
|
+
enabled: bedrock?.promptCache === true,
|
|
1037
|
+
promptCacheTtl: bedrock?.promptCacheTtl, bedrockModelId: resolveClientOptionsModel(clientOptions),
|
|
1038
|
+
}) : bounded;
|
|
1039
|
+
const history = system == null ? windowWithCache : await system.invoke(windowWithCache, config);
|
|
1040
|
+
const request = prepareProviderRequest({
|
|
1041
|
+
model,
|
|
1042
|
+
messages: [...history, new HumanMessage(instruction)],
|
|
1043
|
+
provider,
|
|
1044
|
+
config,
|
|
1045
|
+
});
|
|
1046
|
+
fallbackIdentity = {provider, model: request.modelId ?? resolveClientOptionsModel(clientOptions)};
|
|
1047
|
+
return request;
|
|
1048
|
+
},
|
|
808
1049
|
config: withBreakerSignal(
|
|
809
1050
|
traceConfig(summarizeConfig, 'cache_hit_compaction'),
|
|
810
1051
|
graph
|
|
@@ -812,19 +1053,53 @@ async function executeSummarizationWithFallback(params: {
|
|
|
812
1053
|
primaryError,
|
|
813
1054
|
onChunk,
|
|
814
1055
|
streamLimitState: graph,
|
|
1056
|
+
invokeModel: (params, config) => withSummarizationRetry(async () => {
|
|
1057
|
+
pendingDeltas.length = 0;
|
|
1058
|
+
const result = await attemptInvoke({...params, onModelComplete: response => {
|
|
1059
|
+
params.onModelComplete?.(response);
|
|
1060
|
+
const usage = readSummarizationUsage(response);
|
|
1061
|
+
if (usage != null && fallbackIdentity != null) onUsage({
|
|
1062
|
+
provider: fallbackIdentity.provider as t.ProviderName, model: fallbackIdentity.model, usage,
|
|
1063
|
+
});
|
|
1064
|
+
}}, config);
|
|
1065
|
+
config?.signal?.throwIfAborted();
|
|
1066
|
+
const response = result.messages?.[0];
|
|
1067
|
+
validateSummaryResponse(response);
|
|
1068
|
+
return result;
|
|
1069
|
+
}, {signal: config?.signal, onRetry: retry => log('debug', 'Retrying fallback summarization', retry)}),
|
|
815
1070
|
});
|
|
816
1071
|
const fbMsg = fbResult?.messages?.[0];
|
|
817
1072
|
if (fbMsg) {
|
|
1073
|
+
summaryUsage = readSummarizationUsage(fbMsg);
|
|
818
1074
|
summaryText = extractResponseText(
|
|
819
1075
|
fbMsg as { content: string | object }
|
|
820
1076
|
);
|
|
1077
|
+
if (summaryText !== '') {
|
|
1078
|
+
if (fallbackIdentity == null) throw new Error('Missing successful fallback identity', {cause: primaryError});
|
|
1079
|
+
summaryProvider = fallbackIdentity.provider;
|
|
1080
|
+
summaryModel = fallbackIdentity.model;
|
|
1081
|
+
await flushSummarizationDeltas(
|
|
1082
|
+
pendingDeltas,
|
|
1083
|
+
summarizeConfig,
|
|
1084
|
+
graph
|
|
1085
|
+
);
|
|
1086
|
+
}
|
|
821
1087
|
}
|
|
822
1088
|
} catch (fbErr) {
|
|
823
|
-
const trip = findStreamLimitAbortReason(
|
|
1089
|
+
const trip = findStreamLimitAbortReason(
|
|
1090
|
+
graph?.getBreakerSignal?.(),
|
|
1091
|
+
summarizeConfig?.signal
|
|
1092
|
+
);
|
|
824
1093
|
if (trip != null) throw trip;
|
|
825
|
-
if (
|
|
1094
|
+
if (
|
|
1095
|
+
fbErr instanceof StreamLimitExceededError ||
|
|
1096
|
+
fbErr instanceof ProviderTextProtectionError ||
|
|
1097
|
+
isProviderCancellation(fbErr)
|
|
1098
|
+
) {
|
|
826
1099
|
throw fbErr;
|
|
827
1100
|
}
|
|
1101
|
+
withBreakerSignal(summarizeConfig, graph)?.signal?.throwIfAborted();
|
|
1102
|
+
errorCode = classifySummarizationError(fbErr);
|
|
828
1103
|
const fbDescribed = describeFallbackError(fbErr, fallbacks);
|
|
829
1104
|
log('warn', `Fallback providers also failed ${fbDescribed.suffix}`, {
|
|
830
1105
|
...fbDescribed.data,
|
|
@@ -834,20 +1109,28 @@ async function executeSummarizationWithFallback(params: {
|
|
|
834
1109
|
if (!summaryText) {
|
|
835
1110
|
log(
|
|
836
1111
|
'warn',
|
|
837
|
-
`Summarization failed
|
|
1112
|
+
`Summarization failed; preserving conversation history ${primaryDescribed.suffix}`,
|
|
838
1113
|
{
|
|
839
1114
|
...primaryDescribed.data,
|
|
840
1115
|
messagesToRefineCount: messages.length,
|
|
841
1116
|
}
|
|
842
1117
|
);
|
|
843
|
-
summaryText =
|
|
844
|
-
usedMetadataStub = true;
|
|
1118
|
+
summaryText = '';
|
|
845
1119
|
}
|
|
846
1120
|
}
|
|
847
1121
|
|
|
848
|
-
const trip = findStreamLimitAbortReason(
|
|
1122
|
+
const trip = findStreamLimitAbortReason(
|
|
1123
|
+
graph?.getBreakerSignal?.(),
|
|
1124
|
+
summarizeConfig?.signal
|
|
1125
|
+
);
|
|
849
1126
|
if (trip != null) throw trip;
|
|
850
|
-
return {
|
|
1127
|
+
return {
|
|
1128
|
+
text: summaryText,
|
|
1129
|
+
usage: summaryUsage,
|
|
1130
|
+
provider: summaryProvider,
|
|
1131
|
+
model: summaryModel,
|
|
1132
|
+
...(summaryText === '' ? { errorCode } : {}),
|
|
1133
|
+
};
|
|
851
1134
|
}
|
|
852
1135
|
|
|
853
1136
|
/** Dispatches run step completion, ON_SUMMARIZE_COMPLETE, and rebuilds token map. */
|
|
@@ -859,6 +1142,7 @@ async function dispatchCompletionEvents(params: {
|
|
|
859
1142
|
agentContext: AgentContext;
|
|
860
1143
|
runStep: t.RunStep;
|
|
861
1144
|
summaryUsage?: Partial<UsageMetadata>;
|
|
1145
|
+
attemptUsage: readonly t.SummarizationAttemptUsage[];
|
|
862
1146
|
agentId: string;
|
|
863
1147
|
/**
|
|
864
1148
|
* Number of messages preserved verbatim by the recency window after
|
|
@@ -876,17 +1160,21 @@ async function dispatchCompletionEvents(params: {
|
|
|
876
1160
|
agentContext,
|
|
877
1161
|
runStep,
|
|
878
1162
|
summaryUsage,
|
|
1163
|
+
attemptUsage,
|
|
879
1164
|
agentId,
|
|
880
1165
|
messagesAfterCount,
|
|
881
1166
|
} = params;
|
|
882
1167
|
|
|
883
1168
|
const assertNotTripped = (): void => {
|
|
884
|
-
const trip = findStreamLimitAbortReason(
|
|
1169
|
+
const trip = findStreamLimitAbortReason(
|
|
1170
|
+
graph.getBreakerSignal?.(),
|
|
1171
|
+
runnableConfig?.signal
|
|
1172
|
+
);
|
|
885
1173
|
if (trip != null) throw trip;
|
|
886
1174
|
};
|
|
887
1175
|
assertNotTripped();
|
|
888
1176
|
runStep.summary = summaryBlock;
|
|
889
|
-
if (summaryUsage) {
|
|
1177
|
+
if (summaryUsage && runStep.usage == null) {
|
|
890
1178
|
runStep.usage = {
|
|
891
1179
|
prompt_tokens: Number(summaryUsage.input_tokens) || 0,
|
|
892
1180
|
completion_tokens: Number(summaryUsage.output_tokens) || 0,
|
|
@@ -910,6 +1198,7 @@ async function dispatchCompletionEvents(params: {
|
|
|
910
1198
|
id: stepId,
|
|
911
1199
|
agentId,
|
|
912
1200
|
summary: summaryBlock,
|
|
1201
|
+
...(attemptUsage.length > 0 ? {attemptUsage: [...attemptUsage]} : {}),
|
|
913
1202
|
} satisfies t.SummarizeCompleteEvent,
|
|
914
1203
|
runnableConfig
|
|
915
1204
|
);
|
|
@@ -1033,7 +1322,8 @@ function findStreamLimitAbortReason(
|
|
|
1033
1322
|
for (const signal of signals) {
|
|
1034
1323
|
if (
|
|
1035
1324
|
signal?.aborted === true &&
|
|
1036
|
-
(signal.reason instanceof StreamLimitExceededError ||
|
|
1325
|
+
(signal.reason instanceof StreamLimitExceededError ||
|
|
1326
|
+
signal.reason instanceof ProviderTextProtectionError)
|
|
1037
1327
|
) {
|
|
1038
1328
|
return signal.reason;
|
|
1039
1329
|
}
|
|
@@ -1163,7 +1453,13 @@ export function createSummarizeNode({
|
|
|
1163
1453
|
}
|
|
1164
1454
|
|
|
1165
1455
|
const maxCtx = agentContext.maxContextTokens ?? 0;
|
|
1166
|
-
|
|
1456
|
+
const usesAgentInstructions =
|
|
1457
|
+
(agentContext.summarizationConfig?.provider ?? agentContext.provider) ===
|
|
1458
|
+
agentContext.provider;
|
|
1459
|
+
const instructionOverhead = usesAgentInstructions
|
|
1460
|
+
? agentContext.instructionTokens
|
|
1461
|
+
: agentContext.toolSchemaTokens;
|
|
1462
|
+
if (usesAgentInstructions && maxCtx > 0 && instructionOverhead >= maxCtx) {
|
|
1167
1463
|
if (request.reason === 'manual') {
|
|
1168
1464
|
throw new ManualSummarizationSkippedError(
|
|
1169
1465
|
'instructions_exceed_budget',
|
|
@@ -1185,67 +1481,47 @@ export function createSummarizeNode({
|
|
|
1185
1481
|
return { summarizationRequest: undefined };
|
|
1186
1482
|
}
|
|
1187
1483
|
|
|
1188
|
-
/**
|
|
1189
|
-
* Capture the original-tool-content map locally before doing the
|
|
1190
|
-
* split. We need it in three places: to restore the head for
|
|
1191
|
-
* summarizer quality, to leave intact on the skip path (state is
|
|
1192
|
-
* unchanged), and — critically — to carry forward the tail-relevant
|
|
1193
|
-
* entries on the summarize-fired path. Clearing it eagerly here
|
|
1194
|
-
* would lose the originals for masked tool messages that the
|
|
1195
|
-
* recency window keeps in the tail; a future summarization could
|
|
1196
|
-
* then only summarize the masked stub instead of the full payload.
|
|
1197
|
-
*/
|
|
1198
|
-
const originalPending = agentContext.pendingOriginalToolContent;
|
|
1199
|
-
|
|
1200
|
-
const restoredMessages = restoreOriginalToolContent(
|
|
1201
|
-
state.messages,
|
|
1202
|
-
originalPending,
|
|
1203
|
-
agentContext.maxContextTokens
|
|
1204
|
-
);
|
|
1205
|
-
|
|
1206
1484
|
const runnableConfig = config ?? graph.config;
|
|
1207
|
-
|
|
1485
|
+
const clientConfig = buildSummarizationClientConfig(
|
|
1486
|
+
agentContext,
|
|
1487
|
+
agentContext.summarizationConfig
|
|
1488
|
+
);
|
|
1489
|
+
const windowMessages = request.windowMessages ?? state.messages;
|
|
1208
1490
|
const retainRecent = agentContext.summarizationConfig?.retainRecent;
|
|
1209
|
-
|
|
1210
|
-
* A manual summary is the user asking for the whole history to become a
|
|
1211
|
-
* checkpoint, so the default recency window does not apply to it. A
|
|
1212
|
-
* `retainRecent` the host configured explicitly still keeps its tail,
|
|
1213
|
-
* with the ordinary turn default when it only sets a token cap.
|
|
1214
|
-
*/
|
|
1215
|
-
const retainTurns =
|
|
1216
|
-
request.reason === 'manual' && retainRecent == null
|
|
1217
|
-
? 0
|
|
1218
|
-
: (retainRecent?.turns ?? DEFAULT_RETAIN_RECENT_TURNS);
|
|
1491
|
+
const retainTurns = retainRecent?.turns ?? DEFAULT_RETAIN_RECENT_TURNS;
|
|
1219
1492
|
const recencyTokenCounter =
|
|
1220
1493
|
agentContext.contextPressureTokenCounts?.count ??
|
|
1221
|
-
agentContext.tokenCounter
|
|
1494
|
+
agentContext.tokenCounter ??
|
|
1495
|
+
(await createTokenCounter(encodingForReceivingAgent(agentContext)));
|
|
1496
|
+
const retainTokens =
|
|
1497
|
+
retainRecent?.tokens ??
|
|
1498
|
+
(retainRecent == null
|
|
1499
|
+
? Math.min(
|
|
1500
|
+
DEFAULT_RETAIN_RECENT_TOKENS,
|
|
1501
|
+
Math.max(
|
|
1502
|
+
1,
|
|
1503
|
+
Math.floor((agentContext.maxContextTokens ?? 100_000) * 0.16)
|
|
1504
|
+
)
|
|
1505
|
+
)
|
|
1506
|
+
: undefined);
|
|
1222
1507
|
const {
|
|
1223
|
-
head:
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
} = splitAtRecencyBoundary(restoredMessages, {
|
|
1508
|
+
head: compactableHead,
|
|
1509
|
+
tail: projectedTail,
|
|
1510
|
+
} = splitAtRecencyBoundary(windowMessages, {
|
|
1227
1511
|
provider: agentContext.provider,
|
|
1228
|
-
turns:
|
|
1229
|
-
|
|
1512
|
+
turns:
|
|
1513
|
+
retainRecent == null
|
|
1514
|
+
? retainTurns
|
|
1515
|
+
: (retainRecent.turns ?? DEFAULT_RETAIN_RECENT_TURNS),
|
|
1516
|
+
tokens: retainTokens,
|
|
1230
1517
|
tokenCounter: recencyTokenCounter,
|
|
1231
1518
|
intraTurnTokens: resolveIntraTurnRetainTokens({
|
|
1232
|
-
tokens:
|
|
1519
|
+
tokens: retainTokens,
|
|
1233
1520
|
maxContextTokens: agentContext.maxContextTokens,
|
|
1234
1521
|
}),
|
|
1235
1522
|
});
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
* truncation prune applied to oversized ToolMessage content stays
|
|
1239
|
-
* truncated in live state. The summarizer above reads the restored
|
|
1240
|
-
* (full-content) head for summary quality, but reinjecting restored
|
|
1241
|
-
* tool payloads into state would defeat masking and bloat the
|
|
1242
|
-
* checkpoint, forcing more expensive re-pruning on later turns.
|
|
1243
|
-
* `restoreOriginalToolContent` returns an array with identical
|
|
1244
|
-
* length and structure to `state.messages` (replacements only at
|
|
1245
|
-
* specific indices), so the same tailStartIndex slices both arrays
|
|
1246
|
-
* at the same turn boundary.
|
|
1247
|
-
*/
|
|
1248
|
-
const messagesToRetain = state.messages.slice(tailStartIndex);
|
|
1523
|
+
|
|
1524
|
+
const messagesToRefine = compactableHead;
|
|
1249
1525
|
|
|
1250
1526
|
if (messagesToRefine.length === 0) {
|
|
1251
1527
|
if (request.reason === 'manual') {
|
|
@@ -1268,7 +1544,7 @@ export function createSummarizeNode({
|
|
|
1268
1544
|
'summarize',
|
|
1269
1545
|
'Summarization skipped — recency window retains all messages',
|
|
1270
1546
|
{
|
|
1271
|
-
messagesRetained:
|
|
1547
|
+
messagesRetained: projectedTail.length,
|
|
1272
1548
|
retainTurns,
|
|
1273
1549
|
},
|
|
1274
1550
|
{ runId: graph.runId, agentId: request.agentId }
|
|
@@ -1277,10 +1553,9 @@ export function createSummarizeNode({
|
|
|
1277
1553
|
return { summarizationRequest: undefined };
|
|
1278
1554
|
}
|
|
1279
1555
|
|
|
1280
|
-
const
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
);
|
|
1556
|
+
const messagesToRetain = windowMessages === state.messages
|
|
1557
|
+
? projectedTail : restoreRetainedMessages(projectedTail, state.messages);
|
|
1558
|
+
|
|
1284
1559
|
const semanticIndex = renderCompactionSemanticIndex(
|
|
1285
1560
|
agentContext.compactionSemanticIndex,
|
|
1286
1561
|
messagesToRefine
|
|
@@ -1295,6 +1570,7 @@ export function createSummarizeNode({
|
|
|
1295
1570
|
provider: clientConfig.provider,
|
|
1296
1571
|
};
|
|
1297
1572
|
|
|
1573
|
+
const attemptUsage: t.SummarizationAttemptUsage[] = [];
|
|
1298
1574
|
const runStep: t.RunStep = {
|
|
1299
1575
|
stepIndex,
|
|
1300
1576
|
id: stepId,
|
|
@@ -1442,40 +1718,34 @@ export function createSummarizeNode({
|
|
|
1442
1718
|
const {
|
|
1443
1719
|
text: rawText,
|
|
1444
1720
|
usage: summaryUsage,
|
|
1445
|
-
|
|
1721
|
+
provider: summaryProvider,
|
|
1722
|
+
model: summaryModel,
|
|
1723
|
+
errorCode,
|
|
1446
1724
|
} = await executeSummarizationWithFallback({
|
|
1447
1725
|
agentContext,
|
|
1448
|
-
messages:
|
|
1726
|
+
messages: windowMessages,
|
|
1727
|
+
requiredHeadLength: messagesToRefine.length,
|
|
1728
|
+
onUsage: attempt => {
|
|
1729
|
+
attemptUsage.push(attempt);
|
|
1730
|
+
runStep.usage = buildSummarizationStepUsage(attemptUsage);
|
|
1731
|
+
},
|
|
1449
1732
|
clientConfig,
|
|
1450
1733
|
summarizeConfig,
|
|
1451
1734
|
stepId,
|
|
1452
1735
|
usePromptCache: isSelfSummarizeModel && hasPromptCache,
|
|
1736
|
+
shrinkInput: request.reason === 'overflow',
|
|
1453
1737
|
semanticIndex,
|
|
1454
1738
|
log,
|
|
1455
1739
|
graph,
|
|
1456
1740
|
});
|
|
1457
1741
|
|
|
1458
|
-
|
|
1459
|
-
* The metadata stub describes the history rather than summarizing it, so
|
|
1460
|
-
* committing it means removing the head and keeping nothing of what it
|
|
1461
|
-
* said. That trade is never worth making to paper over an overflow, and
|
|
1462
|
-
* never for a manual compaction, which would replace the whole history
|
|
1463
|
-
* with a message count: the recovery would "succeed" only by destroying
|
|
1464
|
-
* the conversation it was supposed to preserve. Leave state untouched
|
|
1465
|
-
* and let the provider error surface instead.
|
|
1466
|
-
*/
|
|
1467
|
-
if (
|
|
1468
|
-
usedMetadataStub === true &&
|
|
1469
|
-
(request.reason === 'overflow' ||
|
|
1470
|
-
request.reason === 'manual' ||
|
|
1471
|
-
usedIntraTurnFallback)
|
|
1472
|
-
) {
|
|
1742
|
+
if (errorCode != null) {
|
|
1473
1743
|
const preservationReason =
|
|
1474
1744
|
PRESERVATION_REASONS[request.reason ?? 'trigger'] ??
|
|
1475
|
-
'
|
|
1745
|
+
'automatic compaction';
|
|
1476
1746
|
log(
|
|
1477
1747
|
'warn',
|
|
1478
|
-
`Summarization failed during ${preservationReason}; keeping history
|
|
1748
|
+
`Summarization failed during ${preservationReason}; keeping history unchanged`
|
|
1479
1749
|
);
|
|
1480
1750
|
agentContext.markSummarizationTriggered(state.messages.length);
|
|
1481
1751
|
agentContext.recordSummarizationFailure();
|
|
@@ -1484,14 +1754,18 @@ export function createSummarizeNode({
|
|
|
1484
1754
|
* consumers tracking step lifecycle keep an unfinished placeholder for
|
|
1485
1755
|
* the rest of the run.
|
|
1486
1756
|
*/
|
|
1487
|
-
|
|
1488
|
-
stepId,
|
|
1757
|
+
if (graph.closeRunStep != null) {
|
|
1758
|
+
await graph.closeRunStep(stepId, 'failed', runnableConfig);
|
|
1759
|
+
} else {
|
|
1760
|
+
await graph.dispatchRunStepCompleted(
|
|
1761
|
+
stepId,
|
|
1489
1762
|
{
|
|
1490
1763
|
type: 'summary',
|
|
1491
1764
|
summary: placeholderSummary,
|
|
1492
1765
|
} satisfies t.SummaryCompleted,
|
|
1493
1766
|
runnableConfig
|
|
1494
|
-
|
|
1767
|
+
);
|
|
1768
|
+
}
|
|
1495
1769
|
if (runnableConfig) {
|
|
1496
1770
|
await safeDispatchCustomEvent(
|
|
1497
1771
|
GraphEvents.ON_SUMMARIZE_COMPLETE,
|
|
@@ -1499,6 +1773,8 @@ export function createSummarizeNode({
|
|
|
1499
1773
|
id: stepId,
|
|
1500
1774
|
agentId: request.agentId,
|
|
1501
1775
|
error: `Summarization failed during ${preservationReason}; conversation history was preserved`,
|
|
1776
|
+
errorCode,
|
|
1777
|
+
...(attemptUsage.length > 0 ? {attemptUsage: [...attemptUsage]} : {}),
|
|
1502
1778
|
} satisfies t.SummarizeCompleteEvent,
|
|
1503
1779
|
runnableConfig
|
|
1504
1780
|
);
|
|
@@ -1530,6 +1806,8 @@ export function createSummarizeNode({
|
|
|
1530
1806
|
id: stepId,
|
|
1531
1807
|
agentId: request.agentId,
|
|
1532
1808
|
error: 'Summarization produced empty output',
|
|
1809
|
+
errorCode: 'unknown',
|
|
1810
|
+
...(attemptUsage.length > 0 ? {attemptUsage: [...attemptUsage]} : {}),
|
|
1533
1811
|
} satisfies t.SummarizeCompleteEvent,
|
|
1534
1812
|
runnableConfig
|
|
1535
1813
|
);
|
|
@@ -1538,7 +1816,10 @@ export function createSummarizeNode({
|
|
|
1538
1816
|
return { summarizationRequest: undefined };
|
|
1539
1817
|
}
|
|
1540
1818
|
|
|
1541
|
-
const postCallTrip = findStreamLimitAbortReason(
|
|
1819
|
+
const postCallTrip = findStreamLimitAbortReason(
|
|
1820
|
+
entryBreakerSignal,
|
|
1821
|
+
config?.signal
|
|
1822
|
+
);
|
|
1542
1823
|
if (postCallTrip != null) throw postCallTrip;
|
|
1543
1824
|
const summaryText = enrichSummary(rawText, messagesToRefine);
|
|
1544
1825
|
|
|
@@ -1547,9 +1828,14 @@ export function createSummarizeNode({
|
|
|
1547
1828
|
agentContext
|
|
1548
1829
|
);
|
|
1549
1830
|
|
|
1550
|
-
const commitTrip = findStreamLimitAbortReason(
|
|
1831
|
+
const commitTrip = findStreamLimitAbortReason(
|
|
1832
|
+
entryBreakerSignal,
|
|
1833
|
+
config?.signal
|
|
1834
|
+
);
|
|
1551
1835
|
if (commitTrip != null) throw commitTrip;
|
|
1552
|
-
|
|
1836
|
+
runnableConfig?.signal?.throwIfAborted();
|
|
1837
|
+
entryBreakerSignal?.throwIfAborted();
|
|
1838
|
+
if (messagesToRetain.length > 0) {
|
|
1553
1839
|
agentContext.setSummary(summaryText, tokenCount, {
|
|
1554
1840
|
precedesMessages: true,
|
|
1555
1841
|
});
|
|
@@ -1579,8 +1865,8 @@ export function createSummarizeNode({
|
|
|
1579
1865
|
coverage: resolveSummaryCoverage(messagesToRetain),
|
|
1580
1866
|
stepId,
|
|
1581
1867
|
stepIndex: runStep.index,
|
|
1582
|
-
modelName:
|
|
1583
|
-
provider:
|
|
1868
|
+
modelName: summaryModel,
|
|
1869
|
+
provider: summaryProvider,
|
|
1584
1870
|
summaryVersion: agentContext.summaryVersion,
|
|
1585
1871
|
});
|
|
1586
1872
|
|
|
@@ -1592,6 +1878,7 @@ export function createSummarizeNode({
|
|
|
1592
1878
|
agentContext,
|
|
1593
1879
|
runStep,
|
|
1594
1880
|
summaryUsage,
|
|
1881
|
+
attemptUsage,
|
|
1595
1882
|
agentId: request.agentId,
|
|
1596
1883
|
messagesAfterCount: messagesToRetain.length,
|
|
1597
1884
|
});
|
|
@@ -1607,28 +1894,7 @@ export function createSummarizeNode({
|
|
|
1607
1894
|
*/
|
|
1608
1895
|
agentContext.markSummarizationTriggered(messagesToRetain.length);
|
|
1609
1896
|
|
|
1610
|
-
|
|
1611
|
-
* Carry forward the original-content entries that correspond to the
|
|
1612
|
-
* retained tail, reindexed for the post-removeAll state where tail
|
|
1613
|
-
* messages start at index 0. Without this, a future summarization
|
|
1614
|
-
* that pulls these tail messages into its head would only see the
|
|
1615
|
-
* masked stubs (since `setSummary` clears `pruneMessages`, and the
|
|
1616
|
-
* fresh pruner at the next turn has no record of prior masks).
|
|
1617
|
-
* Entries for indices < `tailStartIndex` belong to messages we just
|
|
1618
|
-
* summarized — they are no longer reachable so they are dropped.
|
|
1619
|
-
*/
|
|
1620
|
-
if (originalPending != null && originalPending.size > 0) {
|
|
1621
|
-
const tailPending = new Map<number, string>();
|
|
1622
|
-
for (const [idx, content] of originalPending) {
|
|
1623
|
-
if (idx >= tailStartIndex) {
|
|
1624
|
-
tailPending.set(idx - tailStartIndex, content);
|
|
1625
|
-
}
|
|
1626
|
-
}
|
|
1627
|
-
agentContext.pendingOriginalToolContent =
|
|
1628
|
-
tailPending.size > 0 ? tailPending : undefined;
|
|
1629
|
-
} else {
|
|
1630
|
-
agentContext.pendingOriginalToolContent = undefined;
|
|
1631
|
-
}
|
|
1897
|
+
agentContext.pendingOriginalToolContent = undefined;
|
|
1632
1898
|
|
|
1633
1899
|
return {
|
|
1634
1900
|
summarizationRequest: undefined,
|
|
@@ -1675,6 +1941,46 @@ function extractResponseText(response: { content: string | object }): string {
|
|
|
1675
1941
|
return parts.join('').trim();
|
|
1676
1942
|
}
|
|
1677
1943
|
|
|
1944
|
+
class ToolOnlySummaryError extends ReasoningOnlySummaryError {
|
|
1945
|
+
constructor() {
|
|
1946
|
+
super();
|
|
1947
|
+
this.name = 'ToolOnlySummaryError';
|
|
1948
|
+
this.message = 'The summarizer requested tools instead of summary text';
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
function validateSummaryResponse(response: BaseMessage | undefined): void {
|
|
1953
|
+
if (response == null) return;
|
|
1954
|
+
if (isReasoningOnlySummary(response)) throw new ReasoningOnlySummaryError();
|
|
1955
|
+
if (extractResponseText(response) === '' && 'tool_calls' in response && Array.isArray(response.tool_calls) && response.tool_calls.length > 0) {
|
|
1956
|
+
const kwargs = response.additional_kwargs as {refusal?: string} | undefined;
|
|
1957
|
+
if (kwargs?.refusal != null || getProviderStopReasons(response).some(reason =>
|
|
1958
|
+
reason !== 'end_turn' && reason !== 'stop' && reason !== 'tool_use' && reason !== 'tool_calls'
|
|
1959
|
+
)) return;
|
|
1960
|
+
throw new ToolOnlySummaryError();
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
function isReasoningOnlySummary(response: BaseMessage): boolean {
|
|
1965
|
+
const kwargs = response.additional_kwargs as (BaseMessage['additional_kwargs'] & {refusal?: string}) | undefined;
|
|
1966
|
+
if (kwargs?.refusal != null || getProviderStopReasons(response).some(
|
|
1967
|
+
reason => reason !== 'end_turn' && reason !== 'stop'
|
|
1968
|
+
)) return false;
|
|
1969
|
+
if ('tool_calls' in response && Array.isArray(response.tool_calls) && response.tool_calls.length > 0) return false;
|
|
1970
|
+
if ('invalid_tool_calls' in response && Array.isArray(response.invalid_tool_calls) && response.invalid_tool_calls.length > 0) return false;
|
|
1971
|
+
let hasReasoning = kwargs != null && hasReasoningKwargs(response);
|
|
1972
|
+
if (typeof response.content === 'string') return hasReasoning && response.content.trim() === '';
|
|
1973
|
+
if (!Array.isArray(response.content)) return false;
|
|
1974
|
+
for (const block of response.content) {
|
|
1975
|
+
if (isReasoningContentBlock(block)) {
|
|
1976
|
+
hasReasoning ||= hasMeaningfulReasoningContentBlock(block);
|
|
1977
|
+
continue;
|
|
1978
|
+
}
|
|
1979
|
+
if (block.type !== 'text' || typeof block.text !== 'string' || block.text.trim() !== '') return false;
|
|
1980
|
+
}
|
|
1981
|
+
return hasReasoning;
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1678
1984
|
/** Creates an `onChunk` callback that dispatches `ON_SUMMARIZE_DELTA` events for streaming. */
|
|
1679
1985
|
export function createSummarizationChunkHandler({
|
|
1680
1986
|
stepId,
|
|
@@ -1682,18 +1988,28 @@ export function createSummarizationChunkHandler({
|
|
|
1682
1988
|
provider,
|
|
1683
1989
|
reasoningKey = 'reasoning_content',
|
|
1684
1990
|
graph,
|
|
1991
|
+
pendingDeltas,
|
|
1685
1992
|
}: {
|
|
1686
1993
|
stepId?: string;
|
|
1687
1994
|
config?: RunnableConfig;
|
|
1688
1995
|
provider?: t.ProviderName;
|
|
1689
1996
|
reasoningKey?: 'reasoning_content' | 'reasoning';
|
|
1690
1997
|
graph?: StreamLimitState & { getBreakerController?: () => AbortController };
|
|
1998
|
+
pendingDeltas?: t.SummarizeDeltaEvent[];
|
|
1691
1999
|
}): OnChunk | undefined {
|
|
1692
2000
|
if (stepId == null || stepId === '' || !config) {
|
|
1693
2001
|
return undefined;
|
|
1694
2002
|
}
|
|
1695
2003
|
const limitMetadata = config.metadata as Record<string, unknown> | undefined;
|
|
2004
|
+
let bufferedAttempt: unknown;
|
|
1696
2005
|
return (chunk, attemptMetadata) => {
|
|
2006
|
+
if (
|
|
2007
|
+
pendingDeltas != null &&
|
|
2008
|
+
bufferedAttempt !== attemptMetadata?.[STREAM_LIMIT_ATTEMPT_KEY]
|
|
2009
|
+
) {
|
|
2010
|
+
pendingDeltas.length = 0;
|
|
2011
|
+
bufferedAttempt = attemptMetadata?.[STREAM_LIMIT_ATTEMPT_KEY];
|
|
2012
|
+
}
|
|
1697
2013
|
/**
|
|
1698
2014
|
* Charged as `producer` so it PAIRS with the run's registered stream
|
|
1699
2015
|
* handler: inside a live run the provider callbacks route each chunk
|
|
@@ -1709,8 +2025,8 @@ export function createSummarizationChunkHandler({
|
|
|
1709
2025
|
* breaker-aborting catch never fires for the same chunk — without the
|
|
1710
2026
|
* trip here, sibling model calls, tools, and subagents would keep
|
|
1711
2027
|
* consuming quota while the summary branch rejects.
|
|
1712
|
-
* `executeSummarizationWithFallback`
|
|
1713
|
-
* the
|
|
2028
|
+
* `executeSummarizationWithFallback` rethrows past fallbacks, failing
|
|
2029
|
+
* the run like any other breach.
|
|
1714
2030
|
*/
|
|
1715
2031
|
if (graph != null) {
|
|
1716
2032
|
try {
|
|
@@ -1728,10 +2044,21 @@ export function createSummarizationChunkHandler({
|
|
|
1728
2044
|
throw error;
|
|
1729
2045
|
}
|
|
1730
2046
|
}
|
|
1731
|
-
const protectionTrip = findStreamLimitAbortReason(
|
|
2047
|
+
const protectionTrip = findStreamLimitAbortReason(
|
|
2048
|
+
graph?.getBreakerController?.().signal,
|
|
2049
|
+
config.signal
|
|
2050
|
+
);
|
|
1732
2051
|
if (protectionTrip != null) throw protectionTrip;
|
|
1733
2052
|
const chunkAny = chunk as Parameters<typeof getChunkContent>[0]['chunk'];
|
|
1734
|
-
const
|
|
2053
|
+
const servingProvider =
|
|
2054
|
+
(attemptMetadata?.[Constants.INVOKED_PROVIDER] as
|
|
2055
|
+
| t.ProviderName
|
|
2056
|
+
| undefined) ?? provider;
|
|
2057
|
+
const raw = getChunkContent({
|
|
2058
|
+
chunk: chunkAny,
|
|
2059
|
+
provider: servingProvider,
|
|
2060
|
+
reasoningKey,
|
|
2061
|
+
});
|
|
1735
2062
|
if (raw == null || (typeof raw === 'string' && !raw)) {
|
|
1736
2063
|
return;
|
|
1737
2064
|
}
|
|
@@ -1740,21 +2067,28 @@ export function createSummarizationChunkHandler({
|
|
|
1740
2067
|
? [{ type: ContentTypes.TEXT, text: raw } as t.MessageContentComplex]
|
|
1741
2068
|
: raw;
|
|
1742
2069
|
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
{
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
2070
|
+
const event: t.SummarizeDeltaEvent = {
|
|
2071
|
+
id: stepId,
|
|
2072
|
+
delta: {
|
|
2073
|
+
summary: {
|
|
2074
|
+
type: ContentTypes.SUMMARY,
|
|
2075
|
+
content: contentBlocks,
|
|
2076
|
+
provider: String(
|
|
2077
|
+
servingProvider ?? config.metadata?.summarization_provider ?? ''
|
|
2078
|
+
),
|
|
2079
|
+
model: String(
|
|
2080
|
+
attemptMetadata?.[Constants.INVOKED_MODEL] ??
|
|
2081
|
+
config.metadata?.summarization_model ??
|
|
2082
|
+
''
|
|
2083
|
+
),
|
|
1754
2084
|
},
|
|
1755
|
-
}
|
|
1756
|
-
|
|
1757
|
-
)
|
|
2085
|
+
},
|
|
2086
|
+
};
|
|
2087
|
+
if (pendingDeltas != null) {
|
|
2088
|
+
pendingDeltas.push(event);
|
|
2089
|
+
return;
|
|
2090
|
+
}
|
|
2091
|
+
void safeDispatchCustomEvent(GraphEvents.ON_SUMMARIZE_DELTA, event, config);
|
|
1758
2092
|
};
|
|
1759
2093
|
}
|
|
1760
2094
|
|
|
@@ -1809,13 +2143,19 @@ export function resolveBedrockCompactionCacheModel(
|
|
|
1809
2143
|
/**
|
|
1810
2144
|
* Cache-friendly compaction: sends raw conversation messages with the
|
|
1811
2145
|
* summarization instruction appended as the final HumanMessage. Bound tool
|
|
1812
|
-
* definitions
|
|
1813
|
-
*
|
|
1814
|
-
* this summarization path does not currently own.
|
|
2146
|
+
* definitions and the turn's system runnable preserve the cached prefix.
|
|
2147
|
+
* Tool output stays masked and the final instruction has reserved headroom.
|
|
1815
2148
|
*/
|
|
1816
2149
|
async function summarizeWithCacheHit({
|
|
2150
|
+
agentContext,
|
|
2151
|
+
onUsage,
|
|
2152
|
+
shrinkInput,
|
|
2153
|
+
outputTokens,
|
|
2154
|
+
clientOptions,
|
|
1817
2155
|
model,
|
|
2156
|
+
tools,
|
|
1818
2157
|
messages,
|
|
2158
|
+
requiredHeadLength,
|
|
1819
2159
|
promptText,
|
|
1820
2160
|
updatePromptText,
|
|
1821
2161
|
priorSummaryText,
|
|
@@ -1830,8 +2170,15 @@ async function summarizeWithCacheHit({
|
|
|
1830
2170
|
bedrockModelId,
|
|
1831
2171
|
log,
|
|
1832
2172
|
}: {
|
|
2173
|
+
agentContext: AgentContext;
|
|
2174
|
+
onUsage: (usage: Partial<UsageMetadata>) => void;
|
|
2175
|
+
shrinkInput?: boolean;
|
|
2176
|
+
outputTokens: number | undefined;
|
|
2177
|
+
clientOptions?: t.ClientOptions;
|
|
1833
2178
|
model: t.ChatModel;
|
|
2179
|
+
tools?: t.GraphTools;
|
|
1834
2180
|
messages: BaseMessage[];
|
|
2181
|
+
requiredHeadLength: number;
|
|
1835
2182
|
promptText: string;
|
|
1836
2183
|
updatePromptText?: string;
|
|
1837
2184
|
priorSummaryText: string;
|
|
@@ -1850,64 +2197,110 @@ async function summarizeWithCacheHit({
|
|
|
1850
2197
|
promptText,
|
|
1851
2198
|
updatePromptText,
|
|
1852
2199
|
priorSummaryText,
|
|
1853
|
-
semanticIndexAppendix
|
|
2200
|
+
semanticIndexAppendix,
|
|
2201
|
+
provider === agentContext.provider && agentContext.systemRunnable != null
|
|
1854
2202
|
);
|
|
1855
2203
|
|
|
1856
|
-
const
|
|
1857
|
-
|
|
2204
|
+
const { count, system, budget } = await prepareSummarizationBudget({
|
|
2205
|
+
agentContext,
|
|
2206
|
+
model,
|
|
1858
2207
|
provider,
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
2208
|
+
clientOptions,
|
|
2209
|
+
maxContextTokens: agentContext.maxContextTokens,
|
|
2210
|
+
outputTokens,
|
|
2211
|
+
contextBudgetMode: agentContext.summarizationBudgetMode,
|
|
2212
|
+
instruction,
|
|
2213
|
+
tools,
|
|
2214
|
+
config,
|
|
1862
2215
|
});
|
|
1863
|
-
const
|
|
1864
|
-
|
|
1865
|
-
const
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
messages: invokeMessages,
|
|
1869
|
-
provider,
|
|
1870
|
-
onChunk: createSummarizationChunkHandler({
|
|
1871
|
-
stepId,
|
|
1872
|
-
config: traceConfig(config, 'cache_hit_compaction'),
|
|
1873
|
-
provider,
|
|
1874
|
-
reasoningKey,
|
|
1875
|
-
graph,
|
|
1876
|
-
}),
|
|
1877
|
-
/** Accounting lease only (summarization passes no `context` so its
|
|
1878
|
-
* producer claim never stacks with the onChunk handler's). */
|
|
1879
|
-
streamLimitState: graph,
|
|
1880
|
-
},
|
|
1881
|
-
withBreakerSignal(traceConfig(config, 'cache_hit_compaction'), graph)
|
|
2216
|
+
const scales = [1, 0.85, 0.65, 0.45, 0.3];
|
|
2217
|
+
let result: Partial<t.BaseGraphState> | undefined;
|
|
2218
|
+
const initialTokens = messages.reduce(
|
|
2219
|
+
(total, message) => total + count(message),
|
|
2220
|
+
0
|
|
1882
2221
|
);
|
|
2222
|
+
let lastError: unknown;
|
|
2223
|
+
for (let attempt = 0; attempt < scales.length; attempt++) {
|
|
2224
|
+
const signalConfig = withBreakerSignal(
|
|
2225
|
+
traceConfig(config, 'cache_hit_compaction'),
|
|
2226
|
+
graph
|
|
2227
|
+
);
|
|
2228
|
+
signalConfig?.signal?.throwIfAborted();
|
|
2229
|
+
const boundedHistory = boundSummarizationInput({
|
|
2230
|
+
messages,
|
|
2231
|
+
requiredHeadLength,
|
|
2232
|
+
tokenCounter: count,
|
|
2233
|
+
budget: Math.floor(
|
|
2234
|
+
Math.min(
|
|
2235
|
+
budget,
|
|
2236
|
+
attempt === 0 && shrinkInput !== true ? budget : initialTokens
|
|
2237
|
+
) * scales[attempt]
|
|
2238
|
+
),
|
|
2239
|
+
provider,
|
|
2240
|
+
shrink: attempt > 0 || shrinkInput === true,
|
|
2241
|
+
});
|
|
2242
|
+
const windowWithCache = provider === Providers.BEDROCK
|
|
2243
|
+
? applySummarizationHistoryCache({messages: boundedHistory, provider, enabled: usePromptCache === true, promptCacheTtl, bedrockModelId})
|
|
2244
|
+
: boundedHistory;
|
|
2245
|
+
const history = system == null ? windowWithCache : await system.invoke(windowWithCache, config);
|
|
2246
|
+
const cachedHistory =
|
|
2247
|
+
system != null || provider === Providers.BEDROCK
|
|
2248
|
+
? history
|
|
2249
|
+
: applySummarizationHistoryCache({
|
|
2250
|
+
messages: history,
|
|
2251
|
+
provider,
|
|
2252
|
+
enabled: usePromptCache === true,
|
|
2253
|
+
promptCacheTtl,
|
|
2254
|
+
bedrockModelId,
|
|
2255
|
+
});
|
|
2256
|
+
const pendingDeltas: t.SummarizeDeltaEvent[] = [];
|
|
2257
|
+
try {
|
|
2258
|
+
result = await attemptInvoke(
|
|
2259
|
+
{
|
|
2260
|
+
model,
|
|
2261
|
+
messages: [...cachedHistory, new HumanMessage(instruction)],
|
|
2262
|
+
provider,
|
|
2263
|
+
onModelComplete: response => {
|
|
2264
|
+
const usage = readSummarizationUsage(response);
|
|
2265
|
+
if (usage != null) onUsage(usage);
|
|
2266
|
+
},
|
|
2267
|
+
onChunk: createSummarizationChunkHandler({
|
|
2268
|
+
stepId,
|
|
2269
|
+
config: traceConfig(config, 'cache_hit_compaction'),
|
|
2270
|
+
provider,
|
|
2271
|
+
reasoningKey,
|
|
2272
|
+
graph,
|
|
2273
|
+
pendingDeltas,
|
|
2274
|
+
}),
|
|
2275
|
+
streamLimitState: graph,
|
|
2276
|
+
},
|
|
2277
|
+
signalConfig
|
|
2278
|
+
);
|
|
2279
|
+
const response = result.messages?.[0];
|
|
2280
|
+
signalConfig?.signal?.throwIfAborted();
|
|
2281
|
+
validateSummaryResponse(response);
|
|
2282
|
+
if (response != null && extractResponseText(response) !== '') {
|
|
2283
|
+
await flushSummarizationDeltas(pendingDeltas, config, graph);
|
|
2284
|
+
}
|
|
2285
|
+
break;
|
|
2286
|
+
} catch (error) {
|
|
2287
|
+
signalConfig?.signal?.throwIfAborted();
|
|
2288
|
+
if (classifySummarizationError(error) !== 'context_exceeded') throw error;
|
|
2289
|
+
lastError = error;
|
|
2290
|
+
log?.('debug', 'Shrinking summarization context', {
|
|
2291
|
+
attempt: attempt + 1,
|
|
2292
|
+
});
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
if (result == null) throw lastError;
|
|
1883
2296
|
|
|
1884
2297
|
const responseMsg = result.messages?.[0];
|
|
1885
2298
|
const text = responseMsg
|
|
1886
2299
|
? extractResponseText(responseMsg as { content: string | object })
|
|
1887
2300
|
: '';
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
responseMsg != null &&
|
|
1892
|
-
'usage_metadata' in responseMsg &&
|
|
1893
|
-
responseMsg.usage_metadata != null
|
|
1894
|
-
) {
|
|
1895
|
-
usage = responseMsg.usage_metadata as Partial<UsageMetadata>;
|
|
1896
|
-
usageSource = 'usage_metadata';
|
|
1897
|
-
} else if (responseMsg != null) {
|
|
1898
|
-
const respMeta = responseMsg.response_metadata as
|
|
1899
|
-
| Record<string, unknown>
|
|
1900
|
-
| undefined;
|
|
1901
|
-
const raw = (respMeta?.metadata as Record<string, unknown> | undefined)
|
|
1902
|
-
?.usage as Record<string, unknown> | undefined;
|
|
1903
|
-
if (raw != null) {
|
|
1904
|
-
usage = {
|
|
1905
|
-
input_tokens: Number(raw.inputTokens) || undefined,
|
|
1906
|
-
output_tokens: Number(raw.outputTokens) || undefined,
|
|
1907
|
-
} as Partial<UsageMetadata>;
|
|
1908
|
-
usageSource = 'response_metadata';
|
|
1909
|
-
}
|
|
1910
|
-
}
|
|
2301
|
+
const usage = readSummarizationUsage(responseMsg);
|
|
2302
|
+
const usageSource = responseMsg != null && 'usage_metadata' in responseMsg && responseMsg.usage_metadata != null
|
|
2303
|
+
? 'usage_metadata' : 'response_metadata';
|
|
1911
2304
|
const cacheDetails = (
|
|
1912
2305
|
usage as
|
|
1913
2306
|
| {
|
|
@@ -1919,7 +2312,7 @@ async function summarizeWithCacheHit({
|
|
|
1919
2312
|
| undefined
|
|
1920
2313
|
)?.input_token_details;
|
|
1921
2314
|
log?.('debug', 'Summarization LLM usage', {
|
|
1922
|
-
source: usageSource,
|
|
2315
|
+
source: usage == null ? 'none' : usageSource,
|
|
1923
2316
|
input_tokens: usage?.input_tokens,
|
|
1924
2317
|
output_tokens: usage?.output_tokens,
|
|
1925
2318
|
...(cacheDetails?.cache_read != null || cacheDetails?.cache_creation != null
|