@juspay/neurolink 13.10.5 → 13.12.0

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.
@@ -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>;
@@ -369,6 +369,219 @@ function declaredInputSchema(name, tool) {
369
369
  return empty;
370
370
  }
371
371
  }
372
+ /**
373
+ * A copy of `input` where each value Zod rejected as "expected date" and that
374
+ * is an ISO-8601 date or date-time string has become a `Date`; undefined when
375
+ * there is nothing to convert. The input itself is never mutated.
376
+ */
377
+ const ISO_DATE_STRING = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})?)?$/;
378
+ /** The Date for an ISO-8601 date or date-time string; undefined for anything else, including 2026-02-31. */
379
+ const parseIsoDate = (value) => {
380
+ if (typeof value !== "string") {
381
+ return undefined;
382
+ }
383
+ const match = ISO_DATE_STRING.exec(value);
384
+ if (match === null) {
385
+ return undefined;
386
+ }
387
+ // Date.parse rolls an impossible day over (2026-02-31 becomes March 3), which
388
+ // would hand the tool a date the model never named. Check the calendar day.
389
+ const [, year, month, day] = match;
390
+ // setUTCFullYear, not Date.UTC: Date.UTC reads years 0-99 as 1900-1999.
391
+ const probe = new Date(0);
392
+ probe.setUTCFullYear(Number(year), Number(month) - 1, Number(day));
393
+ if (probe.getUTCFullYear() !== Number(year) ||
394
+ probe.getUTCMonth() !== Number(month) - 1 ||
395
+ probe.getUTCDate() !== Number(day)) {
396
+ return undefined;
397
+ }
398
+ const time = Date.parse(value);
399
+ return Number.isNaN(time) ? undefined : new Date(time);
400
+ };
401
+ /**
402
+ * The ways to read a failed validation as "these strings were meant as dates".
403
+ * Each candidate is a set of positions to convert together. Positions outside
404
+ * any union are in every candidate; a union contributes one alternative per
405
+ * branch, so a branch that wants a date in one field is tried without the dates
406
+ * the other branches wanted elsewhere.
407
+ *
408
+ * A union failure is one issue with each branch's issues nested. Zod 4 puts
409
+ * them in `errors` with paths relative to the union's; Zod 3 puts them in
410
+ * `unionErrors[].issues` with absolute paths.
411
+ */
412
+ const valueAt = (input, path) => {
413
+ let cursor = input;
414
+ for (const key of path) {
415
+ cursor = cursor?.[key];
416
+ }
417
+ return cursor;
418
+ };
419
+ const dateCandidates = (issues, base, input) => {
420
+ let candidates = [[]];
421
+ if (!Array.isArray(issues)) {
422
+ return candidates;
423
+ }
424
+ for (const issue of issues) {
425
+ if (!Array.isArray(issue.path)) {
426
+ continue;
427
+ }
428
+ const path = [...base, ...issue.path];
429
+ let alternatives;
430
+ if (issue.code === "invalid_type" && issue.expected === "date") {
431
+ // A position that holds nothing convertible is left to fail as it did.
432
+ const value = valueAt(input, path);
433
+ if (Array.isArray(value)) {
434
+ // A set reached through a preprocess is reported at the field with the
435
+ // array as its value: convert its date strings member by member. The
436
+ // reading that converts every one is tried first; then, for up to
437
+ // eight members, one that leaves a member as the string it was, since
438
+ // the schema may accept a literal that merely looks like a date.
439
+ const members = value
440
+ .map((v, i) => (parseIsoDate(v) !== undefined ? i : -1))
441
+ .filter((i) => i >= 0);
442
+ if (members.length > 0) {
443
+ // The reading that converts every member comes first. Then, over the
444
+ // first six members, every smaller subset (largest first), so any
445
+ // number of date-shaped literals can be left as the strings they
446
+ // were: the schema may accept a literal that merely looks like a date.
447
+ const head = members.slice(0, 6);
448
+ const subsets = [];
449
+ for (let mask = (1 << head.length) - 2; mask > 0; mask--) {
450
+ subsets.push(head.filter((_, bit) => (mask >> bit) & 1));
451
+ }
452
+ subsets.sort((x, y) => y.length - x.length);
453
+ alternatives = [
454
+ members.map((i) => [...path, i]),
455
+ ...subsets.map((subset) => [...subset, ...members.slice(6)].map((i) => [...path, i])),
456
+ ];
457
+ }
458
+ }
459
+ else if (parseIsoDate(value) !== undefined) {
460
+ alternatives = [[path]];
461
+ }
462
+ }
463
+ else if (issue.code === "invalid_union") {
464
+ const branches = [];
465
+ if (Array.isArray(issue.errors)) {
466
+ for (const branch of issue.errors) {
467
+ branches.push(dateCandidates(branch, path, input));
468
+ }
469
+ }
470
+ if (Array.isArray(issue.unionErrors)) {
471
+ for (const e of issue.unionErrors) {
472
+ branches.push(dateCandidates(e?.issues, [], input));
473
+ }
474
+ }
475
+ // Alternatives are the branches' own candidates, those that convert
476
+ // something; a union with none contributes nothing.
477
+ const useful = branches
478
+ .flat()
479
+ .filter((candidate) => candidate.length > 0);
480
+ if (useful.length > 0) {
481
+ alternatives = useful;
482
+ }
483
+ }
484
+ if (alternatives !== undefined) {
485
+ const next = [];
486
+ for (const have of candidates) {
487
+ for (const add of alternatives) {
488
+ next.push([...have, ...add]);
489
+ }
490
+ }
491
+ // Bounded: a schema with many unions must not multiply without limit.
492
+ // Only alternatives that can apply to this input got here, so the cap
493
+ // never drops the one conversion that would have worked.
494
+ candidates = next.slice(0, 512);
495
+ }
496
+ }
497
+ return candidates;
498
+ };
499
+ /**
500
+ * A copy of `input` with the string at each position converted, or undefined
501
+ * if any position holds something that is not a date string. Only the
502
+ * containers on the way to a converted value are copied: everything else is
503
+ * shared with `input`, so a class instance elsewhere in it keeps its prototype
504
+ * and nothing uncloneable is ever cloned.
505
+ */
506
+ const applyDateConversions = (input, positions) => {
507
+ const rewrite = (node, rest) => {
508
+ // Positions that end here are converted; the others descend by their key.
509
+ const here = rest.find((path) => path.length === 0);
510
+ if (here !== undefined) {
511
+ return parseIsoDate(node);
512
+ }
513
+ if (node === null || typeof node !== "object") {
514
+ return undefined;
515
+ }
516
+ const byKey = new Map();
517
+ for (const path of rest) {
518
+ const [key, ...tail] = path;
519
+ byKey.set(key, [...(byKey.get(key) ?? []), tail]);
520
+ }
521
+ const replacements = new Map();
522
+ for (const [key, tails] of byKey) {
523
+ const replaced = rewrite(node[key], tails);
524
+ if (replaced === undefined) {
525
+ return undefined;
526
+ }
527
+ replacements.set(key, replaced);
528
+ }
529
+ if (Array.isArray(node)) {
530
+ const copy = Array.prototype.slice.call(node);
531
+ for (const [key, value] of replacements) {
532
+ copy[key] = value;
533
+ }
534
+ return copy;
535
+ }
536
+ // Own property descriptors, not Object.assign: assigning would run every
537
+ // getter on the object, including ones outside the schema that throw. The
538
+ // converted properties are written into the descriptors before anything is
539
+ // defined, so a frozen or non-writable original is never redefined.
540
+ const descriptors = Object.getOwnPropertyDescriptors(node);
541
+ for (const [key, value] of replacements) {
542
+ descriptors[key] = {
543
+ value,
544
+ writable: true,
545
+ enumerable: true,
546
+ configurable: true,
547
+ };
548
+ }
549
+ const proto = Object.getPrototypeOf(node);
550
+ if (proto !== Object.prototype && proto !== null) {
551
+ // A class instance may keep state in private fields, which a copy made
552
+ // with Object.create would not have. A proxy keeps the original as the
553
+ // receiver for everything except the converted properties.
554
+ return new Proxy(node, {
555
+ get: (target, key) => {
556
+ if (replacements.has(key)) {
557
+ return replacements.get(key);
558
+ }
559
+ const value = Reflect.get(target, key, target);
560
+ return typeof value === "function" ? value.bind(target) : value;
561
+ },
562
+ has: (target, key) => replacements.has(key) || Reflect.has(target, key),
563
+ });
564
+ }
565
+ return Object.defineProperties(Object.create(Object.getPrototypeOf(node)), descriptors);
566
+ };
567
+ return positions.length === 0 ? undefined : rewrite(input, positions);
568
+ };
569
+ /**
570
+ * The inputs worth validating again after a failure: for each way of reading
571
+ * the issues as dates, the input with those strings converted. Empty when no
572
+ * reading applies.
573
+ */
574
+ const reviveDateStrings = (input, error) => {
575
+ const issues = error?.issues;
576
+ const out = [];
577
+ for (const positions of dateCandidates(issues, [], input)) {
578
+ const revived = applyDateConversions(input, positions);
579
+ if (revived !== undefined) {
580
+ out.push(revived);
581
+ }
582
+ }
583
+ return out;
584
+ };
372
585
  /**
373
586
  * Validate parsed input against the tool's own schema when it exposes one.
374
587
  *
@@ -390,9 +603,34 @@ export const validateToolInput = async (tool, input) => {
390
603
  typeof schema.safeParse !== "function") {
391
604
  return { input };
392
605
  }
393
- const result = "safeParseAsync" in schema && typeof schema.safeParseAsync === "function"
394
- ? await schema.safeParseAsync(input)
395
- : schema.safeParse(input);
606
+ const parse = async (value) => "safeParseAsync" in schema && typeof schema.safeParseAsync === "function"
607
+ ? await schema.safeParseAsync(value)
608
+ : schema.safeParse(value);
609
+ let result = await parse(input);
610
+ if (!result.success) {
611
+ // The wire schema describes z.date() as a date-time string (JSON has no
612
+ // Date), so a model sends a string and a plain z.date() rejects it. Turn
613
+ // exactly the strings Zod named as "expected date" into Dates and
614
+ // validate again; every other mismatch is left to fail as before.
615
+ // Each reading of the failure is tried; the first that validates wins.
616
+ // When none does, the last retry's error is reported, so a date that
617
+ // parses but breaks `.min()` says so rather than repeating "expected
618
+ // date" and inviting the same value again.
619
+ for (const revived of reviveDateStrings(input, result.error)) {
620
+ try {
621
+ const retry = await parse(revived);
622
+ result = retry;
623
+ if (retry.success) {
624
+ break;
625
+ }
626
+ }
627
+ catch {
628
+ // A branch that cannot take this reading (a refinement that throws
629
+ // on a Date) must not stop the readings that follow it.
630
+ continue;
631
+ }
632
+ }
633
+ }
396
634
  if (result.success) {
397
635
  return { input: result.data };
398
636
  }
@@ -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
@@ -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;
@@ -36,6 +38,21 @@ export declare class AnthropicProvider extends BaseProvider {
36
38
  oauthToken?: string;
37
39
  baseURL?: string;
38
40
  });
41
+ /**
42
+ * The thread state for this turn, or undefined when message threads (beta)
43
+ * were not asked for. Opt-in per call (`StreamOptions.messageThreads`) and
44
+ * limited to API-key auth, because the subscription (OAuth) path rewrites
45
+ * beta headers in its own fetch wrapper, which has not been checked against
46
+ * the thread beta.
47
+ */
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;
39
56
  /**
40
57
  * Get authentication headers based on current auth method and configuration.
41
58
  *
@@ -23,6 +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 { AsyncLocalStorage } from "node:async_hooks";
27
+ import { AnthropicThreadStore, createAnthropicThreadSession, settleThread, threadRecovery, } from "./threads.js";
26
28
  import { DEFAULT_BEFORE_STEP_TIMEOUT_MS } from "../../utils/parameterValidation.js";
27
29
  import { runAgenticLoop } from "../../core/loopEngine.js";
28
30
  import { hasNativeDoGenerate, resolveStepToolChoice, runNativeGenerateLoop, toNativeToolDeclaration, toPrepareStepRecord, } from "../../core/nativeGenerateLoop.js";
@@ -489,12 +491,22 @@ const mapAnthropicStopReason = (raw) => {
489
491
  // max_tokens (our model-ceiling default) works. Per-request duration is still
490
492
  // bounded by the abort signal NeuroLink composes for each call.
491
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();
492
502
  /**
493
503
  * Anthropic Provider v2 - BaseProvider Implementation
494
504
  * Enhanced with OAuth support, subscription tiers, and beta headers for Claude Code integration.
495
505
  */
496
506
  export class AnthropicProvider extends BaseProvider {
497
507
  client;
508
+ /** The API key this client was built with; only ever hashed, never logged or sent elsewhere. */
509
+ apiKeyForThreads;
498
510
  authMethod;
499
511
  subscriptionTier;
500
512
  enableBetaFeatures;
@@ -642,6 +654,7 @@ export class AnthropicProvider extends BaseProvider {
642
654
  else {
643
655
  // Traditional API key authentication
644
656
  const apiKeyToUse = credentials?.apiKey ?? config?.apiKey ?? getAnthropicApiKey();
657
+ this.apiKeyForThreads = apiKeyToUse;
645
658
  client = new Anthropic({
646
659
  apiKey: apiKeyToUse,
647
660
  // SDK 1.x moved two defaults with its API version: it sends an apiKey
@@ -700,6 +713,83 @@ export class AnthropicProvider extends BaseProvider {
700
713
  : "disabled",
701
714
  });
702
715
  }
716
+ /**
717
+ * The thread state for this turn, or undefined when message threads (beta)
718
+ * were not asked for. Opt-in per call (`StreamOptions.messageThreads`) and
719
+ * limited to API-key auth, because the subscription (OAuth) path rewrites
720
+ * beta headers in its own fetch wrapper, which has not been checked against
721
+ * the thread beta.
722
+ */
723
+ createMessageThreadSession(options) {
724
+ if (options.messageThreads !== true &&
725
+ options.messageThreads !== "session") {
726
+ return undefined;
727
+ }
728
+ if (this.authMethod !== "api_key") {
729
+ logger.debug("[anthropic] messageThreads requested but not used: it needs API-key auth", { authMethod: this.authMethod });
730
+ return undefined;
731
+ }
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
+ };
792
+ }
703
793
  /**
704
794
  * Get authentication headers based on current auth method and configuration.
705
795
  *
@@ -1272,9 +1362,46 @@ export class AnthropicProvider extends BaseProvider {
1272
1362
  const requestSignal = composeAbortSignals(options.abortSignal, timeoutController?.controller.signal);
1273
1363
  let response;
1274
1364
  try {
1275
- response = await client.messages.create(params, {
1276
- signal: requestSignal,
1277
- });
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
+ }
1278
1405
  }
1279
1406
  catch (error) {
1280
1407
  // The Anthropic SDK collapses ANY fired signal into its generic
@@ -1516,7 +1643,9 @@ export class AnthropicProvider extends BaseProvider {
1516
1643
  await this.ensureModelLimits();
1517
1644
  const options = this.normalizeTextOptions(optionsOrPrompt);
1518
1645
  if (resolveRequestKind(options, this.modelName) !== "text") {
1519
- return super.generate(options, analysisSchema);
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));
1520
1649
  }
1521
1650
  this.validateOptions(options);
1522
1651
  const mergedTools = await this.getToolsForStream(options);
@@ -1588,7 +1717,12 @@ export class AnthropicProvider extends BaseProvider {
1588
1717
  : undefined;
1589
1718
  const conversation = (await this.buildMessagesForStream(options));
1590
1719
  const toolExecutionSummaries = [];
1591
- const loop = await runNativeGenerateLoop({
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({
1592
1726
  doGenerate,
1593
1727
  provider: this.providerName,
1594
1728
  ...createNativeGenerateGuard({
@@ -1636,7 +1770,10 @@ export class AnthropicProvider extends BaseProvider {
1636
1770
  throw this.handleProviderError(err);
1637
1771
  }),
1638
1772
  onRejectedToolCall: (name, error, id) => this.emitRejectedToolCall(name, error, id),
1639
- }, toolExecutionSummaries);
1773
+ }, toolExecutionSummaries));
1774
+ if (!options.schema) {
1775
+ threadState?.leave?.(loop.text);
1776
+ }
1640
1777
  const enhanced = {
1641
1778
  content: loop.text,
1642
1779
  provider: this.providerName,
@@ -2029,10 +2166,16 @@ export class AnthropicProvider extends BaseProvider {
2029
2166
  ...(thinking ? { thinking } : {}),
2030
2167
  };
2031
2168
  };
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 = "";
2032
2174
  const baseAdapter = createAnthropicLoopAdapter({
2033
2175
  client,
2034
2176
  provider: this.providerName,
2035
2177
  maxSteps,
2178
+ ...(messageThreads ? { threads: messageThreads } : {}),
2036
2179
  toolsRecord,
2037
2180
  buildParams,
2038
2181
  planReclaim,
@@ -2242,6 +2385,7 @@ export class AnthropicProvider extends BaseProvider {
2242
2385
  bufferedText += chunk.content;
2243
2386
  }
2244
2387
  else {
2388
+ streamedText += chunk.content;
2245
2389
  pushChunk({ content: chunk.content });
2246
2390
  }
2247
2391
  }
@@ -2315,6 +2459,11 @@ export class AnthropicProvider extends BaseProvider {
2315
2459
  finalResultText === undefined) {
2316
2460
  turnMetadata.stopReason = "step-cap";
2317
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
+ }
2318
2467
  resolveUsage(buildDeferredUsage());
2319
2468
  resolveFinish(lastStop ?? "stop");
2320
2469
  };