@j-o-r/hello-dave 0.0.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 (53) hide show
  1. package/LICENSE +73 -0
  2. package/README.md +207 -0
  3. package/bin/hdAsk.js +103 -0
  4. package/bin/hdClear.js +13 -0
  5. package/bin/hdCode.js +110 -0
  6. package/bin/hdConnect.js +230 -0
  7. package/bin/hdInspect.js +28 -0
  8. package/bin/hdNpm.js +114 -0
  9. package/bin/hdPrompt.js +108 -0
  10. package/examples/claude-test.js +89 -0
  11. package/examples/claude.js +143 -0
  12. package/examples/gpt.js +127 -0
  13. package/examples/gpt_code.js +125 -0
  14. package/examples/gpt_note_keeping.js +117 -0
  15. package/examples/grok.js +119 -0
  16. package/examples/grok_code.js +114 -0
  17. package/examples/grok_note_keeping.js +111 -0
  18. package/lib/API/anthropic.com/text.js +402 -0
  19. package/lib/API/brave.com/search.js +239 -0
  20. package/lib/API/openai.com/README.md +1 -0
  21. package/lib/API/openai.com/reponses/MESSAGES.md +69 -0
  22. package/lib/API/openai.com/reponses/text.js +416 -0
  23. package/lib/API/x.ai/text.js +415 -0
  24. package/lib/AgentClient.js +197 -0
  25. package/lib/AgentManager.js +144 -0
  26. package/lib/AgentServer.js +336 -0
  27. package/lib/Cli.js +256 -0
  28. package/lib/Prompt.js +728 -0
  29. package/lib/Session.js +231 -0
  30. package/lib/ToolSet.js +186 -0
  31. package/lib/fafs.js +93 -0
  32. package/lib/genericToolset.js +170 -0
  33. package/lib/index.js +34 -0
  34. package/lib/promptHelpers.js +132 -0
  35. package/lib/testToolset.js +42 -0
  36. package/module.md +189 -0
  37. package/package.json +49 -0
  38. package/types/API/anthropic.com/text.d.ts +207 -0
  39. package/types/API/brave.com/search.d.ts +156 -0
  40. package/types/API/openai.com/reponses/text.d.ts +225 -0
  41. package/types/API/x.ai/text.d.ts +286 -0
  42. package/types/AgentClient.d.ts +70 -0
  43. package/types/AgentManager.d.ts +112 -0
  44. package/types/AgentServer.d.ts +38 -0
  45. package/types/Cli.d.ts +52 -0
  46. package/types/Prompt.d.ts +298 -0
  47. package/types/Session.d.ts +31 -0
  48. package/types/ToolSet.d.ts +95 -0
  49. package/types/fafs.d.ts +47 -0
  50. package/types/genericToolset.d.ts +3 -0
  51. package/types/index.d.ts +23 -0
  52. package/types/promptHelpers.d.ts +1 -0
  53. package/types/testToolset.d.ts +3 -0
@@ -0,0 +1,239 @@
1
+ import Session from '../../Session.js';
2
+ import { jsType } from '../../fafs.js';
3
+ import { request as doRequest } from '@j-o-r/apiserver';
4
+ /**
5
+ * @typedef {import('../../ToolSet.js').default} ToolSet
6
+ */
7
+ /**
8
+ * @typedef {object} BraveRequest
9
+ * @property {BRSearchAPIHeaders} headers
10
+ * @property {string} url
11
+ *
12
+ * @typedef {object} BRSearchOptions
13
+ *
14
+ * @property {string} [q] - question
15
+ * @property {string} [country] - Country Code
16
+ * @property {string} [search_lang] - The 2 or more character language code for which the search results are provided.
17
+ * @property {string} [ui_lang] - Usually of the format <language_code>-<country_code> RFC 9110
18
+ * @property {number} [count] - The number of search results returned in response. The maximum is 20
19
+ * @property {number} [offset] - The zero based offset that indicates number of search results per page (count) to skip before returning the result.
20
+ * @property {string} [safesearch] - off, moderate, strict
21
+ * @property {string} [freshness] - pd (24 h) pw (1 week) pm (1 month) py (1 year) , YYYY-MM-DDtoYYYY-MM-DD (range 2022-04-01to2022-07-30)
22
+ * @property {boolean} [text_decoration] - Whether display strings (e.g. result snippets) should include decoration markers (e.g. highlighting characters).
23
+ * @property {boolean} [spellcheck] - Whether to spellcheck provided query.
24
+ * @property {string} [result_filter] - discussions,faq,infobox,news,query,summarizer,videos,web
25
+ * @property {string} [goggles_id] - Goggles act as a custom re-ranking on top of Brave’s search index
26
+ * @property {string} [units] - metric , imperial
27
+ * @property {boolean} [extra_snippets] - (only pro plan) A snippet is an excerpt from a page you get as a result of the query
28
+ * @property {number} [summary] - 1 | 0 (only pro plan) This parameter enables summary key generation in web search results.
29
+ *
30
+ * @typedef {Object} BRSearchAPIHeaders
31
+ * @property {string} [Accept="application/json"] - The default supported media type is application/json.
32
+ * @property {string} [AcceptEncoding="gzip"] - The supported compression type is gzip.
33
+ * @property {string} [ContentType="application/json"] -
34
+ * @property {string} [ApiVersion] - The Brave Web Search API version to use, denoted by the format YYYY-MM-DD. The latest version is used by default.
35
+ * @property {string} [CacheControl] - Search will return cached web search results by default. To prevent caching, set the Cache-Control header to no-cache.
36
+ * @property {string} [UserAgent] - The user agent of the client sending the request. Search can utilize the user agent to provide a different experience depending on the client.
37
+ * @property {number} [XLocLat] - The latitude of the client's geographical location in degrees, to provide relevant local results. Must be >= -90.0 and <= +90.0 degrees.
38
+ * @property {number} [XLocLong] - The longitude of the client's geographical location in degrees, to provide relevant local results. Must be >= -180.0 and <= +180.0 degrees.
39
+ * @property {string} [XLocTimezone] - The IANA timezone for the client's device.
40
+ * @property {string} [XLocCity] - The generic name of the client city.
41
+ * @property {string} [XLocState] - The code representing the client’s state/region, can be up to 3 characters long.
42
+ * @property {string} [XLocStateName] - The name of the client's state/region.
43
+ * @property {string} [XLocCountry] - The two-letter code for the client's country.
44
+ * @property {string} [XLocPostalCode] - The client's postal code.
45
+ * @property {string} [XSubscriptionToken] - The secret token for the subscribed plan to authenticate the request. Can be obtained from API Keys.
46
+ */
47
+ const API_URL = 'https://api.search.brave.com/res/v1/web/search';
48
+ /** @type {BRSearchOptions} */
49
+ const defaultBraveSettings = {
50
+ q: '',
51
+ country: 'NL',
52
+ search_lang: 'en',
53
+ ui_lang: 'en-US',
54
+ count: 10,
55
+ offset: 0,
56
+ safesearch: 'off',
57
+ freshness: '',
58
+ text_decoration: false,
59
+ spellcheck: true,
60
+ // discussions' or 'faq' or 'infobox' or 'news' or 'query' or 'videos' or 'web' or 'summarizer' or 'locations'
61
+ result_filter: 'discussions,faq,infobox,news,query,summarizer,videos,web',
62
+ units: 'metric',
63
+ summary: 0,
64
+ };
65
+
66
+
67
+ /**
68
+ * Get the default headers
69
+ * @returns {object}
70
+ */
71
+ const getBraveHeaders = () => {
72
+ if (!process.env['BRAVESEARCHKEY']) {
73
+ throw new Error('Missing BRAVESEARCHKEY! export BRAVESEARCHKEY=<BRAVE_SEARCH_KEY>');
74
+ }
75
+ const KEY = process.env['BRAVESEARCHKEY'];
76
+ /** @type {BRSearchAPIHeaders} */
77
+ return {
78
+ 'ContentType': 'application/json',
79
+ 'Accept': 'application/json',
80
+ 'XSubscriptionToken': `${KEY}`
81
+ }
82
+ }
83
+ /**
84
+ * @param {string} propertyName
85
+ * @return {string}
86
+ */
87
+ function translatePropertyNameToHeaderName(propertyName) {
88
+ return propertyName
89
+ // Insert a hyphen before each uppercase letter or number that is either preceded by a lowercase letter or followed by an uppercase letter.
90
+ .replace(/([a-z])([A-Z0-9])|([A-Z0-9])([A-Z])/g, '$1$3-$2$4')
91
+ // Convert the entire string to lowercase to match header naming conventions.
92
+ .toLowerCase();
93
+ }
94
+
95
+ /**
96
+ * Recursively converts all object keys to camelCase.
97
+ * @param {Object} obj - The original object.
98
+ * @returns {Object} A new object with all keys converted to camelCase.
99
+ */
100
+ function toHeaders(obj) {
101
+ return Object.entries(obj).reduce((newObj, [key, value]) => {
102
+ // @ts-ignore
103
+ newObj[translatePropertyNameToHeaderName(key)] = value;
104
+ return newObj;
105
+ }, {});
106
+ }
107
+ /** To query params
108
+ * @param {object} obj
109
+ * @retuns {string}
110
+ */
111
+ const objectToQueryString = (obj) => {
112
+ const params = new URLSearchParams();
113
+ for (const key in obj) {
114
+ if (obj.hasOwnProperty(key)) {
115
+ // @ts-ignore
116
+ params.append(key, obj[key]);
117
+ }
118
+ }
119
+ return params.toString();
120
+ }
121
+ /**
122
+ * Create an brave search request
123
+ * It will use the last message as the search query to stay compatible with the prompt/records logic
124
+ * @param {string} query
125
+ * @param {BRSearchOptions} [opts] overwrite default request settings
126
+ * @param {BRSearchAPIHeaders} [hdrs] - optional headers to pass
127
+ * @returns {BraveRequest}
128
+ * @throws {Error}
129
+ */
130
+ const generateRequest = (query, opts = {}, hdrs = {}) => {
131
+ /** @type {BRSearchOptions} */
132
+ if (
133
+ jsType(query) !== 'String' ||
134
+ query.split('\n').length > 1 ||
135
+ query.trim() === '') {
136
+ throw Error('Brave Search query invalid string (query can only contain one line');
137
+ }
138
+ /** @type {BRSearchOptions} */
139
+ const options = { ...defaultBraveSettings, ...opts };
140
+ const headers = toHeaders({ ...getBraveHeaders(), ...hdrs });
141
+
142
+ if (query.trim() === '' || query.split('\n').length > 1) {
143
+ }
144
+ options.q = query;
145
+ const params = objectToQueryString(options)
146
+ return { headers, url: API_URL + `?${params}` };
147
+ };
148
+
149
+ /// ---------------------------------------------------
150
+
151
+ /*
152
+ * @param {string[]} sums
153
+ * @returns {string}
154
+ */
155
+ const extractSummary = (sums) => {
156
+ if (!sums) {
157
+ sums = [];
158
+ }
159
+ let result = '';
160
+ let i = 0;
161
+ const len = sums.length
162
+ for (; i < len; i++) {
163
+ result = result + sums[i] + '\n\n';
164
+ }
165
+ return result;
166
+ }
167
+
168
+ /**
169
+ * Converts an array of objects to a markdown string.
170
+ * @param {Array<object>} entries - The array of objects.
171
+ * @returns {string} - The combined markdown string.
172
+ */
173
+ function convertToMarkdown(entries) {
174
+ return entries.map((entry, index) => {
175
+ // @ts-ignore
176
+ let content = `### ${index + 1}. ${entry.title}\n\n${entry.description}\n\n[${entry.subtype} link](${entry.url})\n`;
177
+ // @ts-ignore
178
+ if (entry.extra_snippets) {
179
+ // @ts-ignore
180
+ content = `${content}\n${entry.extra_snippets.join('\n')}\n`;
181
+ }
182
+ return content;
183
+ }).join('\n');
184
+ }
185
+
186
+ /**
187
+ * Process an openai response
188
+ * @param {object} response
189
+ * @returns {string}
190
+ * @throws {Error}
191
+ */
192
+ const parseResponse = (response) => {
193
+ // @ts-ignore
194
+ if (response.query['bad_results'] === false && response['web'] && response['web']['results'] && response.web.results.length > 0) {
195
+ // @ts-ignore
196
+ const sum = extractSummary(response.summary);
197
+ const msg = convertToMarkdown(response.web.results)
198
+ return sum + msg;
199
+ } else {
200
+ return 'No results.'
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Create an brave search request
206
+ * It will use the last message as the search query to stay compatible with the prompt/records logic
207
+ * @param {string} query
208
+ * @param {BRSearchOptions} [opts] overwrite default request settings
209
+ * @param {BRSearchAPIHeaders} [hdrs] - optional headers to pass
210
+ * @throws {Error}
211
+ * @returns {Promise<import('../../ToolSet.js').TSCallResponse>}
212
+ */
213
+ async function request(query, opts = {}, hdrs = {}) {
214
+ /** @type {import('lib/Prompt').PRRecord[]} */
215
+ const records = [];
216
+ const record = Session.templateRecord();
217
+ const start = new Date().getTime();
218
+ const { headers, url } = generateRequest(query, opts, hdrs)
219
+ const res = await doRequest(url, 'GET', headers);
220
+ record.model = 'search';
221
+ record.id = 'ts:' + new Date().getTime();
222
+ record.environment = 'search.brave.com';
223
+ record.isoDate = new Date().toISOString();
224
+ record.tokensIn = 1;
225
+ record.tokensOut = 1;
226
+ record.duration = new Date().getTime() - start;
227
+ if (res.status !== 200) {
228
+ new Error(`${res.status}: response.response`)
229
+ }
230
+ records.push(record);
231
+ const response = parseResponse(res.response);
232
+ return { response, records }
233
+ }
234
+
235
+ export {
236
+ generateRequest,
237
+ parseResponse,
238
+ request
239
+ }
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,69 @@
1
+ ## Message RESPONSE types OPENAI
2
+
3
+ ### message output in json examples:
4
+ **tool calls**
5
+ Tool calls are function_requests PRFunctionRequest
6
+ ```
7
+ [
8
+ {
9
+ "index": 0,
10
+ "message": {
11
+ "role": "assistant",
12
+ "content": "\n",
13
+ "tool_calls": [
14
+ {
15
+ "id": "call_43974044",
16
+ "function": {
17
+ "name": "get_date_time",
18
+ "arguments": "{}"
19
+ },
20
+ "type": "function"
21
+ },
22
+ {
23
+ "id": "call_08990177",
24
+ "function": {
25
+ "name": "get_current_weather",
26
+ "arguments": "{\"location\":\"Amsterdam, The Netherlands\"}"
27
+ },
28
+ "type": "function"
29
+ }
30
+ ],
31
+ "refusal": null
32
+ },
33
+ "finish_reason": "stop"
34
+ }
35
+ ]
36
+
37
+ ```
38
+ ** assistant answer **
39
+ ```
40
+ [
41
+ {
42
+ "index": 0,
43
+ "message": {
44
+ "role": "assistant",
45
+ "content": "\n",
46
+ "tool_calls": [
47
+ {
48
+ "id": "call_43974044",
49
+ "function": {
50
+ "name": "get_date_time",
51
+ "arguments": "{}"
52
+ },
53
+ "type": "function"
54
+ },
55
+ {
56
+ "id": "call_08990177",
57
+ "function": {
58
+ "name": "get_current_weather",
59
+ "arguments": "{\"location\":\"Amsterdam, The Netherlands\"}"
60
+ },
61
+ "type": "function"
62
+ }
63
+ ],
64
+ "refusal": null
65
+ },
66
+ "finish_reason": "stop"
67
+ }
68
+ ]
69
+ ```