Étape 13 sur 13 - Environ 35 min
Lab 12 - Run it for real
Time: about 35 minutes. You will: run Steward as an always-on service that survives restarts, cannot run up a surprise bill, shuts down cleanly, and can be backed up.
Why
"Always on" changes the failure modes. The machine restarts at 3 AM. You start a second copy by mistake. A loop keeps calling the model while you sleep. The disk fails. Each of these is a small piece of code - but only if you plan for it.
Concepts
One process per data folder
The per-session queue (lab 08) orders turns inside one process. Two processes on the same data
folder would each have their own queue and interleave writes. src/runtime/lock.ts creates
<dataDir>/steward.pid with the exclusive wx flag; a second process is refused with the pid of
the first. A lock left by a crashed process (its pid no longer exists) is taken over.
A daily spending cap
src/security/budget.ts records the cost of every turn - main turns, scheduled jobs, and helpers,
also a turn that fails or is cancelled after some model calls - in <dataDir>/spend.jsonl. The
cost comes from the pricing table in your config (USD per million tokens; check it against the
pricing page when prices change).
Each request is priced at the model that served it (a fallback model may answer, lab 01) and at
the long-prompt rates when the model has them (lab 03). An interrupted turn keeps its usage in
its turn_interrupted event, so /usage shows the same spend as the ledger. Before a turn starts, the assistant
checks today's total (in your time zone) against limits.dailyUsd (5 in the example config; 0
turns it off). Over the limit:
- a new message is kept in the log, but the model is not called, and Steward says why;
- an approval answered after the limit closes the waiting tool calls with error results, so the history stays valid;
- the cap resets at midnight.
The cap is checked between turns, so one long turn can go past it. For a second safety net that does not depend on your code, give the service its own API key in its own workspace with a monthly spend limit.
Graceful shutdown
On SIGTERM (sent by launchd, systemd, and Docker on stop):
- the scheduler stops,
- the web server stops taking requests,
- turns in flight are cancelled through their abort signals - each is recorded as
turn_interruptedin its session log, with open tool calls closed (lab 02), - turns still queued never start,
- the lock is released.
Then the next start has nothing to repair.
Health
GET /health (no token needed, localhost only) returns status, uptime, queue depth, open
sessions, turns in flight, the scheduler's last tick and next job, and today's spend against the
limit - enough for a monitor or a quick curl.
Secrets
- The API key never goes in
config/or in service files: useant auth login(the TypeScript SDK reads the profile), or an environment file readable only by you. - Programs started by
run_programget a minimal environment without your key (lab 04). - Memory refuses anything that looks like a secret (lab 06).
Backups
steward backup <folder> copies the data folder to <folder>/steward-backup-<time>. It is safe
while Steward runs: logs are append-only (a copy can only have a torn last line, which lab 02's
recovery handles) and index files are replaced atomically.
Or let Anthropic run it
Everything in this lab - hosting the loop, the sandbox for tools, sessions, schedules - is what Claude Managed Agents provides as a service: Anthropic runs the agent loop and a per-session container, with scheduled deployments for cron-like work. Building it yourself, as here, is how you learn what such a platform does for you, and gives full control when you need it.
Build
src/runtime/lock.ts-ProcessLock.src/security/budget.ts-SpendLedger;src/core/assistant.ts- the budget check before every turn andledger.record()after.src/gateway/gateway.ts-close(): abort in-flight turns, refuse queued ones, wait.src/cli.ts-run(): SIGTERM handling,/healthfields;backup.src/runtime/backup.ts- the copy, skipping the lock file and temp files.deploy/- launchd (macOS), systemd (Linux), and Docker files.
Run
Pick one:
macOS (launchd). Edit deploy/launchd/com.example.steward.plist (your home folder, the node
path, a web token), run ant auth login once, then:
cp deploy/launchd/com.example.steward.plist ~/Library/LaunchAgents/
launchctl load ~/Library/LaunchAgents/com.example.steward.plist
tail -f ~/Library/Logs/steward.logLinux (systemd user service). Follow the comments at the top of
deploy/systemd/steward.service (the key goes in ~/.config/steward/env, mode 600; check the
lab folder in WorkingDirectory and that systemd finds Node 24).
Docker. Put ANTHROPIC_API_KEY and STEWARD_WEB_TOKEN in deploy/docker/.env, then:
docker compose -f deploy/docker/compose.yaml up -d --build
curl -s http://127.0.0.1:8787/healthThe container listens on all interfaces inside, and compose publishes the port on your machine's
localhost only. The image includes your config/ folder, so a local config/steward.json is used
in the container too; data lives in the steward-data volume and the workspace is
~/steward-workspace on your machine.
Then, wherever it runs:
curl -s http://127.0.0.1:8787/health
pnpm steward backup ~/BackupsWith Docker, the data is in the volume, not in ~/.steward; copy it out with
docker compose -f deploy/docker/compose.yaml cp steward:/data ~/Backups/steward-data.
Break it
- Second copy. With the launchd or systemd service running, run
pnpm steward chat. It refuses: "another Steward process (pid ...) is using ...". (With Docker the container has its own data volume, so a chat on the host uses a different data folder and starts normally. Rundocker compose -f deploy/docker/compose.yaml exec steward node src/cli.ts chatto see the refusal inside the container.) - Budget. Set
"limits": { "dailyUsd": 0.01 }in your local config, restart, and chat for a few turns. Once the cap is reached, Steward answers that the daily limit has been reached, and/usageshows today's spend. Put the limit back. - Stop mid-answer. Ask something long in the web chat and stop the service
(
launchctl unload ...,systemctl --user stop steward, ordocker compose -f deploy/docker/compose.yaml stop). Start it again and runpnpm steward show(with Docker:docker compose -f deploy/docker/compose.yaml exec steward node src/cli.ts show): the turn ends withturn_interrupted(reason: "the gateway shut down"), written during the shutdown itself. Compare with lab 02'skill -9, where the repair happened at the next start.
Check
pnpm lab 12The checkpoint proves: spend adds up per day in your time zone, survives a restart and a torn
line, and resets at midnight; over the cap no model is called, the message is kept, and the
terminal says why; every turn's cost is recorded, also when the turn fails; a late approval closes waiting calls validly; one process per data folder
with stale-lock takeover; shutdown cancels the turn in flight (recorded as interrupted) and never
starts queued ones; backups skip the lock; the service files run serve without keys.
Exercises
- Send a notice through
gateway.deliver()when spend passes 80% of the daily limit. - Add
steward restore <backup>that refuses to run while the lock is held. - Add structured JSON logs (one line per turn: session, stop, tokens, cost, duration) and graph a week of them.
Claude API docs
- Rate limits - what an always-on service runs into, and spend limits
- Errors - which errors the SDK retries on its own, and which reach Steward
- Pricing - the numbers behind
pricingandlimits.dailyUsd - Workspaces - a separate key and spend limit for the service
- TypeScript SDK - how the client finds credentials and retries
Exam connection
CCA-F - Context Management & Reliability: operating agents reliably - single-writer state, cost controls, graceful shutdown, and recovery.
Related, for running AI apps in production on their platforms: AWS Certified Generative AI Developer - Professional (AIP-C01) - Operational Efficiency and Optimization, and Microsoft Azure AI Apps and Agents Developer Associate (AI-103) - Plan and manage an Azure AI solution.
Practice for the exam
You have now built every part of a persistent assistant: the loop, durable state, context and caching, guarded tools, approvals, memory, long-context handling, channels, scheduling, delegation, evals, and operations. The CCA-F exam asks you to choose between these designs under time pressure. Take a full CCA-F practice exam on CertLabPro, or keep practicing on your phone with the CertLabPro app for iOS and Android.
Previous: Lab 11 - Back to the lab overview