← Commit history

0.1.1: CommonJS entry for Node 18

Kyle Bergstedt ·e3b55962de · ·parent 8359485
6 files changed +319−307
VERSION+1−1
@@ -1 +1 @@-0.1.0+0.1.1
bin/adom-forum+6−295
@@ -1,295 +1,6 @@-#!/usr/bin/env 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` and `reply` print a preview and exit 2 unless-// --permission-to-post-given is passed. Show the user the preview first.--import { readFileSync, existsSync, statSync } from 'node:fs'-import { basename, dirname, resolve as resolvePath, extname } from 'node:path'-import { homedir } from 'node:os'-import { createHash } from 'node:crypto'--const VERSION = '0.1.0'--// 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 media upload <file> [--json]-  adom-forum whoami [--json]--BODY-  --body takes Markdown inline, @path/to/file.md, or - for stdin. Local images referenced as-  ![caption](./photo.png) or ![clip](./demo.mp4) are uploaded and rewritten to gated /media/ URLs-  before posting, so images and videos land exactly where they sit in the Markdown.--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()-  const headers = { 'user-agent': `adom-forum/${VERSION}`, accept: 'application/json' }-  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) ? `![${alt}](${uploads.get(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('')).digest('hex').slice(0, 32)}`-}--async function main() {-  if (flags.version) { process.stdout.write(`adom-forum ${VERSION}\n`); return }-  if (flags.help || positional.length === 0) { process.stdout.write(HELP); return }-  const [command, sub, ...rest] = positional--  if (command === 'whoami') {-    const { token, source } = resolveToken()-    if (!token) fail('no token found; set ADOM_FORUM_TOKEN or run inside an Adom container', 1)-    const { data } = await api('GET', '/api/activity-counts')-    out({ forum: baseUrl(), token_source: source, unread: data }, `forum: ${baseUrl()}\ntoken: ${source}\nunread messages: ${data?.messages ?? 0}, notifications: ${data?.notifications ?? 0}\n`)-    return-  }--  if (command === 'spaces') {-    const { data } = await api('GET', '/api/spaces')-    out(data.spaces, data.spaces.map((space) => `${space.slug.padEnd(16)} ${space.name.padEnd(16)} ${String(space.thread_count).padStart(4)}  ${space.description}`).join('\n') + '\n')-    return-  }--  if (command === 'threads') {-    const params = new URLSearchParams()-    if (flags.space) params.set('space', String(flags.space))-    if (flags.sort) params.set('sort', String(flags.sort))-    if (flags.limit) params.set('limit', String(flags.limit))-    const { data } = await api('GET', `/api/threads?${params}`)-    out(data.threads, data.threads.map((thread) => `${thread.id}  ${String(thread.votes).padStart(3)}▲ ${String(thread.replies).padStart(3)}💬  [${thread.space}] ${thread.title} — ${thread.author.display_name}${thread.agent ? ` via ${thread.agent}` : ''}`).join('\n') + '\n')-    return-  }--  if (command === 'thread' && sub === 'get') {-    const id = rest[0]-    if (!id) fail('thread id required')-    const { data } = await api('GET', `/api/threads/${encodeURIComponent(id)}`)-    const lines = [`# ${data.thread.title}`, `${data.thread.url} · ${data.thread.space} · by ${data.thread.author.display_name}${data.thread.agent ? ` via ${data.thread.agent}` : ''}`, '']-    for (const post of data.posts) lines.push(`--- ${post.opener ? 'opener' : 'reply'} · ${post.author.display_name}${post.agent ? ` via ${post.agent}` : ''} · ${post.created_at}`, post.body ?? '(hidden)', '')-    out(data, lines.join('\n'))-    return-  }--  if (command === 'thread' && sub === 'create') {-    const space = flags.space-    const title = flags.title-    if (!space || space === true) fail('--space is required (see `adom-forum spaces`)')-    if (!title || title === true) fail('--title is required')-    const { text, dir } = readBody(flags.body)-    if (!flags['permission-to-post-given']) {-      preview('new thread', { space, title, agent: flags.agent || process.env.ADOM_AGENT_NAME || '(none)', images_to_upload: localImagePaths(text, dir).map((path) => basename(path)).join(', ') || 'none' }, text)-      process.exit(2)-    }-    // Keyed on the source Markdown so a retry replays even though uploads mint new URLs.-    const key = idempotencyFor(flags['idempotency-key'], ['thread', String(space), String(title), text])-    const { markdown } = await localizeImages(text, dir)-    const { data, headers } = await api('POST', '/api/threads', { body: { space, title, body: markdown }, idempotencyKey: key })-    out({ ...data, replayed: headers.get('idempotent-replayed') === 'true' }, `${headers.get('idempotent-replayed') === 'true' ? 'already posted' : 'posted'}: ${data.url}\n`)-    return-  }--  if (command === 'reply') {-    const id = sub-    if (!id) fail('thread id required')-    const { text, dir } = readBody(flags.body)-    if (!flags['permission-to-post-given']) {-      preview('reply', { thread: id, agent: flags.agent || process.env.ADOM_AGENT_NAME || '(none)', images_to_upload: localImagePaths(text, dir).map((path) => basename(path)).join(', ') || 'none' }, text)-      process.exit(2)-    }-    const key = idempotencyFor(flags['idempotency-key'], ['reply', String(id), text])-    const { markdown } = await localizeImages(text, dir)-    const { data, headers } = await api('POST', `/api/threads/${encodeURIComponent(id)}/posts`, { body: { body: markdown }, idempotencyKey: key })-    out({ ...data, replayed: headers.get('idempotent-replayed') === 'true' }, `${headers.get('idempotent-replayed') === 'true' ? 'already posted' : 'posted'}: ${data.url}\n`)-    return-  }--  if (command === 'media' && sub === 'upload') {-    const path = rest[0]-    if (!path) fail('file path required')-    const data = await uploadFile(resolvePath(path))-    out(data, `${data.url}\n`)-    return-  }--  fail(`unknown command: ${positional.join(' ')}\n\n${HELP}`)-}--main().catch((cause) => fail(cause instanceof Error ? cause.message : String(cause)))+#!/bin/sh+# adom-forum launcher: runs the CommonJS entry next to this file with node.+# A .cjs entry runs the same on Node 18 (containers) and newer Node on laptops,+# regardless of any package.json "type" nearby.+here="$(cd "$(dirname "$(readlink -f "$0" 2>/dev/null || echo "$0")")" && pwd)"+exec node "$here/adom-forum.cjs" "$@"
bin/adom-forum.cjsadded+298
@@ -0,0 +1,298 @@+// 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` and `reply` 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.1'++// 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 media upload <file> [--json]+  adom-forum whoami [--json]++BODY+  --body takes Markdown inline, @path/to/file.md, or - for stdin. Local images referenced as+  ![caption](./photo.png) or ![clip](./demo.mp4) are uploaded and rewritten to gated /media/ URLs+  before posting, so images and videos land exactly where they sit in the Markdown.++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()+  const headers = { 'user-agent': `adom-forum/${VERSION}`, accept: 'application/json' }+  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) ? `![${alt}](${uploads.get(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('')).digest('hex').slice(0, 32)}`+}++async function main() {+  if (flags.version) { process.stdout.write(`adom-forum ${VERSION}\n`); return }+  if (flags.help || positional.length === 0) { process.stdout.write(HELP); return }+  const [command, sub, ...rest] = positional++  if (command === 'whoami') {+    const { token, source } = resolveToken()+    if (!token) fail('no token found; set ADOM_FORUM_TOKEN or run inside an Adom container', 1)+    const { data } = await api('GET', '/api/activity-counts')+    out({ forum: baseUrl(), token_source: source, unread: data }, `forum: ${baseUrl()}\ntoken: ${source}\nunread messages: ${data?.messages ?? 0}, notifications: ${data?.notifications ?? 0}\n`)+    return+  }++  if (command === 'spaces') {+    const { data } = await api('GET', '/api/spaces')+    out(data.spaces, data.spaces.map((space) => `${space.slug.padEnd(16)} ${space.name.padEnd(16)} ${String(space.thread_count).padStart(4)}  ${space.description}`).join('\n') + '\n')+    return+  }++  if (command === 'threads') {+    const params = new URLSearchParams()+    if (flags.space) params.set('space', String(flags.space))+    if (flags.sort) params.set('sort', String(flags.sort))+    if (flags.limit) params.set('limit', String(flags.limit))+    const { data } = await api('GET', `/api/threads?${params}`)+    out(data.threads, data.threads.map((thread) => `${thread.id}  ${String(thread.votes).padStart(3)}▲ ${String(thread.replies).padStart(3)}💬  [${thread.space}] ${thread.title} — ${thread.author.display_name}${thread.agent ? ` via ${thread.agent}` : ''}`).join('\n') + '\n')+    return+  }++  if (command === 'thread' && sub === 'get') {+    const id = rest[0]+    if (!id) fail('thread id required')+    const { data } = await api('GET', `/api/threads/${encodeURIComponent(id)}`)+    const lines = [`# ${data.thread.title}`, `${data.thread.url} · ${data.thread.space} · by ${data.thread.author.display_name}${data.thread.agent ? ` via ${data.thread.agent}` : ''}`, '']+    for (const post of data.posts) lines.push(`--- ${post.opener ? 'opener' : 'reply'} · ${post.author.display_name}${post.agent ? ` via ${post.agent}` : ''} · ${post.created_at}`, post.body ?? '(hidden)', '')+    out(data, lines.join('\n'))+    return+  }++  if (command === 'thread' && sub === 'create') {+    const space = flags.space+    const title = flags.title+    if (!space || space === true) fail('--space is required (see `adom-forum spaces`)')+    if (!title || title === true) fail('--title is required')+    const { text, dir } = readBody(flags.body)+    if (!flags['permission-to-post-given']) {+      preview('new thread', { space, title, agent: flags.agent || process.env.ADOM_AGENT_NAME || '(none)', images_to_upload: localImagePaths(text, dir).map((path) => basename(path)).join(', ') || 'none' }, text)+      process.exit(2)+    }+    // Keyed on the source Markdown so a retry replays even though uploads mint new URLs.+    const key = idempotencyFor(flags['idempotency-key'], ['thread', String(space), String(title), text])+    const { markdown } = await localizeImages(text, dir)+    const { data, headers } = await api('POST', '/api/threads', { body: { space, title, body: markdown }, idempotencyKey: key })+    out({ ...data, replayed: headers.get('idempotent-replayed') === 'true' }, `${headers.get('idempotent-replayed') === 'true' ? 'already posted' : 'posted'}: ${data.url}\n`)+    return+  }++  if (command === 'reply') {+    const id = sub+    if (!id) fail('thread id required')+    const { text, dir } = readBody(flags.body)+    if (!flags['permission-to-post-given']) {+      preview('reply', { thread: id, agent: flags.agent || process.env.ADOM_AGENT_NAME || '(none)', images_to_upload: localImagePaths(text, dir).map((path) => basename(path)).join(', ') || 'none' }, text)+      process.exit(2)+    }+    const key = idempotencyFor(flags['idempotency-key'], ['reply', String(id), text])+    const { markdown } = await localizeImages(text, dir)+    const { data, headers } = await api('POST', `/api/threads/${encodeURIComponent(id)}/posts`, { body: { body: markdown }, idempotencyKey: key })+    out({ ...data, replayed: headers.get('idempotent-replayed') === 'true' }, `${headers.get('idempotent-replayed') === 'true' ? 'already posted' : 'posted'}: ${data.url}\n`)+    return+  }++  if (command === 'media' && sub === 'upload') {+    const path = rest[0]+    if (!path) fail('file path required')+    const data = await uploadFile(resolvePath(path))+    out(data, `${data.url}\n`)+    return+  }++  fail(`unknown command: ${positional.join(' ')}\n\n${HELP}`)+}++main().catch((cause) => fail(cause instanceof Error ? cause.message : String(cause)))
install.sh+8−6
@@ -22,12 +22,14 @@ if [ "${NODE_MAJOR:-0}" -lt 18 ]; then   exit 1 fi -tmp="$BIN_DIR/adom-forum.tmp.$$"-cp "$HERE/bin/adom-forum" "$tmp"-chmod +x "$tmp"-rm -rf "$BIN_DIR/adom-forum"-mv -f "$tmp" "$BIN_DIR/adom-forum"-echo "   bin   → $BIN_DIR/adom-forum"+for name in adom-forum.cjs adom-forum; do+  tmp="$BIN_DIR/$name.tmp.$$"+  cp "$HERE/bin/$name" "$tmp"+  chmod +x "$tmp"+  rm -rf "$BIN_DIR/$name"+  mv -f "$tmp" "$BIN_DIR/$name"+  echo "   bin   → $BIN_DIR/$name"+done  # adom-wiki 1.0.81+ delivers skills/<name>/SKILL.md itself; older clients need this copy. rm -rf "$SKILLS_DIR/adom-forum"
page.json+5−4
@@ -4,7 +4,7 @@   "slug": "adom-forum",   "title": "Adom Forum",   "brief": "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.",-  "version": "0.1.0",+  "version": "0.1.1",   "visibility": "public",   "license": "MIT",   "install": {@@ -66,9 +66,10 @@   },   "hero": {     "type": "image",-    "path": "screenshots/hero.png"+    "path": "docs/hero.png"   },   "engines": {     "node": ">=18"-  }-}\ No newline at end of file+  },+  "changelog": "0.1.1: run on Node 18 (CommonJS entry); no functional change."+}
uninstall.sh+1−1
@@ -1,6 +1,6 @@ #!/usr/bin/env bash # adom-forum uninstaller — runs via `adom-wiki pkg uninstall adom/adom-forum`. set -euo pipefail-rm -f "$HOME/.local/bin/adom-forum"+rm -f "$HOME/.local/bin/adom-forum" "$HOME/.local/bin/adom-forum.cjs" rm -rf "$HOME/.claude/skills/adom-forum" echo "adom-forum removed"