Build a Flight Planner
Learn how to build a VFR flight planner with subagents, planning, memory and a web UI.
This recipe starts from the navlog template. It picks up where Getting Started leaves off. If you haven't built the hello agent yet, start there.
What will we build?Copy link to section: What will we build?
The template is a VFR flight planner for a Cessna 172N at /navlog. It sends a performance subagent out, computes the navlog in code from the 1978 172N POH tables together with its weather facts from live aviationweather.gov data (no key), narrates those facts, and files an ICAO flight plan only when the pilot asks and a person approves. A browser client, the B4.run Workbench, sits in front of it.
The unit tests and evals need no API key. Live runs need a real model and an OpenAI API key.
Create the appCopy link to section: Create the app
First, scaffold the app and install its dependencies:
npm create b4-app@latest my-navlog -- --template navlog
cd my-navlog
npm installThe --template navlog flag picks the flight-planner template instead of the default. You need Node.js 24 or later and npm 11.
Look at the agentsCopy link to section: Look at the agents
The app is an npm workspace with two packages. server/ is the B4.run app, and web/ is the Workbench. The root npm install installs both.
The planning route lives in server/src/app/navlog/. Let's look at the coordinator, its subagent and the app config:
import { agent } from "@b4run/sdk"
export default agent({
model: "gpt-5-mini",
// A plan fans out: baseline + recall → plan → the performance subagent → compute →
// brief. That legitimately exceeds LangGraph's default 25 super-steps.
recursionLimit: 100,
description:
"A VFR flight planner for a Cessna 172N: looks up POH performance, computes the navlog and its weather facts in code, narrates them, and files a flight plan on request.",
tools: { deny: ["runBash"], approve: [{ tool: "fileFlightPlan", allowAlways: false }] },
systemPrompt: `You are a VFR flight-planning assistant for a Cessna 172N. Given a request:
1. Start by calling \`readDoc({ path: "aircraft/c172n.md" })\` and \`recall({ query: "pilot aircraft overrides and preferences" })\` together. The baseline file is the demo aircraft. A recalled fact overrides it, and what the pilot says in the request overrides both. Do not stop to ask for anything the three leave open: use the baseline and list each baseline value you relied on in Assumptions.
2. Parse the request into departure, destination, optional waypoints, cruise altitude, departure time (UTC) and people on board. Ask only when the departure, the destination or the cruise altitude cannot be determined; ask for the departure time only when none is given. Never ask whether a clock time means the next occurrence: it does. If the pilot did not say how many people are on board, assume 1 and say so in the reply. Departure time: an ISO 8601 UTC instant such as 2026-10-06T14:00:00Z; a UTC clock time such as 1400Z, which means the next occurrence; or, when the pilot names the day, "today 1400Z" or "tomorrow 1400Z". Call \`resolveDeparture({ departure })\` with it exactly as given, keeping any day the pilot named, and use the departureUtc it returns everywhere after: for computeNavlog and in Assumptions. Never work out a date or hours ahead yourself.
3. Record the legs as todos.
4. Call \`lookupAirport\` for each airport, and \`lookupNavaid\` for each navaid, that you have not already looked up. A navaid is a waypoint written with a navaid type in parentheses, such as \`SNS (VORTAC)\`, or one \`lookupAirport\` has no record for. A navaid enters computeNavlog with kind navaid and its own magnetic variation.
5. Call \`findRouteStations\` with the waypoint identifiers in route order, each with its kind (airport or navaid). Leave corridorNm and max at their defaults unless the pilot asked for a wider or narrower search.
6. Dispatch \`task({ subagent: "performance", input: "<airports, altitude, cruise RPM>" })\`.
7. Call \`computeNavlog\` with the waypoints, the altitude, departureUtc as the departure time, the aircraft from step 1 (tail number, cruise RPM, usable fuel), personsOnBoard and the stations from step 5 (id and alongNm). Never pass winds: the tool takes the forecast for the time each leg is flown. Its \`forecast\` block is authoritative: the winds, each airport's category now and when you are there, the advisories and their relevance, whether the forecasts reach the flight (coverage) and the verdict floor. Narrate it; never recompute it. Mention forecast.notes where they matter to the flight.
8. Save the navlog with \`writeFile({ path: "reports/<departure>-<destination>.md", content: "<markdown table of the legs and totals>" })\`.
9. If a chart would help, \`renderChart({ title, series })\` with fuel remaining by checkpoint.
10. Reply with the planning answer described under Answer format, and nothing else.
11. When the pilot states a durable preference or an aircraft fact, call \`remember({ data, content })\`.
12. File a flight plan only when the pilot asks; see Filing.
Answer format. Every reply is a list of brief components (the response schema describes each). A planning answer is, in this order: BottomLine, RouteSummary, WatchFor, KeyNumbers, Assumptions, Citations, then one closing Prose. Any other reply (a question, a filing confirmation, a short answer) is a single Prose and nothing else. Keep a planning answer short and scannable, under about 180 words of text in all.
- BottomLine: level at least forecast.verdictFloor.level. Raise it only for a reason the facts do not already state (terrain, a lower altitude that avoids icing is not legal), and say that reason; never lower it. The sentence states the floor's most important reason, or your raise.
- RouteSummary: from, via (empty when direct), to, the cruise altitude in feet and the departure time in UTC. Never distance or ETE here.
- WatchFor: up to 3 items from forecast.advisories with relevance during-flight and from forecast.verdictFloor.reasons, each with its altitude in what, its valid window in when and a severity. Skip the coverage reason (forecast preliminary): the Workbench shows coverage. An empty list when nothing applies.
- KeyNumbers: one item each for distance; ETE, which is takeoff to landing, the navlog's total time; fuel burned, which already includes 1.1 gal for start, taxi and takeoff (say so once, and never tell the pilot to add it again); fuel at landing; and reserve. Durations (ETE, reserve) are h:mm, such as 0:33 or 4:24, with unit null; every other value is a plain number with its unit in unit. Never use tool field names such as reserveOk.
- Assumptions: the departure instant in UTC with its date; people on board ("1 assumed — tell me if different" when the pilot did not say); any baseline value you used. Never state whether the forecast is preliminary: the Workbench shows forecast.coverage.
- Citations: one item per source, with ids c1, c2, … in the order first cited. Every POH figure, weather fact and hazard you state puts the id of its source in its cite, and every item is cited. Sources are POH documents (source poh/<file>.md, locator Figure N) and weather products named in forecast (source METAR <ICAO> with locator <time>Z; TAF <ICAO>, AIRMET <hazard> or SIGMET <hazard> with an empty locator), never a reports/ or aircraft/ file. Distance and ETE come from the computed navlog and cite nothing. Fuel burned cites the POH cruise figure.
- Prose: one closing line offering to file the plan, try another altitude, or re-brief closer to departure.
Assumptions and Prose never name a file or path: say "the aircraft baseline" rather than its file, and never mention where the navlog was saved (the navlog sheet shows it).
The Workbench shows the navlog table and the weather, so never repeat the leg table.
Filing. When the pilot asks to file, call \`fileFlightPlan({ flightPlan })\` once with the flightPlan from the latest computeNavlog. The runtime asks the pilot to approve that call; never ask for approval yourself. After it returns, reply with a single Prose of 2 to 4 lines:
- "Recorded the flight plan for <tail number> <departure>→<destination>, departing <HHMM>Z <date>. This demo records it in the workspace; it does not transmit to Flight Service."
- One line reading the key items correctly: item 15 is cruise speed, level and route (N0109VFR DCT is 109 kt true airspeed, VFR, direct), and item 16 is the destination and the total estimated elapsed time (KDLH0125 is KDLH, 1 h 25 min).
Never ask for approval again after the tool ran, and never say the plan was or will be transmitted. If the pilot denied the call, say the plan was not recorded.
Never write tool-call syntax such as recall({...}), a to-do list or its statuses, a list of what you ran, workspace file paths outside Citations, or a list of sources in a reply's text; sources go only in Citations.`,
})The coordinator plans the flight, looks up each airport and navaid, finds the reporting stations along the route with findRouteStations, sends the performance subagent out, and calls computeNavlog for every number on the navlog. computeNavlog also times each leg, takes the winds-aloft forecast for the time that leg is flown, and returns a forecast block: each airport's category now and when you are there, the advisories and their relevance, whether the forecasts reach the flight, and the verdict floor. The coordinator narrates those facts and never recomputes them. The tools are shared in server/src/tools/, and the subagent's tools scope keeps it to its own. fileFlightPlan asks a person before each call. The config keeps tool output inline up to 12,000 characters and makes new memories wait for review. Threads persist to SQLite by default, so they survive a restart.
A few more files shape the agent:
server/src/app/navlog/
plan.md # seeds each thread's todo list
memory.md # route-specific prompt guidance
memory.ts # typed cross-session memory
subagents/performance/ # POH tables for the actual fields
skills/brief-weather/ # loaded on demand: narrating the computed forecast
skills/poh-lookup/ # loaded on demand: reading and citing the POH
evals/navlog-quality.eval.ts # the dataset and scorers
evals/navlog-quality.fixtures.ts # its scripted model runs
server/src/tools/
computeNavlog.ts # the navlog and its forecast, computed in code
fileFlightPlan.ts # records an ICAO flight plan, after approval
getMetar.ts getTaf.ts getWindsAloft.ts getAdvisories.ts lookupAirport.ts
lookupNavaid.ts # a VOR, VORTAC or NDB from the bundled snapshot
findRouteStations.ts # METAR stations within 25 nm of the course
resolveDeparture.ts # turns "tomorrow 1500Z" into one UTC instant
readDoc.ts # reads the aircraft baseline, a POH table or a regulation excerpt
renderChart.ts # draws a bar chart the user sees
server/src/lib/ # the math, POH tables and parsers the tools call
read-only-paths.ts # keeps the reference corpus read-only
server/data/navaids.json # navaids with magnetic variation, for lookupNavaid
server/scripts/build-waypoints.mjs # rebuilds the waypoint snapshot
server/workspace/
AGENTS.md # prompt guidance injected every turn
aircraft/ # the demo aircraft baseline, N734ST
poh/ regs/ # the POH tables and regulation excerptsplan.mdturns on planning. Its checklist seeds each thread's todos.workspace/AGENTS.mdand the route'smemory.mdadd persistent prompt guidance.workspace/aircraft/c172n.mdis the demo aircraft the plan starts from. A pilot's own facts, held in memory, override it, and what the pilot says in the request overrides both.b4.config.tswraps the workspace filesystem withreadOnlyPaths, soAGENTS.md,aircraft/,poh/andregs/can't be rewritten by the agent, andagentsMd: { writable: false }injectsAGENTS.mdas read-only guidance instead of telling the model to update it. Every visitor's turns share one workspace directory, and B4.run's path gate covers only paths outside it.memory.tsdefines typed memory records that the agent reads withrecalland writes withremember.- The agent loads skills under
skills/by name when it needs them.
The waypoint snapshotCopy link to section: The waypoint snapshot
lookupNavaid reads server/data/navaids.json, and the Workbench's route bar searches web/data/waypoints.json (US airports and VOR, VOR-DME, VORTAC, NDB and NDB-DME navaids). aviationweather.gov's navaid endpoint returns nothing, so both files are built ahead of time from OurAirports, which is public domain, and committed with the date they were built. They are community data for practice, not for navigation.
To refresh them, download airports.csv and navaids.csv (the URLs are in the script's header comment), then run from server/:
node scripts/build-waypoints.mjs <airports.csv> <navaids.csv>The script writes both files and stamps today's date (UTC), or the date you pass with --date YYYY-MM-DD.
Verify and testCopy link to section: Verify and test
Run these from the workspace root. Each script delegates to the package that owns it:
npm run typegen
npm run check
npm run typechecktypegen writes server/.b4/b4.generated.d.ts. check validates routes, tools and configuration without writing files:
B4.run app is valid: 2 routes discovered.
- /navlog (agent)
- /navlog/subagents/performance (agent)Next, run both packages' tests:
npm testThe server tests are unit tests of the navlog math, the forecast rules, the POH tables, the weather parsers and the tools, with fetch stubbed. The web tests cover the Workbench. Neither needs an API key.
Then run the quality eval:
npm run evalThe eval plans four flights. Its scorers require the performance subagent, a well-formed navlog whose totals add up with a legal reserve, a bottom line no better than the computed verdict floor, a POH citation, no filing unless asked, and a passing quality grade from a model judge. Scripted fixtures cover the agent and the judge, so the eval runs without an API key; computeNavlog still reaches aviationweather.gov for its forecast.
Run it liveCopy link to section: Run it live
These fixture-backed runs prove the app works without a key. To plan a new flight, we need a real model.
Copy the server's environment example, add your API key, run the preflight and start the dev server:
cp server/.env.example server/.env
# Add your OPENAI_API_KEY to server/.env
npm run verify
npm run dev:serververify checks the app, its types, its dependencies, Node and the provider environment. The dev server listens on http://127.0.0.1:3002 and serves Agent Protocol and AG-UI.
In a second terminal, ask for a flight:
cd server
echo '{"messages":[{"role":"user","content":"Plan a VFR flight from KSTP to KRST at 4500 feet, departing 1400Z, in N738ZU (172N, 2400 RPM, 50 gal usable), and save the navlog."}]}' | npx b4 run /navlog --url http://127.0.0.1:3002The navlog lands in server/workspace/reports/. Thread state is saved to server/.b4/checkpoints.sqlite, so threads survive dev-server restarts.
See it in a UICopy link to section: See it in a UI
The Workbench is a chat UI over the same agent. Leave the server running and start it in another terminal:
npm run dev:webOpen http://localhost:3010 and choose Plan a flight. You'll see the plan card and the performance subagent card update as the agent works, tool cards, the flight-plan approval and a panel for reviewing memory. You can also type a route such as KPAO SNS KSBA in the bar across the top of the map and choose Plan, which sends the route to the agent as a chat message. The sheet's Weather tab shows computeNavlog's forecast by origin, en route and destination. The Workbench talks to B4.run over AG-UI and holds no model credentials. Those stay in server/.env.
To build your own client, follow Flight Planner Web UI.
The scaffold also installs the Inspector. Open it in a third terminal to review the records the agent saves with remember:
npx b4 inspect --cwd serverWhen you're ready to ship, compare Deployment Options and follow Node and Docker for the default self-hosted path.
Use the agent in the Mac appCopy link to section: Use the agent in the Mac app
The app guide explains how to connect this agent to Agent Workspace. You can also inspect a recorded aircraft lookup before running it. That lesson follows the request, the readDoc result, and a second turn in the same conversation.