@librechat/agents 4.2.4 → 4.2.6

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.
Files changed (103) hide show
  1. package/dist/cjs/harness/identity.cjs +26 -0
  2. package/dist/cjs/harness/identity.cjs.map +1 -0
  3. package/dist/cjs/harness/index.cjs +3 -15
  4. package/dist/cjs/harness/index.cjs.map +1 -1
  5. package/dist/cjs/harness/providerText.cjs +79 -0
  6. package/dist/cjs/harness/providerText.cjs.map +1 -0
  7. package/dist/cjs/llm/contextPressureMeter.cjs +1 -1
  8. package/dist/cjs/llm/contextPressureMeter.cjs.map +1 -1
  9. package/dist/cjs/llm/google/index.cjs +27 -6
  10. package/dist/cjs/llm/google/index.cjs.map +1 -1
  11. package/dist/cjs/llm/google/utils/common.cjs +27 -14
  12. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  13. package/dist/cjs/llm/google/utils/signatures.cjs +137 -0
  14. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -0
  15. package/dist/cjs/llm/openai/index.cjs +21 -12
  16. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  17. package/dist/cjs/llm/openai/streamMetadata.cjs +4 -1
  18. package/dist/cjs/llm/openai/streamMetadata.cjs.map +1 -1
  19. package/dist/cjs/llm/providerTextBoundary.cjs +3 -0
  20. package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
  21. package/dist/cjs/llm/vertexai/index.cjs +90 -7
  22. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  23. package/dist/cjs/main.cjs +11 -0
  24. package/dist/cjs/messages/content.cjs +4 -1
  25. package/dist/cjs/messages/content.cjs.map +1 -1
  26. package/dist/cjs/messages/format.cjs +11 -8
  27. package/dist/cjs/messages/format.cjs.map +1 -1
  28. package/dist/cjs/stream.cjs +4 -1
  29. package/dist/cjs/stream.cjs.map +1 -1
  30. package/dist/cjs/tools/BashExecutor.cjs +2 -1
  31. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  32. package/dist/cjs/tools/ToolNode.cjs +141 -94
  33. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  34. package/dist/cjs/tools/toolOutputReferences.cjs +39 -17
  35. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  36. package/dist/esm/harness/identity.mjs +24 -0
  37. package/dist/esm/harness/identity.mjs.map +1 -0
  38. package/dist/esm/harness/index.mjs +3 -15
  39. package/dist/esm/harness/index.mjs.map +1 -1
  40. package/dist/esm/harness/providerText.mjs +78 -0
  41. package/dist/esm/harness/providerText.mjs.map +1 -0
  42. package/dist/esm/llm/contextPressureMeter.mjs +1 -1
  43. package/dist/esm/llm/contextPressureMeter.mjs.map +1 -1
  44. package/dist/esm/llm/google/index.mjs +23 -7
  45. package/dist/esm/llm/google/index.mjs.map +1 -1
  46. package/dist/esm/llm/google/utils/common.mjs +27 -14
  47. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  48. package/dist/esm/llm/google/utils/signatures.mjs +132 -0
  49. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -0
  50. package/dist/esm/llm/openai/index.mjs +21 -12
  51. package/dist/esm/llm/openai/index.mjs.map +1 -1
  52. package/dist/esm/llm/openai/streamMetadata.mjs +4 -1
  53. package/dist/esm/llm/openai/streamMetadata.mjs.map +1 -1
  54. package/dist/esm/llm/providerTextBoundary.mjs +3 -0
  55. package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
  56. package/dist/esm/llm/vertexai/index.mjs +91 -8
  57. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  58. package/dist/esm/main.mjs +4 -1
  59. package/dist/esm/messages/content.mjs +4 -1
  60. package/dist/esm/messages/content.mjs.map +1 -1
  61. package/dist/esm/messages/format.mjs +11 -8
  62. package/dist/esm/messages/format.mjs.map +1 -1
  63. package/dist/esm/stream.mjs +4 -1
  64. package/dist/esm/stream.mjs.map +1 -1
  65. package/dist/esm/tools/BashExecutor.mjs +2 -1
  66. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  67. package/dist/esm/tools/ToolNode.mjs +142 -95
  68. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  69. package/dist/esm/tools/toolOutputReferences.mjs +39 -18
  70. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  71. package/dist/types/harness/identity.d.ts +14 -0
  72. package/dist/types/harness/index.d.ts +5 -9
  73. package/dist/types/harness/providerText.d.ts +32 -0
  74. package/dist/types/index.d.ts +2 -0
  75. package/dist/types/llm/google/index.d.ts +4 -2
  76. package/dist/types/llm/google/utils/common.d.ts +5 -1
  77. package/dist/types/llm/google/utils/signatures.d.ts +23 -0
  78. package/dist/types/llm/openai/streamMetadata.d.ts +3 -3
  79. package/dist/types/llm/vertexai/index.d.ts +2 -17
  80. package/dist/types/messages/format.d.ts +3 -1
  81. package/dist/types/tools/ToolNode.d.ts +7 -7
  82. package/dist/types/tools/toolOutputReferences.d.ts +16 -4
  83. package/dist/types/types/llm.d.ts +2 -2
  84. package/package.json +1 -1
  85. package/src/harness/identity.ts +34 -0
  86. package/src/harness/index.ts +15 -23
  87. package/src/harness/providerText.ts +128 -0
  88. package/src/index.ts +9 -0
  89. package/src/llm/contextPressureMeter.ts +2 -4
  90. package/src/llm/google/index.ts +20 -6
  91. package/src/llm/google/utils/common.ts +23 -10
  92. package/src/llm/google/utils/signatures.ts +215 -0
  93. package/src/llm/openai/index.ts +60 -20
  94. package/src/llm/openai/streamMetadata.ts +14 -3
  95. package/src/llm/providerTextBoundary.ts +3 -0
  96. package/src/llm/vertexai/index.ts +127 -39
  97. package/src/messages/content.ts +14 -6
  98. package/src/messages/format.ts +42 -29
  99. package/src/stream.ts +10 -1
  100. package/src/tools/BashExecutor.ts +2 -1
  101. package/src/tools/ToolNode.ts +333 -256
  102. package/src/tools/toolOutputReferences.ts +101 -32
  103. package/src/types/llm.ts +10 -2
@@ -0,0 +1,23 @@
1
+ import type { BaseMessage } from '@langchain/core/messages';
2
+ import type { GeminiPart } from '@langchain/google-common';
3
+ import type { Part } from '@google/generative-ai';
4
+ export declare const GEMINI_PARTS = "__gemini_parts__";
5
+ export declare const GEMINI_REPLAY_UNSUPPORTED = "__gemini_replay_unsupported__";
6
+ export declare const GEMINI_SIGNATURES = "__gemini_function_call_thought_signatures__";
7
+ export type GeminiReplayPart = {
8
+ type: 'text';
9
+ length: number;
10
+ hash: string;
11
+ thought?: boolean;
12
+ thoughtSignature?: string;
13
+ } | {
14
+ type: 'function_call';
15
+ id: string;
16
+ hash: string;
17
+ thoughtSignature?: string;
18
+ };
19
+ export declare function isGeminiReplayParts(value: unknown): value is GeminiReplayPart[];
20
+ /** Captures native boundaries without duplicating prose. Known Gemini 1/2 models retain their existing signature formats for cross-model compatibility. */
21
+ export declare function captureGeminiReplayParts(message: BaseMessage, parts: readonly (Part | GeminiPart)[], model?: string): void;
22
+ /** Returns original parts only when the current message still matches every text hash and call id. */
23
+ export declare function restoreGeminiReplayParts(message: BaseMessage, replay?: unknown): GeminiPart[] | undefined;
@@ -4,9 +4,9 @@ export type SeenScalarMetadata = Map<number, Set<string>>;
4
4
  /**
5
5
  * Strip scalar `response_metadata`/`generationInfo` fields that have already
6
6
  * appeared on an earlier chunk of the same completion (tracked in `seen`),
7
- * keeping the first occurrence so the aggregated message still carries the
8
- * value once. Scoped per completion index so multi-choice (`n > 1`) responses,
9
- * which `_generate` aggregates separately, keep each choice's own metadata.
7
+ * keeping the first occurrence (first nonempty snapshot for usage) so the
8
+ * aggregated message still carries the value once. Scoped per completion index
9
+ * so multi-choice (`n > 1`) responses keep each choice's own metadata.
10
10
  *
11
11
  * Deletes from a shallow clone rather than in place: providers such as
12
12
  * `ChatDeepSeek` split one raw chunk into several synthetic pieces that share
@@ -2,8 +2,8 @@ import { ChatGoogle } from '@langchain/google-gauth';
2
2
  import { AIMessageChunk } from '@langchain/core/messages';
3
3
  import type { GeminiContent, GoogleAIModelRequestParams, GoogleAbstractedClient } from '@langchain/google-common';
4
4
  import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
5
- import type { BaseMessage, UsageMetadata } from '@langchain/core/messages';
6
5
  import type { ChatGenerationChunk } from '@langchain/core/outputs';
6
+ import type { BaseMessage, UsageMetadata } from '@langchain/core/messages';
7
7
  import type { GoogleThinkingConfig, VertexAIClientOptions } from '@/types';
8
8
  /**
9
9
  * `@langchain/google-common`'s `_streamResponseChunks` emits usage on TWO
@@ -39,22 +39,7 @@ export declare function repairStreamUsageMetadata(current: UsageMetadata | undef
39
39
  * the parse check is left unstamped and falls back to the lazy path.
40
40
  */
41
41
  export declare function sealCompleteStreamedToolCalls(message: AIMessageChunk): void;
42
- /**
43
- * Fixes thought signatures on functionCall parts in the formatted Gemini request.
44
- *
45
- * `@langchain/google-common` stores signatures as a flat array in
46
- * `additional_kwargs.signatures` (one per response part) and re-attaches them
47
- * by index only when `signatures.length === parts.length`. This fails when:
48
- * - The API omits a signature (length mismatch)
49
- * - Streaming chunks merge with different part counts
50
- * - The signature for a functionCall part is an empty string
51
- *
52
- * This function correlates each "model" content block in the formatted request
53
- * back to its originating AI message by *position*, then re-attaches non-empty
54
- * signatures that the library failed to apply. AI messages without signatures
55
- * still consume their slot — filtering them out shifted later messages onto
56
- * the wrong content block and dropped real signatures on the floor.
57
- */
42
+ /** Restores native part order. Legacy text with merged positional slots has lost its boundaries and requires regeneration. */
58
43
  export declare function fixThoughtSignatures(contents: GeminiContent[], input: BaseMessage[]): void;
59
44
  /**
60
45
  * Integration with Google Vertex AI chat models.
@@ -1,8 +1,8 @@
1
1
  import { AIMessage, ToolMessage, BaseMessage, HumanMessage, SystemMessage } from '@langchain/core/messages';
2
2
  import type { MessageContentImageUrl } from '@langchain/core/messages';
3
3
  import type { RunnableConfig } from '@langchain/core/runnables';
4
- import type { ToolHistoryPreparation } from './toolHistoryProjection';
5
4
  import type { MessageContentComplex, TPayload, ProviderName, CompactionSemanticIndex, CompactionSemanticIndexSnapshot } from '@/types';
5
+ import type { ToolHistoryPreparation } from './toolHistoryProjection';
6
6
  import { Providers } from '@/common';
7
7
  interface MediaMessageParams {
8
8
  message: {
@@ -102,6 +102,8 @@ export interface FormatAgentMessagesOptions {
102
102
  * tool-call messages. Explicit opt-in for OpenAI-compatible endpoints that
103
103
  * replay reasoning across turns; defaults to on for DeepSeek thinking-mode. */
104
104
  preserveReasoningContent?: boolean;
105
+ /** Preserve exact assistant text bytes for provider signature replay. */
106
+ preserveTextContent?: boolean;
105
107
  /** Skill names already primed fresh this turn (manual/always-apply). Their
106
108
  * historical `skill` tool_calls are not reconstructed into a HumanMessage,
107
109
  * so the same SKILL.md body is not injected twice in one request. */
@@ -2,7 +2,7 @@ import { ToolCall } from '@langchain/core/messages/tool';
2
2
  import { END, Command, MessagesAnnotation } from '@langchain/langgraph';
3
3
  import type { RunnableConfig } from '@langchain/core/runnables';
4
4
  import type { BaseMessage } from '@langchain/core/messages';
5
- import type { ToolOutputResolveView, ToolOutputReferenceState, ResolvedArgsByCallId } from '@/tools/toolOutputReferences';
5
+ import type { ToolOutputResolveView, ToolOutputReferenceState, ResolvedArgsByCallId, ResolveResult } from '@/tools/toolOutputReferences';
6
6
  import type { SubagentToolNodeResumeState } from '@/tools/subagent/SubagentReplay';
7
7
  import type * as t from '@/types';
8
8
  import { ToolOutputReferenceRegistry } from '@/tools/toolOutputReferences';
@@ -21,6 +21,7 @@ type RunToolBatchContext<T = unknown> = {
21
21
  batchScopeId?: string;
22
22
  /** Batch-local sink for post-substitution args. */
23
23
  resolvedArgsByCallId?: ResolvedArgsByCallId;
24
+ resolvedInput?: ResolveResult<ToolCall['args']>;
24
25
  /** File identities actually injected into each direct code call. */
25
26
  codeSessionBaselineByCallId?: Map<string, ReadonlyMap<string, string>>;
26
27
  /**
@@ -310,6 +311,7 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
310
311
  * substitutions. Omit when no registration should occur.
311
312
  */
312
313
  protected runTool(call: ToolCall, config: RunnableConfig, batchContext?: RunToolBatchContext<T>): Promise<BaseMessage | Command>;
314
+ private unresolvedReferenceMessage;
313
315
  /**
314
316
  * Runs a single in-process tool call with the same lifecycle hooks
315
317
  * the event-dispatch path fires (`PreToolUse`, `PermissionDenied`,
@@ -343,8 +345,8 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
343
345
  * the rest of the SDK's HITL-disabled default). One-time
344
346
  * warning logged so hosts notice the gap.
345
347
  * - `PreToolUse.updatedInput` is applied to the call before
346
- * `runTool` runs; placeholder resolution inside `runTool` is
347
- * idempotent on already-resolved args.
348
+ * `runTool` runs; the resolution result is carried to invocation so
349
+ * substituted output and escaped literals are never expanded twice.
348
350
  * - `PostToolUse.updatedOutput` replaces the returned
349
351
  * `ToolMessage` content (preserving id/name/status).
350
352
  * - `PostToolUseFailure` fires when `runTool` returns a
@@ -389,10 +391,8 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
389
391
  * @param refKey Precomputed `tool<i>turn<n>` key, or undefined when
390
392
  * the output is not to be registered (errors, disabled feature,
391
393
  * unavailable batch/turn).
392
- * @param unresolved Placeholder keys that did not resolve; surfaced
393
- * to the LLM lazily so it can self-correct.
394
- * @returns A `ToolMessageRefMetadata` object when there is anything
395
- * to stamp, otherwise `undefined`.
394
+ * @returns A `ToolMessageRefMetadata` object when the output was
395
+ * registered, otherwise `undefined`.
396
396
  */
397
397
  private recordOutputReference;
398
398
  /**
@@ -10,7 +10,12 @@
10
10
  * Subsequent tool calls can pipe a previous output into their args by
11
11
  * embedding `{{tool<idx>turn<turn>}}` inside any string argument;
12
12
  * {@link ToolOutputReferenceRegistry.resolve} walks the args and
13
- * substitutes the placeholders immediately before invocation.
13
+ * substitutes the placeholders immediately before invocation. Backslashes
14
+ * directly before a placeholder follow the usual escape rule: each pair
15
+ * collapses to one literal backslash, and a remaining single backslash is
16
+ * removed and escapes the placeholder, which then passes through as literal
17
+ * text without a registry lookup. So `\{{tool0turn0}}` is the literal
18
+ * placeholder and `\\{{tool0turn0}}` is a backslash followed by the output.
14
19
  *
15
20
  * The registry stores the *raw, untruncated* tool output so a later
16
21
  * `{{…}}` substitution pipes the full payload into the next tool —
@@ -77,6 +82,7 @@ export type ResolveResult<T> = {
77
82
  * point in time, ignoring any subsequent registrations.
78
83
  */
79
84
  export interface ToolOutputResolveView {
85
+ readonly availableKeys?: readonly string[];
80
86
  resolve<T>(args: T, options?: ResolveOptions): ResolveResult<T>;
81
87
  }
82
88
  /**
@@ -88,6 +94,8 @@ export interface ToolOutputResolveView {
88
94
  */
89
95
  export type ResolveOptions = {
90
96
  substituteIntentKey?: boolean;
97
+ /** Detached pre-editor input; unchanged string leaves stay literal. */
98
+ previouslyResolved?: Record<string, unknown> | string;
91
99
  };
92
100
  /**
93
101
  * Pre-resolved arg map keyed by `toolCallId`. Used by the mixed
@@ -122,9 +130,11 @@ export declare class ToolOutputReferenceRegistry {
122
130
  private readonly maxTotalSize;
123
131
  private readonly maxActiveRuns;
124
132
  /**
125
- * Local stateful matcher used only by `replaceInString`. Kept
126
- * off-module so callers of the exported `TOOL_OUTPUT_REF_PATTERN`
127
- * never see a stale `lastIndex`.
133
+ * Global matcher used only by `replaceInString`. Kept off-module so
134
+ * callers of the exported `TOOL_OUTPUT_REF_PATTERN` never see a stale
135
+ * `lastIndex`. Leading backslashes are counted by hand rather than
136
+ * matched: a `\\*` prefix would backtrack quadratically over a long
137
+ * backslash run that no placeholder follows.
128
138
  */
129
139
  private static readonly PLACEHOLDER_MATCHER;
130
140
  constructor(options?: ToolOutputReferenceRegistryOptions);
@@ -208,6 +218,8 @@ export declare class ToolOutputReferenceRegistry {
208
218
  private replaceInString;
209
219
  private evictWithinBucket;
210
220
  }
221
+ /** Detached editor baseline; reference-free inputs need no retained values. */
222
+ export declare function snapshotResolvedArgs(args: Record<string, unknown>): Record<string, unknown>;
211
223
  /**
212
224
  * Annotates `content` with a reference key and/or unresolved-ref
213
225
  * warnings so the LLM sees both alongside the tool output.
@@ -51,7 +51,7 @@ export type AnthropicReasoning = {
51
51
  export type GoogleThinkingConfig = {
52
52
  thinkingBudget?: number;
53
53
  includeThoughts?: boolean;
54
- thinkingLevel?: 'THINKING_LEVEL_UNSPECIFIED' | 'LOW' | 'MEDIUM' | 'HIGH';
54
+ thinkingLevel?: 'THINKING_LEVEL_UNSPECIFIED' | 'LOW' | 'MEDIUM' | 'HIGH' | 'XHIGH';
55
55
  };
56
56
  /** GPT-5.6 managed-request passthrough fields, shared by the OpenAI and
57
57
  * Azure wrappers that both read them. */
@@ -122,7 +122,7 @@ export type BedrockAnthropicInput = ChatBedrockConverseInput & StreamSmoothingOp
122
122
  };
123
123
  export type BedrockConverseClientOptions = BedrockAnthropicInput;
124
124
  export type BedrockAnthropicClientOptions = BedrockAnthropicInput;
125
- export type GoogleClientOptions = GoogleGenerativeAIChatInput & StreamSmoothingOptions & {
125
+ export type GoogleClientOptions = Omit<GoogleGenerativeAIChatInput, 'thinkingConfig'> & StreamSmoothingOptions & {
126
126
  customHeaders?: RequestOptions['customHeaders'];
127
127
  thinkingConfig?: GoogleThinkingConfig;
128
128
  includeServerSideToolInvocations?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "4.2.4",
3
+ "version": "4.2.6",
4
4
  "reova": {
5
5
  "enabled": true,
6
6
  "endpoint": "https://telemetry.reo.dev/data"
@@ -0,0 +1,34 @@
1
+ import { z } from 'zod';
2
+
3
+ const requiredIdentityField = z
4
+ .string()
5
+ .refine((value) => value.trim().length > 0);
6
+
7
+ /** Established by the authenticated host, never inferred from model arguments. */
8
+ export const executionIdentitySchema = z.object({
9
+ runtimeId: requiredIdentityField,
10
+ agentId: requiredIdentityField,
11
+ runId: requiredIdentityField,
12
+ userId: requiredIdentityField,
13
+ tenantId: z.string().optional(),
14
+ conversationId: z.string().optional(),
15
+ });
16
+
17
+ export type ExecutionIdentity = z.infer<typeof executionIdentitySchema>;
18
+ const identityKeys = executionIdentitySchema.keyof().options;
19
+
20
+ /** Validates and snapshots identity at the host binding boundary. */
21
+ export function snapshotExecutionIdentity(
22
+ source: Readonly<ExecutionIdentity>
23
+ ): Readonly<ExecutionIdentity> {
24
+ const result = executionIdentitySchema.safeParse(source);
25
+ if (!result.success) throw new Error('Incomplete execution identity');
26
+ return Object.freeze(result.data);
27
+ }
28
+
29
+ export function matchesExecutionIdentity(
30
+ a: Readonly<ExecutionIdentity>,
31
+ b: Readonly<ExecutionIdentity>
32
+ ): boolean {
33
+ return identityKeys.every((key) => a[key] === b[key]);
34
+ }
@@ -5,17 +5,11 @@ import type {
5
5
  ToolExecuteBatchRequest,
6
6
  ToolExecuteResult,
7
7
  } from '@/types';
8
+ import type { ExecutionIdentity } from './identity';
9
+ import { snapshotExecutionIdentity } from './identity';
8
10
  import { GraphEvents } from '@/common';
9
-
10
- /** Established by the authenticated host, never inferred from model arguments. */
11
- export interface ExecutionIdentity {
12
- runtimeId: string;
13
- agentId: string;
14
- runId: string;
15
- userId: string;
16
- tenantId?: string;
17
- conversationId?: string;
18
- }
11
+ export { snapshotExecutionIdentity } from './identity';
12
+ export type { ExecutionIdentity } from './identity';
19
13
 
20
14
  /** A host reference selects an authorized implementation, not a URL or executable name. */
21
15
  export interface HostToolDescriptor {
@@ -81,19 +75,7 @@ export function createHostToolBindings(options: {
81
75
  }): HostToolBindings {
82
76
  if (Number(options.service.version) !== 1)
83
77
  throw new Error('Unsupported host tool service version');
84
- const source = options.identity;
85
- const identity = Object.freeze({
86
- runtimeId: source.runtimeId,
87
- agentId: source.agentId,
88
- runId: source.runId,
89
- userId: source.userId,
90
- tenantId: source.tenantId,
91
- conversationId: source.conversationId,
92
- });
93
- for (const key of ['runtimeId', 'agentId', 'runId', 'userId'] as const) {
94
- if (identity[key].trim().length === 0)
95
- throw new Error('Incomplete execution identity');
96
- }
78
+ const identity = snapshotExecutionIdentity(options.identity);
97
79
  const references = new Map<string, string>();
98
80
  const toolDefinitions: LCTool[] = [];
99
81
  for (const descriptor of options.tools) {
@@ -224,3 +206,13 @@ export function createHostToolBindings(options: {
224
206
  },
225
207
  };
226
208
  }
209
+
210
+ export {
211
+ createHostProviderTextService,
212
+ createHostProviderTextProtection,
213
+ } from './providerText';
214
+ export type {
215
+ HostProviderTextDescriptor,
216
+ HostProviderTextRequest,
217
+ HostProviderTextService,
218
+ } from './providerText';
@@ -0,0 +1,128 @@
1
+ import { z } from 'zod';
2
+ import type { ProviderTextProtection } from '@/protection/providerText';
3
+ import type { ExecutionIdentity } from './identity';
4
+ import {
5
+ ProviderTextAttempt,
6
+ ProviderTextProtectionError,
7
+ validateProviderTextProtection,
8
+ } from '@/protection/providerText';
9
+ import {
10
+ executionIdentitySchema,
11
+ snapshotExecutionIdentity,
12
+ matchesExecutionIdentity,
13
+ } from './identity';
14
+
15
+ /** Host-owned limits, negotiated before executing a graph. Contains no credentials or callbacks. */
16
+ export type HostProviderTextDescriptor = Pick<
17
+ ProviderTextProtection,
18
+ 'version' | 'timeoutMs' | 'maxAttemptBytes' | 'maxBufferedBytes'
19
+ >;
20
+
21
+ export interface HostProviderTextRequest {
22
+ readonly version: 1;
23
+ readonly identity: Readonly<ExecutionIdentity>;
24
+ readonly content: string;
25
+ }
26
+
27
+ /** Transport implementations authenticate callers and validate incoming data before dispatch. */
28
+ export interface HostProviderTextService {
29
+ readonly version: 1;
30
+ inspect(
31
+ request: HostProviderTextRequest,
32
+ signal?: AbortSignal
33
+ ): Promise<string>;
34
+ }
35
+
36
+ const requestSchema = z.object({
37
+ version: z.literal(1),
38
+ content: z.string(),
39
+ identity: executionIdentitySchema,
40
+ });
41
+
42
+ function boundIdentity(
43
+ source: Readonly<ExecutionIdentity>
44
+ ): Readonly<ExecutionIdentity> {
45
+ try {
46
+ return snapshotExecutionIdentity(source);
47
+ } catch {
48
+ throw new ProviderTextProtectionError('incompatible');
49
+ }
50
+ }
51
+
52
+ /** Classification, inspection, deadlines and shared raw-text budgets remain authoritative on the host. */
53
+ export function createHostProviderTextService(options: {
54
+ identity: Readonly<ExecutionIdentity>;
55
+ policy: ProviderTextProtection;
56
+ }): {
57
+ descriptor: HostProviderTextDescriptor;
58
+ service: HostProviderTextService;
59
+ } {
60
+ const identity = boundIdentity(options.identity);
61
+ const policy = options.policy;
62
+ validateProviderTextProtection(policy);
63
+ return {
64
+ descriptor: Object.freeze({
65
+ version: 1,
66
+ timeoutMs: policy.timeoutMs,
67
+ maxAttemptBytes: policy.maxAttemptBytes,
68
+ maxBufferedBytes: policy.maxBufferedBytes,
69
+ }),
70
+ service: {
71
+ version: 1,
72
+ inspect: async (request, signal): Promise<string> => {
73
+ const parsed = requestSchema.safeParse(request);
74
+ if (
75
+ !parsed.success ||
76
+ !matchesExecutionIdentity(parsed.data.identity, identity)
77
+ )
78
+ throw new ProviderTextProtectionError('incompatible');
79
+ const attempt = new ProviderTextAttempt(policy, signal);
80
+ try {
81
+ attempt.append(parsed.data.content);
82
+ return await attempt.release();
83
+ } finally {
84
+ attempt.finish();
85
+ }
86
+ },
87
+ },
88
+ };
89
+ }
90
+
91
+ /**
92
+ * Installs the SDK's existing release boundary around a transport-neutral host service.
93
+ * The SDK release boundary buffers each attempt before one host request.
94
+ * Classification and inspection statistics belong to the host. The adapter returns only canonical text.
95
+ */
96
+ export function createHostProviderTextProtection(options: {
97
+ identity: Readonly<ExecutionIdentity>;
98
+ descriptor: HostProviderTextDescriptor;
99
+ service: HostProviderTextService;
100
+ }): ProviderTextProtection {
101
+ const identity = boundIdentity(options.identity);
102
+ const service = options.service;
103
+ const serviceVersion: number = service.version;
104
+ const descriptorVersion: number = options.descriptor.version;
105
+ if (serviceVersion !== 1 || descriptorVersion !== 1)
106
+ throw new ProviderTextProtectionError('incompatible');
107
+ const policy: ProviderTextProtection = {
108
+ version: 1,
109
+ timeoutMs: options.descriptor.timeoutMs,
110
+ maxAttemptBytes: options.descriptor.maxAttemptBytes,
111
+ maxBufferedBytes: options.descriptor.maxBufferedBytes,
112
+ // The synchronous SDK classification gate defers to authoritative host classification.
113
+ classify: () => 'prose',
114
+ inspect: async ({ content, signal }) => {
115
+ const canonical = await service.inspect(
116
+ { version: 1, identity, content },
117
+ signal
118
+ );
119
+ return {
120
+ version: 1,
121
+ ok: true,
122
+ value: { content: canonical, replacements: 0, categories: [] },
123
+ };
124
+ },
125
+ };
126
+ validateProviderTextProtection(policy);
127
+ return Object.freeze(policy);
128
+ }
package/src/index.ts CHANGED
@@ -133,5 +133,14 @@ export type {
133
133
  ProviderTextProtectionErrorCode,
134
134
  } from './protection/providerText';
135
135
 
136
+ export {
137
+ GEMINI_PARTS,
138
+ GEMINI_REPLAY_UNSUPPORTED,
139
+ captureGeminiReplayParts,
140
+ restoreGeminiReplayParts,
141
+ isGeminiReplayParts,
142
+ } from './llm/google/utils/signatures';
143
+ export type { GeminiReplayPart } from './llm/google/utils/signatures';
144
+
136
145
  /* Host execution harness */
137
146
  export * from './harness';
@@ -1,16 +1,14 @@
1
1
  import { isProxy } from 'node:util/types';
2
2
  import { ToolMessage } from '@langchain/core/messages';
3
-
4
3
  import type { AIMessage, BaseMessage } from '@langchain/core/messages';
5
4
  import type { ProviderPayloadMeasurement } from '@/llm/prepareProviderRequest';
6
5
  import type * as t from '@/types';
7
-
8
6
  import {
9
7
  REPLY_PRIMER_TOKENS,
10
8
  isSyntheticProviderContextMessage,
11
9
  } from '@/messages';
12
- import { createToolMessageUsageAccumulator } from '@/messages/budget';
13
10
  import { readTokenMetadataProperty, apportionTokenCounts } from '@/utils';
11
+ import { createToolMessageUsageAccumulator } from '@/messages/budget';
14
12
 
15
13
  interface ContextPressureUsage {
16
14
  contextBudget?: number;
@@ -409,7 +407,7 @@ export function createContextPressureMeter({
409
407
  baselineRemaining != null &&
410
408
  Number.isFinite(baselineRemaining)
411
409
  ? availableMessageTokens -
412
- Math.min(availableMessageTokens, Math.max(0, baselineRemaining))
410
+ Math.min(availableMessageTokens, baselineRemaining)
413
411
  : undefined;
414
412
  const toolUsage = createToolMessageUsageAccumulator(provider);
415
413
  const toolUsageState: { error?: Error } = {};
@@ -15,7 +15,7 @@ import type {
15
15
  import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
16
16
  import type { BaseMessage, UsageMetadata } from '@langchain/core/messages';
17
17
  import type { GeminiApiUsageMetadata, InputTokenDetails } from './types';
18
- import type { GoogleClientOptions, GoogleThinkingConfig } from '@/types';
18
+ import type { GoogleClientOptions } from '@/types';
19
19
  import {
20
20
  convertResponseContentToChatGenerationChunk,
21
21
  convertBaseMessagesToContent,
@@ -40,7 +40,7 @@ type GoogleToolConfigWithServerSideInvocations = ToolConfig & {
40
40
 
41
41
  export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
42
42
  _lc_stream_delay: number;
43
- thinkingConfig?: GoogleThinkingConfig;
43
+ thinkingConfig?: ChatGoogleGenerativeAI['thinkingConfig'];
44
44
  includeServerSideToolInvocations?: boolean;
45
45
 
46
46
  /**
@@ -58,7 +58,10 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
58
58
  }
59
59
 
60
60
  constructor(fields: GoogleClientOptions) {
61
- super(fields);
61
+ // The upstream type omits Hydrogen's XHIGH level; the API accepts it unchanged.
62
+ const thinkingConfig =
63
+ fields.thinkingConfig as ChatGoogleGenerativeAI['thinkingConfig'];
64
+ super({ ...fields, thinkingConfig });
62
65
 
63
66
  this._lc_stream_delay = resolveStreamDelay(fields._lc_stream_delay);
64
67
  this.model = fields.model.replace(/^models\//, '');
@@ -115,7 +118,7 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
115
118
  }
116
119
  }
117
120
 
118
- this.thinkingConfig = fields.thinkingConfig ?? this.thinkingConfig;
121
+ this.thinkingConfig = thinkingConfig ?? this.thinkingConfig;
119
122
  this.includeServerSideToolInvocations =
120
123
  fields.includeServerSideToolInvocations ??
121
124
  this.includeServerSideToolInvocations;
@@ -172,7 +175,7 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
172
175
  total_tokens: usageMetadata.totalTokenCount ?? 0,
173
176
  };
174
177
 
175
- if (usageMetadata.cachedContentTokenCount) {
178
+ if ((usageMetadata.cachedContentTokenCount ?? 0) > 0) {
176
179
  output.input_token_details ??= {};
177
180
  output.input_token_details.cache_read =
178
181
  usageMetadata.cachedContentTokenCount;
@@ -188,7 +191,7 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
188
191
  0,
189
192
  (usageMetadata.cachedContentTokenCount ?? 0) - 200000
190
193
  );
191
- if (over200k) {
194
+ if (over200k > 0) {
192
195
  output.input_token_details = {
193
196
  ...output.input_token_details,
194
197
  over_200k: over200k,
@@ -285,6 +288,7 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
285
288
  /** @ts-ignore */
286
289
  const generationResult = mapGenerateContentResultToChatResult(response, {
287
290
  usageMetadata,
291
+ model: this.model,
288
292
  });
289
293
 
290
294
  await runManager?.handleLLMNewToken(
@@ -359,6 +363,7 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
359
363
 
360
364
  const chunk = convertResponseContentToChatGenerationChunk(response, {
361
365
  usageMetadata: undefined,
366
+ model: this.model,
362
367
  index,
363
368
  });
364
369
  index += 1;
@@ -380,3 +385,12 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
380
385
  }
381
386
  }
382
387
  }
388
+
389
+ export {
390
+ GEMINI_PARTS,
391
+ GEMINI_REPLAY_UNSUPPORTED,
392
+ captureGeminiReplayParts,
393
+ restoreGeminiReplayParts,
394
+ isGeminiReplayParts,
395
+ } from './utils/signatures';
396
+ export type { GeminiReplayPart } from './utils/signatures';