omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
omega-mv / apps / aienos-site / om / allen-page / allen-js.om
| 1 | note Allen chat client. ~N~ tokens expand the single definitions in contract.om. |
| 2 | note Each text holds one JS function or one group of declarations; the last binds the page. |
| 3 | note Composed with contract.om and allen.om by check.sh, never compiled on its own. |
| 4 | |
| 5 | note JavaScript prelude |
| 6 | text js0 "/* Aien chat client.\n *\n * Generated by om/allen-page/allen-js.om; never hand-edit. The page skeleton is\n * generated by om/allen-page/allen.om. Model and network text only ever reaches\n * textContent, a text node, or the srcdoc of a frame sandboxed to allow-scripts\n * alone: nothing from the network is parsed as markup in this document. The\n * conversation lives in this closure only: no storage, no cookies.\n */\n(() => {\n 'use strict';\n const root = document.getElementById('~0~');\n if (!root) return;\n const byId = id => document.getElementById(id);\n const log = byId('~1~');\n const form = byId('~2~');\n const input = byId('~3~');\n const sendButton = byId('~4~');\n const stopButton = byId('~5~');\n const status = byId('~6~');\n const newButton = byId('~7~');\n const examples = byId('~15~');\n const speed = { model: byId('~8~'), queue: byId('~9~'), ttft: byId('~10~'), first: byId('~11~'), rate: byId('~12~'), tokens: byId('~13~'), server: byId('~14~') };\n /* The gateway is always same origin, under /aien/api/ (the hub also keeps /allen/api/); local development\n serves the page and proxies the API on one origin (dev_proxy.py). */\n const CHAT = '~16~';\n const OMEGA = '~17~';\n const LIMIT = { count: ~18~, each: ~19~, total: ~20~, source: ~21~ };\n const CSP = \"~22~\";\n const SANDBOX = '~23~';\n const CALL_MS = ~25~;\n const SUBMIT = '~28~';\n const STATUS = '~29~';\n const INTRODUCE = '~30~';\n const FORGET = '~31~';\n const PRIVACY_MAIL = '~32~';\n const POLL_MS = ~33~;\n const POLL_LIMIT = ~34~;\n const REVIEW_HOST = '~36~';\n const PROJECTS = '~56~';\n const GALLERY = '~57~';\n const FORGET_ME = '~37~';\n const KEY_NAME = '~38~';\n const KEY_PATTERN = /^[0-9a-f]{32}$/;\n const VOICE_DIR = '~60~';\n const RELAY = '~41~';\n const PRESENCE = '~42~';\n const HANDOFF = '~43~';\n const SESSION = '~44~';\n const SAY = '~45~';\n const PRESENCE_MS = ~46~;\n /* Drake's greetings, byte for byte the gateway's opening for each kind of\n start, and the line a returning visitor's page sends first. */\n const GREETING_REMEMBER = \"~51~\";\n const GREETING_ANONYMOUS = \"~52~\";\n const BACK_LINE = '~53~';\n const entry = new URLSearchParams(location.search).get('mode');\n const turns = [];\n const runners = new Set();\n let active = null;\n let epoch = 0;\n let countdown = 0;\n /* What the visitor said they are, from the greeting buttons only; kept in\n this closure and sent to the model as one short first line. */\n let kind = '';\n let choices = null;\n /* A fresh random id per page load and per new conversation, sent with chat\n only when this browser holds an Aien key. */\n let conversation = '';\n" |
| 7 | |
| 8 | note JavaScript bus |
| 9 | text js1 " /* The transport as events for a page UI (window.allen.on). Every detail is\n a frozen plain object; its strings are network or model text and belong\n in textContent only. A listener that throws never stops the chat. */\n const listeners = new Map();\n function emit(type, detail) {\n const set = listeners.get(type);\n if (!set) return;\n const frozen = Object.freeze({ ...detail });\n for (const fn of [...set]) {\n try {\n fn(frozen);\n } catch (_) {\n /* Ignore a broken listener. */\n }\n }\n }\n function on(type, fn) {\n if (typeof type !== 'string' || typeof fn !== 'function') throw new TypeError('allen.on(type, fn)');\n if (!listeners.has(type)) listeners.set(type, new Set());\n listeners.get(type).add(fn);\n return () => listeners.get(type).delete(fn);\n }\n" |
| 10 | |
| 11 | note JavaScript el |
| 12 | text js2 " function el(tag, className, text) {\n const node = document.createElement(tag);\n if (className) node.className = className;\n if (text !== undefined) node.textContent = text;\n return node;\n }\n" |
| 13 | |
| 14 | note JavaScript setText |
| 15 | text js3 " function setText(node, value) {\n if (node && node.textContent !== value) node.textContent = value;\n }\n" |
| 16 | |
| 17 | note JavaScript button |
| 18 | text js4 " function button(label, handler) {\n const node = el('button', 'allen-tool', label);\n node.type = 'button';\n node.addEventListener('click', handler);\n return node;\n }\n" |
| 19 | |
| 20 | note JavaScript ms |
| 21 | text js5 " function ms(value) {\n return Number.isFinite(value) ? `${Math.round(value)} ms` : '-';\n }\n function count(value) {\n return Number.isSafeInteger(value) && value >= 0 ? String(value) : '?';\n }\n" |
| 22 | |
| 23 | note JavaScript cut |
| 24 | text js6 " /* Contract limits count characters; never leave half a surrogate pair behind. */\n function cut(text, max) {\n if (text.length <= max) return text;\n const head = text.slice(0, max);\n return /[\\ud800-\\udbff]$/.test(head) ? head.slice(0, -1) : head;\n }\n" |
| 25 | |
| 26 | note JavaScript fit |
| 27 | text js7 " /* The newest turns that fit the gateway: at most LIMIT.count messages, each at\n most LIMIT.each characters, LIMIT.total in all, starting with a user turn. */\n function fit(list) {\n const out = list.map(turn => ({ role: turn.role, content: cut(turn.content, LIMIT.each) }));\n const lead = kind ? `I am ${kind === 'agent' ? 'an agent' : 'a human'}.\\n` : '';\n let total = out.reduce((sum, turn) => sum + turn.content.length, 0) + lead.length;\n while (out.length > 1 && (out.length > LIMIT.count || total > LIMIT.total || out[0].role !== 'user')) {\n total -= out.shift().content.length;\n }\n if (lead) out[0].content = cut(lead + out[0].content, LIMIT.each);\n return out;\n }\n" |
| 28 | |
| 29 | note JavaScript sse |
| 30 | text js8 " /* Incremental server-sent events: a chunk may end anywhere, even inside a line. */\n function sse(onEvent) {\n let carry = '';\n let name = '';\n let data = [];\n function line(text) {\n if (text === '') {\n if (data.length) onEvent(name || 'message', data.join('\\n'));\n name = '';\n data = [];\n return;\n }\n if (text.startsWith(':')) return;\n const colon = text.indexOf(':');\n const field = colon < 0 ? text : text.slice(0, colon);\n let value = colon < 0 ? '' : text.slice(colon + 1);\n if (value.startsWith(' ')) value = value.slice(1);\n if (field === 'event') name = value;\n else if (field === 'data') data.push(value);\n }\n return {\n feed(chunk) {\n carry += chunk;\n let start = 0;\n for (;;) {\n const end = carry.indexOf('\\n', start);\n if (end < 0) break;\n line(carry.slice(start, end).replace(/\\r$/, ''));\n start = end + 1;\n }\n carry = carry.slice(start);\n },\n end() {\n if (carry) line(carry.replace(/\\r$/, ''));\n carry = '';\n line('');\n },\n };\n }\n" |
| 31 | |
| 32 | note JavaScript inline |
| 33 | text js9 " /* Inline code and bold only; every piece becomes a text node. */\n function inline(parent, text) {\n let at = 0;\n for (const match of text.matchAll(/`([^`\\n]+)`|\\*\\*([^*\\n]+)\\*\\*/g)) {\n if (match.index > at) parent.append(document.createTextNode(text.slice(at, match.index)));\n parent.append(match[1] !== undefined ? el('code', '', match[1]) : el('strong', '', match[2]));\n at = match.index + match[0].length;\n }\n if (at < text.length) parent.append(document.createTextNode(text.slice(at)));\n }\n" |
| 34 | |
| 35 | note JavaScript renderer |
| 36 | text js10 " /* Streams a reply into nodes. Each token is appended to the text node of the\n line being written; a finished line is re-rendered as paragraph text, a\n heading, or a line of a fenced code block. A line that may still become a\n fence is held back until it is decided, so fences never flash as text. */\n function renderer(body) {\n const st = { block: null, sep: null, tail: null, code: null, codeText: null, lang: '', wrap: null, bar: null, pre: null, line: '', held: false, text: '' };\n const opening = /^ {0,3}```\\s*([A-Za-z0-9_+.-]*)\\s*$/;\n const closing = /^ {0,3}```\\s*$/;\n const maybeOpening = /^ {0,3}`{1,3}[A-Za-z0-9_+.-]*$/;\n const maybeClosing = /^ {0,3}`{1,3}$/;\n function closeParagraph() {\n if (st.block && !st.block.firstChild) st.block.remove();\n st.block = null;\n }\n function tailNode() {\n if (st.tail) return st.tail;\n st.tail = document.createTextNode('');\n if (st.code) {\n st.code.append(st.tail);\n } else {\n if (!st.block) {\n st.block = el('p', 'allen-p');\n body.append(st.block);\n } else if (st.block.firstChild) {\n st.sep = document.createTextNode('\\n');\n st.block.append(st.sep);\n }\n st.block.append(st.tail);\n }\n return st.tail;\n }\n function retract(keepSep) {\n if (st.tail) st.tail.remove();\n if (st.sep && !keepSep) st.sep.remove();\n st.tail = null;\n st.sep = null;\n }\n function openCode(lang) {\n st.wrap = el('div', 'allen-code');\n st.bar = el('div', 'allen-tools');\n st.bar.append(el('span', 'allen-lang', lang || 'text'));\n st.pre = el('pre');\n st.code = el('code');\n st.codeText = document.createTextNode('');\n st.code.append(st.codeText);\n st.pre.append(st.code);\n st.wrap.append(st.bar, st.pre);\n body.append(st.wrap);\n st.lang = lang;\n }\n function closeCode() {\n retract(false);\n const source = st.codeText.data.replace(/\\n$/, '');\n tools(st.lang, source, st.wrap, st.bar, st.pre);\n emit('card', { type: st.lang, source, node: st.wrap });\n st.code = null;\n st.codeText = null;\n }\n function commit() {\n const line = st.line;\n st.line = '';\n st.held = false;\n if (st.code) {\n retract(false);\n if (closing.test(line)) closeCode();\n else st.codeText.appendData(line + '\\n');\n return;\n }\n const open = opening.exec(line);\n const heading = /^#{1,4}\\s+(.*)$/.exec(line);\n if (open || heading || !line.trim()) {\n retract(false);\n closeParagraph();\n if (open) {\n openCode(open[1].toLowerCase());\n } else if (heading) {\n const node = el('p', 'allen-h');\n inline(node, heading[1]);\n body.append(node);\n }\n return;\n }\n tailNode();\n retract(true);\n inline(st.block, line);\n }\n return {\n push(token) {\n st.text += token;\n token.split('\\n').forEach((piece, index) => {\n if (index > 0) commit();\n if (!piece) return;\n st.line += piece;\n if ((st.code ? maybeClosing : maybeOpening).test(st.line)) {\n st.held = true;\n } else if (st.held) {\n st.held = false;\n tailNode().data = st.line;\n } else {\n tailNode().appendData(piece);\n }\n });\n },\n finish() {\n if (st.line) commit();\n if (st.code) closeCode();\n retract(false);\n closeParagraph();\n return st.text;\n },\n };\n }\n" |
| 37 | |
| 38 | note JavaScript tools |
| 39 | text js11 " /* Buttons under a finished fenced block: html runs in a sandbox, omega\n compiles to WebAssembly, both download and publish; issue and introduce\n blocks become cards that act only on a visitor's click. */\n function tools(lang, source, wrap, bar, pre) {\n const type = /^html?$/.test(lang) ? 'html' : /^(omega|om)$/.test(lang) ? 'omega' : /^(issue|introduce|relay)$/.test(lang) ? lang : '';\n const out = el('div', 'allen-out');\n if (type === 'issue' || type === 'introduce' || type === 'relay') {\n pre.hidden = true;\n wrap.append(out);\n if (type === 'issue') issueCard(cardFields(source), out);\n else if (type === 'relay') relayCard(cardFields(source), out);\n else out.append(remembered ? introCard(introLines(cardFields(source).fields)) : rememberOffer(introLines(cardFields(source).fields)));\n return;\n }\n let view = null;\n const showCode = shown => {\n pre.hidden = !shown;\n if (view) view.setAttribute('aria-pressed', String(shown));\n };\n const project = type ? makeProject(type, source) : null;\n if (type === 'html') {\n bar.append(button('Run', () => {\n runHtml(source, out);\n showCode(false);\n }));\n }\n if (type === 'omega') {\n bar.append(button('Compile and run', event => compileOmega(source, out, event.currentTarget, project)));\n }\n if (type) {\n view = button('Code', () => showCode(pre.hidden));\n view.setAttribute('aria-pressed', 'true');\n bar.append(view);\n }\n const copy = button('Copy', () => copyText(source, copy));\n bar.append(copy);\n if (project) {\n const more = el('div', 'allen-more');\n const pub = el('div', 'allen-pub');\n downloads(project, more, pub);\n wrap.append(more, pub);\n }\n wrap.append(out);\n }\n" |
| 40 | |
| 41 | note JavaScript makeProject |
| 42 | text js12 " /* One block is one project: its main file, a README and, for Omega, the\n wasm once it has been compiled. */\n function slugify(text) {\n return text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+/, '').slice(0, 40).replace(/-+$/, '');\n }\n function makeProject(type, source) {\n if (type === 'html') {\n const named = /<title[^>]*>([^<]{1,80})<\\/title>/i.exec(source);\n const title = named && named[1].trim() ? named[1].trim() : 'Aien app';\n return { type, title, base: slugify(title) || 'allen-app', main: 'index.html', source, wasm: null, functions: [], wasmButton: null, htmlButton: null, pin: '' };\n }\n const first = /^\\s*fn\\s+([A-Za-z0-9_]+)/m.exec(source);\n const title = first ? first[1] : 'program';\n const base = slugify(title) || 'program';\n return { type, title, base, main: `${base}.om`, source, wasm: null, functions: [], wasmButton: null, htmlButton: null, pin: '' };\n }\n function signature(fn) {\n const params = Array.isArray(fn.params) ? fn.params : [];\n return `${fn.name}(${params.map(p => `${p.name}: ${p.type}`).join(', ')}) to ${typeof fn.ret === 'string' ? fn.ret : 'void'}`;\n }\n" |
| 43 | |
| 44 | note JavaScript readme |
| 45 | text js13 " function readme(project, description) {\n const lines = [`# ${project.title}`, '', description || \"Written by Aien, Drake's AI, at https://www.aienos.com/aien/.\", ''];\n if (project.type === 'html') {\n lines.push('Open index.html in a browser. It is one self-contained file.');\n } else {\n 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`, '```');\n if (project.functions.length) {\n lines.push('', `${project.base}.wasm has no imports. It exports:`, '');\n for (const fn of project.functions) lines.push(`- ${signature(fn)}`);\n }\n 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.`);\n }\n lines.push('', 'Learn about Omega: https://www.aienos.com/omega/', '');\n return lines.join('\\n');\n }\n" |
| 46 | |
| 47 | note JavaScript crc32 |
| 48 | text js14 " const CRC_TABLE = (() => {\n const table = new Uint32Array(256);\n for (let n = 0; n < 256; n += 1) {\n let c = n;\n for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n table[n] = c >>> 0;\n }\n return table;\n })();\n function crc32(bytes) {\n let c = 0xffffffff;\n for (let i = 0; i < bytes.length; i += 1) c = CRC_TABLE[(c ^ bytes[i]) & 255] ^ (c >>> 8);\n return (c ^ 0xffffffff) >>> 0;\n }\n" |
| 49 | |
| 50 | note JavaScript zip |
| 51 | text js15 " /* A store-only zip: local headers, the bytes, a central directory and the\n end record, names flagged UTF-8, every entry with its CRC-32. */\n function zip(files) {\n const encoder = new TextEncoder();\n const now = new Date();\n const time = (now.getHours() << 11) | (now.getMinutes() << 5) | Math.floor(now.getSeconds() / 2);\n const date = ((Math.max(1980, now.getFullYear()) - 1980) << 9) | ((now.getMonth() + 1) << 5) | now.getDate();\n const parts = [];\n const central = [];\n let offset = 0;\n for (const file of files) {\n const name = encoder.encode(file.name);\n const data = file.data;\n const crc = crc32(data);\n const local = new DataView(new ArrayBuffer(30));\n local.setUint32(0, 0x04034b50, true);\n local.setUint16(4, 20, true);\n local.setUint16(6, 0x0800, true);\n local.setUint16(8, 0, true);\n local.setUint16(10, time, true);\n local.setUint16(12, date, true);\n local.setUint32(14, crc, true);\n local.setUint32(18, data.length, true);\n local.setUint32(22, data.length, true);\n local.setUint16(26, name.length, true);\n local.setUint16(28, 0, true);\n parts.push(new Uint8Array(local.buffer), name, data);\n const entry = new DataView(new ArrayBuffer(46));\n entry.setUint32(0, 0x02014b50, true);\n entry.setUint16(4, 20, true);\n entry.setUint16(6, 20, true);\n entry.setUint16(8, 0x0800, true);\n entry.setUint16(10, 0, true);\n entry.setUint16(12, time, true);\n entry.setUint16(14, date, true);\n entry.setUint32(16, crc, true);\n entry.setUint32(20, data.length, true);\n entry.setUint32(24, data.length, true);\n entry.setUint16(28, name.length, true);\n entry.setUint32(42, offset, true);\n central.push(new Uint8Array(entry.buffer), name);\n offset += 30 + name.length + data.length;\n }\n const size = central.reduce((sum, part) => sum + part.length, 0);\n const end = new DataView(new ArrayBuffer(22));\n end.setUint32(0, 0x06054b50, true);\n end.setUint16(8, files.length, true);\n end.setUint16(10, files.length, true);\n end.setUint32(12, size, true);\n end.setUint32(16, offset, true);\n const all = [...parts, ...central, new Uint8Array(end.buffer)];\n const out = new Uint8Array(all.reduce((sum, part) => sum + part.length, 0));\n let at = 0;\n for (const part of all) {\n out.set(part, at);\n at += part.length;\n }\n return out;\n }\n" |
| 52 | |
| 53 | note JavaScript save |
| 54 | text js16 " /* Downloads are made here, in the browser: a Blob and an anchor with download. */\n function save(name, data, type) {\n const url = URL.createObjectURL(new Blob([data], { type }));\n const anchor = document.createElement('a');\n anchor.href = url;\n anchor.download = name;\n anchor.rel = 'noopener';\n anchor.hidden = true;\n document.body.append(anchor);\n anchor.click();\n anchor.remove();\n setTimeout(() => URL.revokeObjectURL(url), 1000);\n }\n function projectFiles(project) {\n const encoder = new TextEncoder();\n const files = [{ name: project.main, data: encoder.encode(project.source) }];\n if (project.wasm) {\n files.push({ name: `${project.base}.wasm`, data: project.wasm });\n files.push({ name: `${project.base}.html`, data: encoder.encode(standalone(project)) });\n }\n files.push({ name: 'README.md', data: encoder.encode(readme(project)) });\n return files;\n }\n" |
| 55 | |
| 56 | note JavaScript downloads |
| 57 | text js17 " /* The first action is Save or publish on GitHub: the project's home in\n the public aien-dev/omega-projects repo, where anyone can read it. The\n local copies follow. For Omega the first download is <base>.html, shown\n once Compile and run has succeeded: the one file a visitor can open and\n run. <base>.om.txt is the source for any text editor; <base>.om stays the\n name the README, the zip and a published project use. */\n function downloads(project, row, pub) {\n const github = button('Save or publish on GitHub', () => publishForm(project, pub));\n github.classList.add('allen-github');\n github.title = 'Saves this project to your home in the public aien-dev/omega-projects repo on GitHub; publishing asks Drake to review it';\n row.append(github, el('span', 'allen-more-label', 'or download a copy'));\n if (project.type === 'omega') {\n project.htmlButton = button(`${project.base}.html`, () => {\n if (project.wasm) save(`${project.base}.html`, standalone(project), 'text/html;charset=utf-8');\n });\n project.htmlButton.hidden = true;\n project.htmlButton.title = 'One file that runs this program in any browser, with no install';\n row.append(project.htmlButton);\n }\n row.append(button(project.main, () => save(project.main, project.source, project.type === 'html' ? 'text/html' : 'text/plain')));\n if (project.type === 'omega') {\n const text = button(`${project.base}.om.txt`, () => save(`${project.base}.om.txt`, sourceText(project), 'text/plain;charset=utf-8'));\n text.title = 'The Omega source as plain text, for any text editor';\n row.append(text);\n project.wasmButton = button(`${project.base}.wasm`, () => {\n if (project.wasm) save(`${project.base}.wasm`, project.wasm, 'application/wasm');\n });\n project.wasmButton.disabled = true;\n project.wasmButton.title = 'Compile it first';\n row.append(project.wasmButton);\n }\n row.append(button('README.md', () => save('README.md', readme(project), 'text/markdown')));\n row.append(button(`${project.base}.zip`, () => save(`${project.base}.zip`, zip(projectFiles(project)), 'application/zip')));\n }\n" |
| 58 | |
| 59 | note JavaScript field |
| 60 | text js18 " function field(parent, label, tag, max) {\n const wrap = el('label', 'allen-field');\n wrap.append(el('span', '', label));\n const input = el(tag);\n if (tag === 'input') input.type = 'text';\n input.maxLength = max;\n input.autocomplete = 'off';\n wrap.append(input);\n parent.append(wrap);\n return input;\n }\n function post(body, extra, identity = true) {\n return { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...(identity ? keyHeaders(false) : {}), ...extra }, body: JSON.stringify(body), cache: 'no-store', credentials: 'omit' };\n }\n function failure(response, reply, tail) {\n const said = reply && typeof reply.message === 'string' ? reply.message.slice(0, 300) : '';\n const wait = retryAfter(response, reply);\n if ([400, 413, 422].includes(response.status) && said) return `${said} ${tail}`.trim();\n return `${refusal(response.status, reply)}${wait ? ` Try again in ${wait} s.` : ''} ${tail}`.trim();\n }\n" |
| 61 | |
| 62 | note JavaScript publishForm |
| 63 | text js19 " const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/;\n const NAME = /^[a-z](?:[a-z0-9]|-(?=[a-z0-9])){1,23}$/;\n /* The builder's home projects/<handle>/ in omega-projects. A remembered\n visitor gets <name>-<tag>, tied to their key and remembered by Aien; an\n anonymous visitor gets a one-time anon- handle whose claim code lives only\n in this page and is shown once. The gateway checks ownership on every save. */\n const home = { handle: '', claim: '' };\n function claimHeaders() {\n return home.claim ? { 'X-Allen-Claim': home.claim } : {};\n }\n async function projectCall(path, body) {\n const response = await fetch(PROJECTS + path, body === undefined\n ? { cache: 'no-store', credentials: 'omit', headers: { Accept: 'application/json', ...keyHeaders(false), ...claimHeaders() } }\n : post(body, claimHeaders()));\n return { response, reply: await response.json().catch(() => null) };\n }\n async function findHome() {\n if (home.handle || !remembered) return home.handle;\n try {\n const { response, reply } = await projectCall('me');\n if (response.ok && reply && typeof reply.handle === 'string') home.handle = reply.handle;\n } catch (_) {\n /* No home yet; the form asks for a name. */\n }\n return home.handle;\n }\n async function makeHome(name, state) {\n const { response, reply } = await projectCall('handle', remembered ? { name } : {});\n if (!response.ok || !reply || typeof reply.handle !== 'string') {\n state.replaceChildren(el('p', 'allen-err', failure(response, reply, 'No home was made.')));\n return '';\n }\n home.handle = reply.handle;\n if (typeof reply.claim === 'string') {\n home.claim = reply.claim;\n const line = el('p', 'allen-keyline');\n line.append(el('span', '', 'Your claim code, shown once: '), el('code', '', reply.claim));\n 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.'));\n }\n return home.handle;\n }\n async function showGallery(out) {\n out.replaceChildren(el('p', 'allen-note', 'Loading the Built with Aien gallery.'));\n try {\n const response = await fetch(GALLERY, { cache: 'no-store', credentials: 'omit', headers: { Accept: 'application/json' } });\n const reply = response.ok ? await response.json() : null;\n const items = reply && Array.isArray(reply.gallery) ? reply.gallery : [];\n const list = el('ul');\n for (const g of items.slice(0, 50)) {\n if (typeof g.project !== 'string' || !SLUG.test(g.project)) continue;\n /* omega-projects has no public page, so a gallery entry is named in plain text. */\n const link = el('strong', '', String(g.title || g.project).slice(0, 80));\n const li = el('li');\n li.append(link, el('span', '', ` by ${String(g.handle).slice(0, 40)}: ${String(g.description || '').slice(0, 200)}`));\n list.append(li);\n }\n out.replaceChildren(list.firstChild ? list : el('p', 'allen-note', 'Nothing is in the gallery yet. Yours could be the first.'));\n } catch (_) {\n out.replaceChildren(el('p', 'allen-err', 'Could not load the gallery.'));\n }\n }\n function publishForm(project, pub) {\n if (pub.firstChild) {\n pub.replaceChildren();\n return;\n }\n const form = el('form', 'allen-card allen-publish');\n form.noValidate = true;\n form.append(el('p', 'allen-card-h', 'Save or publish'));\n 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);\n name.disabled = !remembered;\n const slug = field(form, 'Project name (lowercase letters, digits and hyphens)', 'input', 40);\n slug.value = project.base;\n const title = field(form, 'Title', 'input', 80);\n title.value = project.title;\n const description = field(form, 'What it is and who it helps', 'textarea', 2000);\n const main = project.type === 'html' ? 'index.html' : project.main;\n const where = el('p', 'allen-note');\n form.append(el('p', 'allen-note', `Files: ${main}, README.md. Email addresses and phone numbers are removed from the text first.`), where);\n const sync = () => setText(where, home.handle\n ? `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.`\n : 'Your home in aien-dev/omega-projects on GitHub is made the first time you save.');\n slug.addEventListener('input', sync);\n const saveButton = el('button', 'allen-tool', 'Save to my home');\n saveButton.type = 'submit';\n const publishButton = button('Publish for Drake\\u2019s review', () => {\n publishButton.hidden = true;\n const confirm = el('div', 'allen-choices');\n confirm.append(el('span', 'allen-note', 'Publish this project publicly as a pull request for Drake to review?'), button('Yes, publish it', () => {\n confirm.remove();\n publishButton.hidden = false;\n send('publish');\n }), button('Cancel', () => {\n confirm.remove();\n publishButton.hidden = false;\n }));\n form.insertBefore(confirm, state);\n });\n const galleryOut = el('div', 'allen-out');\n const state = el('div', 'allen-card-state');\n form.append(saveButton, publishButton, button('Built with Aien gallery', () => showGallery(galleryOut)), state, galleryOut);\n findHome().then(handle => {\n if (handle) name.value = handle.replace(/-[0-9a-f]{8}$/, '');\n sync();\n });\n const again = {\n set hidden(value) { saveButton.hidden = value; publishButton.hidden = value; },\n set disabled(value) { saveButton.disabled = value; publishButton.disabled = value; },\n };\n async function send(kind) {\n const problems = [];\n const about = description.value.trim();\n if (!SLUG.test(slug.value)) problems.push('The project name must be 1 to 40 lowercase letters, digits or inner hyphens.');\n if (title.value.trim().length < 3 || title.value.trim().length > 80) problems.push('The title must be 3 to 80 characters.');\n if (about.length < 10 || about.length > 2000) problems.push('Say what it is and who it helps in 10 to 2000 characters.');\n 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.');\n if (problems.length) {\n state.replaceChildren(el('p', 'allen-err', problems.join(' ')));\n return;\n }\n again.disabled = true;\n try {\n const handle = home.handle || await makeHome(name.value, state);\n if (!handle) {\n again.disabled = false;\n return;\n }\n sync();\n 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) }] };\n const note = el('div');\n state.append(note);\n const { response, reply } = await projectCall(kind, item);\n if (!response.ok || !reply || typeof reply !== 'object') {\n note.replaceChildren(el('p', 'allen-err', failure(response, reply, 'Nothing was saved.')));\n again.disabled = false;\n return;\n }\n await track(reply, note, item, again);\n again.disabled = false;\n } catch (_) {\n state.append(el('p', 'allen-err', 'Could not reach Aien. Nothing was saved.'));\n again.disabled = false;\n }\n }\n form.addEventListener('submit', event => {\n event.preventDefault();\n send('save');\n });\n pub.replaceChildren(form);\n (remembered && !name.value ? name : slug).focus();\n }\n" |
| 64 | |
| 65 | note JavaScript cardFields |
| 66 | text js20 " /* Header lines \"Key: value\" up to the first line that is not one; the rest\n is the body. Keys from the model land in a prototype-free object. */\n function cardFields(source) {\n const fields = Object.create(null);\n const lines = source.split('\\n');\n let i = 0;\n for (; i < lines.length; i += 1) {\n const match = /^\\s*([A-Za-z]+)\\s*:\\s?(.*)$/.exec(lines[i]);\n if (!match) break;\n fields[match[1].toLowerCase()] = match[2].trim();\n }\n return { fields, body: lines.slice(i).join('\\n').trim() };\n }\n 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' };\n function introLines(fields) {\n const out = Object.create(null);\n for (const [line, key] of Object.entries(INTRO_LINES)) if (fields[line]) out[key] = fields[line];\n return out;\n }\n" |
| 67 | |
| 68 | note JavaScript issueCard |
| 69 | text js21 " function issueCard(parsed, out) {\n 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') };\n const card = el('div', 'allen-card');\n card.append(el('p', 'allen-card-h', 'Proposed GitHub issue'));\n const facts = el('dl', 'allen-kv');\n for (const [label, value] of [['Type', item.template], ['Area', item.area], ['Title', item.title]]) facts.append(el('dt', '', label), el('dd', '', value));\n card.append(facts, el('pre', 'allen-card-body', item.body));\n const problems = [];\n if (!['feature', 'question', 'bug'].includes(item.template)) problems.push('Type must be feature, question or bug.');\n if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(item.area)) problems.push('Area must be a repository name or unknown.');\n if (item.title.length < 8 || item.title.length > 120) problems.push('The title must be 8 to 120 characters.');\n if (item.body.length < 20 || item.body.length > 6000) problems.push('The body must be 20 to 6000 characters.');\n const state = el('div', 'allen-card-state');\n if (problems.length) {\n state.append(el('p', 'allen-err', `This cannot be filed as written: ${problems.join(' ')} Ask Aien to fix it.`));\n card.append(state);\n out.replaceChildren(card);\n return;\n }\n 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.'));\n const file = button('File this on GitHub', () => {\n file.hidden = true;\n const confirm = el('div', 'allen-choices');\n confirm.append(el('span', 'allen-note', 'File this exact issue publicly?'), button('Yes, file it', () => {\n confirm.remove();\n submitItem(item, state, file);\n }), button('Cancel', () => {\n confirm.remove();\n file.hidden = false;\n }));\n card.insertBefore(confirm, state);\n });\n card.append(file, state);\n out.replaceChildren(card);\n }\n" |
| 70 | |
| 71 | note JavaScript submitItem |
| 72 | text js22 " async function submitItem(item, state, again) {\n state.replaceChildren(el('p', 'allen-note', 'Sending.'));\n let response;\n let reply;\n try {\n response = await fetch(SUBMIT, post(item));\n reply = await response.json().catch(() => null);\n } catch (_) {\n state.replaceChildren(el('p', 'allen-err', 'Could not reach Aien. Nothing was sent.'));\n again.hidden = false;\n again.disabled = false;\n return;\n }\n if (!response.ok || !reply || typeof reply !== 'object') {\n state.replaceChildren(el('p', 'allen-err', failure(response, reply, 'Nothing was filed.')));\n again.hidden = false;\n again.disabled = false;\n return;\n }\n track(reply, state, item, again);\n }\n" |
| 73 | |
| 74 | note JavaScript track |
| 75 | text js23 " /* Status every POLL_MS until filed, rejected or failed. Only a link to an\n issue or pull request in aien-dev/omega-projects becomes an anchor. A\n rejected item can be edited and sent again; a failed one can go to Drake\n as a relay instead, with its text prefilled and nothing sent unconfirmed. */\n function showStatus(status, state, id, item, again) {\n 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 : '';\n const reason = typeof status.reason === 'string' && status.reason ? status.reason.slice(0, 300) : '';\n if (status.state === 'filed') {\n const done = el('p', 'allen-ok', url ? (item.kind === 'save' ? 'Saved: ' : 'Filed: ') : 'Filed, without a tracking link.');\n if (url) {\n /* omega-projects has no public page: the tracking address is shown as plain text, never linked. */\n done.append(el('code', '', url));\n }\n state.replaceChildren(done);\n return true;\n }\n if (status.state === 'rejected') {\n state.replaceChildren(el('p', 'allen-err', `Not filed: ${reason || 'no reason given'}`));\n if (item.kind === 'issue') {\n state.append(editIssue(item, state));\n } else {\n again.hidden = false;\n again.disabled = false;\n state.append(el('p', 'allen-note', 'Edit the fields above and submit again.'));\n }\n return true;\n }\n if (status.state === 'failed') {\n const box = el('div', 'allen-fail');\n const relayOut = el('div', 'allen-out');\n const offer = button('Send it to Drake instead', () => {\n offer.remove();\n relayCard({ fields: Object.create(null), body: relayText(item) }, relayOut);\n });\n box.append(el('p', 'allen-err', `I could not file this: ${reason || 'no reason given'}`), offer, relayOut);\n state.replaceChildren(box);\n return true;\n }\n 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.`));\n return false;\n }\n function relayText(item) {\n 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}`;\n }\n async function track(first, state, item, again) {\n const id = typeof first.id === 'string' && /^[0-9a-f]{20}$/.test(first.id) ? first.id : '';\n if (!id) {\n state.replaceChildren(el('p', 'allen-err', 'The gateway returned no tracking id.'));\n return;\n }\n const began = performance.now();\n let current = first;\n for (;;) {\n if (showStatus(current, state, id, item, again)) return;\n /* A token not yet installed never resolves, so stop after POLL_LIMIT;\n retries end in filed or failed within a few minutes, so wait longer. */\n const retrying = typeof current.reason === 'string' && current.reason.startsWith('retrying');\n if (performance.now() - began >= (retrying ? 3 * POLL_LIMIT : POLL_LIMIT)) {\n const why = typeof current.reason === 'string' && current.reason ? current.reason.slice(0, 200) : 'not filed yet';\n 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.`));\n return;\n }\n await new Promise(done => setTimeout(done, POLL_MS));\n try {\n const response = await fetch(STATUS + id, { cache: 'no-store', credentials: 'omit', headers: { Accept: 'application/json', ...keyHeaders(false) } });\n const reply = response.ok ? await response.json() : null;\n if (reply && typeof reply === 'object') current = reply;\n } catch (_) {\n /* Keep the last status and try again on the next tick. */\n }\n }\n }\n /* After a rejection: the same issue, editable, sent again only on a click. */\n function editIssue(item, state) {\n const form = el('form', 'allen-card allen-reissue');\n form.noValidate = true;\n const title = field(form, 'Title', 'input', 120);\n title.value = item.title;\n const body = field(form, 'Body', 'textarea', 6000);\n body.value = item.body;\n const resend = el('button', 'allen-tool', 'File the edited issue');\n resend.type = 'submit';\n const note = el('p', 'allen-card-state');\n form.append(resend, note);\n form.addEventListener('submit', event => {\n event.preventDefault();\n const next = { ...item, title: title.value.trim(), body: body.value.trim() };\n if (next.title.length < 8 || next.title.length > 120 || next.body.length < 20 || next.body.length > 6000) {\n setText(note, 'The title must be 8 to 120 characters and the body 20 to 6000.');\n return;\n }\n resend.disabled = true;\n submitItem(next, note, resend);\n });\n return form;\n }\n" |
| 76 | |
| 77 | note JavaScript introCard |
| 78 | text js24 " const INTRO = [\n ['name', 'Name', 100, 'input'],\n ['org', 'Organization', 100, 'input'],\n ['contact', 'Contact (email or another way to reach you)', 200, 'input'],\n ['github', 'GitHub name', 39, 'input'],\n ['origin', 'Where you are from', 200, 'input'],\n ['purpose', 'What you are building', 1000, 'textarea'],\n ['homepage', 'Homepage (https)', 200, 'input'],\n ['framework', 'Framework (agents)', 100, 'input'],\n ['model', 'Model (agents)', 100, 'input'],\n ['human', 'Your human (agents: the person or organization operating you)', 200, 'input'],\n ];\n function introCard(prefill) {\n const form = el('form', 'allen-card allen-introduce');\n form.noValidate = true;\n form.append(el('p', 'allen-card-h', 'Introduce yourself to Aien'));\n const kindWrap = el('label', 'allen-field');\n kindWrap.append(el('span', '', 'You are'));\n const who = el('select');\n for (const value of ['human', 'agent']) {\n const option = el('option', '', value === 'human' ? 'a human' : 'an agent');\n option.value = value;\n who.append(option);\n }\n who.value = String(prefill.kind || kind).toLowerCase() === 'agent' ? 'agent' : 'human';\n kindWrap.append(who);\n form.append(kindWrap);\n const inputs = {};\n for (const [key, label, max, tag] of INTRO) {\n inputs[key] = field(form, label, tag, max);\n inputs[key].value = cut(String(prefill[key] || ''), max);\n }\n const notice = el('div', 'allen-consent');\n notice.append(\n el('p', '', 'What is kept if you save: the fields above and the time you sent them.'),\n el('p', '', 'Why: so Drake can follow up with you.'),\n 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.'),\n el('p', '', \"Where: privately on Drake's own computer. Never published, never sold.\"),\n 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}.`),\n el('p', '', 'Declining changes nothing: you can keep chatting and nothing is saved.'),\n );\n const agreeWrap = el('label', 'allen-agree');\n const agree = el('input');\n agree.type = 'checkbox';\n agreeWrap.append(agree, el('span', '', 'I agree that this introduction is kept as described above.'));\n const keep = el('button', 'allen-tool', 'Save');\n keep.type = 'submit';\n keep.disabled = true;\n agree.addEventListener('change', () => {\n keep.disabled = !agree.checked;\n });\n const state = el('div', 'allen-card-state');\n const paste = el('div', 'allen-paste');\n 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);\n const use = button('Use this key', () => {\n if (!agree.checked) return;\n const value = pasted.value.trim().toLowerCase();\n if (!KEY_PATTERN.test(value)) {\n state.replaceChildren(el('p', 'allen-err', 'An Aien key is exactly 32 characters, 0 to 9 and a to f.'));\n return;\n }\n if (!keepKey(value)) {\n state.replaceChildren(el('p', 'allen-err', 'This browser refused to store the key.'));\n return;\n }\n remembered = true;\n conversation = conversationId();\n showMode();\n keyPanel();\n for (const control of form.querySelectorAll('input, textarea, select, button')) control.disabled = true;\n state.replaceChildren(el('p', 'allen-ok', 'Key saved in this browser. Aien will recognize you from your next message.'));\n });\n use.disabled = true;\n paste.append(use);\n agree.addEventListener('change', () => {\n use.disabled = !agree.checked;\n });\n form.append(notice, agreeWrap, keep, paste, state);\n form.addEventListener('submit', event => {\n event.preventDefault();\n if (agree.checked) saveIntro(who.value, inputs, state, keep, form);\n });\n return form;\n }\n" |
| 79 | |
| 80 | note JavaScript saveIntro |
| 81 | text js25 " async function saveIntro(who, inputs, state, keep, form) {\n const record = { consent: true, kind: who };\n for (const [key] of INTRO) record[key] = inputs[key].value.trim();\n if (!record.name && !record.contact) {\n state.replaceChildren(el('p', 'allen-err', 'Give at least a name or a contact.'));\n return;\n }\n if (record.homepage && !/^https:\\/\\/\\S{4,}$/.test(record.homepage)) {\n state.replaceChildren(el('p', 'allen-err', 'The homepage must be an https address.'));\n return;\n }\n keep.disabled = true;\n state.replaceChildren(el('p', 'allen-note', 'Saving.'));\n let response;\n let reply;\n try {\n response = await fetch(INTRODUCE, post(record, { 'X-Allen-Via': 'chat' }, false));\n reply = await response.json().catch(() => null);\n } catch (_) {\n state.replaceChildren(el('p', 'allen-err', 'Could not reach Aien. Nothing was saved.'));\n keep.disabled = false;\n return;\n }\n if (!response.ok || !reply || reply.stored !== true) {\n state.replaceChildren(el('p', 'allen-err', failure(response, reply, 'Nothing was saved.')));\n keep.disabled = false;\n return;\n }\n for (const control of form.querySelectorAll('input, textarea, select')) control.disabled = true;\n keep.hidden = true;\n /* The gateway hands out the visitor key only with a consented introduction. */\n const kept_ = typeof reply.key === 'string' && KEY_PATTERN.test(reply.key) && keepKey(reply.key);\n if (kept_) {\n remembered = true;\n conversation = conversationId();\n showMode();\n keyPanel();\n }\n 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.');\n 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 : '';\n if (!link) {\n state.replaceChildren(el('p', 'allen-ok', `Saved. The delete link did not arrive intact; write to ${PRIVACY_MAIL} to have it deleted.`), memo);\n return;\n }\n const kept = el('p', 'allen-ok', 'Saved. Keep this delete link; it deletes your introduction: ');\n const anchor = el('a', '', link);\n anchor.href = link;\n kept.append(anchor);\n const copy = button('Copy link', () => copyText(link, copy));\n state.replaceChildren(kept, copy, el('p', 'allen-note', `Or write to ${PRIVACY_MAIL} to have it deleted.`), memo);\n }\n" |
| 82 | |
| 83 | note JavaScript forgetOffer |
| 84 | text js26 " /* A delete link opens this page at #forget=<id>.<token>; nothing is sent\n until the visitor confirms, and the token leaves the address afterwards. */\n function forgetOffer() {\n const match = /^#forget=(c_[0-9a-f]{16})\\.([A-Za-z0-9_-]{20,64})$/.exec(location.hash);\n if (!match) return;\n const id = match[1];\n const token = match[2];\n const note = message('allen', 'Aien');\n note.body.append(el('p', 'allen-p', `You opened the delete link for introduction ${id}. Delete it?`));\n const row = el('div', 'allen-choices');\n const state = el('div', 'allen-card-state');\n const remove = button('Delete my introduction', async () => {\n remove.disabled = true;\n decline.disabled = true;\n state.replaceChildren(el('p', 'allen-note', 'Sending.'));\n try {\n const response = await fetch(FORGET, post({ id, token }));\n const reply = await response.json().catch(() => null);\n if (response.ok && reply && reply.accepted === true) {\n row.remove();\n 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.\"));\n try {\n history.replaceState(null, '', location.pathname + location.search);\n } catch (_) {\n location.hash = '';\n }\n return;\n }\n state.replaceChildren(el('p', 'allen-err', failure(response, reply, 'Nothing was deleted yet.')));\n } catch (_) {\n state.replaceChildren(el('p', 'allen-err', 'Could not reach Aien. Nothing was deleted yet.'));\n }\n remove.disabled = false;\n decline.disabled = false;\n });\n const decline = button('Keep it', () => {\n row.remove();\n state.replaceChildren(el('p', 'allen-note', 'Nothing changed.'));\n });\n row.append(remove, decline);\n note.body.append(row, state);\n }\n" |
| 85 | |
| 86 | note JavaScript keys |
| 87 | text js27 " /* The visitor key: 32 hex from the gateway, kept under KEY_NAME in local\n storage only after a consented introduction or when the visitor pastes\n their own key. Nothing else is ever stored in this browser. */\n function storedKey() {\n try {\n const value = localStorage.getItem(KEY_NAME);\n return value && KEY_PATTERN.test(value) ? value : '';\n } catch (_) {\n return '';\n }\n }\n function keepKey(value) {\n try {\n localStorage.setItem(KEY_NAME, value);\n return storedKey() === value;\n } catch (_) {\n return false;\n }\n }\n function dropKey() {\n try {\n localStorage.removeItem(KEY_NAME);\n } catch (_) {\n /* Nothing was stored. */\n }\n }\n /* 128 random bits (32 hex): the conversation id is the live-session bearer. */\n function conversationId() {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');\n }\n /* Anonymous is the default: a visitor is remembered only after Remember me,\n through the consent card. Anonymous calls say so and never carry a key. */\n let remembered = false;\n let oldKey = '';\n function keyHeaders(chat) {\n if (!remembered) return { 'X-Allen-Anonymous': '1' };\n const key = storedKey();\n if (!key) return { 'X-Allen-Anonymous': '1' };\n return chat ? { 'X-Allen-Key': key, 'X-Allen-Conversation': conversation } : { 'X-Allen-Key': key };\n }\n" |
| 88 | |
| 89 | note JavaScript keyPanel |
| 90 | text js28 " function keyPanel(said) {\n const body = byId('~40~');\n if (!body) return;\n const key = remembered ? storedKey() : '';\n const state = el('p', 'allen-card-state', said || '');\n const parts = [];\n if (key) {\n const line = el('p', 'allen-keyline');\n line.append(el('span', '', 'Your Aien key: '), el('code', '', key));\n const row = el('div', 'allen-choices');\n const copy = button('Copy', () => copyText(key, copy));\n const forget = button('Forget me', () => forgetMe(forget, state));\n row.append(copy, forget);\n 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.\"));\n } else {\n 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.\"));\n if (oldKey) {\n const forget = button('Forget me', () => forgetOld(forget, state));\n 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);\n }\n }\n parts.push(state);\n body.replaceChildren(...parts);\n const panel = byId('~39~');\n if (panel) panel.dataset.key = key ? 'yes' : 'no';\n }\n" |
| 91 | |
| 92 | note JavaScript forgetMe |
| 93 | text js29 " async function forgetMe(trigger, state) {\n if (!storedKey()) {\n keyPanel();\n return;\n }\n trigger.disabled = true;\n setText(state, 'Sending.');\n try {\n const response = await fetch(FORGET_ME, post({}));\n const reply = await response.json().catch(() => null);\n if (response.ok) {\n dropKey();\n remembered = false;\n showMode();\n keyPanel(\"Forgotten: Aien's notes about you and your introduction are being deleted, and the key is gone from this browser.\");\n return;\n }\n setText(state, failure(response, reply, 'Nothing was deleted; your key is still here so you can try again.'));\n } catch (_) {\n setText(state, 'Could not reach Aien. Nothing was deleted; your key is still here so you can try again.');\n }\n trigger.disabled = false;\n }\n" |
| 94 | |
| 95 | note JavaScript volunteer |
| 96 | text js30 " /* Open Humanity volunteer inference: an anonymous visitor may tick the box\n to let a volunteer's Spark answer when Drake's is full. Never with a key,\n never in remember-me mode, never ticked by the page. */\n function volunteerHeaders() {\n const tick = byId('~54~');\n if (remembered || !tick || !tick.checked) return {};\n return { 'X-Allen-Volunteer': '1' };\n }\n function setVolunteer(on) {\n const tick = byId('~54~');\n if (tick) tick.checked = Boolean(on) && !remembered;\n }\n function volunteerModel(value) {\n const oh = value && typeof value.oh === 'object' && value.oh !== null && !Array.isArray(value.oh) ? value.oh : null;\n if (!oh || oh.answered_by !== 'volunteer') return '';\n return typeof oh.model === 'string' && oh.model ? oh.model.slice(0, 80) : 'model not reported';\n }\n" |
| 97 | |
| 98 | note JavaScript mode |
| 99 | text js31 " /* The badge says which mode the chat is in; its one button switches. */\n function showMode() {\n root.dataset.mode = remembered ? 'remembered' : 'anonymous';\n setText(byId('~50~'), remembered ? 'Remembered: Aien knows you by your Aien key' : \"Anonymous: Aien won't remember this chat\");\n setText(byId('~35~'), remembered ? 'Go anonymous' : 'Remember me');\n /* The volunteer opt-in belongs to anonymous chat only, and starts off. */\n const box = byId('~55~');\n if (box) box.hidden = remembered;\n if (remembered) setVolunteer(false);\n emit('mode', { mode: remembered ? 'remembered' : 'anonymous' });\n }\n function switchMode() {\n if (remembered) goAnonymous(false);\n else openIntro();\n }\n /* Go anonymous: the key leaves this browser at once and calls say\n X-Allen-Anonymous from now on. The old key stays in memory only so Forget\n me can still delete notes kept under it; that one call carries it. */\n function goAnonymous(fromLink) {\n const key = storedKey();\n dropKey();\n remembered = false;\n conversation = conversationId();\n if (key) oldKey = key;\n showMode();\n keyPanel();\n if (fromLink) return;\n if (key) offerForget();\n else notice(\"Anonymous: Aien won't remember this chat.\");\n }\n function offerForget() {\n const note = message('allen', 'Aien');\n const state = el('div', 'allen-card-state');\n const forget = button('Forget me', () => forgetOld(forget, state));\n 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);\n }\n async function forgetOld(trigger, state) {\n if (!oldKey) return;\n trigger.disabled = true;\n setText(state, 'Sending.');\n try {\n 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' });\n const reply = await response.json().catch(() => null);\n if (response.ok) {\n oldKey = '';\n trigger.hidden = true;\n setText(state, \"Forgotten: Aien's notes about you and your introduction are being deleted.\");\n keyPanel();\n return;\n }\n setText(state, failure(response, reply, 'Nothing was deleted yet.'));\n } catch (_) {\n setText(state, 'Could not reach Aien. Nothing was deleted yet.');\n }\n trigger.disabled = false;\n }\n /* What an introduce block becomes while anonymous: an offer, nothing more. */\n function rememberOffer(prefill) {\n const card = el('div', 'allen-card');\n 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.\"));\n const offer = button('Remember me', () => card.replaceWith(introCard(prefill)));\n card.append(offer);\n return card;\n }\n" |
| 100 | |
| 101 | note JavaScript relayCard |
| 102 | text js32 " /* A message Aien offers to pass on. The exact text is shown and goes out\n only when the visitor presses Send to Drake; the conversation is attached\n only if the visitor ticks the box. */\n function relayCard(parsed, out) {\n const text = parsed.body;\n const name = String(parsed.fields.name || '').slice(0, 100);\n const contact = String(parsed.fields.contact || '').slice(0, 200);\n const card = el('div', 'allen-card allen-relay');\n card.append(el('p', 'allen-card-h', 'Message for Drake'));\n if (name) {\n const facts = el('dl', 'allen-kv');\n facts.append(el('dt', '', 'Name'), el('dd', '', name));\n card.append(facts);\n }\n card.append(el('pre', 'allen-card-body', text));\n const reach = field(card, 'Your contact, for this one message (optional)', 'input', 200);\n reach.value = contact;\n 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.\"));\n const state = el('div', 'allen-card-state');\n if (!text) {\n state.append(el('p', 'allen-err', 'There is no message to send. Ask Aien to write it again.'));\n card.append(state);\n out.replaceChildren(card);\n return;\n }\n const includeWrap = el('label', 'allen-agree');\n const include = el('input');\n include.type = 'checkbox';\n includeWrap.append(include, el('span', '', 'include this conversation'));\n const send = button('Send to Drake', () => sendRelay({ text, name, contact: reach.value.trim().slice(0, 200) }, include, send, state));\n 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);\n out.replaceChildren(card);\n }\n function transcript() {\n return turns.slice(-LIMIT.count).map(turn => ({ role: turn.role, content: cut(turn.content, LIMIT.each) }));\n }\n function sessionHeaders() {\n return { 'X-Allen-Conversation': conversation };\n }\n" |
| 103 | |
| 104 | note JavaScript sendRelay |
| 105 | text js33 " async function sendRelay(item, include, send, state) {\n send.disabled = true;\n include.disabled = true;\n state.replaceChildren(el('p', 'allen-note', 'Sending.'));\n const body = { message: item.text, name: item.name, contact: item.contact, transcript: include.checked ? transcript() : [] };\n let response;\n let reply;\n try {\n response = await fetch(RELAY, post(body, sessionHeaders()));\n reply = await response.json().catch(() => null);\n } catch (_) {\n state.replaceChildren(el('p', 'allen-err', 'Could not reach Aien. Nothing was sent.'));\n send.disabled = false;\n include.disabled = false;\n return;\n }\n if (!response.ok || !reply || reply.sent !== true) {\n state.replaceChildren(el('p', 'allen-err', failure(response, reply, 'Nothing was sent.')));\n send.disabled = false;\n include.disabled = false;\n return;\n }\n send.hidden = true;\n state.replaceChildren(el('p', 'allen-ok', reply.duplicate === true ? 'Sent before: this exact message already reached Drake in this conversation.' : 'Sent.'));\n message('allen', 'Aien').body.append(el('p', 'allen-p', \"I've sent this to Drake.\"));\n }\n" |
| 106 | |
| 107 | note JavaScript presence |
| 108 | text js34 " /* Presence comes from the gateway every PRESENCE_MS. Talk to Drake live is\n offered only while he is online and taking handoffs. */\n const drake = { online: false, handoff: false, hours: '', state: '', stream: null };\n async function presence() {\n if (document.hidden && drake.hours) return;\n try {\n const response = await fetch(PRESENCE, { cache: 'no-store', credentials: 'omit', headers: { Accept: 'application/json', ...keyHeaders(false) } });\n const reply = response.ok ? await response.json() : null;\n if (reply && typeof reply === 'object') {\n drake.online = reply.online === true;\n drake.handoff = reply.handoff === true;\n drake.hours = typeof reply.hours === 'string' ? reply.hours.slice(0, 200) : '';\n }\n } catch (_) {\n /* Keep the last reading. */\n }\n showPresence();\n }\n function showPresence() {\n const box = byId('~47~');\n if (!box) return;\n const parts = [];\n if (drake.state === 'waiting') {\n parts.push(el('span', '', 'Waiting for Drake to join. Aien keeps answering until he does.'));\n } else if (drake.state === 'joined') {\n parts.push(el('span', '', 'Drake is here: your messages go to him, not to Aien.'));\n } else if (drake.online && drake.handoff) {\n parts.push(el('span', '', 'Drake is online right now.'), button('Talk to Drake live', event => handoff(event.currentTarget)));\n } else if (drake.hours) {\n parts.push(el('span', '', `Drake's usual hours: ${drake.hours}`));\n }\n box.replaceChildren(...parts);\n box.hidden = !parts.length;\n box.dataset.state = drake.state || (drake.online && drake.handoff ? 'online' : 'away');\n emit('presence', { online: drake.online, handoff: drake.handoff, hours: drake.hours, drake: drake.state });\n }\n" |
| 109 | |
| 110 | note JavaScript handoff |
| 111 | text js35 " async function handoff(trigger) {\n if (drake.state) return;\n trigger.disabled = true;\n try {\n const response = await fetch(HANDOFF, post({ transcript: transcript() }, sessionHeaders()));\n const reply = await response.json().catch(() => null);\n if (!response.ok || !reply || reply.waiting !== true) {\n notice(failure(response, reply, 'Aien is still with you.'));\n trigger.disabled = false;\n return;\n }\n } catch (_) {\n notice('Could not reach Drake. Aien is still with you.');\n trigger.disabled = false;\n return;\n }\n drake.state = 'waiting';\n showPresence();\n session(conversation);\n }\n" |
| 112 | |
| 113 | note JavaScript session |
| 114 | text js36 " /* Holds the session stream for this conversation, reconnecting every\n POLL_MS while Drake is waited for or present. */\n async function session(id) {\n const controller = new AbortController();\n drake.stream = controller;\n while (drake.stream === controller && drake.state) {\n try {\n const response = await fetch(SESSION, { cache: 'no-store', credentials: 'omit', headers: { Accept: 'text/event-stream', 'X-Allen-Conversation': id, ...keyHeaders(false) }, signal: controller.signal });\n if (response.ok && response.body) {\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const parser = sse((name, data) => onSession(name, data, controller));\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n parser.feed(decoder.decode(value, { stream: true }));\n }\n parser.feed(decoder.decode());\n parser.end();\n } else if (response.status >= 400 && response.status < 500 && response.status !== 429) {\n endSession('Drake is not available right now. Aien is with you again.');\n return;\n }\n } catch (_) {\n if (controller.signal.aborted) return;\n }\n if (drake.stream !== controller || !drake.state) return;\n await new Promise(done => setTimeout(done, POLL_MS));\n }\n }\n function onSession(name, data, controller) {\n if (drake.stream !== controller) return;\n let value;\n try {\n value = JSON.parse(data);\n } catch (_) {\n return;\n }\n if (!value || typeof value !== 'object') return;\n if (name === 'human' && typeof value.text === 'string') {\n humanMessage(value.text.slice(0, 8000));\n emit('human', { text: value.text.slice(0, 8000) });\n }\n else if (name === 'state' && ['waiting', 'joined', 'left'].includes(value.drake)) {\n if (value.drake === 'left') {\n endSession('Drake handed you back to Aien.');\n return;\n }\n if (value.drake === 'joined' && drake.state !== 'joined') notice('Drake joined. Your messages now go to him.');\n drake.state = value.drake;\n emit('drake', { state: value.drake });\n showPresence();\n }\n }\n function endSession(text) {\n const stream = drake.stream;\n drake.stream = null;\n drake.state = '';\n if (stream) stream.abort();\n emit('drake', { state: '' });\n showPresence();\n if (text) message('allen', 'Aien').body.append(el('p', 'allen-p', text));\n }\n" |
| 115 | |
| 116 | note JavaScript humanMessage |
| 117 | text js37 " /* The only place the Drake name and avatar are made. It is fed only by\n event: human on the session channel, which the gateway emits only for\n messages typed in Drake's authenticated console. Model tokens and visitor\n text never reach it. */\n function humanMessage(text) {\n const item = el('li', 'allen-msg allen-msg-drake');\n const who = el('p', 'allen-who');\n who.append(el('span', 'allen-avatar', 'D'), document.createTextNode('Drake'));\n const body = el('div', 'allen-body');\n body.append(el('p', 'allen-p', text));\n item.append(who, body);\n log.append(item);\n }\n" |
| 118 | |
| 119 | note JavaScript sayToDrake |
| 120 | text js38 " async function sayToDrake(text) {\n message('user', 'You').body.append(el('p', 'allen-p', text));\n try {\n const response = await fetch(SAY, post({ text }, sessionHeaders()));\n if (!response.ok) {\n const reply = await response.json().catch(() => null);\n notice(failure(response, reply, 'That message did not reach Drake.'));\n }\n } catch (_) {\n notice('That message did not reach Drake. Check your connection.');\n }\n }\n" |
| 121 | |
| 122 | note JavaScript start |
| 123 | text js39 " /* A returning visitor (Aien key kept, not anonymous) gets no static\n greeting: the page sends BACK_LINE as the first turn, unshown, so the\n gateway can bring that visitor's notes and Aien greets them himself. */\n function start() {\n if (remembered && storedKey()) {\n ask(BACK_LINE, true);\n return;\n }\n greeting();\n }\n" |
| 124 | |
| 125 | note JavaScript greeting |
| 126 | text js40 " /* Aien's first message is written here, not by the model: zero latency,\n no request. The answer stays in this closure. */\n function greeting() {\n const hello = message('allen', 'Aien');\n /* The gateway prepends the remember opening exactly when the chat carries\n a key and no X-Allen-Anonymous, so the page shows the same one. */\n const greet = remembered && storedKey() ? GREETING_REMEMBER : GREETING_ANONYMOUS;\n hello.body.append(el('p', 'allen-p', greet), el('p', 'allen-p', 'Are you a human or an agent?'));\n const row = el('div', 'allen-choices');\n row.append(button('Human', () => answer('human')), button('Agent', () => answer('agent')), button('Skip', () => answer('')));\n hello.body.append(row, el('p', 'allen-note', 'Or just type below. The answer only tells Aien who is asking.'));\n choices = row;\n }\n function openIntro(prefill) {\n const note = message('allen', 'Aien');\n note.body.append(introCard(prefill || Object.create(null)));\n note.item.scrollIntoView({ block: 'nearest' });\n }\n function answer(who) {\n if (choices) choices.remove();\n choices = null;\n if (!who) return;\n kind = who;\n message('user', 'You').body.append(el('p', 'allen-p', who === 'agent' ? 'I am an agent.' : 'I am a human.'));\n const reply = message('allen', 'Aien');\n if (who === 'human') {\n 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.'));\n return;\n }\n reply.body.append(\n el('p', 'allen-p', 'Welcome. Who is your human? Tell me the person or organization operating you. You can keep chatting without naming them.'),\n 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.'),\n );\n const row = el('div', 'allen-choices');\n row.append(button('Introduce yourself', () => {\n row.remove();\n openIntro();\n }));\n reply.body.append(row);\n }\n" |
| 127 | |
| 128 | note JavaScript copyText |
| 129 | text js41 " async function copyText(source, node) {\n if (node.dataset.label === undefined) node.dataset.label = node.textContent;\n try {\n await navigator.clipboard.writeText(source);\n setText(node, 'Copied');\n } catch (_) {\n setText(node, 'Copy blocked');\n }\n setTimeout(() => setText(node, node.dataset.label), 1500);\n }\n" |
| 130 | |
| 131 | note JavaScript sandboxed |
| 132 | text js42 " /* The policy becomes the first element of the program's head: after an\n existing head tag that only whitespace, a doctype, comments and an html\n tag precede, else in a head of its own placed after any doctype and html\n tag. A linear scan (no backtracking regex): each comment ends at its\n first -->, as the HTML parser ends it. */\n function sandboxed(source) {\n const meta = `<meta http-equiv=\"Content-Security-Policy\" content=\"${CSP}\">`;\n const lower = source.toLowerCase();\n let at = 0;\n const space = () => {\n while (at < source.length && /\\s/.test(source[at])) at += 1;\n };\n const tag = name => {\n const open = `<${name}`;\n if (!lower.startsWith(open, at)) return false;\n const next = source[at + open.length];\n if (next !== '>' && !(next && /\\s/.test(next))) return false;\n const close = source.indexOf('>', at + open.length);\n if (close < 0) return false;\n at = close + 1;\n return true;\n };\n const doctype = () => {\n if (!lower.startsWith('<!doctype', at)) return false;\n const close = source.indexOf('>', at + 9);\n if (close < 0) return false;\n at = close + 1;\n return true;\n };\n const comments = () => {\n for (;;) {\n space();\n if (!lower.startsWith('<!--', at)) return;\n const close = source.indexOf('-->', at + 4);\n if (close < 0) return;\n at = close + 3;\n }\n };\n space();\n if (doctype()) space();\n const lead = (() => {\n const mark = at;\n const html = tag('html');\n const end = at;\n at = mark;\n return html ? end : mark;\n })();\n comments();\n if (tag('html')) comments();\n if (tag('head')) return source.slice(0, at) + meta + source.slice(at);\n return `${source.slice(0, lead)}<head>${meta}</head>${source.slice(lead)}`;\n }\n" |
| 133 | |
| 134 | note JavaScript runHtml |
| 135 | text js43 " /* The page policy forbids inline scripts, and a srcdoc frame would inherit\n it, so the program runs in /aien/run.html, the one document whose policy\n allows them. That document writes only what its parent posts, and only\n while sandboxed to an opaque origin. */\n function runHtml(source, out) {\n const frame = document.createElement('iframe');\n frame.setAttribute('sandbox', SANDBOX);\n frame.setAttribute('referrerpolicy', 'no-referrer');\n frame.setAttribute('title', 'Program written by Aien, sandboxed');\n frame.className = 'allen-frame';\n frame.addEventListener('load', () => frame.contentWindow.postMessage(sandboxed(source), '*'), { once: true });\n frame.src = '/aien/run.html';\n const box = el('div', 'allen-frame-box');\n box.append(frame);\n 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.'));\n }\n" |
| 136 | |
| 137 | note JavaScript retryAfter |
| 138 | text js44 " function retryAfter(response, body) {\n const value = Number(body && body.retry_after !== undefined ? body.retry_after : response.headers.get('Retry-After'));\n return Number.isFinite(value) && value > 0 ? Math.ceil(value) : 0;\n }\n" |
| 139 | |
| 140 | note JavaScript refusal |
| 141 | text js45 " function refusal(code, body) {\n const said = body && typeof body.message === 'string' ? body.message.slice(0, 300) : '';\n if (code === 429) return 'You are sending faster than Aien takes turns.';\n if (code === 503) return 'Aien is busy with other visitors right now.';\n if (code === 413) return 'That is longer than Aien accepts in one go. Shorten it, or start a new conversation.';\n if (code === 400) return `Aien could not read that request${said ? `: ${said}` : '.'}`;\n return `Aien is unreachable right now (HTTP ${code}).`;\n }\n" |
| 142 | |
| 143 | note JavaScript notice |
| 144 | text js46 " /* Status line text, with a live countdown when the gateway says when to retry. */\n function notice(text, wait) {\n clearInterval(countdown);\n emit('status', { text, wait: wait || 0 });\n if (!wait) {\n setText(status, text);\n return;\n }\n let left = wait;\n const show = () => setText(status, left > 0 ? `${text} Try again in ${left} s.` : `${text} You can try again now.`);\n show();\n countdown = setInterval(() => {\n left -= 1;\n show();\n if (left <= 0) clearInterval(countdown);\n }, 1000);\n }\n" |
| 145 | |
| 146 | note JavaScript types |
| 147 | text js47 " /* Omega scalar types: i32 for the narrow ones (JS Number), i64 for the wide\n ones (JS BigInt). Inputs are checked against the declared range. */\n const TYPES = {\n bool: { wide: false, min: 0n, max: 1n },\n uchar: { wide: false, min: 0n, max: 255n },\n ushort: { wide: false, min: 0n, max: 65535n },\n uint: { wide: false, min: 0n, max: 4294967295n },\n byte: { wide: false, min: -128n, max: 127n },\n short: { wide: false, min: -32768n, max: 32767n },\n int: { wide: false, min: -2147483648n, max: 2147483647n },\n ulong: { wide: true, min: 0n, max: 18446744073709551615n },\n long: { wide: true, min: -9223372036854775808n, max: 9223372036854775807n },\n };\n const known = type => typeof type === 'string' && Object.hasOwn(TYPES, type);\n" |
| 148 | |
| 149 | note JavaScript argument |
| 150 | text js48 " function argument(type, raw) {\n const range = TYPES[type];\n const text = raw.trim();\n if (type === 'bool' && /^(true|false)$/i.test(text)) return text.toLowerCase() === 'true' ? 1 : 0;\n if (!/^-?\\d{1,20}$/.test(text)) throw new RangeError('needs a whole number');\n const value = BigInt(text);\n if (value < range.min || value > range.max) throw new RangeError(`must be ${range.min} to ${range.max}`);\n return range.wide ? value : Number(value);\n }\n" |
| 151 | |
| 152 | note JavaScript shown |
| 153 | text js49 " /* wasm hands back i32 as a signed Number and i64 as a signed BigInt; show\n each value the way its Omega type reads it. */\n function shown(type, value) {\n switch (type) {\n case 'bool': return value !== 0 ? 'true' : 'false';\n case 'uchar': return String(value & 255);\n case 'ushort': return String(value & 65535);\n case 'uint': return String(value >>> 0);\n case 'byte': return String((value << 24) >> 24);\n case 'short': return String((value << 16) >> 16);\n case 'int': return String(value | 0);\n case 'ulong': return BigInt.asUintN(64, value).toString();\n case 'long': return BigInt.asIntN(64, value).toString();\n default: return value === undefined ? 'done' : String(value);\n }\n }\n" |
| 154 | |
| 155 | note JavaScript workerMain |
| 156 | text js50 " /* Runs inside a dedicated worker, so a long loop never freezes this page:\n the page ends the worker when a call overruns CALL_MS. */\n function workerMain() {\n let ready = null;\n self.onmessage = async event => {\n const job = event.data;\n if (job.module) {\n ready = WebAssembly.instantiate(job.module, {});\n ready.catch(() => {});\n return;\n }\n try {\n const instance = await ready;\n const value = instance.exports[job.name](...job.args);\n self.postMessage({ id: job.id, ok: true, value });\n } catch (error) {\n self.postMessage({ id: job.id, ok: false, trap: error instanceof WebAssembly.RuntimeError, message: String((error && error.message) || error) });\n }\n };\n }\n" |
| 157 | |
| 158 | note JavaScript runner |
| 159 | text js51 " function runner(module) {\n let worker = null;\n let next = 0;\n const pending = new Map();\n function stop() {\n if (worker) worker.terminate();\n worker = null;\n for (const job of pending.values()) {\n clearTimeout(job.timer);\n job.done({ ok: false, message: 'the runner was reset' });\n }\n pending.clear();\n }\n function start() {\n const url = URL.createObjectURL(new Blob([`(${workerMain.toString()})();`], { type: 'text/javascript' }));\n worker = new Worker(url);\n URL.revokeObjectURL(url);\n worker.onmessage = event => {\n const job = pending.get(event.data.id);\n if (!job) return;\n pending.delete(event.data.id);\n clearTimeout(job.timer);\n job.done(event.data);\n };\n worker.onerror = event => {\n event.preventDefault();\n stop();\n };\n worker.postMessage({ module });\n }\n function run(name, args) {\n if (!worker) start();\n return new Promise(done => {\n const id = next;\n next += 1;\n const timer = setTimeout(() => {\n pending.delete(id);\n stop();\n done({ ok: false, timeout: true });\n }, CALL_MS);\n pending.set(id, { timer, done });\n worker.postMessage({ id, name, args });\n });\n }\n const handle = { run, stop };\n runners.add(handle);\n return handle;\n }\n" |
| 160 | |
| 161 | note JavaScript fnForm |
| 162 | text js52 " function fnForm(fn, exported, machine) {\n const name = typeof fn.name === 'string' ? fn.name : '';\n const params = Array.isArray(fn.params) ? fn.params : [];\n const ret = typeof fn.ret === 'string' ? fn.ret : 'void';\n const form = el('form', 'allen-fn');\n form.noValidate = true;\n const head = el('p', 'allen-sig');\n head.append(el('code', '', signature({ name, params, ret })));\n form.append(head);\n const fields = params.map(param => {\n const label = el('label', 'allen-arg');\n label.append(el('span', '', `${param.name}: ${param.type}`));\n const field = el('input');\n field.type = 'text';\n field.inputMode = 'numeric';\n field.autocomplete = 'off';\n field.spellcheck = false;\n if (known(param.type)) field.placeholder = `${TYPES[param.type].min} to ${TYPES[param.type].max}`;\n label.append(field);\n form.append(label);\n return field;\n });\n const call = el('button', 'allen-tool', 'Call');\n call.type = 'submit';\n const result = el('output', 'allen-result');\n form.append(call, result);\n if (!exported.has(name) || !params.every(p => known(p.type)) || !(ret === 'void' || known(ret))) {\n call.disabled = true;\n setText(result, 'This function uses a type this page cannot call.');\n }\n form.addEventListener('submit', async event => {\n event.preventDefault();\n const args = [];\n for (let i = 0; i < params.length; i += 1) {\n try {\n args.push(argument(params[i].type, fields[i].value));\n } catch (error) {\n setText(result, `${params[i].name} ${error.message}`);\n fields[i].focus();\n return;\n }\n }\n call.disabled = true;\n setText(result, 'running');\n const answer = await machine.run(name, args);\n call.disabled = false;\n if (answer.ok) setText(result, `= ${shown(ret, answer.value)}`);\n else if (answer.timeout) setText(result, `stopped: no answer within ${CALL_MS / 1000} s, so the runner was reset`);\n else if (answer.trap) setText(result, `trapped: ${answer.message}`);\n else setText(result, `error: ${answer.message}`);\n });\n return form;\n }\n" |
| 163 | |
| 164 | note JavaScript omegaReady |
| 165 | text js53 " async function omegaReady(reply, out, project) {\n const bytes = Uint8Array.from(atob(reply.wasm), c => c.charCodeAt(0));\n const module = await WebAssembly.compile(bytes);\n const exported = new Set(WebAssembly.Module.exports(module).filter(item => item.kind === 'function').map(item => item.name));\n const machine = runner(module);\n const panel = el('div', 'allen-wasm');\n const pin = typeof reply.omc_sha256 === 'string' ? reply.omc_sha256.slice(0, 12) : '?';\n 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}).`));\n const list = Array.isArray(reply.functions) ? reply.functions : [];\n for (const fn of list) panel.append(fnForm(fn, exported, machine));\n if (!list.length) panel.append(el('p', 'allen-note', 'This unit exports no functions.'));\n out.replaceChildren(panel);\n project.wasm = bytes;\n project.functions = list.filter(fn => fn && typeof fn.name === 'string');\n project.pin = typeof reply.omc_sha256 === 'string' && /^[0-9a-f]{64}$/.test(reply.omc_sha256) ? reply.omc_sha256 : '';\n if (project.wasmButton) {\n project.wasmButton.disabled = false;\n project.wasmButton.title = '';\n }\n if (project.htmlButton) project.htmlButton.hidden = false;\n }\n" |
| 166 | |
| 167 | note JavaScript omegaFailed |
| 168 | text js54 " function omegaFailed(source, reply, out) {\n const where = reply.stage === 'irwasm' ? 'The WebAssembly translator refused it' : reply.stage === 'limit' ? 'It is over a size limit' : 'The Omega compiler refused it';\n const message = typeof reply.message === 'string' ? reply.message.slice(0, 500) : 'no message';\n const hint = typeof reply.hint === 'string' ? reply.hint.slice(0, 500) : '';\n const box = el('div', 'allen-fail');\n box.append(el('p', 'allen-err', `${where}: ${message}`));\n if (hint) box.append(el('p', 'allen-note', hint));\n box.append(button('Ask Aien to fix it', () => fixRequest(source, message, hint)));\n out.replaceChildren(box);\n }\n" |
| 169 | |
| 170 | note JavaScript fixRequest |
| 171 | text js55 " function fixRequest(source, message, hint) {\n 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`;\n const room = LIMIT.each - head.length - 4;\n const body = source.length > room ? `${cut(source, Math.max(0, room - 20))}\\n(source cut to fit)` : source;\n ask(`${head}${body}\\n\\`\\`\\``);\n }\n" |
| 172 | |
| 173 | note JavaScript compileOmega |
| 174 | text js56 " async function compileOmega(source, out, trigger, project) {\n if (new TextEncoder().encode(source).length > LIMIT.source) {\n out.replaceChildren(el('p', 'allen-err', `This source is over the ${LIMIT.source} byte limit for compiling.`));\n return;\n }\n trigger.disabled = true;\n out.replaceChildren(el('p', 'allen-note', 'Compiling on the Spark.'));\n try {\n const response = await fetch(OMEGA, post({ source }));\n const reply = await response.json().catch(() => null);\n if (!response.ok || !reply || typeof reply !== 'object') {\n out.replaceChildren(el('p', 'allen-err', failure(response, reply, '')));\n } else if (reply.ok === true && typeof reply.wasm === 'string') {\n await omegaReady(reply, out, project);\n } else {\n omegaFailed(source, reply, out);\n }\n } catch (error) {\n out.replaceChildren(el('p', 'allen-err', `Could not compile and load it: ${error.message}`));\n } finally {\n trigger.disabled = false;\n }\n }\n" |
| 175 | |
| 176 | note JavaScript message |
| 177 | text js57 " function message(role, label) {\n const item = el('li', `allen-msg allen-msg-${role}`);\n /* Aien's own words, in his voice, as opposed to Drake's page copy. */\n if (role === 'allen') item.dataset.speaker = 'allen';\n item.append(el('p', 'allen-who', label));\n const body = el('div', 'allen-body');\n item.append(body);\n log.append(item);\n return { item, body };\n }\n" |
| 178 | |
| 179 | note JavaScript voice |
| 180 | text js58 " /* Aien's voice: first-party clips the gateway names for a reply in its\n meta event. Off until the visitor turns it on; the choice lives in page\n memory only, never in browser storage. One Audio element plays a turn's\n clips in order; a clip that fails is skipped silently, since the text is\n already on the page. */\n const voice = { on: false, list: [], at: -1, audio: null };\n function voiceClips(value) {\n const list = value && Array.isArray(value.voice) ? value.voice : [];\n return list\n .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))\n .slice(0, 24)\n .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 }));\n }\n function voiceShow() {\n const toggle = byId('~58~');\n const next = byId('~59~');\n if (toggle) {\n toggle.setAttribute('aria-pressed', String(voice.on));\n setText(toggle, voice.on ? 'Voice: on' : 'Voice: off');\n }\n if (next) next.hidden = !voice.on || voice.list.length === 0;\n 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) });\n }\n function voicePlay(i) {\n if (!voice.on || i < 0 || i >= voice.list.length) {\n voice.at = voice.list.length;\n voiceShow();\n return;\n }\n if (!voice.audio) {\n voice.audio = new Audio();\n voice.audio.preload = 'auto';\n voice.audio.addEventListener('ended', () => voicePlay(voice.at + 1));\n voice.audio.addEventListener('error', () => voicePlay(voice.at + 1));\n }\n voice.at = i;\n voice.audio.src = voice.list[i].file;\n const playing = voice.audio.play();\n if (playing && playing.catch) playing.catch(() => voiceShow());\n voiceShow();\n }\n function voiceStop() {\n if (voice.audio) voice.audio.pause();\n voice.at = voice.list.length;\n }\n /* A new turn replaces whatever the last one was still saying. */\n function voiceQueue(clips) {\n voiceStop();\n voice.list = clips;\n voice.at = -1;\n if (voice.on && clips.length) voicePlay(0);\n else voiceShow();\n }\n function voiceNext() {\n if (!voice.list.length) return;\n voicePlay(voice.at + 1 < voice.list.length ? voice.at + 1 : voice.list.length - 1);\n }\n function voiceEnable(on) {\n voice.on = Boolean(on);\n if (!voice.on) voiceStop();\n else if (voice.list.length && voice.at < 0) voicePlay(0);\n voiceShow();\n }\n" |
| 181 | |
| 182 | note JavaScript speedReset |
| 183 | text js59 " function speedReset() {\n for (const key of ['queue', 'ttft', 'first', 'rate', 'tokens', 'server']) setText(speed[key], '-');\n }\n" |
| 184 | |
| 185 | note JavaScript busy |
| 186 | text js60 " function busy(on) {\n sendButton.disabled = on;\n stopButton.disabled = !on;\n root.dataset.busy = String(on);\n for (const example of examples.querySelectorAll('button')) example.disabled = on;\n }\n" |
| 187 | |
| 188 | note JavaScript onEvent |
| 189 | text js61 " /* One server event. Times are this page's own clock: queue wait runs from\n Send to the start event, model time to first token from the start event to\n the first non-empty token, and the rate counts tokens after the first. */\n function onEvent(name, data, clock, render) {\n let value;\n try {\n value = JSON.parse(data);\n } catch (_) {\n return;\n }\n const now = performance.now();\n if (name === 'message') {\n if (typeof value !== 'string') return;\n clock.tokens += 1;\n if (Number.isNaN(clock.first)) {\n if (value) {\n clock.first = now;\n setText(speed.ttft, ms(now - clock.start));\n setText(speed.first, ms(now - clock.sent));\n notice('Aien is answering.');\n }\n } else {\n clock.after += 1;\n clock.last = now;\n const span = clock.last - clock.first;\n if (span > 0) setText(speed.rate, (clock.after * 1000 / span).toFixed(1));\n }\n setText(speed.tokens, String(clock.tokens));\n if (value) render.push(value);\n 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 });\n } else if (name === 'queue' && value && Number.isSafeInteger(value.position)) {\n setText(speed.queue, `waiting, ${value.position} ahead`);\n notice(`In line: ${value.position} ${value.position === 1 ? 'request' : 'requests'} ahead of you.`);\n emit('queue', { position: value.position });\n } else if (name === 'start' && value) {\n if (volunteerModel(value)) clock.volunteer = volunteerModel(value);\n clock.start = now;\n setText(speed.queue, `${ms(now - clock.sent)} (server ${count(value.queued_ms)} ms)`);\n if (typeof value.model === 'string' && value.model.length <= 80) setText(speed.model, value.model);\n notice('The model has your message.');\n 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 });\n } else if (name === 'meta' && value && typeof value === 'object' && !Array.isArray(value)) {\n /* Sent after start, before the first token; no voice key means text only. */\n const clips = voiceClips(value);\n emit('voice', { clips, source: typeof value.source === 'string' ? value.source.slice(0, 40) : '' });\n voiceQueue(clips);\n } else if (name === 'done' && value) {\n if (volunteerModel(value)) clock.volunteer = volunteerModel(value);\n clock.finished = true;\n 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`);\n if (value.finish === 'length') clock.outcome = 'The reply reached its length limit and was cut off.';\n 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 });\n } else if (/^pane\\.(open|update|close)$/.test(name) && value && typeof value === 'object' && !Array.isArray(value)) {\n /* Science panes ride the chat stream; the page UI renders them. */\n emit(name, value);\n } else if (name === 'error' && value) {\n clock.finished = true;\n const said = typeof value.message === 'string' ? value.message.slice(0, 300) : 'no message';\n emit('error', { code: typeof value.code === 'string' ? value.code.slice(0, 40) : '', message: said });\n 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}`;\n }\n }\n" |
| 190 | |
| 191 | note JavaScript stream |
| 192 | text js62 " async function stream(body, clock, render) {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n const parser = sse((name, data) => onEvent(name, data, clock, render));\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n parser.feed(decoder.decode(value, { stream: true }));\n }\n parser.feed(decoder.decode());\n parser.end();\n if (!clock.finished && !clock.outcome) clock.outcome = 'The connection closed before Aien finished.';\n }\n" |
| 193 | |
| 194 | note JavaScript ask |
| 195 | text js63 " async function ask(raw, silent = false) {\n const text = cut(String(raw).trim(), LIMIT.each);\n if (!text) return;\n if (choices) {\n choices.remove();\n choices = null;\n }\n if (drake.state === 'joined') {\n sayToDrake(text);\n return;\n }\n if (active) {\n notice('Aien is still answering. Stop that reply first, or wait for it.');\n return;\n }\n const mine = epoch;\n const controller = new AbortController();\n active = controller;\n busy(true);\n speedReset();\n turns.push({ role: 'user', content: text });\n if (!silent) message('user', 'You').body.append(el('p', 'allen-p', text));\n const reply = message('allen', 'Aien');\n reply.item.setAttribute('aria-busy', 'true');\n const render = renderer(reply.body);\n emit('send', { text, silent });\n voiceQueue([]);\n const clock = { sent: performance.now(), start: NaN, first: NaN, last: NaN, tokens: 0, after: 0, finished: false, outcome: '', volunteer: '' };\n let wait = 0;\n notice('Sending.');\n try {\n 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 });\n if (!response.ok) {\n const body = await response.json().catch(() => null);\n wait = retryAfter(response, body);\n clock.outcome = refusal(response.status, body);\n } else if (!response.body || !(response.headers.get('content-type') || '').includes('text/event-stream')) {\n clock.outcome = 'Aien answered in a form this page does not read.';\n } else {\n /* The coordinator names the volunteer's model in X-OH-Model, and the\n final chunk's oh object says the same. */\n const header = response.headers.get('X-OH-Model') || response.headers.get('X-OH-Volunteer');\n if (header) clock.volunteer = /^[\\x20-\\x7e]{1,80}$/.test(header) && header !== '1' ? header : 'model not reported';\n await stream(response.body, clock, render);\n }\n } catch (error) {\n clock.outcome = controller.signal.aborted ? 'Stopped.' : 'Could not reach Aien. Check your connection and try again.';\n }\n const said = render.finish();\n reply.item.removeAttribute('aria-busy');\n if (active === controller) active = null;\n busy(false);\n if (mine !== epoch) return;\n if (said.trim()) {\n turns.push({ role: 'assistant', content: said });\n } else {\n turns.pop();\n if (!input.value) input.value = text;\n }\n if (clock.volunteer) reply.item.append(el('p', 'allen-note allen-volunteer-note', `answered by a volunteer's Spark (${clock.volunteer})`));\n if (clock.outcome) reply.item.append(el('p', 'allen-err', clock.outcome));\n notice(clock.outcome && !said ? clock.outcome : '', wait);\n emit('reply', { text: said, outcome: clock.outcome, volunteer: clock.volunteer });\n }\n" |
| 196 | |
| 197 | note JavaScript regenerate |
| 198 | text js64 " /* Ask again for the last reply: the last answer leaves the history and the\n same user turn is sent once more, unshown, so it is never duplicated. */\n function regenerate() {\n if (active || drake.state === 'joined') return false;\n const n = turns.length;\n if (n < 2 || turns[n - 1].role !== 'assistant' || turns[n - 2].role !== 'user') return false;\n turns.pop();\n const last = turns.pop();\n ask(last.content, true);\n return true;\n }\n" |
| 199 | |
| 200 | note JavaScript draft |
| 201 | text js65 " /* /aien/#draft=<text>: another page hands the visitor a message to start\n from. It only fills the input for editing and is never sent by itself;\n the hash is cleared at once. */\n let draftText = '';\n function takeDraft() {\n const match = /^#draft=([\\s\\S]*)$/.exec(location.hash);\n if (!match) return;\n let text = '';\n try {\n text = decodeURIComponent(match[1]);\n } catch (_) {\n text = '';\n }\n try {\n history.replaceState(null, '', location.pathname + location.search);\n } catch (_) {\n /* The draft still fills the input. */\n }\n text = cut(text.replace(/[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/g, ''), 2000);\n if (!text.trim()) return;\n draftText = text;\n input.value = text;\n emit('draft', { text });\n }\n" |
| 202 | |
| 203 | note JavaScript bind |
| 204 | text js66 " form.addEventListener('submit', event => {\n event.preventDefault();\n if (active) {\n notice('Aien is still answering. Stop that reply first, or wait for it.');\n return;\n }\n const text = input.value;\n if (!text.trim()) return;\n input.value = '';\n ask(text);\n });\n input.addEventListener('keydown', event => {\n if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {\n event.preventDefault();\n form.requestSubmit();\n }\n });\n stopButton.addEventListener('click', () => {\n if (active) active.abort();\n });\n newButton.addEventListener('click', () => {\n epoch += 1;\n if (active) active.abort();\n if (drake.state) endSession('');\n voiceQueue([]);\n turns.length = 0;\n kind = '';\n conversation = conversationId();\n for (const machine of runners) machine.stop();\n runners.clear();\n log.replaceChildren();\n speedReset();\n start();\n notice('New conversation. Nothing from the last one was kept.');\n input.focus();\n });\n for (const example of examples.querySelectorAll('button')) {\n example.addEventListener('click', () => ask(example.textContent));\n }\n byId('~35~').addEventListener('click', switchMode);\n byId('~58~').addEventListener('click', () => voiceEnable(!voice.on));\n byId('~59~').addEventListener('click', voiceNext);\n window.addEventListener('hashchange', forgetOffer);\n window.addEventListener('hashchange', takeDraft);\n conversation = conversationId();\n /* /aien/?mode=anonymous forces anonymous and clears any key; otherwise a\n key kept after an earlier Remember me means this visitor opted in.\n /aien/?mode=remember only opens the consent card; it never opts in. */\n if (entry === 'anonymous') goAnonymous(true);\n else remembered = Boolean(storedKey());\n showMode();\n keyPanel();\n start();\n if (entry === 'anonymous' && oldKey) offerForget();\n if (entry === 'remember' && !remembered) openIntro();\n forgetOffer();\n presence();\n setInterval(presence, PRESENCE_MS);\n /* The transport for a page UI. It adds no powers the page does not\n already show: introductions still pass the consent card, programs still\n run sandboxed, and only the session channel speaks as Drake. */\n window.allen = Object.freeze({\n version: 1,\n on,\n send: text => ask(text),\n regenerate,\n stop: () => {\n if (active) active.abort();\n },\n newConversation: () => newButton.click(),\n mode: () => Object.freeze({ mode: remembered ? 'remembered' : 'anonymous' }),\n rememberMe: () => {\n if (!remembered) openIntro();\n },\n goAnonymous: () => {\n if (remembered) goAnonymous(false);\n },\n forgetMe: async () => {\n if (!remembered || !storedKey()) return false;\n const state = el('p', 'allen-card-state');\n const trigger = el('button');\n await forgetMe(trigger, state);\n return !storedKey();\n },\n presence: () => Object.freeze({ online: drake.online, handoff: drake.handoff, hours: drake.hours, drake: drake.state }),\n handoff: async () => {\n if (drake.state || !drake.online || !drake.handoff) return false;\n await handoff(el('button'));\n return drake.state === 'waiting';\n },\n draft: () => draftText,\n voice: on => {\n if (on !== undefined) voiceEnable(on);\n return voice.on;\n },\n nextClip: voiceNext,\n volunteer: on => {\n if (on !== undefined) setVolunteer(on);\n const tick = byId('~54~');\n return Boolean(tick && tick.checked && !remembered);\n },\n say: text => {\n const said = cut(String(text).trim(), LIMIT.each);\n if (said && drake.state === 'joined') sayToDrake(said);\n },\n });\n root.dataset.ready = 'true';\n document.dispatchEvent(new Event('allen-ready'));\n takeDraft();\n})();\n" |
| 205 | |
| 206 | note JavaScript standalone: the plain text source and the one file runner a visitor keeps |
| 207 | text js67 " /* What a visitor keeps. The source download is <base>.om.txt, so any text\n editor opens it; its note lines are Omega comments, so omc still takes the\n file as it is. The runnable download is <base>.html: one file holding the\n source as text, the compiled wasm as base64 and this page's own runner\n (argument, shown, workerMain), under a policy that allows no network. */\n function sourceText(project) {\n const name = project.base;\n const head = [\n `note ${name}.om.txt: Omega source code as plain text. Aien wrote it at https://www.aienos.com/aien/`,\n \"note Omega is Drake Stapleton's programming language for programs written by AI: https://www.aienos.com/omega/\",\n `note To run it with no tools, download ${name}.html from the same page after Compile and run, then open it in any browser.`,\n `note To build it yourself, save this file as ${name}.om and use the seeded compiler omc and the IR to WebAssembly`,\n 'note translator irwasm, both from https://interplane.io/drakestapleton/omega-mv/tree/main/seed :',\n `note { printf 'ir\\\\n'; cat ${name}.om; } | omc > ${name}.ir`,\n `note irwasm < ${name}.ir > ${name}.wasm`,\n 'note Lines that start with note are comments. The language guide:',\n 'note https://interplane.io/drakestapleton/omega-mv/blob/main/docs/one_layer/OMEGESE.md',\n '',\n ];\n return head.join('\\n') + project.source + (project.source.endsWith('\\n') ? '' : '\\n');\n }\n function escapeHtml(text) {\n return String(text).replace(/[&<>\"']/g, c => `&#${c.charCodeAt(0)};`);\n }\n function base64(bytes) {\n let text = '';\n for (let i = 0; i < bytes.length; i += 8192) text += String.fromCharCode(...bytes.subarray(i, i + 8192));\n return btoa(text);\n }\n function standalone(project) {\n const types = Object.entries(TYPES).map(([type, range]) => `${type}: { wide: ${range.wide}, min: ${range.min}n, max: ${range.max}n }`).join(', ');\n 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' }));\n 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'\";\n const script = `(() => {\n'use strict';\nconst CALL_MS = ${CALL_MS};\nconst TYPES = { ${types} };\nconst FUNCTIONS = ${JSON.stringify(list).replace(/</g, '\\\\u003c')};\nconst WASM = '${base64(project.wasm)}';\nconst known = ${known};\n${argument}\n${shown}\n${signature}\n${workerMain}\nconst engine = document.getElementById('engine');\nconst box = document.getElementById('fns');\nlet module = null;\nlet worker = null;\nlet local = null;\nlet next = 0;\nconst pending = new Map();\nfunction stop() {\n if (worker) worker.terminate();\n worker = null;\n for (const job of pending.values()) {\n clearTimeout(job.timer);\n job.done({ ok: false, message: 'the runner was reset' });\n }\n pending.clear();\n}\nfunction start() {\n try {\n const url = URL.createObjectURL(new Blob([\\`(\\${workerMain.toString()})();\\`], { type: 'text/javascript' }));\n worker = new Worker(url);\n URL.revokeObjectURL(url);\n } catch (_) {\n worker = null;\n return false;\n }\n worker.onmessage = event => {\n const job = pending.get(event.data.id);\n if (!job) return;\n pending.delete(event.data.id);\n clearTimeout(job.timer);\n job.done(event.data);\n };\n worker.onerror = event => {\n event.preventDefault();\n stop();\n };\n worker.postMessage({ module });\n return true;\n}\nasync function run(name, args) {\n if (!local && !worker && !start()) {\n local = await WebAssembly.instantiate(module, {});\n engine.textContent = 'Running on this page: this browser refused a worker for a local file, so a call cannot be stopped early.';\n }\n if (local) {\n try {\n return { ok: true, value: local.exports[name](...args) };\n } catch (error) {\n return { ok: false, trap: error instanceof WebAssembly.RuntimeError, message: String((error && error.message) || error) };\n }\n }\n return new Promise(done => {\n const id = next;\n next += 1;\n const timer = setTimeout(() => {\n pending.delete(id);\n stop();\n done({ ok: false, timeout: true });\n }, CALL_MS);\n pending.set(id, { timer, done });\n worker.postMessage({ id, name, args });\n });\n}\nfunction form(fn, exported) {\n const node = document.createElement('form');\n node.className = 'fn';\n node.dataset.name = fn.name;\n node.noValidate = true;\n const head = document.createElement('code');\n head.textContent = signature(fn);\n node.append(head);\n const fields = fn.params.map(param => {\n const label = document.createElement('label');\n const caption = document.createElement('span');\n caption.textContent = \\`\\${param.name}: \\${param.type}\\`;\n const field = document.createElement('input');\n field.type = 'text';\n field.inputMode = 'numeric';\n field.autocomplete = 'off';\n if (known(param.type)) field.placeholder = \\`\\${TYPES[param.type].min} to \\${TYPES[param.type].max}\\`;\n label.append(caption, field);\n node.append(label);\n return field;\n });\n const call = document.createElement('button');\n call.type = 'submit';\n call.textContent = 'Call';\n const result = document.createElement('output');\n node.append(call, result);\n if (!exported.has(fn.name) || !fn.params.every(p => known(p.type)) || !(fn.ret === 'void' || known(fn.ret))) {\n call.disabled = true;\n result.textContent = 'This function uses a type this file cannot call.';\n }\n node.addEventListener('submit', async event => {\n event.preventDefault();\n const args = [];\n for (let i = 0; i < fn.params.length; i += 1) {\n try {\n args.push(argument(fn.params[i].type, fields[i].value));\n } catch (error) {\n result.textContent = \\`\\${fn.params[i].name} \\${error.message}\\`;\n fields[i].focus();\n return;\n }\n }\n call.disabled = true;\n result.textContent = 'running';\n const answer = await run(fn.name, args);\n call.disabled = false;\n if (answer.ok) result.textContent = \\`= \\${shown(fn.ret, answer.value)}\\`;\n else if (answer.timeout) result.textContent = \\`stopped: no answer within \\${CALL_MS / 1000} s, so the runner was reset\\`;\n else if (answer.trap) result.textContent = \\`trapped: \\${answer.message}\\`;\n else result.textContent = \\`error: \\${answer.message}\\`;\n });\n return node;\n}\n(async () => {\n try {\n module = await WebAssembly.compile(Uint8Array.from(atob(WASM), c => c.charCodeAt(0)));\n } catch (error) {\n engine.textContent = \\`This browser could not load the WebAssembly: \\${error.message}\\`;\n return;\n }\n const exported = new Set(WebAssembly.Module.exports(module).filter(item => item.kind === 'function').map(item => item.name));\n for (const fn of FUNCTIONS) box.append(form(fn, exported));\n if (!FUNCTIONS.length) engine.textContent = 'This program exports no functions.';\n else engine.textContent = 'Ready. Type whole numbers and press Call. Each call runs in a worker and stops after ' + CALL_MS / 1000 + ' s.';\n})();\n})();`.replace(/<\\/(script)/gi, '<\\\\/$1');\n const pin = project.pin ? ` (omc ${escapeHtml(project.pin)})` : '';\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"${policy}\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${escapeHtml(project.title)}: an Omega program</title>\n<style>\nbody { font: 16px/1.5 system-ui, sans-serif; margin: 0; background: #0d1117; color: #e6edf3; }\nmain { max-width: 760px; margin: 0 auto; padding: 24px 16px 48px; }\na { color: #79c0ff; }\npre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 12px; overflow-x: auto; }\nform.fn { border: 1px solid #30363d; border-radius: 6px; padding: 12px; margin: 12px 0; display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: end; }\nform.fn code { flex-basis: 100%; }\nlabel { display: flex; flex-direction: column; font-size: 14px; }\ninput { font: inherit; padding: 4px 6px; width: 12em; }\nbutton { font: inherit; padding: 4px 14px; }\noutput { font-family: ui-monospace, monospace; }\n.small { color: #8b949e; font-size: 14px; }\n</style>\n</head>\n<body>\n<main>\n<h1>${escapeHtml(project.title)}</h1>\n<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>\n<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>\n<p id=\"engine\">Loading the program.</p>\n<noscript><p>Turn on JavaScript in this browser to run the program. The source below is plain text.</p></noscript>\n<div id=\"fns\"></div>\n<h2>The Omega source</h2>\n<pre><code>${escapeHtml(project.source)}</code></pre>\n<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>\n</main>\n<script>\n${script}\n</script>\n</body>\n</html>\n`;\n }\n" |
| 208 | |
| 209 | fn javascript to void |
| 210 | flush |
| 211 | put target 0 3 |
| 212 | js_prelude |
| 213 | js_bus |
| 214 | js_el |
| 215 | js_setText |
| 216 | js_button |
| 217 | js_ms |
| 218 | js_cut |
| 219 | js_fit |
| 220 | js_sse |
| 221 | js_inline |
| 222 | js_renderer |
| 223 | js_tools |
| 224 | js_makeProject |
| 225 | js_readme |
| 226 | js_crc32 |
| 227 | js_zip |
| 228 | js_save |
| 229 | js_downloads |
| 230 | js_standalone |
| 231 | js_field |
| 232 | js_publishForm |
| 233 | js_cardFields |
| 234 | js_issueCard |
| 235 | js_submitItem |
| 236 | js_track |
| 237 | js_introCard |
| 238 | js_saveIntro |
| 239 | js_forgetOffer |
| 240 | js_keys |
| 241 | js_keyPanel |
| 242 | js_forgetMe |
| 243 | js_volunteer |
| 244 | js_mode |
| 245 | js_relayCard |
| 246 | js_sendRelay |
| 247 | js_presence |
| 248 | js_handoff |
| 249 | js_session |
| 250 | js_humanMessage |
| 251 | js_sayToDrake |
| 252 | js_start |
| 253 | js_greeting |
| 254 | js_copyText |
| 255 | js_sandboxed |
| 256 | js_runHtml |
| 257 | js_retryAfter |
| 258 | js_refusal |
| 259 | js_notice |
| 260 | js_types |
| 261 | js_argument |
| 262 | js_shown |
| 263 | js_workerMain |
| 264 | js_runner |
| 265 | js_fnForm |
| 266 | js_omegaReady |
| 267 | js_omegaFailed |
| 268 | js_fixRequest |
| 269 | js_compileOmega |
| 270 | js_message |
| 271 | js_voice |
| 272 | js_speedReset |
| 273 | js_busy |
| 274 | js_onEvent |
| 275 | js_stream |
| 276 | js_ask |
| 277 | js_regenerate |
| 278 | js_draft |
| 279 | js_bind |
| 280 | flush |
| 281 | put target 0 1 |
| 282 | end |
| 283 | |
| 284 | fn js_prelude to void |
| 285 | for b ulong len js0 |
| 286 | byteput get js0 b |
| 287 | end |
| 288 | end |
| 289 | |
| 290 | fn js_bus to void |
| 291 | for b ulong len js1 |
| 292 | byteput get js1 b |
| 293 | end |
| 294 | end |
| 295 | |
| 296 | fn js_el to void |
| 297 | for b ulong len js2 |
| 298 | byteput get js2 b |
| 299 | end |
| 300 | end |
| 301 | |
| 302 | fn js_setText to void |
| 303 | for b ulong len js3 |
| 304 | byteput get js3 b |
| 305 | end |
| 306 | end |
| 307 | |
| 308 | fn js_button to void |
| 309 | for b ulong len js4 |
| 310 | byteput get js4 b |
| 311 | end |
| 312 | end |
| 313 | |
| 314 | fn js_ms to void |
| 315 | for b ulong len js5 |
| 316 | byteput get js5 b |
| 317 | end |
| 318 | end |
| 319 | |
| 320 | fn js_cut to void |
| 321 | for b ulong len js6 |
| 322 | byteput get js6 b |
| 323 | end |
| 324 | end |
| 325 | |
| 326 | fn js_fit to void |
| 327 | for b ulong len js7 |
| 328 | byteput get js7 b |
| 329 | end |
| 330 | end |
| 331 | |
| 332 | fn js_sse to void |
| 333 | for b ulong len js8 |
| 334 | byteput get js8 b |
| 335 | end |
| 336 | end |
| 337 | |
| 338 | fn js_inline to void |
| 339 | for b ulong len js9 |
| 340 | byteput get js9 b |
| 341 | end |
| 342 | end |
| 343 | |
| 344 | fn js_renderer to void |
| 345 | for b ulong len js10 |
| 346 | byteput get js10 b |
| 347 | end |
| 348 | end |
| 349 | |
| 350 | fn js_tools to void |
| 351 | for b ulong len js11 |
| 352 | byteput get js11 b |
| 353 | end |
| 354 | end |
| 355 | |
| 356 | fn js_makeProject to void |
| 357 | for b ulong len js12 |
| 358 | byteput get js12 b |
| 359 | end |
| 360 | end |
| 361 | |
| 362 | fn js_readme to void |
| 363 | for b ulong len js13 |
| 364 | byteput get js13 b |
| 365 | end |
| 366 | end |
| 367 | |
| 368 | fn js_crc32 to void |
| 369 | for b ulong len js14 |
| 370 | byteput get js14 b |
| 371 | end |
| 372 | end |
| 373 | |
| 374 | fn js_zip to void |
| 375 | for b ulong len js15 |
| 376 | byteput get js15 b |
| 377 | end |
| 378 | end |
| 379 | |
| 380 | fn js_save to void |
| 381 | for b ulong len js16 |
| 382 | byteput get js16 b |
| 383 | end |
| 384 | end |
| 385 | |
| 386 | fn js_downloads to void |
| 387 | for b ulong len js17 |
| 388 | byteput get js17 b |
| 389 | end |
| 390 | end |
| 391 | |
| 392 | fn js_standalone to void |
| 393 | for b ulong len js67 |
| 394 | byteput get js67 b |
| 395 | end |
| 396 | end |
| 397 | |
| 398 | fn js_field to void |
| 399 | for b ulong len js18 |
| 400 | byteput get js18 b |
| 401 | end |
| 402 | end |
| 403 | |
| 404 | fn js_publishForm to void |
| 405 | for b ulong len js19 |
| 406 | byteput get js19 b |
| 407 | end |
| 408 | end |
| 409 | |
| 410 | fn js_cardFields to void |
| 411 | for b ulong len js20 |
| 412 | byteput get js20 b |
| 413 | end |
| 414 | end |
| 415 | |
| 416 | fn js_issueCard to void |
| 417 | for b ulong len js21 |
| 418 | byteput get js21 b |
| 419 | end |
| 420 | end |
| 421 | |
| 422 | fn js_submitItem to void |
| 423 | for b ulong len js22 |
| 424 | byteput get js22 b |
| 425 | end |
| 426 | end |
| 427 | |
| 428 | fn js_track to void |
| 429 | for b ulong len js23 |
| 430 | byteput get js23 b |
| 431 | end |
| 432 | end |
| 433 | |
| 434 | fn js_introCard to void |
| 435 | for b ulong len js24 |
| 436 | byteput get js24 b |
| 437 | end |
| 438 | end |
| 439 | |
| 440 | fn js_saveIntro to void |
| 441 | for b ulong len js25 |
| 442 | byteput get js25 b |
| 443 | end |
| 444 | end |
| 445 | |
| 446 | fn js_forgetOffer to void |
| 447 | for b ulong len js26 |
| 448 | byteput get js26 b |
| 449 | end |
| 450 | end |
| 451 | |
| 452 | fn js_keys to void |
| 453 | for b ulong len js27 |
| 454 | byteput get js27 b |
| 455 | end |
| 456 | end |
| 457 | |
| 458 | fn js_keyPanel to void |
| 459 | for b ulong len js28 |
| 460 | byteput get js28 b |
| 461 | end |
| 462 | end |
| 463 | |
| 464 | fn js_forgetMe to void |
| 465 | for b ulong len js29 |
| 466 | byteput get js29 b |
| 467 | end |
| 468 | end |
| 469 | |
| 470 | fn js_volunteer to void |
| 471 | for b ulong len js30 |
| 472 | byteput get js30 b |
| 473 | end |
| 474 | end |
| 475 | |
| 476 | fn js_mode to void |
| 477 | for b ulong len js31 |
| 478 | byteput get js31 b |
| 479 | end |
| 480 | end |
| 481 | |
| 482 | fn js_relayCard to void |
| 483 | for b ulong len js32 |
| 484 | byteput get js32 b |
| 485 | end |
| 486 | end |
| 487 | |
| 488 | fn js_sendRelay to void |
| 489 | for b ulong len js33 |
| 490 | byteput get js33 b |
| 491 | end |
| 492 | end |
| 493 | |
| 494 | fn js_presence to void |
| 495 | for b ulong len js34 |
| 496 | byteput get js34 b |
| 497 | end |
| 498 | end |
| 499 | |
| 500 | fn js_handoff to void |
| 501 | for b ulong len js35 |
| 502 | byteput get js35 b |
| 503 | end |
| 504 | end |
| 505 | |
| 506 | fn js_session to void |
| 507 | for b ulong len js36 |
| 508 | byteput get js36 b |
| 509 | end |
| 510 | end |
| 511 | |
| 512 | fn js_humanMessage to void |
| 513 | for b ulong len js37 |
| 514 | byteput get js37 b |
| 515 | end |
| 516 | end |
| 517 | |
| 518 | fn js_sayToDrake to void |
| 519 | for b ulong len js38 |
| 520 | byteput get js38 b |
| 521 | end |
| 522 | end |
| 523 | |
| 524 | fn js_start to void |
| 525 | for b ulong len js39 |
| 526 | byteput get js39 b |
| 527 | end |
| 528 | end |
| 529 | |
| 530 | fn js_greeting to void |
| 531 | for b ulong len js40 |
| 532 | byteput get js40 b |
| 533 | end |
| 534 | end |
| 535 | |
| 536 | fn js_copyText to void |
| 537 | for b ulong len js41 |
| 538 | byteput get js41 b |
| 539 | end |
| 540 | end |
| 541 | |
| 542 | fn js_sandboxed to void |
| 543 | for b ulong len js42 |
| 544 | byteput get js42 b |
| 545 | end |
| 546 | end |
| 547 | |
| 548 | fn js_runHtml to void |
| 549 | for b ulong len js43 |
| 550 | byteput get js43 b |
| 551 | end |
| 552 | end |
| 553 | |
| 554 | fn js_retryAfter to void |
| 555 | for b ulong len js44 |
| 556 | byteput get js44 b |
| 557 | end |
| 558 | end |
| 559 | |
| 560 | fn js_refusal to void |
| 561 | for b ulong len js45 |
| 562 | byteput get js45 b |
| 563 | end |
| 564 | end |
| 565 | |
| 566 | fn js_notice to void |
| 567 | for b ulong len js46 |
| 568 | byteput get js46 b |
| 569 | end |
| 570 | end |
| 571 | |
| 572 | fn js_types to void |
| 573 | for b ulong len js47 |
| 574 | byteput get js47 b |
| 575 | end |
| 576 | end |
| 577 | |
| 578 | fn js_argument to void |
| 579 | for b ulong len js48 |
| 580 | byteput get js48 b |
| 581 | end |
| 582 | end |
| 583 | |
| 584 | fn js_shown to void |
| 585 | for b ulong len js49 |
| 586 | byteput get js49 b |
| 587 | end |
| 588 | end |
| 589 | |
| 590 | fn js_workerMain to void |
| 591 | for b ulong len js50 |
| 592 | byteput get js50 b |
| 593 | end |
| 594 | end |
| 595 | |
| 596 | fn js_runner to void |
| 597 | for b ulong len js51 |
| 598 | byteput get js51 b |
| 599 | end |
| 600 | end |
| 601 | |
| 602 | fn js_fnForm to void |
| 603 | for b ulong len js52 |
| 604 | byteput get js52 b |
| 605 | end |
| 606 | end |
| 607 | |
| 608 | fn js_omegaReady to void |
| 609 | for b ulong len js53 |
| 610 | byteput get js53 b |
| 611 | end |
| 612 | end |
| 613 | |
| 614 | fn js_omegaFailed to void |
| 615 | for b ulong len js54 |
| 616 | byteput get js54 b |
| 617 | end |
| 618 | end |
| 619 | |
| 620 | fn js_fixRequest to void |
| 621 | for b ulong len js55 |
| 622 | byteput get js55 b |
| 623 | end |
| 624 | end |
| 625 | |
| 626 | fn js_compileOmega to void |
| 627 | for b ulong len js56 |
| 628 | byteput get js56 b |
| 629 | end |
| 630 | end |
| 631 | |
| 632 | fn js_message to void |
| 633 | for b ulong len js57 |
| 634 | byteput get js57 b |
| 635 | end |
| 636 | end |
| 637 | |
| 638 | fn js_voice to void |
| 639 | for b ulong len js58 |
| 640 | byteput get js58 b |
| 641 | end |
| 642 | end |
| 643 | |
| 644 | fn js_speedReset to void |
| 645 | for b ulong len js59 |
| 646 | byteput get js59 b |
| 647 | end |
| 648 | end |
| 649 | |
| 650 | fn js_busy to void |
| 651 | for b ulong len js60 |
| 652 | byteput get js60 b |
| 653 | end |
| 654 | end |
| 655 | |
| 656 | fn js_onEvent to void |
| 657 | for b ulong len js61 |
| 658 | byteput get js61 b |
| 659 | end |
| 660 | end |
| 661 | |
| 662 | fn js_stream to void |
| 663 | for b ulong len js62 |
| 664 | byteput get js62 b |
| 665 | end |
| 666 | end |
| 667 | |
| 668 | fn js_ask to void |
| 669 | for b ulong len js63 |
| 670 | byteput get js63 b |
| 671 | end |
| 672 | end |
| 673 | |
| 674 | fn js_regenerate to void |
| 675 | for b ulong len js64 |
| 676 | byteput get js64 b |
| 677 | end |
| 678 | end |
| 679 | |
| 680 | fn js_draft to void |
| 681 | for b ulong len js65 |
| 682 | byteput get js65 b |
| 683 | end |
| 684 | end |
| 685 | |
| 686 | fn js_bind to void |
| 687 | for b ulong len js66 |
| 688 | byteput get js66 b |
| 689 | end |
| 690 | end |