@juspay/neurolink 10.12.8 → 10.12.9

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.
@@ -25,7 +25,7 @@ import { calculateCacheSavingsPercent, extractCacheCreationTokens, extractCacheR
25
25
  import { DEFAULT_MAX_STEPS, DEFAULT_WRAPUP_TIME_LEAD_MS, } from "../constants.js";
26
26
  import { createStepBudgetGuard, estimateFixedOverheadTokens, } from "../../context/stepBudgetGuard.js";
27
27
  import { isTemperatureDeprecatedError, isSchemaComplexityError, isToolsSchemaConflictError, isToolsSchemaExclusionInForce, } from "./structuredOutputPolicy.js";
28
- import { coerceJsonToSchema } from "../../utils/json/coerce.js";
28
+ import { coerceJsonToSchema, recoverScalarRoot, schemaAccepts, } from "../../utils/json/coerce.js";
29
29
  import { convertZodToJsonSchema } from "../../utils/schemaConversion.js";
30
30
  import { NoObjectGeneratedError } from "../../utils/generationErrors.js";
31
31
  import { Output, stepCountIs } from "../../utils/tool.js";
@@ -800,26 +800,35 @@ export class GenerationHandler {
800
800
  }
801
801
  return coerced.content;
802
802
  }
803
- try {
804
- const scalar = JSON.parse(strippedText);
805
- if (scalar === "") {
803
+ const scalar = recoverScalarRoot(strippedText, options.schema);
804
+ switch (scalar.kind) {
805
+ case "empty":
806
806
  // A JSON-encoded empty string is an EMPTY completion, not a
807
807
  // recovered scalar — normalize to a true empty ('' content, no
808
808
  // structuredData) so callers' empty-response handling fires
809
809
  // instead of a literal '""' reaching the user.
810
810
  logger.warn("[GenerationHandler] schema requested but the model returned an empty JSON string; normalizing to empty content", { provider: this.providerName, model: this.modelName });
811
811
  return "";
812
- }
813
- if (scalar !== null && scalar !== undefined) {
814
- structuredData = scalar;
812
+ case "accepted":
813
+ // A JSON scalar root is only real structured data when the caller's
814
+ // schema actually accepts it. Under an OBJECT schema a recovered
815
+ // string/number is the raw completion in disguise (the shape a
816
+ // truncated response degrades to) — publishing it would hand the
817
+ // caller a `structuredData` that violates the schema they passed.
818
+ structuredData = scalar.value;
819
+ return strippedText;
820
+ case "rejected":
821
+ logger.warn("[GenerationHandler] recovered a JSON scalar the requested schema rejects; leaving structuredData unset", {
822
+ provider: this.providerName,
823
+ model: this.modelName,
824
+ scalarType: typeof scalar.value,
825
+ });
826
+ return strippedText;
827
+ case "nullish":
828
+ case "not-json":
829
+ logger.warn("[GenerationHandler] schema requested but no JSON could be recovered from model text; returning raw text", { provider: this.providerName, model: this.modelName });
815
830
  return strippedText;
816
- }
817
- }
818
- catch {
819
- // not JSON at all — fall through to raw text + WARN
820
831
  }
821
- logger.warn("[GenerationHandler] schema requested but no JSON could be recovered from model text; returning raw text", { provider: this.providerName, model: this.modelName });
822
- return strippedText;
823
832
  };
824
833
  if (useStructuredOutput) {
825
834
  try {
@@ -834,7 +843,20 @@ export class GenerationHandler {
834
843
  // (a string identical to the step text) and coerce it instead.
835
844
  const rawTextEcho = typeof experimentalOutput === "string" &&
836
845
  experimentalOutput === (generateResult.text ?? "");
837
- if (experimentalOutput !== undefined && !rawTextEcho) {
846
+ // The equality check above only catches an EXACT echo. On a multi-step
847
+ // or truncated turn the echo can differ from `text` (a different step's
848
+ // text, a fence, trailing whitespace), and a raw string would then be
849
+ // published as `structuredData` under an object schema — the "returned
850
+ // a string instead of the schema object" failure. A string is trusted
851
+ // as structured output ONLY when the caller's schema accepts it
852
+ // (string-root schemas keep working); otherwise it is coerced like any
853
+ // other raw model text.
854
+ const untrustedStringOutput = typeof experimentalOutput === "string" &&
855
+ !!options.schema &&
856
+ !schemaAccepts(options.schema, experimentalOutput);
857
+ if (experimentalOutput !== undefined &&
858
+ !rawTextEcho &&
859
+ !untrustedStringOutput) {
838
860
  // AI-SDK already parsed + schema-validated the object. Expose it
839
861
  // directly and serialise canonically — no hand-parsing needed.
840
862
  structuredData = experimentalOutput;
@@ -25,7 +25,7 @@ import { calculateCacheSavingsPercent, extractCacheCreationTokens, extractCacheR
25
25
  import { DEFAULT_MAX_STEPS, DEFAULT_WRAPUP_TIME_LEAD_MS, } from "../constants.js";
26
26
  import { createStepBudgetGuard, estimateFixedOverheadTokens, } from "../../context/stepBudgetGuard.js";
27
27
  import { isTemperatureDeprecatedError, isSchemaComplexityError, isToolsSchemaConflictError, isToolsSchemaExclusionInForce, } from "./structuredOutputPolicy.js";
28
- import { coerceJsonToSchema } from "../../utils/json/coerce.js";
28
+ import { coerceJsonToSchema, recoverScalarRoot, schemaAccepts, } from "../../utils/json/coerce.js";
29
29
  import { convertZodToJsonSchema } from "../../utils/schemaConversion.js";
30
30
  import { NoObjectGeneratedError } from "../../utils/generationErrors.js";
31
31
  import { Output, stepCountIs } from "../../utils/tool.js";
@@ -800,26 +800,35 @@ export class GenerationHandler {
800
800
  }
801
801
  return coerced.content;
802
802
  }
803
- try {
804
- const scalar = JSON.parse(strippedText);
805
- if (scalar === "") {
803
+ const scalar = recoverScalarRoot(strippedText, options.schema);
804
+ switch (scalar.kind) {
805
+ case "empty":
806
806
  // A JSON-encoded empty string is an EMPTY completion, not a
807
807
  // recovered scalar — normalize to a true empty ('' content, no
808
808
  // structuredData) so callers' empty-response handling fires
809
809
  // instead of a literal '""' reaching the user.
810
810
  logger.warn("[GenerationHandler] schema requested but the model returned an empty JSON string; normalizing to empty content", { provider: this.providerName, model: this.modelName });
811
811
  return "";
812
- }
813
- if (scalar !== null && scalar !== undefined) {
814
- structuredData = scalar;
812
+ case "accepted":
813
+ // A JSON scalar root is only real structured data when the caller's
814
+ // schema actually accepts it. Under an OBJECT schema a recovered
815
+ // string/number is the raw completion in disguise (the shape a
816
+ // truncated response degrades to) — publishing it would hand the
817
+ // caller a `structuredData` that violates the schema they passed.
818
+ structuredData = scalar.value;
819
+ return strippedText;
820
+ case "rejected":
821
+ logger.warn("[GenerationHandler] recovered a JSON scalar the requested schema rejects; leaving structuredData unset", {
822
+ provider: this.providerName,
823
+ model: this.modelName,
824
+ scalarType: typeof scalar.value,
825
+ });
826
+ return strippedText;
827
+ case "nullish":
828
+ case "not-json":
829
+ logger.warn("[GenerationHandler] schema requested but no JSON could be recovered from model text; returning raw text", { provider: this.providerName, model: this.modelName });
815
830
  return strippedText;
816
- }
817
- }
818
- catch {
819
- // not JSON at all — fall through to raw text + WARN
820
831
  }
821
- logger.warn("[GenerationHandler] schema requested but no JSON could be recovered from model text; returning raw text", { provider: this.providerName, model: this.modelName });
822
- return strippedText;
823
832
  };
824
833
  if (useStructuredOutput) {
825
834
  try {
@@ -834,7 +843,20 @@ export class GenerationHandler {
834
843
  // (a string identical to the step text) and coerce it instead.
835
844
  const rawTextEcho = typeof experimentalOutput === "string" &&
836
845
  experimentalOutput === (generateResult.text ?? "");
837
- if (experimentalOutput !== undefined && !rawTextEcho) {
846
+ // The equality check above only catches an EXACT echo. On a multi-step
847
+ // or truncated turn the echo can differ from `text` (a different step's
848
+ // text, a fence, trailing whitespace), and a raw string would then be
849
+ // published as `structuredData` under an object schema — the "returned
850
+ // a string instead of the schema object" failure. A string is trusted
851
+ // as structured output ONLY when the caller's schema accepts it
852
+ // (string-root schemas keep working); otherwise it is coerced like any
853
+ // other raw model text.
854
+ const untrustedStringOutput = typeof experimentalOutput === "string" &&
855
+ !!options.schema &&
856
+ !schemaAccepts(options.schema, experimentalOutput);
857
+ if (experimentalOutput !== undefined &&
858
+ !rawTextEcho &&
859
+ !untrustedStringOutput) {
838
860
  // AI-SDK already parsed + schema-validated the object. Expose it
839
861
  // directly and serialise canonically — no hand-parsing needed.
840
862
  structuredData = experimentalOutput;
@@ -775,6 +775,21 @@ export declare class NeuroLink {
775
775
  private applyClassifierRouting;
776
776
  private prepareGenerateAugmentations;
777
777
  private buildGenerateTextOptions;
778
+ /**
779
+ * Provider-agnostic JSON recovery for schema requests. Structured-output
780
+ * enforcement makes valid JSON the overwhelming case; for every other
781
+ * provider path — including generate() overrides (Vertex, Anthropic,
782
+ * Bedrock, Google AI Studio) — object/array roots are recovered here via
783
+ * balanced-scan + jsonrepair and scalar JSON roots via plain JSON.parse,
784
+ * with the parsed value exposed as `structuredData`. If nothing JSON-shaped
785
+ * is recoverable (pure prose), the raw text is returned, `structuredData`
786
+ * stays undefined, and a WARN makes the case observable.
787
+ *
788
+ * Mutates `textResult` in place, and must run BEFORE the end-of-generation
789
+ * emits so event consumers see the same content/structuredData the caller
790
+ * receives.
791
+ */
792
+ private recoverStructuredData;
778
793
  private finalizeGenerateRequestResult;
779
794
  private emitGenerateErrorEvent;
780
795
  /**
@@ -74,7 +74,7 @@ import { CircuitBreaker, ERROR_CODES, ErrorFactory, isAbortError, isRetriableErr
74
74
  import { hasLifecycleErrorFired, markLifecycleErrorFired, } from "./utils/lifecycleCallbacks.js";
75
75
  import { resolveLifecycleTimeoutMs } from "./utils/lifecycleTimeout.js";
76
76
  import { cloneOptionsForCallIsolation } from "./utils/cloneOptions.js";
77
- import { coerceJsonToSchema } from "./utils/json/coerce.js";
77
+ import { coerceJsonToSchema, recoverScalarRoot, schemaAccepts, } from "./utils/json/coerce.js";
78
78
  // Factory processing imports
79
79
  import { createCleanStreamOptions, enhanceTextGenerationOptions, processFactoryOptions, processStreamingFactoryOptions, validateFactoryConfig, } from "./utils/factoryProcessing.js";
80
80
  import { logger, mcpLogger } from "./utils/logger.js";
@@ -4058,52 +4058,85 @@ Current user's request: ${currentInput}`;
4058
4058
  }
4059
4059
  return textOptions;
4060
4060
  }
4061
- finalizeGenerateRequestResult(params) {
4062
- const { generateSpan, options, textOptions, textResult, factoryResult, originalPrompt, startTime, } = params;
4063
- // Provider-agnostic JSON coercion for schema requests. Structured-output
4064
- // enforcement makes valid JSON the overwhelming case; for every other
4065
- // provider pathincluding generate() overrides (Vertex, Anthropic,
4066
- // Bedrock, Google AI Studio) object/array roots are recovered here via
4067
- // balanced-scan + jsonrepair and scalar JSON roots via plain JSON.parse,
4068
- // with the parsed value exposed as `structuredData`. If nothing
4069
- // JSON-shaped is recoverable (pure prose), the raw text is returned,
4070
- // `structuredData` stays undefined, and a WARN makes the case observable.
4071
- // Runs BEFORE the end-of-generation emits below so event consumers see
4072
- // the same coerced content/structuredData the caller receives.
4073
- if (textOptions.schema &&
4074
- textResult.structuredData === undefined &&
4075
- typeof textResult.content === "string") {
4076
- const coerced = coerceJsonToSchema(textResult.content, textOptions.schema);
4077
- if (coerced) {
4078
- textResult.content = coerced.content;
4079
- textResult.structuredData = coerced.structuredData;
4080
- if (coerced.repaired) {
4081
- textResult.jsonRepaired = true;
4082
- }
4083
- if (coerced.truncated) {
4084
- textResult.jsonTruncated = true;
4085
- }
4061
+ /**
4062
+ * Provider-agnostic JSON recovery for schema requests. Structured-output
4063
+ * enforcement makes valid JSON the overwhelming case; for every other
4064
+ * provider path including generate() overrides (Vertex, Anthropic,
4065
+ * Bedrock, Google AI Studio) object/array roots are recovered here via
4066
+ * balanced-scan + jsonrepair and scalar JSON roots via plain JSON.parse,
4067
+ * with the parsed value exposed as `structuredData`. If nothing JSON-shaped
4068
+ * is recoverable (pure prose), the raw text is returned, `structuredData`
4069
+ * stays undefined, and a WARN makes the case observable.
4070
+ *
4071
+ * Mutates `textResult` in place, and must run BEFORE the end-of-generation
4072
+ * emits so event consumers see the same content/structuredData the caller
4073
+ * receives.
4074
+ */
4075
+ recoverStructuredData(textResult, schema) {
4076
+ // A provider path that produced its own `structuredData` normally owns it.
4077
+ // The one exception is a STRING the caller's schema rejects: that is the
4078
+ // raw completion leaking through as structured output (the shape a
4079
+ // truncated response degrades to), so re-run recovery over the text rather
4080
+ // than handing back a value the declared schema forbids.
4081
+ const structuredIsRejectedString = typeof textResult.structuredData === "string" &&
4082
+ !schemaAccepts(schema, textResult.structuredData);
4083
+ if (!schema ||
4084
+ (textResult.structuredData !== undefined &&
4085
+ !structuredIsRejectedString) ||
4086
+ typeof textResult.content !== "string") {
4087
+ return;
4088
+ }
4089
+ if (structuredIsRejectedString) {
4090
+ textResult.structuredData = undefined;
4091
+ }
4092
+ const coerced = coerceJsonToSchema(textResult.content, schema);
4093
+ if (coerced) {
4094
+ textResult.content = coerced.content;
4095
+ textResult.structuredData = coerced.structuredData;
4096
+ if (coerced.repaired) {
4097
+ textResult.jsonRepaired = true;
4086
4098
  }
4087
- else {
4088
- try {
4089
- const scalar = JSON.parse(textResult.content);
4090
- if (scalar === "") {
4091
- // A JSON-encoded empty string is an EMPTY completion, not a
4092
- // recovered scalar — normalize to a true empty so callers'
4093
- // empty-response handling fires instead of a literal '""'
4094
- // reaching the user. `structuredData` stays undefined.
4095
- textResult.content = "";
4096
- logger.warn("[NeuroLink] schema requested but the model returned an empty JSON string; normalizing to empty content", { provider: textResult.provider, model: textResult.model });
4097
- }
4098
- else if (scalar !== null && scalar !== undefined) {
4099
- textResult.structuredData = scalar;
4100
- }
4101
- }
4102
- catch {
4103
- logger.warn("[NeuroLink] schema requested but no JSON could be recovered from model output; returning raw text", { provider: textResult.provider, model: textResult.model });
4104
- }
4099
+ if (coerced.truncated) {
4100
+ textResult.jsonTruncated = true;
4105
4101
  }
4102
+ return;
4106
4103
  }
4104
+ const scalar = recoverScalarRoot(textResult.content, schema);
4105
+ switch (scalar.kind) {
4106
+ case "empty":
4107
+ // A JSON-encoded empty string is an EMPTY completion, not a recovered
4108
+ // scalar — normalize to a true empty so callers' empty-response
4109
+ // handling fires instead of a literal '""' reaching the user.
4110
+ // `structuredData` stays undefined.
4111
+ textResult.content = "";
4112
+ logger.warn("[NeuroLink] schema requested but the model returned an empty JSON string; normalizing to empty content", { provider: textResult.provider, model: textResult.model });
4113
+ break;
4114
+ case "accepted":
4115
+ // Only publish a scalar root the caller's schema actually accepts.
4116
+ // Under an OBJECT schema a recovered string is the raw completion in
4117
+ // disguise — the shape a truncated response degrades to — and exposing
4118
+ // it hands the caller a `structuredData` that violates the schema they
4119
+ // passed.
4120
+ textResult.structuredData = scalar.value;
4121
+ break;
4122
+ case "rejected":
4123
+ logger.warn("[NeuroLink] recovered a JSON scalar the requested schema rejects; leaving structuredData unset", {
4124
+ provider: textResult.provider,
4125
+ model: textResult.model,
4126
+ scalarType: typeof scalar.value,
4127
+ });
4128
+ break;
4129
+ case "nullish":
4130
+ // JSON null/undefined — no structured value to publish.
4131
+ break;
4132
+ case "not-json":
4133
+ logger.warn("[NeuroLink] schema requested but no JSON could be recovered from model output; returning raw text", { provider: textResult.provider, model: textResult.model });
4134
+ break;
4135
+ }
4136
+ }
4137
+ finalizeGenerateRequestResult(params) {
4138
+ const { generateSpan, options, textOptions, textResult, factoryResult, originalPrompt, startTime, } = params;
4139
+ this.recoverStructuredData(textResult, textOptions.schema);
4107
4140
  // Surface truncation when a schema was requested: either the provider
4108
4141
  // reported finishReason="length" or the recovered JSON came from an
4109
4142
  // unclosed span. Either way `structuredData` may be incomplete — warn at
@@ -1206,6 +1206,9 @@ export class AnthropicProvider extends BaseProvider {
1206
1206
  }
1207
1207
  const content = [];
1208
1208
  let finalResultText;
1209
+ // Text emitted in forced-json mode, kept only as a fallback (see below).
1210
+ const jsonModeText = [];
1211
+ let jsonToolAnswered = false;
1209
1212
  for (const block of response.content) {
1210
1213
  if (block.type === "thinking") {
1211
1214
  content.push({ type: "reasoning", text: block.thinking });
@@ -1213,13 +1216,17 @@ export class AnthropicProvider extends BaseProvider {
1213
1216
  else if (block.type === "text") {
1214
1217
  // In forced-json mode the payload arrives via the tool input, not
1215
1218
  // text — pass text through only in normal mode.
1216
- if (!jsonTool) {
1219
+ if (jsonTool) {
1220
+ jsonModeText.push(block.text);
1221
+ }
1222
+ else {
1217
1223
  content.push({ type: "text", text: block.text });
1218
1224
  }
1219
1225
  }
1220
1226
  else if (block.type === "tool_use") {
1221
1227
  if (jsonTool && block.name === jsonTool) {
1222
1228
  // Unwrap the synthetic tool call back into text JSON.
1229
+ jsonToolAnswered = true;
1223
1230
  content.push({
1224
1231
  type: "text",
1225
1232
  text: stringifyToolInput(block.input),
@@ -1241,6 +1248,15 @@ export class AnthropicProvider extends BaseProvider {
1241
1248
  }
1242
1249
  }
1243
1250
  }
1251
+ // Forced-json mode normally drops text blocks because the payload rides
1252
+ // in the synthetic tool's input. But when the response is cut short
1253
+ // (stop_reason "max_tokens") the tool call can be missing entirely, and
1254
+ // dropping the text would leave an EMPTY completion with nothing for
1255
+ // coerceJsonToSchema to recover. Fall back to the text so a partial
1256
+ // object can still be salvaged and flagged truncated.
1257
+ if (jsonTool && !jsonToolAnswered && jsonModeText.length > 0) {
1258
+ content.push({ type: "text", text: jsonModeText.join("") });
1259
+ }
1244
1260
  // final_result is terminal — parity with the native Claude-on-Vertex
1245
1261
  // and Gemini loops, which break out of the tool loop the moment it
1246
1262
  // arrives. Reasoning blocks are kept; any prose preamble and any tool
@@ -279,3 +279,32 @@ export type JsonCoercionResult = {
279
279
  */
280
280
  truncated: boolean;
281
281
  };
282
+ /**
283
+ * Decision returned by `recoverScalarRoot`. Each caller applies it to its own
284
+ * result shape and logger prefix, preserving its existing warning behaviour:
285
+ *
286
+ * - `empty` — the text is a JSON-encoded empty string (an EMPTY
287
+ * completion, not a recovered scalar). Callers normalize to a
288
+ * true empty.
289
+ * - `accepted` — a scalar root the caller's schema accepts; safe to publish
290
+ * as `structuredData`.
291
+ * - `rejected` — a scalar root the caller's schema rejects (e.g. a raw
292
+ * string under an object schema — the shape a truncated
293
+ * response degrades to). Do NOT publish it.
294
+ * - `nullish` — the text is the JSON literals `null`/`undefined`; there is
295
+ * no structured value to publish.
296
+ * - `not-json` — the text is not JSON at all.
297
+ */
298
+ export type ScalarRecoveryDecision = {
299
+ kind: "empty";
300
+ } | {
301
+ kind: "accepted";
302
+ value: unknown;
303
+ } | {
304
+ kind: "rejected";
305
+ value: unknown;
306
+ } | {
307
+ kind: "nullish";
308
+ } | {
309
+ kind: "not-json";
310
+ };
@@ -1,4 +1,24 @@
1
- import type { JsonCoercionResult, ValidationSchema } from "../../types/index.js";
1
+ import type { JsonCoercionResult, ScalarRecoveryDecision, ValidationSchema } from "../../types/index.js";
2
+ /**
3
+ * Does `value` satisfy `schema`? A schema we cannot validate with (absent, or
4
+ * without a Zod-style `safeParse`) accepts everything — callers use this as a
5
+ * gate, not as proof, so an unknown schema must never block a value.
6
+ *
7
+ * Exists so the consumers of coerceJsonToSchema can refuse to publish a
8
+ * recovered value as `structuredData` when the caller's schema rejects it —
9
+ * e.g. a raw *string* under an object schema, which is the shape a truncated
10
+ * response degrades to.
11
+ */
12
+ export declare function schemaAccepts(schema: ValidationSchema | undefined, value: unknown): boolean;
13
+ /**
14
+ * Recover a JSON *scalar* root (string/number/boolean) from model text. The
15
+ * object/array case is handled by `coerceJsonToSchema`; this covers the
16
+ * residual scalar root after that path returns null. Encapsulates the JSON
17
+ * parsing, the empty-string normalization, and the `schemaAccepts` gate so the
18
+ * same policy cannot drift between consumers (`neurolink.recoverStructuredData`
19
+ * and `GenerationHandler.coerceTextMode`).
20
+ */
21
+ export declare function recoverScalarRoot(text: string, schema: ValidationSchema | undefined): ScalarRecoveryDecision;
2
22
  /**
3
23
  * Try to produce canonical JSON from `text`. Returns null when no JSON object
4
24
  * could be recovered (caller should then keep the raw text).