@j-o-r/hello-dave 0.0.7 → 0.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/TODO.md +13 -0
- package/docs/agent-manager.md +244 -0
- package/docs/bin-dave.md +62 -0
- package/docs/codeserver-pattern.md +191 -0
- package/docs/generic-toolset.md +326 -0
- package/docs/howtos/agent-networking.md +253 -0
- package/docs/howtos/spawn-agents.md.bak +200 -0
- package/docs/howtos/spawn-agents.md.bak_new +200 -0
- package/docs/jsdoc-best-practices.md +278 -0
- package/docs/multi-agent-clusters.md +265 -0
- package/docs/multi-agent-clusters.md.bak +229 -0
- package/docs/path-resolution-best-practices.md +104 -0
- package/docs/project-overview.md +67 -0
- package/docs/prompt/spawn_agent.md +173 -0
- package/docs/prompt/spawn_agent.md.bak +201 -0
- package/docs/prompt-class.md +141 -0
- package/docs/suggestions.md +38 -0
- package/docs/todo-archive-v0.0.8.md +1 -0
- package/docs/todo-archive.md +44 -0
- package/docs/tools-syntax-validation.md +121 -0
- package/docs/toolset.md +164 -0
- package/docs/xai-responses.md +111 -0
- package/docs/xai_collections.md +106 -0
- package/lib/genericToolset.js +26 -13
- package/package.json +1 -1
- package/README.md.bak +0 -218
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# Spawning and Managing Agents
|
|
2
|
+
|
|
3
|
+
This guide covers how to directly call agents, use the Spawn Dave workflow, and utilize Spawn Agent for creating, testing, and improving agents. It includes practical examples in Bash and JavaScript, as well as concepts for self-improvement loops. For foundational concepts on agent interactions, refer to [agent-networking.md](./agent-networking.md).
|
|
4
|
+
|
|
5
|
+
## 1. Direct Agent Calls
|
|
6
|
+
|
|
7
|
+
Direct agent calls allow you to invoke specific agents from the command line or scripts without spawning a full workflow. This is useful for quick queries or testing individual agent behaviors.
|
|
8
|
+
|
|
9
|
+
### Real Project Example: Calling GPT Agent
|
|
10
|
+
|
|
11
|
+
In the project, you can directly invoke the GPT agent using the provided script.
|
|
12
|
+
|
|
13
|
+
**JavaScript Snippet (examples/gpt_agent.js):**
|
|
14
|
+
```javascript
|
|
15
|
+
// examples/gpt_agent.js
|
|
16
|
+
const { createAgent } = require('../lib/agent-factory'); // Assuming agent factory module
|
|
17
|
+
|
|
18
|
+
async function runAgent(query) {
|
|
19
|
+
const agent = createAgent('gpt'); // Initialize GPT agent
|
|
20
|
+
const response = await agent.process(query);
|
|
21
|
+
console.log(response);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (require.main === module) {
|
|
25
|
+
const query = process.argv[2];
|
|
26
|
+
if (!query) {
|
|
27
|
+
console.error('Usage: node examples/gpt_agent.js "your query"');
|
|
28
|
+
process.exit(1);
|
|
29
|
+
}
|
|
30
|
+
runAgent(query).catch(console.error);
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
**Bash Command to Run:**
|
|
35
|
+
```bash
|
|
36
|
+
node examples/gpt_agent.js "What is the capital of France?"
|
|
37
|
+
# Output: Paris (or similar GPT response)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
This is a real example from the project, enabling straightforward execution. Extend it by passing additional flags for configuration, e.g., `--model gpt-4`.
|
|
41
|
+
|
|
42
|
+
## 2. Spawn Dave Workflow
|
|
43
|
+
|
|
44
|
+
The Spawn Dave workflow (examples/spawn_dave.js) is a predefined sequence for initializing a "Dave" agent instance, which handles complex tasks like multi-step reasoning or integration with external tools.
|
|
45
|
+
|
|
46
|
+
### Overview
|
|
47
|
+
- **Purpose:** Spawn a Dave agent that can orchestrate sub-agents or workflows.
|
|
48
|
+
- **Key Features:** Tool integration, state management, and logging.
|
|
49
|
+
|
|
50
|
+
### Example: Running Spawn Dave
|
|
51
|
+
|
|
52
|
+
**JavaScript Snippet (examples/spawn_dave.js):**
|
|
53
|
+
```javascript
|
|
54
|
+
// examples/spawn_dave.js
|
|
55
|
+
const { spawnDave } = require('../workflows/spawn-dave'); // Import workflow
|
|
56
|
+
|
|
57
|
+
async function main(task) {
|
|
58
|
+
const dave = await spawnDave({
|
|
59
|
+
tools: ['web_search', 'code_executor'],
|
|
60
|
+
model: 'gpt-4'
|
|
61
|
+
});
|
|
62
|
+
const outcome = await dave.execute(task);
|
|
63
|
+
console.log('Dave's response:', outcome);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (require.main === module) {
|
|
67
|
+
const task = process.argv[2] || 'Default task: Analyze market trends.';
|
|
68
|
+
main(task).catch(console.error);
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
**Bash Command:**
|
|
73
|
+
```bash
|
|
74
|
+
node examples/spawn_dave.js "Summarize recent AI advancements."
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
This workflow automatically handles agent lifecycle: spawn, execute, and cleanup. For networking multiple Daves, see [agent-networking.md](./agent-networking.md).
|
|
78
|
+
|
|
79
|
+
## 3. Spawn Agent (examples/spawn_agent.js or agentDave)
|
|
80
|
+
|
|
81
|
+
Spawn Agent is a utility for dynamically creating, testing, and improving agents based on outcomes. It's ideal for iterative development, where agents self-improve through workflows and tests. The entry point is `examples/spawn_agent.js`, which can be aliased as `agentDave` via the `package.json` scripts (e.g., `npm run agentDave -- create ...`).
|
|
82
|
+
|
|
83
|
+
### Core Functionality
|
|
84
|
+
- **Creating Agents:** Define agent specs (prompts, tools, models) and spawn instances.
|
|
85
|
+
- **Testing:** Run predefined tests to evaluate performance.
|
|
86
|
+
- **Improving:** Use feedback loops to refine prompts or configurations based on outcomes.
|
|
87
|
+
- **Self-Improvement Loops:** Agents can analyze their own outputs and suggest updates.
|
|
88
|
+
|
|
89
|
+
### Example: Basic Spawn and Test
|
|
90
|
+
|
|
91
|
+
**Bash Usage (via examples/spawn_agent.js or npm run agentDave):**
|
|
92
|
+
```bash
|
|
93
|
+
# Spawn a new agent for math tasks
|
|
94
|
+
node examples/spawn_agent.js create --name math-solver --tools calculator --prompt "Solve math problems step-by-step."
|
|
95
|
+
|
|
96
|
+
# Or using alias
|
|
97
|
+
npm run agentDave -- create --name math-solver --tools calculator --prompt "Solve math problems step-by-step."
|
|
98
|
+
|
|
99
|
+
# Test the agent
|
|
100
|
+
node examples/spawn_agent.js test --name math-solver --input "2+2*3" --expected 8
|
|
101
|
+
|
|
102
|
+
# Improve based on outcomes
|
|
103
|
+
node examples/spawn_agent.js improve --name math-solver --feedback "Failed on algebra; add quadratic formula."
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
**JavaScript Integration (Custom Script):**
|
|
107
|
+
```javascript
|
|
108
|
+
// test-spawn.js
|
|
109
|
+
const { spawnAgent, testAgent, improveAgent } = require('../examples/spawn_agent');
|
|
110
|
+
|
|
111
|
+
async function workflow() {
|
|
112
|
+
// Create
|
|
113
|
+
const agent = await spawnAgent({
|
|
114
|
+
name: 'researcher',
|
|
115
|
+
tools: ['web_search', 'browse_page'],
|
|
116
|
+
prompt: 'Conduct thorough research on topics.'
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
// Test
|
|
120
|
+
const testResult = await testAgent(agent, { query: 'Latest on quantum computing', expected: /qubits/ });
|
|
121
|
+
console.log('Test passed:', testResult.passed);
|
|
122
|
+
|
|
123
|
+
// Self-Improvement Loop
|
|
124
|
+
if (!testResult.passed) {
|
|
125
|
+
const improvements = await improveAgent(agent, testResult.feedback);
|
|
126
|
+
console.log('Suggested improvements:', improvements);
|
|
127
|
+
// Re-spawn with updates
|
|
128
|
+
const updatedAgent = await spawnAgent({ ...agent.config, prompt: improvements.newPrompt });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
workflow().catch(console.error);
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
**Running the Script:**
|
|
136
|
+
```bash
|
|
137
|
+
node test-spawn.js
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### Self-Improvement Loops
|
|
141
|
+
Implement loops where agents evaluate their performance using tools like `test_agent.js` for testing and `memory_agent` for storing past evaluations and improvements.
|
|
142
|
+
|
|
143
|
+
1. **Execute Task:** Run agent on input.
|
|
144
|
+
2. **Evaluate Outcome:** Use `test_agent.js` to compare against benchmarks.
|
|
145
|
+
3. **Store and Generate Improvements:** Leverage `memory_agent` to recall past failures and suggest refinements.
|
|
146
|
+
4. **Update and Iterate:** Apply changes and re-test.
|
|
147
|
+
|
|
148
|
+
**Example Loop in JS (using test_agent.js and memory_agent):**
|
|
149
|
+
```javascript
|
|
150
|
+
// self-improve-loop.js
|
|
151
|
+
const { spawnAgent } = require('../examples/spawn_agent');
|
|
152
|
+
const { testAgent } = require('../examples/test_agent');
|
|
153
|
+
const { memoryAgent } = require('../lib/memory_agent'); // Assuming memory agent for evaluation storage
|
|
154
|
+
|
|
155
|
+
async function selfImproveLoop(initialConfig, task, maxIterations = 5) {
|
|
156
|
+
let agent = await spawnAgent(initialConfig);
|
|
157
|
+
const memory = memoryAgent(); // For storing evaluations
|
|
158
|
+
|
|
159
|
+
for (let i = 0; i < maxIterations; i++) {
|
|
160
|
+
const result = await agent.execute(task);
|
|
161
|
+
const testResult = await testAgent(agent, { input: task, output: result, expected: /desired pattern/ });
|
|
162
|
+
|
|
163
|
+
// Store in memory
|
|
164
|
+
await memory.store({ iteration: i, test: testResult });
|
|
165
|
+
|
|
166
|
+
if (testResult.passed) {
|
|
167
|
+
console.log('Improvement loop converged.');
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Retrieve past suggestions from memory
|
|
172
|
+
const pastFeedback = await memory.retrieve('improvements');
|
|
173
|
+
const improvements = await agent.suggestImprovements(testResult.feedback, pastFeedback);
|
|
174
|
+
agent.updateConfig(improvements);
|
|
175
|
+
|
|
176
|
+
console.log(`Iteration ${i + 1}: Updated agent config.`);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return agent;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Usage
|
|
183
|
+
selfImproveLoop(
|
|
184
|
+
{ name: 'improving-agent', prompt: 'Initial prompt.' },
|
|
185
|
+
'Complex query here.'
|
|
186
|
+
).catch(console.error);
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
For scaling to networks of agents, integrate with concepts from [agent-networking.md](./agent-networking.md), such as peer-to-peer spawning.
|
|
190
|
+
|
|
191
|
+
## Best Practices
|
|
192
|
+
- Always backup agent configs before improvements.
|
|
193
|
+
- Use version control for agent definitions (e.g., JSON specs in `./agents/`).
|
|
194
|
+
- Monitor resource usage in loops to avoid infinite iterations.
|
|
195
|
+
- Test in isolated environments.
|
|
196
|
+
|
|
197
|
+
## Upcoming Features (v0.0.7)
|
|
198
|
+
For planned enhancements related to agent spawning, testing, and self-improvement, refer to the tasks outlined in [TODO.md](../TODO.md). This includes improvements to loop efficiency, better memory integration, and expanded tool support.
|
|
199
|
+
|
|
200
|
+
For more on agent workflows, explore related docs like [agent-networking.md](./agent-networking.md).
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# Spawning and Managing Agents
|
|
2
|
+
|
|
3
|
+
This guide covers how to directly call agents, use the Spawn Dave workflow, and utilize Spawn Agent for creating, testing, and improving agents. It includes practical examples in Bash and JavaScript, as well as concepts for self-improvement loops. For foundational concepts on agent interactions, refer to [agent-networking.md](./agent-networking.md).
|
|
4
|
+
|
|
5
|
+
## 1. Direct Agent Calls
|
|
6
|
+
|
|
7
|
+
Direct agent calls allow you to invoke specific agents from the command line or scripts without spawning a full workflow. This is useful for quick queries or testing individual agent behaviors.
|
|
8
|
+
|
|
9
|
+
### Real Project Example: Calling GPT Agent
|
|
10
|
+
|
|
11
|
+
In the project, you can directly invoke the GPT agent using the provided script.
|
|
12
|
+
|
|
13
|
+
**JavaScript Snippet (examples/gpt_agent.js):**
|
|
14
|
+
```javascript
|
|
15
|
+
// examples/gpt_agent.js
|
|
16
|
+
const { createAgent } = require('../lib/agent-factory'); // Assuming agent factory module
|
|
17
|
+
|
|
18
|
+
async function runAgent(query) {
|
|
19
|
+
const agent = createAgent('gpt'); // Initialize GPT agent
|
|
20
|
+
const response = await agent.process(query);
|
|
21
|
+
console.log(response);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (require.main === module) {
|
|
25
|
+
const query = process.argv[2];
|
|
26
|
+
if (!query) {
|
|
27
|
+
console.error('Usage: node examples/gpt_agent.js "your query"');
|
|
28
|
+
process.exit(1);
|
|
29
|
+
}
|
|
30
|
+
runAgent(query).catch(console.error);
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
**Bash Command to Run:**
|
|
35
|
+
```bash
|
|
36
|
+
node examples/gpt_agent.js "What is the capital of France?"
|
|
37
|
+
# Output: Paris (or similar GPT response)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
This is a real example from the project, enabling straightforward execution. Extend it by passing additional flags for configuration, e.g., `--model gpt-4`.
|
|
41
|
+
|
|
42
|
+
## 2. Spawn Dave Workflow
|
|
43
|
+
|
|
44
|
+
The Spawn Dave workflow (examples/spawn_dave.js) is a predefined sequence for initializing a "Dave" agent instance, which handles complex tasks like multi-step reasoning or integration with external tools.
|
|
45
|
+
|
|
46
|
+
### Overview
|
|
47
|
+
- **Purpose:** Spawn a Dave agent that can orchestrate sub-agents or workflows.
|
|
48
|
+
- **Key Features:** Tool integration, state management, and logging.
|
|
49
|
+
|
|
50
|
+
### Example: Running Spawn Dave
|
|
51
|
+
|
|
52
|
+
**JavaScript Snippet (examples/spawn_dave.js):**
|
|
53
|
+
```javascript
|
|
54
|
+
// examples/spawn_dave.js
|
|
55
|
+
const { spawnDave } = require('../workflows/spawn-dave'); // Import workflow
|
|
56
|
+
|
|
57
|
+
async function main(task) {
|
|
58
|
+
const dave = await spawnDave({
|
|
59
|
+
tools: ['web_search', 'code_executor'],
|
|
60
|
+
model: 'gpt-4'
|
|
61
|
+
});
|
|
62
|
+
const outcome = await dave.execute(task);
|
|
63
|
+
console.log('Dave's response:', outcome);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (require.main === module) {
|
|
67
|
+
const task = process.argv[2] || 'Default task: Analyze market trends.';
|
|
68
|
+
main(task).catch(console.error);
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
**Bash Command:**
|
|
73
|
+
```bash
|
|
74
|
+
node examples/spawn_dave.js "Summarize recent AI advancements."
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
This workflow automatically handles agent lifecycle: spawn, execute, and cleanup. For networking multiple Daves, see [agent-networking.md](./agent-networking.md).
|
|
78
|
+
|
|
79
|
+
## 3. Spawn Agent (examples/spawn_agent.js or agentDave)
|
|
80
|
+
|
|
81
|
+
Spawn Agent is a utility for dynamically creating, testing, and improving agents based on outcomes. It's ideal for iterative development, where agents self-improve through workflows and tests. The entry point is `examples/spawn_agent.js`, which can be aliased as `agentDave` via the `package.json` scripts (e.g., `npm run agentDave -- create ...`).
|
|
82
|
+
|
|
83
|
+
### Core Functionality
|
|
84
|
+
- **Creating Agents:** Define agent specs (prompts, tools, models) and spawn instances.
|
|
85
|
+
- **Testing:** Run predefined tests to evaluate performance.
|
|
86
|
+
- **Improving:** Use feedback loops to refine prompts or configurations based on outcomes.
|
|
87
|
+
- **Self-Improvement Loops:** Agents can analyze their own outputs and suggest updates.
|
|
88
|
+
|
|
89
|
+
### Example: Basic Spawn and Test
|
|
90
|
+
|
|
91
|
+
**Bash Usage (via examples/spawn_agent.js or npm run agentDave):**
|
|
92
|
+
```bash
|
|
93
|
+
# Spawn a new agent for math tasks
|
|
94
|
+
node examples/spawn_agent.js create --name math-solver --tools calculator --prompt "Solve math problems step-by-step."
|
|
95
|
+
|
|
96
|
+
# Or using alias
|
|
97
|
+
npm run agentDave -- create --name math-solver --tools calculator --prompt "Solve math problems step-by-step."
|
|
98
|
+
|
|
99
|
+
# Test the agent
|
|
100
|
+
node examples/spawn_agent.js test --name math-solver --input "2+2*3" --expected 8
|
|
101
|
+
|
|
102
|
+
# Improve based on outcomes
|
|
103
|
+
node examples/spawn_agent.js improve --name math-solver --feedback "Failed on algebra; add quadratic formula."
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
**JavaScript Integration (Custom Script):**
|
|
107
|
+
```javascript
|
|
108
|
+
// test-spawn.js
|
|
109
|
+
const { spawnAgent, testAgent, improveAgent } = require('../examples/spawn_agent');
|
|
110
|
+
|
|
111
|
+
async function workflow() {
|
|
112
|
+
// Create
|
|
113
|
+
const agent = await spawnAgent({
|
|
114
|
+
name: 'researcher',
|
|
115
|
+
tools: ['web_search', 'browse_page'],
|
|
116
|
+
prompt: 'Conduct thorough research on topics.'
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
// Test
|
|
120
|
+
const testResult = await testAgent(agent, { query: 'Latest on quantum computing', expected: /qubits/ });
|
|
121
|
+
console.log('Test passed:', testResult.passed);
|
|
122
|
+
|
|
123
|
+
// Self-Improvement Loop
|
|
124
|
+
if (!testResult.passed) {
|
|
125
|
+
const improvements = await improveAgent(agent, testResult.feedback);
|
|
126
|
+
console.log('Suggested improvements:', improvements);
|
|
127
|
+
// Re-spawn with updates
|
|
128
|
+
const updatedAgent = await spawnAgent({ ...agent.config, prompt: improvements.newPrompt });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
workflow().catch(console.error);
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
**Running the Script:**
|
|
136
|
+
```bash
|
|
137
|
+
node test-spawn.js
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### Self-Improvement Loops
|
|
141
|
+
Implement loops where agents evaluate their performance using tools like `test_agent.js` for testing and `memory_agent` for storing past evaluations and improvements.
|
|
142
|
+
|
|
143
|
+
1. **Execute Task:** Run agent on input.
|
|
144
|
+
2. **Evaluate Outcome:** Use `test_agent.js` to compare against benchmarks.
|
|
145
|
+
3. **Store and Generate Improvements:** Leverage `memory_agent` to recall past failures and suggest refinements.
|
|
146
|
+
4. **Update and Iterate:** Apply changes and re-test.
|
|
147
|
+
|
|
148
|
+
**Example Loop in JS (using test_agent.js and memory_agent):**
|
|
149
|
+
```javascript
|
|
150
|
+
// self-improve-loop.js
|
|
151
|
+
const { spawnAgent } = require('../examples/spawn_agent');
|
|
152
|
+
const { testAgent } = require('../examples/test_agent');
|
|
153
|
+
const { memoryAgent } = require('../lib/memory_agent'); // Assuming memory agent for evaluation storage
|
|
154
|
+
|
|
155
|
+
async function selfImproveLoop(initialConfig, task, maxIterations = 5) {
|
|
156
|
+
let agent = await spawnAgent(initialConfig);
|
|
157
|
+
const memory = memoryAgent(); // For storing evaluations
|
|
158
|
+
|
|
159
|
+
for (let i = 0; i < maxIterations; i++) {
|
|
160
|
+
const result = await agent.execute(task);
|
|
161
|
+
const testResult = await testAgent(agent, { input: task, output: result, expected: /desired pattern/ });
|
|
162
|
+
|
|
163
|
+
// Store in memory
|
|
164
|
+
await memory.store({ iteration: i, test: testResult });
|
|
165
|
+
|
|
166
|
+
if (testResult.passed) {
|
|
167
|
+
console.log('Improvement loop converged.');
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Retrieve past suggestions from memory
|
|
172
|
+
const pastFeedback = await memory.retrieve('improvements');
|
|
173
|
+
const improvements = await agent.suggestImprovements(testResult.feedback, pastFeedback);
|
|
174
|
+
agent.updateConfig(improvements);
|
|
175
|
+
|
|
176
|
+
console.log(`Iteration ${i + 1}: Updated agent config.`);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return agent;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Usage
|
|
183
|
+
selfImproveLoop(
|
|
184
|
+
{ name: 'improving-agent', prompt: 'Initial prompt.' },
|
|
185
|
+
'Complex query here.'
|
|
186
|
+
).catch(console.error);
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
For scaling to networks of agents, integrate with concepts from [agent-networking.md](./agent-networking.md), such as peer-to-peer spawning.
|
|
190
|
+
|
|
191
|
+
## Best Practices
|
|
192
|
+
- Always backup agent configs before improvements.
|
|
193
|
+
- Use version control for agent definitions (e.g., JSON specs in `./agents/`).
|
|
194
|
+
- Monitor resource usage in loops to avoid infinite iterations.
|
|
195
|
+
- Test in isolated environments.
|
|
196
|
+
|
|
197
|
+
## Upcoming Features (v0.0.7)
|
|
198
|
+
For planned enhancements related to agent spawning, testing, and self-improvement, refer to the tasks outlined in [TODO.md](../TODO.md). This includes improvements to loop efficiency, better memory integration, and expanded tool support.
|
|
199
|
+
|
|
200
|
+
For more on agent workflows, explore related docs like [agent-networking.md](./agent-networking.md).
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
# JSDoc Best Practices for JavaScript Modules
|
|
2
|
+
|
|
3
|
+
## Introduction
|
|
4
|
+
|
|
5
|
+
JSDoc is a markup language used to annotate JavaScript source code files. It allows developers to document their code in a structured way, generating documentation that is readable by humans and machines alike. This is particularly valuable for JavaScript modules, especially toolsets or utility libraries, where clear documentation helps users understand APIs, types, and usage.
|
|
6
|
+
|
|
7
|
+
Best practices ensure documentation is consistent, comprehensive, and maintainable. Key benefits include:
|
|
8
|
+
- Improved code readability and maintainability.
|
|
9
|
+
- IDE support for autocompletion, type checking, and hover tooltips.
|
|
10
|
+
- Generation of static HTML documentation sites.
|
|
11
|
+
- Reusability across teams and projects.
|
|
12
|
+
|
|
13
|
+
This guide focuses on documenting functions, classes, parameters, returns, and types, with examples tailored to utility libraries.
|
|
14
|
+
|
|
15
|
+
## Documenting Modules
|
|
16
|
+
|
|
17
|
+
Use the `@module` tag to mark a file as a module. All symbols in the file become module members. For utility libraries, document exports explicitly.
|
|
18
|
+
|
|
19
|
+
### Example: Exporting Functions in a Utility Module
|
|
20
|
+
```javascript
|
|
21
|
+
/**
|
|
22
|
+
* @module utils/string
|
|
23
|
+
* String manipulation utilities.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Formats a string by capitalizing the first letter.
|
|
28
|
+
* @param {string} str - The input string.
|
|
29
|
+
* @returns {string} The formatted string.
|
|
30
|
+
* @example
|
|
31
|
+
* capitalize("hello world"); // "Hello world"
|
|
32
|
+
*/
|
|
33
|
+
function capitalize(str) {
|
|
34
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
module.exports = { capitalize };
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
This creates a documented module `module:utils/string` with exported member `module:utils/string.capitalize`.
|
|
41
|
+
|
|
42
|
+
### Namespaces for Organization
|
|
43
|
+
For larger libraries, use `@namespace` to group related utilities.
|
|
44
|
+
```javascript
|
|
45
|
+
/**
|
|
46
|
+
* @module math
|
|
47
|
+
* @namespace math.utils
|
|
48
|
+
*/
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Documenting Functions
|
|
52
|
+
|
|
53
|
+
Functions are the core of utility libraries. Use `@param` for parameters, `@returns` for return values, and include types and descriptions.
|
|
54
|
+
|
|
55
|
+
### Basic Function Documentation
|
|
56
|
+
```javascript
|
|
57
|
+
/**
|
|
58
|
+
* Adds two numbers.
|
|
59
|
+
* @param {number} a - The first number.
|
|
60
|
+
* @param {number} b - The second number.
|
|
61
|
+
* @returns {number} The sum of a and b.
|
|
62
|
+
* @throws {Error} If inputs are not numbers.
|
|
63
|
+
* @example
|
|
64
|
+
* add(2, 3); // 5
|
|
65
|
+
*/
|
|
66
|
+
function add(a, b) {
|
|
67
|
+
if (typeof a !== "number" || typeof b !== "number") {
|
|
68
|
+
throw new Error("Inputs must be numbers");
|
|
69
|
+
}
|
|
70
|
+
return a + b;
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Optional Parameters and Defaults
|
|
75
|
+
```javascript
|
|
76
|
+
/**
|
|
77
|
+
* Formats a number with thousand separators.
|
|
78
|
+
* @param {number} value - The number to format.
|
|
79
|
+
* @param {string} [separator=","] - The separator (default: comma).
|
|
80
|
+
* @returns {string} The formatted string.
|
|
81
|
+
* @example
|
|
82
|
+
* formatNumber(1000); // "1,000"
|
|
83
|
+
* formatNumber(1000, "."); // "1.000"
|
|
84
|
+
*/
|
|
85
|
+
function formatNumber(value, separator = ",") {
|
|
86
|
+
return value.toLocaleString("en-US", { separator });
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Variadic (Rest) Parameters
|
|
91
|
+
```javascript
|
|
92
|
+
/**
|
|
93
|
+
* Sums multiple numbers.
|
|
94
|
+
* @param {...number} nums - Numbers to sum.
|
|
95
|
+
* @returns {number} The total sum.
|
|
96
|
+
* @example
|
|
97
|
+
* sum(1, 2, 3); // 6
|
|
98
|
+
*/
|
|
99
|
+
function sum(...nums) {
|
|
100
|
+
return nums.reduce((acc, n) => acc + n, 0);
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Asynchronous Functions
|
|
105
|
+
```javascript
|
|
106
|
+
/**
|
|
107
|
+
* Fetches data asynchronously.
|
|
108
|
+
* @param {string} url - The URL to fetch.
|
|
109
|
+
* @returns {Promise<Object>} A promise resolving to the data.
|
|
110
|
+
*/
|
|
111
|
+
async function fetchData(url) {
|
|
112
|
+
const response = await fetch(url);
|
|
113
|
+
return response.json();
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Documenting Classes
|
|
118
|
+
|
|
119
|
+
For classes in utility libraries (e.g., a Validator class), document constructors, methods, and properties. JSDoc 3.4+ auto-detects ES6 classes.
|
|
120
|
+
|
|
121
|
+
### Simple Class Example
|
|
122
|
+
```javascript
|
|
123
|
+
/**
|
|
124
|
+
* A utility class for validating inputs.
|
|
125
|
+
*/
|
|
126
|
+
class Validator {
|
|
127
|
+
/**
|
|
128
|
+
* Creates a new Validator instance.
|
|
129
|
+
* @param {Object} options - Configuration options.
|
|
130
|
+
* @param {boolean} [options.strict=false] - Strict mode.
|
|
131
|
+
*/
|
|
132
|
+
constructor(options = {}) {
|
|
133
|
+
this.strict = options.strict || false;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Validates an email address.
|
|
138
|
+
* @param {string} email - The email to validate.
|
|
139
|
+
* @returns {boolean} True if valid.
|
|
140
|
+
* @memberof Validator
|
|
141
|
+
*/
|
|
142
|
+
validateEmail(email) {
|
|
143
|
+
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
144
|
+
return regex.test(email);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Static method to validate without instance.
|
|
149
|
+
* @param {string} email - The email to validate.
|
|
150
|
+
* @returns {boolean} True if valid.
|
|
151
|
+
* @static
|
|
152
|
+
*/
|
|
153
|
+
static isValidEmail(email) {
|
|
154
|
+
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
155
|
+
return regex.test(email);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Extending Classes
|
|
161
|
+
```javascript
|
|
162
|
+
/**
|
|
163
|
+
* Advanced validator extending basic Validator.
|
|
164
|
+
* @extends Validator
|
|
165
|
+
*/
|
|
166
|
+
class AdvancedValidator extends Validator {
|
|
167
|
+
/**
|
|
168
|
+
* @param {Object} options - Options.
|
|
169
|
+
* @param {number} options.maxLength - Max length.
|
|
170
|
+
*/
|
|
171
|
+
constructor(options) {
|
|
172
|
+
super(options);
|
|
173
|
+
this.maxLength = options.maxLength || 255;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Validates with length check.
|
|
178
|
+
* @param {string} str - The string.
|
|
179
|
+
* @returns {boolean} True if valid.
|
|
180
|
+
* @override
|
|
181
|
+
*/
|
|
182
|
+
validateEmail(str) {
|
|
183
|
+
return super.validateEmail(str) && str.length <= this.maxLength;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
## Type Annotations
|
|
189
|
+
|
|
190
|
+
Use types in curly braces `{}` for precision. Define complex types with `@typedef` for reuse.
|
|
191
|
+
|
|
192
|
+
### Basic Types
|
|
193
|
+
- Primitives: `{string}`, `{number}`, `{boolean}`
|
|
194
|
+
- Arrays: `{string[]}` or `{Array.<string>}`
|
|
195
|
+
- Objects: `{Object}`
|
|
196
|
+
- Unions: `{string|number}`
|
|
197
|
+
- Nullable: `{string?}`
|
|
198
|
+
- Any: `{*}`
|
|
199
|
+
- Promises: `{Promise<string>}`
|
|
200
|
+
|
|
201
|
+
### Variables and Properties
|
|
202
|
+
```javascript
|
|
203
|
+
/** @type {string} */
|
|
204
|
+
let message = "Hello";
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* User object type.
|
|
208
|
+
* @typedef {Object} User
|
|
209
|
+
* @property {string} name - User name.
|
|
210
|
+
* @property {number} age - User age.
|
|
211
|
+
* @property {string[]} hobbies - User hobbies.
|
|
212
|
+
*/
|
|
213
|
+
|
|
214
|
+
/** @type {User} */
|
|
215
|
+
const user = { name: "Alice", age: 30, hobbies: ["reading"] };
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
### In Parameters and Returns
|
|
219
|
+
Types are integrated into `@param` and `@returns`:
|
|
220
|
+
```javascript
|
|
221
|
+
/**
|
|
222
|
+
* Processes a user.
|
|
223
|
+
* @param {User} user - The user object.
|
|
224
|
+
* @returns {User} Processed user.
|
|
225
|
+
*/
|
|
226
|
+
function processUser(user) {
|
|
227
|
+
return { ...user, processed: true };
|
|
228
|
+
}
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
## Advanced: Typedefs for Complex Types
|
|
232
|
+
For utility libraries, define reusable types:
|
|
233
|
+
```javascript
|
|
234
|
+
/**
|
|
235
|
+
* Response from API.
|
|
236
|
+
* @typedef {Object} ApiResponse
|
|
237
|
+
* @property {boolean} success - Success flag.
|
|
238
|
+
* @property {any} data - Response data.
|
|
239
|
+
* @property {string} [error] - Error message if failed.
|
|
240
|
+
*/
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Fetches API data.
|
|
244
|
+
* @param {string} endpoint - API endpoint.
|
|
245
|
+
* @returns {Promise<ApiResponse>} The API response.
|
|
246
|
+
*/
|
|
247
|
+
async function apiFetch(endpoint) {
|
|
248
|
+
// Implementation
|
|
249
|
+
}
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
## Best Practices
|
|
253
|
+
|
|
254
|
+
1. **Consistency**: Use the same style for all docs (e.g., always include types, descriptions).
|
|
255
|
+
2. **Readability**:
|
|
256
|
+
- Start descriptions with a capital letter and end with a period.
|
|
257
|
+
- Use hyphens for parameter descriptions: `@param {type} name - Description.`
|
|
258
|
+
- Keep comments concise but informative.
|
|
259
|
+
3. **Completeness**: Document all public APIs; use `@private` or `@internal` for internals.
|
|
260
|
+
4. **Examples**: Include `@example` blocks for complex usage.
|
|
261
|
+
5. **Namespaces**: Group related items with `@namespace` and `@memberOf` for large libraries.
|
|
262
|
+
```javascript
|
|
263
|
+
/**
|
|
264
|
+
* @namespace utils.array
|
|
265
|
+
* Array utility functions.
|
|
266
|
+
*/
|
|
267
|
+
```
|
|
268
|
+
6. **Error Handling**: Use `@throws` for possible exceptions.
|
|
269
|
+
7. **Links**: Use `@see` for related items, `@link` for external.
|
|
270
|
+
8. **IDE Integration**: Test in VS Code or WebStorm for type hints.
|
|
271
|
+
9. **Generation**: Use JSDoc CLI (`jsdoc yourfile.js`) to generate HTML docs. Configure with `jsdoc.json` for templates like docdash.
|
|
272
|
+
10. **Maintenance**: Update docs alongside code changes; treat as code.
|
|
273
|
+
|
|
274
|
+
For toolsets/utility libraries, prioritize documenting exports and focus on user-facing APIs to make integration easy.
|
|
275
|
+
|
|
276
|
+
## References
|
|
277
|
+
- [Official JSDoc Documentation](https://jsdoc.app/)
|
|
278
|
+
- [JSDoc Tags](https://jsdoc.app/tags-*)
|