Skip to content

matthewwong525/WongStack / .agents/skills/reply-link

reply-link

Verified

Reply links and the live line's helper.

FileKindSize
SKILL.mdskill md362 B
scripts/helper.mjsscript17.1 KB
scripts/lib/computer.mjsscript13.1 KB
scripts/lib/helper-log.mjsscript1.4 KB
scripts/lib/inbox.mjsscript4.0 KB
scripts/lib/line.mjsscript3.8 KB
scripts/lib/uploads.mjsscript3.8 KB
scripts/lib/wake.mjsscript2.9 KB
scripts/reply-link.mjsscript53.3 KB

scripts/reply-link.mjs

View on GitHub
#!/usr/bin/env node
// Opens a reply link: a page the assistant made, at a web address that closes itself, whose send puts the person's
// text into the chat that opened it. Not a private link: it never carries a secret. wiki/development/reply-links.md

import { execFileSync, spawn } from 'node:child_process';
import { createHash, randomBytes } from 'node:crypto';
import { createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:http';
import { homedir } from 'node:os';
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { isMain, parseCli, usageError } from '../../memory/scripts/lib/cli.mjs';
import { lookCss } from '../../plan/scripts/look.mjs';
import { computerId, guardShared, hasOwnHelper, helperFiles, leaveShared, ownHelper, primaryOf, readApps, rememberApp } from './lib/computer.mjs';
import { logAction } from './lib/helper-log.mjs';
import { checkin, closeItem, companyFor, inTime, listLink, openSocket, probe, readFile, tapResult, upload, waitingReviews } from './lib/inbox.mjs';
import { appLines, nextPoll, waiter } from './lib/line.mjs';
import { bytesRefused, FILE_LIMITS, filesLines, nameRefused, removeFile, saveFile, savedPath, uploadsFor } from './lib/uploads.mjs';
import { alive, freePort, hasCloudflared, keyMatches, killTunnel, linkAnswers, signal, startTunnel } from '../../browser/skills/hand-over/scripts/lib/tunnel.mjs';
import { canWake, chatTarget, liveChats, wakeChat } from './lib/wake.mjs';

const USAGE = `usage: reply-link.mjs open <file> --header "<line>" [--hours N] [--action <name>=<message>]... [--uploads <dir>]
       reply-link.mjs item --title "<words>" --header "<line>" [--hours N] [--action <name>=<message>]...
                      [--hidden] [--keep-open] [--stop "<message>"]
       reply-link.mjs close <file> | close-plan <change> | list
  open    show one self-contained HTML file at a link that closes itself and print
          REPLY_LINK=<url>; its page sends text to this chat under the header line.
          A plan's review page opens in the live app's inbox when it answers this person;
          any other page, or no inbox, opens at a tunnel, and the inbox lists that link after it prints.
          Prints REPLY_LINK=none and REPLY_REASON=off|no-chat|no-cloudflared|tunnel-down
          where no link can open, and exits 0: fall back to the file
          --header: the fixed first line of every message the page sends
          --hours: how long the link stays open (default 24)
          --action: a button the page may offer, and the one-line message a tap on it
          sends to this chat; the page can never change that message (6 at most)
          --uploads: the folder for files the page sends (default .scratch/<page folder>-uploads)
  item    put an item with no file in the inbox for this chat and print REPLY_ITEM=<id>, or none;
          an open item of this chat with the same title is replaced
          --hidden: the inbox lists no card for it; it still takes taps
          --keep-open: a tap leaves it open, and moves its close to --hours from then
          --stop: the one message this chat gets when it closes at its time
  close   close the file's link
  close-plan  close each plan page titled "Review · <change>" waiting in the app, wherever it was
          opened; prints PLAN_PAGE=closed=<n> or PLAN_PAGE=skipped (<reason>)
  list    print each open page's file and when it closes`;
export const LIMITS = { text: 20_000, body: 128 * 1024, header: 300, action: 300, actions: 6 };
const HOURS = 24;
// Raised when the server or inbox helper changes: one from older code is swapped for this one. The shared page server
// takes the highest copy; a project's own helper compares only its own project's copies.
export const PROTOCOL = 16;
const ID = /^[0-9a-f]{32}$/;
const ACTION = /^[a-z][a-z0-9-]{0,30}$/;
const ROUTE = /^\/p\/([0-9a-f]{32})\/(alive|send|act|file)?$/;
const TUNNEL_WAIT_MS = Number(process.env.REPLY_LINK_TUNNEL_WAIT_MS) || 30_000;
const POLL_MS = Number(process.env.REPLY_LINK_POLL_MS) || 5000;
const SEND_GAP_MS = Number(process.env.REPLY_LINK_SEND_GAP_MS) || 5000;
const PROBE_MS = 4000;
// The file limits, smaller in tests only.
const FILE_MAX = Number(process.env.REPLY_LINK_FILE_BYTES) || FILE_LIMITS.file;
const FILES_MAX = Number(process.env.REPLY_LINK_FILES_BYTES) || FILE_LIMITS.total;
// The app fails a collected tap 2 minutes after its claim, or its last file part read, with no result; one older than
// this here is reported, never woken.
const DELIVER_MS = 90_000;
const sleep = ms => new Promise(done => setTimeout(done, ms));
const readJson = file => { try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return null; } };

/** The state files under `env.HOME`, apart from hand-over's. The page server's are shared by every project; the inbox's
 *  items and helper record are `project`'s own helper's, or with none the shared helper's. */
function files(env = process.env, project = null) {
  const dir = join(env.HOME || homedir(), '.wong-stack', 'reply-link');
  const { items, inbox } = helperFiles(env, project);
  return { dir, project, pages: join(dir, 'pages'), items, uploads: join(dir, 'uploads'), inbox, server: join(dir, 'server.json'), lock: join(dir, 'starting.lock'), log: join(dir, 'tunnel.log'), config: join(dir, 'cloudflared.yml') };
}

/** The state an item from `cwd` goes in: its project's own helper's when it has one, so only that one delivers it. */
const stateFor = (env, cwd) => files(env, ownHelper(cwd, env));
/** Where an open item from `cwd` may be: its project's own state, then the shared one it may predate. */
const statesFor = (env, cwd) => {
  const own = ownHelper(cwd, env);
  return own ? [files(env, own), files(env)] : [files(env)];
};

const pageFile = (state, id) => join(state.pages, `${id}.json`);

/** A registration as written, or null when it is missing, malformed, or past its deadline. */
function readPage(state, id, now = Date.now()) {
  const page = ID.test(id) ? readJson(pageFile(state, id)) : null;
  const sound = page && page.id === id && typeof page.file === 'string' && typeof page.key === 'string' && typeof page.header === 'string' && Number.isFinite(page.deadline);
  return sound && page.deadline > now ? page : null;
}

/** Every unexpired registration; with `sweep`, an expired or broken one's file is removed. */
function openPages(state, { sweep = false } = {}) {
  let names;
  try { names = readdirSync(state.pages); } catch { return []; }
  const found = [];
  for (const name of names) {
    const page = readPage(state, name.replace(/\.json$/, ''));
    if (page) found.push(page);
    else if (sweep) {
      rmSync(join(state.pages, name), { force: true });
      dropUnsent(state, name.replace(/\.json$/, ''));
    }
  }
  return found;
}

/** The `[name, message]` pairs as one name-to-message object; throws on a pair outside the limits. */
function checkActions(pairs) {
  if (pairs.length > LIMITS.actions) throw new Error(`--action: ${LIMITS.actions} at most`);
  const actions = {};
  for (const [name, message] of pairs) {
    const text = typeof message === 'string' ? message.trim() : '';
    if (!ACTION.test(name) || Object.hasOwn(actions, name)) throw new Error(`--action takes <name>=<message>, each name once, lowercase: ${name}`);
    if (!text || /[\r\n]/.test(text) || text.length > LIMITS.action) throw new Error(`--action ${name} takes one line of text`);
    actions[name] = text;
  }
  return actions;
}

/** A registration's actions; one written before actions has none. */
const actionsOf = page => (page.actions && typeof page.actions === 'object' ? page.actions : {});

/** Writes the file's registration, keeping an open one's id and key so its link stays; its actions are replaced. */
function register(state, { file, header, actions, hours, target, uploads }) {
  mkdirSync(state.pages, { recursive: true, mode: 0o700 });
  const kept = openPages(state).find(page => page.file === file);
  const page = { id: kept?.id ?? randomBytes(16).toString('hex'), file, key: kept?.key ?? randomBytes(32).toString('hex'), header, actions, target,
    uploads, deadline: Date.now() + hours * 3_600_000 };
  writeFileSync(pageFile(state, page.id), `${JSON.stringify(page)}\n`, { mode: 0o600 });
  return page;
}

const PAGE_HEADERS = { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-frame-options': 'DENY', 'content-security-policy': "frame-ancestors 'none'" };
const CLOSED_STYLE = 'body{display:grid;place-items:center;min-height:100vh;margin:0;padding:1rem;box-sizing:border-box;line-height:1.5}'
  + '.card{max-width:24rem;padding:1.5rem}h1{margin:0 0 .25rem;font-size:1.25rem}p{margin:0;color:var(--muted-foreground)}';
const CLOSED_PAGE = '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">'
  + `<title>This link has closed</title><style>${lookCss()}${CLOSED_STYLE}</style>`
  + '<body><main class="card"><h1>This link has closed</h1><p>Ask your assistant for a new link.</p></main></body></html>';

function reply(response, status, body) {
  const text = body ? JSON.stringify(body) : '';
  response.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', 'content-length': Buffer.byteLength(text) }).end(text);
}

function html(response, status, text) {
  response.writeHead(status, PAGE_HEADERS).end(text);
}

/** The request's JSON body, or null when it is over the limit or not JSON; an oversized one is read and dropped. */
async function readBody(request) {
  const chunks = [];
  let size = 0;
  for await (const chunk of request) {
    size += chunk.length;
    if (size <= LIMITS.body) chunks.push(chunk);
  }
  if (size > LIMITS.body) return null;
  try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return null; }
}

/** The text a send carries, or null: a non-empty string within the limit. */
function sendText(body) {
  const text = body && typeof body.text === 'string' ? body.text.trim() : '';
  return text && text.length <= LIMITS.text ? text : null;
}

/** The SHA-256 of the page's file as it stands, or null when the file is gone. */
function fileVersion(page) {
  try { return createHash('sha256').update(readFileSync(page.file)).digest('hex'); } catch { return null; }
}

// ── files a page sent: saved in its uploads folder, listed per page so a close in another process finds them ──
const uploadsFile = (state, id) => join(state.uploads, `${id}.json`);
const readUploads = (state, id) => (ID.test(id) ? readJson(uploadsFile(state, id)) : null) ?? [];
function writeUploads(state, id, list) {
  mkdirSync(state.uploads, { recursive: true, mode: 0o700 });
  writeFileSync(uploadsFile(state, id), `${JSON.stringify(list)}\n`, { mode: 0o600 });
}

/** Deletes each file page `id` saved but never sent to the chat; the sent ones stay for it. */
function dropUnsent(state, id) {
  for (const file of readUploads(state, id)) if (!file.sent) removeFile(file.path);
  rmSync(uploadsFile(state, id), { force: true });
}

/** The page's files a send names, or null when it names one the page never saved or the list is malformed. */
function namedFiles(state, page, body) {
  if (!Object.hasOwn(body, 'files')) return [];
  if (!Array.isArray(body.files) || body.files.length > 60) return null;
  const saved = readUploads(state, page.id);
  const found = body.files.map(id => saved.find(file => file.id === id));
  return found.every(Boolean) && new Set(body.files).size === body.files.length ? found : null;
}

/** Marks `files` as in the chat, so the link's close keeps them. */
function markSent(state, page, files) {
  const ids = new Set(files.map(file => file.id));
  writeUploads(state, page.id, readUploads(state, page.id).map(file => (ids.has(file.id) ? { ...file, sent: true } : file)));
}

/** A header's words, decoded, or null when they are missing, unreadable, or longer than `max`. */
function headerText(request, name, max) {
  try {
    const text = decodeURIComponent(request.headers[name] ?? '').trim();
    return text && text.length <= max ? text : null;
  } catch { return null; }
}

/** Streams a request's body to `path`, keeping its first 4096 bytes; `size` past `max` stops the writing. */
async function streamTo(request, path, max) {
  const out = createWriteStream(path, { mode: 0o600, flags: 'wx' });
  const head = [];
  let size = 0, headSize = 0;
  try {
    for await (const chunk of request) {
      size += chunk.length;
      if (size > max) continue;
      if (headSize < 4096) { head.push(chunk); headSize += chunk.length; }
      if (!out.write(chunk)) await new Promise(done => out.once('drain', done));
    }
  } finally { await new Promise(done => out.end(done)); }
  return { size, head: Buffer.concat(head).subarray(0, 4096) };
}

/** POST file: one file, saved at once in the page's uploads folder; a send names it later by its id. */
async function saveUpload(state, page, request, response) {
  const name = headerText(request, 'x-file-name', FILE_LIMITS.name);
  const question = headerText(request, 'x-file-question', FILE_LIMITS.question);
  const refused = !question ? 'a file needs its question' : nameRefused(name);
  if (refused) { request.resume(); return reply(response, 400, { error: refused }); }
  const saved = readUploads(state, page.id);
  const left = Math.min(FILE_MAX, FILES_MAX - saved.reduce((sum, file) => sum + file.size, 0));
  const id = randomBytes(16).toString('hex');
  const path = savedPath(page.uploads ?? uploadsFor(page.file), id, name);
  // A cut-off upload leaves no part of itself: nothing lists it, so the link's close would never find it.
  const { size, head } = await streamTo(request, path, left).catch(error => { removeFile(path); throw error; });
  const why = size > FILE_MAX ? `${name} is over 25 MB` : size > left ? 'this link has taken 100 MB of files' : bytesRefused(name, head);
  if (why) { removeFile(path); return reply(response, size > left ? 413 : 400, { error: why }); }
  writeUploads(state, page.id, [...readUploads(state, page.id), { id, name, question, size, path, sent: false }]);
  return reply(response, 200, { id });
}

/** The request handler for every registered page. `wake(target, message)` resolves to wakeChat's
 * answer; the page supplies neither the header, nor the target, nor an action's message. */
export function replyRoutes(state, { wake = wakeChat } = {}) {
  const lastSend = new Map();
  const accepted = new Map();
  /** True when this page sent inside the gap; otherwise the gap starts now. */
  function tooSoon(page) {
    if (Date.now() - (lastSend.get(page.id) ?? -Infinity) < SEND_GAP_MS) return true;
    lastSend.set(page.id, Date.now());
    return false;
  }
  async function send(page, request, response) {
    if (tooSoon(page)) return reply(response, 429, { sent: false });
    const body = await readBody(request);
    const text = sendText(body);
    const named = text && namedFiles(state, page, body);
    if (!named) return reply(response, 400, { sent: false });
    const sent = (await wake(page.target, [`${page.header}\n${text}`, filesLines(named)].filter(Boolean).join('\n'))) === 'notified';
    if (sent) markSent(state, page, named);
    return reply(response, sent ? 200 : 502, { sent });
  }
  /** The names accepted for the page's file as it stands; a new version starts empty. */
  function acceptedFor(page, version) {
    if (accepted.get(page.id)?.version !== version) accepted.set(page.id, { version, names: new Set() });
    return accepted.get(page.id).names;
  }
  async function act(page, request, response) {
    if (tooSoon(page)) return reply(response, 429, { sent: false });
    const body = await readBody(request);
    const actions = actionsOf(page);
    const name = typeof body?.action === 'string' && Object.hasOwn(actions, body.action) ? body.action : null;
    const named = name && namedFiles(state, page, body);
    if (!named || (Object.hasOwn(body, 'text') && (typeof body.text !== 'string' || body.text.length > LIMITS.text))) return reply(response, 400, { sent: false });
    const text = body.text?.trim() || '';
    const version = fileVersion(page);
    if (!version) return reply(response, 410, { closed: true });
    if (body.version !== version) return reply(response, 409, { changed: true });
    const names = acceptedFor(page, version);
    if (names.has(name)) return reply(response, 409, { done: true });
    // Marked before the wake, so a tap that arrives during it is refused; unmarked when the chat did not get it.
    names.add(name);
    const sent = (await wake(page.target, [actions[name], text, filesLines(named)].filter(Boolean).join('\n'))) === 'notified';
    if (sent) markSent(state, page, named);
    else names.delete(name);
    return reply(response, sent ? 200 : 502, { sent });
  }
  return async (request, response) => {
    const { pathname } = new URL(request.url, 'http://page');
    // The outside probe asks `/`: it answers with nothing, so the address is known to route.
    if (pathname === '/') return reply(response, request.method === 'GET' ? 204 : 405);
    const [, id, action] = ROUTE.exec(pathname) ?? [];
    if (!id) return reply(response, 404);
    const page = readPage(state, id);
    if (!action) {
      if (request.method !== 'GET') return reply(response, 405);
      let text = null;
      try { if (page) text = readFileSync(page.file); } catch { /* the file is gone: the link has closed */ }
      return text ? html(response, 200, text) : html(response, 410, CLOSED_PAGE);
    }
    if (!page) return reply(response, 410, { closed: true });
    if (!keyMatches(request.headers['x-reply-key'], page.key)) return reply(response, 403);
    if (request.method !== (action === 'alive' ? 'GET' : 'POST')) return reply(response, 405);
    if (action === 'alive') return reply(response, 200, { closesAt: page.deadline, actions: Object.keys(actionsOf(page)), version: fileVersion(page) });
    if (action === 'file') return saveUpload(state, page, request, response);
    return (action === 'send' ? send : act)(page, request, response);
  };
}

/** Serves every page on 127.0.0.1:`port` until no page is unexpired or the tunnel dies, then kills the tunnel. */
async function serve(port, tunnelPid) {
  const state = files();
  const routes = replyRoutes(state);
  const server = createServer((request, response) => void routes(request, response).catch(() => reply(response, 500)));
  await new Promise((resolve, reject) => server.once('error', reject).listen(port, '127.0.0.1', resolve));
  let ending = false;
  const end = async () => {
    if (ending) return;
    ending = true;
    server.close();
    server.closeAllConnections();
    await killTunnel(tunnelPid);
    await unlist(openPages(state));
    // The links close with the server: a file no send named goes too.
    for (const name of (() => { try { return readdirSync(state.uploads); } catch { return []; } })()) dropUnsent(state, name.replace(/\.json$/, ''));
    if (readJson(state.server)?.pid === process.pid) for (const file of [state.server, state.log, state.config]) rmSync(file, { force: true });
    process.exit(0);
  };
  for (const sig of ['SIGTERM', 'SIGINT', 'SIGHUP']) process.on(sig, end);
  for (;;) {
    await sleep(POLL_MS);
    if (!openPages(state, { sweep: true }).length || !alive(tunnelPid)) return end();
  }
}

/** The running server's record when it and its tunnel are alive and the public address answers, else null. */
async function liveServer(state) {
  const server = readJson(state.server);
  if (!server || !alive(server.pid) || !alive(server.tunnelPid)) return null;
  return (await linkAnswers(server.origin, server.port, server.tunnelPid, Date.now() + PROBE_MS)) ? server : null;
}

/** True when this process now holds the start lock; a lock whose holder died is taken over. */
function takeLock(state) {
  for (let i = 0; i < 2; i++) {
    try { writeFileSync(state.lock, `${process.pid}\n`, { flag: 'wx' }); return true; } catch { /* held */ }
    // An empty lock is one being written this instant: still held.
    let holder = '';
    try { holder = readFileSync(state.lock, 'utf8').trim(); } catch { continue; }
    if (!holder || alive(Number(holder))) return false;
    rmSync(state.lock, { force: true });
  }
  return false;
}

/** Ends a server that no longer answers, and its tunnel. */
async function endStale(state) {
  const old = readJson(state.server);
  if (!old) return;
  if (alive(old.pid)) signal(old.pid, 'SIGKILL');
  await killTunnel(old.tunnelPid);
  rmSync(state.server, { force: true });
}

/** Spawns the detached server for `port`, tied to the tunnel's life. */
function spawnServer(port, tunnelPid, env) {
  const child = spawn(process.execPath, [fileURLToPath(import.meta.url), 'serve', String(port), String(tunnelPid)], { detached: true, stdio: 'ignore', env });
  child.unref();
  return child;
}

/** Replaces a running server from older code with this one on the same port, keeping its tunnel, so
 * every open link keeps its address. Resolves to the new record, or null when the address stops answering. */
async function swapServer(state, old, env) {
  // SIGKILL, not SIGTERM: the old server's own ending would take the tunnel with it.
  signal(old.pid, 'SIGKILL');
  for (let i = 0; i < 50 && alive(old.pid); i++) await sleep(100);
  const child = spawnServer(old.port, old.tunnelPid, env);
  if (!(await linkAnswers(old.origin, old.port, old.tunnelPid, Date.now() + TUNNEL_WAIT_MS))) return null;
  const server = { ...old, pid: child.pid, protocol: PROTOCOL };
  writeFileSync(state.server, `${JSON.stringify(server)}\n`, { mode: 0o600 });
  return server;
}

/** Starts the tunnel and the detached server; resolves to the server's record, or to why not. */
async function startServer(state, env) {
  await endStale(state);
  if (!hasCloudflared()) return { reason: 'no-cloudflared' };
  const port = await freePort();
  const deadline = Date.now() + TUNNEL_WAIT_MS;
  const tunnel = await startTunnel(port, deadline, state);
  const child = tunnel.origin ? spawnServer(port, tunnel.pid, env) : null;
  if (!child || !(await linkAnswers(tunnel.origin, port, tunnel.pid, deadline))) {
    if (child) signal(child.pid, 'SIGKILL');
    await killTunnel(tunnel.pid);
    return { reason: 'tunnel-down' };
  }
  const server = { pid: child.pid, port, tunnelPid: tunnel.pid, origin: tunnel.origin, protocol: PROTOCOL };
  writeFileSync(state.server, `${JSON.stringify(server)}\n`, { mode: 0o600 });
  return server;
}

/** The one shared server, started when none answers; another opener's start is waited for, not doubled. */
async function ensureServer(state, env) {
  const until = Date.now() + TUNNEL_WAIT_MS + PROBE_MS;
  let live;
  for (;;) {
    live = await liveServer(state);
    if (live && (live.protocol ?? 1) >= PROTOCOL) return live;
    if (takeLock(state)) break;
    if (Date.now() >= until) return { reason: 'tunnel-down' };
    await sleep(250);
  }
  try { return (live && await swapServer(state, live, env)) || await startServer(state, env); } finally { rmSync(state.lock, { force: true }); }
}

// ── the inbox: the live app lists the page and holds each tap until this computer delivers it ──
const itemFile = (state, id) => join(state.items, `${id}.json`);
const PLAN_MARK = '<!-- wong-review:3 -->';
const sha = text => createHash('sha256').update(text).digest('hex');

/** An inbox item as written, or null when it is missing or malformed; one past its deadline is still read, to close. */
function readItem(state, id) {
  const item = ID.test(id) ? readJson(itemFile(state, id)) : null;
  return item && item.id === id && typeof item.header === 'string' && typeof item.version === 'string' && Number.isFinite(item.deadline) ? item : null;
}

function openItems(state) {
  let names;
  try { names = readdirSync(state.items); } catch { return []; }
  return names.map(name => readItem(state, name.replace(/\.json$/, ''))).filter(Boolean);
}

const writeItem = (state, item) => writeFileSync(itemFile(state, item.id), `${JSON.stringify(item)}\n`, { mode: 0o600 });
/** Writes an item back only while it is still open here: a closed one never comes back. */
const keepItem = (state, item) => { if (existsSync(itemFile(state, item.id))) writeItem(state, item); };

/** A plan's title from its `<title>`, else the file's name. */
function titleOf(text, file) {
  const named = /<title>([^<]{1,400})<\/title>/i.exec(text)?.[1].replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').trim();
  return (named || basename(file)).slice(0, 200);
}

/** What the app keeps of an item: its words, actions and chat's agent id, never its target chat or messages. */
const shown = (item, body) => ({ id: item.id, kind: item.kind, title: item.title, workspace: item.workspace, body,
  actions: Object.keys(item.actions), version: item.version, closesAt: item.deadline, ...(item.hidden && { hidden: true }),
  ...(item.chat && { chat: item.chat }) });

/** The item's body as it stands: a plan's file, or the words it was made with; null when the file is gone. */
function bodyOf(item) {
  if (item.file === null) return item.body;
  try { return readFileSync(item.file, 'utf8'); } catch { return null; }
}

/** A process's command line, from /proc where it exists, else `ps` (macOS); '' when neither answers. */
function commandOf(pid) {
  try { return readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').join(' '); } catch { /* no /proc */ }
  try { return execFileSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); } catch { return ''; }
}

const isInboxHelper = pid => /reply-link\.mjs serve-inbox\b/.test(commandOf(pid));

const writeInbox = (state, pid, service = false) =>
  writeFileSync(state.inbox, `${JSON.stringify({ pid, protocol: PROTOCOL, ...(service && { service: true }) })}\n`, { mode: 0o600 });

/** Starts the inbox server for `state`'s project unless a current one, or its background helper, runs; it stops once no
 * item is open. One from older code is ended first: it reads its record only between rounds, so never stops for us. */
export async function startInbox(state, env) {
  const running = readJson(state.inbox);
  if (alive(running?.pid)) {
    if (running.service || (running.protocol ?? 1) >= PROTOCOL) return;
    // A record outlives its helper, and the pid may since belong to another program: signal only our own helper.
    if (isInboxHelper(running.pid)) {
      signal(running.pid, 'SIGTERM');
      for (let i = 0; i < 50 && alive(running.pid); i++) await sleep(100);
    }
  }
  const project = state.project ? ['--project', state.project] : [];
  const child = spawn(process.execPath, [fileURLToPath(import.meta.url), 'serve-inbox', ...project], { detached: true, stdio: 'ignore', env });
  child.unref();
  writeInbox(state, child.pid);
}

/** Puts an item in the person's inbox: `{id, link}`, or null where it does not answer. `spec` is `{kind, header,
 * actions, hours, target, cwd}`, a plan's `file` or an item's `title` and `body`; may name its `id` and `workspace`. */
export async function openInboxItem(spec, { env = process.env, clientFor = companyFor, start = startInbox } = {}) {
  const file = spec.file ?? null;
  const body = file === null ? spec.body : readFileSync(file, 'utf8');
  // Only a plan's review page can talk to the inbox around it; any other page keeps its tunnel.
  if (file !== null && !body.startsWith(PLAN_MARK)) return null;
  const client = await clientFor(spec.cwd);
  const origin = client && await probe(client);
  if (!origin) return null;
  // A project with its own helper keeps its items there: the shared helper never sees them.
  const state = stateFor(env, spec.cwd);
  mkdirSync(state.items, { recursive: true, mode: 0o700 });
  const kept = file === null ? null : openItems(state).find(item => item.file === file);
  const item = { id: kept?.id ?? spec.id ?? randomBytes(16).toString('hex'), file, kind: spec.kind, title: file === null ? spec.title : titleOf(body, file),
    workspace: (spec.workspace ?? basename(spec.cwd)).slice(0, 100), header: spec.header, actions: spec.actions, target: spec.target,
    deadline: Date.now() + spec.hours * 3_600_000, version: sha(body), ...(file === null && { body }), done: kept?.done ?? { version: null, names: [] },
    uploads: spec.uploads ?? uploadsFor(file ?? join(spec.cwd, 'inbox', 'item'), spec.cwd),
    app: { cwd: spec.cwd, origin }, ...(spec.hidden && { hidden: true }), ...(spec.keepOpen && { keepOpen: true, hours: spec.hours }),
    ...(spec.stop && { stop: spec.stop }), ...(env.PASEO_AGENT_ID && { chat: env.PASEO_AGENT_ID.slice(0, 128) }) };
  if (!(await upload(client, shown(item, body)))) return null;
  writeItem(state, item);
  rememberApp(spec.cwd, env);
  await start(state, env);
  return { id: item.id, link: `${origin}/apps/inbox/?item=${item.id}` };
}

/** Closes the item in the app, then here; true once the app took it. Until then, or its deadline, it stays here
 * marked ended, so each round tries the close again and no tap reaches it. */
async function endItem(state, client, item, now = Date.now()) {
  const closed = Boolean(client && await closeItem(client, item.id));
  if (closed || item.deadline <= now) rmSync(itemFile(state, item.id), { force: true });
  else keepItem(state, { ...item, ended: true });
  return closed;
}

/** The app an item or listed page was put in; one from older code names none, and was opened from its chat's folder. */
const appOf = record => record.app ?? { cwd: record.target?.cwd };

/** Each record's client, signed in from its app's folder once per folder, else from a remembered folder signed in to
 * the record's app; null when none is, as another app must never get this one's ids. */
function clientsFor(clientFor, env = process.env) {
  const byFolder = new Map();
  const signIn = cwd => { if (!byFolder.has(cwd)) byFolder.set(cwd, clientFor(cwd)); return byFolder.get(cwd); };
  const fits = (client, origin) => Boolean(client && (!origin || client.target() === origin));
  return async record => {
    const { cwd, origin } = appOf(record);
    const own = await signIn(cwd);
    if (fits(own, origin)) return own;
    // A closed chat's folder is deleted; its item still reaches its app through another folder.
    for (const app of origin ? readApps(env) : []) {
      const client = await signIn(app.cwd);
      if (fits(client, origin)) return client;
    }
    return null;
  };
}

/** Closes inbox item `id`, in the app it was put in; true when it was open here, for `cwd`'s project. */
export async function closeInboxItem(id, { env = process.env, clientFor = companyFor, cwd = process.cwd() } = {}) {
  for (const state of statesFor(env, cwd)) {
    const item = readItem(state, id);
    if (!item) continue;
    await endItem(state, await clientsFor(clientFor, env)(item), item);
    return true;
  }
  return false;
}

/** Closes each plan page titled `Review · <name>`: this computer's own, then each still waiting in the app of the
 * folder `cwd`, wherever it was opened. Answers `closed=<n>`, or `skipped (<reason>)`. */
export async function closePlanPages(cwd, name, { env = process.env, clientFor = companyFor } = {}) {
  const title = `Review · ${name}`;
  const clientOf = clientsFor(clientFor, env);
  // Page id → closed: a page whose own close failed and the app's list then closed counts once, as closed. `held` keeps
  // the state each page sits in: this project's own helper's, or the shared one it may predate.
  const pages = new Map(), held = new Map();
  for (const state of statesFor(env, cwd)) {
    for (const item of openItems(state).filter(open => open.title === title)) {
      held.set(item.id, state);
      pages.set(item.id, await endItem(state, await clientOf(item), item));
    }
  }
  const client = await clientFor(cwd);
  const waiting = client && await waitingReviews(client, name);
  if (!waiting) return `skipped (${client ? 'the Inbox did not answer' : 'no app is connected here'})`;
  for (const review of waiting.filter(page => page.title === title)) {
    const done = Boolean(await closeItem(client, review.id));
    if (done && held.has(review.id)) rmSync(itemFile(held.get(review.id), review.id), { force: true });
    pages.set(review.id, pages.get(review.id) || done);
  }
  const closed = [...pages.values()].filter(Boolean).length, missed = pages.size - closed;
  return missed ? `skipped (${missed} of ${pages.size} did not close)` : `closed=${closed}`;
}

/** The tap's files, each read from the app, checked as a tunnel's are, and saved in the item's uploads folder; null
 * once one fails, with what it saved removed. */
async function fetchFiles(item, tap, read) {
  const listed = Array.isArray(tap.files) ? tap.files : [];
  const saved = [];
  let total = 0;
  for (const { id } of listed) {
    const file = typeof id === 'string' && /^[0-9a-f]{32}$/.test(id) ? await read(id) : null;
    total += file?.bytes.length ?? 0;
    const why = !file ? 'unread' : file.bytes.length !== file.size || file.size > FILE_LIMITS.file || total > FILE_LIMITS.total ? 'size'
      : nameRefused(file.name) ?? bytesRefused(file.name, file.bytes);
    const folder = item.uploads ?? uploadsFor(item.file ?? join(appOf(item).cwd, 'inbox', 'item'), appOf(item).cwd);
    let path = null;
    if (!why) try { path = saveFile(folder, id, file.name, file.bytes); } catch { /* a folder it can't write */ }
    if (!path) { saved.forEach(done => removeFile(done.path)); return null; }
    saved.push({ name: file.name, question: file.question, size: file.size, path });
  }
  return saved;
}

/** One tap's outcome under `act`'s rules: `changed` on an old version, `sent` with no second wake for a done action.
 * `gap` paces the item's wakes, one per SEND_GAP_MS, as a page's sends are; a tap held too long is `failed`. */
async function deliver(state, item, tap, { wake, gap, read }) {
  if (tap.version !== item.version) return 'changed';
  const text = typeof tap.text === 'string' ? tap.text.trim() : '';
  if (tap.action !== 'send' && !Object.hasOwn(item.actions, tap.action)) return 'failed';
  if (item.done.version !== item.version) item.done = { version: item.version, names: [] };
  const once = tap.action !== 'send' && !item.keepOpen;
  if (once && item.done.names.includes(tap.action)) return 'sent';
  if ((tap.action === 'send' && !text) || !(await gap(item.id))) return 'failed';
  const saved = await fetchFiles(item, tap, read);
  if (!saved) return 'failed';
  // A kept-open item takes the same action again and again: each tap is its own wake, with no notes.
  const words = tap.action === 'send' ? [`${item.header}\n${text}`] : item.keepOpen ? [item.actions[tap.action]] : [item.actions[tap.action], text];
  // Marked before the wake, so a second tap during it is never woken twice; unmarked when the chat did not get it.
  if (once) { item.done.names.push(tap.action); keepItem(state, item); }
  if ((await wake(item.target, [...words, filesLines(saved)].filter(Boolean).join('\n'))) === 'notified') return 'sent';
  if (once) { item.done.names = item.done.names.filter(name => name !== tap.action); keepItem(state, item); }
  saved.forEach(file => removeFile(file.path));
  return 'failed';
}

/** Waits out the rest of the item's gap since its last wake, then starts the next; false once the tap is too old.
 * `claim.at` is when the app last held the round's taps: their collection, or a file part read since. */
function pacer({ lastWake, wait, claim }) {
  return async id => {
    const left = (lastWake.get(id) ?? -Infinity) + SEND_GAP_MS - Date.now();
    if (left > 0) await wait(left);
    if (Date.now() - claim.at > DELIVER_MS) return false;
    lastWake.set(id, Date.now());
    return true;
  };
}

const untold = entry => !entry.told && Date.now() - entry.at < DELIVER_MS;

/** Sends each outcome not yet taken to the app that handed its tap out, side by side, so an app that never answers
 * holds back no other's; true while any is left to send. */
async function report(reported) {
  await Promise.all([...reported].filter(([, entry]) => untold(entry))
    .map(async ([id, entry]) => { entry.told = Boolean(await tapResult(entry.client, id, entry.outcome)); }));
  return [...reported.values()].some(untold);
}

const isEnded = (item, body, { live, now }) => item.ended || item.deadline <= now || body === null || Boolean(live && !live.has(item.target?.agentId));

/** The items whose taps can go this round, by app origin: `origin → {client, items}`. One that ran out, lost its chat
 * or its file closes; one whose app can't be reached waits, as does a rebuilt plan the app has not taken. */
async function readyApps(state, { clientOf, chats, now, wake }) {
  const apps = new Map();
  const items = openItems(state);
  // The helper's rounds with nothing open ask no chat list of Paseo.
  const live = items.length ? await chats() : null;
  for (const item of items) {
    const client = await clientOf(item);
    const body = bodyOf(item);
    if (isEnded(item, body, { live, now })) {
      // Only an item that ran out of time tells its chat, once: a lost chat or file has no one to tell.
      if (item.stop && !item.ended && item.deadline <= now && body !== null && !(live && !live.has(item.target?.agentId))) await wake(item.target, item.stop);
      await endItem(state, client, item, now);
      continue;
    }
    if (!client) continue;
    const version = sha(body);
    if (version !== item.version && !(await upload(client, shown({ ...item, version }, body)))) continue;
    if (version !== item.version) writeItem(state, Object.assign(item, { version }));
    const origin = client.target();
    if (!apps.has(origin)) apps.set(origin, { client, items: new Map() });
    apps.get(origin).items.set(item.id, item);
  }
  return apps;
}

/** How many open items can reach their app. */
async function reachable(state, clientOf) {
  let count = 0;
  for (const item of openItems(state)) if (await clientOf(item)) count += 1;
  return count;
}

/** One inbox round, each item through its own app: close what ran out, re-upload rebuilt plans, deliver taps.
 * `reported` and `lastWake` carry across rounds. Resolves to the open items whose app answers. */
export async function inboxTick(state, { clientFor, env = process.env, wake = wakeChat, chats = liveChats, now = Date.now(),
  reported = new Map(), lastWake = new Map(), wait = sleep, log = () => {} }) {
  const clientOf = clientsFor(clientFor, env);
  const earlier = report(reported);
  const apps = [...(await readyApps(state, { clientOf, chats, now, wake })).values()];
  // Side by side: an app that never answers would otherwise hold another's taps past DELIVER_MS.
  await Promise.all([earlier, ...apps.map(app => serveApp(state, app, { wake, reported, lastWake, wait, log }))]);
  return reachable(state, clientOf);
}

/** A kept-open item after a tap: its close moves to its hours from now, here and in the app. */
async function renew(state, client, item) {
  item.deadline = Date.now() + item.hours * 3_600_000;
  keepItem(state, item);
  await upload(client, shown(item, bodyOf(item)));
}

/** One app's round: collect its taps, deliver each, close what got its answer, and tell the app each outcome. */
async function serveApp(state, { client, items }, { wake, reported, lastWake, wait, log }) {
  const taps = (await checkin(client, [...items.keys()])) ?? [];
  const claim = { at: Date.now() };
  const gap = pacer({ lastWake, wait, claim });
  const read = id => readFile(client, id, () => { claim.at = Date.now(); });
  for (const tap of taps) {
    const item = items.get(tap.item);
    // An item this round closed takes no second answer; one made elsewhere was never collected for it.
    const known = reported.get(tap.id)?.outcome;
    const outcome = known ?? (item ? await deliver(state, item, tap, { wake, gap, read }) : 'expired');
    if (!known) log({ event: 'tap', app: client.target(), item: tap.item, tap: tap.id, action: tap.action, outcome });
    reported.set(tap.id, { outcome, told: false, at: Date.now(), client });
    // Told at once: a later tap's files can take longer to read than the app waits for this one's result.
    await report(new Map([[tap.id, reported.get(tap.id)]]));
    // Any item is answered once its answer is in the chat; a rebuilt plan opened again comes back as a new item.
    if (item && outcome === 'sent' && item.keepOpen) await renew(state, client, item);
    else if (item && outcome === 'sent') { await endItem(state, client, item); items.delete(item.id); }
  }
}

/** The apps to keep a line to, `origin → {client, roots}`: each open item's app, and in service mode `project`'s, or
 * with none each remembered one. `roots`, its schedules' main checkouts, are `project`, or those with no own helper. */
async function watchedApps(state, { clientFor, env, service, project = null }) {
  const clientOf = clientsFor(clientFor, env);
  const apps = new Map();
  const serves = root => (project ? root === project : !hasOwnHelper(root, env));
  const add = (client, root) => {
    let origin;
    try { origin = client?.target(); } catch { return; /* its sign-in changed */ }
    if (!origin) return;
    if (!apps.has(origin)) apps.set(origin, { client, roots: [] });
    if (root && serves(root) && !apps.get(origin).roots.includes(root)) apps.get(origin).roots.push(root);
  };
  for (const item of openItems(state)) add(await clientOf(item), primaryOf(appOf(item).cwd));
  if (service && project) add(await clientOf({ app: { cwd: project } }), project);
  // A project with its own helper is never served here, even when an older copy listed it again.
  else if (service) for (const { cwd } of readApps(env)) {
    const root = primaryOf(cwd);
    if (root && serves(root)) add(await clientOf({ app: { cwd } }), root);
  }
  return apps;
}

const MIRROR_MS = 15 * 60_000;
/** The least time between two rounds, however many looks arrive. */
const ROUND_GAP_MS = 1000;
const appRuns = () => import('../../../inbox/runs.mjs');

/** Starts each app's due schedules on this computer, and sends its Paseo schedules to the app every 15 minutes. A
 * project's own helper notes its runs in its own `ledger`. */
async function scheduleRounds(apps, { rounds, computer, log, mirrored, ledger, now = Date.now() }) {
  let runs;
  try { runs = await rounds(); } catch { return; }
  await Promise.all([...apps].filter(([, app]) => app.roots.length).map(async ([origin, { client, roots }]) => {
    const own = ledger ? { ledger } : {};
    try { await runs.runRound(client, { computer, roots, log, ...own }); } catch { /* the next round tries again */ }
    if (now - (mirrored.get(origin) ?? -Infinity) < MIRROR_MS) return;
    mirrored.set(origin, now);
    try { await runs.mirrorRound(client, { computer, roots, log }); } catch { /* likewise */ }
  }));
}

/** Waits until `gap` ms after `since`, or until stopped. */
function rest(since, gap, stop) {
  const left = since + gap - Date.now();
  if (left <= 0 || stop?.aborted) return Promise.resolve();
  return new Promise(done => {
    const end = () => { clearTimeout(timer); stop?.removeEventListener('abort', end); done(); };
    const timer = setTimeout(end, left);
    stop?.addEventListener('abort', end, { once: true });
  });
}

/** Makes this service the one inbox helper: one started for a single item would never stop for it. */
function takeInbox(state) {
  const running = readJson(state.inbox);
  if (running?.pid !== process.pid && alive(running?.pid) && isInboxHelper(running.pid)) signal(running.pid, 'SIGTERM');
  mkdirSync(dirname(state.inbox), { recursive: true, mode: 0o700 });
  writeInbox(state, process.pid, true);
}

/** True once this helper may end, no item reaching its app. Its record goes first: an item written meanwhile
 * starts a new helper, or is taken up here. */
async function released(state, clientFor, env) {
  if (readJson(state.inbox)?.pid !== process.pid) return true;
  rmSync(state.inbox, { force: true });
  if (!(await reachable(state, clientsFor(clientFor, env)))) return true;
  writeInbox(state, process.pid);
  return false;
}

/** Delivers taps, keeping a live line to each app so a tap wakes it at once; as the background helper (`service`) it
 * never stops and starts schedules. With `project` it serves that project alone (wiki/stack/live-line.md). */
export async function serveInbox({ service = false, project = null, env = process.env, clientFor = companyFor, connect = openSocket, rounds = appRuns,
  computer = computerId(env), log = entry => logAction(entry, { env, root: project }), signal: stop, pollFor = nextPoll, roundGap = ROUND_GAP_MS } = {}) {
  const state = files(env, project);
  const ledger = project ? helperFiles(env, project).runs : undefined;
  const memory = { reported: new Map(), lastWake: new Map(), log };
  const wakeUp = waiter();
  const lines = appLines({ connect: client => connect(client, computer), computer, protocol: PROTOCOL, onLook: wakeUp.poke, log });
  const mirrored = new Map();
  if (service) takeInbox(state);
  // Between rounds too: a round may be 5 minutes off, and the shared helper may claim this project's run at the hour.
  const unguard = service && project ? guardShared(project, env) : () => {};
  try {
    while (!stop?.aborted) {
      const started = Date.now();
      let count = 1;
      try {
        // An older session may list this project with the shared helper again, or put an item there.
        if (service && project) leaveShared(project, env);
        const apps = await watchedApps(state, { clientFor, env, service, project });
        lines.sync(new Map([...apps].map(([origin, app]) => [origin, app.client])));
        count = await inboxTick(state, { clientFor, env, ...memory });
        if (service) await scheduleRounds(apps, { rounds, computer, log, mirrored, ledger });
      } catch (error) { if (!service) throw error; }
      const owed = [...memory.reported.values()].some(untold);
      if (!service && !count && !owed && await released(state, clientFor, env)) return;
      await wakeUp.wait(pollFor(lines.allOpen() && !owed, env), stop);
      await rest(started, roundGap, stop);
    }
  } finally {
    unguard();
    lines.close();
    if (service && readJson(state.inbox)?.pid === process.pid) rmSync(state.inbox, { force: true });
  }
}

/** Lists a tunnel page in the inbox as a form, by its link alone, and marks it with its app so its close closes the
 * item there. */
async function listPage(state, page, link, cwd = process.cwd()) {
  const client = await companyFor(cwd);
  const item = { id: page.id, what: 'form', title: page.header.slice(0, 200), url: link, closesAt: page.deadline, workspace: basename(cwd).slice(0, 100) };
  if (!client || !(await listLink(client, item)) || !readPage(state, page.id)) return;
  writeFileSync(pageFile(state, page.id), `${JSON.stringify({ ...page, listed: true, app: { cwd, origin: client.target() } })}\n`, { mode: 0o600 });
}

/** Closes each of `pages` the inbox lists, in the app that lists it. */
export async function unlist(pages, { clientFor = companyFor } = {}) {
  const clientOf = clientsFor(clientFor);
  await Promise.all(pages.filter(page => page.listed).map(async page => {
    const client = await clientOf(page);
    if (client) await closeItem(client, page.id);
  }));
}

/** `{link}` for the file's reply link, the inbox's first, or `{link: null, reason}` where none can open. A page at a
 * tunnel that is no plan comes back as `page`, for the inbox to list. */
async function openLink({ file, header, actions = {}, hours = HOURS, env = process.env, cwd = process.cwd(), inbox = {}, uploads }) {
  const checked = checkActions(Object.entries(actions));
  if (env.REPLY_LINK === 'off') return { link: null, reason: 'off' };
  const target = chatTarget(env, cwd);
  if (!canWake(target, env)) return { link: null, reason: 'no-chat' };
  const real = realpathSync(file);
  const folder = resolve(cwd, uploads ?? uploadsFor(real, cwd));
  const item = await openInboxItem({ file: real, kind: 'plan', header, actions: checked, hours, target, cwd, uploads: folder }, { env, ...inbox });
  if (item) return { link: item.link };
  const state = files(env);
  const page = register(state, { file: real, header, actions: checked, hours, target, uploads: folder });
  const server = await ensureServer(state, env);
  if (server.reason) {
    rmSync(pageFile(state, page.id), { force: true });
    return { link: null, reason: server.reason };
  }
  const plan = readFileSync(real, 'utf8').startsWith(PLAN_MARK);
  return { link: `${server.origin}/p/${page.id}/#key=${page.key}`, ...(!plan && { page }) };
}

/** The file's reply link, or null, quickly and quietly, where none can open: the caller then offers the file.
 * `header` is every message's first line; `actions` maps each button to its message; `inbox` takes test stand-ins. */
export async function openReplyLink(options) {
  try { return (await openLink(options)).link; } catch { return null; }
}

/** The file's real path, or exit 1 once it has said the file is missing. */
function realFile(file) {
  try { return realpathSync(file); } catch {
    console.error(`No such file: ${file}`);
    process.exit(1);
  }
}

async function open(file, { header, actions, hours, uploads }) {
  const { link, reason, page } = await openLink({ file: realFile(file), header, actions, hours, uploads });
  console.log(`REPLY_LINK=${link ?? 'none'}`);
  if (!link) console.log(`REPLY_REASON=${reason}`);
  // The chat has its link first: the inbox's listing waits at most 3 s, and a failed one changes nothing.
  if (page) await inTime(listPage(files(), page, link));
}

async function close(file) {
  const state = files();
  let path = resolve(file);
  try { path = realpathSync(file); } catch { /* a deleted file's link still closes */ }
  const page = openPages(state).find(open => open.file === path);
  if (page) {
    rmSync(pageFile(state, page.id), { force: true });
    dropUnsent(state, page.id);
    await unlist([page]);
  }
  const item = statesFor(process.env, process.cwd()).flatMap(openItems).find(open => open.file === path);
  if (item) await closeInboxItem(item.id);
  console.log(`REPLY_CLOSED=${page || item ? 'yes' : 'no'}`);
}

/** Puts a file-less item in the inbox for this chat; replaces this chat's open item of the same title. */
async function putItem({ title, header, actions, hours, hidden, keepOpen, stop }, env = process.env, cwd = process.cwd()) {
  const target = chatTarget(env, cwd);
  if (env.REPLY_LINK === 'off' || !canWake(target, env)) { console.log('REPLY_ITEM=none'); return; }
  const kept = openItems(stateFor(env, cwd)).find(open => open.file === null && open.title === title && open.target?.agentId === target.agentId);
  const opened = await openInboxItem({ id: kept?.id, kind: 'approval', title, body: JSON.stringify({ text: title }), header, actions, hours,
    target, cwd, hidden, keepOpen, stop }, { env }).catch(() => null);
  console.log(`REPLY_ITEM=${opened?.id ?? 'none'}`);
}

function list() {
  for (const page of [...openPages(files()), ...statesFor(process.env, process.cwd()).flatMap(openItems)]) console.log(`${page.file ?? page.title}\tcloses ${new Date(page.deadline).toISOString()}`);
}

if (isMain(import.meta.url)) {
  const { values, positionals: [command, ...rest] } = parseCli({ usage: USAGE, allowPositionals: true, options: { header: { type: 'string' }, hours: { type: 'string' }, action: { type: 'string', multiple: true }, service: { type: 'boolean' },
    title: { type: 'string' }, hidden: { type: 'boolean' }, 'keep-open': { type: 'boolean' }, stop: { type: 'string' }, uploads: { type: 'string' }, project: { type: 'string' } } });
  const takes = { open: 1, item: 0, close: 1, 'close-plan': 1, list: 0, serve: 2, 'serve-inbox': 0 }[command];
  if (takes === undefined || rest.length !== takes) usageError(USAGE, command ? `unknown command: ${[command, ...rest].join(' ')}` : 'missing command');
  const hours = Number(values.hours ?? HOURS);
  if (!(hours > 0)) usageError(USAGE, '--hours must be a positive number');
  const header = values.header?.trim() ?? '';
  const opens = command === 'open' || command === 'item';
  if (opens && (!header || /[\r\n]/.test(header) || header.length > LIMITS.header)) usageError(USAGE, '--header takes one line of text');
  if (!opens && (values.header !== undefined || values.hours !== undefined || values.action !== undefined)) usageError(USAGE, '--header, --hours, and --action go with open or item only');
  const title = values.title?.trim() ?? '', stop = values.stop?.trim() ?? '';
  if (command === 'item' && (!title || title.length > 200 || stop.length > LIMITS.action)) usageError(USAGE, '--title takes 1 to 200 characters, --stop at most 300');
  if (command !== 'item' && (values.title ?? values.stop ?? values.hidden ?? values['keep-open']) !== undefined) usageError(USAGE, '--title, --hidden, --keep-open and --stop go with item only');
  if (values.service && command !== 'serve-inbox') usageError(USAGE, '--service goes with serve-inbox only');
  if (values.project !== undefined && (command !== 'serve-inbox' || !isAbsolute(values.project))) usageError(USAGE, '--project takes a main checkout\'s full path, with serve-inbox only');
  if (values.uploads !== undefined && (command !== 'open' || !values.uploads.trim())) usageError(USAGE, '--uploads takes a folder, with open only');
  let actions;
  try { actions = checkActions((values.action ?? []).map(pair => pair.split(/=(.*)/s).slice(0, 2))); } catch (error) { usageError(USAGE, error.message); }
  const itemSpec = { title, header, actions, hours, hidden: Boolean(values.hidden), keepOpen: Boolean(values['keep-open']), stop };
  await { open: () => open(rest[0], { header, actions, hours, uploads: values.uploads }), item: () => putItem(itemSpec), close: () => close(rest[0]),
    'close-plan': async () => console.log(`PLAN_PAGE=${await closePlanPages(process.cwd(), rest[0])}`), list, serve: () => serve(Number(rest[0]), Number(rest[1])), 'serve-inbox': () => serveInbox({ service: Boolean(values.service), project: values.project ?? null }) }[command]();
  // An app call past its 3 s wait would keep the process, and the chat's answer, alive until it fails.
  if (opens || command === 'close' || command === 'close-plan') process.exit(process.exitCode ?? 0);
}
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall