interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / om / allen-page / allen-js.om

690 lines · 117027 bytes Raw Blame History
1note Allen chat client. ~N~ tokens expand the single definitions in contract.om.
2note Each text holds one JS function or one group of declarations; the last binds the page.
3note Composed with contract.om and allen.om by check.sh, never compiled on its own.
4
5note JavaScript prelude
6text 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
8note JavaScript bus
9text 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
11note JavaScript el
12text 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
14note JavaScript setText
15text js3 " function setText(node, value) {\n if (node && node.textContent !== value) node.textContent = value;\n }\n"
16
17note JavaScript button
18text 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
20note JavaScript ms
21text 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
23note JavaScript cut
24text 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
26note JavaScript fit
27text 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
29note JavaScript sse
30text 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
32note JavaScript inline
33text 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
35note JavaScript renderer
36text 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
38note JavaScript tools
39text 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
41note JavaScript makeProject
42text 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
44note JavaScript readme
45text 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
47note JavaScript crc32
48text 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
50note JavaScript zip
51text 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
53note JavaScript save
54text 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
56note JavaScript downloads
57text 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
59note JavaScript field
60text 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
62note JavaScript publishForm
63text 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
65note JavaScript cardFields
66text 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
68note JavaScript issueCard
69text 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
71note JavaScript submitItem
72text 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
74note JavaScript track
75text 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
77note JavaScript introCard
78text 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
80note JavaScript saveIntro
81text 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
83note JavaScript forgetOffer
84text 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
86note JavaScript keys
87text 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
89note JavaScript keyPanel
90text 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
92note JavaScript forgetMe
93text 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
95note JavaScript volunteer
96text 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
98note JavaScript mode
99text 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
101note JavaScript relayCard
102text 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
104note JavaScript sendRelay
105text 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
107note JavaScript presence
108text 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
110note JavaScript handoff
111text 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
113note JavaScript session
114text 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
116note JavaScript humanMessage
117text 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
119note JavaScript sayToDrake
120text 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
122note JavaScript start
123text 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
125note JavaScript greeting
126text 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
128note JavaScript copyText
129text 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
131note JavaScript sandboxed
132text 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
134note JavaScript runHtml
135text 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
137note JavaScript retryAfter
138text 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
140note JavaScript refusal
141text 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
143note JavaScript notice
144text 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
146note JavaScript types
147text 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
149note JavaScript argument
150text 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
152note JavaScript shown
153text 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
155note JavaScript workerMain
156text 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
158note JavaScript runner
159text 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
161note JavaScript fnForm
162text 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
164note JavaScript omegaReady
165text 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
167note JavaScript omegaFailed
168text 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
170note JavaScript fixRequest
171text 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
173note JavaScript compileOmega
174text 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
176note JavaScript message
177text 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
179note JavaScript voice
180text 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
182note JavaScript speedReset
183text js59 " function speedReset() {\n for (const key of ['queue', 'ttft', 'first', 'rate', 'tokens', 'server']) setText(speed[key], '-');\n }\n"
184
185note JavaScript busy
186text 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
188note JavaScript onEvent
189text 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
191note JavaScript stream
192text 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
194note JavaScript ask
195text 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
197note JavaScript regenerate
198text 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
200note JavaScript draft
201text 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
203note JavaScript bind
204text 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
206note JavaScript standalone: the plain text source and the one file runner a visitor keeps
207text 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
209fn javascript to void
210flush
211put target 0 3
212js_prelude
213js_bus
214js_el
215js_setText
216js_button
217js_ms
218js_cut
219js_fit
220js_sse
221js_inline
222js_renderer
223js_tools
224js_makeProject
225js_readme
226js_crc32
227js_zip
228js_save
229js_downloads
230js_standalone
231js_field
232js_publishForm
233js_cardFields
234js_issueCard
235js_submitItem
236js_track
237js_introCard
238js_saveIntro
239js_forgetOffer
240js_keys
241js_keyPanel
242js_forgetMe
243js_volunteer
244js_mode
245js_relayCard
246js_sendRelay
247js_presence
248js_handoff
249js_session
250js_humanMessage
251js_sayToDrake
252js_start
253js_greeting
254js_copyText
255js_sandboxed
256js_runHtml
257js_retryAfter
258js_refusal
259js_notice
260js_types
261js_argument
262js_shown
263js_workerMain
264js_runner
265js_fnForm
266js_omegaReady
267js_omegaFailed
268js_fixRequest
269js_compileOmega
270js_message
271js_voice
272js_speedReset
273js_busy
274js_onEvent
275js_stream
276js_ask
277js_regenerate
278js_draft
279js_bind
280flush
281put target 0 1
282end
283
284fn js_prelude to void
285for b ulong len js0
286byteput get js0 b
287end
288end
289
290fn js_bus to void
291for b ulong len js1
292byteput get js1 b
293end
294end
295
296fn js_el to void
297for b ulong len js2
298byteput get js2 b
299end
300end
301
302fn js_setText to void
303for b ulong len js3
304byteput get js3 b
305end
306end
307
308fn js_button to void
309for b ulong len js4
310byteput get js4 b
311end
312end
313
314fn js_ms to void
315for b ulong len js5
316byteput get js5 b
317end
318end
319
320fn js_cut to void
321for b ulong len js6
322byteput get js6 b
323end
324end
325
326fn js_fit to void
327for b ulong len js7
328byteput get js7 b
329end
330end
331
332fn js_sse to void
333for b ulong len js8
334byteput get js8 b
335end
336end
337
338fn js_inline to void
339for b ulong len js9
340byteput get js9 b
341end
342end
343
344fn js_renderer to void
345for b ulong len js10
346byteput get js10 b
347end
348end
349
350fn js_tools to void
351for b ulong len js11
352byteput get js11 b
353end
354end
355
356fn js_makeProject to void
357for b ulong len js12
358byteput get js12 b
359end
360end
361
362fn js_readme to void
363for b ulong len js13
364byteput get js13 b
365end
366end
367
368fn js_crc32 to void
369for b ulong len js14
370byteput get js14 b
371end
372end
373
374fn js_zip to void
375for b ulong len js15
376byteput get js15 b
377end
378end
379
380fn js_save to void
381for b ulong len js16
382byteput get js16 b
383end
384end
385
386fn js_downloads to void
387for b ulong len js17
388byteput get js17 b
389end
390end
391
392fn js_standalone to void
393for b ulong len js67
394byteput get js67 b
395end
396end
397
398fn js_field to void
399for b ulong len js18
400byteput get js18 b
401end
402end
403
404fn js_publishForm to void
405for b ulong len js19
406byteput get js19 b
407end
408end
409
410fn js_cardFields to void
411for b ulong len js20
412byteput get js20 b
413end
414end
415
416fn js_issueCard to void
417for b ulong len js21
418byteput get js21 b
419end
420end
421
422fn js_submitItem to void
423for b ulong len js22
424byteput get js22 b
425end
426end
427
428fn js_track to void
429for b ulong len js23
430byteput get js23 b
431end
432end
433
434fn js_introCard to void
435for b ulong len js24
436byteput get js24 b
437end
438end
439
440fn js_saveIntro to void
441for b ulong len js25
442byteput get js25 b
443end
444end
445
446fn js_forgetOffer to void
447for b ulong len js26
448byteput get js26 b
449end
450end
451
452fn js_keys to void
453for b ulong len js27
454byteput get js27 b
455end
456end
457
458fn js_keyPanel to void
459for b ulong len js28
460byteput get js28 b
461end
462end
463
464fn js_forgetMe to void
465for b ulong len js29
466byteput get js29 b
467end
468end
469
470fn js_volunteer to void
471for b ulong len js30
472byteput get js30 b
473end
474end
475
476fn js_mode to void
477for b ulong len js31
478byteput get js31 b
479end
480end
481
482fn js_relayCard to void
483for b ulong len js32
484byteput get js32 b
485end
486end
487
488fn js_sendRelay to void
489for b ulong len js33
490byteput get js33 b
491end
492end
493
494fn js_presence to void
495for b ulong len js34
496byteput get js34 b
497end
498end
499
500fn js_handoff to void
501for b ulong len js35
502byteput get js35 b
503end
504end
505
506fn js_session to void
507for b ulong len js36
508byteput get js36 b
509end
510end
511
512fn js_humanMessage to void
513for b ulong len js37
514byteput get js37 b
515end
516end
517
518fn js_sayToDrake to void
519for b ulong len js38
520byteput get js38 b
521end
522end
523
524fn js_start to void
525for b ulong len js39
526byteput get js39 b
527end
528end
529
530fn js_greeting to void
531for b ulong len js40
532byteput get js40 b
533end
534end
535
536fn js_copyText to void
537for b ulong len js41
538byteput get js41 b
539end
540end
541
542fn js_sandboxed to void
543for b ulong len js42
544byteput get js42 b
545end
546end
547
548fn js_runHtml to void
549for b ulong len js43
550byteput get js43 b
551end
552end
553
554fn js_retryAfter to void
555for b ulong len js44
556byteput get js44 b
557end
558end
559
560fn js_refusal to void
561for b ulong len js45
562byteput get js45 b
563end
564end
565
566fn js_notice to void
567for b ulong len js46
568byteput get js46 b
569end
570end
571
572fn js_types to void
573for b ulong len js47
574byteput get js47 b
575end
576end
577
578fn js_argument to void
579for b ulong len js48
580byteput get js48 b
581end
582end
583
584fn js_shown to void
585for b ulong len js49
586byteput get js49 b
587end
588end
589
590fn js_workerMain to void
591for b ulong len js50
592byteput get js50 b
593end
594end
595
596fn js_runner to void
597for b ulong len js51
598byteput get js51 b
599end
600end
601
602fn js_fnForm to void
603for b ulong len js52
604byteput get js52 b
605end
606end
607
608fn js_omegaReady to void
609for b ulong len js53
610byteput get js53 b
611end
612end
613
614fn js_omegaFailed to void
615for b ulong len js54
616byteput get js54 b
617end
618end
619
620fn js_fixRequest to void
621for b ulong len js55
622byteput get js55 b
623end
624end
625
626fn js_compileOmega to void
627for b ulong len js56
628byteput get js56 b
629end
630end
631
632fn js_message to void
633for b ulong len js57
634byteput get js57 b
635end
636end
637
638fn js_voice to void
639for b ulong len js58
640byteput get js58 b
641end
642end
643
644fn js_speedReset to void
645for b ulong len js59
646byteput get js59 b
647end
648end
649
650fn js_busy to void
651for b ulong len js60
652byteput get js60 b
653end
654end
655
656fn js_onEvent to void
657for b ulong len js61
658byteput get js61 b
659end
660end
661
662fn js_stream to void
663for b ulong len js62
664byteput get js62 b
665end
666end
667
668fn js_ask to void
669for b ulong len js63
670byteput get js63 b
671end
672end
673
674fn js_regenerate to void
675for b ulong len js64
676byteput get js64 b
677end
678end
679
680fn js_draft to void
681for b ulong len js65
682byteput get js65 b
683end
684end
685
686fn js_bind to void
687for b ulong len js66
688byteput get js66 b
689end
690end