@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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  ## Changelog
2
2
 
3
+ ### v0.0.8 (Released - April 15, 2026)
4
+ - **lib/genericToolset.js Timeout Refinements**: Switched `execute_bash_script` to @j-o-r/sh `.options({timeout: ms}).run()` with heredoc delimiter for verbatim multi-line bash_script safety. Default 360s (resets on stdout/stderr output for true idle detection only), SIGTERM on expiry. `execute_remote_script` stdin pipe preserved. Tests: success, sleep timeout (3s<7s), exit1 error, interactive `read -p` no hang.
5
+ - **TODO.md Cleanup**: Archived all completed tasks (timeout refinements, prior v0.0.7 carryovers) to `docs/todo-archive-v0.0.8.md`. Pending changelog task completed here. Clean post-release state.
6
+ - **.npmignore & package-lock.json**: Minor updates for cleaner packaging.
7
+ - **Release Prep**: `package.json` bumped to v0.0.8. `npm run release` ready (types + pack to `./release/`).
8
+
3
9
  ### v0.0.7 (Released - April 13, 2026)
4
10
  - **spawn_agent Enhancements**: Strict blueprint enforcement in `docs/prompt/spawn_agent.md` (mandatory tool sequence: INSPECT → VALIDATE → GATHER → GENERATE → AUTO-DEPLOY/TEST). Fixed one-shot hallucination/no-deploy via verbatim AGENT BLUEPRINT TEMPLATE, temp_agent.js validation (syntax/blueprint checks), PROJECT auto-deploy (write/mv/chmod/test/rm), FRESH manual code/bash. Robust fetchLivePrompt() (live MD full-load + fallbacks). CodeServer/PM2 awareness (LAUNCH_MODE detect, client connect hints). Tested 2026-04-13: /tmp FRESH, PROJECT diag_agent.js deploy+--help success.
5
11
  - **JSDoc Updates (lib/ modules)**: Comprehensive JSDoc added/fixed for AgentClient.js, AgentManager.js, AgentServer.js, Cli.js, Prompt.js, Session.js, ToolSet.js, fafs.js, genericToolset.js, wsCli.js, wsIO.js. Typedefs, @returns, @private tags. Note: Some parser warnings (HTML entities &lt; → &lt;, import() expr); HTML generated in docs/jsdoc/.
package/TODO.md ADDED
@@ -0,0 +1,24 @@
1
+ ## TODO (high priority pending)
2
+ - [ ] Create a personal CDN on VPS using SSH + Nginx to serve static assets (images, HTML, JS) so that Grok / browse_page tools can directly access them without crawling or conversion issues
3
+ - [ ] Subtask: Set up VPS and SSH access
4
+ - [ ] Subtask: Install and configure Nginx for static file serving
5
+ - [ ] Subtask: Implement security measures (e.g., firewall, SSL/TLS, access controls)
6
+ - [ ] Subtask: Upload and organize static assets
7
+ - [ ] Subtask: Test with previous image test case and verify direct access via tools
8
+ - [ ] Create publish_agent.js in agents/ for secure deployment of documents to remote VPS (Nginx + ~/htdocs or /var/www/htdocs). Features: persistent config for multiple VPS (SSH host, port, user, htdocs path, http base URL), ask for missing endpoints on first use, generate long/obscure/randomized filenames for privacy (especially sensitive files), clean old/unused files in htdocs, rsync or scp with safety, support for static publishing of docs/markdown/html. Integrate with memory_agent for config persistence if possible. High privacy focus.
9
+
10
+ ## In Progress
11
+ (none)
12
+
13
+ ## Later (future tasks)
14
+ (none)
15
+
16
+ ## Done
17
+ - [x] Document and review the "agent dave websocket protocol". Focus on communication between lib/AgentServer.js (central hub), lib/AgentClient.js (agent connections), and lib/wsIO.js (user interaction). Include description of the protocol, sequence diagrams if possible, and optimization suggestions.
18
+ - [x] Subtask: Review and analyze source files (AgentServer.js, AgentClient.js, wsIO.js)
19
+ - [x] Subtask: Summarize findings from review - Protocol uses JSON messages with 'action' from fixed ACTIONS list, bidirectional query/response with IDs for matching, introduction for registration, user_* for CLI/WS interaction, reset handling with epoch, pending response map with timeout. Suggestion: Add sequence diagram in Mermaid and document in docs/agent-dave-websocket-protocol.md.
20
+ - [x] Subtask: Document the protocol structure and message formats
21
+ - [x] Subtask: Create sequence diagrams for key interactions (Mermaid diagrams added to the new docs file)
22
+ - [x] Subtask: Identify and suggest optimizations for performance and reliability (detailed section added with 6 categories of improvements)
23
+
24
+ Older tasks archived on 2026-04-20 to docs/todo-archive-v0.0.9.md. Previous archives: docs/todo-archive-v0.0.8.md (2026-04-15), docs/todo-archive.md (2026-04-13).
@@ -24,7 +24,7 @@ if (args['secret']) {
24
24
  // Set properties only if provided via command line (except model which has default)
25
25
  if (args['model'] || true) { // model gets default value
26
26
  // @ts-ignore
27
- options.model = args['model'] || 'grok-4-1-fast-reasoning';
27
+ options.model = args['model'] || 'grok-4.20-reasoning';
28
28
  }
29
29
  // if (args['temperature']) {
30
30
  options.temperature = 0.2;
@@ -35,14 +35,14 @@ if (args['tokens']) {
35
35
  if (args['top_p']) {
36
36
  options.top_p = parseFloat(args['top_p']);
37
37
  }
38
- const reasoning = args['reasoning'] ? args['reasoning'] : 'medium';
39
- if (reasoning) {
40
- options.reasoning = {
41
- // @ts-ignore
42
- effort:reasoning,
43
- summary: 'auto'
44
- }
45
- }
38
+ // const reasoning = args['reasoning'] ? args['reasoning'] : 'medium';
39
+ // if (reasoning) {
40
+ // options.reasoning = {
41
+ // // @ts-ignore
42
+ // effort:reasoning,
43
+ // summary: 'auto'
44
+ // }
45
+ // }
46
46
  const toolsetMode = 'auto';
47
47
  const contextWindow = args['context'] ? parseInt(args['context']) : 2565000;
48
48
 
package/bin/dave.js CHANGED
@@ -118,9 +118,9 @@ if (args.clear) {
118
118
  };
119
119
  options.tools.push({ type: 'web_search' });
120
120
  options.tools.push({ type: 'x_search' });
121
- options.model = args.model || 'grok-4-1-fast-reasoning';
121
+ options.model = args.model || 'grok-4.20-reasoning';
122
122
  options.temperature = 0.2;
123
- options.reasoning = { effort: 'medium', summary: 'auto' };
123
+ // options.reasoning = { effort: 'medium', summary: 'auto' };
124
124
 
125
125
  const prompt = `
126
126
  Respond briefly and directly, using minimal words. Reason step-by-step first. Focus solely on core point; avoid elaboration or follow-ups. If unclear, ask clarifying questions before proceeding.
@@ -0,0 +1,180 @@
1
+ # Agent Dave WebSocket Protocol
2
+
3
+ **Version**: 0.0.8 (as of April 2026)
4
+ **Repository**: https://codeberg.org/duin/hello-dave
5
+ **Core Files**:
6
+ - `lib/AgentServer.js` — Central hub, registers agents as dynamic tools, handles user interactions and sessions.
7
+ - `lib/AgentClient.js` — Agent-side wrapper (Prompt + ToolSet), queue-based message processor, auto-reconnect, epoch-based reset handling.
8
+ - `lib/wsIO.js` — One-shot WS client for CLI tools (`dave --connect`, `wsio()` helper).
9
+
10
+ ## Overview
11
+
12
+ The protocol enables **multi-agent collaboration** over WebSocket.
13
+
14
+ - A central **AgentServer** listens on `ws://127.0.0.1:<port>/ws`.
15
+ - **AgentClient** instances connect, introduce themselves, and get registered as **dynamic tools** in the server's `ToolSet`.
16
+ - The server exposes these agents to the main Prompt, allowing the LLM to call them like any other tool (`agent_query` / `agent_response`).
17
+ - **User/CLI interaction** uses `user_*` actions (via `wsIO.js` or `dave` CLI).
18
+ - All messages are **JSON** objects with an `action` field validated against a fixed list.
19
+ - **Authentication**: `?wssrc_id=<secret>` query param (plain in AgentServer, base64 in wsIO.js).
20
+ - **Reset handling**: Broadcast `reset`, clients use an `#epoch` counter to invalidate in-flight work.
21
+ - **Response matching**: Uses `id` (timestamp-based) + pending map on server.
22
+
23
+ This design turns specialized agents (code, todo, memory, readme, etc.) into callable tools while supporting direct CLI, interactive REPL, and one-shot queries.
24
+
25
+ ## Message Format
26
+
27
+ Every message is a JSON object:
28
+
29
+ ```json
30
+ {
31
+ "action": "one_of_the_actions_below",
32
+ "content": "string or object (varies)",
33
+ "id": "unique_timestamp_string_or_number",
34
+ "name"?: "agent_name_on_introduction"
35
+ }
36
+ ```
37
+
38
+ ### Supported Actions (ACTIONS array in AgentServer.js)
39
+
40
+ **Agent ↔ Server (Tool Calls)**
41
+ - `agent_introduction` — Agent registers itself (sends `name` + `description`).
42
+ - `agent_query` — Server calls an agent tool with natural language `content` (query).
43
+ - `agent_response` — Agent returns result.
44
+ - `agent_error` — Agent reports failure.
45
+
46
+ **User/CLI ↔ Server**
47
+ - `user_introduction` — CLI connects (sent by wsIO.js).
48
+ - `user_request` — User query to main prompt.
49
+ - `server_response` — Final answer from main prompt.
50
+ - `server_error` — Error from main prompt.
51
+ - `user_reset` — Reset current session.
52
+ - `user_sessionlist` — Request list of saved sessions.
53
+ - `user_loadsession` — Load a previous session.
54
+ - `user_info` — Get server/prompt/session info.
55
+
56
+ **Server → Clients (broadcasts/responses)**
57
+ - `reset` — Broadcast to all agents on reset.
58
+ - `server_reset`, `server_sessionlist`, `server_sessionloaded`, `server_info` — Responses to user actions.
59
+
60
+ Unknown actions cause immediate client disconnection.
61
+
62
+ ## Key Interactions & Sequence Diagrams
63
+
64
+ ### 1. Agent Registration & Tool Call
65
+
66
+ ```mermaid
67
+ sequenceDiagram
68
+ participant AgentClient
69
+ participant AgentServer
70
+ participant Prompt/ToolSet
71
+
72
+ AgentClient->>AgentServer: WS connect + ?wssrc_id=secret
73
+ AgentClient->>AgentServer: {action: "agent_introduction", name: "code", content: "Code execution agent..."}
74
+ AgentServer->>ToolSet: add("code", description, schema, handler)
75
+ Note over ToolSet,AgentServer: Tool now available to LLM
76
+
77
+ Prompt->>ToolSet: LLM decides to call "code" with query
78
+ ToolSet->>AgentServer: handler(query) → Promise
79
+ AgentServer->>AgentClient: {action: "agent_query", id: "1745...", content: "Write a bash script..."}
80
+ AgentClient->>AgentClient: #queue.push(), #processOne()
81
+ AgentClient->>Prompt: prompt.call(query)
82
+ AgentClient->>AgentServer: {action: "agent_response", id: "1745...", content: "```bash ...```"}
83
+ AgentServer->>Prompt: resolve(promise)
84
+ Prompt->>LLM: Continue with tool result
85
+ ```
86
+
87
+ ### 2. User One-Shot Query (via wsIO.js or dave --connect)
88
+
89
+ ```mermaid
90
+ sequenceDiagram
91
+ participant CLI (wsIO)
92
+ participant AgentServer
93
+ participant Prompt
94
+
95
+ CLI->>AgentServer: WS connect + wssrc_id
96
+ CLI->>AgentServer: {action: "user_introduction", id: X}
97
+ CLI->>AgentServer: {action: "user_request", id: Y, content: "Hello Dave"}
98
+ AgentServer->>Prompt: prompt.call("Hello Dave")
99
+ Prompt->>LLM: Full reasoning + tool calls (may call registered agents)
100
+ Prompt-->>AgentServer: Final content
101
+ AgentServer->>CLI: {action: "server_response", id: Y, content: "..."}
102
+ CLI->>CLI: resolve promise, close WS
103
+ ```
104
+
105
+ ### 3. Reset Handling
106
+
107
+ ```mermaid
108
+ sequenceDiagram
109
+ participant User
110
+ participant AgentServer
111
+ participant AgentClient
112
+
113
+ User->>AgentServer: {action: "user_reset"}
114
+ AgentServer->>Prompt: prompt.reset()
115
+ AgentServer-->>All Agents: broadcast {action: "reset"}
116
+ AgentClient->>AgentClient: #epoch++, #queue=[], prompt.reset()
117
+ ```
118
+
119
+ ## Implementation Details
120
+
121
+ - **Server-side pending responses**: `pendingResponses` Map keyed by `${conn.id}:${msg.id}` with timeout via `setInterval` (30s intervals, max 20 → 10min).
122
+ - **Client-side queue**: Strict sequential processing (`#processing` guard, 2s polling interval by default). Prevents race conditions in tool calls.
123
+ - **Auto-reconnect**: AgentClient retries every 5s on close.
124
+ - **Session Management**: Integrated with `Session.js` for `user_sessionlist` / `user_loadsession`.
125
+ - **wsIO.js specifics**: Sends both `user_introduction` + action in one connection, matches response by `id`, then closes. Uses base64 secret.
126
+
127
+ ## Optimizations & Suggestions
128
+
129
+ **Current Strengths**
130
+ - Simple JSON, no complex framing.
131
+ - Epoch prevents stale responses after reset.
132
+ - Dynamic tool registration — agents can be added at runtime.
133
+
134
+ **Potential Improvements**
135
+ 1. **Performance**:
136
+ - Replace polling interval in AgentClient with event-driven queue (e.g. `setImmediate` or microtask after each message).
137
+ - Use a proper request-response correlation library or WebSocket subprotocol.
138
+ - Add backpressure handling for high-volume tool calls.
139
+
140
+ 2. **Reliability**:
141
+ - Heartbeat/ping-pong to detect dead connections faster than timeout.
142
+ - Exponential backoff on reconnect.
143
+ - Persistent message IDs (UUID instead of timestamp).
144
+ - Schema validation for all incoming messages (e.g. Zod or JSON Schema).
145
+
146
+ 3. **Observability**:
147
+ - Add structured logging (instead of console.log).
148
+ - Metrics: active clients, avg response time, error rate.
149
+ - OpenTelemetry or Prometheus integration.
150
+
151
+ 4. **Security**:
152
+ - Current secret is weak (query param). Consider JWT or mTLS for production.
153
+ - Rate limiting per connection.
154
+ - Validate `content` size.
155
+
156
+ 5. **Extensibility**:
157
+ - Support binary messages for large data (e.g. images, files).
158
+ - Add `agent_stream` for streaming responses from agents.
159
+ - Formalize as a subprotocol (`Sec-WebSocket-Protocol: agent-dave-v1`).
160
+
161
+ 6. **Documentation**:
162
+ - Generate Mermaid diagrams automatically from code comments.
163
+ - Add protocol test suite in `scenarios/`.
164
+
165
+ **Next Steps** (from TODO):
166
+ - Complete sequence diagrams (expand the Mermaid examples above).
167
+ - Identify specific performance bottlenecks via profiling.
168
+ - Create formal spec with error codes and versioning.
169
+
170
+ ## References
171
+
172
+ - `lib/AgentServer.js`
173
+ - `lib/AgentClient.js`
174
+ - `lib/wsIO.js`
175
+ - `agents/spawn_agent.js` (uses this protocol for hybrid/server/client modes)
176
+ - `docs/multi-agent-clusters.md`
177
+ - `docs/prompt/spawn_agent.md`
178
+
179
+ *Last updated: April 20, 2026*
180
+ *This document was generated as part of the TODO task "Document and review the 'agent dave websocket protocol'."*
@@ -0,0 +1,244 @@
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(); // Interactive CLI mode
54
+ // Or: await agent.directCall('Write a Bash script'); // One-shot (pair with readIn for piped CLI)
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&lt;string&gt;\` | One-shot query (via \`prompt.call()\`). **Ideal for piped CLI scripts & cron jobs.** |
83
+ | \`getPrompt()\` | - | \`Prompt\` | Access internal \`Prompt\`. |
84
+ | \`getToolset()\` | - | \`ToolSet\\|void\` | Access tools. |
85
+ | \`environment()\` | - | \`Promise&lt;EnvironmentInfo&gt;\` | 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&lt;void&gt;\` | **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: **Interactive 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
+ - **Interactive CLI**: \`start()\` → chat loop until Ctrl+C.
105
+ - **One-Shot Piped CLI**: Custom script w/ \`readIn()\` + \`directCall()\` (stdin detection; exits after 1 response). No loop.
106
+ - **WS Server**: \`start(port)\` → \`AgentServer\` (localhost only). Exposes agent as tool (name/desc). \`secret\` required for clients. \`prompt.on('reset')\` → \`server.resetAll()\`.
107
+ - **WS Client**: \`start(undefined, url)\` → \`AgentClient\`. Connects to remote server; agent callable as tool.
108
+ - **Direct**: \`directCall()\` bypasses networking/CLI.
109
+
110
+ ## Examples
111
+
112
+ ### 1. Interactive CLI Agent
113
+ \`\`\`javascript
114
+ import { AgentManager } from '@j-o-r/hello-dave';
115
+
116
+ const agent = new AgentManager({ name: 'chatbot' });
117
+ agent.setup({
118
+ prompt: 'You are a friendly chatbot.',
119
+ api: 'xai',
120
+ toolsetMode: 'auto'
121
+ });
122
+ await agent.start('Chatbot ready!'); // Interactive chat loop
123
+ \`\`\`
124
+
125
+ ### 2. WS Server (Expose as Tool)
126
+ \`\`\`javascript
127
+ import { AgentManager } from '@j-o-r/hello-dave';
128
+
129
+ agent.setup({ ... });
130
+ await agent.start(8000, undefined, undefined, 'weathertool', 'Get real-time weather');
131
+ \`\`\`
132
+ - Clients: \`npx @j-o-r/hello-dave dave --connect ws://localhost:8000/ws --secret mysecret\`
133
+
134
+ ### 3. Hybrid + Direct Call
135
+ \`\`\`javascript
136
+ import { AgentManager } from '@j-o-r/hello-dave';
137
+
138
+ await agent.start(8001, 'ws://other:8000/ws'); // Server on 8001 + client to other
139
+ const resp = await agent.directCall('Hybrid query'); // Uses attached tools too
140
+ \`\`\`
141
+
142
+ ### 4. Custom Tools + Generics
143
+ \`\`\`javascript
144
+ import { AgentManager } from '@j-o-r/hello-dave';
145
+
146
+ agent.setup({ toolsetMode: 'required' });
147
+ const ts = agent.getToolset();
148
+ ts.add('custommath', 'Add numbers', {
149
+ type: 'object', properties: {a: {type: 'number'}, b: {type: 'number'}},
150
+ required: ['a', 'b']
151
+ }, async ({a, b}) => a + b);
152
+ agent.addGenericToolcall('javascript_interpreter');
153
+ \`\`\`
154
+
155
+ ### 5. CLI One-Shot Piped Usage (Scripts/Cron)
156
+ Uses \`@j-o-r/sh\` (\`readIn()\`, \`parseArgs()\`) + \`AgentManager.directCall()\` for fast, single-turn queries from stdin. **Detects piped input vs interactive** (empty stdin → help). Ideal for bash pipelines, cron jobs, automation.
157
+
158
+ **Boilerplate Snippet** (see \`agents/grok_agent.js\`, \`agents/docs_agent.js\` etc.):
159
+ \`\`\`javascript
160
+ #!/usr/bin/env node
161
+ import { AgentManager } from '@j-o-r/hello-dave';
162
+ import { parseArgs, readIn } from '@j-o-r/sh';
163
+
164
+ const name = 'grok_agent'; // Matches naming rules
165
+ const api = 'xai';
166
+ const secret = process.env.SECRET || '';
167
+
168
+ const input = await readIn();
169
+ const args = parseArgs();
170
+ if (args.help || !input?.trim()) {
171
+ console.log(\`
172
+ Usage: echo "query" | \${name}.js [--model grok-4] [--temperature 0.7]
173
+
174
+ Options:
175
+ --model [str] e.g., 'grok-4', 'grok-beta'
176
+ --temperature [float] 0.0 - 2.0
177
+ --tokens [int] Max output tokens
178
+ --top_p [float]
179
+ --context [int] Context window (default: 1.9M)
180
+ \`);
181
+ process.exit(0);
182
+ }
183
+
184
+ const options = {
185
+ tools: [{type: 'web_search'}, {type: 'x_search'}],
186
+ model: args.model || 'grok-4.20-multi-agent-0309',
187
+ temperature: args.temperature ? parseFloat(args.temperature) : undefined,
188
+ max_output_tokens: args.tokens ? parseInt(args.tokens) : undefined,
189
+ top_p: args.top_p ? parseFloat(args.top_p) : undefined,
190
+ reasoning: { effort: 'medium', summary: 'auto' }
191
+ };
192
+
193
+ const agent = new AgentManager({ name, secret });
194
+ agent.setup({
195
+ prompt: 'Respond briefly and directly. Reason step-by-step first.',
196
+ api,
197
+ options,
198
+ toolsetMode: 'auto',
199
+ contextWindow: args.context ? parseInt(args.context) : 1900000
200
+ });
201
+
202
+ const res = await agent.directCall(input);
203
+ console.log(res);
204
+ \`\`\`
205
+
206
+ **Bash Examples**:
207
+ \`\`\`bash
208
+ # Quick query
209
+ echo "Explain async/await" | agents/grok_agent.js --model grok-4
210
+
211
+ # Custom options
212
+ echo "Daily summary" | agents/grok_agent.js --model grok-4 --temperature 0.1 --tokens 500
213
+
214
+ # Cron job (append to log)
215
+ 0 8 * * 1 echo "Weekly report: sales data" | /path/to/grok_agent.js >> reports.log
216
+
217
+ # Pipe chain
218
+ cat data.txt | agents/docs_agent.js --model grok-4 | jq .
219
+ \`\`\`
220
+
221
+ **Interactive vs Piped**:
222
+ | Mode | Invocation | Behavior |
223
+ |------|------------|----------|
224
+ | **Interactive** | \`agent.start()\` | Chat loop (multi-turn, until Ctrl+C). |
225
+ | **Piped** | \`readIn() + directCall()\` | Single response, fast exit. Stdin empty → help. |
226
+
227
+ **Suitability**: Cron/CLI automation (lightweight, no server). Complements WS modes.
228
+
229
+ **Cross-Ref**: [README.md#cli-one-shot-with-example-agents](../README.md#cli-one-shot-with-example-agents) (\`agents/*.js\` ready-to-run).
230
+
231
+ ## Advanced: Networking & Secrets
232
+ - **Server-Client Chain**: Server A attaches to Server B → A callable from B (and vice versa if mutual).
233
+ - **Cron/CLI Messaging**: Pipe to one-shot scripts (above) or WS clients: \`echo 'query' | npx @j-o-r/hello-dave dave --connect ...\`
234
+ - **Reset**: \`Prompt\` emits \`'reset'\` → propagates to attached servers/clients.
235
+
236
+ ## Errors
237
+ - No \`setup()\`: Throws.
238
+ - **Invalid \`name\`/\`toolName\`: Regex \`/^[a-z_0-9_]{2,}$/\` fail → \`Error\`**.
239
+ - No \`toolset\` on server: Throws.
240
+
241
+ See source \`lib/AgentManager.js\` for full JSDoc/types. Cross-links:
242
+ - [Prompt](./prompt-class.md)
243
+ - [ToolSet](./toolset.md)
244
+ - [Generic Tools](../lib/genericToolset.js)
@@ -0,0 +1,62 @@
1
+ # Dave CLI Usage
2
+
3
+ ## Introduction
4
+
5
+ The Dave CLI tool is the entry point for interacting with the Hello Dave project. It is located at `bin/dave.js` and can be run globally or via npx.
6
+
7
+ ## Installation
8
+
9
+ ### Global Installation
10
+
11
+ To install globally and use the `dave` command:
12
+
13
+ ```bash
14
+ npm install -g @j-o-r/hello-dave
15
+ ```
16
+
17
+ ### Local Usage with npx
18
+
19
+ Run without installation:
20
+
21
+ ```bash
22
+ npx @j-o-r/hello-dave [flags]
23
+ ```
24
+
25
+ ## Available Flags
26
+
27
+ The CLI supports various flags for configuration and launching services. Common flags include:
28
+
29
+ - `--help`: Display help information.
30
+ - `--version`: Show the current version of the Dave CLI.
31
+ - `--code [port] [--secret secret]`: Launch a portable CodeServer instance. Optionally specify a port (defaults to 8080 if omitted). Use `--secret` to set an access password for the server.
32
+
33
+ For detailed information on the CodeServer pattern and integration, refer to [codeserver-pattern.md](codeserver-pattern.md).
34
+
35
+ Other flags may be available depending on the version; run `dave --help` for the full list.
36
+
37
+ ## Examples
38
+
39
+ ### Basic Usage
40
+
41
+ - Show help (global):
42
+ ```bash
43
+ dave --help
44
+ ```
45
+
46
+ - Show version (npx):
47
+ ```bash
48
+ npx @j-o-r/hello-dave --version
49
+ ```
50
+
51
+ ### Launching CodeServer
52
+
53
+ - Launch on default port (global):
54
+ ```bash
55
+ dave --code
56
+ ```
57
+
58
+ - Launch on custom port with secret (npx):
59
+ ```bash
60
+ npx @j-o-r/hello-dave --code 3000 --secret mysecretpassword
61
+ ```
62
+