aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / public / js / allen.js
| 1 | /* Aien chat client. |
| 2 | * |
| 3 | * Generated by om/allen-page/allen-js.om; never hand-edit. The page skeleton is |
| 4 | * generated by om/allen-page/allen.om. Model and network text only ever reaches |
| 5 | * textContent, a text node, or the srcdoc of a frame sandboxed to allow-scripts |
| 6 | * alone: nothing from the network is parsed as markup in this document. The |
| 7 | * conversation lives in this closure only: no storage, no cookies. |
| 8 | */ |
| 9 | (() => { |
| 10 | 'use strict'; |
| 11 | const root = document.getElementById('allen'); |
| 12 | if (!root) return; |
| 13 | const byId = id => document.getElementById(id); |
| 14 | const log = byId('allen-log'); |
| 15 | const form = byId('allen-form'); |
| 16 | const input = byId('allen-input'); |
| 17 | const sendButton = byId('allen-send'); |
| 18 | const stopButton = byId('allen-stop'); |
| 19 | const status = byId('allen-status'); |
| 20 | const newButton = byId('allen-new'); |
| 21 | const examples = byId('allen-examples'); |
| 22 | const speed = { model: byId('allen-model'), queue: byId('allen-queue'), ttft: byId('allen-ttft'), first: byId('allen-first'), rate: byId('allen-rate'), tokens: byId('allen-tokens'), server: byId('allen-server') }; |
| 23 | /* The gateway is always same origin, under /aien/api/ (the hub also keeps /allen/api/); local development |
| 24 | serves the page and proxies the API on one origin (dev_proxy.py). */ |
| 25 | const CHAT = '/aien/api/chat'; |
| 26 | const OMEGA = '/aien/api/omega'; |
| 27 | const LIMIT = { count: 24, each: 4000, total: 16000, source: 16384 }; |
| 28 | const CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; form-action 'none'; base-uri 'none'"; |
| 29 | const SANDBOX = 'allow-scripts'; |
| 30 | const CALL_MS = 3000; |
| 31 | const SUBMIT = '/aien/api/submit'; |
| 32 | const STATUS = '/aien/api/status/'; |
| 33 | const INTRODUCE = '/aien/api/introduce'; |
| 34 | const FORGET = '/aien/api/forget'; |
| 35 | const PRIVACY_MAIL = 'aien@aienos.com'; |
| 36 | const POLL_MS = 3000; |
| 37 | const POLL_LIMIT = 120000; |
| 38 | const REVIEW_HOST = 'aien-dev.github.io/omega-projects/projects/'; |
| 39 | const PROJECTS = '/aien/api/projects/'; |
| 40 | const GALLERY = '/aien/api/gallery'; |
| 41 | const FORGET_ME = '/aien/api/forget-me'; |
| 42 | const KEY_NAME = 'allen.key'; |
| 43 | const KEY_PATTERN = /^[0-9a-f]{32}$/; |
| 44 | const VOICE_DIR = '/aien/voice/'; |
| 45 | const RELAY = '/aien/api/relay'; |
| 46 | const PRESENCE = '/aien/api/presence'; |
| 47 | const HANDOFF = '/aien/api/handoff'; |
| 48 | const SESSION = '/aien/api/session'; |
| 49 | const SAY = '/aien/api/say'; |
| 50 | const PRESENCE_MS = 60000; |
| 51 | /* Drake's greetings, byte for byte the gateway's opening for each kind of |
| 52 | start, and the line a returning visitor's page sends first. */ |
| 53 | const GREETING_REMEMBER = "Hi, I'm Aien (you say it like Ian). It's nice to meet you! You don't have to tell me your name, but if you do, that would be super awesome and we could chat over time. When you come back, I can remember who you are and we can pick up where we left off. We can talk about all kinds of good things in the universe."; |
| 54 | const GREETING_ANONYMOUS = "Hi, I'm Aien (you say it like Ian). It's nice to meet you! We can talk about all kinds of good things in the universe."; |
| 55 | const BACK_LINE = '(I am back.)'; |
| 56 | const entry = new URLSearchParams(location.search).get('mode'); |
| 57 | const turns = []; |
| 58 | const runners = new Set(); |
| 59 | let active = null; |
| 60 | let epoch = 0; |
| 61 | let countdown = 0; |
| 62 | /* What the visitor said they are, from the greeting buttons only; kept in |
| 63 | this closure and sent to the model as one short first line. */ |
| 64 | let kind = ''; |
| 65 | let choices = null; |
| 66 | /* A fresh random id per page load and per new conversation, sent with chat |
| 67 | only when this browser holds an Aien key. */ |
| 68 | let conversation = ''; |
| 69 | /* The transport as events for a page UI (window.allen.on). Every detail is |
| 70 | a frozen plain object; its strings are network or model text and belong |
| 71 | in textContent only. A listener that throws never stops the chat. */ |
| 72 | const listeners = new Map(); |
| 73 | function emit(type, detail) { |
| 74 | const set = listeners.get(type); |
| 75 | if (!set) return; |
| 76 | const frozen = Object.freeze({ ...detail }); |
| 77 | for (const fn of [...set]) { |
| 78 | try { |
| 79 | fn(frozen); |
| 80 | } catch (_) { |
| 81 | /* Ignore a broken listener. */ |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | function on(type, fn) { |
| 86 | if (typeof type !== 'string' || typeof fn !== 'function') throw new TypeError('allen.on(type, fn)'); |
| 87 | if (!listeners.has(type)) listeners.set(type, new Set()); |
| 88 | listeners.get(type).add(fn); |
| 89 | return () => listeners.get(type).delete(fn); |
| 90 | } |
| 91 | function el(tag, className, text) { |
| 92 | const node = document.createElement(tag); |
| 93 | if (className) node.className = className; |
| 94 | if (text !== undefined) node.textContent = text; |
| 95 | return node; |
| 96 | } |
| 97 | function setText(node, value) { |
| 98 | if (node && node.textContent !== value) node.textContent = value; |
| 99 | } |
| 100 | function button(label, handler) { |
| 101 | const node = el('button', 'allen-tool', label); |
| 102 | node.type = 'button'; |
| 103 | node.addEventListener('click', handler); |
| 104 | return node; |
| 105 | } |
| 106 | function ms(value) { |
| 107 | return Number.isFinite(value) ? `${Math.round(value)} ms` : '-'; |
| 108 | } |
| 109 | function count(value) { |
| 110 | return Number.isSafeInteger(value) && value >= 0 ? String(value) : '?'; |
| 111 | } |
| 112 | /* Contract limits count characters; never leave half a surrogate pair behind. */ |
| 113 | function cut(text, max) { |
| 114 | if (text.length <= max) return text; |
| 115 | const head = text.slice(0, max); |
| 116 | return /[\ud800-\udbff]$/.test(head) ? head.slice(0, -1) : head; |
| 117 | } |
| 118 | /* The newest turns that fit the gateway: at most LIMIT.count messages, each at |
| 119 | most LIMIT.each characters, LIMIT.total in all, starting with a user turn. */ |
| 120 | function fit(list) { |
| 121 | const out = list.map(turn => ({ role: turn.role, content: cut(turn.content, LIMIT.each) })); |
| 122 | const lead = kind ? `I am ${kind === 'agent' ? 'an agent' : 'a human'}.\n` : ''; |
| 123 | let total = out.reduce((sum, turn) => sum + turn.content.length, 0) + lead.length; |
| 124 | while (out.length > 1 && (out.length > LIMIT.count || total > LIMIT.total || out[0].role !== 'user')) { |
| 125 | total -= out.shift().content.length; |
| 126 | } |
| 127 | if (lead) out[0].content = cut(lead + out[0].content, LIMIT.each); |
| 128 | return out; |
| 129 | } |
| 130 | /* Incremental server-sent events: a chunk may end anywhere, even inside a line. */ |
| 131 | function sse(onEvent) { |
| 132 | let carry = ''; |
| 133 | let name = ''; |
| 134 | let data = []; |
| 135 | function line(text) { |
| 136 | if (text === '') { |
| 137 | if (data.length) onEvent(name || 'message', data.join('\n')); |
| 138 | name = ''; |
| 139 | data = []; |
| 140 | return; |
| 141 | } |
| 142 | if (text.startsWith(':')) return; |
| 143 | const colon = text.indexOf(':'); |
| 144 | const field = colon < 0 ? text : text.slice(0, colon); |
| 145 | let value = colon < 0 ? '' : text.slice(colon + 1); |
| 146 | if (value.startsWith(' ')) value = value.slice(1); |
| 147 | if (field === 'event') name = value; |
| 148 | else if (field === 'data') data.push(value); |
| 149 | } |
| 150 | return { |
| 151 | feed(chunk) { |
| 152 | carry += chunk; |
| 153 | let start = 0; |
| 154 | for (;;) { |
| 155 | const end = carry.indexOf('\n', start); |
| 156 | if (end < 0) break; |
| 157 | line(carry.slice(start, end).replace(/\r$/, '')); |
| 158 | start = end + 1; |
| 159 | } |
| 160 | carry = carry.slice(start); |
| 161 | }, |
| 162 | end() { |
| 163 | if (carry) line(carry.replace(/\r$/, '')); |
| 164 | carry = ''; |
| 165 | line(''); |
| 166 | }, |
| 167 | }; |
| 168 | } |
| 169 | /* Inline code and bold only; every piece becomes a text node. */ |
| 170 | function inline(parent, text) { |
| 171 | let at = 0; |
| 172 | for (const match of text.matchAll(/`([^`\n]+)`|\*\*([^*\n]+)\*\*/g)) { |
| 173 | if (match.index > at) parent.append(document.createTextNode(text.slice(at, match.index))); |
| 174 | parent.append(match[1] !== undefined ? el('code', '', match[1]) : el('strong', '', match[2])); |
| 175 | at = match.index + match[0].length; |
| 176 | } |
| 177 | if (at < text.length) parent.append(document.createTextNode(text.slice(at))); |
| 178 | } |
| 179 | /* Streams a reply into nodes. Each token is appended to the text node of the |
| 180 | line being written; a finished line is re-rendered as paragraph text, a |
| 181 | heading, or a line of a fenced code block. A line that may still become a |
| 182 | fence is held back until it is decided, so fences never flash as text. */ |
| 183 | function renderer(body) { |
| 184 | const st = { block: null, sep: null, tail: null, code: null, codeText: null, lang: '', wrap: null, bar: null, pre: null, line: '', held: false, text: '' }; |
| 185 | const opening = /^ {0,3}```\s*([A-Za-z0-9_+.-]*)\s*$/; |
| 186 | const closing = /^ {0,3}```\s*$/; |
| 187 | const maybeOpening = /^ {0,3}`{1,3}[A-Za-z0-9_+.-]*$/; |
| 188 | const maybeClosing = /^ {0,3}`{1,3}$/; |
| 189 | function closeParagraph() { |
| 190 | if (st.block && !st.block.firstChild) st.block.remove(); |
| 191 | st.block = null; |
| 192 | } |
| 193 | function tailNode() { |
| 194 | if (st.tail) return st.tail; |
| 195 | st.tail = document.createTextNode(''); |
| 196 | if (st.code) { |
| 197 | st.code.append(st.tail); |
| 198 | } else { |
| 199 | if (!st.block) { |
| 200 | st.block = el('p', 'allen-p'); |
| 201 | body.append(st.block); |
| 202 | } else if (st.block.firstChild) { |
| 203 | st.sep = document.createTextNode('\n'); |
| 204 | st.block.append(st.sep); |
| 205 | } |
| 206 | st.block.append(st.tail); |
| 207 | } |
| 208 | return st.tail; |
| 209 | } |
| 210 | function retract(keepSep) { |
| 211 | if (st.tail) st.tail.remove(); |
| 212 | if (st.sep && !keepSep) st.sep.remove(); |
| 213 | st.tail = null; |
| 214 | st.sep = null; |
| 215 | } |
| 216 | function openCode(lang) { |
| 217 | st.wrap = el('div', 'allen-code'); |
| 218 | st.bar = el('div', 'allen-tools'); |
| 219 | st.bar.append(el('span', 'allen-lang', lang || 'text')); |
| 220 | st.pre = el('pre'); |
| 221 | st.code = el('code'); |
| 222 | st.codeText = document.createTextNode(''); |
| 223 | st.code.append(st.codeText); |
| 224 | st.pre.append(st.code); |
| 225 | st.wrap.append(st.bar, st.pre); |
| 226 | body.append(st.wrap); |
| 227 | st.lang = lang; |
| 228 | } |
| 229 | function closeCode() { |
| 230 | retract(false); |
| 231 | const source = st.codeText.data.replace(/\n$/, ''); |
| 232 | tools(st.lang, source, st.wrap, st.bar, st.pre); |
| 233 | emit('card', { type: st.lang, source, node: st.wrap }); |
| 234 | st.code = null; |
| 235 | st.codeText = null; |
| 236 | } |
| 237 | function commit() { |
| 238 | const line = st.line; |
| 239 | st.line = ''; |
| 240 | st.held = false; |
| 241 | if (st.code) { |
| 242 | retract(false); |
| 243 | if (closing.test(line)) closeCode(); |
| 244 | else st.codeText.appendData(line + '\n'); |
| 245 | return; |
| 246 | } |
| 247 | const open = opening.exec(line); |
| 248 | const heading = /^#{1,4}\s+(.*)$/.exec(line); |
| 249 | if (open || heading || !line.trim()) { |
| 250 | retract(false); |
| 251 | closeParagraph(); |
| 252 | if (open) { |
| 253 | openCode(open[1].toLowerCase()); |
| 254 | } else if (heading) { |
| 255 | const node = el('p', 'allen-h'); |
| 256 | inline(node, heading[1]); |
| 257 | body.append(node); |
| 258 | } |
| 259 | return; |
| 260 | } |
| 261 | tailNode(); |
| 262 | retract(true); |
| 263 | inline(st.block, line); |
| 264 | } |
| 265 | return { |
| 266 | push(token) { |
| 267 | st.text += token; |
| 268 | token.split('\n').forEach((piece, index) => { |
| 269 | if (index > 0) commit(); |
| 270 | if (!piece) return; |
| 271 | st.line += piece; |
| 272 | if ((st.code ? maybeClosing : maybeOpening).test(st.line)) { |
| 273 | st.held = true; |
| 274 | } else if (st.held) { |
| 275 | st.held = false; |
| 276 | tailNode().data = st.line; |
| 277 | } else { |
| 278 | tailNode().appendData(piece); |
| 279 | } |
| 280 | }); |
| 281 | }, |
| 282 | finish() { |
| 283 | if (st.line) commit(); |
| 284 | if (st.code) closeCode(); |
| 285 | retract(false); |
| 286 | closeParagraph(); |
| 287 | return st.text; |
| 288 | }, |
| 289 | }; |
| 290 | } |
| 291 | /* Buttons under a finished fenced block: html runs in a sandbox, omega |
| 292 | compiles to WebAssembly, both download and publish; issue and introduce |
| 293 | blocks become cards that act only on a visitor's click. */ |
| 294 | function tools(lang, source, wrap, bar, pre) { |
| 295 | const type = /^html?$/.test(lang) ? 'html' : /^(omega|om)$/.test(lang) ? 'omega' : /^(issue|introduce|relay)$/.test(lang) ? lang : ''; |
| 296 | const out = el('div', 'allen-out'); |
| 297 | if (type === 'issue' || type === 'introduce' || type === 'relay') { |
| 298 | pre.hidden = true; |
| 299 | wrap.append(out); |
| 300 | if (type === 'issue') issueCard(cardFields(source), out); |
| 301 | else if (type === 'relay') relayCard(cardFields(source), out); |
| 302 | else out.append(remembered ? introCard(introLines(cardFields(source).fields)) : rememberOffer(introLines(cardFields(source).fields))); |
| 303 | return; |
| 304 | } |
| 305 | let view = null; |
| 306 | const showCode = shown => { |
| 307 | pre.hidden = !shown; |
| 308 | if (view) view.setAttribute('aria-pressed', String(shown)); |
| 309 | }; |
| 310 | const project = type ? makeProject(type, source) : null; |
| 311 | if (type === 'html') { |
| 312 | bar.append(button('Run', () => { |
| 313 | runHtml(source, out); |
| 314 | showCode(false); |
| 315 | })); |
| 316 | } |
| 317 | if (type === 'omega') { |
| 318 | bar.append(button('Compile and run', event => compileOmega(source, out, event.currentTarget, project))); |
| 319 | } |
| 320 | if (type) { |
| 321 | view = button('Code', () => showCode(pre.hidden)); |
| 322 | view.setAttribute('aria-pressed', 'true'); |
| 323 | bar.append(view); |
| 324 | } |
| 325 | const copy = button('Copy', () => copyText(source, copy)); |
| 326 | bar.append(copy); |
| 327 | if (project) { |
| 328 | const more = el('div', 'allen-more'); |
| 329 | const pub = el('div', 'allen-pub'); |
| 330 | downloads(project, more, pub); |
| 331 | wrap.append(more, pub); |
| 332 | } |
| 333 | wrap.append(out); |
| 334 | } |
| 335 | /* One block is one project: its main file, a README and, for Omega, the |
| 336 | wasm once it has been compiled. */ |
| 337 | function slugify(text) { |
| 338 | return text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+/, '').slice(0, 40).replace(/-+$/, ''); |
| 339 | } |
| 340 | function makeProject(type, source) { |
| 341 | if (type === 'html') { |
| 342 | const named = /<title[^>]*>([^<]{1,80})<\/title>/i.exec(source); |
| 343 | const title = named && named[1].trim() ? named[1].trim() : 'Aien app'; |
| 344 | return { type, title, base: slugify(title) || 'allen-app', main: 'index.html', source, wasm: null, functions: [], wasmButton: null, htmlButton: null, pin: '' }; |
| 345 | } |
| 346 | const first = /^\s*fn\s+([A-Za-z0-9_]+)/m.exec(source); |
| 347 | const title = first ? first[1] : 'program'; |
| 348 | const base = slugify(title) || 'program'; |
| 349 | return { type, title, base, main: `${base}.om`, source, wasm: null, functions: [], wasmButton: null, htmlButton: null, pin: '' }; |
| 350 | } |
| 351 | function signature(fn) { |
| 352 | const params = Array.isArray(fn.params) ? fn.params : []; |
| 353 | return `${fn.name}(${params.map(p => `${p.name}: ${p.type}`).join(', ')}) to ${typeof fn.ret === 'string' ? fn.ret : 'void'}`; |
| 354 | } |
| 355 | function readme(project, description) { |
| 356 | const lines = [`# ${project.title}`, '', description || "Written by Aien, Drake's AI, at https://www.aienos.com/aien/.", '']; |
| 357 | if (project.type === 'html') { |
| 358 | lines.push('Open index.html in a browser. It is one self-contained file.'); |
| 359 | } else { |
| 360 | lines.push(`${project.main} is scalar Omega in IR mode. To build it with the pinned seeded compiler and the IR to WebAssembly translator:`, '', '```sh', `{ printf 'ir\\n'; cat ${project.main}; } | omc > ${project.base}.ir`, `irwasm < ${project.base}.ir > ${project.base}.wasm`, '```'); |
| 361 | if (project.functions.length) { |
| 362 | lines.push('', `${project.base}.wasm has no imports. It exports:`, ''); |
| 363 | for (const fn of project.functions) lines.push(`- ${signature(fn)}`); |
| 364 | } |
| 365 | if (project.wasm) lines.push('', `${project.base}.html runs it in any browser with no install and no network: open it and call a function.`); |
| 366 | } |
| 367 | lines.push('', 'Learn about Omega: https://www.aienos.com/omega/', ''); |
| 368 | return lines.join('\n'); |
| 369 | } |
| 370 | const CRC_TABLE = (() => { |
| 371 | const table = new Uint32Array(256); |
| 372 | for (let n = 0; n < 256; n += 1) { |
| 373 | let c = n; |
| 374 | for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; |
| 375 | table[n] = c >>> 0; |
| 376 | } |
| 377 | return table; |
| 378 | })(); |
| 379 | function crc32(bytes) { |
| 380 | let c = 0xffffffff; |
| 381 | for (let i = 0; i < bytes.length; i += 1) c = CRC_TABLE[(c ^ bytes[i]) & 255] ^ (c >>> 8); |
| 382 | return (c ^ 0xffffffff) >>> 0; |
| 383 | } |
| 384 | /* A store-only zip: local headers, the bytes, a central directory and the |
| 385 | end record, names flagged UTF-8, every entry with its CRC-32. */ |
| 386 | function zip(files) { |
| 387 | const encoder = new TextEncoder(); |
| 388 | const now = new Date(); |
| 389 | const time = (now.getHours() << 11) | (now.getMinutes() << 5) | Math.floor(now.getSeconds() / 2); |
| 390 | const date = ((Math.max(1980, now.getFullYear()) - 1980) << 9) | ((now.getMonth() + 1) << 5) | now.getDate(); |
| 391 | const parts = []; |
| 392 | const central = []; |
| 393 | let offset = 0; |
| 394 | for (const file of files) { |
| 395 | const name = encoder.encode(file.name); |
| 396 | const data = file.data; |
| 397 | const crc = crc32(data); |
| 398 | const local = new DataView(new ArrayBuffer(30)); |
| 399 | local.setUint32(0, 0x04034b50, true); |
| 400 | local.setUint16(4, 20, true); |
| 401 | local.setUint16(6, 0x0800, true); |
| 402 | local.setUint16(8, 0, true); |
| 403 | local.setUint16(10, time, true); |
| 404 | local.setUint16(12, date, true); |
| 405 | local.setUint32(14, crc, true); |
| 406 | local.setUint32(18, data.length, true); |
| 407 | local.setUint32(22, data.length, true); |
| 408 | local.setUint16(26, name.length, true); |
| 409 | local.setUint16(28, 0, true); |
| 410 | parts.push(new Uint8Array(local.buffer), name, data); |
| 411 | const entry = new DataView(new ArrayBuffer(46)); |
| 412 | entry.setUint32(0, 0x02014b50, true); |
| 413 | entry.setUint16(4, 20, true); |
| 414 | entry.setUint16(6, 20, true); |
| 415 | entry.setUint16(8, 0x0800, true); |
| 416 | entry.setUint16(10, 0, true); |
| 417 | entry.setUint16(12, time, true); |
| 418 | entry.setUint16(14, date, true); |
| 419 | entry.setUint32(16, crc, true); |
| 420 | entry.setUint32(20, data.length, true); |
| 421 | entry.setUint32(24, data.length, true); |
| 422 | entry.setUint16(28, name.length, true); |
| 423 | entry.setUint32(42, offset, true); |
| 424 | central.push(new Uint8Array(entry.buffer), name); |
| 425 | offset += 30 + name.length + data.length; |
| 426 | } |
| 427 | const size = central.reduce((sum, part) => sum + part.length, 0); |
| 428 | const end = new DataView(new ArrayBuffer(22)); |
| 429 | end.setUint32(0, 0x06054b50, true); |
| 430 | end.setUint16(8, files.length, true); |
| 431 | end.setUint16(10, files.length, true); |
| 432 | end.setUint32(12, size, true); |
| 433 | end.setUint32(16, offset, true); |
| 434 | const all = [...parts, ...central, new Uint8Array(end.buffer)]; |
| 435 | const out = new Uint8Array(all.reduce((sum, part) => sum + part.length, 0)); |
| 436 | let at = 0; |
| 437 | for (const part of all) { |
| 438 | out.set(part, at); |
| 439 | at += part.length; |
| 440 | } |
| 441 | return out; |
| 442 | } |
| 443 | /* Downloads are made here, in the browser: a Blob and an anchor with download. */ |
| 444 | function save(name, data, type) { |
| 445 | const url = URL.createObjectURL(new Blob([data], { type })); |
| 446 | const anchor = document.createElement('a'); |
| 447 | anchor.href = url; |
| 448 | anchor.download = name; |
| 449 | anchor.rel = 'noopener'; |
| 450 | anchor.hidden = true; |
| 451 | document.body.append(anchor); |
| 452 | anchor.click(); |
| 453 | anchor.remove(); |
| 454 | setTimeout(() => URL.revokeObjectURL(url), 1000); |
| 455 | } |
| 456 | function projectFiles(project) { |
| 457 | const encoder = new TextEncoder(); |
| 458 | const files = [{ name: project.main, data: encoder.encode(project.source) }]; |
| 459 | if (project.wasm) { |
| 460 | files.push({ name: `${project.base}.wasm`, data: project.wasm }); |
| 461 | files.push({ name: `${project.base}.html`, data: encoder.encode(standalone(project)) }); |
| 462 | } |
| 463 | files.push({ name: 'README.md', data: encoder.encode(readme(project)) }); |
| 464 | return files; |
| 465 | } |
| 466 | /* The first action is Save or publish on GitHub: the project's home in |
| 467 | the public aien-dev/omega-projects repo, where anyone can read it. The |
| 468 | local copies follow. For Omega the first download is <base>.html, shown |
| 469 | once Compile and run has succeeded: the one file a visitor can open and |
| 470 | run. <base>.om.txt is the source for any text editor; <base>.om stays the |
| 471 | name the README, the zip and a published project use. */ |
| 472 | function downloads(project, row, pub) { |
| 473 | const github = button('Save or publish on GitHub', () => publishForm(project, pub)); |
| 474 | github.classList.add('allen-github'); |
| 475 | github.title = 'Saves this project to your home in the public aien-dev/omega-projects repo on GitHub; publishing asks Drake to review it'; |
| 476 | row.append(github, el('span', 'allen-more-label', 'or download a copy')); |
| 477 | if (project.type === 'omega') { |
| 478 | project.htmlButton = button(`${project.base}.html`, () => { |
| 479 | if (project.wasm) save(`${project.base}.html`, standalone(project), 'text/html;charset=utf-8'); |
| 480 | }); |
| 481 | project.htmlButton.hidden = true; |
| 482 | project.htmlButton.title = 'One file that runs this program in any browser, with no install'; |
| 483 | row.append(project.htmlButton); |
| 484 | } |
| 485 | row.append(button(project.main, () => save(project.main, project.source, project.type === 'html' ? 'text/html' : 'text/plain'))); |
| 486 | if (project.type === 'omega') { |
| 487 | const text = button(`${project.base}.om.txt`, () => save(`${project.base}.om.txt`, sourceText(project), 'text/plain;charset=utf-8')); |
| 488 | text.title = 'The Omega source as plain text, for any text editor'; |
| 489 | row.append(text); |
| 490 | project.wasmButton = button(`${project.base}.wasm`, () => { |
| 491 | if (project.wasm) save(`${project.base}.wasm`, project.wasm, 'application/wasm'); |
| 492 | }); |
| 493 | project.wasmButton.disabled = true; |
| 494 | project.wasmButton.title = 'Compile it first'; |
| 495 | row.append(project.wasmButton); |
| 496 | } |
| 497 | row.append(button('README.md', () => save('README.md', readme(project), 'text/markdown'))); |
| 498 | row.append(button(`${project.base}.zip`, () => save(`${project.base}.zip`, zip(projectFiles(project)), 'application/zip'))); |
| 499 | } |
| 500 | /* What a visitor keeps. The source download is <base>.om.txt, so any text |
| 501 | editor opens it; its note lines are Omega comments, so omc still takes the |
| 502 | file as it is. The runnable download is <base>.html: one file holding the |
| 503 | source as text, the compiled wasm as base64 and this page's own runner |
| 504 | (argument, shown, workerMain), under a policy that allows no network. */ |
| 505 | function sourceText(project) { |
| 506 | const name = project.base; |
| 507 | const head = [ |
| 508 | `note ${name}.om.txt: Omega source code as plain text. Aien wrote it at https://www.aienos.com/aien/`, |
| 509 | "note Omega is Drake Stapleton's programming language for programs written by AI: https://www.aienos.com/omega/", |
| 510 | `note To run it with no tools, download ${name}.html from the same page after Compile and run, then open it in any browser.`, |
| 511 | `note To build it yourself, save this file as ${name}.om and use the seeded compiler omc and the IR to WebAssembly`, |
| 512 | 'note translator irwasm, both from https://interplane.io/drakestapleton/omega-mv/tree/main/seed :', |
| 513 | `note { printf 'ir\\n'; cat ${name}.om; } | omc > ${name}.ir`, |
| 514 | `note irwasm < ${name}.ir > ${name}.wasm`, |
| 515 | 'note Lines that start with note are comments. The language guide:', |
| 516 | 'note https://interplane.io/drakestapleton/omega-mv/blob/main/docs/one_layer/OMEGESE.md', |
| 517 | '', |
| 518 | ]; |
| 519 | return head.join('\n') + project.source + (project.source.endsWith('\n') ? '' : '\n'); |
| 520 | } |
| 521 | function escapeHtml(text) { |
| 522 | return String(text).replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`); |
| 523 | } |
| 524 | function base64(bytes) { |
| 525 | let text = ''; |
| 526 | for (let i = 0; i < bytes.length; i += 8192) text += String.fromCharCode(...bytes.subarray(i, i + 8192)); |
| 527 | return btoa(text); |
| 528 | } |
| 529 | function standalone(project) { |
| 530 | const types = Object.entries(TYPES).map(([type, range]) => `${type}: { wide: ${range.wide}, min: ${range.min}n, max: ${range.max}n }`).join(', '); |
| 531 | const list = project.functions.map(fn => ({ name: fn.name, params: (Array.isArray(fn.params) ? fn.params : []).map(p => ({ name: String(p && p.name), type: String(p && p.type) })), ret: typeof fn.ret === 'string' ? fn.ret : 'void' })); |
| 532 | const policy = "default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval'; worker-src blob:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"; |
| 533 | const script = `(() => { |
| 534 | 'use strict'; |
| 535 | const CALL_MS = ${CALL_MS}; |
| 536 | const TYPES = { ${types} }; |
| 537 | const FUNCTIONS = ${JSON.stringify(list).replace(/</g, '\\u003c')}; |
| 538 | const WASM = '${base64(project.wasm)}'; |
| 539 | const known = ${known}; |
| 540 | ${argument} |
| 541 | ${shown} |
| 542 | ${signature} |
| 543 | ${workerMain} |
| 544 | const engine = document.getElementById('engine'); |
| 545 | const box = document.getElementById('fns'); |
| 546 | let module = null; |
| 547 | let worker = null; |
| 548 | let local = null; |
| 549 | let next = 0; |
| 550 | const pending = new Map(); |
| 551 | function stop() { |
| 552 | if (worker) worker.terminate(); |
| 553 | worker = null; |
| 554 | for (const job of pending.values()) { |
| 555 | clearTimeout(job.timer); |
| 556 | job.done({ ok: false, message: 'the runner was reset' }); |
| 557 | } |
| 558 | pending.clear(); |
| 559 | } |
| 560 | function start() { |
| 561 | try { |
| 562 | const url = URL.createObjectURL(new Blob([\`(\${workerMain.toString()})();\`], { type: 'text/javascript' })); |
| 563 | worker = new Worker(url); |
| 564 | URL.revokeObjectURL(url); |
| 565 | } catch (_) { |
| 566 | worker = null; |
| 567 | return false; |
| 568 | } |
| 569 | worker.onmessage = event => { |
| 570 | const job = pending.get(event.data.id); |
| 571 | if (!job) return; |
| 572 | pending.delete(event.data.id); |
| 573 | clearTimeout(job.timer); |
| 574 | job.done(event.data); |
| 575 | }; |
| 576 | worker.onerror = event => { |
| 577 | event.preventDefault(); |
| 578 | stop(); |
| 579 | }; |
| 580 | worker.postMessage({ module }); |
| 581 | return true; |
| 582 | } |
| 583 | async function run(name, args) { |
| 584 | if (!local && !worker && !start()) { |
| 585 | local = await WebAssembly.instantiate(module, {}); |
| 586 | engine.textContent = 'Running on this page: this browser refused a worker for a local file, so a call cannot be stopped early.'; |
| 587 | } |
| 588 | if (local) { |
| 589 | try { |
| 590 | return { ok: true, value: local.exports[name](...args) }; |
| 591 | } catch (error) { |
| 592 | return { ok: false, trap: error instanceof WebAssembly.RuntimeError, message: String((error && error.message) || error) }; |
| 593 | } |
| 594 | } |
| 595 | return new Promise(done => { |
| 596 | const id = next; |
| 597 | next += 1; |
| 598 | const timer = setTimeout(() => { |
| 599 | pending.delete(id); |
| 600 | stop(); |
| 601 | done({ ok: false, timeout: true }); |
| 602 | }, CALL_MS); |
| 603 | pending.set(id, { timer, done }); |
| 604 | worker.postMessage({ id, name, args }); |
| 605 | }); |
| 606 | } |
| 607 | function form(fn, exported) { |
| 608 | const node = document.createElement('form'); |
| 609 | node.className = 'fn'; |
| 610 | node.dataset.name = fn.name; |
| 611 | node.noValidate = true; |
| 612 | const head = document.createElement('code'); |
| 613 | head.textContent = signature(fn); |
| 614 | node.append(head); |
| 615 | const fields = fn.params.map(param => { |
| 616 | const label = document.createElement('label'); |
| 617 | const caption = document.createElement('span'); |
| 618 | caption.textContent = \`\${param.name}: \${param.type}\`; |
| 619 | const field = document.createElement('input'); |
| 620 | field.type = 'text'; |
| 621 | field.inputMode = 'numeric'; |
| 622 | field.autocomplete = 'off'; |
| 623 | if (known(param.type)) field.placeholder = \`\${TYPES[param.type].min} to \${TYPES[param.type].max}\`; |
| 624 | label.append(caption, field); |
| 625 | node.append(label); |
| 626 | return field; |
| 627 | }); |
| 628 | const call = document.createElement('button'); |
| 629 | call.type = 'submit'; |
| 630 | call.textContent = 'Call'; |
| 631 | const result = document.createElement('output'); |
| 632 | node.append(call, result); |
| 633 | if (!exported.has(fn.name) || !fn.params.every(p => known(p.type)) || !(fn.ret === 'void' || known(fn.ret))) { |
| 634 | call.disabled = true; |
| 635 | result.textContent = 'This function uses a type this file cannot call.'; |
| 636 | } |
| 637 | node.addEventListener('submit', async event => { |
| 638 | event.preventDefault(); |
| 639 | const args = []; |
| 640 | for (let i = 0; i < fn.params.length; i += 1) { |
| 641 | try { |
| 642 | args.push(argument(fn.params[i].type, fields[i].value)); |
| 643 | } catch (error) { |
| 644 | result.textContent = \`\${fn.params[i].name} \${error.message}\`; |
| 645 | fields[i].focus(); |
| 646 | return; |
| 647 | } |
| 648 | } |
| 649 | call.disabled = true; |
| 650 | result.textContent = 'running'; |
| 651 | const answer = await run(fn.name, args); |
| 652 | call.disabled = false; |
| 653 | if (answer.ok) result.textContent = \`= \${shown(fn.ret, answer.value)}\`; |
| 654 | else if (answer.timeout) result.textContent = \`stopped: no answer within \${CALL_MS / 1000} s, so the runner was reset\`; |
| 655 | else if (answer.trap) result.textContent = \`trapped: \${answer.message}\`; |
| 656 | else result.textContent = \`error: \${answer.message}\`; |
| 657 | }); |
| 658 | return node; |
| 659 | } |
| 660 | (async () => { |
| 661 | try { |
| 662 | module = await WebAssembly.compile(Uint8Array.from(atob(WASM), c => c.charCodeAt(0))); |
| 663 | } catch (error) { |
| 664 | engine.textContent = \`This browser could not load the WebAssembly: \${error.message}\`; |
| 665 | return; |
| 666 | } |
| 667 | const exported = new Set(WebAssembly.Module.exports(module).filter(item => item.kind === 'function').map(item => item.name)); |
| 668 | for (const fn of FUNCTIONS) box.append(form(fn, exported)); |
| 669 | if (!FUNCTIONS.length) engine.textContent = 'This program exports no functions.'; |
| 670 | else engine.textContent = 'Ready. Type whole numbers and press Call. Each call runs in a worker and stops after ' + CALL_MS / 1000 + ' s.'; |
| 671 | })(); |
| 672 | })();`.replace(/<\/(script)/gi, '<\\/$1'); |
| 673 | const pin = project.pin ? ` (omc ${escapeHtml(project.pin)})` : ''; |
| 674 | return `<!DOCTYPE html> |
| 675 | <html lang="en"> |
| 676 | <head> |
| 677 | <meta charset="utf-8"> |
| 678 | <meta http-equiv="Content-Security-Policy" content="${policy}"> |
| 679 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 680 | <title>${escapeHtml(project.title)}: an Omega program</title> |
| 681 | <style> |
| 682 | body { font: 16px/1.5 system-ui, sans-serif; margin: 0; background: #0d1117; color: #e6edf3; } |
| 683 | main { max-width: 760px; margin: 0 auto; padding: 24px 16px 48px; } |
| 684 | a { color: #79c0ff; } |
| 685 | pre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 12px; overflow-x: auto; } |
| 686 | form.fn { border: 1px solid #30363d; border-radius: 6px; padding: 12px; margin: 12px 0; display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: end; } |
| 687 | form.fn code { flex-basis: 100%; } |
| 688 | label { display: flex; flex-direction: column; font-size: 14px; } |
| 689 | input { font: inherit; padding: 4px 6px; width: 12em; } |
| 690 | button { font: inherit; padding: 4px 14px; } |
| 691 | output { font-family: ui-monospace, monospace; } |
| 692 | .small { color: #8b949e; font-size: 14px; } |
| 693 | </style> |
| 694 | </head> |
| 695 | <body> |
| 696 | <main> |
| 697 | <h1>${escapeHtml(project.title)}</h1> |
| 698 | <p>A program written in Omega by Aien, Drake Stapleton's AI. It runs right here: this one file holds the compiled WebAssembly, so it needs no install and makes no network requests.</p> |
| 699 | <p>Omega is Drake Stapleton's programming language for programs written by AI. <a href="https://www.aienos.com/omega/">Learn about Omega</a>.</p> |
| 700 | <p id="engine">Loading the program.</p> |
| 701 | <noscript><p>Turn on JavaScript in this browser to run the program. The source below is plain text.</p></noscript> |
| 702 | <div id="fns"></div> |
| 703 | <h2>The Omega source</h2> |
| 704 | <pre><code>${escapeHtml(project.source)}</code></pre> |
| 705 | <p class="small">Compiled to ${project.wasm.length} bytes of WebAssembly with no imports by the pinned seeded Omega compiler${pin} at <a href="https://www.aienos.com/aien/">https://www.aienos.com/aien/</a>.</p> |
| 706 | </main> |
| 707 | <script> |
| 708 | ${script} |
| 709 | </script> |
| 710 | </body> |
| 711 | </html> |
| 712 | `; |
| 713 | } |
| 714 | function field(parent, label, tag, max) { |
| 715 | const wrap = el('label', 'allen-field'); |
| 716 | wrap.append(el('span', '', label)); |
| 717 | const input = el(tag); |
| 718 | if (tag === 'input') input.type = 'text'; |
| 719 | input.maxLength = max; |
| 720 | input.autocomplete = 'off'; |
| 721 | wrap.append(input); |
| 722 | parent.append(wrap); |
| 723 | return input; |
| 724 | } |
| 725 | function post(body, extra, identity = true) { |
| 726 | return { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...(identity ? keyHeaders(false) : {}), ...extra }, body: JSON.stringify(body), cache: 'no-store', credentials: 'omit' }; |
| 727 | } |
| 728 | function failure(response, reply, tail) { |
| 729 | const said = reply && typeof reply.message === 'string' ? reply.message.slice(0, 300) : ''; |
| 730 | const wait = retryAfter(response, reply); |
| 731 | if ([400, 413, 422].includes(response.status) && said) return `${said} ${tail}`.trim(); |
| 732 | return `${refusal(response.status, reply)}${wait ? ` Try again in ${wait} s.` : ''} ${tail}`.trim(); |
| 733 | } |
| 734 | const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/; |
| 735 | const NAME = /^[a-z](?:[a-z0-9]|-(?=[a-z0-9])){1,23}$/; |
| 736 | /* The builder's home projects/<handle>/ in omega-projects. A remembered |
| 737 | visitor gets <name>-<tag>, tied to their key and remembered by Aien; an |
| 738 | anonymous visitor gets a one-time anon- handle whose claim code lives only |
| 739 | in this page and is shown once. The gateway checks ownership on every save. */ |
| 740 | const home = { handle: '', claim: '' }; |
| 741 | function claimHeaders() { |
| 742 | return home.claim ? { 'X-Allen-Claim': home.claim } : {}; |
| 743 | } |
| 744 | async function projectCall(path, body) { |
| 745 | const response = await fetch(PROJECTS + path, body === undefined |
| 746 | ? { cache: 'no-store', credentials: 'omit', headers: { Accept: 'application/json', ...keyHeaders(false), ...claimHeaders() } } |
| 747 | : post(body, claimHeaders())); |
| 748 | return { response, reply: await response.json().catch(() => null) }; |
| 749 | } |
| 750 | async function findHome() { |
| 751 | if (home.handle || !remembered) return home.handle; |
| 752 | try { |
| 753 | const { response, reply } = await projectCall('me'); |
| 754 | if (response.ok && reply && typeof reply.handle === 'string') home.handle = reply.handle; |
| 755 | } catch (_) { |
| 756 | /* No home yet; the form asks for a name. */ |
| 757 | } |
| 758 | return home.handle; |
| 759 | } |
| 760 | async function makeHome(name, state) { |
| 761 | const { response, reply } = await projectCall('handle', remembered ? { name } : {}); |
| 762 | if (!response.ok || !reply || typeof reply.handle !== 'string') { |
| 763 | state.replaceChildren(el('p', 'allen-err', failure(response, reply, 'No home was made.'))); |
| 764 | return ''; |
| 765 | } |
| 766 | home.handle = reply.handle; |
| 767 | if (typeof reply.claim === 'string') { |
| 768 | home.claim = reply.claim; |
| 769 | const line = el('p', 'allen-keyline'); |
| 770 | line.append(el('span', '', 'Your claim code, shown once: '), el('code', '', reply.claim)); |
| 771 | state.replaceChildren(line, el('p', 'allen-note', 'Copy it now. It is the only way to save to this home again; Aien does not keep it.')); |
| 772 | } |
| 773 | return home.handle; |
| 774 | } |
| 775 | async function showGallery(out) { |
| 776 | out.replaceChildren(el('p', 'allen-note', 'Loading the Built with Aien gallery.')); |
| 777 | try { |
| 778 | const response = await fetch(GALLERY, { cache: 'no-store', credentials: 'omit', headers: { Accept: 'application/json' } }); |
| 779 | const reply = response.ok ? await response.json() : null; |
| 780 | const items = reply && Array.isArray(reply.gallery) ? reply.gallery : []; |
| 781 | const list = el('ul'); |
| 782 | for (const g of items.slice(0, 50)) { |
| 783 | if (typeof g.project !== 'string' || !SLUG.test(g.project)) continue; |
| 784 | /* omega-projects has no public page, so a gallery entry is named in plain text. */ |
| 785 | const link = el('strong', '', String(g.title || g.project).slice(0, 80)); |
| 786 | const li = el('li'); |
| 787 | li.append(link, el('span', '', ` by ${String(g.handle).slice(0, 40)}: ${String(g.description || '').slice(0, 200)}`)); |
| 788 | list.append(li); |
| 789 | } |
| 790 | out.replaceChildren(list.firstChild ? list : el('p', 'allen-note', 'Nothing is in the gallery yet. Yours could be the first.')); |
| 791 | } catch (_) { |
| 792 | out.replaceChildren(el('p', 'allen-err', 'Could not load the gallery.')); |
| 793 | } |
| 794 | } |
| 795 | function publishForm(project, pub) { |
| 796 | if (pub.firstChild) { |
| 797 | pub.replaceChildren(); |
| 798 | return; |
| 799 | } |
| 800 | const form = el('form', 'allen-card allen-publish'); |
| 801 | form.noValidate = true; |
| 802 | form.append(el('p', 'allen-card-h', 'Save or publish')); |
| 803 | const name = field(form, remembered ? 'Your builder name (lowercase letters, digits and hyphens; never an email)' : 'Anonymous: you get a one-time home and a claim code', 'input', 24); |
| 804 | name.disabled = !remembered; |
| 805 | const slug = field(form, 'Project name (lowercase letters, digits and hyphens)', 'input', 40); |
| 806 | slug.value = project.base; |
| 807 | const title = field(form, 'Title', 'input', 80); |
| 808 | title.value = project.title; |
| 809 | const description = field(form, 'What it is and who it helps', 'textarea', 2000); |
| 810 | const main = project.type === 'html' ? 'index.html' : project.main; |
| 811 | const where = el('p', 'allen-note'); |
| 812 | form.append(el('p', 'allen-note', `Files: ${main}, README.md. Email addresses and phone numbers are removed from the text first.`), where); |
| 813 | const sync = () => setText(where, home.handle |
| 814 | ? `Save commits to your home projects/${home.handle}/${slug.value || 'project'}/ in aien-dev/omega-projects on GitHub (branch u/${home.handle}), public at once. Publish asks Drake to review it; once he merges it, it is live at ${REVIEW_HOST}${home.handle}/${slug.value || 'project'}/ and in the Built with Aien gallery.` |
| 815 | : 'Your home in aien-dev/omega-projects on GitHub is made the first time you save.'); |
| 816 | slug.addEventListener('input', sync); |
| 817 | const saveButton = el('button', 'allen-tool', 'Save to my home'); |
| 818 | saveButton.type = 'submit'; |
| 819 | const publishButton = button('Publish for Drake\u2019s review', () => { |
| 820 | publishButton.hidden = true; |
| 821 | const confirm = el('div', 'allen-choices'); |
| 822 | confirm.append(el('span', 'allen-note', 'Publish this project publicly as a pull request for Drake to review?'), button('Yes, publish it', () => { |
| 823 | confirm.remove(); |
| 824 | publishButton.hidden = false; |
| 825 | send('publish'); |
| 826 | }), button('Cancel', () => { |
| 827 | confirm.remove(); |
| 828 | publishButton.hidden = false; |
| 829 | })); |
| 830 | form.insertBefore(confirm, state); |
| 831 | }); |
| 832 | const galleryOut = el('div', 'allen-out'); |
| 833 | const state = el('div', 'allen-card-state'); |
| 834 | form.append(saveButton, publishButton, button('Built with Aien gallery', () => showGallery(galleryOut)), state, galleryOut); |
| 835 | findHome().then(handle => { |
| 836 | if (handle) name.value = handle.replace(/-[0-9a-f]{8}$/, ''); |
| 837 | sync(); |
| 838 | }); |
| 839 | const again = { |
| 840 | set hidden(value) { saveButton.hidden = value; publishButton.hidden = value; }, |
| 841 | set disabled(value) { saveButton.disabled = value; publishButton.disabled = value; }, |
| 842 | }; |
| 843 | async function send(kind) { |
| 844 | const problems = []; |
| 845 | const about = description.value.trim(); |
| 846 | if (!SLUG.test(slug.value)) problems.push('The project name must be 1 to 40 lowercase letters, digits or inner hyphens.'); |
| 847 | if (title.value.trim().length < 3 || title.value.trim().length > 80) problems.push('The title must be 3 to 80 characters.'); |
| 848 | if (about.length < 10 || about.length > 2000) problems.push('Say what it is and who it helps in 10 to 2000 characters.'); |
| 849 | if (remembered && !home.handle && !NAME.test(name.value)) problems.push('Your builder name must be 2 to 24 lowercase letters, digits or inner hyphens, starting with a letter.'); |
| 850 | if (problems.length) { |
| 851 | state.replaceChildren(el('p', 'allen-err', problems.join(' '))); |
| 852 | return; |
| 853 | } |
| 854 | again.disabled = true; |
| 855 | try { |
| 856 | const handle = home.handle || await makeHome(name.value, state); |
| 857 | if (!handle) { |
| 858 | again.disabled = false; |
| 859 | return; |
| 860 | } |
| 861 | sync(); |
| 862 | const item = { kind, handle, project: slug.value, title: title.value.trim(), description: about, files: [{ name: main, content: project.source }, { name: 'README.md', content: readme({ ...project, title: title.value.trim() }, about) }] }; |
| 863 | const note = el('div'); |
| 864 | state.append(note); |
| 865 | const { response, reply } = await projectCall(kind, item); |
| 866 | if (!response.ok || !reply || typeof reply !== 'object') { |
| 867 | note.replaceChildren(el('p', 'allen-err', failure(response, reply, 'Nothing was saved.'))); |
| 868 | again.disabled = false; |
| 869 | return; |
| 870 | } |
| 871 | await track(reply, note, item, again); |
| 872 | again.disabled = false; |
| 873 | } catch (_) { |
| 874 | state.append(el('p', 'allen-err', 'Could not reach Aien. Nothing was saved.')); |
| 875 | again.disabled = false; |
| 876 | } |
| 877 | } |
| 878 | form.addEventListener('submit', event => { |
| 879 | event.preventDefault(); |
| 880 | send('save'); |
| 881 | }); |
| 882 | pub.replaceChildren(form); |
| 883 | (remembered && !name.value ? name : slug).focus(); |
| 884 | } |
| 885 | /* Header lines "Key: value" up to the first line that is not one; the rest |
| 886 | is the body. Keys from the model land in a prototype-free object. */ |
| 887 | function cardFields(source) { |
| 888 | const fields = Object.create(null); |
| 889 | const lines = source.split('\n'); |
| 890 | let i = 0; |
| 891 | for (; i < lines.length; i += 1) { |
| 892 | const match = /^\s*([A-Za-z]+)\s*:\s?(.*)$/.exec(lines[i]); |
| 893 | if (!match) break; |
| 894 | fields[match[1].toLowerCase()] = match[2].trim(); |
| 895 | } |
| 896 | return { fields, body: lines.slice(i).join('\n').trim() }; |
| 897 | } |
| 898 | const INTRO_LINES = { kind: 'kind', name: 'name', org: 'org', contact: 'contact', github: 'github', from: 'origin', building: 'purpose', homepage: 'homepage', human: 'human', framework: 'framework', model: 'model' }; |
| 899 | function introLines(fields) { |
| 900 | const out = Object.create(null); |
| 901 | for (const [line, key] of Object.entries(INTRO_LINES)) if (fields[line]) out[key] = fields[line]; |
| 902 | return out; |
| 903 | } |
| 904 | function issueCard(parsed, out) { |
| 905 | const item = { v: 1, kind: 'issue', template: String(parsed.fields.type || '').toLowerCase(), title: String(parsed.fields.title || ''), body: parsed.body, area: String(parsed.fields.area || 'unknown') }; |
| 906 | const card = el('div', 'allen-card'); |
| 907 | card.append(el('p', 'allen-card-h', 'Proposed GitHub issue')); |
| 908 | const facts = el('dl', 'allen-kv'); |
| 909 | for (const [label, value] of [['Type', item.template], ['Area', item.area], ['Title', item.title]]) facts.append(el('dt', '', label), el('dd', '', value)); |
| 910 | card.append(facts, el('pre', 'allen-card-body', item.body)); |
| 911 | const problems = []; |
| 912 | if (!['feature', 'question', 'bug'].includes(item.template)) problems.push('Type must be feature, question or bug.'); |
| 913 | if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(item.area)) problems.push('Area must be a repository name or unknown.'); |
| 914 | if (item.title.length < 8 || item.title.length > 120) problems.push('The title must be 8 to 120 characters.'); |
| 915 | if (item.body.length < 20 || item.body.length > 6000) problems.push('The body must be 20 to 6000 characters.'); |
| 916 | const state = el('div', 'allen-card-state'); |
| 917 | if (problems.length) { |
| 918 | state.append(el('p', 'allen-err', `This cannot be filed as written: ${problems.join(' ')} Ask Aien to fix it.`)); |
| 919 | card.append(state); |
| 920 | out.replaceChildren(card); |
| 921 | return; |
| 922 | } |
| 923 | card.append(el('p', 'allen-note', 'Filing publishes exactly this text as an issue in aien-dev/omega-projects on GitHub. Email addresses and phone numbers are removed first. Nothing is filed until you confirm.')); |
| 924 | const file = button('File this on GitHub', () => { |
| 925 | file.hidden = true; |
| 926 | const confirm = el('div', 'allen-choices'); |
| 927 | confirm.append(el('span', 'allen-note', 'File this exact issue publicly?'), button('Yes, file it', () => { |
| 928 | confirm.remove(); |
| 929 | submitItem(item, state, file); |
| 930 | }), button('Cancel', () => { |
| 931 | confirm.remove(); |
| 932 | file.hidden = false; |
| 933 | })); |
| 934 | card.insertBefore(confirm, state); |
| 935 | }); |
| 936 | card.append(file, state); |
| 937 | out.replaceChildren(card); |
| 938 | } |
| 939 | async function submitItem(item, state, again) { |
| 940 | state.replaceChildren(el('p', 'allen-note', 'Sending.')); |
| 941 | let response; |
| 942 | let reply; |
| 943 | try { |
| 944 | response = await fetch(SUBMIT, post(item)); |
| 945 | reply = await response.json().catch(() => null); |
| 946 | } catch (_) { |
| 947 | state.replaceChildren(el('p', 'allen-err', 'Could not reach Aien. Nothing was sent.')); |
| 948 | again.hidden = false; |
| 949 | again.disabled = false; |
| 950 | return; |
| 951 | } |
| 952 | if (!response.ok || !reply || typeof reply !== 'object') { |
| 953 | state.replaceChildren(el('p', 'allen-err', failure(response, reply, 'Nothing was filed.'))); |
| 954 | again.hidden = false; |
| 955 | again.disabled = false; |
| 956 | return; |
| 957 | } |
| 958 | track(reply, state, item, again); |
| 959 | } |
| 960 | /* Status every POLL_MS until filed, rejected or failed. Only a link to an |
| 961 | issue or pull request in aien-dev/omega-projects becomes an anchor. A |
| 962 | rejected item can be edited and sent again; a failed one can go to Drake |
| 963 | as a relay instead, with its text prefilled and nothing sent unconfirmed. */ |
| 964 | function showStatus(status, state, id, item, again) { |
| 965 | const url = typeof status.url === 'string' && /^https:\/\/github\.com\/aien-dev\/omega-projects\/(issues\/\d+|pull\/\d+|commit\/[0-9a-f]{40})$/.test(status.url) ? status.url : ''; |
| 966 | const reason = typeof status.reason === 'string' && status.reason ? status.reason.slice(0, 300) : ''; |
| 967 | if (status.state === 'filed') { |
| 968 | const done = el('p', 'allen-ok', url ? (item.kind === 'save' ? 'Saved: ' : 'Filed: ') : 'Filed, without a tracking link.'); |
| 969 | if (url) { |
| 970 | /* omega-projects has no public page: the tracking address is shown as plain text, never linked. */ |
| 971 | done.append(el('code', '', url)); |
| 972 | } |
| 973 | state.replaceChildren(done); |
| 974 | return true; |
| 975 | } |
| 976 | if (status.state === 'rejected') { |
| 977 | state.replaceChildren(el('p', 'allen-err', `Not filed: ${reason || 'no reason given'}`)); |
| 978 | if (item.kind === 'issue') { |
| 979 | state.append(editIssue(item, state)); |
| 980 | } else { |
| 981 | again.hidden = false; |
| 982 | again.disabled = false; |
| 983 | state.append(el('p', 'allen-note', 'Edit the fields above and submit again.')); |
| 984 | } |
| 985 | return true; |
| 986 | } |
| 987 | if (status.state === 'failed') { |
| 988 | const box = el('div', 'allen-fail'); |
| 989 | const relayOut = el('div', 'allen-out'); |
| 990 | const offer = button('Send it to Drake instead', () => { |
| 991 | offer.remove(); |
| 992 | relayCard({ fields: Object.create(null), body: relayText(item) }, relayOut); |
| 993 | }); |
| 994 | box.append(el('p', 'allen-err', `I could not file this: ${reason || 'no reason given'}`), offer, relayOut); |
| 995 | state.replaceChildren(box); |
| 996 | return true; |
| 997 | } |
| 998 | state.replaceChildren(el('p', 'allen-note', `Waiting to file on GitHub${reason ? `: ${reason}` : ''} (item ${id}${status.duplicate ? ', the same text was sent before' : ''}). Checking every ${POLL_MS / 1000} s.`)); |
| 999 | return false; |
| 1000 | } |
| 1001 | function relayText(item) { |
| 1002 | return item.kind === 'issue' ? `Issue for ${item.area} (${item.template}): ${item.title}\n\n${item.body}` : `Omega project ${item.handle}/${item.project}: ${item.title}\n\n${item.description}`; |
| 1003 | } |
| 1004 | async function track(first, state, item, again) { |
| 1005 | const id = typeof first.id === 'string' && /^[0-9a-f]{20}$/.test(first.id) ? first.id : ''; |
| 1006 | if (!id) { |
| 1007 | state.replaceChildren(el('p', 'allen-err', 'The gateway returned no tracking id.')); |
| 1008 | return; |
| 1009 | } |
| 1010 | const began = performance.now(); |
| 1011 | let current = first; |
| 1012 | for (;;) { |
| 1013 | if (showStatus(current, state, id, item, again)) return; |
| 1014 | /* A token not yet installed never resolves, so stop after POLL_LIMIT; |
| 1015 | retries end in filed or failed within a few minutes, so wait longer. */ |
| 1016 | const retrying = typeof current.reason === 'string' && current.reason.startsWith('retrying'); |
| 1017 | if (performance.now() - began >= (retrying ? 3 * POLL_LIMIT : POLL_LIMIT)) { |
| 1018 | const why = typeof current.reason === 'string' && current.reason ? current.reason.slice(0, 200) : 'not filed yet'; |
| 1019 | state.replaceChildren(el('p', 'allen-note', `queued: ${why} (item ${id}). The request is kept and is filed when Drake's filing service runs; checking stopped.`)); |
| 1020 | return; |
| 1021 | } |
| 1022 | await new Promise(done => setTimeout(done, POLL_MS)); |
| 1023 | try { |
| 1024 | const response = await fetch(STATUS + id, { cache: 'no-store', credentials: 'omit', headers: { Accept: 'application/json', ...keyHeaders(false) } }); |
| 1025 | const reply = response.ok ? await response.json() : null; |
| 1026 | if (reply && typeof reply === 'object') current = reply; |
| 1027 | } catch (_) { |
| 1028 | /* Keep the last status and try again on the next tick. */ |
| 1029 | } |
| 1030 | } |
| 1031 | } |
| 1032 | /* After a rejection: the same issue, editable, sent again only on a click. */ |
| 1033 | function editIssue(item, state) { |
| 1034 | const form = el('form', 'allen-card allen-reissue'); |
| 1035 | form.noValidate = true; |
| 1036 | const title = field(form, 'Title', 'input', 120); |
| 1037 | title.value = item.title; |
| 1038 | const body = field(form, 'Body', 'textarea', 6000); |
| 1039 | body.value = item.body; |
| 1040 | const resend = el('button', 'allen-tool', 'File the edited issue'); |
| 1041 | resend.type = 'submit'; |
| 1042 | const note = el('p', 'allen-card-state'); |
| 1043 | form.append(resend, note); |
| 1044 | form.addEventListener('submit', event => { |
| 1045 | event.preventDefault(); |
| 1046 | const next = { ...item, title: title.value.trim(), body: body.value.trim() }; |
| 1047 | if (next.title.length < 8 || next.title.length > 120 || next.body.length < 20 || next.body.length > 6000) { |
| 1048 | setText(note, 'The title must be 8 to 120 characters and the body 20 to 6000.'); |
| 1049 | return; |
| 1050 | } |
| 1051 | resend.disabled = true; |
| 1052 | submitItem(next, note, resend); |
| 1053 | }); |
| 1054 | return form; |
| 1055 | } |
| 1056 | const INTRO = [ |
| 1057 | ['name', 'Name', 100, 'input'], |
| 1058 | ['org', 'Organization', 100, 'input'], |
| 1059 | ['contact', 'Contact (email or another way to reach you)', 200, 'input'], |
| 1060 | ['github', 'GitHub name', 39, 'input'], |
| 1061 | ['origin', 'Where you are from', 200, 'input'], |
| 1062 | ['purpose', 'What you are building', 1000, 'textarea'], |
| 1063 | ['homepage', 'Homepage (https)', 200, 'input'], |
| 1064 | ['framework', 'Framework (agents)', 100, 'input'], |
| 1065 | ['model', 'Model (agents)', 100, 'input'], |
| 1066 | ['human', 'Your human (agents: the person or organization operating you)', 200, 'input'], |
| 1067 | ]; |
| 1068 | function introCard(prefill) { |
| 1069 | const form = el('form', 'allen-card allen-introduce'); |
| 1070 | form.noValidate = true; |
| 1071 | form.append(el('p', 'allen-card-h', 'Introduce yourself to Aien')); |
| 1072 | const kindWrap = el('label', 'allen-field'); |
| 1073 | kindWrap.append(el('span', '', 'You are')); |
| 1074 | const who = el('select'); |
| 1075 | for (const value of ['human', 'agent']) { |
| 1076 | const option = el('option', '', value === 'human' ? 'a human' : 'an agent'); |
| 1077 | option.value = value; |
| 1078 | who.append(option); |
| 1079 | } |
| 1080 | who.value = String(prefill.kind || kind).toLowerCase() === 'agent' ? 'agent' : 'human'; |
| 1081 | kindWrap.append(who); |
| 1082 | form.append(kindWrap); |
| 1083 | const inputs = {}; |
| 1084 | for (const [key, label, max, tag] of INTRO) { |
| 1085 | inputs[key] = field(form, label, tag, max); |
| 1086 | inputs[key].value = cut(String(prefill[key] || ''), max); |
| 1087 | } |
| 1088 | const notice = el('div', 'allen-consent'); |
| 1089 | notice.append( |
| 1090 | el('p', '', 'What is kept if you save: the fields above and the time you sent them.'), |
| 1091 | el('p', '', 'Why: so Drake can follow up with you.'), |
| 1092 | el('p', '', 'Aien also keeps short notes about you from your chats (who you are, what you build, your open asks), keyed to a random Aien key saved in this browser. Anyone without the key is a stranger to Aien.'), |
| 1093 | el('p', '', "Where: privately on Drake's own computer. Never published, never sold."), |
| 1094 | el('p', '', `For how long: until you delete it, with the delete link shown after saving, with Forget me in Your Aien key, or by writing to ${PRIVACY_MAIL}.`), |
| 1095 | el('p', '', 'Declining changes nothing: you can keep chatting and nothing is saved.'), |
| 1096 | ); |
| 1097 | const agreeWrap = el('label', 'allen-agree'); |
| 1098 | const agree = el('input'); |
| 1099 | agree.type = 'checkbox'; |
| 1100 | agreeWrap.append(agree, el('span', '', 'I agree that this introduction is kept as described above.')); |
| 1101 | const keep = el('button', 'allen-tool', 'Save'); |
| 1102 | keep.type = 'submit'; |
| 1103 | keep.disabled = true; |
| 1104 | agree.addEventListener('change', () => { |
| 1105 | keep.disabled = !agree.checked; |
| 1106 | }); |
| 1107 | const state = el('div', 'allen-card-state'); |
| 1108 | const paste = el('div', 'allen-paste'); |
| 1109 | const pasted = field(paste, 'Introduced before on another device? Paste your Aien key instead (32 characters, 0 to 9 and a to f)', 'input', 32); |
| 1110 | const use = button('Use this key', () => { |
| 1111 | if (!agree.checked) return; |
| 1112 | const value = pasted.value.trim().toLowerCase(); |
| 1113 | if (!KEY_PATTERN.test(value)) { |
| 1114 | state.replaceChildren(el('p', 'allen-err', 'An Aien key is exactly 32 characters, 0 to 9 and a to f.')); |
| 1115 | return; |
| 1116 | } |
| 1117 | if (!keepKey(value)) { |
| 1118 | state.replaceChildren(el('p', 'allen-err', 'This browser refused to store the key.')); |
| 1119 | return; |
| 1120 | } |
| 1121 | remembered = true; |
| 1122 | conversation = conversationId(); |
| 1123 | showMode(); |
| 1124 | keyPanel(); |
| 1125 | for (const control of form.querySelectorAll('input, textarea, select, button')) control.disabled = true; |
| 1126 | state.replaceChildren(el('p', 'allen-ok', 'Key saved in this browser. Aien will recognize you from your next message.')); |
| 1127 | }); |
| 1128 | use.disabled = true; |
| 1129 | paste.append(use); |
| 1130 | agree.addEventListener('change', () => { |
| 1131 | use.disabled = !agree.checked; |
| 1132 | }); |
| 1133 | form.append(notice, agreeWrap, keep, paste, state); |
| 1134 | form.addEventListener('submit', event => { |
| 1135 | event.preventDefault(); |
| 1136 | if (agree.checked) saveIntro(who.value, inputs, state, keep, form); |
| 1137 | }); |
| 1138 | return form; |
| 1139 | } |
| 1140 | async function saveIntro(who, inputs, state, keep, form) { |
| 1141 | const record = { consent: true, kind: who }; |
| 1142 | for (const [key] of INTRO) record[key] = inputs[key].value.trim(); |
| 1143 | if (!record.name && !record.contact) { |
| 1144 | state.replaceChildren(el('p', 'allen-err', 'Give at least a name or a contact.')); |
| 1145 | return; |
| 1146 | } |
| 1147 | if (record.homepage && !/^https:\/\/\S{4,}$/.test(record.homepage)) { |
| 1148 | state.replaceChildren(el('p', 'allen-err', 'The homepage must be an https address.')); |
| 1149 | return; |
| 1150 | } |
| 1151 | keep.disabled = true; |
| 1152 | state.replaceChildren(el('p', 'allen-note', 'Saving.')); |
| 1153 | let response; |
| 1154 | let reply; |
| 1155 | try { |
| 1156 | response = await fetch(INTRODUCE, post(record, { 'X-Allen-Via': 'chat' }, false)); |
| 1157 | reply = await response.json().catch(() => null); |
| 1158 | } catch (_) { |
| 1159 | state.replaceChildren(el('p', 'allen-err', 'Could not reach Aien. Nothing was saved.')); |
| 1160 | keep.disabled = false; |
| 1161 | return; |
| 1162 | } |
| 1163 | if (!response.ok || !reply || reply.stored !== true) { |
| 1164 | state.replaceChildren(el('p', 'allen-err', failure(response, reply, 'Nothing was saved.'))); |
| 1165 | keep.disabled = false; |
| 1166 | return; |
| 1167 | } |
| 1168 | for (const control of form.querySelectorAll('input, textarea, select')) control.disabled = true; |
| 1169 | keep.hidden = true; |
| 1170 | /* The gateway hands out the visitor key only with a consented introduction. */ |
| 1171 | const kept_ = typeof reply.key === 'string' && KEY_PATTERN.test(reply.key) && keepKey(reply.key); |
| 1172 | if (kept_) { |
| 1173 | remembered = true; |
| 1174 | conversation = conversationId(); |
| 1175 | showMode(); |
| 1176 | keyPanel(); |
| 1177 | } |
| 1178 | const memo = el('p', 'allen-note', kept_ ? 'Aien will remember you in this browser by your Aien key; see Your Aien key below the chat to copy it or forget it.' : 'Aien will not recognize you on a later visit: no key was kept in this browser.'); |
| 1179 | const link = typeof reply.delete === 'string' && /^https:\/\/www\.aienos\.com\/(?:aien|allen)\/#forget=c_[0-9a-f]{16}\.[A-Za-z0-9_-]{20,64}$/.test(reply.delete) ? reply.delete : ''; |
| 1180 | if (!link) { |
| 1181 | state.replaceChildren(el('p', 'allen-ok', `Saved. The delete link did not arrive intact; write to ${PRIVACY_MAIL} to have it deleted.`), memo); |
| 1182 | return; |
| 1183 | } |
| 1184 | const kept = el('p', 'allen-ok', 'Saved. Keep this delete link; it deletes your introduction: '); |
| 1185 | const anchor = el('a', '', link); |
| 1186 | anchor.href = link; |
| 1187 | kept.append(anchor); |
| 1188 | const copy = button('Copy link', () => copyText(link, copy)); |
| 1189 | state.replaceChildren(kept, copy, el('p', 'allen-note', `Or write to ${PRIVACY_MAIL} to have it deleted.`), memo); |
| 1190 | } |
| 1191 | /* A delete link opens this page at #forget=<id>.<token>; nothing is sent |
| 1192 | until the visitor confirms, and the token leaves the address afterwards. */ |
| 1193 | function forgetOffer() { |
| 1194 | const match = /^#forget=(c_[0-9a-f]{16})\.([A-Za-z0-9_-]{20,64})$/.exec(location.hash); |
| 1195 | if (!match) return; |
| 1196 | const id = match[1]; |
| 1197 | const token = match[2]; |
| 1198 | const note = message('allen', 'Aien'); |
| 1199 | note.body.append(el('p', 'allen-p', `You opened the delete link for introduction ${id}. Delete it?`)); |
| 1200 | const row = el('div', 'allen-choices'); |
| 1201 | const state = el('div', 'allen-card-state'); |
| 1202 | const remove = button('Delete my introduction', async () => { |
| 1203 | remove.disabled = true; |
| 1204 | decline.disabled = true; |
| 1205 | state.replaceChildren(el('p', 'allen-note', 'Sending.')); |
| 1206 | try { |
| 1207 | const response = await fetch(FORGET, post({ id, token })); |
| 1208 | const reply = await response.json().catch(() => null); |
| 1209 | if (response.ok && reply && reply.accepted === true) { |
| 1210 | row.remove(); |
| 1211 | state.replaceChildren(el('p', 'allen-ok', "Deletion requested. Drake's computer removes the introduction the next time it reads the queue; a link that matches nothing changes nothing.")); |
| 1212 | try { |
| 1213 | history.replaceState(null, '', location.pathname + location.search); |
| 1214 | } catch (_) { |
| 1215 | location.hash = ''; |
| 1216 | } |
| 1217 | return; |
| 1218 | } |
| 1219 | state.replaceChildren(el('p', 'allen-err', failure(response, reply, 'Nothing was deleted yet.'))); |
| 1220 | } catch (_) { |
| 1221 | state.replaceChildren(el('p', 'allen-err', 'Could not reach Aien. Nothing was deleted yet.')); |
| 1222 | } |
| 1223 | remove.disabled = false; |
| 1224 | decline.disabled = false; |
| 1225 | }); |
| 1226 | const decline = button('Keep it', () => { |
| 1227 | row.remove(); |
| 1228 | state.replaceChildren(el('p', 'allen-note', 'Nothing changed.')); |
| 1229 | }); |
| 1230 | row.append(remove, decline); |
| 1231 | note.body.append(row, state); |
| 1232 | } |
| 1233 | /* The visitor key: 32 hex from the gateway, kept under KEY_NAME in local |
| 1234 | storage only after a consented introduction or when the visitor pastes |
| 1235 | their own key. Nothing else is ever stored in this browser. */ |
| 1236 | function storedKey() { |
| 1237 | try { |
| 1238 | const value = localStorage.getItem(KEY_NAME); |
| 1239 | return value && KEY_PATTERN.test(value) ? value : ''; |
| 1240 | } catch (_) { |
| 1241 | return ''; |
| 1242 | } |
| 1243 | } |
| 1244 | function keepKey(value) { |
| 1245 | try { |
| 1246 | localStorage.setItem(KEY_NAME, value); |
| 1247 | return storedKey() === value; |
| 1248 | } catch (_) { |
| 1249 | return false; |
| 1250 | } |
| 1251 | } |
| 1252 | function dropKey() { |
| 1253 | try { |
| 1254 | localStorage.removeItem(KEY_NAME); |
| 1255 | } catch (_) { |
| 1256 | /* Nothing was stored. */ |
| 1257 | } |
| 1258 | } |
| 1259 | /* 128 random bits (32 hex): the conversation id is the live-session bearer. */ |
| 1260 | function conversationId() { |
| 1261 | const bytes = new Uint8Array(16); |
| 1262 | crypto.getRandomValues(bytes); |
| 1263 | return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join(''); |
| 1264 | } |
| 1265 | /* Anonymous is the default: a visitor is remembered only after Remember me, |
| 1266 | through the consent card. Anonymous calls say so and never carry a key. */ |
| 1267 | let remembered = false; |
| 1268 | let oldKey = ''; |
| 1269 | function keyHeaders(chat) { |
| 1270 | if (!remembered) return { 'X-Allen-Anonymous': '1' }; |
| 1271 | const key = storedKey(); |
| 1272 | if (!key) return { 'X-Allen-Anonymous': '1' }; |
| 1273 | return chat ? { 'X-Allen-Key': key, 'X-Allen-Conversation': conversation } : { 'X-Allen-Key': key }; |
| 1274 | } |
| 1275 | function keyPanel(said) { |
| 1276 | const body = byId('allen-key-body'); |
| 1277 | if (!body) return; |
| 1278 | const key = remembered ? storedKey() : ''; |
| 1279 | const state = el('p', 'allen-card-state', said || ''); |
| 1280 | const parts = []; |
| 1281 | if (key) { |
| 1282 | const line = el('p', 'allen-keyline'); |
| 1283 | line.append(el('span', '', 'Your Aien key: '), el('code', '', key)); |
| 1284 | const row = el('div', 'allen-choices'); |
| 1285 | const copy = button('Copy', () => copyText(key, copy)); |
| 1286 | const forget = button('Forget me', () => forgetMe(forget, state)); |
| 1287 | row.append(copy, forget); |
| 1288 | parts.push(line, row, el('p', 'allen-note', "Aien recognizes you only by this key, never by a name or email you give. Keep it private, and paste it into Remember me on another device to be recognized there. Forget me deletes Aien's notes about you and your introduction, then removes the key from this browser.")); |
| 1289 | } else { |
| 1290 | parts.push(el('p', 'allen-note', "Anonymous: this browser holds no Aien key, so Aien won't remember this chat. Remember me asks for your consent first.")); |
| 1291 | if (oldKey) { |
| 1292 | const forget = button('Forget me', () => forgetOld(forget, state)); |
| 1293 | parts.push(el('p', 'allen-note', 'Notes Aien kept about you before you went anonymous stay on Drake\'s computer until you delete them.'), forget); |
| 1294 | } |
| 1295 | } |
| 1296 | parts.push(state); |
| 1297 | body.replaceChildren(...parts); |
| 1298 | const panel = byId('allen-key'); |
| 1299 | if (panel) panel.dataset.key = key ? 'yes' : 'no'; |
| 1300 | } |
| 1301 | async function forgetMe(trigger, state) { |
| 1302 | if (!storedKey()) { |
| 1303 | keyPanel(); |
| 1304 | return; |
| 1305 | } |
| 1306 | trigger.disabled = true; |
| 1307 | setText(state, 'Sending.'); |
| 1308 | try { |
| 1309 | const response = await fetch(FORGET_ME, post({})); |
| 1310 | const reply = await response.json().catch(() => null); |
| 1311 | if (response.ok) { |
| 1312 | dropKey(); |
| 1313 | remembered = false; |
| 1314 | showMode(); |
| 1315 | keyPanel("Forgotten: Aien's notes about you and your introduction are being deleted, and the key is gone from this browser."); |
| 1316 | return; |
| 1317 | } |
| 1318 | setText(state, failure(response, reply, 'Nothing was deleted; your key is still here so you can try again.')); |
| 1319 | } catch (_) { |
| 1320 | setText(state, 'Could not reach Aien. Nothing was deleted; your key is still here so you can try again.'); |
| 1321 | } |
| 1322 | trigger.disabled = false; |
| 1323 | } |
| 1324 | /* Open Humanity volunteer inference: an anonymous visitor may tick the box |
| 1325 | to let a volunteer's Spark answer when Drake's is full. Never with a key, |
| 1326 | never in remember-me mode, never ticked by the page. */ |
| 1327 | function volunteerHeaders() { |
| 1328 | const tick = byId('allen-volunteer'); |
| 1329 | if (remembered || !tick || !tick.checked) return {}; |
| 1330 | return { 'X-Allen-Volunteer': '1' }; |
| 1331 | } |
| 1332 | function setVolunteer(on) { |
| 1333 | const tick = byId('allen-volunteer'); |
| 1334 | if (tick) tick.checked = Boolean(on) && !remembered; |
| 1335 | } |
| 1336 | function volunteerModel(value) { |
| 1337 | const oh = value && typeof value.oh === 'object' && value.oh !== null && !Array.isArray(value.oh) ? value.oh : null; |
| 1338 | if (!oh || oh.answered_by !== 'volunteer') return ''; |
| 1339 | return typeof oh.model === 'string' && oh.model ? oh.model.slice(0, 80) : 'model not reported'; |
| 1340 | } |
| 1341 | /* The badge says which mode the chat is in; its one button switches. */ |
| 1342 | function showMode() { |
| 1343 | root.dataset.mode = remembered ? 'remembered' : 'anonymous'; |
| 1344 | setText(byId('allen-mode'), remembered ? 'Remembered: Aien knows you by your Aien key' : "Anonymous: Aien won't remember this chat"); |
| 1345 | setText(byId('allen-introduce'), remembered ? 'Go anonymous' : 'Remember me'); |
| 1346 | /* The volunteer opt-in belongs to anonymous chat only, and starts off. */ |
| 1347 | const box = byId('allen-volunteer-box'); |
| 1348 | if (box) box.hidden = remembered; |
| 1349 | if (remembered) setVolunteer(false); |
| 1350 | emit('mode', { mode: remembered ? 'remembered' : 'anonymous' }); |
| 1351 | } |
| 1352 | function switchMode() { |
| 1353 | if (remembered) goAnonymous(false); |
| 1354 | else openIntro(); |
| 1355 | } |
| 1356 | /* Go anonymous: the key leaves this browser at once and calls say |
| 1357 | X-Allen-Anonymous from now on. The old key stays in memory only so Forget |
| 1358 | me can still delete notes kept under it; that one call carries it. */ |
| 1359 | function goAnonymous(fromLink) { |
| 1360 | const key = storedKey(); |
| 1361 | dropKey(); |
| 1362 | remembered = false; |
| 1363 | conversation = conversationId(); |
| 1364 | if (key) oldKey = key; |
| 1365 | showMode(); |
| 1366 | keyPanel(); |
| 1367 | if (fromLink) return; |
| 1368 | if (key) offerForget(); |
| 1369 | else notice("Anonymous: Aien won't remember this chat."); |
| 1370 | } |
| 1371 | function offerForget() { |
| 1372 | const note = message('allen', 'Aien'); |
| 1373 | const state = el('div', 'allen-card-state'); |
| 1374 | const forget = button('Forget me', () => forgetOld(forget, state)); |
| 1375 | note.body.append(el('p', 'allen-p', "You are anonymous now: this browser no longer holds your Aien key, and Aien won't recognize you. Notes kept about you earlier stay on Drake's computer unless you delete them."), forget, state); |
| 1376 | } |
| 1377 | async function forgetOld(trigger, state) { |
| 1378 | if (!oldKey) return; |
| 1379 | trigger.disabled = true; |
| 1380 | setText(state, 'Sending.'); |
| 1381 | try { |
| 1382 | const response = await fetch(FORGET_ME, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-Allen-Key': oldKey }, body: '{}', cache: 'no-store', credentials: 'omit' }); |
| 1383 | const reply = await response.json().catch(() => null); |
| 1384 | if (response.ok) { |
| 1385 | oldKey = ''; |
| 1386 | trigger.hidden = true; |
| 1387 | setText(state, "Forgotten: Aien's notes about you and your introduction are being deleted."); |
| 1388 | keyPanel(); |
| 1389 | return; |
| 1390 | } |
| 1391 | setText(state, failure(response, reply, 'Nothing was deleted yet.')); |
| 1392 | } catch (_) { |
| 1393 | setText(state, 'Could not reach Aien. Nothing was deleted yet.'); |
| 1394 | } |
| 1395 | trigger.disabled = false; |
| 1396 | } |
| 1397 | /* What an introduce block becomes while anonymous: an offer, nothing more. */ |
| 1398 | function rememberOffer(prefill) { |
| 1399 | const card = el('div', 'allen-card'); |
| 1400 | card.append(el('p', 'allen-card-h', 'Remember me'), el('p', 'allen-note', "Aien offered to remember you. This chat is anonymous, so nothing about you is kept unless you choose Remember me and agree.")); |
| 1401 | const offer = button('Remember me', () => card.replaceWith(introCard(prefill))); |
| 1402 | card.append(offer); |
| 1403 | return card; |
| 1404 | } |
| 1405 | /* A message Aien offers to pass on. The exact text is shown and goes out |
| 1406 | only when the visitor presses Send to Drake; the conversation is attached |
| 1407 | only if the visitor ticks the box. */ |
| 1408 | function relayCard(parsed, out) { |
| 1409 | const text = parsed.body; |
| 1410 | const name = String(parsed.fields.name || '').slice(0, 100); |
| 1411 | const contact = String(parsed.fields.contact || '').slice(0, 200); |
| 1412 | const card = el('div', 'allen-card allen-relay'); |
| 1413 | card.append(el('p', 'allen-card-h', 'Message for Drake')); |
| 1414 | if (name) { |
| 1415 | const facts = el('dl', 'allen-kv'); |
| 1416 | facts.append(el('dt', '', 'Name'), el('dd', '', name)); |
| 1417 | card.append(facts); |
| 1418 | } |
| 1419 | card.append(el('pre', 'allen-card-body', text)); |
| 1420 | const reach = field(card, 'Your contact, for this one message (optional)', 'input', 200); |
| 1421 | reach.value = contact; |
| 1422 | card.append(el('p', 'allen-note', remembered ? 'The contact goes only into the email to Drake.' : "You are anonymous: the contact goes only into this one email to Drake, and Aien won't keep it.")); |
| 1423 | const state = el('div', 'allen-card-state'); |
| 1424 | if (!text) { |
| 1425 | state.append(el('p', 'allen-err', 'There is no message to send. Ask Aien to write it again.')); |
| 1426 | card.append(state); |
| 1427 | out.replaceChildren(card); |
| 1428 | return; |
| 1429 | } |
| 1430 | const includeWrap = el('label', 'allen-agree'); |
| 1431 | const include = el('input'); |
| 1432 | include.type = 'checkbox'; |
| 1433 | includeWrap.append(include, el('span', '', 'include this conversation')); |
| 1434 | const send = button('Send to Drake', () => sendRelay({ text, name, contact: reach.value.trim().slice(0, 200) }, include, send, state)); |
| 1435 | card.append(el('p', 'allen-note', 'Exactly this text goes to Drake by email. Nothing is sent until you press Send to Drake.'), includeWrap, send, state); |
| 1436 | out.replaceChildren(card); |
| 1437 | } |
| 1438 | function transcript() { |
| 1439 | return turns.slice(-LIMIT.count).map(turn => ({ role: turn.role, content: cut(turn.content, LIMIT.each) })); |
| 1440 | } |
| 1441 | function sessionHeaders() { |
| 1442 | return { 'X-Allen-Conversation': conversation }; |
| 1443 | } |
| 1444 | async function sendRelay(item, include, send, state) { |
| 1445 | send.disabled = true; |
| 1446 | include.disabled = true; |
| 1447 | state.replaceChildren(el('p', 'allen-note', 'Sending.')); |
| 1448 | const body = { message: item.text, name: item.name, contact: item.contact, transcript: include.checked ? transcript() : [] }; |
| 1449 | let response; |
| 1450 | let reply; |
| 1451 | try { |
| 1452 | response = await fetch(RELAY, post(body, sessionHeaders())); |
| 1453 | reply = await response.json().catch(() => null); |
| 1454 | } catch (_) { |
| 1455 | state.replaceChildren(el('p', 'allen-err', 'Could not reach Aien. Nothing was sent.')); |
| 1456 | send.disabled = false; |
| 1457 | include.disabled = false; |
| 1458 | return; |
| 1459 | } |
| 1460 | if (!response.ok || !reply || reply.sent !== true) { |
| 1461 | state.replaceChildren(el('p', 'allen-err', failure(response, reply, 'Nothing was sent.'))); |
| 1462 | send.disabled = false; |
| 1463 | include.disabled = false; |
| 1464 | return; |
| 1465 | } |
| 1466 | send.hidden = true; |
| 1467 | state.replaceChildren(el('p', 'allen-ok', reply.duplicate === true ? 'Sent before: this exact message already reached Drake in this conversation.' : 'Sent.')); |
| 1468 | message('allen', 'Aien').body.append(el('p', 'allen-p', "I've sent this to Drake.")); |
| 1469 | } |
| 1470 | /* Presence comes from the gateway every PRESENCE_MS. Talk to Drake live is |
| 1471 | offered only while he is online and taking handoffs. */ |
| 1472 | const drake = { online: false, handoff: false, hours: '', state: '', stream: null }; |
| 1473 | async function presence() { |
| 1474 | if (document.hidden && drake.hours) return; |
| 1475 | try { |
| 1476 | const response = await fetch(PRESENCE, { cache: 'no-store', credentials: 'omit', headers: { Accept: 'application/json', ...keyHeaders(false) } }); |
| 1477 | const reply = response.ok ? await response.json() : null; |
| 1478 | if (reply && typeof reply === 'object') { |
| 1479 | drake.online = reply.online === true; |
| 1480 | drake.handoff = reply.handoff === true; |
| 1481 | drake.hours = typeof reply.hours === 'string' ? reply.hours.slice(0, 200) : ''; |
| 1482 | } |
| 1483 | } catch (_) { |
| 1484 | /* Keep the last reading. */ |
| 1485 | } |
| 1486 | showPresence(); |
| 1487 | } |
| 1488 | function showPresence() { |
| 1489 | const box = byId('allen-drake'); |
| 1490 | if (!box) return; |
| 1491 | const parts = []; |
| 1492 | if (drake.state === 'waiting') { |
| 1493 | parts.push(el('span', '', 'Waiting for Drake to join. Aien keeps answering until he does.')); |
| 1494 | } else if (drake.state === 'joined') { |
| 1495 | parts.push(el('span', '', 'Drake is here: your messages go to him, not to Aien.')); |
| 1496 | } else if (drake.online && drake.handoff) { |
| 1497 | parts.push(el('span', '', 'Drake is online right now.'), button('Talk to Drake live', event => handoff(event.currentTarget))); |
| 1498 | } else if (drake.hours) { |
| 1499 | parts.push(el('span', '', `Drake's usual hours: ${drake.hours}`)); |
| 1500 | } |
| 1501 | box.replaceChildren(...parts); |
| 1502 | box.hidden = !parts.length; |
| 1503 | box.dataset.state = drake.state || (drake.online && drake.handoff ? 'online' : 'away'); |
| 1504 | emit('presence', { online: drake.online, handoff: drake.handoff, hours: drake.hours, drake: drake.state }); |
| 1505 | } |
| 1506 | async function handoff(trigger) { |
| 1507 | if (drake.state) return; |
| 1508 | trigger.disabled = true; |
| 1509 | try { |
| 1510 | const response = await fetch(HANDOFF, post({ transcript: transcript() }, sessionHeaders())); |
| 1511 | const reply = await response.json().catch(() => null); |
| 1512 | if (!response.ok || !reply || reply.waiting !== true) { |
| 1513 | notice(failure(response, reply, 'Aien is still with you.')); |
| 1514 | trigger.disabled = false; |
| 1515 | return; |
| 1516 | } |
| 1517 | } catch (_) { |
| 1518 | notice('Could not reach Drake. Aien is still with you.'); |
| 1519 | trigger.disabled = false; |
| 1520 | return; |
| 1521 | } |
| 1522 | drake.state = 'waiting'; |
| 1523 | showPresence(); |
| 1524 | session(conversation); |
| 1525 | } |
| 1526 | /* Holds the session stream for this conversation, reconnecting every |
| 1527 | POLL_MS while Drake is waited for or present. */ |
| 1528 | async function session(id) { |
| 1529 | const controller = new AbortController(); |
| 1530 | drake.stream = controller; |
| 1531 | while (drake.stream === controller && drake.state) { |
| 1532 | try { |
| 1533 | const response = await fetch(SESSION, { cache: 'no-store', credentials: 'omit', headers: { Accept: 'text/event-stream', 'X-Allen-Conversation': id, ...keyHeaders(false) }, signal: controller.signal }); |
| 1534 | if (response.ok && response.body) { |
| 1535 | const reader = response.body.getReader(); |
| 1536 | const decoder = new TextDecoder(); |
| 1537 | const parser = sse((name, data) => onSession(name, data, controller)); |
| 1538 | for (;;) { |
| 1539 | const { value, done } = await reader.read(); |
| 1540 | if (done) break; |
| 1541 | parser.feed(decoder.decode(value, { stream: true })); |
| 1542 | } |
| 1543 | parser.feed(decoder.decode()); |
| 1544 | parser.end(); |
| 1545 | } else if (response.status >= 400 && response.status < 500 && response.status !== 429) { |
| 1546 | endSession('Drake is not available right now. Aien is with you again.'); |
| 1547 | return; |
| 1548 | } |
| 1549 | } catch (_) { |
| 1550 | if (controller.signal.aborted) return; |
| 1551 | } |
| 1552 | if (drake.stream !== controller || !drake.state) return; |
| 1553 | await new Promise(done => setTimeout(done, POLL_MS)); |
| 1554 | } |
| 1555 | } |
| 1556 | function onSession(name, data, controller) { |
| 1557 | if (drake.stream !== controller) return; |
| 1558 | let value; |
| 1559 | try { |
| 1560 | value = JSON.parse(data); |
| 1561 | } catch (_) { |
| 1562 | return; |
| 1563 | } |
| 1564 | if (!value || typeof value !== 'object') return; |
| 1565 | if (name === 'human' && typeof value.text === 'string') { |
| 1566 | humanMessage(value.text.slice(0, 8000)); |
| 1567 | emit('human', { text: value.text.slice(0, 8000) }); |
| 1568 | } |
| 1569 | else if (name === 'state' && ['waiting', 'joined', 'left'].includes(value.drake)) { |
| 1570 | if (value.drake === 'left') { |
| 1571 | endSession('Drake handed you back to Aien.'); |
| 1572 | return; |
| 1573 | } |
| 1574 | if (value.drake === 'joined' && drake.state !== 'joined') notice('Drake joined. Your messages now go to him.'); |
| 1575 | drake.state = value.drake; |
| 1576 | emit('drake', { state: value.drake }); |
| 1577 | showPresence(); |
| 1578 | } |
| 1579 | } |
| 1580 | function endSession(text) { |
| 1581 | const stream = drake.stream; |
| 1582 | drake.stream = null; |
| 1583 | drake.state = ''; |
| 1584 | if (stream) stream.abort(); |
| 1585 | emit('drake', { state: '' }); |
| 1586 | showPresence(); |
| 1587 | if (text) message('allen', 'Aien').body.append(el('p', 'allen-p', text)); |
| 1588 | } |
| 1589 | /* The only place the Drake name and avatar are made. It is fed only by |
| 1590 | event: human on the session channel, which the gateway emits only for |
| 1591 | messages typed in Drake's authenticated console. Model tokens and visitor |
| 1592 | text never reach it. */ |
| 1593 | function humanMessage(text) { |
| 1594 | const item = el('li', 'allen-msg allen-msg-drake'); |
| 1595 | const who = el('p', 'allen-who'); |
| 1596 | who.append(el('span', 'allen-avatar', 'D'), document.createTextNode('Drake')); |
| 1597 | const body = el('div', 'allen-body'); |
| 1598 | body.append(el('p', 'allen-p', text)); |
| 1599 | item.append(who, body); |
| 1600 | log.append(item); |
| 1601 | } |
| 1602 | async function sayToDrake(text) { |
| 1603 | message('user', 'You').body.append(el('p', 'allen-p', text)); |
| 1604 | try { |
| 1605 | const response = await fetch(SAY, post({ text }, sessionHeaders())); |
| 1606 | if (!response.ok) { |
| 1607 | const reply = await response.json().catch(() => null); |
| 1608 | notice(failure(response, reply, 'That message did not reach Drake.')); |
| 1609 | } |
| 1610 | } catch (_) { |
| 1611 | notice('That message did not reach Drake. Check your connection.'); |
| 1612 | } |
| 1613 | } |
| 1614 | /* A returning visitor (Aien key kept, not anonymous) gets no static |
| 1615 | greeting: the page sends BACK_LINE as the first turn, unshown, so the |
| 1616 | gateway can bring that visitor's notes and Aien greets them himself. */ |
| 1617 | function start() { |
| 1618 | if (remembered && storedKey()) { |
| 1619 | ask(BACK_LINE, true); |
| 1620 | return; |
| 1621 | } |
| 1622 | greeting(); |
| 1623 | } |
| 1624 | /* Aien's first message is written here, not by the model: zero latency, |
| 1625 | no request. The answer stays in this closure. */ |
| 1626 | function greeting() { |
| 1627 | const hello = message('allen', 'Aien'); |
| 1628 | /* The gateway prepends the remember opening exactly when the chat carries |
| 1629 | a key and no X-Allen-Anonymous, so the page shows the same one. */ |
| 1630 | const greet = remembered && storedKey() ? GREETING_REMEMBER : GREETING_ANONYMOUS; |
| 1631 | hello.body.append(el('p', 'allen-p', greet), el('p', 'allen-p', 'Are you a human or an agent?')); |
| 1632 | const row = el('div', 'allen-choices'); |
| 1633 | row.append(button('Human', () => answer('human')), button('Agent', () => answer('agent')), button('Skip', () => answer(''))); |
| 1634 | hello.body.append(row, el('p', 'allen-note', 'Or just type below. The answer only tells Aien who is asking.')); |
| 1635 | choices = row; |
| 1636 | } |
| 1637 | function openIntro(prefill) { |
| 1638 | const note = message('allen', 'Aien'); |
| 1639 | note.body.append(introCard(prefill || Object.create(null))); |
| 1640 | note.item.scrollIntoView({ block: 'nearest' }); |
| 1641 | } |
| 1642 | function answer(who) { |
| 1643 | if (choices) choices.remove(); |
| 1644 | choices = null; |
| 1645 | if (!who) return; |
| 1646 | kind = who; |
| 1647 | message('user', 'You').body.append(el('p', 'allen-p', who === 'agent' ? 'I am an agent.' : 'I am a human.')); |
| 1648 | const reply = message('allen', 'Aien'); |
| 1649 | if (who === 'human') { |
| 1650 | reply.body.append(el('p', 'allen-p', 'Welcome. What are you building, and where are you from? Ask me anything: I can explain Omega or write you a small program that runs right here.')); |
| 1651 | return; |
| 1652 | } |
| 1653 | reply.body.append( |
| 1654 | el('p', 'allen-p', 'Welcome. Who is your human? Tell me the person or organization operating you. You can keep chatting without naming them.'), |
| 1655 | el('p', 'allen-p', 'To introduce yourself with consent, use the button below, or send POST https://www.aienos.com/aien/api/introduce with JSON (schema in https://www.aienos.com/llms.txt). Nothing is stored without "consent": true.'), |
| 1656 | ); |
| 1657 | const row = el('div', 'allen-choices'); |
| 1658 | row.append(button('Introduce yourself', () => { |
| 1659 | row.remove(); |
| 1660 | openIntro(); |
| 1661 | })); |
| 1662 | reply.body.append(row); |
| 1663 | } |
| 1664 | async function copyText(source, node) { |
| 1665 | if (node.dataset.label === undefined) node.dataset.label = node.textContent; |
| 1666 | try { |
| 1667 | await navigator.clipboard.writeText(source); |
| 1668 | setText(node, 'Copied'); |
| 1669 | } catch (_) { |
| 1670 | setText(node, 'Copy blocked'); |
| 1671 | } |
| 1672 | setTimeout(() => setText(node, node.dataset.label), 1500); |
| 1673 | } |
| 1674 | /* The policy becomes the first element of the program's head: after an |
| 1675 | existing head tag that only whitespace, a doctype, comments and an html |
| 1676 | tag precede, else in a head of its own placed after any doctype and html |
| 1677 | tag. A linear scan (no backtracking regex): each comment ends at its |
| 1678 | first -->, as the HTML parser ends it. */ |
| 1679 | function sandboxed(source) { |
| 1680 | const meta = `<meta http-equiv="Content-Security-Policy" content="${CSP}">`; |
| 1681 | const lower = source.toLowerCase(); |
| 1682 | let at = 0; |
| 1683 | const space = () => { |
| 1684 | while (at < source.length && /\s/.test(source[at])) at += 1; |
| 1685 | }; |
| 1686 | const tag = name => { |
| 1687 | const open = `<${name}`; |
| 1688 | if (!lower.startsWith(open, at)) return false; |
| 1689 | const next = source[at + open.length]; |
| 1690 | if (next !== '>' && !(next && /\s/.test(next))) return false; |
| 1691 | const close = source.indexOf('>', at + open.length); |
| 1692 | if (close < 0) return false; |
| 1693 | at = close + 1; |
| 1694 | return true; |
| 1695 | }; |
| 1696 | const doctype = () => { |
| 1697 | if (!lower.startsWith('<!doctype', at)) return false; |
| 1698 | const close = source.indexOf('>', at + 9); |
| 1699 | if (close < 0) return false; |
| 1700 | at = close + 1; |
| 1701 | return true; |
| 1702 | }; |
| 1703 | const comments = () => { |
| 1704 | for (;;) { |
| 1705 | space(); |
| 1706 | if (!lower.startsWith('<!--', at)) return; |
| 1707 | const close = source.indexOf('-->', at + 4); |
| 1708 | if (close < 0) return; |
| 1709 | at = close + 3; |
| 1710 | } |
| 1711 | }; |
| 1712 | space(); |
| 1713 | if (doctype()) space(); |
| 1714 | const lead = (() => { |
| 1715 | const mark = at; |
| 1716 | const html = tag('html'); |
| 1717 | const end = at; |
| 1718 | at = mark; |
| 1719 | return html ? end : mark; |
| 1720 | })(); |
| 1721 | comments(); |
| 1722 | if (tag('html')) comments(); |
| 1723 | if (tag('head')) return source.slice(0, at) + meta + source.slice(at); |
| 1724 | return `${source.slice(0, lead)}<head>${meta}</head>${source.slice(lead)}`; |
| 1725 | } |
| 1726 | /* The page policy forbids inline scripts, and a srcdoc frame would inherit |
| 1727 | it, so the program runs in /aien/run.html, the one document whose policy |
| 1728 | allows them. That document writes only what its parent posts, and only |
| 1729 | while sandboxed to an opaque origin. */ |
| 1730 | function runHtml(source, out) { |
| 1731 | const frame = document.createElement('iframe'); |
| 1732 | frame.setAttribute('sandbox', SANDBOX); |
| 1733 | frame.setAttribute('referrerpolicy', 'no-referrer'); |
| 1734 | frame.setAttribute('title', 'Program written by Aien, sandboxed'); |
| 1735 | frame.className = 'allen-frame'; |
| 1736 | frame.addEventListener('load', () => frame.contentWindow.postMessage(sandboxed(source), '*'), { once: true }); |
| 1737 | frame.src = '/aien/run.html'; |
| 1738 | const box = el('div', 'allen-frame-box'); |
| 1739 | box.append(frame); |
| 1740 | out.replaceChildren(box, el('p', 'allen-note', 'Sandboxed: its scripts run with no access to this page or your cookies, and its content security policy blocks network loads. Drag the corner to resize.')); |
| 1741 | } |
| 1742 | function retryAfter(response, body) { |
| 1743 | const value = Number(body && body.retry_after !== undefined ? body.retry_after : response.headers.get('Retry-After')); |
| 1744 | return Number.isFinite(value) && value > 0 ? Math.ceil(value) : 0; |
| 1745 | } |
| 1746 | function refusal(code, body) { |
| 1747 | const said = body && typeof body.message === 'string' ? body.message.slice(0, 300) : ''; |
| 1748 | if (code === 429) return 'You are sending faster than Aien takes turns.'; |
| 1749 | if (code === 503) return 'Aien is busy with other visitors right now.'; |
| 1750 | if (code === 413) return 'That is longer than Aien accepts in one go. Shorten it, or start a new conversation.'; |
| 1751 | if (code === 400) return `Aien could not read that request${said ? `: ${said}` : '.'}`; |
| 1752 | return `Aien is unreachable right now (HTTP ${code}).`; |
| 1753 | } |
| 1754 | /* Status line text, with a live countdown when the gateway says when to retry. */ |
| 1755 | function notice(text, wait) { |
| 1756 | clearInterval(countdown); |
| 1757 | emit('status', { text, wait: wait || 0 }); |
| 1758 | if (!wait) { |
| 1759 | setText(status, text); |
| 1760 | return; |
| 1761 | } |
| 1762 | let left = wait; |
| 1763 | const show = () => setText(status, left > 0 ? `${text} Try again in ${left} s.` : `${text} You can try again now.`); |
| 1764 | show(); |
| 1765 | countdown = setInterval(() => { |
| 1766 | left -= 1; |
| 1767 | show(); |
| 1768 | if (left <= 0) clearInterval(countdown); |
| 1769 | }, 1000); |
| 1770 | } |
| 1771 | /* Omega scalar types: i32 for the narrow ones (JS Number), i64 for the wide |
| 1772 | ones (JS BigInt). Inputs are checked against the declared range. */ |
| 1773 | const TYPES = { |
| 1774 | bool: { wide: false, min: 0n, max: 1n }, |
| 1775 | uchar: { wide: false, min: 0n, max: 255n }, |
| 1776 | ushort: { wide: false, min: 0n, max: 65535n }, |
| 1777 | uint: { wide: false, min: 0n, max: 4294967295n }, |
| 1778 | byte: { wide: false, min: -128n, max: 127n }, |
| 1779 | short: { wide: false, min: -32768n, max: 32767n }, |
| 1780 | int: { wide: false, min: -2147483648n, max: 2147483647n }, |
| 1781 | ulong: { wide: true, min: 0n, max: 18446744073709551615n }, |
| 1782 | long: { wide: true, min: -9223372036854775808n, max: 9223372036854775807n }, |
| 1783 | }; |
| 1784 | const known = type => typeof type === 'string' && Object.hasOwn(TYPES, type); |
| 1785 | function argument(type, raw) { |
| 1786 | const range = TYPES[type]; |
| 1787 | const text = raw.trim(); |
| 1788 | if (type === 'bool' && /^(true|false)$/i.test(text)) return text.toLowerCase() === 'true' ? 1 : 0; |
| 1789 | if (!/^-?\d{1,20}$/.test(text)) throw new RangeError('needs a whole number'); |
| 1790 | const value = BigInt(text); |
| 1791 | if (value < range.min || value > range.max) throw new RangeError(`must be ${range.min} to ${range.max}`); |
| 1792 | return range.wide ? value : Number(value); |
| 1793 | } |
| 1794 | /* wasm hands back i32 as a signed Number and i64 as a signed BigInt; show |
| 1795 | each value the way its Omega type reads it. */ |
| 1796 | function shown(type, value) { |
| 1797 | switch (type) { |
| 1798 | case 'bool': return value !== 0 ? 'true' : 'false'; |
| 1799 | case 'uchar': return String(value & 255); |
| 1800 | case 'ushort': return String(value & 65535); |
| 1801 | case 'uint': return String(value >>> 0); |
| 1802 | case 'byte': return String((value << 24) >> 24); |
| 1803 | case 'short': return String((value << 16) >> 16); |
| 1804 | case 'int': return String(value | 0); |
| 1805 | case 'ulong': return BigInt.asUintN(64, value).toString(); |
| 1806 | case 'long': return BigInt.asIntN(64, value).toString(); |
| 1807 | default: return value === undefined ? 'done' : String(value); |
| 1808 | } |
| 1809 | } |
| 1810 | /* Runs inside a dedicated worker, so a long loop never freezes this page: |
| 1811 | the page ends the worker when a call overruns CALL_MS. */ |
| 1812 | function workerMain() { |
| 1813 | let ready = null; |
| 1814 | self.onmessage = async event => { |
| 1815 | const job = event.data; |
| 1816 | if (job.module) { |
| 1817 | ready = WebAssembly.instantiate(job.module, {}); |
| 1818 | ready.catch(() => {}); |
| 1819 | return; |
| 1820 | } |
| 1821 | try { |
| 1822 | const instance = await ready; |
| 1823 | const value = instance.exports[job.name](...job.args); |
| 1824 | self.postMessage({ id: job.id, ok: true, value }); |
| 1825 | } catch (error) { |
| 1826 | self.postMessage({ id: job.id, ok: false, trap: error instanceof WebAssembly.RuntimeError, message: String((error && error.message) || error) }); |
| 1827 | } |
| 1828 | }; |
| 1829 | } |
| 1830 | function runner(module) { |
| 1831 | let worker = null; |
| 1832 | let next = 0; |
| 1833 | const pending = new Map(); |
| 1834 | function stop() { |
| 1835 | if (worker) worker.terminate(); |
| 1836 | worker = null; |
| 1837 | for (const job of pending.values()) { |
| 1838 | clearTimeout(job.timer); |
| 1839 | job.done({ ok: false, message: 'the runner was reset' }); |
| 1840 | } |
| 1841 | pending.clear(); |
| 1842 | } |
| 1843 | function start() { |
| 1844 | const url = URL.createObjectURL(new Blob([`(${workerMain.toString()})();`], { type: 'text/javascript' })); |
| 1845 | worker = new Worker(url); |
| 1846 | URL.revokeObjectURL(url); |
| 1847 | worker.onmessage = event => { |
| 1848 | const job = pending.get(event.data.id); |
| 1849 | if (!job) return; |
| 1850 | pending.delete(event.data.id); |
| 1851 | clearTimeout(job.timer); |
| 1852 | job.done(event.data); |
| 1853 | }; |
| 1854 | worker.onerror = event => { |
| 1855 | event.preventDefault(); |
| 1856 | stop(); |
| 1857 | }; |
| 1858 | worker.postMessage({ module }); |
| 1859 | } |
| 1860 | function run(name, args) { |
| 1861 | if (!worker) start(); |
| 1862 | return new Promise(done => { |
| 1863 | const id = next; |
| 1864 | next += 1; |
| 1865 | const timer = setTimeout(() => { |
| 1866 | pending.delete(id); |
| 1867 | stop(); |
| 1868 | done({ ok: false, timeout: true }); |
| 1869 | }, CALL_MS); |
| 1870 | pending.set(id, { timer, done }); |
| 1871 | worker.postMessage({ id, name, args }); |
| 1872 | }); |
| 1873 | } |
| 1874 | const handle = { run, stop }; |
| 1875 | runners.add(handle); |
| 1876 | return handle; |
| 1877 | } |
| 1878 | function fnForm(fn, exported, machine) { |
| 1879 | const name = typeof fn.name === 'string' ? fn.name : ''; |
| 1880 | const params = Array.isArray(fn.params) ? fn.params : []; |
| 1881 | const ret = typeof fn.ret === 'string' ? fn.ret : 'void'; |
| 1882 | const form = el('form', 'allen-fn'); |
| 1883 | form.noValidate = true; |
| 1884 | const head = el('p', 'allen-sig'); |
| 1885 | head.append(el('code', '', signature({ name, params, ret }))); |
| 1886 | form.append(head); |
| 1887 | const fields = params.map(param => { |
| 1888 | const label = el('label', 'allen-arg'); |
| 1889 | label.append(el('span', '', `${param.name}: ${param.type}`)); |
| 1890 | const field = el('input'); |
| 1891 | field.type = 'text'; |
| 1892 | field.inputMode = 'numeric'; |
| 1893 | field.autocomplete = 'off'; |
| 1894 | field.spellcheck = false; |
| 1895 | if (known(param.type)) field.placeholder = `${TYPES[param.type].min} to ${TYPES[param.type].max}`; |
| 1896 | label.append(field); |
| 1897 | form.append(label); |
| 1898 | return field; |
| 1899 | }); |
| 1900 | const call = el('button', 'allen-tool', 'Call'); |
| 1901 | call.type = 'submit'; |
| 1902 | const result = el('output', 'allen-result'); |
| 1903 | form.append(call, result); |
| 1904 | if (!exported.has(name) || !params.every(p => known(p.type)) || !(ret === 'void' || known(ret))) { |
| 1905 | call.disabled = true; |
| 1906 | setText(result, 'This function uses a type this page cannot call.'); |
| 1907 | } |
| 1908 | form.addEventListener('submit', async event => { |
| 1909 | event.preventDefault(); |
| 1910 | const args = []; |
| 1911 | for (let i = 0; i < params.length; i += 1) { |
| 1912 | try { |
| 1913 | args.push(argument(params[i].type, fields[i].value)); |
| 1914 | } catch (error) { |
| 1915 | setText(result, `${params[i].name} ${error.message}`); |
| 1916 | fields[i].focus(); |
| 1917 | return; |
| 1918 | } |
| 1919 | } |
| 1920 | call.disabled = true; |
| 1921 | setText(result, 'running'); |
| 1922 | const answer = await machine.run(name, args); |
| 1923 | call.disabled = false; |
| 1924 | if (answer.ok) setText(result, `= ${shown(ret, answer.value)}`); |
| 1925 | else if (answer.timeout) setText(result, `stopped: no answer within ${CALL_MS / 1000} s, so the runner was reset`); |
| 1926 | else if (answer.trap) setText(result, `trapped: ${answer.message}`); |
| 1927 | else setText(result, `error: ${answer.message}`); |
| 1928 | }); |
| 1929 | return form; |
| 1930 | } |
| 1931 | async function omegaReady(reply, out, project) { |
| 1932 | const bytes = Uint8Array.from(atob(reply.wasm), c => c.charCodeAt(0)); |
| 1933 | const module = await WebAssembly.compile(bytes); |
| 1934 | const exported = new Set(WebAssembly.Module.exports(module).filter(item => item.kind === 'function').map(item => item.name)); |
| 1935 | const machine = runner(module); |
| 1936 | const panel = el('div', 'allen-wasm'); |
| 1937 | const pin = typeof reply.omc_sha256 === 'string' ? reply.omc_sha256.slice(0, 12) : '?'; |
| 1938 | panel.append(el('p', 'allen-note', `Omega compiled to WebAssembly by the pinned seeded compiler on the Spark, running in your browser. Compiled in ${count(reply.compile_ms)} ms to ${bytes.length} bytes of wasm with no imports (omc ${pin}).`)); |
| 1939 | const list = Array.isArray(reply.functions) ? reply.functions : []; |
| 1940 | for (const fn of list) panel.append(fnForm(fn, exported, machine)); |
| 1941 | if (!list.length) panel.append(el('p', 'allen-note', 'This unit exports no functions.')); |
| 1942 | out.replaceChildren(panel); |
| 1943 | project.wasm = bytes; |
| 1944 | project.functions = list.filter(fn => fn && typeof fn.name === 'string'); |
| 1945 | project.pin = typeof reply.omc_sha256 === 'string' && /^[0-9a-f]{64}$/.test(reply.omc_sha256) ? reply.omc_sha256 : ''; |
| 1946 | if (project.wasmButton) { |
| 1947 | project.wasmButton.disabled = false; |
| 1948 | project.wasmButton.title = ''; |
| 1949 | } |
| 1950 | if (project.htmlButton) project.htmlButton.hidden = false; |
| 1951 | } |
| 1952 | function omegaFailed(source, reply, out) { |
| 1953 | const where = reply.stage === 'irwasm' ? 'The WebAssembly translator refused it' : reply.stage === 'limit' ? 'It is over a size limit' : 'The Omega compiler refused it'; |
| 1954 | const message = typeof reply.message === 'string' ? reply.message.slice(0, 500) : 'no message'; |
| 1955 | const hint = typeof reply.hint === 'string' ? reply.hint.slice(0, 500) : ''; |
| 1956 | const box = el('div', 'allen-fail'); |
| 1957 | box.append(el('p', 'allen-err', `${where}: ${message}`)); |
| 1958 | if (hint) box.append(el('p', 'allen-note', hint)); |
| 1959 | box.append(button('Ask Aien to fix it', () => fixRequest(source, message, hint))); |
| 1960 | out.replaceChildren(box); |
| 1961 | } |
| 1962 | function fixRequest(source, message, hint) { |
| 1963 | const head = `This Omega did not compile. The gateway said: ${message}${hint ? `\nHint: ${hint}` : ''}\nPlease fix it and show the whole corrected unit.\n\n\`\`\`omega\n`; |
| 1964 | const room = LIMIT.each - head.length - 4; |
| 1965 | const body = source.length > room ? `${cut(source, Math.max(0, room - 20))}\n(source cut to fit)` : source; |
| 1966 | ask(`${head}${body}\n\`\`\``); |
| 1967 | } |
| 1968 | async function compileOmega(source, out, trigger, project) { |
| 1969 | if (new TextEncoder().encode(source).length > LIMIT.source) { |
| 1970 | out.replaceChildren(el('p', 'allen-err', `This source is over the ${LIMIT.source} byte limit for compiling.`)); |
| 1971 | return; |
| 1972 | } |
| 1973 | trigger.disabled = true; |
| 1974 | out.replaceChildren(el('p', 'allen-note', 'Compiling on the Spark.')); |
| 1975 | try { |
| 1976 | const response = await fetch(OMEGA, post({ source })); |
| 1977 | const reply = await response.json().catch(() => null); |
| 1978 | if (!response.ok || !reply || typeof reply !== 'object') { |
| 1979 | out.replaceChildren(el('p', 'allen-err', failure(response, reply, ''))); |
| 1980 | } else if (reply.ok === true && typeof reply.wasm === 'string') { |
| 1981 | await omegaReady(reply, out, project); |
| 1982 | } else { |
| 1983 | omegaFailed(source, reply, out); |
| 1984 | } |
| 1985 | } catch (error) { |
| 1986 | out.replaceChildren(el('p', 'allen-err', `Could not compile and load it: ${error.message}`)); |
| 1987 | } finally { |
| 1988 | trigger.disabled = false; |
| 1989 | } |
| 1990 | } |
| 1991 | function message(role, label) { |
| 1992 | const item = el('li', `allen-msg allen-msg-${role}`); |
| 1993 | /* Aien's own words, in his voice, as opposed to Drake's page copy. */ |
| 1994 | if (role === 'allen') item.dataset.speaker = 'allen'; |
| 1995 | item.append(el('p', 'allen-who', label)); |
| 1996 | const body = el('div', 'allen-body'); |
| 1997 | item.append(body); |
| 1998 | log.append(item); |
| 1999 | return { item, body }; |
| 2000 | } |
| 2001 | /* Aien's voice: first-party clips the gateway names for a reply in its |
| 2002 | meta event. Off until the visitor turns it on; the choice lives in page |
| 2003 | memory only, never in browser storage. One Audio element plays a turn's |
| 2004 | clips in order; a clip that fails is skipped silently, since the text is |
| 2005 | already on the page. */ |
| 2006 | const voice = { on: false, list: [], at: -1, audio: null }; |
| 2007 | function voiceClips(value) { |
| 2008 | const list = value && Array.isArray(value.voice) ? value.voice : []; |
| 2009 | return list |
| 2010 | .filter(c => c && typeof c.file === 'string' && c.file.startsWith(VOICE_DIR) && c.file.endsWith('.mp3') && !c.file.includes('..') && /^[\x21-\x7e]{1,200}$/.test(c.file)) |
| 2011 | .slice(0, 24) |
| 2012 | .map(c => Object.freeze({ id: typeof c.id === 'string' ? c.id.slice(0, 80) : '', file: c.file, text: typeof c.text === 'string' ? c.text.slice(0, 2000) : '', duration: Number.isFinite(c.duration) ? c.duration : NaN })); |
| 2013 | } |
| 2014 | function voiceShow() { |
| 2015 | const toggle = byId('allen-voice'); |
| 2016 | const next = byId('allen-voice-next'); |
| 2017 | if (toggle) { |
| 2018 | toggle.setAttribute('aria-pressed', String(voice.on)); |
| 2019 | setText(toggle, voice.on ? 'Voice: on' : 'Voice: off'); |
| 2020 | } |
| 2021 | if (next) next.hidden = !voice.on || voice.list.length === 0; |
| 2022 | emit('voiceState', { on: voice.on, playing: Boolean(voice.audio && !voice.audio.paused), clip: voice.list[voice.at] || null, left: Math.max(0, voice.list.length - voice.at - 1) }); |
| 2023 | } |
| 2024 | function voicePlay(i) { |
| 2025 | if (!voice.on || i < 0 || i >= voice.list.length) { |
| 2026 | voice.at = voice.list.length; |
| 2027 | voiceShow(); |
| 2028 | return; |
| 2029 | } |
| 2030 | if (!voice.audio) { |
| 2031 | voice.audio = new Audio(); |
| 2032 | voice.audio.preload = 'auto'; |
| 2033 | voice.audio.addEventListener('ended', () => voicePlay(voice.at + 1)); |
| 2034 | voice.audio.addEventListener('error', () => voicePlay(voice.at + 1)); |
| 2035 | } |
| 2036 | voice.at = i; |
| 2037 | voice.audio.src = voice.list[i].file; |
| 2038 | const playing = voice.audio.play(); |
| 2039 | if (playing && playing.catch) playing.catch(() => voiceShow()); |
| 2040 | voiceShow(); |
| 2041 | } |
| 2042 | function voiceStop() { |
| 2043 | if (voice.audio) voice.audio.pause(); |
| 2044 | voice.at = voice.list.length; |
| 2045 | } |
| 2046 | /* A new turn replaces whatever the last one was still saying. */ |
| 2047 | function voiceQueue(clips) { |
| 2048 | voiceStop(); |
| 2049 | voice.list = clips; |
| 2050 | voice.at = -1; |
| 2051 | if (voice.on && clips.length) voicePlay(0); |
| 2052 | else voiceShow(); |
| 2053 | } |
| 2054 | function voiceNext() { |
| 2055 | if (!voice.list.length) return; |
| 2056 | voicePlay(voice.at + 1 < voice.list.length ? voice.at + 1 : voice.list.length - 1); |
| 2057 | } |
| 2058 | function voiceEnable(on) { |
| 2059 | voice.on = Boolean(on); |
| 2060 | if (!voice.on) voiceStop(); |
| 2061 | else if (voice.list.length && voice.at < 0) voicePlay(0); |
| 2062 | voiceShow(); |
| 2063 | } |
| 2064 | function speedReset() { |
| 2065 | for (const key of ['queue', 'ttft', 'first', 'rate', 'tokens', 'server']) setText(speed[key], '-'); |
| 2066 | } |
| 2067 | function busy(on) { |
| 2068 | sendButton.disabled = on; |
| 2069 | stopButton.disabled = !on; |
| 2070 | root.dataset.busy = String(on); |
| 2071 | for (const example of examples.querySelectorAll('button')) example.disabled = on; |
| 2072 | } |
| 2073 | /* One server event. Times are this page's own clock: queue wait runs from |
| 2074 | Send to the start event, model time to first token from the start event to |
| 2075 | the first non-empty token, and the rate counts tokens after the first. */ |
| 2076 | function onEvent(name, data, clock, render) { |
| 2077 | let value; |
| 2078 | try { |
| 2079 | value = JSON.parse(data); |
| 2080 | } catch (_) { |
| 2081 | return; |
| 2082 | } |
| 2083 | const now = performance.now(); |
| 2084 | if (name === 'message') { |
| 2085 | if (typeof value !== 'string') return; |
| 2086 | clock.tokens += 1; |
| 2087 | if (Number.isNaN(clock.first)) { |
| 2088 | if (value) { |
| 2089 | clock.first = now; |
| 2090 | setText(speed.ttft, ms(now - clock.start)); |
| 2091 | setText(speed.first, ms(now - clock.sent)); |
| 2092 | notice('Aien is answering.'); |
| 2093 | } |
| 2094 | } else { |
| 2095 | clock.after += 1; |
| 2096 | clock.last = now; |
| 2097 | const span = clock.last - clock.first; |
| 2098 | if (span > 0) setText(speed.rate, (clock.after * 1000 / span).toFixed(1)); |
| 2099 | } |
| 2100 | setText(speed.tokens, String(clock.tokens)); |
| 2101 | if (value) render.push(value); |
| 2102 | emit('token', { text: value, tokens: clock.tokens, ttftMs: clock.first - clock.start, firstMs: clock.first - clock.sent, rate: clock.last > clock.first ? clock.after * 1000 / (clock.last - clock.first) : NaN }); |
| 2103 | } else if (name === 'queue' && value && Number.isSafeInteger(value.position)) { |
| 2104 | setText(speed.queue, `waiting, ${value.position} ahead`); |
| 2105 | notice(`In line: ${value.position} ${value.position === 1 ? 'request' : 'requests'} ahead of you.`); |
| 2106 | emit('queue', { position: value.position }); |
| 2107 | } else if (name === 'start' && value) { |
| 2108 | if (volunteerModel(value)) clock.volunteer = volunteerModel(value); |
| 2109 | clock.start = now; |
| 2110 | setText(speed.queue, `${ms(now - clock.sent)} (server ${count(value.queued_ms)} ms)`); |
| 2111 | if (typeof value.model === 'string' && value.model.length <= 80) setText(speed.model, value.model); |
| 2112 | notice('The model has your message.'); |
| 2113 | emit('start', { model: typeof value.model === 'string' ? value.model.slice(0, 80) : '', queuedMs: Number.isFinite(value.queued_ms) ? value.queued_ms : NaN, queueWaitMs: now - clock.sent }); |
| 2114 | } else if (name === 'meta' && value && typeof value === 'object' && !Array.isArray(value)) { |
| 2115 | /* Sent after start, before the first token; no voice key means text only. */ |
| 2116 | const clips = voiceClips(value); |
| 2117 | emit('voice', { clips, source: typeof value.source === 'string' ? value.source.slice(0, 40) : '' }); |
| 2118 | voiceQueue(clips); |
| 2119 | } else if (name === 'done' && value) { |
| 2120 | if (volunteerModel(value)) clock.volunteer = volunteerModel(value); |
| 2121 | clock.finished = true; |
| 2122 | setText(speed.server, `prompt ${count(value.prompt_tokens)}, completion ${count(value.completion_tokens)} tokens; first token ${count(value.upstream_ttft_ms)} ms, whole reply ${count(value.upstream_ms)} ms`); |
| 2123 | if (value.finish === 'length') clock.outcome = 'The reply reached its length limit and was cut off.'; |
| 2124 | emit('done', { promptTokens: value.prompt_tokens, completionTokens: value.completion_tokens, finish: value.finish === 'length' ? 'length' : 'stop', upstreamTtftMs: value.upstream_ttft_ms, upstreamMs: value.upstream_ms }); |
| 2125 | } else if (/^pane\.(open|update|close)$/.test(name) && value && typeof value === 'object' && !Array.isArray(value)) { |
| 2126 | /* Science panes ride the chat stream; the page UI renders them. */ |
| 2127 | emit(name, value); |
| 2128 | } else if (name === 'error' && value) { |
| 2129 | clock.finished = true; |
| 2130 | const said = typeof value.message === 'string' ? value.message.slice(0, 300) : 'no message'; |
| 2131 | emit('error', { code: typeof value.code === 'string' ? value.code.slice(0, 40) : '', message: said }); |
| 2132 | clock.outcome = value.code === 'human' ? 'Drake is answering you directly; Aien stays quiet until he hands you back.' : value.code === 'busy' ? `Aien is busy: ${said}` : value.code === 'timeout' ? `The model took too long: ${said}` : `The model stopped with an error: ${said}`; |
| 2133 | } |
| 2134 | } |
| 2135 | async function stream(body, clock, render) { |
| 2136 | const reader = body.getReader(); |
| 2137 | const decoder = new TextDecoder(); |
| 2138 | const parser = sse((name, data) => onEvent(name, data, clock, render)); |
| 2139 | for (;;) { |
| 2140 | const { value, done } = await reader.read(); |
| 2141 | if (done) break; |
| 2142 | parser.feed(decoder.decode(value, { stream: true })); |
| 2143 | } |
| 2144 | parser.feed(decoder.decode()); |
| 2145 | parser.end(); |
| 2146 | if (!clock.finished && !clock.outcome) clock.outcome = 'The connection closed before Aien finished.'; |
| 2147 | } |
| 2148 | async function ask(raw, silent = false) { |
| 2149 | const text = cut(String(raw).trim(), LIMIT.each); |
| 2150 | if (!text) return; |
| 2151 | if (choices) { |
| 2152 | choices.remove(); |
| 2153 | choices = null; |
| 2154 | } |
| 2155 | if (drake.state === 'joined') { |
| 2156 | sayToDrake(text); |
| 2157 | return; |
| 2158 | } |
| 2159 | if (active) { |
| 2160 | notice('Aien is still answering. Stop that reply first, or wait for it.'); |
| 2161 | return; |
| 2162 | } |
| 2163 | const mine = epoch; |
| 2164 | const controller = new AbortController(); |
| 2165 | active = controller; |
| 2166 | busy(true); |
| 2167 | speedReset(); |
| 2168 | turns.push({ role: 'user', content: text }); |
| 2169 | if (!silent) message('user', 'You').body.append(el('p', 'allen-p', text)); |
| 2170 | const reply = message('allen', 'Aien'); |
| 2171 | reply.item.setAttribute('aria-busy', 'true'); |
| 2172 | const render = renderer(reply.body); |
| 2173 | emit('send', { text, silent }); |
| 2174 | voiceQueue([]); |
| 2175 | const clock = { sent: performance.now(), start: NaN, first: NaN, last: NaN, tokens: 0, after: 0, finished: false, outcome: '', volunteer: '' }; |
| 2176 | let wait = 0; |
| 2177 | notice('Sending.'); |
| 2178 | try { |
| 2179 | const response = await fetch(CHAT, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream', 'X-Allen-Hour': String(new Date().getHours()), ...keyHeaders(true), ...volunteerHeaders() }, body: JSON.stringify({ messages: fit(turns) }), cache: 'no-store', credentials: 'omit', signal: controller.signal }); |
| 2180 | if (!response.ok) { |
| 2181 | const body = await response.json().catch(() => null); |
| 2182 | wait = retryAfter(response, body); |
| 2183 | clock.outcome = refusal(response.status, body); |
| 2184 | } else if (!response.body || !(response.headers.get('content-type') || '').includes('text/event-stream')) { |
| 2185 | clock.outcome = 'Aien answered in a form this page does not read.'; |
| 2186 | } else { |
| 2187 | /* The coordinator names the volunteer's model in X-OH-Model, and the |
| 2188 | final chunk's oh object says the same. */ |
| 2189 | const header = response.headers.get('X-OH-Model') || response.headers.get('X-OH-Volunteer'); |
| 2190 | if (header) clock.volunteer = /^[\x20-\x7e]{1,80}$/.test(header) && header !== '1' ? header : 'model not reported'; |
| 2191 | await stream(response.body, clock, render); |
| 2192 | } |
| 2193 | } catch (error) { |
| 2194 | clock.outcome = controller.signal.aborted ? 'Stopped.' : 'Could not reach Aien. Check your connection and try again.'; |
| 2195 | } |
| 2196 | const said = render.finish(); |
| 2197 | reply.item.removeAttribute('aria-busy'); |
| 2198 | if (active === controller) active = null; |
| 2199 | busy(false); |
| 2200 | if (mine !== epoch) return; |
| 2201 | if (said.trim()) { |
| 2202 | turns.push({ role: 'assistant', content: said }); |
| 2203 | } else { |
| 2204 | turns.pop(); |
| 2205 | if (!input.value) input.value = text; |
| 2206 | } |
| 2207 | if (clock.volunteer) reply.item.append(el('p', 'allen-note allen-volunteer-note', `answered by a volunteer's Spark (${clock.volunteer})`)); |
| 2208 | if (clock.outcome) reply.item.append(el('p', 'allen-err', clock.outcome)); |
| 2209 | notice(clock.outcome && !said ? clock.outcome : '', wait); |
| 2210 | emit('reply', { text: said, outcome: clock.outcome, volunteer: clock.volunteer }); |
| 2211 | } |
| 2212 | /* Ask again for the last reply: the last answer leaves the history and the |
| 2213 | same user turn is sent once more, unshown, so it is never duplicated. */ |
| 2214 | function regenerate() { |
| 2215 | if (active || drake.state === 'joined') return false; |
| 2216 | const n = turns.length; |
| 2217 | if (n < 2 || turns[n - 1].role !== 'assistant' || turns[n - 2].role !== 'user') return false; |
| 2218 | turns.pop(); |
| 2219 | const last = turns.pop(); |
| 2220 | ask(last.content, true); |
| 2221 | return true; |
| 2222 | } |
| 2223 | /* /aien/#draft=<text>: another page hands the visitor a message to start |
| 2224 | from. It only fills the input for editing and is never sent by itself; |
| 2225 | the hash is cleared at once. */ |
| 2226 | let draftText = ''; |
| 2227 | function takeDraft() { |
| 2228 | const match = /^#draft=([\s\S]*)$/.exec(location.hash); |
| 2229 | if (!match) return; |
| 2230 | let text = ''; |
| 2231 | try { |
| 2232 | text = decodeURIComponent(match[1]); |
| 2233 | } catch (_) { |
| 2234 | text = ''; |
| 2235 | } |
| 2236 | try { |
| 2237 | history.replaceState(null, '', location.pathname + location.search); |
| 2238 | } catch (_) { |
| 2239 | /* The draft still fills the input. */ |
| 2240 | } |
| 2241 | text = cut(text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ''), 2000); |
| 2242 | if (!text.trim()) return; |
| 2243 | draftText = text; |
| 2244 | input.value = text; |
| 2245 | emit('draft', { text }); |
| 2246 | } |
| 2247 | form.addEventListener('submit', event => { |
| 2248 | event.preventDefault(); |
| 2249 | if (active) { |
| 2250 | notice('Aien is still answering. Stop that reply first, or wait for it.'); |
| 2251 | return; |
| 2252 | } |
| 2253 | const text = input.value; |
| 2254 | if (!text.trim()) return; |
| 2255 | input.value = ''; |
| 2256 | ask(text); |
| 2257 | }); |
| 2258 | input.addEventListener('keydown', event => { |
| 2259 | if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { |
| 2260 | event.preventDefault(); |
| 2261 | form.requestSubmit(); |
| 2262 | } |
| 2263 | }); |
| 2264 | stopButton.addEventListener('click', () => { |
| 2265 | if (active) active.abort(); |
| 2266 | }); |
| 2267 | newButton.addEventListener('click', () => { |
| 2268 | epoch += 1; |
| 2269 | if (active) active.abort(); |
| 2270 | if (drake.state) endSession(''); |
| 2271 | voiceQueue([]); |
| 2272 | turns.length = 0; |
| 2273 | kind = ''; |
| 2274 | conversation = conversationId(); |
| 2275 | for (const machine of runners) machine.stop(); |
| 2276 | runners.clear(); |
| 2277 | log.replaceChildren(); |
| 2278 | speedReset(); |
| 2279 | start(); |
| 2280 | notice('New conversation. Nothing from the last one was kept.'); |
| 2281 | input.focus(); |
| 2282 | }); |
| 2283 | for (const example of examples.querySelectorAll('button')) { |
| 2284 | example.addEventListener('click', () => ask(example.textContent)); |
| 2285 | } |
| 2286 | byId('allen-introduce').addEventListener('click', switchMode); |
| 2287 | byId('allen-voice').addEventListener('click', () => voiceEnable(!voice.on)); |
| 2288 | byId('allen-voice-next').addEventListener('click', voiceNext); |
| 2289 | window.addEventListener('hashchange', forgetOffer); |
| 2290 | window.addEventListener('hashchange', takeDraft); |
| 2291 | conversation = conversationId(); |
| 2292 | /* /aien/?mode=anonymous forces anonymous and clears any key; otherwise a |
| 2293 | key kept after an earlier Remember me means this visitor opted in. |
| 2294 | /aien/?mode=remember only opens the consent card; it never opts in. */ |
| 2295 | if (entry === 'anonymous') goAnonymous(true); |
| 2296 | else remembered = Boolean(storedKey()); |
| 2297 | showMode(); |
| 2298 | keyPanel(); |
| 2299 | start(); |
| 2300 | if (entry === 'anonymous' && oldKey) offerForget(); |
| 2301 | if (entry === 'remember' && !remembered) openIntro(); |
| 2302 | forgetOffer(); |
| 2303 | presence(); |
| 2304 | setInterval(presence, PRESENCE_MS); |
| 2305 | /* The transport for a page UI. It adds no powers the page does not |
| 2306 | already show: introductions still pass the consent card, programs still |
| 2307 | run sandboxed, and only the session channel speaks as Drake. */ |
| 2308 | window.allen = Object.freeze({ |
| 2309 | version: 1, |
| 2310 | on, |
| 2311 | send: text => ask(text), |
| 2312 | regenerate, |
| 2313 | stop: () => { |
| 2314 | if (active) active.abort(); |
| 2315 | }, |
| 2316 | newConversation: () => newButton.click(), |
| 2317 | mode: () => Object.freeze({ mode: remembered ? 'remembered' : 'anonymous' }), |
| 2318 | rememberMe: () => { |
| 2319 | if (!remembered) openIntro(); |
| 2320 | }, |
| 2321 | goAnonymous: () => { |
| 2322 | if (remembered) goAnonymous(false); |
| 2323 | }, |
| 2324 | forgetMe: async () => { |
| 2325 | if (!remembered || !storedKey()) return false; |
| 2326 | const state = el('p', 'allen-card-state'); |
| 2327 | const trigger = el('button'); |
| 2328 | await forgetMe(trigger, state); |
| 2329 | return !storedKey(); |
| 2330 | }, |
| 2331 | presence: () => Object.freeze({ online: drake.online, handoff: drake.handoff, hours: drake.hours, drake: drake.state }), |
| 2332 | handoff: async () => { |
| 2333 | if (drake.state || !drake.online || !drake.handoff) return false; |
| 2334 | await handoff(el('button')); |
| 2335 | return drake.state === 'waiting'; |
| 2336 | }, |
| 2337 | draft: () => draftText, |
| 2338 | voice: on => { |
| 2339 | if (on !== undefined) voiceEnable(on); |
| 2340 | return voice.on; |
| 2341 | }, |
| 2342 | nextClip: voiceNext, |
| 2343 | volunteer: on => { |
| 2344 | if (on !== undefined) setVolunteer(on); |
| 2345 | const tick = byId('allen-volunteer'); |
| 2346 | return Boolean(tick && tick.checked && !remembered); |
| 2347 | }, |
| 2348 | say: text => { |
| 2349 | const said = cut(String(text).trim(), LIMIT.each); |
| 2350 | if (said && drake.state === 'joined') sayToDrake(said); |
| 2351 | }, |
| 2352 | }); |
| 2353 | root.dataset.ready = 'true'; |
| 2354 | document.dispatchEvent(new Event('allen-ready')); |
| 2355 | takeDraft(); |
| 2356 | })(); |