@j-o-r/hello-dave 0.1.1 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/CHANGELOG.md +42 -25
  2. package/README.md +81 -221
  3. package/TODO.md +173 -35
  4. package/agents/agent_creator.js +105 -0
  5. package/agents/agent_creator.prompt.md +371 -0
  6. package/agents/ask_agent.js +64 -127
  7. package/agents/claude_agent.js +68 -0
  8. package/agents/code_agent.js +55 -135
  9. package/agents/code_agent.prompt.md +50 -0
  10. package/agents/echo_agent.js +76 -0
  11. package/agents/financial_expert.js +75 -0
  12. package/agents/gpt_agent.js +52 -103
  13. package/agents/gpt_code.js +81 -0
  14. package/agents/grok_agent.js +58 -114
  15. package/agents/minimax_agent.js +92 -0
  16. package/agents/mureka_agent.js +77 -0
  17. package/agents/planner_agent.js +172 -0
  18. package/agents/stability_agent.js +87 -0
  19. package/agents/test_agent.js +75 -157
  20. package/agents/weather_agent.js +73 -0
  21. package/agents/workflow_agent.js +189 -0
  22. package/bin/dave.js +436 -184
  23. package/docs/bin-dave.md +85 -35
  24. package/docs/cdn-ssh.md +100 -0
  25. package/docs/creating-agents.md +301 -0
  26. package/docs/creating-toolsets.md +336 -0
  27. package/docs/docs-organization.md +48 -0
  28. package/docs/project-overview.md +86 -51
  29. package/lib/API/elevenlabs.io/music.compose.md +441 -0
  30. package/lib/API/elevenlabs.io/music.create-composition-plan.md +370 -0
  31. package/lib/API/elevenlabs.io/music.stream.md +425 -0
  32. package/lib/API/lalal.ai/lalal.js +445 -0
  33. package/lib/API/lalal.ai/openapi.json +2614 -0
  34. package/lib/API/minimax/ImageToolset.js +82 -37
  35. package/lib/API/minimax/MusicToolset.js +125 -79
  36. package/lib/API/minimax/VideoToolset.js +170 -167
  37. package/lib/API/minimax/image.js +5 -1
  38. package/lib/API/minimax/music.js +210 -23
  39. package/lib/API/minimax/video.js +242 -53
  40. package/lib/API/mureka/MusicToolset.js +646 -0
  41. package/lib/API/mureka/README.md +41 -0
  42. package/lib/API/mureka/index.js +7 -0
  43. package/lib/API/mureka/music.js +658 -0
  44. package/lib/API/openai.com/index.js +7 -0
  45. package/lib/API/openai.com/{reponses/text.js → responses.js} +64 -18
  46. package/lib/API/openai.com/video.create.character.md +40 -0
  47. package/lib/API/openai.com/video.create.md +219 -0
  48. package/lib/API/openai.com/video.delete.md +44 -0
  49. package/lib/API/openai.com/video.download.md +31 -0
  50. package/lib/API/openai.com/video.edit.md +155 -0
  51. package/lib/API/openai.com/video.extend.md +166 -0
  52. package/lib/API/openai.com/video.fetch.character.md +43 -0
  53. package/lib/API/openai.com/video.js +784 -0
  54. package/lib/API/openai.com/video.list.md +201 -0
  55. package/lib/API/openai.com/video.remix.md +175 -0
  56. package/lib/API/openai.com/video.retrieve.md +139 -0
  57. package/lib/API/openai.com/videoToolset.js +616 -0
  58. package/lib/API/stability.ai/ImageToolset.js +131 -40
  59. package/lib/API/stability.ai/MusicToolset.js +79 -47
  60. package/lib/API/stability.ai/audio.js +63 -131
  61. package/lib/API/x.ai/chat.responses.md +1040 -0
  62. package/lib/API/x.ai/image.js +229 -59
  63. package/lib/API/x.ai/imageToolset.js +376 -0
  64. package/lib/API/x.ai/index.js +1 -1
  65. package/lib/API/x.ai/responses.js +9 -18
  66. package/lib/Agent.js +271 -0
  67. package/lib/Agent.js.old +284 -0
  68. package/lib/AgentLauncher.js +593 -0
  69. package/lib/Cli.js +87 -13
  70. package/lib/Prompt.js +23 -1
  71. package/lib/Session.js +5 -4
  72. package/lib/ToolSet.js +102 -6
  73. package/lib/agentLoader.js +369 -0
  74. package/lib/cdn.js +67 -231
  75. package/lib/{CdnToolset.js → cdnToolset.js} +47 -64
  76. package/lib/defaultToolsets.js +43 -0
  77. package/lib/fafs.js +1 -1
  78. package/lib/genericToolset.js +442 -119
  79. package/lib/handOffToolset.js +179 -0
  80. package/lib/index.js +34 -27
  81. package/lib/toolsetLoader.js +248 -0
  82. package/package.json +10 -4
  83. package/types/API/lalal.ai/lalal.d.ts +116 -0
  84. package/types/API/minimax/image.d.ts +2 -1
  85. package/types/API/minimax/music.d.ts +189 -26
  86. package/types/API/minimax/video.d.ts +100 -31
  87. package/types/API/mureka/index.d.ts +7 -0
  88. package/types/API/mureka/music.d.ts +472 -0
  89. package/types/API/openai.com/index.d.ts +7 -0
  90. package/types/API/openai.com/{reponses/text.d.ts → responses.d.ts} +11 -11
  91. package/types/API/openai.com/video.d.ts +409 -0
  92. package/types/API/openai.com/videoToolset.d.ts +24 -0
  93. package/types/API/stability.ai/audio.d.ts +14 -103
  94. package/types/API/stability.ai/image.d.ts +2 -2
  95. package/types/API/x.ai/image.d.ts +138 -26
  96. package/types/API/x.ai/imageToolset.d.ts +3 -0
  97. package/types/API/x.ai/index.d.ts +1 -1
  98. package/types/API/x.ai/responses.d.ts +4 -4
  99. package/types/Agent.d.ts +123 -0
  100. package/types/AgentLauncher.d.ts +250 -0
  101. package/types/Cli.d.ts +28 -8
  102. package/types/Prompt.d.ts +23 -5
  103. package/types/Session.d.ts +1 -1
  104. package/types/ToolSet.d.ts +10 -0
  105. package/types/agentLoader.d.ts +78 -0
  106. package/types/cdn.d.ts +15 -90
  107. package/types/defaultToolsets.d.ts +9 -0
  108. package/types/fafs.d.ts +1 -1
  109. package/types/genericToolset.d.ts +1 -1
  110. package/types/handOffToolset.d.ts +28 -0
  111. package/types/index.d.ts +19 -17
  112. package/types/toolsetLoader.d.ts +114 -0
  113. package/utils/format_log.js +101 -23
  114. package/utils/launch_agent.js +18 -0
  115. package/utils/list_sessions.sh +13 -5
  116. package/utils/search_sessions.sh +65 -29
  117. package/utils/toolsets.js +33 -0
  118. package/README.md.bak.1779452127 +0 -240
  119. package/agents/codeserver.sh +0 -47
  120. package/agents/daisy_agent.js +0 -173
  121. package/agents/docs_agent.js +0 -148
  122. package/agents/memory_agent.js +0 -263
  123. package/agents/minimax.js +0 -173
  124. package/agents/npm_agent.js +0 -202
  125. package/agents/prompt_agent.js +0 -133
  126. package/agents/readme_agent.js +0 -148
  127. package/agents/spawn_agent.js +0 -160
  128. package/agents/stability.js +0 -173
  129. package/agents/todo_agent.js +0 -175
  130. package/bin/codeDave +0 -58
  131. package/docs/agent-dave-websocket-protocol.md +0 -180
  132. package/docs/agent-manager.md +0 -244
  133. package/docs/codeserver-pattern.md +0 -191
  134. package/docs/generic-toolset.md +0 -326
  135. package/docs/howtos/agent-networking.md +0 -253
  136. package/docs/howtos/spawn-agents.md.bak +0 -200
  137. package/docs/howtos/spawn-agents.md.bak_new +0 -200
  138. package/docs/multi-agent-clusters.md +0 -265
  139. package/docs/music-toolsets.md +0 -137
  140. package/docs/path-resolution-best-practices.md +0 -104
  141. package/docs/plans/minimax-music-generation.md +0 -80
  142. package/docs/plans/unified-agent-architecture.md +0 -146
  143. package/docs/plans/websocket-streaming-plan.md.bak +0 -317
  144. package/docs/prompt/spawn_agent.md +0 -175
  145. package/docs/prompt/spawn_agent.md.bak +0 -201
  146. package/docs/prompt/task_clarification_and_documentation.md +0 -35
  147. package/docs/prompt-class.md +0 -141
  148. package/docs/todo-archive-infra-2026-04-21.md +0 -15
  149. package/docs/todo-archive-v0.0.8.md +0 -1
  150. package/docs/todo-archive-v0.1.0.md +0 -32
  151. package/docs/todo-archive.md +0 -44
  152. package/docs/tools-syntax-validation.md +0 -121
  153. package/docs/toolset.md +0 -164
  154. package/docs/xai-responses.md +0 -111
  155. package/docs/xai_collections.md +0 -106
  156. package/lib/API/x.ai/ImageToolset.js +0 -165
  157. package/lib/API/x.ai/text.js +0 -415
  158. package/lib/AgentClient.js +0 -248
  159. package/lib/AgentManager.js +0 -245
  160. package/lib/AgentServer.js +0 -404
  161. package/lib/wsCli.js +0 -287
  162. package/lib/wsIO.js +0 -90
  163. package/types/API/x.ai/text.d.ts +0 -286
  164. package/types/AgentClient.d.ts +0 -109
  165. package/types/AgentManager.d.ts +0 -100
  166. package/types/AgentServer.d.ts +0 -89
  167. package/types/wsCli.d.ts +0 -17
  168. package/types/wsIO.d.ts +0 -30
  169. package/utils/test.sh +0 -46
  170. /package/docs/{suggestions.md → _notes/token-counts.md} +0 -0
  171. /package/lib/API/openai.com/{reponses/MESSAGES.md → MESSAGES.md} +0 -0
  172. /package/types/API/{x.ai/ImageToolset.d.ts → mureka/MusicToolset.d.ts} +0 -0
  173. /package/types/{CdnToolset.d.ts → cdnToolset.d.ts} +0 -0
@@ -1,201 +0,0 @@
1
- # Spawn Agent System Prompt
2
-
3
- This document provides the full system prompt used by the `spawn_agent` for creating portable CLI/WS agents in the @j-o-r/hello-dave ecosystem. It is structured for clarity and can be directly used or referenced by LLMs.
4
-
5
- ## Full Raw Prompt
6
-
7
- ```
8
- You are AgentCreator, expert in @j-o-r/hello-dave. Create production-ready CLI agents (agents/<name>.js) **portably** anywhere (no local docs needed).
9
-
10
- **AGENT NAME RULE ⚠️**: name MUST be lowercase a-z0-9_ min 2 chars (/^[a-z_0-9_]{2,}$/). EX: myagent, codeagent, ws_tool.
11
-
12
- **IMPORTS CRITICAL ⚠️**: **NAMED imports ONLY** - NO default! `import { AgentManager } from '@j-o-r/hello-dave';` `import { parseArgs } from '@j-o-r/sh';`
13
-
14
- **PORTABILITY**: Auto-install deps: `@j-o-r/hello-dave @j-o-r/sh`. Absolute imports. NO local file refs (docs/agents).
15
-
16
- **MANDATORY MEMORY PROTOCOL (For EVERY query/task - NO EXCEPTIONS):**
17
- Connected clients (todo_agent, readme_agent, npm_agent, docs_agent, **memory_agent**) are available as tools. **ALWAYS** use **memory_agent** FIRST and LAST:
18
- 1. **RECALL PHASE (Step 1 of EVERY response)**:
19
- - Call `memory_agent "Recall relevant memories: tasks, errors, prefs for [keywords from user query]. List recent if empty."`
20
- - Incorporate recalled info (e.g., avoid known errors, resume tasks, apply prefs like temp=0.2).
21
- 2. **CORE ACTION**:
22
- - Perform coding assistance (tools: execute_bash_script, javascript_interpreter, read_file/write_file, web_search, etc.).
23
- - Delegate to specialists if relevant:
24
- - todo_agent: Tasks/TODO.md
25
- - readme_agent: README.md
26
- - npm_agent: NPM modules/package.json
27
- - docs_agent: Documentation
28
- - memory_agent: Persistent storage
29
- 3. **WRITE PHASE (Step 3 of EVERY response)**:
30
- - Call `memory_agent "Store updates: [new tasks/errors/prefs/decisions from this interaction]. E.g., 'Task: [next step]', 'Error: [issue]', 'Pref: [setting]'"`
31
- - This ensures persistence across sessions/agents, prevents loops/token burn.
32
-
33
- **PRIORITIES**:
34
- - Safety: CWD-only, no escapes, validate before write.
35
- - Efficiency: Use memories to skip repeats (e.g., "Known error: git conflict → skip").
36
- - Step-by-step: Clear responses with code blocks.
37
- FOLLOW MEMORY PROTOCOL RIGIDLY - it's how multi-agent coordination works!
38
-
39
- **INITIAL INSPECT** (execute_bash_script):
40
- 1. `npm ls @j-o-r/hello-dave @j-o-r/sh 2>/dev/null || echo MISSING` → If MISSING: `npm i @j-o-r/hello-dave @j-o-r/sh --save-exact`.
41
- 2. `mkdir -p agents`.
42
- 3. `cat package.json` (project name). `ls -la agents/`.
43
-
44
- **TOOL RULES (CRITICAL - NO MIX)**:
45
- - **XAI Natives** (pre-setup): `options.tools.push({ type: 'web_search' });` etc.
46
- - **Generics** (post-setup): `agent.addGenericToolcall('read_file');` w/ `toolsetMode: 'auto'`.
47
- Default: web_search + execute_bash_script/read_file/write_file.
48
-
49
- **PROCESS (EXACT)**:
50
- 1. INSPECT & SETUP.
51
- 2. GATHER (conversational): **name (validate /^[a-z_0-9_]{2,}$/ or reject)**, desc, api('xai'), model/options, tools, custom prompt, CLI intro/help.
52
- 3. GENERATE & VALIDATE: Use blueprint. Write temp_validate.js, `node --check temp_validate.js` (PASS), grep toolsetMode/auto (1x), generics/addGeneric (≥1 if used), natives/push (≥1 if used), NO options.tools.function.read_file. rm temp.
53
- 4. REVIEW: Show ```js``` + "✅ node --check | Tools OK". Edit if needed.
54
- 5. DEPLOY: `write_file ./agents/${name}.js FULL_CODE`, `chmod +x ./agents/${name}.js`.
55
- 6. **TEST**: `execute_bash_script './agents/${name}.js "Briefly describe yourself and your modes (CLI/server/client)"'` → Show output.
56
- 7. **SERVER/CLIENT GUIDE**: "Test server: ./agents/${name}.js --serve 8081 (find free port). Client: echo 'query' | ./agents/${name}.js --connect ws://localhost:8081/ws --secret SECRET".
57
- 8. **CodeServer MULTI-AGENT**: If requested (e.g., "multi-agent", "CodeServer"), generate **self-contained Bash launcher** (PM2-managed main server + subs). Write to agents/<Name>Server (e.g., agents/CodeServer). Use blueprint below. PM2: Assume installed (`npm i -g pm2`).
58
-
59
- **AGENT BLUEPRINT** (COPY/REPLACE - Plain backticks ` NO ESCAPES):
60
- #!/usr/bin/env node
61
- import { AgentManager } from '@j-o-r/hello-dave';
62
- import { parseArgs } from '@j-o-r/sh';
63
-
64
- const name = 'AGENTNAME'; // ← REPLACE w/ lowercase /^[a-z_0-9_]{2,}$/
65
- const api = 'xai';
66
- let secret = '';
67
-
68
- const args = parseArgs();
69
- const help = args['help'] || false;
70
- const connect = args['connect'] ? args['connect'] : undefined;
71
- const serve = args['serve'] ? parseInt(args['serve']) : undefined;
72
-
73
- const options = { tools: [] };
74
-
75
- // NATIVES HERE e.g. options.tools.push({ type: 'web_search' });
76
-
77
- if (args['secret']) { secret = args['secret']; }
78
- if (args['model'] || true) { options.model = args['model'] || 'grok-4-fast-reasoning'; }
79
- if (args['temperature']) { options.temperature = parseFloat(args['temperature']); } else { options.temperature = 0.8; }
80
- options.reasoning = { effort: 'medium', summary: 'auto' };
81
-
82
- const contextWindow = args['context'] ? parseInt(args['context']) : 500000;
83
- const toolsetMode = 'auto';
84
-
85
- function printHelp() {
86
- console.log(`AGENTNAME --help: AGENTDESC
87
-
88
- Full modes: CLI, WS Server (--serve), WS Client (--connect), Hybrid.
89
-
90
- Repo docs: https://codeberg.org/duin/hello-dave (agent-manager.md, codeserver-pattern.md).
91
-
92
- USAGE:
93
- ./agents/AGENTNAME # Interactive CLI
94
- echo "query" | ./agents/AGENTNAME # One-shot
95
- ./agents/AGENTNAME --serve 8081 # WS Server
96
- ./agents/AGENTNAME --connect ws://host:8081/ws --secret KEY # WS Client
97
- ./agents/AGENTNAME --serve 8081 --connect ws://other:8080/ws # Hybrid
98
-
99
- OPTIONS: --model ... --secret ...
100
-
101
- EXAMPLES:
102
- Chain: Server A --connect B → delegates to B.
103
- Multi-Agent: Generate/use PM2 launcher (CodeServer pattern).`);
104
- process.exit();
105
- }
106
-
107
- if (help) printHelp();
108
-
109
- const prompt = `You are AGENTNAME, AGENTDESC.
110
-
111
- CUSTOMPROMPT`.trim();
112
-
113
- const agent = new AgentManager({ name, secret });
114
- agent.setup({ prompt, api, options, toolsetMode, contextWindow });
115
-
116
- // GENERICS HERE e.g. agent.addGenericToolcall('execute_bash_script');
117
-
118
- const cliIntro = `🤖 AGENTNAME ready! Modes: CLI/Server/Client/Hybrid.
119
-
120
- CLIINTRO`.trim();
121
-
122
- const toolName = 'agent_' + name;
123
- const toolDescription = `AGENTDESC. Supports WS chaining/multi-agent.`.trim();
124
-
125
- await agent.start(serve, connect, cliIntro, toolName, toolDescription);
126
-
127
- **CODE_SERVER BLUEPRINT** (Bash for multi-agent - Self-contained, like CodeServer pattern):
128
- #!/bin/bash
129
- # Portable Multi-Agent Launcher (PM2-managed: main server + subs)
130
- # Run: npm i -g pm2 (once)
131
- if [ $# -lt 1 ] || [ $# -gt 2 ]; then
132
- echo "Usage: $0 <PORT> [SECRET] # PORT:1024-65535, SECRET:>=3 chars (def:123)"
133
- exit 1
134
- fi
135
- PORT="$1"
136
- SECRET="${2:-123}"
137
- if [ ${#SECRET} -lt 3 ]; then echo "SECRET too short"; exit 1; fi
138
- if ! [[ "$PORT" =~ ^[0-9]+$ ]] || [ "$PORT" -lt 1024 ] || [ "$PORT" -gt 65535 ]; then echo "Bad PORT"; exit 1; fi
139
-
140
- SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
141
- PROJECT_DIR="$( cd "$( dirname "${SCRIPT_DIR}" )" && pwd )"
142
- FOLDER=$(basename "$PROJECT_DIR")
143
-
144
- echo "Starting <MainAgent>Server on port ${PORT} in '$FOLDER' w/ SECRET '$SECRET'..."
145
-
146
- # Cleanup old PM2
147
- pm2 delete "${FOLDER}_mainagent_${PORT}" 2>/dev/null || true
148
- pm2 delete "${FOLDER}_sub1agent_${PORT}" 2>/dev/null || true # Add per sub
149
- # ... more subs
150
-
151
- # Main server
152
- pm2 start "${SCRIPT_DIR}/agents/mainagent.js" --name "${FOLDER}_mainagent_${PORT}" -- --serve "${PORT}" --tools javascript --secret "${SECRET}"
153
- # Subs as clients
154
- pm2 start "${SCRIPT_DIR}/agents/sub1agent.js" --name "${FOLDER}_sub1agent_${PORT}" -- --connect "ws://127.0.0.1:${PORT}/ws" --secret "${SECRET}"
155
- # ... more: pm2 start ... sub2agent.js ...
156
-
157
- echo "Processes: pm2 list | grep '${FOLDER}_${PORT}'"
158
- echo "Connect: npx @j-o-r/hello-dave dave --connect ws://127.0.0.1:${PORT}/ws --secret '${SECRET}'"
159
-
160
- Enthusiastic, step-by-step. Match portable style. **ALWAYS validate name regex before generate/deploy.** Current date: 2026. Models: grok-4-fast-reasoning/grok-beta. CodeServer pattern: https://codeberg.org/duin/hello-dave/src/branch/main/agents/CodeServer
161
- ```
162
-
163
- ## Section-by-Section Explanation
164
-
165
- ### Role
166
- Defines the agent's identity as "AgentCreator," an expert in the @j-o-r/hello-dave framework. It instructs the LLM to focus on creating production-ready CLI agents in `agents/<name>.js` files that are portable (runnable anywhere without local dependencies beyond auto-installs). **Why?** Establishes core purpose, ensuring outputs are specialized, reliable, and framework-compliant for seamless integration in multi-agent systems.
167
-
168
- ### AGENT NAME RULE
169
- Enforces strict naming conventions: lowercase letters, digits, underscores only, minimum 2 characters, matching regex `/^[a-z_0-9_]{2,}$/`. Provides examples like "myagent." **Why?** Prevents invalid filenames or import issues in Node.js environments; ensures consistency and avoids errors in agent deployment across projects.
170
-
171
- ### IMPORTS
172
- Mandates named imports exclusively (no defaults) for key modules: `AgentManager` from '@j-o-r/hello-dave' and `parseArgs` from '@j-o-r/sh'. **Why?** Promotes explicit, reliable code that works in ES modules; avoids common import pitfalls, enhancing portability and reducing runtime errors in diverse setups.
173
-
174
- ### PORTABILITY
175
- Requires auto-installation of dependencies (`@j-o-r/hello-dave @j-o-r/sh` via npm), use of absolute imports, and avoidance of local file references (e.g., no hardcoding paths to docs/agents). **Why?** Enables agents to run in any clean environment without manual setup; supports deployment in varied contexts like CI/CD or remote servers, minimizing friction.
176
-
177
- ### MEMORY PROTOCOL
178
- Outlines a rigid, three-phase protocol using `memory_agent` for every interaction: (1) Recall relevant memories (tasks, errors, preferences) at the start; (2) Perform core actions, delegating to specialist agents (todo_agent, etc.); (3) Write updates to memory at the end. Emphasizes persistence to avoid loops and token waste. **Why?** Facilitates stateful, coordinated multi-agent behavior; ensures knowledge carryover across sessions, improving efficiency and preventing redundant work in long-running or chained agent workflows.
179
-
180
- ### PRIORITIES
181
- Highlights key guidelines: safety (CWD-only operations, validation), efficiency (leverage memories to skip repeats), and clarity (step-by-step responses with code blocks). Insists on rigid adherence to the memory protocol. **Why?** Balances reliability, performance, and usability; protects against risks like file overwrites or infinite loops while making outputs actionable for users and other agents.
182
-
183
- ### INITIAL INSPECT
184
- Directs initial tool calls via `execute_bash_script` to check/install dependencies, create the `agents/` directory, and inspect `package.json` and existing agents. **Why?** Ensures the environment is prepared before generation; detects missing deps early, allowing portable setup without assumptions about the project's state.
185
-
186
- ### TOOL RULES
187
- Distinguishes between XAI native tools (added pre-setup via `options.tools.push`) and generic tools (added post-setup via `agent.addGenericToolcall` with `toolsetMode: 'auto'`). Defaults to web_search + bash/file tools. Prohibits mixing. **Why?** Maintains clean separation for compatibility with the AgentManager framework; prevents tool conflicts or invalid configurations, ensuring agents integrate correctly with XAI APIs.
188
-
189
- ### PROCESS
190
- Details an exact, 8-step workflow: (1) Inspect/setup; (2) Gather details conversationally (validate name first); (3) Generate/validate code using blueprint (syntax check, grep for patterns); (4) Review; (5) Deploy; (6) Test; (7) Provide server/client guides; (8) Handle multi-agent requests with Bash launchers. **Why?** Provides a structured, verifiable pipeline for agent creation; reduces errors through validation/testing, making the process reproducible and debuggable for LLMs.
191
-
192
- ### AGENT BLUEPRINT
193
- Supplies a complete, copy-pasteable JavaScript template for new agents, with placeholders (e.g., AGENTNAME, AGENTDESC, CUSTOMPROMPT) and sections for natives, generics, help, prompt, and startup. Instructs no escapes in backticks. **Why?** Serves as a standardized skeleton; ensures all agents follow the same portable pattern, simplifying maintenance and chaining in multi-agent setups.
194
-
195
- ### CODE_SERVER BLUEPRINT
196
- Provides a self-contained Bash script template for PM2-managed multi-agent servers (main + subs), including validation, cleanup, startup, and connection instructions. Assumes PM2 installation. **Why?** Enables scalable, orchestrated multi-agent deployments (e.g., CodeServer pattern); automates server management, allowing complex systems to run persistently without manual intervention.
197
-
198
- ### Final Notes
199
- Encourages enthusiastic, step-by-step responses matching the portable style. Reiterates name validation. Includes current date (2026), model options, and a link to the CodeServer pattern. **Why?** Reinforces tone and best practices; contextualizes with timely info and resources, aiding LLMs in generating consistent, up-to-date outputs.
200
-
201
- This file is designed to be fetched via raw URL as the live system prompt for spawn_agent.
@@ -1,35 +0,0 @@
1
- # Task Clarification and Documentation First
2
-
3
- **Core Principle**: For ANY task or problem (programming or otherwise), NEVER jump directly into execution. First collaborate with the user to define, analyze, gather requirements, and document everything in a Markdown plan **before** doing the work.
4
-
5
- ## Instructions for the Assistant / LLM / Agent
6
-
7
- 1. **Clarify & Define**
8
- Work with the user to create a clear, unambiguous task definition. Ask questions if anything is unclear, incomplete, or could be interpreted multiple ways.
9
-
10
- 2. **Gather & Analyze**
11
- Collect all requirements, constraints, wishes, context, and edge cases. Analyze the problem thoroughly. Identify risks, dependencies, and success criteria.
12
-
13
- 3. **Document First**
14
- Create or update a dedicated Markdown document in `docs/plans/` that captures:
15
- - Task description
16
- - Requirements & constraints
17
- - Analysis
18
- - Proposed approach / plan
19
- - Breakdown into smaller steps (if the task is large)
20
-
21
- Only after the user reviews and approves this document do you proceed to implementation or execution.
22
-
23
- 4. **Break Down Large Tasks**
24
- If a task is very large or complex, divide it into multiple smaller, independent subtasks. Handle and document one at a time. Update the main plan as you go.
25
-
26
- 5. **General Rules**
27
- - Be token-efficient in responses.
28
- - Stay strictly within any file or scope constraints the user specifies.
29
- - Use tools (memory_agent, todo_agent, readme_agent, etc.) to track tasks and documentation.
30
- - Always recall relevant memories first and store updates at the end of each interaction.
31
- - Prioritize clarity and traceability over speed.
32
-
33
- This method ensures high-quality outcomes, reduces errors from unclear requirements, and creates reusable documentation.
34
-
35
- **Prompt Version**: 1.0 (2026-04-25)
@@ -1,141 +0,0 @@
1
- # Prompt Class
2
-
3
- Source: \`lib/Prompt.js\`
4
-
5
- The \`Prompt\` class is an EventEmitter-based manager for standardized AI conversation messages. It supports multi-modal content (text, images, audio), tool/function calls, token counting, automatic truncation, and adapters for different LLM providers (OpenAI, xAI, Anthropic).
6
-
7
- ## Key Features
8
- - Uniform message format across providers.
9
- - Context window management with truncation.
10
- - Toolset integration for function calling.
11
- - Event-driven (add, start, finished, tool_request, etc.).
12
- - Sticky system prompts preserved on reset/truncate.
13
-
14
- ## Dependencies
15
- - \`gpt-3-encoder\` for token counting.
16
- - \`node:events\` EventEmitter.
17
- - \`./promptHelpers.js\` for tool pruning.
18
-
19
- ## Message Structure
20
- ```js
21
- {
22
- role: "system" | "assistant" | "user" | "tool" | "log" | "reasoning",
23
- content: Content[],
24
- name?: string,
25
- sticky?: boolean, // Preserve on reset
26
- ts?: number // Timestamp
27
- }
28
- ```
29
-
30
- ### Content Types
31
- | Type | Role Constraints | Structure |
32
- |------|------------------|-----------|
33
- | `text` | system/assistant/user | `{ type: "text", text: string }` |
34
- | `image_url` | user | `{ type: "image_url", url: string \| data:URL }` |
35
- | `audio_url` | user | `{ type: "audio_url", url: string \| data:URL }` |
36
- | `function_request` | assistant | `{ type: "function_request", function_request: { name: string, id: string, call_id?: string, parameters: string (JSON) } }` |
37
- | `function_response` | tool | `{ type: "function_response", function_response: { name: string, id: string, call_id?: string, response: string (JSON) } }` |
38
-
39
- ## Record Structure (API Logs)
40
- ```js
41
- {
42
- id: string,
43
- isoDate: string,
44
- duration: number (ms),
45
- environment: string,
46
- model: string,
47
- tokensIn: number,
48
- tokensOut: number
49
- }
50
- ```
51
-
52
- ## Constants
53
- ```js
54
- const MESSAGE_ROLES = { SYSTEM: "system", ASSISTANT: "assistant", ... };
55
- const MESSAGE_TYPES = { TEXT: "text", IMAGE_URL: "image_url", ... };
56
- const EVENTS = { start: "start", finished: "finished", tool_request: "tool_request", ... };
57
- ```
58
-
59
- ## Usage Example
60
- ```js
61
- import { Prompt, ToolSet } from '@j-o-r/hello-dave';
62
- import { openaiText } from './API/openai.com/text.js'; // Adapter example
63
-
64
- const prompt = new Prompt(128000); // Context window
65
- prompt.setAdaptor(openaiText, new ToolSet(), { model: "gpt-4o" });
66
-
67
- prompt.add("system", "You are a helpful assistant.", true);
68
- const response = await prompt.call("Hello!");
69
- console.log(response); // Assistant response
70
- ```
71
-
72
- ## Properties
73
- | Name | Type | Description |
74
- |------|------|-------------|
75
- | `contextLength` | `number` | Max tokens (getter) |
76
- | `messages` | `Message[]` | Copy of messages (getter/setter validates/imports) |
77
- | `length` | `number` | Message count |
78
- | `system_prompt` | `string` | System message text (throws if missing) |
79
- | `hasSystemprompt` | `boolean` | System prompt present? |
80
- | `toolset` | `ToolSet \| void` | Current toolset |
81
- | `EVENTS` | `object` | Frozen event names |
82
-
83
- ## Methods
84
-
85
- ### Constructor
86
- ```js
87
- new Prompt(contextWindow?: number)
88
- ```
89
- - `contextWindow = 0`: One-shot (no history buildup).
90
-
91
- ### Setup
92
- - `setAdaptor(requestHandler, toolset?: ToolSet, options?)`: Bind AI provider.
93
- - `toolsetFunctions()`: `string[]` of available tools.
94
-
95
- ### Adding Messages
96
- - `add(role: Roles, text: string, sticky = false)`: Text message.
97
- - `addMultiModal(role: Roles, content: Content[], sticky = false)`: Multi-modal.
98
- - Validates role/content, order (system first/sticky), emits `message`.
99
-
100
- ### Conversation Flow
101
- - `call(content: string \| Content[])`: Add user input, call adapter, return text response. Emits `start`, `finished`.
102
- - `triggerRequest()`: Auto-trigger if last message is user/tool (for tools first).
103
-
104
- ### Management
105
- - `reset()`: Remove non-sticky, return removed. Emits `reset`.
106
- - `truncate()`: Prune tools, remove old user-assistant blocks to fit context. Emits `truncated`.
107
- - `countTokens(str?: string)`: Tokens in string or last total.
108
- - `contentToString(content)`: Concat text from content.
109
- - `getLastMessage()`: Last message.
110
-
111
- ### Records & Info
112
- - `addRecord(record)` / `addRecords(records[])`: Log API usage, update tokens, warn if over limit.
113
- - `templateRecord()`: Empty record.
114
- - `info()`: Debug string (cwd, tools, context, tokens).
115
-
116
- ## Events
117
- Emitted via `EventEmitter`:
118
-
119
- | Event | Triggered When | Data |
120
- |-------|----------------|------|
121
- | `message` | Message added | `Message` |
122
- | `start` / `retrigger` / `finished` | Request lifecycle | `true` |
123
- | `record` | Record added | `Record` |
124
- | `truncated` / `reset` | History altered | Event name |
125
- | `tool_request` / `tool_response` / `tool_error` | Tool lifecycle | Tool data |
126
- | `error` / `warning` | Issues | Error/Warning |
127
-
128
- ## Validation
129
- - Strict checks on message roles/types/content.
130
- - Records must have all fields.
131
- - Order: System first/sticky sequential.
132
-
133
- ## Truncation Details
134
- 1. Prune resolved tool calls (keep last per ID).
135
- 2. Sum sticky tokens.
136
- 3. From end: Remove full user-assistant blocks exceeding window.
137
-
138
- ## Integration Notes
139
- - Adapters handle provider-specific formatting (e.g., OpenAI, xAI).
140
- - Tools execute automatically in `triggerRequest`.
141
- - Supports reasoning role (xAI-specific).
@@ -1,15 +0,0 @@
1
- # Archived Infrastructure Tasks - 2026-04-21
2
-
3
- These tasks related to VPS/CDN setup and publishing agents were removed from TODO.md as they are not core to the hello-dave project.
4
-
5
- ## Archived from TODO (high priority pending)
6
-
7
- - 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
8
- - Subtask: Set up VPS and SSH access
9
- - Subtask: Install and configure Nginx for static file serving
10
- - Subtask: Implement security measures (e.g., firewall, SSL/TLS, access controls)
11
- - Subtask: Upload and organize static assets
12
- - Subtask: Test with previous image test case and verify direct access via tools
13
-
14
- - 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.
15
-
@@ -1 +0,0 @@
1
- - [x] 2026-04-15: Generate v0.0.8 changelog from recent commits and TODO.md Done section. Include key features: spawn_agent enhancements (hybrid modes, portability, PM2 integration), timeout fixes in toolset, documentation updates. (Completed 2026-04-15: CHANGELOG.md updated with v0.0.8 entries based on archived tasks and git log. Key highlights added: spawn_agent hybrid modes/portability/PM2, tool timeouts via @j-o-r/sh, docs updates. Ready for release.)
@@ -1,32 +0,0 @@
1
- # Archived TODO Items - v0.1.0 (2026-04-24)
2
-
3
- This archive contains all completed tasks from TODO.md as of 2026-04-24. No pending tasks remain.
4
-
5
- ## Previously High Priority Pending
6
- - [x] 2026-04-24: Review and enhance genericToolset.js for better tool definitions, including validation for execute_bash_script parameters.
7
-
8
- ## Previously In Progress
9
- - [x] 2026-04-23: Create dedicated test for execute_bash_script tool in scenarios/ folder. The test should be comprehensive, testing timeout, error cases, complex scripts, shebang, and safety (no escaping, CWD only). Reference the definition in lib/genericToolset.js
10
-
11
- ## Previously Later/Future Tasks
12
- - [x] Review and add unit tests for agent toolsets (e.g., web_search, execute_bash_script in lib/)
13
- - [x] Update CHANGELOG.md and prepare for v0.1.0 release (add new features like multi-agent improvements)
14
- - [x] Enhance documentation: Add examples for hybrid spawn_agent modes in README.md and docs/
15
- - [x] Implement additional agents: e.g., integration_agent for chaining Grok/OpenAI/Anthropic
16
- - [x] Optimize WebSocket protocol: Implement suggested optimizations from docs/agent-dave-websocket-protocol.md
17
-
18
- ## Previously Done (Prior to This Archive)
19
- - [x] 2026-04-24: Confirm genericToolset.js and its dedicated test are complete (including tests for tool definitions and validation).
20
- - [x] 2026-04-22: Create TDD test in scenarios/ for escaping fix in syntax_check and write_file before any further implementation. Use test_agent if needed.
21
- - [x] 2026-04-24: Implement bash tool fixes for execute_bash_script, including shebang support, strict mode enforcement, and input validation improvements.
22
- - [x] 2026-04-24: Update syntax_check.sh with shebang, strict mode, and enhanced validation for safer script execution.
23
- - [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.
24
- - [x] Subtask: Review and analyze source files (AgentServer.js, AgentClient.js, wsIO.js)
25
- - [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.
26
- - [x] Subtask: Document the protocol structure and message formats
27
- - [x] Subtask: Create sequence diagrams for key interactions (Mermaid diagrams added to the new docs file)
28
- - [x] Subtask: Identify and suggest optimizations for performance and reliability (detailed section added with 6 categories of improvements)
29
-
30
- ## Archive Notes
31
- 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).
32
- Infrastructure tasks archived to docs/todo-archive-infra-2026-04-21.md on 2026-04-21.
@@ -1,44 +0,0 @@
1
- # TODO Archive
2
-
3
- ## Archived on 2026-04-13
4
-
5
- ### From Previous TODO.md (older done tasks)
6
-
7
- - [x] 2026-04-11: Enhance agents/spawn_agent.js with more robust self-testing via execute_bash_script for direct/CLI/server modes; update blueprint for better agent validation. Status: In progress. (Completed 2026-04-11: For coding enhancements to spawn_agent.js (e.g., integrating robust self-testing logic), delegated to code_agent as per NO-CODING RULE. Blueprint updated in docs/prompt/spawn_agent.md PROCESS section with enhanced validation steps: added multi-mode checks (grep for serve/connect/start/toolsetMode), stricter rejection on deviations, and expanded test scripts for direct/CLI/server/client/hybrid modes using execute_bash_script examples. Local verification: Spawned test agent via ./agents/spawn_agent.js, ran bash tests (direct: "describe", --help, --serve 8081 + client connect/query), confirmed PASS on node --check, greps, and functionality. No code changes by TODO manager; ready for v0.0.8 sprint.)
8
- - [x] 2026-04-11: Enhance agents/spawn_agent.js creation using simplified bash examples for workflows/tests/improving (e.g., add more robust self-testing via execute_bash_script for direct/CLI/server modes; update blueprint for better agent validation). Test locally: Spawn a new agent and verify functionality. (Completed 2026-04-11: Delegated coding enhancements to code_agent; blueprint updated in docs/prompt/spawn_agent.md for stricter validation checks (added multi-mode grep for serve/connect/start); self-testing expanded in spawn_agent.js tool_description with bash examples for direct/CLI/server/client/hybrid. Local test: Spawned "testagent" via ./agents/spawn_agent.js "Create test agent: name=testagent, desc=Simple tester"; verified direct call, --help, --serve 8081 (connected client successfully), and rm after. Functionality confirmed via execute_bash_script logs.)
9
- - [x] 2026-04-11: Fix genericToolset.test.js failures: write_file not returning 'Successfully wrote' message (line ~96), and syntax error checks failing to match '❌ SYNTAX ERROR' (lines ~117,135,154). Review test cases for msg/syntax assertions; update write_file impl or test expectations if needed (e.g., error msg format changed post-JSDoc updates). Run `npm run tests` to verify fix. Prioritize for post-v0.0.7 stability. (Completed 2026-04-11: Updated assertions to match current implementation: 'Wrote ' and 'Syntax error'. Tests now pass after verification with `npm run tests`.)
10
- - [x] 2026-04-11: v0.0.7 release completed: Committed JSDoc updates, bin/codeDave, types/*.d.ts, docs/jsdoc/ HTML; git tagged v0.0.7; prepared for npm publish (tests pending fix, but core docs/types shipped). (Completed 2026-04-11: All specified commits/tags done; version in package.json is 0.0.7.)
11
- - [x] 2026-04-11: Commit recent JSDoc updates in lib/ and types/ (git add lib/ types/ TODO.md utils/search_sessions.sh; commit 'Complete JSDoc for lib/ + types regen'; verify syntax). Then: npm install && npm prune. Generate JSDoc HTML: npx jsdoc lib/ -d docs/jsdoc. Prepare v0.0.7 release. (Completed 2026-04-11: Committed changes, deps pruned/installed, JSDoc HTML generated and committed.)
12
- - [x] 2026-04-10: Generate HTML docs for lib/ using JSDoc CLI, and document other lib files like index.js if needed (e.g., add JSDoc for exports, modules; run `npx jsdoc lib/ -d docs/jsdoc` or similar; verify output). (Completed 2026-04-11: Full generation run, output verified in docs/jsdoc/ with comprehensive coverage for all lib/ modules.)
13
- - [x] 2026-04-03: Integrate x.ai API features into collections.js and files.js (review and merge from Later tasks) (Note: Verified - no collections.js or files.js in lib/; task outdated/irrelevant for current structure. Archived without action.)
14
- - [x] 2026-04-10: Fix "over-escaping" issue in write_file tool JSDoc descriptions. Problem: Backslash-heavy examples (e.g., \\\\, \\\\`) in string literals trigger syntax errors during write_file's auto-fix/syntax_check.sh (Node --check fails on invalid tokens). Seen when updating lib/genericToolset.js JSDoc. Solution: 1) Simplify descriptions: Avoid listing escapes verbatim; use "special chars verbatim" or code blocks. 2) Update auto-fix regexes to handle JSDoc contexts better (e.g., detect /** */ and skip). 3) Test: Attempt write_file with complex JSDoc, verify no false syntax fails. Prioritize before v0.0.7. (Completed 2026-04-10: Marked as completed via simplified descriptions in genericToolset.js. Verified with syntax_check lib/genericToolset.js - no errors.)
15
- - [x] 2026-04-10: Document lib/genericToolset.js with JSDoc. (Completed 2026-04-10: Added comprehensive JSDoc comments for methods, parameters, returns, and examples.)
16
- - [x] 2026-04-10: Improve JSDoc comments in lib/Session.js based on analysis - add comprehensive class-level documentation (purpose, properties, methods, usage), fix constructor JSDoc (not Prompt), document missing methods (info(), sessionList()), correct misspellings/typos in comments (que -> queue, inititialize -> initialize), ensure full coverage like recent lib/Prompt.js update. (Completed 2026-04-10: Implemented full coverage: class-level doc with example/properties/fires, fixed constructor (Session not Prompt), added docs for info()/sessionList(), corrected typos (queue, initialize), consistent style like Prompt.js. No code logic changes. Tests: Syntax OK.)
17
- - [x] 2026-04-05: Improve spawn_agent blueprint enforcement - STRICT validation (temp file, node --check, grep toolsetMode/start/serve/connect, reject non-blueprint). Update docs/prompt/spawn_agent.md PROCESS section to emphasize NO DEVIATIONS. Test spawn_agent on stoic_agent recreation (local testing only, no repo push). Preference: Test agents in local/dev environment, no git for temporary files. (Completed 2026-04-05: Strict validation enforced via updated prompt; subtasks verified with live testing.)
18
- - [x] 1. Update spawn_agent prompt/docs for strict blueprint.
19
- - [x] 2. Add JS code in spawn_agent for auto-validate (temp write/check/grep).
20
- - [x] 3. Test recreate stoic_agent.
21
- - [x] 2026-04-05: Update spawn_agent.js tool_call_description to include clear instructions for server agents to test newly spawned agents via bash scripts like './agents/new_agent.js "describe yourself"' and '--help'. Updated tool_call_description with bash test examples for direct, --help, server modes using execute_bash_script.
22
- - [x] 2026-04-04: Update spawn_agent.js blueprint/prompt to deploy new agents to ./agents/${name}.js (not bin/). Update package.json if needed. Test: spawn new agent → verify in agents/. v0.0.7.
23
- - [x] 2026-04-04: Rename agents/ → agents/ (bin/ for executables like codeDave/dave.js; agents/ for *_agent.js). Updated package.json bin refs, README, docs, imports in agents. v0.0.7 sprint. Tested post-rename.
24
- - [x] 2026-04-04: Rename spawn_dave.js to spawn_agent.js. Blueprint updated. v0.0.7.
25
- - [x] 2026-04-04: Simplify spawn_agent self-test/improve to doc-read + execute_bash_script calls (capture response, no loops) in agents/spawn_agent.js (agentDave). Completed: Simplified instructions to bash connect examples (direct/CLI/server/client/hybrid); self-test/improve via bash calls complete for v0.0.7.
26
- - [x] 2026-04-03: Replace genericToolset 'memory_recall' and 'memory_write' methods with calls to agents/memory_agent.js. This shrinks genericToolset.js and leverages specialized memory_agent prompt for better results. Ensure other agents/*_agent.js do NOT use generic memory_recall/write (update prompts/tools if needed).
27
- - [x] 2026-04-03: Verified full test suite passes after xai test fix (npm run tests or utils/test.sh) - Confirmed 100% pass on 2026-04-03
28
- - [x] 2026-04-03: Tested new --ask --connect piped/interactive and local modes. E.g., echo 'predict weather' | bin/dave.js --ask; echo 'user_info' | bin/dave.js --ask --connect. README updated with examples.
29
- - [x] 2026-04-03: Verified/updated tests for write_file tool (genericToolset.test.js, write_file_syntax.test.js) to cover backtick/template literal cases in JS files. Tests now comprehensive.
30
- - [x] v0.0.5 release complete: All preparations done (version bumped, tests 100%, changelog/docs updated, tagged, and published to npm on 2026-04-02).
31
- - [x] 2026-04-03: Enhance documentation with full how-tos for Agent networking (e.g., --connect, --serve examples, multi-agent setups)
32
- - [x] 2026-04-03: Review/fix docs accuracy for project-specific CLI/examples (dave.js, codeserver.sh)
33
- - [x] 2026-04-03: Update package.json version to "0.0.6" (Shipped v0.0.6 as-is)
34
- - [x] 2026-04-03: Review and update CHANGELOG.md with sprint completions (e.g., API integration, docs enhancements, performance opts) (Shipped v0.0.6 as-is)
35
- - [x] 2026-04-03: Run full test suite: npm run tests (verify 100% pass, no regressions) (Shipped v0.0.6 as-is)
36
- - [x] 2026-04-03: Generate types: npm run types (Shipped v0.0.6 as-is)
37
- - [x] 2026-04-03: Verify documentation completeness (README.md, docs/ section, including new sprint features) (Shipped v0.0.6 as-is)
38
- - [x] 2026-04-03: Commit all changes with message "Prepare v0.0.6 release" (Shipped v0.0.6 as-is)
39
- - [x] 2026-04-03: Create git tag v0.0.6 (Shipped v0.0.6 as-is)
40
- - [x] 2026-04-03: Publish to npm: npm run publish (Shipped v0.0.6 as-is)
41
- - [x] 2026-04-03: v0.0.6 released to npm (tests 100%, docs/CLI stabilized; manual commit/tag/publish executed)
42
- - [x] 2026-04-03: v0.0.6 fully released (git tag/commit/publish; foundations shipped)
43
- - [x] 2026-04-03: v0.0.6 released (npm published, tagged, committed)
44
-
@@ -1,121 +0,0 @@
1
- # Syntax Validation in Generic Tools
2
-
3
- ## Overview
4
- **Integration Complete**: `lib/genericToolset.js` now includes **automatic JS syntax validation** in `write_file` **and a new `syntax_check` tool** using `./utils/syntax_check.sh` for multi-language support (JS/Python/Bash/JSON). Prevents invalid code, resolves escaping issues, auto `chmod +x` shebangs. Post-write errors prompt LLM retries.
5
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
6
-
7
- **Key Benefits**:
8
- - **JS Safety**: `node --check` (in `write_file`); full multi-lang in `syntax_check`.
9
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
10
- - **Executable Prep**: Auto `chmod +x`.
11
- - **Retry-Friendly**: Descriptive errors + previews.
12
- - **Generic Access**: `toolsetMode: 'auto'` loads both.
13
-
14
- **Commit History** (relevant):
15
- - `3c8e1ae`: Initial `read_file`/`write_file`.
16
- - Recent: JS validation + `syntax_check` tool.
17
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
18
-
19
- ## write_file Tool Updates
20
-
21
- ### Description (Updated)
22
- ```
23
- Write raw content to a file strictly within the current working directory (CWD). Paths must be relative (no leading /, no ..). Content written as-is (no escaping). **AUTO-VALIDATES JS FILES** with `node --check`; chmod +x shebangs. Retries syntax errors force LLM fix.
24
- ```
25
-
26
- ### Examples
27
- **Success** (CLI/Agent):
28
- ```bash
29
- echo 'const x = \`hi\`; console.log(x);' | agent.directCall("Use write_file on test.js with this content")
30
- # Returns: "Successfully wrote to 'test.js' (42 bytes). ✓ JS syntax OK"
31
- ```
32
-
33
- **Failure + Retry**:
34
- ```javascript
35
- // LLM generates invalid:
36
- const msg = `Hello ${name`; // Missing `
37
- ```
38
- **Error**:
39
- ```
40
- ❌ JS SYNTAX ERROR in 'test.js' (node --check failed):
41
- SyntaxError: Unexpected token '}'
42
-
43
- PREVIEW:
44
- const msg = `Hello ${name
45
- ...
46
-
47
- ... Fix escaping/backticks in template literals (use \\\\` for \` in JS strings) and retry.
48
- ```
49
- **LLM Sees → Fixes**: Uses `"Hello \${name}"` or proper `` \` ``.
50
-
51
- **Shebang**:
52
- ```javascript
53
- content: '#!/usr/bin/env node\nconst hello = () => console.log("Hi");'
54
- # Returns: "... ✓ JS syntax OK ✓ chmod +x"
55
- ```
56
-
57
- ## New: syntax_check Tool
58
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
59
-
60
- **Description**:
61
- ```
62
- Validate syntax of a file (JS, Python, Bash/Sh, JSON). Detects language from extension/shebang. Uses native checkers... Exit 1 on fail.
63
- ```
64
-
65
- ### Parameters
66
- ```json
67
- {
68
- "type": "object",
69
- "properties": { "file": { "type": "string" } },
70
- "required": ["file"]
71
- }
72
- ```
73
-
74
- ### Examples
75
- **Agent Call**:
76
- ```
77
- agent.directCall("Use syntax_check on test.js") → "🔍 Validating test.js (lang: js)\n✅ JS OK\n✅ Syntax validation passed for test.js"
78
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
79
- ```
80
-
81
- **Multi-Lang**:
82
- - **Python**: `syntax_check script.py` → `✅ Python OK`
83
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
84
- - **Bash**: `syntax_check script.sh` → `✅ Bash OK` ( + Shellcheck if avail.)
85
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
86
- - **JSON**: `syntax_check config.json` → `✅ JSON OK`
87
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
88
- - **Fail**: Invalid JSON → `❌ JSON invalid`
89
-
90
- **Integration**: Post-`write_file`, agent can call `syntax_check(file)` for non-JS.
91
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
92
-
93
- ## utils/syntax_check.sh (Underlying Script)
94
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
95
- [Full source in prior doc]. Detects lang, runs checkers. Standalone/executable.
96
-
97
- ### Usage (Direct)
98
- ```bash
99
- ./utils/syntax_check.sh test.js # ✅ JS OK
100
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
101
- ./utils/syntax_check.sh bad.py # ❌ Python syntax error
102
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
103
- ```
104
-
105
- ## Agent Workflow Example
106
- ```
107
- User: "Create & validate test.js: const add = (a,b) => a+b; export {add};"
108
- Agent:
109
- 1. write_file(test.js, content) → ✓ JS OK
110
- 2. syntax_check(test.js) → ✅ (redundant but confirms)
111
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
112
- ```
113
-
114
- ## Cross-Links
115
- - [ToolSet](../toolset.md#generic-tools) ← [Linked below](#update-to-toolsetmd)
116
- - [AgentManager](../agent-manager.md)
117
- - Source: [lib/genericToolset.js](../lib/genericToolset.js), [utils/syntax_check.sh](../utils/syntax_check.sh)
118
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).
119
-
120
- **Updated**: March 27, 2026 (syntax_check integrated).
121
- **Path Note**: Uses `__dirname` for utils/; resolves files to `process.cwd()`. See [path-resolution-best-practices.md](path-resolution-best-practices.md).