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

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,278 @@
1
+ # JSDoc Best Practices for JavaScript Modules
2
+
3
+ ## Introduction
4
+
5
+ JSDoc is a markup language used to annotate JavaScript source code files. It allows developers to document their code in a structured way, generating documentation that is readable by humans and machines alike. This is particularly valuable for JavaScript modules, especially toolsets or utility libraries, where clear documentation helps users understand APIs, types, and usage.
6
+
7
+ Best practices ensure documentation is consistent, comprehensive, and maintainable. Key benefits include:
8
+ - Improved code readability and maintainability.
9
+ - IDE support for autocompletion, type checking, and hover tooltips.
10
+ - Generation of static HTML documentation sites.
11
+ - Reusability across teams and projects.
12
+
13
+ This guide focuses on documenting functions, classes, parameters, returns, and types, with examples tailored to utility libraries.
14
+
15
+ ## Documenting Modules
16
+
17
+ Use the `@module` tag to mark a file as a module. All symbols in the file become module members. For utility libraries, document exports explicitly.
18
+
19
+ ### Example: Exporting Functions in a Utility Module
20
+ ```javascript
21
+ /**
22
+ * @module utils/string
23
+ * String manipulation utilities.
24
+ */
25
+
26
+ /**
27
+ * Formats a string by capitalizing the first letter.
28
+ * @param {string} str - The input string.
29
+ * @returns {string} The formatted string.
30
+ * @example
31
+ * capitalize("hello world"); // "Hello world"
32
+ */
33
+ function capitalize(str) {
34
+ return str.charAt(0).toUpperCase() + str.slice(1);
35
+ }
36
+
37
+ module.exports = { capitalize };
38
+ ```
39
+
40
+ This creates a documented module `module:utils/string` with exported member `module:utils/string.capitalize`.
41
+
42
+ ### Namespaces for Organization
43
+ For larger libraries, use `@namespace` to group related utilities.
44
+ ```javascript
45
+ /**
46
+ * @module math
47
+ * @namespace math.utils
48
+ */
49
+ ```
50
+
51
+ ## Documenting Functions
52
+
53
+ Functions are the core of utility libraries. Use `@param` for parameters, `@returns` for return values, and include types and descriptions.
54
+
55
+ ### Basic Function Documentation
56
+ ```javascript
57
+ /**
58
+ * Adds two numbers.
59
+ * @param {number} a - The first number.
60
+ * @param {number} b - The second number.
61
+ * @returns {number} The sum of a and b.
62
+ * @throws {Error} If inputs are not numbers.
63
+ * @example
64
+ * add(2, 3); // 5
65
+ */
66
+ function add(a, b) {
67
+ if (typeof a !== "number" || typeof b !== "number") {
68
+ throw new Error("Inputs must be numbers");
69
+ }
70
+ return a + b;
71
+ }
72
+ ```
73
+
74
+ ### Optional Parameters and Defaults
75
+ ```javascript
76
+ /**
77
+ * Formats a number with thousand separators.
78
+ * @param {number} value - The number to format.
79
+ * @param {string} [separator=","] - The separator (default: comma).
80
+ * @returns {string} The formatted string.
81
+ * @example
82
+ * formatNumber(1000); // "1,000"
83
+ * formatNumber(1000, "."); // "1.000"
84
+ */
85
+ function formatNumber(value, separator = ",") {
86
+ return value.toLocaleString("en-US", { separator });
87
+ }
88
+ ```
89
+
90
+ ### Variadic (Rest) Parameters
91
+ ```javascript
92
+ /**
93
+ * Sums multiple numbers.
94
+ * @param {...number} nums - Numbers to sum.
95
+ * @returns {number} The total sum.
96
+ * @example
97
+ * sum(1, 2, 3); // 6
98
+ */
99
+ function sum(...nums) {
100
+ return nums.reduce((acc, n) => acc + n, 0);
101
+ }
102
+ ```
103
+
104
+ ### Asynchronous Functions
105
+ ```javascript
106
+ /**
107
+ * Fetches data asynchronously.
108
+ * @param {string} url - The URL to fetch.
109
+ * @returns {Promise<Object>} A promise resolving to the data.
110
+ */
111
+ async function fetchData(url) {
112
+ const response = await fetch(url);
113
+ return response.json();
114
+ }
115
+ ```
116
+
117
+ ## Documenting Classes
118
+
119
+ For classes in utility libraries (e.g., a Validator class), document constructors, methods, and properties. JSDoc 3.4+ auto-detects ES6 classes.
120
+
121
+ ### Simple Class Example
122
+ ```javascript
123
+ /**
124
+ * A utility class for validating inputs.
125
+ */
126
+ class Validator {
127
+ /**
128
+ * Creates a new Validator instance.
129
+ * @param {Object} options - Configuration options.
130
+ * @param {boolean} [options.strict=false] - Strict mode.
131
+ */
132
+ constructor(options = {}) {
133
+ this.strict = options.strict || false;
134
+ }
135
+
136
+ /**
137
+ * Validates an email address.
138
+ * @param {string} email - The email to validate.
139
+ * @returns {boolean} True if valid.
140
+ * @memberof Validator
141
+ */
142
+ validateEmail(email) {
143
+ const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
144
+ return regex.test(email);
145
+ }
146
+
147
+ /**
148
+ * Static method to validate without instance.
149
+ * @param {string} email - The email to validate.
150
+ * @returns {boolean} True if valid.
151
+ * @static
152
+ */
153
+ static isValidEmail(email) {
154
+ const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
155
+ return regex.test(email);
156
+ }
157
+ }
158
+ ```
159
+
160
+ ### Extending Classes
161
+ ```javascript
162
+ /**
163
+ * Advanced validator extending basic Validator.
164
+ * @extends Validator
165
+ */
166
+ class AdvancedValidator extends Validator {
167
+ /**
168
+ * @param {Object} options - Options.
169
+ * @param {number} options.maxLength - Max length.
170
+ */
171
+ constructor(options) {
172
+ super(options);
173
+ this.maxLength = options.maxLength || 255;
174
+ }
175
+
176
+ /**
177
+ * Validates with length check.
178
+ * @param {string} str - The string.
179
+ * @returns {boolean} True if valid.
180
+ * @override
181
+ */
182
+ validateEmail(str) {
183
+ return super.validateEmail(str) && str.length <= this.maxLength;
184
+ }
185
+ }
186
+ ```
187
+
188
+ ## Type Annotations
189
+
190
+ Use types in curly braces `{}` for precision. Define complex types with `@typedef` for reuse.
191
+
192
+ ### Basic Types
193
+ - Primitives: `{string}`, `{number}`, `{boolean}`
194
+ - Arrays: `{string[]}` or `{Array.<string>}`
195
+ - Objects: `{Object}`
196
+ - Unions: `{string|number}`
197
+ - Nullable: `{string?}`
198
+ - Any: `{*}`
199
+ - Promises: `{Promise<string>}`
200
+
201
+ ### Variables and Properties
202
+ ```javascript
203
+ /** @type {string} */
204
+ let message = "Hello";
205
+
206
+ /**
207
+ * User object type.
208
+ * @typedef {Object} User
209
+ * @property {string} name - User name.
210
+ * @property {number} age - User age.
211
+ * @property {string[]} hobbies - User hobbies.
212
+ */
213
+
214
+ /** @type {User} */
215
+ const user = { name: "Alice", age: 30, hobbies: ["reading"] };
216
+ ```
217
+
218
+ ### In Parameters and Returns
219
+ Types are integrated into `@param` and `@returns`:
220
+ ```javascript
221
+ /**
222
+ * Processes a user.
223
+ * @param {User} user - The user object.
224
+ * @returns {User} Processed user.
225
+ */
226
+ function processUser(user) {
227
+ return { ...user, processed: true };
228
+ }
229
+ ```
230
+
231
+ ## Advanced: Typedefs for Complex Types
232
+ For utility libraries, define reusable types:
233
+ ```javascript
234
+ /**
235
+ * Response from API.
236
+ * @typedef {Object} ApiResponse
237
+ * @property {boolean} success - Success flag.
238
+ * @property {any} data - Response data.
239
+ * @property {string} [error] - Error message if failed.
240
+ */
241
+
242
+ /**
243
+ * Fetches API data.
244
+ * @param {string} endpoint - API endpoint.
245
+ * @returns {Promise<ApiResponse>} The API response.
246
+ */
247
+ async function apiFetch(endpoint) {
248
+ // Implementation
249
+ }
250
+ ```
251
+
252
+ ## Best Practices
253
+
254
+ 1. **Consistency**: Use the same style for all docs (e.g., always include types, descriptions).
255
+ 2. **Readability**:
256
+ - Start descriptions with a capital letter and end with a period.
257
+ - Use hyphens for parameter descriptions: `@param {type} name - Description.`
258
+ - Keep comments concise but informative.
259
+ 3. **Completeness**: Document all public APIs; use `@private` or `@internal` for internals.
260
+ 4. **Examples**: Include `@example` blocks for complex usage.
261
+ 5. **Namespaces**: Group related items with `@namespace` and `@memberOf` for large libraries.
262
+ ```javascript
263
+ /**
264
+ * @namespace utils.array
265
+ * Array utility functions.
266
+ */
267
+ ```
268
+ 6. **Error Handling**: Use `@throws` for possible exceptions.
269
+ 7. **Links**: Use `@see` for related items, `@link` for external.
270
+ 8. **IDE Integration**: Test in VS Code or WebStorm for type hints.
271
+ 9. **Generation**: Use JSDoc CLI (`jsdoc yourfile.js`) to generate HTML docs. Configure with `jsdoc.json` for templates like docdash.
272
+ 10. **Maintenance**: Update docs alongside code changes; treat as code.
273
+
274
+ For toolsets/utility libraries, prioritize documenting exports and focus on user-facing APIs to make integration easy.
275
+
276
+ ## References
277
+ - [Official JSDoc Documentation](https://jsdoc.app/)
278
+ - [JSDoc Tags](https://jsdoc.app/tags-*)
@@ -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&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
+ 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**: &quot;123&quot; (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 &quot;hello-dave_code_9000&quot; -- --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 &quot;online&quot; status).
35
+ - Test connection: Use a WebSocket client to connect to `ws://127.0.0.1:9000/ws` with secret &quot;123&quot;.
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 &quot;Create weather predictor agent with prompt: You are a weather prediction agent. Use tools to fetch data.&quot; --connect ws://127.0.0.1:9000/ws --secret 123 --tools web_search,weather_api
49
+ ```
50
+ - This spawns the agent (e.g., named &quot;weatherPredictor&quot; 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 &quot;query&quot; | ./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 &quot;predict weather in NYC&quot; | ./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 &quot;test query&quot; | ./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 &quot;first&quot; | ...` then `echo &quot;follow-up&quot; | ...`
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 &quot;test_code&quot; -- --serve --port 9000 --secret 123
155
+ sleep 2
156
+ echo &quot;Hello cluster!&quot; | ./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: &quot;If running under PM2/CodeServer (detect via args like --serve/--connect or initial `pm2 list` inspect), coordinate with cluster agents.&quot;
166
+
167
+ - **Implementation** (ESM Syntax):
168
+ Agents auto-detect via argument parsing and PM2 inspection:
169
+ ```javascript
170
+ import { execSync } from &apos;child_process&apos;;
171
+ import { process } from &apos;process&apos;; // Built-in
172
+
173
+ const args = process.argv.slice(2);
174
+ const isServeMode = args.includes(&apos;--serve&apos;);
175
+ const isConnectMode = args.includes(&apos;--connect&apos;);
176
+ const pm2Status = execSync(&apos;pm2 list&apos;, { encoding: &apos;utf8&apos; }).includes(&apos;hello-dave_code_9000&apos;);
177
+
178
+ if (isServeMode || isConnectMode || pm2Status) {
179
+ // Cluster mode: Share context, route to other agents
180
+ console.log(&apos;Detected cluster environment&apos;);
181
+ }
182
+ ```
183
+ This enables self-aware routing, e.g., &quot;Delegate weather query to weatherPredictor in cluster.&quot; 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.*