@j-o-r/hello-dave 0.0.7 → 0.0.8

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.
@@ -0,0 +1,265 @@
1
+ # Multi-Agent Clusters in Dave: v0.0.9
2
+
3
+ Welcome to the exciting world of **Multi-Agent Clusters** in the Dave framework! 🚀 If you're ready to scale your AI agents into powerful, collaborative clusters, you've come to the right place. This guide walks you through setting up CodeServer with PM2, spawning agents, launching in server mode, connecting clients, querying sessions, managing with PM2, testing, and more. By the end, you'll have a robust cluster humming along, enabling self-aware, interconnected agents. Let's dive in step-by-step!
4
+
5
+ Note: Dave v0.0.9 is fully ESM (ECMAScript Modules) consistent. All JavaScript examples use `import`/`export` syntax—no CommonJS `require`/`module.exports`.
6
+
7
+ ## CodeServer PM2 Setup
8
+
9
+ CodeServer is the backbone of your multi-agent cluster, providing a WebSocket-based server for agent communication. It integrates seamlessly with PM2 for process management, ensuring high availability and easy scaling.
10
+
11
+ ### Prerequisites
12
+ - Node.js (v18+ recommended)
13
+ - PM2 installed globally: `npm install -g pm2`
14
+ - Dave project cloned and dependencies installed: `npm install`
15
+
16
+ ### Step-by-Step Setup
17
+ 1. **Choose Your Launch Method**:
18
+ - Use the binary script: `./bin/codeDave` (convenient for quick starts).
19
+ - Or the shell script: `./agents/codeserver.sh` (for more customization).
20
+
21
+ 2. **Default Configuration**:
22
+ - **Port**: 9000 (change with `--port 8080` if needed).
23
+ - **Secret**: "123" (for secure WebSocket connections; override with `--secret your_secret`).
24
+
25
+ 3. **Launch CodeServer with PM2**:
26
+ Run the following to start CodeServer as a PM2-managed process:
27
+ ```
28
+ pm2 start ./bin/codeDave --name "hello-dave_code_9000" -- --serve --port 9000 --secret 123
29
+ ```
30
+ - `--serve`: Enables server mode (detailed below).
31
+ - This creates a process named `hello-dave_code_9000` for easy identification.
32
+
33
+ 4. **Verify Setup**:
34
+ - Check PM2 status: `pm2 list` (look for `hello-dave_code_9000` in "online" status).
35
+ - Test connection: Use a WebSocket client to connect to `ws://127.0.0.1:9000/ws` with secret "123".
36
+
37
+ ## Creating Agents via spawn_agent
38
+
39
+ Spawning agents is where the magic happens! Use the `spawn_agent` function to dynamically create and integrate new agents into your cluster. In v0.0.9, spawning is primarily via CLI for seamless integration with the ESM project structure.
40
+
41
+ ### Reference to spawn_agent Blueprint
42
+ For a deep dive into `spawn_agent`, check the [spawn_agent blueprint](../blueprints/spawn-agent.md) (or implement based on the core Dave agent manager patterns in [agent-manager.md](./agent-manager.md)).
43
+
44
+ ### Step-by-Step Agent Creation
45
+ 1. **CLI Spawning (Recommended)**:
46
+ Use the `./agents/spawn_agent.js` script to spawn agents directly from the command line, attaching them to the cluster:
47
+ ```
48
+ ./agents/spawn_agent.js "Create weather predictor agent with prompt: You are a weather prediction agent. Use tools to fetch data." --connect ws://127.0.0.1:9000/ws --secret 123 --tools web_search,weather_api
49
+ ```
50
+ - This spawns the agent (e.g., named "weatherPredictor" based on description), registers it with CodeServer, and enables collaborative querying.
51
+ - Flags: `--connect` for cluster attachment, `--secret` for authentication, `--tools` for tool assignment.
52
+
53
+ 2. **Integration with Cluster**:
54
+ - Agents auto-register with CodeServer upon spawn via the CLI.
55
+ - For programmatic control in ESM scripts, import and use as shown in examples below.
56
+
57
+ ## Launching Server Mode (--serve)
58
+
59
+ Server mode turns CodeServer into a persistent hub for multi-agent interactions.
60
+
61
+ 1. **Command**:
62
+ ```
63
+ ./bin/codeDave --serve --port 9000 --secret 123
64
+ ```
65
+
66
+ 2. **What Happens**:
67
+ - Listens on WebSocket endpoint `/ws`.
68
+ - Handles agent registrations and session management.
69
+ - Supports multiple concurrent clients.
70
+
71
+ 3. **PM2 Integration**:
72
+ As shown in setup, wrap it in PM2 for daemonization and auto-restart.
73
+
74
+ ## Attaching Clients (--connect)
75
+
76
+ Clients (like other Dave instances or tools) connect to the cluster for tool calls and session sharing.
77
+
78
+ 1. **Basic Connection**:
79
+ ```
80
+ ./bin/dave.js --connect ws://127.0.0.1:9000/ws --secret 123
81
+ ```
82
+ - This attaches the client as a tool-calling endpoint.
83
+ - Use in scripts for agent-to-agent communication.
84
+
85
+ 2. **Advanced Usage**:
86
+ - Pipe inputs: `echo "query" | ./bin/dave.js --connect ...`
87
+ - Handle toolcalls: Clients receive and execute tools on behalf of the cluster.
88
+
89
+ ## Querying via bin/dave.js --connect
90
+
91
+ For one-shot queries or building sessions, use `bin/dave.js` with connection flags.
92
+
93
+ ### One-Shot Example
94
+ Predict weather with a quick query:
95
+ ```
96
+ echo "predict weather in NYC" | ./bin/dave.js --connect ws://127.0.0.1:9000/ws --secret 123
97
+ ```
98
+ - Builds a temporary session, routes to relevant agents (e.g., weatherPredictor), and returns results.
99
+
100
+ ### Session Building
101
+ For persistent sessions:
102
+ ```
103
+ ./bin/dave.js --connect ws://127.0.0.1:9000/ws --secret 123 --session my_weather_session
104
+ ```
105
+ - Follow with queries to maintain state across interactions.
106
+
107
+ ## PM2 Start/Stop/Reload
108
+
109
+ PM2 makes cluster management a breeze!
110
+
111
+ 1. **List Processes**:
112
+ ```
113
+ pm2 list
114
+ ```
115
+ - Shows status of `hello-dave_code_9000` and other agents.
116
+
117
+ 2. **Start/Stop**:
118
+ ```
119
+ pm2 start hello-dave_code_9000 # Start
120
+ pm2 stop hello-dave_code_9000 # Stop
121
+ pm2 restart hello-dave_code_9000 # Restart
122
+ ```
123
+
124
+ 3. **Reload (Zero-Downtime)**:
125
+ ```
126
+ pm2 reload hello-dave_code_9000
127
+ ```
128
+ - Ideal for updates without interrupting sessions.
129
+
130
+ 4. **Logs and Monitoring**:
131
+ ```
132
+ pm2 logs hello-dave_code_9000
133
+ pm2 monit
134
+ ```
135
+
136
+ ## Testing One-Shots and Sessions
137
+
138
+ Ensure your cluster is rock-solid with these tests.
139
+
140
+ ### One-Shot Testing
141
+ 1. Spawn a test agent.
142
+ 2. Run: `echo "test query" | ./bin/dave.js --connect ...`
143
+ 3. Verify output matches expected (e.g., no errors, relevant response).
144
+
145
+ ### Session Testing
146
+ 1. Start a session: `./bin/dave.js --connect ... --session test`
147
+ 2. Send multiple queries: `echo "first" | ...` then `echo "follow-up" | ...`
148
+ 3. Check session persistence (e.g., context retained).
149
+
150
+ ### End-to-End Test Script
151
+ ```bash
152
+ #!/bin/bash
153
+ # test_cluster.sh
154
+ pm2 start ./bin/codeDave --name "test_code" -- --serve --port 9000 --secret 123
155
+ sleep 2
156
+ echo "Hello cluster!" | ./bin/dave.js --connect ws://127.0.0.1:9000/ws --secret 123
157
+ pm2 stop test_code
158
+ ```
159
+
160
+ ## Self-Awareness: Detecting PM2/CodeServer in Prompts
161
+
162
+ Make your agents smarter by embedding cluster awareness! In v0.0.9, self-awareness leverages argument detection and initial PM2 inspection for accurate blueprint compliance.
163
+
164
+ - **In Agent Prompts**:
165
+ Include detection logic: "If running under PM2/CodeServer (detect via args like --serve/--connect or initial `pm2 list` inspect), coordinate with cluster agents."
166
+
167
+ - **Implementation** (ESM Syntax):
168
+ Agents auto-detect via argument parsing and PM2 inspection:
169
+ ```javascript
170
+ import { execSync } from 'child_process';
171
+ import { process } from 'process'; // Built-in
172
+
173
+ const args = process.argv.slice(2);
174
+ const isServeMode = args.includes('--serve');
175
+ const isConnectMode = args.includes('--connect');
176
+ const pm2Status = execSync('pm2 list', { encoding: 'utf8' }).includes('hello-dave_code_9000');
177
+
178
+ if (isServeMode || isConnectMode || pm2Status) {
179
+ // Cluster mode: Share context, route to other agents
180
+ console.log('Detected cluster environment');
181
+ }
182
+ ```
183
+ This enables self-aware routing, e.g., "Delegate weather query to weatherPredictor in cluster." Aligns with blueprint by inspecting PM2 initially for process awareness.
184
+
185
+ ## Mermaid Diagram: Cluster Architecture
186
+
187
+ Visualize your setup!
188
+
189
+ ```mermaid
190
+ graph TD
191
+ A[PM2 Manager] --> B[CodeServer<br/>Port 9000 /ws]
192
+ B --> C[Agent 1<br/>spawn_agent()]
193
+ B --> D[Agent 2<br/>e.g., WeatherPredictor]
194
+ E[Client / bin/dave.js] -->|connect| B
195
+ E -->|one-shot| F[Session Builder]
196
+ G[Tools: web_search, etc.] <-->|toolcalls| C
197
+ G <-->|toolcalls| D
198
+ style B fill:#f9f,stroke:#333,stroke-width:2px
199
+ ```
200
+
201
+ - **Nodes**: PM2 oversees CodeServer, which hubs agents and clients.
202
+ - **Flows**: Connections for spawning, querying, and tool execution.
203
+
204
+ ## Examples
205
+
206
+ ### Full ESM Node Script for Custom Agent Launch (--serve)
207
+ Here&apos;s a complete ESM script (`custom-agent-launch.mjs`) to spawn and launch a custom agent in server mode:
208
+
209
+ ```javascript
210
+ #!/usr/bin/env node
211
+ // custom-agent-launch.mjs - ESM for v0.0.9
212
+
213
+ import { spawn_agent } from &apos;./agents/spawn.js&apos;; // ESM import
214
+ import { connectToCluster } from &apos;./utils/cluster.js&apos;; // Hypothetical utility
215
+
216
+ async function main() {
217
+ const agentConfig = {
218
+ name: &quot;queryMaster&quot;,
219
+ prompt: &quot;You are a master query router in the cluster.&quot;,
220
+ tools: [&apos;web_search&apos;],
221
+ cluster: &quot;ws://127.0.0.1:9000/ws&quot;
222
+ };
223
+
224
+ // Spawn the agent
225
+ const agent = await spawn_agent(agentConfig);
226
+
227
+ // Connect to cluster if in server mode
228
+ if (process.argv.includes(&apos;--serve&apos;)) {
229
+ await connectToCluster(agent, { secret: &quot;123&quot; });
230
+ console.log(&apos;Agent launched in server mode!&quot;);
231
+ }
232
+ }
233
+
234
+ main().catch(console.error);
235
+ ```
236
+
237
+ Run it: `node custom-agent-launch.mjs --serve`
238
+
239
+ ### Full Cluster Spawn and Query (CLI + ESM)
240
+ 1. Start CodeServer: `pm2 start ./bin/codeDave --name code_9000 -- --serve --port 9000 --secret 123`
241
+ 2. Spawn Agent (CLI):
242
+ ```
243
+ ./agents/spawn_agent.js &quot;Create queryMaster: You are a master query router.&quot; --connect ws://127.0.0.1:9000/ws --secret 123
244
+ ```
245
+ 3. Query: `echo &quot;What&apos;s the plan?&quot; | ./bin/dave.js --connect ws://127.0.0.1:9000/ws --secret 123`
246
+
247
+ ### Multi-Agent Collaboration
248
+ - Spawn multiple: weather, news, summary agents.
249
+ - Query: &quot;Summarize today&apos;s news and weather&quot; → Routes to respective agents via cluster.
250
+
251
+ ## Troubleshooting
252
+
253
+ - **Connection Refused**: Ensure CodeServer is running (`pm2 list`) and port 9000 is free (`lsof -i :9000`).
254
+ - **Secret Mismatch**: Double-check `--secret` flags match.
255
+ - **PM2 Crashes**: View logs (`pm2 logs`)—common issues: missing deps or port conflicts. Restart: `pm2 restart all`.
256
+ - **Agent Not Attaching**: Verify `spawn_agent` cluster URL and secret. Test WebSocket manually.
257
+ - **Session Loss**: Check PM2 memory limits (`pm2 desc code_9000`); increase if needed.
258
+ - **One-Shot Fails**: Ensure input is piped correctly; debug with `--verbose`.
259
+ - **ESM Import Errors**: Ensure `package.json` has &quot;type&quot;: &quot;module&quot; and files use `.mjs` or `.js` with ESM syntax.
260
+
261
+ If issues persist, reference [project-overview.md](./project-overview.md) or spawn a debug agent!
262
+
263
+ ---
264
+
265
+ *Ready for v0.0.9 deployment! Cluster up and conquer those multi-agent challenges. 🎉 Questions? Ping the Dave community.*
@@ -0,0 +1,229 @@
1
+ # Multi-Agent Clusters in Dave: v0.0.9
2
+
3
+ Welcome to the exciting world of **Multi-Agent Clusters** in the Dave framework! 🚀 If you&apos;re ready to scale your AI agents into powerful, collaborative clusters, you&apos;ve come to the right place. This guide walks you through setting up CodeServer with PM2, spawning agents, launching in server mode, connecting clients, querying sessions, managing with PM2, testing, and more. By the end, you&apos;ll have a robust cluster humming along, enabling self-aware, interconnected agents. Let&apos;s dive in step-by-step!
4
+
5
+ ## CodeServer PM2 Setup
6
+
7
+ CodeServer is the backbone of your multi-agent cluster, providing a WebSocket-based server for agent communication. It integrates seamlessly with PM2 for process management, ensuring high availability and easy scaling.
8
+
9
+ ### Prerequisites
10
+ - Node.js (v18+ recommended)
11
+ - PM2 installed globally: `npm install -g pm2`
12
+ - Dave project cloned and dependencies installed: `npm install`
13
+
14
+ ### Step-by-Step Setup
15
+ 1. **Choose Your Launch Method**:
16
+ - Use the binary script: `./bin/codeDave` (convenient for quick starts).
17
+ - Or the shell script: `./agents/codeserver.sh` (for more customization).
18
+
19
+ 2. **Default Configuration**:
20
+ - **Port**: 9000 (change with `--port 8080` if needed).
21
+ - **Secret**: &quot;123&quot; (for secure WebSocket connections; override with `--secret your_secret`).
22
+
23
+ 3. **Launch CodeServer with PM2**:
24
+ Run the following to start CodeServer as a PM2-managed process:
25
+ ```
26
+ pm2 start ./bin/codeDave --name &quot;hello-dave_code_9000&quot; -- --serve --port 9000 --secret 123
27
+ ```
28
+ - `--serve`: Enables server mode (detailed below).
29
+ - This creates a process named `hello-dave_code_9000` for easy identification.
30
+
31
+ 4. **Verify Setup**:
32
+ - Check PM2 status: `pm2 list` (look for `hello-dave_code_9000` in &quot;online&quot; status).
33
+ - Test connection: Use a WebSocket client to connect to `ws://127.0.0.1:9000/ws` with secret &quot;123&quot;.
34
+
35
+ ## Creating Agents via spawn_agent
36
+
37
+ Spawning agents is where the magic happens! Use the `spawn_agent` function to dynamically create and integrate new agents into your cluster.
38
+
39
+ ### Reference to spawn_agent Blueprint
40
+ For a deep dive into `spawn_agent`, check the [spawn_agent blueprint](../blueprints/spawn-agent.md) (or implement based on the core Dave agent manager patterns in [agent-manager.md](./agent-manager.md)).
41
+
42
+ ### Step-by-Step Agent Creation
43
+ 1. **Import and Initialize**:
44
+ In your Node.js script:
45
+ ```javascript
46
+ const { spawn_agent } = require(&apos;./agents/spawn&apos;); // Adjust path as needed
47
+ ```
48
+
49
+ 2. **Spawn an Agent**:
50
+ ```javascript
51
+ const newAgent = spawn_agent({
52
+ name: &quot;weatherPredictor&quot;,
53
+ prompt: &quot;You are a weather prediction agent. Use tools to fetch data.&quot;,
54
+ tools: [&apos;web_search&apos;, &apos;weather_api&apos;],
55
+ cluster: &quot;ws://127.0.0.1:9000/ws&quot; // Attach to your CodeServer
56
+ });
57
+ ```
58
+ - This generates the agent and attaches it to the cluster for collaborative querying.
59
+
60
+ 3. **Integration with Cluster**:
61
+ - Agents auto-register with CodeServer upon spawn.
62
+ - Use `newAgent.connect({ secret: &quot;123&quot; })` to ensure secure attachment.
63
+
64
+ ## Launching Server Mode (--serve)
65
+
66
+ Server mode turns CodeServer into a persistent hub for multi-agent interactions.
67
+
68
+ 1. **Command**:
69
+ ```
70
+ ./bin/codeDave --serve --port 9000 --secret 123
71
+ ```
72
+
73
+ 2. **What Happens**:
74
+ - Listens on WebSocket endpoint `/ws`.
75
+ - Handles agent registrations and session management.
76
+ - Supports multiple concurrent clients.
77
+
78
+ 3. **PM2 Integration**:
79
+ As shown in setup, wrap it in PM2 for daemonization and auto-restart.
80
+
81
+ ## Attaching Clients (--connect)
82
+
83
+ Clients (like other Dave instances or tools) connect to the cluster for tool calls and session sharing.
84
+
85
+ 1. **Basic Connection**:
86
+ ```
87
+ ./bin/dave.js --connect ws://127.0.0.1:9000/ws --secret 123
88
+ ```
89
+ - This attaches the client as a tool-calling endpoint.
90
+ - Use in scripts for agent-to-agent communication.
91
+
92
+ 2. **Advanced Usage**:
93
+ - Pipe inputs: `echo &quot;query&quot; | ./bin/dave.js --connect ...`
94
+ - Handle toolcalls: Clients receive and execute tools on behalf of the cluster.
95
+
96
+ ## Querying via bin/dave.js --connect
97
+
98
+ For one-shot queries or building sessions, use `bin/dave.js` with connection flags.
99
+
100
+ ### One-Shot Example
101
+ Predict weather with a quick query:
102
+ ```
103
+ echo &quot;predict weather in NYC&quot; | ./bin/dave.js --connect ws://127.0.0.1:9000/ws --secret 123
104
+ ```
105
+ - Builds a temporary session, routes to relevant agents (e.g., weatherPredictor), and returns results.
106
+
107
+ ### Session Building
108
+ For persistent sessions:
109
+ ```
110
+ ./bin/dave.js --connect ws://127.0.0.1:9000/ws --secret 123 --session my_weather_session
111
+ ```
112
+ - Follow with queries to maintain state across interactions.
113
+
114
+ ## PM2 Start/Stop/Reload
115
+
116
+ PM2 makes cluster management a breeze!
117
+
118
+ 1. **List Processes**:
119
+ ```
120
+ pm2 list
121
+ ```
122
+ - Shows status of `hello-dave_code_9000` and other agents.
123
+
124
+ 2. **Start/Stop**:
125
+ ```
126
+ pm2 start hello-dave_code_9000 # Start
127
+ pm2 stop hello-dave_code_9000 # Stop
128
+ pm2 restart hello-dave_code_9000 # Restart
129
+ ```
130
+
131
+ 3. **Reload (Zero-Downtime)**:
132
+ ```
133
+ pm2 reload hello-dave_code_9000
134
+ ```
135
+ - Ideal for updates without interrupting sessions.
136
+
137
+ 4. **Logs and Monitoring**:
138
+ ```
139
+ pm2 logs hello-dave_code_9000
140
+ pm2 monit
141
+ ```
142
+
143
+ ## Testing One-Shots and Sessions
144
+
145
+ Ensure your cluster is rock-solid with these tests.
146
+
147
+ ### One-Shot Testing
148
+ 1. Spawn a test agent.
149
+ 2. Run: `echo &quot;test query&quot; | ./bin/dave.js --connect ...`
150
+ 3. Verify output matches expected (e.g., no errors, relevant response).
151
+
152
+ ### Session Testing
153
+ 1. Start a session: `./bin/dave.js --connect ... --session test`
154
+ 2. Send multiple queries: `echo &quot;first&quot; | ...` then `echo &quot;follow-up&quot; | ...`
155
+ 3. Check session persistence (e.g., context retained).
156
+
157
+ ### End-to-End Test Script
158
+ ```bash
159
+ #!/bin/bash
160
+ # test_cluster.sh
161
+ pm2 start ./bin/codeDave --name &quot;test_code&quot; -- --serve --port 9000 --secret 123
162
+ sleep 2
163
+ echo &quot;Hello cluster!&quot; | ./bin/dave.js --connect ws://127.0.0.1:9000/ws --secret 123
164
+ pm2 stop test_code
165
+ ```
166
+
167
+ ## Self-Awareness: Detecting PM2/CodeServer in Prompts
168
+
169
+ Make your agents smarter by embedding cluster awareness!
170
+
171
+ - **In Agent Prompts**:
172
+ Include detection logic: &quot;If running under PM2/CodeServer (detect via env vars like PM2_PROCESS_ID or connection to ws://localhost:9000), coordinate with cluster agents.&quot;
173
+
174
+ - **Implementation**:
175
+ Agents auto-detect via:
176
+ ```javascript
177
+ if (process.env.PM2_PROCESS_ID || connection.url.includes(&apos;9000&apos;)) {
178
+ // Cluster mode: Share context
179
+ }
180
+ ```
181
+ This enables self-aware routing, e.g., &quot;Delegate weather query to weatherPredictor in cluster.&quot;
182
+
183
+ ## Mermaid Diagram: Cluster Architecture
184
+
185
+ Visualize your setup!
186
+
187
+ ```mermaid
188
+ graph TD
189
+ A[PM2 Manager] --> B[CodeServer<br/>Port 9000 /ws]
190
+ B --> C[Agent 1<br/>spawn_agent()]
191
+ B --> D[Agent 2<br/>e.g., WeatherPredictor]
192
+ E[Client / bin/dave.js] -->|connect| B
193
+ E -->|one-shot| F[Session Builder]
194
+ G[Tools: web_search, etc.] <-->|toolcalls| C
195
+ G <-->|toolcalls| D
196
+ style B fill:#f9f,stroke:#333,stroke-width:2px
197
+ ```
198
+
199
+ - **Nodes**: PM2 oversees CodeServer, which hubs agents and clients.
200
+ - **Flows**: Connections for spawning, querying, and tool execution.
201
+
202
+ ## Examples
203
+
204
+ ### Full Cluster Spawn and Query
205
+ 1. Start CodeServer: `pm2 start ./bin/codeDave --name code_9000 -- --serve --port 9000 --secret 123`
206
+ 2. Spawn Agent (in Node script):
207
+ ```javascript
208
+ const agent = spawn_agent({ name: &quot;queryMaster&quot;, cluster: &quot;ws://127.0.0.1:9000/ws&quot; });
209
+ ```
210
+ 3. Query: `echo &quot;What&apos;s the plan?&quot; | ./bin/dave.js --connect ws://127.0.0.1:9000/ws --secret 123`
211
+
212
+ ### Multi-Agent Collaboration
213
+ - Spawn multiple: weather, news, summary agents.
214
+ - Query: &quot;Summarize today&apos;s news and weather&quot; → Routes to respective agents via cluster.
215
+
216
+ ## Troubleshooting
217
+
218
+ - **Connection Refused**: Ensure CodeServer is running (`pm2 list`) and port 9000 is free (`lsof -i :9000`).
219
+ - **Secret Mismatch**: Double-check `--secret` flags match.
220
+ - **PM2 Crashes**: View logs (`pm2 logs`)—common issues: missing deps or port conflicts. Restart: `pm2 restart all`.
221
+ - **Agent Not Attaching**: Verify `spawn_agent` cluster URL and secret. Test WebSocket manually.
222
+ - **Session Loss**: Check PM2 memory limits (`pm2 desc code_9000`); increase if needed.
223
+ - **One-Shot Fails**: Ensure input is piped correctly; debug with `--verbose`.
224
+
225
+ If issues persist, reference [project-overview.md](./project-overview.md) or spawn a debug agent!
226
+
227
+ ---
228
+
229
+ *Ready for v0.0.9 deployment! Cluster up and conquer those multi-agent challenges. 🎉 Questions? Ping the Dave community.*
@@ -0,0 +1,104 @@
1
+ # Path Resolution Best Practices for Generic Tools
2
+
3
+ ## Overview
4
+ In `lib/genericToolset.js` and related tools (e.g., `syntax_check`, `write_file`), **path resolution** distinguishes between:
5
+ - **Module-relative paths** (utils/scripts): Use `__dirname` for portability.
6
+ - **User-provided file paths**: Resolve to `process.cwd()` (CWD sandbox) + strict validation.
7
+
8
+ This ensures **sandboxing** (no escapes), **portability** (works from any CWD/PM2), and **security**. All tools enforce: no `/`, `..`, `\\\\`; `resolvedPath.startsWith(process.cwd())`.
9
+
10
+ **ESM Setup** (genericToolset.js):
11
+ ```javascript
12
+ const __dirname = path.dirname(fileURLToPath(import.meta.url)); // Polyfill for ESM
13
+ ```
14
+
15
+ ## __dirname vs process.cwd(): When to Use What
16
+
17
+ | Context | Resolution | Example Code | Rationale |
18
+ |---------|------------|--------------|-----------|
19
+ | **Utils/Scripts** (e.g., syntax_check.sh, search_sessions.sh) | `__dirname` (module-rel) | `path.resolve(__dirname, '..', 'utils', 'syntax_check.sh')` | Portable: Locates utils/ from `lib/` regardless of CWD. Works in servers/clients. |
20
+ | **User Files** (read/write/syntax/memory) | `process.cwd()` | `path.resolve(process.cwd(), params.file)` | Sandbox: Pins to project CWD (`~/devpri/js/hello-dave`). Prevents jailbreaks. |
21
+ | **Cache/Memory** | `path.join(process.cwd(), '.cache/...')` | `.cache/hello-dave/memory.ndjson` | Per-project persistence. |
22
+ | **Shebangs/Chmod** | Absolute (resolved) | `SH`chmod +x ${[resolvedPath]}` | Post-write on validated path. |
23
+
24
+ **Universal Validation** (in read_file, write_file, syntax_check):
25
+ ```javascript
26
+ const file = params.file?.trim();
27
+ if (file.startsWith('/') || file.includes('..') || file.includes('\\\\')) {
28
+ throw new Error('Path must be relative within CWD only (no `/`, `..`, or `\\\\`).');
29
+ }
30
+ const resolvedPath = path.resolve(process.cwd(), file);
31
+ if (!resolvedPath.startsWith(process.cwd())) {
32
+ throw new Error(`Path '${file}' escapes CWD scope.`);
33
+ }
34
+ ```
35
+
36
+ ## syntax_check.sh Path Fix (User-Reported)
37
+
38
+ **Issue** (Early Versions):
39
+ - Relative paths passed to SH`` → Failed if CWD != lib/.
40
+ - E.g., `SH`syntax_check.sh "rel/file.js"`` → "No such file" in sub-processes (PM2/CodeServer).
41
+
42
+ **Fix** (Implemented):
43
+ 1. **Absolute Script Path**: `path.resolve(__dirname, '..', 'utils', 'syntax_check.sh')`.
44
+ 2. **Absolute File Arg**: `${syntaxChecker} "${resolvedPath}"` (resolvedPath = CWD-abs).
45
+ 3. **Script Handles Absolutes**: `FILE="$1"`; `head -n1 "$FILE"` works anywhere.
46
+
47
+ **Test from Any CWD**:
48
+ ```bash
49
+ cd /tmp
50
+ /full/path/to/hello-dave/utils/syntax_check.sh /full/path/to/hello-dave/test.js # ✅ JS OK
51
+ # Or via tool: agent.directCall("syntax_check('test.js')") # Resolves internally
52
+ ```
53
+
54
+ **SH Best Practice**: Use array args `${[resolvedPath]}` → Auto-quotes/escapes paths with spaces.
55
+
56
+ ## Best Practices & Pitfalls
57
+
58
+ ### ✅ Do
59
+ 1. **Utils**: Always `__dirname, '..', 'utils', 'script.sh'` → Portable across deployments.
60
+ 2. **Files**: `process.cwd()` + validation → Sandboxed writes/reads.
61
+ 3. **SH Calls**: `SH`${script} ${[path]}`.run()` → Safe quoting via @j-o-r/sh.
62
+ 4. **Join vs Resolve**: `path.join(process.cwd(), '.cache')` for dirs; `resolve` for files.
63
+ 5. **ESM __dirname**: Polyfill with `fileURLToPath(import.meta.url)`.
64
+
65
+ ### ❌ Avoid
66
+ 1. `path.resolve(file)` → Assumes CWD; skips validation.
67
+ 2. `__dirname` for user files → Escapes to lib/ (security hole).
68
+ 3. Relative SH args → Breaks in non-lib CWD (e.g., WS clients).
69
+ 4. `process.chdir()` → Mutates global; use per-tool cwd.
70
+
71
+ ### Real-World Examples (from genericToolset.js)
72
+ - **history_search**:
73
+ ```js
74
+ const history_search = path.resolve(__dirname, '..', 'utils', 'search_sessions.sh');
75
+ SH`${history_search} "${escapedQuery}"`.run();
76
+ ```
77
+ - **syntax_check**:
78
+ ```js
79
+ const syntaxChecker = path.resolve(__dirname, '..', 'utils', 'syntax_check.sh');
80
+ return await SH`${syntaxChecker} "${resolvedPath}"`.run();
81
+ ```
82
+ - **write_file** (AUTO-VALIDATE):
83
+ ```js
84
+ const syntaxChecker = path.resolve(__dirname, '..', 'utils', 'syntax_check.sh');
85
+ await SH`${syntaxChecker} ${[resolvedPath]}`.run(); // Throws on fail
86
+ ```
87
+
88
+ ## Troubleshooting
89
+ | Issue | Cause | Fix |
90
+ |-------|-------|-----|
91
+ | "No such file: utils/script.sh" | Wrong CWD | Use `__dirname` for utils. |
92
+ | "Path escapes CWD" | `..` in input | Input validation blocks. |
93
+ | SH arg unescaped | Spaces/specials | Array `${[path]}` auto-handles. |
94
+ | ESM no __dirname | Node <20 | Polyfill shown above. |
95
+
96
+ **Pro Tip**: For custom tools, copy pattern: `__dirname` (utils), `process.cwd()` (files).
97
+
98
+ ## Cross-Links
99
+ - [ToolSet](../toolset.md#generic-tools)
100
+ - [Syntax Validation](../tools-syntax-validation.md)
101
+ - [genericToolset.js](../lib/genericToolset.js) (grep "path.resolve")
102
+ - Utils: [syntax_check.sh](../utils/syntax_check.sh)
103
+
104
+ **Updated**: March 27, 2026 (syntax_check.sh path fix documented).
@@ -0,0 +1,67 @@
1
+ # Hello-Dave Project Overview
2
+
3
+ ## Root Directory
4
+ The root contains essential project configuration, documentation, and entry points:
5
+ - **README.md**: Main project documentation and setup instructions.
6
+ - **TODO.md**: Outstanding tasks and development notes.
7
+ - **package.json**: NPM package metadata, dependencies, and scripts.
8
+ - **LICENSE**: Project license (Apache 2.0).
9
+ - **jsconfig.json** / **tsc.json**: TypeScript/JavaScript configuration for editor and compiler support.
10
+ - **.gitignore** / **.npmignore**: Git and NPM ignore rules.
11
+ - **workspace.js**: Development or workspace management script.
12
+ - Directories: `bin/`, `docs/`, `agents/`, `lib/`, `scenarios/`, `types/`, `utils/`, `release/`, `node_modules/`, `.cache/` (for sessions).
13
+
14
+ ## bin/
15
+ Executable CLI scripts (npm bin entries) for spawning and interacting with specialized \"Dave\" agents. These are user-facing tools for quick tasks:
16
+ - `spawn_agent.js`: Generates and runs custom agent scripts.
17
+ - `ask_agent.js`, `chat2_agent.js`: General interactive chat/query.
18
+ - `code_agent.js`: Code-related agent.
19
+ - `prompt_agent.js`, `docs_agent.js`: Prompt engineering and docs management.
20
+ - `readme_agent.js`, `todo_agent.js`: Project maintenance (README/TODO).
21
+ - `npm_agent.js`: NPM module inspection/publishing.
22
+ - Others: `format_agent.js`, `clear_agent.js`, `CodeServer`.
23
+
24
+ ## lib/
25
+ Core library code (ESM modules) **named exports only** from `lib/index.js` (NO default export):
26
+ - **index.js**: Main export barrel (`{ AgentManager, Prompt, ToolSet, ... }`).
27
+ - **AgentManager.js**: Central orchestrator for agents—handles setup, sessions, tools, networking (WS server/client), and `start()` for CLI/server modes.
28
+ - **Prompt.js**: Conversation manager (EventEmitter)—tracks messages, tools, truncation, token counting, provider adapters.
29
+ - **ToolSet.js**: Defines/extends tools (JSON Schema + handlers) like bash execution, web search, JS interpreter.
30
+ - **AgentServer.js**, **AgentClient.js**: WebSocket server/client for agent networking.
31
+ - **Session.js**: Persistent chat history/logs (NDJSON in `.cache/`).
32
+ - **Cli.js**: CLI input/output handling.
33
+ - **genericToolset.js**: Pre-configured toolset with common tools.
34
+ - **fafs.js**, **promptHelpers.js**: Utilities (env, file access, prompt ops).
35
+ - **API/**: Provider-specific wrappers (subdirs):
36
+ - `anthropic.com/`: Claude API.
37
+ - `brave.com/`: Search API.
38
+ - `openai.com/`: GPT API.
39
+ - `x.ai/`: Grok/xAI API (responses, files, collections).
40
+
41
+ ## Agent Workflow
42
+ An **Agent** (via `AgentManager`) is configured with:
43
+ 1. **System prompt** (via `Prompt.js`): Defines personality/task.
44
+ 2. **API provider** (from `lib/API/`): xAI/Grok, OpenAI/GPT, Anthropic/Claude.
45
+ 3. **ToolSet** (`ToolSet.js`): Custom/local functions (e.g., `execute_bash_script`, `web_search`); extensible.
46
+ 4. **Session**: Conversation history.
47
+
48
+ Modes: Standalone CLI, one-shot query, WS **server** (expose as tool), **client** (attach to server), hybrid. `bin/spawn_agent.js` generates custom agents leveraging this.
49
+
50
+ ## docs/
51
+ Project documentation (Markdown) ✅ **Complete** (reviewed Mar 24, 2026):
52
+ - `project-overview.md`: This file.
53
+ - `prompt-class.md`: Deep dive on `Prompt.js`.
54
+ - `toolset.md`: `ToolSet.js` details + 9 generics.
55
+ - `agent-manager.md`: **AgentManager** workflows, options, Mermaid diagrams.
56
+ - `xai-responses.md`: xAI Responses API integration/examples.
57
+ - `xai-collections.md`: xAI Collections (raw; Later priority).
58
+
59
+ ## Other Directories
60
+ - **agents/**: Usage demos (e.g., `daisy_agent.js` music agent).
61
+ - **scenarios/**: Tests/demos (e.g., `grok_agent.js`, `wsAgent.js`).
62
+ - **types/**: TypeScript `.d.ts` files.
63
+ - **utils/**: Miscellaneous utilities.
64
+ - **release/**: NPM pack artifacts.
65
+
66
+ ## Summary
67
+ `hello-dave` (@j-o-r/hello-dave NPM pkg) is a lightweight ESM Node.js framework for **tool-using AI agents** with unified LLM access (Grok/Claude/GPT), WS networking, and CLI tools. **Import via named exports: `import { AgentManager } from '@j-o-r/hello-dave';`**. Focus: Rapid prototyping of domain agents (code, docs, music) via `AgentManager` + `Prompt` + `ToolSet` + APIs. Sessions in `.cache/`. Node >=20.