Files
stack/packages/webui/src/public/agents.js
T

156 lines
19 KiB
JavaScript

/* Row 194 (#1692, D7): the Agents section of Settings. bus.js draws it with section(view, ctx) after the
role instances, from the same instances read. Create and Delete go through /api/instances; Launch,
Terminate and Regenerate through /api/agent/*; Keep, Unkeep, No-hire and Hire through /api/veto.
Every answer that names a request is followed at /api/agent/request until the request closes.
Regenerate and Delete take a second click to confirm. Nothing retries: an unknown outcome says so
and asks for a fresh read. The tester listener offers Launch and Terminate only (D4.1). */
(() => {
'use strict';
const UNAVAILABLE = 'Agent actions are unavailable here. Use mosaic business instance from the instance CLI.';
const REQUEST_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const POLL_MS = 2000, POLL_LIMIT = 90;
const UNKNOWN = 'Outcome unknown. Read the agents again before trying; nothing was retried.';
// The same text bus.js shows for an instances.set answer (bus.js RESTART_TEXT, NO_RESTART_TEXT).
const RESTART_TEXT = 'Restart needed: the running bus keeps the roles it loaded at start. The Console does not restart it.';
const NO_RESTART_TEXT = 'No restart: the launcher reads the change at its next launch check.';
const DONE = { launch: 'Launched', regenerate: 'Regenerated', end: 'Terminated', delete: 'Deleted' };
let ctx = null, view = null, busy = false, receipt = '', confirming = null, pending = null, generation = 0;
let create = { instance: '', definition: '' };
const reasons = {};
// Mirrors the thread definitions used by the existing instances read.
const threadDefinitions = new Set(['assistant', 'companion', 'ideas', 'research', 'proofreader', 'fact-checker', 'continuity']);
const usable = () => !!ctx && (ctx.canSend || ctx.isTester) && !ctx.out();
const human = () => !!ctx && ctx.canSend && !ctx.isTester;
const redraw = () => { if (ctx && !ctx.out()) return ctx.render(); };
const reread = () => { if (ctx && !ctx.out()) ctx.refresh(); };
let editing = null;
function section(v, c) {
ctx = c; view = v;
const { txt, esc } = c, title = '<h2 id="agents-title" class="sr-only">Agents</h2>';
if (!v) return `<section class="panel" id="agents-section">${title}<p class="small warn">The agents could not be read, so there is nothing to act on. Read again to retry.</p></section>`;
const open=usable(), off=!open||busy||pending?' disabled':'', addOff=!open||busy||pending||c.instanceBusyOps.includes('add')?' disabled':'', changeOff=!open||busy||pending||c.instanceBusyOps.includes('change')?' disabled':'', defs=Object.keys(v.definitions||{}), accepted=defs.filter(d=>v.definitions[d]?.accepted);
const instanceStatus=op=>{const text=c.instanceReceipts[op]||'', current=c.instanceReceiptOp===op||(!c.instanceReceiptOp&&op==='add');return `<p role="status" data-instance-receipt="${op}"${current?' id="instances-receipt"':''} class="${text.startsWith('Outcome unknown')?'banner ref':text.includes('Draft kept')?'banner err':text.startsWith('Added')||text.startsWith('Changed')?'settings-success':''}">${txt(text)}</p>`;};
const option=(name,selected,first)=>`<option value="">${first}</option>${accepted.map(d=>`<option value="${esc(d)}"${d===selected?' selected':''}>${txt(d)}</option>`).join('')}`;
const button=(action,name,label)=>`<button type="button"${['keep','unkeep'].includes(action)?' role="menuitem"':''} data-agent-action="${esc(action)}" data-agent-name="${esc(name)}"${off}>${txt(label)}</button>`;
const rows=Object.entries(v.instances).map(([name,e])=>{
const running=Array.isArray(e.running)?e.running:[], alive=Array.isArray(e.alive)?e.alive:[];
const menu=open?`<button type="button" class="agent-more" aria-haspopup="menu" aria-expanded="false" aria-label="More actions for ${esc(name)}"${off}>⋯</button><div class="agent-menu" role="menu" hidden>${!c.isTester&&!e.protected?`<button type="button" role="menuitem" data-agent-edit="${esc(name)}">Edit</button>`:''}<button type="button" role="menuitem" data-agent-dialog="end" data-agent-name="${esc(name)}">Terminate…</button>${!c.isTester?`<button type="button" role="menuitem" data-agent-dialog="regenerate" data-agent-name="${esc(name)}">Regenerate…</button>${button(e.kept?'unkeep':'keep',name,e.kept?'Unkeep':'Keep')}${!e.endProtected?`<hr><button type="button" role="menuitem" class="agent-danger" data-agent-dialog="delete" data-agent-name="${esc(name)}">Delete…</button>`:''}`:''}</div>`:'';
const d=c.instanceDrafts.change?.instance===name?c.instanceDrafts.change:{};
const editor=editing===name?`<tr class="agent-editor"><td colspan="6"><form id="instance-change-form" class="instance-form" data-op="change"><input type="hidden" data-instance-field="instance" value="${esc(name)}"><label>Definition <select data-instance-field="definition"${changeOff}>${option(name,d.definition,'Keep the definition')}</select></label>${v.launch?`<label>Launch <select data-instance-field="launch"${changeOff}><option value="">Keep</option><option value="yes"${d.launch==='yes'?' selected':''}>Launch it</option><option value="no"${d.launch==='no'?' selected':''}>Don't launch it</option></select></label>`:''}<details id="instance-change-vars"><summary>Vars as JSON</summary><p>Harness, model and thinking are set in Routing.</p><label><span class="sr-only">Vars as JSON</span><textarea data-instance-field="vars" rows="3"${changeOff}>${esc(d.vars??'')}</textarea></label></details><div class="settings-actions${c.instanceDrafts.change?' has-draft':''}">${instanceStatus('change')}<button type="submit"${changeOff}>${c.instanceBusyOps.includes('change')?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save agent'}</button><button type="button" data-instance-discard${c.instanceDrafts.change?'':' hidden'}${changeOff}>Discard draft</button></div></form></td></tr>`:'';
return `<tr><th scope="row">${txt(name)}</th><td headers="agent-col-definition"><span class="agent-mobile-label" aria-hidden="true">Definition: </span>${txt(e.definition)}</td><td headers="agent-col-launch"><span class="agent-mobile-label" aria-hidden="true">Launch: </span>${e.launcher?'Launcher':e.launched?'Yes':'No'}</td><td headers="agent-col-kept"><span class="agent-mobile-label" aria-hidden="true">Kept: </span>${e.kept?'Yes':'No'}</td><td headers="agent-col-running"><span class="agent-mobile-label" aria-hidden="true">Running: </span>${running.length?running.map(r=>`<code>${txt(r)}</code>`).join(' '):'<span class="muted">None</span>'}${alive.map(r=>` <strong class="agent-alive">still running after fire: <code>${txt(r)}</code></strong>`).join('')}</td><td class="agent-actions">${threadDefinitions.has(e.definition)?'<span class="agent-start-hint">Starts when you message it</span>':open?button('launch',name,'Launch'):''}${menu}</td></tr>${editor}`;
}).join('');
const d=c.instanceDrafts.add||{}, bound=defs.filter(n=>Array.isArray(v.definitions[n].services)&&v.definitions[n].services.length).map(n=>`${txt(n)} (${v.definitions[n].services.map(txt).join(', ')})`);
const add=!c.isTester&&open?`<section class="panel"><h3>Add an agent</h3><form id="instance-add-form" class="instance-form" data-op="add"><div class="filters"><label>Name <input data-instance-field="instance" value="${esc(d.instance??'')}" maxlength="64"${addOff}></label><label>Definition <select data-instance-field="definition"${addOff}>${option('',d.definition,'Choose a definition')}</select></label>${v.launch?`<label><input type="checkbox" data-instance-field="launch"${d.launch?' checked':''}${addOff}> Launch it</label>`:''}</div><details id="instance-add-vars"><summary>Vars as JSON</summary><p>Harness, model and thinking are set in Routing.</p><label><span class="sr-only">Vars as JSON</span><textarea data-instance-field="vars" rows="3"${addOff}>${esc(d.vars??'')}</textarea></label></details><div class="settings-actions${c.instanceDrafts.add?' has-draft':''}">${instanceStatus('add')}<button type="submit"${addOff}>${c.instanceBusyOps.includes('add')?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Add agent'}</button><button type="button" data-instance-discard${c.instanceDrafts.add?'':' hidden'}${addOff}>Discard draft</button></div></form>${bound.length?`<p>Definitions that declare credentials are a hand edit: ${bound.join(', ')}.</p>`:''}</section>`:'';
const noHire=Array.isArray(v.noHire)?v.noHire:[], retired=Array.isArray(v.retired)?v.retired:[];
const hiring=!c.isTester?`<section class="panel"><h3>Hiring</h3><p>Turn hiring off to stop new agents of a definition.</p><div class="hiring-grid">${defs.map(n=>`<div>${open?`<button type="button" role="switch" aria-label="Hiring allowed for ${esc(n)}" aria-checked="${!noHire.includes(n)}" data-agent-action="${noHire.includes(n)?'hire':'nohire'}" data-agent-name="${esc(n)}"${off}><span class="switch-track"></span></button>`:`<span>${noHire.includes(n)?'Off':'On'}</span>`}<span class="hiring-name">${txt(n)}</span></div>`).join('')}</div>${retired.length?`<p>Retired names, never reused: ${retired.map(txt).join(', ')}.</p>`:''}</section>`:'';
const state=pending?`<p id="agents-pending">Request <code>${txt(pending.request)}</code> to ${txt(pending.action)} ${txt(pending.instance)}: ${txt(pending.state)}.</p>`:'';
return `<div id="agents-section">${title}${state}<section class="panel"><div class="table-wrap" role="region" aria-label="Agents"><table id="agents-table"><thead><tr><th id="agent-col-name" scope="col">Agent</th><th id="agent-col-definition" scope="col">Definition</th><th id="agent-col-launch" scope="col">Launch</th><th id="agent-col-kept" scope="col">Kept</th><th id="agent-col-running" scope="col">Running</th><th scope="col">Actions</th></tr></thead><tbody>${rows}</tbody></table></div><p role="status" id="agents-receipt">${txt(receipt)}</p>${!open||c.isTester?instanceStatus('add'):''}</section>${add}${hiring}<dialog id="agent-dialog" aria-labelledby="agent-dialog-title"><h2 id="agent-dialog-title"></h2><p id="agent-dialog-copy"></p><label id="agent-reason-label" hidden>Reason <input id="agent-dialog-reason" maxlength="500"></label><div><button type="button" id="agent-dialog-confirm">Confirm</button><button type="button" id="agent-dialog-cancel">Cancel</button></div></dialog></div>`;
}
// One POST. `null` means the page signed out; otherwise the status and the parsed answer.
async function post(url, payload) {
const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload), cache: 'no-store', redirect: 'manual' });
if (res.type === 'opaqueredirect') { ctx.signOut(); return null; }
let result = null;
try { result = await res.json(); } catch { /* an unreadable answer is an unknown outcome */ }
return { ok: res.ok, result };
}
const refused = r => r?.sent === false && typeof r.message === 'string' ? `${r.message}` : UNKNOWN;
function plan(action, name) {
switch (action) {
case 'launch': return ['/api/agent/launch', { instance: name }];
case 'regenerate': return ['/api/agent/regenerate', { instance: name }];
case 'end': { const reason = String(reasons[name] ?? '').trim(); return ['/api/agent/terminate', reason ? { instance: name, reason } : { instance: name }]; }
case 'delete': return ['/api/instances', { revision: view.revision, instance: name, op: 'delete' }];
default: return ['/api/veto', { revision: view.revision, op: action, name }];
}
}
async function act(action, name) {
if (!usable() || busy || pending || !view) return;
const [url, payload] = plan(action, name);
busy = true; confirming = null; receipt = ''; redraw();
let answer;
try { answer = await post(url, payload); } catch { answer = { ok: false, result: { sent: 'unknown' } }; }
busy = false;
if (answer === null) return;
const { ok, result } = answer;
if (!ok) { receipt = refused(result); redraw(); return; }
// Row 194 b6 (webby-0094 B1): a veto says whether the reload took, as a create does.
if (url === '/api/veto') { receipt = `${{ keep: 'Kept', unkeep: 'Unkept', nohire: 'No hire for', hire: 'Hiring allowed for' }[action]} ${name}. ${result.restart ? RESTART_TEXT : NO_RESTART_TEXT}`; reread(); return; }
if (!REQUEST_ID.test(result?.request ?? '')) { receipt = UNKNOWN; redraw(); return; }
if (action === 'end') delete reasons[name];
pending = { request: result.request, action, instance: name, state: 'open', tries: 0 };
receipt = action === 'end' && Array.isArray(result.runs)
? `Terminate asked for ${result.runs.length} run${result.runs.length === 1 ? '' : 's'}.` : '';
follow(generation);
}
// Polls the request until it closes, the page signs out or the limit passes. A read that fails
// is shown and the poll goes on; the request itself is never sent again.
async function follow(gen) {
while (pending && gen === generation) {
redraw();
await new Promise(r => setTimeout(r, POLL_MS));
if (!pending || gen !== generation || ctx.out()) return;
if (++pending.tries > POLL_LIMIT) { receipt = `Request ${pending.request} is still ${pending.state}. Read the agents again later.`; pending = null; reread(); return; }
let res, r = null;
try { res = await fetch(`/api/agent/request?id=${encodeURIComponent(pending.request)}`, { cache: 'no-store', redirect: 'manual' }); } catch { continue; }
if (res.type === 'opaqueredirect') { pending = null; ctx.signOut(); return; }
try { r = await res.json(); } catch { continue; }
if (!res.ok || r?.request !== pending.request) { receipt = `Could not read request ${pending.request}: ${r?.message ?? 'no answer'}. Still following it.`; continue; }
pending.state = r.state;
if (r.state !== 'closed') continue;
const { action, instance } = pending;
pending = null;
// sage-1610 (b): a deleted agent's Vikunja bot stays in Vikunja until the human removes it.
const bot = /^bot-[a-z0-9][a-z0-9._-]{0,60}$/.test(r.done?.bot ?? '') ? ` Remove the Vikunja bot user ${r.done.bot} and any token it holds by hand in Vikunja.` : '';
receipt = r.reason ? `${instance}: ${r.done?.refusal && r.reason !== r.done.refusal ? r.done.refusal + ': ' : ''}${r.reason}.` : `${DONE[action] ?? 'Done'} ${instance}${r.done?.run ? ` (run ${r.done.run})` : ''}.${bot}`;
reread();
return;
}
}
async function createAgent() {
if (!usable() || busy || pending || !view || ctx.isTester) return;
const instance = create.instance.trim(), definition = create.definition;
if (!instance || !definition) { receipt = 'Name the instance and choose a definition.'; redraw(); return; }
busy = true; receipt = ''; redraw();
let answer;
try { answer = await post('/api/instances', { revision: view.revision, instance, op: 'add', definition }); } catch { answer = { ok: false, result: { sent: 'unknown' } }; }
busy = false;
if (answer === null) return;
if (answer.ok && /^[a-f0-9]{64}$/.test(answer.result?.revision ?? '')) { create = { instance: '', definition: '' }; receipt = `Created ${instance}. ${answer.result.restart ? RESTART_TEXT : NO_RESTART_TEXT}`; reread(); }
else { receipt = answer.ok ? UNKNOWN : `${refused(answer.result)} Draft kept.`; redraw(); }
}
let dialogAction=null, dialogName=null, dialogReturn=null;
function closeMenu(more, focus=false){const menu=more?.nextElementSibling;if(!menu)return;menu.hidden=true;more.setAttribute('aria-expanded','false');if(focus)more.focus();}
function openMenu(more){document.querySelectorAll('.agent-more[aria-expanded="true"]').forEach(b=>closeMenu(b));more.nextElementSibling.hidden=false;more.setAttribute('aria-expanded','true');more.nextElementSibling.querySelector('button')?.focus();}
document.addEventListener('click', e => {
const t=e.target, more=t.closest?.('.agent-more');
if(more){if(more.getAttribute('aria-expanded')==='true')closeMenu(more);else openMenu(more);return;}
if(t.id==='agent-dialog-cancel'){document.querySelector('#agent-dialog').close();dialogReturn?.focus();return;}
if(t.id==='agent-dialog-confirm'){const dialog=document.querySelector('#agent-dialog');if(dialogAction==='end')reasons[dialogName]=document.querySelector('#agent-dialog-reason').value;dialog.close();act(dialogAction,dialogName);return;}
if(!t.closest?.('#agents-section'))return;
if(t.dataset.agentEdit!==undefined){editing=t.dataset.agentEdit;closeMenu(t.closest('.agent-menu')?.previousElementSibling);redraw()?.then(()=>document.querySelector('#instance-change-form select')?.focus());return;}
if(t.dataset.agentDialog){dialogAction=t.dataset.agentDialog;dialogName=t.dataset.agentName;dialogReturn=t.closest('.agent-menu').previousElementSibling;closeMenu(dialogReturn);const dialog=document.querySelector('#agent-dialog'),label={end:'Terminate',regenerate:'Regenerate',delete:'Delete'}[dialogAction];document.querySelector('#agent-dialog-title').textContent=`${label} ${dialogName}?`;document.querySelector('#agent-dialog-copy').textContent=dialogAction==='regenerate'?`Its workspace is renamed under .retired and it starts fresh.`:dialogAction==='delete'?`Its evidence and its workspace under .retired stay.`:'';document.querySelector('#agent-reason-label').hidden=dialogAction!=='end';document.querySelector('#agent-dialog-reason').value='';document.querySelector('#agent-dialog-confirm').textContent=label;dialog.showModal();(dialogAction==='end'?document.querySelector('#agent-dialog-reason'):document.querySelector('#agent-dialog-cancel')).focus();return;}
const actionButton=t.closest?.('[data-agent-action]');if(actionButton?.disabled)return;const action=actionButton?.dataset.agentAction,name=actionButton?.dataset.agentName;if(action&&name!==undefined){const menu=t.closest('.agent-menu');if(menu)closeMenu(menu.previousElementSibling);act(action,name);}
});
document.addEventListener('keydown',e=>{const menu=e.target.closest?.('.agent-menu'),more=e.target.closest?.('.agent-more');if(more && ['ArrowDown','Enter',' '].includes(e.key)){e.preventDefault();openMenu(more);return;}if(menu){const trigger=menu.previousElementSibling,items=[...menu.querySelectorAll('button')];if(e.key==='Escape'){e.preventDefault();closeMenu(trigger,true);}else if(e.key==='Tab')closeMenu(trigger);else if(e.key==='ArrowDown'||e.key==='ArrowUp'){e.preventDefault();items[(items.indexOf(e.target)+(e.key==='ArrowDown'?1:-1)+items.length)%items.length]?.focus();}}});
document.addEventListener('cancel',e=>{if(e.target.id==='agent-dialog'){e.preventDefault();e.target.close();dialogReturn?.focus();}},true);
document.addEventListener('input', e => {
const t = e.target;
if (t?.dataset?.agentReason !== undefined) reasons[t.dataset.agentReason] = t.value;
else if (t?.dataset?.agentCreate !== undefined) create[t.dataset.agentCreate] = t.value;
});
document.addEventListener('change', e => { const t = e.target; if (t?.dataset?.agentCreate !== undefined) create[t.dataset.agentCreate] = t.value; });
document.addEventListener('submit', e => { if (e.target?.id !== 'agent-create-form') return; e.preventDefault(); createAgent(); });
// A sign-out stops any poll; nothing that was asked is retried.
document.addEventListener('mosaic-signed-out', () => { generation++; pending = null; confirming = null; });
window.MosaicAgents = Object.freeze({ section });
})();