@librechat/agents 4.2.17 → 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/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 +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/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 +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/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 +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
|
@@ -14,6 +14,7 @@ import { StreamLimitExceededError } from '../llm/streamLimits.js';
|
|
|
14
14
|
import { SubagentExecutor } from '../tools/subagent/index.js';
|
|
15
15
|
import { ProviderTextProtectionError } from '../protection/providerText.js';
|
|
16
16
|
import { ToolOutputReferenceRegistry } from '../tools/toolOutputReferences.js';
|
|
17
|
+
import { createSummarizeNode } from '../summarization/node.js';
|
|
17
18
|
import { PreparedSubagents, PreparedSubagentError } from '../tools/preparedSubagents.js';
|
|
18
19
|
import { ToolNode as CustomToolNode } from '../tools/ToolNode.js';
|
|
19
20
|
import { SearchCitations } from '../tools/search/citations.js';
|
|
@@ -319,6 +320,11 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode>
|
|
|
319
320
|
* these on every streamed chunk event.
|
|
320
321
|
*/
|
|
321
322
|
streamLimits: ResolvedStreamLimits;
|
|
323
|
+
/** A single compaction claim per logical run, including Stop continuations. */
|
|
324
|
+
private readonly claimQueuedCompaction?;
|
|
325
|
+
private queuedCompactionClaimed;
|
|
326
|
+
private queuedCompactionSummaryRestored;
|
|
327
|
+
private queuedCompactionDeferredCount;
|
|
322
328
|
/** Default-off mandatory provider prose release. */
|
|
323
329
|
providerTextProtection?: t.StandardGraphInput['providerTextProtection'];
|
|
324
330
|
/** Default-off host inspection of selected tools' result text. */
|
|
@@ -453,7 +459,7 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode>
|
|
|
453
459
|
* from a discard.
|
|
454
460
|
*/
|
|
455
461
|
private preemptRestartPending;
|
|
456
|
-
constructor({ runId, signal, agents, langfuse, tokenCounter, indexTokenCountMap, calibrationRatio, fadingTier, fadingTiers, subagentUsageSink, subagentTasks, subagentScope, subagentExecutionContext, subagentContext, onSubagentResolutionFailure, preemption, streamLimits, providerTextProtection, toolResultProtection, resolveAttachment, toolExecution, clientDelegatedToolNames, }: t.StandardGraphInput, dependencies?: GraphFactoryDependencies);
|
|
462
|
+
constructor({ runId, signal, agents, langfuse, tokenCounter, indexTokenCountMap, calibrationRatio, fadingTier, fadingTiers, subagentUsageSink, subagentTasks, subagentScope, subagentExecutionContext, subagentContext, onSubagentResolutionFailure, preemption, claimQueuedCompaction, streamLimits, providerTextProtection, toolResultProtection, resolveAttachment, toolExecution, clientDelegatedToolNames, }: t.StandardGraphInput, dependencies?: GraphFactoryDependencies);
|
|
457
463
|
/**
|
|
458
464
|
* A compaction applies its remove-all inside the agent subgraph, so the
|
|
459
465
|
* subgraph's result carries only the retained tail, and an outer reducer
|
|
@@ -726,6 +732,7 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode>
|
|
|
726
732
|
* for every other run so the ordinary step proceeds.
|
|
727
733
|
*/
|
|
728
734
|
private summarizeOnlyStep;
|
|
735
|
+
private takeQueuedCompaction;
|
|
729
736
|
createCallModel(agentId?: string): (state: t.AgentSubgraphState, config?: RunnableConfig) => Promise<Partial<t.AgentSubgraphState>>;
|
|
730
737
|
/**
|
|
731
738
|
* Fires `PreemptBoundary` after a sealed turn and returns whatever the
|
|
@@ -742,7 +749,10 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode>
|
|
|
742
749
|
*/
|
|
743
750
|
private dispatchPreemptBoundary;
|
|
744
751
|
protected createRunStepStateAnnotation(): RunStepStateChannel;
|
|
745
|
-
createAgentNode(agentId: string): t.CompiledAgentWorfklow;
|
|
752
|
+
createAgentNode(agentId: string, summarizer?: ReturnType<typeof createSummarizeNode>): t.CompiledAgentWorfklow;
|
|
753
|
+
private createGraphSummarizer;
|
|
754
|
+
/** A manual request shares the existing node's step budget, but keeps summary event identity. */
|
|
755
|
+
private compactAtBoundary;
|
|
746
756
|
createWorkflow(): t.CompiledStateWorkflow;
|
|
747
757
|
/**
|
|
748
758
|
* Indicates if this is a multi-agent graph.
|
|
@@ -8,6 +8,14 @@ import type { ProviderName } from '../types/index.js';
|
|
|
8
8
|
export type TruncationStopReason = 'max_tokens' | 'length';
|
|
9
9
|
/** Normalizes native invoke and stream stop reasons without hiding conflicting fields. */
|
|
10
10
|
export declare function getProviderStopReasons(message: Pick<BaseMessage, 'response_metadata' | 'additional_kwargs'> | undefined | null): string[];
|
|
11
|
+
/**
|
|
12
|
+
* Whether Anthropic paused the turn (`stop_reason: 'pause_turn'`). Anthropic
|
|
13
|
+
* returns this when a long-running server tool loop hit its iteration limit;
|
|
14
|
+
* the caller is expected to send the response back unchanged so the turn
|
|
15
|
+
* continues. Reads the same invoke (`response_metadata`) and stream
|
|
16
|
+
* (`additional_kwargs`) fields as {@link getProviderStopReasons}.
|
|
17
|
+
*/
|
|
18
|
+
export declare function isPauseTurn(message: Pick<BaseMessage, 'response_metadata' | 'additional_kwargs'> | undefined | null): boolean;
|
|
11
19
|
/**
|
|
12
20
|
* Reads the truncation stop reason off a message, covering every provider
|
|
13
21
|
* shape we stream:
|
|
@@ -123,6 +123,15 @@ export declare function withCacheControl<T extends MessageContentComplex>(block:
|
|
|
123
123
|
* Returns a new array; only messages that require modification are cloned.
|
|
124
124
|
*/
|
|
125
125
|
export declare function addTailCacheControl<T extends AnthropicMessage | BaseMessage>(messages: T[], ttl?: PromptCacheTtl): T[];
|
|
126
|
+
/**
|
|
127
|
+
* Synthetic skill/meta messages (reconstructed skill bodies, primed SKILL.md
|
|
128
|
+
* instructions) are re-injected every turn and are not stable conversation
|
|
129
|
+
* turns. They must not anchor a fresh prompt-cache marker — doing so pins the
|
|
130
|
+
* cache to a volatile/duplicated prefix. Stale markers are still stripped from
|
|
131
|
+
* them; only the *adding* of new markers is suppressed. Detected via
|
|
132
|
+
* `additional_kwargs.isMeta === true` or `additional_kwargs.source === 'skill'`.
|
|
133
|
+
*/
|
|
134
|
+
export declare function isSyntheticMetaMessage(message: MessageWithContent): boolean;
|
|
126
135
|
export declare function addCacheControlToStablePrefixMessages<T extends AnthropicMessage | BaseMessage>(messages: T[], maxCachePoints: number, ttl?: PromptCacheTtl): T[];
|
|
127
136
|
/**
|
|
128
137
|
* Removes all Anthropic cache_control fields from messages
|
package/dist/types/run.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import type { StandardGraph } from './graphs/Graph.js';
|
|
|
6
6
|
import type * as t from './types/index.js';
|
|
7
7
|
export declare const defaultOmitOptions: Set<string>;
|
|
8
8
|
export declare class Run<_T extends t.BaseGraphState> {
|
|
9
|
+
static readonly supportsQueuedCompaction = true;
|
|
9
10
|
id: string;
|
|
10
11
|
private tokenCounter?;
|
|
11
12
|
private handlerRegistry?;
|
|
@@ -24,6 +25,7 @@ export declare class Run<_T extends t.BaseGraphState> {
|
|
|
24
25
|
private providerTextProtection?;
|
|
25
26
|
private toolResultProtection?;
|
|
26
27
|
private resolveAttachment?;
|
|
28
|
+
private readonly claimQueuedCompaction?;
|
|
27
29
|
private streamLimits?;
|
|
28
30
|
private subagentTasks?;
|
|
29
31
|
private subagentContext?;
|
|
@@ -2,6 +2,7 @@ import type { BaseMessage } from '@langchain/core/messages';
|
|
|
2
2
|
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
3
3
|
import type { StreamLimitState } from '../llm/streamLimits.js';
|
|
4
4
|
import type { AgentContext } from '../agents/AgentContext.js';
|
|
5
|
+
import type { RecencySplit } from '../messages/recency.js';
|
|
5
6
|
import type { HookRegistry } from '../hooks/index.js';
|
|
6
7
|
import type { OnChunk } from '../llm/invoke.js';
|
|
7
8
|
import type * as t from '../types/index.js';
|
|
@@ -55,13 +56,17 @@ interface CreateSummarizeNodeParams {
|
|
|
55
56
|
} & StreamLimitState;
|
|
56
57
|
generateStepId: (stepKey: string) => [string, number];
|
|
57
58
|
}
|
|
59
|
+
export declare function resolveSummaryRecencyWindow(agentContext: AgentContext, windowMessages: BaseMessage[], queued: boolean): Promise<RecencySplit>;
|
|
58
60
|
export declare function createSummarizeNode({ agentContext, graph: adapterGraph, generateStepId, }: CreateSummarizeNodeParams): (state: {
|
|
59
61
|
messages: BaseMessage[];
|
|
60
62
|
summarizationRequest?: t.SummarizationNodeInput;
|
|
63
|
+
queuedCompactionSummary?: t.AgentSubgraphState["queuedCompactionSummary"];
|
|
61
64
|
}, config?: RunnableConfig) => Promise<{
|
|
62
65
|
summarizationRequest: undefined;
|
|
63
66
|
messages?: BaseMessage[];
|
|
64
67
|
manualSummary?: string;
|
|
68
|
+
queuedCompactionApplied?: boolean;
|
|
69
|
+
queuedCompactionSummary?: t.AgentSubgraphState["queuedCompactionSummary"];
|
|
65
70
|
}>;
|
|
66
71
|
/**
|
|
67
72
|
* Creates an `onChunk` callback that dispatches each chunk as an
|
|
@@ -8,7 +8,7 @@ import type { RunnableConfig, Runnable } from '@langchain/core/runnables';
|
|
|
8
8
|
import type { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
9
9
|
import type { GoogleAIToolType } from '@langchain/google-common';
|
|
10
10
|
import type { RunStep, ModelResponseEvent, ModelToolsClaimedEvent, RunStepDeltaEvent, RunStepResumeState, RunStepClosedEvent, ToolCallsDispatchedEvent, MessageDeltaEvent, ReasoningDeltaEvent } from './stream.js';
|
|
11
|
-
import type { SummarizationNodeInput, SummarizeCompleteEvent, CompactionSemanticIndex, SummarizationConfig, SummarizeStartEvent, SummarizeDeltaEvent } from './summarize.js';
|
|
11
|
+
import type { SummarizationNodeInput, ClaimQueuedCompaction, SummarizeCompleteEvent, CompactionSemanticIndex, SummarizationConfig, SummarizeStartEvent, SummarizeDeltaEvent } from './summarize.js';
|
|
12
12
|
import type { ToolMap, ToolSessionMap, ToolEndEvent, GenericTool, LCTool, ToolExecutionConfig, ToolExecuteBatchRequest } from './tools.js';
|
|
13
13
|
import type { TokenCounter, StreamLimits, StreamPreemption, TokenBudgetBreakdown } from './run.js';
|
|
14
14
|
import type { SubagentResolutionFailureHandler } from '../tools/subagent/diagnostics.js';
|
|
@@ -82,6 +82,13 @@ export type BaseGraphState = {
|
|
|
82
82
|
};
|
|
83
83
|
export type AgentSubgraphState = BaseGraphState & {
|
|
84
84
|
summarizationRequest?: SummarizationNodeInput;
|
|
85
|
+
queuedCompactionApplied?: boolean;
|
|
86
|
+
queuedCompactionSummary?: {
|
|
87
|
+
text: string;
|
|
88
|
+
tokenCount: number;
|
|
89
|
+
precedesMessages: boolean;
|
|
90
|
+
};
|
|
91
|
+
queuedCompactionDeferredCount?: number | null;
|
|
85
92
|
};
|
|
86
93
|
export type SubagentGraphResult = {
|
|
87
94
|
agentId: string;
|
|
@@ -348,6 +355,7 @@ export type StandardGraphInput = {
|
|
|
348
355
|
* provider-safe sealing path without targeting the top-level conversation.
|
|
349
356
|
*/
|
|
350
357
|
preemption?: StreamPreemption;
|
|
358
|
+
claimQueuedCompaction?: ClaimQueuedCompaction;
|
|
351
359
|
/**
|
|
352
360
|
* Stream circuit breakers, forwarded from `RunConfig.streamLimits` and
|
|
353
361
|
* resolved once at graph construction. Enforced by the stream handler on
|
|
@@ -324,6 +324,8 @@ export type RunConfig = {
|
|
|
324
324
|
toolResultProtection?: g.StandardGraphInput['toolResultProtection'];
|
|
325
325
|
/** Resolves attachments that messages carry by reference, for every graph of the run. */
|
|
326
326
|
resolveAttachment?: g.StandardGraphInput['resolveAttachment'];
|
|
327
|
+
/** Optional host queue for a top-level standard graph; never inherited by child graphs. */
|
|
328
|
+
claimQueuedCompaction?: g.StandardGraphInput['claimQueuedCompaction'];
|
|
327
329
|
streamLimits?: StreamLimits;
|
|
328
330
|
returnContent?: boolean;
|
|
329
331
|
tokenCounter?: TokenCounter;
|
|
@@ -387,6 +387,8 @@ export type SummaryCoverage = {
|
|
|
387
387
|
};
|
|
388
388
|
export type SummaryContentBlock = {
|
|
389
389
|
type: ContentTypes.SUMMARY;
|
|
390
|
+
initiatedBy?: 'user';
|
|
391
|
+
inline?: true;
|
|
390
392
|
content?: MessageContentComplex[];
|
|
391
393
|
/** Injection budget: provider output-token space when usage was reported, plus
|
|
392
394
|
* the wrapper added at injection time. Not comparable with per-message counts
|
|
@@ -95,11 +95,15 @@ export interface SummarizeResult {
|
|
|
95
95
|
model?: string;
|
|
96
96
|
provider?: string;
|
|
97
97
|
}
|
|
98
|
+
/** Atomically consumes a host request. `terminal` is the last safe boundary of a graph segment. */
|
|
99
|
+
export type ClaimQueuedCompaction = (boundary: 'model' | 'terminal', signal?: AbortSignal) => boolean | Promise<boolean>;
|
|
98
100
|
export interface SummarizationNodeInput {
|
|
99
101
|
remainingContextTokens: number;
|
|
100
102
|
agentId: string;
|
|
101
103
|
/** Pruned, masked provider history from the turn requesting compaction. */
|
|
102
104
|
windowMessages?: BaseMessage[];
|
|
105
|
+
/** Preflighted recency cut for a queued request. */
|
|
106
|
+
queuedTailStartIndex?: number;
|
|
103
107
|
/**
|
|
104
108
|
* Why the detour was requested.
|
|
105
109
|
*
|
|
@@ -110,9 +114,10 @@ export interface SummarizationNodeInput {
|
|
|
110
114
|
* variant performs no model call — the corrected budget alone is what the
|
|
111
115
|
* retry needs.
|
|
112
116
|
* - `manual`: the host asked for a summary outright (a summarize-only run).
|
|
113
|
-
*
|
|
117
|
+
* - `queued`: the host requested compaction without ending the active run.
|
|
118
|
+
* Always retains a recent tail, even when configured to retain zero turns.
|
|
114
119
|
*/
|
|
115
|
-
reason?: 'trigger' | 'overflow' | 'manual';
|
|
120
|
+
reason?: 'trigger' | 'overflow' | 'manual' | 'queued';
|
|
116
121
|
/**
|
|
117
122
|
* Whether an overflow recovery may spend a summarization model call.
|
|
118
123
|
*
|
|
@@ -87,6 +87,12 @@ type InputImageDetail = 'low' | 'high' | 'auto' | 'original';
|
|
|
87
87
|
* converter without invoking accessors or user-defined serialization hooks.
|
|
88
88
|
*/
|
|
89
89
|
export declare function getComputerCallOutputScreenshot(content: unknown): ComputerCallOutputScreenshot | undefined;
|
|
90
|
+
/**
|
|
91
|
+
* Returns the URL of a well-formed `image_url` block (an `http(s)` URL or a
|
|
92
|
+
* base64 image data URL within the inline image ceiling), reading only own
|
|
93
|
+
* data properties and never invoking serialization hooks.
|
|
94
|
+
*/
|
|
95
|
+
export declare function getToolContentImageUrl(block: unknown): string | undefined;
|
|
90
96
|
/** Returns the provider image URL when a screenshot is URL-backed. */
|
|
91
97
|
export declare function getComputerCallOutputImageUrl(content: unknown): string | undefined;
|
|
92
98
|
/** Returns whether content can be sent as a native computer screenshot. */
|
package/package.json
CHANGED
|
@@ -28,6 +28,7 @@ import {
|
|
|
28
28
|
} from '@/tools/CallerCapabilities';
|
|
29
29
|
import {
|
|
30
30
|
addTailCacheControl,
|
|
31
|
+
isSyntheticMetaMessage,
|
|
31
32
|
stripAnthropicCacheControl,
|
|
32
33
|
addCacheControlToStablePrefixMessages,
|
|
33
34
|
buildAnthropicCacheControl,
|
|
@@ -35,6 +36,7 @@ import {
|
|
|
35
36
|
resolvePromptCacheTtl,
|
|
36
37
|
resolveBedrockPromptCacheTtl,
|
|
37
38
|
cloneMessage,
|
|
39
|
+
getCacheControl,
|
|
38
40
|
type PromptCacheTtl,
|
|
39
41
|
} from '@/messages/cache';
|
|
40
42
|
import {
|
|
@@ -49,6 +51,9 @@ import {
|
|
|
49
51
|
ORIGINAL_CONTENT_MAX_CHARS,
|
|
50
52
|
clampCalibrationRatio,
|
|
51
53
|
createPruneMessages,
|
|
54
|
+
findLastIndex,
|
|
55
|
+
getProviderMessageProvenance,
|
|
56
|
+
isSyntheticProviderContextMessage,
|
|
52
57
|
syncBudgetDerivedFields,
|
|
53
58
|
} from '@/messages';
|
|
54
59
|
import {
|
|
@@ -103,6 +108,41 @@ type ProgrammaticToolInstructionTarget = {
|
|
|
103
108
|
*/
|
|
104
109
|
const MAX_SUMMARIZATION_FAILURES = 3;
|
|
105
110
|
|
|
111
|
+
/**
|
|
112
|
+
* User-role context the SDK builds, such as tool history folded for an agent
|
|
113
|
+
* without tools or the payload `projectArtifactPayload` appends for a tool's
|
|
114
|
+
* images. Provenance survives the copies legacy formatting makes: a fold's
|
|
115
|
+
* starts with a synthetic part, and a tool payload's names no user part.
|
|
116
|
+
*/
|
|
117
|
+
function isProviderContextMessage(message: BaseMessage): boolean {
|
|
118
|
+
if (isSyntheticProviderContextMessage(message)) {
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
const parts = getProviderMessageProvenance(message)?.parts ?? [];
|
|
122
|
+
return (
|
|
123
|
+
parts.length > 0 &&
|
|
124
|
+
(parts.some((part) => part.attribution === 'synthetic') ||
|
|
125
|
+
!parts.some((part) => part.attribution === 'user'))
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The user's own message: not a cue, a skill prime or context the SDK built. */
|
|
130
|
+
function isUserMessage(message: BaseMessage): boolean {
|
|
131
|
+
return (
|
|
132
|
+
message.getType() === 'human' &&
|
|
133
|
+
!isSyntheticMetaMessage(message) &&
|
|
134
|
+
!isProviderContextMessage(message)
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Whether a message carries a cache breakpoint. */
|
|
139
|
+
function hasCacheMarker(message: BaseMessage): boolean {
|
|
140
|
+
return (
|
|
141
|
+
Array.isArray(message.content) &&
|
|
142
|
+
message.content.some((block) => getCacheControl(block) != null)
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
106
146
|
/**
|
|
107
147
|
* Encapsulates agent-specific state that can vary between agents in a multi-agent system
|
|
108
148
|
*/
|
|
@@ -1062,9 +1102,10 @@ export class AgentContext {
|
|
|
1062
1102
|
}
|
|
1063
1103
|
|
|
1064
1104
|
const promptCacheProvider = this.getPromptCacheProvider();
|
|
1105
|
+
const anchorsOnUser = this.anchorsPromptCacheOnUser(promptCacheProvider);
|
|
1065
1106
|
const shouldMoveDynamicInstructions =
|
|
1066
1107
|
promptCacheProvider != null &&
|
|
1067
|
-
stableInstructions !== '' &&
|
|
1108
|
+
(stableInstructions !== '' || anchorsOnUser) &&
|
|
1068
1109
|
dynamicInstructions !== '';
|
|
1069
1110
|
const systemMessage = this.buildSystemMessage({
|
|
1070
1111
|
stableInstructions,
|
|
@@ -1094,6 +1135,20 @@ export class AgentContext {
|
|
|
1094
1135
|
this.summaryText != null &&
|
|
1095
1136
|
this.summaryText !== '';
|
|
1096
1137
|
|
|
1138
|
+
if (anchorsOnUser) {
|
|
1139
|
+
return [
|
|
1140
|
+
...prefix,
|
|
1141
|
+
...this.buildUserAnchoredPromptCacheBody({
|
|
1142
|
+
messages,
|
|
1143
|
+
dynamicInstructions: shouldMoveDynamicInstructions
|
|
1144
|
+
? dynamicInstructions
|
|
1145
|
+
: '',
|
|
1146
|
+
hasSummaryBody,
|
|
1147
|
+
ttl: this.getPromptCacheTtl(promptCacheProvider),
|
|
1148
|
+
}),
|
|
1149
|
+
];
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1097
1152
|
const bodyWithSummary =
|
|
1098
1153
|
hasSummaryBody && promptCacheProvider == null
|
|
1099
1154
|
? [this.buildSummaryHumanMessage(promptCacheProvider), ...messages]
|
|
@@ -1200,6 +1255,84 @@ export class AgentContext {
|
|
|
1200
1255
|
return [...cacheablePrefix, ...tail, ...cacheableTrailingMessages];
|
|
1201
1256
|
}
|
|
1202
1257
|
|
|
1258
|
+
/**
|
|
1259
|
+
* OpenAI models behind OpenRouter read a cached prefix back only from a
|
|
1260
|
+
* system, user or tool breakpoint (observed in live probes; an assistant
|
|
1261
|
+
* breakpoint gives nothing to read), so their volatile context follows the
|
|
1262
|
+
* latest user message, which carries the conversation breakpoint.
|
|
1263
|
+
*/
|
|
1264
|
+
private anchorsPromptCacheOnUser(
|
|
1265
|
+
promptCacheProvider: PromptCacheProvider | undefined
|
|
1266
|
+
): boolean {
|
|
1267
|
+
if (promptCacheProvider !== Providers.OPENROUTER) {
|
|
1268
|
+
return false;
|
|
1269
|
+
}
|
|
1270
|
+
const model = (this.clientOptions as { model?: string } | undefined)?.model;
|
|
1271
|
+
return (
|
|
1272
|
+
typeof model === 'string' && model.toLowerCase().startsWith('openai/')
|
|
1273
|
+
);
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
private buildUserAnchoredPromptCacheBody({
|
|
1277
|
+
messages,
|
|
1278
|
+
dynamicInstructions,
|
|
1279
|
+
hasSummaryBody,
|
|
1280
|
+
ttl,
|
|
1281
|
+
}: {
|
|
1282
|
+
messages: BaseMessage[];
|
|
1283
|
+
dynamicInstructions: string;
|
|
1284
|
+
hasSummaryBody: boolean;
|
|
1285
|
+
ttl?: PromptCacheTtl;
|
|
1286
|
+
}): BaseMessage[] {
|
|
1287
|
+
const summary = hasSummaryBody
|
|
1288
|
+
? [this.buildSummaryHumanMessage(undefined)]
|
|
1289
|
+
: [];
|
|
1290
|
+
const dynamic =
|
|
1291
|
+
dynamicInstructions !== '' ? [new HumanMessage(dynamicInstructions)] : [];
|
|
1292
|
+
const anchorIndex = findLastIndex(messages, isUserMessage);
|
|
1293
|
+
|
|
1294
|
+
if (anchorIndex < 0) {
|
|
1295
|
+
return [...summary, ...this.markPromptCacheTail(messages, ttl), ...dynamic];
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
const summaryFirst = this.summaryPrecedesMessages;
|
|
1299
|
+
return [
|
|
1300
|
+
...(summaryFirst ? summary : []),
|
|
1301
|
+
...stripAnthropicCacheControl(messages.slice(0, anchorIndex)),
|
|
1302
|
+
...(!summaryFirst ? summary : []),
|
|
1303
|
+
...addTailCacheControl([messages[anchorIndex]], ttl),
|
|
1304
|
+
...dynamic,
|
|
1305
|
+
...this.markPromptCacheTail(messages.slice(anchorIndex + 1), ttl),
|
|
1306
|
+
];
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
/**
|
|
1310
|
+
* Marks the last message these models can read a cached prefix back from.
|
|
1311
|
+
* Assistant breakpoints give them nothing to read, so the marker passes
|
|
1312
|
+
* over assistant messages, such as a predecessor agent's reply before a
|
|
1313
|
+
* handoff cue, and a tail with nothing else to mark carries none.
|
|
1314
|
+
*/
|
|
1315
|
+
private markPromptCacheTail(
|
|
1316
|
+
messages: BaseMessage[],
|
|
1317
|
+
ttl?: PromptCacheTtl
|
|
1318
|
+
): BaseMessage[] {
|
|
1319
|
+
const stripped = stripAnthropicCacheControl(messages);
|
|
1320
|
+
for (let index = stripped.length - 1; index >= 0; index--) {
|
|
1321
|
+
if (stripped[index].getType() === 'ai') {
|
|
1322
|
+
continue;
|
|
1323
|
+
}
|
|
1324
|
+
const [marked] = addTailCacheControl([stripped[index]], ttl);
|
|
1325
|
+
if (hasCacheMarker(marked)) {
|
|
1326
|
+
return [
|
|
1327
|
+
...stripped.slice(0, index),
|
|
1328
|
+
marked,
|
|
1329
|
+
...stripped.slice(index + 1),
|
|
1330
|
+
];
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
return stripped;
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1203
1336
|
private getPromptCacheDynamicTailIndex(
|
|
1204
1337
|
messages: BaseMessage[],
|
|
1205
1338
|
promptCacheProvider: PromptCacheProvider | undefined
|
|
@@ -1338,6 +1471,9 @@ export class AgentContext {
|
|
|
1338
1471
|
}
|
|
1339
1472
|
|
|
1340
1473
|
if (promptCacheProvider === Providers.OPENROUTER && !stableInstructions) {
|
|
1474
|
+
if (shouldMoveDynamicInstructions) {
|
|
1475
|
+
return undefined;
|
|
1476
|
+
}
|
|
1341
1477
|
return new SystemMessage(dynamicInstructions);
|
|
1342
1478
|
}
|
|
1343
1479
|
|