@j-o-r/hello-dave 0.0.2 → 0.0.3

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 (60) hide show
  1. package/README.md +288 -163
  2. package/README.md.backup +269 -0
  3. package/bin/dave.js +165 -0
  4. package/examples/CodeServer +43 -0
  5. package/{bin/hdAsk.js → examples/askDave.js} +50 -39
  6. package/{bin/hdCode.js → examples/codeDave.js} +47 -47
  7. package/examples/coderev.js +72 -0
  8. package/examples/daisy.js +177 -0
  9. package/examples/docsDave.js +119 -0
  10. package/examples/gpt.js +54 -72
  11. package/examples/grok.js +47 -68
  12. package/examples/npmDave.js +175 -0
  13. package/examples/promptDave.js +112 -0
  14. package/examples/readmeDave.js +144 -0
  15. package/examples/spawndave.js +240 -0
  16. package/examples/todoDave.js +132 -0
  17. package/lib/API/openai.com/reponses/text.js +12 -18
  18. package/lib/API/x.ai/collections.js +354 -0
  19. package/lib/API/x.ai/files.js +218 -0
  20. package/lib/API/x.ai/responses.js +494 -0
  21. package/lib/API/x.ai/text.js +1 -1
  22. package/lib/AgentClient.js +13 -6
  23. package/lib/AgentManager.js +79 -10
  24. package/lib/AgentServer.js +45 -21
  25. package/lib/Cli.js +7 -1
  26. package/lib/Prompt.js +4 -2
  27. package/lib/ToolSet.js +2 -1
  28. package/lib/genericToolset.js +124 -87
  29. package/lib/index.js +4 -2
  30. package/lib/wsCli.js +257 -0
  31. package/lib/wsIO.js +96 -0
  32. package/package.json +26 -20
  33. package/types/API/openai.com/reponses/text.d.ts +17 -3
  34. package/types/API/x.ai/collections.d.ts +167 -0
  35. package/types/API/x.ai/files.d.ts +84 -0
  36. package/types/API/x.ai/responses.d.ts +379 -0
  37. package/types/AgentClient.d.ts +5 -0
  38. package/types/AgentManager.d.ts +24 -31
  39. package/types/AgentServer.d.ts +5 -1
  40. package/types/Prompt.d.ts +4 -2
  41. package/types/ToolSet.d.ts +1 -0
  42. package/types/index.d.ts +4 -3
  43. package/types/wsCli.d.ts +3 -0
  44. package/types/wsIO.d.ts +26 -0
  45. package/utils/bars.js +40 -0
  46. package/utils/clear_sessions.sh +54 -0
  47. package/{bin/hdInspect.js → utils/format_log.js} +5 -0
  48. package/utils/list_sessions.sh +46 -0
  49. package/utils/search_sessions.sh +73 -0
  50. package/bin/hdClear.js +0 -13
  51. package/bin/hdConnect.js +0 -230
  52. package/bin/hdNpm.js +0 -114
  53. package/bin/hdPrompt.js +0 -108
  54. package/examples/claude-test.js +0 -89
  55. package/examples/claude.js +0 -143
  56. package/examples/gpt_code.js +0 -125
  57. package/examples/gpt_note_keeping.js +0 -117
  58. package/examples/grok_code.js +0 -114
  59. package/examples/grok_note_keeping.js +0 -111
  60. package/module.md +0 -189
@@ -0,0 +1,269 @@
1
+ # @j-o-r/hello-dave
2
+
3
+ [![npm version](https://badge.fury.io/js/%40j-o-r%2Fhello-dave.svg)](https://www.npmjs.com/package/%40j-o-r%2Fhello-dave)
4
+ [![Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
5
+ [![Node.js >=20](https://img.shields.io/badge/Node.js-%3E=20-green.svg)](https://nodejs.org/)
6
+
7
+ ## Table of Contents
8
+
9
+ - [Description](#description)
10
+ - [Features](#features)
11
+ - [Installation](#installation)
12
+ - [Quick Start](#quick-start)
13
+ - [Usage](#usage)
14
+ - [Examples](#examples)
15
+ - [Development](#development)
16
+ - [Changelog](#changelog)
17
+ - [Contributing](#contributing)
18
+ - [License](#license)
19
+ - [TODO Alignment](#todo-alignment)
20
+
21
+ ## Description
22
+
23
+ **@j-o-r/hello-dave** is a lightweight, ESM-only Node.js framework for building intelligent AI agents powered by large language models (LLMs) such as xAI Grok, Anthropic Claude, or OpenAI GPT. It simplifies the creation of custom agents with features like the central `AgentManager` class, WebSocket-based client/server support for networked agents, seamless tool integration (e.g., bash execution, web search), customizable system prompts, and robust session management supporting large context windows (up to millions of tokens).
24
+
25
+ The framework emphasizes ease of use, allowing developers and non-experts alike to rapidly prototype and deploy specialized agents. Core integrations include unified xAI Grok API access, WebSocket (WS) networking with secret-based authentication, and direct CLI/cron messaging (no heartbeat/ping mechanism required). Example scripts like `readmeDave`, `todoDave`, and others have been reorganized into the `examples/` folder for clarity.
26
+
27
+ Whether you're building a code reviewer, a research assistant, or a creative collaborator, `@j-o-r/hello-dave` abstracts away API complexities, providing a unified interface across providers. It's alpha-stage but production-ready for personal projects, with persistence for sessions and logs in NDJSON format.
28
+
29
+ ## Features
30
+
31
+ - **Unified LLM Access**: Seamless integration with xAI Grok API, Anthropic Claude, and OpenAI GPT via a single API.
32
+ - **AgentManager Class**: Core orchestrator for prompts, tools, sessions, and interactions (CLI, direct calls, WebSocket).
33
+ - **Tool Integration**: Built-in tools for bash scripting, web search, JavaScript execution, and more; easily extensible.
34
+ - **WebSocket Networking with Secrets**: Agents can act as servers or clients with optional secret authentication, enabling secure distributed agent networks across machines.
35
+ - **Direct CLI/Cron Messaging**: Simplified interactions without needing heartbeat mechanisms—ideal for scheduled tasks.
36
+ - **Customizable Prompts**: Tailor agent behavior with system prompts for specialized tasks (e.g., music production, code analysis).
37
+ - **Session Management**: Persistent conversations with large context windows; automatic truncation and history search.
38
+ - **CLI Utilities**: Core tool at `bin/dave.js` for cache management, WS connections, and interactive queries; plus agent generator.
39
+ - **Lightweight & TypeScript-Friendly**: ESM-only, no heavy deps; full types included.
40
+
41
+ ## Installation
42
+
43
+ Install as a dependency in your Node.js project (requires Node.js >= 20 with `"type": "module"` in `package.json`):
44
+
45
+ ```bash
46
+ npm install @j-o-r/hello-dave
47
+ ```
48
+
49
+ For global access to CLI tools (including `dave` from `bin/dave.js`):
50
+
51
+ ```bash
52
+ npm install -g @j-o-r/hello-dave
53
+ ```
54
+
55
+ Set your API keys via environment variables (only set what you need):
56
+ - `XAIKEY` for xAI Grok
57
+ - `ANTHKEY` for Anthropic Claude
58
+ - `OPENAIKEY` for OpenAI GPT
59
+ - `BRAVESEARCHKEY` for web search (optional)
60
+
61
+ Create a cache directory for sessions:
62
+ ```bash
63
+ mkdir .cache
64
+ ```
65
+
66
+ ## Quick Start
67
+
68
+ 1. Set an API key (e.g., for Grok):
69
+ ```bash
70
+ export XAIKEY=your_xai_api_key
71
+ ```
72
+
73
+ 2. Use the core CLI utility `bin/dave.js` for interactive queries or management:
74
+ ```bash
75
+ npx @j-o-r/hello-dave dave --ask
76
+ ```
77
+ - Launches an interactive agent session. Use `Alt+d` to exit, `Alt+r` to reset.
78
+ - Example: Ask questions about anything; it uses xAI Grok by default with web search and X search tools.
79
+
80
+ 3. For one-shot queries via piped input:
81
+ ```bash
82
+ echo "Explain quantum computing" | npx @j-o-r/hello-dave dave --ask --model grok-4
83
+ ```
84
+ - Provides a direct response using the specified model (e.g., `--model grok-4`).
85
+
86
+ 4. Connect to a WebSocket server (e.g., for networked agents):
87
+ ```bash
88
+ npx @j-o-r/hello-dave dave --connect ws://localhost:8080 --secret your_secret
89
+ ```
90
+
91
+ 5. Generate a custom agent using the spawner (snippet from `bin/dave.js` integration):
92
+ ```bash
93
+ npx @j-o-r/hello-dave spawnDave
94
+ ```
95
+ - Interactive: Follow prompts to create a new agent script in `bin/`.
96
+
97
+ `bin/dave.js` also supports cache operations like `--list` (list sessions), `--search "query"`, `--clear`, and `--inspect path/to/log.ndjson`.
98
+
99
+ ## Usage
100
+
101
+ ### Core CLI via `bin/dave.js`
102
+
103
+ `bin/dave.js` provides essential utilities and examples for agent spawning, WS interactions, and basic querying. Key commands:
104
+
105
+ - **Ask Mode** (Interactive or Piped One-Shot):
106
+ ```bash
107
+ # Interactive
108
+ npx @j-o-r/hello-dave dave --ask --model grok-4 --temperature 0.2
109
+
110
+ # Piped one-shot
111
+ echo "What is quantum computing?" | npx @j-o-r/hello-dave dave --ask --model grok-4
112
+ ```
113
+ - Note: Piped input triggers a direct response via `directCall`; without pipe, it launches an interactive CLI session.
114
+ - `--model` option works for both modes (e.g., `grok-4`, `grok-4-1-fast-reasoning`).
115
+ - Uses `AgentManager` with xAI Grok API integration, adds tools like `web_search`, `x_search`, `open_link`, `send_email`, `history_search`.
116
+ - System prompt emphasizes brief, direct responses with step-by-step reasoning.
117
+
118
+ - **WebSocket Client Mode** (with secrets for secure networking):
119
+ ```bash
120
+ # Interactive connection
121
+ npx @j-o-r/hello-dave dave --connect ws://localhost:8080 --secret "mysecret"
122
+
123
+ # Piped one-shot (direct CLI/cron messaging, no heartbeat needed)
124
+ echo "Predict the weather" | npx @j-o-r/hello-dave dave --connect ws://localhost:8080 --secret "mysecret"
125
+ echo "user_reset" | npx @j-o-r/hello-dave dave --connect ws://localhost:8080 --secret "mysecret"
126
+ ```
127
+
128
+ - **Cache Management**:
129
+ ```bash
130
+ npx @j-o-r/hello-dave dave --list # List sessions
131
+ npx @j-o-r/hello-dave dave --search "AI agents" # Search history
132
+ npx @j-o-r/hello-dave dave --clear # Clear cache
133
+ ```
134
+
135
+ For custom agents, use `AgentManager` programmatically (see Examples).
136
+
137
+ ### Programmatic Usage with AgentManager
138
+
139
+ ```javascript
140
+ import AgentManager from '@j-o-r/hello-dave';
141
+
142
+ const agent = new AgentManager({ name: 'MyAgent', secret: 'optional_secret' });
143
+ agent.setup({
144
+ prompt: 'You are a helpful assistant...',
145
+ api: 'xai', // Uses unified xAI Grok API access
146
+ options: { model: 'grok-4', temperature: 0.7, tools: [{ type: 'web_search' }] },
147
+ toolsetMode: 'auto',
148
+ contextWindow: 500000
149
+ });
150
+
151
+ agent.addGenericToolcall('execute_bash_script'); // Post-setup generics
152
+ agent.addGenericToolcall('read_file');
153
+ agent.addGenericToolcall('write_file');
154
+
155
+ await agent.start(); // Interactive CLI
156
+ // Or: await agent.start(undefined, 8000, undefined, 'Intro', 'toolName', 'desc'); // WS server
157
+ // Or: const response = await agent.directCall('Query'); // One-shot
158
+ ```
159
+
160
+ Direct CLI/cron: Pipe inputs to custom scripts for non-interactive use. WS supports secrets for authentication; no heartbeat required due to event-driven messaging.
161
+
162
+ ## Examples
163
+
164
+ Example scripts (e.g., `readmeDave.js` for README management, `todoDave.js` for task handling, `spawnDave.js` for agent creation) are now organized in the `examples/` folder. These demonstrate specialized agents using `AgentManager`, xAI Grok API integration, and tools.
165
+
166
+ - **Link to Examples Folder**: Explore [examples/](examples/) for full scripts like `daisy.js` (music agent), `codeDave.js` (code review), `npmDave.js` (NPM inspector).
167
+
168
+ ### Snippet: Spawning Agents (from `examples/spawnDave.js` integration via `bin/dave.js`)
169
+
170
+ `spawnDave` uses `AgentManager` to interactively generate new agent scripts:
171
+
172
+ ```javascript
173
+ // Core setup in spawnDave
174
+ const agent = new AgentManager({ name: 'spawn_dave', secret });
175
+ agent.setup({
176
+ prompt: 'You are AgentCreator... [detailed prompt for portability, validation]',
177
+ api: 'xai',
178
+ options: { model: 'grok-4-fast-reasoning', tools: [{ type: 'web_search' }], reasoning: { effort: 'high' } },
179
+ toolsetMode: 'auto',
180
+ contextWindow: 500000
181
+ });
182
+ agent.addGenericToolcall('execute_bash_script'); // For project inspection
183
+ agent.addGenericToolcall('read_file');
184
+ agent.addGenericToolcall('write_file'); // For generating bin/ scripts
185
+
186
+ await agent.start(); // Guides user to create e.g., bin/myagent.js
187
+ ```
188
+
189
+ - Validates generated ESM code with `node --check` and tool rules (xAI natives pre-setup, generics post-setup).
190
+ - Ensures absolute imports for portability.
191
+
192
+ ### Snippet: Using xAI Grok API Integration
193
+
194
+ The unified xAI Grok API access supports options like reasoning and tools:
195
+
196
+ ```javascript
197
+ // In AgentManager setup
198
+ const options = {
199
+ model: 'grok-4-1-fast-reasoning',
200
+ temperature: 0.8,
201
+ tools: [{ type: 'web_search' }, { type: 'x_search', from_date: '2024-01-01' }], // Native xAI tools
202
+ reasoning: { effort: 'medium', summary: 'auto' } // Chain-of-thought support
203
+ };
204
+ ```
205
+
206
+ Detailed examples for xAI integration (e.g., advanced tool calls, reasoning) are planned (see TODO).
207
+
208
+ ### Running Examples
209
+
210
+ ```bash
211
+ # Music agent (examples/daisy.js)
212
+ chmod +x examples/daisy.js
213
+ ./examples/daisy.js "Generate lyrics for a pop song"
214
+
215
+ # TODO manager (examples/todoDave.js)
216
+ ./examples/todoDave.js --connect ws://localhost:8080 --secret "secret"
217
+
218
+ # Server setup for networked examples
219
+ npx @j-o-r/hello-dave dave --ask --serve 8080 # Expose as WS server
220
+ ```
221
+
222
+ ## Development
223
+
224
+ - **Scripts**: `npm test` (runs scenarios/grok.js), `npm run types` (generate TypeScript defs), `npm run release` (pack for release).
225
+ - **Structure**: Core in `lib/` (AgentManager.js, wsCli.js, etc.), API integrations in `lib/API/`, examples in `examples/`, utils in `utils/`.
226
+ - **Testing**: Basic validation via `npm test`. Unit tests for xAI integration planned (see TODO).
227
+ - **Prep for v0.0.4**: Focus on spawnDave enhancements and release testing.
228
+
229
+ ## Changelog
230
+
231
+ ### v0.0.4 (Prep - March 2026)
232
+ - Reorganized examples to `examples/` folder (readmeDave, todoDave, etc.).
233
+ - Enhanced `bin/dave.js` for core utilities: spawning, WS with secrets, direct messaging.
234
+ - Improved xAI Grok API integration; added native tools/reasoning support.
235
+ - Removed heartbeat needs; direct CLI/cron support.
236
+ - Added piped one-shot support to dave --ask.
237
+ - TODO alignment: High-priority items noted (release prep, spawnDave enhancements).
238
+
239
+ ### v0.0.3 (Previous)
240
+ - Initial WS secrets, generic tools, AgentManager refinements.
241
+
242
+ Full history in git tags.
243
+
244
+ ## Contributing
245
+
246
+ Contributions are welcome! Fork the repo at [https://codeberg.org/duin/hello-dave](https://codeberg.org/duin/hello-dave), create a feature branch, and submit a pull request.
247
+
248
+ 1. Install deps: `npm install`
249
+ 2. Self dep `npm run link-self`
250
+ 3. Run tests: `npm test`
251
+ 4. Generate types: `npm run types`
252
+ 5. Report issues: [https://codeberg.org/duin/hello-dave/issues](https://codeberg.org/duin/hello-dave/issues)
253
+
254
+ Follow the [Code of Conduct](CODE_OF_CONDUCT.md) and Apache-2.0 license.
255
+
256
+ ## License
257
+
258
+ Apache License 2.0. See [LICENSE](LICENSE) for details.
259
+
260
+ ## TODO Alignment
261
+
262
+ This README aligns with high-priority items from [TODO.md](TODO.md):
263
+ - **v0.0.4 Prep**: Changelog snippet added; release testing emphasized in Development.
264
+ - **spawnDave Enhancements**: Highlighted in Examples with portability notes.
265
+ - xAI integration tests/examples: Deferred to later (general enhancements).
266
+ - Documentation tasks (e.g., AgentManager internals) integrated into Usage/Examples.
267
+ - Deferred: Other xAI features to later; focus on core release and spawnDave.
268
+
269
+ For full TODO, see [TODO.md](TODO.md).
package/bin/dave.js ADDED
@@ -0,0 +1,165 @@
1
+ #!/usr/bin/env -S node
2
+ import path from 'node:path';
3
+ import cli from '@j-o-r/cli';
4
+ import wsCli from '../lib/wsCli.js';
5
+ import wsIO from '../lib/wsIO.js';
6
+ import { AgentManager } from '@j-o-r/hello-dave';
7
+ import { SH, parseArgs, readIn, bashEscape } from '@j-o-r/sh';
8
+ import { fileURLToPath } from 'node:url';
9
+
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = path.dirname(__filename);
12
+ const pipedInput = await readIn();
13
+ const args = parseArgs();
14
+
15
+ function printHelp(exitCode = 0) {
16
+ console.log(`
17
+ FLAGS:
18
+ --help : Show this help
19
+ --clear : Removes the entire 'hello-dave' cache (chat history etc.)
20
+ --search "[search_query_or_regex]" : Search in cache history
21
+ --list : List all agent sessions in this folder
22
+ --inspect "[path_to_ndjson_log]" : Inspect, Format and output a ndjson log file
23
+ --connect [ws://url][--secret "..."] : Connect to Agent websocket server
24
+ Interactive: bin/dave.js --connect 'ws://localhost:8080' --secret '123'
25
+ Piped actions:
26
+ echo "predict the weather" | bin/dave.js --connect 'ws://...' --secret '123' # user_request
27
+ echo "user_info" | bin/dave.js --connect 'ws://...' --secret '123' # user_info
28
+ echo "user_reset" | bin/dave.js --connect 'ws://...' --secret '123' # user_reset
29
+ --ask : Launches a CLI and ask questions about whatever is on your mind
30
+ XAIKEY required: export XAIKEY=xai-...
31
+ `);
32
+ process.exit(exitCode)
33
+ }
34
+
35
+ // Make sure an action is defined
36
+ const keys = Object.keys(args);
37
+ if (
38
+ !(
39
+ keys.indexOf('help') > 0 ||
40
+ keys.indexOf('clear') > 0 ||
41
+ keys.indexOf('search') > 0 ||
42
+ keys.indexOf('list') > 0 ||
43
+ keys.indexOf('inspect') > 0 ||
44
+ keys.indexOf('connect') > 0 ||
45
+ keys.indexOf('ask') > 0
46
+ )
47
+ ) {
48
+ printHelp(1);
49
+ }
50
+
51
+ if (args.help) {
52
+ printHelp();
53
+ }
54
+
55
+ if (args.clear) {
56
+ const clear_sessions = path.resolve(__dirname, '..', 'utils', 'clear_sessions.sh')
57
+ const y = await cli.yesNo('Delete entire cache? (y/n) ');
58
+ if (y) {
59
+ console.log(clear_sessions);
60
+ const res = await SH`${clear_sessions}`.run()
61
+ console.log(res);
62
+ }
63
+ process.exit();
64
+ } else if (args.search) {
65
+ const history_search = path.resolve(__dirname, '..', 'utils', 'search_sessions.sh')
66
+ if (typeof args.search !== 'string') {
67
+ printHelp(1)
68
+ }
69
+ const res = await SH`${history_search} "${bashEscape(args.search)}"`.run();
70
+ console.log(res);
71
+ process.exit();
72
+ } else if (args.list) {
73
+ const list = path.resolve(__dirname, '..', 'utils', 'list_sessions.sh');
74
+ const res = await SH`${list}`.run();
75
+ console.log(res);
76
+ process.exit();
77
+ } else if (args.inspect) {
78
+ const format = path.resolve(__dirname, '..', 'utils', 'format_log.js')
79
+ if (typeof args.inspect !== 'string') {
80
+ printHelp(1)
81
+ }
82
+ try {
83
+ const res = await SH`${format} "${bashEscape(args.inspect)}"`.run();
84
+ console.log(res);
85
+ } catch (e) {
86
+ console.error(e);
87
+ process.exit(1);
88
+ }
89
+ } else if (args.connect) {
90
+ let secret = args.secret ? args.secret : '';
91
+
92
+ if (typeof pipedInput === 'string' && pipedInput.trim() !== '') {
93
+ // Piped input mode: use wsIO for one-shot actions
94
+ let action, input;
95
+ const trimmed = pipedInput.trim();
96
+ if (trimmed === 'user_info' || trimmed === 'user_reset') {
97
+ action = trimmed;
98
+ input = '';
99
+ } else {
100
+ action = 'user_request';
101
+ input = trimmed;
102
+ }
103
+
104
+ try {
105
+ const response = await wsIO(args.connect, secret, action, input);
106
+ console.log(response.content);
107
+ } catch (e) {
108
+ console.error(`Error: ${e.message}`);
109
+ process.exit(1);
110
+ }
111
+ } else {
112
+ // No piped input: interactive wsCli mode
113
+ wsCli(args.connect, secret);
114
+ }
115
+ } else if (args.ask) {
116
+ const name = 'ask_dave';
117
+ const api = 'xai';
118
+ let secret = '';
119
+ const contextWindow = 1900000;
120
+ const toolsetMode = 'auto';
121
+ /** @type {import('lib/API/x.ai/responses.js').XAIOptions} */
122
+ const options = {
123
+ tools: []
124
+ };
125
+ options.tools.push({ type: 'web_search' });
126
+ options.tools.push({ type: 'x_search' });
127
+ options.model = args.model || args['model'] || 'grok-4-1-fast-reasoning';
128
+ options.temperature = 0.2;
129
+ options.reasoning = { effort: 'medium', summary: 'auto' };
130
+
131
+ const prompt = `
132
+ Respond briefly and directly, using minimal words. Reason step-by-step first. Focus solely on core point; avoid elaboration or follow-ups. If unclear, ask clarifying questions before proceeding.
133
+ `.trim();
134
+
135
+ const agent = new AgentManager({ name, secret });
136
+ agent.setup({
137
+ prompt,
138
+ api,
139
+ options,
140
+ toolsetMode,
141
+ contextWindow
142
+ });
143
+ agent.addGenericToolcall('open_link');
144
+ agent.addGenericToolcall('send_email');
145
+ agent.addGenericToolcall('history_search');
146
+
147
+ const cliIntro = `
148
+ ${name} ${options.model}.
149
+ - context: ${contextWindow}
150
+ `.trim();
151
+ const description = `Ask dave, he knows.`.trim();
152
+
153
+ // Support piped one-shot (like --connect), else interactive CLI
154
+ if (typeof pipedInput === 'string' && pipedInput.trim() !== '') {
155
+ try {
156
+ const response = await agent.directCall(pipedInput.trim());
157
+ console.log(response);
158
+ } catch (e) {
159
+ console.error(`Error: ${e.message}`);
160
+ process.exit(1);
161
+ }
162
+ } else {
163
+ await agent.start(undefined, undefined, cliIntro, name, description);
164
+ }
165
+ }
@@ -0,0 +1,43 @@
1
+ #!/bin/bash
2
+ if [ $# -lt 1 ] || [ $# -gt 2 ]; then
3
+ echo "Usage: $0 <PORT> [SECRET] # PORT: 1024-65535, SECRET: optional (defaults to '123')"
4
+ exit 1
5
+ fi
6
+
7
+ PORT="$1"
8
+ SECRET="${2:-123}"
9
+
10
+ if [ -z "$SECRET" ] || [ ${#SECRET} -lt 3 ]; then
11
+ echo "Error: SECRET must be at least 3 characters: '$SECRET'"
12
+ exit 1
13
+ fi
14
+
15
+ if ! [[ "$PORT" =~ ^[0-9]+$ ]] || [ "$PORT" -lt 1024 ] || [ "$PORT" -gt 65535 ]; then
16
+ echo "Error: Invalid port number: $PORT. Must be between 1024 and 65535."
17
+ exit 1
18
+ fi
19
+
20
+ # Compute paths relative to THIS script's location (portable from anywhere)
21
+ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
22
+ PROJECT_DIR="$( cd "$( dirname "${SCRIPT_DIR}" )" && pwd )"
23
+ FOLDER=$(basename "$PROJECT_DIR")
24
+
25
+ echo "Starting CodeServer on port ${PORT} in folder '${FOLDER}' (SCRIPT_DIR: ${SCRIPT_DIR}) with SECRET '${SECRET}'..."
26
+
27
+ # Delete existing processes with folder_port suffix
28
+ pm2 delete "${FOLDER}_code_agent_${PORT}" 2>/dev/null || true
29
+ pm2 delete "${FOLDER}_todo_agent_${PORT}" 2>/dev/null || true
30
+ pm2 delete "${FOLDER}_readme_agent_${PORT}" 2>/dev/null || true
31
+ pm2 delete "${FOLDER}_npm_agent_${PORT}" 2>/dev/null || true
32
+ pm2 delete "${FOLDER}_docs_agent_${PORT}" 2>/dev/null || true
33
+
34
+ # Spawn main Agent / server (absolute paths to scripts)
35
+ pm2 start "${SCRIPT_DIR}/codeDave.js" --name "${FOLDER}_code_agent_${PORT}" -- --serve "${PORT}" --tools javascript --secret "${SECRET}"
36
+ # Attach clients
37
+ pm2 start "${SCRIPT_DIR}/todoDave.js" --name "${FOLDER}_todo_agent_${PORT}" -- --connect "ws://127.0.0.1:${PORT}/ws" --secret "${SECRET}"
38
+ pm2 start "${SCRIPT_DIR}/readmeDave.js" --name "${FOLDER}_readme_agent_${PORT}" -- --connect "ws://127.0.0.1:${PORT}/ws" --secret "${SECRET}"
39
+ pm2 start "${SCRIPT_DIR}/npmDave.js" --name "${FOLDER}_npm_agent_${PORT}" -- --connect "ws://127.0.0.1:${PORT}/ws" --secret "${SECRET}"
40
+ pm2 start "${SCRIPT_DIR}/docsDave.js" --name "${FOLDER}_docs_agent_${PORT}" -- --connect "ws://127.0.0.1:${PORT}/ws" --secret "${SECRET}"
41
+
42
+ echo "CodeServer processes spawned with prefix '${FOLDER}_' and suffix _${PORT}. Check with: pm2 list | grep '${FOLDER}_${PORT}'"
43
+ echo "dave --connect ws://127.0.0.1:${PORT}/ws --secret '$SECRET'"
@@ -1,37 +1,51 @@
1
1
  #!/usr/bin/env node
2
- import AgentManager from '../lib/AgentManager.js';
3
- import { parseArgs, readIn } from '@j-o-r/sh';
2
+ import { AgentManager } from '@j-o-r/hello-dave';
3
+ import { parseArgs } from '@j-o-r/sh';
4
4
 
5
- const name = 'hdAsk';
6
- const api = 'grok';
5
+ const name = 'ask_dave';
6
+ const api = 'xai';
7
+ let secret = '';
7
8
 
8
- const input = await readIn();
9
+ // const input = await readIn();
9
10
  const args = parseArgs();
10
11
  const help = args['help'] || false;
11
12
  const connect = args['connect'] ? args['connect'] : undefined;
12
13
  const serve = args['serve'] ? parseInt(args['serve']) : undefined;
13
14
 
14
- /** @type {import('lib/API/x.ai/text.js').XOptions} */
15
- const options = {}
15
+ /** @type {import('lib/API/x.ai/responses.js').XAIOptions} */
16
+ const options = {
17
+ tools: []
18
+ }
19
+ options.tools.push({
20
+ type: 'web_search'
21
+ });
22
+ options.tools.push({
23
+ type: 'x_search'
24
+ });
25
+
26
+ if (args['secret']) { // model gets default value
27
+ secret = args['secret'];
28
+ }
16
29
  // Set properties only if provided via command line (except model which has default)
17
30
  if (args['model'] || true) { // model gets default value
18
- // @ts-ignore
19
- options.model = args['model'] || 'grok-4-fast';
31
+ // @ts-ignore || grok-4-1-fast-non-reasoning
32
+ options.model = args['model'] || 'grok-4-1-fast-reasoning';
20
33
  }
21
34
  if (args['temperature']) {
22
35
  options.temperature = parseFloat(args['temperature']);
23
36
  }
24
37
  if (args['tokens']) {
25
- options.max_completion_tokens = parseInt(args['tokens']);
38
+ options.max_output_tokens = parseInt(args['tokens']);
26
39
  }
27
40
  if (args['top_p']) {
28
41
  options.top_p = parseFloat(args['top_p']);
29
42
  }
30
- options.search_parameters = { mode: 'auto' }
31
- const reasoning = args['reasoning'] ? args['reasoning'] : null;
43
+ const reasoning = true // args['reasoning'] ? args['reasoning'] : null;
32
44
  if (reasoning) {
33
- // @ts-ignore
34
- options.reasoning_effort = reasoning
45
+ options.reasoning = {
46
+ effort: 'medium',
47
+ summary: 'auto'
48
+ }
35
49
  }
36
50
  // Large context on grok-4-fast
37
51
  const contextWindow = args['context'] ? parseInt(args['context']) : 1900000;
@@ -45,12 +59,15 @@ OPTIONS:
45
59
  --tokens [number]: max generated tokens
46
60
  --context [number] : truncate message history to context-windows size default 130000
47
61
  --temperature [float] : -2 / +2
48
- --model [grok-4|grok-3|grok-3-mini|grok-3-mini-fast|grok-code-fast-1]
62
+ --model ['grok-4-1-fast-reasoning'|'grok-4-1-fast-non-reasoning'|'grok-code-fast-1'|'grok-4-fast-reasoning'|'grok-4-fast-non-reasoning']
49
63
  --top_p [float]: number > 0, 0.1 means no top_p
50
64
  --reasoning [low|high]
51
65
  --tools [javascript,bash] comma seperated list
52
- e.g.
53
- grok.js --model grok-3-mini --tokens 4000 --context 10000
66
+
67
+ SERVER TOOLS:
68
+ --serve [number]: create a Agent server on port number ws://127.0.0.1:[serve]/ws
69
+ --connect [url]: connect to a Server Agent e.g ws://127.0.0.1:8080/ws (https://my.domain/ws) ...
70
+ --secret [string] : limit access to websocket server with a secret
54
71
 
55
72
  `);
56
73
  process.exit()
@@ -61,11 +78,9 @@ if (help) {
61
78
 
62
79
  const prompt = `
63
80
  Respond briefly and directly, using minimal words. Reason step-by-step first. Focus solely on core point; avoid elaboration or follow-ups. If unclear, ask clarifying questions before proceeding.
64
- - open_link: [url] — open in local browser.
65
- - send_email: send to [email_address]; message: [message].
66
81
  `.trim();
67
82
 
68
- const agent = new AgentManager({ name });
83
+ const agent = new AgentManager({ name, secret });
69
84
  agent.setup({
70
85
  prompt,
71
86
  api,
@@ -73,31 +88,27 @@ agent.setup({
73
88
  toolsetMode,
74
89
  contextWindow
75
90
  });
76
- agent.addGenericToolcall('open_link');
77
- agent.addGenericToolcall('send_email');
91
+ agent.addGenericToolcall('open_link');
92
+ agent.addGenericToolcall('send_email');
93
+ agent.addGenericToolcall('history_search');
78
94
 
95
+ const addTools = (args['tools']) ? args['tools'].split(',') : ['bash'];
96
+ if (addTools.includes('javascript')) {
97
+ agent.addGenericToolcall('javascript_interpreter');
98
+ }
99
+ if (addTools.includes('bash')) {
100
+ agent.addGenericToolcall('execute_bash_script');
101
+ }
102
+ if (addTools.includes('ssh')) {
103
+ agent.addGenericToolcall('execute_remote_script');
104
+ }
79
105
  const cliIntro = `
80
106
  ${name} ${options.model}.
81
- - search ${options.search_parameters.mode}
82
107
  - context: ${contextWindow}
83
108
  `.trim();
84
109
  const description = `
85
110
  Guide for this smart online AI Agent:
86
- - query: Formulate ONE efficient, comprehensive search query in natural language, combining multiple sources/subjects/domains; mention optional sources if needed. Avoid multiple queries—conso
87
- lidate into a single one.
88
- - open_link: [URL] — Open in local browser.
89
- - send_email: Send to [email_address]; Message: [message].
111
+ - query: Formulate ONE efficient, comprehensive search query in natural language, combining multiple sources/subjects/domains; mention optional sources if needed. Avoid multiple queries—consolidate into a single one.
90
112
  `.trim();
91
113
 
92
- if (input === '' && serve) {
93
- agent.enableServer(name, description, serve);
94
- }
95
- if (input !== '') {
96
- // Direct input output
97
- const res = await agent.directCall(input);
98
- console.log(res);
99
- } else if(connect) {
100
- agent.attach('online_agent', description, connect)
101
- } else {
102
- agent.startCli(cliIntro);
103
- }
114
+ await agent.start(serve, connect, cliIntro, "search_agent", description);