@librechat/agents 4.2.17 → 4.2.19
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 +160 -10
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/llm/truncation.cjs +4 -0
- package/dist/cjs/llm/truncation.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 +56 -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 +161 -11
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/llm/truncation.mjs +4 -1
- package/dist/esm/llm/truncation.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 +56 -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 +11 -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 +488 -180
- package/src/llm/truncation.ts +16 -0
- 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 +75 -33
- package/src/tools/ToolNode.ts +67 -8
- package/src/types/graph.ts +11 -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/llmConfig.ts +1 -1
- package/src/utils/toolContent.ts +72 -21
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:
|
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,17 @@ 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
|
+
retainedMessageCount: messagesToRetain.length,
|
|
2170
|
+
},
|
|
2171
|
+
}
|
|
2172
|
+
: {}),
|
|
2131
2173
|
};
|
|
2132
2174
|
};
|
|
2133
2175
|
}
|
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,15 @@ 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
|
+
/** Absent on older checkpoints. */
|
|
145
|
+
retainedMessageCount?: number;
|
|
146
|
+
};
|
|
147
|
+
queuedCompactionDeferredCount?: number | null;
|
|
138
148
|
};
|
|
139
149
|
|
|
140
150
|
export type SubagentGraphResult = {
|
|
@@ -469,6 +479,7 @@ export type StandardGraphInput = {
|
|
|
469
479
|
* provider-safe sealing path without targeting the top-level conversation.
|
|
470
480
|
*/
|
|
471
481
|
preemption?: StreamPreemption;
|
|
482
|
+
claimQueuedCompaction?: ClaimQueuedCompaction;
|
|
472
483
|
/**
|
|
473
484
|
* Stream circuit breakers, forwarded from `RunConfig.streamLimits` and
|
|
474
485
|
* 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
|
*
|
package/src/utils/llmConfig.ts
CHANGED
|
@@ -125,7 +125,7 @@ export const llmConfigs: Record<string, t.BuiltInLLMConfig | undefined> = {
|
|
|
125
125
|
},
|
|
126
126
|
[Providers.ANTHROPIC]: {
|
|
127
127
|
provider: Providers.ANTHROPIC,
|
|
128
|
-
model: 'claude-sonnet-
|
|
128
|
+
model: 'claude-sonnet-5-5',
|
|
129
129
|
streaming: true,
|
|
130
130
|
streamUsage: true,
|
|
131
131
|
},
|
package/src/utils/toolContent.ts
CHANGED
|
@@ -1956,6 +1956,17 @@ export type CompactToolContentResult = {
|
|
|
1956
1956
|
originalChars: number;
|
|
1957
1957
|
};
|
|
1958
1958
|
|
|
1959
|
+
/** Whether `value` has a control or space character before index `end`. */
|
|
1960
|
+
function hasUrlControlChars(value: string, end: number): boolean {
|
|
1961
|
+
for (let i = 0; i < end; i++) {
|
|
1962
|
+
const code = value.charCodeAt(i);
|
|
1963
|
+
if (code <= 0x20 || code === 0x7f) {
|
|
1964
|
+
return true;
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
return false;
|
|
1968
|
+
}
|
|
1969
|
+
|
|
1959
1970
|
function isProviderImageUrl(value: unknown): value is string {
|
|
1960
1971
|
if (typeof value !== 'string' || value === '') {
|
|
1961
1972
|
return false;
|
|
@@ -1969,20 +1980,17 @@ function isProviderImageUrl(value: unknown): value is string {
|
|
|
1969
1980
|
) {
|
|
1970
1981
|
return false;
|
|
1971
1982
|
}
|
|
1972
|
-
for (let i = 0; i < value.length; i++) {
|
|
1973
|
-
const code = value.charCodeAt(i);
|
|
1974
|
-
if (code <= 0x20 || code === 0x7f) {
|
|
1975
|
-
return false;
|
|
1976
|
-
}
|
|
1977
|
-
}
|
|
1978
1983
|
if (isDataImage) {
|
|
1979
1984
|
const separator = value.indexOf(',');
|
|
1980
1985
|
if (
|
|
1981
1986
|
separator < 0 ||
|
|
1987
|
+
hasUrlControlChars(value, separator) ||
|
|
1982
1988
|
!value.slice(0, separator).toLowerCase().endsWith(';base64')
|
|
1983
1989
|
) {
|
|
1984
1990
|
return false;
|
|
1985
1991
|
}
|
|
1992
|
+
/** The base64 alphabet excludes every control and space character, so the
|
|
1993
|
+
* payload, up to megabytes of it, needs no separate character scan. */
|
|
1986
1994
|
const payload = value.slice(separator + 1);
|
|
1987
1995
|
return (
|
|
1988
1996
|
payload.length > 0 &&
|
|
@@ -1990,6 +1998,9 @@ function isProviderImageUrl(value: unknown): value is string {
|
|
|
1990
1998
|
/^[a-z0-9+/]+={0,2}$/i.test(payload)
|
|
1991
1999
|
);
|
|
1992
2000
|
}
|
|
2001
|
+
if (hasUrlControlChars(value, value.length)) {
|
|
2002
|
+
return false;
|
|
2003
|
+
}
|
|
1993
2004
|
try {
|
|
1994
2005
|
const url = new URL(value);
|
|
1995
2006
|
return url.protocol === 'http:' || url.protocol === 'https:';
|
|
@@ -2281,26 +2292,66 @@ export function getComputerCallOutputScreenshot(
|
|
|
2281
2292
|
file_id: validFileId as string,
|
|
2282
2293
|
};
|
|
2283
2294
|
}
|
|
2295
|
+
if (type.value === 'image_url') {
|
|
2296
|
+
const url = readImageUrlBlockUrl(block, type, imageUrl, fileId);
|
|
2297
|
+
return url != null ? { type: 'input_image', image_url: url } : undefined;
|
|
2298
|
+
}
|
|
2299
|
+
return undefined;
|
|
2300
|
+
}
|
|
2301
|
+
|
|
2302
|
+
function readImageUrlBlockUrl(
|
|
2303
|
+
block: Record<string, unknown>,
|
|
2304
|
+
type: OwnDataProperty,
|
|
2305
|
+
imageUrl: OwnDataProperty,
|
|
2306
|
+
fileId: OwnDataProperty
|
|
2307
|
+
): string | undefined {
|
|
2284
2308
|
if (
|
|
2285
|
-
type.
|
|
2286
|
-
|
|
2287
|
-
|
|
2309
|
+
!type.found ||
|
|
2310
|
+
type.value !== 'image_url' ||
|
|
2311
|
+
fileId.found ||
|
|
2312
|
+
!imageUrl.found ||
|
|
2313
|
+
!hasOnlyEnumerableKeys(block, IMAGE_URL_KEYS)
|
|
2288
2314
|
) {
|
|
2289
|
-
|
|
2290
|
-
|
|
2315
|
+
return undefined;
|
|
2316
|
+
}
|
|
2317
|
+
if (isProviderImageUrl(imageUrl.value)) {
|
|
2318
|
+
return imageUrl.value;
|
|
2319
|
+
}
|
|
2320
|
+
if (
|
|
2321
|
+
!isRecord(imageUrl.value) ||
|
|
2322
|
+
!hasOnlyEnumerableKeys(imageUrl.value, NESTED_IMAGE_URL_KEYS)
|
|
2323
|
+
) {
|
|
2324
|
+
return undefined;
|
|
2325
|
+
}
|
|
2326
|
+
const url = readOwnEnumerableDataProperty(imageUrl.value, 'url');
|
|
2327
|
+
return url.found && isProviderImageUrl(url.value) ? url.value : undefined;
|
|
2328
|
+
}
|
|
2329
|
+
|
|
2330
|
+
/**
|
|
2331
|
+
* Returns the URL of a well-formed `image_url` block (an `http(s)` URL or a
|
|
2332
|
+
* base64 image data URL within the inline image ceiling), reading only own
|
|
2333
|
+
* data properties and never invoking serialization hooks.
|
|
2334
|
+
*/
|
|
2335
|
+
export function getToolContentImageUrl(block: unknown): string | undefined {
|
|
2336
|
+
try {
|
|
2337
|
+
if (!isRecord(block) || isProxy(block)) {
|
|
2338
|
+
return undefined;
|
|
2291
2339
|
}
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
const url = readOwnEnumerableDataProperty(imageUrl.value, 'url');
|
|
2298
|
-
if (url.found && isProviderImageUrl(url.value)) {
|
|
2299
|
-
return { type: 'input_image', image_url: url.value };
|
|
2300
|
-
}
|
|
2340
|
+
/** Every content block passes through here; settle the type from its own
|
|
2341
|
+
* data property before walking the block for serialization hooks. */
|
|
2342
|
+
const type = readOwnEnumerableDataProperty(block, 'type');
|
|
2343
|
+
if (type.value !== 'image_url' || hasUnsafeCallableToJSON(block)) {
|
|
2344
|
+
return undefined;
|
|
2301
2345
|
}
|
|
2346
|
+
return readImageUrlBlockUrl(
|
|
2347
|
+
block,
|
|
2348
|
+
type,
|
|
2349
|
+
readOwnEnumerableDataProperty(block, 'image_url'),
|
|
2350
|
+
readOwnEnumerableDataProperty(block, 'file_id')
|
|
2351
|
+
);
|
|
2352
|
+
} catch {
|
|
2353
|
+
return undefined;
|
|
2302
2354
|
}
|
|
2303
|
-
return undefined;
|
|
2304
2355
|
}
|
|
2305
2356
|
|
|
2306
2357
|
/** Returns the provider image URL when a screenshot is URL-backed. */
|