valyu-js 2.5.9 → 2.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -26,6 +26,7 @@ interface SearchOptions {
26
26
  relevanceThreshold?: number;
27
27
  includedSources?: string[];
28
28
  excludeSources?: string[];
29
+ sourceBiases?: Record<string, number>;
29
30
  category?: string;
30
31
  startDate?: string;
31
32
  endDate?: string;
@@ -115,6 +116,7 @@ interface ContentsAsyncJobResponse {
115
116
  jobId: string;
116
117
  status: "pending";
117
118
  urlsTotal: number;
119
+ pollUrl?: string;
118
120
  webhookSecret?: string;
119
121
  txId: string;
120
122
  }
@@ -253,6 +255,7 @@ interface DeepResearchSearchConfig {
253
255
  searchType?: "all" | "web" | "proprietary";
254
256
  includedSources?: string[];
255
257
  excludedSources?: string[];
258
+ sourceBiases?: Record<string, number>;
256
259
  startDate?: string;
257
260
  endDate?: string;
258
261
  category?: string;
@@ -265,6 +268,8 @@ interface DeepResearchCreateOptions {
265
268
  model?: DeepResearchMode;
266
269
  outputFormats?: DeepResearchOutputFormat[];
267
270
  strategy?: string;
271
+ researchStrategy?: string;
272
+ reportFormat?: string;
268
273
  search?: DeepResearchSearchConfig;
269
274
  urls?: string[];
270
275
  files?: FileAttachment[];
@@ -471,6 +476,8 @@ interface BatchTaskInput {
471
476
  query?: string;
472
477
  input?: string;
473
478
  strategy?: string;
479
+ researchStrategy?: string;
480
+ reportFormat?: string;
474
481
  urls?: string[];
475
482
  metadata?: Record<string, string | number | boolean>;
476
483
  }
package/dist/index.d.ts CHANGED
@@ -26,6 +26,7 @@ interface SearchOptions {
26
26
  relevanceThreshold?: number;
27
27
  includedSources?: string[];
28
28
  excludeSources?: string[];
29
+ sourceBiases?: Record<string, number>;
29
30
  category?: string;
30
31
  startDate?: string;
31
32
  endDate?: string;
@@ -115,6 +116,7 @@ interface ContentsAsyncJobResponse {
115
116
  jobId: string;
116
117
  status: "pending";
117
118
  urlsTotal: number;
119
+ pollUrl?: string;
118
120
  webhookSecret?: string;
119
121
  txId: string;
120
122
  }
@@ -253,6 +255,7 @@ interface DeepResearchSearchConfig {
253
255
  searchType?: "all" | "web" | "proprietary";
254
256
  includedSources?: string[];
255
257
  excludedSources?: string[];
258
+ sourceBiases?: Record<string, number>;
256
259
  startDate?: string;
257
260
  endDate?: string;
258
261
  category?: string;
@@ -265,6 +268,8 @@ interface DeepResearchCreateOptions {
265
268
  model?: DeepResearchMode;
266
269
  outputFormats?: DeepResearchOutputFormat[];
267
270
  strategy?: string;
271
+ researchStrategy?: string;
272
+ reportFormat?: string;
268
273
  search?: DeepResearchSearchConfig;
269
274
  urls?: string[];
270
275
  files?: FileAttachment[];
@@ -471,6 +476,8 @@ interface BatchTaskInput {
471
476
  query?: string;
472
477
  input?: string;
473
478
  strategy?: string;
479
+ researchStrategy?: string;
480
+ reportFormat?: string;
474
481
  urls?: string[];
475
482
  metadata?: Record<string, string | number | boolean>;
476
483
  }
package/dist/index.js CHANGED
@@ -60,6 +60,7 @@ function normalizeContentsAsyncJobResponse(api) {
60
60
  jobId: api.job_id ?? api.jobId,
61
61
  status: "pending",
62
62
  urlsTotal: api.urls_total ?? api.urlsTotal ?? 0,
63
+ pollUrl: api.poll_url ?? api.pollUrl,
63
64
  webhookSecret: api.webhook_secret ?? api.webhookSecret,
64
65
  txId: api.tx_id ?? api.txId ?? ""
65
66
  };
@@ -338,6 +339,9 @@ var Valyu = class {
338
339
  if (options.excludeSources !== void 0) {
339
340
  payload.exclude_sources = options.excludeSources;
340
341
  }
342
+ if (options.sourceBiases !== void 0) {
343
+ payload.source_biases = options.sourceBiases;
344
+ }
341
345
  if (options.category !== void 0) {
342
346
  payload.category = options.category;
343
347
  }
@@ -630,6 +634,10 @@ var Valyu = class {
630
634
  code_execution: options.codeExecution !== false
631
635
  };
632
636
  if (options.strategy) payload.strategy = options.strategy;
637
+ if (options.researchStrategy)
638
+ payload.research_strategy = options.researchStrategy;
639
+ if (options.reportFormat)
640
+ payload.report_format = options.reportFormat;
633
641
  if (options.search) {
634
642
  payload.search = {};
635
643
  if (options.search.searchType) {
@@ -641,6 +649,9 @@ var Valyu = class {
641
649
  if (options.search.excludedSources) {
642
650
  payload.search.excluded_sources = options.search.excludedSources;
643
651
  }
652
+ if (options.search.sourceBiases) {
653
+ payload.search.source_biases = options.search.sourceBiases;
654
+ }
644
655
  if (options.search.startDate) {
645
656
  payload.search.start_date = options.search.startDate;
646
657
  }
@@ -937,6 +948,9 @@ var Valyu = class {
937
948
  if (options.search.excludedSources) {
938
949
  payload.search.excluded_sources = options.search.excludedSources;
939
950
  }
951
+ if (options.search.sourceBiases) {
952
+ payload.search.source_biases = options.search.sourceBiases;
953
+ }
940
954
  if (options.search.startDate) {
941
955
  payload.search.start_date = options.search.startDate;
942
956
  }
@@ -1024,6 +1038,10 @@ var Valyu = class {
1024
1038
  }
1025
1039
  if (task.id) taskPayload.id = task.id;
1026
1040
  if (task.strategy) taskPayload.strategy = task.strategy;
1041
+ if (task.researchStrategy)
1042
+ taskPayload.research_strategy = task.researchStrategy;
1043
+ if (task.reportFormat)
1044
+ taskPayload.report_format = task.reportFormat;
1027
1045
  if (task.urls) taskPayload.urls = task.urls;
1028
1046
  if (task.metadata) taskPayload.metadata = task.metadata;
1029
1047
  return taskPayload;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from \"crypto\";\nimport axios from \"axios\";\nimport {\n SearchResponse,\n SearchType,\n SearchOptions,\n ContentsOptions,\n ContentsResponse,\n ContentsAsyncJobResponse,\n ContentsJobResponse,\n ContentsJobWaitOptions,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerStreamChunk,\n SearchResult,\n DeepResearchCreateOptions,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n CreateBatchOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksOptions,\n AddBatchTasksResponse,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DeepResearchBatch,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n\n/** Normalize API job response (snake_case) to SDK format (camelCase). Omits poll_url. */\nfunction normalizeContentsJobResponse(api: Record<string, any>): ContentsJobResponse {\n return {\n success: api.success ?? true,\n jobId: api.job_id ?? api.jobId,\n status: api.status ?? \"pending\",\n urlsTotal: api.urls_total ?? api.urlsTotal ?? 0,\n urlsProcessed: api.urls_processed ?? api.urlsProcessed ?? 0,\n urlsFailed: api.urls_failed ?? api.urlsFailed ?? 0,\n createdAt: api.created_at ?? api.createdAt ?? 0,\n updatedAt: api.updated_at ?? api.updatedAt ?? 0,\n currentBatch: api.current_batch ?? api.currentBatch,\n totalBatches: api.total_batches ?? api.totalBatches,\n results: api.results,\n actualCostDollars: api.actual_cost_dollars ?? api.actualCostDollars,\n error: api.error,\n webhookSecret: api.webhook_secret ?? api.webhookSecret,\n };\n}\n\n/** Normalize API async job creation response (202) to SDK format. */\nfunction normalizeContentsAsyncJobResponse(\n api: Record<string, any>\n): ContentsAsyncJobResponse {\n return {\n success: api.success ?? true,\n jobId: api.job_id ?? api.jobId,\n status: \"pending\",\n urlsTotal: api.urls_total ?? api.urlsTotal ?? 0,\n webhookSecret: api.webhook_secret ?? api.webhookSecret,\n txId: api.tx_id ?? api.txId ?? \"\",\n };\n}\n\n/**\n * Verify webhook signature for Contents API async completion notifications.\n * Use the raw request body (not parsed JSON) as payload.\n * @param payload - Raw request body string\n * @param signature - X-Webhook-Signature header value\n * @param timestamp - X-Webhook-Timestamp header value\n * @param secret - webhookSecret from job creation\n */\nexport function verifyContentsWebhookSignature(\n payload: string,\n signature: string,\n timestamp: string,\n secret: string\n): boolean {\n const expected = createHmac(\"sha256\", secret)\n .update(`${timestamp}.${payload}`)\n .digest(\"hex\");\n const expectedSignature = `sha256=${expected}`;\n if (signature.length !== expectedSignature.length) return false;\n return timingSafeEqual(\n Buffer.from(signature, \"utf8\"),\n Buffer.from(expectedSignature, \"utf8\")\n );\n}\n\n// Valyu API client\nexport class Valyu {\n private baseUrl: string;\n private headers: Record<string, string>;\n\n // DeepResearch namespace\n public deepresearch: {\n create: (\n options: DeepResearchCreateOptions\n ) => Promise<DeepResearchCreateResponse>;\n status: (taskId: string) => Promise<DeepResearchStatusResponse>;\n wait: (\n taskId: string,\n options?: WaitOptions\n ) => Promise<DeepResearchStatusResponse>;\n stream: (taskId: string, callback: StreamCallback) => Promise<void>;\n list: (options: ListOptions) => Promise<DeepResearchListResponse>;\n update: (\n taskId: string,\n instruction: string\n ) => Promise<DeepResearchUpdateResponse>;\n cancel: (taskId: string) => Promise<DeepResearchCancelResponse>;\n delete: (taskId: string) => Promise<DeepResearchDeleteResponse>;\n togglePublic: (\n taskId: string,\n isPublic: boolean\n ) => Promise<DeepResearchTogglePublicResponse>;\n getAssets: (\n taskId: string,\n assetId: string,\n options?: DeepResearchGetAssetsOptions\n ) => Promise<DeepResearchGetAssetsResponse>;\n };\n\n // Batch API namespace\n public batch: {\n create: (options?: CreateBatchOptions) => Promise<CreateBatchResponse>;\n status: (batchId: string) => Promise<BatchStatusResponse>;\n addTasks: (\n batchId: string,\n options: AddBatchTasksOptions\n ) => Promise<AddBatchTasksResponse>;\n listTasks: (\n batchId: string,\n options?: ListBatchTasksOptions\n ) => Promise<ListBatchTasksResponse>;\n cancel: (batchId: string) => Promise<CancelBatchResponse>;\n list: (options?: ListBatchesOptions) => Promise<ListBatchesResponse>;\n waitForCompletion: (\n batchId: string,\n options?: BatchWaitOptions\n ) => Promise<DeepResearchBatch>;\n };\n\n // Datasources API namespace\n public datasources: {\n list: (options?: DatasourcesListOptions) => Promise<DatasourcesListResponse>;\n categories: () => Promise<DatasourcesCategoriesResponse>;\n };\n\n constructor(apiKey?: string, baseUrl: string = \"https://api.valyu.ai/v1\") {\n if (!apiKey) {\n apiKey = process.env.VALYU_API_KEY;\n if (!apiKey) {\n throw new Error(\"VALYU_API_KEY is not set\");\n }\n }\n this.baseUrl = baseUrl;\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n };\n\n // Initialize DeepResearch namespace\n this.deepresearch = {\n create: this._deepresearchCreate.bind(this),\n status: this._deepresearchStatus.bind(this),\n wait: this._deepresearchWait.bind(this),\n stream: this._deepresearchStream.bind(this),\n list: this._deepresearchList.bind(this),\n update: this._deepresearchUpdate.bind(this),\n cancel: this._deepresearchCancel.bind(this),\n delete: this._deepresearchDelete.bind(this),\n togglePublic: this._deepresearchTogglePublic.bind(this),\n getAssets: this._deepresearchGetAssets.bind(this),\n };\n\n // Initialize Batch namespace\n this.batch = {\n create: this._batchCreate.bind(this),\n status: this._batchStatus.bind(this),\n addTasks: this._batchAddTasks.bind(this),\n listTasks: this._batchListTasks.bind(this),\n cancel: this._batchCancel.bind(this),\n list: this._batchList.bind(this),\n waitForCompletion: this._batchWaitForCompletion.bind(this),\n };\n\n // Initialize Datasources namespace\n this.datasources = {\n list: this._datasourcesList.bind(this),\n categories: this._datasourcesCategories.bind(this),\n };\n }\n\n /**\n * Validates date format (YYYY-MM-DD)\n */\n private validateDateFormat(date: string): boolean {\n const dateRegex = /^\\d{4}-\\d{2}-\\d{2}$/;\n if (!dateRegex.test(date)) {\n return false;\n }\n const parsedDate = new Date(date);\n return parsedDate instanceof Date && !isNaN(parsedDate.getTime());\n }\n\n /**\n * Validates if a string is a valid URL\n */\n private validateUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Validates if a string is a valid domain (with optional path)\n */\n private validateDomain(domain: string): boolean {\n // Domain must have at least one dot and valid structure\n // Supports: example.com, example.com/path, subdomain.example.com/path/to/resource\n const domainRegex =\n /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\\/.+)?$/;\n return domainRegex.test(domain);\n }\n\n /**\n * Validates if a string is a valid dataset identifier (provider/datasetname)\n */\n private validateDatasetId(datasetId: string): boolean {\n // Dataset format: provider/datasetname (exactly one slash)\n // Provider and dataset name can contain alphanumeric, hyphens, underscores\n const parts = datasetId.split(\"/\");\n if (parts.length !== 2) return false;\n\n const providerRegex = /^[a-zA-Z0-9_-]+$/;\n const datasetRegex = /^[a-zA-Z0-9_-]+$/;\n\n return (\n providerRegex.test(parts[0]) &&\n datasetRegex.test(parts[1]) &&\n parts[0].length > 0 &&\n parts[1].length > 0\n );\n }\n\n /**\n * Validates source strings (domains, URLs, or dataset IDs)\n */\n private validateSource(source: string): boolean {\n // Check if it's a valid URL\n if (this.validateUrl(source)) {\n return true;\n }\n\n // Check if it's a valid domain (with optional path)\n if (this.validateDomain(source)) {\n return true;\n }\n\n // Check if it's a valid dataset identifier\n if (this.validateDatasetId(source)) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Validates an array of source strings\n */\n private validateSources(sources: string[]): {\n valid: boolean;\n invalidSources: string[];\n } {\n const invalidSources: string[] = [];\n\n for (const source of sources) {\n if (!this.validateSource(source)) {\n invalidSources.push(source);\n }\n }\n\n return {\n valid: invalidSources.length === 0,\n invalidSources,\n };\n }\n\n /**\n * Search for information using the Valyu DeepSearch API\n * @param query - The search query string\n * @param options - Search configuration options\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.maxNumResults - Maximum number of results (1-100)\n * @param options.maxPrice - Maximum price per thousand characters (CPM)\n * @param options.isToolCall - Whether this is a tool call\n * @param options.relevanceThreshold - Minimum relevance score (0-1)\n * @param options.includedSources - List of specific sources to include\n * @param options.excludeSources - List of URLs/domains to exclude from search results\n * @param options.category - Category filter for search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.countryCode - Country code filter for search results\n * @param options.responseLength - Response content length: \"short\"/\"medium\"/\"large\"/\"max\" or integer character count\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.urlOnly - Returns shortened snippets (default: false)\n * @returns Promise resolving to search results\n */\n async search(\n query: string,\n options: SearchOptions = {}\n ): Promise<SearchResponse> {\n try {\n // Default values\n const defaultSearchType: SearchType = \"all\";\n const defaultMaxNumResults = 10;\n const defaultIsToolCall = true;\n const defaultRelevanceThreshold = 0.5;\n\n // Validate searchType\n let finalSearchType: SearchType = defaultSearchType;\n const providedSearchTypeString = options.searchType?.toLowerCase();\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n } else if (options.searchType !== undefined) {\n return {\n success: false,\n error:\n \"Invalid searchType provided. Must be one of: all, web, proprietary, news\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return {\n success: false,\n error: \"Invalid startDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return {\n success: false,\n error: \"Invalid endDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate maxNumResults range\n const maxNumResults = options.maxNumResults ?? defaultMaxNumResults;\n if (maxNumResults < 1 || maxNumResults > 100) {\n return {\n success: false,\n error: \"maxNumResults must be between 1 and 100\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate includedSources format\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return {\n success: false,\n error: \"includedSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const includedSourcesValidation = this.validateSources(\n options.includedSources\n );\n if (!includedSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid includedSources format. Invalid sources: ${includedSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Validate excludeSources format\n if (options.excludeSources !== undefined) {\n if (!Array.isArray(options.excludeSources)) {\n return {\n success: false,\n error: \"excludeSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const excludeSourcesValidation = this.validateSources(\n options.excludeSources\n );\n if (!excludeSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid excludeSources format. Invalid sources: ${excludeSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n query,\n search_type: finalSearchType,\n max_num_results: maxNumResults,\n is_tool_call: options.isToolCall ?? defaultIsToolCall,\n relevance_threshold:\n options.relevanceThreshold ?? defaultRelevanceThreshold,\n };\n\n // Add maxPrice only if explicitly provided\n if (options.maxPrice !== undefined) {\n payload.max_price = options.maxPrice;\n }\n\n // Add optional parameters only if provided\n if (options.includedSources !== undefined) {\n payload.included_sources = options.includedSources;\n }\n\n if (options.excludeSources !== undefined) {\n payload.exclude_sources = options.excludeSources;\n }\n\n if (options.category !== undefined) {\n payload.category = options.category;\n }\n\n if (options.startDate !== undefined) {\n payload.start_date = options.startDate;\n }\n\n if (options.endDate !== undefined) {\n payload.end_date = options.endDate;\n }\n\n if (options.countryCode !== undefined) {\n payload.country_code = options.countryCode;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.fastMode !== undefined) {\n payload.fast_mode = options.fastMode;\n }\n\n if (options.urlOnly !== undefined) {\n payload.url_only = options.urlOnly;\n }\n\n const response = await axios.post(`${this.baseUrl}/deepsearch`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n return response.data;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * Extract content from URLs with optional AI processing\n * @param urls - Array of URLs to process (max 10 sync, max 50 with async: true)\n * @param options - Content extraction configuration options\n * @param options.summary - AI summary configuration: false (raw), true (auto), string (custom), or JSON schema\n * @param options.extractEffort - Extraction thoroughness: \"normal\", \"high\", or \"auto\"\n * @param options.responseLength - Content length per URL\n * @param options.maxPriceDollars - Maximum cost limit in USD\n * @param options.screenshot - Request page screenshots (default: false)\n * @param options.async - Force async processing (required for >10 URLs)\n * @param options.webhookUrl - HTTPS URL for completion notification (async only)\n * @returns Promise resolving to sync results or async job (when async: true or >10 URLs)\n */\n async contents(\n urls: string[],\n options: ContentsOptions = {}\n ): Promise<ContentsResponse | ContentsAsyncJobResponse> {\n try {\n // Validate URLs array\n if (!urls || !Array.isArray(urls)) {\n return {\n success: false,\n error: \"urls must be an array\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length === 0) {\n return {\n success: false,\n error: \"urls array cannot be empty\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n const isAsync = options.async === true || urls.length > 10;\n\n if (urls.length > 10 && !options.async) {\n return {\n success: false,\n error:\n \"Requests with more than 10 URLs require async processing. Add async: true to the request.\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length > 50) {\n return {\n success: false,\n error: \"Maximum 50 URLs allowed per request\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate extractEffort if provided\n if (\n options.extractEffort &&\n ![\"normal\", \"high\", \"auto\"].includes(options.extractEffort)\n ) {\n return {\n success: false,\n error: \"extractEffort must be 'normal', 'high', or 'auto'\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate responseLength if provided\n if (options.responseLength !== undefined) {\n const validLengths = [\"short\", \"medium\", \"large\", \"max\"];\n if (\n typeof options.responseLength === \"string\" &&\n !validLengths.includes(options.responseLength)\n ) {\n return {\n success: false,\n error:\n \"responseLength must be 'short', 'medium', 'large', 'max', or a number\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n if (\n typeof options.responseLength === \"number\" &&\n options.responseLength <= 0\n ) {\n return {\n success: false,\n error: \"responseLength number must be positive\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n urls,\n };\n\n // Add optional parameters only if provided\n if (options.summary !== undefined) {\n payload.summary = options.summary;\n }\n\n if (options.extractEffort !== undefined) {\n payload.extract_effort = options.extractEffort;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.maxPriceDollars !== undefined) {\n payload.max_price_dollars = options.maxPriceDollars;\n }\n\n if (options.screenshot !== undefined) {\n payload.screenshot = options.screenshot;\n }\n\n if (isAsync) {\n payload.async = true;\n }\n if (options.webhookUrl !== undefined) {\n payload.webhook_url = options.webhookUrl;\n }\n\n const response = await axios.post(`${this.baseUrl}/contents`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error || \"Request failed\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // 202 Accepted - async job created\n if (response.status === 202) {\n return normalizeContentsAsyncJobResponse(response.data);\n }\n\n return response.data as ContentsResponse;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * Get async Contents job status and results\n * @param jobId - Job ID from contents() async response\n * @returns Promise resolving to job status\n */\n async getContentsJob(jobId: string): Promise<ContentsJobResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/contents/jobs/${jobId}`,\n { headers: this.headers }\n );\n return normalizeContentsJobResponse(response.data);\n } catch (e: any) {\n const errData = e.response?.data;\n const status = e.response?.status;\n return {\n success: false,\n jobId,\n status: \"failed\",\n urlsTotal: 0,\n urlsProcessed: 0,\n urlsFailed: 0,\n createdAt: 0,\n updatedAt: 0,\n error:\n errData?.error ||\n (status === 403\n ? \"Forbidden - you do not have access to this job\"\n : status === 404\n ? `Job ${jobId} not found`\n : e.message),\n };\n }\n }\n\n /**\n * Wait for async Contents job completion (polls until terminal state)\n * @param jobId - Job ID from contents() async response\n * @param options - Wait configuration (pollInterval, maxWaitTime, onProgress)\n * @returns Promise resolving to final job status with results\n */\n async waitForJob(\n jobId: string,\n options: ContentsJobWaitOptions = {}\n ): Promise<ContentsJobResponse> {\n const pollInterval = options.pollInterval ?? 5000;\n const maxWaitTime = options.maxWaitTime ?? 7200000;\n const startTime = Date.now();\n\n while (true) {\n const status = await this.getContentsJob(jobId);\n\n if (!status.success && status.error) {\n throw new Error(status.error);\n }\n\n if (options.onProgress) {\n options.onProgress(status);\n }\n\n if (\n status.status === \"completed\" ||\n status.status === \"partial\" ||\n status.status === \"failed\"\n ) {\n return status;\n }\n\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * DeepResearch: Create a new research task\n * @param options.search - Search configuration options\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n */\n private async _deepresearchCreate(\n options: DeepResearchCreateOptions\n ): Promise<DeepResearchCreateResponse> {\n try {\n // Use query field (input is supported for backward compatibility)\n const queryValue = options.query ?? options.input;\n\n // Validation\n if (!queryValue?.trim()) {\n return {\n success: false,\n error: \"query is required and cannot be empty\",\n };\n }\n\n // Build payload with snake_case\n // Prefer mode over model (backward compatible)\n const mode = options.mode ?? options.model;\n const payload: Record<string, any> = {\n query: queryValue,\n mode: mode || \"fast\", // API defaults to \"standard\", but we keep \"fast\" for backward compatibility\n output_formats: options.outputFormats || [\"markdown\"],\n code_execution: options.codeExecution !== false,\n };\n\n // Add optional fields\n if (options.strategy) payload.strategy = options.strategy;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.urls) payload.urls = options.urls;\n if (options.files) payload.files = options.files;\n if (options.deliverables) payload.deliverables = options.deliverables;\n if (options.mcpServers) payload.mcp_servers = options.mcpServers;\n if (options.previousReports) {\n payload.previous_reports = options.previousReports;\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.brandCollectionId)\n payload.brand_collection_id = options.brandCollectionId;\n if (options.alertEmail) {\n if (typeof options.alertEmail === \"string\") {\n payload.alert_email = options.alertEmail;\n } else {\n payload.alert_email = {\n email: options.alertEmail.email,\n custom_url: options.alertEmail.custom_url,\n };\n }\n }\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task status\n */\n private async _deepresearchStatus(\n taskId: string\n ): Promise<DeepResearchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/status`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Wait for task completion with polling\n */\n private async _deepresearchWait(\n taskId: string,\n options: WaitOptions = {}\n ): Promise<DeepResearchStatusResponse> {\n const pollInterval = options.pollInterval || 5000;\n const maxWaitTime = options.maxWaitTime || 7200000;\n const startTime = Date.now();\n\n while (true) {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n throw new Error(status.error);\n }\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(status);\n }\n\n // Terminal states\n if (\n status.status === \"completed\" ||\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n return status;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * DeepResearch: Stream real-time updates\n */\n private async _deepresearchStream(\n taskId: string,\n callback: StreamCallback\n ): Promise<void> {\n let isComplete = false;\n let lastMessageCount = 0;\n\n while (!isComplete) {\n try {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n if (callback.onError) {\n callback.onError(new Error(status.error));\n }\n return;\n }\n\n // Progress updates\n if (status.progress && callback.onProgress) {\n callback.onProgress(\n status.progress.current_step,\n status.progress.total_steps\n );\n }\n\n // New messages\n if (status.messages && callback.onMessage) {\n const newMessages = status.messages.slice(lastMessageCount);\n newMessages.forEach((msg) => callback.onMessage!(msg));\n lastMessageCount = status.messages.length;\n }\n\n // Terminal states\n if (status.status === \"completed\") {\n if (callback.onComplete) {\n callback.onComplete(status);\n }\n isComplete = true;\n } else if (\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n if (callback.onError) {\n callback.onError(\n new Error(status.error || `Task ${status.status}`)\n );\n }\n isComplete = true;\n }\n\n if (!isComplete) {\n await new Promise((resolve) => setTimeout(resolve, 5000));\n }\n } catch (error: any) {\n if (callback.onError) {\n callback.onError(error);\n }\n throw error;\n }\n }\n }\n\n /**\n * DeepResearch: List all tasks\n */\n private async _deepresearchList(\n options?: ListOptions\n ): Promise<DeepResearchListResponse> {\n try {\n const limit = options?.limit || 10;\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/list?limit=${limit}`,\n { headers: this.headers }\n );\n\n return { success: true, data: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Add follow-up instruction\n */\n private async _deepresearchUpdate(\n taskId: string,\n instruction: string\n ): Promise<DeepResearchUpdateResponse> {\n try {\n if (!instruction?.trim()) {\n return {\n success: false,\n error: \"instruction is required and cannot be empty\",\n };\n }\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/update`,\n { instruction },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Cancel task\n */\n private async _deepresearchCancel(\n taskId: string\n ): Promise<DeepResearchCancelResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Delete task\n */\n private async _deepresearchDelete(\n taskId: string\n ): Promise<DeepResearchDeleteResponse> {\n try {\n const response = await axios.delete(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/delete`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Toggle public flag\n */\n private async _deepresearchTogglePublic(\n taskId: string,\n isPublic: boolean\n ): Promise<DeepResearchTogglePublicResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/public`,\n { public: isPublic },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task assets (images, deliverables, PDFs)\n */\n private async _deepresearchGetAssets(\n taskId: string,\n assetId: string,\n options: DeepResearchGetAssetsOptions = {}\n ): Promise<DeepResearchGetAssetsResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.token) {\n params.append(\"token\", options.token);\n }\n\n // Build headers - use API key if no token provided\n const headers: Record<string, string> = {};\n if (!options.token) {\n headers[\"x-api-key\"] = this.headers[\"x-api-key\"];\n }\n\n const url = `${\n this.baseUrl\n }/deepresearch/tasks/${taskId}/assets/${assetId}${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n\n const response = await axios.get(url, {\n headers,\n responseType: \"arraybuffer\", // For binary data\n });\n\n return {\n success: true,\n data: Buffer.from(response.data),\n contentType:\n response.headers[\"content-type\"] || \"application/octet-stream\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Create a new batch\n * @param options - Batch configuration options\n * @param options.name - Optional name for the batch\n * @param options.model - DeepResearch mode: \"fast\", \"standard\", or \"heavy\" (default: \"standard\")\n * @param options.outputFormats - Output formats for tasks (default: [\"markdown\"])\n * @param options.search - Search configuration for all tasks in batch\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n * @param options.webhookUrl - Optional HTTPS URL for completion notification\n * @param options.metadata - Optional metadata key-value pairs\n * @returns Promise resolving to batch creation response with batch_id and webhook_secret\n */\n private async _batchCreate(\n options: CreateBatchOptions = {}\n ): Promise<CreateBatchResponse> {\n try {\n const payload: Record<string, any> = {};\n\n if (options.name) payload.name = options.name;\n // Accept both mode (preferred) and model (backward compatible)\n const mode = options.mode ?? options.model;\n if (mode) payload.mode = mode;\n if (options.outputFormats) payload.output_formats = options.outputFormats;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Get batch status\n * @param batchId - The batch ID to query\n * @returns Promise resolving to batch status with counts and usage\n */\n private async _batchStatus(batchId: string): Promise<BatchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/batches/${batchId}`,\n { headers: this.headers }\n );\n\n return { success: true, batch: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Add tasks to a batch\n * @param batchId - The batch ID to add tasks to\n * @param options - Task configuration options\n * @param options.tasks - Array of task inputs (use 'query' field for each task)\n * @returns Promise resolving to response with added, tasks array, counts, and batch_id\n */\n private async _batchAddTasks(\n batchId: string,\n options: AddBatchTasksOptions\n ): Promise<AddBatchTasksResponse> {\n try {\n if (!options.tasks || !Array.isArray(options.tasks)) {\n return {\n success: false,\n error: \"tasks must be an array\",\n };\n }\n\n if (options.tasks.length === 0) {\n return {\n success: false,\n error: \"tasks array cannot be empty\",\n };\n }\n\n if (options.tasks.length > 100) {\n return {\n success: false,\n error: \"Maximum 100 tasks allowed per request\",\n };\n }\n\n // Validate that each task has a query\n for (const task of options.tasks) {\n if (!task.query && !task.input) {\n return {\n success: false,\n error: \"Each task must have a 'query' field\",\n };\n }\n }\n\n // Convert tasks to snake_case format for API\n // Note: Tasks can only include: id, query, strategy, urls, metadata\n // Tasks inherit model, output_formats, and search_params from batch\n const tasksPayload = options.tasks.map((task) => {\n const taskPayload: Record<string, any> = {};\n\n // Use query field (input is supported for backward compatibility)\n const queryValue = task.query ?? task.input;\n if (queryValue) {\n taskPayload.query = queryValue;\n }\n\n if (task.id) taskPayload.id = task.id;\n if (task.strategy) taskPayload.strategy = task.strategy;\n if (task.urls) taskPayload.urls = task.urls;\n if (task.metadata) taskPayload.metadata = task.metadata;\n\n return taskPayload;\n });\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/tasks`,\n { tasks: tasksPayload },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all tasks in a batch\n * @param batchId - The batch ID to query\n * @param options - Optional pagination and filtering options\n * @param options.status - Filter by status: \"queued\", \"running\", \"completed\", \"failed\", or \"cancelled\"\n * @param options.limit - Maximum number of tasks to return\n * @param options.lastKey - Pagination token from previous response\n * @returns Promise resolving to list of tasks with their status and pagination info\n */\n private async _batchListTasks(\n batchId: string,\n options: ListBatchTasksOptions = {}\n ): Promise<ListBatchTasksResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.status) {\n params.append(\"status\", options.status);\n }\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n if (options.lastKey) {\n params.append(\"last_key\", options.lastKey);\n }\n if (options.includeOutput !== undefined) {\n params.append(\"include_output\", options.includeOutput.toString());\n }\n\n const url = `${this.baseUrl}/deepresearch/batches/${batchId}/tasks${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Cancel a batch and all its pending tasks\n * @param batchId - The batch ID to cancel\n * @returns Promise resolving to cancellation confirmation\n */\n private async _batchCancel(batchId: string): Promise<CancelBatchResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all batches\n * @param options - Optional options\n * @param options.limit - Maximum number of batches to return\n * @returns Promise resolving to list of all batches\n */\n private async _batchList(\n options: ListBatchesOptions = {}\n ): Promise<ListBatchesResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n\n const url = `${this.baseUrl}/deepresearch/batches${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, {\n headers: this.headers,\n });\n\n return { success: true, batches: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Wait for batch completion with polling\n * @param batchId - The batch ID to wait for\n * @param options - Wait configuration options\n * @param options.pollInterval - Polling interval in milliseconds (default: 10000)\n * @param options.maxWaitTime - Maximum wait time in milliseconds (default: 7200000)\n * @param options.onProgress - Callback for progress updates\n * @returns Promise resolving to final batch status\n */\n private async _batchWaitForCompletion(\n batchId: string,\n options: BatchWaitOptions = {}\n ): Promise<DeepResearchBatch> {\n const pollInterval = options.pollInterval || 10000; // 10 seconds default\n const maxWaitTime = options.maxWaitTime || 7200000; // 2 hours default\n const startTime = Date.now();\n\n while (true) {\n const statusResponse = await this._batchStatus(batchId);\n\n if (!statusResponse.success || !statusResponse.batch) {\n throw new Error(statusResponse.error || \"Failed to get batch status\");\n }\n\n const batch = statusResponse.batch;\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(batch);\n }\n\n // Terminal states\n if (\n batch.status === \"completed\" ||\n batch.status === \"completed_with_errors\" ||\n batch.status === \"cancelled\"\n ) {\n return batch;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * Get AI-powered answers using the Valyu Answer API\n * @param query - The question or query string\n * @param options - Answer configuration options\n * @param options.structuredOutput - JSON Schema object for structured responses\n * @param options.systemInstructions - Custom system-level instructions (max 2000 chars)\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.dataMaxPrice - Maximum spend (USD) for data retrieval\n * @param options.countryCode - Country code filter for search results\n * @param options.includedSources - List of specific sources to include\n * @param options.excludedSources - List of URLs/domains to exclude from search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.streaming - Enable streaming mode (default: false)\n * @returns Promise resolving to answer response, or AsyncGenerator for streaming\n */\n async answer(\n query: string,\n options: AnswerOptions = {}\n ): Promise<\n AnswerResponse | AsyncGenerator<AnswerStreamChunk, void, unknown>\n > {\n // Validate inputs first\n const validationError = this.validateAnswerParams(query, options);\n if (validationError) {\n if (options.streaming) {\n return this.createErrorGenerator(validationError);\n }\n return { success: false, error: validationError };\n }\n\n const payload = this.buildAnswerPayload(query, options);\n\n if (options.streaming) {\n return this.streamAnswer(payload);\n } else {\n return this.fetchAnswer(payload);\n }\n }\n\n /**\n * Validate answer parameters\n */\n private validateAnswerParams(\n query: string,\n options: AnswerOptions\n ): string | null {\n // Validate query\n if (!query || typeof query !== \"string\" || query.trim().length === 0) {\n return \"Query is required and must be a non-empty string\";\n }\n\n // Validate searchType\n const providedSearchTypeString = options.searchType?.toLowerCase();\n if (\n providedSearchTypeString !== undefined &&\n providedSearchTypeString !== \"web\" &&\n providedSearchTypeString !== \"proprietary\" &&\n providedSearchTypeString !== \"all\" &&\n providedSearchTypeString !== \"news\"\n ) {\n return \"Invalid searchType provided. Must be one of: all, web, proprietary, news\";\n }\n\n // Validate systemInstructions\n if (options.systemInstructions !== undefined) {\n if (typeof options.systemInstructions !== \"string\") {\n return \"systemInstructions must be a string\";\n }\n const trimmed = options.systemInstructions.trim();\n if (trimmed.length === 0) {\n return \"systemInstructions cannot be empty when provided\";\n }\n if (trimmed.length > 2000) {\n return \"systemInstructions must be 2000 characters or less\";\n }\n }\n\n // Validate dataMaxPrice\n if (options.dataMaxPrice !== undefined) {\n if (\n typeof options.dataMaxPrice !== \"number\" ||\n options.dataMaxPrice <= 0\n ) {\n return \"dataMaxPrice must be a positive number\";\n }\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return \"Invalid startDate format. Must be YYYY-MM-DD\";\n }\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return \"Invalid endDate format. Must be YYYY-MM-DD\";\n }\n if (options.startDate && options.endDate) {\n const startDate = new Date(options.startDate);\n const endDate = new Date(options.endDate);\n if (startDate > endDate) {\n return \"startDate must be before endDate\";\n }\n }\n\n // Validate sources\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return \"includedSources must be an array\";\n }\n const validation = this.validateSources(options.includedSources);\n if (!validation.valid) {\n return `Invalid includedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n if (options.excludedSources !== undefined) {\n if (!Array.isArray(options.excludedSources)) {\n return \"excludedSources must be an array\";\n }\n const validation = this.validateSources(options.excludedSources);\n if (!validation.valid) {\n return `Invalid excludedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n\n return null;\n }\n\n /**\n * Build payload for answer API\n */\n private buildAnswerPayload(\n query: string,\n options: AnswerOptions\n ): Record<string, any> {\n const defaultSearchType: SearchType = \"all\";\n const providedSearchTypeString = options.searchType?.toLowerCase();\n let finalSearchType: SearchType = defaultSearchType;\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n }\n\n const payload: Record<string, any> = {\n query: query.trim(),\n search_type: finalSearchType,\n };\n\n if (options.dataMaxPrice !== undefined)\n payload.data_max_price = options.dataMaxPrice;\n if (options.structuredOutput !== undefined)\n payload.structured_output = options.structuredOutput;\n if (options.systemInstructions !== undefined)\n payload.system_instructions = options.systemInstructions.trim();\n if (options.countryCode !== undefined)\n payload.country_code = options.countryCode;\n if (options.includedSources !== undefined)\n payload.included_sources = options.includedSources;\n if (options.excludedSources !== undefined)\n payload.excluded_sources = options.excludedSources;\n if (options.startDate !== undefined) payload.start_date = options.startDate;\n if (options.endDate !== undefined) payload.end_date = options.endDate;\n if (options.fastMode !== undefined) payload.fast_mode = options.fastMode;\n\n return payload;\n }\n\n /**\n * Fetch answer (non-streaming mode)\n */\n private async fetchAnswer(\n payload: Record<string, any>\n ): Promise<AnswerResponse> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n return {\n success: false,\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n }\n\n // Collect streamed data into final response\n let fullContent = \"\";\n let searchResults: SearchResult[] = [];\n let finalMetadata: any = {};\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (reader) {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") continue;\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && !parsed.success) {\n searchResults = [...searchResults, ...parsed.search_results];\n }\n // Handle content chunks\n else if (parsed.choices) {\n const content = parsed.choices[0]?.delta?.content || \"\";\n if (content) fullContent += content;\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n finalMetadata = parsed;\n }\n } catch {\n continue;\n }\n }\n }\n }\n\n // Build final response\n if (finalMetadata.success) {\n const finalSearchResults =\n finalMetadata.search_results || searchResults;\n const response: AnswerSuccessResponse = {\n success: true,\n tx_id: finalMetadata.tx_id || \"\",\n original_query: finalMetadata.original_query || payload.query,\n contents: finalMetadata.contents || fullContent || \"\",\n search_results: finalSearchResults,\n search_metadata: finalMetadata.search_metadata || {\n tx_ids: [],\n number_of_results: 0,\n total_characters: 0,\n },\n ai_usage: finalMetadata.ai_usage || {\n input_tokens: 0,\n output_tokens: 0,\n },\n cost: finalMetadata.cost || {\n total_deduction_dollars: 0,\n search_deduction_dollars: 0,\n ai_deduction_dollars: 0,\n },\n };\n if (finalMetadata.extraction_metadata) {\n response.extraction_metadata = finalMetadata.extraction_metadata;\n }\n return response;\n }\n\n return {\n success: false,\n error: finalMetadata.error || \"Unknown error occurred\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.message || \"Request failed\",\n };\n }\n }\n\n /**\n * Stream answer using SSE\n */\n private async *streamAnswer(\n payload: Record<string, any>\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n yield {\n type: \"error\",\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (!reader) {\n yield { type: \"error\", error: \"No response body\" };\n return;\n }\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") {\n yield { type: \"done\" };\n continue;\n }\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && parsed.success === undefined) {\n yield {\n type: \"search_results\",\n search_results: parsed.search_results,\n };\n }\n // Handle content chunks\n else if (parsed.choices) {\n const delta = parsed.choices[0]?.delta || {};\n const content = delta.content || \"\";\n const finishReason = parsed.choices[0]?.finish_reason;\n\n if (content || finishReason) {\n yield { type: \"content\", content, finish_reason: finishReason };\n }\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n yield {\n type: \"metadata\",\n tx_id: parsed.tx_id,\n original_query: parsed.original_query,\n contents: parsed.contents,\n search_results: parsed.search_results,\n search_metadata: parsed.search_metadata,\n ai_usage: parsed.ai_usage,\n cost: parsed.cost,\n extraction_metadata: parsed.extraction_metadata,\n };\n }\n } catch {\n continue;\n }\n }\n }\n } catch (e: any) {\n yield { type: \"error\", error: e.message || \"Stream failed\" };\n }\n }\n\n /**\n * Create an error generator for streaming errors\n */\n private async *createErrorGenerator(\n error: string\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n yield { type: \"error\", error };\n }\n\n /**\n * Datasources: List all available datasources\n * @param options - Optional filter options\n * @param options.category - Filter by category (e.g., \"research\", \"markets\", \"healthcare\")\n * @returns Promise resolving to list of datasources with their metadata\n */\n private async _datasourcesList(\n options: DatasourcesListOptions = {}\n ): Promise<DatasourcesListResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.category) {\n params.append(\"category\", options.category);\n }\n\n const url = `${this.baseUrl}/datasources${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, datasources: response.data.datasources };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Datasources: Get all available categories\n * @returns Promise resolving to list of categories with their metadata\n */\n private async _datasourcesCategories(): Promise<DatasourcesCategoriesResponse> {\n try {\n const response = await axios.get(`${this.baseUrl}/datasources/categories`, {\n headers: this.headers,\n });\n\n return { success: true, categories: response.data.categories };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n}\n\nexport type {\n SearchResponse,\n SearchType,\n SearchResult,\n FeedbackSentiment,\n FeedbackResponse,\n SearchOptions,\n CountryCode,\n ResponseLength,\n ContentsOptions,\n ContentsResponse,\n ContentsAsyncJobResponse,\n ContentsJobResponse,\n ContentsJobStatus,\n ContentsJobWaitOptions,\n ContentResult,\n ContentResultSuccess,\n ContentResultFailed,\n ExtractEffort,\n ContentResponseLength,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerErrorResponse,\n AnswerStreamChunk,\n AnswerStreamChunkType,\n SearchMetadata,\n AIUsage,\n Cost,\n ExtractionMetadata,\n AlertEmailConfig,\n DeepResearchMode,\n DeepResearchStatus,\n DeepResearchOutputFormat,\n ImageType,\n ChartType,\n FileAttachment,\n MCPServerConfig,\n DeepResearchSearchConfig,\n DeepResearchCreateOptions,\n Progress,\n ChartDataPoint,\n ChartDataSeries,\n ImageMetadata,\n DeepResearchSource,\n DeepResearchUsage,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchTaskListItem,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n BatchStatus,\n BatchCounts,\n DeepResearchBatch,\n CreateBatchOptions,\n BatchTaskInput,\n AddBatchTasksOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksResponse,\n BatchTaskCreated,\n BatchTaskListItem,\n BatchPagination,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DatasourceCategoryId,\n DatasourceModality,\n DatasourcePricing,\n DatasourceCoverage,\n Datasource,\n DatasourceCategory,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA4C;AAC5C,mBAAkB;AA8ClB,SAAS,6BAA6B,KAA+C;AACnF,SAAO;AAAA,IACL,SAAS,IAAI,WAAW;AAAA,IACxB,OAAO,IAAI,UAAU,IAAI;AAAA,IACzB,QAAQ,IAAI,UAAU;AAAA,IACtB,WAAW,IAAI,cAAc,IAAI,aAAa;AAAA,IAC9C,eAAe,IAAI,kBAAkB,IAAI,iBAAiB;AAAA,IAC1D,YAAY,IAAI,eAAe,IAAI,cAAc;AAAA,IACjD,WAAW,IAAI,cAAc,IAAI,aAAa;AAAA,IAC9C,WAAW,IAAI,cAAc,IAAI,aAAa;AAAA,IAC9C,cAAc,IAAI,iBAAiB,IAAI;AAAA,IACvC,cAAc,IAAI,iBAAiB,IAAI;AAAA,IACvC,SAAS,IAAI;AAAA,IACb,mBAAmB,IAAI,uBAAuB,IAAI;AAAA,IAClD,OAAO,IAAI;AAAA,IACX,eAAe,IAAI,kBAAkB,IAAI;AAAA,EAC3C;AACF;AAGA,SAAS,kCACP,KAC0B;AAC1B,SAAO;AAAA,IACL,SAAS,IAAI,WAAW;AAAA,IACxB,OAAO,IAAI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AO,SAAS,IAAI,IAAI,OAAO,SAAS,CAAC,KAAK,EAChD;AACA,YAAM,WAAW,MAAM,aAAAD,QAAM,IAAI,KAAK,EAAE,SAAS,KAAK,QAAQ,CAAC;AAE/D,aAAO,EAAE,SAAS,MAAM,aAAa,SAAS,KAAK,YAAY;AAAA,IACjE,SAAS,GAAQ;AACf,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,EAAE,UAAU,MAAM,SAAS,EAAE;AAAA,MACtC;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,yBAAiE;AAC7E,QAAI;AACF,YAAM,WAAW,MAAM,aAAAA,QAAM,IAAI,GAAG,KAAK,OAAO,2BAA2B;AAAA,QACzE,SAAS,KAAK;AAAA,MAChB,CAAC;AAED,aAAO,EAAE,SAAS,MAAM,YAAY,SAAS,KAAK,WAAW;AAAA,IAC/D,SAAS,GAAQ;AACf,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,EAAE,UAAU,MAAM,SAAS,EAAE;AAAA,MACtC;AAAA,IACF;AAAA,EACF;AACF;","names":["axios","response"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from \"crypto\";\nimport axios from \"axios\";\nimport {\n SearchResponse,\n SearchType,\n SearchOptions,\n ContentsOptions,\n ContentsResponse,\n ContentsAsyncJobResponse,\n ContentsJobResponse,\n ContentsJobWaitOptions,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerStreamChunk,\n SearchResult,\n DeepResearchCreateOptions,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n CreateBatchOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksOptions,\n AddBatchTasksResponse,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DeepResearchBatch,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n\n/** Normalize API job response (snake_case) to SDK format (camelCase). */\nfunction normalizeContentsJobResponse(api: Record<string, any>): ContentsJobResponse {\n return {\n success: api.success ?? true,\n jobId: api.job_id ?? api.jobId,\n status: api.status ?? \"pending\",\n urlsTotal: api.urls_total ?? api.urlsTotal ?? 0,\n urlsProcessed: api.urls_processed ?? api.urlsProcessed ?? 0,\n urlsFailed: api.urls_failed ?? api.urlsFailed ?? 0,\n createdAt: api.created_at ?? api.createdAt ?? 0,\n updatedAt: api.updated_at ?? api.updatedAt ?? 0,\n currentBatch: api.current_batch ?? api.currentBatch,\n totalBatches: api.total_batches ?? api.totalBatches,\n results: api.results,\n actualCostDollars: api.actual_cost_dollars ?? api.actualCostDollars,\n error: api.error,\n webhookSecret: api.webhook_secret ?? api.webhookSecret,\n };\n}\n\n/** Normalize API async job creation response (202) to SDK format. */\nfunction normalizeContentsAsyncJobResponse(\n api: Record<string, any>\n): ContentsAsyncJobResponse {\n return {\n success: api.success ?? true,\n jobId: api.job_id ?? api.jobId,\n status: \"pending\",\n urlsTotal: api.urls_total ?? api.urlsTotal ?? 0,\n pollUrl: api.poll_url ?? api.pollUrl,\n webhookSecret: api.webhook_secret ?? api.webhookSecret,\n txId: api.tx_id ?? api.txId ?? \"\",\n };\n}\n\n/**\n * Verify webhook signature for Contents API async completion notifications.\n * Use the raw request body (not parsed JSON) as payload.\n * @param payload - Raw request body string\n * @param signature - X-Webhook-Signature header value\n * @param timestamp - X-Webhook-Timestamp header value\n * @param secret - webhookSecret from job creation\n */\nexport function verifyContentsWebhookSignature(\n payload: string,\n signature: string,\n timestamp: string,\n secret: string\n): boolean {\n const expected = createHmac(\"sha256\", secret)\n .update(`${timestamp}.${payload}`)\n .digest(\"hex\");\n const expectedSignature = `sha256=${expected}`;\n if (signature.length !== expectedSignature.length) return false;\n return timingSafeEqual(\n Buffer.from(signature, \"utf8\"),\n Buffer.from(expectedSignature, \"utf8\")\n );\n}\n\n// Valyu API client\nexport class Valyu {\n private baseUrl: string;\n private headers: Record<string, string>;\n\n // DeepResearch namespace\n public deepresearch: {\n create: (\n options: DeepResearchCreateOptions\n ) => Promise<DeepResearchCreateResponse>;\n status: (taskId: string) => Promise<DeepResearchStatusResponse>;\n wait: (\n taskId: string,\n options?: WaitOptions\n ) => Promise<DeepResearchStatusResponse>;\n stream: (taskId: string, callback: StreamCallback) => Promise<void>;\n list: (options: ListOptions) => Promise<DeepResearchListResponse>;\n update: (\n taskId: string,\n instruction: string\n ) => Promise<DeepResearchUpdateResponse>;\n cancel: (taskId: string) => Promise<DeepResearchCancelResponse>;\n delete: (taskId: string) => Promise<DeepResearchDeleteResponse>;\n togglePublic: (\n taskId: string,\n isPublic: boolean\n ) => Promise<DeepResearchTogglePublicResponse>;\n getAssets: (\n taskId: string,\n assetId: string,\n options?: DeepResearchGetAssetsOptions\n ) => Promise<DeepResearchGetAssetsResponse>;\n };\n\n // Batch API namespace\n public batch: {\n create: (options?: CreateBatchOptions) => Promise<CreateBatchResponse>;\n status: (batchId: string) => Promise<BatchStatusResponse>;\n addTasks: (\n batchId: string,\n options: AddBatchTasksOptions\n ) => Promise<AddBatchTasksResponse>;\n listTasks: (\n batchId: string,\n options?: ListBatchTasksOptions\n ) => Promise<ListBatchTasksResponse>;\n cancel: (batchId: string) => Promise<CancelBatchResponse>;\n list: (options?: ListBatchesOptions) => Promise<ListBatchesResponse>;\n waitForCompletion: (\n batchId: string,\n options?: BatchWaitOptions\n ) => Promise<DeepResearchBatch>;\n };\n\n // Datasources API namespace\n public datasources: {\n list: (options?: DatasourcesListOptions) => Promise<DatasourcesListResponse>;\n categories: () => Promise<DatasourcesCategoriesResponse>;\n };\n\n constructor(apiKey?: string, baseUrl: string = \"https://api.valyu.ai/v1\") {\n if (!apiKey) {\n apiKey = process.env.VALYU_API_KEY;\n if (!apiKey) {\n throw new Error(\"VALYU_API_KEY is not set\");\n }\n }\n this.baseUrl = baseUrl;\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n };\n\n // Initialize DeepResearch namespace\n this.deepresearch = {\n create: this._deepresearchCreate.bind(this),\n status: this._deepresearchStatus.bind(this),\n wait: this._deepresearchWait.bind(this),\n stream: this._deepresearchStream.bind(this),\n list: this._deepresearchList.bind(this),\n update: this._deepresearchUpdate.bind(this),\n cancel: this._deepresearchCancel.bind(this),\n delete: this._deepresearchDelete.bind(this),\n togglePublic: this._deepresearchTogglePublic.bind(this),\n getAssets: this._deepresearchGetAssets.bind(this),\n };\n\n // Initialize Batch namespace\n this.batch = {\n create: this._batchCreate.bind(this),\n status: this._batchStatus.bind(this),\n addTasks: this._batchAddTasks.bind(this),\n listTasks: this._batchListTasks.bind(this),\n cancel: this._batchCancel.bind(this),\n list: this._batchList.bind(this),\n waitForCompletion: this._batchWaitForCompletion.bind(this),\n };\n\n // Initialize Datasources namespace\n this.datasources = {\n list: this._datasourcesList.bind(this),\n categories: this._datasourcesCategories.bind(this),\n };\n }\n\n /**\n * Validates date format (YYYY-MM-DD)\n */\n private validateDateFormat(date: string): boolean {\n const dateRegex = /^\\d{4}-\\d{2}-\\d{2}$/;\n if (!dateRegex.test(date)) {\n return false;\n }\n const parsedDate = new Date(date);\n return parsedDate instanceof Date && !isNaN(parsedDate.getTime());\n }\n\n /**\n * Validates if a string is a valid URL\n */\n private validateUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Validates if a string is a valid domain (with optional path)\n */\n private validateDomain(domain: string): boolean {\n // Domain must have at least one dot and valid structure\n // Supports: example.com, example.com/path, subdomain.example.com/path/to/resource\n const domainRegex =\n /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\\/.+)?$/;\n return domainRegex.test(domain);\n }\n\n /**\n * Validates if a string is a valid dataset identifier (provider/datasetname)\n */\n private validateDatasetId(datasetId: string): boolean {\n // Dataset format: provider/datasetname (exactly one slash)\n // Provider and dataset name can contain alphanumeric, hyphens, underscores\n const parts = datasetId.split(\"/\");\n if (parts.length !== 2) return false;\n\n const providerRegex = /^[a-zA-Z0-9_-]+$/;\n const datasetRegex = /^[a-zA-Z0-9_-]+$/;\n\n return (\n providerRegex.test(parts[0]) &&\n datasetRegex.test(parts[1]) &&\n parts[0].length > 0 &&\n parts[1].length > 0\n );\n }\n\n /**\n * Validates source strings (domains, URLs, or dataset IDs)\n */\n private validateSource(source: string): boolean {\n // Check if it's a valid URL\n if (this.validateUrl(source)) {\n return true;\n }\n\n // Check if it's a valid domain (with optional path)\n if (this.validateDomain(source)) {\n return true;\n }\n\n // Check if it's a valid dataset identifier\n if (this.validateDatasetId(source)) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Validates an array of source strings\n */\n private validateSources(sources: string[]): {\n valid: boolean;\n invalidSources: string[];\n } {\n const invalidSources: string[] = [];\n\n for (const source of sources) {\n if (!this.validateSource(source)) {\n invalidSources.push(source);\n }\n }\n\n return {\n valid: invalidSources.length === 0,\n invalidSources,\n };\n }\n\n /**\n * Search for information using the Valyu DeepSearch API\n * @param query - The search query string\n * @param options - Search configuration options\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.maxNumResults - Maximum number of results (1-100)\n * @param options.maxPrice - Maximum price per thousand characters (CPM)\n * @param options.isToolCall - Whether this is a tool call\n * @param options.relevanceThreshold - Minimum relevance score (0-1)\n * @param options.includedSources - List of specific sources to include\n * @param options.excludeSources - List of URLs/domains to exclude from search results\n * @param options.category - Category filter for search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.countryCode - Country code filter for search results\n * @param options.responseLength - Response content length: \"short\"/\"medium\"/\"large\"/\"max\" or integer character count\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.urlOnly - Returns shortened snippets (default: false)\n * @returns Promise resolving to search results\n */\n async search(\n query: string,\n options: SearchOptions = {}\n ): Promise<SearchResponse> {\n try {\n // Default values\n const defaultSearchType: SearchType = \"all\";\n const defaultMaxNumResults = 10;\n const defaultIsToolCall = true;\n const defaultRelevanceThreshold = 0.5;\n\n // Validate searchType\n let finalSearchType: SearchType = defaultSearchType;\n const providedSearchTypeString = options.searchType?.toLowerCase();\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n } else if (options.searchType !== undefined) {\n return {\n success: false,\n error:\n \"Invalid searchType provided. Must be one of: all, web, proprietary, news\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return {\n success: false,\n error: \"Invalid startDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return {\n success: false,\n error: \"Invalid endDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate maxNumResults range\n const maxNumResults = options.maxNumResults ?? defaultMaxNumResults;\n if (maxNumResults < 1 || maxNumResults > 100) {\n return {\n success: false,\n error: \"maxNumResults must be between 1 and 100\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate includedSources format\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return {\n success: false,\n error: \"includedSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const includedSourcesValidation = this.validateSources(\n options.includedSources\n );\n if (!includedSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid includedSources format. Invalid sources: ${includedSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Validate excludeSources format\n if (options.excludeSources !== undefined) {\n if (!Array.isArray(options.excludeSources)) {\n return {\n success: false,\n error: \"excludeSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const excludeSourcesValidation = this.validateSources(\n options.excludeSources\n );\n if (!excludeSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid excludeSources format. Invalid sources: ${excludeSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n query,\n search_type: finalSearchType,\n max_num_results: maxNumResults,\n is_tool_call: options.isToolCall ?? defaultIsToolCall,\n relevance_threshold:\n options.relevanceThreshold ?? defaultRelevanceThreshold,\n };\n\n // Add maxPrice only if explicitly provided\n if (options.maxPrice !== undefined) {\n payload.max_price = options.maxPrice;\n }\n\n // Add optional parameters only if provided\n if (options.includedSources !== undefined) {\n payload.included_sources = options.includedSources;\n }\n\n if (options.excludeSources !== undefined) {\n payload.exclude_sources = options.excludeSources;\n }\n\n if (options.sourceBiases !== undefined) {\n payload.source_biases = options.sourceBiases;\n }\n\n if (options.category !== undefined) {\n payload.category = options.category;\n }\n\n if (options.startDate !== undefined) {\n payload.start_date = options.startDate;\n }\n\n if (options.endDate !== undefined) {\n payload.end_date = options.endDate;\n }\n\n if (options.countryCode !== undefined) {\n payload.country_code = options.countryCode;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.fastMode !== undefined) {\n payload.fast_mode = options.fastMode;\n }\n\n if (options.urlOnly !== undefined) {\n payload.url_only = options.urlOnly;\n }\n\n const response = await axios.post(`${this.baseUrl}/deepsearch`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n return response.data;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * Extract content from URLs with optional AI processing\n * @param urls - Array of URLs to process (max 10 sync, max 50 with async: true)\n * @param options - Content extraction configuration options\n * @param options.summary - AI summary configuration: false (raw), true (auto), string (custom), or JSON schema\n * @param options.extractEffort - Extraction thoroughness: \"normal\", \"high\", or \"auto\"\n * @param options.responseLength - Content length per URL\n * @param options.maxPriceDollars - Maximum cost limit in USD\n * @param options.screenshot - Request page screenshots (default: false)\n * @param options.async - Force async processing (required for >10 URLs)\n * @param options.webhookUrl - HTTPS URL for completion notification (async only)\n * @returns Promise resolving to sync results or async job (when async: true or >10 URLs)\n */\n async contents(\n urls: string[],\n options: ContentsOptions = {}\n ): Promise<ContentsResponse | ContentsAsyncJobResponse> {\n try {\n // Validate URLs array\n if (!urls || !Array.isArray(urls)) {\n return {\n success: false,\n error: \"urls must be an array\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length === 0) {\n return {\n success: false,\n error: \"urls array cannot be empty\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n const isAsync = options.async === true || urls.length > 10;\n\n if (urls.length > 10 && !options.async) {\n return {\n success: false,\n error:\n \"Requests with more than 10 URLs require async processing. Add async: true to the request.\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length > 50) {\n return {\n success: false,\n error: \"Maximum 50 URLs allowed per request\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate extractEffort if provided\n if (\n options.extractEffort &&\n ![\"normal\", \"high\", \"auto\"].includes(options.extractEffort)\n ) {\n return {\n success: false,\n error: \"extractEffort must be 'normal', 'high', or 'auto'\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate responseLength if provided\n if (options.responseLength !== undefined) {\n const validLengths = [\"short\", \"medium\", \"large\", \"max\"];\n if (\n typeof options.responseLength === \"string\" &&\n !validLengths.includes(options.responseLength)\n ) {\n return {\n success: false,\n error:\n \"responseLength must be 'short', 'medium', 'large', 'max', or a number\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n if (\n typeof options.responseLength === \"number\" &&\n options.responseLength <= 0\n ) {\n return {\n success: false,\n error: \"responseLength number must be positive\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n urls,\n };\n\n // Add optional parameters only if provided\n if (options.summary !== undefined) {\n payload.summary = options.summary;\n }\n\n if (options.extractEffort !== undefined) {\n payload.extract_effort = options.extractEffort;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.maxPriceDollars !== undefined) {\n payload.max_price_dollars = options.maxPriceDollars;\n }\n\n if (options.screenshot !== undefined) {\n payload.screenshot = options.screenshot;\n }\n\n if (isAsync) {\n payload.async = true;\n }\n if (options.webhookUrl !== undefined) {\n payload.webhook_url = options.webhookUrl;\n }\n\n const response = await axios.post(`${this.baseUrl}/contents`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error || \"Request failed\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // 202 Accepted - async job created\n if (response.status === 202) {\n return normalizeContentsAsyncJobResponse(response.data);\n }\n\n return response.data as ContentsResponse;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * Get async Contents job status and results\n * @param jobId - Job ID from contents() async response\n * @returns Promise resolving to job status\n */\n async getContentsJob(jobId: string): Promise<ContentsJobResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/contents/jobs/${jobId}`,\n { headers: this.headers }\n );\n return normalizeContentsJobResponse(response.data);\n } catch (e: any) {\n const errData = e.response?.data;\n const status = e.response?.status;\n return {\n success: false,\n jobId,\n status: \"failed\",\n urlsTotal: 0,\n urlsProcessed: 0,\n urlsFailed: 0,\n createdAt: 0,\n updatedAt: 0,\n error:\n errData?.error ||\n (status === 403\n ? \"Forbidden - you do not have access to this job\"\n : status === 404\n ? `Job ${jobId} not found`\n : e.message),\n };\n }\n }\n\n /**\n * Wait for async Contents job completion (polls until terminal state)\n * @param jobId - Job ID from contents() async response\n * @param options - Wait configuration (pollInterval, maxWaitTime, onProgress)\n * @returns Promise resolving to final job status with results\n */\n async waitForJob(\n jobId: string,\n options: ContentsJobWaitOptions = {}\n ): Promise<ContentsJobResponse> {\n const pollInterval = options.pollInterval ?? 5000;\n const maxWaitTime = options.maxWaitTime ?? 7200000;\n const startTime = Date.now();\n\n while (true) {\n const status = await this.getContentsJob(jobId);\n\n if (!status.success && status.error) {\n throw new Error(status.error);\n }\n\n if (options.onProgress) {\n options.onProgress(status);\n }\n\n if (\n status.status === \"completed\" ||\n status.status === \"partial\" ||\n status.status === \"failed\"\n ) {\n return status;\n }\n\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * DeepResearch: Create a new research task\n * @param options.search - Search configuration options\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n */\n private async _deepresearchCreate(\n options: DeepResearchCreateOptions\n ): Promise<DeepResearchCreateResponse> {\n try {\n // Use query field (input is supported for backward compatibility)\n const queryValue = options.query ?? options.input;\n\n // Validation\n if (!queryValue?.trim()) {\n return {\n success: false,\n error: \"query is required and cannot be empty\",\n };\n }\n\n // Build payload with snake_case\n // Prefer mode over model (backward compatible)\n const mode = options.mode ?? options.model;\n const payload: Record<string, any> = {\n query: queryValue,\n mode: mode || \"fast\", // API defaults to \"standard\", but we keep \"fast\" for backward compatibility\n output_formats: options.outputFormats || [\"markdown\"],\n code_execution: options.codeExecution !== false,\n };\n\n // Add optional fields\n if (options.strategy) payload.strategy = options.strategy;\n if (options.researchStrategy)\n payload.research_strategy = options.researchStrategy;\n if (options.reportFormat)\n payload.report_format = options.reportFormat;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.sourceBiases) {\n payload.search.source_biases = options.search.sourceBiases;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.urls) payload.urls = options.urls;\n if (options.files) payload.files = options.files;\n if (options.deliverables) payload.deliverables = options.deliverables;\n if (options.mcpServers) payload.mcp_servers = options.mcpServers;\n if (options.previousReports) {\n payload.previous_reports = options.previousReports;\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.brandCollectionId)\n payload.brand_collection_id = options.brandCollectionId;\n if (options.alertEmail) {\n if (typeof options.alertEmail === \"string\") {\n payload.alert_email = options.alertEmail;\n } else {\n payload.alert_email = {\n email: options.alertEmail.email,\n custom_url: options.alertEmail.custom_url,\n };\n }\n }\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task status\n */\n private async _deepresearchStatus(\n taskId: string\n ): Promise<DeepResearchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/status`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Wait for task completion with polling\n */\n private async _deepresearchWait(\n taskId: string,\n options: WaitOptions = {}\n ): Promise<DeepResearchStatusResponse> {\n const pollInterval = options.pollInterval || 5000;\n const maxWaitTime = options.maxWaitTime || 7200000;\n const startTime = Date.now();\n\n while (true) {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n throw new Error(status.error);\n }\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(status);\n }\n\n // Terminal states\n if (\n status.status === \"completed\" ||\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n return status;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * DeepResearch: Stream real-time updates\n */\n private async _deepresearchStream(\n taskId: string,\n callback: StreamCallback\n ): Promise<void> {\n let isComplete = false;\n let lastMessageCount = 0;\n\n while (!isComplete) {\n try {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n if (callback.onError) {\n callback.onError(new Error(status.error));\n }\n return;\n }\n\n // Progress updates\n if (status.progress && callback.onProgress) {\n callback.onProgress(\n status.progress.current_step,\n status.progress.total_steps\n );\n }\n\n // New messages\n if (status.messages && callback.onMessage) {\n const newMessages = status.messages.slice(lastMessageCount);\n newMessages.forEach((msg) => callback.onMessage!(msg));\n lastMessageCount = status.messages.length;\n }\n\n // Terminal states\n if (status.status === \"completed\") {\n if (callback.onComplete) {\n callback.onComplete(status);\n }\n isComplete = true;\n } else if (\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n if (callback.onError) {\n callback.onError(\n new Error(status.error || `Task ${status.status}`)\n );\n }\n isComplete = true;\n }\n\n if (!isComplete) {\n await new Promise((resolve) => setTimeout(resolve, 5000));\n }\n } catch (error: any) {\n if (callback.onError) {\n callback.onError(error);\n }\n throw error;\n }\n }\n }\n\n /**\n * DeepResearch: List all tasks\n */\n private async _deepresearchList(\n options?: ListOptions\n ): Promise<DeepResearchListResponse> {\n try {\n const limit = options?.limit || 10;\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/list?limit=${limit}`,\n { headers: this.headers }\n );\n\n return { success: true, data: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Add follow-up instruction\n */\n private async _deepresearchUpdate(\n taskId: string,\n instruction: string\n ): Promise<DeepResearchUpdateResponse> {\n try {\n if (!instruction?.trim()) {\n return {\n success: false,\n error: \"instruction is required and cannot be empty\",\n };\n }\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/update`,\n { instruction },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Cancel task\n */\n private async _deepresearchCancel(\n taskId: string\n ): Promise<DeepResearchCancelResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Delete task\n */\n private async _deepresearchDelete(\n taskId: string\n ): Promise<DeepResearchDeleteResponse> {\n try {\n const response = await axios.delete(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/delete`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Toggle public flag\n */\n private async _deepresearchTogglePublic(\n taskId: string,\n isPublic: boolean\n ): Promise<DeepResearchTogglePublicResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/public`,\n { public: isPublic },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task assets (images, deliverables, PDFs)\n */\n private async _deepresearchGetAssets(\n taskId: string,\n assetId: string,\n options: DeepResearchGetAssetsOptions = {}\n ): Promise<DeepResearchGetAssetsResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.token) {\n params.append(\"token\", options.token);\n }\n\n // Build headers - use API key if no token provided\n const headers: Record<string, string> = {};\n if (!options.token) {\n headers[\"x-api-key\"] = this.headers[\"x-api-key\"];\n }\n\n const url = `${\n this.baseUrl\n }/deepresearch/tasks/${taskId}/assets/${assetId}${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n\n const response = await axios.get(url, {\n headers,\n responseType: \"arraybuffer\", // For binary data\n });\n\n return {\n success: true,\n data: Buffer.from(response.data),\n contentType:\n response.headers[\"content-type\"] || \"application/octet-stream\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Create a new batch\n * @param options - Batch configuration options\n * @param options.name - Optional name for the batch\n * @param options.model - DeepResearch mode: \"fast\", \"standard\", or \"heavy\" (default: \"standard\")\n * @param options.outputFormats - Output formats for tasks (default: [\"markdown\"])\n * @param options.search - Search configuration for all tasks in batch\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n * @param options.webhookUrl - Optional HTTPS URL for completion notification\n * @param options.metadata - Optional metadata key-value pairs\n * @returns Promise resolving to batch creation response with batch_id and webhook_secret\n */\n private async _batchCreate(\n options: CreateBatchOptions = {}\n ): Promise<CreateBatchResponse> {\n try {\n const payload: Record<string, any> = {};\n\n if (options.name) payload.name = options.name;\n // Accept both mode (preferred) and model (backward compatible)\n const mode = options.mode ?? options.model;\n if (mode) payload.mode = mode;\n if (options.outputFormats) payload.output_formats = options.outputFormats;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.sourceBiases) {\n payload.search.source_biases = options.search.sourceBiases;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Get batch status\n * @param batchId - The batch ID to query\n * @returns Promise resolving to batch status with counts and usage\n */\n private async _batchStatus(batchId: string): Promise<BatchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/batches/${batchId}`,\n { headers: this.headers }\n );\n\n return { success: true, batch: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Add tasks to a batch\n * @param batchId - The batch ID to add tasks to\n * @param options - Task configuration options\n * @param options.tasks - Array of task inputs (use 'query' field for each task)\n * @returns Promise resolving to response with added, tasks array, counts, and batch_id\n */\n private async _batchAddTasks(\n batchId: string,\n options: AddBatchTasksOptions\n ): Promise<AddBatchTasksResponse> {\n try {\n if (!options.tasks || !Array.isArray(options.tasks)) {\n return {\n success: false,\n error: \"tasks must be an array\",\n };\n }\n\n if (options.tasks.length === 0) {\n return {\n success: false,\n error: \"tasks array cannot be empty\",\n };\n }\n\n if (options.tasks.length > 100) {\n return {\n success: false,\n error: \"Maximum 100 tasks allowed per request\",\n };\n }\n\n // Validate that each task has a query\n for (const task of options.tasks) {\n if (!task.query && !task.input) {\n return {\n success: false,\n error: \"Each task must have a 'query' field\",\n };\n }\n }\n\n // Convert tasks to snake_case format for API\n // Note: Tasks can only include: id, query, strategy, urls, metadata\n // Tasks inherit model, output_formats, and search_params from batch\n const tasksPayload = options.tasks.map((task) => {\n const taskPayload: Record<string, any> = {};\n\n // Use query field (input is supported for backward compatibility)\n const queryValue = task.query ?? task.input;\n if (queryValue) {\n taskPayload.query = queryValue;\n }\n\n if (task.id) taskPayload.id = task.id;\n if (task.strategy) taskPayload.strategy = task.strategy;\n if (task.researchStrategy)\n taskPayload.research_strategy = task.researchStrategy;\n if (task.reportFormat)\n taskPayload.report_format = task.reportFormat;\n if (task.urls) taskPayload.urls = task.urls;\n if (task.metadata) taskPayload.metadata = task.metadata;\n\n return taskPayload;\n });\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/tasks`,\n { tasks: tasksPayload },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all tasks in a batch\n * @param batchId - The batch ID to query\n * @param options - Optional pagination and filtering options\n * @param options.status - Filter by status: \"queued\", \"running\", \"completed\", \"failed\", or \"cancelled\"\n * @param options.limit - Maximum number of tasks to return\n * @param options.lastKey - Pagination token from previous response\n * @returns Promise resolving to list of tasks with their status and pagination info\n */\n private async _batchListTasks(\n batchId: string,\n options: ListBatchTasksOptions = {}\n ): Promise<ListBatchTasksResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.status) {\n params.append(\"status\", options.status);\n }\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n if (options.lastKey) {\n params.append(\"last_key\", options.lastKey);\n }\n if (options.includeOutput !== undefined) {\n params.append(\"include_output\", options.includeOutput.toString());\n }\n\n const url = `${this.baseUrl}/deepresearch/batches/${batchId}/tasks${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Cancel a batch and all its pending tasks\n * @param batchId - The batch ID to cancel\n * @returns Promise resolving to cancellation confirmation\n */\n private async _batchCancel(batchId: string): Promise<CancelBatchResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all batches\n * @param options - Optional options\n * @param options.limit - Maximum number of batches to return\n * @returns Promise resolving to list of all batches\n */\n private async _batchList(\n options: ListBatchesOptions = {}\n ): Promise<ListBatchesResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n\n const url = `${this.baseUrl}/deepresearch/batches${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, {\n headers: this.headers,\n });\n\n return { success: true, batches: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Wait for batch completion with polling\n * @param batchId - The batch ID to wait for\n * @param options - Wait configuration options\n * @param options.pollInterval - Polling interval in milliseconds (default: 10000)\n * @param options.maxWaitTime - Maximum wait time in milliseconds (default: 7200000)\n * @param options.onProgress - Callback for progress updates\n * @returns Promise resolving to final batch status\n */\n private async _batchWaitForCompletion(\n batchId: string,\n options: BatchWaitOptions = {}\n ): Promise<DeepResearchBatch> {\n const pollInterval = options.pollInterval || 10000; // 10 seconds default\n const maxWaitTime = options.maxWaitTime || 7200000; // 2 hours default\n const startTime = Date.now();\n\n while (true) {\n const statusResponse = await this._batchStatus(batchId);\n\n if (!statusResponse.success || !statusResponse.batch) {\n throw new Error(statusResponse.error || \"Failed to get batch status\");\n }\n\n const batch = statusResponse.batch;\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(batch);\n }\n\n // Terminal states\n if (\n batch.status === \"completed\" ||\n batch.status === \"completed_with_errors\" ||\n batch.status === \"cancelled\"\n ) {\n return batch;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * Get AI-powered answers using the Valyu Answer API\n * @param query - The question or query string\n * @param options - Answer configuration options\n * @param options.structuredOutput - JSON Schema object for structured responses\n * @param options.systemInstructions - Custom system-level instructions (max 2000 chars)\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.dataMaxPrice - Maximum spend (USD) for data retrieval\n * @param options.countryCode - Country code filter for search results\n * @param options.includedSources - List of specific sources to include\n * @param options.excludedSources - List of URLs/domains to exclude from search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.streaming - Enable streaming mode (default: false)\n * @returns Promise resolving to answer response, or AsyncGenerator for streaming\n */\n async answer(\n query: string,\n options: AnswerOptions = {}\n ): Promise<\n AnswerResponse | AsyncGenerator<AnswerStreamChunk, void, unknown>\n > {\n // Validate inputs first\n const validationError = this.validateAnswerParams(query, options);\n if (validationError) {\n if (options.streaming) {\n return this.createErrorGenerator(validationError);\n }\n return { success: false, error: validationError };\n }\n\n const payload = this.buildAnswerPayload(query, options);\n\n if (options.streaming) {\n return this.streamAnswer(payload);\n } else {\n return this.fetchAnswer(payload);\n }\n }\n\n /**\n * Validate answer parameters\n */\n private validateAnswerParams(\n query: string,\n options: AnswerOptions\n ): string | null {\n // Validate query\n if (!query || typeof query !== \"string\" || query.trim().length === 0) {\n return \"Query is required and must be a non-empty string\";\n }\n\n // Validate searchType\n const providedSearchTypeString = options.searchType?.toLowerCase();\n if (\n providedSearchTypeString !== undefined &&\n providedSearchTypeString !== \"web\" &&\n providedSearchTypeString !== \"proprietary\" &&\n providedSearchTypeString !== \"all\" &&\n providedSearchTypeString !== \"news\"\n ) {\n return \"Invalid searchType provided. Must be one of: all, web, proprietary, news\";\n }\n\n // Validate systemInstructions\n if (options.systemInstructions !== undefined) {\n if (typeof options.systemInstructions !== \"string\") {\n return \"systemInstructions must be a string\";\n }\n const trimmed = options.systemInstructions.trim();\n if (trimmed.length === 0) {\n return \"systemInstructions cannot be empty when provided\";\n }\n if (trimmed.length > 2000) {\n return \"systemInstructions must be 2000 characters or less\";\n }\n }\n\n // Validate dataMaxPrice\n if (options.dataMaxPrice !== undefined) {\n if (\n typeof options.dataMaxPrice !== \"number\" ||\n options.dataMaxPrice <= 0\n ) {\n return \"dataMaxPrice must be a positive number\";\n }\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return \"Invalid startDate format. Must be YYYY-MM-DD\";\n }\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return \"Invalid endDate format. Must be YYYY-MM-DD\";\n }\n if (options.startDate && options.endDate) {\n const startDate = new Date(options.startDate);\n const endDate = new Date(options.endDate);\n if (startDate > endDate) {\n return \"startDate must be before endDate\";\n }\n }\n\n // Validate sources\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return \"includedSources must be an array\";\n }\n const validation = this.validateSources(options.includedSources);\n if (!validation.valid) {\n return `Invalid includedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n if (options.excludedSources !== undefined) {\n if (!Array.isArray(options.excludedSources)) {\n return \"excludedSources must be an array\";\n }\n const validation = this.validateSources(options.excludedSources);\n if (!validation.valid) {\n return `Invalid excludedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n\n return null;\n }\n\n /**\n * Build payload for answer API\n */\n private buildAnswerPayload(\n query: string,\n options: AnswerOptions\n ): Record<string, any> {\n const defaultSearchType: SearchType = \"all\";\n const providedSearchTypeString = options.searchType?.toLowerCase();\n let finalSearchType: SearchType = defaultSearchType;\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n }\n\n const payload: Record<string, any> = {\n query: query.trim(),\n search_type: finalSearchType,\n };\n\n if (options.dataMaxPrice !== undefined)\n payload.data_max_price = options.dataMaxPrice;\n if (options.structuredOutput !== undefined)\n payload.structured_output = options.structuredOutput;\n if (options.systemInstructions !== undefined)\n payload.system_instructions = options.systemInstructions.trim();\n if (options.countryCode !== undefined)\n payload.country_code = options.countryCode;\n if (options.includedSources !== undefined)\n payload.included_sources = options.includedSources;\n if (options.excludedSources !== undefined)\n payload.excluded_sources = options.excludedSources;\n if (options.startDate !== undefined) payload.start_date = options.startDate;\n if (options.endDate !== undefined) payload.end_date = options.endDate;\n if (options.fastMode !== undefined) payload.fast_mode = options.fastMode;\n\n return payload;\n }\n\n /**\n * Fetch answer (non-streaming mode)\n */\n private async fetchAnswer(\n payload: Record<string, any>\n ): Promise<AnswerResponse> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n return {\n success: false,\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n }\n\n // Collect streamed data into final response\n let fullContent = \"\";\n let searchResults: SearchResult[] = [];\n let finalMetadata: any = {};\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (reader) {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") continue;\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && !parsed.success) {\n searchResults = [...searchResults, ...parsed.search_results];\n }\n // Handle content chunks\n else if (parsed.choices) {\n const content = parsed.choices[0]?.delta?.content || \"\";\n if (content) fullContent += content;\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n finalMetadata = parsed;\n }\n } catch {\n continue;\n }\n }\n }\n }\n\n // Build final response\n if (finalMetadata.success) {\n const finalSearchResults =\n finalMetadata.search_results || searchResults;\n const response: AnswerSuccessResponse = {\n success: true,\n tx_id: finalMetadata.tx_id || \"\",\n original_query: finalMetadata.original_query || payload.query,\n contents: finalMetadata.contents || fullContent || \"\",\n search_results: finalSearchResults,\n search_metadata: finalMetadata.search_metadata || {\n tx_ids: [],\n number_of_results: 0,\n total_characters: 0,\n },\n ai_usage: finalMetadata.ai_usage || {\n input_tokens: 0,\n output_tokens: 0,\n },\n cost: finalMetadata.cost || {\n total_deduction_dollars: 0,\n search_deduction_dollars: 0,\n ai_deduction_dollars: 0,\n },\n };\n if (finalMetadata.extraction_metadata) {\n response.extraction_metadata = finalMetadata.extraction_metadata;\n }\n return response;\n }\n\n return {\n success: false,\n error: finalMetadata.error || \"Unknown error occurred\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.message || \"Request failed\",\n };\n }\n }\n\n /**\n * Stream answer using SSE\n */\n private async *streamAnswer(\n payload: Record<string, any>\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n yield {\n type: \"error\",\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (!reader) {\n yield { type: \"error\", error: \"No response body\" };\n return;\n }\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") {\n yield { type: \"done\" };\n continue;\n }\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && parsed.success === undefined) {\n yield {\n type: \"search_results\",\n search_results: parsed.search_results,\n };\n }\n // Handle content chunks\n else if (parsed.choices) {\n const delta = parsed.choices[0]?.delta || {};\n const content = delta.content || \"\";\n const finishReason = parsed.choices[0]?.finish_reason;\n\n if (content || finishReason) {\n yield { type: \"content\", content, finish_reason: finishReason };\n }\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n yield {\n type: \"metadata\",\n tx_id: parsed.tx_id,\n original_query: parsed.original_query,\n contents: parsed.contents,\n search_results: parsed.search_results,\n search_metadata: parsed.search_metadata,\n ai_usage: parsed.ai_usage,\n cost: parsed.cost,\n extraction_metadata: parsed.extraction_metadata,\n };\n }\n } catch {\n continue;\n }\n }\n }\n } catch (e: any) {\n yield { type: \"error\", error: e.message || \"Stream failed\" };\n }\n }\n\n /**\n * Create an error generator for streaming errors\n */\n private async *createErrorGenerator(\n error: string\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n yield { type: \"error\", error };\n }\n\n /**\n * Datasources: List all available datasources\n * @param options - Optional filter options\n * @param options.category - Filter by category (e.g., \"research\", \"markets\", \"healthcare\")\n * @returns Promise resolving to list of datasources with their metadata\n */\n private async _datasourcesList(\n options: DatasourcesListOptions = {}\n ): Promise<DatasourcesListResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.category) {\n params.append(\"category\", options.category);\n }\n\n const url = `${this.baseUrl}/datasources${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, datasources: response.data.datasources };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Datasources: Get all available categories\n * @returns Promise resolving to list of categories with their metadata\n */\n private async _datasourcesCategories(): Promise<DatasourcesCategoriesResponse> {\n try {\n const response = await axios.get(`${this.baseUrl}/datasources/categories`, {\n headers: this.headers,\n });\n\n return { success: true, categories: response.data.categories };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n}\n\nexport type {\n SearchResponse,\n SearchType,\n SearchResult,\n FeedbackSentiment,\n FeedbackResponse,\n SearchOptions,\n CountryCode,\n ResponseLength,\n ContentsOptions,\n ContentsResponse,\n ContentsAsyncJobResponse,\n ContentsJobResponse,\n ContentsJobStatus,\n ContentsJobWaitOptions,\n ContentResult,\n ContentResultSuccess,\n ContentResultFailed,\n ExtractEffort,\n ContentResponseLength,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerErrorResponse,\n AnswerStreamChunk,\n AnswerStreamChunkType,\n SearchMetadata,\n AIUsage,\n Cost,\n ExtractionMetadata,\n AlertEmailConfig,\n DeepResearchMode,\n DeepResearchStatus,\n DeepResearchOutputFormat,\n ImageType,\n ChartType,\n FileAttachment,\n MCPServerConfig,\n DeepResearchSearchConfig,\n DeepResearchCreateOptions,\n Progress,\n ChartDataPoint,\n ChartDataSeries,\n ImageMetadata,\n DeepResearchSource,\n DeepResearchUsage,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchTaskListItem,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n BatchStatus,\n BatchCounts,\n DeepResearchBatch,\n CreateBatchOptions,\n BatchTaskInput,\n AddBatchTasksOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksResponse,\n BatchTaskCreated,\n BatchTaskListItem,\n BatchPagination,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DatasourceCategoryId,\n DatasourceModality,\n DatasourcePricing,\n DatasourceCoverage,\n Datasource,\n DatasourceCategory,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA4C;AAC5C,mBAAkB;AA8ClB,SAAS,6BAA6B,KAA+C;AACnF,SAAO;AAAA,IACL,SAAS,IAAI,WAAW;AAAA,IACxB,OAAO,IAAI,UAAU,IAAI;AAAA,IACzB,QAAQ,IAAI,UAAU;AAAA,IACtB,WAAW,IAAI,cAAc,IAAI,aAAa;AAAA,IAC9C,eAAe,IAAI,kBAAkB,IAAI,iBAAiB;AAAA,IAC1D,YAAY,IAAI,eAAe,IAAI,cAAc;AAAA,IACjD,WAAW,IAAI,cAAc,IAAI,aAAa;AAAA,IAC9C,WAAW,IAAI,cAAc,IAAI,aAAa;AAAA,IAC9C,cAAc,IAAI,iBAAiB,IAAI;AAAA,IACvC,cAAc,IAAI,iBAAiB,IAAI;AAAA,IACvC,SAAS,IAAI;AAAA,IACb,mBAAmB,IAAI,uBAA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;AAAA,QACL,SAAS;AAAA,QACT,OAAO,EAAE,UAAU,MAAM,SAAS,EAAE;AAAA,MACtC;AAAA,IACF;AAAA,EACF;AACF;","names":["axios","response"]}
package/dist/index.mjs CHANGED
@@ -25,6 +25,7 @@ function normalizeContentsAsyncJobResponse(api) {
25
25
  jobId: api.job_id ?? api.jobId,
26
26
  status: "pending",
27
27
  urlsTotal: api.urls_total ?? api.urlsTotal ?? 0,
28
+ pollUrl: api.poll_url ?? api.pollUrl,
28
29
  webhookSecret: api.webhook_secret ?? api.webhookSecret,
29
30
  txId: api.tx_id ?? api.txId ?? ""
30
31
  };
@@ -303,6 +304,9 @@ var Valyu = class {
303
304
  if (options.excludeSources !== void 0) {
304
305
  payload.exclude_sources = options.excludeSources;
305
306
  }
307
+ if (options.sourceBiases !== void 0) {
308
+ payload.source_biases = options.sourceBiases;
309
+ }
306
310
  if (options.category !== void 0) {
307
311
  payload.category = options.category;
308
312
  }
@@ -595,6 +599,10 @@ var Valyu = class {
595
599
  code_execution: options.codeExecution !== false
596
600
  };
597
601
  if (options.strategy) payload.strategy = options.strategy;
602
+ if (options.researchStrategy)
603
+ payload.research_strategy = options.researchStrategy;
604
+ if (options.reportFormat)
605
+ payload.report_format = options.reportFormat;
598
606
  if (options.search) {
599
607
  payload.search = {};
600
608
  if (options.search.searchType) {
@@ -606,6 +614,9 @@ var Valyu = class {
606
614
  if (options.search.excludedSources) {
607
615
  payload.search.excluded_sources = options.search.excludedSources;
608
616
  }
617
+ if (options.search.sourceBiases) {
618
+ payload.search.source_biases = options.search.sourceBiases;
619
+ }
609
620
  if (options.search.startDate) {
610
621
  payload.search.start_date = options.search.startDate;
611
622
  }
@@ -902,6 +913,9 @@ var Valyu = class {
902
913
  if (options.search.excludedSources) {
903
914
  payload.search.excluded_sources = options.search.excludedSources;
904
915
  }
916
+ if (options.search.sourceBiases) {
917
+ payload.search.source_biases = options.search.sourceBiases;
918
+ }
905
919
  if (options.search.startDate) {
906
920
  payload.search.start_date = options.search.startDate;
907
921
  }
@@ -989,6 +1003,10 @@ var Valyu = class {
989
1003
  }
990
1004
  if (task.id) taskPayload.id = task.id;
991
1005
  if (task.strategy) taskPayload.strategy = task.strategy;
1006
+ if (task.researchStrategy)
1007
+ taskPayload.research_strategy = task.researchStrategy;
1008
+ if (task.reportFormat)
1009
+ taskPayload.report_format = task.reportFormat;
992
1010
  if (task.urls) taskPayload.urls = task.urls;
993
1011
  if (task.metadata) taskPayload.metadata = task.metadata;
994
1012
  return taskPayload;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from \"crypto\";\nimport axios from \"axios\";\nimport {\n SearchResponse,\n SearchType,\n SearchOptions,\n ContentsOptions,\n ContentsResponse,\n ContentsAsyncJobResponse,\n ContentsJobResponse,\n ContentsJobWaitOptions,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerStreamChunk,\n SearchResult,\n DeepResearchCreateOptions,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n CreateBatchOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksOptions,\n AddBatchTasksResponse,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DeepResearchBatch,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n\n/** Normalize API job response (snake_case) to SDK format (camelCase). Omits poll_url. */\nfunction normalizeContentsJobResponse(api: Record<string, any>): ContentsJobResponse {\n return {\n success: api.success ?? true,\n jobId: api.job_id ?? api.jobId,\n status: api.status ?? \"pending\",\n urlsTotal: api.urls_total ?? api.urlsTotal ?? 0,\n urlsProcessed: api.urls_processed ?? api.urlsProcessed ?? 0,\n urlsFailed: api.urls_failed ?? api.urlsFailed ?? 0,\n createdAt: api.created_at ?? api.createdAt ?? 0,\n updatedAt: api.updated_at ?? api.updatedAt ?? 0,\n currentBatch: api.current_batch ?? api.currentBatch,\n totalBatches: api.total_batches ?? api.totalBatches,\n results: api.results,\n actualCostDollars: api.actual_cost_dollars ?? api.actualCostDollars,\n error: api.error,\n webhookSecret: api.webhook_secret ?? api.webhookSecret,\n };\n}\n\n/** Normalize API async job creation response (202) to SDK format. */\nfunction normalizeContentsAsyncJobResponse(\n api: Record<string, any>\n): ContentsAsyncJobResponse {\n return {\n success: api.success ?? true,\n jobId: api.job_id ?? api.jobId,\n status: \"pending\",\n urlsTotal: api.urls_total ?? api.urlsTotal ?? 0,\n webhookSecret: api.webhook_secret ?? api.webhookSecret,\n txId: api.tx_id ?? api.txId ?? \"\",\n };\n}\n\n/**\n * Verify webhook signature for Contents API async completion notifications.\n * Use the raw request body (not parsed JSON) as payload.\n * @param payload - Raw request body string\n * @param signature - X-Webhook-Signature header value\n * @param timestamp - X-Webhook-Timestamp header value\n * @param secret - webhookSecret from job creation\n */\nexport function verifyContentsWebhookSignature(\n payload: string,\n signature: string,\n timestamp: string,\n secret: string\n): boolean {\n const expected = createHmac(\"sha256\", secret)\n .update(`${timestamp}.${payload}`)\n .digest(\"hex\");\n const expectedSignature = `sha256=${expected}`;\n if (signature.length !== expectedSignature.length) return false;\n return timingSafeEqual(\n Buffer.from(signature, \"utf8\"),\n Buffer.from(expectedSignature, \"utf8\")\n );\n}\n\n// Valyu API client\nexport class Valyu {\n private baseUrl: string;\n private headers: Record<string, string>;\n\n // DeepResearch namespace\n public deepresearch: {\n create: (\n options: DeepResearchCreateOptions\n ) => Promise<DeepResearchCreateResponse>;\n status: (taskId: string) => Promise<DeepResearchStatusResponse>;\n wait: (\n taskId: string,\n options?: WaitOptions\n ) => Promise<DeepResearchStatusResponse>;\n stream: (taskId: string, callback: StreamCallback) => Promise<void>;\n list: (options: ListOptions) => Promise<DeepResearchListResponse>;\n update: (\n taskId: string,\n instruction: string\n ) => Promise<DeepResearchUpdateResponse>;\n cancel: (taskId: string) => Promise<DeepResearchCancelResponse>;\n delete: (taskId: string) => Promise<DeepResearchDeleteResponse>;\n togglePublic: (\n taskId: string,\n isPublic: boolean\n ) => Promise<DeepResearchTogglePublicResponse>;\n getAssets: (\n taskId: string,\n assetId: string,\n options?: DeepResearchGetAssetsOptions\n ) => Promise<DeepResearchGetAssetsResponse>;\n };\n\n // Batch API namespace\n public batch: {\n create: (options?: CreateBatchOptions) => Promise<CreateBatchResponse>;\n status: (batchId: string) => Promise<BatchStatusResponse>;\n addTasks: (\n batchId: string,\n options: AddBatchTasksOptions\n ) => Promise<AddBatchTasksResponse>;\n listTasks: (\n batchId: string,\n options?: ListBatchTasksOptions\n ) => Promise<ListBatchTasksResponse>;\n cancel: (batchId: string) => Promise<CancelBatchResponse>;\n list: (options?: ListBatchesOptions) => Promise<ListBatchesResponse>;\n waitForCompletion: (\n batchId: string,\n options?: BatchWaitOptions\n ) => Promise<DeepResearchBatch>;\n };\n\n // Datasources API namespace\n public datasources: {\n list: (options?: DatasourcesListOptions) => Promise<DatasourcesListResponse>;\n categories: () => Promise<DatasourcesCategoriesResponse>;\n };\n\n constructor(apiKey?: string, baseUrl: string = \"https://api.valyu.ai/v1\") {\n if (!apiKey) {\n apiKey = process.env.VALYU_API_KEY;\n if (!apiKey) {\n throw new Error(\"VALYU_API_KEY is not set\");\n }\n }\n this.baseUrl = baseUrl;\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n };\n\n // Initialize DeepResearch namespace\n this.deepresearch = {\n create: this._deepresearchCreate.bind(this),\n status: this._deepresearchStatus.bind(this),\n wait: this._deepresearchWait.bind(this),\n stream: this._deepresearchStream.bind(this),\n list: this._deepresearchList.bind(this),\n update: this._deepresearchUpdate.bind(this),\n cancel: this._deepresearchCancel.bind(this),\n delete: this._deepresearchDelete.bind(this),\n togglePublic: this._deepresearchTogglePublic.bind(this),\n getAssets: this._deepresearchGetAssets.bind(this),\n };\n\n // Initialize Batch namespace\n this.batch = {\n create: this._batchCreate.bind(this),\n status: this._batchStatus.bind(this),\n addTasks: this._batchAddTasks.bind(this),\n listTasks: this._batchListTasks.bind(this),\n cancel: this._batchCancel.bind(this),\n list: this._batchList.bind(this),\n waitForCompletion: this._batchWaitForCompletion.bind(this),\n };\n\n // Initialize Datasources namespace\n this.datasources = {\n list: this._datasourcesList.bind(this),\n categories: this._datasourcesCategories.bind(this),\n };\n }\n\n /**\n * Validates date format (YYYY-MM-DD)\n */\n private validateDateFormat(date: string): boolean {\n const dateRegex = /^\\d{4}-\\d{2}-\\d{2}$/;\n if (!dateRegex.test(date)) {\n return false;\n }\n const parsedDate = new Date(date);\n return parsedDate instanceof Date && !isNaN(parsedDate.getTime());\n }\n\n /**\n * Validates if a string is a valid URL\n */\n private validateUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Validates if a string is a valid domain (with optional path)\n */\n private validateDomain(domain: string): boolean {\n // Domain must have at least one dot and valid structure\n // Supports: example.com, example.com/path, subdomain.example.com/path/to/resource\n const domainRegex =\n /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\\/.+)?$/;\n return domainRegex.test(domain);\n }\n\n /**\n * Validates if a string is a valid dataset identifier (provider/datasetname)\n */\n private validateDatasetId(datasetId: string): boolean {\n // Dataset format: provider/datasetname (exactly one slash)\n // Provider and dataset name can contain alphanumeric, hyphens, underscores\n const parts = datasetId.split(\"/\");\n if (parts.length !== 2) return false;\n\n const providerRegex = /^[a-zA-Z0-9_-]+$/;\n const datasetRegex = /^[a-zA-Z0-9_-]+$/;\n\n return (\n providerRegex.test(parts[0]) &&\n datasetRegex.test(parts[1]) &&\n parts[0].length > 0 &&\n parts[1].length > 0\n );\n }\n\n /**\n * Validates source strings (domains, URLs, or dataset IDs)\n */\n private validateSource(source: string): boolean {\n // Check if it's a valid URL\n if (this.validateUrl(source)) {\n return true;\n }\n\n // Check if it's a valid domain (with optional path)\n if (this.validateDomain(source)) {\n return true;\n }\n\n // Check if it's a valid dataset identifier\n if (this.validateDatasetId(source)) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Validates an array of source strings\n */\n private validateSources(sources: string[]): {\n valid: boolean;\n invalidSources: string[];\n } {\n const invalidSources: string[] = [];\n\n for (const source of sources) {\n if (!this.validateSource(source)) {\n invalidSources.push(source);\n }\n }\n\n return {\n valid: invalidSources.length === 0,\n invalidSources,\n };\n }\n\n /**\n * Search for information using the Valyu DeepSearch API\n * @param query - The search query string\n * @param options - Search configuration options\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.maxNumResults - Maximum number of results (1-100)\n * @param options.maxPrice - Maximum price per thousand characters (CPM)\n * @param options.isToolCall - Whether this is a tool call\n * @param options.relevanceThreshold - Minimum relevance score (0-1)\n * @param options.includedSources - List of specific sources to include\n * @param options.excludeSources - List of URLs/domains to exclude from search results\n * @param options.category - Category filter for search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.countryCode - Country code filter for search results\n * @param options.responseLength - Response content length: \"short\"/\"medium\"/\"large\"/\"max\" or integer character count\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.urlOnly - Returns shortened snippets (default: false)\n * @returns Promise resolving to search results\n */\n async search(\n query: string,\n options: SearchOptions = {}\n ): Promise<SearchResponse> {\n try {\n // Default values\n const defaultSearchType: SearchType = \"all\";\n const defaultMaxNumResults = 10;\n const defaultIsToolCall = true;\n const defaultRelevanceThreshold = 0.5;\n\n // Validate searchType\n let finalSearchType: SearchType = defaultSearchType;\n const providedSearchTypeString = options.searchType?.toLowerCase();\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n } else if (options.searchType !== undefined) {\n return {\n success: false,\n error:\n \"Invalid searchType provided. Must be one of: all, web, proprietary, news\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return {\n success: false,\n error: \"Invalid startDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return {\n success: false,\n error: \"Invalid endDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate maxNumResults range\n const maxNumResults = options.maxNumResults ?? defaultMaxNumResults;\n if (maxNumResults < 1 || maxNumResults > 100) {\n return {\n success: false,\n error: \"maxNumResults must be between 1 and 100\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate includedSources format\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return {\n success: false,\n error: \"includedSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const includedSourcesValidation = this.validateSources(\n options.includedSources\n );\n if (!includedSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid includedSources format. Invalid sources: ${includedSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Validate excludeSources format\n if (options.excludeSources !== undefined) {\n if (!Array.isArray(options.excludeSources)) {\n return {\n success: false,\n error: \"excludeSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const excludeSourcesValidation = this.validateSources(\n options.excludeSources\n );\n if (!excludeSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid excludeSources format. Invalid sources: ${excludeSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n query,\n search_type: finalSearchType,\n max_num_results: maxNumResults,\n is_tool_call: options.isToolCall ?? defaultIsToolCall,\n relevance_threshold:\n options.relevanceThreshold ?? defaultRelevanceThreshold,\n };\n\n // Add maxPrice only if explicitly provided\n if (options.maxPrice !== undefined) {\n payload.max_price = options.maxPrice;\n }\n\n // Add optional parameters only if provided\n if (options.includedSources !== undefined) {\n payload.included_sources = options.includedSources;\n }\n\n if (options.excludeSources !== undefined) {\n payload.exclude_sources = options.excludeSources;\n }\n\n if (options.category !== undefined) {\n payload.category = options.category;\n }\n\n if (options.startDate !== undefined) {\n payload.start_date = options.startDate;\n }\n\n if (options.endDate !== undefined) {\n payload.end_date = options.endDate;\n }\n\n if (options.countryCode !== undefined) {\n payload.country_code = options.countryCode;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.fastMode !== undefined) {\n payload.fast_mode = options.fastMode;\n }\n\n if (options.urlOnly !== undefined) {\n payload.url_only = options.urlOnly;\n }\n\n const response = await axios.post(`${this.baseUrl}/deepsearch`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n return response.data;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * Extract content from URLs with optional AI processing\n * @param urls - Array of URLs to process (max 10 sync, max 50 with async: true)\n * @param options - Content extraction configuration options\n * @param options.summary - AI summary configuration: false (raw), true (auto), string (custom), or JSON schema\n * @param options.extractEffort - Extraction thoroughness: \"normal\", \"high\", or \"auto\"\n * @param options.responseLength - Content length per URL\n * @param options.maxPriceDollars - Maximum cost limit in USD\n * @param options.screenshot - Request page screenshots (default: false)\n * @param options.async - Force async processing (required for >10 URLs)\n * @param options.webhookUrl - HTTPS URL for completion notification (async only)\n * @returns Promise resolving to sync results or async job (when async: true or >10 URLs)\n */\n async contents(\n urls: string[],\n options: ContentsOptions = {}\n ): Promise<ContentsResponse | ContentsAsyncJobResponse> {\n try {\n // Validate URLs array\n if (!urls || !Array.isArray(urls)) {\n return {\n success: false,\n error: \"urls must be an array\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length === 0) {\n return {\n success: false,\n error: \"urls array cannot be empty\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n const isAsync = options.async === true || urls.length > 10;\n\n if (urls.length > 10 && !options.async) {\n return {\n success: false,\n error:\n \"Requests with more than 10 URLs require async processing. Add async: true to the request.\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length > 50) {\n return {\n success: false,\n error: \"Maximum 50 URLs allowed per request\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate extractEffort if provided\n if (\n options.extractEffort &&\n ![\"normal\", \"high\", \"auto\"].includes(options.extractEffort)\n ) {\n return {\n success: false,\n error: \"extractEffort must be 'normal', 'high', or 'auto'\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate responseLength if provided\n if (options.responseLength !== undefined) {\n const validLengths = [\"short\", \"medium\", \"large\", \"max\"];\n if (\n typeof options.responseLength === \"string\" &&\n !validLengths.includes(options.responseLength)\n ) {\n return {\n success: false,\n error:\n \"responseLength must be 'short', 'medium', 'large', 'max', or a number\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n if (\n typeof options.responseLength === \"number\" &&\n options.responseLength <= 0\n ) {\n return {\n success: false,\n error: \"responseLength number must be positive\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n urls,\n };\n\n // Add optional parameters only if provided\n if (options.summary !== undefined) {\n payload.summary = options.summary;\n }\n\n if (options.extractEffort !== undefined) {\n payload.extract_effort = options.extractEffort;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.maxPriceDollars !== undefined) {\n payload.max_price_dollars = options.maxPriceDollars;\n }\n\n if (options.screenshot !== undefined) {\n payload.screenshot = options.screenshot;\n }\n\n if (isAsync) {\n payload.async = true;\n }\n if (options.webhookUrl !== undefined) {\n payload.webhook_url = options.webhookUrl;\n }\n\n const response = await axios.post(`${this.baseUrl}/contents`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error || \"Request failed\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // 202 Accepted - async job created\n if (response.status === 202) {\n return normalizeContentsAsyncJobResponse(response.data);\n }\n\n return response.data as ContentsResponse;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * Get async Contents job status and results\n * @param jobId - Job ID from contents() async response\n * @returns Promise resolving to job status\n */\n async getContentsJob(jobId: string): Promise<ContentsJobResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/contents/jobs/${jobId}`,\n { headers: this.headers }\n );\n return normalizeContentsJobResponse(response.data);\n } catch (e: any) {\n const errData = e.response?.data;\n const status = e.response?.status;\n return {\n success: false,\n jobId,\n status: \"failed\",\n urlsTotal: 0,\n urlsProcessed: 0,\n urlsFailed: 0,\n createdAt: 0,\n updatedAt: 0,\n error:\n errData?.error ||\n (status === 403\n ? \"Forbidden - you do not have access to this job\"\n : status === 404\n ? `Job ${jobId} not found`\n : e.message),\n };\n }\n }\n\n /**\n * Wait for async Contents job completion (polls until terminal state)\n * @param jobId - Job ID from contents() async response\n * @param options - Wait configuration (pollInterval, maxWaitTime, onProgress)\n * @returns Promise resolving to final job status with results\n */\n async waitForJob(\n jobId: string,\n options: ContentsJobWaitOptions = {}\n ): Promise<ContentsJobResponse> {\n const pollInterval = options.pollInterval ?? 5000;\n const maxWaitTime = options.maxWaitTime ?? 7200000;\n const startTime = Date.now();\n\n while (true) {\n const status = await this.getContentsJob(jobId);\n\n if (!status.success && status.error) {\n throw new Error(status.error);\n }\n\n if (options.onProgress) {\n options.onProgress(status);\n }\n\n if (\n status.status === \"completed\" ||\n status.status === \"partial\" ||\n status.status === \"failed\"\n ) {\n return status;\n }\n\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * DeepResearch: Create a new research task\n * @param options.search - Search configuration options\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n */\n private async _deepresearchCreate(\n options: DeepResearchCreateOptions\n ): Promise<DeepResearchCreateResponse> {\n try {\n // Use query field (input is supported for backward compatibility)\n const queryValue = options.query ?? options.input;\n\n // Validation\n if (!queryValue?.trim()) {\n return {\n success: false,\n error: \"query is required and cannot be empty\",\n };\n }\n\n // Build payload with snake_case\n // Prefer mode over model (backward compatible)\n const mode = options.mode ?? options.model;\n const payload: Record<string, any> = {\n query: queryValue,\n mode: mode || \"fast\", // API defaults to \"standard\", but we keep \"fast\" for backward compatibility\n output_formats: options.outputFormats || [\"markdown\"],\n code_execution: options.codeExecution !== false,\n };\n\n // Add optional fields\n if (options.strategy) payload.strategy = options.strategy;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.urls) payload.urls = options.urls;\n if (options.files) payload.files = options.files;\n if (options.deliverables) payload.deliverables = options.deliverables;\n if (options.mcpServers) payload.mcp_servers = options.mcpServers;\n if (options.previousReports) {\n payload.previous_reports = options.previousReports;\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.brandCollectionId)\n payload.brand_collection_id = options.brandCollectionId;\n if (options.alertEmail) {\n if (typeof options.alertEmail === \"string\") {\n payload.alert_email = options.alertEmail;\n } else {\n payload.alert_email = {\n email: options.alertEmail.email,\n custom_url: options.alertEmail.custom_url,\n };\n }\n }\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task status\n */\n private async _deepresearchStatus(\n taskId: string\n ): Promise<DeepResearchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/status`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Wait for task completion with polling\n */\n private async _deepresearchWait(\n taskId: string,\n options: WaitOptions = {}\n ): Promise<DeepResearchStatusResponse> {\n const pollInterval = options.pollInterval || 5000;\n const maxWaitTime = options.maxWaitTime || 7200000;\n const startTime = Date.now();\n\n while (true) {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n throw new Error(status.error);\n }\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(status);\n }\n\n // Terminal states\n if (\n status.status === \"completed\" ||\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n return status;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * DeepResearch: Stream real-time updates\n */\n private async _deepresearchStream(\n taskId: string,\n callback: StreamCallback\n ): Promise<void> {\n let isComplete = false;\n let lastMessageCount = 0;\n\n while (!isComplete) {\n try {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n if (callback.onError) {\n callback.onError(new Error(status.error));\n }\n return;\n }\n\n // Progress updates\n if (status.progress && callback.onProgress) {\n callback.onProgress(\n status.progress.current_step,\n status.progress.total_steps\n );\n }\n\n // New messages\n if (status.messages && callback.onMessage) {\n const newMessages = status.messages.slice(lastMessageCount);\n newMessages.forEach((msg) => callback.onMessage!(msg));\n lastMessageCount = status.messages.length;\n }\n\n // Terminal states\n if (status.status === \"completed\") {\n if (callback.onComplete) {\n callback.onComplete(status);\n }\n isComplete = true;\n } else if (\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n if (callback.onError) {\n callback.onError(\n new Error(status.error || `Task ${status.status}`)\n );\n }\n isComplete = true;\n }\n\n if (!isComplete) {\n await new Promise((resolve) => setTimeout(resolve, 5000));\n }\n } catch (error: any) {\n if (callback.onError) {\n callback.onError(error);\n }\n throw error;\n }\n }\n }\n\n /**\n * DeepResearch: List all tasks\n */\n private async _deepresearchList(\n options?: ListOptions\n ): Promise<DeepResearchListResponse> {\n try {\n const limit = options?.limit || 10;\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/list?limit=${limit}`,\n { headers: this.headers }\n );\n\n return { success: true, data: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Add follow-up instruction\n */\n private async _deepresearchUpdate(\n taskId: string,\n instruction: string\n ): Promise<DeepResearchUpdateResponse> {\n try {\n if (!instruction?.trim()) {\n return {\n success: false,\n error: \"instruction is required and cannot be empty\",\n };\n }\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/update`,\n { instruction },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Cancel task\n */\n private async _deepresearchCancel(\n taskId: string\n ): Promise<DeepResearchCancelResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Delete task\n */\n private async _deepresearchDelete(\n taskId: string\n ): Promise<DeepResearchDeleteResponse> {\n try {\n const response = await axios.delete(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/delete`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Toggle public flag\n */\n private async _deepresearchTogglePublic(\n taskId: string,\n isPublic: boolean\n ): Promise<DeepResearchTogglePublicResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/public`,\n { public: isPublic },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task assets (images, deliverables, PDFs)\n */\n private async _deepresearchGetAssets(\n taskId: string,\n assetId: string,\n options: DeepResearchGetAssetsOptions = {}\n ): Promise<DeepResearchGetAssetsResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.token) {\n params.append(\"token\", options.token);\n }\n\n // Build headers - use API key if no token provided\n const headers: Record<string, string> = {};\n if (!options.token) {\n headers[\"x-api-key\"] = this.headers[\"x-api-key\"];\n }\n\n const url = `${\n this.baseUrl\n }/deepresearch/tasks/${taskId}/assets/${assetId}${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n\n const response = await axios.get(url, {\n headers,\n responseType: \"arraybuffer\", // For binary data\n });\n\n return {\n success: true,\n data: Buffer.from(response.data),\n contentType:\n response.headers[\"content-type\"] || \"application/octet-stream\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Create a new batch\n * @param options - Batch configuration options\n * @param options.name - Optional name for the batch\n * @param options.model - DeepResearch mode: \"fast\", \"standard\", or \"heavy\" (default: \"standard\")\n * @param options.outputFormats - Output formats for tasks (default: [\"markdown\"])\n * @param options.search - Search configuration for all tasks in batch\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n * @param options.webhookUrl - Optional HTTPS URL for completion notification\n * @param options.metadata - Optional metadata key-value pairs\n * @returns Promise resolving to batch creation response with batch_id and webhook_secret\n */\n private async _batchCreate(\n options: CreateBatchOptions = {}\n ): Promise<CreateBatchResponse> {\n try {\n const payload: Record<string, any> = {};\n\n if (options.name) payload.name = options.name;\n // Accept both mode (preferred) and model (backward compatible)\n const mode = options.mode ?? options.model;\n if (mode) payload.mode = mode;\n if (options.outputFormats) payload.output_formats = options.outputFormats;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Get batch status\n * @param batchId - The batch ID to query\n * @returns Promise resolving to batch status with counts and usage\n */\n private async _batchStatus(batchId: string): Promise<BatchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/batches/${batchId}`,\n { headers: this.headers }\n );\n\n return { success: true, batch: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Add tasks to a batch\n * @param batchId - The batch ID to add tasks to\n * @param options - Task configuration options\n * @param options.tasks - Array of task inputs (use 'query' field for each task)\n * @returns Promise resolving to response with added, tasks array, counts, and batch_id\n */\n private async _batchAddTasks(\n batchId: string,\n options: AddBatchTasksOptions\n ): Promise<AddBatchTasksResponse> {\n try {\n if (!options.tasks || !Array.isArray(options.tasks)) {\n return {\n success: false,\n error: \"tasks must be an array\",\n };\n }\n\n if (options.tasks.length === 0) {\n return {\n success: false,\n error: \"tasks array cannot be empty\",\n };\n }\n\n if (options.tasks.length > 100) {\n return {\n success: false,\n error: \"Maximum 100 tasks allowed per request\",\n };\n }\n\n // Validate that each task has a query\n for (const task of options.tasks) {\n if (!task.query && !task.input) {\n return {\n success: false,\n error: \"Each task must have a 'query' field\",\n };\n }\n }\n\n // Convert tasks to snake_case format for API\n // Note: Tasks can only include: id, query, strategy, urls, metadata\n // Tasks inherit model, output_formats, and search_params from batch\n const tasksPayload = options.tasks.map((task) => {\n const taskPayload: Record<string, any> = {};\n\n // Use query field (input is supported for backward compatibility)\n const queryValue = task.query ?? task.input;\n if (queryValue) {\n taskPayload.query = queryValue;\n }\n\n if (task.id) taskPayload.id = task.id;\n if (task.strategy) taskPayload.strategy = task.strategy;\n if (task.urls) taskPayload.urls = task.urls;\n if (task.metadata) taskPayload.metadata = task.metadata;\n\n return taskPayload;\n });\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/tasks`,\n { tasks: tasksPayload },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all tasks in a batch\n * @param batchId - The batch ID to query\n * @param options - Optional pagination and filtering options\n * @param options.status - Filter by status: \"queued\", \"running\", \"completed\", \"failed\", or \"cancelled\"\n * @param options.limit - Maximum number of tasks to return\n * @param options.lastKey - Pagination token from previous response\n * @returns Promise resolving to list of tasks with their status and pagination info\n */\n private async _batchListTasks(\n batchId: string,\n options: ListBatchTasksOptions = {}\n ): Promise<ListBatchTasksResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.status) {\n params.append(\"status\", options.status);\n }\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n if (options.lastKey) {\n params.append(\"last_key\", options.lastKey);\n }\n if (options.includeOutput !== undefined) {\n params.append(\"include_output\", options.includeOutput.toString());\n }\n\n const url = `${this.baseUrl}/deepresearch/batches/${batchId}/tasks${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Cancel a batch and all its pending tasks\n * @param batchId - The batch ID to cancel\n * @returns Promise resolving to cancellation confirmation\n */\n private async _batchCancel(batchId: string): Promise<CancelBatchResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all batches\n * @param options - Optional options\n * @param options.limit - Maximum number of batches to return\n * @returns Promise resolving to list of all batches\n */\n private async _batchList(\n options: ListBatchesOptions = {}\n ): Promise<ListBatchesResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n\n const url = `${this.baseUrl}/deepresearch/batches${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, {\n headers: this.headers,\n });\n\n return { success: true, batches: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Wait for batch completion with polling\n * @param batchId - The batch ID to wait for\n * @param options - Wait configuration options\n * @param options.pollInterval - Polling interval in milliseconds (default: 10000)\n * @param options.maxWaitTime - Maximum wait time in milliseconds (default: 7200000)\n * @param options.onProgress - Callback for progress updates\n * @returns Promise resolving to final batch status\n */\n private async _batchWaitForCompletion(\n batchId: string,\n options: BatchWaitOptions = {}\n ): Promise<DeepResearchBatch> {\n const pollInterval = options.pollInterval || 10000; // 10 seconds default\n const maxWaitTime = options.maxWaitTime || 7200000; // 2 hours default\n const startTime = Date.now();\n\n while (true) {\n const statusResponse = await this._batchStatus(batchId);\n\n if (!statusResponse.success || !statusResponse.batch) {\n throw new Error(statusResponse.error || \"Failed to get batch status\");\n }\n\n const batch = statusResponse.batch;\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(batch);\n }\n\n // Terminal states\n if (\n batch.status === \"completed\" ||\n batch.status === \"completed_with_errors\" ||\n batch.status === \"cancelled\"\n ) {\n return batch;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * Get AI-powered answers using the Valyu Answer API\n * @param query - The question or query string\n * @param options - Answer configuration options\n * @param options.structuredOutput - JSON Schema object for structured responses\n * @param options.systemInstructions - Custom system-level instructions (max 2000 chars)\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.dataMaxPrice - Maximum spend (USD) for data retrieval\n * @param options.countryCode - Country code filter for search results\n * @param options.includedSources - List of specific sources to include\n * @param options.excludedSources - List of URLs/domains to exclude from search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.streaming - Enable streaming mode (default: false)\n * @returns Promise resolving to answer response, or AsyncGenerator for streaming\n */\n async answer(\n query: string,\n options: AnswerOptions = {}\n ): Promise<\n AnswerResponse | AsyncGenerator<AnswerStreamChunk, void, unknown>\n > {\n // Validate inputs first\n const validationError = this.validateAnswerParams(query, options);\n if (validationError) {\n if (options.streaming) {\n return this.createErrorGenerator(validationError);\n }\n return { success: false, error: validationError };\n }\n\n const payload = this.buildAnswerPayload(query, options);\n\n if (options.streaming) {\n return this.streamAnswer(payload);\n } else {\n return this.fetchAnswer(payload);\n }\n }\n\n /**\n * Validate answer parameters\n */\n private validateAnswerParams(\n query: string,\n options: AnswerOptions\n ): string | null {\n // Validate query\n if (!query || typeof query !== \"string\" || query.trim().length === 0) {\n return \"Query is required and must be a non-empty string\";\n }\n\n // Validate searchType\n const providedSearchTypeString = options.searchType?.toLowerCase();\n if (\n providedSearchTypeString !== undefined &&\n providedSearchTypeString !== \"web\" &&\n providedSearchTypeString !== \"proprietary\" &&\n providedSearchTypeString !== \"all\" &&\n providedSearchTypeString !== \"news\"\n ) {\n return \"Invalid searchType provided. Must be one of: all, web, proprietary, news\";\n }\n\n // Validate systemInstructions\n if (options.systemInstructions !== undefined) {\n if (typeof options.systemInstructions !== \"string\") {\n return \"systemInstructions must be a string\";\n }\n const trimmed = options.systemInstructions.trim();\n if (trimmed.length === 0) {\n return \"systemInstructions cannot be empty when provided\";\n }\n if (trimmed.length > 2000) {\n return \"systemInstructions must be 2000 characters or less\";\n }\n }\n\n // Validate dataMaxPrice\n if (options.dataMaxPrice !== undefined) {\n if (\n typeof options.dataMaxPrice !== \"number\" ||\n options.dataMaxPrice <= 0\n ) {\n return \"dataMaxPrice must be a positive number\";\n }\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return \"Invalid startDate format. Must be YYYY-MM-DD\";\n }\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return \"Invalid endDate format. Must be YYYY-MM-DD\";\n }\n if (options.startDate && options.endDate) {\n const startDate = new Date(options.startDate);\n const endDate = new Date(options.endDate);\n if (startDate > endDate) {\n return \"startDate must be before endDate\";\n }\n }\n\n // Validate sources\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return \"includedSources must be an array\";\n }\n const validation = this.validateSources(options.includedSources);\n if (!validation.valid) {\n return `Invalid includedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n if (options.excludedSources !== undefined) {\n if (!Array.isArray(options.excludedSources)) {\n return \"excludedSources must be an array\";\n }\n const validation = this.validateSources(options.excludedSources);\n if (!validation.valid) {\n return `Invalid excludedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n\n return null;\n }\n\n /**\n * Build payload for answer API\n */\n private buildAnswerPayload(\n query: string,\n options: AnswerOptions\n ): Record<string, any> {\n const defaultSearchType: SearchType = \"all\";\n const providedSearchTypeString = options.searchType?.toLowerCase();\n let finalSearchType: SearchType = defaultSearchType;\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n }\n\n const payload: Record<string, any> = {\n query: query.trim(),\n search_type: finalSearchType,\n };\n\n if (options.dataMaxPrice !== undefined)\n payload.data_max_price = options.dataMaxPrice;\n if (options.structuredOutput !== undefined)\n payload.structured_output = options.structuredOutput;\n if (options.systemInstructions !== undefined)\n payload.system_instructions = options.systemInstructions.trim();\n if (options.countryCode !== undefined)\n payload.country_code = options.countryCode;\n if (options.includedSources !== undefined)\n payload.included_sources = options.includedSources;\n if (options.excludedSources !== undefined)\n payload.excluded_sources = options.excludedSources;\n if (options.startDate !== undefined) payload.start_date = options.startDate;\n if (options.endDate !== undefined) payload.end_date = options.endDate;\n if (options.fastMode !== undefined) payload.fast_mode = options.fastMode;\n\n return payload;\n }\n\n /**\n * Fetch answer (non-streaming mode)\n */\n private async fetchAnswer(\n payload: Record<string, any>\n ): Promise<AnswerResponse> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n return {\n success: false,\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n }\n\n // Collect streamed data into final response\n let fullContent = \"\";\n let searchResults: SearchResult[] = [];\n let finalMetadata: any = {};\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (reader) {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") continue;\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && !parsed.success) {\n searchResults = [...searchResults, ...parsed.search_results];\n }\n // Handle content chunks\n else if (parsed.choices) {\n const content = parsed.choices[0]?.delta?.content || \"\";\n if (content) fullContent += content;\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n finalMetadata = parsed;\n }\n } catch {\n continue;\n }\n }\n }\n }\n\n // Build final response\n if (finalMetadata.success) {\n const finalSearchResults =\n finalMetadata.search_results || searchResults;\n const response: AnswerSuccessResponse = {\n success: true,\n tx_id: finalMetadata.tx_id || \"\",\n original_query: finalMetadata.original_query || payload.query,\n contents: finalMetadata.contents || fullContent || \"\",\n search_results: finalSearchResults,\n search_metadata: finalMetadata.search_metadata || {\n tx_ids: [],\n number_of_results: 0,\n total_characters: 0,\n },\n ai_usage: finalMetadata.ai_usage || {\n input_tokens: 0,\n output_tokens: 0,\n },\n cost: finalMetadata.cost || {\n total_deduction_dollars: 0,\n search_deduction_dollars: 0,\n ai_deduction_dollars: 0,\n },\n };\n if (finalMetadata.extraction_metadata) {\n response.extraction_metadata = finalMetadata.extraction_metadata;\n }\n return response;\n }\n\n return {\n success: false,\n error: finalMetadata.error || \"Unknown error occurred\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.message || \"Request failed\",\n };\n }\n }\n\n /**\n * Stream answer using SSE\n */\n private async *streamAnswer(\n payload: Record<string, any>\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n yield {\n type: \"error\",\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (!reader) {\n yield { type: \"error\", error: \"No response body\" };\n return;\n }\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") {\n yield { type: \"done\" };\n continue;\n }\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && parsed.success === undefined) {\n yield {\n type: \"search_results\",\n search_results: parsed.search_results,\n };\n }\n // Handle content chunks\n else if (parsed.choices) {\n const delta = parsed.choices[0]?.delta || {};\n const content = delta.content || \"\";\n const finishReason = parsed.choices[0]?.finish_reason;\n\n if (content || finishReason) {\n yield { type: \"content\", content, finish_reason: finishReason };\n }\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n yield {\n type: \"metadata\",\n tx_id: parsed.tx_id,\n original_query: parsed.original_query,\n contents: parsed.contents,\n search_results: parsed.search_results,\n search_metadata: parsed.search_metadata,\n ai_usage: parsed.ai_usage,\n cost: parsed.cost,\n extraction_metadata: parsed.extraction_metadata,\n };\n }\n } catch {\n continue;\n }\n }\n }\n } catch (e: any) {\n yield { type: \"error\", error: e.message || \"Stream failed\" };\n }\n }\n\n /**\n * Create an error generator for streaming errors\n */\n private async *createErrorGenerator(\n error: string\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n yield { type: \"error\", error };\n }\n\n /**\n * Datasources: List all available datasources\n * @param options - Optional filter options\n * @param options.category - Filter by category (e.g., \"research\", \"markets\", \"healthcare\")\n * @returns Promise resolving to list of datasources with their metadata\n */\n private async _datasourcesList(\n options: DatasourcesListOptions = {}\n ): Promise<DatasourcesListResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.category) {\n params.append(\"category\", options.category);\n }\n\n const url = `${this.baseUrl}/datasources${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, datasources: response.data.datasources };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Datasources: Get all available categories\n * @returns Promise resolving to list of categories with their metadata\n */\n private async _datasourcesCategories(): Promise<DatasourcesCategoriesResponse> {\n try {\n const response = await axios.get(`${this.baseUrl}/datasources/categories`, {\n headers: this.headers,\n });\n\n return { success: true, categories: response.data.categories };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n}\n\nexport type {\n SearchResponse,\n SearchType,\n SearchResult,\n FeedbackSentiment,\n FeedbackResponse,\n SearchOptions,\n CountryCode,\n ResponseLength,\n ContentsOptions,\n ContentsResponse,\n ContentsAsyncJobResponse,\n ContentsJobResponse,\n ContentsJobStatus,\n ContentsJobWaitOptions,\n ContentResult,\n ContentResultSuccess,\n ContentResultFailed,\n ExtractEffort,\n ContentResponseLength,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerErrorResponse,\n AnswerStreamChunk,\n AnswerStreamChunkType,\n SearchMetadata,\n AIUsage,\n Cost,\n ExtractionMetadata,\n AlertEmailConfig,\n DeepResearchMode,\n DeepResearchStatus,\n DeepResearchOutputFormat,\n ImageType,\n ChartType,\n FileAttachment,\n MCPServerConfig,\n DeepResearchSearchConfig,\n DeepResearchCreateOptions,\n Progress,\n ChartDataPoint,\n ChartDataSeries,\n ImageMetadata,\n DeepResearchSource,\n DeepResearchUsage,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchTaskListItem,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n BatchStatus,\n BatchCounts,\n DeepResearchBatch,\n CreateBatchOptions,\n BatchTaskInput,\n AddBatchTasksOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksResponse,\n BatchTaskCreated,\n BatchTaskListItem,\n BatchPagination,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DatasourceCategoryId,\n DatasourceModality,\n DatasourcePricing,\n DatasourceCoverage,\n Datasource,\n DatasourceCategory,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n"],"mappings":";AAAA,SAAS,YAAY,uBAAuB;AAC5C,OAAO,WAAW;AA8ClB,SAAS,6B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/index.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from \"crypto\";\nimport axios from \"axios\";\nimport {\n SearchResponse,\n SearchType,\n SearchOptions,\n ContentsOptions,\n ContentsResponse,\n ContentsAsyncJobResponse,\n ContentsJobResponse,\n ContentsJobWaitOptions,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerStreamChunk,\n SearchResult,\n DeepResearchCreateOptions,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n CreateBatchOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksOptions,\n AddBatchTasksResponse,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DeepResearchBatch,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n\n/** Normalize API job response (snake_case) to SDK format (camelCase). */\nfunction normalizeContentsJobResponse(api: Record<string, any>): ContentsJobResponse {\n return {\n success: api.success ?? true,\n jobId: api.job_id ?? api.jobId,\n status: api.status ?? \"pending\",\n urlsTotal: api.urls_total ?? api.urlsTotal ?? 0,\n urlsProcessed: api.urls_processed ?? api.urlsProcessed ?? 0,\n urlsFailed: api.urls_failed ?? api.urlsFailed ?? 0,\n createdAt: api.created_at ?? api.createdAt ?? 0,\n updatedAt: api.updated_at ?? api.updatedAt ?? 0,\n currentBatch: api.current_batch ?? api.currentBatch,\n totalBatches: api.total_batches ?? api.totalBatches,\n results: api.results,\n actualCostDollars: api.actual_cost_dollars ?? api.actualCostDollars,\n error: api.error,\n webhookSecret: api.webhook_secret ?? api.webhookSecret,\n };\n}\n\n/** Normalize API async job creation response (202) to SDK format. */\nfunction normalizeContentsAsyncJobResponse(\n api: Record<string, any>\n): ContentsAsyncJobResponse {\n return {\n success: api.success ?? true,\n jobId: api.job_id ?? api.jobId,\n status: \"pending\",\n urlsTotal: api.urls_total ?? api.urlsTotal ?? 0,\n pollUrl: api.poll_url ?? api.pollUrl,\n webhookSecret: api.webhook_secret ?? api.webhookSecret,\n txId: api.tx_id ?? api.txId ?? \"\",\n };\n}\n\n/**\n * Verify webhook signature for Contents API async completion notifications.\n * Use the raw request body (not parsed JSON) as payload.\n * @param payload - Raw request body string\n * @param signature - X-Webhook-Signature header value\n * @param timestamp - X-Webhook-Timestamp header value\n * @param secret - webhookSecret from job creation\n */\nexport function verifyContentsWebhookSignature(\n payload: string,\n signature: string,\n timestamp: string,\n secret: string\n): boolean {\n const expected = createHmac(\"sha256\", secret)\n .update(`${timestamp}.${payload}`)\n .digest(\"hex\");\n const expectedSignature = `sha256=${expected}`;\n if (signature.length !== expectedSignature.length) return false;\n return timingSafeEqual(\n Buffer.from(signature, \"utf8\"),\n Buffer.from(expectedSignature, \"utf8\")\n );\n}\n\n// Valyu API client\nexport class Valyu {\n private baseUrl: string;\n private headers: Record<string, string>;\n\n // DeepResearch namespace\n public deepresearch: {\n create: (\n options: DeepResearchCreateOptions\n ) => Promise<DeepResearchCreateResponse>;\n status: (taskId: string) => Promise<DeepResearchStatusResponse>;\n wait: (\n taskId: string,\n options?: WaitOptions\n ) => Promise<DeepResearchStatusResponse>;\n stream: (taskId: string, callback: StreamCallback) => Promise<void>;\n list: (options: ListOptions) => Promise<DeepResearchListResponse>;\n update: (\n taskId: string,\n instruction: string\n ) => Promise<DeepResearchUpdateResponse>;\n cancel: (taskId: string) => Promise<DeepResearchCancelResponse>;\n delete: (taskId: string) => Promise<DeepResearchDeleteResponse>;\n togglePublic: (\n taskId: string,\n isPublic: boolean\n ) => Promise<DeepResearchTogglePublicResponse>;\n getAssets: (\n taskId: string,\n assetId: string,\n options?: DeepResearchGetAssetsOptions\n ) => Promise<DeepResearchGetAssetsResponse>;\n };\n\n // Batch API namespace\n public batch: {\n create: (options?: CreateBatchOptions) => Promise<CreateBatchResponse>;\n status: (batchId: string) => Promise<BatchStatusResponse>;\n addTasks: (\n batchId: string,\n options: AddBatchTasksOptions\n ) => Promise<AddBatchTasksResponse>;\n listTasks: (\n batchId: string,\n options?: ListBatchTasksOptions\n ) => Promise<ListBatchTasksResponse>;\n cancel: (batchId: string) => Promise<CancelBatchResponse>;\n list: (options?: ListBatchesOptions) => Promise<ListBatchesResponse>;\n waitForCompletion: (\n batchId: string,\n options?: BatchWaitOptions\n ) => Promise<DeepResearchBatch>;\n };\n\n // Datasources API namespace\n public datasources: {\n list: (options?: DatasourcesListOptions) => Promise<DatasourcesListResponse>;\n categories: () => Promise<DatasourcesCategoriesResponse>;\n };\n\n constructor(apiKey?: string, baseUrl: string = \"https://api.valyu.ai/v1\") {\n if (!apiKey) {\n apiKey = process.env.VALYU_API_KEY;\n if (!apiKey) {\n throw new Error(\"VALYU_API_KEY is not set\");\n }\n }\n this.baseUrl = baseUrl;\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n };\n\n // Initialize DeepResearch namespace\n this.deepresearch = {\n create: this._deepresearchCreate.bind(this),\n status: this._deepresearchStatus.bind(this),\n wait: this._deepresearchWait.bind(this),\n stream: this._deepresearchStream.bind(this),\n list: this._deepresearchList.bind(this),\n update: this._deepresearchUpdate.bind(this),\n cancel: this._deepresearchCancel.bind(this),\n delete: this._deepresearchDelete.bind(this),\n togglePublic: this._deepresearchTogglePublic.bind(this),\n getAssets: this._deepresearchGetAssets.bind(this),\n };\n\n // Initialize Batch namespace\n this.batch = {\n create: this._batchCreate.bind(this),\n status: this._batchStatus.bind(this),\n addTasks: this._batchAddTasks.bind(this),\n listTasks: this._batchListTasks.bind(this),\n cancel: this._batchCancel.bind(this),\n list: this._batchList.bind(this),\n waitForCompletion: this._batchWaitForCompletion.bind(this),\n };\n\n // Initialize Datasources namespace\n this.datasources = {\n list: this._datasourcesList.bind(this),\n categories: this._datasourcesCategories.bind(this),\n };\n }\n\n /**\n * Validates date format (YYYY-MM-DD)\n */\n private validateDateFormat(date: string): boolean {\n const dateRegex = /^\\d{4}-\\d{2}-\\d{2}$/;\n if (!dateRegex.test(date)) {\n return false;\n }\n const parsedDate = new Date(date);\n return parsedDate instanceof Date && !isNaN(parsedDate.getTime());\n }\n\n /**\n * Validates if a string is a valid URL\n */\n private validateUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Validates if a string is a valid domain (with optional path)\n */\n private validateDomain(domain: string): boolean {\n // Domain must have at least one dot and valid structure\n // Supports: example.com, example.com/path, subdomain.example.com/path/to/resource\n const domainRegex =\n /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\\/.+)?$/;\n return domainRegex.test(domain);\n }\n\n /**\n * Validates if a string is a valid dataset identifier (provider/datasetname)\n */\n private validateDatasetId(datasetId: string): boolean {\n // Dataset format: provider/datasetname (exactly one slash)\n // Provider and dataset name can contain alphanumeric, hyphens, underscores\n const parts = datasetId.split(\"/\");\n if (parts.length !== 2) return false;\n\n const providerRegex = /^[a-zA-Z0-9_-]+$/;\n const datasetRegex = /^[a-zA-Z0-9_-]+$/;\n\n return (\n providerRegex.test(parts[0]) &&\n datasetRegex.test(parts[1]) &&\n parts[0].length > 0 &&\n parts[1].length > 0\n );\n }\n\n /**\n * Validates source strings (domains, URLs, or dataset IDs)\n */\n private validateSource(source: string): boolean {\n // Check if it's a valid URL\n if (this.validateUrl(source)) {\n return true;\n }\n\n // Check if it's a valid domain (with optional path)\n if (this.validateDomain(source)) {\n return true;\n }\n\n // Check if it's a valid dataset identifier\n if (this.validateDatasetId(source)) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Validates an array of source strings\n */\n private validateSources(sources: string[]): {\n valid: boolean;\n invalidSources: string[];\n } {\n const invalidSources: string[] = [];\n\n for (const source of sources) {\n if (!this.validateSource(source)) {\n invalidSources.push(source);\n }\n }\n\n return {\n valid: invalidSources.length === 0,\n invalidSources,\n };\n }\n\n /**\n * Search for information using the Valyu DeepSearch API\n * @param query - The search query string\n * @param options - Search configuration options\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.maxNumResults - Maximum number of results (1-100)\n * @param options.maxPrice - Maximum price per thousand characters (CPM)\n * @param options.isToolCall - Whether this is a tool call\n * @param options.relevanceThreshold - Minimum relevance score (0-1)\n * @param options.includedSources - List of specific sources to include\n * @param options.excludeSources - List of URLs/domains to exclude from search results\n * @param options.category - Category filter for search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.countryCode - Country code filter for search results\n * @param options.responseLength - Response content length: \"short\"/\"medium\"/\"large\"/\"max\" or integer character count\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.urlOnly - Returns shortened snippets (default: false)\n * @returns Promise resolving to search results\n */\n async search(\n query: string,\n options: SearchOptions = {}\n ): Promise<SearchResponse> {\n try {\n // Default values\n const defaultSearchType: SearchType = \"all\";\n const defaultMaxNumResults = 10;\n const defaultIsToolCall = true;\n const defaultRelevanceThreshold = 0.5;\n\n // Validate searchType\n let finalSearchType: SearchType = defaultSearchType;\n const providedSearchTypeString = options.searchType?.toLowerCase();\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n } else if (options.searchType !== undefined) {\n return {\n success: false,\n error:\n \"Invalid searchType provided. Must be one of: all, web, proprietary, news\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return {\n success: false,\n error: \"Invalid startDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return {\n success: false,\n error: \"Invalid endDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate maxNumResults range\n const maxNumResults = options.maxNumResults ?? defaultMaxNumResults;\n if (maxNumResults < 1 || maxNumResults > 100) {\n return {\n success: false,\n error: \"maxNumResults must be between 1 and 100\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate includedSources format\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return {\n success: false,\n error: \"includedSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const includedSourcesValidation = this.validateSources(\n options.includedSources\n );\n if (!includedSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid includedSources format. Invalid sources: ${includedSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Validate excludeSources format\n if (options.excludeSources !== undefined) {\n if (!Array.isArray(options.excludeSources)) {\n return {\n success: false,\n error: \"excludeSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const excludeSourcesValidation = this.validateSources(\n options.excludeSources\n );\n if (!excludeSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid excludeSources format. Invalid sources: ${excludeSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n query,\n search_type: finalSearchType,\n max_num_results: maxNumResults,\n is_tool_call: options.isToolCall ?? defaultIsToolCall,\n relevance_threshold:\n options.relevanceThreshold ?? defaultRelevanceThreshold,\n };\n\n // Add maxPrice only if explicitly provided\n if (options.maxPrice !== undefined) {\n payload.max_price = options.maxPrice;\n }\n\n // Add optional parameters only if provided\n if (options.includedSources !== undefined) {\n payload.included_sources = options.includedSources;\n }\n\n if (options.excludeSources !== undefined) {\n payload.exclude_sources = options.excludeSources;\n }\n\n if (options.sourceBiases !== undefined) {\n payload.source_biases = options.sourceBiases;\n }\n\n if (options.category !== undefined) {\n payload.category = options.category;\n }\n\n if (options.startDate !== undefined) {\n payload.start_date = options.startDate;\n }\n\n if (options.endDate !== undefined) {\n payload.end_date = options.endDate;\n }\n\n if (options.countryCode !== undefined) {\n payload.country_code = options.countryCode;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.fastMode !== undefined) {\n payload.fast_mode = options.fastMode;\n }\n\n if (options.urlOnly !== undefined) {\n payload.url_only = options.urlOnly;\n }\n\n const response = await axios.post(`${this.baseUrl}/deepsearch`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n return response.data;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * Extract content from URLs with optional AI processing\n * @param urls - Array of URLs to process (max 10 sync, max 50 with async: true)\n * @param options - Content extraction configuration options\n * @param options.summary - AI summary configuration: false (raw), true (auto), string (custom), or JSON schema\n * @param options.extractEffort - Extraction thoroughness: \"normal\", \"high\", or \"auto\"\n * @param options.responseLength - Content length per URL\n * @param options.maxPriceDollars - Maximum cost limit in USD\n * @param options.screenshot - Request page screenshots (default: false)\n * @param options.async - Force async processing (required for >10 URLs)\n * @param options.webhookUrl - HTTPS URL for completion notification (async only)\n * @returns Promise resolving to sync results or async job (when async: true or >10 URLs)\n */\n async contents(\n urls: string[],\n options: ContentsOptions = {}\n ): Promise<ContentsResponse | ContentsAsyncJobResponse> {\n try {\n // Validate URLs array\n if (!urls || !Array.isArray(urls)) {\n return {\n success: false,\n error: \"urls must be an array\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length === 0) {\n return {\n success: false,\n error: \"urls array cannot be empty\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n const isAsync = options.async === true || urls.length > 10;\n\n if (urls.length > 10 && !options.async) {\n return {\n success: false,\n error:\n \"Requests with more than 10 URLs require async processing. Add async: true to the request.\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length > 50) {\n return {\n success: false,\n error: \"Maximum 50 URLs allowed per request\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate extractEffort if provided\n if (\n options.extractEffort &&\n ![\"normal\", \"high\", \"auto\"].includes(options.extractEffort)\n ) {\n return {\n success: false,\n error: \"extractEffort must be 'normal', 'high', or 'auto'\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate responseLength if provided\n if (options.responseLength !== undefined) {\n const validLengths = [\"short\", \"medium\", \"large\", \"max\"];\n if (\n typeof options.responseLength === \"string\" &&\n !validLengths.includes(options.responseLength)\n ) {\n return {\n success: false,\n error:\n \"responseLength must be 'short', 'medium', 'large', 'max', or a number\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n if (\n typeof options.responseLength === \"number\" &&\n options.responseLength <= 0\n ) {\n return {\n success: false,\n error: \"responseLength number must be positive\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n urls,\n };\n\n // Add optional parameters only if provided\n if (options.summary !== undefined) {\n payload.summary = options.summary;\n }\n\n if (options.extractEffort !== undefined) {\n payload.extract_effort = options.extractEffort;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.maxPriceDollars !== undefined) {\n payload.max_price_dollars = options.maxPriceDollars;\n }\n\n if (options.screenshot !== undefined) {\n payload.screenshot = options.screenshot;\n }\n\n if (isAsync) {\n payload.async = true;\n }\n if (options.webhookUrl !== undefined) {\n payload.webhook_url = options.webhookUrl;\n }\n\n const response = await axios.post(`${this.baseUrl}/contents`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error || \"Request failed\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // 202 Accepted - async job created\n if (response.status === 202) {\n return normalizeContentsAsyncJobResponse(response.data);\n }\n\n return response.data as ContentsResponse;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * Get async Contents job status and results\n * @param jobId - Job ID from contents() async response\n * @returns Promise resolving to job status\n */\n async getContentsJob(jobId: string): Promise<ContentsJobResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/contents/jobs/${jobId}`,\n { headers: this.headers }\n );\n return normalizeContentsJobResponse(response.data);\n } catch (e: any) {\n const errData = e.response?.data;\n const status = e.response?.status;\n return {\n success: false,\n jobId,\n status: \"failed\",\n urlsTotal: 0,\n urlsProcessed: 0,\n urlsFailed: 0,\n createdAt: 0,\n updatedAt: 0,\n error:\n errData?.error ||\n (status === 403\n ? \"Forbidden - you do not have access to this job\"\n : status === 404\n ? `Job ${jobId} not found`\n : e.message),\n };\n }\n }\n\n /**\n * Wait for async Contents job completion (polls until terminal state)\n * @param jobId - Job ID from contents() async response\n * @param options - Wait configuration (pollInterval, maxWaitTime, onProgress)\n * @returns Promise resolving to final job status with results\n */\n async waitForJob(\n jobId: string,\n options: ContentsJobWaitOptions = {}\n ): Promise<ContentsJobResponse> {\n const pollInterval = options.pollInterval ?? 5000;\n const maxWaitTime = options.maxWaitTime ?? 7200000;\n const startTime = Date.now();\n\n while (true) {\n const status = await this.getContentsJob(jobId);\n\n if (!status.success && status.error) {\n throw new Error(status.error);\n }\n\n if (options.onProgress) {\n options.onProgress(status);\n }\n\n if (\n status.status === \"completed\" ||\n status.status === \"partial\" ||\n status.status === \"failed\"\n ) {\n return status;\n }\n\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * DeepResearch: Create a new research task\n * @param options.search - Search configuration options\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n */\n private async _deepresearchCreate(\n options: DeepResearchCreateOptions\n ): Promise<DeepResearchCreateResponse> {\n try {\n // Use query field (input is supported for backward compatibility)\n const queryValue = options.query ?? options.input;\n\n // Validation\n if (!queryValue?.trim()) {\n return {\n success: false,\n error: \"query is required and cannot be empty\",\n };\n }\n\n // Build payload with snake_case\n // Prefer mode over model (backward compatible)\n const mode = options.mode ?? options.model;\n const payload: Record<string, any> = {\n query: queryValue,\n mode: mode || \"fast\", // API defaults to \"standard\", but we keep \"fast\" for backward compatibility\n output_formats: options.outputFormats || [\"markdown\"],\n code_execution: options.codeExecution !== false,\n };\n\n // Add optional fields\n if (options.strategy) payload.strategy = options.strategy;\n if (options.researchStrategy)\n payload.research_strategy = options.researchStrategy;\n if (options.reportFormat)\n payload.report_format = options.reportFormat;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.sourceBiases) {\n payload.search.source_biases = options.search.sourceBiases;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.urls) payload.urls = options.urls;\n if (options.files) payload.files = options.files;\n if (options.deliverables) payload.deliverables = options.deliverables;\n if (options.mcpServers) payload.mcp_servers = options.mcpServers;\n if (options.previousReports) {\n payload.previous_reports = options.previousReports;\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.brandCollectionId)\n payload.brand_collection_id = options.brandCollectionId;\n if (options.alertEmail) {\n if (typeof options.alertEmail === \"string\") {\n payload.alert_email = options.alertEmail;\n } else {\n payload.alert_email = {\n email: options.alertEmail.email,\n custom_url: options.alertEmail.custom_url,\n };\n }\n }\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task status\n */\n private async _deepresearchStatus(\n taskId: string\n ): Promise<DeepResearchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/status`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Wait for task completion with polling\n */\n private async _deepresearchWait(\n taskId: string,\n options: WaitOptions = {}\n ): Promise<DeepResearchStatusResponse> {\n const pollInterval = options.pollInterval || 5000;\n const maxWaitTime = options.maxWaitTime || 7200000;\n const startTime = Date.now();\n\n while (true) {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n throw new Error(status.error);\n }\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(status);\n }\n\n // Terminal states\n if (\n status.status === \"completed\" ||\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n return status;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * DeepResearch: Stream real-time updates\n */\n private async _deepresearchStream(\n taskId: string,\n callback: StreamCallback\n ): Promise<void> {\n let isComplete = false;\n let lastMessageCount = 0;\n\n while (!isComplete) {\n try {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n if (callback.onError) {\n callback.onError(new Error(status.error));\n }\n return;\n }\n\n // Progress updates\n if (status.progress && callback.onProgress) {\n callback.onProgress(\n status.progress.current_step,\n status.progress.total_steps\n );\n }\n\n // New messages\n if (status.messages && callback.onMessage) {\n const newMessages = status.messages.slice(lastMessageCount);\n newMessages.forEach((msg) => callback.onMessage!(msg));\n lastMessageCount = status.messages.length;\n }\n\n // Terminal states\n if (status.status === \"completed\") {\n if (callback.onComplete) {\n callback.onComplete(status);\n }\n isComplete = true;\n } else if (\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n if (callback.onError) {\n callback.onError(\n new Error(status.error || `Task ${status.status}`)\n );\n }\n isComplete = true;\n }\n\n if (!isComplete) {\n await new Promise((resolve) => setTimeout(resolve, 5000));\n }\n } catch (error: any) {\n if (callback.onError) {\n callback.onError(error);\n }\n throw error;\n }\n }\n }\n\n /**\n * DeepResearch: List all tasks\n */\n private async _deepresearchList(\n options?: ListOptions\n ): Promise<DeepResearchListResponse> {\n try {\n const limit = options?.limit || 10;\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/list?limit=${limit}`,\n { headers: this.headers }\n );\n\n return { success: true, data: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Add follow-up instruction\n */\n private async _deepresearchUpdate(\n taskId: string,\n instruction: string\n ): Promise<DeepResearchUpdateResponse> {\n try {\n if (!instruction?.trim()) {\n return {\n success: false,\n error: \"instruction is required and cannot be empty\",\n };\n }\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/update`,\n { instruction },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Cancel task\n */\n private async _deepresearchCancel(\n taskId: string\n ): Promise<DeepResearchCancelResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Delete task\n */\n private async _deepresearchDelete(\n taskId: string\n ): Promise<DeepResearchDeleteResponse> {\n try {\n const response = await axios.delete(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/delete`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Toggle public flag\n */\n private async _deepresearchTogglePublic(\n taskId: string,\n isPublic: boolean\n ): Promise<DeepResearchTogglePublicResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/public`,\n { public: isPublic },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task assets (images, deliverables, PDFs)\n */\n private async _deepresearchGetAssets(\n taskId: string,\n assetId: string,\n options: DeepResearchGetAssetsOptions = {}\n ): Promise<DeepResearchGetAssetsResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.token) {\n params.append(\"token\", options.token);\n }\n\n // Build headers - use API key if no token provided\n const headers: Record<string, string> = {};\n if (!options.token) {\n headers[\"x-api-key\"] = this.headers[\"x-api-key\"];\n }\n\n const url = `${\n this.baseUrl\n }/deepresearch/tasks/${taskId}/assets/${assetId}${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n\n const response = await axios.get(url, {\n headers,\n responseType: \"arraybuffer\", // For binary data\n });\n\n return {\n success: true,\n data: Buffer.from(response.data),\n contentType:\n response.headers[\"content-type\"] || \"application/octet-stream\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Create a new batch\n * @param options - Batch configuration options\n * @param options.name - Optional name for the batch\n * @param options.model - DeepResearch mode: \"fast\", \"standard\", or \"heavy\" (default: \"standard\")\n * @param options.outputFormats - Output formats for tasks (default: [\"markdown\"])\n * @param options.search - Search configuration for all tasks in batch\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n * @param options.webhookUrl - Optional HTTPS URL for completion notification\n * @param options.metadata - Optional metadata key-value pairs\n * @returns Promise resolving to batch creation response with batch_id and webhook_secret\n */\n private async _batchCreate(\n options: CreateBatchOptions = {}\n ): Promise<CreateBatchResponse> {\n try {\n const payload: Record<string, any> = {};\n\n if (options.name) payload.name = options.name;\n // Accept both mode (preferred) and model (backward compatible)\n const mode = options.mode ?? options.model;\n if (mode) payload.mode = mode;\n if (options.outputFormats) payload.output_formats = options.outputFormats;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.sourceBiases) {\n payload.search.source_biases = options.search.sourceBiases;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Get batch status\n * @param batchId - The batch ID to query\n * @returns Promise resolving to batch status with counts and usage\n */\n private async _batchStatus(batchId: string): Promise<BatchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/batches/${batchId}`,\n { headers: this.headers }\n );\n\n return { success: true, batch: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Add tasks to a batch\n * @param batchId - The batch ID to add tasks to\n * @param options - Task configuration options\n * @param options.tasks - Array of task inputs (use 'query' field for each task)\n * @returns Promise resolving to response with added, tasks array, counts, and batch_id\n */\n private async _batchAddTasks(\n batchId: string,\n options: AddBatchTasksOptions\n ): Promise<AddBatchTasksResponse> {\n try {\n if (!options.tasks || !Array.isArray(options.tasks)) {\n return {\n success: false,\n error: \"tasks must be an array\",\n };\n }\n\n if (options.tasks.length === 0) {\n return {\n success: false,\n error: \"tasks array cannot be empty\",\n };\n }\n\n if (options.tasks.length > 100) {\n return {\n success: false,\n error: \"Maximum 100 tasks allowed per request\",\n };\n }\n\n // Validate that each task has a query\n for (const task of options.tasks) {\n if (!task.query && !task.input) {\n return {\n success: false,\n error: \"Each task must have a 'query' field\",\n };\n }\n }\n\n // Convert tasks to snake_case format for API\n // Note: Tasks can only include: id, query, strategy, urls, metadata\n // Tasks inherit model, output_formats, and search_params from batch\n const tasksPayload = options.tasks.map((task) => {\n const taskPayload: Record<string, any> = {};\n\n // Use query field (input is supported for backward compatibility)\n const queryValue = task.query ?? task.input;\n if (queryValue) {\n taskPayload.query = queryValue;\n }\n\n if (task.id) taskPayload.id = task.id;\n if (task.strategy) taskPayload.strategy = task.strategy;\n if (task.researchStrategy)\n taskPayload.research_strategy = task.researchStrategy;\n if (task.reportFormat)\n taskPayload.report_format = task.reportFormat;\n if (task.urls) taskPayload.urls = task.urls;\n if (task.metadata) taskPayload.metadata = task.metadata;\n\n return taskPayload;\n });\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/tasks`,\n { tasks: tasksPayload },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all tasks in a batch\n * @param batchId - The batch ID to query\n * @param options - Optional pagination and filtering options\n * @param options.status - Filter by status: \"queued\", \"running\", \"completed\", \"failed\", or \"cancelled\"\n * @param options.limit - Maximum number of tasks to return\n * @param options.lastKey - Pagination token from previous response\n * @returns Promise resolving to list of tasks with their status and pagination info\n */\n private async _batchListTasks(\n batchId: string,\n options: ListBatchTasksOptions = {}\n ): Promise<ListBatchTasksResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.status) {\n params.append(\"status\", options.status);\n }\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n if (options.lastKey) {\n params.append(\"last_key\", options.lastKey);\n }\n if (options.includeOutput !== undefined) {\n params.append(\"include_output\", options.includeOutput.toString());\n }\n\n const url = `${this.baseUrl}/deepresearch/batches/${batchId}/tasks${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Cancel a batch and all its pending tasks\n * @param batchId - The batch ID to cancel\n * @returns Promise resolving to cancellation confirmation\n */\n private async _batchCancel(batchId: string): Promise<CancelBatchResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all batches\n * @param options - Optional options\n * @param options.limit - Maximum number of batches to return\n * @returns Promise resolving to list of all batches\n */\n private async _batchList(\n options: ListBatchesOptions = {}\n ): Promise<ListBatchesResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n\n const url = `${this.baseUrl}/deepresearch/batches${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, {\n headers: this.headers,\n });\n\n return { success: true, batches: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Wait for batch completion with polling\n * @param batchId - The batch ID to wait for\n * @param options - Wait configuration options\n * @param options.pollInterval - Polling interval in milliseconds (default: 10000)\n * @param options.maxWaitTime - Maximum wait time in milliseconds (default: 7200000)\n * @param options.onProgress - Callback for progress updates\n * @returns Promise resolving to final batch status\n */\n private async _batchWaitForCompletion(\n batchId: string,\n options: BatchWaitOptions = {}\n ): Promise<DeepResearchBatch> {\n const pollInterval = options.pollInterval || 10000; // 10 seconds default\n const maxWaitTime = options.maxWaitTime || 7200000; // 2 hours default\n const startTime = Date.now();\n\n while (true) {\n const statusResponse = await this._batchStatus(batchId);\n\n if (!statusResponse.success || !statusResponse.batch) {\n throw new Error(statusResponse.error || \"Failed to get batch status\");\n }\n\n const batch = statusResponse.batch;\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(batch);\n }\n\n // Terminal states\n if (\n batch.status === \"completed\" ||\n batch.status === \"completed_with_errors\" ||\n batch.status === \"cancelled\"\n ) {\n return batch;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * Get AI-powered answers using the Valyu Answer API\n * @param query - The question or query string\n * @param options - Answer configuration options\n * @param options.structuredOutput - JSON Schema object for structured responses\n * @param options.systemInstructions - Custom system-level instructions (max 2000 chars)\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.dataMaxPrice - Maximum spend (USD) for data retrieval\n * @param options.countryCode - Country code filter for search results\n * @param options.includedSources - List of specific sources to include\n * @param options.excludedSources - List of URLs/domains to exclude from search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.streaming - Enable streaming mode (default: false)\n * @returns Promise resolving to answer response, or AsyncGenerator for streaming\n */\n async answer(\n query: string,\n options: AnswerOptions = {}\n ): Promise<\n AnswerResponse | AsyncGenerator<AnswerStreamChunk, void, unknown>\n > {\n // Validate inputs first\n const validationError = this.validateAnswerParams(query, options);\n if (validationError) {\n if (options.streaming) {\n return this.createErrorGenerator(validationError);\n }\n return { success: false, error: validationError };\n }\n\n const payload = this.buildAnswerPayload(query, options);\n\n if (options.streaming) {\n return this.streamAnswer(payload);\n } else {\n return this.fetchAnswer(payload);\n }\n }\n\n /**\n * Validate answer parameters\n */\n private validateAnswerParams(\n query: string,\n options: AnswerOptions\n ): string | null {\n // Validate query\n if (!query || typeof query !== \"string\" || query.trim().length === 0) {\n return \"Query is required and must be a non-empty string\";\n }\n\n // Validate searchType\n const providedSearchTypeString = options.searchType?.toLowerCase();\n if (\n providedSearchTypeString !== undefined &&\n providedSearchTypeString !== \"web\" &&\n providedSearchTypeString !== \"proprietary\" &&\n providedSearchTypeString !== \"all\" &&\n providedSearchTypeString !== \"news\"\n ) {\n return \"Invalid searchType provided. Must be one of: all, web, proprietary, news\";\n }\n\n // Validate systemInstructions\n if (options.systemInstructions !== undefined) {\n if (typeof options.systemInstructions !== \"string\") {\n return \"systemInstructions must be a string\";\n }\n const trimmed = options.systemInstructions.trim();\n if (trimmed.length === 0) {\n return \"systemInstructions cannot be empty when provided\";\n }\n if (trimmed.length > 2000) {\n return \"systemInstructions must be 2000 characters or less\";\n }\n }\n\n // Validate dataMaxPrice\n if (options.dataMaxPrice !== undefined) {\n if (\n typeof options.dataMaxPrice !== \"number\" ||\n options.dataMaxPrice <= 0\n ) {\n return \"dataMaxPrice must be a positive number\";\n }\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return \"Invalid startDate format. Must be YYYY-MM-DD\";\n }\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return \"Invalid endDate format. Must be YYYY-MM-DD\";\n }\n if (options.startDate && options.endDate) {\n const startDate = new Date(options.startDate);\n const endDate = new Date(options.endDate);\n if (startDate > endDate) {\n return \"startDate must be before endDate\";\n }\n }\n\n // Validate sources\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return \"includedSources must be an array\";\n }\n const validation = this.validateSources(options.includedSources);\n if (!validation.valid) {\n return `Invalid includedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n if (options.excludedSources !== undefined) {\n if (!Array.isArray(options.excludedSources)) {\n return \"excludedSources must be an array\";\n }\n const validation = this.validateSources(options.excludedSources);\n if (!validation.valid) {\n return `Invalid excludedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n\n return null;\n }\n\n /**\n * Build payload for answer API\n */\n private buildAnswerPayload(\n query: string,\n options: AnswerOptions\n ): Record<string, any> {\n const defaultSearchType: SearchType = \"all\";\n const providedSearchTypeString = options.searchType?.toLowerCase();\n let finalSearchType: SearchType = defaultSearchType;\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n }\n\n const payload: Record<string, any> = {\n query: query.trim(),\n search_type: finalSearchType,\n };\n\n if (options.dataMaxPrice !== undefined)\n payload.data_max_price = options.dataMaxPrice;\n if (options.structuredOutput !== undefined)\n payload.structured_output = options.structuredOutput;\n if (options.systemInstructions !== undefined)\n payload.system_instructions = options.systemInstructions.trim();\n if (options.countryCode !== undefined)\n payload.country_code = options.countryCode;\n if (options.includedSources !== undefined)\n payload.included_sources = options.includedSources;\n if (options.excludedSources !== undefined)\n payload.excluded_sources = options.excludedSources;\n if (options.startDate !== undefined) payload.start_date = options.startDate;\n if (options.endDate !== undefined) payload.end_date = options.endDate;\n if (options.fastMode !== undefined) payload.fast_mode = options.fastMode;\n\n return payload;\n }\n\n /**\n * Fetch answer (non-streaming mode)\n */\n private async fetchAnswer(\n payload: Record<string, any>\n ): Promise<AnswerResponse> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n return {\n success: false,\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n }\n\n // Collect streamed data into final response\n let fullContent = \"\";\n let searchResults: SearchResult[] = [];\n let finalMetadata: any = {};\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (reader) {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") continue;\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && !parsed.success) {\n searchResults = [...searchResults, ...parsed.search_results];\n }\n // Handle content chunks\n else if (parsed.choices) {\n const content = parsed.choices[0]?.delta?.content || \"\";\n if (content) fullContent += content;\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n finalMetadata = parsed;\n }\n } catch {\n continue;\n }\n }\n }\n }\n\n // Build final response\n if (finalMetadata.success) {\n const finalSearchResults =\n finalMetadata.search_results || searchResults;\n const response: AnswerSuccessResponse = {\n success: true,\n tx_id: finalMetadata.tx_id || \"\",\n original_query: finalMetadata.original_query || payload.query,\n contents: finalMetadata.contents || fullContent || \"\",\n search_results: finalSearchResults,\n search_metadata: finalMetadata.search_metadata || {\n tx_ids: [],\n number_of_results: 0,\n total_characters: 0,\n },\n ai_usage: finalMetadata.ai_usage || {\n input_tokens: 0,\n output_tokens: 0,\n },\n cost: finalMetadata.cost || {\n total_deduction_dollars: 0,\n search_deduction_dollars: 0,\n ai_deduction_dollars: 0,\n },\n };\n if (finalMetadata.extraction_metadata) {\n response.extraction_metadata = finalMetadata.extraction_metadata;\n }\n return response;\n }\n\n return {\n success: false,\n error: finalMetadata.error || \"Unknown error occurred\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.message || \"Request failed\",\n };\n }\n }\n\n /**\n * Stream answer using SSE\n */\n private async *streamAnswer(\n payload: Record<string, any>\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n yield {\n type: \"error\",\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (!reader) {\n yield { type: \"error\", error: \"No response body\" };\n return;\n }\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") {\n yield { type: \"done\" };\n continue;\n }\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && parsed.success === undefined) {\n yield {\n type: \"search_results\",\n search_results: parsed.search_results,\n };\n }\n // Handle content chunks\n else if (parsed.choices) {\n const delta = parsed.choices[0]?.delta || {};\n const content = delta.content || \"\";\n const finishReason = parsed.choices[0]?.finish_reason;\n\n if (content || finishReason) {\n yield { type: \"content\", content, finish_reason: finishReason };\n }\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n yield {\n type: \"metadata\",\n tx_id: parsed.tx_id,\n original_query: parsed.original_query,\n contents: parsed.contents,\n search_results: parsed.search_results,\n search_metadata: parsed.search_metadata,\n ai_usage: parsed.ai_usage,\n cost: parsed.cost,\n extraction_metadata: parsed.extraction_metadata,\n };\n }\n } catch {\n continue;\n }\n }\n }\n } catch (e: any) {\n yield { type: \"error\", error: e.message || \"Stream failed\" };\n }\n }\n\n /**\n * Create an error generator for streaming errors\n */\n private async *createErrorGenerator(\n error: string\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n yield { type: \"error\", error };\n }\n\n /**\n * Datasources: List all available datasources\n * @param options - Optional filter options\n * @param options.category - Filter by category (e.g., \"research\", \"markets\", \"healthcare\")\n * @returns Promise resolving to list of datasources with their metadata\n */\n private async _datasourcesList(\n options: DatasourcesListOptions = {}\n ): Promise<DatasourcesListResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.category) {\n params.append(\"category\", options.category);\n }\n\n const url = `${this.baseUrl}/datasources${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, datasources: response.data.datasources };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Datasources: Get all available categories\n * @returns Promise resolving to list of categories with their metadata\n */\n private async _datasourcesCategories(): Promise<DatasourcesCategoriesResponse> {\n try {\n const response = await axios.get(`${this.baseUrl}/datasources/categories`, {\n headers: this.headers,\n });\n\n return { success: true, categories: response.data.categories };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n}\n\nexport type {\n SearchResponse,\n SearchType,\n SearchResult,\n FeedbackSentiment,\n FeedbackResponse,\n SearchOptions,\n CountryCode,\n ResponseLength,\n ContentsOptions,\n ContentsResponse,\n ContentsAsyncJobResponse,\n ContentsJobResponse,\n ContentsJobStatus,\n ContentsJobWaitOptions,\n ContentResult,\n ContentResultSuccess,\n ContentResultFailed,\n ExtractEffort,\n ContentResponseLength,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerErrorResponse,\n AnswerStreamChunk,\n AnswerStreamChunkType,\n SearchMetadata,\n AIUsage,\n Cost,\n ExtractionMetadata,\n AlertEmailConfig,\n DeepResearchMode,\n DeepResearchStatus,\n DeepResearchOutputFormat,\n ImageType,\n ChartType,\n FileAttachment,\n MCPServerConfig,\n DeepResearchSearchConfig,\n DeepResearchCreateOptions,\n Progress,\n ChartDataPoint,\n ChartDataSeries,\n ImageMetadata,\n DeepResearchSource,\n DeepResearchUsage,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchTaskListItem,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n BatchStatus,\n BatchCounts,\n DeepResearchBatch,\n CreateBatchOptions,\n BatchTaskInput,\n AddBatchTasksOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksResponse,\n BatchTaskCreated,\n BatchTaskListItem,\n BatchPagination,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DatasourceCategoryId,\n DatasourceModality,\n DatasourcePricing,\n DatasourceCoverage,\n Datasource,\n DatasourceCategory,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n"],"mappings":";AAAA,SAAS,YAAY,uBAAuB;AAC5C,OAAO,WAAW;AA8ClB,SAAS,6BAA6B,KAA+C;AACnF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E,UAAU,MAAM,SAAS,EAAE;AAAA,MACtC;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,yBAAiE;AAC7E,QAAI;AACF,YAAM,WAAW,MAAM,MAAM,IAAI,GAAG,KAAK,OAAO,2BAA2B;AAAA,QACzE,SAAS,KAAK;AAAA,MAChB,CAAC;AAED,aAAO,EAAE,SAAS,MAAM,YAAY,SAAS,KAAK,WAAW;AAAA,IAC/D,SAAS,GAAQ;AACf,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,EAAE,UAAU,MAAM,SAAS,EAAE;AAAA,MACtC;AAAA,IACF;AAAA,EACF;AACF;","names":["response"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "valyu-js",
3
- "version": "2.5.9",
3
+ "version": "2.6.1",
4
4
  "description": "Deepsearch API for AI.",
5
5
  "files": [
6
6
  "dist"