Files
stack/packages/webui/src/public/agents.js
T
jason.woltje bb2f79f3d9 fix(webui): sp1 review round, a switch carries nothing across and first run keeps its board (#1873, lane sp1)
- First run (no organization yet) keeps #/ as its board; the router no longer rewrites it to
  #/dashboard, which first run cannot draw.
- An organization switch stops the agents section's request poll and clears what it held. A
  route-change restart chain finishes on the organization it started in.
- A write in flight at a switch drops its answer: an org epoch in bus.js, checked after each
  await. The switch clears every busy flag, receipt and reply, and the doc drafts.
- The bus banner reads org state again only when the route crosses /dashboard, not on every
  hashchange inside one organization.
- The down banner does not repeat its heading as the reason.
- Tests: first run wordmark, poll stop on switch, restart pinned to its organization, settings
  save in flight at a switch, banner without a repeated reason. The org-switch test comment and
  wait match the in-place switch.
2026-11-14 23:19:05 -06:00

465 lines
45 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 org 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 restartText(), NO_RESTART_TEXT).
// F3: on an organization Console its owner restarts the bus from the receipt (console-restart.js).
const restartText = () => window.MosaicConsole?.busRestart
? 'Restart needed: the running bus keeps the roles it loaded at start. Restart the bus to load the change.'
: 'Restart needed: the running bus keeps the roles it loaded at start. The Console does not restart it.';
const busControl = text => (String(text).includes('Restart needed:') ? window.MosaicConsole?.busButton('Restart bus') ?? '' : '');
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>${busControl(text)}`;};
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>${busControl(receipt)}${!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();
const gen = generation;
let answer;
try { answer = await post(url, payload); } catch { answer = { ok: false, result: { sent: 'unknown' } }; }
// #1873 SP1: an organization switch while this was in flight drops the answer; the switch already cleared busy.
if (gen !== generation) return;
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 ? restartText() : 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();
const gen = generation;
let answer;
try { answer = await post('/api/instances', { revision: view.revision, instance, op: 'add', definition }); } catch { answer = { ok: false, result: { sent: 'unknown' } }; }
if (gen !== generation) return;
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 ? restartText() : 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; });
// #1873 SP1: opening another organization stops any poll and clears what this section held for the
// old one. A request already sent finishes on the old organization's bus; its page reads it again there.
document.addEventListener('mosaic-org-switch', () => {
generation++; pending = null; receipt = ''; editing = null; confirming = null; busy = false;
create = { instance: '', definition: '' };
for (const k of Object.keys(reasons)) delete reasons[k];
});
// F3: restart an agent so a route change reaches it now, offered by the Routing receipt. One
// terminate; then reads of the instances until the run has left (up to the 60 s regenerate
// allows); then one launch. A thread definition is not launched: its next message starts it.
// A refusal, a sign-out or an unknown outcome stops the chain and says so; nothing is retried.
let restarts = Object.create(null);
// #1873 SP1: the chain's reads and writes go to the organization it started in, which the fetch
// wrapper passes through unchanged. A switch clears what the new page shows; the old chain keeps
// its own entry and stops painting.
const pin = (org, path) => org ? `/api/orgs/${encodeURIComponent(org)}/${path.slice('/api/'.length)}` : path;
document.addEventListener('mosaic-org-switch', () => { restarts = Object.create(null); });
const RESTART_WAIT = 30;
function restartMarkup(name, thread = false) {
const r = restarts[name];
return `<span class="agent-restart"><button type="button" class="btn" data-agent-restart="${esc(name)}" data-agent-thread="${thread ? 'yes' : 'no'}"${r?.busy ? ' disabled' : ''}>${r?.busy ? 'Restarting…' : `Restart ${esc(name)} now`}</button> <span role="status" data-agent-restart-status="${esc(name)}">${esc(r?.text ?? '')}</span></span>`;
}
const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
const paintRestart = (name, org = window.MosaicOrg?.id ?? null) => (window.MosaicOrg?.id ?? null) !== org ? undefined : document.querySelectorAll('.agent-restart').forEach(el => {
const b = el.querySelector('[data-agent-restart]');
if (b?.dataset.agentRestart === name) el.outerHTML = restartMarkup(name, b.dataset.agentThread === 'yes');
});
async function send(url, payload) {
let res, result = null;
try { res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload), cache: 'no-store', redirect: 'manual' }); }
catch { return { unknown: true }; }
if (res.type === 'opaqueredirect') return { signedOut: true };
try { result = await res.json(); } catch { return { unknown: true }; }
return { ok: res.ok, result };
}
// The request's closing read, or a reason the chain stops.
async function closing(request, org) {
for (let tries = 0; tries < POLL_LIMIT; tries++) {
await new Promise(r => setTimeout(r, POLL_MS));
let res, r = null;
try { res = await fetch(pin(org, `/api/agent/request?id=${encodeURIComponent(request)}`), { cache: 'no-store', redirect: 'manual' }); } catch { continue; }
if (res.type === 'opaqueredirect') return { stop: 'Sign in again, then read the agents.' };
try { r = await res.json(); } catch { continue; }
if (res.ok && r?.request === request && r.state === 'closed') return { done: r };
}
return { stop: `Request ${request} is still open. Read the agents again later.` };
}
async function runs(name, org) {
try {
const res = await fetch(pin(org, '/api/bus/instances'), { cache: 'no-store', redirect: 'manual' });
if (!res.ok || res.type === 'opaqueredirect') return null;
const e = (await res.json())?.rows?.[0]?.instances?.[name];
return e ? (Array.isArray(e.running) ? e.running.length : 0) : 0;
} catch { return null; }
}
async function restartAgent(name, thread) {
const org = window.MosaicOrg?.id ?? null;
const r = restarts[name] = { busy: true, text: `Terminating ${name}…` };
const paint = () => paintRestart(name, org);
const stop = text => { r.busy = false; r.text = text; paint(); };
paint();
const asked = await send(pin(org, '/api/agent/terminate'), { instance: name, reason: 'route change' });
if (asked.signedOut) return stop('Sign in again, then retry.');
if (asked.unknown || !asked.ok || !REQUEST_ID.test(asked.result?.request ?? '')) return stop(asked.ok || asked.unknown ? UNKNOWN : refused(asked.result));
const ended = await closing(asked.result.request, org);
if (ended.stop) return stop(ended.stop);
if (ended.done.reason) return stop(`${name}: ${ended.done.reason}. It was not restarted.`);
r.text = `Terminated ${name}. Waiting for its session to end…`; paint();
let left = false;
for (let i = 0; i < RESTART_WAIT && !left; i++) { await new Promise(res => setTimeout(res, POLL_MS)); left = (await runs(name, org)) === 0; }
if (!left) return stop(`${name} was asked to end but its session is still running. Launch it from Agents once it has ended.`);
if (thread) return stop(`Terminated ${name} at ${new Date().toLocaleTimeString()}. Its next message starts it on the new route.`);
r.text = `Launching ${name}…`; paint();
const launch = await send(pin(org, '/api/agent/launch'), { instance: name });
if (launch.signedOut) return stop('Sign in again. It was terminated and not launched.');
if (launch.unknown || !launch.ok || !REQUEST_ID.test(launch.result?.request ?? '')) return stop(launch.ok || launch.unknown ? `${UNKNOWN} It was terminated.` : `${refused(launch.result)} It was terminated and not launched.`);
const started = await closing(launch.result.request, org);
if (started.stop) return stop(started.stop);
if (started.done.reason) return stop(`${name}: ${started.done.reason}. It was terminated and not launched.`);
return stop(`Restarted ${name} on the new route${started.done.done?.run ? ` (run ${started.done.done.run})` : ''}.`);
}
document.addEventListener('click', e => {
const b = e.target.closest?.('[data-agent-restart]');
if (!b || b.disabled || restarts[b.dataset.agentRestart]?.busy) return;
restartAgent(b.dataset.agentRestart, b.dataset.agentThread === 'yes');
});
window.MosaicAgents = Object.freeze({ section, restartMarkup, isThread: definition => threadDefinitions.has(definition) });
})();
/* #1873 A2: Settings > Agents, the root and project agent levels. bus.js awaits section() for the
Agents page and puts it under the organization's own agents. Each grid comes from a fresh read:
GET /api/agents/root for the root file and GET /api/orgs/<org>/agent-levels/projects/<project>
for a project, each with the revision a write sends back. After a write the section reads
everything again and repaints. The server checks the owner, the exact Origin and Fetch Metadata,
the revision and the documents; this file only asks and reports. It never shows a var value
other than the model, and its own messages name keys only. */
(() => {
'use strict';
const $ = id => document.getElementById(id);
const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
const clock = () => new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
const enc = encodeURIComponent;
const UNKNOWN = 'Outcome unknown. Nothing was retried. The grid below was read again.';
let root = null, levels = null, project = null, selected = { org: '', project: '' };
let receipts = { root: '', project: '' }, busy = false, confirming = null;
// What each form holds, kept here so a polling render, a picker change or the other form's save
// repaints it as typed. A draft keeps the revision it began at, so a save sends that and a file
// changed meanwhile refuses rather than being overwritten unseen. The project draft belongs to its
// organization and project. Only the submitted form's own success clears it.
const drafts = { root: null, project: null };
const read = url => fetch(url, { cache: 'no-store', redirect: 'manual' }).then(async r => {
if (r.type === 'opaqueredirect') return { signedOut: true };
let body = null; try { body = await r.json(); } catch { /* unreadable */ }
return r.ok ? body : { refused: body?.error ?? 'unreadable', status: r.status };
}).catch(() => null);
async function load() {
[levels, root] = await Promise.all([read('/api/agents/levels'), read('/api/agents/root')]);
const orgs = orgsOf();
if (!orgs.some(o => o.id === selected.org)) selected = { org: window.MosaicOrg?.id && orgs.some(o => o.id === window.MosaicOrg.id) ? window.MosaicOrg.id : (orgs[0]?.id ?? ''), project: '' };
const projects = orgs.find(o => o.id === selected.org)?.projects ?? [];
if (!projects.includes(selected.project)) selected.project = projects[0] ?? '';
project = selected.org && selected.project ? await read(`/api/orgs/${enc(selected.org)}/agent-levels/projects/${enc(selected.project)}`) : null;
}
const orgsOf = () => (Array.isArray(levels?.orgs) ? levels.orgs : []).filter(o => o?.state === 'ok')
.map(o => ({ id: o.id, projects: [...new Set([...Object.keys(o.projects ?? {}), ...Object.keys(o.defined ?? {})])].sort() }));
const writable = () => root?.writable === true;
// KEY=VALUE lines. A value that reads as JSON other than a string (a number, true, false, a list
// or an object) is sent as JSON. A malformed line is named by its number, never by its text.
function parseVars(text) {
const vars = {};
const lines = String(text ?? '').split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (!line) continue;
const at = line.indexOf('=');
if (at < 1) throw new Error(`Variables line ${i + 1} needs KEY=VALUE.`);
const key = line.slice(0, at).trim(), raw = line.slice(at + 1).trim();
if (Object.hasOwn(vars, key)) throw new Error(`Variable ${key} is given twice.`);
let value = raw;
try { const parsed = JSON.parse(raw); if (typeof parsed !== 'string') value = parsed; } catch { /* a plain string */ }
vars[key] = value;
}
return vars;
}
const list = text => String(text ?? '').split(',').map(s => s.trim()).filter(Boolean);
function rootGrid() {
if (!root || root.refused || root.signedOut) return `<p class="small warn" id="agent-levels-root-grid">The root agent file could not be read${root?.refused ? ` (${esc(root.refused)})` : ''}. Nothing can be changed until it reads.</p>`;
if (!root.agents.length) return `<p class="muted" id="agent-levels-root-grid">No root agents${root.state === 'absent' ? '; the root agent file does not exist yet' : ''}.</p>`;
const off = !writable() || busy ? ' disabled' : '';
return `<div class="table-wrap" role="region" aria-label="Root agents"><table id="agent-levels-root-grid"><thead><tr><th scope="col">Agent</th><th scope="col">Definition</th><th scope="col">Model</th><th scope="col">Other variables</th><th scope="col">Not in</th><th scope="col">Actions</th></tr></thead><tbody>${root.agents.map(a => `<tr data-root-agent="${esc(a.name)}"><th scope="row">${esc(a.name)}</th><td>${esc(a.definition ?? '')}</td><td>${a.model ? `<code>${esc(a.model)}</code>` : '<span class="muted">Inherited</span>'}</td><td>${a.varKeys.length ? a.varKeys.map(k => `<code>${esc(k)}</code>`).join(' ') : '<span class="muted">None</span>'}</td><td>${a.excludeOrgs.length ? a.excludeOrgs.map(esc).join(', ') : '<span class="muted">Every organization</span>'}</td><td>${writable() ? `<button type="button" data-level-remove="root" data-level-name="${esc(a.name)}"${off}>${confirming === `root:${a.name}` ? 'Confirm remove' : 'Remove'}</button>` : ''}</td></tr>`).join('')}</tbody></table></div>`;
}
function projectGrid() {
if (!selected.project) return '<p class="muted" id="agent-levels-project-grid">This organization has no projects.</p>';
if (!project || project.refused || project.signedOut) return `<p class="small warn" id="agent-levels-project-grid">The project could not be read${project?.refused ? ` (${esc(project.refused)})` : ''}.</p>`;
if (project.library) return '<p class="muted" id="agent-levels-project-grid">This is a library project; it takes no agents.</p>';
if (!project.agents.length) return '<p class="muted" id="agent-levels-project-grid">No project entries. The project has the organization\'s agents and the root agents.</p>';
const off = !writable() || busy ? ' disabled' : '';
const what = a => a.form === 'define' ? `Defines ${esc(a.definition ?? '')}` : a.form === 'narrow' ? 'Narrows an inherited agent' : 'Excludes an inherited agent';
return `<div class="table-wrap" role="region" aria-label="Project agent entries"><table id="agent-levels-project-grid"><thead><tr><th scope="col">Agent</th><th scope="col">Entry</th><th scope="col">Variables</th><th scope="col">Actions</th></tr></thead><tbody>${project.agents.map(a => `<tr data-project-agent="${esc(a.name)}" data-form="${esc(a.form)}"><th scope="row">${esc(a.name)}</th><td>${what(a)}</td><td>${a.varKeys?.length ? a.varKeys.map(k => `<code>${esc(k)}</code>`).join(' ') : '<span class="muted">None</span>'}</td><td>${writable() ? `<button type="button" data-level-remove="project" data-level-name="${esc(a.name)}"${off}>${confirming === `project:${a.name}` ? 'Confirm remove' : 'Remove'}</button>` : ''}</td></tr>`).join('')}</tbody></table></div>`;
}
const receiptLine = which => {
const text = receipts[which];
return `<p role="status" id="agent-levels-${which}-receipt" class="${text.startsWith('Saved') || text.startsWith('Removed') ? 'settings-success' : text ? 'banner err' : ''}">${esc(text)}</p>`;
};
const projectDraft = () => drafts.project && drafts.project.org === selected.org && drafts.project.project === selected.project ? drafts.project : null;
const shownDraft = which => which === 'root' ? drafts.root : projectDraft();
const field = (which, key) => esc(shownDraft(which)?.values?.[key] ?? '');
const filled = d => !!d && Object.entries(d.values).some(([k, v]) => k !== 'form' && String(v).trim());
function markup() {
if (!levels || levels.refused || levels.signedOut) return '';
const off = !writable() || busy ? ' disabled' : '';
const at = (which, current) => esc(shownDraft(which)?.revision ?? current);
const key = (which, name) => ` data-focus-key="level-${which}-${name}"`;
const chosen = v => (projectDraft()?.values?.form ?? 'define') === v ? ' selected' : '';
const readOnly = writable() ? '' : '<p class="small">This Console was started without writes, so these levels are read only here. <code>mosaic agents root</code> and <code>mosaic project agents</code> change them from a terminal.</p>';
const rootForm = writable() && root && !root.refused ? `<form id="agent-levels-root-form" class="level-form" data-revision="${at('root', root.revision)}"><h4>Add or change a root agent</h4><div class="filters"><label>Name <input name="name" maxlength="64" required autocomplete="off" value="${field('root', 'name')}"${key('root', 'name')}${off}></label><label>Definition <input name="definition" maxlength="64" autocomplete="off" placeholder="Unchanged" value="${field('root', 'definition')}"${key('root', 'definition')}${off}></label><label>Model <input name="model" maxlength="200" autocomplete="off" placeholder="Unchanged" value="${field('root', 'model')}"${key('root', 'model')}${off}></label></div><div class="filters"><label>Other variables, one KEY=VALUE per line <textarea name="vars" rows="2"${key('root', 'vars')}${off}>${field('root', 'vars')}</textarea></label><label>Remove variables, comma separated <input name="unset" autocomplete="off" value="${field('root', 'unset')}"${key('root', 'unset')}${off}></label><label>Not in organizations, comma separated, or none <input name="excludeOrgs" autocomplete="off" placeholder="Unchanged" value="${field('root', 'excludeOrgs')}"${key('root', 'excludeOrgs')}${off}></label></div><div class="settings-actions${filled(drafts.root) ? ' has-draft' : ''}"><button type="submit"${off}>Save root agent</button></div></form>` : '';
const orgs = orgsOf(), projects = orgs.find(o => o.id === selected.org)?.projects ?? [];
const pick = `<div class="filters"><label>Organization <select id="agent-levels-org"${busy ? ' disabled' : ''}>${orgs.map(o => `<option value="${esc(o.id)}"${o.id === selected.org ? ' selected' : ''}>${esc(o.id)}</option>`).join('')}</select></label><label>Project <select id="agent-levels-project"${busy ? ' disabled' : ''}>${projects.map(p => `<option value="${esc(p)}"${p === selected.project ? ' selected' : ''}>${esc(p)}</option>`).join('')}</select></label></div>`;
const projectForm = writable() && project && !project.refused && !project.library ? `<form id="agent-levels-project-form" class="level-form" data-revision="${at('project', project.revision)}"><h4>Add or change a project entry</h4><div class="filters"><label>Agent <input name="name" maxlength="64" required autocomplete="off" value="${field('project', 'name')}"${key('project', 'name')}${off}></label><label>Entry <select name="form"${key('project', 'form')}${off}><option value="define"${chosen('define')}>Define a project agent</option><option value="narrow"${chosen('narrow')}>Narrow an inherited agent</option><option value="exclude"${chosen('exclude')}>Exclude an inherited agent</option></select></label><label>Definition, for a defined agent <input name="definition" maxlength="64" autocomplete="off" value="${field('project', 'definition')}"${key('project', 'definition')}${off}></label></div><label>Variables, one KEY=VALUE per line. A narrow takes limits.tools, limits.network and limits.authority only. <textarea name="vars" rows="2"${key('project', 'vars')}${off}>${field('project', 'vars')}</textarea></label><div class="settings-actions${filled(projectDraft()) ? ' has-draft' : ''}"><button type="submit"${off}>Save project entry</button></div></form>` : '';
return `<div id="agent-levels-edit" data-agent-levels-edit><section class="panel" aria-labelledby="agent-levels-root-title"><h3 id="agent-levels-root-title">Root agents</h3><p>Root agents are in every organization unless a row excludes it. They are read from the instance's root agent file and are not launched yet.</p>${readOnly}${rootGrid()}${receiptLine('root')}${rootForm}</section><section class="panel" aria-labelledby="agent-levels-project-title"><h3 id="agent-levels-project-title">Project agents</h3><p>A project can define its own agents, narrow an inherited agent's limits, or exclude one. Project agents are not launched yet.</p>${orgs.length ? pick : '<p class="muted">No organization to show.</p>'}${orgs.length ? projectGrid() : ''}${receiptLine('project')}${projectForm}</section></div>`;
}
const repaint = () => { const box = $('agent-levels-edit'); if (box) box.outerHTML = markup(); };
async function section() {
await load();
return markup();
}
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') return { signedOut: true };
let body = null; try { body = await res.json(); } catch { /* unknown below */ }
return { ok: res.ok, body };
}
const refusedText = body => body?.error === 'revision-conflict' ? 'Refused: the file changed since this page read it. The grid below was read again; check it and save again.'
: typeof body?.message === 'string' ? `Refused (${body.error}): ${body.message}` : UNKNOWN;
// fromForm: the submitted form's draft is cleared on success. A row's Remove leaves it alone.
async function write(which, url, payload, done, focus, fromForm = false) {
busy = true; receipts[which] = ''; repaint();
let answer;
try { answer = await post(url, payload); } catch { answer = null; }
busy = false; confirming = null;
if (answer?.signedOut) { receipts[which] = 'Sign in again, then retry.'; repaint(); return false; }
const ok = answer?.ok && answer.body?.outcome === 'done';
receipts[which] = ok ? done(answer.body.receipt) : answer ? refusedText(answer.body) : UNKNOWN;
const conflict = answer?.body?.error === 'revision-conflict';
await load();
if (ok && fromForm) drafts[which] = null;
// After a conflict the grid is read again and the receipt asks for a check: the next save is a
// deliberate one against what is shown now.
if (conflict && fromForm && shownDraft(which)) shownDraft(which).revision = which === 'root' ? root?.revision : project?.revision;
repaint();
(focus && $(focus))?.focus?.();
return ok;
}
// Take what a form holds into its draft, keeping the revision the draft began at.
function capture(form) {
const which = form.id === 'agent-levels-root-form' ? 'root' : 'project';
const values = Object.fromEntries(new FormData(form));
const old = shownDraft(which);
drafts[which] = { ...(which === 'project' ? { org: selected.org, project: selected.project } : {}), revision: old?.revision ?? form.dataset.revision, values };
form.querySelector('.settings-actions')?.classList.toggle('has-draft', filled(drafts[which]));
return which;
}
async function saveRoot(form) {
const f = Object.fromEntries(new FormData(form));
const name = String(f.name ?? '').trim(), entry = {};
try {
if (String(f.definition ?? '').trim()) entry.definition = String(f.definition).trim();
const vars = parseVars(f.vars);
if (String(f.model ?? '').trim()) { if (Object.hasOwn(vars, 'model')) throw new Error('Variable model is given twice.'); vars.model = String(f.model).trim(); }
for (const key of list(f.unset)) { if (Object.hasOwn(vars, key)) throw new Error(`Variable ${key} is both set and removed.`); vars[key] = null; }
if (Object.keys(vars).length) entry.vars = vars;
if (String(f.excludeOrgs ?? '').trim()) entry.excludeOrgs = String(f.excludeOrgs).trim() === 'none' ? [] : list(f.excludeOrgs);
if (!name) throw new Error('A root agent needs a name.');
if (!Object.keys(entry).length) throw new Error('Nothing to change: give a definition, a variable or the organizations it is not in.');
} catch (error) { receipts.root = error.message; capture(form); repaint(); return; }
await write('root', '/api/agents/root', { revision: form.dataset.revision, name, entry },
r => `Saved ${r.agent} at ${clock()}: ${r.changed.join(', ')}.`, 'agent-levels-root-title', true);
}
async function saveProject(form) {
const f = Object.fromEntries(new FormData(form));
const name = String(f.name ?? '').trim();
let entry;
try {
if (!name) throw new Error('A project entry needs an agent name.');
const vars = parseVars(f.vars);
if (f.form === 'exclude') { if (Object.keys(vars).length || String(f.definition ?? '').trim()) throw new Error('An exclude takes no definition and no variables.'); entry = { exclude: true }; }
else if (f.form === 'narrow') { if (String(f.definition ?? '').trim()) throw new Error('A narrow takes no definition.'); if (!Object.keys(vars).length) throw new Error('A narrow needs at least one variable.'); entry = { vars }; }
else { if (!String(f.definition ?? '').trim()) throw new Error('A defined agent needs a definition.'); entry = { definition: String(f.definition).trim(), ...(Object.keys(vars).length ? { vars } : {}) }; }
} catch (error) { receipts.project = error.message; capture(form); repaint(); return; }
await write('project', `/api/orgs/${enc(selected.org)}/agent-levels/projects/${enc(selected.project)}`, { revision: form.dataset.revision, name, entry },
r => `Saved ${r.agent} in ${r.project} at ${clock()}: ${r.form}.`, 'agent-levels-project-title', true);
}
async function remove(which, name) {
if (confirming !== `${which}:${name}`) { confirming = `${which}:${name}`; repaint(); document.querySelector(`[data-level-remove="${which}"][data-level-name="${CSS.escape(name)}"]`)?.focus(); return; }
if (which === 'root') await write('root', '/api/agents/root', { revision: root.revision, name, entry: null }, r => `Removed ${r.agent} at ${clock()}.`, 'agent-levels-root-title');
else await write('project', `/api/orgs/${enc(selected.org)}/agent-levels/projects/${enc(selected.project)}`, { revision: project.revision, name, entry: null }, r => `Removed ${r.agent} from ${r.project} at ${clock()}.`, 'agent-levels-project-title');
}
document.addEventListener('submit', e => {
const form = e.target;
if (form.id !== 'agent-levels-root-form' && form.id !== 'agent-levels-project-form') return;
e.preventDefault();
if (busy) return;
capture(form);
(form.id === 'agent-levels-root-form' ? saveRoot : saveProject)(form);
});
for (const kind of ['input', 'change']) document.addEventListener(kind, e => {
const form = e.target?.closest?.('.level-form');
if (form && e.target !== form) capture(form);
});
document.addEventListener('click', e => {
const button = e.target.closest?.('[data-level-remove]');
if (!button || button.disabled || busy || !writable()) return;
remove(button.dataset.levelRemove, button.dataset.levelName);
});
document.addEventListener('change', async e => {
if (e.target.id !== 'agent-levels-org' && e.target.id !== 'agent-levels-project') return;
if (e.target.id === 'agent-levels-org') selected = { org: e.target.value, project: '' };
else selected.project = e.target.value;
receipts.project = ''; confirming = null;
const id = e.target.id;
await load(); repaint(); $(id)?.focus();
});
// hasDraft feeds the Settings nav's unsaved-changes dot (bus.js settingsShell and its input listener).
window.MosaicAgentLevels = Object.freeze({ section, hasDraft: () => filled(drafts.root) || filled(drafts.project) });
})();