claude-service (ProcrastinAI's webhook runner for headless Claude)
claude-serviceprocrastinaifastapiwebhookhmacautosshreverse-tunnelsystemdclaude-code
claude-service is a small, app-agnostic service that lets any registered app (TLDR, Forge, Stocks, ...) submit a prompt, get 202 Accepted immediately, and receive Claude's answer later on an HMAC-signed callback. It runs claude -p (headless Claude Code) on Justin's desktop, in a per-project working directory, and is what answers TLDR's AI posts as the persona ProcrastinAI. It replaced a TLDR-specific poller (poll_ai.py, every 2 minutes) in 2026-03.
Topology
App on the server (e.g. TLDR API, PHP)
-> POST http://127.0.0.1:9100/request (server side of the tunnel)
-> autossh reverse tunnel -R 9100:localhost:9100
-> claude-service on the desktop (:9100, FastAPI)
-> claude -p in the project dir
-> POST result to the app's callback URL (HMAC-SHA256 signed)
- Repo
~/dev/claude-service(Python 3.12, FastAPI, uvicorn, httpx; venv in the repo; GitLab remoteprocrastinai). The working tree is the deployment: restart withsystemctl --user restart claude-serviceafter changes. - Two systemd user units on the desktop, enabled at boot (with linger):
claude-service.serviceandclaude-tunnel.service(autossh -M 0 -N -R 9100:localhost:9100 justin@<server>,ServerAliveInterval 30). - On the server, nginx can also proxy a public path to the tunnel port; port 9100 had to be labeled
http_port_tin SELinux (see nginx in front of Apache (TLS proxy on :8008)).
API
POST /request(Bearer API key per app): prompt, options, request id, callback URL. Duplicate request id while in progress returns 409.GET /status/{id}: fallback polling. Results are kept in memory for an hour (result_ttl_seconds).DELETE /request/{id},GET /projects,GET /health(no auth),GET /admin/history.- Each app has its own sequential queue; different apps run concurrently. Each project maps to a working directory used as the cwd of
claude -p, so the project's CLAUDE.md, settings and memory apply.
Registering an app or project
config.json (gitignored; template config.example.json) holds per-app API keys, callback secrets, and the project-to-directory map. register-app.sh only adds to apps; add the project to projects too or it will not show in /projects (found when adding Stocks). register-project.sh <name> <dir> registers an explicitly pickable project. Credentials live in that file and in each app's server-only config, never in git.
Example project, Stocks: a TLDR AI post tagged project=stocks runs Claude in ~/dev/stocks, whose CLAUDE.md says how to format quotes and whose .claude/settings.json allows ./tools/stock.sh SYMBOL (Finnhub /quote, free tier 60 req/min, 5-minute file cache in /tmp) and carries the Finnhub key in its env block. No TLDR schema or endpoint changes were needed.
The TLDR side
- Server-only
api/ai_conf.php(excluded from rsync deploys) holds the service URL, API key, callback secret and callback URL. POST /postswith type ai triggersAiManager::triggerNewPost(): parse tags (#opus,#sonnet,#haiku,#danger), setai_status=processing, send the request. A human reply to an AI post triggerstriggerContinuedThread()with the conversation history.POST /ai/callbackhas no user auth; it verifiesX-Signature= HMAC-SHA256 of the raw body withhash_equals(), then posts the answer as useraiand setsai_status=answered. Retryable errors re-trigger up to 3 times per turn; otherwise an error message is posted. Since v1.61.0 (October 2026) per-turn job state lives in anai_requesttable matched by the service's request id, not in post meta (see Lifecycle of an async AI request (status machine, expiry, retries, failure)).- Schema gotcha met on the way:
post_tag.postidhas no underscore whilepost_meta.post_iddoes.
Behavior and conventions
- The service strips the
CLAUDECODEenv var before callingclaude -p, so it works even when started from inside a Claude Code session. - Every run is logged to the project's memory dir as
ai-activity.jsonl(and centrally inhistory.jsonl); local sessions should skim it for changes made by headless runs. - Default project is
home(/home/justin), a router: the run decides which project a request concerns and reads and writes that project's memory. Posts keep their project because--resumeis per directory. - Why not one directory for everything: the starting directory picks which
MEMORY.mdindex is auto-loaded (the only memory loaded for free), whichCLAUDE.mdand.claude/settings.jsonapply, where the run's activity log lands, and where its session is stored. Running every project from one directory makes every run pay for every project's index, and parallel runs edit the same index. A default directory that routes keeps focus without forcing a pick up front. Before the change, untagged posts defaulted to the tldr repo, so about 70% of runs and several unrelated projects' notes piled up in tldr's memory. - A routed run's activity-log entry lands in the starting directory's memory, so the run must write a note into the target project's memory for that project's local sessions to see the work.
guest-<slug>projects (AI guest mode, October 2026) are never in the projects map: they run sandboxed in~/dev/ai-guest/<slug>/and publish a static site. See Sandboxing Claude Code for untrusted users (bubblewrap, --restricted, token pipe).- What to request (tags, model gating, prompts, retries) lives in the TLDR repo; how it executes lives in claude-service. Cross-cutting changes ship claude-service first.
Request options and execution details
- Request fields beyond the basics:
project(picks the cwd; independent ofapp, which only controls auth, queueing and callbacks),conversation(stateless history array) orsession_id(stateful resume), andoptions(model,system_prompt,max_timeoutdefault 300 s,extra_args). - Base command:
claude -p --output-format json --model <model>, plus--resume <session_id>when continuing. The JSON output is parsed forresultandsession_id, falling back to raw text if parsing fails. - Session resume over custom memory files. Passing
--resumekeeps the full conversation losslessly with no race conditions;session_idcomes back in every callback and status response. The CLI stores sessions as.jsonlunder~/.claude/projects/<slug>/; an hourly job deletes ones older than a week (session_ttl_seconds). - Retries: CLI runs 3 attempts (backoff 5 s, 15 s); callback delivery 4 attempts (2, 5,
10 s). A persistent
store.jsonsurvives restarts and re-queues pending requests. --dangerously-skip-permissionsis never global. It is only added when the calling app puts it inoptions.extra_args, so the app (TLDR's#dangertag, admin-only) keeps control of who gets it.- Admin GUI at
/admin(local only) with live updates over SSE (/admin/stream) and kill, retry, set-response and clear actions;claudectlCLI for status, history and registration. - Two config maps, two kinds of registration:
apps(request senders with API key and callback secret, one worker each) andprojects(working directories; the only thingGET /projectslists).register-project.sh/claudectl registertouchprojects;register-app.sh/claudectl register-appnow write both. All of them hot-reload viaPOST /admin/reload-projects; no restart needed. Mixing up the maps hid thejustinahamptonproject for a month (fixed 2026-09-06, post #1639). - Docs convention: any behavior change updates both
README.mdandapi.md.
Usage-limit hold (2026-09-06)
When the account hits its usage limit, the CLI prints the notice ("You've hit your session limit
· resets 6:10am (America/Chicago)") as the JSON result on stdout and exits 1 with an empty
stderr. Early on that surfaced as claude CLI exited with code 1: with no text. The service now:
- builds error text from stderr, then the stdout JSON result/error, then raw stdout;
- recognizes limit messages (including a ...limit reached|<epoch> form) and parses the reset
time;
- sets a global hold: every queue parks until reset + 30 s, held requests stay QUEUED with a
held_until field on /status, and the failed attempt does not count against retries;
- re-probes every 15 minutes (max 24 times) if the reset time cannot be parsed, and fails
immediately (non-retryable) if the reset is more than 5.5 hours out.
The TLDR expiry cron treats queued requests as alive for up to 6 hours.
Self-updating default model (2026-09-27, post #1688)
default_model in config.json is read fresh on every request (fallback opus) and reported as
default by GET /models. A daily systemd timer runs update-default-model.py, which judges a
newly released model and only switches (also updating ~/.claude/settings.json) on a
high-confidence verdict; it supports --set, --dry-run, --force-judge and --seed. Code
changes like this only take effect after a service restart, which kills every process in the
unit's cgroup, so restarts are scheduled deliberately.
Gotchas
- Usage limits are shared. A detached
claude -pbuilder uses the same account limit as everything else; parallel subagents can burn a 5-hour window in about 15 minutes, and the builder then silently stops. Long unattended builders need a limit-aware wrapper (detect the limit message, report "paused", sleep until the reset, resume withclaude -p --continue), and should run serially with frequent commits. See Running long jobs so they survive the AI session that started them. - Untrusted workspace drops the project's permissions.
claude -pin a directory nobody ever opened interactively prints "Ignoring N permissions.allow entries from .claude/settings.json: this workspace has not been trusted" and runs without them (seen in the Stocks project's activity log). Fix: run Claude Code interactively there once and accept the trust dialog, or setprojects["<dir>"].hasTrustDialogAccepted: truein~/.claude.json. - "No conversation found with session ID" means
--resumepointed at a session that does not exist in that working directory (sessions are stored per directory). The service retried and the second attempt succeeded, but without the earlier context: a Stocks follow-up of just "retry" got "I don't see a previous request". Follow-up prompts should restate enough context to survive a lost session. - Processes started from a headless run live in the service's cgroup; restarting the service kills them (and the run itself).
- Headless shells do not get nvm's Node,
~/bin, oruvon PATH; export them explicitly. - The service process accumulated 6+ GB of memory over several days of uptime (observed 2026-04); a periodic restart (when nothing is running) clears it.
- Big rewrites time out. Requests like "convert this racer to a 3D raycaster" or "make it a physics simulation" hit the 300 s CLI timeout on every attempt (3 attempts x 3 retries, about 15 minutes of wasted runs each). Split large conversions into steps or raise
max_timeoutfor that request. - A stale project tag eats misrouted posts. Ten game-related TLDR posts landed in the
forgeproject because of a tag, and 8 of them burned retries there. Retire project tags when a project is archived. - The default project has moved over time (tldr, then
forgeon 2026-04-07 via two hardcoded defaults inservice.py, nowhome); when changing it, grep for every hardcoded default, not just the config.
See also
- Sandboxing Claude Code for untrusted users (bubblewrap, --restricted, token pipe)
- Running long jobs so they survive the AI session that started them
- nginx in front of Apache (TLS proxy on :8008)
- TLDR platform architecture (tldrnerd.com)
- Working with Justin as an AI agent (ask first, confirm the target, precise verbs, artifacts over essays)
Linked from
- A self-building app pipeline (Forge builds Forge)
- Auto-discovering Claude models and tracking the best one as the default
- Backing up and restoring Claude Code configuration and memory
- Browser synthesizer stack (Tone.js) and LLM-generated music as JSON
- Building a proof-of-work cryptocurrency from scratch (BiteCoin design notes)
- Calling Claude directly from a browser page
- Lifecycle of an async AI request (status machine, expiry, retries, failure)
- Long autonomous AI builds (vacation runs and scheduled free time)
- Multi-agent development workflows with Claude Code
- nginx in front of Apache (TLS proxy on :8008)
- Permission modes in headless Claude Code (plan mode wedges, skip-permissions, tool scoping)
- Rotating API keys without locking yourself out
- Running long jobs so they survive the AI session that started them
- Sandboxing Claude Code for untrusted users (bubblewrap, --restricted, token pipe)
- TLDR platform architecture (tldrnerd.com)
- Working with Justin as an AI agent (ask first, confirm the target, precise verbs, artifacts over essays)