@framers/agentos-ext-deep-research 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +98 -0
  2. package/dist/ResearchService.d.ts +106 -0
  3. package/dist/ResearchService.d.ts.map +1 -0
  4. package/dist/ResearchService.js +450 -0
  5. package/dist/ResearchService.js.map +1 -0
  6. package/dist/engine/DeepResearchEngine.d.ts +40 -0
  7. package/dist/engine/DeepResearchEngine.d.ts.map +1 -0
  8. package/dist/engine/DeepResearchEngine.js +557 -0
  9. package/dist/engine/DeepResearchEngine.js.map +1 -0
  10. package/dist/engine/DeepResearchTool.d.ts +27 -0
  11. package/dist/engine/DeepResearchTool.d.ts.map +1 -0
  12. package/dist/engine/DeepResearchTool.js +118 -0
  13. package/dist/engine/DeepResearchTool.js.map +1 -0
  14. package/dist/engine/FirecrawlClient.d.ts +49 -0
  15. package/dist/engine/FirecrawlClient.d.ts.map +1 -0
  16. package/dist/engine/FirecrawlClient.js +101 -0
  17. package/dist/engine/FirecrawlClient.js.map +1 -0
  18. package/dist/engine/ResearchBudgetTracker.d.ts +36 -0
  19. package/dist/engine/ResearchBudgetTracker.d.ts.map +1 -0
  20. package/dist/engine/ResearchBudgetTracker.js +68 -0
  21. package/dist/engine/ResearchBudgetTracker.js.map +1 -0
  22. package/dist/engine/index.d.ts +9 -0
  23. package/dist/engine/index.d.ts.map +1 -0
  24. package/dist/engine/index.js +34 -0
  25. package/dist/engine/index.js.map +1 -0
  26. package/dist/engine/prompts.d.ts +14 -0
  27. package/dist/engine/prompts.d.ts.map +1 -0
  28. package/dist/engine/prompts.js +67 -0
  29. package/dist/engine/prompts.js.map +1 -0
  30. package/dist/engine/types.d.ts +133 -0
  31. package/dist/engine/types.d.ts.map +1 -0
  32. package/dist/engine/types.js +18 -0
  33. package/dist/engine/types.js.map +1 -0
  34. package/dist/index.d.ts +53 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +161 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/tools/academic.d.ts +41 -0
  39. package/dist/tools/academic.d.ts.map +1 -0
  40. package/dist/tools/academic.js +42 -0
  41. package/dist/tools/academic.js.map +1 -0
  42. package/dist/tools/aggregate.d.ts +44 -0
  43. package/dist/tools/aggregate.d.ts.map +1 -0
  44. package/dist/tools/aggregate.js +39 -0
  45. package/dist/tools/aggregate.js.map +1 -0
  46. package/dist/tools/investigate.d.ts +44 -0
  47. package/dist/tools/investigate.d.ts.map +1 -0
  48. package/dist/tools/investigate.js +39 -0
  49. package/dist/tools/investigate.js.map +1 -0
  50. package/dist/tools/scrape.d.ts +36 -0
  51. package/dist/tools/scrape.d.ts.map +1 -0
  52. package/dist/tools/scrape.js +38 -0
  53. package/dist/tools/scrape.js.map +1 -0
  54. package/dist/tools/trending.d.ts +35 -0
  55. package/dist/tools/trending.d.ts.map +1 -0
  56. package/dist/tools/trending.js +37 -0
  57. package/dist/tools/trending.js.map +1 -0
  58. package/manifest.json +25 -0
  59. package/package.json +35 -0
package/LICENSE ADDED
@@ -0,0 +1,98 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License.
30
+
31
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License.
34
+
35
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
36
+
37
+ 4. Redistribution.
38
+
39
+ You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
40
+
41
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
42
+
43
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
44
+
45
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
46
+
47
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
48
+
49
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
50
+
51
+ 5. Submission of Contributions.
52
+
53
+ Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
54
+
55
+ 6. Trademarks.
56
+
57
+ This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
58
+
59
+ 7. Disclaimer of Warranty.
60
+
61
+ Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
62
+
63
+ 8. Limitation of Liability.
64
+
65
+ In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
66
+
67
+ 9. Accepting Warranty or Additional Liability.
68
+
69
+ While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
70
+
71
+ END OF TERMS AND CONDITIONS
72
+
73
+ APPENDIX: How to apply the Apache License to your work.
74
+
75
+ To apply the Apache License to your work, attach the following
76
+ boilerplate notice, with the fields enclosed by brackets "[]"
77
+ replaced with your own identifying information. (Don't include
78
+ the brackets!) The text should be enclosed in the appropriate
79
+ comment syntax for the file format. We also recommend that a
80
+ file or class name and description of purpose be included on the
81
+ same "printed page" as the copyright notice for easier
82
+ identification within third-party archives.
83
+
84
+ Copyright (c) 2025 Framers
85
+
86
+ Licensed under the Apache License, Version 2.0 (the "License");
87
+ you may not use this file except in compliance with the License.
88
+ You may obtain a copy of the License at
89
+
90
+ http://www.apache.org/licenses/LICENSE-2.0
91
+
92
+ Unless required by applicable law or agreed to in writing, software
93
+ distributed under the License is distributed on an "AS IS" BASIS,
94
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
95
+ See the License for the specific language governing permissions and
96
+ limitations under the License.
97
+
98
+
@@ -0,0 +1,106 @@
1
+ /**
2
+ * @fileoverview Deep Research service layer.
3
+ *
4
+ * Provides multi-source investigation, academic search, content scraping,
5
+ * aggregate search, and trend discovery via HTTP APIs.
6
+ */
7
+ export interface ResearchConfig {
8
+ serperApiKey: string;
9
+ braveApiKey?: string;
10
+ serpApiKey?: string;
11
+ }
12
+ export interface InvestigationResult {
13
+ query: string;
14
+ sources: string[];
15
+ findings: Array<{
16
+ source: string;
17
+ title: string;
18
+ snippet: string;
19
+ url: string;
20
+ relevance: number;
21
+ }>;
22
+ crossReferences: Array<{
23
+ claim: string;
24
+ supportedBy: string[];
25
+ confidence: number;
26
+ }>;
27
+ summary: string;
28
+ }
29
+ export interface AcademicResult {
30
+ title: string;
31
+ authors: string[];
32
+ abstract: string;
33
+ url: string;
34
+ year?: number;
35
+ citations?: number;
36
+ source: string;
37
+ }
38
+ export interface ScrapeResult {
39
+ url: string;
40
+ type: string;
41
+ title: string;
42
+ content: string;
43
+ metadata: Record<string, unknown>;
44
+ }
45
+ export interface AggregateResult {
46
+ engine: string;
47
+ results: Array<{
48
+ title: string;
49
+ snippet: string;
50
+ url: string;
51
+ position: number;
52
+ }>;
53
+ }
54
+ export interface TrendingResult {
55
+ platform: string;
56
+ trends: Array<{
57
+ title: string;
58
+ description?: string;
59
+ url?: string;
60
+ score?: number;
61
+ category?: string;
62
+ }>;
63
+ fetchedAt: string;
64
+ }
65
+ export declare class ResearchService {
66
+ private config;
67
+ private httpClient;
68
+ private running;
69
+ constructor(config: ResearchConfig);
70
+ initialize(): Promise<void>;
71
+ shutdown(): Promise<void>;
72
+ get isRunning(): boolean;
73
+ investigate(query: string, sources?: string[], maxResults?: number): Promise<InvestigationResult>;
74
+ searchAcademic(query: string, opts?: {
75
+ source?: string;
76
+ maxResults?: number;
77
+ }): Promise<AcademicResult[]>;
78
+ scrapeContent(url: string, type?: string): Promise<ScrapeResult>;
79
+ aggregateSearch(query: string, engines?: string[], maxResults?: number): Promise<AggregateResult[]>;
80
+ discoverTrending(platform?: string, category?: string): Promise<TrendingResult>;
81
+ private serperSearch;
82
+ private braveSearch;
83
+ private serpApiSearch;
84
+ private searchArxiv;
85
+ private searchGoogleScholar;
86
+ private searchSemanticScholar;
87
+ private scrapeYouTube;
88
+ private scrapeWikipedia;
89
+ private scrapeGeneric;
90
+ private getHackerNewsTrends;
91
+ /** Map common category keywords to actual subreddit names. */
92
+ private static readonly REDDIT_CATEGORY_MAP;
93
+ /**
94
+ * Fetch raw JSON from any Reddit URL by appending .json.
95
+ * Works for subreddits, posts, user profiles, search results, etc.
96
+ * Example: reddit.com/r/programming → reddit.com/r/programming.json
97
+ */
98
+ fetchRedditJson(redditUrl: string): Promise<any>;
99
+ private getRedditTrends;
100
+ private getYouTubeTrends;
101
+ private getTwitterTrends;
102
+ private extractYouTubeId;
103
+ private buildCrossReferences;
104
+ private requireRunning;
105
+ }
106
+ //# sourceMappingURL=ResearchService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ResearchService.d.ts","sourceRoot":"","sources":["../src/ResearchService.ts"],"names":[],"mappings":"AACA;;;;;GAKG;AAQH,MAAM,WAAW,cAAc;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,QAAQ,EAAE,KAAK,CAAC;QACd,MAAM,EAAE,MAAM,CAAC;QACf,KAAK,EAAE,MAAM,CAAC;QACd,OAAO,EAAE,MAAM,CAAC;QAChB,GAAG,EAAE,MAAM,CAAC;QACZ,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC,CAAC;IACH,eAA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AO,CAAC,cAAc;CAGvB"}
@@ -0,0 +1,450 @@
1
+ "use strict";
2
+ // @ts-nocheck
3
+ /**
4
+ * @fileoverview Deep Research service layer.
5
+ *
6
+ * Provides multi-source investigation, academic search, content scraping,
7
+ * aggregate search, and trend discovery via HTTP APIs.
8
+ */
9
+ var __importDefault = (this && this.__importDefault) || function (mod) {
10
+ return (mod && mod.__esModule) ? mod : { "default": mod };
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.ResearchService = void 0;
14
+ const axios_1 = __importDefault(require("axios"));
15
+ // ---------------------------------------------------------------------------
16
+ // Service
17
+ // ---------------------------------------------------------------------------
18
+ class ResearchService {
19
+ constructor(config) {
20
+ this.running = false;
21
+ this.config = config;
22
+ this.httpClient = axios_1.default.create({ timeout: 30000 });
23
+ }
24
+ async initialize() {
25
+ this.running = true;
26
+ }
27
+ async shutdown() {
28
+ this.running = false;
29
+ }
30
+ get isRunning() {
31
+ return this.running;
32
+ }
33
+ // ── Multi-Source Investigation ──
34
+ async investigate(query, sources = ['web', 'academic', 'news'], maxResults = 10) {
35
+ this.requireRunning();
36
+ const findings = [];
37
+ // Search across requested sources
38
+ for (const source of sources) {
39
+ try {
40
+ switch (source) {
41
+ case 'web': {
42
+ const webResults = await this.serperSearch(query, 'search', maxResults);
43
+ for (const r of webResults) {
44
+ findings.push({ source: 'web', title: r.title, snippet: r.snippet, url: r.link, relevance: 0.8 });
45
+ }
46
+ break;
47
+ }
48
+ case 'academic': {
49
+ const papers = await this.searchAcademic(query, { source: 'arxiv', maxResults });
50
+ for (const p of papers) {
51
+ findings.push({ source: 'academic', title: p.title, snippet: p.abstract.slice(0, 300), url: p.url, relevance: 0.9 });
52
+ }
53
+ break;
54
+ }
55
+ case 'news': {
56
+ const newsResults = await this.serperSearch(query, 'news', maxResults);
57
+ for (const r of newsResults) {
58
+ findings.push({ source: 'news', title: r.title, snippet: r.snippet, url: r.link, relevance: 0.7 });
59
+ }
60
+ break;
61
+ }
62
+ case 'social': {
63
+ const socialResults = await this.serperSearch(`${query} site:reddit.com OR site:twitter.com`, 'search', maxResults);
64
+ for (const r of socialResults) {
65
+ findings.push({ source: 'social', title: r.title, snippet: r.snippet, url: r.link, relevance: 0.6 });
66
+ }
67
+ break;
68
+ }
69
+ }
70
+ }
71
+ catch {
72
+ // Continue with other sources if one fails
73
+ }
74
+ }
75
+ // Cross-reference findings by looking for overlapping claims
76
+ const crossReferences = this.buildCrossReferences(findings);
77
+ return {
78
+ query,
79
+ sources,
80
+ findings: findings.slice(0, maxResults),
81
+ crossReferences,
82
+ summary: `Found ${findings.length} results across ${sources.length} sources with ${crossReferences.length} cross-references.`,
83
+ };
84
+ }
85
+ // ── Academic Search ──
86
+ async searchAcademic(query, opts = {}) {
87
+ this.requireRunning();
88
+ const source = opts.source ?? 'arxiv';
89
+ const maxResults = opts.maxResults ?? 10;
90
+ switch (source) {
91
+ case 'arxiv':
92
+ return this.searchArxiv(query, maxResults);
93
+ case 'scholar':
94
+ return this.searchGoogleScholar(query, maxResults);
95
+ case 'semantic':
96
+ return this.searchSemanticScholar(query, maxResults);
97
+ default:
98
+ return this.searchArxiv(query, maxResults);
99
+ }
100
+ }
101
+ // ── Content Scraping ──
102
+ async scrapeContent(url, type = 'generic') {
103
+ this.requireRunning();
104
+ switch (type) {
105
+ case 'youtube':
106
+ return this.scrapeYouTube(url);
107
+ case 'wikipedia':
108
+ return this.scrapeWikipedia(url);
109
+ case 'blog':
110
+ case 'generic':
111
+ default:
112
+ return this.scrapeGeneric(url);
113
+ }
114
+ }
115
+ // ── Aggregate Search ──
116
+ async aggregateSearch(query, engines = ['serper'], maxResults = 10) {
117
+ this.requireRunning();
118
+ const results = [];
119
+ for (const engine of engines) {
120
+ try {
121
+ switch (engine) {
122
+ case 'serper': {
123
+ const serperResults = await this.serperSearch(query, 'search', maxResults);
124
+ results.push({
125
+ engine: 'serper',
126
+ results: serperResults.map((r, i) => ({
127
+ title: r.title,
128
+ snippet: r.snippet,
129
+ url: r.link,
130
+ position: i + 1,
131
+ })),
132
+ });
133
+ break;
134
+ }
135
+ case 'brave': {
136
+ if (!this.config.braveApiKey)
137
+ break;
138
+ const braveResults = await this.braveSearch(query, maxResults);
139
+ results.push({
140
+ engine: 'brave',
141
+ results: braveResults.map((r, i) => ({
142
+ title: r.title,
143
+ snippet: r.description,
144
+ url: r.url,
145
+ position: i + 1,
146
+ })),
147
+ });
148
+ break;
149
+ }
150
+ case 'serpapi': {
151
+ if (!this.config.serpApiKey)
152
+ break;
153
+ const serpResults = await this.serpApiSearch(query, maxResults);
154
+ results.push({
155
+ engine: 'serpapi',
156
+ results: serpResults.map((r, i) => ({
157
+ title: r.title,
158
+ snippet: r.snippet,
159
+ url: r.link,
160
+ position: i + 1,
161
+ })),
162
+ });
163
+ break;
164
+ }
165
+ }
166
+ }
167
+ catch {
168
+ // Continue with other engines
169
+ }
170
+ }
171
+ return results;
172
+ }
173
+ // ── Trend Discovery ──
174
+ async discoverTrending(platform = 'hackernews', category) {
175
+ this.requireRunning();
176
+ switch (platform) {
177
+ case 'hackernews':
178
+ return this.getHackerNewsTrends(category);
179
+ case 'reddit':
180
+ return this.getRedditTrends(category);
181
+ case 'youtube':
182
+ return this.getYouTubeTrends(category);
183
+ case 'twitter':
184
+ return this.getTwitterTrends(category);
185
+ default:
186
+ return this.getHackerNewsTrends(category);
187
+ }
188
+ }
189
+ // ── Private: Search Providers ──
190
+ async serperSearch(query, type, maxResults) {
191
+ const response = await this.httpClient.post('https://google.serper.dev/search', { q: query, type, num: maxResults }, { headers: { 'X-API-KEY': this.config.serperApiKey, 'Content-Type': 'application/json' } });
192
+ return response.data.organic ?? response.data.news ?? [];
193
+ }
194
+ async braveSearch(query, maxResults) {
195
+ const response = await this.httpClient.get('https://api.search.brave.com/res/v1/web/search', {
196
+ params: { q: query, count: maxResults },
197
+ headers: { 'Accept': 'application/json', 'Accept-Encoding': 'gzip', 'X-Subscription-Token': this.config.braveApiKey },
198
+ });
199
+ return response.data.web?.results ?? [];
200
+ }
201
+ async serpApiSearch(query, maxResults) {
202
+ const response = await this.httpClient.get('https://serpapi.com/search', {
203
+ params: { q: query, api_key: this.config.serpApiKey, num: maxResults, engine: 'google' },
204
+ });
205
+ return response.data.organic_results ?? [];
206
+ }
207
+ // ── Private: Academic Providers ──
208
+ async searchArxiv(query, maxResults) {
209
+ const response = await this.httpClient.get('http://export.arxiv.org/api/query', {
210
+ params: { search_query: `all:${query}`, start: 0, max_results: maxResults },
211
+ });
212
+ const entries = response.data.match(/<entry>([\s\S]*?)<\/entry>/g) ?? [];
213
+ return entries.map((entry) => {
214
+ const title = entry.match(/<title>([\s\S]*?)<\/title>/)?.[1]?.trim() ?? '';
215
+ const abstract = entry.match(/<summary>([\s\S]*?)<\/summary>/)?.[1]?.trim() ?? '';
216
+ const url = entry.match(/<id>([\s\S]*?)<\/id>/)?.[1]?.trim() ?? '';
217
+ const authorMatches = entry.match(/<name>([\s\S]*?)<\/name>/g) ?? [];
218
+ const authors = authorMatches.map((a) => a.replace(/<\/?name>/g, '').trim());
219
+ const published = entry.match(/<published>([\s\S]*?)<\/published>/)?.[1]?.trim() ?? '';
220
+ const year = published ? new Date(published).getFullYear() : undefined;
221
+ return { title, authors, abstract, url, year, source: 'arxiv' };
222
+ });
223
+ }
224
+ async searchGoogleScholar(query, maxResults) {
225
+ // Use Serper's scholar endpoint as a proxy for Google Scholar
226
+ const response = await this.httpClient.post('https://google.serper.dev/scholar', { q: query, num: maxResults }, { headers: { 'X-API-KEY': this.config.serperApiKey, 'Content-Type': 'application/json' } });
227
+ return (response.data.organic ?? []).map((r) => ({
228
+ title: r.title ?? '',
229
+ authors: r.publication_info?.authors?.map((a) => a.name) ?? [],
230
+ abstract: r.snippet ?? '',
231
+ url: r.link ?? '',
232
+ year: r.publication_info?.year,
233
+ citations: r.inline_links?.cited_by?.total,
234
+ source: 'scholar',
235
+ }));
236
+ }
237
+ async searchSemanticScholar(query, maxResults) {
238
+ const response = await this.httpClient.get('https://api.semanticscholar.org/graph/v1/paper/search', {
239
+ params: { query, limit: maxResults, fields: 'title,authors,abstract,url,year,citationCount' },
240
+ });
241
+ return (response.data.data ?? []).map((p) => ({
242
+ title: p.title ?? '',
243
+ authors: (p.authors ?? []).map((a) => a.name),
244
+ abstract: p.abstract ?? '',
245
+ url: p.url ?? `https://www.semanticscholar.org/paper/${p.paperId}`,
246
+ year: p.year,
247
+ citations: p.citationCount,
248
+ source: 'semantic',
249
+ }));
250
+ }
251
+ // ── Private: Content Scrapers ──
252
+ async scrapeYouTube(url) {
253
+ const videoId = this.extractYouTubeId(url);
254
+ // Use YouTube's oEmbed endpoint for metadata
255
+ const oembedRes = await this.httpClient.get(`https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${videoId}&format=json`);
256
+ return {
257
+ url,
258
+ type: 'youtube',
259
+ title: oembedRes.data.title ?? '',
260
+ content: `Video: ${oembedRes.data.title}\nAuthor: ${oembedRes.data.author_name}\nChannel: ${oembedRes.data.author_url}`,
261
+ metadata: { videoId, author: oembedRes.data.author_name, thumbnail: oembedRes.data.thumbnail_url },
262
+ };
263
+ }
264
+ async scrapeWikipedia(url) {
265
+ // Extract article title from URL or use as-is
266
+ const titleMatch = url.match(/\/wiki\/(.+?)(?:#|$|\?)/);
267
+ const title = titleMatch ? decodeURIComponent(titleMatch[1]) : url;
268
+ const response = await this.httpClient.get('https://en.wikipedia.org/api/rest_v1/page/summary/' + encodeURIComponent(title));
269
+ return {
270
+ url: response.data.content_urls?.desktop?.page ?? url,
271
+ type: 'wikipedia',
272
+ title: response.data.title ?? title,
273
+ content: response.data.extract ?? '',
274
+ metadata: { description: response.data.description, thumbnail: response.data.thumbnail?.source },
275
+ };
276
+ }
277
+ async scrapeGeneric(url) {
278
+ const response = await this.httpClient.get(url, {
279
+ headers: { 'User-Agent': 'AgentOS-DeepResearch/0.1.0', 'Accept': 'text/html,application/xhtml+xml' },
280
+ timeout: 15000,
281
+ });
282
+ const html = response.data;
283
+ const title = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1]?.trim() ?? '';
284
+ // Basic HTML to text conversion
285
+ const bodyMatch = html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
286
+ const bodyHtml = bodyMatch?.[1] ?? html;
287
+ const content = bodyHtml
288
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
289
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
290
+ .replace(/<[^>]+>/g, ' ')
291
+ .replace(/\s+/g, ' ')
292
+ .trim()
293
+ .slice(0, 10000);
294
+ return { url, type: 'generic', title, content, metadata: {} };
295
+ }
296
+ // ── Private: Trend Providers ──
297
+ async getHackerNewsTrends(_category) {
298
+ const response = await this.httpClient.get('https://hacker-news.firebaseio.com/v0/topstories.json');
299
+ const ids = response.data.slice(0, 20);
300
+ const stories = await Promise.all(ids.map((id) => this.httpClient.get(`https://hacker-news.firebaseio.com/v0/item/${id}.json`).then((r) => r.data)));
301
+ return {
302
+ platform: 'hackernews',
303
+ trends: stories.map((s) => ({
304
+ title: s.title ?? '',
305
+ description: s.text?.slice(0, 200),
306
+ url: s.url ?? `https://news.ycombinator.com/item?id=${s.id}`,
307
+ score: s.score,
308
+ })),
309
+ fetchedAt: new Date().toISOString(),
310
+ };
311
+ }
312
+ /**
313
+ * Fetch raw JSON from any Reddit URL by appending .json.
314
+ * Works for subreddits, posts, user profiles, search results, etc.
315
+ * Example: reddit.com/r/programming → reddit.com/r/programming.json
316
+ */
317
+ async fetchRedditJson(redditUrl) {
318
+ // Normalize: strip trailing slash, ensure .json suffix
319
+ let url = redditUrl.replace(/\/+$/, '');
320
+ if (!url.endsWith('.json')) {
321
+ // Strip query params, add .json, re-add query params
322
+ const [base, query] = url.split('?');
323
+ url = `${base}.json${query ? `?${query}` : ''}`;
324
+ }
325
+ // Ensure https://www.reddit.com prefix
326
+ if (!url.startsWith('http')) {
327
+ url = `https://www.reddit.com${url.startsWith('/') ? '' : '/'}${url}`;
328
+ }
329
+ const response = await this.httpClient.get(url, {
330
+ headers: { 'User-Agent': 'AgentOS-DeepResearch/0.1.0' },
331
+ });
332
+ return response.data ?? response;
333
+ }
334
+ async getRedditTrends(category) {
335
+ // Resolve category to real subreddit(s)
336
+ const key = (category ?? '').toLowerCase().replace(/[^a-z]/g, '');
337
+ const subreddits = ResearchService.REDDIT_CATEGORY_MAP[key] ?? [category ?? 'all'];
338
+ // Fetch from multiple subreddits in parallel
339
+ const allPosts = [];
340
+ await Promise.all(subreddits.map(async (sub) => {
341
+ try {
342
+ const response = await this.httpClient.get(`https://www.reddit.com/r/${sub}/hot.json?limit=10`, { headers: { 'User-Agent': 'AgentOS-DeepResearch/0.1.0' } });
343
+ const posts = response.data?.data?.children ?? [];
344
+ allPosts.push(...posts);
345
+ }
346
+ catch {
347
+ // Subreddit may not exist or be private — skip silently
348
+ }
349
+ }));
350
+ // Sort by score and deduplicate
351
+ const seen = new Set();
352
+ const unique = allPosts
353
+ .filter((p) => {
354
+ const id = p.data?.id;
355
+ if (!id || seen.has(id))
356
+ return false;
357
+ seen.add(id);
358
+ return true;
359
+ })
360
+ .sort((a, b) => (b.data?.score ?? 0) - (a.data?.score ?? 0))
361
+ .slice(0, 20);
362
+ return {
363
+ platform: 'reddit',
364
+ trends: unique.map((p) => ({
365
+ title: p.data.title ?? '',
366
+ description: p.data.selftext?.slice(0, 200),
367
+ url: `https://reddit.com${p.data.permalink}`,
368
+ score: p.data.score,
369
+ category: p.data.subreddit,
370
+ })),
371
+ fetchedAt: new Date().toISOString(),
372
+ };
373
+ }
374
+ async getYouTubeTrends(_category) {
375
+ // Use Serper to search for trending YouTube content
376
+ const results = await this.serperSearch('site:youtube.com trending', 'search', 20);
377
+ return {
378
+ platform: 'youtube',
379
+ trends: results.map((r) => ({
380
+ title: r.title ?? '',
381
+ description: r.snippet,
382
+ url: r.link,
383
+ })),
384
+ fetchedAt: new Date().toISOString(),
385
+ };
386
+ }
387
+ async getTwitterTrends(_category) {
388
+ // Use Serper to search for Twitter/X trending topics
389
+ const results = await this.serperSearch('site:twitter.com OR site:x.com trending now', 'news', 20);
390
+ return {
391
+ platform: 'twitter',
392
+ trends: results.map((r) => ({
393
+ title: r.title ?? '',
394
+ description: r.snippet,
395
+ url: r.link,
396
+ })),
397
+ fetchedAt: new Date().toISOString(),
398
+ };
399
+ }
400
+ // ── Private: Helpers ──
401
+ extractYouTubeId(url) {
402
+ const match = url.match(/(?:v=|\/embed\/|youtu\.be\/|\/v\/)([a-zA-Z0-9_-]{11})/);
403
+ return match?.[1] ?? url;
404
+ }
405
+ buildCrossReferences(findings) {
406
+ const titleWords = new Map();
407
+ for (const f of findings) {
408
+ const words = f.title.toLowerCase().split(/\s+/).filter((w) => w.length > 4);
409
+ for (const word of words) {
410
+ const sources = titleWords.get(word) ?? [];
411
+ if (!sources.includes(f.source)) {
412
+ sources.push(f.source);
413
+ titleWords.set(word, sources);
414
+ }
415
+ }
416
+ }
417
+ const crossRefs = [];
418
+ for (const [word, sources] of titleWords) {
419
+ if (sources.length >= 2) {
420
+ crossRefs.push({
421
+ claim: word,
422
+ supportedBy: sources,
423
+ confidence: Math.min(sources.length / 4, 1),
424
+ });
425
+ }
426
+ }
427
+ return crossRefs.slice(0, 10);
428
+ }
429
+ requireRunning() {
430
+ if (!this.running)
431
+ throw new Error('ResearchService not initialized');
432
+ }
433
+ }
434
+ exports.ResearchService = ResearchService;
435
+ /** Map common category keywords to actual subreddit names. */
436
+ ResearchService.REDDIT_CATEGORY_MAP = {
437
+ 'indiehackers': ['SideProject', 'indiebiz', 'EntrepreneurRideAlong', 'microsaas'],
438
+ 'saas': ['SaaS', 'microsaas', 'startups'],
439
+ 'marketvalidation': ['Entrepreneur', 'startups', 'smallbusiness'],
440
+ 'techtrends': ['technology', 'programming', 'webdev'],
441
+ 'ai': ['artificial', 'MachineLearning', 'LocalLLaMA'],
442
+ 'startup': ['startups', 'Entrepreneur', 'smallbusiness'],
443
+ 'webdev': ['webdev', 'javascript', 'reactjs'],
444
+ 'crypto': ['CryptoCurrency', 'ethereum', 'defi'],
445
+ 'devtools': ['devops', 'selfhosted', 'opensource'],
446
+ 'marketing': ['digital_marketing', 'SEO', 'socialmedia'],
447
+ 'design': ['web_design', 'UI_Design', 'userexperience'],
448
+ 'remote': ['remotework', 'digitalnomad', 'WorkOnline'],
449
+ };
450
+ //# sourceMappingURL=ResearchService.js.map