// The service's HTML: the landing page at `/`, the signed-in page, the chat page, the 404, and the // shell the sign-in pages in src/oauth.ts share. Server-rendered, no external assets. Only the chat // and docs pages (and the landing, for its copy button) run scripts, their own (/chat.js, /docs.js), and nothing inline. // // The look follows the first languid.ai (2024): lowercase, `# headings`, dashed rules, green on // hover, and the snail. The text is Inter, served from src/fonts; code stays monospace. import crypto from 'node:crypto' import fs from 'node:fs' import { publishedClientRelease, renderClientInstaller } from './client-release.ts' import { diffLines, diffWordsWithSpace } from 'diff' import { checkPrice } from './auto-approve.ts' import { DEFAULT_SERVICE } from './state.ts' import { RISK_DOCS, RISK_LINES, RISK_TITLE } from './computer-risk.ts' import { CONNECTION_SHOWN, CONNECTIONS, type Connection, HOUSE_LABEL, makerOf, RECENT_SHOWN } from './model-groups.ts' import { MANAGED_MARKUP } from './owners.ts' import { OWNER_WORK, ownerProfileSummary, type OwnerProfile } from './records.ts' export interface Page { status: number headers: Record body: string } /** * The snail: one line from tail to head, a spiral shell, two stalks. Drawn for languid, 64x64. The * stalks end in their round caps; dots on the tips, wider than the stroke, left a step on each. */ const SNAIL_ATTRS = 'viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="5.5" stroke-linecap="round" stroke-linejoin="round"' /** * The header's viewBox: SNAIL_ATTRS's cropped to the ink (strokes included), which sits low and to * the right in the 64x64 box. Centering the cropped box beside the text centers the drawing itself. */ const SNAIL_INK_VIEWBOX = '6.5 18.5 53.5 38.5' const SNAIL = '' /** The tab icon: the snail, dark on light tab bars and light on dark ones. */ export const FAVICON = `${SNAIL}` /** The favicon's address carries a hash of it, so browsers that cached an older icon fetch this one. */ const FAVICON_HREF = `/favicon.svg?v=${crypto.createHash('sha256').update(FAVICON).digest('hex').slice(0, 10)}` /** The 404 from the first languid.ai. */ const ART_404 = `____________/\\\\\\________/\\\\\\\\\\\\\\_______________/\\\\\\____ __________/\\\\\\\\\\______/\\\\\\/////\\\\\\___________/\\\\\\\\\\____ ________/\\\\\\/\\\\\\_____/\\\\\\____\\//\\\\\\________/\\\\\\/\\\\\\____ ______/\\\\\\/\\/\\\\\\____\\/\\\\\\_____\\/\\\\\\______/\\\\\\/\\/\\\\\\____ ____/\\\\\\/__\\/\\\\\\____\\/\\\\\\_____\\/\\\\\\____/\\\\\\/__\\/\\\\\\____ __/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_\\/\\\\\\_____\\/\\\\\\__/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_ _\\///////////\\\\\\//__\\//\\\\\\____/\\\\\\__\\///////////\\\\\\//__ ___________\\/\\\\\\_____\\///\\\\\\\\\\\\\\/_____________\\/\\\\\\____ ___________\\///________\\///////_______________\\///_____` /** A message that may start lowercase (errors are written for the CLI), capitalized for a page. */ export const sentence = (s: string) => s.charAt(0).toUpperCase() + s.slice(1) export const esc = (s: string) => s.replace(/[&<>"']/g, (ch) => `&#${ch.charCodeAt(0)};`) /** Inter (OFL, src/fonts/inter-license.txt): Fontsource's Latin subset, one variable-weight file. */ export const INTER = fs.readFileSync(new URL('./fonts/inter-latin-wght-normal.woff2', import.meta.url)) export const INTER_HREF = `/fonts/inter.woff2?v=${crypto.createHash('sha256').update(INTER).digest('hex').slice(0, 10)}` /** Fonts the service serves from /fonts, by path, with their content types. A missing file is left out. */ export const FONT_FILES: Record = { '/fonts/inter.woff2': { data: INTER, type: 'font/woff2' } } function fontHref(route: string, file: string, type: string): string | undefined { try { const data = fs.readFileSync(new URL(`./fonts/${file}`, import.meta.url)) FONT_FILES[route] = { data, type } return `${route}?v=${crypto.createHash('sha256').update(data).digest('hex').slice(0, 10)}` } catch { return undefined } } /** Titles and agent names: Comfortaa, round like the mark. */ const DISPLAY_HREF = fontHref('/fonts/comfortaa.ttf', 'comfortaa.ttf', 'font/ttf') /** Everything else, when the file is there; Inter otherwise. */ const FRANKLIN_HREF = fontHref('/fonts/libre-franklin.ttf', 'libre-franklin.ttf', 'font/ttf') const SANS = '"Libre Franklin",Inter,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif' const DISPLAY = 'Comfortaa,"Libre Franklin",system-ui,sans-serif' const MONO = 'ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,"Liberation Mono",monospace' /** * The Foot and shell scale. Every size on every page comes from these: four text sizes and three * display sizes, three weights, a 4px spacing step, three radii, two control heights, and two line * weights (hairlines for dividers, the mark's 1.5px for icons). Documented on the Foot and shell page. */ const SCALE = '--t-xs:.75rem;--t-sm:.875rem;--t-md:1rem;--t-lg:1.125rem;' + '--d-sm:1.25rem;--d-md:1.5rem;--d-lg:2.5rem;--d-xl:clamp(2.25rem,4.5vw,3.25rem);' + '--w-regular:400;--w-medium:500;--w-strong:600;' + '--s-1:.25rem;--s-2:.5rem;--s-3:.75rem;--s-4:1rem;--s-5:1.5rem;--s-6:2rem;--s-7:3rem;' + '--r-pill:999px;--r-block:12px;--r-panel:18px;' + '--control:2rem;--control-sm:1.75rem;--hairline:1px;--stroke:1.5px;--fast:120ms' const TOKENS_LIGHT = '--bg:#faf9f6;--fg:#1c1a17;--ink2:#2f2c28;--muted:#59544d;--faint:#7a746b;--line:#d6d0c5;--hr:#e9e5de;--hair:#e9e5de;--box:#f1eee8;--code:#f1eee8;' + '--tint:rgb(28 26 23/.04);--tint2:rgb(28 26 23/.07);--glass:#faf9f6;--hi:transparent;--shadow:none;' + '--green:#1c1a17;--green-rgb:28 26 23;--amber:#1c1a17;--amber-rgb:28 26 23;--red:#8f2d1f;--red-rgb:143 45 31;--on-green:#faf9f6' const TOKENS_DARK = '--bg:#131210;--fg:#d3cec5;--ink2:#b5afa5;--muted:#8a847b;--faint:#706b64;--line:#3a3631;--hr:#2a2724;--hair:#2a2724;--box:#1d1b18;--code:#1d1b18;' + '--tint:rgb(211 206 197/.05);--tint2:rgb(211 206 197/.09);--glass:#131210;--hi:transparent;--shadow:none;' + '--green:#d3cec5;--green-rgb:211 206 197;--amber:#d3cec5;--amber-rgb:211 206 197;--red:#d98b7a;--red-rgb:217 139 122;--on-green:#131210' /** * Foot and shell, over the older rules: Comfortaa for titles and names, pill controls, no glass, * no colour for state (the shell glyphs carry it), and every transition fast. */ const FOOT_AND_SHELL = [ `h1,.empty h2,.thread-bar h1,article.docs h1,article.docs h2,.box-title,.mark b,.app-body>main h2,.thread-panel .agent-card b{font-family:${DISPLAY};font-weight:400}`, 'h1{letter-spacing:0}', '.app-body>main h1{font-size:clamp(2.2rem,4.5vw,3.2rem);line-height:1.05;margin:.75rem 0 .75rem}', '.app-body>main h2{font-size:1.4rem;line-height:1.2;margin:2.75rem 0 .75rem;letter-spacing:0}', '.mark b{font-size:1.15rem;letter-spacing:0}.mark:hover{color:var(--fg)}', 'a{text-decoration-color:color-mix(in srgb,currentColor 35%,transparent);text-underline-offset:.2em;text-decoration-thickness:1px}a:hover{color:var(--fg);text-decoration-color:currentColor}', // Controls: pills. One filled pill per place for the main action; outlines and text for the rest. 'button{padding:.42rem 1rem;border:1px solid var(--muted);border-radius:999px;background:transparent;color:var(--fg);font-size:.9rem;line-height:1.3}', 'button:hover{background:var(--tint2);color:var(--fg);border-color:var(--fg)}', 'button:disabled{background:transparent;color:var(--fg)}', ':is(form.signin,form.signup)>button,form.signup button,.approval .buttons .yes{background:var(--fg);color:var(--bg);border-color:var(--fg)}', ':is(form.signin,form.signup)>button:hover,form.signup button:hover,.approval .buttons .yes:hover{background:var(--fg);color:var(--bg);opacity:.86}', 'input{border:1px solid var(--muted);border-radius:999px;padding:.5rem 1rem;background:transparent}input:focus{outline:none;border-color:var(--fg)}', ':focus-visible{outline:1.5px solid var(--fg);outline-offset:3px}body.wide :focus-visible,body.docs :focus-visible{outline:1.5px solid var(--fg)}', '.error{border-left:2px solid var(--red)}', 'pre{border-radius:12px}', // The landing and sign-in boxes: a title over the form, no frame. '.box{border:0;padding:0;margin:2.5rem 0 1.5rem}.box-title{position:static;background:none;padding:0;margin:0 0 1rem;font-size:2.4rem;line-height:1.1}', // The sidebar. '.app-nav{border-right:1px solid var(--hair)}.app-nav>.mark{border-bottom:0}', '.app-nav h2{font-weight:500;letter-spacing:.08em;text-transform:uppercase;font-size:.66rem;color:var(--muted)}', '.app-nav a.item{border-radius:999px}.app-nav a.item:hover{background:var(--tint)}.app-nav a.item[aria-current]{background:var(--tint2);font-weight:400}', `.app-nav a.agent .name{font-family:${DISPLAY};font-size:1rem;overflow:hidden;text-overflow:ellipsis}`, '.app-nav a.agent .state{margin-left:auto;font-size:.72rem;color:var(--muted)}.app-nav a.agent.waiting .state{color:var(--fg)}', '.app-nav .row a.item.agent{padding-right:2.2rem}.app-nav .row:hover a.agent .state{visibility:hidden}', '.app-top{border-bottom:0;background:var(--bg)}', // The shell: idle, running, done, needs you, failed. '.shell{height:15px;width:auto;flex:none;overflow:visible;color:var(--fg)}.shell path{vector-effect:non-scaling-stroke;stroke-width:1.5px}', '.shell.running path{stroke-dasharray:100;animation:wind 1.6s ease-in-out infinite alternate}@keyframes wind{from{stroke-dashoffset:64}to{stroke-dashoffset:0}}', '.app-nav .shell{width:15px}.app-nav .shell.waiting{width:auto}', // Idle is the same spiral as the rest, faint and still, so every agent wears one mark. '.shell.idle{color:var(--faint)}', // Bold is for a word or two, and in the dark it glares: semibold on paper, medium on ink. 'b,strong{font-weight:600}@media (prefers-color-scheme:dark){b,strong{font-weight:500;color:var(--fg)}}', // Form controls on every page: pills on a 1px line, sized to their content, with a drawn chevron. 'body select{appearance:none;-webkit-appearance:none;font:inherit;font-size:.92rem;line-height:1.3;color:var(--fg);width:auto;max-width:min(100%,22rem);min-width:9rem;text-overflow:ellipsis;' + 'padding:.45rem 2.4rem .45rem .95rem;border:1px solid var(--muted);border-radius:999px;cursor:pointer;' + 'background:linear-gradient(45deg,transparent calc(50% - .75px),currentColor calc(50% - .75px),currentColor calc(50% + .75px),transparent calc(50% + .75px)),linear-gradient(-45deg,transparent calc(50% - .75px),currentColor calc(50% - .75px),currentColor calc(50% + .75px),transparent calc(50% + .75px));background-size:6px 6px,6px 6px;background-position:calc(100% - 1.3rem) 52%,calc(100% - .95rem) 52%;background-repeat:no-repeat;background-color:transparent}', 'body select:hover{border-color:var(--fg)}body select:focus-visible{outline:1.5px solid var(--fg);outline-offset:3px}body select option{background:var(--bg);color:var(--fg)}', 'body input:is([type=text],[type=number],[type=url],[type=password],[type=search],:not([type])){font:inherit;font-size:.92rem;line-height:1.3;color:var(--fg);padding:.45rem .95rem;border:1px solid var(--muted);border-radius:999px;background:transparent}', 'body input[type=number]{width:6.5rem;flex:none;font-variant-numeric:tabular-nums}', 'body input:is([type=text],[type=number],[type=url],[type=password],[type=search],:not([type])):hover{border-color:var(--fg)}', 'body input:is([type=checkbox],[type=radio]){accent-color:var(--fg);width:1rem;height:1rem}', // Multi-line fields: the same outline as the pills, on the page's own background (no browser fill), with rounded corners. 'body textarea{font:inherit;font-size:.9rem;line-height:1.5;color:var(--fg);padding:.7rem .95rem;border:1px solid var(--muted);background:transparent;resize:vertical}', 'body textarea:hover{border-color:var(--fg)}body textarea:focus{outline:none;border-color:var(--fg)}', '.app-body>main label{margin-right:var(--s-2)}', '.app-body>main .field{gap:.6rem 1rem}.app-body>main .field label{min-width:9rem;font-size:.92rem;color:var(--ink2)}', '.app-body>main :is(p,small,label,li,td){overflow-wrap:anywhere}.app-body>main p{max-width:46rem}', '.app-body>main .field+p.muted,.app-body>main .field+.muted{margin:.1rem 0 1.4rem;font-size:.88rem;max-width:40rem}', // The settings, computers, Discord and admin pages: sections on space, not in frames. '.app-body>main .card{border:0;border-radius:0;padding:0;margin:2.75rem 0}.app-body>main .computer{border:0;border-radius:0;padding:0;margin:2.25rem 0}', '.app-nav .row:has(.gear[aria-current]) .state{visibility:hidden}', // List rows on every page: no hanging dash indent (it leaks into inline badges), and controls centred on the row. '.app-body>main :is(.rows,.checks) li{text-indent:0;padding-left:0}.app-body>main .rows li{align-items:center}.app-body>main .tag{text-indent:0;margin-left:.5rem;border-radius:999px;border-color:var(--line)}', '.app-body>main .fail{color:var(--red)}', // A dashed list's hanging indent belongs to its own text only, never to badges, buttons or blocks inside it. 'li *{text-indent:0}', '.app-body>main .card h2{margin:0 0 .4rem;font-size:1.35rem}', 'body select{border:1px solid var(--muted);border-radius:999px;padding:.35rem .8rem}', 'body .notice{border-left:2px solid var(--fg)}', // What connecting a computer exposes (riskNotice): set apart, ahead of the commands that connect one. '.risk{border-left:2px solid var(--fg);padding:.1rem 0 .1rem 1rem;margin:1rem 0;max-width:40rem}.risk h3{margin:0 0 .35rem;font-size:1rem}.risk p{margin:0}', '.app-body>main .rows li{border-bottom-color:var(--hair)}', // Home. '.lede{font-size:1.1rem;color:var(--ink2);max-width:40rem}', '.needs{display:grid;gap:.6rem;margin:1rem 0 0}.needs a{display:flex;align-items:center;gap:.7rem;width:fit-content;text-decoration:none}.needs a:hover .t{text-decoration:underline}', '.needs .shell{height:17px}', '.agents{display:grid;margin:.5rem 0 0;max-width:46rem}', '.agents .a{display:grid;grid-template-columns:1.6rem minmax(0,1fr) auto;align-items:center;gap:.1rem .9rem;padding:.7rem 0}', '.agents .a .shell{grid-row:span 2;height:18px;width:auto;max-width:1.6rem}', `.agents .a .nm{font-family:${DISPLAY};font-size:1.3rem;line-height:1.2;text-decoration:none}`, '.agents .a .sub{grid-column:2;font-size:.85rem;color:var(--muted)}.agents .a .sub a{color:inherit}', '.agents .a .st{grid-row:span 2;grid-column:3;font-size:.8rem;color:var(--muted)}.agents .a.waiting .st{color:var(--fg);font-weight:500}', '.money{margin:var(--s-2) 0 0;font-size:var(--t-sm);color:var(--muted)}.money b{color:var(--fg);font-weight:var(--w-medium);font-variant-numeric:tabular-nums}.money a{color:inherit}', '.cards-ag{display:grid;grid-template-columns:repeat(auto-fill,minmax(17rem,1fr));gap:var(--s-4);margin:var(--s-3) 0 0;max-width:60rem}', '.ag{display:flex;flex-direction:column;gap:var(--s-1);min-width:0;padding:var(--s-4) var(--s-4) var(--s-3);border:1px solid var(--hair);border-radius:var(--r-block)}', '.ag .top{display:flex;align-items:center;gap:var(--s-2);min-width:0}.ag .shell{height:16px;width:auto;max-width:1.6rem}', `.ag .nm{font-family:${DISPLAY};font-size:var(--d-sm);line-height:1.2;text-decoration:none;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}`, '.ag .st{margin-left:auto;font-size:var(--t-xs);color:var(--muted)}.ag.waiting .st{color:var(--fg);font-weight:var(--w-medium)}', '.ag p{margin:0}.ag .meta{font-size:var(--t-xs);color:var(--muted)}', '.ag .last{display:flex;flex-direction:column;margin:var(--s-2) 0 0;font-size:var(--t-sm);text-decoration:none;min-width:0}.ag .last.none{color:var(--faint)}', '.ag .last .tn,.ag .last .tp{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ag .last .tp{color:var(--muted);font-size:var(--t-xs)}.ag a.last:hover .tn{text-decoration:underline}', '.ag .acts{display:flex;align-items:center;gap:var(--s-3);margin-top:auto;padding-top:var(--s-3)}', '.ag .btn{display:inline-flex;align-items:center;height:var(--control-sm);padding:0 var(--s-4);border-radius:var(--r-pill);background:var(--fg);color:var(--bg);font-size:var(--t-sm);text-decoration:none}.ag .btn:hover{color:var(--bg);opacity:.86}', '.ag .set{font-size:var(--t-xs);color:var(--muted);text-decoration:none}.ag .set:hover{color:var(--fg)}', '.ag.new{border-style:dashed;justify-content:center}.ag.new label{font-family:inherit;font-size:var(--t-sm);color:var(--muted);margin:0}', '.ag.new .row{display:flex;gap:var(--s-2);margin-top:var(--s-1)}.ag.new input{flex:1 1 auto;min-width:0;height:var(--control-sm);padding:0 var(--s-3);font-size:var(--t-sm)}.ag.new button{height:var(--control-sm);padding:0 var(--s-3);font-size:var(--t-sm)}', '.cards-ag:has(>.ag.new:only-child) .ag.new button{background:var(--fg);color:var(--bg);border-color:var(--fg)}.cards-ag:has(>.ag.new:only-child) .ag.new button:hover{opacity:.86}', '.ag.new .error{margin:var(--s-2) 0 0;font-size:var(--t-xs)}', // About you: Home's onboarding step, and its page. '.app-body>main .about{margin:var(--s-5) 0 0;padding:var(--s-4);border:1px solid var(--hair);border-radius:var(--r-block);max-width:40rem}', '.app-body>main .about h2{margin:0;padding:0;font-size:var(--d-sm)}.app-body>main .about p{margin:var(--s-1) 0 0;font-size:var(--t-sm);color:var(--muted)}.app-body>main .about p.error{color:var(--fg)}', '.app-body>main .about .choices{display:flex;flex-wrap:wrap;gap:var(--s-2);margin:var(--s-3) 0 0}.app-body>main .about button{margin:0}', '.app-body>main .about .choices button{height:var(--control-sm);padding:0 var(--s-4);font-size:var(--t-sm)}.app-body>main .about .choices button:hover{border-color:var(--fg)}', '.app-body>main .about .choices button.on{background:var(--fg);border-color:var(--fg);color:var(--bg)}', '.app-body>main .about .other{display:flex;gap:var(--s-2);margin:var(--s-2) 0 0;max-width:24rem}', '.app-body>main .about .other input{flex:1 1 auto;min-width:0;height:var(--control-sm);padding:0 var(--s-3);font-size:var(--t-sm)}.app-body>main .about .other button{height:var(--control-sm);padding:0 var(--s-3);font-size:var(--t-sm)}', '.app-body>main .about .foot{display:flex;flex-wrap:wrap;align-items:center;gap:var(--s-3);margin:var(--s-3) 0 0}', '.app-body>main .about .foot :is(a,button){height:auto;padding:0;border:0;background:none;color:var(--muted);font-size:var(--t-xs);text-decoration:none}.app-body>main .about .foot :is(a,button):hover{color:var(--fg)}', 'details.term{margin:var(--s-6) 0 0}details.term>summary{cursor:pointer;width:fit-content;font-size:var(--t-sm);color:var(--muted)}details.term>summary:hover{color:var(--fg)}', // Chat. '.thread-bar h1{font-size:1.15rem;letter-spacing:0}', '.thread-panel .agent-card b{font-size:1.4rem;letter-spacing:0}', '.thread-panel .new{border-radius:999px}.thread-panel .threads a{border-radius:999px}.thread-panel .threads li.on a{background:var(--tint2);font-weight:400}', '.threads a{border-radius:999px}', '.empty h2{letter-spacing:0;font-size:2.4rem}', '.msg.user{border-radius:18px;background:var(--box)}', // A check drawn with borders: the page's CSP allows no data: images, so no masks. ':is(details.tool,details.calls).ok>summary .dot{background:none;box-shadow:none;width:12px;height:12px;top:.4em;left:-3px}', ':is(details.tool,details.calls).ok>summary .dot::before{content:"";position:absolute;left:4px;top:1px;width:4px;height:8px;border:solid var(--fg);border-width:0 1.5px 1.5px 0;transform:rotate(45deg)}', ':is(details.tool,details.calls).err>summary .dot{background:none;box-shadow:none;width:11px;height:11px;top:.45em;left:-2px}', ':is(details.tool,details.calls).err>summary .dot::before,:is(details.tool,details.calls).err>summary .dot::after{content:"";position:absolute;left:-1px;right:-1px;top:50%;height:1.5px;margin-top:-.75px;border-radius:1px;background:var(--fg);transform:rotate(45deg)}', ':is(details.tool,details.calls).err>summary .dot::after{transform:rotate(-45deg)}', 'details.calls>summary .fails{color:var(--fg)}', '.md code,.md pre,.md .code-block{background:var(--code)}', // A diff without colour: removed lines fade and strike, added lines keep the ink. '.dl.add,.dl.del{background:none}.dl.add .dg{color:var(--fg)}.dl.del .dg{color:var(--muted)}.dl.del .dt{color:var(--muted)}', '.dl.add mark{background:var(--tint2)}.dl.del mark{background:none;text-decoration:line-through}.diff-n .a,.diff-n .r{color:inherit}', // The question before a call: no card, the shell with its head up, small pill buttons, ⌘↵ and esc. '.approval{border:0;border-radius:0;padding:0;background:none;backdrop-filter:none;-webkit-backdrop-filter:none;box-shadow:none}', '.approval .need{display:flex;align-items:center;gap:.45rem;margin:0 0 .45rem;font-size:.85rem}.approval .need svg{width:22px;height:22px;flex:none;margin:-2px -2px -2px -4px}', '.app-nav a.item .dot{margin-left:auto;width:7px;height:7px;border-radius:50%;background:var(--fg);flex:none}', '.app-nav .state.count{margin-left:auto;display:inline-flex;align-items:center;gap:.2rem;font-size:.72rem}.app-nav .state.count svg{width:17px;height:17px;color:var(--fg)}', '.needs svg{width:24px;height:24px;flex:none;margin-left:-4px}', '.app-nav a.item svg:not(.shell){width:17px;height:17px;color:var(--ink2)}', // The external-link glyph after Docs: small and quiet, at the icons' line weight for its size; at the row's end in the sidebar. 'svg.ext{width:11px;height:11px;flex:none;margin-left:.3rem;stroke-width:2.3;opacity:.6;vertical-align:-1px}.app-nav a.item>svg.ext:not(.shell){display:block;width:12px;height:12px;margin-left:auto;color:inherit}', '.approval:has(.answer) .need{display:none}', '.approval .q{font-weight:400;color:var(--ink2)}', '.approval pre,.approval .diff{border-radius:10px}', '.approval .buttons{flex-wrap:wrap}.approval .buttons button{height:1.9rem;padding:0 .85rem;border-radius:999px;border:1px solid var(--muted);background:transparent;font-size:.82rem}', '.approval .buttons button:hover{border-color:var(--fg);background:transparent}', '.approval .buttons .yes::after{content:"⌘↵";margin-left:.45rem;font-size:.72em;opacity:.6}', '.approval .buttons [data-approve=no]{border-color:transparent;color:var(--muted)}.approval .buttons [data-approve=no]::after{content:"esc";margin-left:.4rem;font-size:.72em;opacity:.6}', // The composer. 'form.composer .card{border-radius:18px;box-shadow:none}form.composer .card:has(textarea:focus-visible){outline:0;border-color:var(--muted)}form.composer textarea{caret-color:var(--fg)}', 'form.composer .pill{border-radius:999px}form.composer .pill:hover,form.composer .pill[aria-expanded=true]{background:var(--tint2);border-color:transparent}', 'form.composer #approval[data-value=allow],form.composer #approval[data-value=allow] svg{color:var(--fg)}', 'form.composer .send:hover{background:var(--fg);color:var(--bg);opacity:.86}', 'form.composer .menu{backdrop-filter:none;-webkit-backdrop-filter:none;background:var(--bg);box-shadow:none;animation:none}', // It opens out of its pill: from the pill's corner, quickly. 'form.composer .menu[data-side=above]{transform-origin:bottom left;animation:grow .12s ease-out}form.composer .menu[data-side=below]{transform-origin:top left;animation:grow .12s ease-out}', '@keyframes grow{from{opacity:0;transform:scale(.94)}}', '@media(prefers-reduced-motion:reduce){form.composer .menu[data-side]{animation:none}}', 'form.composer .opt svg{color:var(--fg)}form.composer .model-favorite[aria-pressed=true]{color:var(--fg)}', 'form.composer.waiting .card{border-color:var(--muted)}', // Pasted or dropped images wait above the text as thumbnails; hovering one shows its ×. 'form.composer .tray{display:flex;flex-wrap:wrap;gap:.5rem;margin:0 0 .85rem}form.composer .tray[hidden]{display:none}', 'form.composer .thumb{position:relative;width:64px;height:64px;flex:none;border:1px solid var(--hair);border-radius:12px;overflow:hidden;background:var(--tint)}', 'form.composer .thumb img{display:block;width:100%;height:100%;object-fit:cover}form.composer .thumb.loading img{opacity:.35}', 'form.composer .thumb .x{position:absolute;top:4px;right:4px;width:20px;height:20px;padding:0;border:0;border-radius:50%;display:none;align-items:center;justify-content:center;background:var(--fg);color:var(--bg);cursor:pointer}', 'form.composer .thumb .x svg{width:11px;height:11px}form.composer .thumb:is(:hover,:focus-within) .x{display:inline-flex}form.composer .thumb .x:hover{background:var(--fg);color:var(--bg)}', '@media (hover:none){form.composer .thumb .x{display:inline-flex}}', 'form.composer .tray-note{flex-basis:100%;margin:.15rem 0 0;font-size:.78rem;color:var(--muted)}', 'form.composer .tray-note button{padding:0;border:0;border-radius:0;background:none;color:var(--fg);font:inherit;text-decoration:underline;text-decoration-color:color-mix(in srgb,currentColor 35%,transparent);text-underline-offset:.2em;cursor:pointer}', 'form.composer .tray-note button:hover{background:none;text-decoration-color:currentColor}', 'form.composer.dropping .card{border-color:var(--fg)}', // Images sent with a message sit over its bubble. '#log>.pics{align-self:flex-end;display:flex;flex-wrap:wrap;justify-content:flex-end;gap:.4rem;max-width:85%;margin-top:.75rem}#log>.pics+.msg.user{margin-top:.4rem}', '#log>.pics img{display:block;width:96px;height:96px;object-fit:cover;border:1px solid var(--hair);border-radius:12px;background:var(--tint)}', // Docs. 'article.docs h1{letter-spacing:0;font-weight:400}article.docs h2{font-weight:400;border-top:0;letter-spacing:0}', 'article.docs .note{border-color:var(--hair)}.cmd .copy.done{color:var(--fg)}', '.docs-toc a{border-radius:999px}.docs-toc a.on{background:var(--tint2);font-weight:400}', // Fast: no settling, fades or slow colour changes, and hovers are instant and never change size. 'a,button,.app-nav a.item,.app-nav .gear,form.composer .pill,form.composer .send,form.composer .opt,.feedback,.feedback>button,.threads .rename,.tile{transition:none!important}', 'button:hover,button:active{border-width:1px}', '#log>*,details[open].tool .io,details[open].calls>.list{animation:none}', ':is(details.tool,details.calls)>summary .dot,form.composer .activity,form.composer .pip,.approval{transition-duration:.12s}', '@media (prefers-reduced-motion:reduce){.shell.running path{animation:none;stroke-dashoffset:0}}', ].join('') /** * The chat's three kinds of thing, each with its own look: the agent's words are bare prose; its * calls are quiet tinted rows; a question for you is an outlined card that stands out. Streamed * words fade in. And the composer is one compact row: text, then its controls and Send. */ const CHAT = [ // Words: streamed text fades in as it arrives (chat.js wraps the new part in .fresh). '.msg .fresh{animation:fresh .6s ease-out both}@keyframes fresh{from{opacity:0}}', // Calls: a tinted row, smaller and quieter than the words around it. '#log>:is(details.tool,details.calls){padding:.55rem .85rem;border-radius:var(--r-block);background:var(--box);font-size:var(--t-sm)}', '#log>:is(details.tool,details.calls)>summary .dot{left:0}', '#log>details.tool .io{margin-left:17px}', // Questions: an outlined card in full ink, with its label up top. '.approval{padding:var(--s-4) var(--s-4) var(--s-3);border:1px solid var(--fg);border-radius:var(--r-panel);background:var(--bg)}', '.approval .need{font-size:var(--t-xs);font-weight:var(--w-medium);letter-spacing:.08em;text-transform:uppercase}', '.approval .q{color:var(--fg)}', '.approval:has(.answer){border-color:var(--line);box-shadow:none}.approval:has(.answer) .q{color:var(--ink2)}', '.approval .buttons [data-approve=all]{border-color:var(--muted)}', // The composer: a narrow pill, a round button at each end (+ and Mic, Send or Stop) and the text between. // It stays a pill on one line, and squares up to a panel once it is taller than that (chat.js marks it // .tall): text over several lines, images waiting, or the controls wrapped under the text. 'form.composer .wrap{max-width:44rem;margin:0 auto;container:composer/inline-size}', 'form.composer .card{display:flex;flex-wrap:wrap;align-items:flex-end;gap:0 .3rem;padding:.3rem;border-radius:var(--r-pill)}', 'form.composer .card.tall{border-radius:var(--r-panel)}', // Text past one line takes the whole width, over the buttons (chat.js marks it .multi). 'form.composer .card.multi textarea{order:-1;flex-basis:100%;padding-left:.6rem}form.composer .card.multi .tray{order:-2}', 'form.composer .tray{flex-basis:100%;margin:.4rem .4rem .5rem}', 'form.composer .plus{position:relative;flex:none;width:2.25rem;height:2.25rem;padding:0;margin:0;border:1px solid var(--line);border-radius:50%;display:inline-flex;align-items:center;justify-content:center;background:transparent;color:var(--muted);cursor:pointer}', 'form.composer .plus:hover,form.composer .plus[aria-expanded=true]{background:var(--tint2);color:var(--fg);border-color:var(--line)}form.composer .plus svg{width:16px;height:16px}', // Allow all is out of sight in the + menu, so a dot on + says it is on. 'form.composer .plus.allow::after{content:"";position:absolute;top:0;right:0;width:8px;height:8px;border-radius:50%;background:var(--amber);box-shadow:0 0 0 2px var(--bg)}', // The + menu: Add image, then a row each for the model, the computer and permissions, which open their own menus. 'form.composer .plus-menu{left:0;width:min(19rem,calc(100% - 1rem))}form.composer .plus-menu hr{margin:.3rem .5rem;border:0;border-top:1px solid var(--hair)}', 'form.composer .row{display:flex;align-items:center;gap:.6rem;width:100%;margin:0;padding:.55rem .65rem;border:0;border-radius:12px;background:transparent;color:var(--fg);font:inherit;font-size:.9rem;text-align:left;cursor:pointer}', 'form.composer .row:hover,form.composer .row:focus-visible{background:var(--tint);outline:0}form.composer .row:disabled{opacity:.5;cursor:default}', 'form.composer .row svg{width:16px;height:16px;flex:none;color:var(--muted)}form.composer .row>svg:last-child:not(:first-child){width:14px;height:14px;margin-left:.1rem}', 'form.composer .row b{flex:none;font-weight:400}', 'form.composer .row span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--muted);font-size:.82rem}form.composer .row span:first-of-type{margin-left:auto}', 'form.composer .row .pill-note{flex:none}form.composer .row .pill-note::before{content:"· "}', 'form.composer #approval[data-value=allow] span{color:var(--amber)}', 'form.composer textarea{flex:1 1 8rem;width:auto;min-width:0;margin:0;padding:.4rem .25rem .4rem .35rem;height:2.25rem;font-size:1rem;box-sizing:border-box}', 'form.composer textarea::placeholder{text-indent:0}', 'form.composer .bar{flex:none;margin:0 0 0 auto;gap:.15rem}', // One round button at the end: Mic while there's nothing to send, Send once there is, Stop while a run goes. 'form.composer :is(.send,.mic){width:2.25rem;height:2.25rem;margin:0}', 'form.composer .mic{border:1px solid var(--line)}form.composer .mic:hover{border-color:var(--line)}', '@media (prefers-reduced-motion:reduce){.msg .fresh{animation:none}}', ].join('') /** * The components, on the scale above, over whatever each page's older rules said. One control * height and text size for buttons, inputs and selects; one badge; one list row; one table; one * label style; three radii. Pages keep their own layout; their controls and rows look the same. */ const SYSTEM = [ // Type: display sizes for headings and names, four text sizes for the rest, no 550s. `.app-body>main h1{font-size:var(--d-xl);line-height:1.05;margin:var(--s-3) 0 var(--s-3)}`, `.app-body>main h2,.app-body>main .card h2{font-family:${DISPLAY};font-weight:var(--w-regular);font-size:var(--d-md);line-height:1.2;margin:var(--s-7) 0 var(--s-3)}`, `.app-body>main .card h2{margin-top:0}`, `.app-body>main h3{font-size:var(--t-md);font-weight:var(--w-strong);margin:var(--s-5) 0 var(--s-2)}`, '.app-top b,.tile b,.thread-bar h1,.thread-panel .agent-card b{font-weight:var(--w-regular)}.app-top b{font-weight:var(--w-medium);font-size:var(--t-sm)}', '.lede{font-size:var(--t-lg)}', '.app-body>main :is(small,.muted small,.hint,.help){font-size:var(--t-sm)}', // Labels: one style for section labels, table heads and eyebrows. '.app-nav h2,.owners th,.tbl th,table.sum th,.label,.eyebrow{font-size:var(--t-xs);font-weight:var(--w-medium);letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}', // Controls: one height, one text size, pills. 'body :is(button:not([class]):not([data-verdict]):not([data-copy]),button.small,button.yes,button[data-approve],form.signin>button,form.signup button,.feedback .row button){display:inline-flex;align-items:center;gap:var(--s-2);height:var(--control);padding:0 var(--s-4);font-size:var(--t-sm);line-height:1;border-radius:var(--r-pill)}', 'body :is(button.small,.approval .buttons button,.feedback .row button){height:var(--control-sm);padding:0 var(--s-3)}', 'body :is(select,input:is([type=text],[type=number],[type=url],[type=password],[type=search],:not([type]))){height:var(--control);padding-top:0;padding-bottom:0;font-size:var(--t-sm)}', 'body textarea{border-radius:var(--r-panel);font-size:var(--t-sm)}', 'form.composer .pill{height:var(--control-sm);font-size:var(--t-xs);border-radius:var(--r-pill)}', '.thread-panel .new{height:var(--control-sm);padding:0 var(--s-3);font-size:var(--t-sm)}', // Badges. '.app-body>main :is(.tag,.badge,.status-tag),.tag,.badge,.status-tag{display:inline-flex;align-items:center;height:1.375rem;padding:0 var(--s-2);font-size:var(--t-xs);font-weight:var(--w-regular);line-height:1;border:var(--hairline) solid var(--line);border-radius:var(--r-pill);color:var(--muted);white-space:nowrap}', // Rows: lists and tables share padding, a hairline and text sizes. '.app-body>main .rows li{padding:var(--s-3) 0;border-bottom:var(--hairline) solid var(--hair);font-size:var(--t-md)}.app-body>main .rows li:last-child{border-bottom:0}', '.app-body>main :is(.owners,.tbl table,table.sum){font-size:var(--t-sm);border-collapse:collapse}', '.app-body>main :is(.owners,.tbl,table.sum) :is(th,td){padding:var(--s-3) var(--s-3) var(--s-3) 0;border-top:0;border-bottom:var(--hairline) solid var(--hair);vertical-align:top}', '.app-body>main .owners th{border-bottom-color:var(--line)}', '.tbl{border:var(--hairline) solid var(--hair);border-radius:var(--r-block)}.tbl :is(th,td){padding-left:var(--s-4)!important}', // Radii: pills for controls and nav, blocks for code, panels for floating and typed-into surfaces. ':is(pre,.md pre,.md .code-block,.cmd,details.tool .io,.approval pre,.approval .diff,article.docs>pre){border-radius:var(--r-block)}', ':is(.msg.user,form.composer .card,form.composer .menu){border-radius:var(--r-panel)}', ':is(.app-nav a.item,.threads a,.thread-panel .threads a,.docs-toc a,form.composer .opt,.md .code-copy,.cmd .copy){border-radius:var(--r-pill)}', ':not(pre)>code,.md code,article.docs :not(pre)>code{border-radius:6px}', // Nav and meta text. '.app-nav,.thread-panel,.docs-toc{font-size:var(--t-sm)}', ':is(.thread-panel .threads time,.tb-sub,.chat-meta,details.tool .tool-name,details.calls>summary .count,.thread-panel .more,.empty .facts){font-size:var(--t-xs)}', // The Memory page on the same scale. '.app-body>main :is(.mem .why,.desc,.none,.tally){font-size:var(--t-sm)}.app-body>main .meta{font-size:var(--t-xs)}.app-body>main .blocks .text{font-size:var(--t-md)}', '.app-body>main .bh h3{font-size:var(--d-sm)}.app-body>main .blocks summary{font-size:var(--t-sm)}', // The lockup, as Foot and shell specifies: Comfortaa at 20px, the snail at three quarters of that on the baseline, half its height apart. '.mark{align-items:baseline;gap:.47rem}.mark b{font-size:var(--d-sm);font-weight:var(--w-regular)}.logo{width:auto;height:.9375rem;top:0}', // The lockup sits on its baseline, so in a bar of fixed height it wraps to centre that line. ':is(.app-nav,.thread-panel,.docs-panel)>.mark{flex-wrap:wrap;align-content:center}', // The sidebar is one column that doesn't scroll: Home and Inbox, the agent and its menu stay put, its threads scroll in the // height that's left, and the account keeps to the bottom. Every row has Home's shape, and nothing nests. '.app-nav>*{flex:none}.app-nav>.nest{display:contents}.app-nav .nest>:not(.threads){flex:none}', // The agent's pages: two to a row under the switcher, quiet and short, the page you're on filled in. '.app-nav .agent-menu{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 .2rem;margin:0 0 var(--s-1)}', '.app-nav .agent-menu a.item.sub{gap:.45rem;height:1.75rem;padding:0 .25rem 0 .6rem;font-size:var(--t-xs);color:var(--muted)}', '.app-nav .agent-menu a.item.sub:hover,.app-nav .agent-menu a.item.sub[aria-current]{color:var(--fg)}.app-nav .agent-menu a.item.sub svg{width:15px;height:15px}', '.app-nav .agent-menu a.item.sub:hover svg,.app-nav .agent-menu a.item.sub[aria-current] svg{color:var(--fg)}', '.app-nav .nest a.item .t{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis}', '.app-nav .nest a.item.new{height:auto;margin-top:var(--s-2);border:0;font-size:inherit}', '.app-nav .nest>.threads{flex:1 1 0;min-height:0;overflow-y:auto;display:block;margin:0 -.75rem var(--s-2);padding:0 .75rem}', '.app-nav .nest .threads li{position:relative}.app-nav .nest .threads li.group{display:none}', // A thread's name lines up with the labels above it, and its age sits at the right, faint, until the pencil takes its place. '.app-nav .nest .threads a{display:flex;align-items:baseline;gap:.5rem;padding:.42rem .6rem .42rem calc(1.15rem + 17px);border-radius:var(--r-pill);color:var(--fg);font-weight:400;text-decoration:none;white-space:nowrap}', '.app-nav .nest .threads a:hover{background:var(--tint);color:var(--fg)}.app-nav .nest .threads li.on a{background:var(--tint2);font-weight:500}', '.app-nav .nest .threads .t{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis}', '.app-nav .nest .threads time{flex:none;margin-left:auto;font-size:var(--t-xs);color:var(--faint);font-variant-numeric:tabular-nums}', '.app-nav .nest .threads li:is(:hover,:focus-within) time{visibility:hidden}', '@media(hover:none){.app-nav .nest .threads a{padding-right:2.1rem}}', '.app-nav .nest .threads li.more{padding:.42rem .6rem .42rem calc(1.15rem + 17px);font-size:var(--t-xs);color:var(--faint)}', // Manage: the account menu's first rows, the same shape as its others. '.app-nav .who .manage{display:flex;flex-direction:column}', '.app-nav .who .manage a.item{gap:.55rem;padding:.42rem .55rem;border-radius:10px;font-size:.84rem;font-weight:400}.app-nav .who .manage a.item:hover{background:var(--tint2)}', '.app-nav .who .manage a.item svg{display:block;width:15px;height:15px}.app-nav .who .manage a.item>svg.ext{width:11px;height:11px;margin-left:.15rem}', '.app-nav .who .manage .bal{margin-left:auto;font-weight:500;font-variant-numeric:tabular-nums}', '.app-nav .nav-foot{margin-top:auto;padding-top:var(--s-1);border-top:1px solid var(--hair)}', // The agent switcher: the current agent's row opens a menu of every agent, a check by the current one, and New agent. '.app-nav .switch{position:relative;margin:var(--s-4) 0 var(--s-1)}', '.app-nav .switch>summary{list-style:none;display:flex;align-items:center;gap:.55rem;padding:.325rem .6rem;border-radius:var(--r-pill);cursor:pointer;color:var(--fg)}', '.app-nav .switch>summary::-webkit-details-marker{display:none}.app-nav .switch>summary:hover{background:var(--tint)}.app-nav .switch[open]>summary{background:var(--tint2)}', '.app-nav .switch>summary:focus-visible{outline:1.5px solid var(--fg);outline-offset:-1.5px}', `.app-nav .switch .name{flex:0 1 auto;min-width:0;font-family:${DISPLAY};font-size:1rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}`, '.app-nav .switch .state{margin-left:auto;font-size:.72rem;color:var(--fg);white-space:nowrap}', '.app-nav .switch .chev{margin-left:auto;display:grid;place-items:center;color:var(--muted)}.app-nav .switch .state+.chev{margin-left:0}', '.app-nav .switch .chev svg{width:15px;height:15px}.app-nav .switch>summary:hover .chev{color:var(--fg)}', '.app-nav .switch .menu{position:absolute;left:0;right:0;top:calc(100% + .25rem);z-index:6;max-height:min(24rem,70vh);overflow-y:auto;padding:.3rem;border:1px solid var(--fg);border-radius:14px;background:var(--bg)}', '.app-nav .switch .menu hr{margin:.3rem .4rem;border:0;border-top:1px solid var(--hair)}', '.app-nav .switch :is(.acct,.act){box-sizing:border-box;width:100%;display:flex;align-items:center;gap:.55rem;padding:.42rem .55rem;border-radius:10px;font-size:.84rem;color:var(--fg);text-decoration:none}', '.app-nav .switch :is(.acct,.act):hover{background:var(--tint2);color:var(--fg)}.app-nav .switch :is(.acct,.act):focus-visible{outline:1.5px solid var(--fg);outline-offset:-1.5px}', '.app-nav .switch .acct .name{font-size:.95rem}.app-nav .switch .acct>svg:not(.shell){width:15px;height:15px;flex:none;margin-left:auto;color:var(--fg)}.app-nav .switch .acct .state+svg{margin-left:0}', '.app-nav .switch .act svg{width:15px;height:15px;flex:none;color:var(--muted)}.app-nav .switch .acct[aria-current]{font-weight:500}', // A section after the wordmark, like /docs, is part of the lockup: same face and size, quieter. `.mark .path{font-family:${DISPLAY};font-size:var(--d-sm);font-weight:var(--w-regular);color:var(--faint);margin-left:.35rem}`, // Notices: one shape. '.app-body>main :is(.notice,.error){border-left:var(--stroke) solid var(--fg);padding:var(--s-1) var(--s-3);margin:var(--s-4) 0}.app-body>main .error{border-left-color:var(--red)}', ].join('') const STYLE = [ // Ink and paper (the Foot and shell design): the same tokens on every page, the chat's included. `:root,:is(body.wide,body.docs){color-scheme:light dark;${SCALE};${TOKENS_LIGHT}}`, `@media (prefers-color-scheme:dark){:root,:is(body.wide,body.docs){${TOKENS_DARK}}}`, `@font-face{font-family:Inter;src:url(${INTER_HREF}) format("woff2");font-weight:100 900;font-display:swap}`, DISPLAY_HREF ? `@font-face{font-family:Comfortaa;src:url(${DISPLAY_HREF}) format("truetype");font-weight:300 700;font-display:swap}` : '', FRANKLIN_HREF ? `@font-face{font-family:"Libre Franklin";src:url(${FRANKLIN_HREF}) format("truetype");font-weight:100 900;font-display:swap}` : '', '*{box-sizing:border-box}', `body{font:16px/1.6 ${SANS};color:var(--fg);background:var(--bg);max-width:36rem;margin:0 auto;padding:1.25rem 1rem 3rem}`, 'header{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:.25rem 1rem}', '.mark{display:inline-flex;align-items:center;gap:.6rem;color:var(--fg);text-decoration:none}', '.mark:hover{color:var(--green)}', // Lifted to the caps' middle: centering in the flex row aligns it with the line box, whose middle // sits a little lower, to leave room for descenders. Measured for Inter at 16px. '.logo{width:1.67rem;height:1.2rem;flex:none;position:relative;top:-.05rem}', '.path{color:var(--muted)}', 'hr{border:0;border-top:1px solid var(--hr);margin:.6rem 0 1.5rem}', 'h1{font-size:1.5rem;line-height:1.3;margin:1.75rem 0 .75rem}', 'h2{font-size:1.05rem;margin:2.25rem 0 .5rem}', 'p{margin:.6rem 0}', 'a{color:inherit}', 'a:hover{color:var(--green)}', 'ul{list-style:none;padding:0;margin:.6rem 0}', // A hanging dash: in a proportional font "- " isn't 2ch wide, so the dash gets a box of its own. 'li{padding-left:1em;text-indent:-1em}', 'li::before{content:"-";display:inline-block;width:1em;text-indent:0;color:var(--muted)}', '.muted,.did{color:var(--muted)}', `.did{font-family:${MONO};font-size:.85rem;word-break:break-all}`, '.box{position:relative;border:2px solid var(--line);border-radius:12px;padding:1.4rem 1rem 1rem;margin:2.5rem 0 1.5rem}', '.box-title{position:absolute;top:-.85rem;left:.75rem;background:var(--bg);padding:0 .5rem;font-weight:600}', 'form.signin{display:flex;gap:.5rem;flex-wrap:wrap}', 'form.signup{display:grid;gap:.9rem}form.signup label{display:block}form.signup input{display:block;width:100%;margin-top:.3rem}form.signup .handle{display:flex;align-items:center;gap:.5rem;margin-top:.3rem}form.signup .handle input{margin:0}form.signup button{justify-self:start}', 'input{font:inherit;flex:1 1 14rem;min-width:0;padding:.5rem .75rem;border:2px solid var(--fg);border-radius:12px;background:var(--bg);color:var(--fg)}', // The first languid.ai's bevelled buttons: lighter on the top and left, darker on the bottom and right. 'button{font:inherit;padding:.5rem 1rem;border:2px solid;border-radius:12px;background:transparent;color:var(--fg);cursor:pointer;' + 'border-color:color-mix(in srgb,var(--fg) 50%,transparent) color-mix(in srgb,var(--fg) 75%,transparent) color-mix(in srgb,var(--fg) 75%,transparent) color-mix(in srgb,var(--fg) 50%,transparent)}', 'button:hover{background:var(--green);color:#000;border-color:color-mix(in srgb,var(--fg) 75%,transparent) color-mix(in srgb,var(--fg) 50%,transparent) color-mix(in srgb,var(--fg) 50%,transparent) color-mix(in srgb,var(--fg) 75%,transparent)}', 'button+button{margin-left:.5rem}', 'button:disabled{opacity:.45;cursor:default;background:transparent;color:var(--fg)}', '.error{border-left:3px solid #dc2626;padding:.25rem .75rem;margin:0 0 1rem}', // The full stack, not a bare "monospace": that one makes browsers rescale font sizes. `pre,code{font-family:${MONO}}`, // Monospace looks larger than Inter at the same size. ':not(pre)>code{font-size:.92em}', 'pre{font-size:.85rem;background:var(--box);padding:.75rem 1rem;border-radius:12px;overflow-x:auto}', // About 66 columns: sized to fit a phone, centered as one block so the staircase stays aligned. 'pre.art{background:none;padding:0;margin:0 auto;width:max-content;max-width:100%;font-size:min(11px,1.95vw);line-height:1.15;overflow:hidden}', 'p code.big{font-size:1.5rem;letter-spacing:.1em}', '.center{text-align:center}', 'footer{margin-top:3rem;font-size:.85rem;color:var(--muted);text-align:center}', // The signed-in pages are an application: a sidebar of the owner's agents and the places to manage // them, fixed down the left, and the page itself in the wide space beside it. 'body.app{max-width:none;margin:0;padding:0;display:grid;grid-template-columns:16rem minmax(0,1fr);min-height:100vh;min-height:100dvh}', '.app-nav{position:sticky;top:0;height:100vh;height:100dvh;overflow-y:auto;display:flex;flex-direction:column;padding:0 .75rem 1rem;border-right:1px solid var(--hr);font-size:.88rem}', '.app-nav>.mark{height:3.5rem;flex:none;margin:0 -.75rem .75rem;padding:0 1.35rem;border-bottom:1px solid var(--hr);font-size:.85rem}', '.app-nav h2{margin:1.1rem .6rem .3rem;font-size:.72rem;font-weight:500;color:var(--muted)}', '.app-nav .row{position:relative}', '.app-nav a.item{display:flex;align-items:center;gap:.55rem;padding:.42rem .6rem;border-radius:6px;color:var(--fg);text-decoration:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}', '.app-nav a.item:hover{background:var(--tint);color:var(--fg)}.app-nav a.item[aria-current]{background:var(--tint2);font-weight:500}', '.app-nav a.item svg{width:15px;height:15px;flex:none;color:var(--muted)}', '.app-nav .row a.item{padding-right:2.2rem}', '.app-nav .gear{position:absolute;right:.25rem;top:50%;transform:translateY(-50%);width:1.75rem;height:1.75rem;display:grid;place-items:center;border-radius:6px;color:var(--muted);opacity:0;transition:opacity .12s}', '.app-nav .row:hover .gear,.app-nav .gear:focus-visible,.app-nav .gear[aria-current]{opacity:1}.app-nav .gear:hover{background:var(--tint2);color:var(--fg)}.app-nav .gear svg{width:15px;height:15px}', '@media(hover:none){.app-nav .gear{opacity:.7}}', '.app-nav .empty-note{margin:.2rem .6rem;color:var(--muted);font-size:.82rem}', // The account menu: who's signed in, opening upward over the sidebar. '.app-nav .who{position:relative;padding-top:.5rem;font-size:.8rem;color:var(--muted)}', '.app-nav .who summary{list-style:none;display:flex;align-items:center;gap:.55rem;padding:.4rem .6rem;border-radius:999px;cursor:pointer;color:var(--fg)}', '.app-nav .who summary::-webkit-details-marker{display:none}.app-nav .who summary:hover,.app-nav .who[open] summary{background:var(--tint2)}', // Open, a clear layer over the page closes it on a click anywhere outside: it's part of the summary, so no script. ".app-nav .who[open] summary::before{content:'';position:fixed;inset:0;z-index:4;cursor:default}", '.app-nav .who .handle{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:left}', '.app-nav .who svg{width:15px;height:15px;flex:none;color:var(--muted)}', '.app-nav .who .avatar{flex:none;width:1.4rem;height:1.4rem;display:grid;place-items:center;border:1px solid var(--fg);border-radius:50%;font-size:.68rem;font-weight:500;color:var(--fg)}', '.app-nav .who .menu{position:absolute;left:0;right:0;bottom:calc(100% + .25rem);z-index:5;padding:.3rem;border:1px solid var(--fg);border-radius:14px;background:var(--bg)}', '.app-nav .who .menu form{margin:0}.app-nav .who .menu hr{margin:.3rem .4rem;border:0;border-top:1px solid var(--hair)}', '.app-nav .who :is(.acct,.act){all:unset;box-sizing:border-box;width:100%;display:flex;align-items:center;gap:.55rem;padding:.42rem .55rem;border-radius:10px;font-size:.84rem;color:var(--fg);cursor:pointer;text-decoration:none}', '.app-nav .who :is(button.acct,.act):hover{background:var(--tint2)}.app-nav .who :is(button.acct,.act):focus-visible{outline:1.5px solid var(--fg);outline-offset:-1.5px}', '.app-nav .who .acct.current{cursor:default;font-weight:500}.app-nav .who .acct.current svg{color:var(--fg)}', '.app-nav .who summary{position:relative}.app-nav .who .bal{flex:none;color:var(--muted);font-variant-numeric:tabular-nums}.app-nav .who .bal.out{color:var(--fg);font-weight:600}', '.app-nav .who summary>.dot{position:absolute;left:calc(.6rem + 1.4rem - 5px);top:.3rem;width:7px;height:7px;border-radius:50%;background:var(--fg);box-shadow:0 0 0 2px var(--bg)}', '.app-nav .who .menu{max-height:calc(100dvh - 5rem);overflow-y:auto}', '.app-nav .nav-foot{position:sticky;bottom:-1rem;z-index:3;margin:auto -.75rem -1rem;padding:var(--s-1) .75rem 1rem;background:var(--bg)}', '.app-top{position:sticky;top:0;z-index:2;height:3.5rem;display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:0 2.5rem;border-bottom:1px solid var(--hr);background:var(--bg);font-size:.85rem;color:var(--muted)}', '.app-top b{color:var(--fg);font-weight:550}.app-top nav a{color:var(--muted);text-decoration:none}.app-top nav a:hover{color:var(--fg)}', '.app-body>main{padding:2rem 2.5rem 4rem;max-width:72rem}', '.app-body>main h1{margin-top:.25rem}', // The home page: the agents as tiles, then the rest as cards. '.tiles{display:grid;grid-template-columns:repeat(auto-fill,minmax(15rem,1fr));gap:1rem;margin:1rem 0 2rem}', '.tile{display:flex;flex-direction:column;gap:.15rem;padding:1rem 1.1rem;border:1px solid var(--hr);border-radius:12px;text-decoration:none;color:var(--fg);transition:background .15s}', '.tile:hover{background:var(--tint);color:var(--fg)}.tile b{font-weight:550}.tile span{font-size:.85rem;color:var(--muted)}', '.tile .links{margin-top:.6rem;font-size:.85rem}.tile .links a{color:var(--muted)}', '.cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(18rem,1fr));gap:1rem;margin:1rem 0 2rem}', '.cards section{padding:1rem 1.1rem;border:1px solid var(--hr);border-radius:12px}.cards h2{margin:0 0 .35rem;font-size:.95rem}.cards p{margin:.3rem 0;font-size:.92rem}', // Narrow, the sidebar folds into a row of links over the page. '@media(max-width:48rem){body.app{display:block}' + '.app-nav{position:static;height:auto;flex-direction:row;flex-wrap:wrap;align-items:center;gap:.1rem .25rem;padding:.5rem .75rem;border-right:0;border-bottom:1px solid var(--hr)}' + '.app-nav>.mark{height:auto;margin:0 .75rem 0 0;padding:.35rem .25rem;border:0}.app-nav h2,.app-nav .empty-note,.app-nav .gear,.app-nav .switch .chev,.app-nav>div.nest{display:none}' + '.app-nav .switch{margin:0}.app-nav .switch>summary{padding:.3rem .55rem}.app-nav .switch .menu{right:auto;width:min(16rem,calc(100vw - 1.5rem))}' + '.app-nav a.item{padding:.35rem .55rem}.app-nav .row a.item{padding-right:.55rem}.app-nav a.item svg{display:none}' + '.app-nav .who{margin:0 0 0 auto;padding:0}.app-nav .who summary{padding:.3rem .45rem}.app-nav .who summary .handle,.app-nav .who summary svg{display:none}' + '.app-nav .nav-foot{display:contents}.app-nav{overflow:visible}.app-nav .who .menu{left:auto;right:0;bottom:auto;top:calc(100% + .25rem);width:min(16rem,calc(100vw - 1.5rem))}' + '.app-nav .who summary .bal{display:none}' + '.app-top{display:none}.app-body>main{padding:1.25rem 1rem 3rem}}', // Chat is correspondence, not a dashboard: quiet surfaces, generous rhythm, and green // reserved for actions and actual activity. Computer and model details stay close to the composer. // The chat fills the window and ends at the composer: the log takes the spare height, so the composer // sits at the bottom whether the thread is short or long, and nothing follows it. 'body.wide{max-width:46rem;min-height:100vh;min-height:100dvh;display:flex;flex-direction:column;padding:1.75rem 1.5rem 0}', 'body.wide>header{font-size:.82rem}body.wide>header .path{display:none}body.wide>header nav a{text-decoration:none;color:var(--muted)}', 'body.wide>hr{border-top:1px solid var(--hair);margin:1.25rem 0 0}', 'body.wide :focus-visible{outline:2px solid var(--green);outline-offset:4px}', 'body.wide>main,#chat{flex:1;display:flex;flex-direction:column}', '#chat>#log{flex:1}', ':is(body.wide,body.docs){background:var(--bg)}', // The open thread's name and who it's with, in a slim bar that stays at the top while the chat scrolls. 'body.wide{--bar-h:3.5rem}', 'body.wide:has(.thread-bar:not([hidden]))>hr{display:none}', '.thread-bar{position:sticky;top:0;z-index:3;display:flex;align-items:center;gap:1rem;min-height:var(--bar-h);margin:0 -1.5rem;padding:.5rem 1.5rem;background:var(--bg);border-bottom:1px solid var(--hair)}', '.tb-main{flex:1;min-width:0;display:flex;align-items:baseline;gap:.75rem}', '.thread-bar h1{margin:0 0 0 -.4rem;min-width:0;font-size:.95rem;font-weight:550;line-height:1.4;letter-spacing:0}', '.thread-bar .title-edit{all:unset;box-sizing:border-box;display:block;max-width:100%;padding:.15rem .4rem;border-radius:6px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:text}', '.thread-bar .title-edit:hover{background:var(--tint)}.thread-bar .title-edit:focus-visible{outline:2px solid var(--green);outline-offset:2px}', '.thread-bar .title-input{width:100%;padding:.15rem .4rem;font:inherit;border:1px solid var(--green);border-radius:6px;background:var(--bg);color:var(--fg);outline:none}', '.tb-sub{flex:none;font-size:.78rem;color:var(--muted);white-space:nowrap}', '.chat-meta{position:relative;flex:none;color:var(--muted);font-size:.78rem}.chat-meta summary{cursor:pointer;list-style:none}.chat-meta summary::-webkit-details-marker{display:none}.chat-meta summary:hover{color:var(--fg)}', '.chat-meta p{position:absolute;right:0;top:calc(100% + .6rem);width:18rem;margin:0;padding:.75rem .9rem;background:var(--glass);border:1px solid var(--hair);border-radius:12px;box-shadow:var(--shadow);line-height:1.55}', // With the sidebar showing, it has the agent's pages and Docs, so the bar keeps to the thread. '@media(min-width:48rem){.chat-meta{display:none}}', '@media(max-width:540px){.thread-bar{margin:0 -1rem;padding:.5rem 1rem}.tb-main{flex-direction:column;align-items:flex-start;gap:0}.thread-bar~.thread-nav{padding-top:.75rem}.tb-sub{font-size:.74rem}}', '.thread-nav{border-bottom:1px solid var(--hair);padding-bottom:1rem;margin-bottom:.5rem;font-size:.82rem;color:var(--muted)}', '.thread-nav>summary{cursor:pointer;width:fit-content}.threads{margin:.75rem 0 0;display:grid;gap:.25rem}', '.threads li{padding:0;text-indent:0;position:relative}.threads li::before{content:none}.threads a{display:block;padding:.4rem 2.1rem .4rem .65rem;border-radius:6px;text-decoration:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}', '.threads a:hover{background:var(--tint);color:var(--fg)}.threads li.on a{color:var(--fg);background:var(--tint)}', '.threads .rename{position:absolute;right:.2rem;top:50%;transform:translateY(-50%);width:1.75rem;height:1.75rem;display:grid;place-items:center;padding:0;border:0;border-radius:6px;background:none;color:var(--muted);cursor:pointer;opacity:0;transition:opacity .12s}', '.threads li:hover .rename,.threads .rename:focus-visible{opacity:1}.threads .rename:hover{background:var(--hair);color:var(--fg)}.threads .rename svg{width:.95rem;height:.95rem}', '.threads .rename-input{width:100%;font:inherit;padding:.4rem .65rem;border:1px solid var(--green);border-radius:6px;background:var(--bg);color:var(--fg);outline:none}', '@media(hover:none){.threads .rename{opacity:.6}}', // On a wide window the threads sit in a panel down the left, and the chat centers in what's left. // Narrower, they fold back into the list above the chat. '.thread-panel{display:none}', '@media(min-width:48rem){' + 'body.wide{margin-left:calc(16rem + max(0rem,(100% - 16rem - 46rem)/2));padding-top:0}' + 'body.wide>header{height:var(--bar-h)}body.wide>hr{margin:0}' + 'body.wide:has(.thread-bar:not([hidden]))>header{display:none}' + '.thread-bar{min-height:calc(var(--bar-h) + 1px)}' + 'body.wide .thread-nav{display:none}' + '.thread-panel{display:flex;flex-direction:column;position:fixed;top:0;left:0;bottom:0;width:16rem;z-index:4;padding:0 .75rem 1rem;' + 'border-right:1px solid var(--hair);background:var(--bg);font-size:.85rem;color:var(--muted)}' + // The mark moves up into the panel, which stays put while the chat scrolls. The page's header // keeps its place with the mark and Docs hidden (the sidebar has both), so the rules under each line up. 'body.wide>header .mark{visibility:hidden}body.wide>header nav{visibility:hidden}' + // Whose threads these are, and which of its computers are up. '.thread-panel .agent-card{display:flex;flex-direction:column;padding:0 .65rem;margin:0 0 1.5rem}' + '.thread-panel .agent-card b{font-size:.95rem;font-weight:550;color:var(--fg);letter-spacing:0}' + '.thread-panel .agent-card .handle{font-size:.76rem;color:var(--faint)}' + '.thread-panel .agent-card a.settings{font-size:.76rem;color:var(--muted);text-decoration:none;margin-top:.15rem}.thread-panel .agent-card a.settings:hover{color:var(--fg)}' + '.thread-panel .agent-card .agent-links{font-size:.76rem;color:var(--muted)}' + '.thread-panel .agent-card .computers{margin-top:.5rem;font-size:.76rem;color:var(--muted);text-decoration:none;width:fit-content}.thread-panel .agent-card .computers:hover{color:var(--fg)}' + '.thread-panel .agent-card .dot{display:inline-block;width:6px;height:6px;margin-right:.4rem;border-radius:50%;vertical-align:.1em;background:var(--faint)}' + '.thread-panel .agent-card .on .dot{background:var(--green)}.thread-panel .agent-card .on.dot{background:var(--green)}' + '.thread-panel .threads li.group{padding:1rem .65rem .3rem;font-size:.72rem;font-weight:500;color:var(--faint)}' + '.thread-panel .threads li.group:first-child{padding-top:.2rem}' + '.thread-panel .panel-head{display:flex;align-items:center;justify-content:space-between;gap:.5rem;padding:0 .4rem 0 .65rem;min-height:1.85rem}' + '.thread-panel .panel-head h2{margin:0;font-size:.82rem;font-weight:500;color:var(--muted)}' + '.thread-panel .new{display:inline-flex;align-items:center;gap:.35rem;padding:.3rem .6rem;border-radius:6px;border:1px solid var(--hair);text-decoration:none;color:var(--fg);font-size:.8rem}' + '.thread-panel .new:hover{background:var(--tint);color:var(--fg)}.thread-panel .new.on{background:var(--tint)}' + '.thread-panel .new svg{width:13px;height:13px}' + '.thread-panel .threads{flex:1;overflow-y:auto;margin:.75rem -.25rem 0;padding:0 .25rem;align-content:start;grid-template-columns:minmax(0,1fr);gap:.1rem}' + '.thread-panel .threads a{display:flex;align-items:baseline;gap:.5rem;padding-right:.65rem;color:var(--fg)}' + '.thread-panel .threads li.on a{background:var(--hair);font-weight:500}' + '.thread-panel .threads .t{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis}' + '.thread-panel .threads time{flex:none;font-size:.74rem;color:var(--faint);font-variant-numeric:tabular-nums}' + // The pencil takes the time's place while the pointer is over a thread; on touch it keeps its own room. '.thread-panel .threads li:hover time,.thread-panel .threads li:focus-within time{visibility:hidden}' + '@media(hover:none){.thread-panel .threads a{padding-right:2.1rem}}' + '.thread-panel .more{margin:.5rem .65rem 0;font-size:.76rem;color:var(--faint)}' + '}', '#log{margin:2rem 0 1.5rem;display:flex;flex-direction:column;gap:1rem}', // A new thread is a greeting with the box right under it, together a little above the middle of the page. // The first message removes the greeting, and the box settles at the bottom like any conversation. '#chat:has(>#log>.empty:only-child){justify-content:center;padding-bottom:10vh}', '#chat>#log:has(>.empty:only-child){flex:none;margin:0 0 1.5rem}', '.empty{text-align:center}', '.empty h2{font-size:2.6rem;font-weight:500;letter-spacing:-.05em;line-height:1.1;margin:0}', '.empty .handle{margin:.4rem 0 0;font-size:.85rem;color:var(--muted)}', '.empty .lede{margin:1.1rem auto 0;max-width:26rem;font-size:1rem;line-height:1.6;color:var(--muted)}', '.empty .facts{display:flex;flex-wrap:wrap;justify-content:center;gap:.45rem 1.5rem;margin:1.35rem 0 0;padding:0;list-style:none;font-size:.78rem;color:var(--faint)}', '.empty .facts li{padding:0;text-indent:0}.empty .facts li::before{content:none}', '.empty .facts a{color:inherit}.empty .facts code{padding:0;background:none;font-size:.95em;color:var(--muted)}', '.empty .facts .dot{display:inline-block;width:6px;height:6px;margin:0 .45rem .1em 0;border-radius:50%;vertical-align:middle;background:var(--faint)}.empty .facts .on .dot{background:var(--green)}', '@media(max-width:540px){body.wide{padding:1rem 1rem 0}#log{gap:.85rem}.empty h2{font-size:2.1rem}}', '#log>*{margin:0}', // An agent's words and its calls read as one turn; the gap opens where the speaker changes. '#log>.msg.user,#log>.msg.user+*{margin-top:.75rem}', '@keyframes settle{from{opacity:0;transform:translateY(6px)}}', '.msg{white-space:pre-wrap;overflow-wrap:anywhere}', '.msg.user{align-self:flex-end;max-width:85%;padding:.75rem 1rem;border-radius:14px 14px 4px 14px;background:var(--tint)}', '.msg.user .who{display:none}', // A task's result (taskResultHtml): a call-like line with its thread, opening to its reply. 'details.task-result>summary .task-open{margin-left:.35rem;font-size:.85rem;color:var(--muted)}details.task-result>summary .task-open:hover{color:var(--fg)}', 'details.task-result .why{margin:0;font-size:.9rem;color:var(--muted)}details.task-result .msg.assistant{font-size:.95rem}', '.task-link{margin:.5rem 0 0;font-size:.85rem}', '.msg.assistant{font-size:1.03rem;line-height:1.65}', // While a run works, one quiet line holds the place the reply will land: a breathing dot and what the agent is doing. Never partial tokens. '.msg.working{display:flex;align-items:center;gap:.55rem;color:var(--muted);font-size:.92rem}', '.msg.working .pip{width:7px;height:7px;border-radius:50%;background:var(--green);animation:breathe 2.8s ease-in-out infinite}', '#log>.feedback{margin-top:-.15rem;display:flex;flex-wrap:wrap;gap:.25rem;align-items:center}', '.feedback>button{width:1.9rem;height:1.9rem;display:inline-grid;place-items:center;border:0;border-radius:6px;background:none;color:var(--muted);cursor:pointer;padding:0}', '.feedback>button:hover,.feedback>button:focus-visible{background:var(--tint);color:var(--fg)}', '.feedback>button[aria-pressed=true]{color:var(--fg);background:var(--tint)}', '.feedback svg{width:1rem;height:1rem;color:inherit;fill:none;stroke:currentColor}', '.feedback form{flex-basis:100%;display:flex;flex-direction:column;gap:.5rem;margin-top:.35rem;padding:.75rem;border:1px solid var(--hair);border-radius:10px}', '.feedback textarea{min-height:4.5rem;resize:vertical}', '.feedback .row{display:flex;flex-wrap:wrap;gap:.75rem;align-items:center;font-size:.85rem;color:var(--muted)}', '.feedback>button+button{margin-left:0}', '.feedback .row button{padding:.3rem .85rem;font-size:.85rem}', '.feedback .row button:first-of-type{margin-left:auto}', '.feedback form .error{margin:0;font-size:.85rem}', '.feedback .said{font-size:.85rem;color:var(--muted)}', // Assistant text after chat.js renders its markdown. '.msg.md{white-space:normal}', '.md>:first-child{margin-top:0}.md>:last-child{margin-bottom:0}', '.md p{margin:.6rem 0}', '.md h3,.md h4,.md h5{font-size:1em;margin:1.2rem 0 .4rem}', '.md ul,.md ol{padding-left:2.5ch;margin:.5rem 0}.md ul{list-style:disc}.md ol{list-style:decimal}', '.md li{padding-left:0;text-indent:0;margin:.15rem 0}.md li::before{content:none}.md li>ul,.md li>ol{margin:.15rem 0}', '.md code{background:var(--code);border-radius:6px;padding:.08em .35em;font-size:.88em}.md pre code{background:none;padding:0;font-size:inherit}', '.md pre{white-space:pre;margin:.75rem 0;background:var(--code);border:1px solid var(--hair);border-radius:14px}', '.md .code-block{margin:.75rem 0;border:1px solid var(--hair);border-radius:14px;overflow:hidden;background:var(--code)}', '.md .code-block .code-toolbar{display:flex;justify-content:flex-end;padding:.35rem .6rem;border-bottom:1px solid var(--hair)}', '.md .code-block pre{margin:0;border:0;border-radius:0}', '.md .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}', '.md blockquote{margin:.6rem 0;padding-left:1rem;border-left:2px solid var(--hair);color:var(--muted)}', '.md .table{overflow-x:auto;margin:.75rem 0}.md table{border-collapse:collapse;font-size:.9rem}', '.md th,.md td{border:1px solid var(--hair);padding:.3rem .65rem;text-align:left;vertical-align:top}', '.md hr{margin:1rem 0;border-top:1px solid var(--hair)}', // Tool calls: quiet lines. A dot fades in when one is done (red if it failed); a faint ring while it runs. 'details.tool,details.calls{font-size:.9rem;color:var(--muted)}', 'details.tool>summary,details.calls>summary{list-style:none;cursor:pointer;position:relative;padding-left:17px;overflow-wrap:anywhere}', 'details.tool>summary::-webkit-details-marker,details.calls>summary::-webkit-details-marker{display:none}', ':is(details.tool,details.calls)>summary .dot{position:absolute;left:0;top:.55em;width:7px;height:7px;border-radius:50%;box-shadow:inset 0 0 0 1.5px var(--faint);transition:background .6s ease,box-shadow .6s ease}', ':is(details.tool,details.calls).live>summary .dot{animation:breathe 2.8s ease-in-out infinite}', ':is(details.tool,details.calls).ok>summary .dot{background:var(--muted);box-shadow:none;animation:none}', ':is(details.tool,details.calls).err>summary .dot{background:var(--red);box-shadow:none;animation:none}', // Two lines: what the call is for, then the tool and where it ran, quieter and all in one face. 'details.tool .what,details.calls .what{display:block;color:var(--fg)}', 'details.tool .tool-name,details.calls .tool-name{font-size:.76rem;line-height:1.35;color:var(--faint);white-space:nowrap}', ':is(details.tool,details.calls) .tool-name code{font-family:inherit;font-size:inherit}', ':is(details.tool,details.calls) .what code{font-size:.92em}', // A run of calls in a row folds into one line: the latest call, and how many there were. Open, the // line gives way to the count, and every call is listed under it, each still opening on its own. 'details.calls>summary .count{font-size:.76rem;color:var(--faint);white-space:nowrap;margin-left:.15rem}', 'details.calls>summary .count::before{content:"· "}details.calls[open]>summary .count::before{content:none}', 'details.calls>summary .fails{color:var(--red)}', 'details.calls>summary .count::after{content:"";display:inline-block;width:.38em;height:.38em;margin-left:.45em;border:solid currentColor;border-width:0 1.5px 1.5px 0;transform:translateY(-.2em) rotate(45deg);transition:transform .2s ease}', 'details.calls[open]>summary .latest{display:none}', 'details.calls[open]>summary{padding-left:0}', 'details.calls[open]>summary .count{margin-left:0}', 'details.calls[open]>summary .count::after{transform:translateY(0) rotate(-135deg)}', 'details.calls>.list{display:flex;flex-direction:column;gap:.7rem;margin:.7rem 0 0 3px;padding-left:14px;border-left:1px solid var(--hair)}', 'details[open].calls>.list{animation:settle .5s cubic-bezier(.2,.7,.2,1)}', 'details.tool .io{margin:.5rem 0 0 17px;border-radius:14px;background:var(--code);border:1px solid var(--hair);overflow:hidden}', 'details[open].tool .io{animation:settle .5s cubic-bezier(.2,.7,.2,1)}', 'details.tool pre{margin:0;padding:.6rem .8rem;background:none;border-radius:0;font-size:.8rem;white-space:pre-wrap;overflow-wrap:anywhere;max-height:24rem;overflow-y:auto}', 'details.tool pre.args{color:var(--fg);border-bottom:1px solid var(--hair)}', 'details.tool pre.out:empty{display:none}', 'details.tool pre.args:has(+pre.out:empty){border-bottom:0}', // The question before a call that changes things: a glass card with the agent's own words, then the command. '.approval{position:relative;border-radius:22px;padding:1rem 1rem .9rem;background:var(--glass);backdrop-filter:blur(20px) saturate(140%);-webkit-backdrop-filter:blur(20px) saturate(140%);' + 'border:1px solid rgb(var(--amber-rgb)/.35);box-shadow:inset 0 1px 0 var(--hi),0 0 40px rgb(var(--amber-rgb)/.08);transition:border-color .6s ease}', '.approval .q{margin:0;font-weight:550}', '.approval .sub{margin:.1rem 0 0;font-size:.82rem;color:var(--muted)}', '.approval pre{margin:.75rem 0 0;padding:.6rem .8rem;border-radius:12px;background:var(--code);font-size:.8rem;white-space:pre-wrap;overflow-wrap:anywhere}', '.approval .buttons{display:flex;gap:.5rem;margin-top:.85rem}', // A diff of what a call changes in a file: the file and counts, then lines on green or red. `.diff{font-family:${MONO};font-size:.78rem;line-height:1.5;color:var(--fg);max-height:24rem;overflow:auto}`, '.approval .diff{margin-top:.75rem;border-radius:12px;background:var(--code);border:1px solid var(--hair)}', 'details.tool .diff{border-bottom:1px solid var(--hair)}details.tool .diff:has(+pre.out:empty){border-bottom:0}', '.diff-head{position:sticky;top:0;z-index:1;display:flex;gap:.75rem;justify-content:space-between;padding:.45rem .7rem;border-bottom:1px solid var(--hair);' + 'background:color-mix(in srgb,var(--bg) 94%,var(--fg))}', '.diff-path{min-width:0;overflow-wrap:anywhere;font-weight:600}.diff-path .dir{font-weight:400;color:var(--muted)}', '.diff-n{flex-shrink:0;font-size:.95em}.diff-n .a{color:var(--green)}.diff-n .r{color:var(--red)}', '.diff-hunk{padding:.3rem 0}.diff-hunk+.diff-hunk{border-top:1px dashed var(--hair)}', '.dl{display:grid;grid-template-columns:1.6em minmax(0,1fr)}', '.dg{text-align:center;color:var(--faint);user-select:none;-webkit-user-select:none}', '.dt{min-height:1.5em;padding-right:.7rem;white-space:pre-wrap;overflow-wrap:anywhere}', '.dl.add{background:rgb(var(--green-rgb)/.12)}.dl.add .dg{color:var(--green)}', '.dl.del{background:rgb(var(--red-rgb)/.11)}.dl.del .dg{color:var(--red)}', '.dl mark{color:inherit;border-radius:3px;padding:.05em 0}.dl.add mark{background:rgb(var(--green-rgb)/.32)}.dl.del mark{background:rgb(var(--red-rgb)/.3)}', `.dl.fold .dt{font-family:${SANS};font-size:.9em;color:var(--faint);padding:.1rem 0}`, '.approval .buttons button{height:2.25rem;margin:0;padding:0 1rem;border-radius:12px;border:1px solid var(--hair);background:var(--tint);color:var(--fg);font-size:.9rem;transition:background .3s ease}', '.approval .buttons button:hover{background:var(--hair);color:var(--fg);border-color:var(--hair)}', '.approval .buttons .yes,.approval .buttons .yes:hover{background:var(--fg);color:var(--bg);border-color:transparent}', '.approval .answer{margin-top:.6rem;font-size:.85rem;color:var(--muted)}', // A restart cut the last run off: one quiet line, and a text button only when the pick-up didn't happen on its own. '.resume{display:flex;flex-wrap:wrap;align-items:baseline;gap:.25rem .6rem;margin:.75rem 0;font-size:.85rem;color:var(--muted)}.resume p{margin:0}', '.resume button{height:auto;min-height:0;margin:0;padding:0;border:0;border-radius:0;background:none;box-shadow:none;color:var(--fg);font-size:inherit;text-decoration:underline;text-decoration-color:var(--hair);text-underline-offset:.2em}', '.resume button:hover{background:none;color:var(--fg);text-decoration-color:currentColor}.resume button:disabled{color:var(--muted)}', '.approval:has(.answer){border-color:var(--hair);box-shadow:inset 0 1px 0 var(--hi)}', // A paper-like composer. The status dot is the only ambient motion; focus never lights up the page. 'form.composer{position:sticky;bottom:0;z-index:2;margin:0 -1rem;padding:1rem 1rem 1rem;background:linear-gradient(to bottom,transparent,var(--bg) 1rem)}', 'form.composer .activity{display:flex;align-items:center;gap:.55rem;height:1.4rem;margin:0 .4rem .6rem;font-size:.85rem;color:var(--muted);white-space:nowrap;overflow:hidden;transition:color .6s ease,height .6s ease,margin .6s ease}', // With nothing to say, the status line folds away, so the box sits right under the thread. 'form.composer:not(.working):not(.waiting) .activity:has(#status:empty){height:0;margin-bottom:0}', 'form.composer #status{overflow:hidden;text-overflow:ellipsis}', 'form.composer .pip{width:6px;height:6px;border-radius:50%;flex:none;background:var(--green);opacity:0;transition:opacity .6s ease,background .6s ease}', 'form.composer.working .pip{opacity:1;animation:breathe 2.8s ease-in-out infinite}', 'form.composer.waiting .pip{opacity:1;background:var(--amber)}', 'form.composer.waiting .activity{color:var(--fg)}', '@keyframes breathe{0%,100%{opacity:.35}50%{opacity:1}}', 'form.composer .wrap{position:relative}', 'form.composer .card{position:relative;overflow:hidden;border-radius:16px;padding:1.1rem .8rem .75rem 1.1rem;background:var(--glass);cursor:text;' + 'border:1px solid var(--hair);box-shadow:var(--shadow);transition:border-color .2s ease}', 'form.composer .card:focus-within{border-color:var(--muted)}', // The card is the text box, so typing rings the card, not the textarea inside it. 'form.composer .card:has(textarea:focus-visible){outline:2px solid var(--green);outline-offset:-1px}', 'body.wide form.composer textarea:focus-visible{outline:0}', 'form.composer.waiting .card{border-color:rgb(var(--amber-rgb)/.3)}', 'form.composer textarea{display:block;width:100%;font:inherit;font-size:1.03rem;line-height:1.5;height:1.5em;max-height:14rem;overflow-y:hidden;resize:none;padding:0 .4rem 0 0;border:0;outline:0;background:transparent;color:var(--fg);caret-color:var(--green)}', // The caret sits at the start of the line; the placeholder starts a hair after it, so the two never overlap. 'form.composer textarea{padding-left:2px}form.composer textarea::placeholder{color:var(--faint);text-indent:3px}', 'form.composer .bar{display:flex;align-items:center;gap:.4rem;margin-top:.75rem;min-width:0}', // Pills open menus; the global bevelled-button look doesn't apply here. 'form.composer .pill{display:inline-flex;align-items:center;gap:.45rem;height:2rem;flex:0 1 auto;min-width:0;margin:0;padding:0 .8rem;border:1px solid transparent;border-radius:6px;background:transparent;color:var(--muted);font:inherit;font-size:.78rem;cursor:pointer;transition:background .2s ease,opacity .2s ease}', 'form.composer .pill:hover,form.composer .pill[aria-expanded=true]{background:var(--hair);color:var(--fg);border-color:var(--hair)}', 'form.composer .pill:disabled{opacity:.5;cursor:default}', // Allow all stays in sight: the pill and its icon turn amber, like a run waiting on you. 'form.composer #approval[data-value=allow],form.composer #approval[data-value=allow] svg{color:var(--amber)}', 'form.composer .pill svg{width:13px;height:13px;flex:none;color:var(--muted)}', 'form.composer .pill span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;max-width:14rem}', 'form.composer .send{margin:0 0 0 auto;flex:none;width:2.4rem;height:2.4rem;padding:0;border:0;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;' + 'background:var(--fg);color:var(--bg);transition:background .2s ease,color .2s ease}', 'form.composer .send:hover{background:var(--green);color:var(--on-green);border:0}', 'form.composer .send:disabled{opacity:1;cursor:default;background:var(--tint);color:var(--faint);box-shadow:none}', 'form.composer .send.stop,form.composer .send.stop:hover{background:var(--fg);color:var(--bg);box-shadow:none}', 'form.composer .send svg{width:18px;height:18px}', // The mic takes Send's place while the box is empty. While it listens it shows the square that stops it. 'form.composer .mic{margin:0 0 0 auto;flex:none;width:2.4rem;height:2.4rem;padding:0;border:0;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;background:transparent;color:var(--muted)}', 'form.composer .mic[hidden]{display:none}', 'form.composer .mic:hover{background:var(--tint);color:var(--fg)}form.composer .mic:disabled{cursor:default;color:var(--faint);background:transparent}', 'form.composer .mic svg{width:18px;height:18px}form.composer .mic>svg+svg,form.composer .mic[aria-pressed=true]>svg:first-child{display:none}form.composer .mic[aria-pressed=true]>svg+svg{display:block}', 'form.composer .mic[aria-pressed=true],form.composer .mic[aria-pressed=true]:hover{background:var(--fg);color:var(--bg)}', // While the agent works, Stop shows the shell winding; pointing at it (or focusing it) shows the square it does. 'form.composer .send.stop .shell{width:auto;height:17px;color:inherit}form.composer .send.stop>svg:not(.shell),form.composer .send.stop:is(:hover,:focus-visible)>.shell{display:none}form.composer .send.stop:is(:hover,:focus-visible)>svg:not(.shell){display:block}', // Sending while the agent works: Send beside Stop, and the message waits under the chat, dashed, until the next step takes it. 'form.composer .send+.stop{margin-left:var(--s-2)}', '#queued{display:flex;flex-direction:column;align-items:flex-end;gap:var(--s-2);margin:-.5rem 0 1.5rem}#queued[hidden]{display:none}', '#queued>.msg.user{background:transparent;border:1px dashed var(--line);display:flex;flex-direction:column;gap:var(--s-2);min-width:min(16rem,85%)}', '#queued .q-pics{font-size:var(--t-sm);color:var(--muted)}', '#queued .q-bar{display:flex;align-items:center;gap:var(--s-3);font-size:var(--t-xs);color:var(--faint);white-space:normal}', '#queued .q-bar .q-label{margin-right:auto;letter-spacing:.06em;text-transform:uppercase}', '#queued .q-bar button{padding:0;border:0;border-radius:0;background:none;color:var(--muted);font-size:var(--t-xs);cursor:pointer}#queued .q-bar button:hover{background:none;color:var(--fg);text-decoration:underline;text-underline-offset:.2em}', '#queued textarea{width:100%;min-height:3.2rem;resize:vertical;border:0;padding:0;background:transparent;color:var(--fg);font:inherit;line-height:inherit;outline:0}', // The menus a pill opens, above the card. 'form.composer .menu{position:absolute;left:.5rem;bottom:calc(100% + .6rem);z-index:3;width:min(23rem,calc(100% - 1rem));max-height:min(26rem,55vh);overflow-y:auto;padding:.4rem;' + 'background:var(--glass);backdrop-filter:blur(24px) saturate(150%);-webkit-backdrop-filter:blur(24px) saturate(150%);border:1px solid var(--hair);border-radius:20px;' + 'box-shadow:inset 0 1px 0 var(--hi),var(--shadow);cursor:default;animation:settle .45s cubic-bezier(.2,.7,.2,1)}', 'form.composer .menu-head{display:flex;justify-content:space-between;align-items:baseline;gap:1rem;padding:.45rem .65rem .25rem;font-size:.78rem;color:var(--muted)}', 'form.composer .menu-head b{font-weight:600;color:var(--fg)}', 'form.composer .menu-label{padding:.55rem .65rem .2rem;font-size:.74rem;color:var(--muted)}', 'form.composer .house{border-bottom:1px solid var(--line);margin-bottom:.25rem;padding-bottom:.25rem}form.composer .house .menu-label{color:var(--fg);font-weight:500}form.composer .menu-note{margin:0;padding:0 .65rem .3rem;font-size:.74rem;color:var(--muted)}', 'form.composer .menu-search{display:block;box-sizing:border-box;width:calc(100% - 1.3rem);margin:.4rem .65rem;padding:.55rem .65rem;font:inherit}', 'form.composer .menu-reasoning{display:flex;align-items:center;gap:.6rem;padding:0 .65rem .45rem;font-size:.78rem;color:var(--muted)}', 'form.composer .menu-reasoning .levels{display:flex;flex-wrap:wrap;gap:.25rem;margin-left:auto}', 'form.composer .level{margin:0;padding:.2rem .55rem;border:1px solid var(--hair);border-radius:999px;background:transparent;color:var(--muted);font:inherit;font-size:.78rem;cursor:pointer}', 'form.composer .level:hover,form.composer .level:focus-visible{color:var(--fg);border-color:var(--fg);outline:0}', 'form.composer .level[aria-pressed=true]{background:var(--fg);border-color:var(--fg);color:var(--bg)}', 'form.composer .pill .pill-note{color:var(--muted)}', 'form.composer .menu-more{display:block;width:100%;margin:0;padding:.45rem .65rem;border:0;border-radius:12px;background:transparent;color:var(--muted);font:inherit;font-size:.82rem;text-align:left;cursor:pointer}', 'form.composer .menu-more:hover,form.composer .menu-more:focus-visible{background:var(--tint);color:var(--fg);outline:0}', 'form.composer .menu-empty{padding:.6rem .65rem;color:var(--muted);font-size:.9rem}', 'form.composer .menu [hidden]{display:none}', 'form.composer .model-row{display:flex;align-items:center}', 'form.composer .model-row .opt{flex:1;min-width:0;width:auto}', 'form.composer .model-favorite{flex:none;margin:0;padding:.45rem;border:0;border-radius:8px;background:transparent;color:var(--muted);font-size:1.2rem;cursor:pointer}', 'form.composer .model-favorite:hover,form.composer .model-favorite:focus-visible{background:var(--tint);color:var(--fg)}', 'form.composer .model-favorite[aria-pressed=true]{color:var(--green)}', // Saved "always allow" rules under the permissions choices, each with a button to ask again. 'form.composer .rule{display:flex;align-items:center;gap:.65rem;padding:.2rem .2rem .2rem .65rem;font-size:.88rem}', 'form.composer .rule span{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}', 'form.composer .rule-remove{flex:none;margin:0;padding:.3rem .55rem;border:0;border-radius:8px;background:transparent;color:var(--muted);font:inherit;font-size:.8rem;cursor:pointer}', 'form.composer .rule-remove:hover,form.composer .rule-remove:focus-visible{background:var(--tint);color:var(--fg)}', 'form.composer .opt{display:flex;align-items:center;gap:.65rem;width:100%;margin:0;padding:.6rem .65rem;border:0;border-radius:12px;background:transparent;color:var(--fg);font:inherit;font-size:.92rem;text-align:left;cursor:pointer}', 'form.composer .opt:hover,form.composer .opt:focus-visible{background:var(--tint);color:var(--fg);border:0;outline:0}', 'form.composer .opt-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}', 'form.composer .opt-note{color:var(--muted);font-size:.8rem;white-space:nowrap;font-variant-numeric:tabular-nums}', 'form.composer .opt svg{width:16px;height:16px;flex:none;color:var(--green);visibility:hidden}', 'form.composer .opt[aria-selected=true] svg{visibility:visible}', 'form.composer .mdot{width:7px;height:7px;border-radius:50%;flex:none;background:var(--faint)}', 'form.composer .mdot.on{background:var(--green)}', // Motion is ambient, never needed: with reduced motion the states are the same, just still. '@media (prefers-reduced-motion:reduce){#log>*,details[open].tool .io,details[open].calls>.list,form.composer .menu,:is(details.tool,details.calls).live>summary .dot,details.calls>summary .count::after,form.composer.working .pip,.msg.working .pip{animation:none}form.composer *{transition:none}}', // The docs: the chat's palette and panel. A fixed panel down the left on a wide window, with the // sections in it; the page itself is a wide column of commands with copy buttons. 'body.docs{max-width:none;padding:0;background:var(--bg)}', 'body.docs>header{height:var(--bar-h,3.5rem);padding:0 1.5rem;font-size:.82rem}body.docs>header nav a{text-decoration:none;color:var(--muted)}body.docs>header nav a:hover{color:var(--fg)}', 'body.docs>hr{border:0;border-top:1px solid var(--hair);margin:0}', 'body.docs :focus-visible{outline:2px solid var(--green);outline-offset:3px}', 'body.docs>footer{margin:0;padding:2rem 1.5rem 3rem}', 'article.docs h2{margin:2.25rem 0 .6rem;font-size:1.3rem;font-weight:600;letter-spacing:-.015em;scroll-margin-top:1rem}', 'article.docs h3{margin:1.5rem 0 .4rem;font-size:1.02rem;font-weight:600;scroll-margin-top:1rem}', 'article.docs h1+p{margin-top:.75rem;font-size:1.08rem;color:var(--muted)}', 'article.docs :is(p,ul,ol){max-width:44rem}', 'article.docs li{margin:.3rem 0}', 'article.docs :not(pre)>code{padding:.08em .35em;border-radius:5px;background:var(--code);font-size:.88em}', 'article.docs>pre{margin:.75rem 0;padding:.85rem 1rem;border:1px solid var(--hair);border-radius:12px;background:var(--code);font-size:.85rem;overflow-x:auto}', 'article.docs .note{max-width:44rem;margin:1rem 0;padding:.7rem 1.1rem;border:1px solid rgb(var(--amber-rgb)/.35);border-radius:14px;font-size:.9rem;color:var(--muted)}', 'article.docs .note>:first-child{margin-top:0}article.docs .note>:last-child{margin-bottom:0}', // A command: one line of mono on a quiet surface, and a copy button docs.js reveals. '.cmd{display:flex;align-items:center;gap:.5rem;max-width:44rem;margin:.75rem 0;border-radius:12px;background:var(--code)}', '.cmd pre{flex:1;min-width:0;margin:0;padding:.75rem 1rem;background:none;border-radius:0;font-size:.88rem;white-space:pre-wrap;overflow-wrap:anywhere}', // The copy button (COPY_INNER): a quiet pill, outlined on hover, "Copied" with a check once it has. ':is(.cmd .copy,.md .code-copy){all:unset;flex:none;display:inline-flex;align-items:center;height:1.75rem;padding:0 .65rem;border-radius:999px;font-size:.8125rem;line-height:1;color:var(--muted);cursor:pointer;white-space:nowrap}', '.cmd .copy{margin-right:.5rem}', ':is(.cmd .copy,.md .code-copy):hover{color:var(--fg);box-shadow:inset 0 0 0 1px var(--fg)}:is(.cmd .copy,.md .code-copy):focus-visible{outline:1.5px solid var(--fg);outline-offset:2px}', ':is(.cmd .copy,.md .code-copy).done{color:var(--fg)}', ':is(.c-idle,.c-done){display:inline-flex;align-items:center;gap:.375rem}.c-done{display:none}.done>.c-idle{display:none}.done>.c-done{display:inline-flex}', ':is(.c-idle,.c-done)>svg{width:1rem;height:1rem;flex:none}', // Tables: a quiet frame, scrolling sideways on a narrow screen rather than squeezing. '.tbl{overflow-x:auto;margin:1rem 0;border:1px solid var(--hair);border-radius:14px}', '.tbl table{width:100%;border-collapse:collapse;font-size:.9rem}', '.tbl :is(th,td){padding:.6rem 1rem;text-align:left;vertical-align:baseline;border-top:1px solid var(--hair)}', '.tbl th{border-top:0;font-size:.78rem;font-weight:500;color:var(--faint)}', '.tbl td:first-child{white-space:nowrap}.tbl td+td{color:var(--muted)}', 'article.docs .tbl code{padding:0;background:none}', '.docs-foot{display:flex;justify-content:space-between;gap:1rem;flex-wrap:wrap;max-width:none!important;margin:4rem 0 0;padding-top:1.25rem;border-top:1px solid var(--hair);font-size:.9rem}', // The site's pages: a fixed panel on a wide window, a fold at the top of the page on a narrow one. '.docs-toc{font-size:.85rem}', '.docs-toc .toc-head{margin:1.1rem 0 .4rem;padding:0 .65rem;font-size:.72rem;font-weight:500;color:var(--faint)}.docs-toc .toc-head:first-child{margin-top:0}', '.docs-toc ul{display:grid;gap:.1rem;margin:0;padding:0;list-style:none}.docs-toc li{margin:0;padding:0;text-indent:0}.docs-toc li::before{content:none}', '.docs-toc a{display:block;padding:.38rem .65rem;border-radius:6px;color:var(--fg);text-decoration:none}', '.docs-toc a:hover{background:var(--tint);color:var(--fg)}.docs-toc a.on{background:var(--hair);font-weight:500}', '.docs-toc ul.subs{margin:.15rem 0 .35rem .65rem;padding-left:.5rem;border-left:1px solid var(--hair)}', '.docs-toc a.sub{padding:.25rem .6rem;color:var(--muted);font-size:.8rem}.docs-toc a.sub.on{background:none;color:var(--fg);font-weight:500}', '.docs-pages{margin:0;padding:.75rem 1.5rem;border-bottom:1px solid var(--hair);font-size:.9rem}', '.docs-pages>summary{cursor:pointer;color:var(--muted)}.docs-pages[open]>summary{margin-bottom:.75rem}', '.docs-panel{display:none}', 'article.docs{max-width:60rem;margin:0 auto;padding:2rem 1.5rem 1rem}', 'article.docs a{text-decoration-color:color-mix(in srgb,currentColor 40%,transparent);text-underline-offset:.15em}', 'article.docs h1{margin:0;max-width:44rem;font-size:clamp(1.6rem,2.6vw,2rem);font-weight:600;line-height:1.2;letter-spacing:-.03em}', '@media(min-width:48rem){' + 'body.docs{margin-left:16rem}' + 'body.docs>header .mark{visibility:hidden}' + '.docs-pages{display:none}' + '.docs-panel{display:flex;flex-direction:column;position:fixed;top:0;left:0;bottom:0;width:16rem;z-index:4;padding:0 .75rem 1rem;overflow-y:auto;border-right:1px solid var(--hair);background:var(--bg);color:var(--muted)}' + '.docs-panel>.mark{font-size:.82rem;padding:0 .65rem;height:var(--bar-h,3.5rem);flex:none;align-self:flex-start}' + '.docs-panel>hr{border:0;border-top:1px solid var(--hair);margin:0 -.75rem 1.25rem}' + 'article.docs{padding:2.5rem 3rem 1rem}' + '}', '@media(max-width:540px){body.docs>header{padding:0 1rem}.docs-pages{padding:.75rem 1rem}article.docs{padding:1.5rem 1rem 1rem}article.docs h2{margin-top:1.75rem}.tbl thead{display:none}.tbl td{display:block;white-space:normal!important;overflow-wrap:anywhere}.tbl td+td{padding-top:0;border-top:0}}', FOOT_AND_SHELL, SYSTEM, CHAT, // Wide, the conversation sits in the middle of the window, and the sidebar stays at the left edge as on every other page. // When the space beside it is narrower than the sidebar, the chat moves right to make room. '@media(min-width:48rem){body.wide{margin-left:max(16rem,(100% - 46rem)/2)}}', '[hidden]{display:none!important}', ].join('') /** * A page's headers. `formAction` widens where forms on the page may go: Chrome checks a form's * redirects against it too, so the sign-in form, whose POST redirects to the owner's PDS, needs more * than 'self'. */ function headers(formAction = "'self'", script: boolean | 'only' = false, microphone = false): Record { // The chat page loads /chat.js and talks to the service with fetch; the docs load /docs.js. No other page runs scripts, // except the landing, which loads /docs.js for its copy button and gets nothing else ('only'). const scripts = script === 'only' ? "; script-src 'self'" : script ? "; script-src 'self'; connect-src 'self'" : '' // The chat composer previews pasted images from blob: URLs before they're sent. const images = script === true ? "'self' blob:" : "'self'" return { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'content-security-policy': `default-src 'none'; style-src 'unsafe-inline'; img-src ${images}; font-src 'self'; form-action ${formAction}; base-uri 'none'; frame-ancestors 'none'${scripts}`, // Not no-referrer: that makes browsers send "Origin: null" on forms, and the service checks Origin. 'referrer-policy': 'same-origin', 'x-content-type-options': 'nosniff', 'x-frame-options': 'DENY', 'cross-origin-opener-policy': 'same-origin', 'permissions-policy': microphone ? 'microphone=(self)' : 'microphone=()', } } const DESCRIPTION = 'AI made simple.' const PRELOAD = (FRANKLIN_HREF ? `` : ``) + (DISPLAY_HREF ? `` : '') /** The snail as the header draws it, beside "Languid"; the chat's thread panel uses it too. */ export const LOGO = `` /** Where the server puts the signed-in owner's sidebar (see appNav) as it sends an app page. */ export const APP_NAV = '' /** Around a page's own part of the sidebar, which the server moves under the open agent's row. */ export const NAV_NEST = ['', ''] as const /** * The sidebar's one script: the agent switcher closes on a click anywhere else, or on Escape. Without scripts it still opens and * closes from its own row (a details element). */ export const NAV_JS = String.raw`(() => { const sw = document.getElementById('agent-switch') if (!sw) return document.addEventListener('click', (e) => { if (sw.open && !sw.contains(e.target)) sw.open = false }) document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && sw.open) { sw.open = false; sw.querySelector('summary').focus() } }) })()` export const NAV_JS_HREF = `/nav.js?v=${crypto.createHash('sha256').update(NAV_JS).digest('hex').slice(0, 10)}` /** Languid's icons: a 24px grid and the mark's round line (see the Foot and shell design). */ const ICON_NAV = (body: string) => `` /** The asking icon: a question mark that starts as a curl of shell. The alert for anything waiting on its owner. */ export const ICON_NEEDS_YOU = ICON_NAV('') /** * Inside every copy button: the copy glyph and "Copy", and the check and "Copied", which a button * with the class done shows instead. Docs, the landing and chat code blocks all use it. */ /** The copy glyph: a sheet in front, and the corner of the one behind it. Copy buttons everywhere draw it. */ const ICON_COPY = ICON_NAV('') /** The check a copy button turns into once it has copied. */ const ICON_COPIED = ICON_NAV('') export const COPY_INNER = `${ICON_COPY}Copy` + `${ICON_COPIED}Copied` const NAV_HOME = ICON_NAV('') /** Inbox: a tray. */ const NAV_INBOX = ICON_NAV('') const NAV_CHAT = ICON_NAV('') const NAV_COMPUTER = ICON_NAV('') const NAV_BELL = ICON_NAV('') const NAV_DISCORD = ICON_NAV('') const NAV_KEY = ICON_NAV('') const NAV_MODEL = ICON_NAV('') const NAV_DOCS = ICON_NAV('') /** Billing: a card with its stripe. */ const NAV_CARD = ICON_NAV('') /** Usage: three bars on a baseline. */ const NAV_USAGE = ICON_NAV('') /** What's new: a small flag. */ const NAV_NEWS = ICON_NAV('') const NAV_GEAR = ICON_NAV('') /** Leaving the app: an arrow out of a box, after a link that opens in a new tab. Drawn heavier since it sits smaller. */ const ICON_EXTERNAL = ICON_NAV('').replace('Docs${ICON_EXTERNAL}` /** What an agent is doing, as the sidebar and Home show it with the shell. */ export type AgentState = 'idle' | 'running' | 'done' | 'waiting' | 'failed' const STATE_LABEL: Record = { idle: 'Idle', running: 'Running', done: 'Done', waiting: 'Needs you', failed: 'Failed' } const SPIRAL_D = SNAIL.match(/d="([^"]+)"/)![1] /** The glyph for a state: the shell's centre dot when idle, the spiral (drawing itself while running), the shell with its head up when it needs you, and an X when it failed. */ export function shellGlyph(state: AgentState): string { const svg = (box: string, inner: string) => `${inner}` const spiral = `` if (state === 'failed') return svg('8 19 31 37', '') if (state === 'waiting') return svg('8 19 50 37', `${spiral}`) return svg('8 19 31 37', spiral) } /** The cookie that remembers which agent the sidebar shows (the last one opened). */ export const AGENT_COOKIE = 'languid_agent' /** How a page finds an agent's full handle by its name; the service sets it (setAgentHandles). */ let agentHandle: (name: string) => string | undefined = () => undefined export function setAgentHandles(of: (name: string) => string | undefined) { agentHandle = of } /** Where an agent's pages start: /agents/, e.g. /agents/scout.languid.ai. Its name when the handle isn't known. */ export const agentBase = (name: string) => `/agents/${encodeURIComponent(agentHandle(name) ?? name)}` /** * The sidebar of an app page: home, the current agent (a switcher to pick another, or make one) with its menu and threads * under it, the places to manage things, and who's signed in. The current agent is the one whose page this is, or the last * one opened (agent), or the first. */ export function appNav(v: { handle: string; agents: { name: string; displayName?: string; handle: string; state?: AgentState }[]; path: string; agent?: string; admin?: boolean; nest?: string; creditUsd?: number; accounts?: { did: string; handle: string }[]; inbox?: number; news?: boolean }): string { const current = (href: string, exact = false) => (exact ? v.path === href : v.path === href || v.path.startsWith(href + '/')) ? ' aria-current="page"' : '' const waiting = v.inbox ?? 0 const item = (href: string, icon: string, label: string, exact = false) => `${icon}${esc(label)}` const cur = v.agents.find((a) => v.path === agentBase(a.name) || v.path.startsWith(`${agentBase(a.name)}/`)) ?? v.agents.find((a) => a.name === v.agent) ?? v.agents[0] const shown = (a: { name: string; displayName?: string }) => esc(a.displayName ?? a.name) const needs = (a: { state?: AgentState }) => (a.state === 'waiting' ? 'Needs you' : '') const agents = cur ? `
` + `${shown(cur)}${needs(cur)}${NAV_CHEVRON}` + `
` + // The current agent's menu and threads: the chat page sends its own (with the thread it shows marked); other pages get the server's. `` : `

No agents yet.

${NAV_PLUS}New agent` return ( item('/', NAV_HOME, 'Home', true) + item('/inbox', NAV_INBOX, 'Inbox').replace('', waiting ? `${ICON_NEEDS_YOU}${waiting}` : '') + agents + // Who's signed in, with what's left of their credit; the places to manage things are in its menu, so the threads keep the height. `` ) } /** Marks the agent's page this is (Memory, Settings and the rest) in its menu. */ function markSub(nest: string, path: string): string { return nest.replace(/ (path === href || path.startsWith(href + '/') ? `${m} aria-current="page"` : m)) } const NAV_CHEVRON = ICON_NAV('') const NAV_CHECK = ICON_NAV('') const NAV_PLUS = ICON_NAV('') const NAV_PERSON = ICON_NAV('') const NAV_OUT = ICON_NAV('') /** * Who's signed in, at the foot of the sidebar, with what's left of their credit: a menu of the places to manage things, the * browser's signed-in accounts (one click switches), adding another, and signing out of the one in use. No script: a details element. */ function accountMenu(handle: string, others: { did: string; handle: string }[], more: { creditUsd?: number; news?: boolean; manage?: string } = {}): string { const initial = (h: string) => `` const out = more.creditUsd !== undefined && more.creditUsd <= 0 const credit = more.creditUsd === undefined ? '' : `${out ? 'Out of credit' : `$${more.creditUsd.toFixed(2)}`}` const dot = more.news ? '' : '' return ( `
${initial(handle)}${dot}${esc(handle)}${credit}${NAV_CHEVRON}` + `
` ) } export function page( status: number, title: string, main: string, opts: { headers?: Record; formAction?: string; path?: string; nav?: string; script?: boolean | 'only'; microphone?: boolean; wide?: boolean; bodyClass?: string; footer?: boolean; app?: boolean; style?: string } = {}, ): Page { const head = `` + `${esc(title)}` + `` + `` + `${PRELOAD}` if (opts.app) { // The sidebar's agents and account are the signed-in owner's: the server fills APP_NAV in as it sends the page. const crumb = title.replace(/ · Languid$/, '') || 'Home' return { status, headers: { ...headers(opts.formAction, opts.script, opts.microphone), ...opts.headers }, body: head + `` + `
${esc(crumb === 'Languid' ? 'Home' : crumb)}
` + `
${main}
`, } } return { status, headers: { ...headers(opts.formAction, opts.script, opts.microphone), ...opts.headers }, body: `` + `${esc(title)}` + `` + `` + `${PRELOAD}${opts.wide || opts.bodyClass ? `` : ''}` + `
${LOGO}` + `Languid${esc(opts.path ?? '/')}

` + `
${main}
${opts.footer === false ? '' : '
Languid · Slow language since 2024
'}`, } } /** A page with the title as its heading: the sign-in steps and errors. */ export function simplePage(status: number, title: string, body: string, extra: Record = {}, opts: { formAction?: string } = {}): Page { return page(status, 'Languid', `

${esc(title)}

${body}`, { headers: extra, ...(opts.formAction ? { formAction: opts.formAction } : {}) }) } /** * The landing page. `signIn` is the service's origin when sign-in is on, or why it is off. * `error` and `handle` come back from a failed attempt so the form can be fixed and resent. */ export function landingPage( signIn: { origin: string } | { reason: string } | { elsewhere: string }, attempt: { error?: string; handle?: string; status?: number; add?: boolean } = {}, ): Page { let form: string let formAction: string | undefined if ('elsewhere' in signIn) { // Reached under another name (a tailnet address, say): sign-in only works on the service's origin. form = `

Sign in at ${esc(new URL(signIn.elsewhere).host)}.

` } else if ('origin' in signIn) { // The form posts here, then the service redirects to the owner's PDS, which can be any HTTPS // origin (or http on a loopback dev stack). formAction = signIn.origin.startsWith('http:') ? "'self' https: http:" : "'self' https:" form = (attempt.error ? `` : '') + `` } else { form = `

Sign-in isn't available on this service: ${esc(signIn.reason)}.

` } if (attempt.add) return page( attempt.status ?? 200, 'Languid', `
Add another account
${form}

Back

`, { formAction, nav: '', path: '', footer: false }, ) const origin = 'origin' in signIn ? signIn.origin : DEFAULT_SERVICE const install = installCommand(origin) const nav = `Docs` + (SOURCE_URL ? `Source` : '') return page( attempt.status ?? 200, 'Languid', `

An open agent platform on atproto.

` + `

Agents for the Atmosphere

${form}` + (INVITES_FROM ? `

New here? Ask ${bluesky(INVITES_FROM)} on Bluesky for an invite.

` : '') + `
` + `` + `
${LANDING_POINTS.map( ([icon, title, text]) => `
${ICON_NAV(icon)}

${esc(title)}

${text}

`, ).join('')}
` + (install ? `

Prefer the terminal?

${esc(install)}
` + `

Install and sign in, then run languid to meet your first agent.

` : '') + `

Languid is early alpha, and your agents run on a server Cameron operates for now. Keep sensitive data out.

` + `
`, { formAction, nav, path: '', footer: false, bodyClass: 'landing', style: LANDING_STYLE, script: 'only' }, ) } /** What Languid is, one line each, from Cameron's intro. Icons on the Foot and shell grid. */ const LANDING_POINTS: [icon: string, title: string, text: string][] = [ [ '', 'Own your data', 'Your data is valuable, but that value goes to AI companies and other platforms. You should have a say in where that value goes.', ], [ '', 'Talk to your agent anywhere', 'Use your terminal, the browser, Discord, Claude or ChatGPT. Each one reaches the same agent, with the same memory.', ], [ '', 'See what your agent remembers', 'Read your agent\'s memory in the browser, fix mistakes, and choose what stays in mind.', ], [ '', 'Works on your computers', 'Connect a computer with one command and your agent can run tasks there. Your agent can also work in a cloud sandbox.', ], [ '', 'Use the model you like', 'Start with the credit your invite includes, or connect your ChatGPT plan, an Anthropic key or OpenRouter.', ], [ '', 'Host Languid yourself', 'Languid is open source. Host any part on your own hardware, or the whole thing.', ], ] /** * The landing's drawing, in the vaguepost style: the tailless snail on the ground, a butterfly (a nod * to atproto's home, not its logo) away along a dotted trail, and a flower ahead. Pen-weight lines. */ const LANDING_SCENE = `` const LANDING_STYLE = [ 'body.landing{max-width:68rem;padding:1.5rem 1.5rem 2.5rem}', 'body.landing>hr{display:none}', 'body.landing header nav{display:flex;gap:var(--s-5);font-size:var(--t-sm)}', 'body.landing header nav a{color:var(--muted);text-decoration:none}body.landing header nav a:hover{color:var(--fg)}', 'body.landing a{transition:none}', '.hero{display:grid;justify-items:start;gap:var(--s-5);margin:clamp(3rem,10vw,7rem) 0 0}', '.hero .lede{margin:0;font-size:var(--t-lg);color:var(--muted)}', `.hero h1{margin:0;font-family:${DISPLAY};font-weight:var(--w-regular);font-size:clamp(2.5rem,7vw,5.25rem);line-height:1.04;letter-spacing:-.01em;max-width:15ch;text-wrap:balance}`, '.hero form.signin{margin-top:var(--s-4);gap:var(--s-2);flex-wrap:nowrap;width:100%;max-width:26rem}', '.hero form.signin input{flex:1;min-width:0;height:var(--control);font-size:var(--t-sm)}', '.hero .error{margin:var(--s-4) 0 0;padding:var(--s-1) var(--s-3);border-left:var(--stroke) solid var(--red)}', '.hero .invite{margin:0;font-size:var(--t-sm);color:var(--muted)}', '.scene{margin:clamp(2rem,6vw,4rem) 0 0;color:var(--fg)}', '.scene svg{display:block;width:100%;height:auto}', '.scene :is(path,circle){stroke-width:1.5px;vector-effect:non-scaling-stroke}', '.scene .thin{stroke-width:1px}.scene .dots{stroke-width:1.75px;stroke-dasharray:0 6}', '.points{display:grid;grid-template-columns:repeat(auto-fit,minmax(16rem,1fr));gap:var(--s-7) var(--s-6);margin:var(--s-7) 0 0;padding-top:var(--s-7);border-top:var(--hairline) solid var(--hair)}', '.point svg{width:28px;height:28px;color:var(--fg)}', `.point h2{margin:var(--s-3) 0 var(--s-2);font-family:${DISPLAY};font-weight:var(--w-regular);font-size:var(--d-sm);line-height:1.2}`, '.point p{margin:0;color:var(--ink2);font-size:var(--t-md);max-width:34ch}', '.landing :not(pre)>code{font-family:' + MONO + ';font-size:.86em;background:var(--code);padding:.1em .4em;border-radius:6px}', '.start{margin:clamp(4rem,10vw,6rem) 0 0;max-width:36rem}', `.start h2{margin:0 0 var(--s-4);font-family:${DISPLAY};font-weight:var(--w-regular);font-size:var(--d-md)}`, '.start .cmd{margin:0}.start pre{padding:var(--s-3) var(--s-4);font-size:var(--t-sm);white-space:pre;overflow-x:auto}', '.start p{margin:var(--s-3) 0 0;color:var(--muted);font-size:var(--t-sm)}', '.foot{margin:clamp(4rem,10vw,6rem) 0 0;padding-top:var(--s-5);border-top:var(--hairline) solid var(--hair);display:flex;flex-wrap:wrap;justify-content:space-between;gap:var(--s-3) var(--s-6);font-size:var(--t-sm);color:var(--muted);text-align:left}', '.foot p{margin:0}.foot .links{display:flex;flex-wrap:wrap;gap:var(--s-5)}', '.foot a{color:var(--muted)}.foot a:hover{color:var(--fg)}', '@media (max-width:40rem){body.landing{padding:1rem 1rem 2rem}.points{gap:var(--s-6)}}', ].join('') /** What connecting a computer exposes, shown before every command or button that connects one. */ export const riskNotice = () => `` /** How a terminal signs in to this service: plain `languid login` for the hosted one. */ export const loginCommand = (origin: string) => (origin === DEFAULT_SERVICE ? 'languid login' : `languid login --url ${origin}`) /** Base for an owner's default first-agent name (`-agent`, `-agent-2` up to 31 chars). */ export function suggestedAgentBase(handle: string): string { const label = handle.split('.')[0].toLowerCase().replace(/[^a-z0-9-]/g, '').replace(/-+/g, '-') return (/^[a-z]/.test(label) ? label : `a${label}`).slice(0, 23).replace(/-+$/, '') } export const suggestedAgentName = (handle: string) => `${suggestedAgentBase(handle)}-agent` /** The page a signed-in owner sees at `/`: what needs them, then each agent with its shell. */ export function accountPage(who: { handle: string did: string agents: string[] origin: string budget?: { budgetUsd: number; spentUsd: number } handles?: Record /** Display names, where an agent has one. */ displayNames?: Record states?: Record /** One line on what just happened, such as an agent deleted from its settings. */ notice?: string /** Why the New agent form didn't make one. */ error?: string /** Per agent: its model, how many computers it has, and its latest thread. */ cards?: Record /** Model calls over the last 7 days: what Languid charged, and how many. */ week?: { charged: number; calls: number } /** The onboarding step asking what they use Languid for (aboutYouCard), until they answer or skip it. */ about?: string }): Page { const nameOf = (a: string) => who.displayNames?.[a] ?? a const stateOf = (a: string) => who.states?.[a]?.state ?? 'idle' const href = (a: string) => agentBase(a) const waiting = who.agents.filter((a) => stateOf(a) === 'waiting') const running = who.agents.filter((a) => stateOf(a) === 'running') const list = (agents: string[]) => { const names = agents.map(nameOf); return names.length < 3 ? names.join(' and ') : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}` } const lede = !who.agents.length ? who.about ? 'No agents yet. Pick below to start one, or name your own.' : 'No agents yet. Name your first one below.' : [ waiting.length ? `${esc(list(waiting))} ${waiting.length === 1 ? 'needs' : 'need'} you.` : '', running.length ? `${esc(list(running))} ${running.length === 1 ? 'is' : 'are'} working.` : '', !waiting.length && !running.length ? 'Nothing needs you right now.' : '', ].filter(Boolean).join(' ') const needs = waiting.length ? `

Needs you

${waiting .map((a) => { const thread = who.states?.[a]?.thread return `${ICON_NEEDS_YOU}${esc(nameOf(a))} is waiting on you` }) .join('')}
` : '' // The agents are the page: a card each, with what it runs, when it last moved and where it left off. const now = Date.now() const since = (iso: string) => { const a = ago(iso, now) return a === 'now' ? 'active now' : /^\d/.test(a) ? `active ${a} ago` : `active ${a}` } const card = (a: string) => { const st = stateOf(a) const label = { idle: '', running: 'Working', done: 'Done', waiting: 'Needs you', failed: 'Failed' }[st] const c = who.cards?.[a] ?? {} const t = c.latest const meta = [c.model ? esc(c.model) : '', t ? since(t.updatedAt) : 'no threads yet'].filter(Boolean).join(' · ') const thread = t ? `${esc(t.name)}${t.preview && t.preview !== t.name ? `${esc(t.preview)}` : ''}` : `

Say hello to start its first thread.

` return ( `` ) } const newLabel = !who.agents.length && who.about ? 'Or name one' : 'New agent' const newPlaceholder = !who.agents.length ? suggestedAgentName(who.handle) : 'name' const newAgent = `
` + `` + `
` + (who.error ? `` : '') + `
` const agents = `

Agents

${who.agents.map(card).join('')}${newAgent}
` // Money in one line: credit left (when there's a budget) and this week's spend, linking to the detail. const money = [ who.budget ? `$${Math.max(0, who.budget.budgetUsd - who.budget.spentUsd).toFixed(2)} credit left` : '', who.week ? (who.week.charged > 0 ? `$${who.week.charged.toFixed(2)} spent this week` : `${who.week.calls} model ${who.week.calls === 1 ? 'call' : 'calls'} this week`) : '', ].filter(Boolean) const moneyLine = money.length ? `

${money.join(' · ')} · Usage${who.budget ? ' · Add credit' : ''}

` : '' // The terminal commands stay folded until they have an agent (and fold back once a computer is connected). const anyComputer = who.agents.some((a) => (who.cards?.[a]?.computers ?? 0) > 0) const terminal = riskNotice() + `
${installCommand(who.origin) ? `${esc(installCommand(who.origin)!)}\n` : ''}${esc(loginCommand(who.origin))}\nlanguid computer setup\nlanguid chat ${esc(who.agents[0] ?? '')}
` + `

computer setup lets your agents work on that computer. Docs

` return page( 200, 'Home · Languid', `

Home

${who.notice ? `

${esc(who.notice)}

` : ''}

${lede}

` + moneyLine + (who.about ?? '') + needs + agents + (anyComputer || !who.agents.length ? `
Use from a terminal${terminal}
` : `

From a terminal

${terminal}`), { app: true }, ) } /** Forms that go on to the owner's PDS, which can be any HTTPS origin (or http on a loopback dev stack). */ export const toPds = (origin: string) => (origin.startsWith('http:') ? "'self' https: http:" : "'self' https:") /** * What they use Languid for, in a couple of taps: personal or work, then (for work) what kind. Home * shows it until they answer or skip; the About you page shows it with their answer picked. */ export function aboutYouCard(v: { step: 'use' | 'work' /** Where the form returns to: `/` or `/profile`. */ next: '/' | '/profile' current?: OwnerProfile error?: string /** Their sign-in predates the permission to save this: offer to sign in again, as `handle`. */ signInAgain?: string /** True on Home when they have no agents yet: answering or skipping starts their first agent. */ firstAgent?: boolean }): string { const on = (yes: boolean) => (yes ? ' class="on" aria-pressed="true"' : '') const c = v.current const hidden = `` const again = v.signInAgain ? `
` : v.error ? `` : '' const skip = v.next === '/' ? `` : '' if (v.step === 'use') { const note = v.firstAgent ? 'Pick one to make your first agent; it starts out knowing this.' : 'Languid will give this information to your agents so they can work with you better.' return ( `

What brings you to Languid?

` + `

${note}

${again}` + `
${hidden}
` + `` + `
` + (skip ? `
${skip}
` : '') + `
` ) } const kinds = (Object.keys(OWNER_WORK) as (keyof typeof OWNER_WORK)[]).filter((k) => k !== 'other') const workNote = v.firstAgent ? 'Pick the closest to start your first agent.' : 'Pick the closest.' return ( `

What kind of work?

` + `

${workNote}

${again}` + `
${hidden}
` + kinds.map((k) => ``).join('') + `
` + `
${hidden}` + `
` + `
${hidden}Back${skip}
` + `
` ) } /** A handle label from a name: "Basil Bot" → "basil-bot". The welcome page's script does the same. */ export function handleFromName(name: string): string { const s = name .normalize('NFKD') .replace(/[\u0300-\u036f]/g, '') .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, '') return (/^[a-z]/.test(s) || !s ? s : `a-${s}`).slice(0, 31).replace(/-+$/, '') } /** Whether a handle label is one an agent can have here (the shape only; whether it's free is the server's call). */ export const handleShapeOk = (h: string) => /^[a-z][a-z0-9-]{0,30}$/.test(h) && !h.endsWith('-') && !h.includes('--') /** * The welcome page's script: tapping a suggested name fills it in, the handle follows the name until * edited on its own, and a quiet check says whether the handle is free. */ export const WELCOME_JS = String.raw`(() => { const form = document.querySelector('form.wl-name') if (!form) return const name = form.querySelector('#agent-name'), handle = form.querySelector('#agent-handle'), status = form.querySelector('.wl-handle-status') const shown = document.querySelectorAll('[data-agent-name]') let manual = handle.value !== '' && handle.value !== slug(name.value) function slug(v) { let s = v.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') if (s && !/^[a-z]/.test(s)) s = 'a-' + s return s.slice(0, 31).replace(/-+$/, '') } const say = (text, state) => { status.textContent = text; status.dataset.state = state || '' } let timer = 0, asked = '' function check() { const h = handle.value clearTimeout(timer) if (!h) return say('', '') if (!/^[a-z][a-z0-9-]{0,30}$/.test(h) || h.endsWith('-') || h.includes('--')) return say('Use lowercase letters, numbers and single dashes, starting with a letter.', 'bad') say('Checking…', 'wait') timer = setTimeout(async () => { asked = h try { const r = await fetch('/agents/available?handle=' + encodeURIComponent(h), { credentials: 'same-origin' }) const j = await r.json() if (asked !== handle.value) return if (j.available) say('Available', 'ok') else say(j.suggestion ? 'Taken. Try ' + j.suggestion + '.' : 'Taken.', 'bad') } catch { if (asked === handle.value) say('', '') } }, 300) } function syncName() { const v = name.value.trim() for (const el of shown) el.textContent = v || el.dataset.agentName if (!manual) { handle.value = slug(v); fit(); check() } } // The handle input is as wide as its text, so the domain sits right after it. const pen = document.createElement('canvas').getContext('2d') function fit() { const cs = getComputedStyle(handle) pen.font = cs.fontStyle + ' ' + cs.fontWeight + ' ' + cs.fontSize + ' ' + cs.fontFamily handle.style.width = Math.ceil(pen.measureText(handle.value || handle.placeholder).width) + 2 + 'px' } if (document.fonts) document.fonts.ready.then(fit) name.addEventListener('input', syncName) handle.addEventListener('input', () => { const v = handle.value.toLowerCase().replace(/[^a-z0-9-]/g, '-') if (v !== handle.value) handle.value = v manual = handle.value !== '' && handle.value !== slug(name.value) if (!handle.value) { manual = false; handle.value = slug(name.value) } fit(); check() }) for (const chip of document.querySelectorAll('.wl-suggest a[data-name]')) { chip.addEventListener('click', (e) => { e.preventDefault() name.value = chip.dataset.name manual = false syncName() name.focus() }) } fit() if (handle.value) check() })()` export const WELCOME_JS_HREF = `/welcome.js?v=${crypto.createHash('sha256').update(WELCOME_JS).digest('hex').slice(0, 10)}` /** * The first jobs a new owner picks from on the welcome page. The pick becomes their agent's first * message, sent for them, so the chat opens with the reply already arriving. */ export const FIRST_JOBS = { day: { title: 'Start my day', line: "A short note each morning with what's ahead.", icon: '', prompt: "Send me a short note every morning with what's on my plate and anything I asked you to remember. Ask me when I usually start my day and what a normal day looks like, then set it up.", }, plan: { title: 'Plan my week', line: 'Lay out the week, then plan the next one together each Sunday.', icon: '', prompt: "Help me plan my week. Ask me what's coming up, lay out a simple plan, then check in every Sunday evening to plan the next one.", }, remind: { title: 'Remind me', line: 'Say it once and get a nudge at the right time.', icon: '', prompt: 'Help me remember things. Ask me what I need to remember and when, then message me at the right time.', }, habit: { title: 'Build a habit', line: 'Daily check-ins and a short weekly summary.', icon: '', prompt: 'Help me keep up a habit. Ask me what it is and when to check in, then check in with me each day and send me a short summary every week.', }, learn: { title: 'Learn something', line: 'Short lessons that build on what you already know.', icon: '', prompt: "Teach me something new, a little at a time. Ask me what I'm curious about and what I already know, start the first lesson, then send me a short review every few days.", }, computer: { title: 'Work on my computer', line: "Sort files, free up space, fix what's broken.", icon: '', prompt: "Help me with my computer. Walk me through connecting it, then ask what needs doing, like tidying files, freeing up space or fixing something that's broken.", }, } as const export type FirstJob = keyof typeof FIRST_JOBS | 'other' /** The longest "something else" a new owner can type as their first job. */ export const FIRST_TASK_MAX = 500 /** What the agent's first message says for a job (and, for "something else", what they typed). */ export function firstJobPrompt(job: FirstJob, task?: string): string | undefined { if (job === 'other') return task?.trim() ? task.trim().slice(0, FIRST_TASK_MAX) : undefined return FIRST_JOBS[job]?.prompt } export const isFirstJob = (v: unknown): v is FirstJob => v === 'other' || (typeof v === 'string' && Object.hasOwn(FIRST_JOBS, v)) const WELCOME_ICON = (paths: string) => `` const WELCOME_BACK = WELCOME_ICON('') const WELCOME_PLUS = WELCOME_ICON('') const WELCOME_STYLE = [ 'body.welcome{max-width:none;margin:0;padding:0;min-height:100vh;min-height:100dvh;display:flex;flex-direction:column}', '.wl-top{display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:1.4rem max(1.5rem,env(safe-area-inset-right)) 1rem max(1.5rem,env(safe-area-inset-left))}', `.wl-top .mark b{font-family:${DISPLAY};font-weight:400;font-size:1.15rem}`, '.wl-steps{display:flex;gap:.4rem}.wl-steps i{width:1.6rem;height:2px;border-radius:2px;background:var(--line)}.wl-steps i.on{background:var(--fg)}', '.wl-top form{margin:0}.wl-top button{border:0;padding:.3rem 0;color:var(--muted);font-size:.9rem;background:none}.wl-top button:hover{color:var(--fg);background:none}', '.wl{flex:1;display:flex;flex-direction:column;justify-content:center;width:100%;max-width:64rem;margin:0 auto;padding:1rem max(1.5rem,env(safe-area-inset-right)) 10vh max(1.5rem,env(safe-area-inset-left))}', '.wl-grid{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(0,1fr);align-items:center;gap:3rem 4rem}', '@media (max-width:52rem){.wl-grid{grid-template-columns:minmax(0,1fr);gap:2.5rem}.wl{justify-content:flex-start;padding-top:2rem}}', `.wl h1{font-family:${DISPLAY};font-weight:400;font-size:clamp(2.1rem,4.6vw,3.2rem);line-height:1.08;letter-spacing:0;margin:0;text-wrap:balance}`, '.wl-eyebrow{display:inline-flex;align-items:center;gap:.4rem;color:var(--muted);font-size:.92rem;margin:0 0 .9rem;text-decoration:none}', 'a.wl-eyebrow:hover{color:var(--fg)}.wl-eyebrow svg{width:1rem;height:1rem}', '.wl-lede{color:var(--ink2);font-size:1.08rem;max-width:30rem;margin:1rem 0 0}', '.wl .error{margin:1.25rem 0 0;padding:.1rem 0 .1rem .8rem;color:var(--fg)}', '.wl .notice{margin:1.25rem 0 0;color:var(--muted)}', // Step one: the jobs as pills. '.wl-chips{display:flex;flex-wrap:wrap;gap:.6rem;margin-top:2rem}', '.wl-chip{display:inline-flex;align-items:center;gap:.5rem;height:2.6rem;padding:0 1.1rem 0 .9rem;border:1px solid var(--line);border-radius:999px;color:var(--fg);text-decoration:none;font-size:.95rem;white-space:nowrap}', 'a.wl-chip:hover,a.wl-chip:focus-visible{border-color:var(--fg);background:var(--tint);color:var(--fg)}', '.wl-chip svg{width:1.15rem;height:1.15rem;flex:none}', '.wl-else{border-style:dashed;color:var(--muted);margin:0;padding-right:.3rem;max-width:100%}.wl-else:focus-within{border-style:solid;border-color:var(--fg);color:var(--fg)}', '.wl-else input{border:0;border-radius:0;padding:0;background:none;font:inherit;color:var(--fg);width:8.5rem;min-width:0;flex:1}.wl-else input:focus{outline:none}.wl-else input::placeholder{color:var(--muted)}', '.wl-else:focus-within input{width:16rem}', '.wl-else button{display:none;height:2rem;padding:0 .9rem;font-size:.85rem;background:var(--fg);color:var(--bg);border-color:var(--fg)}.wl-else button:hover{background:var(--fg);color:var(--bg);opacity:.86}', '.wl-else:focus-within button,.wl-else input:not(:placeholder-shown)+button{display:inline-flex;align-items:center}', // The card: the agent as it takes shape. '.wl-card{border:1px solid var(--line);border-radius:var(--r-panel);padding:1.75rem;width:100%;max-width:23rem;justify-self:center}', '.wl-card .hd{display:flex;align-items:center;justify-content:space-between;gap:1rem}.wl-card .hd .logo{width:2.3rem;height:auto;top:0}.wl-card .st{color:var(--muted);font-size:.85rem}', '.wl-card .wl-unnamed{color:var(--faint)}', `.wl-card .nm{display:block;font-family:${DISPLAY};font-size:2.3rem;line-height:1.3;margin:1rem 0 .9rem;overflow-wrap:anywhere}`, '.wl-card input.nm{display:block;width:100%;height:auto;line-height:1.5;padding:.1em 0 .12em;overflow:visible;color:var(--fg);border:0;border-bottom:1.5px solid var(--fg);border-radius:0;background:none}', '.wl-card input.nm:focus{outline:none;border-bottom-style:dashed}', '.wl-card input.nm::placeholder{color:var(--faint);text-transform:none}', '.wl-handle{display:flex;align-items:baseline;flex-wrap:wrap;gap:0;margin:-.35rem 0 .2rem;font-size:.95rem;color:var(--muted)}', '.wl-card .wl-handle input{font:inherit;color:var(--fg);background:none;border:0;border-bottom:1px dashed transparent;border-radius:0;height:auto;line-height:1.5;padding:0;margin:0;min-width:4ch;max-width:100%;flex:none}', '.wl-card .wl-handle input:hover{border-bottom-color:var(--line)}.wl-card .wl-handle input:focus{outline:none;border-bottom-color:var(--fg)}.wl-card .wl-handle input::placeholder{color:var(--faint)}', '.wl-handle-status{min-height:1.2rem;margin:0 0 .6rem;font-size:.82rem;color:var(--faint)}.wl-handle-status[data-state=ok]{color:var(--ink2)}.wl-handle-status[data-state=bad]{color:var(--red)}', '.wl-suggest{display:flex;flex-wrap:wrap;gap:.5rem;margin-top:1.5rem}', `.wl-suggest .wl-chip{height:2.3rem;padding:0 1rem;font-family:${DISPLAY}}`, '.wl-card dl{margin:0;display:grid}.wl-card dl div{display:flex;justify-content:space-between;align-items:baseline;gap:1rem;border-top:1px solid var(--hair);padding:.65rem 0 0;margin-top:.65rem}', '.wl-card dt{color:var(--muted);font-size:.92rem;flex:none}.wl-card dd{margin:0;text-align:right;font-size:.92rem;min-width:0;overflow-wrap:anywhere}.wl-card dd.none{color:var(--faint)}', // Step two: name and start. '.wl-acts{display:flex;flex-wrap:wrap;align-items:center;gap:1rem 1.4rem;margin-top:2rem}', '.wl-acts button{background:var(--fg);color:var(--bg);border-color:var(--fg);padding:.6rem 1.5rem;font-size:1rem}.wl-acts button:hover{background:var(--fg);color:var(--bg);opacity:.86}', '.wl-fine{color:var(--faint);font-size:.88rem;margin:1.5rem 0 0}', // While the agent is made (a few seconds): the snail, winding, and its name. '.wl-wake{align-items:center;text-align:center}.wl-wake h1{font-size:clamp(1.8rem,4vw,2.4rem);margin-top:1.75rem}', '.wl-snail{width:5.5rem;height:auto;color:var(--fg)}.wl-snail path{vector-effect:non-scaling-stroke;stroke-width:2.5px}', '.wl-snail .spiral{stroke-dasharray:100;animation:wind 1.6s ease-in-out infinite alternate}', '@media (prefers-reduced-motion:reduce){.wl-snail .spiral{animation:none}}', ].join('') /** * What an owner with no agents sees at `/`: a full-screen flow to their first agent, with no sidebar. * Step one picks a first job; step two names the agent (one is ready) on a card beside the form and * starts it. Making the agent sends the job as its first message and opens the chat. */ export function welcomePage(v: { step: 'job' | 'meet' /** The name they typed (or tapped), if any. */ name: string /** The handle label, from the name unless they edited it. */ handle?: string /** Names to tap: short words free on this service. */ suggestions?: string[] /** The handle domain, such as `.languid.ai`. */ domain?: string job?: FirstJob /** What they typed under "Something else". */ task?: string /** The model a new agent gets, by name, and the credit that pays for it. */ model?: string credit?: number error?: string /** A status line, like the last agent having just been deleted. */ notice?: string }): Page { const meet = v.step === 'meet' && !!v.job && (v.job !== 'other' || !!v.task?.trim()) const dots = (on: number) => ` 1 ? ' class="on"' : ''}>` const top = `
${LOGO}Languid${dots(meet ? 2 : 1)}` + `
` const error = (v.notice ? `

${esc(v.notice)}

` : '') + (v.error ? `` : '') const jobLabel = !v.job ? '' : v.job === 'other' ? (v.task ?? '').trim() : FIRST_JOBS[v.job].title const shortJob = jobLabel.length > 48 ? `${jobLabel.slice(0, 47)}…` : jobLabel const display = v.name.trim() const card = (name: string) => `
${LOGO}${meet ? 'Ready' : 'Waiting for a job'}
${name}
` + `
First job
${meet ? esc(shortJob) : 'Pick one'}
` + (v.model ? `
Model
${esc(v.model)}
` : '') + (v.credit !== undefined ? `
Paid from
$${v.credit.toFixed(2)} credit
` : '') + `
Remembers
What matters after each chat
` let main: string if (!meet) { const chips = (Object.keys(FIRST_JOBS) as (keyof typeof FIRST_JOBS)[]) .map((k) => `${WELCOME_ICON(FIRST_JOBS[k].icon)}${esc(FIRST_JOBS[k].title)}`) .join('') main = `

Your first agent

Pick a first job.

` + `

Your agent starts right away and learns the rest as you talk.

${error}` + `
${chips}
${WELCOME_PLUS}` + `
` + card(`Your agent`) + `
` } else { const back = `/?job=${encodeURIComponent(v.job!)}${v.job === 'other' ? `&task=${encodeURIComponent(v.task ?? '')}` : ''}` const chips = (v.suggestions ?? []) .map((n) => `${esc(n)}`) .join('') const handle = v.handle ?? handleFromName(v.name) main = `
` + (v.job === 'other' ? `` : '') + `
${WELCOME_BACK}${esc(shortJob)}

Name your agent.

` + `

Pick a name or type your own on the card. Your agent’s handle comes from the name, and you can change it.

` + (chips ? `
${chips}
` : '') + error + `
` + `

Pick another model or connect a computer later, in settings.

` + card( `` + `

${esc(v.domain ?? '')}

` + `

`, ) + `
` } // The name step runs /welcome.js (suggestions, the handle preview and its check); step one runs nothing. const script = meet ? `` : '' return { status: v.error ? 400 : 200, headers: headers("'self'", meet), body: welcomeHead() + top + main + script + '' } } const welcomeHead = () => `` + `Welcome · Languid` + `${PRELOAD}` /** * The welcome page while the first agent is made: the service sends this at once, makes the agent, * then ends the page with `wakingEnd`, which moves the browser on. No script needed. */ export const wakingStart = (name: string) => welcomeHead() + `
${LOGO}Languid
` + `
` + `

${esc(name.charAt(0).toUpperCase() + name.slice(1))} is waking up

` /** The waking page's headers, sent before the page itself. */ export const wakingHeaders = () => headers() /** Where to go once the agent is made (its chat) or wasn't (back to the form, with the reason). */ export const wakingEnd = (location: string) => `

Continue

` /** About you: what they told Languid they use it for, and a way to change it. */ export function aboutYouPage(v: { card: string; current?: OwnerProfile; notice?: string; sharing?: boolean; origin?: string }): Page { const saved = v.current ? `

You said: ${esc(ownerProfileSummary(v.current))}. Agents you make from now on start out knowing this; agents you already have don't.

` : `

You haven't said yet.

` // Share usage with Languid (src/visits.ts, src/client-errors.ts): off until they turn it on. const sharing = `` const style = '' return page(200, 'About you · Languid', `${style}

About you

${v.notice ? `

${esc(v.notice)}

` : ''}${saved}${v.card}${sharing}`, { app: true, ...(v.origin ? { formAction: toPds(v.origin) } : {}), }) } /** The handle form for a terminal's sign-in, posting to `/oauth/login/handle`. */ function terminalHandleForm(flow: string, handle = '', label = 'Continue') { return ( `` ) } /** `languid login` without a handle, opened in a browser that isn't signed in here: which account? */ export function terminalHandlePage( v: { flow: string; origin: string; error?: string; handle?: string; status?: number }, headers: Record = {}, ): Page { return page( v.status ?? 200, 'Languid', `

Sign in your terminal

` + (v.error ? `` : '') + `

Sign in at your PDS, then confirm the code your terminal shows.

` + terminalHandleForm(v.flow, v.handle), { headers, formAction: toPds(v.origin) }, ) } /** * Approve a terminal's sign-in: who it signs in as and the code it should be showing. Reached from a * browser already signed in here, it also offers another account. */ export function terminalConfirmPage( v: { flow: string; handle: string; did: string; code: string; origin: string; otherAccount: boolean }, headers: Record = {}, ): Page { return page( 200, 'Languid', `

Sign in your terminal

` + `

A terminal is asking to use Languid as ${esc(v.handle)}.
${esc(v.did)}

` + `

It should be showing this code:

${esc(v.code)}

` + `

Approve only if you started this from your own terminal and the code matches.

` + `
` + `
` + (v.otherAccount ? `
Use another account${terminalHandleForm(v.flow, '', 'Sign in')}
` : ''), { headers, formAction: v.otherAccount ? toPds(v.origin) : undefined }, ) } /** The sign-up form an owner invite links to. POST /signup redirects straight to the PDS to sign in, so form-action must allow it. */ export function signupPage(code: string, domain: string, origin: string, attempt: { error?: string; handle?: string; status?: number; test?: boolean; password?: string } = {}): Page { return page( attempt.status ?? 200, 'Languid', `

You're invited

` + `

Pick a handle and a password. You'll enter the password once more to sign in.

` + (attempt.test ? `

Test account. Copy the password for the sign-in step. Delete test accounts from Admin.

` : '') + `
Sign up
` + (attempt.error ? `` : '') + `` + `

3–20 characters: a–z, 0–9 and inner hyphens. Password at least 10 characters; there's no email reset yet, so save it.

` + `
`, { formAction: toPds(origin), path: '/signup' }, ) } /** After sign-up: the new account, and the way in. */ export function signupDonePage(handle: string, origin: string): Page { return page( 201, 'Languid', `

Welcome

` + `

Your account is ${esc(handle)}. Sign in with your new password.

` + `
Sign in
` + `
` + `

Then set up a terminal.

`, { formAction: toPds(origin), path: '/signup' }, ) } /** An invite link that was used, expired, or never existed. */ export function signupGonePage(): Page { return page( 410, 'Languid', `

Invite used up

This link was used, expired or never existed. Ask for a new one.

Home

`, { path: '/signup' }, ) } /** Where the source is published, linked from the landing page (the AGPL asks a network service to offer it). */ export const SOURCE_URL: string | undefined = 'https://tangled.org/cameron.stream/languid' /** * Who hands out invites, by Bluesky handle: the landing page and the not-invited page point there. * A service run by someone else changes it, or sets it to undefined to leave the line out. */ export const INVITES_FROM: string | undefined = 'cameron.stream' const bluesky = (handle: string) => `${esc(handle)}` /** Installers fetch the published, checksummed commit archive, never a moving branch. */ const SOURCE_TARBALL = publishedClientRelease()?.tarball /** How to install the CLI: this service's own install script, when there's code to fetch. */ export const installCommand = (origin: string): string | undefined => (SOURCE_TARBALL ? `curl -fsSL ${origin}/install | sh` : undefined) /** * The install script (scripts/install.sh), filled in with this service and where the code is. * Undefined when there's no code to point it at, or the values wouldn't be safe in a shell string. */ export function installScript(origin: string, kind: 'sh' | 'ps1' = 'sh'): string | undefined { const release = publishedClientRelease() if (!release) return undefined const template = (installTemplates[kind] ??= fs.readFileSync(new URL(`../scripts/install.${kind}`, import.meta.url), 'utf8')) try { return renderClientInstaller(template, origin, release) } catch { return undefined } } const installTemplates: { sh?: string; ps1?: string } = {} /** How to install the CLI on Windows, in PowerShell: scripts/install.ps1. */ export const installCommandWindows = (origin: string): string | undefined => (SOURCE_TARBALL ? `irm ${origin}/install.ps1 | iex` : undefined) /** The docs pages' script: copy buttons on the commands, and the panel marking the section in view. */ export const DOCS_JS = String.raw`(() => { 'use strict' for (const button of document.querySelectorAll('.cmd .copy')) { button.hidden = false let timer button.addEventListener('click', async () => { const code = button.closest('.cmd').querySelector('code') try { await navigator.clipboard.writeText(code.textContent) button.classList.add('done') } catch { const range = document.createRange() range.selectNodeContents(code) const sel = getSelection() sel.removeAllRanges() sel.addRange(range) } clearTimeout(timer) timer = setTimeout(() => { button.classList.remove('done') }, 1600) }) } // "A turn, step by step": the steps under the map become a stepper, and each lights up its parts of the map. const map = document.querySelector('.turn-map') if (map) { const parts = JSON.parse(map.dataset.steps || '{}') const looping = JSON.parse(map.dataset.loop || '[]') const steps = [] let el = map.nextElementSibling while (el && el.tagName !== 'H2' && !el.classList.contains('note')) { const after = el.nextElementSibling if (el.tagName === 'H3') { const step = document.createElement('div') step.className = 'turn-step' step.dataset.id = el.id el.before(step) steps.push(step) } if (steps.length) steps[steps.length - 1].appendChild(el) el = after } if (steps.length) { const box = document.createElement('div') box.className = 'turn-stepper' steps[0].before(box) for (const s of steps) box.appendChild(s) const controls = document.createElement('div') controls.className = 'turn-controls' const count = document.createElement('span') count.className = 'count' const dots = document.createElement('div') dots.className = 'turn-dots' dots.setAttribute('role', 'group') dots.setAttribute('aria-label', 'Steps') const btns = document.createElement('div') btns.className = 'turn-btns' const back = document.createElement('button') back.type = 'button' back.textContent = 'Back' const next = document.createElement('button') next.type = 'button' next.className = 'next' btns.append(back, next) controls.append(count, dots, btns) box.appendChild(controls) let at = 0 const show = (n) => { at = Math.max(0, Math.min(steps.length - 1, n)) const id = steps[at].dataset.id const p = parts[id] || { nodes: [], edges: [] } steps.forEach((s, k) => (s.hidden = k !== at)) map.classList.add('stepping') for (const g of map.querySelectorAll('[data-node]')) g.classList.toggle('on', p.nodes.includes(g.dataset.node)) for (const e of map.querySelectorAll('[data-edge]')) e.classList.toggle('on', p.edges.includes(e.dataset.edge)) dots.querySelectorAll('button').forEach((d, k) => (k === at ? d.setAttribute('aria-current', 'step') : d.removeAttribute('aria-current'))) count.textContent = 'Step ' + (at + 1) + ' of ' + steps.length back.disabled = at === 0 next.textContent = at === steps.length - 1 ? 'Start over' : 'Next' } steps.forEach((s, k) => { const d = document.createElement('button') d.type = 'button' d.textContent = String(k + 1) d.className = looping.includes(s.dataset.id) ? 'dot loop' : 'dot' d.setAttribute('aria-label', 'Step ' + (k + 1) + ': ' + s.querySelector('h3').textContent) d.addEventListener('click', () => show(k)) dots.appendChild(d) }) back.addEventListener('click', () => show(at - 1)) next.addEventListener('click', () => show(at === steps.length - 1 ? 0 : at + 1)) box.addEventListener('keydown', (e) => { if (e.key === 'ArrowRight') show(at + 1) else if (e.key === 'ArrowLeft') show(at - 1) }) const linked = steps.findIndex((s) => '#' + s.dataset.id === location.hash) show(linked < 0 ? 0 : linked) } } const links = [...document.querySelectorAll('.docs-panel a.sub')] const sections = links.map((a) => document.getElementById(a.hash.slice(1))).filter(Boolean) if (!sections.length) return const mark = () => { let current = sections[0] for (const s of sections) if (s.getBoundingClientRect().top < innerHeight * 0.3) current = s if (innerHeight + scrollY >= document.documentElement.scrollHeight - 2) current = sections[sections.length - 1] for (const a of links) a.classList.toggle('on', a.hash === '#' + current.id) } addEventListener('scroll', mark, { passive: true }) mark() })() ` export const DOCS_JS_HREF = `/docs.js?v=${crypto.createHash('sha256').update(DOCS_JS).digest('hex').slice(0, 10)}` /** A web sign-in by someone who isn't on this service's invite list. */ export function notInvitedPage(who: { handle: string; did: string }, extra: Record = {}): Page { return page( 403, 'Languid', `

Not invited

` + `

${esc(who.handle)} isn't on this service's invite list.

` + (INVITES_FROM ? `

Ask ${bluesky(INVITES_FROM)} on Bluesky, with this DID:

` : `

Send this DID to whoever runs the service:

`) + `
${esc(who.did)}
` + `

Back

`, { headers: extra }, ) } /** A browser asked for a page that doesn't exist. */ export function notFoundPage(path: string): Page { return page( 404, 'Languid', `
404
${esc(ART_404)}
` + `

Nothing at ${esc(path)}. Go home.

`, { path }, ) } // ---- chat ------------------------------------------------------------------ /** One tool call in a chat transcript, with its result once there is one. */ export interface ChatCall { id: string tool: string arguments: string computer?: string output?: string isError?: boolean } /** A thread as the chat page shows it: user turns, and assistant turns with their tool calls. */ export type ChatItem = | { role: 'user' text: string at: string from?: string /** URLs of the images sent with it. */ images?: string[] /** A task's result, woken into the thread that started it (docs/agents.md). */ task?: { thread: string; title: string; outcome: 'finished' | 'stopped' | 'failed'; reply: string; why?: string } } | { role: 'assistant'; text: string; at: string; error?: string; calls: ChatCall[]; rkey?: string } export interface ChatView { agent: string /** What it's called: its display name, or (unset) its name. */ displayName?: string handle: string model: string /** Models the service can call, for the picker. */ models: { provider: string; id: string; name: string; cost?: { input: number; output: number }; connection?: Connection; /** It takes images. */ image?: boolean; /** Reasoning levels it supports, for models that reason. */ levels?: string[] }[] /** How hard the shown model reasons in this thread (pi's thinking level). */ reasoning?: string /** This owner's favorites, shared across agents and browsers. Values are provider/model IDs. */ favoriteModels?: string[] /** The models Languid picks (LANGUID_HOUSE_MODELS), first in the picker. */ houseModels?: string[] /** The service can transcribe speech, so the composer shows its mic. */ voice?: boolean /** Auto approvals (src/auto-approve.ts): on, or off because the owner is out of credit. */ autoApproval?: 'on' | 'no_credit' /** Models this owner picked lately, newest first. Values are provider/model IDs. */ recentModels?: string[] /** Tools that run on a computer without asking: its ai.languid.computer.permissions records. */ alwaysAllowed?: { computer: string; tool: string }[] computers: { name: string; online: boolean }[] threads: { rkey: string; title: string; name: string; preview: string; updatedAt: string }[] /** The thread shown, or undefined for a new one. */ thread?: string items: ChatItem[] /** Items left out from the start of a long thread. */ hidden: number /** A run on this thread that is still going: the page picks it up from event `since`. */ /** The thread's last run was cut off by a restart, with calls that never finished: chat.js can pick it up. 'pending': the service is about to resume it on its own. */ interrupted?: boolean | 'pending' /** Tasks started in this thread whose results haven't come back yet: the page waits for them. */ tasks?: number run?: { id: string; since: number; approvals: { id: string; tool: string; arguments: string; computer?: string; always?: { command?: string } }[] } /** Another run of this agent's, on another thread. */ budget?: { budgetUsd: number; spentUsd: number } } /** pi's thinking levels, as the model picker names them. */ const REASONING_LABEL: Record = { off: 'Off', low: 'Low', medium: 'Medium', high: 'High', xhigh: 'X-high', max: 'Max' } /** Tool output shown in a transcript is cut to this many characters. */ const OUTPUT_SHOWN = 4000 /** Longest intention a call's label shows. */ const INTENTION_SHOWN = 160 const parseArgs = (args: string): Record | undefined => { try { const a = JSON.parse(args) return a && typeof a === 'object' && !Array.isArray(a) ? a : undefined } catch { return undefined } } /** * The call_intention a call states (see tools.ts), on one line and cut to length; undefined for * calls without one, such as those recorded before tools had it. It's the agent's own words: shown * as a label, never in place of what the call does. */ export function callIntention(args: string): string | undefined { const v = parseArgs(args)?.call_intention const t = typeof v === 'string' ? v.replace(/\s+/g, ' ').trim() : '' if (!t) return undefined return t.length > INTENTION_SHOWN ? `${t.slice(0, INTENTION_SHOWN - 1)}…` : t } /** A tool call's arguments in one line: the command for bash, the path for file tools, else the JSON. */ export function callSummary(tool: string, args: string): string { let shown = args const a = parseArgs(args) if (a) { const { call_intention: _i, ...rest } = a if (tool === 'bash' && typeof a.command === 'string') shown = a.command else if (tool === 'send_message' && typeof a.text === 'string') shown = a.text else if (tool === 'feedback' && typeof a.text === 'string') shown = a.text else if (tool === 'feedback_share') shown = 'Share error reports and feedback with the Languid maintainer' else if (typeof a.path === 'string') shown = a.path else if (typeof a.label === 'string') shown = a.label else shown = JSON.stringify(rest) } shown = shown.replace(/\s+/g, ' ').trim() return shown.length > 120 ? `${shown.slice(0, 119)}…` : shown } /** What a call does, in full: the whole command for bash, else its arguments but the intention, indented. */ export function callDetail(tool: string, args: string): string { const a = parseArgs(args) if (!a) return args if (tool === 'bash' && typeof a.command === 'string') return a.command if (tool === 'send_message' && typeof a.text === 'string') return a.text if (tool === 'feedback' && typeof a.text === 'string') return a.text if (tool === 'feedback_share') return 'Lets the Languid maintainer read this agent\'s error reports and feedback, never its memory or messages. Stop any time in its settings.' const { call_intention: _i, ...rest } = a return JSON.stringify(rest, null, 2) } const clip = (s: string) => (s.length > OUTPUT_SHOWN ? `${s.slice(0, OUTPUT_SHOWN)}\n… (${s.length - OUTPUT_SHOWN} more characters)` : s) // ---- diffs ----------------------------------------------------------------- /** * One line of a diff: unchanged (' '), added ('+') or removed ('-'), as spans of text with the * changed words marked; or a fold ('…') standing for that many unchanged lines. */ export type DiffLine = [' ' | '+' | '-', [text: string, changed: boolean][]] | ['…', number] /** What a call would do to a file, as a diff: one hunk per replacement. */ export interface FileChange { path: string hunks: DiffLine[][] added: number removed: number } /** Unchanged lines kept next to a change; longer runs fold. */ const DIFF_CONTEXT = 3 /** Lines longer than this aren't compared word by word. */ const WORD_DIFF_MAX = 2000 /** A removed line and the added line in its place, with the changed words marked, if enough stayed the same to be worth it. */ function wordPair(del: string, add: string): [DiffLine, DiffLine] { const plain: [DiffLine, DiffLine] = [['-', [[del, false]]], ['+', [[add, false]]]] if (del.length > WORD_DIFF_MAX || add.length > WORD_DIFF_MAX) return plain const parts = diffWordsWithSpace(del, add) const same = parts.reduce((n, p) => (p.added || p.removed ? n : n + p.value.length), 0) if (same < 0.4 * Math.max(del.length, add.length)) return plain return [ ['-', parts.filter((p) => !p.added).map((p) => [p.value, !!p.removed])], ['+', parts.filter((p) => !p.removed).map((p) => [p.value, !!p.added])], ] } /** Long runs of unchanged lines fold, keeping DIFF_CONTEXT lines next to each change. */ function fold(lines: DiffLine[]): DiffLine[] { const out: DiffLine[] = [] for (let i = 0; i < lines.length; ) { if (lines[i][0] !== ' ') { out.push(lines[i++]) continue } let j = i while (j < lines.length && lines[j][0] === ' ') j++ const head = i > 0 ? DIFF_CONTEXT : 0 const tail = j < lines.length ? DIFF_CONTEXT : 0 const hidden = j - i - head - tail if (hidden >= 2) out.push(...lines.slice(i, i + head), ['…', hidden], ...lines.slice(j - tail, j)) else out.push(...lines.slice(i, j)) i = j } return out } /** The lines of a text, without a split-off empty last line. */ const linesOf = (s: string) => s.replace(/\n$/, '').split('\n') /** A line diff of two texts, removed lines before added ones, changed words marked where lines pair up. */ export function diffText(before: string, after: string): DiffLine[] { // Both end in a newline, so a last line without one still compares equal to itself. const parts = diffLines(`${before}\n`, `${after}\n`, { timeout: 200 }) ?? [ { value: `${before}\n`, removed: true, added: false, count: 0 }, { value: `${after}\n`, added: true, removed: false, count: 0 }, ] const out: DiffLine[] = [] let dels: string[] = [] let adds: string[] = [] const flush = () => { const pairs = dels.map((d, i) => (i < adds.length ? wordPair(d, adds[i]) : undefined)) for (let i = 0; i < dels.length; i++) out.push(pairs[i]?.[0] ?? ['-', [[dels[i], false]]]) for (let i = 0; i < adds.length; i++) out.push(pairs[i]?.[1] ?? ['+', [[adds[i], false]]]) dels = [] adds = [] } for (const p of parts) { const lines = linesOf(p.value) if (p.removed) dels.push(...lines) else if (p.added) adds.push(...lines) else { flush() for (const l of lines) out.push([' ', [[l, false]]]) } } flush() return fold(out) } /** An edit call's replacements, read as leniently as pi's edit tool reads them (a JSON string, a lone object, or legacy oldText/newText). */ function replacements(a: Record): { oldText: string; newText: string }[] { let e: unknown = a.edits if (typeof e === 'string') { try { e = JSON.parse(e) } catch { e = undefined } } const list = (Array.isArray(e) ? e : e && typeof e === 'object' ? [e] : []).filter( (x): x is { oldText: string; newText: string } => !!x && typeof x.oldText === 'string' && typeof x.newText === 'string', ) if (typeof a.oldText === 'string' && typeof a.newText === 'string') list.push({ oldText: a.oldText, newText: a.newText }) return list } /** * What a file-changing call would do, as a diff: edit (and block_replace) as each replacement's * before and after, write as its whole content added. Undefined for other calls, and for * arguments that don't parse. */ export function callChange(tool: string, args: string): FileChange | undefined { const a = parseArgs(args) if (!a) return undefined let path: unknown let hunks: DiffLine[][] if (tool === 'write' && typeof a.content === 'string') { path = a.path hunks = [linesOf(a.content).map((l): DiffLine => ['+', [[l, false]]])] } else if (tool === 'edit' || tool === 'block_replace') { path = tool === 'edit' ? a.path : typeof a.label === 'string' ? `block ${a.label}` : undefined hunks = replacements(a).map((r) => diffText(r.oldText, r.newText)) } else return undefined if (typeof path !== 'string' || !hunks.length) return undefined const count = (k: string) => hunks.reduce((n, h) => n + h.filter((l) => l[0] === k).length, 0) return { path, hunks, added: count('+'), removed: count('-') } } const DIFF_KIND = { ' ': 'ctx', '+': 'add', '-': 'del' } as const /** A change as markup: the file and its counts, then each hunk's lines. chat.js builds the same in changeNode. */ export function changeHtml(c: FileChange): string { const cut = c.path.lastIndexOf('/') + 1 const line = (l: DiffLine) => l[0] === '…' ? `
${l[1]} unchanged lines
` : `
${l[0]}${l[1].map(([t, ch]) => (ch ? `${esc(t)}` : esc(t))).join('')}
` return ( `
${esc(c.path.slice(0, cut))}${esc(c.path.slice(cut))}` + `+${c.added} −${c.removed}
` + c.hunks.map((h) => `
${h.map(line).join('')}
`).join('') + `
` ) } /** * A call's one-line label: its intention, then the tool and computer; a call without an intention * shows the tool and its arguments instead. chat.js builds the same markup. */ /** "List the files" as it reads after "scout would like to": a leading capital lowered, unless it starts an acronym. */ export const lowerFirst = (s: string) => (/^[A-Z][a-z]/.test(s) ? s.charAt(0).toLowerCase() + s.slice(1) : s) /** * A call's one-line label: its intention, then the tool and computer; a call without an intention * shows its arguments instead. A dot before it shows its state. chat.js builds the same markup. */ function callLabel(tool: string, args: string, computer?: string, state = 'running'): string { const intention = callIntention(args) const where = computer ? ` · ${esc(computer)}` : '' return ( `` + (intention ? `${esc(intention)}` : `${esc(callSummary(tool, args))}`) + ` ${esc(tool)}${where}` ) } /** What a call does: a diff for calls that change a file, else its detail. */ export function argsHtml(tool: string, args: string, cls?: string): string { const change = callChange(tool, args) return change ? changeHtml(change) : `${esc(callDetail(tool, args))}` } const callState = (c: ChatCall) => (c.output === undefined ? '' : c.isError ? ' err' : ' ok') const callStateLabel = (c: ChatCall) => (c.output === undefined ? 'no result' : c.isError ? 'failed' : 'done') /** A `task` call's thread, from its result (docs/agents.md; "Helper thread" before v210). chat.js finds it the same way. */ export const taskThread = (tool: string, output?: string) => (tool === 'task' ? /(?:^|\n)(?:Task|Helper) thread: ([a-z0-9]+)\s*$/.exec(output ?? '')?.[1] : undefined) function callHtml(c: ChatCall): string { const task = taskThread(c.tool, c.output) return ( `
${callLabel(c.tool, c.arguments, c.computer, callStateLabel(c))}` + `
${argsHtml(c.tool, c.arguments, 'args')}
${c.output === undefined ? '' : esc(clip(c.output))}
` + (task ? `` : '') + `
` ) } /** * Calls made one after another, with nothing said between them: one call stands alone; more fold * into one line showing the latest, which opens to list them all. chat.js groups the same way. */ const failed = (calls: ChatCall[]) => { const n = calls.filter((c) => c.isError).length return n ? ` · ${n} failed` : '' } function callsHtml(calls: ChatCall[]): string { if (calls.length === 1) return callHtml(calls[0]) const last = calls[calls.length - 1] return ( `
${callLabel(last.tool, last.arguments, last.computer, callStateLabel(last))}` + `${calls.length} calls${failed(calls)}
${calls.map(callHtml).join('')}
` ) } /** The question about one call: the agent's intention in its own words, where it runs, and the exact command. chat.js renders the same markup. */ /** "Always allow": this call, and from now on the rule it offers (a bash command by its leading words, or the tool) on that computer. */ const alwaysButton = (agent: string, tool: string, computer: string, command?: string) => `` /** "Allow all": this call, every other waiting, and the rest of the run without asking; the composer's Permissions turns to Allow all. Never for sharing. */ const allowAllButton = (tool: string) => tool === 'feedback_share' ? '' : `` function approvalHtml(run: string, agent: string, a: { id: string; tool: string; arguments: string; computer?: string; always?: { command?: string } }): string { const intention = callIntention(a.arguments) return ( `

${ICON_NEEDS_YOU}Needs you

` + `

${esc(agent)} would like to ${intention ? esc(lowerFirst(intention)) : `run ${esc(a.tool)}`}

` + `

${esc(a.tool)}${a.computer ? ` on ${esc(a.computer)}` : ''}

` + argsHtml(a.tool, a.arguments) + `
` + (a.computer && a.always ? alwaysButton(agent, a.tool, a.computer, a.always.command) : '') + allowAllButton(a.tool) + `
` ) } /** * A thread a restart cut off. The service resumes such runs on its own after a restart ('pending'), * and chat.js asks for it straight away (POST resume) so the page follows along; otherwise a quiet * Continue does it. chat.js makes the same. */ const resumeHtml = (agent: string, pending: boolean) => pending ? `

Languid restarted. ${esc(agent)} is picking up from there.

` : `

${esc(agent)} stopped when Languid restarted.

` const THUMB_UP = 'M7 11v9H4v-9zM7 11l4-8a2 2 0 0 1 3 2l-1 5h6a2 2 0 0 1 2 2.3l-1.3 6A2 2 0 0 1 17.7 20H7' const THUMB_DOWN = 'M7 13V4H4v9zM7 13l4 8a2 2 0 0 0 3-2l-1-5h6a2 2 0 0 0 2-2.3l-1.3-6A2 2 0 0 0 17.7 4H7' /** 👍/👎 under a reply: either one saves this moment as an eval case (docs/evals.md). Then copy, for the reply's text. chat.js makes the same for live replies. */ export function feedbackHtml(rkey: string): string { return ( `` ) } /** * A task's result as it woke this thread: one line saying how it ended, with its thread, opening to * its reply. The agent answers it in its next message. chat.js shows nothing of its own: the page * reloads when a result comes in. */ export function taskResultHtml(t: { thread: string; title: string; outcome: 'finished' | 'stopped' | 'failed'; reply: string; why?: string }): string { const state = t.outcome === 'finished' ? 'ok' : 'err' const said = t.outcome === 'finished' ? 'Task finished' : t.outcome === 'stopped' ? 'Task stopped' : 'Task failed' const label = t.outcome === 'finished' ? 'done' : 'failed' return ( `
` + `${said}: ${esc(t.title)} Open thread` + `
${t.why ? `

${esc(t.why)}

` : ''}${t.reply ? `
${esc(t.reply)}
` : '

No reply.

'}
` ) } /** A transcript: its turns in order, with each run of calls in a row, across turns, folded together. */ function itemsHtml(items: ChatItem[]): string { let html = '' let run: ChatCall[] = [] const flush = () => { if (run.length) html += callsHtml(run) run = [] } for (const item of items) { if (item.role === 'user' && item.task) { flush() html += taskResultHtml(item.task) continue } if (item.role === 'user') { flush() if (item.images?.length) html += `
${item.images.map((src) => `Image sent with the message`).join('')}
` if (item.text) html += `
${esc(item.from ?? 'You')}${esc(item.text)}
` continue } if (item.text || item.error) flush() if (item.text) html += `
${esc(item.text)}
` + (item.rkey ? feedbackHtml(item.rkey) : '') if (item.error) html += `

${esc(item.error)}

` run.push(...item.calls) } flush() return html } /** Small stroked icons for the composer, drawn in the text color. */ const icon = ICON_NAV const ICON_SEND = icon('') const ICON_MIC = icon('') const ICON_STOP = icon('') const ICON_MODEL = icon('') const ICON_SHIELD = icon('') const ICON_COMPUTER = icon('') const ICON_CHECK = icon('') const ICON_RENAME = icon('') const ICON_PLUS = icon('') const ICON_IMAGE = icon('') const ICON_CHEVRON = icon('') /** Memory: a notebook. Records: a stack of them. Evals: a flask. Schedules: a clock. */ const ICON_MEMORY = icon('') const ICON_RECORDS = icon('') const ICON_EVALS = icon('') const ICON_SCHEDULES = icon('') const ICON_ACTIVITY = icon('') const ICON_UP = icon(``) const ICON_DOWN = icon(``) /** Threads the left panel lists; older ones are counted, not shown. */ const PANEL_THREADS = 100 /** How long ago, as the thread panel shows it: "now", "5m", "3h", "2d", then the date. */ export function ago(iso: string, now = Date.now()): string { const t = Date.parse(iso) if (Number.isNaN(t)) return '' const s = Math.max(0, (now - t) / 1000) if (s < 60) return 'now' if (s < 3600) return `${Math.floor(s / 60)}m` if (s < 86400) return `${Math.floor(s / 3600)}h` if (s < 7 * 86400) return `${Math.floor(s / 86400)}d` const d = new Date(t) const sameYear = d.getUTCFullYear() === new Date(now).getUTCFullYear() return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', ...(sameYear ? {} : { year: 'numeric' }), timeZone: 'UTC' }) } /** * The current agent's part of the sidebar: its pages, rows like Home's, then New thread and its latest threads, which scroll on their * own. thread is the one shown, on the chat page; undefined there means a new one, and null means no thread is open (another page). */ export function agentNest(agent: string, threads: { rkey: string; name: string; updatedAt: string }[], thread?: string | null, now = Date.now()): string { const base = agentBase(agent) const threadHref = (rkey: string) => `${base}?thread=${encodeURIComponent(rkey)}` const on = (rkey: string) => (rkey === thread ? ' class="on"' : '') const renameButton = (t: { rkey: string; name: string }) => `` // The agent's pages, named, two to a row in short rows, so the threads keep the height. const sub = (href: string, glyph: string, label: string) => `${glyph}${label}` const threadItem = (t: { rkey: string; name: string; updatedAt: string }) => `` + `${esc(t.name)}${renameButton(t)}` const fresh = thread === undefined return ( `` + `${ICON_PLUS}New thread` + `
    ${threads.slice(0, PANEL_THREADS).map(threadItem).join('')}` + (threads.length > PANEL_THREADS ? `
  • ${threads.length - PANEL_THREADS} older threads aren't listed.
  • ` : '') + `
` ) } /** The chat page: an agent's threads, the one being shown, and a box to talk in. */ export function chatPage(v: ChatView): Page { const shown = v.displayName || v.agent const base = agentBase(v.agent) const computers = v.computers.length ? v.computers.map((m) => `${esc(m.name)}${m.online ? '' : ' (offline)'}`).join(', ') : 'None yet: languid computer setup lets it use a computer' const threadHref = (rkey: string) => `${base}?thread=${encodeURIComponent(rkey)}` const on = (rkey: string) => (rkey === v.thread ? ' class="on"' : '') const renameButton = (t: { rkey: string; name: string }) => `` const threads = `` const now = Date.now() const panel = `` + NAV_NEST[0] + agentNest(v.agent, v.threads, v.thread, now) + NAV_NEST[1] const threadName = v.threads.find((t) => t.rkey === v.thread)?.name ?? (v.thread ? 'Thread' : 'New thread') const budget = v.budget ? ` · $${v.budget.spentUsd.toFixed(2)} of $${v.budget.budgetUsd.toFixed(2)} spent` : '' // A thread with nothing in it yet opens on a greeting that says who it is and what it can reach, // in place of the agent heading, so the name and the memory line aren't said twice. const fresh = !v.items.length && !v.hidden && !v.run // A new thread is just who you're talking to: the box and its pills say the rest. const welcome = `

${esc(shown)}

${esc(v.handle)}

` const log = (v.hidden ? `

${v.hidden} earlier messages aren't shown.

` : '') + (fresh ? welcome : itemsHtml(v.items)) + (v.run ? v.run.approvals.map((a) => approvalHtml(v.run!.id, shown, a)).join('') : '') + (v.interrupted ? resumeHtml(shown, v.interrupted === 'pending') : '') // The agent's model. The menu opens short: Languid's picks, recent choices and favorites, then the // first few models of each account the owner connected. Everything else (all of Languid's catalog) // is a search away, or a "Show all" under its group. Choosing one saves the agent's config (chat.js posts it). // The current model is listed even if the service can no longer call it, so the pill shows the truth. const current = v.model type Listed = ChatView['models'][number] const options: Listed[] = v.models.some((m) => `${m.provider}/${m.id}` === current) ? v.models : [{ provider: current.split('/')[0], id: current.slice(current.indexOf('/') + 1), name: current }, ...v.models] const usd = (n: number) => `$${Number(n.toFixed(2))}` const valueOf = (m: Listed) => `${m.provider}/${m.id}` const byValue = new Map(options.map((m) => [valueOf(m), m])) const currentName = byValue.get(current)?.name ?? current const option = (value: string, label: string, selected: boolean, lead: string, note: string, image = false) => `` // The model, computer and permissions are rows in the + menu, each opening its own menu. A row's first // span is its current choice (chat.js's setChoice writes it). const modelPill = `` const favorites = new Set(v.favoriteModels ?? []) const modelRow = (m: Listed, extra = false) => { const value = valueOf(m) const favorite = favorites.has(value) const cost = m.cost && (m.cost.input || m.cost.output) ? `${usd(m.cost.input)} / ${usd(m.cost.output)}` : '' return `
` + option(value, m.name, value === current, '', cost, !!m.image) + `
` } const group = (label: string, rows: string, attrs: string, more = '') => `
${rows}${more}
` // Up top, each model once: Languid's picks, then recent and favorites that aren't among them. const house = (v.houseModels ?? []).filter((x) => byValue.has(x)) const upTop = new Set(house) const recent = (v.recentModels ?? []).filter((x) => byValue.has(x)) if (!recent.includes(current) && byValue.has(current)) recent.unshift(current) const recentTop = recent.filter((x) => !upTop.has(x)).slice(0, RECENT_SHOWN) for (const x of recentTop) upTop.add(x) const favoriteRows = options.filter((m) => favorites.has(valueOf(m)) && !upTop.has(valueOf(m))).map((m) => modelRow(m)).join('') const houseRows = house.map((x) => modelRow(byValue.get(x)!)).join('') const recentRows = recentTop.map((x) => modelRow(byValue.get(x)!)).join('') // Every model under the account that pays for it. A connected account shows its first few; Languid's // own catalog, which can run to hundreds, shows none until asked when there are picks above it. const connectionGroups = CONNECTIONS.map((c) => { const models = options.filter((m) => (m.connection ?? 'languid') === c.id) const cap = c.id === 'languid' && houseRows ? 0 : CONNECTION_SHOWN const more = models.length > cap ? `` : '' return group(c.label, models.map((m, i) => modelRow(m, i >= cap)).join(''), `data-connection="${c.id}"`, more) }).join('') const modelMenu = `` // Where computer tools run: "any" lets the service place each call; chat.js remembers the choice per agent. const computerPill = v.computers.length ? `` : '' const computerMenu = v.computers.length ? `` : '' // Whether computer tools that change things ask first or just run. Sent with each message, so it // applies to the next run; chat.js remembers it per agent in this browser. Only computers run them. const approvalPill = v.computers.length ? `` : '' const rules = v.alwaysAllowed ?? [] // A saved rule, as chat.js's ruleNode draws one. const ruleRow = (r: { computer: string; tool: string }) => `
${esc(r.tool)} on ${esc(r.computer)}` + `
` const approvalMenu = v.computers.length ? `` : '' return page( 200, `${shown} · Languid`, panel + // The thread's name, which opens to rename it, and who it's with. A fresh thread gets it, filled in, // when its first message starts it. `
` + `

` + `${esc(shown)}
` + `
About

${budget ? budget.slice(3) + '
' : ''}Computers: ${computers}
Settings · Memory · Records · Evals · Machines

` + `
` + `
Threads ${threads}
` + `
${log}
` + `
` + `
` + `
` + `` + `` + `
` + (v.voice ? `` : '') + `` + `
` + `` + `${modelMenu}${computerMenu}${approvalMenu}
` + `` + ``, { path: base, script: true, microphone: true, wide: true, footer: false }, ) } /** What + says on hover, and what chat.js puts back when Allow all is turned off. */ const PLUS_TITLE = 'Add an image, choose the model and more' /** * The chat page's script: sends messages, polls the run, shows text, tool calls and approvals as they * come. Everything from the service goes in through textContent, never as HTML. */ export const CHAT_JS = String.raw`(() => { 'use strict' const root = document.getElementById('chat') if (!root) return const base = root.dataset.base || '/agents/' + encodeURIComponent(root.dataset.agent) const log = document.getElementById('log') const form = document.getElementById('composer') const input = form.elements.text const sendButton = form.querySelector('button[type=submit]') const stopButton = document.getElementById('stop') const status = document.getElementById('status') // Messages queued during a run (see queueMessage), and the images each took, to show or put back. const queuedBox = document.getElementById('queued') const queuedPics = new Map() let thread = root.dataset.thread || '' let run = root.dataset.run || '' let since = Number(root.dataset.since || 0) // Tasks started here whose results haven't come back: while idle, the page asks every few seconds, // and reloads (or follows the run, if a message is being written) when a result wakes the thread. let tasksPending = Number(root.dataset.tasks || 0) let working = null let failures = 0 // Errors from the service are written for the CLI and may start lowercase. const upper = (s) => (s ? s.charAt(0).toUpperCase() + s.slice(1) : s) const el = (tag, cls, text) => { const e = document.createElement(tag) if (cls) e.className = cls if (text !== undefined && text !== null) e.textContent = text return e } // Copy only the code, never the toolbar or fence markers. The fallback also supports HTTP dev. const copyText = async (text) => { try { if (navigator.clipboard?.writeText) { await navigator.clipboard.writeText(text) return } } catch { /* Clipboard permission denied: try the selection-based fallback. */ } const active = document.activeElement const selection = window.getSelection() const ranges = selection ? Array.from({ length: selection.rangeCount }, (_, i) => selection.getRangeAt(i).cloneRange()) : [] const area = el('textarea') area.value = text area.setAttribute('readonly', '') area.style.cssText = 'position:fixed;left:-9999px;top:0' document.body.appendChild(area) try { area.select() if (!document.execCommand('copy')) throw new Error('Copy failed') } finally { area.remove() active?.focus({ preventScroll: true }) if (selection) { selection.removeAllRanges() for (const range of ranges) selection.addRange(range) } } } const codeBlock = (text) => { const block = el('div', 'code-block') const toolbar = block.appendChild(el('div', 'code-toolbar')) const button = toolbar.appendChild(el('button', 'code-copy')) button.insertAdjacentHTML('afterbegin', ${JSON.stringify(COPY_INNER)}) button.type = 'button' button.setAttribute('aria-label', 'Copy code') const feedback = toolbar.appendChild(el('span', 'sr-only')) feedback.setAttribute('role', 'status') let reset button.addEventListener('click', async () => { clearTimeout(reset) button.disabled = true try { await copyText(text) button.classList.add('done') feedback.textContent = 'Code copied to clipboard' } catch { button.textContent = 'Copy failed' feedback.textContent = 'Copy failed. Select it to copy manually.' } finally { button.disabled = false reset = setTimeout(() => { button.classList.remove('done') if (!button.firstElementChild) { button.textContent = ''; button.insertAdjacentHTML('afterbegin', ${JSON.stringify(COPY_INNER)}) } feedback.textContent = '' }, 2000) } }) block.appendChild(el('pre')).appendChild(el('code', null, text)) return block } // Markdown, the subset models write: paragraphs, headings, lists, fences, quotes, tables, rules, // and inline code, bold, italics and links. Builds nodes with textContent only; links must be // http(s) or mailto. const INLINE = /(\`+)([\s\S]*?[^\`])\1(?!\`)|\*\*(?=\S)([\s\S]*?\S)\*\*|__(?=\S)([\s\S]*?\S)__|(?]+)>?\)|(https?:\/\/[^\s<>]*[^\s<>.,;:!?'")\]*_])/g const link = (href, label, bare) => { const a = /^(https?:\/\/|mailto:)/i.test(href) ? el('a') : document.createDocumentFragment() if (a.nodeName === 'A') { a.href = href a.rel = 'noopener noreferrer nofollow' a.target = '_blank' } if (bare) a.appendChild(document.createTextNode(label)) else inline(a, label, true) return a } /** Inline markup into parent. Inside a link's text, bare URLs stay text. */ function inline(parent, text, inLink) { const re = new RegExp(INLINE.source, 'g') let at = 0 let m while ((m = re.exec(text))) { if (m.index > at) parent.appendChild(document.createTextNode(text.slice(at, m.index))) if (m[1]) { const c = m[2] parent.appendChild(el('code', null, /^ .*[^ ].* $/.test(c) ? c.slice(1, -1) : c)) } else if (m[3] || m[4]) parent.appendChild(inline(el('strong'), m[3] || m[4], inLink)) else if (m[5] || m[6]) parent.appendChild(inline(el('em'), m[5] || m[6], inLink)) else if (m[7] && !inLink) parent.appendChild(link(m[8], m[7])) else if (m[9] && !inLink) parent.appendChild(link(m[9], m[9], true)) else parent.appendChild(document.createTextNode(m[0])) at = re.lastIndex } if (at < text.length) parent.appendChild(document.createTextNode(text.slice(at))) return parent } const lines = (parent, ls) => { ls.forEach((l, i) => { if (i) parent.appendChild(el('br')) inline(parent, l) }) return parent } const FENCE = /^ {0,3}(\`{3,}|~{3,})/ const RULE = /^ {0,3}([-*_])( *\1){2,} *$/ const HEADING = /^ {0,3}(#{1,6}) +(.*?)(?: +#+)? *$/ const ITEM = /^( *)([-*+]|\d{1,9}[.)]) +(.*)$/ const QUOTE = /^ {0,3}> ?(.*)$/ const ROW = /^ *\|.*\| *$|^[^|]*\|[^|]*/ const DIVIDER = /^ *\|? *:?-+:? *(\| *:?-+:? *)*\|? *$/ const cells = (row) => row.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((c) => c.trim()) const special = (l) => FENCE.test(l) || RULE.test(l) || HEADING.test(l) || ITEM.test(l) || QUOTE.test(l) function list(ls) { // ls: lines of one list block, items and their continuation lines. Nests by indent; a change // between bullets and numbers at the same depth starts a new list. const out = document.createDocumentFragment() const stack = [] let last = null for (const l of ls) { const m = ITEM.exec(l) if (!m) { if (last) { last.appendChild(el('br')) inline(last, l.trim()) } continue } const indent = m[1].length const ordered = /\d/.test(m[2]) while (stack.length && indent < stack[stack.length - 1].indent) stack.pop() let cur = stack[stack.length - 1] if (cur && indent <= cur.indent + 1 && cur.ordered !== ordered) { stack.pop() cur = stack[stack.length - 1] } if (!cur || indent > cur.indent + 1) { const node = el(ordered ? 'ol' : 'ul') if (ordered && parseInt(m[2], 10) !== 1) node.start = parseInt(m[2], 10) ;(stack.length ? stack[stack.length - 1].li : out).appendChild(node) cur = { indent, ordered, node, li: null } stack.push(cur) } last = cur.li = inline(el('li'), m[3]) cur.node.appendChild(last) } return out } function md(text) { const out = document.createDocumentFragment() const ls = text.replace(/\r\n?/g, '\n').split('\n') let i = 0 while (i < ls.length) { const l = ls[i] let m if (!l.trim()) { i++ } else if ((m = FENCE.exec(l))) { const close = new RegExp('^ {0,3}' + m[1][0] + '{' + m[1].length + ',} *$') const body = [] for (i++; i < ls.length && !close.test(ls[i]); i++) body.push(ls[i]) i++ out.appendChild(codeBlock(body.join('\n'))) } else if (RULE.test(l)) { out.appendChild(el('hr')) i++ } else if ((m = HEADING.exec(l))) { out.appendChild(inline(el('h' + Math.min(5, m[1].length + 2)), m[2])) i++ } else if (QUOTE.test(l)) { const body = [] for (; i < ls.length && (m = QUOTE.exec(ls[i])); i++) body.push(m[1]) out.appendChild(el('blockquote')).appendChild(md(body.join('\n'))) } else if (ITEM.test(l)) { const body = [] for (; i < ls.length; i++) { const x = ls[i] if (ITEM.test(x) || (x.trim() && /^\s/.test(x))) body.push(x) else if (!x.trim() && i + 1 < ls.length && (ITEM.test(ls[i + 1]) || /^\s+\S/.test(ls[i + 1]))) continue else break } out.appendChild(list(body)) } else if (ROW.test(l) && i + 1 < ls.length && DIVIDER.test(ls[i + 1]) && ls[i + 1].includes('-')) { const wrap = el('div', 'table') const table = wrap.appendChild(el('table')) const head = table.appendChild(el('thead')).appendChild(el('tr')) for (const c of cells(l)) head.appendChild(inline(el('th'), c)) const tbody = table.appendChild(el('tbody')) for (i += 2; i < ls.length && ls[i].trim() && ls[i].includes('|'); i++) { const tr = tbody.appendChild(el('tr')) for (const c of cells(ls[i])) tr.appendChild(inline(el('td'), c)) } out.appendChild(wrap) } else { const body = [] for (; i < ls.length && ls[i].trim() && !(body.length && special(ls[i])); i++) body.push(ls[i]) out.appendChild(lines(el('p'), body)) } } return out } /** Shows text as markdown, or as plain text if rendering fails, and keeps the markdown for the reply's copy button. */ const sources = new WeakMap() const render = (node, text) => { sources.set(node, text) try { node.replaceChildren(md(text)) node.classList.add('md') } catch { node.textContent = text node.classList.remove('md') } return node } const atBottom = () => window.innerHeight + window.scrollY >= document.body.scrollHeight - 80 const add = (node) => { const stick = atBottom() log.querySelector('.empty')?.remove() if (working && working.parentNode === log) log.insertBefore(node, working) else log.appendChild(node) if (stick) window.scrollTo(0, document.body.scrollHeight) return node } const byId = (sel, id) => [...log.querySelectorAll(sel)].find((n) => n.dataset.id === id) // The pills open menus of options. Arrow keys move through them, Escape or a click elsewhere closes. const menus = [] function menu(pill, list, choose) { if (!pill || !list) return const search = list.querySelector('input[type=search]') const options = () => [...list.querySelectorAll('[role=option]')].filter((o) => !o.hidden) const filter = () => { const terms = search.value.toLowerCase().trim().split(/\s+/) // Searching looks through every model, each once; otherwise the short list shows, groups as opened. const narrowed = search.value.trim() !== '' for (const o of list.querySelectorAll('[role=option]')) { const row = o.parentElement?.classList.contains('model-row') ? o.parentElement : null const text = (o.dataset.label + ' ' + o.dataset.value + ' ' + (row?.dataset.maker ?? '')).toLowerCase() o.hidden = !terms.every((term) => text.includes(term)) || (narrowed && !!o.closest('[data-top]')) || (!narrowed && !!row?.hasAttribute('data-extra') && !row.closest('[data-expanded]')) if (row) row.hidden = o.hidden } for (const more of list.querySelectorAll('.menu-more')) more.hidden = narrowed || more.closest('[role=group]').hasAttribute('data-expanded') for (const group of list.querySelectorAll('[role=group]')) { group.hidden = ![...group.querySelectorAll('[role=option], .menu-more')].some((o) => !o.hidden) } list.querySelector('.menu-empty').hidden = options().length > 0 } search?.addEventListener('input', filter) // A row of the + menu opens its menu from the + button, which gets the focus back when it closes. const anchor = (pill.closest?.('[role=menu]') && document.getElementById('plus')) || pill const close = (refocus) => { if (list.hidden) return list.hidden = true pill.setAttribute('aria-expanded', 'false') if (refocus) anchor.focus() } // A menu grows out of its button: the same left edge, just below it when there's room, // otherwise just above it (over the text box), as if the button opened up. const place = () => { const box = list.offsetParent?.getBoundingClientRect() if (!box) return const p = anchor.getBoundingClientRect() const left = Math.max(8, Math.min(p.left - box.left, box.width - list.offsetWidth - 8)) const below = window.innerHeight - p.bottom - 16 const above = p.top - 16 const tallest = Math.min(416, window.innerHeight * 0.6) list.style.left = left + 'px' if (below >= Math.min(tallest, 300) || below > above) { list.style.top = (p.bottom - box.top + 6) + 'px' list.style.bottom = 'auto' list.style.maxHeight = Math.min(tallest, below) + 'px' list.dataset.side = 'below' } else { list.style.top = 'auto' list.style.bottom = (box.bottom - p.top + 6) + 'px' list.style.maxHeight = Math.min(tallest, above) + 'px' list.dataset.side = 'above' } } globalThis.addEventListener?.('resize', () => { if (!list.hidden) place() }) const open = () => { for (const m of menus) m.close(false) list.hidden = false place() pill.setAttribute('aria-expanded', 'true') if (search) { search.value = '' for (const g of list.querySelectorAll('[data-expanded]')) g.removeAttribute('data-expanded') filter() search.focus() } else (options().find((o) => o.getAttribute('aria-selected') === 'true') || options()[0])?.focus() } pill.addEventListener('click', () => (list.hidden ? open() : close(true))) // Safari (and some Chromium builds) don't focus a button on click: pressing one sends focus to // the body, the focusout below closes the menu, and the click lands on nothing. Keep focus put. list.addEventListener('mousedown', (ev) => { if (ev.target.closest('button')) ev.preventDefault() }) list.addEventListener('click', (ev) => { // "Show all" under a group lists the rest of it. const more = ev.target.closest('.menu-more') if (more) { const group = more.closest('[role=group]') group.setAttribute('data-expanded', '') filter() group.querySelector('[role=option]:not([hidden])')?.focus() return } const o = ev.target.closest('[role=option]') if (!o) return close(true) choose(o) }) list.addEventListener('keydown', (ev) => { const all = options() const i = all.indexOf(document.activeElement) const inSearch = document.activeElement === search const to = inSearch ? { ArrowDown: 0, ArrowUp: all.length - 1 }[ev.key] : { ArrowDown: i + 1, ArrowUp: i - 1, Home: 0, End: all.length - 1 }[ev.key] if (ev.key === 'Enter' && inSearch) { ev.preventDefault() all[0]?.click() } else if (to !== undefined) { ev.preventDefault() all[(to + all.length) % all.length]?.focus() } else if (ev.key === 'Escape') { ev.preventDefault() close(true) } }) list.addEventListener('focusout', () => { queueMicrotask(() => { if (!list.contains(document.activeElement)) close(false) }) }) document.addEventListener('click', (ev) => { if (!list.contains(ev.target) && !pill.contains(ev.target) && !anchor.contains(ev.target)) close(false) }) menus.push({ close }) } /** Show value as the pill's choice: its label, and the check in its menu. */ function setChoice(pill, list, value) { const o = [...list.querySelectorAll('[role=option]')].find((x) => x.dataset.value === value) if (!o) return false pill.dataset.value = value pill.querySelector('span').textContent = o.dataset.label for (const x of list.querySelectorAll('[role=option]')) x.setAttribute('aria-selected', String(x.dataset.value === value)) if (pill.id === 'approval') flagAllow(value) return true } // The + button opens one menu: Add image, and rows that open the model, computer and permissions menus. // Arrow keys move through it, Enter picks, Escape or a click elsewhere closes it. const plus = document.getElementById('plus') const plusMenu = document.getElementById('plus-menu') const plusTitle = plus?.title || '' /** Allow all is out of sight in the + menu, so + wears a dot while it is on. */ function flagAllow(value) { if (!plus) return plus.classList.toggle('allow', value === 'allow') plus.title = value === 'allow' ? 'Allow all is on' : plusTitle } if (plus && plusMenu) { const items = () => [...plusMenu.querySelectorAll('[role=menuitem]')].filter((b) => !b.hidden && !b.disabled) const closePlus = (refocus) => { if (plusMenu.hidden) return plusMenu.hidden = true plus.setAttribute('aria-expanded', 'false') if (refocus) plus.focus() } const openPlus = () => { for (const m of menus) m.close(false) plusMenu.hidden = false plusMenu.dataset.side = 'above' plus.setAttribute('aria-expanded', 'true') items()[0]?.focus() } plus.addEventListener('click', () => (plusMenu.hidden ? openPlus() : closePlus(true))) plus.addEventListener('keydown', (ev) => { if (ev.key !== 'ArrowUp' && ev.key !== 'ArrowDown') return ev.preventDefault() openPlus() }) // As in the other menus: keep the focus where it is on a press, so focusout doesn't close it first. plusMenu.addEventListener('mousedown', (ev) => { if (ev.target.closest('button')) ev.preventDefault() }) // A row's own handler runs first (Add image opens the file picker, the others their menus); then this closes. plusMenu.addEventListener('click', (ev) => { if (ev.target.closest('[role=menuitem]')) closePlus(false) }) plusMenu.addEventListener('keydown', (ev) => { const all = items() const i = all.indexOf(document.activeElement) const to = { ArrowDown: i + 1, ArrowUp: i - 1, Home: 0, End: all.length - 1 }[ev.key] if (to !== undefined) { ev.preventDefault() all[(to + all.length) % all.length]?.focus() } else if (ev.key === 'Escape') { ev.preventDefault() closePlus(true) } else if (ev.key === 'Tab') closePlus(false) }) plusMenu.addEventListener('focusout', () => { queueMicrotask(() => { if (!plusMenu.contains(document.activeElement)) closePlus(false) }) }) document.addEventListener('click', (ev) => { if (!plusMenu.contains(ev.target) && !plus.contains(ev.target)) closePlus(false) }) menus.push({ close: closePlus }) } // The computer: sent with each message. Remembered per agent in this browser only. const picker = document.getElementById('computer') const pickerMenu = document.getElementById('computer-menu') const pickKey = 'languid.computer.' + root.dataset.agent if (picker) { try { const saved = localStorage.getItem(pickKey) if (saved !== null) setChoice(picker, pickerMenu, saved) } catch {} menu(picker, pickerMenu, (o) => { setChoice(picker, pickerMenu, o.dataset.value) try { localStorage.setItem(pickKey, o.dataset.value) } catch {} }) } // Permissions: ask before each change, or allow them all. Sent with each message, and changing it // while a run goes applies to that run's calls still to come; Allow all also says yes to any // waiting now. Remembered per agent in this browser only. const approvalPicker = document.getElementById('approval') const approvalMenu = document.getElementById('approval-menu') const approvalKey = 'languid.approval.' + root.dataset.agent function choosePermission(value, runId) { if (approvalPicker) setChoice(approvalPicker, approvalMenu, value) try { localStorage.setItem(approvalKey, value) } catch {} if (!runId) return Promise.resolve() return api('/runs/' + encodeURIComponent(runId) + '/mode', { approval: value }).catch((err) => { if (err.status === 404) return status.textContent = upper(err.message) }) } if (approvalPicker) { try { const saved = localStorage.getItem(approvalKey) if (saved !== null) setChoice(approvalPicker, approvalMenu, saved) } catch {} menu(approvalPicker, approvalMenu, (o) => choosePermission(o.dataset.value, run)) } // Saved "always allow" rules, listed in the permissions menu. "Ask again" removes one. const rules = approvalMenu?.querySelector('[data-rules]') // A saved rule, as ruleRow in web.ts draws one. function ruleNode(r) { const row = el('div', 'rule') row.dataset.computer = r.computer row.dataset.tool = r.tool const what = el('span') what.append(el('code', null, r.tool), document.createTextNode(' on ' + r.computer)) const remove = el('button', 'rule-remove', 'Ask again') remove.type = 'button' remove.setAttribute('aria-label', 'Ask before ' + r.tool + ' on ' + r.computer + ' again') row.append(what, remove) return row } const ruleRows = () => [...(rules?.querySelectorAll('.rule') ?? [])] function addRule(r) { if (!rules || ruleRows().some((x) => x.dataset.computer === r.computer && x.dataset.tool === r.tool)) return rules.appendChild(ruleNode(r)) rules.hidden = false } rules?.addEventListener('click', async (ev) => { const b = ev.target.closest('.rule-remove') if (!b) return const row = b.closest('.rule') b.disabled = true try { await api('/approvals/revoke', { computer: row.dataset.computer, tool: row.dataset.tool }) row.remove() rules.hidden = !ruleRows().length status.textContent = 'It asks before ' + row.dataset.tool + ' on ' + row.dataset.computer + ' again' if (!approvalMenu.hidden) (rules.querySelector('.rule-remove') || approvalMenu.querySelector('[role=option][aria-selected=true]'))?.focus() } catch (err) { b.disabled = false status.textContent = upper(err.message) } }) // The model: saved to the agent as soon as it's chosen; a refusal puts the old one back. const modelPicker = document.getElementById('model') const modelMenu = document.getElementById('model-menu') modelMenu?.addEventListener('click', async (ev) => { const star = ev.target.closest('.model-favorite') if (!star || star.getAttribute('aria-disabled') === 'true') return const favorite = star.getAttribute('aria-pressed') !== 'true' star.setAttribute('aria-disabled', 'true') try { await api('/model-favorite', { value: star.dataset.value, favorite }) const label = star.previousElementSibling.dataset.label const stars = [...modelMenu.querySelectorAll('.model-favorite')].filter((x) => x.dataset.value === star.dataset.value) for (const x of stars) { x.setAttribute('aria-pressed', String(favorite)) x.setAttribute('aria-label', (favorite ? 'Remove ' : 'Add ') + label + (favorite ? ' from' : ' to') + ' favorites') x.title = (favorite ? 'Remove from' : 'Add to') + ' favorites' x.textContent = favorite ? '★' : '☆' } const group = modelMenu.querySelector('[data-favorites]') const kept = stars.find((x) => group.contains(x)) if (favorite && !kept) { const copy = star.parentElement.cloneNode(true) copy.removeAttribute('data-extra') group.appendChild(copy) } else if (!favorite && kept) kept.parentElement.remove() modelMenu.querySelector('input[type=search]').dispatchEvent(new Event('input')) status.textContent = favorite ? 'Model added to favorites' : 'Model removed from favorites' } catch (err) { status.textContent = err.message } finally { star.removeAttribute('aria-disabled') if (!modelMenu.hidden) star.focus() } }) // The model is this thread's: saved on the thread, or, before a new thread's first message, sent // with it. The agent's own model (its settings) is what threads start with. It can change mid-run: // the run picks it up at its next step. let pickedModel = '' // How hard the model reasons, for models that can: saved with the thread's model. A model that // can't do the level asked for gets the nearest it can, as the service does (clampThinkingLevel). const LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] let reasoning = modelPicker?.dataset.reasoning || 'off' let pickedReasoning = '' const levelsOf = (value) => { const o = modelMenu && [...modelMenu.querySelectorAll('[role=option]')].find((x) => x.dataset.value === value) const levels = o?.parentElement?.dataset.levels return levels ? levels.split(' ') : [] } const clampLevel = (levels, level) => { if (!levels.length) return 'off' if (levels.includes(level)) return level const at = LEVELS.indexOf(level) return LEVELS.slice(at).find((l) => levels.includes(l)) || LEVELS.slice(0, at).reverse().find((l) => levels.includes(l)) || 'off' } const showReasoning = () => { if (!modelPicker || !modelMenu) return const levels = levelsOf(modelPicker.dataset.value) const level = clampLevel(levels, reasoning) const box = modelMenu.querySelector('.menu-reasoning') if (box) box.hidden = !levels.length for (const b of modelMenu.querySelectorAll('.level')) { b.hidden = !levels.includes(b.dataset.level) b.setAttribute('aria-pressed', String(b.dataset.level === level)) } const note = modelPicker.querySelector('.pill-note') if (note) { note.hidden = !levels.length || level === 'off' note.textContent = modelMenu.querySelector('.level[data-level="' + level + '"]')?.textContent || '' } } // Save this thread's model and level; before a new thread's first message, they go with it. const saveModel = async (value, before, beforeReasoning) => { if (!thread) { pickedModel = value pickedReasoning = reasoning status.textContent = 'Set for this thread' return } modelPicker.disabled = true const slash = value.indexOf('/') try { await api('/model', { provider: value.slice(0, slash), model: value.slice(slash + 1), thread, reasoning }) status.textContent = 'Set for this thread' } catch (err) { setChoice(modelPicker, modelMenu, before) reasoning = beforeReasoning showReasoning() renderTray() status.textContent = err.message } finally { modelPicker.disabled = false // Disabling it while saving dropped the focus it had; give it back. if (document.activeElement === document.body) modelPicker.focus() } } modelMenu?.querySelector('.levels')?.addEventListener('click', (ev) => { const b = ev.target.closest('.level') if (!b || b.getAttribute('aria-pressed') === 'true') return const before = reasoning reasoning = b.dataset.level showReasoning() saveModel(modelPicker.dataset.value, modelPicker.dataset.value, before) }) menu(modelPicker, modelMenu, async (o) => { const before = modelPicker.dataset.value const value = o.dataset.value if (value === before) return setChoice(modelPicker, modelMenu, value) showReasoning() renderTray() await saveModel(value, before, reasoning) }) // Images pasted or dropped into the composer wait above the text as thumbnails until they're sent. // Big ones are scaled down here first, so a phone photo or a retina screenshot fits the 5 MB limit. const tray = document.getElementById('tray') const MAX_IMAGES = 4 const MAX_IMAGE_BYTES = 5 * 1024 * 1024 const MAX_SIDE = 2048 const SMALL_ENOUGH = 1.5 * 1024 * 1024 let pending = [] const readBase64 = (blob) => new Promise((ok, fail) => { const r = new FileReader() r.onload = () => ok(String(r.result).slice(String(r.result).indexOf(',') + 1)) r.onerror = () => fail(r.error) r.readAsDataURL(blob) }) const encode = (canvas, type, quality) => new Promise((ok) => canvas.toBlob(ok, type, quality)) async function shrink(file) { // A GIF may move, so it goes as it is. if (file.type === 'image/gif') return file const bitmap = await createImageBitmap(file).catch(() => null) if (!bitmap) return file const scale = Math.min(1, MAX_SIDE / Math.max(bitmap.width, bitmap.height)) if (scale === 1 && file.size <= SMALL_ENOUGH) { bitmap.close() return file } const canvas = document.createElement('canvas') canvas.width = Math.max(1, Math.round(bitmap.width * scale)) canvas.height = Math.max(1, Math.round(bitmap.height * scale)) const ctx = canvas.getContext('2d') ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height) bitmap.close() let out = await encode(canvas, file.type === 'image/png' ? 'image/png' : 'image/jpeg', 0.88) if (!out || out.size > SMALL_ENOUGH) { // JPEG has no transparency: paper behind it, not black. ctx.globalCompositeOperation = 'destination-over' ctx.fillStyle = '#fff' ctx.fillRect(0, 0, canvas.width, canvas.height) out = await encode(canvas, 'image/jpeg', 0.85) } return out && out.size < file.size ? out : file } const removeIcon = () => { const ns = 'http://www.w3.org/2000/svg' const svg = document.createElementNS(ns, 'svg') for (const [k, v] of Object.entries({ viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'aria-hidden': 'true' })) svg.setAttribute(k, v) const path = document.createElementNS(ns, 'path') path.setAttribute('d', 'M7 7l10 10M17 7 7 17') svg.appendChild(path) return svg } // Whether the agent's model can see images, by the model menu's own option for it. const modelSees = () => { const picker = document.getElementById('model') const list = document.getElementById('model-menu') if (!picker || !list) return true const o = [...list.querySelectorAll('[role=option]')].find((x) => x.dataset.value === picker.dataset.value) return !o || 'image' in o.dataset } function renderTray() { if (!tray) return tray.replaceChildren(...pending.map((p) => p.el)) tray.hidden = !pending.length input.required = !pending.length if (pending.length && !modelSees()) { const picker = document.getElementById('model') const note = tray.appendChild(el('p', 'tray-note', picker.querySelector('span').textContent + " can't see images. ")) const pick = note.appendChild(el('button', '', 'Use a model that can')) pick.type = 'button' pick.addEventListener('click', () => picker.click()) } canSend() } const drop = (p) => { pending = pending.filter((q) => q !== p) URL.revokeObjectURL(p.url) renderTray() } function addImages(files) { if (!tray) return for (const file of files) { if (!/^image\/(png|jpeg|gif|webp)$/.test(file.type)) { status.textContent = 'Images must be PNG, JPEG, GIF or WebP' continue } if (pending.length >= MAX_IMAGES) { status.textContent = 'A message takes at most ' + MAX_IMAGES + ' images' break } const p = { url: URL.createObjectURL(file), mimeType: file.type, data: null } p.el = el('div', 'thumb loading') const img = p.el.appendChild(el('img')) img.src = p.url img.alt = 'Pasted image' const x = p.el.appendChild(el('button', 'x')) x.type = 'button' x.title = 'Remove' x.setAttribute('aria-label', 'Remove image') x.appendChild(removeIcon()) x.addEventListener('click', () => { drop(p) input.focus() }) p.ready = shrink(file) .then(async (blob) => { if (blob.size > MAX_IMAGE_BYTES) throw new Error('That image is over 5 MB') p.mimeType = blob.type || file.type p.data = await readBase64(blob) p.el.classList.remove('loading') }) .catch((err) => { drop(p) status.textContent = upper(err.message || 'That image could not be read') }) pending.push(p) } renderTray() } const attach = document.getElementById('attach') const attachFile = document.getElementById('attach-file') if (attach && attachFile) { attach.addEventListener('click', () => attachFile.click()) attachFile.addEventListener('change', () => { addImages([...attachFile.files]) attachFile.value = '' input.focus() }) } input.addEventListener('paste', (ev) => { const clipboard = ev.clipboardData if (!clipboard) return // Some clipboard sources expose images as items rather than in the file list. Prefer the // file list when present: browsers commonly expose the same image through both APIs. let files = [...(clipboard.files || [])].filter((f) => f.type.startsWith('image/')) if (!files.length) files = [...(clipboard.items || [])] .filter((item) => item.kind === 'file' && item.type.startsWith('image/')) .map((item) => item.getAsFile()).filter(Boolean) if (!files.length) return // An image copied with text beside it (from a page, say) pastes both. if (![...(clipboard.types || [])].includes('text/plain')) ev.preventDefault() addImages(files) }) const carriesFiles = (ev) => [...(ev.dataTransfer?.types || [])].includes('Files') form.addEventListener('dragover', (ev) => { if (!carriesFiles(ev) || !tray) return ev.preventDefault() form.classList.add('dropping') }) form.addEventListener('dragleave', (ev) => { if (!form.contains(ev.relatedTarget)) form.classList.remove('dropping') }) form.addEventListener('drop', (ev) => { form.classList.remove('dropping') if (!carriesFiles(ev) || !tray) return ev.preventDefault() addImages([...ev.dataTransfer.files]) input.focus() }) // One round button ends the composer: the mic while there's nothing to send (and voice works here), // Send once there's text or an image (dim while empty if there's no mic), and Stop while a run goes. const mic = document.getElementById('mic') let busyNow = false let sending = false let micOn = false let listening = false const canSend = () => { const empty = !input.value.trim() && !pending.length const showMic = micOn && !busyNow && (empty || listening || mic.disabled) if (mic) mic.hidden = !showMic // While a run goes, Stop stays; Send joins it once there's something to queue. sendButton.hidden = showMic || (busyNow && empty) sendButton.disabled = empty || sending stopButton.hidden = !busyNow } // The mic: click to speak, click again (or wait out 5 minutes) and the words land in the box to edit. if (mic && navigator.mediaDevices?.getUserMedia && window.MediaRecorder) { micOn = true canSend() const MAX_MS = 5 * 60 * 1000 let rec = null let started = 0 let ticker = 0 const clock = (ms) => Math.floor(ms / 60000) + ':' + String(Math.floor(ms / 1000) % 60).padStart(2, '0') const idle = () => { listening = false mic.setAttribute('aria-pressed', 'false') mic.setAttribute('aria-label', 'Speak') clearInterval(ticker) canSend() } const insert = (words) => { const at = input.selectionStart ?? input.value.length const end = input.selectionEnd ?? at const before = input.value.slice(0, at) const after = input.value.slice(end) const pad = before && !/\s$/.test(before) ? ' ' : '' const tail = after && !/^\s/.test(after) ? ' ' : '' input.value = before + pad + words + tail + after const caret = (before + pad + words).length input.focus() input.setSelectionRange(caret, caret) grow() canSend() } mic.addEventListener('click', async () => { if (rec) return rec.stop() let stream try { stream = await navigator.mediaDevices.getUserMedia({ audio: true }) } catch { status.textContent = 'Allow the microphone for this site to speak a message' return } const type = ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4', 'audio/ogg;codecs=opus'].find((t) => MediaRecorder.isTypeSupported?.(t)) const r = (rec = type ? new MediaRecorder(stream, { mimeType: type }) : new MediaRecorder(stream)) const chunks = [] r.ondataavailable = (e) => { if (e.data?.size) chunks.push(e.data) } r.onstop = async () => { rec = null stream.getTracks().forEach((t) => t.stop()) idle() const seconds = (Date.now() - started) / 1000 const blob = new Blob(chunks, { type: (r.mimeType || type || 'audio/webm').split(';')[0] }) if (seconds < 0.5 || !blob.size) { status.textContent = '' return } mic.disabled = true status.textContent = 'Turning speech into text' try { const j = await api('/transcribe', { audio: await readBase64(blob), mimeType: blob.type, seconds }) if (j.text) insert(j.text) status.textContent = j.text ? '' : "Didn't catch any words" } catch (err) { status.textContent = err.message } finally { mic.disabled = false canSend() } } r.start() listening = true started = Date.now() mic.setAttribute('aria-pressed', 'true') mic.setAttribute('aria-label', 'Stop and transcribe') status.textContent = 'Listening 0:00' ticker = setInterval(() => { const ms = Date.now() - started if (ms >= MAX_MS && rec) return rec.stop() status.textContent = 'Listening ' + clock(ms) }, 250) }) } // The composer's state: working (the light moves), waiting (on you), or at rest. const mood = (m) => { form.classList.toggle('working', m === 'working') form.classList.toggle('waiting', m === 'waiting') } const setBusy = (busy, text) => { mood(busy ? (pendingApproval() ? 'waiting' : 'working') : '') busyNow = busy canSend() for (const m of menus) m.close(false) if (picker) picker.disabled = busy status.textContent = text || '' } async function api(path, body) { const init = body === undefined ? { headers: { accept: 'application/json' } } : { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify(body) } const r = await fetch(base + path, init) const j = await r.json().catch(() => ({})) const message = j.message || 'request failed (' + r.status + ')' // The service writes errors for the CLI, lowercase; the page shows them as sentences. if (!r.ok) throw Object.assign(new Error(message.charAt(0).toUpperCase() + message.slice(1)), { status: r.status }) return j } // 👍/👎 under a reply: say what good looks like, and the moment is saved as an eval case. const UP = ${JSON.stringify(THUMB_UP)} const DOWN = ${JSON.stringify(THUMB_DOWN)} // ICON_COPY and ICON_COPIED as path data, built as elements: the script never writes HTML. const COPY = ['M11 8h7a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-7a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2z', 'M15 8V5a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3'] const COPIED = ['M4.5 12.5l5 5L19.5 7'] const thumb = (...ds) => { const NS = 'http://www.w3.org/2000/svg' const svg = document.createElementNS(NS, 'svg') for (const [k, v] of [['viewBox', '0 0 24 24'], ['fill', 'none'], ['stroke', 'currentColor'], ['stroke-width', '1.5'], ['stroke-linecap', 'round'], ['stroke-linejoin', 'round'], ['aria-hidden', 'true']]) svg.setAttribute(k, v) for (const d of ds) svg.appendChild(document.createElementNS(NS, 'path')).setAttribute('d', d) return svg } function feedbackNode(rkey) { const d = el('div', 'feedback') d.dataset.message = rkey for (const [verdict, shape, label] of [['good', UP, 'Good reply: save as an eval case'], ['bad', DOWN, 'Wrong reply: save as an eval case']]) { const b = d.appendChild(el('button')) b.type = 'button' b.dataset.verdict = verdict b.appendChild(thumb(shape)) b.setAttribute('aria-label', label) b.title = verdict === 'good' ? 'Good: save as an eval case' : 'Wrong: save as an eval case' } const c = d.appendChild(el('button')) c.type = 'button' c.dataset.copy = '' c.setAttribute('aria-label', 'Copy reply') c.title = 'Copy' c.appendChild(thumb(...COPY)) return d } // Copy: the reply's markdown, or its text if the source isn't here. The check shows for a moment. log.addEventListener('click', async (ev) => { const b = ev.target.closest('.feedback > button[data-copy]') if (!b) return const msg = b.parentElement.previousElementSibling if (!msg || !msg.classList.contains('assistant')) return clearTimeout(b._reset) try { await copyText(sources.get(msg) ?? msg.innerText) b.replaceChildren(thumb(...COPIED)) b.title = 'Copied' b.setAttribute('aria-label', 'Copied') } catch { b.title = 'Copy failed' } b._reset = setTimeout(() => { b.replaceChildren(thumb(...COPY)) b.title = 'Copy' b.setAttribute('aria-label', 'Copy reply') }, 1500) }) log.addEventListener('click', (ev) => { const b = ev.target.closest('.feedback > button[data-verdict]') if (!b) return const box = b.parentElement const verdict = b.dataset.verdict for (const x of box.querySelectorAll(':scope > button[data-verdict]')) x.setAttribute('aria-pressed', String(x === b)) box.querySelector('form')?.remove() box.querySelector('.said')?.remove() box.classList.add('open') const f = box.appendChild(el('form')) const note = f.appendChild(el('textarea')) note.name = 'note' note.placeholder = verdict === 'good' ? 'What was good about it? (optional)' : 'What should it have done?' note.setAttribute('aria-label', note.placeholder) note.maxLength = 2000 const row = f.appendChild(el('div', 'row')) const hold = row.appendChild(el('label')) const check = hold.appendChild(el('input')) check.type = 'checkbox' check.name = 'holdout' hold.append(' Hold out (the agent can\'t see it)') const cancel = row.appendChild(el('button', 'quiet', 'Cancel')) cancel.type = 'button' cancel.addEventListener('click', () => { f.remove() box.classList.remove('open') for (const x of box.querySelectorAll(':scope > button[data-verdict]')) x.setAttribute('aria-pressed', 'false') }) const save = row.appendChild(el('button', 'primary', 'Save as a case')) save.type = 'submit' save.style.marginLeft = '0' f.addEventListener('submit', async (sub) => { sub.preventDefault() save.disabled = true try { const r = await api('/evals/save', { thread, message: box.dataset.message, verdict, note: note.value, holdout: check.checked }) f.remove() box.classList.remove('open') const said = box.appendChild(el('span', 'said')) said.append('Saved as ' + (r.holdout ? 'a held-out case. ' : 'a case. ')) const a = said.appendChild(el('a', '', 'See evals')) a.href = base + '/evals' if (r.changedBlocks && r.changedBlocks.length) said.append(' Blocks changed since this reply: ' + r.changedBlocks.join(', ') + '.') } catch (err) { save.disabled = false let p = f.querySelector('.error') || f.appendChild(el('p', 'error')) p.textContent = err.message } }) note.focus() }) // The same labels as callIntention, callSummary and callDetail in web.ts. const parse = (args) => { try { const a = JSON.parse(args) return a && typeof a === 'object' && !Array.isArray(a) ? a : null } catch { return null } } function intention(args) { const v = parse(args)?.call_intention const t = typeof v === 'string' ? v.replace(/\s+/g, ' ').trim() : '' return t.length > 160 ? t.slice(0, 159) + '…' : t } function summary(tool, args) { let shown = args const a = parse(args) if (a) { const { call_intention, ...rest } = a if (tool === 'bash' && typeof a.command === 'string') shown = a.command else if (tool === 'send_message' && typeof a.text === 'string') shown = a.text else if (typeof a.path === 'string') shown = a.path else if (typeof a.label === 'string') shown = a.label else shown = JSON.stringify(rest) } shown = shown.replace(/\s+/g, ' ').trim() return shown.length > 120 ? shown.slice(0, 119) + '…' : shown } function detail(tool, args) { const a = parse(args) if (!a) return args if (tool === 'bash' && typeof a.command === 'string') return a.command if (tool === 'send_message' && typeof a.text === 'string') return a.text const { call_intention, ...rest } = a return JSON.stringify(rest, null, 2) } // A change to a file, as changeHtml in web.ts draws it: the file and counts, then each hunk's lines. const DIFF_KIND = { ' ': 'ctx', '+': 'add', '-': 'del' } function changeNode(c) { const d = el('div', 'diff') const head = d.appendChild(el('div', 'diff-head')) const cut = c.path.lastIndexOf('/') + 1 head.appendChild(el('span', 'diff-path')).append(el('span', 'dir', c.path.slice(0, cut)), c.path.slice(cut)) head.appendChild(el('span', 'diff-n')).append(el('span', 'a', '+' + c.added), ' ', el('span', 'r', '−' + c.removed)) for (const h of c.hunks) { const hunk = d.appendChild(el('div', 'diff-hunk')) for (const l of h) { const row = hunk.appendChild(el('div', 'dl ' + (l[0] === '…' ? 'fold' : DIFF_KIND[l[0]]))) row.appendChild(el('span', 'dg', l[0] === '…' ? '' : l[0])) const t = row.appendChild(el('span', 'dt', l[0] === '…' ? l[1] + ' unchanged lines' : null)) if (l[0] !== '…') for (const [text, changed] of l[1]) t.append(changed ? el('mark', null, text) : text) } } return d } // What a call does, as argsHtml in web.ts: the diff the service sent with it, else its detail. const argsNode = (e, cls) => (e.change ? changeNode(e.change) : el('pre', cls, detail(e.tool, e.arguments))) const agentName = root.dataset.name || root.dataset.agent const lowerFirst = (t) => (/^[A-Z][a-z]/.test(t) ? t.charAt(0).toLowerCase() + t.slice(1) : t) // A call's line, as callHtml in web.ts draws it: a dot for its state, its intention, the tool and computer. function callNode(e) { const d = el('details', 'tool live') d.dataset.id = e.id const s = el('summary') const dot = el('span', 'dot') dot.setAttribute('role', 'img') dot.setAttribute('aria-label', 'running') s.appendChild(dot) const said = intention(e.arguments) const what = s.appendChild(el('span', 'what', said || null)) if (!said) what.appendChild(el('code', null, summary(e.tool, e.arguments))) s.appendChild(document.createTextNode(' ')) const name = s.appendChild(el('span', 'tool-name')) name.appendChild(el('code', null, e.tool)) if (e.computer) name.appendChild(document.createTextNode(' · ' + e.computer)) const io = el('div', 'io') io.append(argsNode(e, 'args'), el('pre', 'out')) d.append(s, io) return d } // Calls in a row fold into one line showing the latest, as callsHtml in web.ts draws them. A call // right after another (nothing said between) joins it: the first one gets wrapped when the second comes. function groupNode() { const g = el('details', 'calls') const s = el('summary') s.append(el('span', 'latest'), el('span', 'count')) g.append(s, el('div', 'list')) return g } function refreshGroup(g) { const calls = g.querySelectorAll(':scope>.list>details.tool') const last = calls[calls.length - 1] if (!last) return g.querySelector(':scope>summary>.latest').replaceChildren(...[...last.querySelector(':scope>summary').childNodes].map((n) => n.cloneNode(true))) const count = g.querySelector(':scope>summary>.count') count.textContent = calls.length + ' calls' const fails = [...calls].filter((c) => c.classList.contains('err')).length if (fails) count.append(' · ', el('span', 'fails', fails + ' failed')) for (const c of ['live', 'ok', 'err']) g.classList.toggle(c, last.classList.contains(c)) } function addCall(d) { const prev = working && working.parentNode === log ? working.previousElementSibling : log.lastElementChild if (!prev || !(prev.matches('details.calls') || prev.matches('details.tool'))) return add(d) const stick = atBottom() let g = prev if (prev.matches('details.tool')) { g = groupNode() // A call the reader had open stays in view. g.open = prev.open prev.replaceWith(g) g.querySelector('.list').appendChild(prev) } g.querySelector('.list').appendChild(d) refreshGroup(g) if (stick) window.scrollTo(0, document.body.scrollHeight) return d } // The question about a call, as approvalHtml in web.ts draws it. function approvalNode(e) { const box = el('div', 'approval') box.dataset.id = e.id box.dataset.run = run const need = el('p', 'need', 'Needs you') need.insertAdjacentHTML('afterbegin', ${JSON.stringify(ICON_NEEDS_YOU)}) box.appendChild(need) const said = intention(e.arguments) box.appendChild(el('p', 'q', agentName + ' would like to ' + (said ? lowerFirst(said) : 'run ' + e.tool))) box.appendChild(el('p', 'sub', e.tool + (e.computer ? ' on ' + e.computer : ''))) box.appendChild(argsNode(e)) const buttons = el('div', 'buttons') const yes = el('button', 'yes', 'Allow') yes.type = 'button' yes.dataset.approve = 'yes' const no = el('button', null, 'Deny') no.type = 'button' no.dataset.approve = 'no' buttons.append(yes) // As alwaysButton in web.ts. if (e.computer && e.always) { const command = e.always.command const always = el('button', null, 'Always allow') if (command) { always.textContent = 'Always allow ' always.appendChild(el('code', null, command)) } always.type = 'button' always.dataset.approve = 'always' always.title = 'Allow, and from now on let ' + agentName + ' run ' + (command ? '“' + command + '”' : e.tool) + ' on ' + e.computer + ' without asking' buttons.append(always) } // As allowAllButton in web.ts. if (e.tool !== 'feedback_share') { const all = el('button', null, 'Allow all') all.type = 'button' all.dataset.approve = 'all' all.title = 'Allow this and every other call for the rest of this run, and set Permissions to Allow all' buttons.append(all) } buttons.append(no) box.appendChild(buttons) return box } function answered(box, approved, reason) { const buttons = box.querySelector('.buttons') if (!buttons) return buttons.replaceWith(el('div', 'answer', (approved ? 'Allowed' : 'Denied') + (reason ? ': ' + reason : ''))) } // What the composer says while a run goes: the call running now, in the agent's words, or that it's working. const pendingApproval = () => !!log.querySelector('.approval .buttons') function settle(text) { if (!run) return const waiting = pendingApproval() mood(waiting ? 'waiting' : 'working') const said = waiting ? 'Waiting for you' : text || agentName + ' is working' status.textContent = said setPendingText(said) } function handle(e) { if (e.type === 'queued_sent') { // A queued message is in the thread now: it moves into the conversation where the agent read it. for (const n of [...queuedBox.children]) if (n.dataset.id === e.id) n.remove() queuedBox.hidden = !queuedBox.children.length const pics = queuedPics.get(e.id) || [] queuedPics.delete(e.id) if (pics.length) { const row = el('div', 'pics') for (const p of pics) { const img = row.appendChild(el('img')) img.src = p.url img.alt = 'Image sent with the message' } add(row) } if (e.text) { const msg = el('div', 'msg user') msg.appendChild(el('span', 'who', 'You')) msg.appendChild(document.createTextNode(e.text)) add(msg) } return } if (e.type === 'text') { clearPending() fadeIn(add(render(el('div', 'msg assistant'), e.text)), 0) } else if (e.type === 'saved') { const replies = log.querySelectorAll('.msg.assistant:not(.working)') const last = replies[replies.length - 1] if (last && !(last.nextElementSibling && last.nextElementSibling.classList.contains('feedback'))) last.after(feedbackNode(e.message)) } else if (e.type === 'tool_call') { if (!byId('details.tool', e.id)) addCall(callNode(e)) const said = intention(e.arguments) settle(said ? said + '…' : '') } else if (e.type === 'tool_result') { const d = byId('details.tool', e.id) || addCall(callNode({ id: e.id, tool: e.tool, arguments: '' })) const out = e.output.length > 4000 ? e.output.slice(0, 4000) + '\n… (' + (e.output.length - 4000) + ' more characters)' : e.output d.querySelector('.out').textContent = out const task = e.tool === 'task' ? /(?:^|\n)(?:Task|Helper) thread: ([a-z0-9]+)\s*$/.exec(e.output || '') : null if (task && !d.querySelector('.task-link')) { const a = el('a', null, 'Open thread') a.href = '?thread=' + encodeURIComponent(task[1]) d.querySelector('.io').appendChild(el('p', 'task-link')).appendChild(a) tasksPending++ } d.classList.remove('live') d.classList.add(e.isError ? 'err' : 'ok') d.querySelector('.dot').setAttribute('aria-label', e.isError ? 'failed' : 'done') const g = d.closest('details.calls') if (g) refreshGroup(g) settle('') } else if (e.type === 'approval') { if (!byId('.approval', e.id)) add(approvalNode(e)) settle('') } else if (e.type === 'decision') { const box = byId('.approval', e.id) if (box) answered(box, e.approved, e.reason) settle('') } } // The reply is not streamed into view: while the run works, one quiet line holds the place // the reply will land, saying what the agent is doing (same words as the status line). // Tool-call and approval cards still appear live; only the prose waits for the end. function ensurePending() { if (working && working.parentNode === log) return working working = el('div', 'msg assistant working') working.appendChild(el('span', 'pip')) working.appendChild(el('span', 'work-text', agentName + ' is working')) const stick = atBottom() log.appendChild(working) if (stick) window.scrollTo(0, document.body.scrollHeight) return working } function setPendingText(text) { if (working && working.parentNode === log) working.querySelector('.work-text').textContent = text } function clearPending() { working?.remove() working = null } // A freshly-arrived reply fades in as one block: after the render, its text is wrapped in // spans that fade (chat.css .fresh). No token-by-token reveal; Languid does not type. function fadeIn(node, shown) { const walk = document.createTreeWalker(node, NodeFilter.SHOW_TEXT) const fresh = [] let seen = 0 for (let t = walk.nextNode(); t; t = walk.nextNode()) { const n = t.nodeValue.length if (seen + n > shown && t.nodeValue.trim()) fresh.push([t, Math.max(0, shown - seen)]) seen += n } for (const [t, at] of fresh) { const tail = at ? t.splitText(at) : t const span = el('span', 'fresh') tail.replaceWith(span) span.appendChild(tail) } return node } async function poll() { if (!run) return const mine = run let st try { st = await api('/runs/' + encodeURIComponent(run) + '?since=' + since) failures = 0 // A message sent as the run ended started another: this poll's run is over. if (run !== mine) return } catch (err) { if (run !== mine) return if (err.status === 404) return lost() failures++ status.textContent = 'Reconnecting' return setTimeout(poll, Math.min(10000, 1000 * failures)) } for (const e of st.events) handle(e) if (st.status === 'running') showQueued(st.queued || []) if (st.title && st.thread) renamed(st.thread, st.title) since = st.next if (st.status === 'running') { ensurePending() setTimeout(poll, 500) } else finish(st) } function finish(st) { clearPending() run = '' // Queued messages the run didn't take go back in the box, with their images, to send or change. const unsent = (st.unsent || []).filter((u) => queuedPics.has(u.id) || u.text) if (unsent.length) { for (const u of unsent) pending.push(...(queuedPics.get(u.id) || [])) input.value = [...unsent.map((u) => u.text), input.value.trim()].filter(Boolean).join('\n\n') renderTray() grow() } queuedBox.replaceChildren() queuedBox.hidden = true queuedPics.clear() setBusy(false, (st.stopped ? 'Stopped' : '') + (unsent.length ? (st.stopped ? '. ' : '') + 'Your queued ' + (unsent.length === 1 ? 'message is' : 'messages are') + ' back in the box' : '')) for (const box of log.querySelectorAll('.approval .buttons')) box.remove() if (st.status === 'error') add(el('p', 'error', upper(st.error || 'the run failed.'))) input.focus() watchTasks() } // While tasks started here are out, ask now and then whether one came back. A result wakes the // thread with a run: reload to show it, unless something is being written, then follow the run. let watching = false async function watchTasks() { if (watching || !thread) return watching = true while (tasksPending > 0) { await new Promise((r) => setTimeout(r, 4000)) if (run || document.hidden) continue let st try { st = await api('/tasks?thread=' + encodeURIComponent(thread)) } catch (err) { continue } if (run) continue const quiet = !input.value.trim() && !pending.length if (st.run) { if (quiet) return location.reload() run = st.run since = 0 setBusy(true, agentName + ' is working') poll() } else if (st.pending < tasksPending && quiet) return location.reload() tasksPending = st.pending } watching = false } // The service no longer has the run (it restarted): say so on any open question, and pick the // thread up, which asks again for whatever was waiting. The service resumes it too; whichever // asks first starts it and the other follows the same run. function lost() { for (const box of log.querySelectorAll('.approval .buttons')) box.replaceWith(el('div', 'answer', 'Not answered before the restart')) finish({ status: 'done' }) if (log.querySelector('.resume')) return pickUp(add(resumeNode(true))) } function resumeNode(pending) { const box = el('div', 'resume') if (pending) { box.dataset.pending = '' box.appendChild(el('p', '', 'Languid restarted. ' + agentName + ' is picking up from there.')) return box } box.appendChild(el('p', '', agentName + ' stopped when Languid restarted.')) const b = box.appendChild(el('button', '', 'Continue')) b.type = 'button' b.dataset.resume = '' return box } // Resume the thread; box is its .resume line. If that fails, the line offers Continue instead. async function pickUp(box) { if (run) return const b = box.querySelector('button') if (b) b.disabled = true try { const body = { thread } if (picker && picker.dataset.value) body.computer = picker.dataset.value if (approvalPicker) body.approval = approvalPicker.dataset.value const r = await api('/resume', body) if (b) box.remove() run = r.run since = r.since || 0 setBusy(true, agentName + ' is working') poll() } catch (err) { // Nothing left to pick up (another tab did): show the thread as it is now. if (err.status === 409) return location.reload() if (b) b.disabled = false else box.replaceWith(resumeNode(false)) status.textContent = upper(err.message) } } log.addEventListener('click', (ev) => { const b = ev.target.closest('button[data-resume]') if (b) pickUp(b.closest('.resume')) }) { const box = log.querySelector('.resume[data-pending]'); if (box) pickUp(box) } log.addEventListener('click', async (ev) => { const b = ev.target.closest('button[data-approve]') if (!b) return const box = b.closest('.approval') for (const x of box.querySelectorAll('button')) x.disabled = true if (b.dataset.approve === 'all') return choosePermission('allow', box.dataset.run) try { const always = b.dataset.approve === 'always' const r = await api('/runs/' + encodeURIComponent(box.dataset.run) + '/approve', { id: box.dataset.id, approved: always || b.dataset.approve === 'yes', ...(always ? { always } : {}) }) if (r.rule && !r.rule.command) addRule(r.rule) } catch (err) { if (err.status === 404) return lost() for (const x of box.querySelectorAll('button')) x.disabled = false status.textContent = upper(err.message) } }) // Renaming a thread from the picker: the name is a record field, so every client sees it. // The link becomes a text field in place; Enter or leaving it saves, Escape cancels. document.addEventListener('click', async (ev) => { const button = ev.target.closest('.threads .rename') if (!button) return const item = button.parentElement const link = item?.querySelector('a') if (!item || !link || item.querySelector('.rename-input')) return const rkey = button.dataset.thread // In the panel the link also holds the time, so the name is its .t; elsewhere it's the whole link. const before = button.dataset.name || (link.querySelector('.t') || link).textContent || '' const field = el('input', 'rename-input') field.type = 'text' field.value = before field.maxLength = 200 field.setAttribute('aria-label', 'Thread name') let done = false const finish = async (save) => { if (done) return done = true const title = field.value.replace(/\s+/g, ' ').trim() if (!save || !title || title === before) { field.replaceWith(link) button.hidden = false return } try { const saved = await api('/threads/rename', { thread: rkey, title }) // The edited link is out of the page until finally puts it back, so name it here too. ;(link.querySelector('.t') || link).textContent = saved.title if (link.title) link.title = saved.title renamed(rkey, saved.title) } catch (err) { status.textContent = upper(err.message) } finally { field.replaceWith(link) button.hidden = false } } link.replaceWith(field) button.hidden = true field.focus() field.select() field.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); void finish(true) } else if (e.key === 'Escape') { e.preventDefault(); void finish(false) } }) field.addEventListener('blur', () => void finish(true)) }) stopButton.addEventListener('click', async () => { if (!run) return stopButton.disabled = true try { await api('/runs/' + encodeURIComponent(run) + '/stop', {}) } catch (err) { status.textContent = upper(err.message) } finally { stopButton.disabled = false } }) // Messages sent while the agent works wait under the chat until its next step takes them. Until // then each can be edited or removed; every open chat shows them (the run's status lists them). function queuedNode(q) { const box = el('div', 'msg user') box.dataset.id = q.id box.dataset.at = String(Date.now()) box.appendChild(el('span', 'q-text', q.text)) if (q.images) box.appendChild(el('span', 'q-pics', q.images === 1 ? '1 image' : q.images + ' images')) const bar = box.appendChild(el('span', 'q-bar')) bar.appendChild(el('span', 'q-label', 'Queued')) for (const [cls, label] of [['q-edit', 'Edit'], ['q-remove', 'Remove']]) { const b = bar.appendChild(el('button', cls, label)) b.type = 'button' } return box } function showQueued(list) { const ids = new Set(list.map((q) => q.id)) // One just sent may be newer than the status that's arriving: leave it a moment. for (const n of [...queuedBox.children]) if (!ids.has(n.dataset.id) && Date.now() - Number(n.dataset.at) > 3000) n.remove() for (const q of list) { const n = [...queuedBox.children].find((x) => x.dataset.id === q.id) if (!n) queuedBox.appendChild(queuedNode(q)) else if (!n.classList.contains('editing')) n.querySelector('.q-text').textContent = q.text } queuedBox.hidden = !queuedBox.children.length } function editQueued(box) { if (box.classList.contains('editing')) return box.classList.add('editing') const shown = box.querySelector('.q-text') const field = el('textarea') field.value = shown.textContent field.setAttribute('aria-label', 'Edit queued message') shown.replaceWith(field) const bar = box.querySelector('.q-bar') const before = [...bar.children] const save = el('button', 'q-save', 'Save') const cancel = el('button', 'q-cancel', 'Cancel') save.type = cancel.type = 'button' bar.replaceChildren(el('span', 'q-label', 'Editing'), cancel, save) const done = (text) => { shown.textContent = text field.replaceWith(shown) bar.replaceChildren(...before) box.classList.remove('editing') } cancel.addEventListener('click', () => done(shown.textContent)) save.addEventListener('click', async () => { save.disabled = true try { const r = await api('/queued', { thread, id: box.dataset.id, text: field.value }) if (r.removed) return box.remove(), (queuedBox.hidden = !queuedBox.children.length) done(r.text) } catch (err) { save.disabled = false status.textContent = err.status === 409 ? 'Too late to edit: ' + agentName + ' has it already' : upper(err.message) if (err.status === 409) done(shown.textContent) } }) field.addEventListener('keydown', (ev) => { if (ev.key === 'Enter' && !ev.shiftKey && !ev.isComposing) { ev.preventDefault(); save.click() } else if (ev.key === 'Escape') { ev.preventDefault(); cancel.click() } }) field.focus() field.setSelectionRange(field.value.length, field.value.length) } queuedBox.addEventListener('click', async (ev) => { const b = ev.target.closest('button') const box = b && b.closest('#queued>.msg') if (!box) return if (b.classList.contains('q-edit')) return editQueued(box) if (!b.classList.contains('q-remove')) return b.disabled = true try { await api('/queued', { thread, id: box.dataset.id, remove: true }) for (const p of queuedPics.get(box.dataset.id) || []) URL.revokeObjectURL(p.url) queuedPics.delete(box.dataset.id) box.remove() queuedBox.hidden = !queuedBox.children.length } catch (err) { b.disabled = false status.textContent = err.status === 409 ? 'Too late to remove: ' + agentName + ' has it already' : upper(err.message) } }) async function queueMessage(text) { const going = pending.slice() sending = true canSend() try { await Promise.all(going.map((p) => p.ready)) const sent = going.filter((p) => p.data) if (!text && !sent.length) return const body = { text, thread, queue: true } if (sent.length) body.images = sent.map((p) => ({ data: p.data, mimeType: p.mimeType })) if (picker && picker.dataset.value) body.computer = picker.dataset.value if (approvalPicker) body.approval = approvalPicker.dataset.value const r = await api('/send', body) input.value = '' grow() pending = pending.filter((p) => !going.includes(p)) renderTray() if (r.queued) { queuedPics.set(r.queued, sent) queuedBox.appendChild(queuedNode({ id: r.queued, text, images: sent.length })) queuedBox.hidden = false window.scrollTo(0, document.body.scrollHeight) return } // The run ended as the message went: it started a new one, which this page follows now. if (sent.length) { const row = el('div', 'pics') for (const p of sent) { const img = row.appendChild(el('img')) img.src = p.url img.alt = 'Image sent with the message' } add(row) } if (text) { const msg = el('div', 'msg user') msg.appendChild(el('span', 'who', 'You')) msg.appendChild(document.createTextNode(text)) add(msg) } run = r.run since = r.since || 0 setBusy(true, agentName + ' is working') poll() } catch (err) { status.textContent = upper(err.message) } finally { sending = false canSend() } } form.addEventListener('submit', async (ev) => { ev.preventDefault() const text = input.value.trim() if ((!text && !pending.length) || sending) return if (run) return queueMessage(text) sending = true setBusy(true, 'Sending') try { await Promise.all(pending.map((p) => p.ready)) const sent = pending.filter((p) => p.data) if (!text && !sent.length) return setBusy(false, '') const body = { text } if (sent.length) body.images = sent.map((p) => ({ data: p.data, mimeType: p.mimeType })) if (thread) body.thread = thread if (picker && picker.dataset.value) body.computer = picker.dataset.value if (approvalPicker) body.approval = approvalPicker.dataset.value if (!thread && pickedModel) { body.model = pickedModel body.reasoning = pickedReasoning } const r = await api('/send', body) pickedModel = '' input.value = '' grow() canSend() if (sent.length) { const pics = el('div', 'pics') for (const p of sent) { const img = pics.appendChild(el('img')) img.src = p.url img.alt = 'Image sent with the message' } add(pics) pending = pending.filter((p) => !sent.includes(p)) renderTray() } if (text) { const msg = el('div', 'msg user') msg.appendChild(el('span', 'who', 'You')) msg.appendChild(document.createTextNode(text)) add(msg) } window.scrollTo(0, document.body.scrollHeight) run = r.run since = r.since || 0 if (r.thread !== thread) { thread = r.thread root.dataset.thread = thread history.replaceState(null, '', base + '?thread=' + encodeURIComponent(thread)) listThread(thread, text || 'Image') } setBusy(true, agentName + ' is working') poll() } catch (err) { setBusy(false, '') add(el('p', 'error', upper(err.message))) } finally { sending = false canSend() } }) // The pencil beside a thread, as chatPage draws it. function renameButton(rkey, name) { const b = el('button', 'rename') b.type = 'button' b.dataset.thread = rkey b.dataset.name = name b.title = 'Rename' b.setAttribute('aria-label', 'Rename thread: ' + name) const ns = 'http://www.w3.org/2000/svg' const svg = document.createElementNS(ns, 'svg') for (const [k, v] of Object.entries({ viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' })) svg.setAttribute(k, v) for (const d of ['M4 20h4l10-10a2.8 2.8 0 0 0-4-4L4 16z', 'M13.5 6.5l4 4']) { const path = document.createElementNS(ns, 'path') path.setAttribute('d', d) svg.appendChild(path) } b.appendChild(svg) return b } // The bar over the chat names the open thread; its name opens to a text field, as in the lists. const bar = document.querySelector('.thread-bar') const titleButton = bar && bar.querySelector('.title-edit') function nameBar(rkey, name) { if (!titleButton || titleButton.dataset.thread !== rkey) return titleButton.textContent = name titleButton.dataset.name = name } /** A thread got a new name (here, or the agent's rename seen in a run): show it in the bar and in every list. */ function renamed(rkey, name) { nameBar(rkey, name) for (const b of document.querySelectorAll('.threads .rename')) { if (b.dataset.thread !== rkey || b.dataset.name === name) continue const a = b.parentElement.querySelector('a') if (a) { ;(a.querySelector('.t') || a).textContent = name if (a.title) a.title = name } b.dataset.name = name b.setAttribute('aria-label', 'Rename thread: ' + name) } } if (titleButton) titleButton.addEventListener('click', () => { const rkey = titleButton.dataset.thread if (!rkey) return const before = titleButton.dataset.name || titleButton.textContent || '' const field = el('input', 'title-input') field.type = 'text' field.value = before field.maxLength = 200 field.setAttribute('aria-label', 'Thread name') let done = false const finish = async (save) => { if (done) return done = true const title = field.value.replace(/\s+/g, ' ').trim() field.replaceWith(titleButton) if (!save || !title || title === before) return titleButton.focus() try { const saved = await api('/threads/rename', { thread: rkey, title }) renamed(rkey, saved.title) } catch (err) { status.textContent = upper(err.message) } } titleButton.replaceWith(field) field.focus() field.select() field.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); void finish(true) } if (e.key === 'Escape') { e.preventDefault(); void finish(false) } }) field.addEventListener('blur', () => void finish(true)) }) // A thread the first message just started: listed at the top of the thread lists, and marked as the one open. function listThread(rkey, text) { const href = base + '?thread=' + encodeURIComponent(rkey) const preview = text.replace(/\s+/g, ' ').trim().slice(0, 80) for (const n of document.querySelectorAll('.app-nav .new, .threads li.new')) n.classList.remove('on') for (const n of document.querySelectorAll('.app-nav .new[aria-current]')) n.removeAttribute('aria-current') for (const list of document.querySelectorAll('ul.threads:not(.rest)')) { for (const li of list.querySelectorAll('li.on')) li.classList.remove('on') for (const a of list.querySelectorAll('a[aria-current]')) a.removeAttribute('aria-current') const li = el('li', 'on') const a = el('a') a.href = href if (list.closest('.app-nav')) { a.title = preview a.setAttribute('aria-current', 'page') a.appendChild(el('span', 't', preview)) const time = el('time', '', 'now') time.dateTime = new Date().toISOString() a.appendChild(time) } else { a.textContent = preview } li.appendChild(a) li.appendChild(renameButton(rkey, preview)) const first = list.querySelector('li.new') let after = first if (list.closest('.app-nav')) { after = list.querySelector('li.group[data-group=day]') if (!after) { after = el('li', 'group', 'Past day') after.dataset.group = 'day' after.setAttribute('aria-hidden', 'true') list.insertBefore(after, list.firstChild) } } list.insertBefore(li, after ? after.nextSibling : list.firstChild) } if (bar && titleButton) { titleButton.dataset.thread = rkey nameBar(rkey, preview) bar.hidden = false } } // The open thread, scrolled into view in the panel when the list is long. const openThread = document.querySelector('.app-nav li.on') if (openThread) openThread.scrollIntoView({ block: 'nearest' }) // The open question: ⌘↵ (Ctrl+Enter) allows it, Esc denies it. Plain Enter only ever sends. const openQuestion = () => [...log.querySelectorAll('.approval')].find((b) => b.querySelector('.buttons button:not(:disabled)')) document.addEventListener('keydown', (ev) => { if (ev.isComposing) return const box = openQuestion() if (!box) return if (ev.key === 'Enter' && (ev.metaKey || ev.ctrlKey)) { ev.preventDefault() ev.stopImmediatePropagation() box.querySelector('button[data-approve=yes]')?.click() } else if (ev.key === 'Escape' && !document.querySelector('form.composer .menu:not([hidden])') && !(document.activeElement === input && input.value)) { ev.preventDefault() box.querySelector('button[data-approve=no]')?.click() } }, true) input.addEventListener('keydown', (ev) => { if (ev.key === 'Enter' && (ev.metaKey || ev.ctrlKey)) return if (ev.key === 'Enter' && !ev.shiftKey && !ev.isComposing) { ev.preventDefault() form.requestSubmit() } }) const grow = () => { // Measured in the one-row layout: text that won't fit there moves to its own line. const box = document.getElementById('card') box.classList.remove('multi') input.style.height = '' if (input.scrollHeight > 40) box.classList.add('multi') input.style.height = '' input.style.height = Math.min(input.scrollHeight, 224) + 'px' input.style.overflowY = input.scrollHeight > 224 ? 'auto' : 'hidden' } input.addEventListener('input', () => { grow() canSend() }) canSend() // The pill squares up once it is taller than one row (2.25rem buttons and .3rem padding, about 43px). const card = document.getElementById('card') if (window.ResizeObserver) new ResizeObserver(() => card.classList.toggle('tall', card.offsetHeight > 52)).observe(card) // The whole box is the place to type: a click on its padding focuses the text. card.addEventListener('click', (ev) => { if (!ev.target.closest('button, .menu')) input.focus() }) for (const m of log.querySelectorAll('.msg.assistant')) render(m, m.textContent) if (run) { setBusy(true, pendingApproval() ? 'Waiting for you' : agentName + ' is working') poll() } else { window.scrollTo(0, document.body.scrollHeight) watchTasks() } })() ` /** The script's address carries a hash of it, so a changed script isn't served from an old cache. */ export const CHAT_JS_HREF = `/chat.js?v=${crypto.createHash('sha256').update(CHAT_JS).digest('hex').slice(0, 10)}`