@juspay/neurolink 13.13.1 → 13.13.3

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.
@@ -835,7 +835,7 @@ export declare abstract class BaseProvider implements AIProvider {
835
835
  /**
836
836
  * Get timeout value in milliseconds - delegated to Utilities
837
837
  */
838
- getTimeout(options: TextGenerationOptions | StreamOptions): number;
838
+ getTimeout(options: TextGenerationOptions | StreamOptions, operation?: "generate" | "stream"): number;
839
839
  /**
840
840
  * Check if tool executions should be stored and handle storage
841
841
  */
@@ -3282,8 +3282,8 @@ export class BaseProvider {
3282
3282
  /**
3283
3283
  * Get timeout value in milliseconds - delegated to Utilities
3284
3284
  */
3285
- getTimeout(options) {
3286
- return this.utilities.getTimeout(options);
3285
+ getTimeout(options, operation = "generate") {
3286
+ return this.utilities.getTimeout(options, operation);
3287
3287
  }
3288
3288
  /**
3289
3289
  * Check if tool executions should be stored and handle storage
@@ -53,7 +53,7 @@ export declare class Utilities {
53
53
  * Get timeout value in milliseconds from options
54
54
  * Supports number or string formats (e.g., '30s', '2m', '1h')
55
55
  */
56
- getTimeout(options: TextGenerationOptions | StreamOptions): number;
56
+ getTimeout(options: TextGenerationOptions | StreamOptions, operation?: "generate" | "stream"): number;
57
57
  /**
58
58
  * Get timeout scaled by estimated input token count.
59
59
  * For large contexts (>100K tokens), increase timeout proportionally.
@@ -157,7 +157,7 @@ export class Utilities {
157
157
  * Get timeout value in milliseconds from options
158
158
  * Supports number or string formats (e.g., '30s', '2m', '1h')
159
159
  */
160
- getTimeout(options) {
160
+ getTimeout(options, operation = "generate") {
161
161
  // If caller specified a timeout, use it (supports number ms and string formats)
162
162
  if (options.timeout !== undefined && options.timeout !== null) {
163
163
  const parsed = parseTimeout(options.timeout);
@@ -165,13 +165,9 @@ export class Utilities {
165
165
  return parsed;
166
166
  }
167
167
  }
168
- // Use per-provider default (e.g., vertex=60s, ollama=5m) instead of global 30s.
169
- // Always use "generate" operation here — streaming operations have their own
170
- // longer timeout (DEFAULT_TIMEOUTS.streaming = 2m) applied by the streaming
171
- // infrastructure in BaseProvider.stream(). Both TextGenerationOptions and
172
- // StreamOptions share the same `input` property, so there is no reliable
173
- // discriminator to detect streaming at this level.
174
- const providerDefault = parseTimeout(getDefaultTimeout(this.providerName, "generate"));
168
+ // The caller knows the operation; the two option types share the same
169
+ // shape and cannot be distinguished from their values here.
170
+ const providerDefault = parseTimeout(getDefaultTimeout(this.providerName, operation));
175
171
  return providerDefault ?? this.defaultTimeout;
176
172
  }
177
173
  /**
package/dist/neurolink.js CHANGED
@@ -444,6 +444,23 @@ function startTurn(span, optionsOrPrompt) {
444
444
  });
445
445
  }
446
446
  }
447
+ // A decision provider's failure message can carry the vendor's error body,
448
+ // which is text the vendor controls. Telemetry records the error class, kind
449
+ // and HTTP status instead; the caller still gets the full message.
450
+ function decisionFailureSummary(error) {
451
+ const cause = error instanceof Error ? error.cause : undefined;
452
+ if (!(error instanceof Error) ||
453
+ typeof cause !== "object" ||
454
+ cause === null ||
455
+ !("kind" in cause) ||
456
+ typeof cause.kind !== "string") {
457
+ return undefined;
458
+ }
459
+ const status = "status" in cause && typeof cause.status === "number"
460
+ ? ` (HTTP ${cause.status})`
461
+ : "";
462
+ return `${error.name}: ${cause.kind}${status}`;
463
+ }
447
464
  function failTurnSpan(span, error) {
448
465
  const message = error.message;
449
466
  if (isAbortError(error)) {
@@ -14986,6 +15003,7 @@ Current user's request: ${currentInput}`;
14986
15003
  name: "decide",
14987
15004
  tracer: tracers.decision,
14988
15005
  expectedFailure: () => !providerName,
15006
+ failureSummary: decisionFailureSummary,
14989
15007
  attributes: {
14990
15008
  "gen_ai.system": providerName,
14991
15009
  "gen_ai.operation.name": "decide",
@@ -15108,7 +15126,8 @@ Current user's request: ${currentInput}`;
15108
15126
  }
15109
15127
  catch (error) {
15110
15128
  span.durationMs = Date.now() - startedAt;
15111
- const ended = SpanSerializer.endSpan(span, SpanStatus.ERROR, error instanceof Error ? error.message : String(error));
15129
+ const ended = SpanSerializer.endSpan(span, SpanStatus.ERROR, decisionFailureSummary(error) ??
15130
+ (error instanceof Error ? error.message : String(error)));
15112
15131
  this.metricsAggregator.recordSpan(ended);
15113
15132
  getMetricsAggregator().recordSpan(ended);
15114
15133
  throw error;
@@ -33,7 +33,7 @@ import { resolveRequestKind } from "../../core/resolveRequestKind.js";
33
33
  import { resolveToolExecutionRecords, toolCallsFromSummaries, } from "../../core/toolExecutionRecorder.js";
34
34
  import { transformToolExecutions } from "../../utils/transformationUtils.js";
35
35
  import { createAnthropicConfig, getProviderModel, validateApiKey, } from "../../utils/providerConfig.js";
36
- import { composeAbortSignals, composeAbortSignalsScoped, createTimeoutController, mergeAbortSignals, TimeoutError, } from "../../utils/timeout.js";
36
+ import { composeAbortSignals, composeAbortSignalsScoped, createTimeoutController, mergeAbortSignals, monitorStreamActivity, TimeoutError, } from "../../utils/timeout.js";
37
37
  import { pauseDeadlineOf, raceWithAbort } from "../../utils/async/index.js";
38
38
  import { normalizeResolvedToolChoice, resolveToolChoice, } from "../../utils/toolChoice.js";
39
39
  import { NoOutputGeneratedError } from "../../utils/generationErrors.js";
@@ -1931,12 +1931,9 @@ export class AnthropicProvider extends BaseProvider {
1931
1931
  // is known good: requestTimeoutMs finite positive, lifetimeTimeoutMs null
1932
1932
  // or finite positive or absent.
1933
1933
  const control = options.executionControl;
1934
- // Same split the generate path already enforces in
1935
- // `BaseProvider.withTurnTimeout`: an explicit, valid `turnTimeoutMs` is
1936
- // the caller's whole-turn contract and owns this timer. Without it the
1937
- // native stream path armed only the provider's own `timeout`, so a caller
1938
- // asking for a 40-minute turn of 5-minute calls was killed at the shorter
1939
- // value — and a caller asking for a 200ms turn was not bounded at all.
1934
+ // An explicit turnTimeoutMs remains a whole-turn deadline. Without one,
1935
+ // rely on the resettable stream idle timer; there is no hard lifetime cap.
1936
+ // executionControl keeps its existing lifetime/per-request contract.
1940
1937
  const hasValidTurnTimeout = typeof options.turnTimeoutMs === "number" &&
1941
1938
  Number.isFinite(options.turnTimeoutMs) &&
1942
1939
  options.turnTimeoutMs > 0;
@@ -1952,13 +1949,24 @@ export class AnthropicProvider extends BaseProvider {
1952
1949
  // that shape removed the turn's ceiling entirely while the caller had said
1953
1950
  // nothing at all about it, and TypeScript could not warn because the field
1954
1951
  // is `?: number | null`. An absent value means "no opinion", and no
1955
- // opinion inherits the legacy handling below.
1952
+ // opinion inherits the handling below.
1953
+ const idleTimeoutMs = this.getTimeout(options, "stream");
1956
1954
  const lifetimeTimeoutMs = control && control.lifetimeTimeoutMs !== undefined
1957
1955
  ? (control.lifetimeTimeoutMs ?? undefined)
1958
1956
  : hasValidTurnTimeout
1959
1957
  ? options.turnTimeoutMs
1960
- : this.getTimeout(options);
1958
+ : control
1959
+ ? this.getTimeout(options)
1960
+ : undefined;
1961
1961
  const timeoutController = createTimeoutController(lifetimeTimeoutMs, this.providerName, "stream");
1962
+ // Execution control has its own per-request and lifetime deadline contract.
1963
+ const idleController = control
1964
+ ? null
1965
+ : createTimeoutController(idleTimeoutMs, this.providerName, "stream");
1966
+ const cleanupTimeouts = () => {
1967
+ timeoutController?.cleanup();
1968
+ idleController?.cleanup();
1969
+ };
1962
1970
  // Consumer-driven abort: fires when the async iterator is closed early
1963
1971
  // (caller breaks out of `for await`) so the background loop stops
1964
1972
  // reading SSE and running tools.
@@ -1966,6 +1974,7 @@ export class AnthropicProvider extends BaseProvider {
1966
1974
  const abortSignal = mergeAbortSignals([
1967
1975
  options.abortSignal,
1968
1976
  timeoutController?.controller.signal,
1977
+ idleController?.controller.signal,
1969
1978
  consumerAbortController.signal,
1970
1979
  ]).signal;
1971
1980
  let toolsRecord;
@@ -2008,7 +2017,7 @@ export class AnthropicProvider extends BaseProvider {
2008
2017
  }
2009
2018
  }
2010
2019
  catch (setupErr) {
2011
- timeoutController?.cleanup();
2020
+ cleanupTimeouts();
2012
2021
  throw this.handleProviderError(setupErr);
2013
2022
  }
2014
2023
  const modelId = this.modelName || getDefaultAnthropicModel();
@@ -2040,7 +2049,25 @@ export class AnthropicProvider extends BaseProvider {
2040
2049
  const { push: pushChunk } = channel;
2041
2050
  const { usagePromise, finishPromise, resolveUsage, resolveFinish } = createDeferredAnalytics();
2042
2051
  let capturedProviderError;
2043
- const client = this.client;
2052
+ // The SDK consumes ping events before the adapter sees them. Monitor its
2053
+ // response body so every wire chunk, including heartbeats, resets idle time.
2054
+ const client = idleController
2055
+ ? this.client.withOptions({
2056
+ middleware: [
2057
+ ...this.client.middleware,
2058
+ async (request, next, context) => {
2059
+ const response = await next(request);
2060
+ return response.ok && context.options?.stream && response.body
2061
+ ? new Response(monitorStreamActivity(response.body, idleController.reset), {
2062
+ status: response.status,
2063
+ statusText: response.statusText,
2064
+ headers: response.headers,
2065
+ })
2066
+ : response;
2067
+ },
2068
+ ],
2069
+ })
2070
+ : this.client;
2044
2071
  // Every attempted call, for the no-output sentinel below; the result
2045
2072
  // reports only calls that returned a value, the rule the generate loop
2046
2073
  // and Bedrock already follow.
@@ -2394,12 +2421,29 @@ export class AnthropicProvider extends BaseProvider {
2394
2421
  // The engine's pause for its per-tool deadline goes down too, so
2395
2422
  // a confirmation the call waits on does not spend that bound.
2396
2423
  const pauseDeadline = pauseDeadlineOf(opts);
2397
- return execute(args, {
2398
- toolCallId: ctx.toolCallId ?? "",
2399
- ...(ctx.abortSignal ? { abortSignal: ctx.abortSignal } : {}),
2400
- ...(pauseDeadline ? { pauseDeadline } : {}),
2401
- messages: [],
2402
- });
2424
+ // No model frames arrive while a tool runs, so the stream idle
2425
+ // timer must not count that time; the tool's own deadline and any
2426
+ // explicit turnTimeoutMs still bound it.
2427
+ const keepAlive = idleController
2428
+ ? setInterval(idleController.reset, Math.max(1, Math.min(250, Math.floor(idleTimeoutMs / 2))))
2429
+ : undefined;
2430
+ // A tool that ignores abort and never settles must not keep the
2431
+ // process alive through this timer.
2432
+ keepAlive?.unref();
2433
+ try {
2434
+ return await execute(args, {
2435
+ toolCallId: ctx.toolCallId ?? "",
2436
+ ...(ctx.abortSignal ? { abortSignal: ctx.abortSignal } : {}),
2437
+ ...(pauseDeadline ? { pauseDeadline } : {}),
2438
+ messages: [],
2439
+ });
2440
+ }
2441
+ finally {
2442
+ if (keepAlive) {
2443
+ clearInterval(keepAlive);
2444
+ }
2445
+ idleController?.reset();
2446
+ }
2403
2447
  },
2404
2448
  };
2405
2449
  }
@@ -2587,7 +2631,7 @@ export class AnthropicProvider extends BaseProvider {
2587
2631
  pushChunk({ content: output });
2588
2632
  }
2589
2633
  }
2590
- timeoutController?.cleanup();
2634
+ cleanupTimeouts();
2591
2635
  channel.close();
2592
2636
  });
2593
2637
  loopPromise.catch(() => {
@@ -37,14 +37,14 @@ export declare class OllamaProvider extends OpenAIChatCompletionsProvider {
37
37
  */
38
38
  supportsTools(): boolean;
39
39
  /**
40
- * Local models are slow; the base already defaults Ollama to a 5-minute
41
- * timeout and honors a per-call `options.timeout`. Preserve the legacy
42
- * `OLLAMA_TIMEOUT` env override for callers who relied on it, applied only
40
+ * Local models are slow; the base defaults Ollama generation to 5 minutes
41
+ * and streaming idle time to 2 minutes, and honors a per-call `options.timeout`.
42
+ * Preserve the legacy `OLLAMA_TIMEOUT` env override, applied only
43
43
  * when no explicit per-call timeout is set. Parsed with the shared
44
44
  * `parseTimeout` so both millisecond numbers ("240000") and duration strings
45
45
  * ("4m", "30s") work; a malformed value is ignored in favour of the default.
46
46
  */
47
- getTimeout(options: TextGenerationOptions | StreamOptions): number;
47
+ getTimeout(options: TextGenerationOptions | StreamOptions, operation?: "generate" | "stream"): number;
48
48
  /**
49
49
  * Health check: probe `/v1/models` and require at least one installed model.
50
50
  * A reachable server with zero models would let `resolveModelName()` fall
@@ -159,14 +159,14 @@ export class OllamaProvider extends OpenAIChatCompletionsProvider {
159
159
  return isToolCapable;
160
160
  }
161
161
  /**
162
- * Local models are slow; the base already defaults Ollama to a 5-minute
163
- * timeout and honors a per-call `options.timeout`. Preserve the legacy
164
- * `OLLAMA_TIMEOUT` env override for callers who relied on it, applied only
162
+ * Local models are slow; the base defaults Ollama generation to 5 minutes
163
+ * and streaming idle time to 2 minutes, and honors a per-call `options.timeout`.
164
+ * Preserve the legacy `OLLAMA_TIMEOUT` env override, applied only
165
165
  * when no explicit per-call timeout is set. Parsed with the shared
166
166
  * `parseTimeout` so both millisecond numbers ("240000") and duration strings
167
167
  * ("4m", "30s") work; a malformed value is ignored in favour of the default.
168
168
  */
169
- getTimeout(options) {
169
+ getTimeout(options, operation = "generate") {
170
170
  if (options.timeout === undefined || options.timeout === null) {
171
171
  const envTimeout = process.env.OLLAMA_TIMEOUT?.trim();
172
172
  if (envTimeout) {
@@ -182,7 +182,7 @@ export class OllamaProvider extends OpenAIChatCompletionsProvider {
182
182
  }
183
183
  }
184
184
  }
185
- return super.getTimeout(options);
185
+ return super.getTimeout(options, operation);
186
186
  }
187
187
  /**
188
188
  * Health check: probe `/v1/models` and require at least one installed model.
@@ -34,7 +34,7 @@ import { logger } from "../utils/logger.js";
34
34
  import { redactUrlCredentials } from "../utils/logSanitize.js";
35
35
  import { NoOutputGeneratedError } from "../utils/generationErrors.js";
36
36
  import { buildNoOutputSentinel, stampNoOutputSpan, } from "../utils/noOutputSentinel.js";
37
- import { composeAbortSignalsScoped, createTimeoutController, mergeAbortSignals, TimeoutError, } from "../utils/timeout.js";
37
+ import { composeAbortSignalsScoped, createTimeoutController, getStreamLifetimeTimeout, mergeAbortSignals, monitorStreamActivity, TimeoutError, } from "../utils/timeout.js";
38
38
  import { resolveRequestKind } from "../core/resolveRequestKind.js";
39
39
  import { appendJsonSchemaInstruction, hasNativeDoGenerate, parseToolInput, resolveStepToolChoice, runNativeGenerateLoop, toNativeToolDeclaration, toPrepareStepRecord, validateToolInput, } from "../core/nativeGenerateLoop.js";
40
40
  import { resolveToolExecutionRecords, toolCallsFromSummaries, } from "../core/toolExecutionRecorder.js";
@@ -728,12 +728,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
728
728
  // the whole point of the SSE wire is that a slow-but-alive
729
729
  // completion keeps the connection (and the timer) fed.
730
730
  const monitored = timeoutController
731
- ? res.body.pipeThrough(new TransformStream({
732
- transform(chunk, controller) {
733
- timeoutController.reset();
734
- controller.enqueue(chunk);
735
- },
736
- }))
731
+ ? monitorStreamActivity(res.body, timeoutController.reset)
737
732
  : res.body;
738
733
  const sse = await parseSSEStream(monitored, () => { });
739
734
  // Re-shape the aggregate into the JSON-wire response so every
@@ -1576,8 +1571,13 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
1576
1571
  async executeStream(options, _analysisSchema) {
1577
1572
  this.validateStreamOptions(options);
1578
1573
  const startTime = Date.now();
1579
- const timeout = this.getTimeout(options);
1574
+ const timeout = this.getTimeout(options, "stream");
1580
1575
  const timeoutController = createTimeoutController(timeout, this.providerName, "stream");
1576
+ const lifetimeController = createTimeoutController(getStreamLifetimeTimeout(options.turnTimeoutMs), this.providerName, "stream");
1577
+ const cleanupTimeouts = () => {
1578
+ timeoutController?.cleanup();
1579
+ lifetimeController?.cleanup();
1580
+ };
1581
1581
  // Consumer-driven abort: fires when the async iterator is closed early
1582
1582
  // (caller breaks out of `for await`). Without this the background
1583
1583
  // `loopPromise` keeps reading SSE and running tools indefinitely.
@@ -1585,6 +1585,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
1585
1585
  const abortSignal = mergeAbortSignals([
1586
1586
  options.abortSignal,
1587
1587
  timeoutController?.controller.signal,
1588
+ lifetimeController?.controller.signal,
1588
1589
  consumerAbortController.signal,
1589
1590
  ]).signal;
1590
1591
  let modelId;
@@ -1619,7 +1620,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
1619
1620
  promptMessages = (await this.buildMessagesForStream(options));
1620
1621
  }
1621
1622
  catch (setupErr) {
1622
- timeoutController?.cleanup();
1623
+ cleanupTimeouts();
1623
1624
  throw setupErr;
1624
1625
  }
1625
1626
  // Structured output rides `response_format`, mirroring the generate
@@ -1732,6 +1733,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
1732
1733
  url,
1733
1734
  fetchImpl,
1734
1735
  abortSignal,
1736
+ onStreamActivity: timeoutController?.reset,
1735
1737
  options: sampled,
1736
1738
  conversation,
1737
1739
  openAITools,
@@ -1815,7 +1817,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
1815
1817
  catch (error) {
1816
1818
  consumerAbortController.abort();
1817
1819
  channel.close();
1818
- timeoutController?.cleanup();
1820
+ cleanupTimeouts();
1819
1821
  throw error;
1820
1822
  }
1821
1823
  // Closure-scoped capture: the runStreamLoop's catch block stashes the
@@ -1974,7 +1976,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
1974
1976
  });
1975
1977
  resolveFinish("stop");
1976
1978
  }
1977
- timeoutController?.cleanup();
1979
+ cleanupTimeouts();
1978
1980
  if (!consumerAbortController.signal.aborted) {
1979
1981
  consumerAbortController.abort();
1980
1982
  }
@@ -2037,15 +2039,23 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
2037
2039
  duration: s.endTime.getTime() - s.startTime.getTime(),
2038
2040
  }))),
2039
2041
  });
2042
+ // The structured-output re-ask runs after the loop settles and is still
2043
+ // inside the turn, so an explicit turnTimeoutMs stays armed until the
2044
+ // stream generator's own cleanup. Only the idle timer ends with the loop.
2040
2045
  loopPromise
2041
- ?.finally(() => timeoutController?.cleanup())
2046
+ ?.finally(() => {
2047
+ timeoutController?.cleanup();
2048
+ if (!options.schema) {
2049
+ lifetimeController?.cleanup();
2050
+ }
2051
+ })
2042
2052
  .catch((error) => {
2043
2053
  captureProviderError(error);
2044
2054
  });
2045
2055
  return result;
2046
2056
  }
2047
2057
  async runStreamLoop(args) {
2048
- const { maxSteps, modelId, url, fetchImpl, abortSignal, options, conversation, openAITools, stepToolChoice, toolsRecord, toolNameFromWire, toolsUsed, toolExecutionSummaries, pushChunk, closeChannel, resolveUsage, resolveFinish, responseFormat, onModelObserved, } = args;
2058
+ const { maxSteps, modelId, url, fetchImpl, abortSignal, options, conversation, openAITools, stepToolChoice, toolsRecord, toolNameFromWire, toolsUsed, toolExecutionSummaries, pushChunk, closeChannel, resolveUsage, resolveFinish, responseFormat, onModelObserved, onStreamActivity, } = args;
2049
2059
  // Hoisted above the try so the catch can resolve the usage accumulated
2050
2060
  // by steps that completed BEFORE the failure — those steps were billed.
2051
2061
  let stepFinish = null;
@@ -2152,6 +2162,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
2152
2162
  openAIToolChoice,
2153
2163
  pushChunk,
2154
2164
  responseFormat,
2165
+ onStreamActivity,
2155
2166
  }));
2156
2167
  lastObservedPromptTokens = stepResult.usage?.prompt_tokens;
2157
2168
  stepFinish = stepResult.finishReason;
@@ -2382,7 +2393,9 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
2382
2393
  if (!res.body) {
2383
2394
  throw new Error(`${this.providerName}: stream response had no body`);
2384
2395
  }
2385
- return parseSSEStream(res.body, (delta) => {
2396
+ return parseSSEStream(args.onStreamActivity
2397
+ ? monitorStreamActivity(res.body, args.onStreamActivity)
2398
+ : res.body, (delta) => {
2386
2399
  args.pushChunk({ content: delta });
2387
2400
  }, (reasoningDelta) => {
2388
2401
  // Reasoning rides alongside an empty `content` so plain-text
@@ -1,6 +1,6 @@
1
1
  import { type Span } from "@opentelemetry/api";
2
2
  import type { GenerationOperation, GenerationRecord, SpanOptions } from "../types/index.js";
3
- export declare function markFailure(span: Span, error: unknown, expected?: boolean): void;
3
+ export declare function markFailure(span: Span, error: unknown, expected?: boolean, summarize?: (error: unknown) => string | undefined): void;
4
4
  /**
5
5
  * @description Ends `span` at WARNING once `stream` is garbage collected while the span is still open, for a stream result whose caller dropped it without reading it to the end or closing it. Best effort: it runs only if and when the collector reclaims `stream`, and a span that already ended is left alone.
6
6
  * @param stream {object} - The iterable handed to the caller; `span` must not keep it reachable.
@@ -24,16 +24,17 @@ function readsAsAbort(error) {
24
24
  return false;
25
25
  }
26
26
  }
27
- export function markFailure(span, error, expected = false) {
27
+ export function markFailure(span, error, expected = false, summarize) {
28
28
  try {
29
- recordFailure(span, error, expected);
29
+ recordFailure(span, error, expected, summarize);
30
30
  }
31
31
  catch {
32
32
  // The span keeps whatever was recorded before the value could not be read.
33
33
  }
34
34
  }
35
- function recordFailure(span, error, expected) {
36
- const message = failureText(error);
35
+ function recordFailure(span, error, expected, summarize) {
36
+ const summary = summarize?.(error);
37
+ const message = summary ?? failureText(error);
37
38
  if (readsAsAbort(error)) {
38
39
  span.setAttributes({
39
40
  [LangfuseOtelSpanAttributes.OBSERVATION_LEVEL]: "WARNING",
@@ -48,7 +49,14 @@ function recordFailure(span, error, expected) {
48
49
  [LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]: message,
49
50
  });
50
51
  }
51
- if (error instanceof Error) {
52
+ if (summary !== undefined) {
53
+ // The thrown error's own message and stack are what the summary replaces.
54
+ span.recordException({
55
+ name: error instanceof Error ? error.name : "Error",
56
+ message,
57
+ });
58
+ }
59
+ else if (error instanceof Error) {
52
60
  span.recordException(error);
53
61
  }
54
62
  }
@@ -109,7 +117,7 @@ export async function withSpan(options, fn) {
109
117
  return result;
110
118
  }
111
119
  catch (error) {
112
- markFailure(span, error, options.expectedFailure?.(error));
120
+ markFailure(span, error, options.expectedFailure?.(error), options.failureSummary);
113
121
  throw error;
114
122
  }
115
123
  finally {
@@ -418,6 +418,8 @@ export type SpanOptions = {
418
418
  attributes?: Record<string, string | number | boolean | undefined>;
419
419
  /** Marks a thrown error as an expected skip whose Langfuse level the span set itself, so `withSpan` keeps it instead of raising ERROR. */
420
420
  expectedFailure?: (error: unknown) => boolean;
421
+ /** For a failure whose message is text from another system: returns the text to record on the span (status message, level message and exception) in its place. The thrown error is untouched. Return undefined to record the error as it is. */
422
+ failureSummary?: (error: unknown) => string | undefined;
421
423
  /** Keeps the span out of the active context, so spans started inside `fn` parent to the nearest ancestor that is exported. */
422
424
  detached?: boolean;
423
425
  /**
@@ -238,6 +238,8 @@ export type StreamLoopArgs = {
238
238
  url: string;
239
239
  fetchImpl: typeof fetch;
240
240
  abortSignal: AbortSignal | undefined;
241
+ /** Re-arm the idle timeout when any upstream wire bytes arrive. */
242
+ onStreamActivity?: () => void;
241
243
  options: StreamOptions;
242
244
  conversation: OpenAICompatChatMessage[];
243
245
  openAITools: OpenAICompatChatTool[] | undefined;
@@ -532,7 +532,9 @@ export type StreamOptions = {
532
532
  schema?: ValidationSchema;
533
533
  tools?: Record<string, Tool>;
534
534
  timeout?: number | string;
535
- /** Wall-clock cap for the whole agentic turn (ms). See GenerateOptions.turnTimeoutMs. */
535
+ /** Optional wall-clock cap for the whole agentic turn (ms). OpenAI-compatible
536
+ * and native Anthropic streams have no lifetime cap by default; `timeout`
537
+ * bounds idle time. See GenerateOptions.turnTimeoutMs. */
536
538
  turnTimeoutMs?: number;
537
539
  /**
538
540
  * Opt-in execution policy for this turn (native Anthropic streaming only).
@@ -136,6 +136,14 @@ export declare function createTimeoutController(timeout: number | string | undef
136
136
  reset: () => void;
137
137
  timeoutMs: number;
138
138
  } | null;
139
+ /** Keep a stream's idle deadline alive for every received wire chunk. */
140
+ export declare function monitorStreamActivity(body: ReadableStream<Uint8Array>, onActivity: () => void): ReadableStream<Uint8Array>;
141
+ /**
142
+ * Hard lifetime cap for a live stream, separate from its resettable idle
143
+ * deadline. Opt-in: only an explicit positive `turnTimeoutMs` sets one;
144
+ * otherwise there is no cap, so long but active streams are not cut off.
145
+ */
146
+ export declare function getStreamLifetimeTimeout(turnTimeoutMs?: number | null): number | undefined;
139
147
  /**
140
148
  * Compose an external abort signal with a timeout controller's signal.
141
149
  * Returns a single AbortSignal that fires when either signal aborts.
@@ -115,11 +115,18 @@ export const DEFAULT_TIMEOUTS = {
115
115
  * @returns Default timeout string
116
116
  */
117
117
  export function getDefaultTimeout(provider, operation = "generate") {
118
+ const providerKey = provider.toLowerCase().replace("_", "-");
119
+ const providerDefault = DEFAULT_TIMEOUTS.providers[providerKey] || DEFAULT_TIMEOUTS.global;
118
120
  if (operation === "stream") {
119
- return DEFAULT_TIMEOUTS.streaming;
121
+ // A stream never gets less than its provider's own budget, so slow-first-
122
+ // token providers (ollama, litellm: 5m) keep theirs instead of dropping
123
+ // to the shared streaming default.
124
+ return (parseTimeout(providerDefault) ?? 0) >
125
+ (parseTimeout(DEFAULT_TIMEOUTS.streaming) ?? 0)
126
+ ? providerDefault
127
+ : DEFAULT_TIMEOUTS.streaming;
120
128
  }
121
- const providerKey = provider.toLowerCase().replace("_", "-");
122
- return (DEFAULT_TIMEOUTS.providers[providerKey] || DEFAULT_TIMEOUTS.global);
129
+ return providerDefault;
123
130
  }
124
131
  /**
125
132
  * Create a timeout promise that rejects after specified duration
@@ -371,6 +378,27 @@ export function createTimeoutController(timeout, provider, operation) {
371
378
  };
372
379
  return { controller, cleanup, reset, timeoutMs };
373
380
  }
381
+ /** Keep a stream's idle deadline alive for every received wire chunk. */
382
+ export function monitorStreamActivity(body, onActivity) {
383
+ return body.pipeThrough(new TransformStream({
384
+ transform(chunk, controller) {
385
+ onActivity();
386
+ controller.enqueue(chunk);
387
+ },
388
+ }));
389
+ }
390
+ /**
391
+ * Hard lifetime cap for a live stream, separate from its resettable idle
392
+ * deadline. Opt-in: only an explicit positive `turnTimeoutMs` sets one;
393
+ * otherwise there is no cap, so long but active streams are not cut off.
394
+ */
395
+ export function getStreamLifetimeTimeout(turnTimeoutMs) {
396
+ return typeof turnTimeoutMs === "number" &&
397
+ Number.isFinite(turnTimeoutMs) &&
398
+ turnTimeoutMs > 0
399
+ ? turnTimeoutMs
400
+ : undefined;
401
+ }
374
402
  /**
375
403
  * Compose an external abort signal with a timeout controller's signal.
376
404
  * Returns a single AbortSignal that fires when either signal aborts.
@@ -1234,10 +1234,11 @@
1234
1234
  {"objectID":"d98dc8888c6b1b9c2181c08fe15c1d7f0545d665022f285f5349ecc5a7dedbe7","title":"Distributed Rate Limiting with Redis","url":"/docs/cookbook/rate-limit-handling#distributed-rate-limiting-with-redis","content":"For multi-instance deployments:","hierarchy":{"lvl0":"Cookbook","lvl1":"Rate Limit Handling","lvl2":"Distributed Rate Limiting with Redis","lvl3":""}},
1235
1235
  {"objectID":"ebb9c835006b8a4ebb952c6342112e445f5a584bc0f24287fc5886e240c8f375","title":"Best Practices","url":"/docs/cookbook/rate-limit-handling#best-practices","content":"Set conservative limits: Start with 80% of provider's limit\nMonitor usage: Track request patterns to optimize limits\nUse burst capacity: Allow occasional spikes while maintaining average rate\nImplement backoff: Exponential backoff on repeated rate limit errors\nCache responses: Reduce duplicate requests (see Cost Optimization)","hierarchy":{"lvl0":"Cookbook","lvl1":"Rate Limit Handling","lvl2":"Best Practices","lvl3":""}},
1236
1236
  {"objectID":"122f6a4b4882fe77a0403e20ab2c3032e58546c210d38e58d571da33ced23320","title":"See Also","url":"/docs/cookbook/rate-limit-handling#see-also","content":"Cost Optimization\nBatch Processing\nError Recovery\nStreaming with Retry","hierarchy":{"lvl0":"Cookbook","lvl1":"Rate Limit Handling","lvl2":"See Also","lvl3":""}},
1237
- {"objectID":"feb0e8fdd5a55ed39cd3eeb932df920702f17bf519b947650e61547319e7cc11","title":"Streaming with Retry Logic","url":"/docs/cookbook/streaming-with-retry","content":"Streaming with Retry Logic\n\nProblem\n\nNetwork interruptions, temporary provider outages, and transient errors can cause streaming responses to fail mid-stream. Without retry logic, users experience incomplete responses and poor reliability.\n\nSolution\n\nImplement automatic retry with exponential backoff for streaming responses. Handle different failure scenarios:\nNetwork timeouts\nConnection drops\nProvider rate limits\nTransient API errors\n\nCode\n\nExplanation\nRetry Configuration\n\nThe RetryConfig interface defines retry behavior:\nmaxRetries: Maximum number of retry attempts\ninitialDelay: Starting delay between retries (milliseconds)\nmaxDelay: Maximum delay to prevent excessive waiting\nbackoffMultiplier: How quickly delays increase (exponential backoff)\nRetry Loop\n\nThe while loop attempts streaming up to maxRetries + 1 times (initial attempt + retries).\nError Classification\n\nNot all errors should trigger retries:\nRetryable: Network errors, rate limits, temporary service issues\nNon-retryable: Authentication errors, invalid requests, missing models\nExponential Backoff\n\nEach retry waits longer than the previous:\nFirst retry: 1000ms\nSecond retry: 2000ms\nThird retry: 4000ms\nFourth retry: 8000ms (capped at maxDelay)\n\nThis prevents overwhelming the provider and gives transient issues time to resolve.\nStream Consumption\n\nThe code accumulates chunks to provide a complete response even if earlier attempts partially succeeded.\n\nVariations\n\nResume from Last Position\n\nFor very long streams, resume from the last received position:\n\nCircuit Breaker Pattern\n\nPrevent repeated failures with a circuit breaker:\n\nProvider Fallback on Retry\n\nTry different providers on subsequent retries:\n\nSee Also\nError Recovery Patterns\nMulti-Provider Fallback\nRate Limit Handling\nStreaming API Reference","hierarchy":{"lvl0":"Cookbook","lvl1":"Streaming with Retry Logic","lvl2":"","lvl3":""}},
1237
+ {"objectID":"feb0e8fdd5a55ed39cd3eeb932df920702f17bf519b947650e61547319e7cc11","title":"Streaming with Retry Logic","url":"/docs/cookbook/streaming-with-retry","content":"Streaming with Retry Logic\n\nProblem\n\nNetwork interruptions, temporary provider outages, and transient errors can cause streaming responses to fail mid-stream. Without retry logic, users experience incomplete responses and poor reliability.\n\nSolution\n\nImplement automatic retry with exponential backoff for streaming responses. Handle different failure scenarios:\nNetwork timeouts\nConnection drops\nProvider rate limits\nTransient API errors\n\nCode\n\nStream timeout policy\n\nStreaming calls now select the existing 2m streaming default instead of the\nprovider's generation default (for example, 30s for OpenAI, 60s for Anthropic).\nExplicit timeout values still take precedence, and Ollama's environment timeout\noverrides are preserved. Non-streaming defaults are unchanged.\n\nFor OpenAI-compatible and native Anthropic streams, timeout bounds inactivity:\neach raw response chunk, including a heartbeat, resets the idle deadline. Active\nstreams have no default lifetime cap and can continue beyond 30 minutes. Set\nturnTimeoutMs to opt in to a total turn deadline; heartbeat activity cannot\nextend it. Anthropic's explicit executionControl policy retains its existing\nper-request and lifetime behavior.\n\nRetry example\n\nExplanation\nRetry Configuration\n\nThe RetryConfig interface defines retry behavior:\nmaxRetries: Maximum number of retry attempts\ninitialDelay: Starting delay between retries (milliseconds)\nmaxDelay: Maximum delay to prevent excessive waiting\nbackoffMultiplier: How quickly delays increase (exponential backoff)\nRetry Loop\n\nThe while loop attempts streaming up to maxRetries + 1 times (initial attempt + retries).\nError Classification\n\nNot all errors should trigger retries:\nRetryable: Network errors, rate limits, temporary service issues\nNon-retryable: Authentication errors, invalid requests, missing models\nExponential Backoff\n\nEach retry waits longer than the previous:\nFirst retry: 1000ms\nSecond retry: 2000ms\nThird retry: 4000ms\nFourth retry: 8000ms (capped at maxDelay)\n\nThis prevents overwhelming the provider and gives transient issues time to resolve.\nStream Consumption\n\nThe code accumulates chunks to provide a complete response even if earlier attempts partially succeeded.\n\nVariations\n\nResume from Last Position\n\nFor very long streams, resume from the last received position:\n\nCircuit Breaker Pattern\n\nPrevent repeated failures with a circuit breaker:\n\nProvider Fallback on Retry\n\nTry different providers on subsequent retries:\n\nSee Also\nError Recovery Patterns\nMulti-Provider Fallback\nRate Limit Handling\nStreaming API Reference","hierarchy":{"lvl0":"Cookbook","lvl1":"Streaming with Retry Logic","lvl2":"","lvl3":""}},
1238
1238
  {"objectID":"472ceb0e39b287f287bd570b5250f75c2c2d8bc15e868b791e472374d26b1e02","title":"Problem","url":"/docs/cookbook/streaming-with-retry#problem","content":"Network interruptions, temporary provider outages, and transient errors can cause streaming responses to fail mid-stream. Without retry logic, users experience incomplete responses and poor reliability.","hierarchy":{"lvl0":"Cookbook","lvl1":"Streaming with Retry Logic","lvl2":"Problem","lvl3":""}},
1239
1239
  {"objectID":"6bcb7cd2ca9e53a0aa68e99dc609654017ddd5f23b6067e390140b05461edeca","title":"Solution","url":"/docs/cookbook/streaming-with-retry#solution","content":"Implement automatic retry with exponential backoff for streaming responses. Handle different failure scenarios:\nNetwork timeouts\nConnection drops\nProvider rate limits\nTransient API errors","hierarchy":{"lvl0":"Cookbook","lvl1":"Streaming with Retry Logic","lvl2":"Solution","lvl3":""}},
1240
- {"objectID":"2e7e45f94094925c5eaeb5816a36861806781b38d3481fc30ab949cc4f4d519f","title":"Code","url":"/docs/cookbook/streaming-with-retry#code","content":"Code","hierarchy":{"lvl0":"Cookbook","lvl1":"Streaming with Retry Logic","lvl2":"Code","lvl3":""}},
1240
+ {"objectID":"004d71f259083aaf893462f593d262c104d2dd0c5c7cdbb3d2f193c39d2cbde0","title":"Stream timeout policy","url":"/docs/cookbook/streaming-with-retry#stream-timeout-policy","content":"Streaming calls now select the existing 2m streaming default instead of the\nprovider's generation default (for example, 30s for OpenAI, 60s for Anthropic).\nExplicit timeout values still take precedence, and Ollama's environment timeout\noverrides are preserved. Non-streaming defaults are unchanged.\n\nFor OpenAI-compatible and native Anthropic streams, timeout bounds inactivity:\neach raw response chunk, including a heartbeat, resets the idle deadline. Active\nstreams have no default lifetime cap and can continue beyond 30 minutes. Set\nturnTimeoutMs to opt in to a total turn deadline; heartbeat activity cannot\nextend it. Anthropic's explicit executionControl policy retains its existing\nper-request and lifetime behavior.","hierarchy":{"lvl0":"Cookbook","lvl1":"Streaming with Retry Logic","lvl2":"Stream timeout policy","lvl3":""}},
1241
+ {"objectID":"e5c135a20ebb1351667908f24421f51aaf357ed494f213f91c985ac79f52c40a","title":"Retry example","url":"/docs/cookbook/streaming-with-retry#retry-example","content":"Retry example","hierarchy":{"lvl0":"Cookbook","lvl1":"Streaming with Retry Logic","lvl2":"Retry example","lvl3":""}},
1241
1242
  {"objectID":"698239032e7c166416bea4bc349591a3c45b04a69856f94b368c51661929c507","title":"1. Retry Configuration","url":"/docs/cookbook/streaming-with-retry#1-retry-configuration","content":"The RetryConfig interface defines retry behavior:\nmaxRetries: Maximum number of retry attempts\ninitialDelay: Starting delay between retries (milliseconds)\nmaxDelay: Maximum delay to prevent excessive waiting\nbackoffMultiplier: How quickly delays increase (exponential backoff)","hierarchy":{"lvl0":"Cookbook","lvl1":"Streaming with Retry Logic","lvl2":"1. Retry Configuration","lvl3":""}},
1242
1243
  {"objectID":"5c86ad31f040c5162dc4dd7b52c1e42f84a44ebfe6a7ff9709e10979f1d8e248","title":"2. Retry Loop","url":"/docs/cookbook/streaming-with-retry#2-retry-loop","content":"The while loop attempts streaming up to maxRetries + 1 times (initial attempt + retries).","hierarchy":{"lvl0":"Cookbook","lvl1":"Streaming with Retry Logic","lvl2":"2. Retry Loop","lvl3":""}},
1243
1244
  {"objectID":"718825ea30baf3d66847139cbd9931c250d2c3d23e13e7a78cb7aa3e7abade9f","title":"3. Error Classification","url":"/docs/cookbook/streaming-with-retry#3-error-classification","content":"Not all errors should trigger retries:\nRetryable: Network errors, rate limits, temporary service issues\nNon-retryable: Authentication errors, invalid requests, missing models","hierarchy":{"lvl0":"Cookbook","lvl1":"Streaming with Retry Logic","lvl2":"3. Error Classification","lvl3":""}},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "13.13.1",
3
+ "version": "13.13.3",
4
4
  "packageManager": "pnpm@10.34.9+sha512.f49b5a8ea0fdedb44bb3c0c1d6575092a53c2950d95b7ad15df11f17974877a2de3a01c07e934e9b28ce716e51c09a94962c7306d09be2e1e4b18a8c8762fd32",
5
5
  "description": "The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002/call) for routing, tool selection and context budgeting. MCP-native (4 transports), voice TTS/STT/realtime, RAG, agents, memory, compaction, 9 observability exporters. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · TypeSafe Jev and more.",
6
6
  "author": {
@@ -215,7 +215,8 @@
215
215
  "test:rag-bounds": "pnpm exec tsx test/continuous-test-suite-rag-bounds.ts",
216
216
  "test:skills": "pnpm exec tsx test/continuous-test-suite-skills.ts",
217
217
  "test:decide": "pnpm run test:decide-offline && pnpm run test:decide-live",
218
- "test:decide-offline": "pnpm exec tsx test/continuous-test-suite-decide.ts",
218
+ "test:decide-offline": "pnpm exec tsx test/continuous-test-suite-decide.ts && pnpm run test:decide-error-redaction",
219
+ "test:decide-error-redaction": "pnpm exec tsx test/continuous-test-suite-decide-error-redaction.ts",
219
220
  "test:decide-live": "pnpm exec tsx test/continuous-test-suite-decide-live.ts",
220
221
  "test:decide-catalog": "pnpm exec tsx test/continuous-test-suite-decide-catalog.ts",
221
222
  "test:agent-mode": "pnpm exec tsx test/continuous-test-suite-agent-mode.ts",