app
Adom Forum
Public Made by Adomby adom
Post to and read the Adom Forum from the terminal, run by your AI. Start threads with Markdown and inline images, reply, and browse spaces. Posts made this way carry a 'via <agent>' badge so people can see an AI posted on your behalf.
main
Kyle Bergstedt
Publish 0.1.7
8783e4a
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
// Entry point: launched by bin/adom-forum (a shell shim) via node.
// adom-forum — post to and read the Adom Forum from a container or a laptop.
//
// Auth: a Carbon session token. Resolution order mirrors adom-wiki:
// ADOM_FORUM_TOKEN → /var/run/adom/api-key → /run/adom/api-key → ~/.config/adom-forum/token
// The token is only ever sent to *.adom.inc, *.adom.internal, or a loopback host.
//
// Every write goes through the forum's Bearer API, which records it as posted
// through an agent and shows a "via <agent>" badge next to the author. Pass
// --agent "Codex Astra" (or set ADOM_AGENT_NAME) so the badge names the tool.
//
// Consent: `thread create`, `reply`, and `edit` print a preview and exit 2 unless
// --permission-to-post-given is passed. Show the user the preview first.
// CommonJS on purpose: this file has no extension, and Node 18 (the version
// in Adom containers) only auto-detects ES modules from Node 22 onward.
'use strict'
const { readFileSync, existsSync, statSync } = require('node:fs')
const { basename, dirname, resolve: resolvePath, extname } = require('node:path')
const { homedir } = require('node:os')
const { createHash } = require('node:crypto')
const VERSION = '0.1.7'
// The CLI runs in the shared Linux runtime behind Hydrogen web, macOS, and
// Windows alike. It depends only on Node 18+ (global fetch, FormData, Blob)
// and the container token file; nothing here touches the host OS.
const NODE_MAJOR = Number(process.versions.node.split('.')[0])
if (NODE_MAJOR < 18) {
process.stderr.write(`adom-forum: Node 18 or newer is required (found ${process.versions.node})\n`)
process.exit(1)
}
const DEFAULT_URL = 'https://forum.adom.inc'
const HELP = `adom-forum ${VERSION} — Adom Forum from the terminal
USAGE
adom-forum spaces [--json]
adom-forum threads [--space <slug>] [--sort hot|new|top] [--limit N] [--json]
adom-forum thread get <id> [--json]
adom-forum thread create --space <slug> --title "<title>" --body <text|@file|-> [--agent "<name>"]
[--idempotency-key <key>] [--permission-to-post-given] [--json]
adom-forum reply <thread-id> --body <text|@file|-> [--agent "<name>"] [--idempotency-key <key>]
[--permission-to-post-given] [--json]
adom-forum edit <post-id> --body <text|@file|-> [--title "<title>"] [--permission-to-post-given] [--json]
adom-forum history <post-id> [--json] (forum admins only)
adom-forum media upload <file> [--json]
adom-forum widgets [--json]
adom-forum whoami [--json]
BODY
--body takes Markdown inline, @path/to/file.md, or - for stdin. Local images referenced as
 or  are uploaded and rewritten to gated /media/ URLs
before posting, so images and videos land exactly where they sit in the Markdown.
WIDGETS
A line holding only ::name{key="value"} embeds a wiki widget (3D viewer, video player, …).
\`adom-forum widgets\` lists the ones the forum can render and their attributes.
EDITING
Only your own posts. --title applies to a thread's opening post. The post is marked edited and
every earlier version is kept as an internal record; \`history\` prints them for forum admins.
Post ids are shown by \`thread get\`.
CONSENT
Writes preview first and exit 2. Re-run with --permission-to-post-given after the user says yes.
ENV
FORUM_URL (default ${DEFAULT_URL}) ADOM_FORUM_TOKEN ADOM_AGENT_NAME
`
function fail(message, code = 1, extra = {}) {
if (flags.json) process.stdout.write(JSON.stringify({ status: 'error', error: message, ...extra }) + '\n')
else process.stderr.write(`adom-forum: ${message}\n`)
process.exit(code)
}
function parseArgs(argv) {
const positional = []
const flags = {}
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index]
if (arg.startsWith('--')) {
const key = arg.slice(2)
const next = argv[index + 1]
if (['json', 'permission-to-post-given', 'help', 'version'].includes(key) || next === undefined || next.startsWith('--')) flags[key] = true
else { flags[key] = next; index += 1 }
} else positional.push(arg)
}
return { positional, flags }
}
const { positional, flags } = parseArgs(process.argv.slice(2))
function resolveToken() {
if (process.env.ADOM_FORUM_TOKEN) return { token: process.env.ADOM_FORUM_TOKEN.trim(), source: 'env:ADOM_FORUM_TOKEN' }
for (const path of ['/var/run/adom/api-key', '/run/adom/api-key', resolvePath(homedir(), '.config/adom-forum/token')]) {
try {
const value = readFileSync(path, 'utf8').trim()
if (value) return { token: value, source: `file:${path}` }
} catch { /* try the next one */ }
}
return { token: null, source: null }
}
function baseUrl() {
return (process.env.FORUM_URL || DEFAULT_URL).replace(/\/+$/, '')
}
function trustedHost(url) {
const host = new URL(url).hostname
return host === 'localhost' || host === '127.0.0.1' || host.endsWith('.adom.inc') || host.endsWith('.adom.internal')
}
async function api(method, path, { body, form, idempotencyKey } = {}) {
const url = `${baseUrl()}${path}`
const { token, source } = resolveToken()
// SvelteKit rejects form-encoded and multipart POSTs whose Origin does not
// match the site (its CSRF guard), which covers the image upload. Sending
// the forum's own origin satisfies it; JSON requests are unaffected.
const headers = { 'user-agent': `adom-forum/${VERSION}`, accept: 'application/json', origin: baseUrl() }
if (token) {
if (!trustedHost(url)) fail(`refusing to send the Adom token to ${new URL(url).hostname}`)
headers.authorization = `Bearer ${token}`
}
const agent = flags.agent || process.env.ADOM_AGENT_NAME
if (agent) headers['x-adom-agent'] = String(agent)
if (idempotencyKey) headers['idempotency-key'] = idempotencyKey
let payload
if (form) payload = form
else if (body !== undefined) { headers['content-type'] = 'application/json'; payload = JSON.stringify(body) }
const response = await fetch(url, { method, headers, body: payload })
const text = await response.text()
let data = null
try { data = text ? JSON.parse(text) : null } catch { data = { raw: text } }
if (!response.ok) {
const message = data?.error || `${response.status} ${response.statusText}`
const hint = response.status === 401 ? (token ? ` (token from ${source} was rejected)` : ' (no token found; set ADOM_FORUM_TOKEN or run inside an Adom container)') : ''
fail(`${message}${hint}`, response.status === 429 ? 3 : 1, { code: data?.code, status: response.status, data: data?.data })
}
return { data, headers: response.headers }
}
function readBody(value) {
if (value === undefined || value === true) fail('--body is required (text, @file, or - for stdin)')
if (value === '-') return { text: readFileSync(0, 'utf8'), dir: process.cwd() }
if (String(value).startsWith('@')) {
const path = resolvePath(String(value).slice(1))
return { text: readFileSync(path, 'utf8'), dir: dirname(path) }
}
return { text: String(value), dir: process.cwd() }
}
const IMAGE_TYPES = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' }
const VIDEO_TYPES = { '.mp4': 'video/mp4', '.webm': 'video/webm', '.mov': 'video/quicktime' }
// Videos go straight to object storage: presign, PUT, confirm. The forum
// never proxies the bytes.
async function uploadVideo(path, type) {
const size = statSync(path).size
const { data: ticket } = await api('POST', '/api/media/videos/presign', { body: { filename: basename(path), content_type: type, size } })
const put = await fetch(ticket.upload_url, { method: ticket.upload_method || 'PUT', headers: { 'content-type': type }, body: readFileSync(path) })
if (!put.ok) fail(`${basename(path)}: storage rejected the upload (${put.status})`)
const { data } = await api('POST', '/api/media/videos/confirm', { body: { id: ticket.id } })
return data
}
async function uploadFile(path) {
const extension = extname(path).toLowerCase()
if (VIDEO_TYPES[extension]) return uploadVideo(path, VIDEO_TYPES[extension])
const type = IMAGE_TYPES[extension]
if (!type) fail(`${path}: only PNG, JPEG, GIF, WebP images and MP4, WebM, MOV videos can be uploaded`)
const bytes = readFileSync(path)
const form = new FormData()
form.append('file', new Blob([bytes], { type }), basename(path))
const { data } = await api('POST', '/api/media', { form })
return data
}
const IMAGE_PATTERN = /!\[([^\]]*)\]\(([^)\s]+)(\s+"[^"]*")?\)/g
function localImagePaths(markdown, dir) {
const paths = new Set()
for (const match of markdown.matchAll(IMAGE_PATTERN)) {
const target = match[2]
if (/^(https?:)?\/\//i.test(target) || target.startsWith('/media/') || target.startsWith('data:')) continue
const path = resolvePath(dir, target)
if (existsSync(path) && statSync(path).isFile()) paths.add(path)
}
return [...paths]
}
// Upload local images referenced in the Markdown and rewrite their URLs.
// Only called once the user has approved the post, so a preview never leaves
// orphaned uploads behind.
async function localizeImages(markdown, dir) {
const pattern = IMAGE_PATTERN
const uploads = new Map()
for (const path of localImagePaths(markdown, dir)) {
if (!uploads.has(path)) {
const uploaded = await uploadFile(path)
uploads.set(path, uploaded.url)
if (!flags.json) process.stderr.write(` ${VIDEO_TYPES[extname(path).toLowerCase()] ? 'video' : 'image'} → ${uploaded.url} (${basename(path)})\n`)
}
}
const rewritten = markdown.replace(pattern, (whole, alt, target, title = '') => {
if (/^(https?:)?\/\//i.test(target) || target.startsWith('/media/') || target.startsWith('data:')) return whole
const path = resolvePath(dir, target)
return uploads.has(path) ? `}${title})` : whole
})
return { markdown: rewritten, uploaded: uploads.size }
}
function preview(kind, fields, markdown) {
process.stdout.write(`\n──── preview: ${kind} ────\n`)
for (const [key, value] of Object.entries(fields)) process.stdout.write(`${key}: ${value}\n`)
process.stdout.write(`\n${markdown.trim()}\n──────────────────────────\n`)
process.stdout.write(`Not posted. Show this to the user; re-run with --permission-to-post-given once they approve.\n`)
}
function out(value, human) {
if (flags.json) process.stdout.write(JSON.stringify({ status: 'ok', data: value }) + '\n')
else process.stdout.write(human)
}
function idempotencyFor(explicit, parts) {
if (explicit && explicit !== true) return String(explicit)
return `adom-forum:${createHash('sha256').update(parts.join('