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

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 (119) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +216 -56
  3. package/README.md.bak +481 -0
  4. package/README.md.bak.1774780058 +338 -0
  5. package/README.md.bak2 +455 -0
  6. package/docs.bak.1774780058/agent-manager.md +167 -0
  7. package/docs.bak.1774780058/agent-manager.md.bak +137 -0
  8. package/docs.bak.1774780058/agent-manager.md.bak2 +157 -0
  9. package/docs.bak.1774780058/codeserver-pattern.md +191 -0
  10. package/docs.bak.1774780058/path-resolution-best-practices.md +104 -0
  11. package/docs.bak.1774780058/project-overview.md +67 -0
  12. package/docs.bak.1774780058/project-overview.md.bak +67 -0
  13. package/docs.bak.1774780058/prompt-class.md +141 -0
  14. package/docs.bak.1774780058/prompt-class.md.bak +142 -0
  15. package/docs.bak.1774780058/tools-syntax-validation.md +121 -0
  16. package/docs.bak.1774780058/tools-syntax-validation.md.bak2 +125 -0
  17. package/docs.bak.1774780058/tools-syntax-validation.md.bak3 +125 -0
  18. package/docs.bak.1774780058/tools-syntax-validation.md.bak4 +106 -0
  19. package/docs.bak.1774780058/tools-syntax-validation.md.bak_path +106 -0
  20. package/docs.bak.1774780058/toolset.md +164 -0
  21. package/docs.bak.1774780058/toolset.md.bak +94 -0
  22. package/docs.bak.1774780058/toolset.md.bak3 +161 -0
  23. package/docs.bak.1774780058/toolset.md.bak4 +161 -0
  24. package/docs.bak.1774780058/toolset.md.bak5 +161 -0
  25. package/docs.bak.1774780058/toolset.md.bak6 +163 -0
  26. package/docs.bak.1774780058/toolset.md.bak_path +163 -0
  27. package/docs.bak.1774780058/toolset.md.bak_syntax +161 -0
  28. package/docs.bak.1774780058/xai-responses.md +111 -0
  29. package/docs.bak.1774780058/xai-responses.md.bak +107 -0
  30. package/docs.bak.1774780058/xai-responses.md.bak2 +107 -0
  31. package/docs.bak.1774780058/xai_collections.md +106 -0
  32. package/examples/ask_agent.js +137 -0
  33. package/examples/code_agent.js +149 -0
  34. package/examples/coderev_agent.js +136 -0
  35. package/examples/codeserver.sh +47 -0
  36. package/examples/daisy_agent.js +170 -0
  37. package/examples/docs_agent.js +148 -0
  38. package/examples/gpt_agent.js +125 -0
  39. package/examples/grok_agent.js +132 -0
  40. package/examples/grok_agent.js.bak +98 -0
  41. package/examples/grok_agent.js.bak.2 +99 -0
  42. package/examples/grok_agent.js.bak.3 +1 -0
  43. package/examples/grok_agent.js.bak.4 +124 -0
  44. package/examples/grok_agent.js.bak.5 +1 -0
  45. package/examples/grok_agent.js.bak.6 +1 -0
  46. package/examples/memory_agent.js +152 -0
  47. package/examples/npm_agent.js +202 -0
  48. package/examples/npm_agent.js.bak.3 +2 -0
  49. package/examples/npm_agent.js.bak.4 +205 -0
  50. package/examples/npm_agent.js.bak.5 +1 -0
  51. package/examples/npm_agent.js.bak.6 +1 -0
  52. package/examples/prompt_agent.js +133 -0
  53. package/examples/readme_agent.js +148 -0
  54. package/examples/spawn_agent.js +293 -0
  55. package/examples/test_agent.js +187 -0
  56. package/examples/todo_agent.js +175 -0
  57. package/{examples/codeDave.js → examples.bak.1774780058/code_agent.js} +40 -6
  58. package/{examples/CodeServer → examples.bak.1774780058/codeserver.sh} +9 -5
  59. package/examples.bak.1774780058/memory_agent.js +112 -0
  60. package/{examples/spawndave.js → examples.bak.1774780058/spawn_agent.js} +29 -6
  61. package/examples.bak.1774780058/test_agent.js +162 -0
  62. package/{examples/todoDave.js → examples.bak.1774780058/todo_agent.js} +8 -2
  63. package/lib/API/x.ai/responses.js +7 -9
  64. package/lib/AgentManager.js +3 -2
  65. package/lib/AgentServer.js +23 -19
  66. package/lib/genericToolset.js +159 -26
  67. package/lib/genericToolset.js.bak_syntax +402 -0
  68. package/lib/wsCli.js +0 -1
  69. package/package.json +4 -5
  70. package/scenarios.bak.1774780058/data/eval_node_message.json +9 -0
  71. package/scenarios.bak.1774780058/data/hist_oa.json +66 -0
  72. package/scenarios.bak.1774780058/data/o3_response1.json +96 -0
  73. package/scenarios.bak.1774780058/data/oa_reasoning_parse.json +112 -0
  74. package/scenarios.bak.1774780058/data/tool_oa.json +96 -0
  75. package/scenarios.bak.1774780058/data/tool_xai.json +59 -0
  76. package/scenarios.bak.1774780058/data/tool_xai2.json +40 -0
  77. package/scenarios.bak.1774780058/data/xai-response-1.json +59 -0
  78. package/scenarios.bak.1774780058/data/xai-response-2.json +10 -0
  79. package/scenarios.bak.1774780058/data/xai_reasoning_tools_resp.json +59 -0
  80. package/scenarios.bak.1774780058/data/xai_search_response.json +58 -0
  81. package/scenarios.bak.1774780058/environment.js +10 -0
  82. package/scenarios.bak.1774780058/example.js +17 -0
  83. package/scenarios.bak.1774780058/genericToolset.test.js +182 -0
  84. package/scenarios.bak.1774780058/grok.js +113 -0
  85. package/scenarios.bak.1774780058/memory-tools.js +51 -0
  86. package/scenarios.bak.1774780058/openai-o3.js +137 -0
  87. package/scenarios.bak.1774780058/openai-prompt.js +155 -0
  88. package/scenarios.bak.1774780058/openai-session.js +148 -0
  89. package/scenarios.bak.1774780058/openai.js +102 -0
  90. package/scenarios.bak.1774780058/prompt.js +118 -0
  91. package/scenarios.bak.1774780058/promptFishbowl.js +76 -0
  92. package/scenarios.bak.1774780058/search.brave.com.js +25 -0
  93. package/scenarios.bak.1774780058/sh.js +15 -0
  94. package/scenarios.bak.1774780058/test-wsio.js +26 -0
  95. package/scenarios.bak.1774780058/testToolset.js +42 -0
  96. package/scenarios.bak.1774780058/toolset.js +16 -0
  97. package/scenarios.bak.1774780058/toolset.test.js +141 -0
  98. package/scenarios.bak.1774780058/write_file_syntax.test.js +145 -0
  99. package/scenarios.bak.1774780058/write_file_validation/README.md +30 -0
  100. package/scenarios.bak.1774780058/write_file_validation/bad.js +3 -0
  101. package/scenarios.bak.1774780058/write_file_validation/good.js +4 -0
  102. package/scenarios.bak.1774780058/write_file_validation/test.sh +43 -0
  103. package/scenarios.bak.1774780058/wsClient.js +69 -0
  104. package/scenarios.bak.1774780058/xai_responses.integration.test.js +57 -0
  105. package/scenarios.bak.1774780058/xai_responses.test.js +154 -0
  106. package/scenarios.bak.1774780058/xaicoll.js +50 -0
  107. package/scenarios.bak.1774780058/xaifiles.js +48 -0
  108. package/types/AgentManager.d.ts +4 -3
  109. package/utils/syntax_check.sh +61 -0
  110. package/utils/test.sh +46 -0
  111. /package/{examples/askDave.js → examples.bak.1774780058/ask_agent.js} +0 -0
  112. /package/{examples/coderev.js → examples.bak.1774780058/coderev_agent.js} +0 -0
  113. /package/{examples/daisy.js → examples.bak.1774780058/daisy_agent.js} +0 -0
  114. /package/{examples/docsDave.js → examples.bak.1774780058/docs_agent.js} +0 -0
  115. /package/{examples/gpt.js → examples.bak.1774780058/gpt_agent.js} +0 -0
  116. /package/{examples/grok.js → examples.bak.1774780058/grok_agent.js} +0 -0
  117. /package/{examples/npmDave.js → examples.bak.1774780058/npm_agent.js} +0 -0
  118. /package/{examples/promptDave.js → examples.bak.1774780058/prompt_agent.js} +0 -0
  119. /package/{examples/readmeDave.js → examples.bak.1774780058/readme_agent.js} +0 -0
package/README.md.bak2 ADDED
@@ -0,0 +1,455 @@
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
+ - [Startup Modes](#startup-modes)
15
+ - [Examples](#examples)
16
+ - [Development](#development)
17
+ - [Changelog](#changelog)
18
+ - [Contributing](#contributing)
19
+ - [License](#license)
20
+ - [TODO Alignment](#todo-alignment)
21
+
22
+ ## Description
23
+
24
+ **@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).
25
+
26
+ 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.
27
+
28
+ 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.
29
+
30
+ ## Features
31
+
32
+ - **Unified LLM Access**: Seamless integration with xAI Grok API, Anthropic Claude, and OpenAI GPT via a single API.
33
+ - **AgentManager Class**: Core orchestrator for prompts, tools, sessions, and interactions (CLI, direct calls, WebSocket).
34
+ - **Tool Integration**: Built-in tools for bash scripting, web search, JavaScript execution, and more; easily extensible.
35
+ - **WebSocket Networking with Secrets**: Agents can act as servers or clients with optional secret authentication, enabling secure distributed agent networks across machines.
36
+ - **Direct CLI/Cron Messaging**: Simplified interactions without needing heartbeat mechanisms—ideal for scheduled tasks.
37
+ - **Customizable Prompts**: Tailor agent behavior with system prompts for specialized tasks (e.g., music production, code analysis).
38
+ - **Session Management**: Persistent conversations with large context windows; automatic truncation and history search.
39
+ - **CLI Utilities**: Core tool at `bin/dave.js` for cache management, WS connections, and interactive queries; plus agent generator.
40
+ - **Lightweight & TypeScript-Friendly**: ESM-only, no heavy deps; full types included.
41
+ - **Memory Tools**: Generic tools `memory_recall` and `memory_write` for persisting and recalling tasks, errors, and preferences in `.cache/memory.ndjson`, optimizing loops and long-running agent sessions (available in `toolsetMode: 'auto'`).
42
+
43
+ ## Installation
44
+
45
+ Install as a dependency in your Node.js project (requires Node.js >= 20 with `"type": "module"` in `package.json`):
46
+
47
+ ```bash
48
+ npm install @j-o-r/hello-dave
49
+ ```
50
+
51
+ For global access to CLI tools (including `dave` from `bin/dave.js`):
52
+
53
+ ```bash
54
+ npm install -g @j-o-r/hello-dave
55
+ ```
56
+
57
+ Set your API keys via environment variables (only set what you need):
58
+ - `XAIKEY` for xAI Grok
59
+ - `ANTHKEY` for Anthropic Claude
60
+ - `OPENAIKEY` for OpenAI GPT
61
+ - `BRAVESEARCHKEY` for web search (optional)
62
+
63
+ Create a cache directory for sessions:
64
+ ```bash
65
+ mkdir .cache
66
+ ```
67
+
68
+ ## Quick Start
69
+
70
+ 1. Set an API key (e.g., for Grok):
71
+ ```bash
72
+ export XAIKEY=your_xai_api_key
73
+ ```
74
+
75
+ 2. Use the core CLI utility `bin/dave.js` for interactive queries or management:
76
+ ```bash
77
+ npx @j-o-r/hello-dave dave --ask
78
+ ```
79
+ - Launches an interactive agent session. Use `Alt+d` to exit, `Alt+r` to reset.
80
+ - Example: Ask questions about anything; it uses xAI Grok by default with web search and X search tools.
81
+
82
+ 3. For one-shot queries via piped input:
83
+ ```bash
84
+ echo "Explain quantum computing" | npx @j-o-r/hello-dave dave --ask --model grok-4
85
+ ```
86
+ - Provides a direct response using the specified model (e.g., `--model grok-4`).
87
+
88
+ 4. Connect to a WebSocket server (e.g., for networked agents):
89
+ ```bash
90
+ npx @j-o-r/hello-dave dave --connect ws://localhost:8080 --secret your_secret
91
+ ```
92
+
93
+ 5. Generate a custom agent using the portable `spawn_agent` tool (CLI/WS agents + CodeServer launchers):
94
+ ```bash
95
+ npx @j-o-r/hello-dave spawn_agent
96
+ ```
97
+ - Interactive: Follow prompts to create a new agent script in `bin/` (e.g., `bin/myagent.js`).
98
+ - Portable to any project (auto-installs deps like `@j-o-r/hello-dave`):
99
+ ```bash
100
+ npx @j-o-r/hello-dave spawn_agent --cwd ~/my-project
101
+ ```
102
+ - Supports one-shot: `echo "Create code-review agent" | npx @j-o-r/hello-dave spawn_agent --cwd ~/proj`.
103
+ - Aligns with CodeServer pattern for multi-agent setups (see Usage/Examples).
104
+
105
+ `bin/dave.js` also supports cache operations like `--list` (list sessions), `--search "query"`, `--clear`, and `--inspect path/to/log.ndjson`.
106
+
107
+ ## Usage
108
+
109
+ ### Core CLI via `bin/dave.js`
110
+
111
+ `bin/dave.js` provides essential utilities and examples for agent spawning, WS interactions, and basic querying. Key commands:
112
+
113
+ - **Ask Mode** (Interactive or Piped One-Shot):
114
+ ```bash
115
+ # Interactive
116
+ npx @j-o-r/hello-dave dave --ask --model grok-4 --temperature 0.2
117
+
118
+ # Piped one-shot
119
+ echo "What is quantum computing?" | npx @j-o-r/hello-dave dave --ask --model grok-4
120
+ ```
121
+ - Note: Piped input triggers a direct response via `directCall`; without pipe, it launches an interactive CLI session.
122
+ - `--model` option works for both modes (e.g., `grok-4`, `grok-4-1-fast-reasoning`).
123
+ - Uses `AgentManager` with xAI Grok API integration, adds tools like `web_search`, `x_search`, `open_link`, `send_email`, `history_search`.
124
+ - System prompt emphasizes brief, direct responses with step-by-step reasoning.
125
+
126
+ - **SpawnDave Mode** (Portable Agent Creator with --cwd Support):
127
+ ```bash
128
+ # Interactive in current project
129
+ npx @j-o-r/hello-dave spawn_agent --model grok-4-fast-reasoning --temperature 0.7
130
+
131
+ # Portable to another project (switches cwd, auto-deps)
132
+ npx @j-o-r/hello-dave spawn_agent --cwd ../other-proj
133
+
134
+ # One-shot for quick generation
135
+ echo "name=coderev desc=Git diff analyzer tools=read_file execute_bash_script web_search" | npx @j-o-r/hello-dave spawn_agent --cwd ~/my-proj
136
+ ```
137
+ - Creates production-ready CLI/WS agents (`bin/<name>.js`) supporting CLI, server (`--serve`), client (`--connect`), and hybrid modes.
138
+ - Generates multi-agent CodeServer launchers (`examples/<Name>Server`) using PM2 for persistent networked setups (main server + sub-agents).
139
+ - **Portable**: Runs via `npx` anywhere—no local install needed. Auto-inspects project, installs `@j-o-r/hello-dave @j-o-r/sh` if missing, validates ESM code (`node --check`), tests deployment.
140
+ - Aligns with CodeServer pattern: Self-contained Bash launchers for PM2-managed multi-agents (e.g., code review + TODO + NPM agents).
141
+ - Requires `XAIKEY`; uses online repo docs (https://codeberg.org/duin/hello-dave) for portability.
142
+ - Example output: Deploys `bin/coderev_agent.js`, tests it, provides server/client usage guide.
143
+
144
+ - **WebSocket Client Mode** (with secrets for secure networking):
145
+ ```bash
146
+ # Interactive connection
147
+ npx @j-o-r/hello-dave dave --connect ws://localhost:8080 --secret "mysecret"
148
+
149
+ # Piped one-shot (direct CLI/cron messaging, no heartbeat needed)
150
+ echo "Predict the weather" | npx @j-o-r/hello-dave dave --connect ws://localhost:8080 --secret "mysecret"
151
+ echo "user_reset" | npx @j-o-r/hello-dave dave --connect ws://localhost:8080 --secret "mysecret"
152
+ ```
153
+
154
+ - **Cache Management**:
155
+ ```bash
156
+ npx @j-o-r/hello-dave dave --list # List sessions
157
+ npx @j-o-r/hello-dave dave --search "AI agents" # Search history
158
+ npx @j-o-r/hello-dave dave --clear # Clear cache
159
+ ```
160
+
161
+ For custom agents, use `AgentManager` programmatically (see Examples).
162
+
163
+ ### Programmatic Usage with AgentManager
164
+
165
+ ```javascript
166
+ import AgentManager from '@j-o-r/hello-dave';
167
+
168
+ const agent = new AgentManager({ name: 'MyAgent', secret: 'optional_secret' });
169
+ agent.setup({
170
+ prompt: 'You are a helpful assistant...',
171
+ api: 'xai', // Uses unified xAI Grok API access
172
+ options: { model: 'grok-4', temperature: 0.7, tools: [{ type: 'web_search' }] },
173
+ toolsetMode: 'auto',
174
+ contextWindow: 500000
175
+ });
176
+
177
+ agent.addGenericToolcall('execute_bash_script'); // Post-setup generics
178
+ agent.addGenericToolcall('read_file');
179
+ agent.addGenericToolcall('write_file');
180
+ agent.addGenericToolcall('memory_recall'); // Persist/recall tasks, errors, prefs in .cache/memory.ndjson
181
+ agent.addGenericToolcall('memory_write'); // Optimizes loops and long-running sessions
182
+
183
+ await agent.start(); // Interactive CLI
184
+ // Or: await agent.start(undefined, 8000, undefined, 'Intro', 'toolName', 'desc'); // WS server
185
+ // Or: const response = await agent.directCall('Query'); // One-shot
186
+ ```
187
+
188
+ 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.
189
+
190
+ The `memory_recall` and `memory_write` tools, available when `toolsetMode: 'auto'`, enable agents to persist and recall tasks, errors, and preferences in `.cache/memory.ndjson`. This optimizes iterative loops and long-running sessions by maintaining state across interactions without relying solely on session history.
191
+
192
+ ## Startup Modes
193
+
194
+ This section details the startup modes for agents like `examples/npm_agent.js`, `bin/dave.js`, and programmatic `AgentManager.start()`. These modes support flexible deployments from one-shot CLI queries to persistent WebSocket servers in networked ecosystems. All modes are cron-friendly with no heartbeat/ping required—agents respond directly to event-driven inputs. In WS modes (--serve, --connect, hybrid), positional arguments are ignored; use interactive CLI or piped inputs for messaging.
195
+
196
+ ### 1. Direct Call (One-Shot, Positional ONLY)
197
+ For single responses via positional query. Ideal for scripts/cron.
198
+
199
+ **npm_agent.js:**
200
+ ```bash
201
+ ./examples/npm_agent.js "What modules are installed?" [--model grok-4]
202
+ ```
203
+
204
+ **bin/dave.js:**
205
+ ```bash
206
+ npx @j-o-r/hello-dave dave "Explain quantum computing" --ask [--model grok-4]
207
+ ```
208
+
209
+ **Programmatic (AgentManager):**
210
+ ```javascript
211
+ import AgentManager from '@j-o-r/hello-dave';
212
+ const agent = new AgentManager({ name: 'MyAgent' });
213
+ await agent.setup({ /* config */ });
214
+ const response = await agent.directCall('What modules are installed?');
215
+ console.log(response);
216
+ ```
217
+
218
+ ### 2. Interactive CLI (No Positional Arg)
219
+ Launches ongoing conversation session.
220
+
221
+ **npm_agent.js:**
222
+ ```bash
223
+ ./examples/npm_agent.js [--model grok-4]
224
+ ```
225
+
226
+ **bin/dave.js:**
227
+ ```bash
228
+ npx @j-o-r/hello-dave dave --ask
229
+ ```
230
+
231
+ **Programmatic:**
232
+ ```javascript
233
+ await agent.start(); // Interactive CLI
234
+ ```
235
+
236
+ ### 3. WS Server (--serve [port])
237
+ Starts WS server at `ws://127.0.0.1:[port]/ws` for remote tool access. Runs indefinitely.
238
+
239
+ **Explanations:**
240
+ - `--serve [port]`: Listen port (e.g., 8080). Exposes agent's tools (e.g., 'npm_module_inspector') to clients.
241
+
242
+ **npm_agent.js:**
243
+ ```bash
244
+ ./examples/npm_agent.js --serve 8080 [--secret mysecret]
245
+ ```
246
+
247
+ **bin/dave.js:**
248
+ ```bash
249
+ npx @j-o-r/hello-dave dave --serve 8080 [--secret mysecret]
250
+ ```
251
+
252
+ **Programmatic:**
253
+ ```javascript
254
+ await agent.start(undefined, 8080, 'mysecret'); // Starts server on port 8080 with secret
255
+ ```
256
+
257
+ See [docs/agent-manager.md](docs/agent-manager.md) for server config.
258
+
259
+ ### 4. WS Client (--connect [ws_url])
260
+ Connects to remote server for tool access; launches interactive CLI.
261
+
262
+ **Explanations:**
263
+ - `--connect [ws_url]`: URL (e.g., ws://127.0.0.1:8080/ws). Gains remote tools.
264
+
265
+ **npm_agent.js:**
266
+ ```bash
267
+ ./examples/npm_agent.js --connect ws://127.0.0.1:8080/ws --secret mysecret
268
+ ```
269
+
270
+ **bin/dave.js:**
271
+ ```bash
272
+ npx @j-o-r/hello-dave dave --connect ws://localhost:8080 --secret mysecret
273
+ ```
274
+
275
+ **Programmatic:**
276
+ ```javascript
277
+ await agent.start('ws://localhost:8080/ws', undefined, 'mysecret');
278
+ ```
279
+
280
+ ### 5. Hybrid (Server + Client, No Positional Arg)
281
+ Serves tools locally while using remote ones.
282
+
283
+ **Explanations:**
284
+ - Combines `--serve` and `--connect`; ignores positional args.
285
+
286
+ **npm_agent.js:**
287
+ ```bash
288
+ ./examples/npm_agent.js --serve 8081 --connect ws://other:8080/ws [--secret mysecret]
289
+ ```
290
+
291
+ **bin/dave.js:**
292
+ ```bash
293
+ npx @j-o-r/hello-dave dave --serve 8081 --connect ws://other:8080 --secret mysecret
294
+ ```
295
+
296
+ **Programmatic:**
297
+ Custom handling required; see [docs/agent-manager.md](docs/agent-manager.md).
298
+
299
+ ### Shared Options & Notes
300
+ - `--secret [string]`: Min 3-char auth token. Servers reject mismatched clients; use same for chains.
301
+ - Other: `--model [grok-4-fast-reasoning|...]`, `--temperature [-2 to +2]`, `--tokens`, `--top_p`, `--context [250000]`.
302
+ - Positional ignored in WS modes; no heartbeat—event-driven.
303
+ - For multi-agent examples, see [examples/](examples/) and [docs/codeserver-pattern.md](docs/codeserver-pattern.md).
304
+
305
+ This completes high-priority TODO: "Explain startup modes...".
306
+
307
+ ## Examples
308
+
309
+ Example scripts (e.g., `readme_agent.js` for README management, `todo_agent.js` for task handling, `spawn_agent.js` for agent creation) are now organized in the `examples/` folder. These demonstrate specialized agents using `AgentManager`, xAI Grok API integration, and tools. **Note**: Agent names and filenames follow lowercase naming rules per [docs/agent-manager.md](docs/agent-manager.md) (regex `/^[a-z_0-9_]{2,}$/` for safety in folders, tools, and filesystems—no uppercase, hyphens, or specials).
310
+
311
+ - **Link to Examples Folder**: Explore [examples/](examples/) for full scripts like `daisy_agent.js` (music agent), `code_agent.js` (code review), `npm_agent.js` (NPM inspector).
312
+
313
+ In custom agents, consider adding `memory_recall` and `memory_write` tools to enable state persistence for complex workflows, such as tracking progress in multi-step tasks or storing user preferences across sessions.
314
+
315
+ ### Persistent Multi-Agent CodeServer Pattern
316
+
317
+ The `examples/CodeServer` script provides a persistent multi-agent setup using PM2 to manage long-running processes. It starts a main code agent as a WebSocket server on a specified port, with sub-agents (for TODO, README, NPM, and docs tasks) attached as clients. This pattern enables a networked ecosystem of specialized agents that maintain state across sessions, ideal for extended development workflows where context persistence and task delegation are key.
318
+
319
+ Benefits include seamless integration for dev sessions—agents stay online, handling queries via WS without restarts, supporting large context windows and tool calls. For full details, see [docs/codeserver-pattern.md](docs/codeserver-pattern.md).
320
+
321
+ **Usage:**
322
+
323
+ ```bash
324
+ # Start the CodeServer (requires PM2: npm i -g pm2)
325
+ ./examples/CodeServer 8080 mysecret
326
+
327
+ # Connect via CLI (interactive or piped)
328
+ npx @j-o-r/hello-dave dave --connect ws://127.0.0.1:8080/ws --secret mysecret
329
+ # Or for one-shot: echo "Review this code" | npx @j-o-r/hello-dave dave --connect ws://127.0.0.1:8080/ws --secret mysecret
330
+ ```
331
+
332
+ Monitor with `pm2 list` and stop via `pm2 delete <name>`.
333
+
334
+ ### Snippet: Spawning Agents (Portable via `bin/dave.js` --spawn_agent)
335
+
336
+ `spawn_agent` uses `AgentManager` to interactively generate new agent scripts, now fully aware of WebSocket server/client modes and the CodeServer multi-agent pattern for networked setups.
337
+
338
+ Now CodeServer-aware: Can generate PM2 multi-agent launchers (e.g., 'Generate CodeServer for coderev + todo'). See updated [examples/spawn_agent.js](examples/spawn_agent.js) and [docs/codeserver-pattern.md](docs/codeserver-pattern.md).
339
+
340
+ **Portable**: `spawn_agent` is fully portable—no local docs/examples needed. Uses online repo links (https://codeberg.org/duin/hello-dave). Works in any project via `npx` (auto-deps with `--cwd`).
341
+
342
+ ```javascript
343
+ // Core setup in spawn_agent
344
+ const agent = new AgentManager({ name: 'spawn_agent', secret });
345
+ agent.setup({
346
+ prompt: 'You are AgentCreator... [detailed prompt for portability, validation]',
347
+ api: 'xai',
348
+ options: { model: 'grok-4-fast-reasoning', tools: [{ type: 'web_search' }], reasoning: { effort: 'high' } },
349
+ toolsetMode: 'auto',
350
+ contextWindow: 500000
351
+ });
352
+ agent.addGenericToolcall('execute_bash_script'); // For project inspection
353
+ agent.addGenericToolcall('read_file');
354
+ agent.addGenericToolcall('write_file'); // For generating bin/ scripts
355
+ agent.addGenericToolcall('memory_recall'); // For recalling previous generations or prefs
356
+ agent.addGenericToolcall('memory_write'); // For persisting agent configs or errors
357
+
358
+ await agent.start(); // Guides user to create e.g., bin/myagent.js
359
+ ```
360
+
361
+ - Validates generated ESM code with `node --check` and tool rules (xAI natives pre-setup, generics post-setup).
362
+ - Ensures absolute imports for portability.
363
+
364
+ **Example Usage:**
365
+
366
+ ```bash
367
+ # Interactive spawning (runs from npm without cloning; current dir)
368
+ npx @j-o-r/hello-dave spawn_agent
369
+
370
+ # Portable to specific project (auto-switches cwd, installs deps if needed)
371
+ npx @j-o-r/hello-dave spawn_agent --cwd ~/my-proj
372
+
373
+ # Piped one-shot for CodeServer launcher (portable, no cloning)
374
+ echo "Generate CodeServer launcher for coderev + tododave" | npx @j-o-r/hello-dave spawn_agent --cwd ~/proj
375
+ ```
376
+
377
+ ### Snippet: Using xAI Grok API Integration
378
+
379
+ The unified xAI Grok API access supports options like reasoning and tools:
380
+
381
+ ```javascript
382
+ // In AgentManager setup
383
+ const options = {
384
+ model: 'grok-4-1-fast-reasoning',
385
+ temperature: 0.8,
386
+ tools: [{ type: 'web_search' }, { type: 'x_search', from_date: '2024-01-01' }], // Native xAI tools
387
+ reasoning: { effort: 'medium', summary: 'auto' } // Chain-of-thought support
388
+ };
389
+ ```
390
+
391
+ Detailed examples for xAI integration (e.g., advanced tool calls, reasoning) are planned (see TODO).
392
+
393
+ ### Running Examples
394
+
395
+ ```bash
396
+ # Music agent (examples/daisy_agent.js)
397
+ chmod +x examples/daisy_agent.js
398
+ ./examples/daisy_agent.js "Generate lyrics for a pop song"
399
+
400
+ # TODO manager (examples/todo_agent.js)
401
+ ./examples/todo_agent.js --connect ws://localhost:8080 --secret "secret"
402
+
403
+ # Server setup for networked examples
404
+ npx @j-o-r/hello-dave dave --ask --serve 8080 # Expose as WS server
405
+ ```
406
+
407
+ ## Development
408
+
409
+ - **Scripts**: `npm test` (runs scenarios/grok_agent.js), `npm run types` (generate TypeScript defs), `npm run release` (pack for release).
410
+ - **Structure**: Core in `lib/` (AgentManager.js, wsCli.js, etc.), API integrations in `lib/API/`, examples in `examples/`, utils in `utils/`.
411
+ - **Testing**: Basic validation via `npm test`. Unit tests for xAI integration planned (see TODO).
412
+ - **Prep for v0.0.4**: Focus on spawn_agent enhancements and release testing.
413
+
414
+ ## Changelog
415
+
416
+ ### v0.0.4 (Prep - March 2026)
417
+ - Reorganized examples to `examples/` folder (readmeDave, todoDave, etc.).
418
+ - Enhanced `bin/dave.js` for core utilities: spawning, WS with secrets, direct messaging.
419
+ - Improved xAI Grok API integration; added native tools/reasoning support.
420
+ - Removed heartbeat needs; direct CLI/cron support.
421
+ - Added piped one-shot support to dave --ask.
422
+ - TODO alignment: High-priority items noted (release prep, spawn_agent enhancements).
423
+
424
+ ### v0.0.3 (Previous)
425
+ - Initial WS secrets, generic tools, AgentManager refinements.
426
+
427
+ Full history in git tags.
428
+
429
+ ## Contributing
430
+
431
+ 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.
432
+
433
+ 1. Install deps: `npm install`
434
+ 2. Self dep `npm run link-self`
435
+ 3. Run tests: `npm test`
436
+ 4. Generate types: `npm run types`
437
+ 5. Report issues: [https://codeberg.org/duin/hello-dave/issues](https://codeberg.org/duin/hello-dave/issues)
438
+
439
+ Follow the [Code of Conduct](CODE_OF_CONDUCT.md) and Apache-2.0 license.
440
+
441
+ ## License
442
+
443
+ Apache License 2.0. See [LICENSE](LICENSE) for details.
444
+
445
+ ## TODO Alignment
446
+
447
+ This README aligns with high-priority items from [TODO.md](TODO.md):
448
+ - **v0.0.4 Prep**: Changelog snippet added; release testing emphasized in Development.
449
+ - **spawn_agent Enhancements**: Highlighted in Examples with portability notes.
450
+ - xAI integration tests/examples: Deferred to later (general enhancements).
451
+ - Documentation tasks (e.g., AgentManager internals) integrated into Usage/Examples.
452
+ - **Completed: Explain startup modes** - New dedicated section added with details on CLI/WS modes, options, and examples.
453
+ - Deferred: Other xAI features to later; focus on core release and spawn_agent.
454
+
455
+ For full TODO, see [TODO.md](TODO.md).
@@ -0,0 +1,167 @@
1
+ # AgentManager (`lib/AgentManager.js`)
2
+
3
+ ## Overview
4
+ **AgentManager** is the central orchestrator class in the hello-dave framework. It manages agent lifecycle: setup (prompts, API, tools, sessions), execution modes (CLI, direct calls, WebSocket server/client), and tool integration. Designed for simplicity and extensibility, it abstracts LLM providers (`xai`, `gpt`, `claude`), `Prompt.js`, `ToolSet.js`, and `Session.js`.
5
+
6
+ **Uses named exports from `lib/index.js` - NO default export.**
7
+
8
+ Key Features:
9
+ - **Modes**: Interactive CLI, one-shot `directCall`, WS **server** (expose agent as tool), **client** (attach to remote server), hybrid (server + client).
10
+ - **Tool Handling**: Pre-configured (`toolsetMode: 'auto'`/`'required'`), generics (`addGenericToolcall`), custom `ToolSet`.
11
+ - **Persistence**: Sessions in `.cache/[name]/` (NDJSON logs).
12
+ - **Networking**: WS with optional `secret` auth (base64-encoded).
13
+ - **Validation**: Strict name regex `/^[a-z_0-9_]{2,}$/`.
14
+ - **Events**: Leverages `Prompt` events (e.g., `reset` → server resetAll).
15
+
16
+ Exports: `{ AgentManager }` (named).
17
+
18
+ ## Agent Naming Rules ⚠️
19
+ **CRITICAL**: The `name` (constructor) and `toolName` (in `start()`) **MUST** match regex `/^[a-z_0-9_]{2,}$/`:
20
+ - Lowercase `a-z`, digits `0-9`, `_` **only**.
21
+ - **Minimum 2 characters**.
22
+
23
+ **Valid ✅**:
24
+ - `myagent`
25
+ - `chatbot`
26
+ - `weather_agent`
27
+ - `tool123`
28
+ - `ws_client`
29
+
30
+ **Invalid ❌ (throws `Error`)**:
31
+ - `MyAgent` (uppercase)
32
+ - `agent-v1` (hyphen)
33
+ - `a` (too short)
34
+ - `agent#tool` (`#` invalid)
35
+ - `Agent_` (uppercase)
36
+
37
+ **Why?** Safe for folders, tool names, filesystems (no specials/caps/spaces).
38
+
39
+ ## Quick Usage
40
+ ```javascript
41
+ import { AgentManager } from '@j-o-r/hello-dave';
42
+
43
+ const agent = new AgentManager({ name: 'myagent', secret: 'mysecret' });
44
+ agent.setup({
45
+ prompt: 'You are a helpful coding assistant.',
46
+ api: 'xai',
47
+ options: { model: 'grok-4-fast-reasoning' },
48
+ toolsetMode: 'auto',
49
+ contextWindow: 128000
50
+ });
51
+ agent.addGenericToolcall('execute_bash_script');
52
+
53
+ await agent.start(); // CLI mode
54
+ // Or: await agent.directCall('Write a Bash script'); // One-shot
55
+ // Or: await agent.start(8000); // WS server on port 8000
56
+ ```
57
+
58
+ ## Constructor Options
59
+ | Property | Type | Default | Description |
60
+ |----------|------|---------|-------------|
61
+ | `name` | string | `'agent'` | **Agent ID (session folder, tool name). MUST match `/^[a-z_0-9_]{2,}$/` (lowercase a-z0-9_; ≥2 chars).** |
62
+ | `secret` | string | `''` | WS auth (base64-encoded; optional, match server/client). |
63
+ | `cachePath` | string | `'.cache/hello-dave'` | Session storage root. |
64
+
65
+ ## setup(setup) → `this` (chainable)
66
+ Configures the agent. Must call before `start()`/`directCall()`.
67
+
68
+ | Property | Type | Default | Description |
69
+ |----------|------|---------|-------------|
70
+ | `prompt` | string | - | **Required**: System prompt. |
71
+ | `api` | `'xai'|'gpt'|'claude'` | `'gpt'` | LLM provider (uses `lib/API/[provider]/text.js`). |
72
+ | `options` | `XAIOptions`/`OAOptions`/etc. | `{}` | Provider-specific (model, temperature, tools, reasoning). |
73
+ | `contextWindow` | number | `300000` | Token limit for `Prompt`. |
74
+ | `toolsetMode` | `'auto'|'required'` | `null` | `'auto'`: Generic tools; `'required'`: Empty `ToolSet` (add manually). |
75
+ | `debug` | boolean | `false` | Verbose logging. |
76
+
77
+ Internals: Creates `Prompt`, `Session`, sets `Prompt.setAdaptor(API.text[api], toolset, options)`.
78
+
79
+ ## Key Methods
80
+ | Method | Args | Returns | Description |
81
+ |--------|------|---------|-------------|
82
+ | `directCall(input)` | `string` | `Promise<string>` | One-shot query (via `prompt.call()`). |
83
+ | `getPrompt()` | - | `Prompt` | Access internal `Prompt`. |
84
+ | `getToolset()` | - | `ToolSet\|void` | Access tools. |
85
+ | `environment()` | - | `Promise<EnvironmentInfo>` | System info (via `fafs.js/env()`). |
86
+ | `addGenericToolcall(name)` | string (e.g., `'read_file'`) | - | Copy from `genericToolset.js` pool. Post-setup only. |
87
+ | `start(servePort?, connectUrl?, cliIntro?, toolName?, toolDesc?)` | Mixed | `Promise<void>` | **Smart launcher**:<br>- `servePort` (num): WS **server** (**toolName** MUST match name regex or auto-gen).<br>- `connectUrl` (str, e.g. `'ws://127.0.0.1:8000/ws'`): WS **client** (toolName/desc for attachment).<br>- Neither: **CLI** mode.<br>- Both: Hybrid. |
88
+
89
+ ## Workflow Diagram
90
+ ```mermaid
91
+ graph TD
92
+ A[New AgentManager name, secret] --> B[setup prompt, api, options, toolsetMode]
93
+ B --> C{start args?}
94
+ C -->|servePort| D[enableServer port, name, desc<br/>+ optional attach client]
95
+ C -->|connectUrl| E[attach client url, name, desc]
96
+ C -->|none| F[startCli intro]
97
+ D --> G[Session Loop: Prompt → API/Tools → Response]
98
+ E --> G
99
+ F --> G
100
+ G --> H[directCall or persist]
101
+ ```
102
+
103
+ **Per-Endpoint Options**:
104
+ - **CLI**: `start()` → `Cli` (interactive/piped). Options via `setup`.
105
+ - **WS Server**: `start(port)` → `AgentServer` (localhost only). Exposes agent as tool (name/desc). `secret` required for clients. `prompt.on('reset')` → `server.resetAll()`.
106
+ - **WS Client**: `start(undefined, url)` → `AgentClient`. Connects to remote server; agent callable as tool.
107
+ - **Direct**: `directCall()` bypasses networking/CLI.
108
+
109
+ ## Examples
110
+
111
+ ### 1. Interactive CLI Agent
112
+ ```javascript
113
+ import { AgentManager } from '@j-o-r/hello-dave';
114
+
115
+ const agent = new AgentManager({ name: 'chatbot' });
116
+ agent.setup({
117
+ prompt: 'You are a friendly chatbot.',
118
+ api: 'xai',
119
+ toolsetMode: 'auto'
120
+ });
121
+ await agent.start('Chatbot ready!'); // Auto-generates intro
122
+ ```
123
+
124
+ ### 2. WS Server (Expose as Tool)
125
+ ```javascript
126
+ import { AgentManager } from '@j-o-r/hello-dave';
127
+
128
+ agent.setup({ ... });
129
+ await agent.start(8000, undefined, undefined, 'weathertool', 'Get real-time weather');
130
+ ```
131
+ - Clients: `npx @j-o-r/hello-dave dave --connect ws://localhost:8000/ws --secret mysecret`
132
+
133
+ ### 3. Hybrid + Direct Call
134
+ ```javascript
135
+ import { AgentManager } from '@j-o-r/hello-dave';
136
+
137
+ await agent.start(8001, 'ws://other:8000/ws'); // Server on 8001 + client to other
138
+ const resp = await agent.directCall('Hybrid query'); // Uses attached tools too
139
+ ```
140
+
141
+ ### 4. Custom Tools + Generics
142
+ ```javascript
143
+ import { AgentManager } from '@j-o-r/hello-dave';
144
+
145
+ agent.setup({ toolsetMode: 'required' });
146
+ const ts = agent.getToolset();
147
+ ts.add('custommath', 'Add numbers', {
148
+ type: 'object', properties: {a: {type: 'number'}, b: {type: 'number'}},
149
+ required: ['a', 'b']
150
+ }, async ({a, b}) => a + b);
151
+ agent.addGenericToolcall('javascript_interpreter');
152
+ ```
153
+
154
+ ## Advanced: Networking & Secrets
155
+ - **Server-Client Chain**: Server A attaches to Server B → A callable from B (and vice versa if mutual).
156
+ - **Cron/CLI Messaging**: Pipe to client: `echo 'query' | npx ... dave --connect ...`
157
+ - **Reset**: `Prompt` emits `'reset'` → propagates to attached servers/clients.
158
+
159
+ ## Errors
160
+ - No `setup()`: Throws.
161
+ - **Invalid `name`/`toolName`: Regex `/^[a-z_0-9_]{2,}$/` fail → `Error`.**
162
+ - No `toolset` on server: Throws.
163
+
164
+ See source `lib/AgentManager.js` for full JSDoc/types. Cross-links:
165
+ - [Prompt](./prompt-class.md)
166
+ - [ToolSet](./toolset.md)
167
+ - [Generic Tools](../lib/genericToolset.js)