Repository navigation
Expand file tree
/
Copy pathagents.js
More file actions
606 lines (508 loc) · 18.8 KB
/
Copy pathagents.js
File metadata and controls
606 lines (508 loc) · 18.8 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
// Agents UI - uses IPC for all backend communication
class AgentsUI {
constructor() {
this.currentAgent = null;
this.isNewAgent = false;
this.selectedAgentElement = null;
this.initializeElements();
this.attachEventListeners();
this.loadAgents();
this.loadRecommendedAgents();
}
initializeElements() {
console.log('Initializing elements...');
// List elements
this.myAgentsList = document.getElementById('agents-my-agents-list');
this.recommendedAgentsList = document.getElementById('agents-recommended-agents-list');
this.myAgentsCount = document.getElementById('agents-my-agents-count');
this.recommendedAgentsCount = document.getElementById('agents-recommended-agents-count');
this.searchInput = document.getElementById('agents-agent-search');
console.log('Elements found:', {
myAgentsList: !!this.myAgentsList,
recommendedAgentsList: !!this.recommendedAgentsList,
newAgentBtn: !!document.getElementById('agents-new-agent-btn')
});
// Detail/Editor elements
this.emptyState = document.getElementById('agents-empty-state');
this.agentDetail = document.getElementById('agents-agent-detail');
this.agentPreview = document.getElementById('agents-agent-preview');
// Form elements
this.agentNameInput = document.getElementById('agents-agent-name');
this.agentContentInput = document.getElementById('agents-agent-content');
this.agentSource = document.getElementById('agents-agent-source');
this.agentModified = document.getElementById('agents-agent-modified');
console.log('Form elements found:', {
agentNameInput: !!this.agentNameInput,
agentContentInput: !!this.agentContentInput,
agentSource: !!this.agentSource,
agentModified: !!this.agentModified
});
// Preview elements
this.previewName = document.getElementById('agents-preview-name');
this.previewSource = document.getElementById('agents-preview-source');
this.previewCategory = document.getElementById('agents-preview-category');
this.previewDescription = document.getElementById('agents-preview-description');
this.previewPrompt = document.getElementById('agents-preview-prompt');
this.previewTools = document.getElementById('agents-preview-tools');
this.previewModel = document.getElementById('agents-preview-model');
// Buttons
this.newAgentBtn = document.getElementById('agents-new-agent-btn');
this.saveBtn = document.getElementById('agents-save-btn');
this.cancelBtn = document.getElementById('agents-cancel-btn');
this.deleteBtn = document.getElementById('agents-delete-btn');
this.cloneBtn = document.getElementById('agents-clone-btn');
this.installBtn = document.getElementById('agents-install-btn');
}
attachEventListeners() {
// Search
this.searchInput.addEventListener('input', () => this.filterAgents());
// New Agent
console.log('Attaching click listener to new agent button:', this.newAgentBtn);
this.newAgentBtn.addEventListener('click', () => {
console.log('New Agent button clicked');
this.createNewAgent();
});
// Save/Cancel
this.saveBtn.addEventListener('click', () => this.saveAgent());
this.cancelBtn.addEventListener('click', () => this.cancelEdit());
// Delete/Clone
this.deleteBtn.addEventListener('click', () => this.deleteAgent());
this.cloneBtn.addEventListener('click', () => this.cloneAgent());
// Install recommended
this.installBtn.addEventListener('click', () => this.installRecommendedAgent());
// Auto-save with debounce
const autoSave = this.debounce(() => {
if (this.currentAgent && !this.isNewAgent) {
this.saveAgent();
}
}, 2000);
this.agentContentInput.addEventListener('input', autoSave);
// Update name in content when name input changes
this.agentNameInput.addEventListener('input', () => {
const newName = this.agentNameInput.value.trim();
if (newName) {
this.agentContentInput.value = this.updateNameInContent(this.agentContentInput.value, newName);
}
});
}
async loadAgents() {
try {
console.log('Loading agents via IPC...');
const result = await window.electronAPI.loadAgents();
if (result.success) {
console.log('Agents loaded:', result.data);
this.renderMyAgents(result.data);
} else {
console.error('Error loading agents:', result.error);
}
} catch (error) {
console.error('Error loading agents:', error);
}
}
async loadRecommendedAgents() {
try {
console.log('Loading recommended agents via IPC...');
const result = await window.electronAPI.loadRecommendedAgents();
if (result.success) {
console.log('Recommended agents loaded:', result.data);
console.log('Number of agents:', result.data ? result.data.length : 0);
// Debug: Check metadata of each agent
if (result.data && result.data.length > 0) {
console.log('[DEBUG] Agent metadata check:');
result.data.forEach(agent => {
console.log(` ${agent.name}: source="${agent.metadata?.source}", license="${agent.metadata?.license}"`);
});
}
this.renderRecommendedAgents(result.data);
} else {
console.error('Error loading recommended agents:', result.error);
}
} catch (error) {
console.error('Error loading recommended agents:', error);
console.error('Stack trace:', error.stack);
}
}
renderMyAgents(agents) {
this.myAgentsList.innerHTML = '';
this.myAgentsCount.textContent = agents.length;
const filteredAgents = this.filterAgentsList(agents);
filteredAgents.forEach(agent => {
const agentElement = this.createAgentElement(agent, false);
this.myAgentsList.appendChild(agentElement);
});
}
renderRecommendedAgents(agents) {
this.recommendedAgentsList.innerHTML = '';
this.recommendedAgentsCount.textContent = agents.length;
const filteredAgents = this.filterAgentsList(agents);
filteredAgents.forEach(agent => {
const agentElement = this.createAgentElement(agent, true);
this.recommendedAgentsList.appendChild(agentElement);
});
}
createAgentElement(agent, isRecommended) {
const div = document.createElement('div');
div.className = 'agent-item';
div.innerHTML = `
<div class="agent-item-header">
<span class="agent-item-name">${this.escapeHtml(agent.name)}</span>
<span class="agent-item-model">${agent.model || 'default'}</span>
</div>
<div class="agent-item-description">${this.escapeHtml(agent.description || 'No description')}</div>
`;
div.addEventListener('click', () => {
this.selectAgent(agent, div, isRecommended);
});
return div;
}
selectAgent(agent, element, isRecommended) {
// Update selection
if (this.selectedAgentElement) {
this.selectedAgentElement.classList.remove('selected');
}
element.classList.add('selected');
this.selectedAgentElement = element;
// Show appropriate panel
if (isRecommended) {
this.showRecommendedAgent(agent);
} else {
this.editAgent(agent);
}
}
showRecommendedAgent(agent) {
console.log('[DEBUG] Showing recommended agent:', agent.name);
console.log('[DEBUG] Agent metadata:', agent.metadata);
this.emptyState.style.display = 'none';
this.agentDetail.style.display = 'none';
this.agentPreview.style.display = 'block';
this.previewName.textContent = agent.name;
this.previewCategory.textContent = agent.category || 'General';
this.previewDescription.textContent = agent.description || 'No description';
this.previewPrompt.textContent = agent.system_prompt || 'No system prompt defined';
this.previewModel.textContent = this.getModelDisplayName(agent.model);
// Set source from metadata
if (this.previewSource) {
const source = agent.metadata?.source || 'unknown';
console.log(`[DEBUG] Setting preview source to: "${source}"`);
this.previewSource.textContent = `Source: ${source}`;
} else {
console.log('[DEBUG] previewSource element not found!');
}
// Render tools
this.previewTools.innerHTML = '';
if (agent.tools && agent.tools.length > 0) {
agent.tools.forEach(tool => {
const toolTag = document.createElement('div');
toolTag.className = 'tool-tag';
toolTag.textContent = tool;
this.previewTools.appendChild(toolTag);
});
} else {
this.previewTools.innerHTML = '<span style="color: var(--text-secondary)">No tools configured</span>';
}
this.currentAgent = agent;
}
editAgent(agent) {
this.emptyState.style.display = 'none';
this.agentPreview.style.display = 'none';
this.agentDetail.style.display = 'block';
this.currentAgent = agent;
this.isNewAgent = false;
// Populate form
this.agentNameInput.value = agent.name || '';
// Generate markdown content from agent data
let content = '---\n';
content += `name: ${agent.name || ''}\n`;
content += `description: ${agent.description || ''}\n`;
content += `model: ${agent.model || 'default'}\n`;
if (agent.tools && agent.tools.length > 0) {
content += 'tools:\n';
agent.tools.forEach(tool => {
content += ` - ${tool}\n`;
});
}
content += '---\n\n';
content += agent.system_prompt || '';
this.agentContentInput.value = content;
// Update metadata
if (agent.metadata) {
this.agentSource.textContent = agent.metadata.source || 'Local';
this.agentModified.textContent = `Modified ${this.formatDate(agent.metadata.modified)}`;
}
}
createNewAgent() {
console.log('Creating new agent...');
this.emptyState.style.display = 'none';
this.agentPreview.style.display = 'none';
this.agentDetail.style.display = 'block';
this.isNewAgent = true;
this.currentAgent = {
name: 'new-agent',
content: this.getDefaultTemplate()
};
// Clear form
this.agentNameInput.value = 'new-agent';
this.agentContentInput.value = this.getDefaultTemplate();
this.agentSource.textContent = 'New Agent';
this.agentModified.textContent = '';
// Verify the values were set
console.log('After setting default values:');
console.log('Name input value:', this.agentNameInput.value);
console.log('Content input value:', this.agentContentInput.value);
console.log('Content length:', this.agentContentInput.value.length);
// Focus name input
this.agentNameInput.focus();
}
getDefaultTemplate() {
return `---
name: new-agent
description: Brief description of what this agent does
model: default
---
You are an expert assistant specializing in [DOMAIN].
## Focus Areas
- [Primary focus area 1]
- [Primary focus area 2]
- [Primary focus area 3]
## Approach
1. [Step 1 in your approach]
2. [Step 2 in your approach]
3. [Step 3 in your approach]
## Output
- [Expected output type 1]
- [Expected output type 2]
- [Expected output type 3]
[Additional instructions or guidelines]`;
}
async saveAgent() {
if (!this.currentAgent) return;
// Get values from form inputs
const nameInputValue = this.agentNameInput.value;
const contentInputValue = this.agentContentInput.value;
console.log('saveAgent - Raw input values:', {
nameInputValue,
contentInputValue,
nameLength: nameInputValue.length,
contentLength: contentInputValue.length
});
const name = nameInputValue.trim();
let content = contentInputValue.trim();
console.log('saveAgent - After trim:', {
name,
content,
nameLength: name.length,
contentLength: content.length
});
if (!name) {
alert('Agent name is required');
return;
}
// Update the name in the frontmatter to match the input field
content = this.updateNameInContent(content, name);
console.log('saveAgent - After updateNameInContent:', {
content,
contentLength: content.length
});
// The content should be saved as-is
const agentData = {
name: name,
content: content
};
console.log('saveAgent - Final agentData:', JSON.stringify(agentData, null, 2));
try {
let result;
if (this.isNewAgent) {
console.log('Creating new agent...');
result = await window.electronAPI.createAgent(agentData);
} else {
console.log('Updating existing agent:', this.currentAgent.name);
result = await window.electronAPI.updateAgent(this.currentAgent.name, agentData);
}
console.log('Save result:', result);
if (result.success) {
await this.loadAgents();
this.showSuccessMessage('Agent saved successfully');
// Update current agent name for future saves
this.currentAgent.name = name;
this.isNewAgent = false;
} else {
alert(`Error saving agent: ${result.error}`);
}
} catch (error) {
console.error('Error saving agent:', error);
alert(`Error saving agent: ${error.message}`);
}
}
updateNameInContent(content, newName) {
// Update the name in YAML frontmatter
const lines = content.split('\n');
let inFrontmatter = false;
let frontmatterStart = -1;
for (let i = 0; i < lines.length; i++) {
if (lines[i] === '---') {
if (!inFrontmatter) {
inFrontmatter = true;
frontmatterStart = i;
} else {
// End of frontmatter
break;
}
} else if (inFrontmatter && lines[i].startsWith('name:')) {
lines[i] = `name: ${newName}`;
}
}
return lines.join('\n');
}
async deleteAgent() {
if (!this.currentAgent || this.isNewAgent) return;
if (confirm(`Are you sure you want to delete "${this.currentAgent.name}"?`)) {
try {
const result = await window.electronAPI.deleteAgent(this.currentAgent.name);
if (result.success) {
await this.loadAgents();
this.showEmptyState();
this.showSuccessMessage('Agent deleted successfully');
} else {
alert(`Error deleting agent: ${result.error}`);
}
} catch (error) {
console.error('Error deleting agent:', error);
alert(`Error deleting agent: ${error.message}`);
}
}
}
async cloneAgent() {
if (!this.currentAgent) return;
const newName = prompt(`Enter name for cloned agent:`, `${this.currentAgent.name}-copy`);
if (newName && newName.trim()) {
try {
const result = await window.electronAPI.cloneAgent(this.currentAgent.name, newName.trim());
if (result.success) {
await this.loadAgents();
this.showSuccessMessage('Agent cloned successfully');
} else {
alert(`Error cloning agent: ${result.error}`);
}
} catch (error) {
console.error('Error cloning agent:', error);
alert(`Error cloning agent: ${error.message}`);
}
}
}
async installRecommendedAgent() {
if (!this.currentAgent) return;
try {
// Generate markdown content for the recommended agent
let content = '---\n';
content += `name: ${this.currentAgent.name}\n`;
content += `description: ${this.currentAgent.description || ''}\n`;
content += `model: ${this.currentAgent.model || 'default'}\n`;
if (this.currentAgent.tools && this.currentAgent.tools.length > 0) {
content += 'tools:\n';
this.currentAgent.tools.forEach(tool => {
content += ` - ${tool}\n`;
});
}
content += '---\n\n';
content += this.currentAgent.system_prompt || '';
const agentData = {
name: this.currentAgent.name,
content: content
};
const result = await window.electronAPI.createAgent(agentData);
if (result.success) {
await this.loadAgents();
this.showSuccessMessage(`Agent "${this.currentAgent.name}" installed successfully`);
// Switch to edit mode for the newly installed agent
const agentsResult = await window.electronAPI.loadAgents();
if (agentsResult.success) {
const installedAgent = agentsResult.data.find(a => a.name === this.currentAgent.name);
if (installedAgent) {
this.editAgent(installedAgent);
}
}
} else {
alert(`Error installing agent: ${result.error}`);
}
} catch (error) {
console.error('Error installing agent:', error);
alert(`Error installing agent: ${error.message}`);
}
}
cancelEdit() {
if (this.isNewAgent || confirm('Discard unsaved changes?')) {
this.showEmptyState();
}
}
showEmptyState() {
this.emptyState.style.display = 'flex';
this.agentDetail.style.display = 'none';
this.agentPreview.style.display = 'none';
this.currentAgent = null;
if (this.selectedAgentElement) {
this.selectedAgentElement.classList.remove('selected');
this.selectedAgentElement = null;
}
}
filterAgents() {
this.loadAgents();
this.loadRecommendedAgents();
}
filterAgentsList(agents) {
const searchTerm = this.searchInput.value.toLowerCase();
if (!searchTerm) return agents;
return agents.filter(agent =>
agent.name.toLowerCase().includes(searchTerm) ||
(agent.description && agent.description.toLowerCase().includes(searchTerm)) ||
(agent.tools && agent.tools.some(tool => tool.toLowerCase().includes(searchTerm)))
);
}
showSuccessMessage(message) {
// Could implement a toast notification here
console.log(message);
}
getModelDisplayName(model) {
const modelNames = {
'default': 'Default',
'haiku': 'Haiku (Fast)',
'sonnet': 'Sonnet (Balanced)',
'opus': 'Opus (Powerful)'
};
return modelNames[model] || model || 'Default';
}
formatDate(date) {
if (!date) return '';
const d = new Date(date);
return d.toLocaleDateString();
}
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
}
// Initialize when agents tab is shown
window.agentsUI = null;
window.initializeAgentsUI = function() {
if (!window.agentsUI) {
console.log('Agents UI initializing...');
try {
window.agentsUI = new AgentsUI();
console.log('Agents UI initialized successfully');
} catch (error) {
console.error('Error initializing Agents UI:', error);
console.error('Stack trace:', error.stack);
}
}
};