-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
224 lines (189 loc) · 7.62 KB
/
index.js
File metadata and controls
224 lines (189 loc) · 7.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
// Configuration File
const CONFIG_FILE = path.join(__dirname, 'dmfr_config.json');
// Default Configuration
const DEFAULT_CONFIG = {
"main_model": "google/gemini-3-pro-preview",
"worker_chain": [
"gemini-2.0-flash-001",
"gemini-1.5-flash",
"gpt-4o-mini"
],
"max_retries": 3,
"timeout": 60000
};
// Load Config
function loadConfig() {
if (fs.existsSync(CONFIG_FILE)) {
try {
return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
} catch (e) {
console.error('Warning: Failed to parse config file, using defaults.');
}
}
return DEFAULT_CONFIG;
}
// Save Config
function saveConfig(config) {
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
console.log('Configuration saved to dmfr_config.json');
}
// Local Task Runner Path (Assumes skill is installed alongside)
const LOCAL_TASK_RUNNER = path.join(__dirname, '..', 'local-task-runner', 'index.js');
// Helper: Run Local Task
function runLocalTask(scriptCode, timeout) {
return new Promise((resolve) => {
// Write to temp file to avoid CLI argument length limits and escaping hell
const tempScriptPath = path.join(__dirname, `worker_${Date.now()}_${Math.random().toString(36).substring(7)}.js`);
fs.writeFileSync(tempScriptPath, scriptCode);
// Use local-task-runner to run the file content passed via --code argument
// We read the file content into the command.
// BETTER: Pass file path if local-task-runner supported it.
// As per local-task-runner interface: node index.js run --code "..."
// We need to be careful about escaping double quotes in the code string when passing to bash.
// Robust approach: Let's modify local-task-runner or just exec node directly?
// Since we are inside a skill, we can just exec 'node tempScriptPath'.
// But the requirement is to use local-task-runner skill.
// Let's stick to the skill interface but ensure we escape properly.
// To simplify: We will EXECUTE directly here to avoid double-wrapping complexity
// while adhering to the "use local execution" policy.
// If we strictly MUST use local-task-runner skill CLI:
// We need to pass the code string.
const command = `node "${LOCAL_TASK_RUNNER}" run --code "$(cat "${tempScriptPath}")" --timeout ${timeout}`;
exec(command, (error, stdout, stderr) => {
// Clean up temp file
try { fs.unlinkSync(tempScriptPath); } catch(e){}
resolve({
success: !error,
error: error ? error.message : null,
stdout: stdout,
stderr: stderr
});
});
});
}
// Helper: Check for Rate Limit Errors in Stderr
function isRateLimitError(stderr) {
if (!stderr) return false;
const errors = ['429', 'Too Many Requests', 'QuotaExceeded', 'Rate limit', 'quota'];
return errors.some(err => stderr.includes(err));
}
// Helper: Generate Worker Script (Real LLM Call)
function generateWorkerScript(model, taskDescription, apiKey) {
// Escaping backticks for template literal inside the script string
const safeTask = taskDescription.replace(/`/g, '\\`').replace(/\$/g, '\\$');
return `
const https = require('https');
const MODEL = '${model}';
const API_KEY = '${apiKey || process.env.GEMINI_API_KEY || ''}';
const TASK = \`${safeTask}\`;
if (!API_KEY) {
console.error('Error: GEMINI_API_KEY not found.');
process.exit(1);
}
const data = JSON.stringify({
contents: [{
parts: [{ text: TASK }]
}]
});
const options = {
hostname: 'generativelanguage.googleapis.com',
path: '/v1beta/models/' + MODEL + ':generateContent?key=' + API_KEY,
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
console.log('[Worker] Requesting ' + MODEL + '...');
const req = https.request(options, (res) => {
let body = '';
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
if (res.statusCode >= 200 && res.statusCode < 300) {
try {
const response = JSON.parse(body);
const content = response.candidates?.[0]?.content?.parts?.[0]?.text || 'No content generated.';
console.log('--- GENERATED CONTENT ---');
console.log(content);
process.exit(0);
} catch (e) {
console.error('Error: Failed to parse API response:', e.message);
process.exit(1);
}
} else {
console.error('Error: API Request Failed with status ' + res.statusCode);
console.error('Response Body:', body);
// Explicitly flag Rate Limit errors
if (res.statusCode === 429) {
console.error('Rate limit exceeded (429).');
}
process.exit(1);
}
});
});
req.on('error', (e) => {
console.error('Error: Network request failed:', e.message);
process.exit(1);
});
req.write(data);
req.end();
`;
}
// Main: Execute Task with DMFR
async function executeTask(taskDescription) {
const config = loadConfig();
const modelChain = config.worker_chain;
const apiKey = process.env.GEMINI_API_KEY;
console.log(`[DMFR] Received Task: "${taskDescription}"`);
console.log(`[DMFR] Model Chain: ${modelChain.join(' -> ')}`);
for (let attempt = 0; attempt < modelChain.length; attempt++) {
const currentModel = modelChain[attempt];
console.log(`[DMFR] Attempt ${attempt + 1}/${modelChain.length}: Running with model "${currentModel}"...`);
const workerScript = generateWorkerScript(currentModel, taskDescription, apiKey);
const result = await runLocalTask(workerScript, config.timeout);
if (result.success) {
console.log(`[DMFR] Success! Task completed with model "${currentModel}".`);
console.log(result.stdout);
return;
} else {
// Check for Rate Limit in stdout/stderr (local-task-runner captures both)
const output = (result.stderr || '') + (result.stdout || '');
if (isRateLimitError(output)) {
console.warn(`[DMFR] Rate Limit detected on model "${currentModel}" (429). Switching to fallback...`);
// Continue to next iteration
} else {
console.error(`[DMFR] Task failed with non-rate-limit error.`);
console.error(result.stderr);
return;
}
}
}
console.error('[DMFR] All models in the chain failed (Rate Limited or Error). Task execution aborted.');
}
// CLI Handler
async function main() {
const args = process.argv.slice(2);
const command = args[0];
if (command === 'configure') {
const config = loadConfig();
const chainIndex = args.indexOf('--chain');
if (chainIndex !== -1 && args[chainIndex+1]) {
config.worker_chain = args[chainIndex+1].split(',');
saveConfig(config);
return;
}
console.log('Usage: configure --chain "model1,model2"');
} else if (command === 'run') {
const taskIndex = args.indexOf('--task');
if (taskIndex !== -1 && args[taskIndex+1]) {
await executeTask(args[taskIndex+1]);
return;
}
console.log('Usage: run --task "Your task description"');
} else {
console.log('Usage: node index.js [run|configure] ...');
}
}
main().catch(console.error);