// SPDX-License-Identifier: MIT // The THOT module: binds the page's knowledge — .persona, .prompt, .model, .history, .memory — into a // sagi.thot_manifest/1 document, byte for byte as bankml's sAGI/thot.py, and keeps every generation by its CID. // A manifest holds digests, never content: it can be published; the history and memory bytes stay in this browser. import { useEffect, useState } from 'react'; import type { ModuleWindowProps, UIFModule } from '../core/modules'; import type { UIFContextValue } from '../components/UIFContext'; import { buildManifest, checkStructure, manifestText, type PageFiles } from './thot'; const CURRENT = 'bankml-ui:thot'; const ARCHIVE = 'bankml-ui:thot:archive'; const KEEP = 64; const load = (k: string, d: T): T => { try { const v = localStorage.getItem(k); return v ? (JSON.parse(v) as T) : d; } catch { return d; } }; const save = (k: string, v: unknown) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch { /* storage off */ } }; export function currentManifest(): any | null { return load(CURRENT, null); } export function archivedManifests(): any[] { return load(ARCHIVE, []); } const slugOf = (persona: unknown) => { const name = persona && typeof persona === 'object' ? String((persona as { persona?: string; name?: string }).persona ?? (persona as { name?: string }).name ?? '') : ''; return name.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '').slice(0, 40) || 'agent'; }; /** The page's files, exactly as its windows export them. */ export function pageFiles(uif: UIFContextValue): PageFiles { const c = uif.context; return { slug: slugOf(c.persona), persona: c.fileText('persona'), prompt: c.fileText('prompt'), model: c.fileText('model'), history: c.fileText('history'), memory: c.fileText('memory'), }; } /** Bind (or re-bind) the page's knowledge: the next generation when a facet changed, the same one otherwise. */ export async function bind(uif: UIFContextValue, reason?: string): Promise { const prev = currentManifest(); const m = await buildManifest(pageFiles(uif), prev, `browser/${location.host}/${uif.storageKey}`, reason); save(CURRENT, m); const archive = archivedManifests().filter(x => x.identity?.cid !== m.identity.cid); save(ARCHIVE, [...archive, m].slice(-KEEP)); return m; } function download(name: string, text: string) { const url = URL.createObjectURL(new Blob([text], { type: 'application/json' })); const a = document.createElement('a'); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); } const short = (s: string, n = 14) => (s.length > n ? s.slice(0, n) + '…' : s); function ThotBody({ uif, Tools }: ModuleWindowProps) { const [m, setM] = useState(currentManifest); const [note, setNote] = useState<{ text: string; error?: boolean } | null>(null); const [busy, setBusy] = useState(false); const [pending, setPending] = useState(null); // Which facets differ from the bound manifest right now (what Bind would change). const files = pageFiles(uif); useEffect(() => { let live = true; buildManifest(files, m, 'browser/preview').then(next => { if (!live) return; const was = Object.fromEntries((m?.facets ?? []).map((f: any) => [f.facet, f.sha256])); const now = Object.fromEntries(next.facets.map((f: any) => [f.facet, f.sha256])); setPending([...new Set([...Object.keys(was), ...Object.keys(now)])].filter(k => was[k] !== now[k]).sort()); }); return () => { live = false; }; // the files' text is what matters // eslint-disable-next-line react-hooks/exhaustive-deps }, [m, files.persona, files.prompt, files.model, files.history, files.memory]); const doBind = async () => { setBusy(true); try { const next = await bind(uif); setM(next); setNote({ text: `bound generation ${next.bundle.generation} · ${short(next.identity.cid, 24)}` }); } catch (err) { setNote({ text: (err as Error).message, error: true }); } finally { setBusy(false); } }; const doVerify = async () => { if (!m) return; const findings = await checkStructure(m); setNote(findings.length ? { text: findings.join('; '), error: true } : { text: 'verified: every root and the identity recompute (§8)' }); }; return (
{m ? (
{m.bundle.officer} · generation {m.bundle.generation} {m.bundle.parent && · parent {short(m.bundle.parent, 20)}}
{m.identity.name} {m.facets.map((f: any) => ( ))}
{f.facet} {f.bytes.toLocaleString()} B {short(f.sha256, 12)}
bundle root {short(m.bundle_root.value, 12)} merkle {short(m.merkle.root, 12)} {m.doctrine_root && doctrine {short(m.doctrine_root, 12)}} rung {m.rung.value}
) : (

Nothing bound yet. Bind commits this page's .persona, .prompt, .model, .history and .memory into a THOT manifest (sagi.thot_manifest/1): digests only, so it can be published; the history and memory stay in this browser.

)}

{pending === null ? '…' : pending.length ? `changed since the bound generation: ${pending.join(', ')}` : m ? 'nothing changed since this generation' : ''}

{archivedManifests().length} generation{archivedManifests().length === 1 ? '' : 's'} kept
{note &&

{note.text}

}
); } /** The THOT module. `field` reaches the page's state for the terminal command (the window gets it as a prop). */ export function makeThotModule(field: () => UIFContextValue | null): UIFModule { return { id: 'thot', label: 'THOT', windows: [ { id: 'thot', file: 'THOT', icon: '◆', summary: "Bind this page's knowledge into a THOT manifest", Body: ThotBody, detail: () => { const m = currentManifest(); return m ? `gen ${m.bundle.generation}` : 'not bound'; }, }, ], actions: [ { id: 'thot-bind', label: 'Bind THOT', command: 'bind', icon: '◆', description: "bind [reason] - bind this page's knowledge into the next THOT generation (digests only; the bytes stay here)", defaultHidden: true, async run(ctx) { const uif = field(); if (!uif) return ctx.print('bind: the page is still starting', 'err'); const m = await bind(uif, ctx.args.join(' ') || undefined); ctx.print(`THOT generation ${m.bundle.generation} · ${m.identity.name}`); ctx.print(`bundle root ${m.bundle_root.value} · merkle ${m.merkle.root} · ${m.facets.length} facets`); }, }, ], }; }