-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
765 lines (697 loc) · 30.1 KB
/
app.js
File metadata and controls
765 lines (697 loc) · 30.1 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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
// app.js — personas + API key bar + Agent Profiles (updated for new layout)
// ======================================================
// Shared helpers (available before DOMContentLoaded)
// ======================================================
function toPlainTextFromResponses(data) {
if (typeof data?.output_text === "string" && data.output_text.trim()) {
return data.output_text;
}
if (Array.isArray(data?.output)) {
const parts = [];
for (const seg of data.output) {
const items = Array.isArray(seg?.content) ? seg.content : [];
for (const c of items) {
if (c?.type === "output_text" || c?.type === "summary_text") {
if (typeof c.text === "string") parts.push(c.text);
} else if (c?.type === "refusal" && typeof c.refusal === "string") {
return `Refusal: ${c.refusal}`;
}
}
}
if (parts.length) return parts.join("");
}
return "";
}
function storageAvailable(kind = "localStorage") {
try {
const s = window[kind];
const testKey = "__sma_test__";
s.setItem(testKey, "1");
s.removeItem(testKey);
return true;
} catch {
return false;
}
}
// ======================================================
// Main
// ======================================================
function __sma_main(){
// ===== API Key Management =====
const KEY_STORAGE = "sma_openai_api_key";
const KEY_FREE_ENABLED = "sma_free_tier_enabled";
const KEY_FREE_REMAINING = "sma_free_tier_remaining";
const FREE_TIER_START = 10;
const FREE_OPENAI_KEY = "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";
const apiKeyInput = document.getElementById("apiKeyInput");
const saveKeyBtn = document.getElementById("saveKeyBtn");
const clearKeyBtn = document.getElementById("clearKeyBtn");
const sessionOnlyChk = document.getElementById("sessionOnlyChk");
const keyStatus = document.getElementById("keyStatus");
const testKeyBtn = document.getElementById("testKeyBtn");
function getStoredKey() {
return sessionStorage.getItem(KEY_STORAGE) || localStorage.getItem(KEY_STORAGE) || "";
}
function isFreeEnabled(){ return localStorage.getItem(KEY_FREE_ENABLED) === "1"; }
function setFreeEnabled(on){ if(on){ localStorage.setItem(KEY_FREE_ENABLED,"1"); } else { localStorage.removeItem(KEY_FREE_ENABLED);} }
function getFreeRemaining(){ return Number(localStorage.getItem(KEY_FREE_REMAINING) || "0"); }
function setFreeRemaining(n){ localStorage.setItem(KEY_FREE_REMAINING, String(Math.max(0, Number(n)||0))); }
async function enforceFreeBeforeUse(){ if (isFreeEnabled() && getFreeRemaining() <= 0) { throw new Error("Free tier limit reached (10 messages)."); } }
function noteFreeUsage(){ if (isFreeEnabled()) { setFreeRemaining(getFreeRemaining()-1); updateFreeBadge(); } }
function getFreeKeyFromWindow(){ try { return (window && window.FREE_OPENAI_KEY) ? String(window.FREE_OPENAI_KEY) : ""; } catch { return ""; } }
function updateFreeBadge(){ try { const badge = document.getElementById("freeBadge"); const remEl = document.getElementById("freeRemain"); if (!badge || !remEl) return; if (isFreeEnabled()) { badge.style.display="inline-block"; remEl.textContent = String(getFreeRemaining()); } else { badge.style.display="none"; } } catch{} }
function activateFreeKey(){
const k = getFreeKeyFromWindow();
if (!k) { alert("Free key not configured. Add assets/secure/free_key.js to enable this."); return; }
try { navigator.clipboard?.writeText(k).catch(()=>{}); } catch {}
try { localStorage.setItem(KEY_STORAGE, k); } catch {}
setFreeEnabled(true);
setFreeRemaining(FREE_TIER_START);
updateFreeBadge();
refreshKeyStatus("Free key set. Validating…");
testKey();
}
function mask(str) {
if (!str) return "";
const start = str.slice(0, 3);
const end = str.slice(-4);
return `${start}…${end}`;
}
function refreshKeyStatus(msg) {
if (msg) { keyStatus.textContent = msg; return; }
const fromSession = !!sessionStorage.getItem(KEY_STORAGE);
const key = getStoredKey();
keyStatus.textContent = key
? `Saved (${fromSession ? "session" : "local"}): ${mask(key)}`
: "No key saved";
}
function saveKey(k, sessionOnly) {
const trimmed = (k || "").trim();
if (!trimmed) {
alert("Please paste a valid key (starts with 'sk-').");
return;
}
if (!trimmed.startsWith("sk-")) {
if (!confirm("This doesn't look like an OpenAI key (sk-…). Save anyway?")) return;
}
const wantsSession = !!sessionOnly;
const targetStore = wantsSession ? "sessionStorage" : "localStorage";
if (!storageAvailable(targetStore)) {
refreshKeyStatus(`Cannot save key: ${targetStore} is blocked by the browser/context.`);
alert(`Storage is blocked. Try a different browser context or disable privacy restrictions. (${targetStore})`);
return;
}
if (wantsSession) {
sessionStorage.setItem(KEY_STORAGE, trimmed);
try { localStorage.removeItem(KEY_STORAGE); } catch {}
} else {
localStorage.setItem(KEY_STORAGE, trimmed);
try { sessionStorage.removeItem(KEY_STORAGE); } catch {}
}
if (apiKeyInput) apiKeyInput.value = "";
refreshKeyStatus();
}
(function importKeyFromUrl() {
const params = new URLSearchParams(window.location.search);
const hashParams = new URLSearchParams(window.location.hash.slice(1));
const k = params.get("key") || hashParams.get("key");
if (k) saveKey(k, false);
})();
saveKeyBtn?.addEventListener("click", () => saveKey(apiKeyInput?.value, !!sessionOnlyChk?.checked));
clearKeyBtn?.addEventListener("click", () => {
try { localStorage.removeItem(KEY_STORAGE); } catch {}
try { sessionStorage.removeItem(KEY_STORAGE); } catch {}
refreshKeyStatus();
});
async function testKey() {
const key = getStoredKey();
if (!key) { alert("No key saved. Paste your key and click Save first."); return; }
try {
const res = await fetch("https://api.openai.com/v1/models", {
method: "GET",
headers: { "Authorization": `Bearer ${key}` }
});
if (res.ok) {
keyStatus.textContent = "Key looks valid ✅";
} else {
const text = await res.text();
keyStatus.textContent = `Key test failed (${res.status})`;
console.warn(text);
alert("Key test failed. See console for details.");
}
} catch (err) {
console.error(err);
keyStatus.textContent = "Network/CORS blocked. Try running from http://localhost";
alert("Network/CORS blocked. Start a local server and try again.");
}
}
testKeyBtn?.addEventListener("click", testKey);
const freeKeyBtn = document.getElementById("freeKeyBtn");
freeKeyBtn?.addEventListener("click", activateFreeKey);
updateFreeBadge();
window.getApiKeyOrThrow = function getApiKeyOrThrow() {
const k = getStoredKey();
if (!k) throw new Error("Missing API key. Save it in the top bar first.");
return k;
};
const localOK = storageAvailable("localStorage");
const sessionOK = storageAvailable("sessionStorage");
if (!localOK && !sessionOK) {
refreshKeyStatus("Browser storage is blocked; cannot save API key.");
} else {
refreshKeyStatus();
}
// ===== Persona generator =====
const INDEX_URL = "data/index.json";
const sel = document.getElementById("personaSelect");
const jsonOut = document.getElementById("jsonOut");
const generateBtn = document.getElementById("generateBtn");
const downloadBtn = document.getElementById("downloadBtn");
const copyBtn = document.getElementById("copyBtn");
const createProfileBtn = document.getElementById("createProfileBtn");
const customNameWrap = document.getElementById("customNameWrap");
const customName = document.getElementById("customName");
const customDomain = document.getElementById("customDomain");
let indexData = null;
let currentJson = null;
async function loadIndex() {
const res = await fetch(INDEX_URL);
if (!res.ok) throw new Error("Failed to load data/index.json");
indexData = await res.json();
indexData.personas.forEach(p => {
const opt = document.createElement("option");
opt.value = p.id;
opt.textContent = `${p.name} — ${p.domain}`;
sel.appendChild(opt);
});
const opt = document.createElement("option");
opt.value = indexData.other.id;
opt.textContent = indexData.other.name;
sel.appendChild(opt);
sel.selectedIndex = 0;
}
function baseOther(name, domain) {
const n = name && name.trim() ? name.trim() : "Custom Agent";
const d = domain && domain.trim() ? domain.trim() : "Custom Domain";
return {
name: n,
role: n,
domain: d,
audience: ["General"],
summary: `A custom agent focused on ${d}.`,
defaults: {
tone: "confident",
formality: "neutral",
length: "medium",
preferred_vocab: ["SLA","SOP","playbook","KPI"],
avoid_vocab: ["vague","hand-wavy"]
},
behavior: {
method: "State assumptions, present steps, highlight risks.",
ask_vs_answer: "Ask 1–2 clarifying questions only if critical.",
worked_examples_when: "When the task is complex or ambiguous."
},
constraints: {
formatting: "Use bullets, tables for configs, and short sections.",
citation_policy: "Cite official sources when appropriate.",
uncertainty: "Flag unknowns and propose quick validation.",
prohibited: ["Speculative claims","Unsafe guidance"]
},
guardrails: {
compliance: ["PII","Security"],
approval_gates: ["Stakeholder sign-off for scope changes"],
risk_flags: ["Ambiguous requirements"]
},
capabilities: [
"Summarize requirements","Draft SOP/checklist","Propose architecture/diagram outline",
"Create acceptance criteria","Generate test plan","Write stakeholder comms"
],
examples: {
good: [{
title: "Custom Agent: Structured plan",
context: `User asks for guidance related to ${d}.`,
prompt: "Help me execute a task aligned to this domain.",
answer_outline: "Inputs → Steps → Risks → Acceptance → Next steps",
why_good: "Actionable and standards-aligned.",
tags: ["plan"]
}],
bad: [{
title: "Custom Agent: Vague advice",
context: "User gets hand-wavy guidance.",
prompt: "How do I do the thing?",
bad_reply: "Just try something until it works.",
why_bad: "No steps, no risks, no references.",
tags: ["vague"]
}]
},
tags: ["custom","other"]
};
}
sel?.addEventListener("change", () => {
const isOther = sel.value === "other";
customNameWrap.classList.toggle("hidden", !isOther);
});
generateBtn?.addEventListener("click", async () => {
const id = sel.value;
if (!id) return;
if (id === "other") {
currentJson = baseOther(customName.value, customDomain.value);
jsonOut.textContent = JSON.stringify(currentJson, null, 2);
try { populatePersonaForm(currentJson); } catch(e){ console.warn(e); }
downloadBtn.disabled = false;
copyBtn.disabled = false;
createProfileBtn.disabled = false;
return;
}
const meta = indexData.personas.find(p => p.id === id);
if (!meta) return;
const res = await fetch(meta.path);
const data = await res.json();
noteFreeUsage();
currentJson = data;
jsonOut.textContent = JSON.stringify(data, null, 2);
try { populatePersonaForm(currentJson); } catch(e){ console.warn(e); }
downloadBtn.disabled = false;
copyBtn.disabled = false;
createProfileBtn.disabled = false;
});
downloadBtn?.addEventListener("click", () => {
if (!currentJson) return;
const blob = new Blob([JSON.stringify(currentJson, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${currentJson.name.replace(/\s+/g, "_").toLowerCase()}.json`;
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(url);
a.remove();
});
copyBtn?.addEventListener("click", async () => {
if (!currentJson) return;
try {
await navigator.clipboard.writeText(JSON.stringify(currentJson, null, 2));
copyBtn.textContent = "Copied!";
setTimeout(()=> copyBtn.textContent = "Copy to Clipboard", 1200);
} catch (e) {
alert("Copy failed. Select and copy manually.");
}
});
// ===== Persona Form helpers =====
const formEls = {
name: document.getElementById("personaName"),
role: document.getElementById("personaRole"),
domain: document.getElementById("personaDomain"),
audience: document.getElementById("personaAudience"),
summary: document.getElementById("personaSummary"),
tone: document.getElementById("defaultsTone"),
formality: document.getElementById("defaultsFormality"),
length: document.getElementById("defaultsLength"),
preferred: document.getElementById("defaultsPreferred"),
avoid: document.getElementById("defaultsAvoid"),
method: document.getElementById("behaviorMethod"),
ask: document.getElementById("behaviorAsk"),
examplesWhen: document.getElementById("behaviorExamplesWhen"),
formatting: document.getElementById("constraintsFormatting"),
citation: document.getElementById("constraintsCitation"),
uncertainty: document.getElementById("constraintsUncertainty"),
prohibited: document.getElementById("constraintsProhibited"),
compliance: document.getElementById("guardrailsCompliance"),
approvals: document.getElementById("guardrailsApprovals"),
risks: document.getElementById("guardrailsRisks"),
capabilities: document.getElementById("capabilitiesList"),
examplesGood: document.getElementById("examplesGoodJson"),
examplesBad: document.getElementById("examplesBadJson"),
tags: document.getElementById("tagsList"),
applyBtn: document.getElementById("applyPersonaBtn"),
status: document.getElementById("personaFormStatus")
};
function listFromCSV(str) {
return (str || "")
.split(/[\,\n]/)
.map(s => s.trim())
.filter(Boolean);
}
function csvFromList(arr) { return (arr || []).join(", "); }
function populatePersonaForm(p) {
try {
formEls.name.value = p.name || "";
formEls.role.value = p.role || "";
formEls.domain.value = p.domain || "";
formEls.audience.value = csvFromList(p.audience);
formEls.summary.value = p.summary || "";
formEls.tone.value = p?.defaults?.tone || "confident";
formEls.formality.value = p?.defaults?.formality || "neutral";
formEls.length.value = p?.defaults?.length || "medium";
formEls.preferred.value = csvFromList(p?.defaults?.preferred_vocab || []);
formEls.avoid.value = csvFromList(p?.defaults?.avoid_vocab || []);
formEls.method.value = p?.behavior?.method || "";
formEls.ask.value = p?.behavior?.ask_vs_answer || "";
formEls.examplesWhen.value = p?.behavior?.worked_examples_when || "";
formEls.formatting.value = p?.constraints?.formatting || "";
formEls.citation.value = p?.constraints?.citation_policy || "";
formEls.uncertainty.value = p?.constraints?.uncertainty || "";
formEls.prohibited.value = csvFromList(p?.constraints?.prohibited || []);
formEls.compliance.value = csvFromList(p?.guardrails?.compliance || []);
formEls.approvals.value = csvFromList(p?.guardrails?.approval_gates || []);
formEls.risks.value = csvFromList(p?.guardrails?.risk_flags || []);
formEls.capabilities.value = csvFromList(p?.capabilities || []);
formEls.examplesGood.value = JSON.stringify(p?.examples?.good || [], null, 2);
formEls.examplesBad.value = JSON.stringify(p?.examples?.bad || [], null, 2);
formEls.tags.value = csvFromList(p?.tags || []);
formEls.status.textContent = "Form loaded.";
} catch (e) {
console.error(e);
formEls.status.textContent = "Failed to load into form.";
}
}
function buildPersonaFromForm() {
let good = [], bad = [];
try { good = JSON.parse(formEls.examplesGood.value || "[]"); }
catch(e){ throw new Error("examples.good is not valid JSON"); }
try { bad = JSON.parse(formEls.examplesBad.value || "[]"); }
catch(e){ throw new Error("examples.bad is not valid JSON"); }
const p = {
name: formEls.name.value.trim(),
role: formEls.role.value.trim() || formEls.name.value.trim(),
domain: formEls.domain.value.trim(),
audience: listFromCSV(formEls.audience.value),
summary: formEls.summary.value.trim(),
defaults: {
tone: formEls.tone.value || "confident",
formality: formEls.formality.value || "neutral",
length: formEls.length.value || "medium",
preferred_vocab: listFromCSV(formEls.preferred.value),
avoid_vocab: listFromCSV(formEls.avoid.value)
},
behavior: {
method: formEls.method.value.trim(),
ask_vs_answer: formEls.ask.value.trim(),
worked_examples_when: formEls.examplesWhen.value.trim()
},
constraints: {
formatting: formEls.formatting.value.trim(),
citation_policy: formEls.citation.value.trim(),
uncertainty: formEls.uncertainty.value.trim(),
prohibited: listFromCSV(formEls.prohibited.value)
},
guardrails: {
compliance: listFromCSV(formEls.compliance.value),
approval_gates: listFromCSV(formEls.approvals.value),
risk_flags: listFromCSV(formEls.risks.value)
},
capabilities: listFromCSV(formEls.capabilities.value),
examples: { good, bad },
tags: listFromCSV(formEls.tags.value)
};
if (!p.name) throw new Error("name is required");
if (!p.domain) throw new Error("domain is required");
if (!p.audience?.length) throw new Error("audience must not be empty");
return p;
}
formEls.applyBtn?.addEventListener("click", () => {
try {
const p = buildPersonaFromForm();
currentJson = p;
if (jsonOut) jsonOut.textContent = JSON.stringify(currentJson, null, 2);
formEls.status.textContent = "Applied to JSON.";
} catch (e) {
console.error(e);
formEls.status.textContent = e.message || "Failed to apply.";
}
});
// ---- Persona Form: description generator wiring (uses #personaDesc if present) ----
(function setupSmaDescriptionOnPersonaForm() {
const formSection = document.querySelector(".persona-form");
if (!formSection) return;
const hint = formSection.querySelector(".hint");
const appended = " Important: Generate the ~200-word persona description from this form using the button below.";
if (hint && !hint.textContent.includes("Important: Generate the ~200-word persona description")) {
hint.insertAdjacentText("beforeend", appended);
}
let personaDesc = document.getElementById("personaDesc");
let generateSmaDescBtn = document.getElementById("generateSmaDescBtn");
// Hide legacy profile-level button if it exists in older markup
try {
const legacyBtn = document.getElementById("generatePersonaDescBtn");
if (legacyBtn) legacyBtn.style.display = "none";
} catch {}
generateSmaDescBtn?.addEventListener("click", async () => {
let persona;
try {
persona = buildPersonaFromForm();
} catch (e) {
alert(e.message || "Fix errors in the Persona Form before generating.");
return;
}
try {
currentJson = persona;
if (jsonOut) jsonOut.textContent = JSON.stringify(currentJson, null, 2);
if (formEls?.status) formEls.status.textContent = "Applied to JSON.";
} catch {}
let key;
try { key = window.getApiKeyOrThrow(); } catch (e) { alert(e.message); return; }
const systemText = "You are SMA Persona Narrator. Write a <200 word> persona description from the persona JSON fields. Focus on domain, skills, guardrails, and value to the user. No secrets or unsafe claims.";
const userText = "Persona JSON:\n" + JSON.stringify(currentJson, null, 2);
const textConfig = { format: { type: "text" } };
try {
await enforceFreeBeforeUse();
const res = await fetch("https://api.openai.com/v1/responses", {
method: "POST",
headers: {
"Authorization": `Bearer ${key}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "gpt-5-mini",
input: [
{ role: "system", content: [{ type: "input_text", text: systemText }] },
{ role: "user", content: [{ type: "input_text", text: userText }] }
],
text: textConfig,
max_output_tokens: 450
})
});
if (!res.ok) {
const t = await res.text();
console.warn(t);
alert("API call failed. Check console for details. Are you on http://localhost and is the key valid?");
return;
}
const data = await res.json();
noteFreeUsage();
let out = toPlainTextFromResponses(data);
if (!out || !out.trim()) out = "(no text returned)";
personaDesc = document.getElementById("personaDesc");
if (personaDesc) personaDesc.value = out.trim();
} catch (err) {
console.error(err);
alert("Network/CORS blocked or other error. Try from a local server.");
}
});
})();
// ===== Agent Profile Logic =====
const LS_PROFILES_KEY = "sma_profiles_v1";
const profileName = document.getElementById("profileName");
const profileDesc = document.getElementById("profileDesc"); // may not exist in new layout
const toolWebSearch = document.getElementById("toolWebSearch");
const toolFileSearch = document.getElementById("toolFileSearch");
const toolCodeInterpreter = document.getElementById("toolCodeInterpreter");
const persistentMemory = document.getElementById("persistentMemory");
const reasoningEffort = document.getElementById("reasoningEffort");
const verbosity = document.getElementById("verbosity");
const vectorStoreId = document.getElementById("vectorStoreId");
const filesList = document.getElementById("filesList");
const shortcuts = document.getElementById("shortcuts");
const reports = document.getElementById("reports");
const saveProfileBtn = document.getElementById("saveProfileBtn");
const deleteProfileBtn = document.getElementById("deleteProfileBtn");
const downloadProfileBtn = document.getElementById("downloadProfileBtn");
const profileSelect = document.getElementById("profileSelect");
const createProfileBtn2 = document.getElementById("createProfileBtn");
let currentProfileId = null;
let draftPersona = null;
function uuid() {
return "prof_" + Math.random().toString(36).slice(2, 10);
}
function getDescField(){
return document.getElementById("personaDesc") || profileDesc || null;
}
function startNewProfileFromPersona(persona) {
currentProfileId = uuid();
draftPersona = persona;
profileName.value = persona.name || "New Agent Profile";
const personaDescEl = document.getElementById("personaDesc");
const descFromPersonaForm = personaDescEl ? (personaDescEl.value || "").trim() : "";
const descTarget = getDescField();
if (descTarget) descTarget.value = descFromPersonaForm;
toolWebSearch.checked = true;
toolFileSearch.checked = true;
toolCodeInterpreter.checked = false;
persistentMemory.checked = false;
reasoningEffort.value = "medium";
verbosity.value = "medium";
vectorStoreId.value = "";
filesList.value = "";
shortcuts.value = "";
reports.value = "";
deleteProfileBtn.disabled = true;
downloadProfileBtn.disabled = true;
alert("Persona copied into new Agent Profile draft. Fill details and click 'Save Agent Profile'.");
}
createProfileBtn2?.addEventListener("click", () => {
if (!currentJson) { alert("Generate a persona first."); return; }
startNewProfileFromPersona(currentJson);
});
function buildProfileJson() {
const persona = buildPersonaFromForm();
const tools = [];
if (toolWebSearch.checked) tools.push({ type: "web_search" });
if (toolFileSearch.checked) tools.push({ type: "file_search" });
if (toolCodeInterpreter.checked) tools.push({ type: "code_interpreter" });
const descEl = getDescField();
const description = descEl ? (descEl.value || "").trim() : "";
const profile = {
id: currentProfileId || uuid(),
name: (profileName.value || "Untitled Profile").trim(),
description,
persona: persona,
tools,
memory: { persistent: !!persistentMemory.checked },
knobs: {
reasoning_effort: reasoningEffort.value,
verbosity: verbosity.value
},
vector_store_id: (vectorStoreId.value || "").trim() || null,
file_ids: (filesList.value || "").split(/\n+/).map(s => s.trim()).filter(Boolean),
shortcuts: (shortcuts.value || "").split(",").map(s => s.trim()).filter(Boolean),
reports: (reports.value || "").split(",").map(s => s.trim()).filter(Boolean),
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
};
return profile;
}
function loadProfiles() {
try {
const raw = localStorage.getItem(LS_PROFILES_KEY);
const arr = raw ? JSON.parse(raw) : [];
return Array.isArray(arr) ? arr : [];
} catch { return []; }
}
function saveProfiles(arr) {
localStorage.setItem(LS_PROFILES_KEY, JSON.stringify(arr));
}
function refreshProfileSelect(selectedId) {
const arr = loadProfiles();
profileSelect.innerHTML = "";
const ph = document.createElement("option");
ph.value = ""; ph.textContent = "— Select a saved profile —";
profileSelect.appendChild(ph);
arr.forEach(p => {
const opt = document.createElement("option");
opt.value = p.id;
opt.textContent = p.name;
if (p.id === selectedId) opt.selected = true;
profileSelect.appendChild(opt);
});
}
function populateEditor(profile) {
currentProfileId = profile.id;
draftPersona = profile.persona;
profileName.value = profile.name || "";
const descEl = getDescField();
if (descEl) descEl.value = profile.description || "";
toolWebSearch.checked = !!profile.tools?.some(t => t.type === "web_search");
toolFileSearch.checked = !!profile.tools?.some(t => t.type === "file_search");
toolCodeInterpreter.checked = !!profile.tools?.some(t => t.type === "code_interpreter");
persistentMemory.checked = !!profile.memory?.persistent;
reasoningEffort.value = profile.knobs?.reasoning_effort || "medium";
verbosity.value = profile.knobs?.verbosity || "medium";
vectorStoreId.value = profile.vector_store_id || "";
filesList.value = (profile.file_ids || []).join("\n");
shortcuts.value = (profile.shortcuts || []).join(", ");
reports.value = (profile.reports || []).join(", ");
deleteProfileBtn.disabled = false;
downloadProfileBtn.disabled = false;
}
saveProfileBtn?.addEventListener("click", () => {
try {
const profile = buildProfileJson();
const arr = loadProfiles();
const idx = arr.findIndex(p => p.id === profile.id);
if (idx >= 0) {
arr[idx] = Object.assign({}, profile, { updated_at: new Date().toISOString() });
} else {
arr.push(profile);
}
saveProfiles(arr);
refreshProfileSelect(profile.id);
deleteProfileBtn.disabled = false;
downloadProfileBtn.disabled = false;
alert("Agent Profile saved.");
} catch (e) {
console.error(e);
alert(e.message || "Failed to save profile.");
}
});
deleteProfileBtn?.addEventListener("click", () => {
if (!currentProfileId) return;
if (!confirm("Delete this profile? This cannot be undone.")) return;
const arr = loadProfiles().filter(p => p.id !== currentProfileId);
saveProfiles(arr);
currentProfileId = null;
draftPersona = null;
[profileName, vectorStoreId, filesList, shortcuts, reports].forEach(i => i.value = "");
[toolWebSearch, toolFileSearch, toolCodeInterpreter, persistentMemory].forEach(i => i.checked = false);
reasoningEffort.value = "medium"; verbosity.value = "medium";
const descEl = getDescField(); if (descEl) descEl.value = "";
deleteProfileBtn.disabled = true;
downloadProfileBtn.disabled = true;
refreshProfileSelect();
alert("Profile deleted.");
});
profileSelect?.addEventListener("change", () => {
const id = profileSelect.value;
if (!id) return;
const arr = loadProfiles();
const p = arr.find(x => x.id === id);
if (p) populateEditor(p);
});
downloadProfileBtn?.addEventListener("click", () => {
const arr = loadProfiles();
const p = arr.find(x => x.id === currentProfileId);
if (!p) { alert("Save the profile first."); return; }
const blob = new Blob([JSON.stringify(p, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url; a.download = `${p.name.replace(/\s+/g, "_").toLowerCase()}.profile.json`;
document.body.appendChild(a); a.click(); URL.revokeObjectURL(url); a.remove();
});
// On boot
loadIndex().catch(err => {
console.error(err);
const out = document.getElementById("jsonOut");
if (out) out.textContent = "Failed to load data/index.json. Serve the folder from a local server if file:// blocks fetch.";
});
refreshProfileSelect();
} // END __sma_main
(function exposeSeederBoot(){
if (typeof window.__SMA_BOOT === "function") return;
window.__SMA_BOOTED__ = !!window.__SMA_BOOTED__;
window.__SMA_BOOT = function(){
if (window.__SMA_BOOTED__) return;
window.__SMA_BOOTED__ = true;
try { __sma_main(); }
catch (e) {
console.error("[SMA] boot failed:", e);
window.__SMA_BOOTED__ = false;
}
};
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => {
if (!window.__SMA_BOOTED__) window.__SMA_BOOT();
}, { once: true });
} else {
window.__SMA_BOOT();
}
})();