Skip to content

Run AI mode locally

AI mode lets an agent build or change a Mica document from a description. Its server half is the agent service in server/: a small Node service that runs the agent over Mica’s authoring tools, streams its progress, and only ever returns a document that import accepts. It runs on your machine, next to the designer’s dev server, with your own Anthropic API key.

This page is for readers with access to the Mica repository. Once the service runs, the designer shows AI mode; Build with AI mode explains how to use it. You can also call the service’s API directly, as described below.

  • Node.js 22.13 or newer and npm, as for running the designer.
  • npm install at the repository root.
  • An Anthropic API key from the Claude Console. Each turn is billed to it.

Create a file named .env at the repository root with one line:

Terminal window
ANTHROPIC_API_KEY=sk-ant-…

.env is git-ignored, so the key never lands in a commit. The service reads it with Node’s own --env-file-if-exists, which parses the file and never runs it as a shell script. A key already set in your environment works too. The key stays in the service: it never reaches the browser, a response, the log or the usage ledger.

Run the agent service and the designer side by side, in two terminals:

Terminal window
npm run dev:agent # the agent service, on http://127.0.0.1:8787
npm run dev # the designer, on http://localhost:4173

In development the designer’s dev server forwards every request under /api to the agent service, so both share one origin. Open the designer and it asks /api/ai/health once at start: when the service answers, the AI button and Describe it instead appear. The static build (npm run build) has no /api/ai at all, and neither does npm run dev alone: a designer that finds no service shows no AI mode. Start the service after the designer and reload the page to pick it up.

Without a key the service still starts, and reports itself unavailable. The designer then shows AI mode with the service’s reason and sending turned off, and asks again each time the pack picker or the Assistant panel opens, and after a request refused for the key or the budget.

Terminal window
curl http://localhost:4173/api/ai/health
{
"available": true,
"model": "claude-sonnet-5-5",
"effort": "high",
"approach": "hybrid",
"cacheTtl": "5m",
"limits": { "maxModelCalls": 20, "maxToolCalls": 60, "maxTokens": 32000, "maxNudges": 2, "maxInputTokens": 100000 },
"dailyCapUsd": 5,
"spentTodayUsd": 0.18,
"remainingUsd": 4.82,
"build": "54b53fe"
}

When available is false, reason says why — no-key or daily-cap — and message says it in words. build is the commit the service runs, or MICA_AI_BUILD when set.

The model, its effort, the tools and the system prompt are fixed by the service, never by a request: a turn can only ever build or edit a Mica document. To change them, set these variables in .env or the environment and restart the service.

Variable Default What it sets
ANTHROPIC_API_KEY — The API key; without it AI mode is unavailable
MICA_AI_MODEL claude-sonnet-5-5 The model: claude-opus-5-5 or claude-sonnet-5-5
MICA_AI_EFFORT high The model’s effort: low, medium, high, xhigh or max
MICA_AI_APPROACH hybrid The tool set: hybrid (a page per call for a first build, fine edits after), fine or whole
MICA_AI_CACHE_TTL 5m The prompt cache’s lifetime: 5m or 1h (see Caching)
MICA_AI_DAILY_CAP_USD 5 US dollars the service may spend per UTC day
MICA_AI_MAX_MODEL_CALLS 20 Model requests per turn
MICA_AI_MAX_TOOL_CALLS 60 Tool calls per turn
MICA_AI_MAX_TOKENS 32000 The most one response may generate, thinking included
MICA_AI_MAX_INPUT_TOKENS 100000 The most one request may carry, by the service’s estimate
MICA_AI_LEDGER .mica-agent/usage.jsonl The usage ledger file
MICA_AI_PORT 8787 The service’s port; the designer’s dev server reads it too
MICA_AI_HOST 127.0.0.1 The address the service listens on
MICA_AI_BASIC_AUTH — user:password every request must present; for a shared local network only (see below)
MICA_ALLOWED_EMAILS — Who may sign in: addresses or *@domain, separated by commas. Once set, even to nothing, AI mode needs a session; an empty list admits nobody
MICA_PUBLIC_URL http://localhost:4173 The origin people open Mica at: sign-in links point there, and only it may post a turn
MICA_AUTH_DB .mica-agent/auth.sqlite The SQLite file of accounts, sessions, links and codes
BETTER_AUTH_SECRET — Signs sessions and encrypts codes; at least 32 characters (openssl rand -base64 32). Without it, each start makes its own, so a restart signs everyone out
SMTP_HOST, SMTP_USER, SMTP_PASS, SMTP_FROM — The mail server sign-in emails go through, and their sender; set all four or none. Without them, links and codes print on the service’s output
SMTP_PORT 587 587 upgrades with STARTTLS; 465 is TLS from the start
NODE_ENV — production: the service must be fully set up for sign-in, and never prints a link or a code

The defaults are what Mica’s evaluation chose: the hybrid tools, as reliable as the other tool sets and the cheapest, on Sonnet 5.5 at high effort. It matched Opus 5.5 at medium effort on every quality check, field errors included, at about half the cost per turn, so the daily cap covers about twice as many turns.

npm run dev listens on every network interface, so anyone who can reach your designer can also reach the agent service through it, and spend your budget. When you run the service on a shared local network, set MICA_AI_BASIC_AUTH; your browser then asks for the user name and password. It is a local-only option: it is not how a hosted Mica is protected, and it is not meant as a login for anyone else. Sign-in is.

Set MICA_ALLOWED_EMAILS and the service asks for sign-in. Only the addresses on that list can sign in, and there are no passwords: owning the inbox is the only way in. Every request under /api/ai then needs a session whose address is on the list at that moment; without one it answers 401 and the designer shows no AI mode. A turn posted from a page on another origin than MICA_PUBLIC_URL is refused with 403.

Signing in takes one email, which carries a link and a six-digit code for the same sign-in:

  • The sign-in page, /sign-in/, asks for it. It answers every address alike, but only an address on the list is sent anything.
  • The link works once, for 15 minutes. It points at /sign-in/link/?token=…, a page that spends the token only when you press Continue to Mica, so a mail scanner that opens links cannot use it up.
  • The code works once, for the same 15 minutes, and only the newest email’s code works. Three wrong tries spend it; ask for a new email.
  • A session lasts 7 days and is renewed while it is used.

Removing an address from the list takes effect when the service restarts: its sessions end, and its links and codes stop working. The check runs on every request too, so nothing that address holds works against a service started with the new list.

The designer’s dev server serves the sign-in pages at /sign-in/ and /sign-in/link/, the same pages the docs site builds, so npm run dev and npm run dev:agent are all you need. Without SMTP settings, the service prints each link and code on its output instead of emailing them. Sign in to the designer describes the pages.

  1. Add your address to .env and restart npm run dev:agent:

    Terminal window
    MICA_ALLOWED_EMAILS=you@example.com
  2. Open http://localhost:4173/sign-in/, enter that address and press Email me a sign-in link. The service prints a line such as:

    [auth] SMTP is not set up; sign-in for you@example.com: http://localhost:4173/sign-in/link/?token=AbC… (code 123456)
  3. Type the code into the page and press Sign in, or open the link and press Continue to Mica. Either signs you in and opens the designer, at /designer/, which now shows AI mode and a sign-out button at the end of the top bar.

Open the designer at http://localhost:4173, the default MICA_PUBLIC_URL: the service refuses sign-in requests from any other origin, http://127.0.0.1:4173 included, and the page says so. If you open the designer at another address, set MICA_PUBLIC_URL to it.

The pages call five routes, and they are the only ones under /api/auth the service answers; every other one answers 404, password routes included:

Route What it does
POST /api/auth/sign-in/magic-link Asks for the email, { "email": "…" }. The answer is { "status": true } whatever the address, but only an address on the list is sent anything
POST /api/auth/sign-in/email-otp Signs in with the code, { "email": "…", "otp": "123456" }
GET /api/auth/magic-link/verify?token=… Signs in with the link’s token; the link page calls it when you press Continue to Mica
GET /api/auth/get-session The session, or null; the designer shows its sign-out button only when there is one
POST /api/auth/sign-out Ends the session

Sign-in requests are rate-limited per client, five link requests a minute for example. The service takes the client’s address from the X-Real-IP header only when the connection comes from a loopback or private-range address, where a proxy in front of it sits and must set that header; from any other address, the connection’s own address is the client, whatever the header says. The dev server’s proxy sets the header for each visitor.

When mail is down, an operator can print a sign-in link for an address on the list, from a shell where the service runs with the same settings:

Terminal window
npm run auth:link -- you@example.com

It refuses any address the list does not hold, and sends nothing. The link works once, for 15 minutes; open it and press Continue to Mica, as with an emailed one.

A service that listens beyond this machine (MICA_AI_HOST other than 127.0.0.1, ::1 or localhost) or runs with NODE_ENV=production refuses to start unless sign-in is fully set up: MICA_ALLOWED_EMAILS with at least one address, MICA_PUBLIC_URL, BETTER_AUTH_SECRET, and SMTP_HOST, SMTP_USER, SMTP_PASS and SMTP_FROM. It names every missing setting. Such a service never prints a link or a code.

Two routes serve a proxy in front of the service:

  • GET /api/gate answers 204 for a signed-in request whose address is on the list, and otherwise 302 to /sign-in/?next= the page asked for (the proxy’s X-Forwarded-Uri), for a proxy that puts pages behind sign-in. Without MICA_ALLOWED_EMAILS it always answers 204.
  • GET /api/healthz answers { "build": "…" }, without sign-in or basic auth, for a platform’s health check.

The service holds every UTC day to MICA_AI_DAILY_CAP_USD, $5 by default. It records what each response cost in a usage ledger (.mica-agent/usage.jsonl, git-ignored), one line per billed request with its day, turn, model and dollars, never a document or a prompt. The ledger survives restarts, so restarting the service does not reset the day.

The cap is never passed. Before every request the service works out the most that request could cost — every input token at the cache-write price, the full MICA_AI_MAX_TOKENS as output — and refuses it if that, added to what the day has already booked, could go over. Three things follow:

  • A new turn is refused, and health reports daily-cap, while some of the day’s budget is still left: about $0.40 with the default settings, a little more late in a long conversation.
  • A request you cancel returns no bill to read, yet may have been billed in part. The service books it from what its stream showed before the stop: the input the API reported (or, if it had not started, the request’s size at the cache-write price), plus as much output as could have been generated in the time it ran and a few seconds after — far more than any model writes. Stopping a turn a few seconds in books about $0.05 to $0.12.
  • A request whose connection dropped may have kept running unseen, so it is booked at its full worst case.

Each turn is also capped by MICA_AI_MAX_MODEL_CALLS, MICA_AI_MAX_TOOL_CALLS, MICA_AI_MAX_TOKENS and MICA_AI_MAX_INPUT_TOKENS. A turn that reaches one of them stops without changing anything.

In Mica’s evaluation, the default setup averaged about $0.07 a turn, measured on small apps with a cold cache — about half what Opus 5.5 at medium effort cost. That is roughly 70 turns a day on the default cap. Turns in one conversation reuse the cache and cost less. Larger documents cost more.

The service logs one JSON line per turn on its output: the outcome, model calls, tool calls, refused calls, token counts, dollars, the day’s total and the time taken. It never logs the request’s words, the document or the key.

Each request caches the tools and the system prompt — the knowledge pack and the playbook, about 20,000 tokens — plus the conversation so far. Reading from the cache costs a tenth of the input price on Sonnet 5.5; writing to it costs more than plain input.

MICA_AI_CACHE_TTL picks how long a cache entry lives:

  • 5m (the default): writes cost 1.25 × input. A turn’s requests run seconds apart, and each read keeps the entry alive, so a turn always reuses its cache. A pause of more than five minutes between turns means the next turn writes the prompt and the conversation again, roughly $0.05 to $0.12.
  • 1h: writes cost 2 × input, so every write costs 60% more, but the cache survives pauses of up to an hour between turns.

Choose 1h if you often pause between five minutes and an hour before the next request in a conversation; otherwise keep 5m.

POST /api/ai/turn runs one turn. It takes JSON:

{
"document": { "envelopeVersion": 1, "ui": { "…": "…" }, "meta": { "…": "…" } },
"prompt": "A packing checklist where I add items and tick them off.",
"transcript": [],
"selection": { "key": "hello-text" }
}
  • document is the current document in the exported form. For a first build it may be a document with no pages yet, or its pack’s untouched blank document (one empty page, as the designer starts it), which the agent builds over whole; its pack is the pack the agent builds in. Anything added to the blank document makes the turn an edit.
  • prompt is what the person asked for.
  • transcript is the conversation so far. The client holds it: it starts empty and, after every turn, the client appends the result’s transcript to it and sends it whole with the next turn.
  • selection, optional, names the element the person has selected.

The service refuses a request that does not have exactly this shape, with status 400 and every problem it found. A transcript may hold only what the service itself returns: text, thinking and calls to the session’s own tools with their results. Other statuses are 401 (no session with sign-in on, or basic auth), 403 (a turn from another origin with sign-in on), 413 (too large), 415 (not JSON), 429 (the daily cap) and 503 (no key). Every refusal is a JSON body, { code, error }, where error says why in words a person reads; a 400 adds problems. The designer shows error as the reason the request failed.

The answer streams as server-sent events:

Event Data
status { text }: a progress note, such as “Declaring the data your host provides” or “Building page Quiz”
draft { document }: the draft after each step that changed it, for a read-only preview
result The finished turn: document, hostContract (what the host must provide, in words), changes (elements added, changed, moved and removed, and host contract changes), text (what the agent wrote), transcript (the messages to append) and usage
error { code, message, issues?, usage }: what stopped the turn, such as the daily cap or a limit, with the draft’s remaining import issues

A turn ends with exactly one result or error. A result always carries a document that passed import’s check. After an error nothing has changed: keep the document and transcript you had. Closing the connection cancels the turn.