@juspay/neurolink 10.6.0 → 10.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/adapters/video/vertexVideoHandler.js +4 -1
  3. package/dist/agent/directTools.d.ts +2 -2
  4. package/dist/agent/orchestration/orchestrator.js +2 -0
  5. package/dist/auth/errors.d.ts +1 -1
  6. package/dist/auth/middleware/AuthMiddleware.d.ts +1 -1
  7. package/dist/auth/providers/BaseAuthProvider.d.ts +1 -1
  8. package/dist/auth/providers/auth0.js +1 -1
  9. package/dist/auth/providers/betterAuth.js +1 -1
  10. package/dist/auth/providers/clerk.js +1 -1
  11. package/dist/auth/providers/firebase.js +1 -1
  12. package/dist/auth/providers/jwt.js +1 -1
  13. package/dist/auth/providers/oauth2.js +1 -1
  14. package/dist/auth/providers/supabase.js +1 -1
  15. package/dist/auth/providers/workos.js +1 -1
  16. package/dist/browser/neurolink.min.js +338 -338
  17. package/dist/cli/commands/proxy.js +2 -0
  18. package/dist/cli/commands/rag.js +2 -4
  19. package/dist/cli/factories/commandFactory.js +3 -2
  20. package/dist/cli/loop/conversationSelector.js +4 -6
  21. package/dist/client/auth.js +2 -7
  22. package/dist/client/reactHooks.js +2 -2
  23. package/dist/client/reactHooks.tsx +5 -10
  24. package/dist/core/baseProvider.d.ts +1 -1
  25. package/dist/core/baseProvider.js +16 -6
  26. package/dist/core/factory.d.ts +4 -3
  27. package/dist/core/modules/GenerationHandler.d.ts +1 -1
  28. package/dist/core/modules/GenerationHandler.js +7 -5
  29. package/dist/core/modules/TelemetryHandler.js +2 -2
  30. package/dist/core/toolExecutionRecorder.d.ts +1 -1
  31. package/dist/core/toolExecutionRecorder.js +1 -2
  32. package/dist/evaluation/errors/EvaluationError.d.ts +1 -1
  33. package/dist/evaluation/scorers/rule/contentSimilarityScorer.js +2 -0
  34. package/dist/evaluation/scorers/rule/formatScorer.js +1 -1
  35. package/dist/factories/providerFactory.d.ts +4 -3
  36. package/dist/factories/providerRegistry.d.ts +9 -4
  37. package/dist/factories/providerRegistry.js +9 -4
  38. package/dist/features/ppt/slideGenerator.js +6 -5
  39. package/dist/features/ppt/utils.d.ts +2 -1
  40. package/dist/features/ppt/utils.js +1 -0
  41. package/dist/lib/adapters/video/vertexVideoHandler.js +4 -1
  42. package/dist/lib/agent/orchestration/orchestrator.js +2 -0
  43. package/dist/lib/auth/providers/auth0.js +1 -1
  44. package/dist/lib/auth/providers/betterAuth.js +1 -1
  45. package/dist/lib/auth/providers/clerk.js +1 -1
  46. package/dist/lib/auth/providers/firebase.js +1 -1
  47. package/dist/lib/auth/providers/jwt.js +1 -1
  48. package/dist/lib/auth/providers/oauth2.js +1 -1
  49. package/dist/lib/auth/providers/supabase.js +1 -1
  50. package/dist/lib/auth/providers/workos.js +1 -1
  51. package/dist/lib/client/auth.js +2 -7
  52. package/dist/lib/client/reactHooks.js +2 -2
  53. package/dist/lib/core/baseProvider.d.ts +1 -1
  54. package/dist/lib/core/baseProvider.js +16 -6
  55. package/dist/lib/core/factory.d.ts +4 -3
  56. package/dist/lib/core/modules/GenerationHandler.d.ts +1 -1
  57. package/dist/lib/core/modules/GenerationHandler.js +7 -5
  58. package/dist/lib/core/modules/TelemetryHandler.js +2 -2
  59. package/dist/lib/core/toolExecutionRecorder.d.ts +1 -1
  60. package/dist/lib/core/toolExecutionRecorder.js +1 -2
  61. package/dist/lib/evaluation/scorers/rule/contentSimilarityScorer.js +2 -0
  62. package/dist/lib/evaluation/scorers/rule/formatScorer.js +1 -1
  63. package/dist/lib/factories/providerFactory.d.ts +4 -3
  64. package/dist/lib/factories/providerRegistry.d.ts +9 -4
  65. package/dist/lib/factories/providerRegistry.js +9 -4
  66. package/dist/lib/features/ppt/slideGenerator.js +6 -5
  67. package/dist/lib/features/ppt/utils.d.ts +2 -1
  68. package/dist/lib/features/ppt/utils.js +1 -0
  69. package/dist/lib/mcp/elicitationProtocol.js +1 -1
  70. package/dist/lib/mcp/mcpRegistryClient.js +1 -1
  71. package/dist/lib/middleware/utils/guardrailsUtils.js +1 -1
  72. package/dist/lib/neurolink.js +15 -7
  73. package/dist/lib/processors/document/ExcelProcessor.js +5 -1
  74. package/dist/lib/processors/media/index.js +0 -10
  75. package/dist/lib/providers/amazonBedrock.js +4 -5
  76. package/dist/lib/providers/amazonSagemaker.d.ts +18 -0
  77. package/dist/lib/providers/amazonSagemaker.js +9 -3
  78. package/dist/lib/providers/anthropic.js +6 -1
  79. package/dist/lib/providers/googleAiStudio.js +5 -12
  80. package/dist/lib/providers/googleVertex.js +26 -5
  81. package/dist/lib/providers/openaiChatCompletionsBase.js +2 -0
  82. package/dist/lib/providers/sagemaker/errors.js +2 -1
  83. package/dist/lib/proxy/proxyFetch.js +6 -2
  84. package/dist/lib/rag/ChunkerFactory.js +1 -1
  85. package/dist/lib/rag/chunking/semanticChunker.js +1 -2
  86. package/dist/lib/rag/document/MDocument.js +1 -2
  87. package/dist/lib/rag/document/loaders.js +16 -3
  88. package/dist/lib/rag/pipeline/RAGPipeline.js +1 -2
  89. package/dist/lib/rag/retrieval/hybridSearch.js +1 -2
  90. package/dist/lib/rag/retrieval/vectorQueryTool.js +1 -2
  91. package/dist/lib/sdk/toolRegistration.js +6 -2
  92. package/dist/lib/server/middleware/cache.d.ts +4 -0
  93. package/dist/lib/server/middleware/cache.js +7 -3
  94. package/dist/lib/server/middleware/validation.js +2 -1
  95. package/dist/lib/server/utils/redaction.js +31 -39
  96. package/dist/lib/server/websocket/WebSocketHandler.js +3 -3
  97. package/dist/lib/services/server/ai/observability/instrumentation.js +8 -5
  98. package/dist/lib/types/classifierRouter.d.ts +2 -1
  99. package/dist/lib/types/providers.d.ts +22 -2
  100. package/dist/lib/utils/pdfProcessor.js +2 -0
  101. package/dist/lib/utils/safeFetch.js +20 -0
  102. package/dist/lib/utils/schemaConversion.d.ts +1 -1
  103. package/dist/lib/utils/schemaConversion.js +5 -1
  104. package/dist/lib/workflow/config.d.ts +1 -1
  105. package/dist/lib/workflow/config.js +1 -1
  106. package/dist/lib/workflow/core/workflowRegistry.js +1 -1
  107. package/dist/lib/workflow/core/workflowRunner.js +1 -1
  108. package/dist/lib/workflow/utils/workflowMetrics.d.ts +1 -1
  109. package/dist/lib/workflow/utils/workflowMetrics.js +1 -1
  110. package/dist/mcp/elicitationProtocol.js +1 -1
  111. package/dist/mcp/mcpRegistryClient.js +1 -1
  112. package/dist/middleware/utils/guardrailsUtils.js +1 -1
  113. package/dist/neurolink.js +15 -7
  114. package/dist/processors/document/ExcelProcessor.js +5 -1
  115. package/dist/processors/media/index.js +0 -10
  116. package/dist/providers/amazonBedrock.js +4 -5
  117. package/dist/providers/amazonSagemaker.d.ts +18 -0
  118. package/dist/providers/amazonSagemaker.js +9 -3
  119. package/dist/providers/anthropic.js +6 -1
  120. package/dist/providers/googleAiStudio.js +5 -12
  121. package/dist/providers/googleVertex.js +26 -5
  122. package/dist/providers/openaiChatCompletionsBase.js +2 -0
  123. package/dist/providers/sagemaker/errors.js +2 -1
  124. package/dist/proxy/proxyFetch.js +6 -2
  125. package/dist/rag/ChunkerFactory.js +1 -1
  126. package/dist/rag/chunking/semanticChunker.js +1 -2
  127. package/dist/rag/document/MDocument.js +1 -2
  128. package/dist/rag/document/loaders.js +16 -3
  129. package/dist/rag/pipeline/RAGPipeline.js +1 -2
  130. package/dist/rag/retrieval/hybridSearch.js +1 -2
  131. package/dist/rag/retrieval/vectorQueryTool.js +1 -2
  132. package/dist/sdk/toolRegistration.js +6 -2
  133. package/dist/server/middleware/cache.d.ts +4 -0
  134. package/dist/server/middleware/cache.js +7 -3
  135. package/dist/server/middleware/validation.js +2 -1
  136. package/dist/server/utils/redaction.js +31 -39
  137. package/dist/server/websocket/WebSocketHandler.js +3 -3
  138. package/dist/services/server/ai/observability/instrumentation.js +8 -5
  139. package/dist/types/classifierRouter.d.ts +2 -1
  140. package/dist/types/providers.d.ts +22 -2
  141. package/dist/utils/pdfProcessor.js +2 -0
  142. package/dist/utils/safeFetch.js +20 -0
  143. package/dist/utils/schemaConversion.d.ts +1 -1
  144. package/dist/utils/schemaConversion.js +5 -1
  145. package/dist/workflow/config.d.ts +2 -2
  146. package/dist/workflow/config.js +1 -1
  147. package/dist/workflow/core/workflowRegistry.js +1 -1
  148. package/dist/workflow/core/workflowRunner.js +1 -1
  149. package/dist/workflow/utils/workflowMetrics.d.ts +1 -1
  150. package/dist/workflow/utils/workflowMetrics.js +1 -1
  151. package/package.json +1 -1
@@ -192,7 +192,8 @@ export function handleSageMakerError(error, endpoint) {
192
192
  /**
193
193
  * Extract request ID from AWS SDK error for debugging
194
194
  *
195
- * @param error - Error object that might contain request ID
195
+ * @param error - Error object that might contain request ID (AWS SDK errors
196
+ * carry it as an untyped extra field, so the value is treated as opaque)
196
197
  * @returns Request ID if found, undefined otherwise
197
198
  */
198
199
  function extractRequestId(error) {
@@ -509,10 +509,14 @@ async function executeProxiedFetch(input, init, proxyEnv) {
509
509
  fetchInput = input;
510
510
  }
511
511
  const undici = await import("undici");
512
- const response = await undici.fetch(fetchInput, {
512
+ // undici's fetch types and lib.dom's diverge on iterator helper details,
513
+ // so the runtime-identical response is typed as either flavor (widening
514
+ // assertion so control flow keeps the union) and narrowed
515
+ // (overlap-checked) back to the DOM flavor at the return boundary.
516
+ const response = (await undici.fetch(fetchInput, {
513
517
  ...fetchInit,
514
518
  dispatcher,
515
- });
519
+ }));
516
520
  if (logger.shouldLog("debug")) {
517
521
  const { parsed: responseBody, size: responseSize, type: responseType, headers: responseHeaders, } = await readResponseBody(response);
518
522
  logger.debug("[Observability] HTTP response from LLM provider", {
@@ -177,7 +177,7 @@ export class ChunkerFactory extends BaseFactory {
177
177
  }, DEFAULT_CHUNKER_METADATA.latex);
178
178
  // Register semantic chunker (placeholder - uses recursive as fallback)
179
179
  this.registerChunker("semantic", async (config) => {
180
- // TODO: Implement dedicated SemanticChunker with LLM support
180
+ // TODO(#1179): Implement dedicated SemanticChunker with LLM support
181
181
  // For now, fall back to RecursiveChunker with semantic defaults
182
182
  const { RecursiveChunker } = await import("./chunkers/RecursiveChunker.js");
183
183
  return new RecursiveChunker(config);
@@ -138,8 +138,7 @@ export class SemanticChunker {
138
138
  async getEmbeddings(segments, provider, modelName) {
139
139
  const embeddingProvider = await ProviderFactory.createProvider(provider, modelName);
140
140
  // Check if provider has embed method
141
- if (typeof embeddingProvider.embed !==
142
- "function") {
141
+ if (typeof embeddingProvider.embed !== "function") {
143
142
  throw new Error(`Provider ${provider} does not support embeddings`);
144
143
  }
145
144
  const embeddings = [];
@@ -210,8 +210,7 @@ export class MDocument {
210
210
  model: modelName,
211
211
  });
212
212
  const embeddingProvider = await ProviderFactory.createProvider(provider, modelName);
213
- if (typeof embeddingProvider.embed !==
214
- "function") {
213
+ if (typeof embeddingProvider.embed !== "function") {
215
214
  throw new Error(`Provider ${provider} does not support embeddings`);
216
215
  }
217
216
  this.state.embeddings = [];
@@ -273,14 +273,27 @@ export class PDFLoader {
273
273
  return ext === ".pdf";
274
274
  }
275
275
  async loadPdfParser() {
276
+ // pdf-parse is an optional dependency — resolve it dynamically and
277
+ // validate at runtime that it exposes a callable parser (either the
278
+ // module itself or its default export) instead of blindly asserting.
279
+ let pdfParseModule;
276
280
  try {
277
- // pdf-parse is an optional dependency - use dynamic import with type assertion
278
- const pdfParse = (await import("pdf-parse"));
279
- return pdfParse.default || pdfParse;
281
+ pdfParseModule = await import("pdf-parse");
280
282
  }
281
283
  catch {
282
284
  throw new Error("pdf-parse module not available");
283
285
  }
286
+ const candidate = (typeof pdfParseModule === "object" &&
287
+ pdfParseModule !== null &&
288
+ "default" in pdfParseModule
289
+ ? pdfParseModule.default
290
+ : undefined) || pdfParseModule;
291
+ if (typeof candidate !== "function") {
292
+ // Outside the try/catch so this message isn't swallowed by the
293
+ // module-not-available rethrow.
294
+ throw new Error("pdf-parse module does not export a parse function");
295
+ }
296
+ return candidate;
284
297
  }
285
298
  parsePageRange(range, totalPages) {
286
299
  const pages = [];
@@ -371,8 +371,7 @@ export class RAGPipeline {
371
371
  if (!this.embeddingProvider) {
372
372
  throw new Error("Embedding provider not initialized");
373
373
  }
374
- if (typeof this.embeddingProvider
375
- .embed !== "function") {
374
+ if (typeof this.embeddingProvider.embed !== "function") {
376
375
  throw new Error(`Provider ${this.config.embeddingModel.provider} does not support embeddings`);
377
376
  }
378
377
  return await withTimeout(this.embeddingProvider.embed(text), DEFAULT_TIMEOUT_MS, "Embedding generation timed out");
@@ -177,8 +177,7 @@ export function createHybridSearch(options) {
177
177
  try {
178
178
  // Generate query embedding
179
179
  const embeddingProvider = await ProviderFactory.createProvider(embeddingModel?.provider, embeddingModel?.modelName);
180
- if (typeof embeddingProvider
181
- .embed !== "function") {
180
+ if (typeof embeddingProvider.embed !== "function") {
182
181
  throw new Error(`Embedding provider does not support the embed() method. ` +
183
182
  `Please use a provider that supports embeddings (e.g., OpenAI text-embedding-3-small, Vertex text-embedding-004).`);
184
183
  }
@@ -66,8 +66,7 @@ export function createVectorQueryTool(config, vectorStore) {
66
66
  // Generate query embedding
67
67
  const embeddingProvider = await ProviderFactory.createProvider(embeddingModel.provider, embeddingModel.modelName);
68
68
  // Check if provider has embed method
69
- if (typeof embeddingProvider
70
- .embed !== "function") {
69
+ if (typeof embeddingProvider.embed !== "function") {
71
70
  throw new Error(`Provider ${embeddingModel.provider} does not support embeddings`);
72
71
  }
73
72
  const queryEmbedding = await embeddingProvider.embed(params.query);
@@ -250,8 +250,12 @@ export function validateTool(name, tool) {
250
250
  throw new Error(`Tool '${name}' parameters must be an object. ` +
251
251
  `Received: ${typeof tool.parameters}`);
252
252
  }
253
- // Check for common schema validation methods (Zod uses 'parse', others might use 'validate')
254
- const params = tool.parameters;
253
+ // Check for common schema validation methods (Zod uses 'parse', others might use 'validate').
254
+ // Despite the declared Zod type, callers may pass custom schema objects at
255
+ // runtime — this function's whole purpose is to validate that; probe as
256
+ // `unknown` and narrow to a generic record for feature detection.
257
+ const paramsCandidate = tool.parameters;
258
+ const params = paramsCandidate;
255
259
  const hasValidationMethod = typeof params.parse === "function" ||
256
260
  typeof params.validate === "function" ||
257
261
  "_def" in params; // Zod schemas have _def property
@@ -83,6 +83,10 @@ export declare class LRUCache<K, V> {
83
83
  * Check if a key exists in the cache
84
84
  */
85
85
  has(key: K): boolean;
86
+ /**
87
+ * Iterate over all keys currently in the cache
88
+ */
89
+ keys(): IterableIterator<K>;
86
90
  /**
87
91
  * Delete a key from the cache
88
92
  */
@@ -219,6 +219,12 @@ export class LRUCache {
219
219
  has(key) {
220
220
  return this.cache.has(key);
221
221
  }
222
+ /**
223
+ * Iterate over all keys currently in the cache
224
+ */
225
+ keys() {
226
+ return this.cache.keys();
227
+ }
222
228
  /**
223
229
  * Delete a key from the cache
224
230
  */
@@ -335,9 +341,7 @@ export class ResponseCacheStore {
335
341
  // For production, consider using a more efficient data structure
336
342
  let invalidated = 0;
337
343
  const keysToDelete = [];
338
- // Get all keys (requires accessing internal cache)
339
- const internalCache = this.cache.cache;
340
- for (const key of internalCache.keys()) {
344
+ for (const key of this.cache.keys()) {
341
345
  const matches = pattern instanceof RegExp ? pattern.test(key) : key.includes(pattern);
342
346
  if (matches) {
343
347
  keysToDelete.push(key);
@@ -75,7 +75,8 @@ export function createRequestValidationMiddleware(config) {
75
75
  const formattedError = errorFormatter(errors.map((e) => new ServerValidationError([e], ctx.requestId)));
76
76
  const error = new ServerValidationError(errors, ctx.requestId);
77
77
  // Attach formatted response to error
78
- error.response = formattedError;
78
+ error.response =
79
+ formattedError;
79
80
  throw error;
80
81
  }
81
82
  return next();
@@ -80,13 +80,13 @@ function redactChunkByType(chunk, redactedFields, placeholder, config) {
80
80
  const chunkType = typedChunk.type;
81
81
  switch (chunkType) {
82
82
  case "step-start":
83
- return redactStepStart(typedChunk, redactedFields, placeholder);
83
+ return redactStepStart(chunk, redactedFields, placeholder);
84
84
  case "tool-call":
85
- return redactToolCall(typedChunk, redactedFields, placeholder, config);
85
+ return redactToolCall(chunk, redactedFields, placeholder, config);
86
86
  case "tool-result":
87
- return redactToolResult(typedChunk, redactedFields, placeholder, config);
87
+ return redactToolResult(chunk, redactedFields, placeholder, config);
88
88
  case "error":
89
- return redactError(typedChunk, redactedFields, placeholder);
89
+ return redactError(chunk, redactedFields, placeholder);
90
90
  default:
91
91
  return redactGenericChunk(typedChunk, redactedFields, placeholder);
92
92
  }
@@ -99,13 +99,12 @@ function redactStepStart(chunk, redactedFields, placeholder) {
99
99
  return chunk;
100
100
  }
101
101
  const { payload, ...rest } = chunk;
102
- const payloadObj = payload;
103
- const redactedPayload = redactObject(payloadObj, redactedFields, placeholder, 0);
104
- return {
102
+ const redactedPayload = redactObject(payload, redactedFields, placeholder, 0);
103
+ const redacted = {
105
104
  ...rest,
106
- type: "step-start",
107
105
  payload: redactedPayload,
108
106
  };
107
+ return redacted;
109
108
  }
110
109
  /**
111
110
  * Redact tool-call chunks
@@ -114,49 +113,45 @@ function redactToolCall(chunk, redactedFields, placeholder, config) {
114
113
  // Handle chunks with payload structure
115
114
  if (hasPayload(chunk)) {
116
115
  const { payload, ...rest } = chunk;
117
- const payloadObj = payload;
118
116
  // Redact tool arguments if configured
119
- if (payloadObj.toolCall && typeof payloadObj.toolCall === "object") {
120
- const toolCall = payloadObj.toolCall;
117
+ if (payload.toolCall && typeof payload.toolCall === "object") {
118
+ const toolCall = payload.toolCall;
121
119
  const redactArgs = config?.redactToolArgs !== false && redactedFields.has("args");
122
- return {
120
+ const redacted = {
123
121
  ...rest,
124
- type: "tool-call",
125
122
  payload: {
126
- ...payloadObj,
123
+ ...payload,
127
124
  toolCall: {
128
125
  ...toolCall,
129
126
  args: redactArgs ? placeholder : toolCall.args,
130
127
  },
131
128
  },
132
129
  };
130
+ return redacted;
133
131
  }
134
- return {
132
+ const redacted = {
135
133
  ...rest,
136
- type: "tool-call",
137
- payload: redactObject(payloadObj, redactedFields, placeholder, 0),
134
+ payload: redactObject(payload, redactedFields, placeholder, 0),
138
135
  };
136
+ return redacted;
139
137
  }
140
138
  // Handle chunks with data structure (DataStreamEvent format)
141
139
  if (hasData(chunk)) {
142
140
  const { data, ...rest } = chunk;
143
- const dataObj = data;
144
141
  const redactArgs = config?.redactToolArgs !== false && redactedFields.has("args");
145
142
  // Check for arguments field in data
146
- if ("arguments" in dataObj && redactArgs) {
143
+ if ("arguments" in data && redactArgs) {
147
144
  return {
148
145
  ...rest,
149
- type: "tool-call",
150
146
  data: {
151
- ...dataObj,
147
+ ...data,
152
148
  arguments: placeholder,
153
149
  },
154
150
  };
155
151
  }
156
152
  return {
157
153
  ...rest,
158
- type: "tool-call",
159
- data: redactObject(dataObj, redactedFields, placeholder, 0),
154
+ data: redactObject(data, redactedFields, placeholder, 0),
160
155
  };
161
156
  }
162
157
  return chunk;
@@ -169,26 +164,23 @@ function redactToolResult(chunk, redactedFields, placeholder, config) {
169
164
  // Handle chunks with payload structure
170
165
  if (hasPayload(chunk)) {
171
166
  const { payload, ...rest } = chunk;
172
- const payloadObj = payload;
173
- return {
167
+ const redacted = {
174
168
  ...rest,
175
- type: "tool-result",
176
169
  payload: {
177
- ...payloadObj,
178
- result: redactResult ? placeholder : payloadObj.result,
170
+ ...payload,
171
+ result: redactResult ? placeholder : payload.result,
179
172
  },
180
173
  };
174
+ return redacted;
181
175
  }
182
176
  // Handle chunks with data structure (DataStreamEvent format)
183
177
  if (hasData(chunk)) {
184
178
  const { data, ...rest } = chunk;
185
- const dataObj = data;
186
179
  return {
187
180
  ...rest,
188
- type: "tool-result",
189
181
  data: {
190
- ...dataObj,
191
- result: redactResult ? placeholder : dataObj.result,
182
+ ...data,
183
+ result: redactResult ? placeholder : data.result,
192
184
  },
193
185
  };
194
186
  }
@@ -202,11 +194,9 @@ function redactError(chunk, redactedFields, placeholder) {
202
194
  // Handle chunks with data structure (DataStreamEvent format)
203
195
  if (hasData(chunk)) {
204
196
  const { data, ...rest } = chunk;
205
- const dataObj = data;
206
- const { stack, ...dataRest } = dataObj;
197
+ const { stack, ...dataRest } = data;
207
198
  return {
208
199
  ...rest,
209
- type: "error",
210
200
  data: {
211
201
  ...redactObject(dataRest, redactedFields, placeholder, 0),
212
202
  ...(isProduction ? {} : { stack }),
@@ -214,7 +204,8 @@ function redactError(chunk, redactedFields, placeholder) {
214
204
  };
215
205
  }
216
206
  // Handle direct chunk with stack
217
- const { stack, ...restChunk } = chunk;
207
+ const chunkRecord = chunk;
208
+ const { stack, ...restChunk } = chunkRecord;
218
209
  const redactedRest = redactObject(restChunk, redactedFields, placeholder, 0);
219
210
  return {
220
211
  ...redactedRest,
@@ -270,9 +261,10 @@ function redactObject(obj, redactedFields, placeholder, depth) {
270
261
  * Type guard for chunks with payload
271
262
  */
272
263
  function hasPayload(chunk) {
273
- return ("payload" in chunk &&
274
- chunk.payload !== null &&
275
- typeof chunk.payload === "object");
264
+ const record = chunk;
265
+ return ("payload" in record &&
266
+ record.payload !== null &&
267
+ typeof record.payload === "object");
276
268
  }
277
269
  /**
278
270
  * Type guard for chunks with data (DataStreamEvent format)
@@ -334,17 +334,17 @@ export function createAgentWebSocketHandler(_neurolink) {
334
334
  // Register message routes
335
335
  router.route("generate", async (connection, payload) => {
336
336
  const { prompt, options: _options } = payload;
337
- // TODO: Implement generate using neurolink
337
+ // TODO(#1179): Implement generate using neurolink
338
338
  return { type: "response", data: `Received: ${prompt}` };
339
339
  });
340
340
  router.route("stream", async (connection, payload) => {
341
341
  const { prompt, options: _options } = payload;
342
- // TODO: Implement streaming using neurolink
342
+ // TODO(#1179): Implement streaming using neurolink
343
343
  return { type: "stream_start", data: { prompt } };
344
344
  });
345
345
  router.route("tool_call", async (connection, payload) => {
346
346
  const { toolName, args: _args } = payload;
347
- // TODO: Implement tool call using neurolink
347
+ // TODO(#1179): Implement tool call using neurolink
348
348
  return { type: "tool_result", data: { toolName, result: null } };
349
349
  });
350
350
  return {
@@ -225,6 +225,7 @@ class ContextEnricher {
225
225
  const userId = context?.userId ?? currentConfig?.userId ?? "guest";
226
226
  const sessionId = context?.sessionId ?? currentConfig?.sessionId;
227
227
  // Get span name for operation auto-detection
228
+ // (sdk-trace-base's Span type includes the ReadableSpan members)
228
229
  const spanName = span.name;
229
230
  // Determine if auto-detection is enabled for this context
230
231
  const autoDetect = this.shouldAutoDetectOperationName(context);
@@ -386,9 +387,11 @@ class ContextEnricher {
386
387
  */
387
388
  onEnd(span) {
388
389
  try {
389
- // Get span attributes (ReadableSpan interface)
390
- const readableSpan = span;
391
- const attributes = readableSpan.attributes || {};
390
+ // Get span attributes (sdk-trace-base's Span type includes the
391
+ // ReadableSpan members, so attributes/name/status are directly typed).
392
+ // Keep the {} fallback: this processor can be attached to an external
393
+ // app-owned TracerProvider whose span implementation may omit attributes.
394
+ const attributes = span.attributes ?? {};
392
395
  // Handle wrapper/trace-root spans: update trace name with detected operation
393
396
  // This supports host apps (like Curator) that create wrapper spans before AI calls
394
397
  // This is optional - if spanContext fails, we skip wrapper span support
@@ -437,7 +440,7 @@ class ContextEnricher {
437
440
  const provider = attributes["gen_ai.system"] ||
438
441
  attributes["ai.model.provider"];
439
442
  logger.debug(`${LOG_PREFIX} GenAI span detected`, {
440
- spanName: readableSpan.name,
443
+ spanName: span.name,
441
444
  model,
442
445
  provider,
443
446
  });
@@ -529,7 +532,7 @@ class ContextEnricher {
529
532
  // *returns* { isError:true } (no exception thrown), so Langfuse sees
530
533
  // level=DEFAULT and no status message. Parse the stringified result
531
534
  // and surface the embedded error text.
532
- if (readableSpan.name === "ai.toolCall" &&
535
+ if (span.name === "ai.toolCall" &&
533
536
  readableStatus?.code !== SpanStatusCode.ERROR) {
534
537
  applyToolCallIsErrorStatus(mutableAttrs);
535
538
  }
@@ -13,6 +13,7 @@
13
13
  * Type names are domain-prefixed `Classifier*` to stay globally unique across
14
14
  * `src/lib/types/` (see CLAUDE.md rule 9).
15
15
  */
16
+ import type { ValidationSchema } from "./aliases.js";
16
17
  /** Coarse difficulty buckets the classifier maps a request into. */
17
18
  export type ClassifierDifficulty = "trivial" | "simple" | "moderate" | "hard" | "expert";
18
19
  /** Which classification strategy to run. */
@@ -166,7 +167,7 @@ export type ClassifierGenerateOptions = {
166
167
  temperature?: number;
167
168
  maxTokens?: number;
168
169
  disableTools?: boolean;
169
- schema?: unknown;
170
+ schema?: ValidationSchema;
170
171
  timeout?: number | string;
171
172
  context?: Record<string, unknown>;
172
173
  };
@@ -2,6 +2,7 @@
2
2
  * Provider-specific type definitions for NeuroLink
3
3
  */
4
4
  import type { UnknownRecord, JsonValue, StreamingCapability } from "./common.js";
5
+ import type { NeuroLink } from "../neurolink.js";
5
6
  import { AIProviderName, AnthropicModels, BedrockModels, DeepSeekModels, GoogleAIModels, LlamaCppModels, LMStudioModels, NvidiaNimModels, OpenAIModels, VertexModels } from "../constants/enums.js";
6
7
  import type { ValidationSchema } from "./aliases.js";
7
8
  import type { EnhancedGenerateResult, GenerateResult, TextGenerationOptions } from "./generate.js";
@@ -1669,8 +1670,8 @@ export type ToolWithLegacyParams = {
1669
1670
  * factory functions.
1670
1671
  */
1671
1672
  export type ProviderConstructor = {
1672
- new (modelName?: string, providerName?: string, sdk?: UnknownRecord, region?: string, credentials?: UnknownRecord): AIProvider;
1673
- } | ((modelName?: string, providerName?: string, sdk?: UnknownRecord, region?: string, credentials?: UnknownRecord) => Promise<AIProvider>);
1673
+ new (modelName?: string, providerName?: string, sdk?: NeuroLink, region?: string, credentials?: UnknownRecord): AIProvider;
1674
+ } | ((modelName?: string, providerName?: string, sdk?: NeuroLink, region?: string, credentials?: UnknownRecord) => Promise<AIProvider>);
1674
1675
  /** Provider registration entry held by ProviderFactory. */
1675
1676
  export type ProviderRegistration = {
1676
1677
  constructor: ProviderConstructor;
@@ -1779,6 +1780,25 @@ export type VertexNativePart = {
1779
1780
  data: string;
1780
1781
  };
1781
1782
  };
1783
+ /**
1784
+ * Part variants that ride the native Gemini agentic tool loop in addition to
1785
+ * the plain `VertexNativePart` content shapes: model-issued function calls
1786
+ * replayed into history, and the function responses (plus wrap-up nudge text
1787
+ * parts) sent back on the next user turn. Mirrors the optional
1788
+ * `functionCall` / `functionResponse` members of the @google/genai SDK's
1789
+ * `Part` type, so loop contents stay directly assignable to the SDK payload.
1790
+ */
1791
+ export type VertexNativeLoopPart = VertexNativePart | {
1792
+ functionCall: {
1793
+ name: string;
1794
+ args: Record<string, unknown>;
1795
+ };
1796
+ } | {
1797
+ functionResponse: {
1798
+ name: string;
1799
+ response: Record<string, unknown>;
1800
+ };
1801
+ };
1782
1802
  /**
1783
1803
  * Subset of `GenerateOptions["input"]` consumed by the shared Gemini-native
1784
1804
  * multimodal-parts builder. Kept narrow so the helper doesn't depend on the
@@ -264,6 +264,8 @@ export class PDFProcessor {
264
264
  clearTimeout(timeoutHandle);
265
265
  }
266
266
  try {
267
+ // Optional call: guards against a runtime pdf-parse version whose
268
+ // instances lack destroy(), while the typed v2 class declares it.
267
269
  await pdf.destroy?.();
268
270
  }
269
271
  catch {
@@ -58,6 +58,23 @@ function buildPinnedAgent(hostname, addresses) {
58
58
  },
59
59
  });
60
60
  }
61
+ /**
62
+ * Runtime-validating narrow across the undici → DOM `Response` type boundary.
63
+ * `readBoundedBuffer` only touches `headers.get()` and `arrayBuffer()`; the
64
+ * two libraries' `Response` declarations disagree on unrelated members
65
+ * (headers iterator shapes), so validate the members actually used instead
66
+ * of blindly asserting.
67
+ */
68
+ function isBoundedBufferResponse(value) {
69
+ if (typeof value !== "object" || value === null) {
70
+ return false;
71
+ }
72
+ const candidate = value;
73
+ return (typeof candidate.arrayBuffer === "function" &&
74
+ typeof candidate.headers === "object" &&
75
+ candidate.headers !== null &&
76
+ typeof candidate.headers.get === "function");
77
+ }
61
78
  /**
62
79
  * Safely download a binary asset from an external URL.
63
80
  *
@@ -96,6 +113,9 @@ export async function safeDownload(url, options) {
96
113
  }
97
114
  // readBoundedBuffer expects a Response that exposes Content-Length and
98
115
  // arrayBuffer(). undici Response satisfies both.
116
+ if (!isBoundedBufferResponse(response)) {
117
+ throw new Error(`safeDownload(${options.label}): response is missing headers.get()/arrayBuffer()`);
118
+ }
99
119
  return readBoundedBuffer(response, options.maxBytes, options.label);
100
120
  }
101
121
  //# sourceMappingURL=safeFetch.js.map
@@ -27,7 +27,7 @@ export declare function ensureNestedSchemaTypes(schema: Record<string, unknown>)
27
27
  * 2. AI SDK `jsonSchema()` wrappers (have `.jsonSchema` property) -- extracted directly
28
28
  * 3. Plain JSON Schema objects (have `type`/`properties` but no `_def`) -- returned as-is
29
29
  */
30
- export declare function convertZodToJsonSchema(zodSchema: ZodUnknownSchema, target?: "jsonSchema7" | "openApi3"): object;
30
+ export declare function convertZodToJsonSchema(zodSchema: ZodUnknownSchema | Record<string, unknown>, target?: "jsonSchema7" | "openApi3"): object;
31
31
  export declare function normalizeJsonSchemaObject(schema: Record<string, unknown> | undefined | null): Record<string, unknown>;
32
32
  /**
33
33
  * Normalize a JSON Schema for the OpenAI chat-completions `tools` wire
@@ -308,7 +308,10 @@ export function ensureNestedSchemaTypes(schema) {
308
308
  * 2. AI SDK `jsonSchema()` wrappers (have `.jsonSchema` property) -- extracted directly
309
309
  * 3. Plain JSON Schema objects (have `type`/`properties` but no `_def`) -- returned as-is
310
310
  */
311
- export function convertZodToJsonSchema(zodSchema,
311
+ export function convertZodToJsonSchema(
312
+ // The union mirrors the three documented input shapes: Zod schemas plus
313
+ // plain-object forms (AI SDK `jsonSchema()` wrappers and raw JSON Schema).
314
+ zodSchema,
312
315
  // Default to JSON Schema draft-07 so non-Vertex consumers (Bedrock, MCP
313
316
  // tool registration, etc.) keep their pre-migration dialect. Vertex/Gemini
314
317
  // callers opt into "openApi3" explicitly to get `nullable: true` instead
@@ -360,6 +363,7 @@ target = "jsonSchema7") {
360
363
  try {
361
364
  // Zod 4→3 boundary: zodToJsonSchema types reference Zod 3's ZodSchema via zod/v3.
362
365
  // Runtime compatible — cast through unknown at this third-party boundary only.
366
+ // eslint-disable-next-line no-restricted-syntax -- genuine third-party type-system boundary: zod-to-json-schema's input type is zod/v3's ZodType, structurally incompatible with the Zod 4 schema held here (no overlap, single assertion cannot compile); runtime-compatible fallback contract documented above.
363
367
  const zodV3Schema = zodSchema;
364
368
  const jsonSchema = zodToJsonSchema(zodV3Schema, {
365
369
  name: "ToolParameters",
@@ -368,7 +368,7 @@ export declare function hasJudge(config: WorkflowConfig): boolean;
368
368
  export declare function getAllJudges(config: WorkflowConfig): JudgeConfig[];
369
369
  /**
370
370
  * Calculate estimated workflow cost (placeholder)
371
- * TODO: Implement actual provider-specific pricing
371
+ * TODO(#1179): Implement actual provider-specific pricing
372
372
  * @param config - Workflow configuration
373
373
  * @param estimatedTokens - Estimated number of tokens for the request
374
374
  * @returns Estimated cost in USD
@@ -383,7 +383,7 @@ export function getAllJudges(config) {
383
383
  }
384
384
  /**
385
385
  * Calculate estimated workflow cost (placeholder)
386
- * TODO: Implement actual provider-specific pricing
386
+ * TODO(#1179): Implement actual provider-specific pricing
387
387
  * @param config - Workflow configuration
388
388
  * @param estimatedTokens - Estimated number of tokens for the request
389
389
  * @returns Estimated cost in USD
@@ -10,7 +10,7 @@ const functionTag = "WorkflowRegistry";
10
10
  // ============================================================================
11
11
  /**
12
12
  * In-memory workflow registry
13
- * TODO: Consider persistent storage in future phases
13
+ * TODO(#1179): Consider persistent storage in future phases
14
14
  */
15
15
  const workflowRegistry = new Map();
16
16
  // ============================================================================
@@ -158,7 +158,7 @@ export async function runWorkflow(config, options) {
158
158
  totalInputTokens: calculateInputTokens(ensembleResult.responses),
159
159
  totalOutputTokens: calculateOutputTokens(ensembleResult.responses),
160
160
  totalTokens: calculateTotalTokens(ensembleResult.responses),
161
- byModel: [], // TODO: Populate per-model breakdown
161
+ byModel: [], // TODO(#1179): Populate per-model breakdown
162
162
  },
163
163
  // Additional metadata
164
164
  metadata: options.metadata,
@@ -46,7 +46,7 @@ export declare function calculateModelMetrics(responses: EnsembleResponse[]): Re
46
46
  /**
47
47
  * Calculate consensus level between responses
48
48
  * NOTE: Placeholder implementation - uses response length similarity
49
- * TODO: Implement semantic similarity in Phase 2
49
+ * TODO(#1179): Implement semantic similarity in Phase 2
50
50
  */
51
51
  export declare function calculateConsensus(responses: EnsembleResponse[]): number;
52
52
  /**
@@ -159,7 +159,7 @@ export function calculateModelMetrics(responses) {
159
159
  /**
160
160
  * Calculate consensus level between responses
161
161
  * NOTE: Placeholder implementation - uses response length similarity
162
- * TODO: Implement semantic similarity in Phase 2
162
+ * TODO(#1179): Implement semantic similarity in Phase 2
163
163
  */
164
164
  export function calculateConsensus(responses) {
165
165
  const successful = responses.filter((r) => r.status === "success");
@@ -355,7 +355,7 @@ export function createSelectRequest(message, selectOptions, options) {
355
355
  */
356
356
  export function createFormRequest(message, fields, options) {
357
357
  const requestOptions = {
358
- fields: fields,
358
+ fields,
359
359
  };
360
360
  if (options.submitLabel !== undefined) {
361
361
  requestOptions.submitLabel = options.submitLabel;
@@ -272,7 +272,7 @@ export class MCPRegistryClient extends EventEmitter {
272
272
  if (wellKnown) {
273
273
  return wellKnown;
274
274
  }
275
- // TODO: Fetch from remote registry
275
+ // TODO(#1179): Fetch from remote registry
276
276
  return undefined;
277
277
  }
278
278
  /**