Let the billing assistant look up the customer's invoices

Node · Node · intermediate · modification

Lets the billing assistant answer questions about the customer's invoices from live data. Adds a `list_invoices` function tool (status filter, up to 20 invoices) whose arguments are parsed and checked against a strict zod schema, so a malformed or out-of-range call goes back to the model as a tool error instead of reaching billing. `answer` now runs the standard tool loop (the assistant turn with its `tool_calls`, then one `tool` message per call id), capped at four model calls with a 502 after that, and the system prompt tells the model which account is signed in and to stay on it. The route passes the session's account id into `answer`.

TypeScript Express 4 customer portal of Ledgerly, a billing SaaS; `openai` 7.43.0, `zod` 4.6.7. `requireCustomer` (existing, unchanged) answers 401 without a valid portal session and otherwise sets `req.customer = { accountId, email }` (typed by the existing augmentation in `src/auth.ts`). `src/billing.ts` (unchanged) wraps the billing provider with the platform's secret key, which can read every account: `billing.listInvoices(accountId, { status, limit })` returns up to `limit` invoices of that account, newest first, as `{ number, status, amountDue, currency, dueDate }`, and `[]` for an unknown account id; `GET /api/invoices` calls it with `req.customer.accountId`. Account ids (`acct_` plus up to 32 letters and digits) are not secret: they are printed on every invoice PDF and in shared payment links. Per-customer rate limiting of the assistant is done by the existing portal middleware. `HELP_FACTS`, `src/openai.ts` and `src/logger.ts` are unchanged.

Requirements

Files touched

Review this PR

Node practice