@librechat/agents 4.2.16 → 4.2.18
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 +63 -2
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +152 -10
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/acceptedModelResponse.cjs +24 -15
- package/dist/cjs/graphs/acceptedModelResponse.cjs.map +1 -1
- package/dist/cjs/llm/truncation.cjs +4 -0
- package/dist/cjs/llm/truncation.cjs.map +1 -1
- package/dist/cjs/llm/vertexai/index.cjs +2 -3
- package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +2 -1
- package/dist/cjs/messages/cache.cjs +1 -0
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +20 -5
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/run.cjs +4 -0
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +55 -30
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +20 -2
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/utils/toolContent.cjs +32 -16
- package/dist/cjs/utils/toolContent.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +64 -3
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +153 -11
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/acceptedModelResponse.mjs +24 -15
- package/dist/esm/graphs/acceptedModelResponse.mjs.map +1 -1
- package/dist/esm/llm/truncation.mjs +4 -1
- package/dist/esm/llm/truncation.mjs.map +1 -1
- package/dist/esm/llm/vertexai/index.mjs +2 -3
- package/dist/esm/llm/vertexai/index.mjs.map +1 -1
- package/dist/esm/main.mjs +3 -3
- package/dist/esm/messages/cache.mjs +1 -1
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +22 -7
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/run.mjs +4 -0
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +55 -31
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +20 -2
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/utils/toolContent.mjs +32 -17
- package/dist/esm/utils/toolContent.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +15 -0
- package/dist/types/graphs/Graph.d.ts +12 -2
- package/dist/types/llm/truncation.d.ts +8 -0
- package/dist/types/messages/cache.d.ts +9 -0
- package/dist/types/run.d.ts +2 -0
- package/dist/types/summarization/node.d.ts +5 -0
- package/dist/types/types/graph.d.ts +9 -1
- package/dist/types/types/run.d.ts +2 -0
- package/dist/types/types/stream.d.ts +2 -0
- package/dist/types/types/summarize.d.ts +7 -2
- package/dist/types/utils/toolContent.d.ts +6 -0
- package/package.json +1 -1
- package/src/agents/AgentContext.ts +137 -1
- package/src/graphs/Graph.ts +468 -180
- package/src/graphs/acceptedModelResponse.ts +31 -24
- package/src/llm/truncation.ts +16 -0
- package/src/llm/vertexai/index.ts +5 -4
- package/src/messages/cache.ts +1 -1
- package/src/messages/core.ts +37 -5
- package/src/run.ts +8 -0
- package/src/summarization/node.ts +74 -33
- package/src/tools/ToolNode.ts +67 -8
- package/src/types/graph.ts +9 -0
- package/src/types/run.ts +2 -0
- package/src/types/stream.ts +2 -0
- package/src/types/summarize.ts +11 -2
- package/src/utils/toolContent.ts +72 -21
|
@@ -262,6 +262,25 @@ function snapshotToolRecords(
|
|
|
262
262
|
return result;
|
|
263
263
|
}
|
|
264
264
|
|
|
265
|
+
function snapshotMessageKwargs(value: unknown): object {
|
|
266
|
+
if (value === null || typeof value !== 'object' || types.isProxy(value)) {
|
|
267
|
+
throw new InvalidModelToolCallError('Invalid model response metadata');
|
|
268
|
+
}
|
|
269
|
+
const copy: object = Object.create(Object.getPrototypeOf(value));
|
|
270
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
271
|
+
const field = Object.getOwnPropertyDescriptor(value, key)!;
|
|
272
|
+
if (typeof key === 'string') {
|
|
273
|
+
if (!('value' in field)) {
|
|
274
|
+
throw new InvalidModelToolCallError('Invalid model response metadata');
|
|
275
|
+
}
|
|
276
|
+
field.configurable = true;
|
|
277
|
+
field.writable = true;
|
|
278
|
+
}
|
|
279
|
+
Object.defineProperty(copy, key, field);
|
|
280
|
+
}
|
|
281
|
+
return copy;
|
|
282
|
+
}
|
|
283
|
+
|
|
265
284
|
/** Providers can mutate and re-yield records. Inspect a per-emission snapshot,
|
|
266
285
|
* leaving their originals intact, but keep producer/consumer charge identity.
|
|
267
286
|
*/
|
|
@@ -274,33 +293,21 @@ export function snapshotValidatedModelChunk(
|
|
|
274
293
|
'Accepted model response contains non-serializable tool calls'
|
|
275
294
|
);
|
|
276
295
|
}
|
|
277
|
-
const
|
|
278
|
-
|
|
279
|
-
//
|
|
280
|
-
for (const
|
|
281
|
-
|
|
282
|
-
if ('
|
|
283
|
-
}
|
|
284
|
-
const kwargs = descriptors.lc_kwargs;
|
|
285
|
-
if (Object.hasOwn(descriptors, 'lc_kwargs') && 'value' in kwargs) {
|
|
286
|
-
const value: unknown = kwargs.value;
|
|
287
|
-
if (value === null || typeof value !== 'object' || types.isProxy(value)) {
|
|
288
|
-
throw new InvalidModelToolCallError('Invalid model response metadata');
|
|
289
|
-
}
|
|
290
|
-
const fields = Object.getOwnPropertyDescriptors(value);
|
|
291
|
-
for (const field of Object.values(fields)) {
|
|
292
|
-
if (!('value' in field)) {
|
|
293
|
-
throw new InvalidModelToolCallError('Invalid model response metadata');
|
|
294
|
-
}
|
|
296
|
+
const copy = Object.create(Object.getPrototypeOf(message)) as AIMessageChunk;
|
|
297
|
+
const source: object = Object(message);
|
|
298
|
+
// Thaw string-keyed fields for LangChain; preserve symbol descriptors as-is.
|
|
299
|
+
for (const key of Reflect.ownKeys(source)) {
|
|
300
|
+
const field = Object.getOwnPropertyDescriptor(source, key)!;
|
|
301
|
+
if (typeof key === 'string') {
|
|
295
302
|
field.configurable = true;
|
|
296
|
-
field
|
|
303
|
+
if ('value' in field) {
|
|
304
|
+
field.writable = true;
|
|
305
|
+
if (key === 'lc_kwargs')
|
|
306
|
+
field.value = snapshotMessageKwargs(field.value);
|
|
307
|
+
}
|
|
297
308
|
}
|
|
298
|
-
|
|
309
|
+
Object.defineProperty(copy, key, field);
|
|
299
310
|
}
|
|
300
|
-
const copy = Object.create(
|
|
301
|
-
Object.getPrototypeOf(message),
|
|
302
|
-
descriptors
|
|
303
|
-
) as AIMessageChunk;
|
|
304
311
|
detachValidatedModelToolCalls(copy, partial);
|
|
305
312
|
if (partial) linkStreamLimitCanonical(copy, message);
|
|
306
313
|
return copy;
|
package/src/llm/truncation.ts
CHANGED
|
@@ -83,6 +83,22 @@ export function getProviderStopReasons(
|
|
|
83
83
|
return reasons;
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
+
/**
|
|
87
|
+
* Whether Anthropic paused the turn (`stop_reason: 'pause_turn'`). Anthropic
|
|
88
|
+
* returns this when a long-running server tool loop hit its iteration limit;
|
|
89
|
+
* the caller is expected to send the response back unchanged so the turn
|
|
90
|
+
* continues. Reads the same invoke (`response_metadata`) and stream
|
|
91
|
+
* (`additional_kwargs`) fields as {@link getProviderStopReasons}.
|
|
92
|
+
*/
|
|
93
|
+
export function isPauseTurn(
|
|
94
|
+
message:
|
|
95
|
+
| Pick<BaseMessage, 'response_metadata' | 'additional_kwargs'>
|
|
96
|
+
| undefined
|
|
97
|
+
| null
|
|
98
|
+
): boolean {
|
|
99
|
+
return getProviderStopReasons(message).includes('pause_turn');
|
|
100
|
+
}
|
|
101
|
+
|
|
86
102
|
/**
|
|
87
103
|
* Reads the truncation stop reason off a message, covering every provider
|
|
88
104
|
* shape we stream:
|
|
@@ -152,7 +152,9 @@ export function fixThoughtSignatures(
|
|
|
152
152
|
|
|
153
153
|
type VertexResponseData = Omit<Partial<GenerateContentResponseData>, 'candidates'> & {
|
|
154
154
|
candidates?: Array<Omit<Partial<GeminiResponseCandidate>, 'content'> & {
|
|
155
|
-
|
|
155
|
+
/** Vertex can send a candidate's `content` without `parts`, e.g. `{ role: 'model' }`. */
|
|
156
|
+
content?: Omit<GeminiResponseCandidate['content'], 'parts'> &
|
|
157
|
+
Partial<Pick<GeminiResponseCandidate['content'], 'parts'>>;
|
|
156
158
|
}>;
|
|
157
159
|
};
|
|
158
160
|
|
|
@@ -178,9 +180,8 @@ class CustomChatConnection extends ChatConnection<VertexAIClientOptions> {
|
|
|
178
180
|
responseToChatGeneration: (response): ChatGenerationChunk | null => {
|
|
179
181
|
const data = response.data as VertexResponseData;
|
|
180
182
|
const candidate = data.candidates?.[0];
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
if (parts.length === 0)
|
|
183
|
+
const parts = candidate?.content?.parts;
|
|
184
|
+
if (candidate?.content == null || parts == null || parts.length === 0)
|
|
184
185
|
return api.responseToChatGeneration(response);
|
|
185
186
|
let combined: ChatGenerationChunk | undefined;
|
|
186
187
|
let generationInfo: ChatGenerationChunk['generationInfo'];
|
package/src/messages/cache.ts
CHANGED
|
@@ -590,7 +590,7 @@ const SKILL_MESSAGE_SOURCE = 'skill';
|
|
|
590
590
|
* them; only the *adding* of new markers is suppressed. Detected via
|
|
591
591
|
* `additional_kwargs.isMeta === true` or `additional_kwargs.source === 'skill'`.
|
|
592
592
|
*/
|
|
593
|
-
function isSyntheticMetaMessage(message: MessageWithContent): boolean {
|
|
593
|
+
export function isSyntheticMetaMessage(message: MessageWithContent): boolean {
|
|
594
594
|
const { additional_kwargs: kwargs } = message as {
|
|
595
595
|
additional_kwargs?: { isMeta?: unknown; source?: unknown };
|
|
596
596
|
};
|
package/src/messages/core.ts
CHANGED
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
getBoundedCacheControlledTextToolContent,
|
|
24
24
|
getBoundedSingleTextToolContent,
|
|
25
25
|
getComputerCallOutputScreenshot,
|
|
26
|
+
getToolContentImageUrl,
|
|
26
27
|
hasComputerCallOutputMarker,
|
|
27
28
|
isComputerCallOutputMessage,
|
|
28
29
|
serializeToolContentBounded,
|
|
@@ -42,7 +43,10 @@ import {
|
|
|
42
43
|
stampSyntheticProviderMessage,
|
|
43
44
|
} from './provenance';
|
|
44
45
|
import { ANTHROPIC_SERVER_TOOL_RESULT_TYPES } from './anthropicServerTools';
|
|
45
|
-
import {
|
|
46
|
+
import {
|
|
47
|
+
HARD_MAX_TOOL_RESULT_CHARS,
|
|
48
|
+
HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE,
|
|
49
|
+
} from '@/utils/truncation';
|
|
46
50
|
import { isReasoningContentBlock } from './reasoningTypes';
|
|
47
51
|
import { stripAnthropicCacheControl } from './cache';
|
|
48
52
|
import { ContentTypes, Providers } from '@/common';
|
|
@@ -530,6 +534,10 @@ interface BoundedContentAccumulator {
|
|
|
530
534
|
readonly blocks: t.MessageContentComplex[];
|
|
531
535
|
hasContent: boolean;
|
|
532
536
|
remainingChars: number;
|
|
537
|
+
/** Image URL characters, budgeted apart from `remainingChars`: an image's
|
|
538
|
+
* context cost follows its pixel size, which the serving payload measure
|
|
539
|
+
* estimates, not the length of its base64 encoding. */
|
|
540
|
+
remainingImageChars: number;
|
|
533
541
|
}
|
|
534
542
|
|
|
535
543
|
function createBoundedContentAccumulator(
|
|
@@ -541,9 +549,25 @@ function createBoundedContentAccumulator(
|
|
|
541
549
|
remainingChars: Number.isFinite(maxChars)
|
|
542
550
|
? Math.max(0, Math.floor(maxChars))
|
|
543
551
|
: Number.MAX_SAFE_INTEGER,
|
|
552
|
+
remainingImageChars: HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE,
|
|
544
553
|
};
|
|
545
554
|
}
|
|
546
555
|
|
|
556
|
+
/** Appends a well-formed `image_url` block against the image budget. */
|
|
557
|
+
function appendBoundedImageBlock(
|
|
558
|
+
accumulator: BoundedContentAccumulator,
|
|
559
|
+
block: unknown
|
|
560
|
+
): boolean {
|
|
561
|
+
const url = getToolContentImageUrl(block);
|
|
562
|
+
if (url == null || url.length > accumulator.remainingImageChars) {
|
|
563
|
+
return false;
|
|
564
|
+
}
|
|
565
|
+
accumulator.blocks.push(block as t.MessageContentComplex);
|
|
566
|
+
accumulator.hasContent = true;
|
|
567
|
+
accumulator.remainingImageChars -= url.length;
|
|
568
|
+
return true;
|
|
569
|
+
}
|
|
570
|
+
|
|
547
571
|
/** Appends a segment only when at least one of its provider-visible bytes fits.
|
|
548
572
|
* Each segment is compacted against the remaining budget before combination,
|
|
549
573
|
* so a later segment cannot be credited merely because recompression replaced
|
|
@@ -592,7 +616,18 @@ function appendBoundedContentContribution(
|
|
|
592
616
|
}
|
|
593
617
|
const retainedContentPartIndices = new Set<number>();
|
|
594
618
|
let complete = true;
|
|
619
|
+
/** Once text cannot fit, later text is dropped, but images still have their
|
|
620
|
+
* own budget, so the scan goes on for them instead of stopping. */
|
|
621
|
+
let textExhausted = false;
|
|
595
622
|
for (let index = 0; index < next.length; index++) {
|
|
623
|
+
if (appendBoundedImageBlock(accumulator, next[index])) {
|
|
624
|
+
retainedContentPartIndices.add(index);
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
if (textExhausted) {
|
|
628
|
+
complete = false;
|
|
629
|
+
continue;
|
|
630
|
+
}
|
|
596
631
|
const projection = appendBoundedContentSegment(accumulator, [next[index]]);
|
|
597
632
|
if (!projection.complete) {
|
|
598
633
|
complete = false;
|
|
@@ -600,10 +635,7 @@ function appendBoundedContentContribution(
|
|
|
600
635
|
if (!projection.contributed) {
|
|
601
636
|
const separatorChars = accumulator.hasContent ? 1 : 0;
|
|
602
637
|
if (accumulator.remainingChars <= separatorChars) {
|
|
603
|
-
|
|
604
|
-
complete = false;
|
|
605
|
-
}
|
|
606
|
-
break;
|
|
638
|
+
textExhausted = true;
|
|
607
639
|
}
|
|
608
640
|
continue;
|
|
609
641
|
}
|
package/src/run.ts
CHANGED
|
@@ -497,6 +497,8 @@ function getResumeUpdateMessages(
|
|
|
497
497
|
}
|
|
498
498
|
|
|
499
499
|
export class Run<_T extends t.BaseGraphState> {
|
|
500
|
+
static readonly supportsQueuedCompaction = true;
|
|
501
|
+
|
|
500
502
|
id: string;
|
|
501
503
|
private tokenCounter?: t.TokenCounter;
|
|
502
504
|
private handlerRegistry?: HandlerRegistry;
|
|
@@ -515,6 +517,7 @@ export class Run<_T extends t.BaseGraphState> {
|
|
|
515
517
|
private providerTextProtection?: t.StandardGraphInput['providerTextProtection'];
|
|
516
518
|
private toolResultProtection?: t.StandardGraphInput['toolResultProtection'];
|
|
517
519
|
private resolveAttachment?: t.StandardGraphInput['resolveAttachment'];
|
|
520
|
+
private readonly claimQueuedCompaction?: t.ClaimQueuedCompaction;
|
|
518
521
|
private streamLimits?: t.StreamLimits;
|
|
519
522
|
private subagentTasks?: t.SubagentTaskConfig;
|
|
520
523
|
private subagentContext?: t.SubagentContextAdapter;
|
|
@@ -617,6 +620,10 @@ export class Run<_T extends t.BaseGraphState> {
|
|
|
617
620
|
this.maxStopContinuations = resolveMaxStopContinuations(
|
|
618
621
|
config.maxStopContinuations
|
|
619
622
|
);
|
|
623
|
+
this.claimQueuedCompaction =
|
|
624
|
+
config.graphConfig?.type === 'multi-agent'
|
|
625
|
+
? undefined
|
|
626
|
+
: config.claimQueuedCompaction;
|
|
620
627
|
this.streamLimits = config.streamLimits;
|
|
621
628
|
this.providerTextProtection = config.providerTextProtection;
|
|
622
629
|
this.toolResultProtection = config.toolResultProtection;
|
|
@@ -733,6 +740,7 @@ export class Run<_T extends t.BaseGraphState> {
|
|
|
733
740
|
signal,
|
|
734
741
|
runId: this.id,
|
|
735
742
|
agents: [agentConfig],
|
|
743
|
+
claimQueuedCompaction: this.claimQueuedCompaction,
|
|
736
744
|
langfuse: this.langfuse,
|
|
737
745
|
tokenCounter: this.tokenCounter,
|
|
738
746
|
indexTokenCountMap: this.indexTokenCountMap,
|
|
@@ -4,6 +4,7 @@ import type { RunnableConfig } from '@langchain/core/runnables';
|
|
|
4
4
|
import type { RenderedCompactionSemanticIndex } from '@/summarization/semanticIndex';
|
|
5
5
|
import type { StreamLimitState } from '@/llm/streamLimits';
|
|
6
6
|
import type { AgentContext } from '@/agents/AgentContext';
|
|
7
|
+
import type { RecencySplit } from '@/messages/recency';
|
|
7
8
|
import type { EncodingName } from '@/utils/tokens';
|
|
8
9
|
import type { HookRegistry } from '@/hooks';
|
|
9
10
|
import type { OnChunk } from '@/llm/invoke';
|
|
@@ -1557,8 +1558,43 @@ const PRESERVATION_REASONS: Partial<
|
|
|
1557
1558
|
> = {
|
|
1558
1559
|
overflow: 'overflow recovery',
|
|
1559
1560
|
manual: 'manual compaction',
|
|
1561
|
+
queued: 'manual compaction',
|
|
1560
1562
|
};
|
|
1561
1563
|
|
|
1564
|
+
export async function resolveSummaryRecencyWindow(
|
|
1565
|
+
agentContext: AgentContext,
|
|
1566
|
+
windowMessages: BaseMessage[],
|
|
1567
|
+
queued: boolean
|
|
1568
|
+
): Promise<RecencySplit> {
|
|
1569
|
+
const retainRecent = agentContext.summarizationConfig?.retainRecent;
|
|
1570
|
+
const retainTurns = retainRecent?.turns ?? DEFAULT_RETAIN_RECENT_TURNS;
|
|
1571
|
+
const recencyTokenCounter =
|
|
1572
|
+
agentContext.contextPressureTokenCounts?.count ??
|
|
1573
|
+
agentContext.tokenCounter ??
|
|
1574
|
+
(await createTokenCounter(encodingForReceivingAgent(agentContext)));
|
|
1575
|
+
const retainTokens =
|
|
1576
|
+
retainRecent?.tokens ??
|
|
1577
|
+
(retainRecent == null
|
|
1578
|
+
? Math.min(
|
|
1579
|
+
DEFAULT_RETAIN_RECENT_TOKENS,
|
|
1580
|
+
Math.max(
|
|
1581
|
+
1,
|
|
1582
|
+
Math.floor((agentContext.maxContextTokens ?? 100_000) * 0.16)
|
|
1583
|
+
)
|
|
1584
|
+
)
|
|
1585
|
+
: undefined);
|
|
1586
|
+
return splitAtRecencyBoundary(windowMessages, {
|
|
1587
|
+
provider: agentContext.provider,
|
|
1588
|
+
turns: queued ? Math.max(1, retainTurns) : retainTurns,
|
|
1589
|
+
tokens: retainTokens,
|
|
1590
|
+
tokenCounter: recencyTokenCounter,
|
|
1591
|
+
intraTurnTokens: resolveIntraTurnRetainTokens({
|
|
1592
|
+
tokens: retainTokens,
|
|
1593
|
+
maxContextTokens: agentContext.maxContextTokens,
|
|
1594
|
+
}),
|
|
1595
|
+
});
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1562
1598
|
export function createSummarizeNode({
|
|
1563
1599
|
agentContext,
|
|
1564
1600
|
graph: adapterGraph,
|
|
@@ -1568,12 +1604,15 @@ export function createSummarizeNode({
|
|
|
1568
1604
|
state: {
|
|
1569
1605
|
messages: BaseMessage[];
|
|
1570
1606
|
summarizationRequest?: t.SummarizationNodeInput;
|
|
1607
|
+
queuedCompactionSummary?: t.AgentSubgraphState['queuedCompactionSummary'];
|
|
1571
1608
|
},
|
|
1572
1609
|
config?: RunnableConfig
|
|
1573
1610
|
): Promise<{
|
|
1574
1611
|
summarizationRequest: undefined;
|
|
1575
1612
|
messages?: BaseMessage[];
|
|
1576
1613
|
manualSummary?: string;
|
|
1614
|
+
queuedCompactionApplied?: boolean;
|
|
1615
|
+
queuedCompactionSummary?: t.AgentSubgraphState['queuedCompactionSummary'];
|
|
1577
1616
|
}> => {
|
|
1578
1617
|
/** The breaker signal is captured at node ENTRY, before dispatchRunStep,
|
|
1579
1618
|
* ON_SUMMARIZE_START, or PreCompact awaits: a sibling's trip plus a
|
|
@@ -1706,42 +1745,27 @@ export function createSummarizeNode({
|
|
|
1706
1745
|
agentContext,
|
|
1707
1746
|
agentContext.summarizationConfig
|
|
1708
1747
|
);
|
|
1748
|
+
const queued = request.reason === 'queued';
|
|
1709
1749
|
const windowMessages = request.windowMessages ?? state.messages;
|
|
1710
|
-
const
|
|
1711
|
-
const retainTurns = retainRecent?.turns ?? DEFAULT_RETAIN_RECENT_TURNS;
|
|
1712
|
-
const recencyTokenCounter =
|
|
1713
|
-
agentContext.contextPressureTokenCounts?.count ??
|
|
1714
|
-
agentContext.tokenCounter ??
|
|
1715
|
-
(await createTokenCounter(encodingForReceivingAgent(agentContext)));
|
|
1716
|
-
const retainTokens =
|
|
1717
|
-
retainRecent?.tokens ??
|
|
1718
|
-
(retainRecent == null
|
|
1719
|
-
? Math.min(
|
|
1720
|
-
DEFAULT_RETAIN_RECENT_TOKENS,
|
|
1721
|
-
Math.max(
|
|
1722
|
-
1,
|
|
1723
|
-
Math.floor((agentContext.maxContextTokens ?? 100_000) * 0.16)
|
|
1724
|
-
)
|
|
1725
|
-
)
|
|
1726
|
-
: undefined);
|
|
1750
|
+
const split = request.queuedTailStartIndex;
|
|
1727
1751
|
const { head: compactableHead, tail: projectedTail } =
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
maxContextTokens: agentContext.maxContextTokens,
|
|
1739
|
-
}),
|
|
1740
|
-
});
|
|
1752
|
+
split == null
|
|
1753
|
+
? await resolveSummaryRecencyWindow(
|
|
1754
|
+
agentContext,
|
|
1755
|
+
windowMessages,
|
|
1756
|
+
queued
|
|
1757
|
+
)
|
|
1758
|
+
: {
|
|
1759
|
+
head: windowMessages.slice(0, split),
|
|
1760
|
+
tail: windowMessages.slice(split),
|
|
1761
|
+
};
|
|
1741
1762
|
|
|
1742
1763
|
const messagesToRefine = compactableHead;
|
|
1743
1764
|
|
|
1744
|
-
if (
|
|
1765
|
+
if (
|
|
1766
|
+
messagesToRefine.length === 0 ||
|
|
1767
|
+
(queued && projectedTail.length === 0)
|
|
1768
|
+
) {
|
|
1745
1769
|
if (request.reason === 'manual') {
|
|
1746
1770
|
throw new ManualSummarizationSkippedError(
|
|
1747
1771
|
'nothing_to_summarize',
|
|
@@ -1763,7 +1787,9 @@ export function createSummarizeNode({
|
|
|
1763
1787
|
'Summarization skipped — recency window retains all messages',
|
|
1764
1788
|
{
|
|
1765
1789
|
messagesRetained: projectedTail.length,
|
|
1766
|
-
retainTurns
|
|
1790
|
+
retainTurns:
|
|
1791
|
+
agentContext.summarizationConfig?.retainRecent?.turns ??
|
|
1792
|
+
DEFAULT_RETAIN_RECENT_TURNS,
|
|
1767
1793
|
},
|
|
1768
1794
|
{ runId: graph.runId, agentId: request.agentId }
|
|
1769
1795
|
);
|
|
@@ -1786,6 +1812,7 @@ export function createSummarizeNode({
|
|
|
1786
1812
|
|
|
1787
1813
|
const placeholderSummary: t.SummaryContentBlock = {
|
|
1788
1814
|
type: ContentTypes.SUMMARY,
|
|
1815
|
+
...(queued && { initiatedBy: 'user' as const, inline: true }),
|
|
1789
1816
|
model: clientConfig.modelName,
|
|
1790
1817
|
provider: clientConfig.provider,
|
|
1791
1818
|
};
|
|
@@ -1844,7 +1871,7 @@ export function createSummarizeNode({
|
|
|
1844
1871
|
executionContext: graph.getSubagentExecutionContext?.(),
|
|
1845
1872
|
messagesBeforeCount: messagesToRefine.length,
|
|
1846
1873
|
trigger:
|
|
1847
|
-
request.reason === 'manual'
|
|
1874
|
+
request.reason === 'manual' || queued
|
|
1848
1875
|
? 'manual'
|
|
1849
1876
|
: (agentContext.summarizationConfig?.trigger?.type ?? 'default'),
|
|
1850
1877
|
},
|
|
@@ -2094,6 +2121,10 @@ export function createSummarizeNode({
|
|
|
2094
2121
|
summaryVersion: agentContext.summaryVersion,
|
|
2095
2122
|
});
|
|
2096
2123
|
|
|
2124
|
+
if (queued) {
|
|
2125
|
+
summaryBlock.initiatedBy = 'user';
|
|
2126
|
+
summaryBlock.inline = true;
|
|
2127
|
+
}
|
|
2097
2128
|
await dispatchCompletionEvents({
|
|
2098
2129
|
graph,
|
|
2099
2130
|
runnableConfig,
|
|
@@ -2128,6 +2159,16 @@ export function createSummarizeNode({
|
|
|
2128
2159
|
: [createRemoveAllMessage()],
|
|
2129
2160
|
/** The run's result, for trace roots that otherwise see no reply. */
|
|
2130
2161
|
...(request.reason === 'manual' ? { manualSummary: summaryText } : {}),
|
|
2162
|
+
...(queued ? { queuedCompactionApplied: true } : {}),
|
|
2163
|
+
...(queued || state.queuedCompactionSummary != null
|
|
2164
|
+
? {
|
|
2165
|
+
queuedCompactionSummary: {
|
|
2166
|
+
text: summaryText,
|
|
2167
|
+
tokenCount,
|
|
2168
|
+
precedesMessages: messagesToRetain.length > 0,
|
|
2169
|
+
},
|
|
2170
|
+
}
|
|
2171
|
+
: {}),
|
|
2131
2172
|
};
|
|
2132
2173
|
};
|
|
2133
2174
|
}
|
package/src/tools/ToolNode.ts
CHANGED
|
@@ -138,6 +138,8 @@ import {
|
|
|
138
138
|
StreamLimitExceededError,
|
|
139
139
|
RUN_BREAKER_SCOPE_CONFIG_KEY,
|
|
140
140
|
} from '@/llm/streamLimits';
|
|
141
|
+
import { isPauseTurn } from '@/llm/truncation';
|
|
142
|
+
import { isAnthropicServerToolResultType } from '@/messages/anthropicServerTools';
|
|
141
143
|
import {
|
|
142
144
|
resolveLocalToolRegistry,
|
|
143
145
|
resolveLocalExecutionTools,
|
|
@@ -6442,15 +6444,71 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
|
|
|
6442
6444
|
}
|
|
6443
6445
|
}
|
|
6444
6446
|
|
|
6447
|
+
/**
|
|
6448
|
+
* Ids of Anthropic server tool calls (`srvtoolu_`) whose result block already
|
|
6449
|
+
* sits in the message content. The provider executes server tools inside the
|
|
6450
|
+
* same response and returns its result block (for example
|
|
6451
|
+
* `code_execution_tool_result`, or a `web_search_tool_result` holding an error
|
|
6452
|
+
* or no hits; see `ANTHROPIC_SERVER_TOOL_RESULT_TYPES`) next to the call, so such a call is settled even when
|
|
6453
|
+
* `handleAnthropicSearchResults` never marked it invoked.
|
|
6454
|
+
*/
|
|
6455
|
+
function getSettledServerToolCallIds(
|
|
6456
|
+
content: AIMessage['content']
|
|
6457
|
+
): Set<string> {
|
|
6458
|
+
const settled = new Set<string>();
|
|
6459
|
+
if (!Array.isArray(content)) return settled;
|
|
6460
|
+
for (const block of content) {
|
|
6461
|
+
const { type, tool_use_id: toolUseId } = block as {
|
|
6462
|
+
type?: unknown;
|
|
6463
|
+
tool_use_id?: unknown;
|
|
6464
|
+
};
|
|
6465
|
+
if (
|
|
6466
|
+
typeof type === 'string' &&
|
|
6467
|
+
isAnthropicServerToolResultType(type) &&
|
|
6468
|
+
typeof toolUseId === 'string' &&
|
|
6469
|
+
toolUseId.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX)
|
|
6470
|
+
) {
|
|
6471
|
+
settled.add(toolUseId);
|
|
6472
|
+
}
|
|
6473
|
+
}
|
|
6474
|
+
return settled;
|
|
6475
|
+
}
|
|
6476
|
+
|
|
6477
|
+
const NO_TOOL_IDS: ReadonlySet<string> = new Set();
|
|
6478
|
+
|
|
6479
|
+
/**
|
|
6480
|
+
* Whether every tool call is already settled: it is in `invokedToolIds`, or it
|
|
6481
|
+
* is a server call whose result block is already in the message content (see
|
|
6482
|
+
* {@link getSettledServerToolCallIds}). Routing a settled server call to the
|
|
6483
|
+
* tool node would run nothing (ToolNode skips `srvtoolu_` calls) and the graph
|
|
6484
|
+
* would call the model again, so the answer is written twice.
|
|
6485
|
+
*
|
|
6486
|
+
* A `pause_turn` stop is excluded from the content check: Anthropic paused a
|
|
6487
|
+
* long server tool loop and expects the request to be repeated to continue,
|
|
6488
|
+
* and routing back is the only way the turn continues.
|
|
6489
|
+
*
|
|
6490
|
+
* The content is scanned only when `invokedToolIds` alone does not settle every
|
|
6491
|
+
* call, since this runs on every routing decision.
|
|
6492
|
+
*/
|
|
6445
6493
|
function areToolCallsInvoked(
|
|
6446
6494
|
message: AIMessage,
|
|
6447
6495
|
invokedToolIds?: Set<string>
|
|
6448
6496
|
): boolean {
|
|
6449
|
-
|
|
6450
|
-
return
|
|
6451
|
-
|
|
6452
|
-
|
|
6453
|
-
|
|
6497
|
+
const calls = message.tool_calls;
|
|
6498
|
+
if (calls == null) return false;
|
|
6499
|
+
const invoked: ReadonlySet<string> = invokedToolIds ?? NO_TOOL_IDS;
|
|
6500
|
+
if (
|
|
6501
|
+
invoked.size > 0 &&
|
|
6502
|
+
calls.every((call) => call.id != null && invoked.has(call.id))
|
|
6503
|
+
) {
|
|
6504
|
+
return true;
|
|
6505
|
+
}
|
|
6506
|
+
if (isPauseTurn(message)) return false;
|
|
6507
|
+
const settledIds = getSettledServerToolCallIds(message.content);
|
|
6508
|
+
if (settledIds.size === 0) return false;
|
|
6509
|
+
return calls.every(
|
|
6510
|
+
(call) =>
|
|
6511
|
+
call.id != null && (invoked.has(call.id) || settledIds.has(call.id))
|
|
6454
6512
|
);
|
|
6455
6513
|
}
|
|
6456
6514
|
|
|
@@ -6643,9 +6701,10 @@ export function toolsCondition<T extends string>(
|
|
|
6643
6701
|
* call is provider-server-executed (`srvtoolu_` — ToolNode's batch filter
|
|
6644
6702
|
* excludes those before execution, so nothing re-runs): that covers both the
|
|
6645
6703
|
* invalid-only turn and the Anthropic server-call + malformed-client-call
|
|
6646
|
-
* mix, where
|
|
6647
|
-
*
|
|
6648
|
-
*
|
|
6704
|
+
* mix, where the server call is settled (marked invoked by
|
|
6705
|
+
* `handleAnthropicSearchResults`, or its result block is in the
|
|
6706
|
+
* message content) and the first branch declines. A valid NON-server call
|
|
6707
|
+
* that was invoked externally stays conservative (no routing) — ToolNode does not filter on
|
|
6649
6708
|
* `invokedToolIds`, so entering it would re-execute that call.
|
|
6650
6709
|
*
|
|
6651
6710
|
* Mirrors ToolNode's own gating exactly, or the routed turn would no-op and
|
package/src/types/graph.ts
CHANGED
|
@@ -26,6 +26,7 @@ import type {
|
|
|
26
26
|
} from '@/types/stream';
|
|
27
27
|
import type {
|
|
28
28
|
SummarizationNodeInput,
|
|
29
|
+
ClaimQueuedCompaction,
|
|
29
30
|
SummarizeCompleteEvent,
|
|
30
31
|
CompactionSemanticIndex,
|
|
31
32
|
SummarizationConfig,
|
|
@@ -135,6 +136,13 @@ export type BaseGraphState = {
|
|
|
135
136
|
|
|
136
137
|
export type AgentSubgraphState = BaseGraphState & {
|
|
137
138
|
summarizationRequest?: SummarizationNodeInput;
|
|
139
|
+
queuedCompactionApplied?: boolean;
|
|
140
|
+
queuedCompactionSummary?: {
|
|
141
|
+
text: string;
|
|
142
|
+
tokenCount: number;
|
|
143
|
+
precedesMessages: boolean;
|
|
144
|
+
};
|
|
145
|
+
queuedCompactionDeferredCount?: number | null;
|
|
138
146
|
};
|
|
139
147
|
|
|
140
148
|
export type SubagentGraphResult = {
|
|
@@ -469,6 +477,7 @@ export type StandardGraphInput = {
|
|
|
469
477
|
* provider-safe sealing path without targeting the top-level conversation.
|
|
470
478
|
*/
|
|
471
479
|
preemption?: StreamPreemption;
|
|
480
|
+
claimQueuedCompaction?: ClaimQueuedCompaction;
|
|
472
481
|
/**
|
|
473
482
|
* Stream circuit breakers, forwarded from `RunConfig.streamLimits` and
|
|
474
483
|
* resolved once at graph construction. Enforced by the stream handler on
|
package/src/types/run.ts
CHANGED
|
@@ -348,6 +348,8 @@ export type RunConfig = {
|
|
|
348
348
|
toolResultProtection?: g.StandardGraphInput['toolResultProtection'];
|
|
349
349
|
/** Resolves attachments that messages carry by reference, for every graph of the run. */
|
|
350
350
|
resolveAttachment?: g.StandardGraphInput['resolveAttachment'];
|
|
351
|
+
/** Optional host queue for a top-level standard graph; never inherited by child graphs. */
|
|
352
|
+
claimQueuedCompaction?: g.StandardGraphInput['claimQueuedCompaction'];
|
|
351
353
|
streamLimits?: StreamLimits;
|
|
352
354
|
returnContent?: boolean;
|
|
353
355
|
tokenCounter?: TokenCounter;
|
package/src/types/stream.ts
CHANGED
|
@@ -449,6 +449,8 @@ export type SummaryCoverage = {
|
|
|
449
449
|
|
|
450
450
|
export type SummaryContentBlock = {
|
|
451
451
|
type: ContentTypes.SUMMARY;
|
|
452
|
+
initiatedBy?: 'user';
|
|
453
|
+
inline?: true;
|
|
452
454
|
content?: MessageContentComplex[];
|
|
453
455
|
/** Injection budget: provider output-token space when usage was reported, plus
|
|
454
456
|
* the wrapper added at injection time. Not comparable with per-message counts
|
package/src/types/summarize.ts
CHANGED
|
@@ -118,11 +118,19 @@ export interface SummarizeResult {
|
|
|
118
118
|
provider?: string;
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
+
/** Atomically consumes a host request. `terminal` is the last safe boundary of a graph segment. */
|
|
122
|
+
export type ClaimQueuedCompaction = (
|
|
123
|
+
boundary: 'model' | 'terminal',
|
|
124
|
+
signal?: AbortSignal
|
|
125
|
+
) => boolean | Promise<boolean>;
|
|
126
|
+
|
|
121
127
|
export interface SummarizationNodeInput {
|
|
122
128
|
remainingContextTokens: number;
|
|
123
129
|
agentId: string;
|
|
124
130
|
/** Pruned, masked provider history from the turn requesting compaction. */
|
|
125
131
|
windowMessages?: BaseMessage[];
|
|
132
|
+
/** Preflighted recency cut for a queued request. */
|
|
133
|
+
queuedTailStartIndex?: number;
|
|
126
134
|
/**
|
|
127
135
|
* Why the detour was requested.
|
|
128
136
|
*
|
|
@@ -133,9 +141,10 @@ export interface SummarizationNodeInput {
|
|
|
133
141
|
* variant performs no model call — the corrected budget alone is what the
|
|
134
142
|
* retry needs.
|
|
135
143
|
* - `manual`: the host asked for a summary outright (a summarize-only run).
|
|
136
|
-
*
|
|
144
|
+
* - `queued`: the host requested compaction without ending the active run.
|
|
145
|
+
* Always retains a recent tail, even when configured to retain zero turns.
|
|
137
146
|
*/
|
|
138
|
-
reason?: 'trigger' | 'overflow' | 'manual';
|
|
147
|
+
reason?: 'trigger' | 'overflow' | 'manual' | 'queued';
|
|
139
148
|
/**
|
|
140
149
|
* Whether an overflow recovery may spend a summarization model call.
|
|
141
150
|
*
|