@juspay/neurolink 13.11.0 → 13.12.1
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/CHANGELOG.md +5 -7
- package/dist/auth/middleware/AuthMiddleware.d.ts +1 -1
- package/dist/browser/neurolink.min.js +435 -435
- package/dist/cli/loop/optionsSchema.d.ts +1 -1
- package/dist/neurolink.d.ts +7 -0
- package/dist/neurolink.js +21 -0
- package/dist/providers/amazonSagemaker.d.ts +1 -1
- package/dist/providers/anthropic/client.d.ts +9 -0
- package/dist/providers/anthropic/client.js +139 -10
- package/dist/providers/anthropic/threads.d.ts +39 -2
- package/dist/providers/anthropic/threads.js +246 -4
- package/dist/providers/catalog/schema.d.ts +1 -1
- package/dist/providers/sagemaker/language-model.d.ts +2 -2
- package/dist/proxy/otelLogSink.d.ts +1 -1
- package/dist/server/utils/validation.d.ts +28 -28
- package/dist/types/generate.d.ts +16 -0
- package/dist/types/loopEngine.d.ts +29 -2
- package/dist/types/stream.d.ts +12 -3
- package/dist/workflow/config.d.ts +7 -7
- package/docs-site/static/search-index.json +1 -0
- package/package.json +14 -11
|
@@ -4,4 +4,4 @@ import type { OptionSchema, TextGenerationOptions } from "../../types/index.js";
|
|
|
4
4
|
* This object provides metadata for validation and help text in the CLI loop.
|
|
5
5
|
* It is derived from the main TextGenerationOptions interface to ensure consistency.
|
|
6
6
|
*/
|
|
7
|
-
export declare const textGenerationOptionsSchema: Record<keyof Omit<TextGenerationOptions, "prompt" | "input" | "schema" | "tools" | "context" | "conversationHistory" | "conversationMessages" | "conversationMemoryConfig" | "originalPrompt" | "middleware" | "expectedOutcome" | "evaluationCriteria" | "region" | "csvOptions" | "pdfOptions" | "imageOptions" | "audioOptions" | "videoOptions" | "officeOptions" | "tts" | "stt" | "thinkingConfig" | "requestId" | "fileRegistry" | "attachmentPolicy" | "abortSignal" | "toolFilter" | "excludeTools" | "toolChoice" | "prepareStep" | "credentials" | "onFinish" | "onError" | "processors" | "piiDetection" | "responseValidation" | "inputValidation" | "toolExecutionCapture" | "toolExecutionRecorder" | "toolRoots">, OptionSchema>;
|
|
7
|
+
export declare const textGenerationOptionsSchema: Record<keyof Omit<TextGenerationOptions, "prompt" | "input" | "schema" | "tools" | "context" | "conversationHistory" | "conversationMessages" | "conversationMemoryConfig" | "messageThreads" | "originalPrompt" | "middleware" | "expectedOutcome" | "evaluationCriteria" | "region" | "csvOptions" | "pdfOptions" | "imageOptions" | "audioOptions" | "videoOptions" | "officeOptions" | "tts" | "stt" | "thinkingConfig" | "requestId" | "fileRegistry" | "attachmentPolicy" | "abortSignal" | "toolFilter" | "excludeTools" | "toolChoice" | "prepareStep" | "credentials" | "onFinish" | "onError" | "processors" | "piiDetection" | "responseValidation" | "inputValidation" | "toolExecutionCapture" | "toolExecutionRecorder" | "toolRoots">, OptionSchema>;
|
package/dist/neurolink.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { DecisionCallerOptions, DecisionLimitsQuery, DecisionLimitsReading, DecisionOptions, DecisionResult, AgentDefinition, AgentNetworkConfig, AgentRunOptions, AgentRunOutcome, AgentToolRegistrationOptions, IsolatedAgentDefinition, NetworkExecutionInput, NetworkExecutionOptions, NetworkExecutionResult, NetworkStreamChunk, WorkerInstanceOptions } from "./types/index.js";
|
|
2
2
|
import type { CompactionConfig, CompactionResult, ArtifactStore, SpanData, ExporterStatus, ObservabilityConfig, MetricsSummary, MCPToolAnnotations, TraceView, AuthenticatedContext, AuthProvider, JsonObject, NeuroLinkEvents, TypedEventEmitter, MCPEnhancementsConfig, NeuroLinkAuthConfig, NeurolinkConstructorConfig, ChatMessage, ConversationSeedMessage, ConversationSeedOptions, RecordConversationTurnOptions, RecordConversationTurnResult, ExternalMCPOperationResult, ExternalMCPServerInstance, ExternalMCPServerHealth, ExternalMCPToolInfo, GenerateOptions, GenerateResult, ProviderStatus, TextGenerationOptions, TextGenerationResult, MCPExecutableTool, MCPServerInfo, MCPStatus, StreamOptions, StreamResult, ToolExecutionContext, ToolExecutionSummary, ToolInfo, ToolRegistrationOptions, BatchOperationResult, StreamGenerationEndContext, ToolRoutingServerDescriptor, ToolDedupConfig, ToolConfig, KnowledgeEngineStatus, ChecklistState, ArtifactPageRequest, BankArtifactOptions, BankedArtifactRef, DelegateCollectRequest, DelegateCollectResult, DelegateHandle, DelegateRegistrationOptions, DelegateSpawnOptions, BackgroundCommandHandle, BackgroundCommandOptions, BackgroundCommandOutputPage, BackgroundCommandPageRequest, BackgroundCommandPolicy, BackgroundCommandStatus, GitToolResult, GitToolsetOptions } from "./types/index.js";
|
|
3
3
|
import { ConversationMemoryManager } from "./core/conversationMemoryManager.js";
|
|
4
|
+
import { AnthropicThreadStore } from "./providers/anthropic/threads.js";
|
|
4
5
|
import type { RedisConversationMemoryManager } from "./core/redisConversationMemoryManager.js";
|
|
5
6
|
import { ExternalServerManager } from "./mcp/externalServerManager.js";
|
|
6
7
|
import { MCPToolRegistry } from "./mcp/toolRegistry.js";
|
|
@@ -93,6 +94,12 @@ export declare class NeuroLink {
|
|
|
93
94
|
private readonly toolCacheDuration;
|
|
94
95
|
private modelAliasConfig?;
|
|
95
96
|
private lastCompactionMessageCount;
|
|
97
|
+
/**
|
|
98
|
+
* Anthropic message threads left for sessions' next calls (opt-in, in memory,
|
|
99
|
+
* per process). Forgetting one here does not delete it on the server: the API
|
|
100
|
+
* has no delete, and the thread expires within an hour.
|
|
101
|
+
*/
|
|
102
|
+
readonly anthropicThreadStore: AnthropicThreadStore;
|
|
96
103
|
/** Extract sessionId from options context for compaction watermark keying */
|
|
97
104
|
private getCompactionSessionId;
|
|
98
105
|
private mcpToolResultCache?;
|
package/dist/neurolink.js
CHANGED
|
@@ -38,6 +38,7 @@ import { ConversationMemoryManager } from "./core/conversationMemoryManager.js";
|
|
|
38
38
|
import { buildToolRoutingCatalog, buildRoutingQueryFromHistory, resolveToolRoutingExclusions, } from "./core/toolRouting.js";
|
|
39
39
|
import { ToolRoutingCache } from "./core/toolRoutingCache.js";
|
|
40
40
|
import { DEFAULT_RECENT_TURNS, KnowledgeGroundingEngine, } from "./knowledge/index.js";
|
|
41
|
+
import { AnthropicThreadStore } from "./providers/anthropic/threads.js";
|
|
41
42
|
import { AIProviderFactory } from "./core/factory.js";
|
|
42
43
|
import { describeDecisionProviderKeys, PROVIDER_ALIAS_INDEX, PROVIDER_DESCRIPTORS_BY_NAME, resolveDefaultDecisionProvider, } from "./factories/providerDescriptors.js";
|
|
43
44
|
import { describeSTTProviderKeys, getSTTProviderDescriptor, listConfiguredSTTProviders, resolveCallSTTEndpoints, resolveDefaultSTTProvider, resolveSTTProviderName, } from "./factories/sttDescriptors.js";
|
|
@@ -617,6 +618,12 @@ export class NeuroLink {
|
|
|
617
618
|
// Compaction watermark: prevents re-triggering compaction on already-compacted messages
|
|
618
619
|
// Per-session map to avoid cross-session pollution in server mode
|
|
619
620
|
lastCompactionMessageCount = new Map();
|
|
621
|
+
/**
|
|
622
|
+
* Anthropic message threads left for sessions' next calls (opt-in, in memory,
|
|
623
|
+
* per process). Forgetting one here does not delete it on the server: the API
|
|
624
|
+
* has no delete, and the thread expires within an hour.
|
|
625
|
+
*/
|
|
626
|
+
anthropicThreadStore = new AnthropicThreadStore();
|
|
620
627
|
/** Extract sessionId from options context for compaction watermark keying */
|
|
621
628
|
getCompactionSessionId(options) {
|
|
622
629
|
return (options.context
|
|
@@ -3357,6 +3364,7 @@ Current user's request: ${currentInput}`;
|
|
|
3357
3364
|
async shutdown() {
|
|
3358
3365
|
try {
|
|
3359
3366
|
logger.debug("[NeuroLink] Starting graceful shutdown");
|
|
3367
|
+
this.anthropicThreadStore.forget();
|
|
3360
3368
|
// Kill host-owned background work first: a shutdown must not leave
|
|
3361
3369
|
// child processes or delegate workers running with nobody to collect
|
|
3362
3370
|
// them.
|
|
@@ -4893,6 +4901,7 @@ Current user's request: ${currentInput}`;
|
|
|
4893
4901
|
// generate() today. Declaring them is a public-type decision and is
|
|
4894
4902
|
// deliberately left out of this fix.
|
|
4895
4903
|
thinkingConfig: options.thinkingConfig,
|
|
4904
|
+
messageThreads: options.messageThreads,
|
|
4896
4905
|
onFinish: options.onFinish,
|
|
4897
4906
|
onError: options.onError,
|
|
4898
4907
|
};
|
|
@@ -12779,6 +12788,9 @@ Current user's request: ${currentInput}`;
|
|
|
12779
12788
|
* Clear conversation history for a specific session (public API)
|
|
12780
12789
|
*/
|
|
12781
12790
|
async clearConversationSession(sessionId) {
|
|
12791
|
+
// The Anthropic thread is local state and goes first, so it is forgotten
|
|
12792
|
+
// even when conversation memory is off and the rest of this throws.
|
|
12793
|
+
this.anthropicThreadStore.forget(sessionId);
|
|
12782
12794
|
// First ensure memory is initialized
|
|
12783
12795
|
const initId = `clear-session-init-${Date.now()}`;
|
|
12784
12796
|
await this.initializeConversationMemoryForGeneration(initId, Date.now(), process.hrtime.bigint());
|
|
@@ -12798,6 +12810,8 @@ Current user's request: ${currentInput}`;
|
|
|
12798
12810
|
* Clear all conversation history (public API)
|
|
12799
12811
|
*/
|
|
12800
12812
|
async clearAllConversations() {
|
|
12813
|
+
// Local state first, for the same reason as clearConversationSession.
|
|
12814
|
+
this.anthropicThreadStore.forget();
|
|
12801
12815
|
// First ensure memory is initialized
|
|
12802
12816
|
const initId = `clear-all-init-${Date.now()}`;
|
|
12803
12817
|
await this.initializeConversationMemoryForGeneration(initId, Date.now(), process.hrtime.bigint());
|
|
@@ -13229,6 +13243,11 @@ Current user's request: ${currentInput}`;
|
|
|
13229
13243
|
* @param userId - Optional user ID for scoped Redis key lookup
|
|
13230
13244
|
*/
|
|
13231
13245
|
async setSessionMessages(sessionId, messages, userId) {
|
|
13246
|
+
// The replaced history is not the one an Anthropic thread was built on
|
|
13247
|
+
// (rows may have been removed or redacted), so the thread goes. Forgotten
|
|
13248
|
+
// before the write, so even a call failing validation leaves none, and
|
|
13249
|
+
// again after it, so a call that started in between cannot keep one.
|
|
13250
|
+
this.anthropicThreadStore.forget(sessionId);
|
|
13232
13251
|
const initId = `set-msgs-init-${Date.now()}`;
|
|
13233
13252
|
await this.initializeConversationMemoryForGeneration(initId, Date.now(), process.hrtime.bigint());
|
|
13234
13253
|
if (!this.conversationMemory) {
|
|
@@ -13251,6 +13270,7 @@ Current user's request: ${currentInput}`;
|
|
|
13251
13270
|
});
|
|
13252
13271
|
}
|
|
13253
13272
|
await this.conversationMemory.setSessionMessages(sessionId, messages, userId);
|
|
13273
|
+
this.anthropicThreadStore.forget(sessionId);
|
|
13254
13274
|
}
|
|
13255
13275
|
/**
|
|
13256
13276
|
* Modify the last assistant message in a session using a transformer function.
|
|
@@ -15968,6 +15988,7 @@ Current user's request: ${currentInput}`;
|
|
|
15968
15988
|
logger.debug("[NeuroLink] Starting disposal of resources...");
|
|
15969
15989
|
// Clear per-session compaction watermarks
|
|
15970
15990
|
this.lastCompactionMessageCount.clear();
|
|
15991
|
+
this.anthropicThreadStore.forget();
|
|
15971
15992
|
const cleanupErrors = [];
|
|
15972
15993
|
try {
|
|
15973
15994
|
// 0. Kill host-owned background work: a disposed instance must not
|
|
@@ -107,7 +107,7 @@ export declare class AmazonSageMakerProvider extends BaseProvider {
|
|
|
107
107
|
provider: string;
|
|
108
108
|
specificationVersion: "v2";
|
|
109
109
|
endpointName: string;
|
|
110
|
-
modelType: "
|
|
110
|
+
modelType: "custom" | "huggingface" | "mistral" | "llama" | "claude" | "jumpstart" | undefined;
|
|
111
111
|
region: string;
|
|
112
112
|
} | {
|
|
113
113
|
capabilities: {
|
|
@@ -8,6 +8,8 @@ import type { LanguageModel } from "../../types/index.js";
|
|
|
8
8
|
*/
|
|
9
9
|
export declare class AnthropicProvider extends BaseProvider {
|
|
10
10
|
private client;
|
|
11
|
+
/** The API key this client was built with; only ever hashed, never logged or sent elsewhere. */
|
|
12
|
+
private apiKeyForThreads;
|
|
11
13
|
private readonly authMethod;
|
|
12
14
|
private readonly subscriptionTier;
|
|
13
15
|
private readonly enableBetaFeatures;
|
|
@@ -44,6 +46,13 @@ export declare class AnthropicProvider extends BaseProvider {
|
|
|
44
46
|
* the thread beta.
|
|
45
47
|
*/
|
|
46
48
|
private createMessageThreadSession;
|
|
49
|
+
/**
|
|
50
|
+
* Where this call's thread is kept for the session's next call, or undefined
|
|
51
|
+
* when it cannot be (no NeuroLink instance, or no session id). The owner is
|
|
52
|
+
* the user, the session, the credential and the endpoint: a thread belongs to
|
|
53
|
+
* the key that made it, and is not shared across any of them.
|
|
54
|
+
*/
|
|
55
|
+
private sessionThreadScope;
|
|
47
56
|
/**
|
|
48
57
|
* Get authentication headers based on current auth method and configuration.
|
|
49
58
|
*
|
|
@@ -23,7 +23,8 @@ import { redactUrlCredentials } from "../../utils/logSanitize.js";
|
|
|
23
23
|
import { ANTHROPIC_MAX_CACHE_BREAKPOINTS, applyAnthropicHistoryCacheBreakpoints, countAnthropicCacheMarkers, } from "../../utils/anthropicCacheBreakpoints.js";
|
|
24
24
|
import { stringifyAnthropicToolOutput } from "./toolOutput.js";
|
|
25
25
|
import { createAnthropicLoopAdapter } from "./loopAdapter.js";
|
|
26
|
-
import {
|
|
26
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
27
|
+
import { AnthropicThreadStore, createAnthropicThreadSession, settleThread, threadRecovery, } from "./threads.js";
|
|
27
28
|
import { DEFAULT_BEFORE_STEP_TIMEOUT_MS } from "../../utils/parameterValidation.js";
|
|
28
29
|
import { runAgenticLoop } from "../../core/loopEngine.js";
|
|
29
30
|
import { hasNativeDoGenerate, resolveStepToolChoice, runNativeGenerateLoop, toNativeToolDeclaration, toPrepareStepRecord, } from "../../core/nativeGenerateLoop.js";
|
|
@@ -490,12 +491,22 @@ const mapAnthropicStopReason = (raw) => {
|
|
|
490
491
|
// max_tokens (our model-ceiling default) works. Per-request duration is still
|
|
491
492
|
// bounded by the abort signal NeuroLink composes for each call.
|
|
492
493
|
const ANTHROPIC_CLIENT_TIMEOUT_MS = 600_000;
|
|
494
|
+
/**
|
|
495
|
+
* Send one non-streaming step of a thread. The SDK's request type does not know
|
|
496
|
+
* the beta `thread` field, so this is the one place it is added to the body,
|
|
497
|
+
* with the thread beta in the headers the plan carries.
|
|
498
|
+
*/
|
|
499
|
+
const createThreadedMessage = (client, plan, signal) => client.messages.create({ ...plan.params, stream: false }, { ...(signal ? { signal } : {}), headers: plan.headers });
|
|
500
|
+
/** The thread session of the generate() call in progress, for its doGenerate. */
|
|
501
|
+
const generateThreadScope = new AsyncLocalStorage();
|
|
493
502
|
/**
|
|
494
503
|
* Anthropic Provider v2 - BaseProvider Implementation
|
|
495
504
|
* Enhanced with OAuth support, subscription tiers, and beta headers for Claude Code integration.
|
|
496
505
|
*/
|
|
497
506
|
export class AnthropicProvider extends BaseProvider {
|
|
498
507
|
client;
|
|
508
|
+
/** The API key this client was built with; only ever hashed, never logged or sent elsewhere. */
|
|
509
|
+
apiKeyForThreads;
|
|
499
510
|
authMethod;
|
|
500
511
|
subscriptionTier;
|
|
501
512
|
enableBetaFeatures;
|
|
@@ -643,6 +654,7 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
643
654
|
else {
|
|
644
655
|
// Traditional API key authentication
|
|
645
656
|
const apiKeyToUse = credentials?.apiKey ?? config?.apiKey ?? getAnthropicApiKey();
|
|
657
|
+
this.apiKeyForThreads = apiKeyToUse;
|
|
646
658
|
client = new Anthropic({
|
|
647
659
|
apiKey: apiKeyToUse,
|
|
648
660
|
// SDK 1.x moved two defaults with its API version: it sends an apiKey
|
|
@@ -709,14 +721,74 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
709
721
|
* the thread beta.
|
|
710
722
|
*/
|
|
711
723
|
createMessageThreadSession(options) {
|
|
712
|
-
if (options.messageThreads !== true
|
|
724
|
+
if (options.messageThreads !== true &&
|
|
725
|
+
options.messageThreads !== "session") {
|
|
713
726
|
return undefined;
|
|
714
727
|
}
|
|
715
728
|
if (this.authMethod !== "api_key") {
|
|
716
729
|
logger.debug("[anthropic] messageThreads requested but not used: it needs API-key auth", { authMethod: this.authMethod });
|
|
717
730
|
return undefined;
|
|
718
731
|
}
|
|
719
|
-
|
|
732
|
+
const scope = options.messageThreads === "session"
|
|
733
|
+
? this.sessionThreadScope(options)
|
|
734
|
+
: undefined;
|
|
735
|
+
const session = createAnthropicThreadSession(this.getAuthHeaders()["anthropic-beta"], scope ? scope.store.take(scope.key) : undefined);
|
|
736
|
+
return {
|
|
737
|
+
session,
|
|
738
|
+
...(scope
|
|
739
|
+
? {
|
|
740
|
+
leave: (assistantText) => {
|
|
741
|
+
const carry = session.carry(assistantText);
|
|
742
|
+
if (carry) {
|
|
743
|
+
scope.store.put(scope.key, scope.sessionId, carry, scope.epoch);
|
|
744
|
+
}
|
|
745
|
+
},
|
|
746
|
+
}
|
|
747
|
+
: {}),
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Where this call's thread is kept for the session's next call, or undefined
|
|
752
|
+
* when it cannot be (no NeuroLink instance, or no session id). The owner is
|
|
753
|
+
* the user, the session, the credential and the endpoint: a thread belongs to
|
|
754
|
+
* the key that made it, and is not shared across any of them.
|
|
755
|
+
*/
|
|
756
|
+
sessionThreadScope(options) {
|
|
757
|
+
const store = this.neurolink?.anthropicThreadStore;
|
|
758
|
+
const context = options.context;
|
|
759
|
+
const rawSession = context?.sessionId;
|
|
760
|
+
const sessionId = typeof rawSession === "string" && rawSession.length > 0
|
|
761
|
+
? rawSession
|
|
762
|
+
: typeof rawSession === "number"
|
|
763
|
+
? String(rawSession)
|
|
764
|
+
: undefined;
|
|
765
|
+
if (store === undefined || sessionId === undefined) {
|
|
766
|
+
return undefined;
|
|
767
|
+
}
|
|
768
|
+
// A thread is private to a user. An id of a kind that cannot be told apart
|
|
769
|
+
// from another's (anything but a string or a number) means the call cannot
|
|
770
|
+
// be attributed, so it does not share a thread rather than falling into the
|
|
771
|
+
// anonymous scope.
|
|
772
|
+
const rawUser = context?.userId;
|
|
773
|
+
if (rawUser !== undefined &&
|
|
774
|
+
rawUser !== null &&
|
|
775
|
+
typeof rawUser !== "string" &&
|
|
776
|
+
typeof rawUser !== "number") {
|
|
777
|
+
return undefined;
|
|
778
|
+
}
|
|
779
|
+
const userId = rawUser === undefined || rawUser === null ? undefined : String(rawUser);
|
|
780
|
+
const credential = this.apiKeyForThreads ?? getAnthropicApiKey() ?? "";
|
|
781
|
+
return {
|
|
782
|
+
store,
|
|
783
|
+
sessionId,
|
|
784
|
+
epoch: store.epochOf(sessionId),
|
|
785
|
+
key: AnthropicThreadStore.keyOf({
|
|
786
|
+
...(userId !== undefined ? { userId } : {}),
|
|
787
|
+
sessionId,
|
|
788
|
+
credential,
|
|
789
|
+
...(this.baseURL !== undefined ? { baseURL: this.baseURL } : {}),
|
|
790
|
+
}),
|
|
791
|
+
};
|
|
720
792
|
}
|
|
721
793
|
/**
|
|
722
794
|
* Get authentication headers based on current auth method and configuration.
|
|
@@ -1290,9 +1362,46 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1290
1362
|
const requestSignal = composeAbortSignals(options.abortSignal, timeoutController?.controller.signal);
|
|
1291
1363
|
let response;
|
|
1292
1364
|
try {
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1365
|
+
const threads = generateThreadScope.getStore();
|
|
1366
|
+
if (threads?.enabled) {
|
|
1367
|
+
// A thread step goes out as a create or a continue. When the API
|
|
1368
|
+
// cannot continue it, or cannot thread the request at all, the
|
|
1369
|
+
// same step is sent once more in full; any other failure ends the
|
|
1370
|
+
// thread so the next step starts a new one (as in the stream loop).
|
|
1371
|
+
let plan = threads.plan(params);
|
|
1372
|
+
for (let attempt = 0;; attempt++) {
|
|
1373
|
+
try {
|
|
1374
|
+
response = await createThreadedMessage(client, plan, requestSignal);
|
|
1375
|
+
settleThread(threads, {
|
|
1376
|
+
sawTerminalEvent: true,
|
|
1377
|
+
messageId: response.id,
|
|
1378
|
+
stopReason: response.stop_reason ?? undefined,
|
|
1379
|
+
});
|
|
1380
|
+
break;
|
|
1381
|
+
}
|
|
1382
|
+
catch (threadError) {
|
|
1383
|
+
threads.reset();
|
|
1384
|
+
const recovery = attempt === 0 ? threadRecovery(threadError) : undefined;
|
|
1385
|
+
if (recovery === "recreate") {
|
|
1386
|
+
plan = threads.plan(params);
|
|
1387
|
+
continue;
|
|
1388
|
+
}
|
|
1389
|
+
if (recovery === "unthreaded") {
|
|
1390
|
+
threads.disable();
|
|
1391
|
+
response = await client.messages.create(params, {
|
|
1392
|
+
signal: requestSignal,
|
|
1393
|
+
});
|
|
1394
|
+
break;
|
|
1395
|
+
}
|
|
1396
|
+
throw threadError;
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
else {
|
|
1401
|
+
response = await client.messages.create(params, {
|
|
1402
|
+
signal: requestSignal,
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1296
1405
|
}
|
|
1297
1406
|
catch (error) {
|
|
1298
1407
|
// The Anthropic SDK collapses ANY fired signal into its generic
|
|
@@ -1534,7 +1643,9 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1534
1643
|
await this.ensureModelLimits();
|
|
1535
1644
|
const options = this.normalizeTextOptions(optionsOrPrompt);
|
|
1536
1645
|
if (resolveRequestKind(options, this.modelName) !== "text") {
|
|
1537
|
-
|
|
1646
|
+
// Run outside any thread scope: a nested non-text call must not read, or
|
|
1647
|
+
// write into, the session of a text call that happens to be active.
|
|
1648
|
+
return generateThreadScope.run(undefined, () => super.generate(options, analysisSchema));
|
|
1538
1649
|
}
|
|
1539
1650
|
this.validateOptions(options);
|
|
1540
1651
|
const mergedTools = await this.getToolsForStream(options);
|
|
@@ -1606,7 +1717,12 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1606
1717
|
: undefined;
|
|
1607
1718
|
const conversation = (await this.buildMessagesForStream(options));
|
|
1608
1719
|
const toolExecutionSummaries = [];
|
|
1609
|
-
|
|
1720
|
+
// Message threads (opt-in): the session is per call, carried to the model
|
|
1721
|
+
// handle's doGenerate through an async scope because the handle itself is
|
|
1722
|
+
// shared. A structured turn leaves no thread for the next call: its reply
|
|
1723
|
+
// is a tool payload, not the text memory will hold.
|
|
1724
|
+
const threadState = this.createMessageThreadSession(options);
|
|
1725
|
+
const loop = await generateThreadScope.run(threadState?.session, () => runNativeGenerateLoop({
|
|
1610
1726
|
doGenerate,
|
|
1611
1727
|
provider: this.providerName,
|
|
1612
1728
|
...createNativeGenerateGuard({
|
|
@@ -1654,7 +1770,10 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
1654
1770
|
throw this.handleProviderError(err);
|
|
1655
1771
|
}),
|
|
1656
1772
|
onRejectedToolCall: (name, error, id) => this.emitRejectedToolCall(name, error, id),
|
|
1657
|
-
}, toolExecutionSummaries);
|
|
1773
|
+
}, toolExecutionSummaries));
|
|
1774
|
+
if (!options.schema) {
|
|
1775
|
+
threadState?.leave?.(loop.text);
|
|
1776
|
+
}
|
|
1658
1777
|
const enhanced = {
|
|
1659
1778
|
content: loop.text,
|
|
1660
1779
|
provider: this.providerName,
|
|
@@ -2047,7 +2166,11 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
2047
2166
|
...(thinking ? { thinking } : {}),
|
|
2048
2167
|
};
|
|
2049
2168
|
};
|
|
2050
|
-
const
|
|
2169
|
+
const threadState = this.createMessageThreadSession(options);
|
|
2170
|
+
const messageThreads = threadState?.session;
|
|
2171
|
+
// Text streamed to the consumer across the whole turn: what conversation
|
|
2172
|
+
// memory will keep as this turn's reply.
|
|
2173
|
+
let streamedText = "";
|
|
2051
2174
|
const baseAdapter = createAnthropicLoopAdapter({
|
|
2052
2175
|
client,
|
|
2053
2176
|
provider: this.providerName,
|
|
@@ -2262,6 +2385,7 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
2262
2385
|
bufferedText += chunk.content;
|
|
2263
2386
|
}
|
|
2264
2387
|
else {
|
|
2388
|
+
streamedText += chunk.content;
|
|
2265
2389
|
pushChunk({ content: chunk.content });
|
|
2266
2390
|
}
|
|
2267
2391
|
}
|
|
@@ -2335,6 +2459,11 @@ export class AnthropicProvider extends BaseProvider {
|
|
|
2335
2459
|
finalResultText === undefined) {
|
|
2336
2460
|
turnMetadata.stopReason = "step-cap";
|
|
2337
2461
|
}
|
|
2462
|
+
// Leave the thread for the session's next call. Not for a structured
|
|
2463
|
+
// turn: its reply is the final_result payload, not the text above.
|
|
2464
|
+
if (!finalResultActive) {
|
|
2465
|
+
threadState?.leave?.(streamedText);
|
|
2466
|
+
}
|
|
2338
2467
|
resolveUsage(buildDeferredUsage());
|
|
2339
2468
|
resolveFinish(lastStop ?? "stop");
|
|
2340
2469
|
};
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* rewrites history, such as a context reclaim, therefore starts a new thread
|
|
16
16
|
* by itself.
|
|
17
17
|
*/
|
|
18
|
-
import type { AnthropicThreadSession } from "../../types/index.js";
|
|
18
|
+
import type { AnthropicThreadCarry, AnthropicThreadSession } from "../../types/index.js";
|
|
19
19
|
export declare const MESSAGE_THREADS_BETA = "message-threads-2026-08-12";
|
|
20
20
|
/**
|
|
21
21
|
* Record how a step's response ended. The API stores a thread turn only when
|
|
@@ -33,7 +33,7 @@ export declare function settleThread(session: AnthropicThreadSession, response:
|
|
|
33
33
|
* @param betaHeader the `anthropic-beta` value the client already sends; the
|
|
34
34
|
* thread beta is added to it, identically on every request of the thread.
|
|
35
35
|
*/
|
|
36
|
-
export declare function createAnthropicThreadSession(betaHeader: string | undefined): AnthropicThreadSession;
|
|
36
|
+
export declare function createAnthropicThreadSession(betaHeader: string | undefined, carried?: AnthropicThreadCarry): AnthropicThreadSession;
|
|
37
37
|
/** The API's `error.details.error_code` for a thread request that was refused, if there is one. */
|
|
38
38
|
export declare function threadErrorCode(error: unknown): string | undefined;
|
|
39
39
|
/**
|
|
@@ -41,3 +41,40 @@ export declare function threadErrorCode(error: unknown): string | undefined;
|
|
|
41
41
|
* thread, send it without a thread at all, or neither (an ordinary error).
|
|
42
42
|
*/
|
|
43
43
|
export declare function threadRecovery(error: unknown): "recreate" | "unthreaded" | undefined;
|
|
44
|
+
/**
|
|
45
|
+
* The threads a NeuroLink instance has left behind for its sessions' next
|
|
46
|
+
* calls. In memory and per process only: another process simply creates a new
|
|
47
|
+
* thread, which is always correct. An entry is taken out by the call that
|
|
48
|
+
* continues it, because a response id can be continued once, so two concurrent
|
|
49
|
+
* calls of one session cannot both continue the same thread.
|
|
50
|
+
*/
|
|
51
|
+
export declare class AnthropicThreadStore {
|
|
52
|
+
private readonly entries;
|
|
53
|
+
private globalEpoch;
|
|
54
|
+
private readonly sessionEpochs;
|
|
55
|
+
private sweepTimer;
|
|
56
|
+
/**
|
|
57
|
+
* The identity of a thread's owner: who asked, in which session, with which
|
|
58
|
+
* credential and endpoint. A thread belongs to the key that created it, so
|
|
59
|
+
* the credential is part of the key (hashed; the key itself is never kept).
|
|
60
|
+
*/
|
|
61
|
+
static keyOf(parts: {
|
|
62
|
+
userId?: string;
|
|
63
|
+
sessionId: string;
|
|
64
|
+
credential: string;
|
|
65
|
+
baseURL?: string;
|
|
66
|
+
}): string;
|
|
67
|
+
take(key: string, now?: number): AnthropicThreadCarry | undefined;
|
|
68
|
+
/** The epoch a call must hand back to `put` for its thread to be kept. */
|
|
69
|
+
epochOf(sessionId: string): string;
|
|
70
|
+
put(key: string, sessionId: string, carry: AnthropicThreadCarry, epoch: string, now?: number): void;
|
|
71
|
+
/** Drop every entry that has expired. */
|
|
72
|
+
sweep(now?: number): void;
|
|
73
|
+
private armSweep;
|
|
74
|
+
/**
|
|
75
|
+
* Forget a session's thread, or every thread when no session is named, and
|
|
76
|
+
* fence any call still running from leaving one afterwards.
|
|
77
|
+
*/
|
|
78
|
+
forget(sessionId?: string): void;
|
|
79
|
+
get size(): number;
|
|
80
|
+
}
|