@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,191 @@
1
+ # CodeServer Pattern
2
+
3
+ [![PM2](https://img.shields.io/badge/PM2-Managed-green.svg)](https://pm2.keymetrics.io/) [![WebSocket](https://img.shields.io/badge/WebSocket-Persistent-blue.svg)](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API)
4
+
5
+ ## Table of Contents
6
+
7
+ - [Introduction & Motivation](#introduction--motivation)
8
+ - [Architecture](#architecture)
9
+ - [Prerequisites](#prerequisites)
10
+ - [Step-by-Step Setup](#step-by-step-setup)
11
+ - [Interaction via \`bin/dave.js\`](#interaction-via-bindavejs)
12
+ - [Monitoring & Stopping with PM2](#monitoring--stopping-with-pm2)
13
+ - [Customization](#customization)
14
+ - [Benefits](#benefits)
15
+ - [Troubleshooting](#troubleshooting)
16
+ - [Integration with AgentManager](#integration-with-agentmanager)
17
+ - [References](#references)
18
+
19
+ ## Introduction & Motivation
20
+
21
+ The **CodeServer pattern** demonstrates a production-ready setup for running a **persistent, always-on agent server** managed by [PM2](https://pm2.keymetrics.io/). It launches:
22
+
23
+ - **Main Server**: \`code_agent.js\` as a WebSocket server (code-focused agent with JavaScript tools).
24
+ - **Sub-Agents (Clients)**: Specialized agents (\`todo_agent.js\`, \`readme_agent.js\`, \`npm_agent.js\`, \`docs_agent.js\`) that **attach as tools** to the main server via WebSocket.
25
+
26
+ **Motivation**:
27
+ - **Persistence**: Long-running sessions without restarts (state in \`.cache/hello-dave/[agent]/\`).
28
+ - **Delegation**: Main agent delegates to specialists (e.g., "update docs" → \`docsDave\` tool).
29
+ - **No Heartbeats**: PM2 handles restarts, monitoring—no custom pings.
30
+ - **Scalability**: Easy to add sub-agents, deploy across machines.
31
+ - **CLI-Friendly**: Interact via \`bin/dave.js --connect\`.
32
+
33
+ Ideal for dev workflows: code execution, docs mgmt, npm inspection, todos—all in one persistent hub.
34
+
35
+ See live example: [agents/CodeServer](../agents/CodeServer)
36
+
37
+ ## Architecture
38
+
39
+ ```mermaid
40
+ graph TB
41
+ PM2[PM2 Process Manager] --> Main[Main: code_agent.js<br/>--serve PORT --secret SECRET<br/>WS Server on /ws]
42
+ PM2 --> Todo[todo_agent.js<br/>--connect ws://localhost:PORT/ws<br/>tool: todo_agent]
43
+ PM2 --> Readme[readme_agent.js<br/>--connect ...<br/>tool: readme_agent]
44
+ PM2 --> NPM[npm_agent.js<br/>--connect ...<br/>tool: npm_module_inspector]
45
+ PM2 --> Docs[docs_agent.js<br/>--connect ...<br/>tool: agent_docs]
46
+
47
+ User[bin/dave.js --connect] -.-> Main
48
+ Main -->|Delegates via tools| Todo & Readme & NPM & Docs
49
+ Todo -.->|File ops| ProjectFiles[(TODO.md, etc.)]
50
+ Docs -.->|Docs mgmt| DocsFolder[./docs/*.md]
51
+ ```
52
+
53
+ **Key Flows**:
54
+ 1. PM2 spawns all processes (named \`FOLDER_agent_PORT\`).
55
+ 2. Clients connect to main server → auto-register as **tools** (e.g., \`todo_agent\`, \`readme_agent\`).
56
+ 3. User queries main server → delegates (e.g., \`call todo_agent {add: "new task"}\`).
57
+ 4. Sessions persist independently per agent.
58
+
59
+ ## Prerequisites
60
+
61
+ | Requirement | Install Command | Notes |
62
+ |-------------|-----------------|-------|
63
+ | **Node.js** | `node --version` (≥18) | ESM support required. |
64
+ | **PM2** | `npm i -g pm2` | Process manager. Startup: `pm2 startup`. |
65
+ | **Project** | `git clone <repo> && cd hello-dave` | Examples in \`./agents/\`. |
66
+
67
+ Verify: `pm2 --version` & `node -e "import('@j-o-r/hello-dave')"`
68
+
69
+ ## Step-by-Step Setup
70
+
71
+ 1. **Navigate to project**:
72
+ ```bash
73
+ cd /path/to/hello-dave
74
+ ```
75
+
76
+ 2. **Launch CodeServer** (pick PORT 1024-65535, SECRET ≥3 chars):
77
+ ```bash
78
+ ./agents/CodeServer 8080 mysecret123
79
+ ```
80
+ Output:
81
+ ```
82
+ Starting CodeServer on port 8080 in folder 'hello-dave' ... with SECRET 'mysecret123'
83
+ CodeServer processes spawned with prefix 'hello-dave_' and suffix _8080.
84
+ dave --connect ws://127.0.0.1:8080/ws --secret 'mysecret123'
85
+ ```
86
+
87
+ 3. **Verify PM2**:
88
+ ```bash
89
+ pm2 list | grep 8080
90
+ ```
91
+ | Name | Status | CPU | Memory |
92
+ |-----------------------|--------|-----|--------|
93
+ | hello-dave_code_agent_8080 | online | ... | ... |
94
+ | hello-dave_todo_agent_8080 | online | ... | ... |
95
+ | ... (4 total) | ... | ... | ... |
96
+
97
+ ## Interaction via \`bin/dave.js\`
98
+
99
+ **Interactive**:
100
+ ```bash
101
+ ./bin/dave.js --connect 'ws://localhost:8080/ws' --secret 'mysecret123'
102
+ ```
103
+ - Chat with **code_agent** (main agent).
104
+ - Delegates automatically: "Manage todos", "Inspect @j-o-r/cli", "Update docs/codeserver-pattern.md".
105
+
106
+ **Piped (one-shot)**:
107
+ ```bash
108
+ echo "List pending todos" | ./bin/dave.js --connect 'ws://localhost:8080/ws' --secret 'mysecret123'
109
+ echo "user_reset" | ./bin/dave.js --connect ... # Reset session
110
+ ```
111
+
112
+ **Delegation Examples**:
113
+ - \`code_agent\`: "Use todo_agent to add 'Review PRs'"
114
+ - \`code_agent\`: "Call agent_docs to create nodejs-guide.md"
115
+
116
+ ## Monitoring & Stopping with PM2
117
+
118
+ **Monitor**:
119
+ - `pm2 list` / `pm2 monit` (dashboard)
120
+ - `pm2 logs hello-dave_code_agent_8080` (agent logs)
121
+ - `pm2 logs *8080 --lines 50`
122
+
123
+ **Stop**:
124
+ ```bash
125
+ pm2 stop hello-dave_*_8080 # All related
126
+ # Or delete:
127
+ pm2 delete hello-dave_code_agent_8080 hello-dave_todo_agent_8080 ...
128
+ ```
129
+
130
+ **Startup** (auto-restart on boot): `pm2 save && pm2 startup`
131
+
132
+ ## Customization
133
+
134
+ ### Adding Sub-Agents
135
+ Edit [agents/CodeServer](../agents/CodeServer):
136
+ ```bash
137
+ # Add new agent
138
+ pm2 start "${SCRIPT_DIR}/newAgent.js" --name "${FOLDER}_new_agent_${PORT}" -- --connect "ws://127.0.0.1:${PORT}/ws" --secret "${SECRET}"
139
+ ```
140
+ - Create \`newAgent.js\` like [agents/todo_agent.js](../agents/todo_agent.js): Set \`tool_call_name\`, prompt.
141
+
142
+ ### Changing Tools
143
+ - Main server: Edit \`code_agent.js\`: \`--tools javascript,bash,ssh\`
144
+ - Sub-agents: \`agent.addGenericToolcall('read_file')\` etc. See [toolset.md](../toolset.md).
145
+
146
+ ### Prompts/Models
147
+ - Per-agent: Edit JS files (e.g., \`options.model = 'grok-4-1-fast-reasoning'\`).
148
+
149
+ ## Benefits
150
+
151
+ | Feature | Advantage |
152
+ |---------|-----------|
153
+ | **Persistent Sessions** | State in \`.cache/hello-dave/[name]/sessions/\`—no re-explaining. |
154
+ | **Delegation** | Main agent uses sub-agents as tools (parallel, specialized). |
155
+ | **No Heartbeat** | PM2 restarts on crash; no custom logic. |
156
+ | **Resource Efficient** | Shared context; subs only active on call. |
157
+ | **Portable** | Script auto-prefixes PM2 names by folder/port. |
158
+
159
+ ## Troubleshooting
160
+
161
+ | Issue | Solution |
162
+ |-------|----------|
163
+ | **Port in use** | Change PORT; `lsof -i :8080` & `kill`. |
164
+ | **Secret mismatch** | Ensure exact match (no extra spaces). |
165
+ | **PM2 not found** | `npm i -g pm2`. |
166
+ | **Connection refused** | Wait 5s for server startup; check `pm2 logs`. |
167
+ | **No delegation** | Verify client tool names in JS (e.g., \`todo_agent\`). |
168
+ | **High memory** | `pm2 del *` or tweak \`contextWindow\`. |
169
+
170
+ Logs: `.cache/hello-dave/[agent]/sessions/*.ndjson` (use \`bin/dave.js --inspect log.ndjson\`).
171
+
172
+ ## Integration with AgentManager
173
+
174
+ Built on [AgentManager](../docs/agent-manager.md):
175
+
176
+ - **Server**: `agent.start(PORT)` → WS server exposing \`code_agent\`.
177
+ - **Clients**: `agent.start(undefined, 'ws://...', undefined, 'todo_agent', 'desc')` → Attaches as tool.
178
+
179
+ **Tools**: Generic from [toolset.md](../docs/toolset.md) (e.g., \`execute_bash_script\`, \`javascript_interpreter\`).
180
+
181
+ Cross-links:
182
+ - [Prompt Class](../docs/prompt-class.md)
183
+ - [Generic Tools](../lib/genericToolset.js)
184
+
185
+ ## References
186
+
187
+ - [PM2 Docs](https://pm2.keymetrics.io/docs/usage/quick-start/)
188
+ - Examples: [CodeServer](../agents/CodeServer), [code_agent.js](../agents/code_agent.js), [todo_agent.js](../agents/todo_agent.js), etc.
189
+ - Sessions: \`bin/dave.js --list\`
190
+
191
+ **Updated**: March 24, 2026
@@ -0,0 +1,326 @@
1
+ # Generic Toolset Module (lib/genericToolset.js)
2
+
3
+ ## Overview
4
+
5
+ The `genericToolset.js` module provides a pre-built collection of 11 utility tools designed for integration with the `ToolSet` class from the hello-dave library. These tools handle common operations like code execution, file I/O, system interactions, and memory management. They are exported as `toolsPool`, an object mapping tool names to `TSTool` objects (containing description, parameters schema, and execution method).
6
+
7
+ This module is ideal for toolsets or utility libraries, enabling agents to perform real-world tasks without custom implementations. Tools follow OpenAI-style JSON Schema for parameters and support asynchronous execution.
8
+
9
+ **Key Benefits**:
10
+ - **Ready-to-Use**: Load into any `ToolSet` instance for immediate functionality.
11
+ - **Secure & Sandboxed**: Tools operate in controlled environments (e.g., specific CWD, no escaping in Bash).
12
+ - **Persistent State**: Memory tools allow offloading state from LLM context for efficiency.
13
+ - **Documentation**: Each tool includes JSDoc annotations for IDE support and generated docs.
14
+
15
+ To generate full JSDoc for this module (and the library):
16
+ 1. Install JSDoc: `npm install -g jsdoc`
17
+ 2. Run: `jsdoc lib/genericToolset.js -d docs/jsdoc/generic-toolset`
18
+ 3. View HTML docs in `docs/jsdoc/generic-toolset/index.html`.
19
+
20
+ See [ToolSet Documentation](../toolset.md) for integration details.
21
+
22
+ ## Exports
23
+
24
+ - **`toolsPool`**: `{ [name: string]: TSTool }` – Object with 11 pre-defined tools.
25
+ - `TSTool`: `{ description: string, parameters: TSSchema, method: async (params: object) => any }`
26
+ - `TSSchema`: JSON Schema object (e.g., `{ type: "object", properties: {...}, required: [...] }`).
27
+
28
+ No default export; use named import: `import { toolsPool } from "@j-o-r/hello-dave/lib/genericToolset.js";`
29
+
30
+ ## Usage Examples
31
+
32
+ ### Basic Import and Population of ToolSet
33
+ ```javascript
34
+ import { ToolSet } from "@j-o-r/hello-dave";
35
+ import { toolsPool } from "@j-o-r/hello-dave/lib/genericToolset.js";
36
+
37
+ const toolset = new ToolSet("auto"); // Or "required" for empty start
38
+
39
+ // Add all generic tools
40
+ Object.entries(toolsPool).forEach(([name, tool]) => {
41
+ toolset.add(name, tool.description, tool.parameters, tool.method);
42
+ });
43
+
44
+ // Or selectively
45
+ toolset.add("memory_recall", toolsPool.memory_recall.description, toolsPool.memory_recall.parameters, toolsPool.memory_recall.method);
46
+
47
+ // List available tools
48
+ console.log(toolset.list());
49
+ ```
50
+
51
+ ### Integration with AgentManager
52
+ ```javascript
53
+ import { AgentManager } from "@j-o-r/hello-dave";
54
+
55
+ const agent = new AgentManager("my-agent");
56
+ agent.setup({
57
+ toolsetMode: "auto" // Automatically loads all tools from toolsPool
58
+ });
59
+
60
+ // Add specific tools post-setup
61
+ agent.addGenericToolcall("execute_bash_script");
62
+ agent.addGenericToolcall("memory_write");
63
+ ```
64
+
65
+ ### Example: Using Memory Tools in a Prompt Workflow
66
+ ```javascript
67
+ import { Prompt } from "@j-o-r/hello-dave";
68
+ import { toolsPool } from "@j-o-r/hello-dave/lib/genericToolset.js";
69
+
70
+ const prompt = new Prompt("You are a task manager. Use memory tools to track progress.");
71
+ const toolset = new ToolSet("required");
72
+ toolset.add("memory_write", ...toolsPool.memory_write); // Spread for destructuring
73
+
74
+ // In agent loop: prompt.addMessage("Start new task: Implement login.");
75
+ await toolset.execute(prompt); // LLM may call tools based on prompt
76
+ ```
77
+
78
+ ## Key Tools
79
+
80
+ Below is a list of the 11 tools in `toolsPool`, with descriptions, parameter schemas, and usage examples. For full JSDoc details, generate docs as noted above.
81
+
82
+ ### 1. `javascript_interpreter`
83
+ **Description**: Execute ESM ES6 JavaScript in a Node.js environment. Captures `console.log` output. CWD: `~/devpri/js/hello-dave`.
84
+
85
+ **Parameters Schema**:
86
+ ```json
87
+ {
88
+ "type": "object",
89
+ "properties": {
90
+ "code": { "type": "string", "description": "JavaScript code to execute" }
91
+ },
92
+ "required": ["code"]
93
+ }
94
+ ```
95
+
96
+ **Usage Example**:
97
+ ```javascript
98
+ await toolset.call("javascript_interpreter", { code: "console.log(2 + 2);" });
99
+ // Returns: { output: "4\n", error: null }
100
+ ```
101
+
102
+ ### 2. `get_user_env`
103
+ **Description**: Retrieve user environment details (name, system info, location, IP).
104
+
105
+ **Parameters Schema**:
106
+ ```json
107
+ {
108
+ "type": "object",
109
+ "properties": {},
110
+ "required": []
111
+ }
112
+ ```
113
+
114
+ **Usage Example**:
115
+ ```javascript
116
+ await toolset.call("get_user_env", {});
117
+ // Returns: { name: "User", system: "Ubuntu 25.10", city: "Example City", ... }
118
+ ```
119
+
120
+ ### 3. `execute_bash_script`
121
+ **Description**: Run raw Bash scripts/commands verbatim (no escaping). Supports Ubuntu 25.10 environment.
122
+
123
+ **Parameters Schema**:
124
+ ```json
125
+ {
126
+ "type": "object",
127
+ "properties": {
128
+ "bash_script": { "type": "string", "description": "Raw Bash script (literal text)" }
129
+ },
130
+ "required": ["bash_script"]
131
+ }
132
+ ```
133
+
134
+ **Usage Example**:
135
+ ```javascript
136
+ await toolset.call("execute_bash_script", { bash_script: "ls -la" });
137
+ // Returns: { stdout: "...", stderr: "", exitCode: 0 }
138
+ ```
139
+
140
+ ### 4. `send_email`
141
+ **Description**: Send email using `msmtp` (to, subject, body).
142
+
143
+ **Parameters Schema**:
144
+ ```json
145
+ {
146
+ "type": "object",
147
+ "properties": {
148
+ "to": { "type": "string" },
149
+ "subject": { "type": "string" },
150
+ "body": { "type": "string" }
151
+ },
152
+ "required": ["to", "subject", "body"]
153
+ }
154
+ ```
155
+
156
+ **Usage Example**:
157
+ ```javascript
158
+ await toolset.call("send_email", { to: "user@example.com", subject: "Hello", body: "Test" });
159
+ // Returns: { success: true }
160
+ ```
161
+
162
+ ### 5. `open_link`
163
+ **Description**: Open URL or file using `xdg-open`.
164
+
165
+ **Parameters Schema**:
166
+ ```json
167
+ {
168
+ "type": "object",
169
+ "properties": {
170
+ "url": { "type": "string", "description": "URL or file path" }
171
+ },
172
+ "required": ["url"]
173
+ }
174
+ ```
175
+
176
+ **Usage Example**:
177
+ ```javascript
178
+ await toolset.call("open_link", { url: "https://example.com" });
179
+ // Returns: { opened: true }
180
+ ```
181
+
182
+ ### 6. `execute_remote_script`
183
+ **Description**: Execute Bash script on remote server via SSH (`ssh://user@host[:port]`).
184
+
185
+ **Parameters Schema**:
186
+ ```json
187
+ {
188
+ "type": "object",
189
+ "properties": {
190
+ "remote": { "type": "string", "description": "SSH URL" },
191
+ "script": { "type": "string", "description": "Bash script" }
192
+ },
193
+ "required": ["remote", "script"]
194
+ }
195
+ ```
196
+
197
+ **Usage Example**:
198
+ ```javascript
199
+ await toolset.call("execute_remote_script", { remote: "ssh://user@host", script: "whoami" });
200
+ // Returns: { stdout: "user\n", ... }
201
+ ```
202
+
203
+ ### 7. `history_search`
204
+ **Description**: Search chat history sessions using regex (e.g., in `.cache/[app]/[prompt]/sessions/*.ndjson`).
205
+
206
+ **Parameters Schema**:
207
+ ```json
208
+ {
209
+ "type": "object",
210
+ "properties": {
211
+ "query": { "type": "string", "description": "Regex query" }
212
+ },
213
+ "required": ["query"]
214
+ }
215
+ ```
216
+
217
+ **Usage Example**:
218
+ ```javascript
219
+ await toolset.call("history_search", { query: package.json });
220
+ // Returns: [{ session: "path", matches: [...] }, ...]
221
+ ```
222
+
223
+ ### 8. `read_file`
224
+ **Description**: Read file content from CWD (relative path, no absolute/parent traversal).
225
+
226
+ **Parameters Schema**:
227
+ ```json
228
+ {
229
+ "type": "object",
230
+ "properties": {
231
+ "path": { "type": "string", "description": "Relative file path" }
232
+ },
233
+ "required": ["path"]
234
+ }
235
+ ```
236
+
237
+ **Usage Example**:
238
+ ```javascript
239
+ await toolset.call("read_file", { path: "example.txt" });
240
+ // Returns: { content: "File text\n", encoding: "utf8" }
241
+ ```
242
+
243
+ ### 9. `write_file`
244
+ **Description**: Write raw content to file in CWD (relative path). Returns bytes written.
245
+
246
+ **Parameters Schema**:
247
+ ```json
248
+ {
249
+ "type": "object",
250
+ "properties": {
251
+ "path": { "type": "string" },
252
+ "content": { "type": "string" }
253
+ },
254
+ "required": ["path", "content"]
255
+ }
256
+ ```
257
+
258
+ **Usage Example**:
259
+ ```javascript
260
+ await toolset.call("write_file", { path: "output.txt", content: "Hello World" });
261
+ // Returns: { bytesWritten: 11 }
262
+ ```
263
+
264
+ ### 10. `memory_recall`
265
+ **Description**: Recall latest values for keys from agent-specific memory (`.cache/[agent]/memory.ndjson`).
266
+
267
+ **Parameters Schema**:
268
+ ```json
269
+ {
270
+ "type": "object",
271
+ "properties": {
272
+ "keys": {
273
+ "type": "array",
274
+ "items": { "type": "string" },
275
+ "description": "List of keys to recall"
276
+ }
277
+ },
278
+ "required": ["keys"]
279
+ }
280
+ ```
281
+
282
+ **Usage Example**:
283
+ ```javascript
284
+ await toolset.call("memory_recall", { keys: ["current_task"] });
285
+ // Returns: { current_task: "Implement login" } or {}
286
+ ```
287
+
288
+ ### 11. `memory_write`
289
+ **Description**: Append/update key-value pairs in agent memory (overwrites same keys).
290
+
291
+ **Parameters Schema**:
292
+ ```json
293
+ {
294
+ "type": "object",
295
+ "properties": {
296
+ "entries": {
297
+ "type": "array",
298
+ "items": {
299
+ "type": "object",
300
+ "properties": {
301
+ "key": { "type": "string" },
302
+ "value": { "type": "string" }
303
+ },
304
+ "required": ["key", "value"]
305
+ }
306
+ }
307
+ },
308
+ "required": ["entries"]
309
+ }
310
+ ```
311
+
312
+ **Usage Example**:
313
+ ```javascript
314
+ await toolset.call("memory_write", { entries: [{ key: "step", value: "1/5" }] });
315
+ // Returns: { stored: [{ key: "step", value: "1/5" }] }
316
+ ```
317
+
318
+ ## Best Practices
319
+ - **Security**: Tools like `execute_bash_script` and `write_file` are powerful; use in trusted environments.
320
+ - **Error Handling**: Methods return `{ success: boolean, error?: string, data: any }` for robustness.
321
+ - **Customization**: Extend `toolsPool` by adding your own tools before populating `ToolSet`.
322
+ - **JSDoc Integration**: Annotations include `@param`, `@returns`, `@example` for full type safety in editors like VS Code.
323
+
324
+ For syntax validation in tools (e.g., JS in `write_file`), see [Tools Syntax Validation](../tools-syntax-validation.md). For path handling, see [Path Resolution Best Practices](../path-resolution-best-practices.md).
325
+
326
+ **Updated**: April 10, 2026