diff --git a/CLAUDE.md b/CLAUDE.md
index 6db238e..acc5fe1 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -43,7 +43,9 @@ These are tested by name (`rule_R…` in `test/`). A change that weakens one is
jurisdictions.
8. "Model text" only when the page's own banner says the code is adopted without amendments.
9. Page text is untrusted. Claude gets refs, never addresses, and no section text by default. The
- screenshot fallback is off by default and lets Claude point at numbered marks, nothing more.
+ screenshot fallback lets Claude point at numbered marks, nothing more. It is on by default (the
+ owner's decision, 1 December 2026, `docs/adr/0011-chosen-for-the-user.md`), is a setting the user
+ can turn off, and the screens say that it sends screenshots of code text.
10. Every page load is paced, below everything else. The hard limits are in `src/shared/validation.ts`.
11. App code loads only codes, chapters and code lists (`permittedAutomated`), and, to sign in with a
saved password, the site's own home or sign-in page (`permittedSignIn`). Tool arguments and
@@ -103,8 +105,18 @@ original plan and any signed-in notes stay out of the repository (see `.gitignor
`folderName` (`src/shared/file-names.ts`), which never give a device name.
- **Validate at the boundary.** Everything arriving from the screens or from Claude's tool arguments
is parsed with zod before use.
-- **Models are discovered from the user's key.** Do not hard-code a model id in `src`. First
- preferences for a fresh install are in `assets/models.default.json`.
+- **Models are discovered from the user's key.** Do not hard-code a model id in `src`. The models
+ the app chooses, and how hard Claude thinks for each kind of work, are in
+ `assets/models.default.json`. An empty `Settings.model` means automatic: read the model through
+ `resolveModel` (`Workspace.modelFor`), never straight from settings, and never write a model ID
+ into the user's settings. Send an effort only through `effortFor`. Every model the app may choose
+ by itself needs a price in `assets/pricing.json`, or the spending limit cannot see it.
+- **The user chooses nothing in Settings.** Every setting has a value that works, and all but the
+ API key and the spending limit render only under **Show advanced settings** (`src/ui/advanced.ts`).
+ A new setting goes in the advanced part with a default that needs no thought, and is never removed
+ to hide it. Stored preferences hold every value, so a changed default needs a migration to reach an
+ existing install (`0010_chosen_for_the_user.sql` is the pattern). Do not speed up the pacing
+ defaults to make the app "more powerful": rule 10.
- **An Electron test script that throws while loading would hang on a dialog.** Always run them
through `test/run-electron.cjs`.
- **The synthetic site is the only site the tests touch.** Nothing in CI reaches the network.
@@ -118,10 +130,17 @@ original plan and any signed-in notes stay out of the repository (see `.gitignor
every screen inside one (`src/ui/App.tsx`).
- **A Claude call made for a queued pull names the pull** (`RunSpec.jobId`, or `jobId` on a run the
caller records itself). Without it, its cost is missing from the pull, the plan and the queue's
- Claude cost panel. Keep every such call within fixed token budgets that `pullCeiling` in
- `src/shared/claude-cost.ts` prices (`QUEUE_SEARCH_TOKENS` via `Limits.tokens`, `VISUAL_LIMITS`), with
- the input budget checked against each request before it is sent, or the queue's "at most" figure
- stops being true. Requests and plans have no token limit; only the queue's own calls do.
+ Claude cost panel.
+- **No call to Claude has a token budget, and every call checks the month's spending limit first.**
+ The owner removed the token budgets on 1 December 2026; do not add one back. What stops a run that
+ goes in circles is its steps and its working time. What bounds the money is
+ `Settings.spendLimitUsd`, a kill switch: a new place that calls Claude reads the spend state
+ (`Workspace.spend`, passed as `spend` to the runtime and to `lookForSection`) before each request
+ and sends nothing while it is reached, or the limit stops being true. That includes a request sent
+ again after a failure: save what the failed attempt cost, then check. Never reset or skip it for a
+ kind of work. The month's spending is `claude_months`, which `runs.save` adds to as a run's usage
+ grows; record a Claude call's usage through `runs.save` and it is counted. That table is not
+ content: `clearContent` must keep it.
- **Saved site passwords:** page programs in `src/sites/upcodes/sign-in.ts` take field names only;
`test/security.test.ts` checks it. Focus a field with `evaluate(…, { afterLoad: true })`: `typeInto`
refuses a page that is still loading. Sign-in uses `ctx.driver.openSignIn` and `ctx.driver.pace` so
diff --git a/README.md b/README.md
index 0eb6e57..1df9034 100644
--- a/README.md
+++ b/README.md
@@ -136,8 +136,11 @@ It runs on Windows, macOS and Linux. Windows is the main target.
the account and tells you why. A human check or a slow-down stops every account until you resume. A
sign-in prompt is answered once with your saved password, if you saved one; if that does not sign
in, the account stops.
-- Send section text or screenshots to Claude, unless you turn that on. See
- [What Claude sees](#what-claude-sees-and-what-it-costs).
+- Send a whole section to Claude as text. Claude gets section numbers and headings. When the reader
+ cannot place a section on a page, the app sends Claude screenshots of that page, which show code
+ text, unless you turn that off. See [What Claude sees](#what-claude-sees-and-what-it-costs).
+- Call Claude once this month's estimated cost has reached your spending limit. See
+ [The monthly spending limit](#the-monthly-spending-limit).
- Upload, share or sync your library. It is a folder on your computer.
- Check for updates, download or install anything by itself. **Check for updates** asks GitHub only
when you choose it, and the new version is yours to download and run.
@@ -213,10 +216,15 @@ The **New request** screen shows a short checklist. Do the two steps once.
clear the account's browser data. Most code pages hold no proof either way, because UpCodes keeps
its sign-out link in a closed menu, so **Done** or **Check now** on a code page leaves the account
as it is.
-2. **Anthropic API key (optional).** In **Settings → Claude**, paste a key and choose **Save key**. The
- app lists the Claude models your key can use and picks one for requests and one for project plans.
- You can change both. Without a key you can still pull by section number or page address, and use
- the library.
+2. **Anthropic API key (optional).** In **Settings**, paste a key and choose **Save key**. That is
+ all there is to set up: the app picks the Claude model (the newest Claude Opus your key offers,
+ for requests and for project plans) and every other setting. You can see and change them under
+ **Show advanced settings**, and you never have to. Without a key you can still pull by section
+ number or page address, and use the library.
+
+There is one thing on the Settings page you may want to change: the **monthly spending limit for
+Claude**, $200 to begin with. When the month's estimated cost reaches it, nothing calls Claude until
+you raise it or the month ends. See [The monthly spending limit](#the-monthly-spending-limit).
The key is encrypted by Windows and kept on this computer. If your system offers no encryption, the
key is held only until you close the app.
@@ -390,9 +398,9 @@ export, a capture or another action is still running.
| Subscription needed | The account cannot view that page | Check the subscription. The app will not buy anything |
| Human check | The site asked for verification | Open the account window, complete it yourself, then **Resume**. Every account waits until you do |
| Asked to slow down | The site sent a rate-limit response | Wait a while, then **Resume**. Every account waits until you do |
-| Section not found | The section is not printed on the pages the app opened | Check the number, or start a new request with the page address. With an API key, Claude is asked once to find the page before this is shown, and, if you allow it, to look at a screenshot of it |
-| Page not recognised | The page did not look the way the reader expects, or it takes text away at the top as it is scrolled, so it never holds the whole chapter at once | With **Let Claude look at the page** on, Claude tries to find the section on a screenshot first. Otherwise **Capture by hand**, or export diagnostics (see below). The stop says when the screenshot fallback could have helped. A page that takes text away is never read in pieces: pull a smaller part, or capture it by hand |
-| Check failed | The page was read, but the PDF or Word document made from it did not read back the same, so nothing was saved. The pull says which document, which page of it, which block and which character differ: for example "the page has a letter where the PDF has a hyphen (U+002D)". It never repeats the text | **Retry** reads the same page and ends the same way, so it helps only after an update. Use **Settings → Advanced → Export diagnostics** and send it with the message; the log holds the same details. **Capture by hand** of a smaller part can get you the rest of the section meanwhile |
+| Section not found | The section is not printed on the pages the app opened | Check the number, or start a new request with the page address. With an API key, Claude is asked once to find the page before this is shown, and then, unless you turned that off, to look at a screenshot of it. A stop that says **Claude is stopped** means this month's spending limit was reached before Claude could be asked: raise the limit in **Settings**, then **Retry** |
+| Page not recognised | The page did not look the way the reader expects, or it takes text away at the top as it is scrolled, so it never holds the whole chapter at once | Claude tries to find the section on a screenshot first, unless you turned **Let Claude look at the page** off or this month's spending limit is reached. Otherwise **Capture by hand**, or export diagnostics (see below). The stop says when the screenshot fallback could have helped. A page that takes text away is never read in pieces: pull a smaller part, or capture it by hand |
+| Check failed | The page was read, but the PDF or Word document made from it did not read back the same, so nothing was saved. The pull says which document, which page of it, which block and which character differ: for example "the page has a letter where the PDF has a hyphen (U+002D)". It never repeats the text | **Retry** reads the same page and ends the same way, so it helps only after an update. Use **Settings → Show advanced settings → Export diagnostics** and send it with the message; the log holds the same details. **Capture by hand** of a smaller part can get you the rest of the section meanwhile |
| Network problem | No connection, or a server fault, after three tries | Check the connection, then **Retry** |
| Failed: "The page did not answer CodePull" | The page loaded, but did not answer the app's reading code within its time limit: its own scripts were busy, or it never finished loading. This is not the connection, so it is not tried again by itself | **Retry** loads the page afresh. If it repeats, open the account window and look at the page |
@@ -638,10 +646,13 @@ the app does not keep one, and says so.
### When the reader cannot place a section: Claude looks at the page
-Turn on **Let Claude look at the page when CodePull cannot find a section on it** in **Settings →
-Claude**. It is off until you do, because screenshots show code text and go to the Anthropic API.
+**Let Claude look at the page when CodePull cannot find a section on it** is on unless you turn it
+off, under **Settings → Show advanced settings → Claude**. The screenshots show code text and go to
+the Anthropic API, so turn it off if you do not want that; a section the reader cannot place then
+stops and waits for you. It needs an API key, and stops with everything else at
+[the monthly spending limit](#the-monthly-spending-limit).
-When a pull cannot be read, or its section cannot be placed, the app then gives Claude screenshots of
+When a pull cannot be read, or its section cannot be placed, the app gives Claude screenshots of
the page with numbered marks. Claude can only point: at a link to open, at the block where the section
starts and the block where it ends, or ask to scroll. The app checks each choice:
@@ -649,12 +660,13 @@ starts and the block where it ends, or ask to scroll. The app checks each choice
load is paced. Purchase and sign-up links are never offered.
- The text between the two points is read from the page by the same reader as a capture by hand,
with the same checks. A start that is not the requested section is refused, and Claude is told why.
-- At most 15 steps, 4 page loads and 100,000 input tokens for one pull, the tokens checked before
- each request. One screenshot goes with each request; none is saved.
-- Each step asks Claude for exactly one pointing choice. Claude thinks before it points, so a step may
- use up to 16,000 output tokens, or the model's own limit if that is lower. On models that offer it,
- each step uses low effort to stay quick. The look stops with a reason if Claude answers without
- pointing, or reaches that limit in one step.
+- At most 40 steps and 4 page loads for one pull. One screenshot goes with each request; none is
+ saved. There is no token limit: what bounds the cost is the month's spending limit, checked before
+ each step.
+- Each step asks Claude for exactly one pointing choice. Claude thinks before it points, and a step
+ may use the model's whole output. On models that offer it, each step uses medium effort. The look
+ stops with a reason if Claude answers without pointing, or writes all a step can hold without
+ pointing.
- While it looks, the account window is shown without taking the focus, because a hidden window draws
nothing. It is hidden again afterwards.
- It is not used for a whole chapter: a chapter's start and its end are further apart than one look
@@ -672,7 +684,7 @@ counted with your other usage.
Claude is used for four things: turning a plain request into a code, edition and section; reading
project notes and drafting a plan; one bounded search for a page when a section cannot be found; and,
-if you allow it, looking at a screenshot of a page the reader could not place. Pulling by section
+unless you turn it off, looking at a screenshot of a page the reader could not place. Pulling by section
number or page address never uses it.
| Sent to Anthropic | When |
@@ -681,17 +693,17 @@ number or page address never uses it.
| Code names, editions, section numbers, counts, warnings | Always |
| Heading titles of a pulled section | At the default setting, **Outlines** |
| Short excerpts of saved text, up to 800 characters at a time | Only at **Outlines and short excerpts** |
-| Screenshots of a page the reader could not place, with numbered marks | Only with **Let Claude look at the page** on. They show code text |
+| Screenshots of a page the reader could not place, with numbered marks | While **Let Claude look at the page** is on, which it is unless you turn it off. They show code text |
| Whole sections as text | Never |
| Your API key, saved passwords, cookies, page addresses | Never. A request that contains a credential is refused before it leaves |
Claude cannot open an address, type or sign in. It names pages by references the app gives it, and on
a screenshot it can only point at the numbers the app drew.
-Tokens are not capped for your requests and plans. Each piece of work has a limit on its steps, and
-pauses after 15 minutes of work; at either it stops and asks whether to continue. The queue's own
-calls to Claude are the exception: they have fixed token budgets (see
-[What the queue costs](#what-the-queue-costs-in-claude)). The top bar shows tokens and an estimated
+Tokens are not capped for anything Claude does. Each piece of work has a limit on its steps, and
+pauses after 60 minutes of work; at either it stops and asks whether to continue. What bounds the
+money is [the monthly spending limit](#the-monthly-spending-limit): when the month's estimated cost
+reaches it, every call to Claude stops. The top bar shows tokens and an estimated
cost for the month, with a spinning mark while Claude is working; the figures grow as each of
Claude's replies comes in. The estimate comes from a price list in `assets/pricing.json`. Your
Anthropic account shows what you are actually charged.
@@ -704,8 +716,9 @@ whole conversation is sent again with each step, so it grows with every step. Wh
- **Tools return references and short facts, not pages.** A page is identified by a reference
number, never its address. A section comes back as its number, heading and counts, never its text.
- Every tool result has a size cap of 1 to 8 KB (roughly 250 to 2,000 tokens); a longer list is
- shortened and marked as cut. An excerpt, only at **Outlines and short excerpts**, is at most 800
+ Every tool result has a size cap of 8 to 64 KB (roughly 2,000 to 16,000 tokens), large enough
+ that a jurisdiction's list of codes or a long section's outline arrives whole; a list longer
+ than that is shortened and marked as cut. A search of a code's contents returns up to 25 hits. An excerpt, only at **Outlines and short excerpts**, is at most 800
characters.
- **Site notes are capped at 4 KB** before they go into Claude's instructions.
- **Claude's instructions and tools are sent first and cached.** Anthropic keeps them, and the
@@ -729,84 +742,138 @@ reached its output or context limit before finishing. Split the request and try
Most pulls cost nothing in Claude: the app finds the page and reads the section by itself. Claude is
asked about one pull only when the app cannot place it, and then only twice at most:
-1. **A search of the code's contents for the page.** It has the request step limit and, unlike your
- own requests, a fixed token budget that no setting changes: 150,000 input tokens and 24,000 output
- tokens in all. It never sends a request that would carry it past its input budget, and it stops
- before a request once its output budget is used, so the last reply may go past that by one reply
- (up to the model's own output limit). Nobody is watching it, so at a limit it stops instead of
- asking, and the pull stops for you as one CodePull could not find.
-2. **A look at the page**, if **Let Claude look at the page** is on. It has fixed limits: 15 steps,
- up to 16,000 output tokens a step, and 100,000 input tokens in all, also checked before each
- request.
+1. **A search of the code's contents for the page.** It has 24 steps, fixed in the app: nobody is
+ watching it, and each step may spend one of the account's paced page loads, so it does not follow
+ the step limit your own requests have. At that limit it stops instead of asking, and the pull
+ stops for you as one CodePull could not find.
+2. **A look at the page**, unless you turned **Let Claude look at the page** off. It has 40 steps and
+ 4 page loads.
+
+Neither has a token limit, and neither do your own requests and plans: every call may use the
+model's whole output. So one pull has no ceiling of its own. What bounds all of it is
+[the monthly spending limit](#the-monthly-spending-limit).
-So what Claude can cost on one pull has a ceiling, and a large queue's ceiling is that times the pulls
-still to run. While pulls are waiting or running, **Pull queue** shows a **Claude cost** panel:
+While pulls are waiting or running, **Pull queue** shows a **Claude cost** panel:
| Figure | What it is |
|---|---|
| **Spent so far** | What Claude has cost on these pulls, with the tokens. It grows as each reply is recorded, while the queue runs |
| **Likely for the rest** | The pulls still to run times what Claude cost per pull over your last 200 finished pulls. Shown once at least 10 have finished |
-| **At most for the rest** | The pulls still to run times the ceiling for one pull: the search, plus the look at the page when it is on |
+| **Left under your limit** | Your monthly spending limit less what Claude has cost this month, for all of its work and not only these pulls. This is the most Claude can still cost this month. "no limit" when you set the limit to 0 |
The panel covers every plan and request that still has pulls open, or only one plan when you filter
the queue by plan. A line under the figures shows each pull Claude is working on now and what it has
cost so far. Each pull that Claude was asked about shows its own cost, and each plan's progress line
adds its total. A section two plans asked for is one pull, and its cost is counted once.
-The ceiling prices every input token at the model's dearest input rate (a cache write), although most
-of a search's input is read from the cache at a small fraction of that. Output is allowed one whole
-reply past the search's output budget, because that budget is checked before each request. It uses
-the prices of the model for requests. With Claude Sonnet 5.5 and the look turned on, one pull can
-cost at most about $4.55: about $1.90 for the search and $2.65 for the look, at the prices in the
-app's list. When the price list has no price for that model, amounts show as unknown and tokens are
-still counted. Claude work already done on a model with no listed price shows as unknown
-too, or as "over" the part that was priced, and is left out of the likely figure rather than counted
-as free. When there is no API key, or the model is not available to the key, the queue makes no
-Claude calls and the ceiling is $0.00: a pull it cannot find stops and waits for you.
-
-Before you approve a plan, its bottom bar adds the same figures for the pulls it will make: at most,
-if every one needed Claude's help (cross-references included), and likely, at the rate of your recent
-pulls. A plan Claude drafted also says what drafting it cost. After approval the bar shows what Claude
-has cost on its pulls so far and the most it can still cost.
-
-**Settings → Claude** shows the ceiling for one pull under the limits, for the model and the
-look-at-the-page switch as you choose them.
+The figures use the prices of the model in use. When the price list has no price for that model,
+amounts show as unknown and tokens are still counted. Claude work already done on a model with no
+listed price shows as unknown too, or as "over" the part that was priced, and is left out of the
+likely figure rather than counted as free. When there is no API key, the key offers no model, or the
+month's limit is reached, the queue makes no Claude calls and the panel says why: a pull it cannot
+find stops and waits for you.
+
+Before you approve a plan, its bottom bar says what its pulls would likely cost at the rate of your
+recent pulls, and what is left under the month's limit. A plan Claude drafted also says what drafting
+it cost. After approval the bar shows what Claude has cost on its pulls so far and what the rest will
+likely cost.
+
+### The monthly spending limit
+
+**Settings** has one money control: **Monthly spending limit for Claude**, in US dollars. It starts
+at $200. It is a kill switch for everything Claude does:
+
+- Before every call to Claude, the app adds up what Claude has cost since the first of the month, by
+ its price list. Once that reaches the limit, **no call is made**: not for a request, a plan, the
+ queue's search for a page, or a look at a page.
+- A request or plan that was working stops before its next step and asks. Raise the limit, then
+ choose **Continue**; it goes on where it stopped, and none of its own step allowance is used up.
+ **Stop** ends it.
+- A new request or plan does not start, and says why. Typing an exact section or pasting a page
+ address still works: those never use Claude.
+- The queue keeps pulling. A pull the app finds and reads by itself is not affected. One it cannot
+ place stops with the same message, and nothing of its one search and one look is used up: after
+ you raise the limit, **Retry** asks Claude as usual.
+- The top bar says **Claude stopped at your limit**, and the queue's cost panel and the New request
+ screen say so too.
+
+It lifts when you raise the limit and save, or when the next month begins. Set it to 0 for no limit.
+
+What to know about it:
+
+- **The limit is checked before each call, not during one.** The call that carries the month past the
+ limit finishes, so the month can end a little above it: by one reply. A reply that failed part-way
+ is counted for what it had cost, and is not asked for again past the limit.
+- **It is an estimate.** The app prices each reply from `assets/pricing.json`. Your Anthropic account
+ shows what you are charged. A model with no price in that list counts as nothing, so the limit
+ cannot stop work on such a model. Every model CodePull chooses by itself has a price.
+- **The month is the calendar month in UTC.** Each of Claude's replies counts in the month it was
+ recorded, so a request begun at the end of one month and continued in the next counts in each for
+ what it cost there.
+- **Delete all content keeps the month's usage**, so it does not reset the limit.
## Settings
-### Claude
+You do not have to choose anything here. CodePull has picked a value for every setting, and the page
+opens showing only what is yours to give: the API key, and a spending limit you may want to change.
+Everything else is behind **Show advanced settings**, with the values CodePull chose. The app
+remembers whether you left that part open.
+
+### What you see first
+
+- **Anthropic API key**: save, replace, remove.
+- **The model in use.** One line says which Claude model CodePull uses for requests and for project
+ plans. It chooses the newest Claude Opus your key offers, for both.
+- **Monthly spending limit for Claude.** $200 unless you change it; 0 to 100,000, and 0 means no
+ limit. See [The monthly spending limit](#the-monthly-spending-limit).
+- **This month**: tokens and the estimated cost, against your limit.
+- **About**, described below.
-- **Anthropic API key**: save, replace, remove. **Refresh models** asks Anthropic again which models
- your key can use.
-- **Model for requests** and **Model for project plans**: picked from that list.
+**Save settings** saves the limit and anything you changed in the advanced part. A value outside its
+limits is refused in place; if it sits in the advanced part while that is hidden, the part opens so
+you can see it.
+
+### Advanced settings: Claude
+
+- **Model for requests** and **Model for project plans**. Both start at **Automatic**, which says
+ which model it stands for now: the first your key offers from the list CodePull ships with
+ (`assets/models.default.json`), a Claude Opus first. Pick another model from the list to use that
+ one instead; a model you picked that your key stops offering goes back to Automatic. **Refresh
+ models** asks Anthropic again which models your key can use.
- **Text sharing**: *Nothing from pages*, *Outlines* (default) or *Outlines and short excerpts*.
-- **Let Claude look at the page when CodePull cannot find a section on it.** Off by default. See
+- **Let Claude look at the page when CodePull cannot find a section on it.** On unless you turn it
+ off. See
[When the reader cannot place a section](#when-the-reader-cannot-place-a-section-claude-looks-at-the-page).
-- **Limits for one piece of work**. Tokens are not capped for your requests and plans: each call to
- Claude may use the model's whole output. These limits stop a request that goes in circles. When one
- is reached, the app stops and asks whether to continue with another allowance of the same size. The
- line under them shows the most Claude can cost on one queued pull with the selected model (see
- [What the queue costs](#what-the-queue-costs-in-claude)).
+- **Limits for one piece of work**. Tokens are not capped for anything Claude does: each call may use
+ the model's whole output. These limits stop a request that goes in circles. When one is reached,
+ the app stops and asks whether to continue with another allowance of the same size. They are set
+ high enough that an ordinary request or plan never reaches one.
| Limit | Default | Range | What it means |
|---|---|---|---|
-| Steps for one request | 14 | 2 to 40 | One step is one call to Claude: it reads what its tools found and decides what to do next. A quick pull usually takes 3 to 6 |
-| Steps for one project plan | 24 | 2 to 60 | A plan takes more: reading the notes, recording the facts, checking each code, then drafting |
-| Largest plan Claude may draft | 30 sections | 1 to 60 | The most sections Claude may put in one plan. Sections past it are left out and Claude is told which. You review every item before anything is pulled |
+| Steps for one request | 40 | 2 to 200 | One step is one call to Claude: it reads what its tools found and decides what to do next. A quick pull usually takes 3 to 6 |
+| Steps for one project plan | 60 | 2 to 200 | A plan takes more: reading the notes, recording the facts, checking each code, then drafting |
+| Largest plan Claude may draft | 60 sections | 1 to 60 | The most sections Claude may put in one plan. Sections past it are left out and Claude is told which. You review every item before anything is pulled |
+
+A request also pauses to ask after 60 minutes of work. Time spent waiting for your answer does not
+count. The queue's own search for a page has 24 steps whatever these say, and a look at a page has
+40; neither can ask, so each stops at its limit.
-A request also pauses to ask after 15 minutes of work. Time spent waiting for your answer does not
-count.
+How hard Claude thinks is chosen for you as well, and is not a setting: high effort for a request
+and for the queue's search, the next level up for a project plan, and medium for each step of a look
+at a page. A model that does not offer a level gets the highest it does offer below it.
-### Pulling
+### Advanced settings: Pulling
- **Show the account window while CodePull is pulling**.
- **Capture the adopting-agency table and print it in documents, when a section has one.** Off by
default: the table is kept with the pull but not printed.
-### Pacing
+### Advanced settings: Pacing
These apply to each account by itself. You can lower them freely. You cannot raise them past the hard
-limits.
+limits. CodePull did not speed these up when it chose the other settings: they are what keeps an
+account in good standing with the site.
| Setting | Default | Hard limit |
|---|---|---|
@@ -817,13 +884,13 @@ limits.
| Pause between sections on one page | 1.5 seconds | Never less than 0.5 |
| Accounts pulling at the same time | 2 | Never more than 4 |
-### Library
+### Advanced settings: Library
- **Days until a pull counts as stale.** Zero means never. A stale pull is marked.
- **Pull a section again when the saved copy is stale.** Off by default.
- **Earlier versions kept for each section.** Default 3.
-### Advanced
+### Advanced settings: Data and diagnostics
- **Export diagnostics** saves a zip with the app version, your settings, the state of the queue and
the activity log. It holds no code text, no passwords and no API key.
@@ -877,10 +944,23 @@ This version opens the same data folder, so your accounts, plans, queue and libr
starts. Before it updates the database, the first start copies it to `app.db.bak-` beside it,
where `` is the number of the last update the old version applied. Things to know afterwards:
-- **There is no source-access notice any more, and no token limit you set.** Settings from an earlier
- version are read without them. Your step limits and plan size are kept. Only the queue's own calls
- to Claude have token budgets, fixed in the app (see
- [What the queue costs](#what-the-queue-costs-in-claude)).
+- **CodePull now chooses the settings for you.** The first start of this version moves an existing
+ install to the new values, once:
+ - Both models go back to **Automatic**, which is the newest Claude Opus your key offers. The app
+ cannot tell a model it picked itself from one you picked, so a pick of yours is reset too. Pick
+ it again under **Show advanced settings** if you want it back.
+ - A step limit or plan size that still held the earlier default (14, 24 and 30) moves to the new
+ one (40, 60 and 60). One you had changed is kept.
+ - **Let Claude look at the page** is turned on. It was off unless you turned it on, so "off" was
+ the earlier default and not a choice. Turn it off under **Show advanced settings** if you do
+ not want screenshots of a page sent to Anthropic.
+ - A **monthly spending limit** of $200 is set. See
+ [The monthly spending limit](#the-monthly-spending-limit).
+ - Pacing, text sharing, the library settings and everything else you set are left as they were.
+- **There is no source-access notice any more, and no token limit anywhere.** Settings from an
+ earlier version are read without them. The queue's own calls to Claude had fixed token budgets
+ until this version; they have none now, and the queue no longer shows an "at most" figure for a
+ pull. The spending limit is what bounds Claude.
- **Pulls that were waiting are still waiting**, each on the account it had, and run by themselves
unless you had paused the queue: a paused queue stays paused.
- **Requests you made to Claude in 0.1 are closed and no longer listed.** The plans they drafted are
@@ -895,7 +975,7 @@ where `` is the number of the last update the old version applied. Things to
app remembers which chapter held it.
- **The text of a pull is wrong.** Do not use it. In **Accounts**, with that account's window on the
page, choose **Save page outline**. It saves the page's structure with no text in it. Then use
- **Settings → Advanced → Export diagnostics**. Those two files show a developer what the reader saw.
+ **Settings → Show advanced settings → Export diagnostics**. Those two files show a developer what the reader saw.
[Validating against the live site](docs/live-validation.md) lists the usual causes.
- **A pull ends "Check failed".** The message names the document, the page, the block and the
character. Export diagnostics: `logs.jsonl` has a `job.blocked` line for that pull with the same
@@ -916,9 +996,9 @@ where `` is the number of the last update the old version applied. Things to
is noticed it stays noticed: a later check on a code page, which holds no proof either way, does not
take it back.
- **A screen says it could not be shown.** Nothing was changed. Choose **Try again**, or go to another
- screen: the others keep working. If it comes back, use **Settings → Advanced → Export diagnostics**
+ screen: the others keep working. If it comes back, use **Settings → Show advanced settings → Export diagnostics**
and keep the line under "Details".
-- **Start over.** **Settings → Advanced → Delete all content** clears the library, plans, queue and
+- **Start over.** **Settings → Show advanced settings → Delete all content** clears the library, plans, queue and
requests and keeps your settings and sign-ins. **Wipe all data** removes everything, sign-ins and
key included.
@@ -1007,4 +1087,6 @@ Each of these is optional or later work in the plan this app was built from.
| One Word file of combined pulls | **Combine into one PDF…** makes one PDF. Its **A folder** choice holds each section's Word document, one per section |
| Saved selections of library pulls | Tick the pulls again, or put the sections in a plan, which keeps them together and can be exported again |
| Encryption of the library | Files are protected by your operating-system account |
+| Web search or web fetch for Claude | Claude works from the site's own list of codes and each code's contents, which say what is adopted and where a section is printed. It cannot open an address, and nothing from the open web enters a request. See [decision 11](docs/adr/0011-chosen-for-the-user.md) |
+| A cost ceiling for one pull | No call to Claude has a token limit, so one pull has none. The monthly spending limit bounds all of Claude's work |
| A second code site | The contract is in place. See [Adding a code site](docs/adding-a-site.md) |
diff --git a/assets/models.default.json b/assets/models.default.json
index 144a7b9..71ae6f5 100644
--- a/assets/models.default.json
+++ b/assets/models.default.json
@@ -1,9 +1,32 @@
{
- "_note": "Preferences for a fresh install. The app lists the models your API key can call and you choose in Settings. 'prefer' is tried in order and the first model your key offers is selected. 'effort' is sent only to models that report the effort control. 'fallbacks' opts a model family into Anthropic's server-side fallback when a safety classifier declines a request.",
+ "_note": "What the app chooses for the user. 'prefer' is tried in order and the first model the API key offers is used while Settings says Automatic; a model picked by hand in Settings wins. 'effort' is how hard Claude thinks for that kind of work: it is sent only to models that report the effort control, and lowered to the highest level the model offers. 'look' is one look at a page (the screenshot fallback). 'fallbacks' opts a model family into Anthropic's server-side fallback when a safety classifier declines a request.",
"roles": {
- "agent": { "prefer": ["claude-sonnet-5-5", "claude-opus-5-5"], "effort": "medium" },
- "planner": { "prefer": ["claude-opus-5-5", "claude-sonnet-5-5"], "effort": "high" }
+ "agent": {
+ "prefer": [
+ "claude-opus-5-5",
+ "claude-opus-5",
+ "claude-opus-4-8",
+ "claude-opus-4-7",
+ "claude-opus-4-6",
+ "claude-sonnet-5-5",
+ "claude-sonnet-5"
+ ],
+ "effort": "high"
+ },
+ "planner": {
+ "prefer": [
+ "claude-opus-5-5",
+ "claude-opus-5",
+ "claude-opus-4-8",
+ "claude-opus-4-7",
+ "claude-opus-4-6",
+ "claude-sonnet-5-5",
+ "claude-sonnet-5"
+ ],
+ "effort": "xhigh"
+ }
},
+ "look": { "effort": "medium" },
"models": {
"claude-opus-5-5": { "fallbacks": true },
"claude-sonnet-5-5": { "fallbacks": true },
diff --git a/docs/adr/0007-claude-tool-loop.md b/docs/adr/0007-claude-tool-loop.md
index 2ec0f92..d4c15d8 100644
--- a/docs/adr/0007-claude-tool-loop.md
+++ b/docs/adr/0007-claude-tool-loop.md
@@ -1,6 +1,9 @@
# 7. Claude chooses what and where; software does the rest
-**Status:** accepted
+**Status:** accepted. Revised on 1 December 2026 by
+[decision 11](0011-chosen-for-the-user.md): the app chooses the models, effort and limits for the
+user, no kind of run has a token budget, and a monthly spending limit stops every call. Where the
+text below says otherwise, decision 11 stands; the section at the end lists what changed here.
## Decision
@@ -84,3 +87,20 @@ pointing tools: see [decision 8](0008-screenshot-fallback.md).
the saved pull as `blocked` with its reason, not as a fault inside the app.
- **`render_document` has no default for the adopting-agency table.** Left out, the saved documents
stay as they are.
+
+## Changed 1 December 2026 ([decision 11](0011-chosen-for-the-user.md))
+
+- **Models are still discovered, and now chosen for the user.** The user no longer picks: an empty
+ setting means automatic, the first model in `assets/models.default.json` the key offers, worked
+ out when it is used (`resolveModel`). Both roles prefer an Opus. A pick by hand still wins.
+- **Effort.** High for requests and the queue's search, xhigh for plans, fitted to the levels the
+ model reports (`effortFor`).
+- **Budgets.** Defaults are 40 steps for a request and 60 for a plan, a plan of up to 60 items, and
+ 60 minutes of working time before a run pauses to ask.
+- **The exception is gone.** The queue's search for a page has no token budget
+ (`QUEUE_SEARCH_TOKENS` was removed) and 24 steps of its own (`QUEUE_SEARCH_STEPS`), which no
+ setting changes.
+- **Tool results** are capped at 8 to 64 KB, so a code list or a long outline arrives whole.
+- **The month's spending limit** is read before a run starts and before every call
+ (`RuntimeDeps.spend`). Reached, the run suspends with a `budget` question and sends nothing until
+ the user has raised the limit and chosen Continue.
diff --git a/docs/adr/0008-screenshot-fallback.md b/docs/adr/0008-screenshot-fallback.md
index 300f4d2..ef45581 100644
--- a/docs/adr/0008-screenshot-fallback.md
+++ b/docs/adr/0008-screenshot-fallback.md
@@ -1,7 +1,10 @@
# 8. Screenshot fallback: Claude points, the reader reads
**Status:** accepted, 19 November 2026. Requests revised the same day for models that refuse a forced
-tool choice and always think (see "Requests to current models").
+tool choice and always think (see "Requests to current models"). Revised on 1 December 2026 by
+[decision 11](0011-chosen-for-the-user.md): the fallback is **on by default**, it has no token
+limits, and it stops at the month's spending limit. Where the text below says otherwise, decision 11
+stands; the section at the end lists what changed here.
## Context
@@ -13,7 +16,7 @@ navigate; the reader, not the model, extracts the text.
## Decision
-- **Off by default** (Settings → Claude → "Let Claude look at the page when CodePull cannot find a
+- **Off by default** until 1 December 2026, and on by default since (see the end) (Settings → Claude → "Let Claude look at the page when CodePull cannot find a
section on it"). Screenshots show code text, and rule 9 keeps section text from Claude unless the
user allows it.
- When a pull stops with `not_found` or `layout_changed` and the setting is on, the queue runs it
@@ -105,3 +108,18 @@ and refuse it, and the reader keeps its role as the only source of text (rule 1)
is and where one starts and ends. A section saved by a look records the adapter version and
follows the adopting-agency table setting; one with far less text than the saved pull is refused
as the queue's own would be.
+
+## Changed 1 December 2026 ([decision 11](0011-chosen-for-the-user.md))
+
+- **On by default.** The owner's decision, and a change to rule 9. It is still a setting
+ (Settings → Show advanced settings), the user can turn it off, and an install that had it off as
+ the earlier default is moved to on once. What Claude can do is unchanged: it points, app code
+ checks, the reader reads.
+- **Bounds:** 40 steps and 4 page loads. No output cap per step (each asks for the model's own
+ output maximum, 64,000 when unknown) and no input budget. The month's spending limit is read
+ before every step (`VisualDeps.spend`); reached, the look ends as a give-up with the stop message.
+- **Effort:** medium, from `assets/models.default.json` (`look.effort`), fitted to the model and
+ passed in by the workspace (`VisualDeps.effort`). The model in use is the one for requests, now an
+ Opus by default.
+- A step that ends at `max_tokens` is still a give-up; its message no longer names a figure.
+- A whole chapter is still not looked for (`cannotLook`): 40 steps do not reach across one either.
diff --git a/docs/adr/0009-claude-cost-in-the-queue.md b/docs/adr/0009-claude-cost-in-the-queue.md
index 6956d19..db070a4 100644
--- a/docs/adr/0009-claude-cost-in-the-queue.md
+++ b/docs/adr/0009-claude-cost-in-the-queue.md
@@ -2,6 +2,9 @@
**Status:** accepted, 19 November 2026. Revised on 20 November 2026, when the request token limits
were removed ([decision 7](0007-claude-tool-loop.md)): the queue's own calls keep fixed budgets.
+**Partly superseded on 1 December 2026** by [decision 11](0011-chosen-for-the-user.md): the owner
+removed the queue's token budgets too, so one pull no longer has a ceiling, and a monthly spending
+limit bounds all of Claude's work instead. The section at the end lists what still holds.
## Context
@@ -85,3 +88,28 @@ Claude Sonnet 5.5: a figure that bounds nothing in practice.
call already bound each pull; a cap across runs would be a new stop to design, with its own notice.
- Prices fetched from Anthropic. The price list stays an editable file in the app, and every figure
says it is an estimate, not a bill.
+
+## Changed 1 December 2026 ([decision 11](0011-chosen-for-the-user.md))
+
+Gone:
+
+- The fixed token budgets (`QUEUE_SEARCH_TOKENS`, `VISUAL_LIMITS.inputTokens` and the look's output
+ cap), and with them the check of each request's input against a budget.
+- The ceiling for one pull (`pullCeiling`, `runCeiling`), "At most for the rest" on the queue and on
+ a plan, and the line under the limits in Settings. Without budgets the only true ceiling for one
+ pull is the context window times the steps, which bounds nothing in practice.
+
+In their place, the month's spending limit (`Settings.spendLimitUsd`): the queue's third figure is
+**Left under your limit**, the limit less the month's estimate (`leftUnderLimit`). That is a ceiling
+the code enforces, for all of Claude's work and not only the queue's.
+
+Still as decided here:
+
+- Every Claude run made for a queued pull records the pull, and figures are live at the grain of one
+ reply.
+- The projection from the last 200 finished pulls (`likelyFor`), shown once 10 have finished. It is
+ no longer capped by a ceiling, there being none.
+- Unknown is not zero, and one pull is counted once.
+- The arithmetic is shared and runs in the screens.
+
+"Not built: a spending cap" no longer holds: it is built, as a cap for the month.
diff --git a/docs/adr/0011-chosen-for-the-user.md b/docs/adr/0011-chosen-for-the-user.md
new file mode 100644
index 0000000..72ef6c6
--- /dev/null
+++ b/docs/adr/0011-chosen-for-the-user.md
@@ -0,0 +1,172 @@
+# 11. CodePull chooses the settings; the user sets one spending limit
+
+**Status:** accepted, 1 December 2026. The owner's decision. It revises decisions
+[7](0007-claude-tool-loop.md), [8](0008-screenshot-fallback.md) and
+[9](0009-claude-cost-in-the-queue.md), and rule 9 in `CLAUDE.md`.
+
+## Context
+
+Settings asked the user to choose: a model for requests and one for plans, how much of a page Claude
+may see, whether Claude may look at a page, step limits, pacing, library housekeeping. A user who
+only wanted to pull sections had to read a page of controls first, and the defaults were cautious
+ones: a mid-tier model for requests, small step limits that paused work to ask, and token budgets on
+the queue's own calls that could end a search or a look before it had found anything.
+
+The owner asked for the opposite. The user should have nothing to choose. The app should be
+well resourced and should work: an Opus for both roles, appropriate thinking, no limits on what
+Claude may read or write. Cost matters less than working, without being wasteful. Nothing that
+exists should be removed, only hidden. And one money control should remain, set by the user, that
+stops everything when it is reached.
+
+## Decision
+
+### Settings are chosen, and hidden
+
+- **Settings opens short.** The API key, a line saying which model is in use, the monthly spending
+ limit, the month's usage, and About. Everything else is behind **Show advanced settings**, with
+ the values the app chose. Nothing was removed from the screens or the code. The choice to show the
+ advanced part is remembered on the computer (`src/ui/advanced.ts`, `localStorage`).
+- **A refused value is never refused out of sight.** Saving with a value outside its limits in the
+ hidden part shows that part.
+- **Links to a hidden setting open it** (pacing, from the queue and the home screen).
+
+### What was chosen
+
+| Setting | Before | Now |
+|---|---|---|
+| Model for requests, and the queue's search and look | Claude Sonnet 5.5 | Automatic: the first Opus the key offers |
+| Model for project plans | Claude Opus 5.5 | Automatic: the same |
+| Effort: requests and the queue's search | medium | high |
+| Effort: project plans | high | xhigh |
+| Effort: each step of a look at a page | low | medium |
+| Steps for one request | 14 (2 to 40) | 40 (2 to 200) |
+| Steps for one project plan | 24 (2 to 60) | 60 (2 to 200) |
+| Largest plan Claude may draft | 30 | 60, the software's own maximum |
+| Working time before a run pauses to ask | 15 minutes | 60 minutes |
+| The queue's search for a page | request steps; 150,000 input and 24,000 output tokens | 24 steps of its own; no token budget |
+| A look at a page | 15 steps; 16,000 output tokens a step; 100,000 input tokens | 40 steps; the model's whole output a step; no input budget |
+| Tool result size caps | 1 to 8 KB | 8 to 64 KB; a contents search returns 25 hits, not 10 |
+| Let Claude look at the page | off | on |
+| Monthly spending limit | none | $200 |
+
+Left as they were: pacing (rule 10 is what keeps an account in good standing; "powerful" does not
+mean more page loads), text sharing at Outlines (rule 9: no section text by default), the page
+loads one look may make (4), the three-tool-errors stop, and the library and pulling switches.
+
+- **Automatic models.** An empty `Settings.model` or `plannerModel` means automatic: the first model
+ in `assets/models.default.json` `roles..prefer` that the key offers, worked out when it is
+ used (`resolveModel`). Nothing writes a model ID into the user's settings any more; `setModels`
+ only puts a hand-picked model the key stopped offering back to automatic. A later version that
+ ships a newer preference moves every install that is on automatic, and none that picked by hand.
+ Model IDs still live only in the asset file, never in `src`.
+- **Effort is per kind of work and fitted to the model.** The Models API reports which levels a
+ model offers (`Model.efforts`). `effortFor` sends the highest offered level that is not above the
+ one wanted, and nothing to a model without the control. A model list saved before levels were
+ recorded is read as offering low, medium and high, and is read once more from Anthropic before the
+ next request that is about to call it anyway (`Workspace.freshenModels`, once per start).
+ Effort is not a setting: it lives in `assets/models.default.json`.
+- **No token limit anywhere.** The queue's search lost `QUEUE_SEARCH_TOKENS`, and the look lost its
+ per-step output cap and its input budget. Every call asks for the model's own output maximum.
+ What remains stops a run that goes in circles, and none of it is a token limit: steps, working
+ time, three failed tool calls in a row, and for the look its page loads.
+- **The queue's search has its own step limit** (`QUEUE_SEARCH_STEPS`, 24, not a setting). It used
+ to follow the request step limit. Nobody watches it and each step may spend one of the account's
+ paced page loads, so raising the request limit to 40 must not also let a failing search spend 40
+ page loads.
+- **Larger tool results.** The caps were small enough to cut a jurisdiction's list of codes or a
+ long section's outline, which Claude checks subsections against. They still exist, as a bound on
+ what one page's worth of untrusted titles can add to a request.
+
+### An install that already exists
+
+Preferences are stored whole, so new defaults alone would never reach an existing install. Migration
+0010 moves it once: both models to automatic (the app cannot tell a model it picked from one the
+user picked, so a pick by hand is reset too, and the README says so); a step limit or plan size
+that still equals the earlier default is taken out, so the new default applies, while a value
+changed by hand stays; and a stored `visualFallback: false` is taken out, because off was the
+earlier default and not a choice. Nothing else is touched.
+
+### The screenshot fallback is on by default
+
+Rule 9 said the fallback is off by default, because screenshots show code text. The owner changed
+that: it is the setting that most decides whether a pull the reader cannot place still succeeds
+without the user, and everything saved that way is marked Needs review. It is still a setting, the
+user can turn it off, and what it can do is unchanged: Claude points at numbered marks, app code
+checks every choice, and the reader reads the text. Settings, the README and the user guide say
+that screenshots of code text go to Anthropic while it is on.
+
+### One spending limit, and it is a kill switch
+
+- **`Settings.spendLimitUsd`**: whole US dollars for one calendar month, 0 to 100,000, $200 by
+ default, 0 for no limit. It is the one value on the short Settings page.
+- **What it counts.** The estimated cost of every reply recorded in the calendar month (UTC), from
+ `claude_months` (`Store.monthSpend`; migration 0011): the same figure the top bar shows. A run
+ saves its usage after every reply, and `runs.save` adds what the save added to the month it is
+ recorded in. Counting a run by the month it began, as the top bar did until now, would have let a
+ run paused in one month and continued in the next go on uncounted. Runs recorded before the table
+ count in the month they began.
+- **Where it is checked: before every call to Claude, in both loops.** `runtime.ts` reads
+ `deps.spend()` before a run starts and before each model call, a call sent again after a reply
+ that could not be read included; what the interrupted reply had cost is saved first, so the
+ check sees it. `visual.ts` reads it before each step. While it is reached nothing is sent, by any
+ kind of work.
+- **What happens to work in hand.** A tool-loop run suspends with a `budget` question whose text is
+ the stop message. Continue checks again: still reached, it asks again and sends nothing; raised,
+ the run goes on and no step allowance is used up (`Header.spendStop`). A run nobody watches is
+ stopped, as at any limit. A new request is refused with the same message
+ (`Workspace.startRun` and `Runtime.start`). A look ends as a give-up with it.
+- **The queue.** `Workspace.findPage` and `lookAtPage` do not start past the limit, and the
+ scheduler (`claudeStopped`) says so on the pull and leaves the job's `searched` and `looked`
+ marks unset, also when the limit was reached while Claude worked, so Retry asks Claude once the
+ limit is raised. Pulls that need no help from Claude are not affected: they cost nothing.
+- **Shown everywhere it matters.** `State.claude.spend` (`monthUsd`, `limitUsd`, `reached`); the top
+ bar, the queue's cost panel, the New request screen, the plan bar and Settings say Claude is
+ stopped, with the same words (`spendStopMessage`).
+- **It replaces the ceiling.** With no token budgets a pull has no ceiling of its own, so the
+ queue's "At most for the rest" and the Settings line under the limits are gone. The panel shows
+ what was spent, what the rest will likely cost, and what is left under the limit, which is the
+ most Claude can still cost this month.
+
+## What the limit does not do
+
+- **It can be passed by one call.** It is checked before a call, not during one. With several
+ accounts working, each call in flight when the limit is reached finishes. A reply may use the
+ model's whole output, so the overshoot is bounded by a few replies, not by a figure.
+- **It is an estimate.** Costs come from `assets/pricing.json`. A model with no price there costs
+ nothing by this count, so the limit cannot stop work on it. Every model the app chooses by itself
+ is priced, and a test keeps it so; a model picked by hand may not be.
+- **It is not Anthropic's limit.** A workspace spend limit in the Anthropic Console is the hard one.
+ This one stops the app from calling.
+- **Deleting all content does not reset it.** `claude_months` is not content.
+
+## Why
+
+- A value nobody has to choose is a value nobody gets wrong. The settings stay for the user who has
+ a reason, and the advanced part says the values work as they are.
+- The token budgets on the queue's calls were the limits most likely to end work that was going
+ well. The search's input budget counted every token of every request, cached or not, and a search
+ resends its whole conversation with each step, so the budget could run out before the steps did.
+ Steps and time stop a run that is stuck without stopping one that is working.
+- One figure in dollars is a limit a user can reason about, and it covers every kind of call. A
+ ceiling per pull covered only the queue's calls and was a number of tokens times a price.
+- Automatic keeps "models are discovered, not hard-coded" true while giving every user the model the
+ owner chose, and lets a later version move them all with one line in an asset file.
+
+## Considered
+
+- **Web search and web fetch for Claude.** Not added. Web fetch takes addresses, which rule 9 keeps
+ from Claude, and could load the code site outside the paced driver (rules 10 and 11). Web search
+ would send queries built from project notes to a search provider and bring untrusted web text
+ into a run, for little gain: what is adopted and where a section is printed are answered by the
+ site's own catalog and contents, which Claude already has tools for. Letting those tools return
+ whole lists helps more.
+- **Compaction or context editing during a run.** Not added. Current models hold a million tokens,
+ tool results are capped, and steps are capped; a run would need hundreds of continued steps to
+ fill that. If a run ever ends at the context limit, this is the next thing to add.
+- **Stopping the whole queue at the limit.** Not done. A pull that needs no help from Claude costs
+ nothing, and stopping it would make the limit cost the user their unattended pulls for no saving.
+- **A re-pick of the models on upgrade instead of automatic.** It would have written a model ID into
+ each install's settings again, and the next change of preference would have needed another
+ migration.
+- **Keeping a per-pull ceiling beside the limit.** That needs token budgets on the queue's calls,
+ which is what the owner asked to remove.
diff --git a/docs/architecture.md b/docs/architecture.md
index 94cc6ae..9b91e36 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -220,42 +220,66 @@ access to the library or the catalog, and is recorded as a `fallback_nav` run fo
## What Claude costs while the queue works
-A pull calls Claude at most twice, and only when the app cannot place it: a `fallback_nav` search,
-then the look at the page within `VISUAL_LIMITS`. Unlike requests and plans, which have no token
-limit, both have fixed token budgets: the search `QUEUE_SEARCH_TOKENS` (`Limits.tokens`, set only for
-`fallback_nav`), the look `VISUAL_LIMITS.inputTokens` and its per-step output. Both check the input
-budget against the request they are about to send, not only against what was sent before, and the
-queue's search is never granted another allowance. So one pull has a cost ceiling, and
-`src/shared/claude-cost.ts` works out, from those budgets and the model's listed prices:
-
-- the ceiling for one pull (`pullCeiling`), priced with every input token at the dearest input rate;
-- the most the pulls still to run can cost (that ceiling times the waiting and running pulls);
-- what they are likely to cost, at the average Claude cost per pull over the last 200 finished pulls
- (`Store.claudeHistory`), once at least 10 have finished;
+A pull calls Claude at most twice, and only when the app cannot place it: a `fallback_nav` search
+(`QUEUE_SEARCH_STEPS` steps), then the look at the page within `VISUAL_LIMITS`. Neither has a token
+budget, and neither do requests and plans ([decision 11](adr/0011-chosen-for-the-user.md)), so one
+pull has no ceiling of its own. `src/shared/claude-cost.ts` works out:
+
- what was spent, from each job's runs (`Job.claude`, summed in `Store.jobs`), each job counted once
although the job list holds a job shared by two plans once for each (`uniqueJobs`). Tokens of runs
costed at nothing, on a model with no listed price, are kept apart as unpriced, so the spend shows
- as unknown rather than free.
-
-`Workspace.state` sends the inputs (`State.claude`: the model, the prices of the models the key
-offers, the search and look budgets with the output one request may ask for, and the history); the
-screens do the arithmetic, so the Settings screen can show the ceiling for a model the user has not
-saved yet. A run saves its usage after every reply and
+ as unknown rather than free;
+- what the pulls still to run are likely to cost (`likelyFor`), at the average Claude cost per pull
+ over the last 200 finished pulls (`Store.claudeHistory`), once at least 10 have finished;
+- what is left under the month's spending limit (`leftUnderLimit`).
+
+`Workspace.state` sends the inputs (`State.claude`: the model in use for each role and what
+automatic stands for, the prices of the models the key offers, the month's spending against the
+limit, and the history); the screens do the arithmetic. A run saves its usage after every reply and
the screens are told, so the figures move while the queue runs.
+## The month's spending limit
+
+`Settings.spendLimitUsd` (whole dollars, 0 for none, $200 by default) is a kill switch on every call
+to Claude ([decision 11](adr/0011-chosen-for-the-user.md)).
+
+- `Workspace.spend()` is `spendState(Store.monthSpend(first of the month), limit)`: the estimated
+ cost of every reply recorded this month, from `claude_months`, against the limit. `runs.save`
+ adds what each save added to a run's usage to the month of the save, so a run continued in a
+ later month counts there.
+- It is read before a run starts and before each model call in `runtime.ts` (`RuntimeDeps.spend`;
+ `heldAtSpendLimit`, also before a request is sent again, after its partial usage is saved),
+ before each step in `visual.ts` (`VisualDeps.spend`), and before `findPage`, `lookAtPage` and
+ `startRun` begin anything.
+- Reached: a tool-loop run suspends with a `budget` question (`Header.spendStop`; Continue checks
+ again and uses up no allowance), a look gives up, a new run is refused, and the scheduler
+ (`SchedulerDeps.claudeStopped`) puts the stop message on the pull and leaves its `searched` and
+ `looked` marks unset so a retry may ask Claude later.
+- Pulls that need no help from Claude are not stopped by it.
+- It is checked before a call, so the call that crosses it finishes; and it counts by
+ `assets/pricing.json`, so a model with no price there is not seen by it.
+
+## Settings the app chose
+
+Settings shows the API key, the model in use, the spending limit and About. The rest renders only
+while the advanced part is shown (`src/ui/advanced.ts`; `localStorage`), and saving a refused value
+in the hidden part shows it. An empty model setting is automatic (`resolveModel`, with
+`assets/models.default.json`); effort per kind of work is in the same file and fitted to the model
+(`effortFor`). Migration 0010 moves an existing install to the new defaults once.
+
## Claude's context
A run is one conversation, sent whole with every step (`src/agent/runtime.ts`). It is append-only
while live, because reasoning blocks must go back unchanged. What keeps it small:
- Tool results are refs, counts and short titles, never section text. Each tool has a byte cap
- (`maxResultBytes`, 1 to 8 KB); `boundResult` shortens the longest lists until the result fits.
+ (`maxResultBytes`, 8 to 64 KB); `boundResult` shortens the longest lists until the result fits.
- Site notes are cut to 4 KB (`boundSiteNotes`). The system prompt and tools are a frozen prefix
with a cache marker, and the conversation uses automatic caching, so repeated input is billed at
cache-read rates.
- Steps are capped per run (`limitsFor`). A run the user continues gets another allowance of the
- same size and keeps its conversation. Only the queue's search for a page also has token budgets
- (see above).
+ same size and keeps its conversation. The queue's search for a page has its own step limit and
+ cannot be continued. No run has a token budget.
- `max_tokens` is the model's own output maximum from the Models API (64,000 when it reports none).
- On `max_tokens` or `model_context_window_exceeded` the run ends with a message to split the
request. There is no compaction or context editing during a run.
diff --git a/docs/live-validation.md b/docs/live-validation.md
index 7c3fb77..3b3459a 100644
--- a/docs/live-validation.md
+++ b/docs/live-validation.md
@@ -100,8 +100,8 @@ runs. The section text is never in the status log.
## 8. The screenshot fallback (needs an Anthropic API key)
-Turn on **Settings → Claude → Let Claude look at the page when CodePull cannot find a section on it**.
-Then request a section the app cannot place by itself: one whose chapter address does not follow the
+**Let Claude look at the page when CodePull cannot find a section on it** is on unless it was turned
+off (**Settings → Show advanced settings**). Request a section the app cannot place by itself: one whose chapter address does not follow the
usual numbering, for example a section in an appendix or a continued chapter.
| Check | Expected |
@@ -111,7 +111,8 @@ usual numbering, for example a section in an appendix or a continued chapter.
| Nothing but code, chapter and code-list pages was opened | Check the window's address while it works |
| While Claude looks, **Pull queue → Claude cost** names the pull and its cost grows with each step | Note the pull's final cost and tokens |
| That cost is close to what the Anthropic Console shows for the same minutes | Usage there can lag by a few minutes. The app's figure is an estimate from its price list |
-| The pull's cost is below the panel's ceiling for one pull (search plus look, shown in Settings) | Yes |
+| **Left under your limit** on the panel fell by about the pull's cost | Yes. It is the monthly spending limit in Settings less the month's estimate |
+| With the monthly spending limit set below the month's estimate, a retry of a pull the app cannot place stops with **Claude is stopped**, and nothing is sent | Yes. Set the limit back afterwards, then **Retry** |
If Claude gives up, the pull says why in one line. Capture it by hand instead.
@@ -234,7 +235,7 @@ Tick **Show the account window while CodePull is pulling** for the first two.
| Check | Expected |
|---|---|
| Pull a whole long chapter (NFPA 13 or NFPA 70 has several) | The window scrolls from the top of the page to its end once, a screen at a time, then returns. Note how long it took |
-| Does the page grow as it scrolls? | **Settings → Advanced → Export diagnostics**: the activity log's `page.scrolled` line says `grew: true` if the page loaded more as it scrolled, and `complete: true` if the end stayed the end. Note both |
+| Does the page grow as it scrolls? | **Settings → Show advanced settings → Export diagnostics**: the activity log's `page.scrolled` line says `grew: true` if the page loaded more as it scrolled, and `complete: true` if the end stayed the end. Note both |
| Pull a section near the end of a long chapter, by number, after the app restarts | It is found. If the page loads as it is read, the log shows one `page.scrolled` for it, with `scope: section` |
| Pull another section from the same chapter page | No second scroll: the log shows no new `page.scrolled` |
| Choose **Pause all** while a chapter page is scrolling | The scrolling stops at once and the pull goes back to waiting |
@@ -282,7 +283,7 @@ was broken, with its period left on the next page
## When something is wrong
-**Settings → Advanced → Export diagnostics** saves a zip with the app's version, settings, queue
+**Settings → Show advanced settings → Export diagnostics** saves a zip with the app's version, settings, queue
states and activity log. It holds no code text, no page content, no passwords and no API key.
**Accounts → Save page outline** (with that account's window on the problem page) saves the page's
diff --git a/docs/user-guide.md b/docs/user-guide.md
index 149f05a..9f5c83a 100644
--- a/docs/user-guide.md
+++ b/docs/user-guide.md
@@ -23,6 +23,13 @@ waiting are still waiting, each on its own account, and run by themselves unless
queue. Requests you made to Claude in 0.1 are closed and not listed. The plans they drafted are kept.
If 0.1 was waiting on a question, ask again from **New request**.
+This version chooses the settings for you, and moves an install that already exists to them once,
+on its first start: both models go to **Automatic** (the newest Claude Opus your key offers, also if
+you had picked another); step limits and the plan size that still held the earlier defaults move to
+the new ones; **Let Claude look at the page** is turned on; and a monthly spending limit of $200 is
+set. Pacing, text sharing and everything else you set stay as they were. All of it can be changed
+under **Settings → Show advanced settings**.
+
## The layout
The left side has six screens.
@@ -78,16 +85,32 @@ the one that new requests start with.
### 2. Add an Anthropic API key (optional)
-Open **Settings → Claude**, paste the key and choose **Save key**. The app asks Anthropic which models
-the key can use and lists them. Pick a **Model for requests** and a **Model for project plans**, or
-keep the ones chosen for you.
+Open **Settings**, paste the key and choose **Save key**. That is the whole setup. The app picks the
+Claude model for you, the newest Claude Opus your key offers, for requests and for project plans,
+and the page says which it is. Every other setting has a value already.
Without a key, everything works except plain-language requests, project plans and the screenshot
fallback.
-In the same section, **Let Claude look at the page when CodePull cannot find a section on it** is off.
-Turn it on if you want Claude to find sections the reader cannot place; see
-[When Claude looks at the page](#when-claude-looks-at-the-page).
+### 3. Look at the spending limit (optional)
+
+The Settings page shows one more thing: **Monthly spending limit for Claude**, in US dollars, $200
+to begin with. When this month's estimated cost reaches it, every call to Claude stops: requests,
+plans and the queue's own. Nothing calls Claude again until you raise the limit or the next month
+begins. Pulls that need no help from Claude carry on. Set it to what you are comfortable with, or
+to 0 for no limit, and choose **Save settings**. See [The spending limit](#the-spending-limit).
+
+### Everything else is chosen for you
+
+**Show advanced settings** opens the rest: the models, what Claude may see from a page, the step
+limits, pacing, the library, diagnostics and deleting data. CodePull has chosen values that work,
+and you do not need to change any of them. Two are worth knowing about:
+
+- **Let Claude look at the page when CodePull cannot find a section on it** is on. When the reader
+ cannot place a section, the app sends Claude screenshots of that page, which show code text. Turn
+ it off if you do not want that; see [When Claude looks at the page](#when-claude-looks-at-the-page).
+- **Model for requests** and **Model for project plans** say **Automatic**, with the model that
+ stands for. Pick another from the list if you want one.
## Ask for a section
@@ -171,10 +194,14 @@ The request shows what is happening, one line at a time, and how many steps and
page. You can leave: the pull keeps running in the queue. Once the request has ended, **×** puts its
panel away.
-A request has a limit on its steps (14 by default; 24 for a project plan). A step is one call to
-Claude: it reads what its tools found so far and decides what to do next. Tokens are not capped. At
-the step limit, or after 15 minutes of work, the request stops and asks whether to continue with
-another allowance of the same size. You can change the step limits in **Settings → Claude**.
+A request has a limit on its steps (40; 60 for a project plan), high enough that an ordinary
+request never reaches it. A step is one call to Claude: it reads what its tools found so far and
+decides what to do next. Tokens are not capped. At the step limit, or after 60 minutes of work, the
+request stops and asks whether to continue with another allowance of the same size. The step limits
+are under **Settings → Show advanced settings**.
+
+If the request stops and says **Claude is stopped**, this month's spending limit was reached. Raise
+it in **Settings**, then choose **Continue**. See [The spending limit](#the-spending-limit).
When it finishes you get a summary: what was pulled, from which code, edition and jurisdiction, when,
and anything that was blocked. **Open pull** shows the section. **Edit and start again** puts the
@@ -411,10 +438,9 @@ page that is already open is still pulled, because it needs no page load.
### What Claude costs
Most pulls cost nothing in Claude. Claude is asked about a pull only when the app cannot find its
-page: first to search the code's contents, then, if **Let Claude look at the page** is on, to look at
-the page. Unlike your own requests, both have fixed token budgets that no setting changes, so one
-pull can cost only so much: with Claude Sonnet 5.5 and the look on, about $4.55 at most. If a search
-uses up its budget, the pull stops for you like one CodePull could not find.
+page: first to search the code's contents, then, unless you turned **Let Claude look at the page**
+off, to look at the page. Neither has a token limit. The search has 24 steps and the look 40; if
+either runs out, the pull stops for you like one CodePull could not find.
While pulls are waiting or running, the **Claude cost** panel shows three figures, which update as
each of Claude's replies comes in:
@@ -422,19 +448,41 @@ each of Claude's replies comes in:
- **Spent so far**: what Claude has cost on these pulls, and the tokens.
- **Likely for the rest**: the pulls still to run, at what Claude cost per pull over your last 200
finished pulls. It appears once 10 have finished.
-- **At most for the rest**: the pulls still to run, each at the most Claude can cost on one pull.
+- **Left under your limit**: your monthly spending limit less what Claude has cost this month, for
+ all of its work. This is the most Claude can still cost this month.
The panel covers every plan and request with pulls still open. Filter the queue by plan to see one
plan's figures. While Claude works on a pull, a line under the figures names it and shows its cost so
far, and the same line appears on the pull. A pull Claude was asked about keeps its cost, and each
-plan's progress line shows its total. **Claude settings** opens Settings, where the line under the
-limits shows the most one pull can cost with the model and the look switch as you choose them.
+plan's progress line shows its total. **Claude settings** opens Settings, where the spending limit
+is.
These are estimates from the price list in the app, not a bill. If the list has no price for your
model, amounts show as unknown, and so does work Claude already did on such a model (or "over" the
part that had a price). Without an API key the queue never calls Claude: a pull it cannot find
stops and waits for you, and the panel says so.
+### The spending limit
+
+The monthly spending limit in **Settings** is a kill switch for everything Claude does. Before each
+call to Claude the app adds up what Claude has cost since the first of the month. Once that reaches
+your limit:
+
+- No call to Claude is made, for a request, a plan, the queue's search for a page or a look at a
+ page.
+- A request or plan that was working stops before its next step and asks. Raise the limit and choose
+ **Continue**, or **Stop**.
+- A new request or plan does not start, and says why. An exact section or a page address still
+ works: those never use Claude.
+- The queue keeps pulling what it can read by itself. A pull it cannot place stops with **Claude is
+ stopped** in its reason. After you raise the limit, **Retry** asks Claude as usual.
+- The top bar says **Claude stopped at your limit**.
+
+It lifts when you raise the limit and save, or when the next month begins. The call that carries the
+month past the limit finishes, so the month can end a little above it. The cost is the app's
+estimate from its price list; a model with no listed price counts as nothing. **Delete all content**
+keeps the month's usage, so it does not reset the limit.
+
### Pulls that need attention
A pull that stops shows a reason and the buttons that deal with it.
@@ -445,8 +493,8 @@ A pull that stops shows a reason and the buttons that deal with it.
| Subscription needed | Check the subscription. **Retry** once it is sorted |
| Human check | Complete the check yourself in the account window. Then **Resume account**, and **Resume** on the banner |
| Asked to slow down | Wait. Then **Resume account**, and **Resume** on the banner |
-| Section not found | Check the number. Or start a new request with the page address. With **Let Claude look at the page** on, Claude has already tried to find it on a screenshot |
-| Page not recognised | **Capture by hand**. Consider saving a page outline and exporting diagnostics. The stop says when turning on **Let Claude look at the page** could help; then choose **Retry** |
+| Section not found | Check the number. Or start a new request with the page address. Claude has already searched for the page and, unless you turned **Let Claude look at the page** off, tried to find the section on a screenshot. If the reason says **Claude is stopped**, raise the spending limit in **Settings**, then **Retry** |
+| Page not recognised | **Capture by hand**. Consider saving a page outline and exporting diagnostics. If you turned **Let Claude look at the page** off, the stop says when it could help; turn it on, then choose **Retry** |
| Check failed | The page was read, but the PDF or Word document made from it did not read back the same, so nothing was saved. The pull names the document, the page, the block and the character that differ, never the text. **Retry** reads the same page and ends the same way: it helps only after an update. Export diagnostics from **Settings → Advanced** and send them with the message |
| Network problem | **Retry** |
| Failed: "The page did not answer CodePull" | The page loaded but was too busy to be read, or never finished loading. **Retry** loads it afresh; if it repeats, look at the page in the account window |
@@ -565,8 +613,9 @@ banner** in the account window's toolbar, so the banner on record is one you poi
## When Claude looks at the page
-**Settings → Claude → Let Claude look at the page when CodePull cannot find a section on it** is off
-until you turn it on. Screenshots show code text, and they go to the Anthropic API.
+**Let Claude look at the page when CodePull cannot find a section on it** is on unless you turn it
+off, under **Settings → Show advanced settings**. Screenshots show code text, and they go to the
+Anthropic API: turn it off if you do not want that.
With it on, when a pull's page cannot be read, or its section cannot be placed, the app shows Claude a
screenshot of the page with numbered marks: red on text blocks, blue on links. Claude points at
@@ -577,14 +626,14 @@ section's text from the page between the two marks, with the same checks as a ca
The account window appears without taking the focus while this happens, and hides again afterwards.
A section found this way is saved with **Needs review** and a note: compare where it starts and ends
-with the page before relying on it. If Claude cannot find the section in 15 steps, or within 100,000
-input tokens, the pull stops with Claude's one-line reason. It also stops, with a reason, if Claude
-answers a step without pointing at anything, or reaches its output limit for one step. What the look
+with the page before relying on it. If Claude cannot find the section in 40 steps, the pull stops with Claude's one-line reason. It
+also stops, with a reason, if Claude answers a step without pointing at anything, or when this
+month's spending limit is reached. What the look
cost shows on the pull and in the queue's **Claude cost** panel.
## Starting over
-**Settings → Advanced** has two ways to start over.
+**Settings → Show advanced settings → Data and diagnostics** has two ways to start over.
- **Delete all content** deletes every pull and document, every plan, the pull queue, every request
and the activity log. Your settings, API key, accounts, saved passwords and sign-ins stay, and so
@@ -631,6 +680,8 @@ version's number and, like any web request, your network address. It sends nothi
differently. Once one pull from a code looks right, the rest are read the same way.
- **Leave the pacing alone.** It is set to what one careful person does. Lower it if you like. There
is rarely a reason to raise it.
+- **Leave the advanced settings alone unless you have a reason.** They are chosen to work. The one
+ setting worth a look is the monthly spending limit.
- **Use the page address when in doubt.** It removes any question about which page is meant.
- **Read `GAPS.md` before handing a bundle to anyone.**
- **Treat the plan as a starting list.** It tells you what to read, not what the code requires.
diff --git a/src/agent/budget.ts b/src/agent/budget.ts
index 8dab19e..88a4896 100644
--- a/src/agent/budget.ts
+++ b/src/agent/budget.ts
@@ -3,9 +3,10 @@ import type { RunKind } from './safety';
import type { Pricing } from './services';
/**
- * Hard stops for one run. A user who chooses to continue is granted one more allowance of the same
- * size. Tokens are not capped here: each call may use the model's whole output, and what a run sends
- * is bounded by its steps (see `docs/adr/0007-claude-tool-loop.md`).
+ * Stops for one run. A user who chooses to continue is granted one more allowance of the same size.
+ * Tokens are not capped for any kind of run: each call may use the model's whole output, and what
+ * stops a run that goes in circles is its steps and its working time. What bounds the money is the
+ * month's spending limit, checked before every call (see `docs/adr/0011-chosen-for-the-user.md`).
*/
export interface Limits {
maxIterations: number;
@@ -14,31 +15,31 @@ export interface Limits {
maxToolErrorsInARow: number;
/** Output ceiling for one model call when the Models API did not report the model's own. */
fallbackTokensPerCall: number;
- /**
- * Token budgets, only for the queue's search for a page (`fallback_nav`), which nobody watches.
- * Not a setting: they keep what one queued pull can cost bounded, so the queue can show it
- * (`src/shared/claude-cost.ts`). Requests and plans have none. Input is checked against the request
- * about to be sent, so it never passes its budget; output is checked before each request, so the
- * last reply may cross it by up to one reply.
- */
- tokens?: { input: number; output: number };
}
-export const wallClockMs = 15 * 60_000;
+export const wallClockMs = 60 * 60_000;
export const maxToolErrorsInARow = 3;
/** Used only when the Models API reports no output maximum. Calls are streamed, so size is safe. */
export const fallbackTokensPerCall = 64_000;
-/** What the queue's search for one page may send and receive in all. The owner's choice, 20 November 2026. */
-export const QUEUE_SEARCH_TOKENS = Object.freeze({ input: 150_000, output: 24_000 });
+/**
+ * Steps for the queue's own search for a page (`fallback_nav`). Not a setting: nobody watches that
+ * run, and each step may spend one of the account's paced page loads, so it does not follow the
+ * step limit the user's own requests have.
+ */
+export const QUEUE_SEARCH_STEPS = 24;
export function limitsFor(kind: RunKind, settings: Settings): Limits {
const b = settings.budgets;
return {
- maxIterations: kind === 'project_plan' ? b.planIterations : b.requestIterations,
+ maxIterations:
+ kind === 'project_plan'
+ ? b.planIterations
+ : kind === 'fallback_nav'
+ ? QUEUE_SEARCH_STEPS
+ : b.requestIterations,
wallClockMs,
maxToolErrorsInARow,
fallbackTokensPerCall,
- ...(kind === 'fallback_nav' && { tokens: { ...QUEUE_SEARCH_TOKENS } }),
};
}
@@ -100,26 +101,17 @@ export function addUsage(
return next;
}
-export type BudgetStop = 'iterations' | 'input_tokens' | 'output_tokens' | 'wall_clock';
+export type BudgetStop = 'iterations' | 'wall_clock';
-/**
- * Which limit, if any, the run has reached with the allowances granted so far. `nextInput` is an
- * upper bound on the input of the request about to be sent, for a run with token budgets.
- */
+/** Which limit, if any, the run has reached with the allowances granted so far. */
export function budgetStop(
usage: RunUsage,
limits: Limits,
allowances: number,
activeMs: number,
- nextInput = 0,
): BudgetStop | undefined {
const granted = Math.max(1, allowances);
if (usage.iterations >= limits.maxIterations * granted) return 'iterations';
- if (limits.tokens) {
- const sent = usage.input + usage.cacheRead + usage.cacheWrite;
- if (sent + nextInput > limits.tokens.input * granted) return 'input_tokens';
- if (usage.output >= limits.tokens.output * granted) return 'output_tokens';
- }
if (activeMs >= limits.wallClockMs * granted) return 'wall_clock';
return undefined;
}
@@ -129,11 +121,9 @@ export function describeStop(stop: BudgetStop, limits: Limits): string {
switch (stop) {
case 'iterations':
return `its limit of ${n(limits.maxIterations)} steps`;
- case 'input_tokens':
- return `its budget of ${n(limits.tokens?.input ?? 0)} input tokens`;
- case 'output_tokens':
- return `its budget of ${n(limits.tokens?.output ?? 0)} output tokens`;
case 'wall_clock':
return `its time limit of ${n(Math.round(limits.wallClockMs / 60_000))} minutes`;
}
}
+
+export { type SpendState, spendState, spendStopMessage } from '../shared/claude-cost';
diff --git a/src/agent/client.ts b/src/agent/client.ts
index b6d7d0e..25cf627 100644
--- a/src/agent/client.ts
+++ b/src/agent/client.ts
@@ -7,11 +7,17 @@ import type { ModelPrice, Pricing } from './services';
export type ClientFactory = (key: string) => Anthropic;
export type ModelRole = 'agent' | 'planner';
-export type Effort = 'low' | 'medium' | 'high';
+export type Effort = NonNullable[number];
+/** Every effort level, lowest first. */
+export const EFFORTS: readonly Effort[] = ['low', 'medium', 'high', 'xhigh', 'max'];
+/** What a model list saved before levels were recorded is read as offering. */
+const EARLIER_EFFORTS: readonly Effort[] = ['low', 'medium', 'high'];
/** Shipped preferences. The user's own pick in Settings always wins over these. */
export interface ModelDefaults {
roles: Record;
+ /** One look at a page (the screenshot fallback): pointing at a number is a short, checked step. */
+ look: { effort: Effort };
/** Per-model request options that only some model families accept. */
models: Record;
}
@@ -43,7 +49,12 @@ export async function listModels(
seen.add(info.id);
const model: Model = { id: info.id, name: info.display_name || info.id };
if (positive(info.max_tokens)) model.maxOutputTokens = info.max_tokens;
- if (info.capabilities?.effort?.supported === true) model.effort = true;
+ const effort = info.capabilities?.effort;
+ if (effort?.supported === true) {
+ model.effort = true;
+ const levels = EFFORTS.filter((level) => effort[level]?.supported === true);
+ if (levels.length) model.efforts = levels;
+ }
const strict = info.capabilities?.structured_outputs?.supported;
if (typeof strict === 'boolean') model.structuredOutputs = strict;
models.push(model);
@@ -57,6 +68,36 @@ export function pickModel(role: ModelRole, available: Model[], defaults: ModelDe
return available[0]?.id ?? '';
}
+/**
+ * The model a role uses: the user's own pick while the key offers it, otherwise the automatic
+ * choice. An empty pick means automatic (`Settings.model`).
+ */
+export function resolveModel(
+ role: ModelRole,
+ chosen: string,
+ available: Model[],
+ defaults: ModelDefaults,
+): string {
+ return chosen && available.some((model) => model.id === chosen)
+ ? chosen
+ : pickModel(role, available, defaults);
+}
+
+/**
+ * The effort to send for a wanted level: the highest level the model offers that is not above it.
+ * Nothing for a model without the effort control, which is then left at its own default.
+ */
+export function effortFor(
+ model: Pick | undefined,
+ wanted: Effort,
+): Effort | undefined {
+ if (!model?.effort) return undefined;
+ const offered = model.efforts?.length ? model.efforts : EARLIER_EFFORTS;
+ for (let rank = EFFORTS.indexOf(wanted); rank >= 0; rank--)
+ if (offered.includes(EFFORTS[rank]!)) return EFFORTS[rank];
+ return undefined;
+}
+
/** A message that is safe to show and to log. */
export function sanitizeError(err: unknown): string {
const message = err instanceof Error ? err.message : 'Operation failed.';
@@ -136,23 +177,26 @@ export function readPricing(raw: Record): Pricing {
}
export function readModelDefaults(raw: Record): ModelDefaults {
const roles = (raw.roles ?? {}) as Record;
+ const level = (value: unknown, fallback: Effort): Effort =>
+ EFFORTS.includes(value as Effort) ? (value as Effort) : fallback;
const role = (name: ModelRole, effort: Effort) => {
const entry = roles[name] ?? {};
return {
prefer: Array.isArray(entry.prefer)
? entry.prefer.filter((id): id is string => typeof id === 'string')
: [],
- effort:
- entry.effort === 'low' || entry.effort === 'medium' || entry.effort === 'high'
- ? entry.effort
- : effort,
+ effort: level(entry.effort, effort),
};
};
const models: ModelDefaults['models'] = {};
for (const [id, entry] of Object.entries((raw.models ?? {}) as Record))
if (entry && typeof entry === 'object')
models[id] = { fallbacks: (entry as { fallbacks?: unknown }).fallbacks === true };
- return { roles: { agent: role('agent', 'medium'), planner: role('planner', 'high') }, models };
+ return {
+ roles: { agent: role('agent', 'high'), planner: role('planner', 'xhigh') },
+ look: { effort: level((raw.look as { effort?: unknown } | undefined)?.effort, 'medium') },
+ models,
+ };
}
/** The assets directory beside the compiled or source tree, in development and inside the package. */
diff --git a/src/agent/index.ts b/src/agent/index.ts
index eca771d..6605154 100644
--- a/src/agent/index.ts
+++ b/src/agent/index.ts
@@ -9,6 +9,8 @@ export {
clientFor,
defaultAssetsDir,
type Effort,
+ effortFor,
+ EFFORTS,
listModels,
loadAgentAssets,
type ModelDefaults,
@@ -17,6 +19,7 @@ export {
publicApiError,
readModelDefaults,
readPricing,
+ resolveModel,
sanitizeError,
} from './client';
export {
diff --git a/src/agent/runtime.ts b/src/agent/runtime.ts
index 32bfa83..50cc678 100644
--- a/src/agent/runtime.ts
+++ b/src/agent/runtime.ts
@@ -9,13 +9,17 @@ import {
emptyUsage,
type Limits,
limitsFor,
+ type SpendState,
+ spendStopMessage,
} from './budget';
import {
type AgentAssets,
type ClientFactory,
clientFor,
+ effortFor,
loadAgentAssets,
publicApiError,
+ resolveModel,
} from './client';
import { buildSystemPrompt, firstUserMessage, promptHash } from './prompts';
import {
@@ -53,7 +57,10 @@ export interface RunSpec {
/** JSON-serializable data placed after the request in the first user message (e.g. previous facts). */
context?: Record;
options: RunRecord['options'];
- /** Default: `settings().model`, or `settings().plannerModel` for a project plan. */
+ /**
+ * Default: the user's pick for the kind of run (`settings().model`, or `plannerModel` for a
+ * project plan) while the key offers it, otherwise the automatic choice.
+ */
model?: string;
/** The queue job the run works for, so what it costs shows on that job. */
jobId?: string;
@@ -74,6 +81,11 @@ export type RuntimeDeps = AgentDeps & {
assets?: Pick;
/** The models the saved key can call. Without it, model limits and effort support are unknown. */
models?: () => Model[];
+ /**
+ * The month's spending against the user's limit, read before a run starts and before every call
+ * to Claude. While it is reached, nothing is sent. Without it there is no limit.
+ */
+ spend?: () => SpendState;
};
/**
@@ -93,6 +105,8 @@ interface Header {
pinnedAccountId?: string;
/** Set when the API rejected the fallback opt-in, so later calls leave it out. */
fallbacksOff?: boolean;
+ /** The run is waiting at the month's spending limit, not at a limit of its own. */
+ spendStop?: boolean;
/** A turn that asked the user: its other results, in call order, with a gap for the answer. */
pending?: { toolUseId: string; results: (ToolResultBlock | null)[] };
/** The transcript was reduced after the run ended and can no longer be resumed. */
@@ -108,12 +122,6 @@ interface Live {
controller: AbortController;
/** When the current stretch of work began, for the wall-clock limit. */
since: number;
- /**
- * An upper bound on the input tokens of the next request: the last request's input, its reply,
- * and the bytes of what was added after it (a token is never shorter than a byte). Unknown, and
- * 0, before the first reply of this stretch of work.
- */
- nextInput?: number;
}
const fallbackBeta = 'server-side-fallback-2026-07-01';
@@ -405,15 +413,43 @@ export function createRuntime(deps: RuntimeDeps): AgentRuntime {
return checked.def.progress(checked.args as never);
}
- /** One model call. Re-issues a turn whose streamed tool input could not be parsed. */
+ /**
+ * The kill switch: at the month's spending limit the run stops and waits, and nothing is sent.
+ * True when it did. Asked before every request, a request sent again included.
+ */
+ function heldAtSpendLimit(state: Live): boolean {
+ const spend = deps.spend?.();
+ if (!spend?.reached) return false;
+ state.header.spendStop = true;
+ suspend(
+ state,
+ {
+ text: spendStopMessage(spend) + ' Then choose Continue.',
+ options: ['Continue', 'Stop'],
+ allowFreeText: false,
+ kind: 'budget',
+ },
+ 'Reached the spending limit for this month. Waiting for your decision.',
+ );
+ return true;
+ }
+
+ /**
+ * One model call. Re-issues a turn whose streamed tool input could not be parsed. Resolves to
+ * nothing when the month's spending limit was reached before it could be sent again: the run is
+ * then waiting for the user.
+ */
async function request(
state: Live,
client: Anthropic,
body: StreamParams,
pricing: ReturnType,
- ): Promise {
+ ): Promise {
const signal = state.controller.signal;
for (let attempt = 0; ; attempt++) {
+ // A request sent again is a request: the limit may have been reached by the attempt before
+ // it, or by other work meanwhile.
+ if (attempt > 0 && heldAtSpendLimit(state)) return undefined;
const { fallbacks: _fallbacks, betas: _betas, ...plain } = body;
const params = state.header.fallbacksOff ? (plain as StreamParams) : body;
let stream: ReturnType | undefined;
@@ -421,9 +457,13 @@ export function createRuntime(deps: RuntimeDeps): AgentRuntime {
stream = client.beta.messages.stream(params, { signal });
return await stream.finalMessage();
} catch (error) {
- // An interrupted stream can still carry usage the provider bills.
+ // An interrupted stream can still carry usage the provider bills. It is recorded at once,
+ // so the month's spending counts it before anything else is sent.
const partial = stream?.currentMessage?.usage;
- if (partial) state.run.usage = addUsage(state.run.usage, partial, state.run.model, pricing);
+ if (partial) {
+ state.run.usage = addUsage(state.run.usage, partial, state.run.model, pricing);
+ persist(state);
+ }
if (signal.aborted) throw error;
if (
error instanceof Anthropic.BadRequestError &&
@@ -461,9 +501,10 @@ export function createRuntime(deps: RuntimeDeps): AgentRuntime {
}
const model = deps.models?.().find((entry) => entry.id === run.model);
const defaults = assets().modelDefaults;
- const effort = model?.effort
- ? defaults.roles[run.kind === 'project_plan' ? 'planner' : 'agent'].effort
- : undefined;
+ const effort = effortFor(
+ model,
+ defaults.roles[run.kind === 'project_plan' ? 'planner' : 'agent'].effort,
+ );
// No output cap of the app's own: each call may use the model's whole output.
const maxTokens = model?.maxOutputTokens ?? limits.fallbackTokensPerCall;
const fallbacks = defaults.models[run.model]?.fallbacks === true;
@@ -484,12 +525,13 @@ export function createRuntime(deps: RuntimeDeps): AgentRuntime {
'Text sharing was lowered while this request was running. Start it again: nothing gathered under the old setting is sent again.',
);
header.sharing = sharing;
+ // The kill switch: at the month's spending limit nothing is sent, whatever the run is for.
+ if (heldAtSpendLimit(state)) return;
const stop: BudgetStop | undefined = budgetStop(
run.usage,
limits,
header.allowances,
activeMs(state),
- state.nextInput,
);
if (stop)
return suspend(
@@ -517,14 +559,9 @@ export function createRuntime(deps: RuntimeDeps): AgentRuntime {
};
scanOutbound(body, secrets);
const message = await request(state, client, body, pricing);
+ if (!message) return;
run.usage = addUsage(run.usage, message.usage, run.model, pricing);
run.usage.iterations += 1;
- // The next request carries all of this one and its reply, then whatever is added below.
- state.nextInput =
- (message.usage.input_tokens ?? 0) +
- (message.usage.cache_read_input_tokens ?? 0) +
- (message.usage.cache_creation_input_tokens ?? 0) +
- (message.usage.output_tokens ?? 0);
if (message.stop_reason === 'refusal') return finish(state, 'failed', refusalMessage);
if (
message.stop_reason === 'max_tokens' ||
@@ -548,7 +585,6 @@ export function createRuntime(deps: RuntimeDeps): AgentRuntime {
const results = await runTurn(state, turn.calls, settings);
if (!results) return;
state.api.push({ role: 'user', content: results });
- state.nextInput += Buffer.byteLength(JSON.stringify(results));
persist(state);
if (header.errorStreak >= limits.maxToolErrorsInARow)
return finish(
@@ -588,9 +624,15 @@ export function createRuntime(deps: RuntimeDeps): AgentRuntime {
function start(spec: RunSpec) {
const settings = deps.settings();
const at = iso();
+ const known = deps.models?.();
+ const planning = spec.kind === 'project_plan';
+ const picked = planning ? settings.plannerModel : settings.model;
+ // An empty pick is the automatic choice; so is a pick the key no longer offers.
const model =
spec.model ||
- (spec.kind === 'project_plan' ? settings.plannerModel || settings.model : settings.model);
+ (known
+ ? resolveModel(planning ? 'planner' : 'agent', picked, known, assets().modelDefaults)
+ : picked || settings.model);
const toolDefinitions = apiTools(spec.kind);
const notes = deps.siteNotes();
const system = buildSystemPrompt(assets().systemPrompt, notes, settings);
@@ -631,14 +673,16 @@ export function createRuntime(deps: RuntimeDeps): AgentRuntime {
run.messages = [state.header, ...state.api];
deps.runs.create(run);
notify();
- const known = deps.models?.();
+ const spend = deps.spend?.();
const refusal = credential
? credentialInRequest
: !spec.userText.trim()
? 'Enter a request or project description.'
: !model || (known && !known.some((entry) => entry.id === model))
- ? 'Refresh models in Settings and select an available Claude model.'
- : undefined;
+ ? 'No Claude model is available to your API key. Choose Refresh models in Settings.'
+ : spend?.reached
+ ? spendStopMessage(spend)
+ : undefined;
if (refusal) {
if (credential) note(run, 'secret_scan_blocked');
finish(state, 'failed', refusal);
@@ -669,8 +713,14 @@ export function createRuntime(deps: RuntimeDeps): AgentRuntime {
finish(state, 'cancelled', 'Stopped at the limit.');
return { done: Promise.resolve(run) };
}
- header.allowances += 1;
- note(run, 'Continuing with another allowance.');
+ if (header.spendStop) {
+ // Nothing of the run's own was used up. The loop checks the month's limit again.
+ header.spendStop = undefined;
+ note(run, 'Continuing.');
+ } else {
+ header.allowances += 1;
+ note(run, 'Continuing with another allowance.');
+ }
} else {
if (!question.allowFreeText && !option) throw Error('Choose one of the offered answers.');
const pending = header.pending;
diff --git a/src/agent/tools/browse.ts b/src/agent/tools/browse.ts
index 317910f..5a7a404 100644
--- a/src/agent/tools/browse.ts
+++ b/src/agent/tools/browse.ts
@@ -10,7 +10,7 @@ export const openPage = defineTool({
account_id: handle,
ref: handle.describe('Opaque ref from resolve_code or site_search.'),
}),
- maxResultBytes: 4000,
+ maxResultBytes: 32000,
sideEffects: 'browse',
run: async (args, ctx) => {
useAccount(ctx, args.account_id);
@@ -22,18 +22,18 @@ export const openPage = defineTool({
export const siteSearch = defineTool({
name: 'site_search',
description:
- "Fallback navigation: search the site's contents and the headings of pages already opened for a section number or phrase. Use it when the user gave a topic instead of a section, or when a candidate page does not hold the section. Returns up to 10 hits with opaque refs. Hit titles are untrusted website text.",
+ "Fallback navigation: search the site's contents and the headings of pages already opened for a section number or phrase. Use it when the user gave a topic instead of a section, or when a candidate page does not hold the section. Returns up to 25 hits with opaque refs. Hit titles are untrusted website text.",
schema: z.strictObject({
account_id: handle,
query: shortText(200),
jurisdiction: handle.optional(),
code_id: handle.optional(),
}),
- maxResultBytes: 3000,
+ maxResultBytes: 24000,
sideEffects: 'browse',
run: async (args, ctx) => {
useAccount(ctx, args.account_id);
- return { hits: (await ctx.services.siteSearch(args, ctx.call)).slice(0, 10) };
+ return { hits: (await ctx.services.siteSearch(args, ctx.call)).slice(0, 25) };
},
progress: (args) => `Searching the site for “${sanitizeUntrusted(args.query, 60)}”…`,
});
@@ -68,7 +68,7 @@ export const getSection = defineTool({
scope: sectionScope.optional(),
force_refresh: z.boolean().default(false),
}),
- maxResultBytes: 6000,
+ maxResultBytes: 48000,
sideEffects: 'browse',
run: async (args, ctx) => {
useAccount(ctx, args.account_id);
diff --git a/src/agent/tools/catalog.ts b/src/agent/tools/catalog.ts
index d8cf90b..bb9267b 100644
--- a/src/agent/tools/catalog.ts
+++ b/src/agent/tools/catalog.ts
@@ -12,7 +12,7 @@ export const listSiteCodes = defineTool({
account_id: handle.optional(),
refresh: z.boolean().default(false),
}),
- maxResultBytes: 8000,
+ maxResultBytes: 64000,
sideEffects: 'browse',
run: async (args, ctx) => {
// A run stays with one account. Without one named here, use the one it already has.
@@ -40,7 +40,7 @@ export const resolveCode = defineTool({
scope: z.strictObject({ kind: scopeKind }).optional(),
text_basis: textBasis.default('jurisdiction_adopted'),
}),
- maxResultBytes: 4000,
+ maxResultBytes: 32000,
sideEffects: 'none',
run: (args, ctx) => ({ ...ctx.services.resolveCode(args) }),
progress: (args) =>
diff --git a/src/agent/tools/documents.ts b/src/agent/tools/documents.ts
index 9a641be..a92c4f5 100644
--- a/src/agent/tools/documents.ts
+++ b/src/agent/tools/documents.ts
@@ -12,7 +12,7 @@ export const verify = defineTool({
schema: z
.strictObject({ candidate_id: handle.optional(), pull_id: handle.optional() })
.refine(oneId, oneIdMessage),
- maxResultBytes: 3000,
+ maxResultBytes: 24000,
sideEffects: 'none',
run: (args, ctx) => ({ ...ctx.services.verify(args) }),
progress: () => 'Verifying…',
@@ -36,7 +36,7 @@ export const renderDocument = defineTool({
include_adoption_table: z.boolean().optional(),
})
.refine(oneId, oneIdMessage),
- maxResultBytes: 1500,
+ maxResultBytes: 12000,
sideEffects: 'writes_library',
run: async (args, ctx) => ({ ...(await ctx.services.renderDocument(args, ctx.call)) }),
progress: () => 'Rendering the document…',
@@ -64,7 +64,7 @@ export const savePull = defineTool({
.optional()
.describe('A short remark for the library. Never document text.'),
}),
- maxResultBytes: 1000,
+ maxResultBytes: 8000,
sideEffects: 'writes_library',
run: async (args, ctx) => ({
// `identity_confirmed` is a gate for Claude, not something the service stores.
diff --git a/src/agent/tools/library.ts b/src/agent/tools/library.ts
index c91a713..e186c82 100644
--- a/src/agent/tools/library.ts
+++ b/src/agent/tools/library.ts
@@ -9,7 +9,7 @@ export const listAccounts = defineTool({
schema: z.strictObject({
site_id: handle.optional().describe("e.g. 'upcodes'. Omit to list every site."),
}),
- maxResultBytes: 2000,
+ maxResultBytes: 16000,
sideEffects: 'none',
// Only these fields ever reach Claude. A login hint, cookie or credential is never one of them.
run: (args, ctx) => ({
@@ -38,7 +38,7 @@ export const searchLibrary = defineTool({
section: handle.optional(),
limit: z.number().int().min(1).max(25).default(10),
}),
- maxResultBytes: 6000,
+ maxResultBytes: 48000,
sideEffects: 'none',
run: (args, ctx) => ({ hits: ctx.services.searchLibrary(args) }),
progress: () => 'Checking the library…',
@@ -49,7 +49,7 @@ export const listXrefs = defineTool({
description:
'List cross-reference candidates found in a saved pull: section references in the same code, NFPA extract locators and external standards. Context around each reference is included only when the user enabled text sharing. Extract locators and external standards are listed for the reader and are never followed.',
schema: z.strictObject({ pull_id: handle }),
- maxResultBytes: 6000,
+ maxResultBytes: 48000,
sideEffects: 'none',
run: (args, ctx) => {
const refs = ctx.services.listXrefs(args.pull_id);
@@ -68,7 +68,7 @@ export const readExcerpt = defineTool({
description:
"Return a bounded excerpt (at most 800 characters) of a saved pull's text by block range, ONLY if the user enabled text sharing. Use it for relevance judgments, never for reproduction. Returns an error if text sharing is off.",
schema: z.strictObject({ pull_id: handle, from_block: handle, to_block: handle }),
- maxResultBytes: 2000,
+ maxResultBytes: 16000,
sideEffects: 'none',
run: (args, ctx) => {
if (ctx.settings.textSharing !== 'excerpts')
diff --git a/src/agent/tools/planning.ts b/src/agent/tools/planning.ts
index a7dcf4a..31b0bd2 100644
--- a/src/agent/tools/planning.ts
+++ b/src/agent/tools/planning.ts
@@ -16,7 +16,7 @@ export const askUser = defineTool({
options: z.array(shortText(120)).max(6).optional(),
allow_free_text: z.boolean().default(true),
}),
- maxResultBytes: 3000,
+ maxResultBytes: 24000,
sideEffects: 'asks_user',
run: () => {
throw new ServiceError('needs_user', 'The run is waiting for the user.');
@@ -29,7 +29,7 @@ export const recordProjectFacts = defineTool({
description:
"Store structured code-driving facts extracted from the user's project description. Call it once, before drafting a plan. Mark unknowns explicitly and never invent a value. A fact the user stated must quote the user's own words in source_quote; a reasoned conclusion is 'inferred'. Give every fact a short unique id so plan items can cite it.",
schema: projectFactsSchema,
- maxResultBytes: 3000,
+ maxResultBytes: 24000,
sideEffects: 'writes_queue',
run: (facts, ctx) => {
const { fact_ids } = ctx.services.recordProjectFacts(facts, ctx.call);
@@ -60,7 +60,7 @@ export const planPulls = defineTool({
title: shortText(120),
items: z.array(planItem).min(1).max(60),
}),
- maxResultBytes: 6000,
+ maxResultBytes: 48000,
sideEffects: 'writes_queue',
run: (args, ctx) => ({ ...ctx.services.planPulls(args, ctx.call) }),
progress: (args) =>
@@ -87,7 +87,7 @@ export const enqueue = defineTool({
.refine((args) => !!args.plan_id !== !!args.single, {
message: 'Give exactly one of plan_id or single.',
}),
- maxResultBytes: 2000,
+ maxResultBytes: 16000,
sideEffects: 'writes_queue',
run: (args, ctx) => {
if (args.single) useAccount(ctx, args.single.account_id);
diff --git a/src/agent/visual.ts b/src/agent/visual.ts
index 21dccf7..ca6fac4 100644
--- a/src/agent/visual.ts
+++ b/src/agent/visual.ts
@@ -3,7 +3,8 @@ import { z } from 'zod';
import type { PageMark } from '../extract/marks';
import type { Model, RunUsage } from '../shared/bridge';
import { BlockedError, type CaptureTarget, type SourceCapture } from '../sites/adapter';
-import { addUsage } from './budget';
+import { addUsage, fallbackTokensPerCall, type SpendState, spendStopMessage } from './budget';
+import type { Effort } from './client';
import { sanitizeUntrusted, scanOutbound } from './safety';
import type { Pricing } from './services';
@@ -16,20 +17,15 @@ interface Message {
}
/**
- * Hard limits for one look at a page. No setting raises them. `maxTokens` is the most one step may
- * ask for, thinking included; a model whose own cap is lower gets its own cap. `inputTokens` is what
- * the look may send in all, checked before each request, so what one look can cost has a ceiling the
- * queue can show.
+ * Limits for one look at a page. No setting raises them. They stop a look that goes in circles and
+ * keep it to a few paced page loads; none of them is a token limit. Each step may use the model's
+ * whole output, thinking included, and what bounds the money is the month's spending limit.
*/
export const VISUAL_LIMITS = Object.freeze({
- actions: 15,
+ actions: 40,
marks: 80,
- maxTokens: 16_000,
pageLoads: 4,
- inputTokens: 100_000,
});
-/** Pointing at a number is a short step. Sent only to a model that reports the effort control. */
-export const VISUAL_EFFORT = 'low';
/** What the navigator may do on the page. Every action is carried out and checked by app code. */
export interface VisualPage {
@@ -54,11 +50,14 @@ export interface VisualDeps {
client: Anthropic;
model: string;
/**
- * What the Models API reported for `model`: its output cap, whether it takes the effort control,
- * and whether it keeps to a strict tool schema. Unknown values fall back to the hard limits,
- * no effort setting, and strict tools.
+ * What the Models API reported for `model`: its output cap and whether it keeps to a strict tool
+ * schema. Unknown values fall back to `fallbackTokensPerCall` and strict tools.
*/
- modelInfo?: Pick;
+ modelInfo?: Pick;
+ /** The effort for each step, already fitted to the model (`effortFor`). Nothing: its default. */
+ effort?: Effort;
+ /** The month's spending against the user's limit, read before every request. */
+ spend?: () => SpendState;
/** The key and any other values no request may carry. */
secrets: string[];
pricing?: Pricing;
@@ -256,14 +255,6 @@ export async function lookForSection(deps: VisualDeps): Promise {
};
let started = false;
let loads = 0;
- /**
- * An upper bound on the input of the next request, so the look never sends past its input limit:
- * the last request, its reply, and the text added since. Each request carries one screenshot of
- * the same window, which replaces the one before; a larger one adds its extra pixels at the
- * documented rate of one token per 750. Leaving out older reasoning only makes a request smaller.
- */
- let nextInput = 0;
- let shotPixels = 0;
const transcript: Message[] = [];
let note = 'This is the page CodePull has open.';
@@ -275,10 +266,6 @@ export async function lookForSection(deps: VisualDeps): Promise {
} finally {
await page.clearMarks();
}
- // Compared with the screenshot in the last request, which this one replaces.
- const pixels = pngPixels(png);
- if (pixels > shotPixels && shotPixels) nextInput += Math.ceil((pixels - shotPixels) / 750);
- if (pixels) shotPixels = pixels;
const openable = marks.filter((m) => m.kind === 'link' && m.href && deps.permitted(m.href));
const text = [
note,
@@ -301,7 +288,8 @@ export async function lookForSection(deps: VisualDeps): Promise {
};
const info = deps.modelInfo;
- const maxTokens = Math.min(info?.maxOutputTokens ?? VISUAL_LIMITS.maxTokens, VISUAL_LIMITS.maxTokens);
+ // No output cap of the app's own: a step that thinks long still gets to point.
+ const maxTokens = info?.maxOutputTokens ?? fallbackTokensPerCall;
const toolDefinitions = visualTools(info?.structuredOutputs !== false);
let view = await look();
@@ -310,9 +298,9 @@ export async function lookForSection(deps: VisualDeps): Promise {
deps.signal?.throwIfAborted();
if (step > VISUAL_LIMITS.actions)
throw new VisualGiveUp(`Claude did not find the section within ${VISUAL_LIMITS.actions} steps.`);
- const sent = usage.input + usage.cacheRead + usage.cacheWrite;
- if (sent + nextInput > VISUAL_LIMITS.inputTokens)
- throw new VisualGiveUp('Claude did not find the section within the token limit for one look.');
+ // The kill switch: at the month's spending limit nothing is sent.
+ const spend = deps.spend?.();
+ if (spend?.reached) throw new VisualGiveUp(spendStopMessage(spend));
const messages = outgoing(transcript);
const body: StreamParams = {
model: deps.model,
@@ -322,7 +310,7 @@ export async function lookForSection(deps: VisualDeps): Promise {
// A forced tool choice is refused by some models. The system prompt asks for exactly one
// call, strict schemas keep its arguments to the tool's shape, and no call is a give-up.
tool_choice: { type: 'auto', disable_parallel_tool_use: true },
- ...(info?.effort ? { output_config: { effort: VISUAL_EFFORT } } : {}),
+ ...(deps.effort ? { output_config: { effort: deps.effort } } : {}),
messages: messages as StreamParams['messages'],
};
// The screenshot is base64 image data; the scan reads every text part of the request.
@@ -331,16 +319,11 @@ export async function lookForSection(deps: VisualDeps): Promise {
usage = addUsage(usage, reply.usage, deps.model, deps.pricing);
usage.iterations += 1;
deps.usage(usage);
- nextInput =
- (reply.usage.input_tokens ?? 0) +
- (reply.usage.cache_read_input_tokens ?? 0) +
- (reply.usage.cache_creation_input_tokens ?? 0) +
- (reply.usage.output_tokens ?? 0);
if (reply.stop_reason === 'refusal') throw new VisualGiveUp('Claude declined to look at this page.');
// A step cut short may hold a tool call with half its arguments. Nothing from it is acted on.
if (reply.stop_reason === 'max_tokens')
throw new VisualGiveUp(
- `Claude reached its limit of ${maxTokens.toLocaleString('en-US')} output tokens for one step before pointing at anything.`,
+ 'Claude reached the most this model can write in one step before pointing at anything.',
);
if (reply.stop_reason === 'model_context_window_exceeded')
throw new VisualGiveUp('The look at this page grew past what Claude can read in one request.');
@@ -440,17 +423,9 @@ export async function lookForSection(deps: VisualDeps): Promise {
],
};
transcript.push(answer);
- // A token is never shorter than a byte. The line that replaces the earlier screenshot is counted too.
- nextInput += Buffer.byteLength(JSON.stringify(withoutImages(answer))) + 64;
}
}
-/** Width times height of a PNG, from its header. 0 when the bytes are not a PNG. */
-function pngPixels(png: Buffer): number {
- if (png.length < 24 || png.toString('ascii', 12, 16) !== 'IHDR') return 0;
- return png.readUInt32BE(16) * png.readUInt32BE(20);
-}
-
/** The reader refused the selection itself: a boundary Claude can move. Never a stop. */
function selectionRefused(error: unknown): boolean {
return (
diff --git a/src/db/migrations/0010_chosen_for_the_user.sql b/src/db/migrations/0010_chosen_for_the_user.sql
new file mode 100644
index 0000000..705e4bb
--- /dev/null
+++ b/src/db/migrations/0010_chosen_for_the_user.sql
@@ -0,0 +1,31 @@
+-- CodePull now chooses Claude's settings for the user (1 December 2026). Stored preferences hold
+-- every value, so an install that already exists would keep the earlier defaults for ever. This
+-- moves it to the new ones once. A value the user changed by hand stays as it is.
+
+-- Models. The app cannot tell a model it picked itself from one the user picked, so both go back to
+-- automatic (an empty pick) once. Automatic follows the preferences shipped with the app.
+UPDATE settings
+ SET value_json = json_set(value_json, '$.model', '', '$.plannerModel', '')
+ WHERE key = 'preferences' AND json_valid(value_json);
+
+-- Step limits and the largest plan. A stored value that still equals the earlier default is taken
+-- out, so the new default applies.
+UPDATE settings
+ SET value_json = json_remove(value_json, '$.budgets.requestIterations')
+ WHERE key = 'preferences' AND json_valid(value_json)
+ AND json_extract(value_json, '$.budgets.requestIterations') = 14;
+UPDATE settings
+ SET value_json = json_remove(value_json, '$.budgets.planIterations')
+ WHERE key = 'preferences' AND json_valid(value_json)
+ AND json_extract(value_json, '$.budgets.planIterations') = 24;
+UPDATE settings
+ SET value_json = json_remove(value_json, '$.budgets.maxPlanItems')
+ WHERE key = 'preferences' AND json_valid(value_json)
+ AND json_extract(value_json, '$.budgets.maxPlanItems') = 30;
+
+-- Looking at the page is on by default now. It was off unless the user turned it on, so a stored
+-- "off" is the earlier default, not a choice: it is taken out once. The user can turn it off again.
+UPDATE settings
+ SET value_json = json_remove(value_json, '$.visualFallback')
+ WHERE key = 'preferences' AND json_valid(value_json)
+ AND json_extract(value_json, '$.visualFallback') = 0;
diff --git a/src/db/migrations/0011_claude_months.sql b/src/db/migrations/0011_claude_months.sql
new file mode 100644
index 0000000..6793d29
--- /dev/null
+++ b/src/db/migrations/0011_claude_months.sql
@@ -0,0 +1,22 @@
+-- What Claude cost in each calendar month (UTC), counted when each reply is recorded. The month's
+-- spending limit is checked against this, and the top bar shows it. Counting by the month a run
+-- began would miss the calls of a run that is continued in a later month.
+--
+-- Not content: "Delete all content" keeps it, so deleting does not reset the limit.
+CREATE TABLE claude_months (
+ month TEXT PRIMARY KEY,
+ -- Everything sent: plain input, cache reads and cache writes.
+ input_tokens INTEGER NOT NULL DEFAULT 0,
+ output_tokens INTEGER NOT NULL DEFAULT 0,
+ est_cost_usd REAL NOT NULL DEFAULT 0
+);
+
+-- Runs recorded before this table carry no date for each reply, so each counts in the month it
+-- began: the figure the top bar showed for them until now.
+INSERT INTO claude_months(month, input_tokens, output_tokens, est_cost_usd)
+SELECT substr(created_at, 1, 7),
+ SUM(input_tokens + cache_read_tokens + cache_write_tokens),
+ SUM(output_tokens),
+ SUM(est_cost_usd)
+ FROM agent_runs
+ GROUP BY substr(created_at, 1, 7);
diff --git a/src/db/store.ts b/src/db/store.ts
index 04705bf..93d3427 100644
--- a/src/db/store.ts
+++ b/src/db/store.ts
@@ -201,26 +201,19 @@ export class Store {
: [];
}
/**
- * Save the model list. A role whose saved choice is no longer offered falls back to `pick`,
- * which reads the shipped role defaults. No model ID is fixed in source.
+ * Save the model list. A model the user picked by hand that is no longer offered goes back to
+ * automatic (an empty pick), which follows the shipped role defaults. No model ID is fixed in
+ * source, and none is written here: the automatic choice is worked out when it is used.
*/
- setModels(
- models: Model[],
- pick: (role: 'agent' | 'planner', available: Model[]) => string = () => '',
- ) {
+ setModels(models: Model[]) {
const settings = this.settings();
- const offered = (id: string) => models.some((m) => m.id === id);
- const choose = (current: string, role: 'agent' | 'planner') => {
- if (offered(current)) return current;
- const preferred = models.length ? pick(role, models) : '';
- return offered(preferred) ? preferred : (models[0]?.id ?? '');
- };
+ const keep = (current: string) => (models.some((m) => m.id === current) ? current : '');
this.tx(() => {
this.set('models', models);
this.set('preferences', {
...settings,
- model: choose(settings.model, 'agent'),
- plannerModel: choose(settings.plannerModel, 'planner'),
+ model: keep(settings.model),
+ plannerModel: keep(settings.plannerModel),
});
});
}
@@ -594,6 +587,20 @@ export class Store {
return claude ? { ...job, claude } : job;
});
}
+ /**
+ * What Claude has cost in the calendar month of `monthStart` (any ISO date in it), by the price
+ * list. The month's spending limit is checked against this, and it is the same figure the top bar
+ * shows. Each reply is counted in the month it was recorded (`claude_months`, kept by
+ * `runs.save`), so a run begun last month and continued in this one counts here for what it
+ * costs here. Deleting content does not touch it.
+ */
+ monthSpend(monthStart: string): { input: number; output: number; estCostUsd: number } {
+ const r = this.one(
+ 'SELECT input_tokens i,output_tokens o,est_cost_usd c FROM claude_months WHERE month=?',
+ monthStart.slice(0, 7),
+ );
+ return { input: Number(r?.i ?? 0), output: Number(r?.o ?? 0), estCostUsd: Number(r?.c ?? 0) };
+ }
/**
* The last finished pulls, newest first: how many there were, how many Claude was asked to help
* with, and what it cost on them. The queue projects what is still to run from this. A pull whose
@@ -1156,6 +1163,29 @@ export class Store {
},
save: (r) => {
const plan = r.result.planId && this.one('SELECT id FROM plans WHERE id=?', r.result.planId);
+ // What this save adds to the run's usage is counted in the month it is recorded in. A run's
+ // usage only grows; a smaller figure than the one stored adds nothing.
+ const before = this.one(
+ 'SELECT input_tokens+cache_read_tokens+cache_write_tokens i,output_tokens o,est_cost_usd c FROM agent_runs WHERE id=?',
+ r.id,
+ );
+ const grown = (now: number, was: unknown) => Math.max(0, now - Number(was ?? 0));
+ const added = {
+ input: grown(r.usage.input + r.usage.cacheRead + r.usage.cacheWrite, before?.i),
+ output: grown(r.usage.output, before?.o),
+ cost: grown(r.usage.estCostUsd, before?.c),
+ };
+ if (added.input || added.output || added.cost)
+ this.run(
+ `INSERT INTO claude_months(month,input_tokens,output_tokens,est_cost_usd) VALUES(?,?,?,?)
+ ON CONFLICT(month) DO UPDATE SET input_tokens=input_tokens+excluded.input_tokens,
+ output_tokens=output_tokens+excluded.output_tokens,
+ est_cost_usd=est_cost_usd+excluded.est_cost_usd`,
+ r.updatedAt.slice(0, 7),
+ added.input,
+ added.output,
+ added.cost,
+ );
this.run(
`UPDATE agent_runs SET status=?,request_text=?,plan_id=?,messages_json=?,pending_question_json=?,model=?,
iterations=?,input_tokens=?,output_tokens=?,cache_read_tokens=?,cache_write_tokens=?,est_cost_usd=?,
diff --git a/src/main/agent-services.ts b/src/main/agent-services.ts
index ca6cf84..290036b 100644
--- a/src/main/agent-services.ts
+++ b/src/main/agent-services.ts
@@ -558,7 +558,7 @@ export function createAgentServices(deps: AgentServiceDeps) {
stopped(error, who.id);
}
}
- return catalog.search(SITE, args.query, { jurisdiction, codeId }, 10).map((h) => {
+ return catalog.search(SITE, args.query, { jurisdiction, codeId }, 25).map((h) => {
const edition = editionOf(h.jurisdiction, h.codeId);
const keyword = /^(Article|Section|Chapter)\s+(\S+)/i.exec(h.section ?? '');
const target: Target =
diff --git a/src/main/workspace.ts b/src/main/workspace.ts
index e80b33f..0f4ee0f 100644
--- a/src/main/workspace.ts
+++ b/src/main/workspace.ts
@@ -7,15 +7,17 @@ import JSZip from 'jszip';
import { z } from 'zod';
import {
createRuntime,
- limitsFor,
+ effortFor,
listModels,
loadAgentAssets,
- pickModel,
+ type ModelRole,
publicApiError,
+ resolveModel,
sanitizeError,
type AgentAssets,
type AgentRuntime,
} from '../agent';
+import { type SpendState, spendState, spendStopMessage } from '../agent/budget';
import type { RunRecord } from '../agent/services';
import { ElectronViewDriver, pacedDriver, type SitePolicy } from '../browser/driver';
import { Pacing, systemClock, type Clock } from '../browser/pacing';
@@ -217,6 +219,7 @@ export class Workspace implements Omit {
findPage: (job, signal) => this.findPage(job, signal),
lookAtPage: (job, signal) => this.lookAtPage(job, signal),
visualFallback: () => store.settings().visualFallback,
+ claudeStopped: () => this.claudeStopped(),
signIn: (accountId, signal) => this.signInAgain(accountId, signal),
});
this.agent = createAgentServices({
@@ -246,6 +249,7 @@ export class Workspace implements Omit {
clientFactory: options.clientFactory as never,
assets: this.assets,
models: () => store.models(),
+ spend: () => this.spend(),
});
this.driver.on({
done: (accountId) => {
@@ -311,16 +315,16 @@ export class Workspace implements Omit {
* confirm the page, pull and save. Returns the saved pull when it is the unit that was asked for.
*/
private async findPage(job: Job, signal: AbortSignal): Promise {
- const settings = this.store.settings();
if (!(await this.apiKey())) return;
- if (!this.store.models().some((m) => m.id === settings.model)) return;
+ const model = this.modelFor('agent');
+ if (!model || this.spend().reached) return;
const t = job.target;
const { runId, done } = this.runtime.start({
kind: 'fallback_nav',
// Names the unit and its scope: a whole chapter is not a section with the chapter's number.
userText: pageSearchRequest(t),
options: { accountId: job.accountId, includeDocx: false, forceRefresh: true },
- model: settings.model,
+ model,
jobId: job.id,
});
this.log('queue', 'fallback_nav.started', {}, { jobId: job.id, runId });
@@ -350,7 +354,7 @@ export class Workspace implements Omit {
return;
}
/**
- * The screenshot fallback, when the user allowed it: Claude looks at the page and points to
+ * The screenshot fallback, unless the user turned it off: Claude looks at the page and points to
* where the section starts and ends; CodePull reads the text from the page between those points,
* checks it like any capture, and saves it marked for review. Returns the saved pull, or nothing
* when the fallback is off or cannot run. Throws why it did not find the section.
@@ -359,8 +363,9 @@ export class Workspace implements Omit {
const settings = this.store.settings();
if (!settings.visualFallback) return;
const key = await this.apiKey();
- const model = this.store.models().find((m) => m.id === settings.model);
- if (!key || !model) return;
+ const modelId = this.modelFor('agent');
+ const model = this.store.models().find((m) => m.id === modelId);
+ if (!key || !model || this.spend().reached) return;
const accountId = job.accountId;
const account = this.store.account(accountId);
const t = captureTarget(job.target);
@@ -379,7 +384,7 @@ export class Workspace implements Omit {
kind: 'fallback_nav',
status: 'running',
request: 'Look at the page for § ' + t.section + ' of ' + t.codeId + ' ' + t.edition,
- model: settings.model,
+ model: model.id,
messages: [],
log: [{ at, text: 'Claude is looking at the page for § ' + t.section + '.' }],
result: { pullIds: [], jobIds: [job.id] },
@@ -415,8 +420,10 @@ export class Workspace implements Omit {
return lookForSection({
client:
(this.options.clientFactory as ((k: string) => never) | undefined)?.(key) ?? clientFor(key),
- model: settings.model,
+ model: model.id,
modelInfo: model,
+ effort: effortFor(model, this.assets.modelDefaults.look.effort),
+ spend: () => this.spend(),
secrets: [key, ...this.sitePasswords.values()],
pricing: this.assets.pricing,
target: t,
@@ -630,16 +637,62 @@ export class Workspace implements Omit {
dismissed: dismissed.has(r.id),
};
}
- async state(): Promise {
- const usage = this.store.one(
- 'SELECT SUM(input_tokens+cache_read_tokens+cache_write_tokens) i,SUM(output_tokens) o,SUM(est_cost_usd) c FROM agent_runs WHERE created_at>=?',
- now().slice(0, 7) + '-01',
+ /**
+ * The first day of the month now (UTC), as the start of what the spending limit counts. By the
+ * same clock that dates each run, so a run always falls in the month it was begun in.
+ */
+ private monthStart() {
+ return now().slice(0, 7) + '-01';
+ }
+ /**
+ * The month's estimated Claude cost against the user's limit. Read before every call to Claude,
+ * by every kind of work: while `reached` is true nothing is sent.
+ */
+ private spend(): SpendState {
+ return spendState(
+ this.store.monthSpend(this.monthStart()).estCostUsd,
+ this.store.settings().spendLimitUsd,
);
+ }
+ /** Why nothing may call Claude now, when the month's spending limit is reached. */
+ private claudeStopped(): string | undefined {
+ const spend = this.spend();
+ return spend.reached ? spendStopMessage(spend) : undefined;
+ }
+ private freshened = false;
+ /**
+ * A model list saved by a version that did not record effort levels is read once more from
+ * Anthropic, right before a request that is about to call it anyway. Without the levels a plan
+ * would run at a lower effort than the model offers. Quiet: on any failure the saved list stays.
+ */
+ private async freshenModels() {
+ // Once for each start of the app: a model that reports no levels would ask every time.
+ if (this.freshened || !this.store.models().some((m) => m.effort && !m.efforts?.length)) return;
+ this.freshened = true;
+ try {
+ await this.key('models');
+ } catch {
+ // The request goes on with the list as saved.
+ }
+ }
+ /** The model a kind of work uses: the user's pick, or the automatic choice. Empty when none. */
+ private modelFor(role: ModelRole): string {
+ const settings = this.store.settings();
+ return resolveModel(
+ role,
+ role === 'planner' ? settings.plannerModel : settings.model,
+ this.store.models(),
+ this.assets.modelDefaults,
+ );
+ }
+ async state(): Promise {
+ const usage = this.store.monthSpend(this.monthStart());
const settings = this.store.settings();
const models = this.store.models();
const hasKey = !!(this.memoryKey || existsSync(this.keyFile));
- const search = limitsFor('fallback_nav', settings);
- const selected = models.find((m) => m.id === settings.model);
+ const model = this.modelFor('agent');
+ const spend = this.spend();
+ const automatic = (role: ModelRole) => resolveModel(role, '', models, this.assets.modelDefaults);
return {
accounts: this.store.accounts().map((a) => ({
...a,
@@ -658,33 +711,19 @@ export class Workspace implements Omit {
models,
hasKey,
keyStorage: (await this.encryption()) ? 'OS-encrypted storage' : 'Memory for this session',
- usage: {
- input: Number(usage?.i ?? 0),
- output: Number(usage?.o ?? 0),
- estCostUsd: Number(usage?.c ?? 0),
- },
+ usage,
claude: {
- model: settings.model,
+ model,
+ plannerModel: this.modelFor('planner'),
+ automatic: { model: automatic('agent'), plannerModel: automatic('planner') },
prices: Object.fromEntries(
models
.filter((m) => Object.hasOwn(this.assets.pricing, m.id))
.map((m) => [m.id, this.assets.pricing[m.id]!]),
),
// The same conditions `findPage` and `lookAtPage` check before they call Claude.
- available: hasKey && !!selected,
- search: {
- inputTokens: search.tokens!.input,
- outputTokens: search.tokens!.output,
- // A search's request asks for the model's whole output, as `runtime.ts` sends it.
- perCall: selected?.maxOutputTokens ?? search.fallbackTokensPerCall,
- },
- look: {
- inputTokens: VISUAL_LIMITS.inputTokens,
- // Each step asks for at most this, as `lookForSection` sends it.
- outputTokens:
- VISUAL_LIMITS.actions *
- Math.min(selected?.maxOutputTokens ?? VISUAL_LIMITS.maxTokens, VISUAL_LIMITS.maxTokens),
- },
+ available: hasKey && !!model && !spend.reached,
+ spend,
history: this.store.claudeHistory(),
},
version: app.getVersion(),
@@ -740,14 +779,13 @@ export class Workspace implements Omit {
this.memoryKey = undefined;
} else this.memoryKey = key;
}
- this.store.setModels(models, (role, available) =>
- pickModel(role, available, this.assets.modelDefaults),
- );
+ this.store.setModels(models);
this.changed();
}
async settings(patch: Parameters[0]) {
const values = settingsPatch.parse(patch);
const models = this.store.models();
+ // An empty pick is the automatic choice.
for (const model of [values.model, values.plannerModel])
if (model && !models.some((m) => m.id === model)) throw Error('Select a model your key can use.');
this.store.set('preferences', mergeSettings(this.store.settings(), values));
@@ -1038,12 +1076,14 @@ export class Workspace implements Omit {
this.changed();
return run.id;
}
- const settings = this.store.settings();
if (!(await this.apiKey()))
throw Error('Add your Anthropic API key in Settings, or enter an exact section.');
- const model = req.mode === 'project' ? settings.plannerModel || settings.model : settings.model;
- if (!this.store.models().some((m) => m.id === model))
- throw Error('Refresh models in Settings and select a model your key can use.');
+ await this.freshenModels();
+ const model = this.modelFor(req.mode === 'project' ? 'planner' : 'agent');
+ if (!model)
+ throw Error('No Claude model is available to your API key. Choose Refresh models in Settings.');
+ const stopped = this.claudeStopped();
+ if (stopped) throw Error(stopped);
const previous = req.previousPlanId ? this.store.plan(req.previousPlanId) : undefined;
if (previous && previous.status !== 'draft') throw Error('Only a draft can be revised.');
const { runId, done } = this.runtime.start({
diff --git a/src/queue/scheduler.ts b/src/queue/scheduler.ts
index 03eb54e..ba13017 100644
--- a/src/queue/scheduler.ts
+++ b/src/queue/scheduler.ts
@@ -58,8 +58,16 @@ export interface SchedulerDeps {
* Throws why it did not find the section. Asked at most once per job.
*/
lookAtPage?: (job: Job, signal: AbortSignal) => Promise;
- /** Whether the user allowed the screenshot fallback, to say so on a pull it could have helped. */
+ /**
+ * Whether the screenshot fallback is on. When the user turned it off, a pull it could have helped
+ * says so.
+ */
visualFallback?: () => boolean;
+ /**
+ * Why nothing may call Claude now, when the month's spending limit is reached. A pull is then
+ * not searched or looked for, and stays free to be when it is retried after the limit is raised.
+ */
+ claudeStopped?: () => string | undefined;
now?: () => number;
setTimer?: (fn: () => void, ms: number) => unknown;
clearTimer?: (handle: unknown) => void;
@@ -340,7 +348,13 @@ export class Scheduler {
? 'verification_failed'
: undefined;
const checkpoint = store.jobCheckpoint(job.id);
- if (reason === 'not_found' && this.deps.findPage && !checkpoint.searched) {
+ // The kill switch: at the month's spending limit Claude is not asked, and the pull says so.
+ const unasked =
+ reason === 'not_found' || reason === 'layout_changed'
+ ? this.deps.claudeStopped?.()
+ : undefined;
+ if (unasked) message += ' ' + unasked;
+ if (!unasked && reason === 'not_found' && this.deps.findPage && !checkpoint.searched) {
// The catalog and the numbering convention both missed. Let Claude search the contents once.
store.jobCheckpoint(job.id, { searched: true });
store.run(
@@ -381,6 +395,13 @@ export class Scheduler {
this.deps.changed();
continue;
}
+ // The limit was reached while it searched: the search did not run its course, and may
+ // again once the user has raised the limit and retries the pull.
+ const stoppedMeanwhile = this.deps.claudeStopped?.();
+ if (stoppedMeanwhile) {
+ store.jobCheckpoint(job.id, { searched: false });
+ message += ' ' + stoppedMeanwhile;
+ }
const restarts = Number(checkpoint.searchRestarts ?? 0);
if ((cutShort || controller.signal.aborted || !this.enabled()) && restarts < SEARCH_RESTARTS) {
// The search did not run its course: the user took the window, pulling was stopped, or
@@ -393,6 +414,8 @@ export class Scheduler {
}
}
if (
+ !unasked &&
+ !this.deps.claudeStopped?.() &&
(reason === 'not_found' || reason === 'layout_changed') &&
this.deps.lookAtPage &&
// A whole chapter cannot be pointed at within one look, and a page that read as far less
@@ -432,6 +455,10 @@ export class Scheduler {
if (lookError instanceof BlockedError && stopsAccount.includes(lookError.reason)) {
reason = lookError.reason;
message = this.deps.sanitize(lookError);
+ } else if (this.deps.claudeStopped?.()) {
+ // The limit was reached while it looked. It may look again after a retry.
+ store.jobCheckpoint(job.id, { looked: false });
+ message += ' ' + this.deps.claudeStopped();
} else
message += ' Looking at the page did not find it either: ' + this.deps.sanitize(lookError);
}
diff --git a/src/shared/bridge.ts b/src/shared/bridge.ts
index 1ff0a7c..35a7c4f 100644
--- a/src/shared/bridge.ts
+++ b/src/shared/bridge.ts
@@ -227,7 +227,10 @@ export interface Pacing {
/** Accounts that may pull at the same time (hard maximum 4). */
activeWorkers: number;
}
-/** Claude's working limits. Tokens are not capped: a run is bounded by its steps and its time. */
+/**
+ * Claude's working limits. Tokens are not capped anywhere: a run is bounded by its steps and its
+ * time, and all of Claude's work by the month's spending limit (`Settings.spendLimitUsd`).
+ */
export interface Budgets {
/** Model calls one plain-language request may make before it stops and asks to continue. */
requestIterations: number;
@@ -237,9 +240,12 @@ export interface Budgets {
maxPlanItems: number;
}
export interface Settings {
- /** Model for the request loop and fallback navigation. */
+ /**
+ * Model for the request loop and fallback navigation. Empty means automatic: the first model the
+ * shipped preferences name that the key offers (`resolveModel` in `src/agent/client.ts`).
+ */
model: string;
- /** Model for project fact extraction and plan drafting. */
+ /** Model for project fact extraction and plan drafting. Empty means automatic, as for `model`. */
plannerModel: string;
stalenessDays: number;
autoRefreshStale: boolean;
@@ -248,9 +254,16 @@ export interface Settings {
textSharing: TextSharing;
/**
* Let Claude look at screenshots of a page when the reader cannot find a section or its chapter.
- * Screenshots show code text, so this is off until the user turns it on.
+ * Screenshots show code text. On by default since 1 December 2026, the owner's decision; the
+ * user can turn it off.
*/
visualFallback: boolean;
+ /**
+ * The most Claude may cost in one calendar month, in whole US dollars by the app's price list.
+ * Once the month's estimate reaches it, no call to Claude is made by anything until the user
+ * raises it or the month ends. 0 means no limit.
+ */
+ spendLimitUsd: number;
pacing: Pacing;
budgets: Budgets;
/** Show the account's browser window while the queue is pulling. */
@@ -265,6 +278,11 @@ export interface Model {
maxOutputTokens?: number;
/** Whether the Models API reports support for the effort control. */
effort?: boolean;
+ /**
+ * The effort levels the Models API reports for it. Absent in a list saved by an earlier version,
+ * which is then read as offering low, medium and high.
+ */
+ efforts?: ('low' | 'medium' | 'high' | 'xhigh' | 'max')[];
/** Whether the Models API reports support for strict tool schemas. Absent when not reported. */
structuredOutputs?: boolean;
}
@@ -272,7 +290,7 @@ export interface RunQuestion {
text: string;
options: string[];
allowFreeText: boolean;
- /** `budget` asks whether to continue after a spending limit was reached. */
+ /** `budget` asks whether to continue after a step, time or spending limit was reached. */
kind: 'question' | 'budget';
}
export interface RunUsage {
@@ -296,22 +314,24 @@ export interface ModelPrice {
* the figures with `src/shared/claude-cost.ts`.
*/
export interface ClaudeOutlook {
- /** The model the queue's Claude runs use (`Settings.model`). */
+ /** The model the queue's Claude runs and requests use: `Settings.model`, or the automatic choice. */
model: string;
+ /** The model project plans use: `Settings.plannerModel`, or the automatic choice. */
+ plannerModel: string;
+ /** What "Automatic" stands for now, for each role. Empty when the key offers no model. */
+ automatic: { model: string; plannerModel: string };
/**
* Prices from the price list in the app for the models the key offers, keyed by model ID. A model
* the list has no price for is missing: its cost is unknown, not nothing.
*/
prices: Record;
- /** The queue can call Claude: a key and a model the key offers. */
+ /** The queue can call Claude: a key, a model the key offers, and the month's limit not reached. */
available: boolean;
/**
- * The fixed token budgets of the queue's search for a page (`QUEUE_SEARCH_TOKENS`), and what one of
- * its requests may ask for: the model's whole output. No setting changes them.
+ * The month's estimated cost against the user's limit (`Settings.spendLimitUsd`; 0 is no limit).
+ * `reached` stops every call to Claude. A model with no listed price counts as nothing here.
*/
- search: { inputTokens: number; outputTokens: number; perCall: number };
- /** Hard limits of one look at the page (`VISUAL_LIMITS`), with its output for every step. */
- look: { inputTokens: number; outputTokens: number };
+ spend: { monthUsd: number; limitUsd: number; reached: boolean };
/**
* The last finished pulls (at most `HISTORY_PULLS`), how many Claude helped with, and its cost.
* A pull Claude worked on with a model that had no listed price is left out: its cost is unknown.
diff --git a/src/shared/claude-cost.ts b/src/shared/claude-cost.ts
index 61122ac..65dc860 100644
--- a/src/shared/claude-cost.ts
+++ b/src/shared/claude-cost.ts
@@ -4,11 +4,14 @@
*
* Most pulls never call Claude: the catalog and the page reader find and read the page by
* themselves. Claude is asked for one pull only when CodePull cannot place it: once to search the
- * code's contents (a `fallback_nav` run within `QUEUE_SEARCH_TOKENS` in `src/agent/budget.ts`), then,
- * if the user allowed it, once to look at the page (`VISUAL_LIMITS` in `src/agent/visual.ts`). Both
- * budgets are fixed, unlike requests and plans, which have no token limits. Each call stops at its
- * budget, so what one pull can cost has a ceiling, and what the queue can still cost is that ceiling
- * times the pulls still to run.
+ * code's contents (a `fallback_nav` run), then, unless the user turned it off, once to look at the
+ * page (`lookForSection` in `src/agent/visual.ts`).
+ *
+ * No call has a token budget (the owner's decision, 1 December 2026), so one pull has no ceiling of
+ * its own. What bounds all of Claude's work is the month's spending limit
+ * (`Settings.spendLimitUsd`): once the month's estimate reaches it, nothing calls Claude. The
+ * screens therefore show what was spent, what the rest will likely cost at the rate of the last
+ * finished pulls, and what is left under the limit.
*
* Every figure is an estimate from the price list in the app (`assets/pricing.json`), never a bill.
*/
@@ -19,91 +22,50 @@ export const HISTORY_PULLS = 200;
/** Fewer finished pulls than this say too little to project from. */
export const HISTORY_MIN = 10;
-const PER_MILLION = 1_000_000;
-
-/** The dearest rate an input token can be billed at: plain input, a cache write or a cache read. */
-const inputRate = (price: ModelPrice) => Math.max(price.input, price.cacheWrite, price.cacheRead);
-
-/**
- * The most one run can cost when it sends at most these tokens and receives at most these. Every
- * input token is priced at the dearest input rate: a search's requests may miss the cache, and are
- * then billed as cache writes.
- */
-export function runCeiling(price: ModelPrice, inputTokens: number, outputTokens: number): number {
- return (
- (Math.max(0, inputTokens) * inputRate(price) + Math.max(0, outputTokens) * price.output) /
- PER_MILLION
- );
-}
-
-export interface PullCeiling {
- /** A search of the code's contents for the page, within its fixed budgets. */
- search: number;
- /** A look at the page, at its fixed limits. Part of `total` only while the setting is on. */
- look: number;
- lookOn: boolean;
- /** The most Claude can cost on one pull. 0 when the queue cannot call Claude at all. */
- total: number;
-}
-
/** A model's listed price. Undefined when the price list has none for it. */
export const priceOf = (outlook: ClaudeOutlook, model = outlook.model): ModelPrice | undefined =>
Object.hasOwn(outlook.prices, model) ? outlook.prices[model] : undefined;
-/**
- * What Claude can cost on one pull, from the fixed budgets and the model's prices (the queue's model
- * unless another is named). Undefined when the price list has no price for the model: the cost is
- * then unknown, not nothing.
- */
-export function pullCeiling(
- outlook: ClaudeOutlook,
- lookOn: boolean,
- model = outlook.model,
-): PullCeiling | undefined {
- const price = priceOf(outlook, model);
- if (!price) return undefined;
- // A search runs with `limitsFor('fallback_nav')`. Its input budget is checked against each request
- // before it is sent, so its input never passes the budget. Its output budget is checked before each
- // request too, so the last reply may cross it by up to one whole reply. The look checks its input
- // the same way, and asks for no more than its step limit times its output for one step.
- const search = runCeiling(
- price,
- outlook.search.inputTokens,
- outlook.search.outputTokens + outlook.search.perCall,
- );
- const look = runCeiling(price, outlook.look.inputTokens, outlook.look.outputTokens);
- return { search, look, lookOn, total: outlook.available ? search + (lookOn ? look : 0) : 0 };
-}
-
/** What Claude cost per pull over the last finished pulls. Undefined with too few of them. */
export function averagePerPull(outlook: ClaudeOutlook): number | undefined {
const { pulls, estCostUsd } = outlook.history;
return pulls >= HISTORY_MIN ? estCostUsd / pulls : undefined;
}
-export interface Projection {
- /** The most Claude can cost on these pulls. Undefined when the model has no listed price. */
- ceilingUsd?: number;
- /**
- * What these pulls would cost at the average of the last finished pulls, never above the ceiling.
- * Undefined without enough history, or without a price.
- */
- likelyUsd?: number;
+/**
+ * The month's spending limit as it stands now: the estimate so far and the limit. `reached` is the
+ * kill switch: while it is true, nothing calls Claude.
+ */
+export type SpendState = ClaudeOutlook['spend'];
+/** The month's estimate against the limit. A limit of 0 is no limit. */
+export function spendState(monthUsd: number, limitUsd: number): SpendState {
+ const spent = Number.isFinite(monthUsd) && monthUsd > 0 ? monthUsd : 0;
+ const limit = Number.isFinite(limitUsd) && limitUsd > 0 ? limitUsd : 0;
+ return { monthUsd: spent, limitUsd: limit, reached: limit > 0 && spent >= limit };
+}
+/** What the user is told when the limit stops Claude. The same words on runs, pulls and screens. */
+export function spendStopMessage(spend: Pick): string {
+ return `Claude is stopped: this month's estimated cost reached your limit of $${spend.limitUsd.toLocaleString('en-US')}. Raise the limit in Settings to go on, or wait for next month.`;
+}
+
+/**
+ * What is left under the month's spending limit. Undefined when no limit is set. This is the most
+ * all of Claude's work can still cost this month, give or take the one call that crosses the limit.
+ */
+export function leftUnderLimit(outlook: ClaudeOutlook): number | undefined {
+ const { limitUsd, monthUsd } = outlook.spend;
+ return limitUsd > 0 ? Math.max(0, limitUsd - monthUsd) : undefined;
}
-/** What Claude may cost on this many pulls that have not run yet. */
-export function project(
- pulls: number,
- outlook: ClaudeOutlook,
- ceiling: PullCeiling | undefined,
-): Projection {
- if (!ceiling) return {};
- const ceilingUsd = Math.max(0, pulls) * ceiling.total;
+/**
+ * What this many pulls that have not run yet would cost at the average of the last finished pulls.
+ * Undefined without enough history, or when the queue's model has no listed price: the cost is then
+ * unknown, not nothing.
+ */
+export function likelyFor(pulls: number, outlook: ClaudeOutlook): number | undefined {
+ if (!priceOf(outlook)) return undefined;
const average = averagePerPull(outlook);
- return {
- ceilingUsd,
- ...(average !== undefined && { likelyUsd: Math.min(ceilingUsd, Math.max(0, pulls) * average) }),
- };
+ return average === undefined ? undefined : Math.max(0, pulls) * average;
}
/** Nothing spent. */
@@ -153,30 +115,26 @@ export const stillToRun = (job: Job) =>
job.status === 'extracting' ||
job.status === 'checking';
-export interface QueueOutlook extends Projection {
+export interface QueueOutlook {
/** Recorded so far on these jobs. */
spent: ClaudeSpend;
/** Jobs still to run, each of which may call Claude. */
remaining: number;
/** Jobs Claude is working on right now. */
working: Job[];
+ /** What the jobs still to run would cost at the rate of the last finished pulls. */
+ likelyUsd?: number;
}
-/**
- * Spent and still possible on a set of jobs. A job that is running counts in full toward what is
- * still possible, although part of it may already be spent: the ceiling errs high, never low.
- */
-export function queueOutlook(
- jobs: readonly Job[],
- outlook: ClaudeOutlook,
- ceiling: PullCeiling | undefined,
-): QueueOutlook {
+/** Spent and likely still to come on a set of jobs. */
+export function queueOutlook(jobs: readonly Job[], outlook: ClaudeOutlook): QueueOutlook {
const unique = uniqueJobs(jobs);
const remaining = unique.filter(stillToRun).length;
+ const likelyUsd = likelyFor(remaining, outlook);
return {
spent: spentOn(unique),
remaining,
working: unique.filter(claudeWorking),
- ...project(remaining, outlook, ceiling),
+ ...(likelyUsd !== undefined && { likelyUsd }),
};
}
diff --git a/src/shared/validation.ts b/src/shared/validation.ts
index a314975..c8ed724 100644
--- a/src/shared/validation.ts
+++ b/src/shared/validation.ts
@@ -148,13 +148,19 @@ export const pacingLimits = {
} as const satisfies Record;
/**
* Claude's working limits. Tokens are not capped by the app: a run ends when Claude is done, at its
- * step limit, or at its time limit, and at a limit it asks whether to continue.
+ * step limit, or at its time limit, and at a limit it asks whether to continue. The defaults are
+ * generous on purpose (1 December 2026): a normal request or plan should never reach one.
*/
export const budgetLimits = {
- requestIterations: { min: 2, max: 40, initial: 14 },
- planIterations: { min: 2, max: 60, initial: 24 },
- maxPlanItems: { min: 1, max: 60, initial: 30 },
+ requestIterations: { min: 2, max: 200, initial: 40 },
+ planIterations: { min: 2, max: 200, initial: 60 },
+ maxPlanItems: { min: 1, max: 60, initial: 60 },
} as const satisfies Record;
+/**
+ * The month's spending limit for Claude, in whole US dollars. 0 means no limit. When the month's
+ * estimated cost reaches it, nothing calls Claude until the user raises it or the month ends.
+ */
+export const spendLimit = { min: 0, max: 100_000, initial: 200 } as const;
const bounded = (limits: Record) =>
z
@@ -180,8 +186,10 @@ export const defaultSettings: Settings = {
autoRefreshStale: false,
keepVersions: 3,
textSharing: 'outline',
- // Screenshots carry code text to Claude, so they are never sent until the user allows it (R9).
- visualFallback: false,
+ // On by default since 1 December 2026 (the owner's decision, R9): a section the reader cannot
+ // place is found by looking at the page, without the user having to turn anything on.
+ visualFallback: true,
+ spendLimitUsd: spendLimit.initial,
pacing: initial(pacingLimits),
budgets: initial(budgetLimits),
showBrowser: false,
@@ -196,6 +204,7 @@ export const settingsPatch = z
keepVersions: z.number().int().min(1).max(50),
textSharing: z.enum(['none', 'outline', 'excerpts']),
visualFallback: z.boolean(),
+ spendLimitUsd: z.number().int().min(spendLimit.min).max(spendLimit.max),
pacing: bounded(pacingLimits),
budgets: bounded(budgetLimits),
showBrowser: z.boolean(),
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index f58d0c1..31a97ce 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -214,6 +214,7 @@ export function App() {
tokens: state.usage.input + state.usage.output,
cost: state.usage.estCostUsd,
working: state.runs.some((r) => r.status === 'running') || state.jobs.some(claudeWorking),
+ stopped: state.claude.spend.reached,
}}
>
{error && (
diff --git a/src/ui/advanced.ts b/src/ui/advanced.ts
new file mode 100644
index 0000000..d2420a6
--- /dev/null
+++ b/src/ui/advanced.ts
@@ -0,0 +1,21 @@
+/**
+ * Whether Settings shows its advanced part. CodePull chooses every value there for the user, so it
+ * is hidden until asked for, and the choice is remembered on this computer.
+ */
+const key = 'codepull.settings.advanced';
+
+export function advancedShown(): boolean {
+ try {
+ return localStorage.getItem(key) === '1';
+ } catch {
+ // Storage can be unavailable. The advanced part is then hidden at every start.
+ return false;
+ }
+}
+export function setAdvancedShown(shown: boolean) {
+ try {
+ localStorage.setItem(key, shown ? '1' : '0');
+ } catch {
+ // Not remembered. It still shows for as long as the page is open.
+ }
+}
diff --git a/src/ui/claude-cost.tsx b/src/ui/claude-cost.tsx
index c45f704..f234154 100644
--- a/src/ui/claude-cost.tsx
+++ b/src/ui/claude-cost.tsx
@@ -3,9 +3,11 @@ import type { ClaudeSpend, Job, Plan } from '../shared/bridge';
import {
claudeWorking,
HISTORY_MIN,
- project,
- pullCeiling,
+ leftUnderLimit,
+ likelyFor,
+ priceOf,
queueOutlook,
+ spendStopMessage,
spentOn,
stillToRun,
uniqueJobs,
@@ -14,9 +16,6 @@ import { Notice } from './components';
import { useWorkspace } from './context';
import { compact, money, plural, sectionLabel } from './format';
-/** An amount, or "unknown" when the price list has no price for the model. */
-export const estimate = (usd: number | undefined) => (usd === undefined ? 'unknown' : money(usd));
-
/**
* What was spent, as an amount. Runs on a model with no listed price make it "over" the priced part,
* or unknown when nothing was priced: never a smaller figure than was really spent.
@@ -37,7 +36,8 @@ const costText = (spend: ClaudeSpend) => {
function unavailable(state: ReturnType['state']) {
if (state.claude.available) return '';
if (!state.hasKey) return 'there is no Anthropic API key';
- return 'the selected model is not available to your key';
+ if (state.claude.spend.reached) return 'this month’s spending limit is reached';
+ return 'your key offers no Claude model';
}
function Figure({ label, value, note }: { label: string; value: string; note: string }) {
@@ -58,8 +58,9 @@ export function ClaudeCostPanel({ jobs, scope }: { jobs: Job[]; scope: string })
const { state, navigate } = useWorkspace();
const outlook = state.claude;
const settings = state.settings;
- const ceiling = pullCeiling(outlook, settings.visualFallback);
- const q = queueOutlook(jobs, outlook, ceiling);
+ const priced = !!priceOf(outlook);
+ const q = queueOutlook(jobs, outlook);
+ const left = leftUnderLimit(outlook);
if (!q.remaining && !q.spent.tokens && !q.working.length) return null;
const history = outlook.history;
const off = unavailable(state);
@@ -91,22 +92,26 @@ export function ClaudeCostPanel({ jobs, scope }: { jobs: Job[]; scope: string })
value={
q.likelyUsd !== undefined
? (q.likelyUsd > 0 ? 'about ' : '') + money(q.likelyUsd)
- : ceiling && !q.remaining
+ : priced && !q.remaining
? money(0)
: '—'
}
note={
q.likelyUsd !== undefined
? 'at the rate of your last ' + plural(history.pulls, 'pull')
- : !ceiling
+ : !priced
? 'no price for ' + outlook.model
: 'shown after ' + HISTORY_MIN + ' finished pulls'
}
/>
{q.working.map((job) => (
@@ -116,12 +121,17 @@ export function ClaudeCostPanel({ jobs, scope }: { jobs: Job[]; scope: string })
{costText(job.claude!)} so far · {compact(job.claude!.tokens)} tokens
))}
- {off ? (
+ {outlook.spend.reached ? (
+
+ {spendStopMessage(outlook.spend)} Until then the queue makes no Claude calls: a pull
+ CodePull cannot find by itself stops and waits for you.
+
+ ) : off ? (
The queue cannot call Claude now because {off}, so it makes no Claude calls. A pull
CodePull cannot find by itself stops and waits for you.
- ) : !ceiling ? (
+ ) : !priced ? (
The price list in the app has no price for {outlook.model}, so what Claude costs cannot be
estimated. Tokens are still counted.
@@ -130,11 +140,8 @@ export function ClaudeCostPanel({ jobs, scope }: { jobs: Job[]; scope: string })
Most pulls cost nothing in Claude: CodePull finds and reads the page by itself. Claude is
asked only for a section it cannot place: a search of the code’s contents
- {ceiling && <>, at most {money(ceiling.search)} a pull>}
- {settings.visualFallback && (
- <>, then a look at the page{ceiling && <>, at most {money(ceiling.look)}>}>
- )}
- .{' '}
+ {settings.visualFallback && <>, then a look at the page>}. Neither has a token limit; your
+ monthly limit in Settings is what stops Claude.{' '}
{history.pulls > 0 &&
`Claude was asked about ${history.helped} of your last ${plural(history.pulls, 'finished pull')}, est. ${money(history.estCostUsd)} in all. `}
These are estimates from the price list in the app, not a bill.
@@ -166,26 +173,24 @@ export function planClaudeNote(jobs: Job[]) {
}
/**
- * What Claude may cost on a plan. Before approval: the most it can cost on the pulls the plan will
- * make (`pulls`, with up to `more` cross-references), and what it would likely cost. After: what it
- * has cost so far and the most it can still cost.
+ * What Claude may cost on a plan. Before approval: what the pulls the plan will make (`pulls`) would
+ * likely cost, and what is left under the month's limit. After: what it has cost so far and what
+ * the rest will likely cost.
*/
export function PlanClaude({
plan,
jobs,
pulls,
- more,
unit,
}: {
plan: Plan;
jobs: Job[];
pulls: number;
- more: number;
unit: string;
}) {
const { state } = useWorkspace();
const outlook = state.claude;
- const ceiling = pullCeiling(outlook, state.settings.visualFallback);
+ const left = leftUnderLimit(outlook);
const drafting = plan.claude?.tokens ? plan.claude : undefined;
const drafted = drafting
? drafting.unpricedTokens && !drafting.estCostUsd
@@ -194,34 +199,43 @@ export function PlanClaude({
: '';
if (plan.status === 'draft') {
if (!pulls) return <>Claude: nothing, because nothing needs a page load.{drafted}>;
+ if (outlook.spend.reached)
+ return (
+ <>
+ Claude is stopped at this month’s spending limit, so these pulls make no Claude calls.
+ {drafted}
+ >
+ );
if (unavailable(state))
return <>Claude is not set up, so these pulls make no Claude calls.{drafted}>;
- if (!ceiling)
+ if (!priceOf(outlook))
return (
<>
Claude: no price is listed for {outlook.model}, so its cost cannot be estimated.{drafted}
>
);
- const all = project(pulls + more, outlook, ceiling);
- const likely = project(pulls, outlook, ceiling).likelyUsd;
+ const likely = likelyFor(pulls, outlook);
return (
<>
- Claude: nothing for a {unit} CodePull finds by itself. At most {money(all.ceilingUsd ?? 0)} if
- every one needed its help
+ Claude: nothing for a {unit} CodePull finds by itself
{likely !== undefined &&
- `; about ${money(likely)} at the rate of your last ${plural(outlook.history.pulls, 'pull')}`}
- .{drafted}
+ `; about ${money(likely)} for these at the rate of your last ${plural(outlook.history.pulls, 'pull')}`}
+ .{left !== undefined && ` ${money(left)} is left under this month’s limit.`}
+ {drafted}
>
);
}
const spent = spentOn(jobs);
const remaining = uniqueJobs(jobs).filter(stillToRun).length;
- const rest = project(remaining, outlook, ceiling).ceilingUsd;
+ const rest = likelyFor(remaining, outlook);
return (
<>
Claude: {costText(spent)} on these pulls so far
{drafting && ` and ${costText(drafting)} drafting the plan`}
- {remaining > 0 && `. At most ${estimate(rest)} for the ${plural(remaining, unit)} still to run`}.
+ {remaining > 0 &&
+ rest !== undefined &&
+ `. About ${money(rest)} likely for the ${plural(remaining, unit)} still to run`}
+ .
>
);
}
diff --git a/src/ui/components.tsx b/src/ui/components.tsx
index 2f8c4c3..a271e85 100644
--- a/src/ui/components.tsx
+++ b/src/ui/components.tsx
@@ -77,8 +77,11 @@ export function Workspace({
waiting: number;
/** The default account, with a short remark when it cannot pull as it is. */
account?: { label: string; ready: boolean; remark: string };
- /** This month's Claude usage, and whether Claude is working now. */
- usage: { tokens: number; cost: number; working: boolean };
+ /**
+ * This month's Claude usage, whether Claude is working now, and whether the month's spending
+ * limit has stopped it.
+ */
+ usage: { tokens: number; cost: number; working: boolean; stopped: boolean };
}) {
const [mobileMenu, setMobileMenu] = useState(false);
const nav = (name: Page) => {
@@ -158,15 +161,18 @@ export function Workspace({
diff --git a/src/ui/queue.tsx b/src/ui/queue.tsx
index b4ba46d..3763e65 100644
--- a/src/ui/queue.tsx
+++ b/src/ui/queue.tsx
@@ -27,6 +27,7 @@ import {
PageTitle,
ProgressBar,
} from './components';
+import { setAdvancedShown } from './advanced';
import { useWorkspace } from './context';
import {
accountStatus,
@@ -219,7 +220,14 @@ export function QueuePage() {
Pacing
-
diff --git a/src/ui/request.tsx b/src/ui/request.tsx
index 130844d..304ca4b 100644
--- a/src/ui/request.tsx
+++ b/src/ui/request.tsx
@@ -18,6 +18,8 @@ import {
import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from 'react';
import type { AgentRun, CatalogCode, CatalogJurisdiction, RunRequest, Target } from '../shared/bridge';
import { Badge, Busy, dateTime, Empty, Notice, PageTitle, SampleCard, type Page } from './components';
+import { spendStopMessage } from '../shared/claude-cost';
+import { setAdvancedShown } from './advanced';
import { useWorkspace } from './context';
import { accountStatus, isUserRun, readable, runStatus, runToShow } from './format';
import { RunPanel } from './run';
@@ -724,6 +726,17 @@ export function RequestPage() {
)}
+ {!explicit && state.hasKey && state.claude.spend.reached && (
+
+ {spendStopMessage(state.claude.spend)}{' '}
+ {mode === 'project'
+ ? 'A project plan needs Claude. '
+ : 'You can still paste an UpCodes page address, type an exact request such as “CEC 2022 695.3”, or choose Enter exact section. '}
+ navigate('Settings')}>
+ Raise the limit in Settings
+
+
+ )}
{mode === 'quick' && !explicit && state.hasKey && (
Your request is sent to the Anthropic API so Claude can work out the code and
@@ -892,8 +905,15 @@ export function RequestPage() {
CodePull never buys, starts a trial or signs up for anything, and never switches a pull
to another account by itself.
- navigate('Settings')}>
- Change in Settings
+ {
+ // Pacing is one of the settings CodePull chose: it sits in the advanced part.
+ setAdvancedShown(true);
+ navigate('Settings');
+ }}
+ >
+ Change in the advanced settings
diff --git a/src/ui/run.tsx b/src/ui/run.tsx
index 696f015..6279c62 100644
--- a/src/ui/run.tsx
+++ b/src/ui/run.tsx
@@ -171,7 +171,10 @@ export function RunPanel({
)}
{question.kind === 'budget' && (
-
You can change these limits in Settings, under Claude.
+
+ You can change these limits in Settings: the monthly spending limit, and the step limits
+ under the advanced settings.
+
)}
)}
diff --git a/src/ui/settings.tsx b/src/ui/settings.tsx
index a708ce1..465da93 100644
--- a/src/ui/settings.tsx
+++ b/src/ui/settings.tsx
@@ -1,4 +1,6 @@
import {
+ ChevronDown,
+ ChevronRight,
Database,
Download,
Gauge,
@@ -8,6 +10,7 @@ import {
RefreshCw,
Save,
ShieldCheck,
+ SlidersHorizontal,
Trash2,
Wrench,
} from 'lucide-react';
@@ -15,9 +18,16 @@ import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } fr
import type { Budgets, Pacing, Settings, TextSharing, UpdateCheck } from '../shared/bridge';
import { Badge, Busy, Confirm, Modal, Notice, PageTitle } from './components';
import { useWorkspace } from './context';
-import { pullCeiling } from '../shared/claude-cost';
+import { advancedShown, setAdvancedShown } from './advanced';
import { calendarDate, dateTime, money } from './format';
-import { budgetLimits, fasterThanDefault, libraryLimits, pacingLimits, type Limit } from './limits';
+import {
+ budgetLimits,
+ fasterThanDefault,
+ libraryLimits,
+ pacingLimits,
+ spendLimit,
+ type Limit,
+} from './limits';
/** The page's working copy. Numbers stay as typed until Save, so a half-typed value is not lost. */
interface Form {
@@ -30,6 +40,7 @@ interface Form {
autoRefreshStale: boolean;
stalenessDays: string;
keepVersions: string;
+ spendLimitUsd: string;
pacing: Record;
budgets: Record;
}
@@ -48,6 +59,7 @@ const toForm = (s: Settings): Form => ({
autoRefreshStale: s.autoRefreshStale,
stalenessDays: String(s.stalenessDays),
keepVersions: String(s.keepVersions),
+ spendLimitUsd: String(s.spendLimitUsd),
pacing: typed(s.pacing),
budgets: typed(s.budgets),
});
@@ -122,32 +134,6 @@ const budgetFields: { key: keyof Budgets; label: string; unit: string; help: str
help: 'The most sections Claude may put in one plan. Sections past it are left out of the draft, and Claude is told which. You still review every item, and each one can cost page loads.',
},
];
-/**
- * What Claude can cost on one queued pull with the model and the look-at-the-page switch as chosen.
- * The queue's search for a page and the look have fixed token budgets; requests and plans have none.
- */
-function QueueCeiling({ model, lookOn }: { model: string; lookOn: boolean }) {
- const { state } = useWorkspace();
- if (!model) return null;
- const ceiling = pullCeiling(state.claude, lookOn, model);
- return (
-
- {ceiling ? (
- <>
- In the pull queue, Claude’s search for a page CodePull cannot find by itself has a fixed
- token budget: at most {money(ceiling.search)} a pull with {model}
- {lookOn && <>, and a look at the page adds at most {money(ceiling.look)}>}. Most pulls do not
- need Claude at all.
- >
- ) : (
- <>
- The price list in the app has no price for {model}, so what Claude can cost on a pull cannot be
- estimated.
- >
- )}
-
- {modelPicker(
- 'model',
- 'Model for requests',
- 'Works out the code and section of a plain-language request.',
- )}
- {modelPicker(
- 'plannerModel',
- 'Model for project plans',
- 'Reads project notes and drafts the plan.',
+
+ {!state.models.length ? (
+ <>Once a key is saved, CodePull picks the Claude model for you.>
+ ) : inUse.model === inUse.plannerModel ? (
+ <>
+ CodePull uses {modelName(inUse.model)} for your requests and your
+ project plans. You do not need to choose anything.
+ >
+ ) : (
+ <>
+ CodePull uses {modelName(inUse.model)} for requests and{' '}
+ {modelName(inUse.plannerModel)} for project plans. You do not need to
+ choose anything.
+ >
)}
-
-
The lists hold the models your key can use, as reported by Anthropic.
-
-
- Your request and your project notes are always sent when you use Claude. Whole sections are
- never sent at any setting. This keeps the code text you license on this computer, keeps
- wording on a page from steering Claude, and keeps each step small: Claude needs section
- numbers and headings to choose what to pull, never the text itself.
-
-
-
Limits for one piece of work
-
- Tokens are not capped for your requests and plans: each call may use the model’s
- whole output. These limits stop a request that goes in circles. When one is reached,
- CodePull stops and asks whether to continue with another allowance of the same size. A
- request also pauses to ask after 15 minutes of work.
-
-
-
+
+ When this month’s estimated cost reaches it, every call to Claude stops:
+ requests, plans and the queue’s own. Nothing calls Claude again until you raise
+ the limit or the month ends. Pulls that need no help from Claude carry on. 0 means no
+ limit. Allowed: {limitNote(spendLimit, 'dollars')}. The estimate comes from the price
+ list in the app, so a model with no listed price counts as nothing.
+ >
+ }
+ change={(spendLimitUsd) => setNumber('spendLimitUsd', { spendLimitUsd })}
+ />
+ {spend.reached && (
+
+ Claude is stopped. This month’s estimated cost reached your limit
+ of {money(spend.limitUsd)}. Raise the limit above and save to go on, or wait for next
+ month.
+
+ )}
This month
{state.usage.input.toLocaleString()} input tokens · {state.usage.output.toLocaleString()}{' '}
output tokens · estimated cost {money(state.usage.estCostUsd)}
+ {spend.limitUsd > 0 && <> of your {money(spend.limitUsd)} limit>}
The cost is an estimate from the price list in the app, not a bill. Your Anthropic
@@ -644,121 +592,262 @@ export function SettingsPage() {
-
-
-
-
-
Pulling
+
+
+
+
+ Advanced settings
+
+ Models, what Claude may see, limits, pacing, the library, diagnostics and deleting
+ data. CodePull has chosen values that work. You do not need to change any of them.
+
- CodePull opens each page for you in your own signed-in session, reads the section, checks
- it and saves it. It keeps to the pacing below and stops whenever the site asks for sign-in,
- a human check or a subscription. It never buys, starts a trial or signs up for anything,
- and never moves a pull to another account by itself.
-
-
-
-
-
-
-
-
-
Pacing
+ {advanced && (
+
+
+
+
+
Claude: models, sharing and limits
+
-
-
-
- Automated pulls load pages about as often as one person reading the site. Every limit below
- is counted for each account by itself. The hard limits are built in and cannot be passed by
- any setting, plan or request.
-
- {fast.length > 0 && (
-
- Faster than the defaults. {fast.map((f) => f.label).join(', ')}
- {fast.length === 1 ? ' is' : ' are'} set to load pages more often than CodePull ships
- with. Slower is safer: a site may limit or close an account that loads pages quickly.
-
- )}
-
+ {modelPicker(
+ 'model',
+ 'Model for requests',
+ 'Works out the code and section of a plain-language request, and finds a page the queue could not.',
+ )}
+ {modelPicker(
+ 'plannerModel',
+ 'Model for project plans',
+ 'Reads project notes and drafts the plan.',
+ )}
+
+
+
+ Automatic follows the choice CodePull ships with. The lists hold the models your key
+ can use, as reported by Anthropic.
+
+ Your request and your project notes are always sent when you use Claude. Whole sections
+ are never sent as text at any setting. This keeps the code text you license on this
+ computer, keeps wording on a page from steering Claude, and keeps each step small: Claude
+ needs section numbers and headings to choose what to pull, never the text itself.
+
+
-
-
-
-
-
-
-
Library
-
-
-
-
- setNumber('stalenessDays', { stalenessDays })}
- />
- setNumber('keepVersions', { keepVersions })}
- />
+
+ Let Claude look at the page when CodePull cannot find a section on it
+
+ On unless you turn it off. When the page reader cannot place a section or its
+ chapter, CodePull sends Claude screenshots of the page with numbered marks, and
+ Claude points to the right place. The screenshots show code text, so they go to the
+ Anthropic API. They are never saved. The section’s text is still read from the
+ page, never from Claude, and the pull is marked for your review.
+
+
+
+
+
Limits for one piece of work
+
+ Tokens are not capped for anything Claude does: each call may use the model’s whole
+ output. These limits stop a request that goes in circles. When one is reached, CodePull
+ stops and asks whether to continue with another allowance of the same size. A request
+ also pauses to ask after 60 minutes of work. What bounds the money is the monthly
+ spending limit above.
+
+ CodePull opens each page for you in your own signed-in session, reads the section,
+ checks it and saves it. It keeps to the pacing below and stops whenever the site asks
+ for sign-in, a human check or a subscription. It never buys, starts a trial or signs up
+ for anything, and never moves a pull to another account by itself.
+
+
+
+
+
+
+
+
+
+
Pacing
+
+
+
+
+ Automated pulls load pages about as often as one person reading the site. Every limit
+ below is counted for each account by itself. The hard limits are built in and cannot be
+ passed by any setting, plan or request.
+
+ {fast.length > 0 && (
+
+ Faster than the defaults. {fast.map((f) => f.label).join(', ')}
+ {fast.length === 1 ? ' is' : ' are'} set to load pages more often than CodePull ships
+ with. Slower is safer: a site may limit or close an account that loads pages quickly.
+
+ )}
+
{problemCount
@@ -788,84 +877,86 @@ export function SettingsPage() {
-
-
-
-
-
Advanced
-
-
-
-
-
- Export diagnostics
-
- Saves a ZIP with the app version, your settings, the state of the queue and the
- activity log. It holds no code text, no passwords and no API key.
-
- Deletes every pull and document, every plan, the pull queue, every request and the
- activity log. Keeps your settings, your API key, your accounts with their saved
- passwords and sign-ins, and the code lists CodePull has read. Files you exported
- elsewhere are not touched. CodePull keeps running.
-
+
+
+
+ Export diagnostics
+
+ Saves a ZIP with the app version, your settings, the state of the queue and the
+ activity log. It holds no code text, no passwords and no API key.
+
- Deletes every pull and document, every plan, the activity log, your saved API key and
- the browser sessions of all accounts, then restarts CodePull. Files you exported
- elsewhere are not touched.
-
+
+
+
+ Delete all content
+
+ Deletes every pull and document, every plan, the pull queue, every request and the
+ activity log. Keeps your settings, your API key, your accounts with their saved
+ passwords and sign-ins, and the code lists CodePull has read. Files you exported
+ elsewhere are not touched. CodePull keeps running.
+
+ Deletes every pull and document, every plan, the activity log, your saved API key and
+ the browser sessions of all accounts, then restarts CodePull. Files you exported
+ elsewhere are not touched.
+
@@ -890,13 +981,16 @@ export function SettingsPage() {
Requests to UpCodes, made in your own signed-in session: the pages
- opened to pull a section, at the pace set above.
+ opened to pull a section, at the pace in the advanced settings.
Anthropic API calls, only when you use Claude: your request, your
project notes and details of each step Claude takes, such as code names and section
numbers. What it may see from a page follows the text-sharing setting, now “
{sharing.find((s) => s.value === state.settings.textSharing)?.title}”.
+ {state.settings.visualFallback
+ ? ' When CodePull cannot find a section on a page, it also sends screenshots of that page, which show code text. You can turn that off in the advanced settings.'
+ : ' Screenshots of a page are not sent: looking at the page is turned off.'}
One request to GitHub, only when you choose Check for updates: it asks
diff --git a/src/ui/styles.css b/src/ui/styles.css
index 889380d..e080895 100644
--- a/src/ui/styles.css
+++ b/src/ui/styles.css
@@ -271,6 +271,10 @@ small {
font-size: 11px;
font-weight: 500;
}
+.token-meter-stopped {
+ color: #8a5a00;
+ font-weight: 600;
+}
.account-indicator {
gap: 7px;
}
@@ -450,6 +454,17 @@ input[type='checkbox'] {
cursor: pointer;
font-weight: 440;
}
+/* A checkbox with an explanation: the explanation sits under its label, not run on after it. */
+.checkline:has(small) {
+ align-items: flex-start;
+}
+.checkline small {
+ display: block;
+ margin-top: 2px;
+ color: var(--muted);
+ font-size: 12px;
+ font-weight: 400;
+}
.grid-two,
.grid-three {
display: grid;
diff --git a/test/agent-client.test.ts b/test/agent-client.test.ts
index 4373de5..051ee44 100644
--- a/test/agent-client.test.ts
+++ b/test/agent-client.test.ts
@@ -18,14 +18,17 @@ import {
limitsFor,
listModels,
loadAgentAssets,
+ type Effort,
+ effortFor,
pickModel,
+ resolveModel,
promptHash,
publicApiError,
readModelDefaults,
readPricing,
tools,
} from '../src/agent';
-import { describeStop, QUEUE_SEARCH_TOKENS } from '../src/agent/budget';
+import { describeStop, QUEUE_SEARCH_STEPS, spendState, spendStopMessage } from '../src/agent/budget';
import { budgetLimits } from '../src/shared/validation';
import { settingsWith } from './helpers/fake-services';
@@ -65,7 +68,17 @@ test('the model list comes from the Models API, not from a fixed list', async ()
info('model-small', { max_tokens: 64_000, capabilities: { effort: { supported: false } } }),
info('model-bare', { display_name: '', max_tokens: null, capabilities: null }),
info('model-strict', {
- capabilities: { effort: { supported: true }, structured_outputs: { supported: true } },
+ capabilities: {
+ effort: {
+ supported: true,
+ low: { supported: true },
+ medium: { supported: true },
+ high: { supported: true },
+ xhigh: { supported: true },
+ max: { supported: false },
+ },
+ structured_outputs: { supported: true },
+ },
}),
info('model-loose', { capabilities: { structured_outputs: { supported: false } } }),
info('model-new'),
@@ -83,6 +96,8 @@ test('the model list comes from the Models API, not from a fixed list', async ()
name: 'MODEL-STRICT',
maxOutputTokens: 128_000,
effort: true,
+ // The levels the model reports, so an effort it does not offer is never sent.
+ efforts: ['low', 'medium', 'high', 'xhigh'],
structuredOutputs: true,
},
{ id: 'model-loose', name: 'MODEL-LOOSE', maxOutputTokens: 128_000, structuredOutputs: false },
@@ -113,9 +128,44 @@ test('a role’s model is the first preference the key offers, else the first av
assert.equal(pickModel('planner', available, defaults), 'model-a');
assert.equal(pickModel('agent', [available[0]!], defaults), 'model-z');
assert.equal(pickModel('agent', [], defaults), '');
- assert.deepEqual(defaults.roles.planner, { prefer: ['model-a', 'model-b'], effort: 'high' });
+ // A level the file misspells falls back to the role's own: plans think hardest.
+ assert.deepEqual(defaults.roles.planner, { prefer: ['model-a', 'model-b'], effort: 'xhigh' });
assert.deepEqual(defaults.models, { 'model-a': { fallbacks: true }, 'model-b': { fallbacks: false } });
- assert.deepEqual(readModelDefaults({}).roles.agent, { prefer: [], effort: 'medium' });
+ assert.deepEqual(readModelDefaults({}).roles.agent, { prefer: [], effort: 'high' });
+ assert.deepEqual(readModelDefaults({}).look, { effort: 'medium' });
+ assert.deepEqual(readModelDefaults({ look: { effort: 'max' } }).look, { effort: 'max' });
+});
+
+test('automatic follows the shipped preference; a pick by hand wins while the key offers it', () => {
+ const defaults = readModelDefaults({
+ roles: { agent: { prefer: ['model-b'] }, planner: { prefer: ['model-a'] } },
+ });
+ const available = [
+ { id: 'model-z', name: 'Z' },
+ { id: 'model-a', name: 'A' },
+ { id: 'model-b', name: 'B' },
+ ];
+ // An empty pick is the automatic choice, for each kind of work by itself.
+ assert.equal(resolveModel('agent', '', available, defaults), 'model-b');
+ assert.equal(resolveModel('planner', '', available, defaults), 'model-a');
+ assert.equal(resolveModel('agent', 'model-z', available, defaults), 'model-z');
+ // A pick the key no longer offers is not used: the automatic choice is.
+ assert.equal(resolveModel('agent', 'model-gone', available, defaults), 'model-b');
+ assert.equal(resolveModel('agent', '', [], defaults), '');
+});
+
+test('an effort is lowered to the highest level the model offers, and left out without the control', () => {
+ const all = { effort: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max'] as Effort[] };
+ assert.equal(effortFor(all, 'xhigh'), 'xhigh');
+ assert.equal(effortFor({ effort: true, efforts: ['low', 'medium', 'high'] }, 'xhigh'), 'high');
+ assert.equal(effortFor({ effort: true, efforts: ['low', 'high', 'max'] }, 'medium'), 'low');
+ // A list saved before levels were recorded is read as offering low, medium and high.
+ assert.equal(effortFor({ effort: true }, 'xhigh'), 'high');
+ assert.equal(effortFor({ effort: true }, 'medium'), 'medium');
+ // Nothing at or below what was asked for: the model's own default stands.
+ assert.equal(effortFor({ effort: true, efforts: ['max'] }, 'high'), undefined);
+ assert.equal(effortFor({}, 'high'), undefined);
+ assert.equal(effortFor(undefined, 'high'), undefined);
});
test('the bundled assets load and agree with each other', () => {
@@ -123,14 +173,17 @@ test('the bundled assets load and agree with each other', () => {
const { modelDefaults, pricing } = assets;
assert.ok(modelDefaults.roles.agent.prefer.length >= 1);
assert.ok(modelDefaults.roles.planner.prefer.length >= 1);
- // The plan asks for a capable mid-tier model for requests and the strongest for planning.
- assert.notEqual(modelDefaults.roles.agent.prefer[0], modelDefaults.roles.planner.prefer[0]);
- assert.equal(modelDefaults.roles.agent.effort, 'medium');
- assert.equal(modelDefaults.roles.planner.effort, 'high');
- for (const id of [...modelDefaults.roles.agent.prefer, ...modelDefaults.roles.planner.prefer]) {
+ // The owner's choice, 1 December 2026: the same model for requests and for plans, an Opus first.
+ assert.equal(modelDefaults.roles.agent.prefer[0], modelDefaults.roles.planner.prefer[0]);
+ assert.match(modelDefaults.roles.agent.prefer[0]!, /^claude-opus-/);
+ assert.equal(modelDefaults.roles.agent.effort, 'high');
+ assert.equal(modelDefaults.roles.planner.effort, 'xhigh');
+ assert.equal(modelDefaults.look.effort, 'medium');
+ // Every model the app may choose by itself has a price, or the spending limit could not see it.
+ for (const id of [...modelDefaults.roles.agent.prefer, ...modelDefaults.roles.planner.prefer])
assert.ok(pricing[id], 'no price for ' + id);
- assert.equal(modelDefaults.models[id]?.fallbacks, true, id);
- }
+ for (const role of [modelDefaults.roles.agent, modelDefaults.roles.planner])
+ assert.equal(modelDefaults.models[role.prefer[0]!]?.fallbacks, true, role.prefer[0]);
assert.ok(!('_note' in pricing));
for (const [id, price] of Object.entries(pricing)) {
assert.ok(price.input > 0 && price.output > price.input, id);
@@ -168,7 +221,7 @@ test('the bundled assets load and agree with each other', () => {
const custom = loadAgentAssets(dir);
assert.deepEqual(custom.pricing, { m: { input: 1, output: 0, cacheRead: 0, cacheWrite: 0 } });
assert.equal(custom.siteNotes, 'Notes');
- assert.deepEqual(custom.modelDefaults.roles.agent, { prefer: ['m'], effort: 'medium' });
+ assert.deepEqual(custom.modelDefaults.roles.agent, { prefer: ['m'], effort: 'high' });
writeFileSync(path.join(dir, 'pricing.json'), '[1,2]');
assert.throws(() => loadAgentAssets(dir), /Invalid asset file: pricing.json/);
} finally {
@@ -185,8 +238,8 @@ test('the system prompt is stable across runs and changes only with settings or
const system = buildSystemPrompt(systemPrompt, siteNotes, settings);
assert.equal(system, buildSystemPrompt(systemPrompt, siteNotes, settingsWith()));
assert.doesNotMatch(system, /\{\{/);
- assert.match(system, /at most 30 items \(the software never accepts more than 60\)/);
- assert.match(system, /A single request gets 14 tool rounds and a project plan gets 24/);
+ assert.match(system, /at most 60 items \(the software never accepts more than 60\)/);
+ assert.match(system, /A single request gets 40 tool rounds and a project plan gets 60/);
assert.match(system, /Text sharing is set to outlines/);
assert.ok(system.includes(siteNotes.trim()));
// Nothing per-run is in the cached prefix.
@@ -261,21 +314,25 @@ test('budgets come from settings and usage is counted per attempt', () => {
const settings = settingsWith();
assert.deepEqual(limitsFor('request', settings), {
maxIterations: budgetLimits.requestIterations.initial,
- wallClockMs: 15 * 60_000,
+ wallClockMs: 60 * 60_000,
maxToolErrorsInARow: 3,
fallbackTokensPerCall: 64_000,
});
const plan = limitsFor('project_plan', settings);
assert.equal(plan.maxIterations, budgetLimits.planIterations.initial);
assert.deepEqual(limitsFor('xref_expand', settings), limitsFor('request', settings));
- // The queue's search for a page has the request steps, plus fixed token budgets that no setting
- // changes, so the queue can say what one pull costs at most. Requests and plans have none.
- const { tokens, ...searchSteps } = limitsFor('fallback_nav', settings);
- assert.deepEqual(searchSteps, limitsFor('request', settings));
- assert.deepEqual(tokens, { ...QUEUE_SEARCH_TOKENS });
- assert.equal(limitsFor('request', settings).tokens, undefined);
- assert.equal(limitsFor('project_plan', settings).tokens, undefined);
- // Tokens are not a setting any more: only steps, time and the plan size are.
+ // The queue's search for a page has its own step limit, which no setting changes: nobody
+ // watches it, and a step may spend a paced page load. No kind of run has a token budget.
+ const search = limitsFor('fallback_nav', settings);
+ assert.equal(search.maxIterations, QUEUE_SEARCH_STEPS);
+ assert.equal(
+ limitsFor('fallback_nav', settingsWith({ budgets: { ...settings.budgets, requestIterations: 2 } }))
+ .maxIterations,
+ QUEUE_SEARCH_STEPS,
+ );
+ for (const kind of ['request', 'project_plan', 'xref_expand', 'fallback_nav'] as const)
+ assert.ok(!('tokens' in limitsFor(kind, settings)), kind);
+ // Tokens are not a setting: only steps, time and the plan size are.
assert.deepEqual(Object.keys(budgetLimits).sort(), [
'maxPlanItems',
'planIterations',
@@ -283,32 +340,43 @@ test('budgets come from settings and usage is counted per attempt', () => {
]);
const limits = limitsFor('request', settings);
+ const steps = limits.maxIterations;
const usage = {
...emptyUsage(),
- iterations: 13,
+ iterations: steps - 1,
input: 100_000,
cacheRead: 40_000,
cacheWrite: 9_999,
};
assert.equal(budgetStop(usage, limits, 1, 0), undefined);
- assert.equal(budgetStop({ ...usage, iterations: 14 }, limits, 1, 0), 'iterations');
+ assert.equal(budgetStop({ ...usage, iterations: steps }, limits, 1, 0), 'iterations');
// However many tokens a run uses, tokens alone never stop it.
assert.equal(
budgetStop({ ...usage, input: 50_000_000, cacheRead: 9_000_000, output: 3_000_000 }, limits, 1, 0),
undefined,
);
- assert.equal(budgetStop(usage, limits, 1, 15 * 60_000), 'wall_clock');
- assert.equal(budgetStop({ ...usage, iterations: 27 }, limits, 2, 29 * 60_000), undefined);
- assert.equal(budgetStop({ ...usage, iterations: 14 }, limits, 0, 0), 'iterations');
- // The queue's search does not send a request that would carry it past its input budget
- // (149,999 sent so far of 150,000), and stops once its output budget is used.
- const search = limitsFor('fallback_nav', settings);
- assert.equal(budgetStop(usage, limits, 1, 0, 20_000), undefined, 'a request has no token budget');
- assert.equal(budgetStop(usage, search, 1, 0, 1), undefined, 'exactly at the budget is allowed');
- assert.equal(budgetStop(usage, search, 1, 0, 2), 'input_tokens');
- assert.equal(budgetStop({ ...usage, cacheWrite: 10_001 }, search, 1, 0), 'input_tokens');
- assert.equal(budgetStop({ ...usage, output: 24_000 }, search, 1, 0), 'output_tokens');
- assert.match(describeStop('input_tokens', search), /budget of 150,000 input tokens/);
+ assert.equal(budgetStop(usage, limits, 1, 60 * 60_000), 'wall_clock');
+ assert.equal(budgetStop(usage, limits, 1, 59 * 60_000), undefined);
+ assert.equal(budgetStop({ ...usage, iterations: 2 * steps - 1 }, limits, 2, 119 * 60_000), undefined);
+ assert.equal(budgetStop({ ...usage, iterations: steps }, limits, 0, 0), 'iterations');
+ // Neither does the queue's own search: it stops at its steps, like any run.
+ assert.equal(
+ budgetStop({ ...usage, iterations: 0, input: 50_000_000, output: 3_000_000 }, search, 1, 0),
+ undefined,
+ );
+ assert.equal(
+ budgetStop({ ...emptyUsage(), iterations: QUEUE_SEARCH_STEPS }, search, 1, 0),
+ 'iterations',
+ );
+ assert.match(describeStop('iterations', search), /limit of 24 steps/);
+ assert.match(describeStop('wall_clock', search), /time limit of 60 minutes/);
+
+ // The month's spending limit: reached at the limit, never with no limit, never by a bad figure.
+ assert.deepEqual(spendState(12.5, 200), { monthUsd: 12.5, limitUsd: 200, reached: false });
+ assert.equal(spendState(200, 200).reached, true);
+ assert.equal(spendState(1_000_000, 0).reached, false, '0 is no limit');
+ assert.deepEqual(spendState(Number.NaN, -5), { monthUsd: 0, limitUsd: 0, reached: false });
+ assert.match(spendStopMessage({ limitUsd: 1500 }), /reached your limit of \$1,500\. Raise the limit/);
const pricing = { priced: { input: 2, output: 10, cacheRead: 0.1, cacheWrite: 2.5 } };
const response = {
diff --git a/test/agent-runtime.test.ts b/test/agent-runtime.test.ts
index 9b901b7..8e5b328 100644
--- a/test/agent-runtime.test.ts
+++ b/test/agent-runtime.test.ts
@@ -2,7 +2,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import Anthropic from '@anthropic-ai/sdk';
import { allowedTools, compactTranscript, createRuntime, readTurn, type RunSpec } from '../src/agent';
-import { QUEUE_SEARCH_TOKENS } from '../src/agent/budget';
+import { QUEUE_SEARCH_STEPS, spendState } from '../src/agent/budget';
import {
harness,
type ModelCall,
@@ -46,30 +46,111 @@ test('a run started for a queued pull records the pull, so its cost shows on it'
assert.ok(!('jobId' in h.runs.get(other)!), 'a request is not tied to a pull');
});
-test('the queue’s search for a page never sends past its input budget; a watched request has none', async () => {
- const script = () =>
+test('no run has a token budget: the queue’s search stops at its own steps, whatever it has sent', async () => {
+ const heavy = () =>
scriptedClient([
- { calls: [lookup('a')], usage: { input_tokens: 60_000 } },
- { calls: [lookup('b')], usage: { input_tokens: 70_000 } },
- { text: 'Done.', usage: { input_tokens: 80_000 } },
+ { calls: [lookup('a')], usage: { input_tokens: 600_000, output_tokens: 90_000 } },
+ { calls: [lookup('b')], usage: { input_tokens: 700_000, output_tokens: 90_000 } },
+ { text: 'Done.', usage: { input_tokens: 800_000 } },
]);
- const sent = (run: { usage: { input: number; cacheRead: number; cacheWrite: number } }) =>
- run.usage.input + run.usage.cacheRead + run.usage.cacheWrite;
- const searchClient = script();
- const search = await createRuntime(harness().deps(searchClient)).start(
+ for (const spec of [
+ request('Find § 1.1', { kind: 'fallback_nav', jobId: 'job-1' }),
+ request('x 1.1'),
+ ]) {
+ const client = heavy();
+ const run = await createRuntime(harness().deps(client)).start(spec).done;
+ assert.equal(client.calls.length, 3, spec.kind + ' is not stopped by tokens');
+ assert.equal(run.status, 'complete');
+ assert.equal(run.usage.input, 2_100_000);
+ }
+
+ // The search has its own step limit, which the user's step setting does not change: nobody
+ // watches it, and each step may spend a paced page load.
+ const rounds: Turn[] = Array.from({ length: QUEUE_SEARCH_STEPS + 5 }, (_, i) => [lookup('q' + i)]);
+ const h = harness({ budgets: { requestIterations: 2 } as never });
+ const client = scriptedClient(rounds);
+ const search = await createRuntime(h.deps(client)).start(
request('Find § 1.1', { kind: 'fallback_nav', jobId: 'job-1' }),
).done;
- // The third request would carry the second (70,000), its reply and the new results: past 150,000.
- assert.equal(searchClient.calls.length, 2);
+ assert.equal(client.calls.length, QUEUE_SEARCH_STEPS);
assert.equal(search.status, 'awaiting_user');
- assert.match(search.question?.text ?? '', /budget of 150,000 input tokens/);
- assert.ok(sent(search) <= QUEUE_SEARCH_TOKENS.input, String(sent(search)));
-
- const requestClient = script();
- const watched = await createRuntime(harness().deps(requestClient)).start(request('x 1.1')).done;
- assert.equal(requestClient.calls.length, 3, 'a request has no token budget');
- assert.equal(watched.status, 'complete');
- assert.ok(sent(watched) > QUEUE_SEARCH_TOKENS.input);
+ assert.match(search.question?.text ?? '', /limit of 24 steps/);
+});
+
+test('the month’s spending limit is a kill switch: nothing is sent while it is reached', async () => {
+ // Reached before the run starts: it fails at once, with what to do, and Claude is not called.
+ let spent = 250;
+ const spend = () => spendState(spent, 200);
+ const h = harness();
+ const refused = scriptedClient(['unreachable']);
+ const never = await createRuntime(h.deps(refused, { spend })).start(request('CEC 695.3')).done;
+ assert.equal(never.status, 'failed');
+ assert.match(
+ never.summary ?? '',
+ /Claude is stopped: this month's estimated cost reached your limit of \$200/,
+ );
+ assert.equal(refused.calls.length, 0);
+
+ // Reached while a run works: the next call is not made, whatever kind of run it is.
+ for (const kind of ['request', 'project_plan', 'fallback_nav'] as const) {
+ spent = 10;
+ const live = harness();
+ const client = scriptedClient([
+ { calls: [lookup('a')], before: () => (spent = 200) },
+ [lookup('b')],
+ 'Done.',
+ ]);
+ const runtime = createRuntime(live.deps(client, { spend }));
+ const held = await runtime.start(request('CEC 2022 695.3', { kind })).done;
+ assert.equal(client.calls.length, 1, kind);
+ assert.equal(held.status, 'awaiting_user', kind);
+ assert.equal(held.question?.kind, 'budget');
+ assert.deepEqual(held.question?.options, ['Continue', 'Stop']);
+ assert.match(held.question?.text ?? '', /reached your limit of \$200\. Raise the limit in Settings/);
+ // Continue while the limit still stands sends nothing and asks again.
+ const still = await runtime.answer(held.id, 'Continue').done;
+ assert.equal(still.status, 'awaiting_user', kind);
+ assert.equal(client.calls.length, 1, kind);
+ // Once the user has raised the limit, Continue goes on, and no step allowance was used up.
+ spent = 10;
+ const done = await runtime.answer(held.id, 'Continue').done;
+ assert.equal(done.status, 'complete', kind);
+ assert.equal(client.calls.length, 3, kind);
+ assert.ok(!done.log.some((line) => /another allowance/.test(line.text)), kind);
+ }
+
+ // A request that failed part-way is not sent again past the limit. What the interrupted reply
+ // already cost is recorded at once, so the month's spending counts it before anything is sent.
+ const dropped = () => [
+ { error: Error('The connection dropped.'), partial: { input_tokens: 0, output_tokens: 1_000 } },
+ 'Done on the second attempt.',
+ ];
+ const tight = harness();
+ const recorded = () => tight.runs.list(50).reduce((sum, run) => sum + run.usage.estCostUsd, 0);
+ const once = scriptedClient(dropped());
+ // 1,000 output tokens of the test model cost $0.01: past a limit of half a cent.
+ const cut = await createRuntime(
+ tight.deps(once, { spend: () => spendState(recorded(), 0.005) }),
+ ).start(request('CEC 2022 695.3')).done;
+ assert.equal(once.calls.length, 1, 'the failed request was sent again past the limit');
+ assert.equal(cut.status, 'awaiting_user');
+ assert.match(cut.question?.text ?? '', /Claude is stopped/);
+ assert.equal(cut.usage.output, 1_000);
+ assert.equal(tight.runs.get(cut.id)!.usage.output, 1_000, 'the partial usage was recorded');
+ // Below the limit, the same failure is sent again as before.
+ const twice = scriptedClient(dropped());
+ const retried = await createRuntime(
+ harness().deps(twice, { spend: () => spendState(0.01, 200) }),
+ ).start(request('CEC 2022 695.3')).done;
+ assert.equal(twice.calls.length, 2);
+ assert.equal(retried.status, 'complete');
+
+ // No limit set: nothing stops, however much was spent.
+ const free = scriptedClient([[lookup('a')], 'Done.']);
+ const open = await createRuntime(
+ harness().deps(free, { spend: () => spendState(1_000_000, 0) }),
+ ).start(request('x 1.1')).done;
+ assert.equal(open.status, 'complete');
});
test('a request loop sends a frozen, cached prefix and an append-only transcript', async () => {
@@ -175,6 +256,31 @@ test("a project plan uses the planner model, its own tools and that model's whol
assert.equal(explicit.model, 'model-agent');
});
+test('with nothing picked, each kind of work runs on the model chosen for it', async () => {
+ // An empty setting is automatic: the shipped preference for the role, among what the key offers.
+ const h = harness({ model: '', plannerModel: '' });
+ const asked = scriptedClient(['Done.']);
+ const quick = await createRuntime(h.deps(asked)).start(request('CEC 695.3')).done;
+ assert.equal(quick.status, 'complete');
+ assert.equal(quick.model, 'model-agent');
+ assert.equal(asked.calls[0]!.body.model, 'model-agent');
+ const planned = scriptedClient(['Drafted.']);
+ const plan = await createRuntime(h.deps(planned)).start(
+ request('A lab building in Sacramento', { kind: 'project_plan' }),
+ ).done;
+ assert.equal(plan.model, 'model-planner');
+ // A plan thinks harder than a request, at the level set for planning.
+ assert.deepEqual(planned.calls[0]!.body.output_config, { effort: 'high' });
+ assert.deepEqual(asked.calls[0]!.body.output_config, { effort: 'medium' });
+ // A pick by hand the key no longer offers is not used either.
+ const gone = harness({ model: 'model-retired' });
+ const again = scriptedClient(['Done.']);
+ assert.equal(
+ (await createRuntime(gone.deps(again)).start(request('x 1.1')).done).model,
+ 'model-agent',
+ );
+});
+
test('a run that cannot start fails at once without calling Claude', async () => {
const cases: [
Parameters[0],
@@ -183,8 +289,7 @@ test('a run that cannot start fails at once without calling Claude', async () =>
RegExp,
][] = [
[{}, { apiKey: async () => undefined }, 'CEC 695.3', /Add your Anthropic API key/],
- [{ model: '' }, {}, 'CEC 695.3', /select an available Claude model/],
- [{ model: 'model-retired' }, {}, 'CEC 695.3', /select an available Claude model/],
+ [{}, { models: () => [] }, 'CEC 695.3', /No Claude model is available to your API key/],
[{}, {}, ' ', /Enter a request/],
];
for (const [settings, deps, text, message] of cases) {
@@ -426,11 +531,11 @@ test('a run that reaches a limit asks before spending more', async () => {
const slow = harness();
const dawdle = scriptedClient([
- { calls: [lookup('a')], before: () => (slow.clock.now += 16 * 60_000) },
+ { calls: [lookup('a')], before: () => (slow.clock.now += 61 * 60_000) },
'unreachable',
]);
const overTime = await createRuntime(slow.deps(dawdle)).start(request('x 1.1')).done;
- assert.match(overTime.question?.text ?? '', /time limit of 15 minutes/);
+ assert.match(overTime.question?.text ?? '', /time limit of 60 minutes/);
// Time spent waiting for the answer is not charged to the next allowance.
slow.clock.now += 3 * 60 * 60_000;
const resumedClient = scriptedClient(['Finished after the wait.']);
diff --git a/test/agent-services.test.ts b/test/agent-services.test.ts
index 31f86e2..40bb763 100644
--- a/test/agent-services.test.ts
+++ b/test/agent-services.test.ts
@@ -507,7 +507,7 @@ test('what an ended run gathered is not kept, and a stored value that does not f
);
assert.deepEqual(w.store.plan(drafted.plan_id).facts, []);
// Other settings are untouched by any of this.
- assert.equal(w.store.settings().budgets.maxPlanItems, 30);
+ assert.equal(w.store.settings().budgets.maxPlanItems, 60);
await after.dispose();
});
diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.ts
index c9c1de3..7c1c46c 100644
--- a/test/agent-tools.test.ts
+++ b/test/agent-tools.test.ts
@@ -84,7 +84,8 @@ test('the registry holds the sixteen planned tools, in a fixed order, with hygie
for (const banned of ['$ref', 'oneOf', 'anyOf', 'allOf', '$schema'])
assert.ok(!(banned in schema), `${tool.name} has ${banned} at its root`);
assert.ok(tool.description.length > 40, tool.name);
- assert.ok(tool.maxResultBytes > 0 && tool.maxResultBytes <= 8000, tool.name);
+ // Large enough that a code list or a long outline arrives whole, and still bounded.
+ assert.ok(tool.maxResultBytes >= 8000 && tool.maxResultBytes <= 64_000, tool.name);
}
// The definitions are deterministic, so the cached request prefix is byte-identical between calls.
assert.equal(JSON.stringify(apiTools('request')), JSON.stringify(apiTools('request')));
@@ -217,19 +218,26 @@ test('service errors map to the tool error taxonomy and unexpected errors are sc
test('results are size-bounded by shortening lists, never by cutting a value', async () => {
const { ctx, services } = context();
- const long = Array.from({ length: 60 }, (_, i) => ({
- marker: '903.' + i,
- untrusted_title: 'Heading '.repeat(30) + i,
- depth: 1,
- }));
- services.on('getSection', async () => section({ outline: long }));
+ const headings = (count: number) =>
+ Array.from({ length: count }, (_, i) => ({
+ marker: '903.' + i,
+ untrusted_title: 'Heading '.repeat(30) + i,
+ depth: 1,
+ }));
+ // A long section's outline arrives whole: Claude checks its subsections against it.
+ services.on('getSection', async () => section({ outline: headings(60) }));
+ const whole = await executeTool('request', 'get_section', { account_id: 'a1', ref: 'r_1' }, ctx);
+ assert.equal((whole.result as Record).outline.length, 60);
+ assert.ok(!('truncated' in whole.result));
+ // One far past the cap is shortened.
+ services.on('getSection', async () => section({ outline: headings(600) }));
const outcome = await executeTool('request', 'get_section', { account_id: 'a1', ref: 'r_1' }, ctx);
assert.equal(outcome.result.ok, true);
const text = JSON.stringify(outcome.result);
- assert.ok(Buffer.byteLength(text) <= 6000, String(Buffer.byteLength(text)));
+ assert.ok(Buffer.byteLength(text) <= 48_000, String(Buffer.byteLength(text)));
const result = outcome.result as Record;
assert.equal(result.truncated, true);
- assert.ok(result.outline.length > 0 && result.outline.length < 60);
+ assert.ok(result.outline.length > 60 && result.outline.length < 600);
// Titles were capped whole (with an ellipsis), then entries were dropped from the end.
for (const entry of result.outline) assert.ok(Array.from(entry.untrusted_title).length <= 100);
assert.equal(result.outline[0].marker, '903.0');
diff --git a/test/claude-cost.test.ts b/test/claude-cost.test.ts
index 7c4ee58..ef93ce2 100644
--- a/test/claude-cost.test.ts
+++ b/test/claude-cost.test.ts
@@ -1,117 +1,93 @@
-// What Claude costs while the queue works: the ceiling for one pull, the projection for the pulls
-// still to run, and the figures the store gives the screens for each job, plan and the history.
+// What Claude costs while the queue works: what was spent, what the pulls still to run will likely
+// cost, what is left under the month's spending limit, and the figures the store gives the screens
+// for each job, plan, the history and the month.
import test, { type TestContext } from 'node:test';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { cpSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { estimateCost, limitsFor, QUEUE_SEARCH_TOKENS } from '../src/agent/budget';
import type { RunRecord } from '../src/agent/services';
-import { VISUAL_LIMITS } from '../src/agent/visual';
import { Store, now } from '../src/db/store';
import type { ClaudeOutlook, Job, ModelPrice, Plan, Target } from '../src/shared/bridge';
import {
averagePerPull,
claudeWorking,
HISTORY_MIN,
- spentOn,
- project,
- pullCeiling,
+ leftUnderLimit,
+ likelyFor,
+ priceOf,
queueOutlook,
- runCeiling,
+ spendState,
+ spendStopMessage,
+ spentOn,
stillToRun,
} from '../src/shared/claude-cost';
-import { defaultSettings } from '../src/shared/validation';
const price: ModelPrice = { input: 4, output: 20, cacheRead: 0.2, cacheWrite: 5 };
-// What `Workspace.state` sends for the queue's search: its fixed budgets.
-const searchTokens = (() => {
- const { tokens } = limitsFor('fallback_nav', defaultSettings);
- return { inputTokens: tokens!.input, outputTokens: tokens!.output };
-})();
const outlook = (patch: Partial = {}): ClaudeOutlook => ({
model: 'model-a',
+ plannerModel: 'model-a',
+ automatic: { model: 'model-a', plannerModel: 'model-a' },
prices: { 'model-a': price },
available: true,
- search: { ...searchTokens, perCall: 128_000 },
- look: {
- inputTokens: VISUAL_LIMITS.inputTokens,
- outputTokens: VISUAL_LIMITS.actions * VISUAL_LIMITS.maxTokens,
- },
+ spend: spendState(0, 200),
history: { pulls: 0, helped: 0, estCostUsd: 0 },
...patch,
});
const close = (actual: number, expected: number) =>
assert.ok(Math.abs(actual - expected) < 1e-9, `${actual} is not ${expected}`);
-test('a run at its limits never costs more than its ceiling, however its input was billed', () => {
- // Every input token at the dearest rate: a cache write here.
- close(runCeiling(price, 1_000_000, 1_000_000), 5 + 20);
- close(runCeiling({ ...price, cacheWrite: 1 }, 1_000_000, 0), 4);
- const ceiling = pullCeiling(outlook(), false)!;
- // The search the queue starts sends at most its input budget, and receives its output budget plus
- // one whole reply, which may ask for the model's whole output.
- for (const billed of [
- { input_tokens: QUEUE_SEARCH_TOKENS.input },
- { cache_creation_input_tokens: QUEUE_SEARCH_TOKENS.input },
- { cache_read_input_tokens: QUEUE_SEARCH_TOKENS.input },
- ])
- assert.ok(
- estimateCost(
- 'model-a',
- { ...billed, output_tokens: QUEUE_SEARCH_TOKENS.output + 128_000 },
- { 'model-a': price },
- ) <=
- ceiling.search + 1e-12,
- );
- // The look at the page: its own fixed limits, no cache.
- assert.ok(
- estimateCost(
- 'model-a',
- {
- input_tokens: VISUAL_LIMITS.inputTokens,
- output_tokens: VISUAL_LIMITS.actions * VISUAL_LIMITS.maxTokens,
- },
- { 'model-a': price },
- ) <= ceiling.look,
+test('the month’s spending limit is reached at the limit, and what is left under it is never negative', () => {
+ assert.deepEqual(spendState(49.5, 200), { monthUsd: 49.5, limitUsd: 200, reached: false });
+ close(leftUnderLimit(outlook({ spend: spendState(49.5, 200) }))!, 150.5);
+ // At the limit and past it: reached, and nothing is left. One call may carry it past.
+ for (const spent of [200, 200.01, 5_000]) {
+ const spend = spendState(spent, 200);
+ assert.equal(spend.reached, true, String(spent));
+ assert.equal(leftUnderLimit(outlook({ spend })), 0);
+ }
+ assert.equal(spendState(199.999, 200).reached, false);
+ // 0 is no limit: never reached, and there is no "left" to show.
+ const none = spendState(12_345, 0);
+ assert.equal(none.reached, false);
+ assert.equal(leftUnderLimit(outlook({ spend: none })), undefined);
+ // Figures that are not amounts count as nothing spent and no limit.
+ assert.deepEqual(spendState(Number.NaN, Number.POSITIVE_INFINITY), {
+ monthUsd: 0,
+ limitUsd: 0,
+ reached: false,
+ });
+ assert.deepEqual(spendState(-3, -1), { monthUsd: 0, limitUsd: 0, reached: false });
+ // The same words wherever the stop is shown, with what to do about it.
+ const message = spendStopMessage({ limitUsd: 2500 });
+ assert.match(
+ message,
+ /^Claude is stopped: this month's estimated cost reached your limit of \$2,500\./,
);
+ assert.match(message, /Raise the limit in Settings to go on, or wait for next month\.$/);
});
-test('the ceiling for one pull counts the look at the page only while it is on, and nothing without Claude', () => {
- const off = pullCeiling(outlook(), false)!;
- const on = pullCeiling(outlook(), true)!;
- close(off.total, off.search);
- close(on.total, on.search + on.look);
- close(off.search, (150_000 * 5 + (24_000 + 128_000) * 20) / 1_000_000);
- // A model that may write more in one reply raises it.
- assert.ok(
- pullCeiling(outlook({ search: { ...searchTokens, perCall: 256_000 } }), false)!.search > off.search,
- );
- // Without a key or a model the queue cannot call Claude: the most it can cost is nothing.
- assert.equal(pullCeiling(outlook({ available: false }), true)!.total, 0);
- // A model the price list does not know costs an unknown amount, not nothing.
- assert.equal(pullCeiling(outlook({ prices: {} }), true), undefined);
- assert.equal(pullCeiling(outlook(), true, 'model-b'), undefined);
+test('a model the price list does not know costs an unknown amount, not nothing', () => {
+ assert.deepEqual(priceOf(outlook()), price);
+ assert.equal(priceOf(outlook({ prices: {} })), undefined);
+ assert.equal(priceOf(outlook(), 'model-b'), undefined);
// A name that is not a model ID is not looked up on the object's prototype.
- assert.equal(pullCeiling(outlook(), true, 'constructor'), undefined);
+ assert.equal(priceOf(outlook(), 'constructor'), undefined);
+ const enough = outlook({ history: { pulls: 40, helped: 2, estCostUsd: 0.8 } });
+ assert.equal(likelyFor(25, { ...enough, prices: {} }), undefined);
});
-test('the likely cost waits for enough history and never exceeds the ceiling', () => {
- const ceiling = pullCeiling(outlook(), false)!;
+test('the likely cost waits for enough history', () => {
const few = outlook({ history: { pulls: HISTORY_MIN - 1, helped: 3, estCostUsd: 9 } });
assert.equal(averagePerPull(few), undefined);
- assert.deepEqual(Object.keys(project(10, few, ceiling)), ['ceilingUsd']);
+ assert.equal(likelyFor(10, few), undefined);
const enough = outlook({ history: { pulls: 40, helped: 2, estCostUsd: 0.8 } });
close(averagePerPull(enough)!, 0.02);
- const projection = project(25, enough, ceiling);
- close(projection.ceilingUsd!, 25 * ceiling.total);
- close(projection.likelyUsd!, 25 * 0.02);
- // An average dearer than the current limits allow is capped by them.
- const dear = outlook({ history: { pulls: 10, helped: 10, estCostUsd: 1000 } });
- close(project(3, dear, ceiling).likelyUsd!, 3 * ceiling.total);
- assert.deepEqual(project(5, enough, undefined), {}, 'no price, no amounts');
+ close(likelyFor(25, enough)!, 25 * 0.02);
+ assert.equal(likelyFor(0, enough), 0);
+ assert.equal(likelyFor(-4, enough), 0);
});
const target: Target = {
@@ -153,15 +129,17 @@ test('the queue adds up what was spent and projects only the pulls still to run'
[true, true, false, false, false, false],
'a stopped pull runs again only when the user retries it',
);
- const ceiling = pullCeiling(outlook(), true)!;
- const q = queueOutlook(jobs, outlook(), ceiling);
+ const q = queueOutlook(jobs, outlook());
close(q.spent.estCostUsd, 0.34);
assert.equal(q.spent.tokens, 59_100);
assert.equal(q.spent.unpricedTokens, 100);
assert.equal(q.spent.running, true);
assert.equal(q.remaining, 2);
- close(q.ceilingUsd!, 2 * ceiling.total);
- assert.equal(q.likelyUsd, undefined);
+ assert.equal(q.likelyUsd, undefined, 'too few finished pulls to project from');
+ assert.ok(!('ceilingUsd' in q), 'no pull has a ceiling of its own: the month’s limit bounds it');
+ // With history, the two pulls still to run are projected at its rate.
+ const known = outlook({ history: { pulls: 40, helped: 2, estCostUsd: 0.8 } });
+ close(queueOutlook(jobs, known).likelyUsd!, 2 * 0.02);
assert.deepEqual(
q.working.map((j) => j.status),
['searching'],
@@ -174,7 +152,7 @@ test('the queue adds up what was spent and projects only the pulls still to run'
...jobs,
...jobs.slice(0, 3).map((j) => ({ ...j, planId: 'p2', itemId: randomUUID() })),
];
- const again = queueOutlook(shared, outlook(), ceiling);
+ const again = queueOutlook(shared, outlook());
assert.deepEqual(again.spent, q.spent);
assert.equal(again.remaining, 2);
assert.equal(again.working.length, 1);
@@ -341,6 +319,93 @@ test('a run on a model with no listed price is an unknown cost, never a free one
close(history.estCostUsd, 0.1);
});
+test('the month’s spending counts every run begun in the month, and survives deleting all content', (t) => {
+ const db = workspace(t).open();
+ const account = db.addAccount('Engineering');
+ const { job } = approved(db, account, '40.2');
+ const month = now().slice(0, 7) + '-01';
+ assert.deepEqual(db.monthSpend(month), { input: 0, output: 0, estCostUsd: 0 });
+ // A queue run, a request of the user's own, and one on a model with no listed price.
+ claudeRun(db, { jobId: job.id });
+ claudeRun(db, { kind: 'request', usage: { ...claudeRun(db, {}).usage, estCostUsd: 1.5 } });
+ claudeRun(db, {
+ model: 'model-without-a-price',
+ usage: { iterations: 1, input: 5_000, output: 300, cacheRead: 0, cacheWrite: 0, estCostUsd: 0 },
+ });
+ // A run from an earlier month is not this month's spending.
+ claudeRun(db, { createdAt: '2020-01-15T00:00:00.000Z', updatedAt: '2020-01-15T00:00:00.000Z' });
+ const spent = db.monthSpend(month);
+ close(spent.estCostUsd, 0.1 + 0.1 + 1.5);
+ assert.equal(spent.input, 3 * 4_500 + 5_000);
+ assert.equal(spent.output, 3 * 200 + 300);
+ assert.equal(spendState(spent.estCostUsd, 1).reached, true);
+ assert.equal(spendState(spent.estCostUsd, 2).reached, false);
+ // Deleting all content keeps what was spent, so it cannot be used to reset the limit.
+ db.clearContent();
+ close(db.monthSpend(month).estCostUsd, 1.7);
+});
+
+test('a run continued in a later month counts each reply in the month it was recorded', (t) => {
+ const db = workspace(t).open();
+ const usage = (estCostUsd: number, output: number) => ({
+ iterations: 1,
+ input: 1_000,
+ output,
+ cacheRead: 0,
+ cacheWrite: 0,
+ estCostUsd,
+ });
+ // Begun, and paused for an answer, at the end of one month.
+ const run = claudeRun(db, {
+ kind: 'request',
+ status: 'awaiting_user',
+ createdAt: '2026-11-30T23:50:00.000Z',
+ updatedAt: '2026-11-30T23:55:00.000Z',
+ usage: usage(0.4, 200),
+ });
+ close(db.monthSpend('2026-11-01').estCostUsd, 0.4);
+ assert.equal(db.monthSpend('2026-12-01').estCostUsd, 0);
+ // Continued in the next: what it adds is that month's spending, and the limit sees it.
+ db.runs.save({ ...run, updatedAt: '2026-12-01T00:10:00.000Z', usage: usage(3.4, 900) });
+ close(db.monthSpend('2026-11-01').estCostUsd, 0.4);
+ close(db.monthSpend('2026-12-01').estCostUsd, 3);
+ assert.equal(db.monthSpend('2026-12-01').output, 700);
+ assert.equal(spendState(db.monthSpend('2026-12-01').estCostUsd, 3).reached, true);
+ // Saving it again with nothing new adds nothing, and a smaller figure takes nothing away.
+ db.runs.save({ ...run, updatedAt: '2026-12-02T00:00:00.000Z', usage: usage(3.4, 900) });
+ db.runs.save({ ...run, updatedAt: '2026-12-02T00:00:00.000Z', usage: usage(1, 100) });
+ close(db.monthSpend('2026-12-01').estCostUsd, 3);
+ // The run itself still carries its whole cost, for the pull and the plan it worked for.
+ close(db.runs.get(run.id)!.usage.estCostUsd, 1);
+});
+
+test('runs recorded before each reply was dated count in the month they began', (t) => {
+ const w = workspace(t);
+ const before = path.join(w.dir, 'before');
+ mkdirSync(before);
+ for (const script of readdirSync(path.resolve('src/db/migrations')))
+ if (parseInt(script) < 11)
+ cpSync(path.join(path.resolve('src/db/migrations'), script), path.join(before, script));
+ const old = w.open(before);
+ const insert = (id: string, at: string, cost: number) =>
+ old.run(
+ `INSERT INTO agent_runs(id,kind,status,request_text,messages_json,model,input_tokens,output_tokens,cache_read_tokens,est_cost_usd,created_at,updated_at)
+ VALUES(?,'request','complete','x','[]','model-a',1000,200,3000,?,?,?)`,
+ id,
+ cost,
+ at,
+ at,
+ );
+ insert('october', '2026-10-09T10:00:00.000Z', 2);
+ insert('november-a', '2026-11-03T10:00:00.000Z', 0.5);
+ insert('november-b', '2026-11-28T10:00:00.000Z', 0.25);
+ old.db.close();
+ const db = w.open();
+ assert.deepEqual(db.monthSpend('2026-11-01'), { input: 8_000, output: 400, estCostUsd: 0.75 });
+ assert.deepEqual(db.monthSpend('2026-10-01'), { input: 4_000, output: 200, estCostUsd: 2 });
+ assert.deepEqual(db.monthSpend('2026-12-01'), { input: 0, output: 0, estCostUsd: 0 });
+});
+
test('a section two plans ask for is one pull, and its Claude cost is counted once', (t) => {
const db = workspace(t).open();
const account = db.addAccount('Engineering');
@@ -351,7 +416,7 @@ test('a section two plans ask for is one pull, and its Claude cost is counted on
const rows = db.jobs().filter((j) => j.id === first.job.id);
assert.equal(rows.length, 2, 'listed once for each plan');
close(spentOn(rows).estCostUsd, 0.1);
- const q = queueOutlook(rows, outlook(), pullCeiling(outlook(), false));
+ const q = queueOutlook(rows, outlook());
close(q.spent.estCostUsd, 0.1);
assert.equal(q.remaining, 1);
});
diff --git a/test/electron-workflow.cjs b/test/electron-workflow.cjs
index 4dd4ac8..977962b 100644
--- a/test/electron-workflow.cjs
+++ b/test/electron-workflow.cjs
@@ -171,19 +171,37 @@ async function exercise() {
state.models.map((m) => [m.id, m.maxOutputTokens, m.effort]),
claude.state.models.map((id) => [id, 64000, true]),
);
- assert.equal(
- state.settings.model,
- 'claude-sonnet-5-5',
- 'the shipped preference for the request role',
- );
- assert.equal(state.settings.plannerModel, 'claude-opus-5-5', 'the shipped preference for planning');
+ // Nothing is stored as the user's pick: both roles are automatic, and automatic is the shipped
+ // preference among what the key offers. An Opus for requests and for plans.
+ assert.equal(state.settings.model, '');
+ assert.equal(state.settings.plannerModel, '');
+ assert.equal(state.claude.model, 'claude-opus-5-5', 'the shipped preference for requests');
+ assert.equal(state.claude.plannerModel, 'claude-opus-5-5', 'the shipped preference for planning');
+ assert.deepEqual(state.claude.automatic, {
+ model: 'claude-opus-5-5',
+ plannerModel: 'claude-opus-5-5',
+ });
+ // A model picked by hand wins while the key offers it, and automatic says what it would be.
await ws.settings({ plannerModel: 'claude-fable-5-2' });
+ state = await ws.state();
+ assert.equal(state.claude.plannerModel, 'claude-fable-5-2');
+ assert.equal(state.claude.automatic.plannerModel, 'claude-opus-5-5');
await assert.rejects(ws.settings({ model: 'claude-made-up' }), /Select a model/);
+ // A key that no longer offers the pick, or the preferred model: back to automatic, which is
+ // then the next preference the key does offer.
+ claude.state.models = ['claude-sonnet-5-5', 'claude-haiku-5-5'];
+ await ws.key('models');
+ state = await ws.state();
+ assert.equal(state.settings.plannerModel, '');
+ assert.equal(state.claude.model, 'claude-sonnet-5-5');
+ assert.equal(state.claude.plannerModel, 'claude-sonnet-5-5');
claude.state.models = ['claude-opus-5-5'];
await ws.key('models');
state = await ws.state();
- assert.equal(state.settings.model, 'claude-opus-5-5');
- assert.equal(state.settings.plannerModel, 'claude-opus-5-5');
+ assert.equal(state.claude.model, 'claude-opus-5-5');
+ assert.equal(state.claude.plannerModel, 'claude-opus-5-5');
+ // The month's spending limit is set from the start, and nothing has been spent.
+ assert.deepEqual(state.claude.spend, { monthUsd: 0, limitUsd: 200, reached: false });
claude.state.models = [];
await assert.rejects(ws.key('models'), /cannot see any Claude model/);
claude.state.models = ['claude-opus-5-5', 'claude-sonnet-5-5'];
@@ -444,6 +462,8 @@ async function exercise() {
return 'Drafted 2 items for the Sacramento lab building. The plan awaits your approval.';
},
];
+ // Plans have their own model setting. Picked by hand here, so the two roles can be told apart.
+ await ws.settings({ plannerModel: 'claude-sonnet-5-5' });
const planRunId = await ws.startRun({
mode: 'project',
request: notes,
@@ -455,9 +475,14 @@ async function exercise() {
assert.equal(claude.state.turns.length, 0);
assert.equal(
claude.state.calls.at(-1).model,
- 'claude-opus-5-5',
+ 'claude-sonnet-5-5',
'the planning role has its own model',
);
+ // Plans think harder than requests. This model reports no levels, so the effort is lowered
+ // to the highest an earlier list is read as offering.
+ assert.deepEqual(claude.state.calls.at(-1).output_config, { effort: 'high' });
+ await ws.settings({ plannerModel: '' });
+ assert.equal((await ws.state()).claude.plannerModel, 'claude-opus-5-5');
const draft = (await ws.state()).plans.find((p) => p.id === planned.planId);
assert.equal(draft.status, 'draft');
assert.equal(draft.mode, 'project');
diff --git a/test/helpers/fake-services.ts b/test/helpers/fake-services.ts
index 2eddf22..c4f386b 100644
--- a/test/helpers/fake-services.ts
+++ b/test/helpers/fake-services.ts
@@ -321,6 +321,8 @@ export type Turn =
usage?: Record;
/** Reject instead of answering. */
error?: unknown;
+ /** Usage the interrupted stream already carried when it was rejected. */
+ partial?: Record;
/** Never answer until the request is aborted. */
hang?: boolean;
/** Runs when the model is asked for this turn. */
@@ -386,7 +388,9 @@ export function scriptedClient(script: Turn[], calls: ModelCall[] = []) {
usage: { ...baseUsage, ...(spec.usage ?? {}) },
};
};
- return { finalMessage, currentMessage: undefined };
+ const partial =
+ turn && typeof turn === 'object' && !Array.isArray(turn) ? turn.partial : undefined;
+ return { finalMessage, currentMessage: partial ? { usage: partial } : undefined };
},
},
},
@@ -454,6 +458,7 @@ export function harness(patch: Partial = {}): Harness {
agent: { prefer: ['model-agent'], effort: 'medium' },
planner: { prefer: ['model-planner'], effort: 'high' },
},
+ look: { effort: 'medium' },
models: { 'model-agent': { fallbacks: false }, 'model-safe': { fallbacks: true } },
},
},
diff --git a/test/review-renderer.electron.cjs b/test/review-renderer.electron.cjs
index 689a173..cb76b45 100644
--- a/test/review-renderer.electron.cjs
+++ b/test/review-renderer.electron.cjs
@@ -13,7 +13,7 @@ const { ZodError } = require('zod');
const { Store } = require('../dist/db/store');
const { Workspace } = require('../dist/main/workspace');
const { sanitizeError } = require('../dist/agent');
-const { pacingLimits, budgetLimits } = require('../dist/shared/validation');
+const { pacingLimits, budgetLimits, spendLimit } = require('../dist/shared/validation');
const { pageTexts } = require('../dist/document/combine');
const fixture = require('./fixtures/site.cjs');
const { createOldWorkspace } = require('./fixtures/old-workspace.cjs');
@@ -623,27 +623,99 @@ async function exercise() {
);
}
- // 2. Settings: the key and its models, the limits, a refused value, and no notice.
+ // 2. Settings. Nothing to choose: the key, a spending limit, and everything else behind
+ // "Show advanced settings" with the values CodePull chose.
const fields = await ui(async (key) => {
const t = window.t;
await t.click('Add key');
await t.waitFor('the Settings page', () => t.find('h1', (el) => t.text(el) === 'Settings'));
const model = () => document.querySelector('select[name="model"]');
const planner = () => document.querySelector('select[name="plannerModel"]');
- if (!model().disabled || !t.has('Add a key to list its models'))
- throw Error('Models are offered before a key is saved.');
+ const inUse = () => t.text(t.find('[data-in-use]'));
+ const toggle = () => t.find('[data-advanced-toggle]');
+ // The first look at the page: a key field, a spending limit and no setting to choose.
+ const hidden = [
+ 'select[name="model"]',
+ 'select[name="plannerModel"]',
+ 'input[name="textSharing"]',
+ 'input[name="visualFallback"]',
+ 'input[name="budgets.requestIterations"]',
+ 'input[name="pacing.minDelaySec"]',
+ 'input[name="stalenessDays"]',
+ 'input[name="showBrowser"]',
+ ];
+ const shownEarly = hidden.filter((selector) => document.querySelector(selector));
+ if (shownEarly.length) throw Error('Shown before advanced settings were asked for: ' + shownEarly);
+ for (const words of ['Export diagnostics', 'Wipe all data', 'Refresh models', 'Pacing'])
+ if (t.has(words)) throw Error('Shown before advanced settings were asked for: ' + words);
+ if (toggle().getAttribute('aria-expanded') !== 'false' || !t.has('Show advanced settings'))
+ throw Error('The advanced settings do not start hidden.');
+ t.expect([
+ 'Your Anthropic API key and a spending limit. CodePull has chosen everything else.',
+ 'Once a key is saved, CodePull picks the Claude model for you.',
+ 'CodePull has chosen values that work. You do not need to change any of them.',
+ 'Monthly spending limit for Claude, in US dollars',
+ 'every call to Claude stops',
+ 'What leaves this computer',
+ ]);
+ const limit = document.querySelector('input[name="spendLimitUsd"]');
+ if (limit.value !== '200') throw Error('The spending limit starts at ' + limit.value);
await t.fill('Anthropic API key', key);
await t.click('Save key');
- await t.waitFor('the saved key', () => t.has('API key saved.') && !model().disabled);
- const offered = [...model().options].map((o) => o.value);
- if (offered.join() !== 'claude-opus-5-5,claude-sonnet-5-5')
- throw Error('The model list is not the list the key offers: ' + offered);
- if (model().value !== 'claude-sonnet-5-5' || planner().value !== 'claude-opus-5-5')
- throw Error('Unexpected role defaults: ' + model().value + ', ' + planner().value);
- t.expect(['Key saved', 'Model for requests', 'Model for project plans']);
+ await t.waitFor('the saved key', () =>
+ t.has('API key saved. CodePull chose the Claude model for you.'),
+ );
+ // An Opus for requests and for plans, without the user choosing anything.
+ await t.waitFor('the model in use', () =>
+ /^CodePull uses claude-opus-5-5 for your requests and your project plans\./.test(inUse()),
+ );
+ t.expect(['Key saved', 'of your $200.00 limit']);
+ if (model()) throw Error('Saving a key showed the model lists.');
if (JSON.stringify(await window.codepull.state()).includes(key))
throw Error('The key reached the renderer.');
+ // The spending limit is the one value on the first page. A refused value stays in place and
+ // does not open the advanced settings.
+ t.type(limit, '-1');
+ await t.click('Save settings');
+ await t.waitFor('the refused limit', () =>
+ t.find('.field-error', (el) => t.text(el) === 'Enter a whole number from 0 to 100,000.'),
+ );
+ if (model()) throw Error('A refused spending limit opened the advanced settings.');
+ t.type(limit, '350');
+ await t.click('Save settings');
+ await t.waitFor(
+ 'the saved limit',
+ () => t.has('Settings saved.') && t.has('of your $350.00 limit'),
+ );
+ await t.idle();
+ t.type(limit, '200');
+ await t.click('Save settings');
+ await t.waitFor('the limit as it was', () => t.has('of your $200.00 limit'));
+ await t.idle();
+
+ // Everything else is one click away, and is remembered.
+ toggle().click();
+ await t.waitFor('the advanced settings', () => model() && !model().disabled);
+ if (toggle().getAttribute('aria-expanded') !== 'true' || !t.has('Hide advanced settings'))
+ throw Error('The toggle does not say the advanced settings are shown.');
+ const stillHidden = hidden.filter((selector) => !document.querySelector(selector));
+ if (stillHidden.length) throw Error('Missing from the advanced settings: ' + stillHidden);
+ if (localStorage.getItem('codepull.settings.advanced') !== '1')
+ throw Error('Showing the advanced settings was not remembered.');
+ const offered = [...model().options].map((o) => o.value);
+ if (offered.join() !== ',claude-opus-5-5,claude-sonnet-5-5')
+ throw Error('The model list is not Automatic and the list the key offers: ' + offered);
+ // Both are automatic, and each says what automatic stands for now.
+ if (model().value !== '' || planner().value !== '')
+ throw Error(
+ 'A model was picked for the user by name: ' + model().value + ', ' + planner().value,
+ );
+ for (const select of [model(), planner()])
+ if (t.text(select.options[0]) !== 'Automatic: claude-opus-5-5')
+ throw Error('Automatic reads: ' + t.text(select.options[0]));
+ t.expect(['Model for requests', 'Model for project plans', 'Refresh models']);
+
// What Claude may see, one sentence each.
const sharing = t.all('input[name="textSharing"]');
if (sharing.length !== 3 || sharing.find((i) => i.checked).value !== 'outline')
@@ -654,34 +726,46 @@ async function exercise() {
'up to 800 characters at a time',
'The cost is an estimate',
]);
- // The most Claude can cost on one queued pull follows the model and the look-at-the-page switch
- // as they are chosen, before they are saved.
- const ceiling = () => t.text(t.find('[data-ceiling]'));
- const before = ceiling();
- if (!/fixed token budget: at most \$\d+\.\d\d a pull with claude-sonnet-5-5\./.test(before))
- throw Error('Unexpected ceiling line: ' + before);
- const look = document.querySelector('input[name="visualFallback"]');
- look.click();
- await t.waitFor('the look counted', () =>
- /a look at the page adds at most \$\d+\.\d\d/.test(ceiling()),
- );
- look.click();
- await t.waitFor('the ceiling as it was', () => ceiling() === before);
- const chosen = document.querySelector('select[name="model"]');
- t.type(chosen, 'claude-opus-5-5');
- await t.waitFor('the other model', () => /a pull with claude-opus-5-5/.test(ceiling()));
- t.type(chosen, 'claude-sonnet-5-5');
- await t.waitFor('the ceiling as it was again', () => ceiling() === before);
+ // No pull has a ceiling of its own any more: the monthly limit is what bounds Claude.
+ if (document.querySelector('[data-ceiling]') || t.has('fixed token budget'))
+ throw Error('A token budget is still described.');
+ // A model picked by hand wins over automatic, and automatic can be chosen again.
+ t.type(model(), 'claude-sonnet-5-5');
+ await t.waitFor('the unsaved pick', () => t.has('You have unsaved changes.'));
+ await t.click('Save settings');
+ await t.waitFor('the model picked by hand', () =>
+ /^CodePull uses claude-sonnet-5-5 for requests and claude-opus-5-5 for project plans\./.test(
+ inUse(),
+ ),
+ );
+ await t.idle();
+ t.type(model(), '');
+ await t.click('Save settings');
+ await t.waitFor('automatic again', () => /for your requests and your project plans/.test(inUse()));
+ await t.idle();
// A value below the hard limit is refused in place, and nothing is saved.
- const delay = document.querySelector('input[name="pacing.minDelaySec"]');
- t.type(delay, '3');
+ t.type(document.querySelector('input[name="pacing.minDelaySec"]'), '3');
await t.click('Save settings');
await t.waitFor('the refused value', () =>
t.find('.field-error', (el) => t.text(el) === 'Enter a whole number from 6 to 600.'),
);
- if (delay.getAttribute('aria-invalid') !== 'true') throw Error('The field is not marked invalid.');
+ if (
+ document.querySelector('input[name="pacing.minDelaySec"]').getAttribute('aria-invalid') !==
+ 'true'
+ )
+ throw Error('The field is not marked invalid.');
t.expect('1 value is outside the limits. Nothing was saved.');
+ // A refused value in the hidden part is never refused out of sight: the part is shown again.
+ toggle().click();
+ await t.waitFor('the hidden advanced settings', () => !model());
+ await t.click('Save settings');
+ await t.waitFor('the refused value, shown again', () =>
+ t.find('.field-error', (el) => t.text(el) === 'Enter a whole number from 6 to 600.'),
+ );
+ if (toggle().getAttribute('aria-expanded') !== 'true')
+ throw Error('The advanced settings stayed hidden over a refused value.');
+ const delay = document.querySelector('input[name="pacing.minDelaySec"]');
// The main process refuses the same value by itself.
const refusal = await window.codepull.settings({ pacing: { minDelaySec: 3 } }).then(
() => 'accepted',
@@ -702,8 +786,8 @@ async function exercise() {
note: t.text(input.closest('label').querySelector('small')),
}));
- // There is one way of working and no notice to accept. The screenshot fallback is off until
- // the user turns it on.
+ // There is one way of working and no notice to accept. Looking at the page is on unless the
+ // user turns it off, and the page says what that sends.
if (t.find('label.choice', (el) => /^(Assisted|Automated)/.test(t.text(el))))
throw Error('An access-mode choice is still offered.');
if (document.querySelector('input[name="acceptedTerms"]') || t.has('Source-access notice'))
@@ -711,18 +795,21 @@ async function exercise() {
t.expect([
'CodePull opens each page for you in your own signed-in session',
'Let Claude look at the page when CodePull cannot find a section on it',
+ 'On unless you turn it off.',
+ 'it also sends screenshots of that page, which show code text',
]);
// Tokens are not capped. Steps and the plan size are, and each one says what it means.
if (document.querySelector('input[name$="InputTokens"], input[name$="OutputTokens"]'))
throw Error('A token limit is still offered.');
t.expect([
- 'Tokens are not capped',
+ 'Tokens are not capped for anything Claude does',
+ 'pauses to ask after 60 minutes of work',
'A step is one call to Claude',
'The most sections Claude may put in one plan.',
'keeps wording on a page from steering Claude',
]);
- if (document.querySelector('input[name="visualFallback"]').checked)
- throw Error('The screenshot fallback starts on.');
+ if (!document.querySelector('input[name="visualFallback"]').checked)
+ throw Error('Looking at the page does not start on.');
const refusedMode = await window.codepull.settings({ automationMode: 'automated' }).then(
() => 'accepted',
(e) => e.message,
@@ -768,6 +855,15 @@ async function exercise() {
return numbers;
}, KEY);
// Every limit the page shows is the limit the main process enforces.
+ {
+ const field = fields.find((f) => f.name === 'spendLimitUsd');
+ assert.ok(field, 'the spending limit is on the Settings page');
+ assert.deepEqual(
+ [field.min, field.max, field.value],
+ [spendLimit.min, spendLimit.max, spendLimit.initial],
+ );
+ assert.match(field.note, /0 means no limit\. Allowed: 0 to 100,000 dollars · default 200\./);
+ }
for (const [group, limits] of [
['pacing', pacingLimits],
['budgets', budgetLimits],
@@ -788,7 +884,11 @@ async function exercise() {
}
assert.equal(store.settings().pacing.minDelaySec, 12, 'the refused value was not saved');
assert.ok(!('acceptedTerms' in store.settings()));
- assert.equal(store.settings().visualFallback, false);
+ assert.equal(store.settings().visualFallback, true);
+ assert.equal(store.settings().spendLimitUsd, 200);
+ assert.equal(store.settings().model, '', 'no model is stored as the user’s pick');
+ assert.equal((await ws.state()).claude.model, 'claude-opus-5-5');
+ assert.equal((await ws.state()).claude.plannerModel, 'claude-opus-5-5');
// 3. An account: added, signed in by hand in its own window, confirmed with Done.
await ui(async () => {
@@ -992,7 +1092,7 @@ async function exercise() {
[
'You answered: 2022',
'Queued § 695.4(B). It will appear in the library when the pull finishes.',
- /Claude · claude-sonnet-5-5 · 4 steps · [\d.,]+K? tokens · est\. /,
+ /Claude · claude-opus-5-5 · 4 steps · [\d.,]+K? tokens · est\. /,
],
t.panel(),
);
@@ -1037,7 +1137,7 @@ async function exercise() {
[
'This run reached its limit of 2 steps. Continue with another allowance of the same size?',
'Reached a limit. Waiting for your decision.',
- 'You can change these limits in Settings, under Claude.',
+ 'You can change these limits in Settings: the monthly spending limit, and the step limits under the advanced settings.',
],
fresh(),
);
@@ -1052,7 +1152,50 @@ async function exercise() {
);
});
assert.equal(claude.state.turns.length, 0);
- await ws.settings({ budgets: { requestIterations: 14 } });
+ await ws.settings({ budgets: { requestIterations: budgetLimits.requestIterations.initial } });
+
+ // The month's spending limit is a kill switch. With the month's estimate at the limit, nothing
+ // calls Claude: the top bar and the form say so, a request does not start, and a pull by
+ // section number still does. Raising the limit lifts it.
+ const thisMonth = new Date().toISOString().slice(0, 7);
+ store.run('UPDATE claude_months SET est_cost_usd=est_cost_usd+5 WHERE month=?', thisMonth);
+ await ws.settings({ spendLimitUsd: 5 });
+ assert.equal((await ws.state()).claude.spend.reached, true);
+ assert.equal((await ws.state()).claude.available, false);
+ const sentBeforeStop = claude.state.calls.length;
+ await ui(async () => {
+ const t = window.t;
+ const meter = () => t.text(t.find('.token-meter'));
+ await t.go('New request');
+ await t.waitFor('the stopped top bar', () => meter().startsWith('Claude stopped at your limit'));
+ t.expect([
+ "Claude is stopped: this month's estimated cost reached your limit of $5. Raise the limit in Settings to go on, or wait for next month.",
+ 'type an exact request such as',
+ 'Raise the limit in Settings',
+ ]);
+ await t.fill('Your request', 'What do I have about sample pumps?');
+ await t.click('Start');
+ await t.waitFor('the refusal at the limit', () =>
+ t.find('.global-message', (el) => t.text(el).includes('Claude is stopped')),
+ );
+ t.find('.global-message button').click();
+ await t.fill('Your request', '');
+ // Settings says so beside the limit, and against the month's usage.
+ await t.go('Settings');
+ t.expect(['Claude is stopped.', 'of your $5.00 limit']);
+ });
+ assert.equal(claude.state.calls.length, sentBeforeStop, 'nothing was sent past the limit');
+ store.run('UPDATE claude_months SET est_cost_usd=est_cost_usd-5 WHERE month=?', thisMonth);
+ await ws.settings({ spendLimitUsd: spendLimit.initial });
+ assert.equal((await ws.state()).claude.spend.reached, false);
+ await ui(async () => {
+ const t = window.t;
+ await t.waitFor('the top bar as it was', () =>
+ t.text(t.find('.token-meter')).startsWith('Claude ·'),
+ );
+ if (t.has('Claude is stopped.')) throw Error('Settings still says Claude is stopped.');
+ await t.go('New request');
+ });
// A working request can be stopped, and a stopped or refused request can be picked up again.
claude.state.turns = [() => hang];
@@ -1305,7 +1448,7 @@ async function exercise() {
'Cross-references can add up to 3 more, about 48 seconds more at most.',
'References to other standards are listed in each pull and never followed.',
// What Claude may cost on the pulls, cross-references included, and what drafting cost.
- /Claude: nothing for a section CodePull finds by itself\. At most \$\d+\.\d\d if every one needed its help/,
+ /Claude: nothing for a section CodePull finds by itself.*\$\d+\.\d\d is left under this month’s limit\./,
/Drafting this plan cost est\. (under )?\$[\d.]+\./,
]);
await t.click('Save draft');
@@ -1892,10 +2035,23 @@ async function exercise() {
t.plainCopy();
await t.go('Settings');
t.expect(/input tokens · [\d,]+ output tokens · estimated cost (under )?\$[\d.]+/);
+ // The page as a user first meets it: the advanced settings hidden.
+ t.find('[data-advanced-toggle]').click();
+ await t.waitFor('the short Settings page', () => !document.querySelector('select[name="model"]'));
window.scrollTo(0, 0);
});
await shot('08-settings.png');
await shot('08-settings-whole.png', true);
+ await ui(async () => {
+ const t = window.t;
+ t.find('[data-advanced-toggle]').click();
+ await t.waitFor('the advanced settings again', () =>
+ document.querySelector('select[name="model"]'),
+ );
+ t.plainCopy();
+ window.scrollTo(0, 0);
+ });
+ await shot('08b-settings-advanced-whole.png', true);
// 12. The rest of each screen: the sample, a finished plan and its bundle, the other account
// actions, diagnostics, and the app without a key.
diff --git a/test/scheduler.test.ts b/test/scheduler.test.ts
index af3ec97..bf3d64f 100644
--- a/test/scheduler.test.ts
+++ b/test/scheduler.test.ts
@@ -51,7 +51,7 @@ async function failedReport() {
return report;
}
-function setup(t: TestContext, fail: (section: string) => Error) {
+function setup(t: TestContext, fail: (section: string) => Error, extra: Partial = {}) {
const dir = mkdtempSync(path.join(os.tmpdir(), 'codepull-scheduler-'));
const store = new Store(path.join(dir, 'workspace.sqlite'), path.resolve('src/db/migrations'));
t.after(() => {
@@ -84,9 +84,10 @@ function setup(t: TestContext, fail: (section: string) => Error) {
changed: () => {},
log: createLog(store),
sanitize: sanitizeError,
+ ...extra,
};
const scheduler = new Scheduler(deps);
- const queue = (section: string) => {
+ const queue = (section: string, scope: Target['scope'] = target.scope) => {
const plan: Plan = {
id: randomUUID(),
mode: 'quick',
@@ -102,6 +103,7 @@ function setup(t: TestContext, fail: (section: string) => Error) {
{
...target,
section,
+ scope,
id: randomUUID(),
reason: 'User request',
included: true,
@@ -207,3 +209,42 @@ test('a page that did not answer fails its pull once, with its own words, and is
assert.equal(waiting.status, 'queued');
assert.match(waiting.detail ?? '', /Network problem\. Trying again shortly/);
});
+
+test('at the month’s spending limit the queue asks Claude nothing, says why, and may ask after a retry', async (t) => {
+ const stop =
+ "Claude is stopped: this month's estimated cost reached your limit of $200. Raise the limit in Settings to go on, or wait for next month.";
+ let stopped: string | undefined = stop;
+ const asked: string[] = [];
+ const q = setup(t, () => new BlockedError('not_found', 'The section is not on this page.'), {
+ claudeStopped: () => stopped,
+ visualFallback: () => true,
+ findPage: async (job) => (asked.push('search ' + job.target.section), undefined),
+ lookAtPage: async (job) => (asked.push('look ' + job.target.section), undefined),
+ });
+ const [first] = [q.queue('40.2', 'section')];
+ const [job] = await q.settled([first!]);
+ assert.equal(job!.status, 'blocked');
+ assert.equal(job!.blockedReason, 'not_found');
+ assert.deepEqual(asked, [], 'neither the search nor the look was started');
+ assert.ok((job!.detail ?? '').includes(stop), job!.detail);
+ // Nothing was used up: once the limit is raised, a retry searches and looks as usual.
+ assert.deepEqual(q.store.jobCheckpoint(job!.id), {});
+ stopped = undefined;
+ const [second] = [q.queue('40.3', 'section')];
+ const [later] = await q.settled([second!]);
+ assert.deepEqual(asked, ['search 40.3', 'look 40.3']);
+ assert.ok(!(later!.detail ?? '').includes('Claude is stopped'));
+
+ // The limit reached while Claude searched: the pull says so, and may be searched again.
+ const during = setup(t, () => new BlockedError('not_found', 'The section is not on this page.'), {
+ claudeStopped: () => stopped,
+ visualFallback: () => true,
+ findPage: async () => ((stopped = stop), undefined),
+ lookAtPage: async (job) => (asked.push('look ' + job.target.section), undefined),
+ });
+ const [third] = [during.queue('40.4', 'section')];
+ const [cut] = await during.settled([third!]);
+ assert.ok((cut!.detail ?? '').includes(stop), cut!.detail);
+ assert.ok(!asked.includes('look 40.4'), 'no look once the limit is reached');
+ assert.notEqual(during.store.jobCheckpoint(cut!.id).searched, true);
+});
diff --git a/test/security.test.ts b/test/security.test.ts
index fe08028..9647c19 100644
--- a/test/security.test.ts
+++ b/test/security.test.ts
@@ -212,13 +212,18 @@ test('rule_R9: the screenshot fallback can only point, and app code checks every
assert.deepEqual(names.sort(), ['give_up', 'mark_end', 'mark_start', 'open_link', 'scroll']);
assert.ok(!/(?:url|href|path|address|text)\s*:\s*\{\s*type: 'string'/.test(visual));
assert.ok(visual.includes('deps.permitted(chosen.href)'));
- assert.match(visual, /actions: 15/);
+ // A look is bounded by its steps and its page loads, and by the month's spending limit.
+ assert.match(visual, /actions: 40/);
+ assert.match(visual, /pageLoads: 4/);
+ assert.ok(visual.includes('if (spend?.reached) throw new VisualGiveUp(spendStopMessage(spend));'));
// The workspace opens a pointed-to link only if app code may open that page by itself, paced.
const ws = read('src/main/workspace.ts');
const look = ws.slice(ws.indexOf('private async lookAtPage('), ws.indexOf('private watchSignIn('));
assert.ok(look.includes('if (!this.adapter.permittedAutomated(url)) return false;'));
assert.ok(look.includes('ctx.driver.open(accountId, url'), 'a load bypasses the paced driver');
+ // The user can turn it off, and then nothing is looked at.
assert.ok(look.includes('if (!settings.visualFallback) return;'));
+ assert.ok(look.includes('this.spend().reached'), 'a look starts past the spending limit');
// The section is read from the page by the same reader as a capture by hand, never from Claude.
assert.ok(look.includes('this.adapter.captureSelection(ctx, t)'));
assert.ok(look.includes("read.tree.meta.heuristicsUsed = ['visual_section_boundary']"));
diff --git a/test/store.test.ts b/test/store.test.ts
index 0e3ed73..974c5b9 100644
--- a/test/store.test.ts
+++ b/test/store.test.ts
@@ -1,7 +1,16 @@
import test, { type TestContext } from 'node:test';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
-import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import {
+ cpSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { RUN_FACTS_PREFIX, Store, exactKey, now, type StoredResult } from '../src/db/store';
@@ -47,35 +56,136 @@ function workspace(t: TestContext) {
},
};
}
-test('the model list is whatever the key offers, and a role falls back to the shipped preference', (t) => {
+test('the model list is whatever the key offers, and no model is written as the user’s pick', (t) => {
const setup = workspace(t);
const offered = ['model-b', 'model-a', 'model-c'].map((id) => ({
id,
name: id,
maxOutputTokens: 64000,
}));
- const prefer = (role: 'agent' | 'planner') => (role === 'agent' ? 'model-a' : 'model-c');
- setup.db.setModels(offered, prefer);
+ setup.db.setModels(offered);
assert.deepEqual(
setup.db.models().map((m) => m.id),
['model-b', 'model-a', 'model-c'],
);
+ // Automatic is an empty pick. Saving the list does not turn it into a model.
+ assert.equal(setup.db.settings().model, '');
+ assert.equal(setup.db.settings().plannerModel, '');
+ // A pick by hand the key still offers is kept; one it no longer offers goes back to automatic.
+ setup.db.set('preferences', { ...setup.db.settings(), model: 'model-a', plannerModel: 'model-c' });
+ setup.db.setModels(offered.slice(0, 2));
assert.equal(setup.db.settings().model, 'model-a');
- assert.equal(setup.db.settings().plannerModel, 'model-c');
- // A saved choice the key still offers is kept; one it no longer offers is replaced.
- setup.db.setModels(offered.slice(0, 2), prefer);
- assert.equal(setup.db.settings().model, 'model-a');
- assert.equal(setup.db.settings().plannerModel, 'model-b');
+ assert.equal(setup.db.settings().plannerModel, '');
const db = setup.reopen();
assert.equal(db.models().length, 2);
db.setModels([]);
assert.equal(db.settings().model, '');
});
+test('an install that already exists moves to the values CodePull now chooses, once', (t) => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'codepull-chosen-'));
+ const file = path.join(dir, 'workspace.sqlite');
+ const all = path.resolve('src/db/migrations');
+ const before = path.join(dir, 'before');
+ mkdirSync(before);
+ for (const script of readdirSync(all))
+ if (parseInt(script) < 10) cpSync(path.join(all, script), path.join(before, script));
+ const opened: Store[] = [];
+ const open = (migrations: string) => {
+ const store = new Store(file, migrations);
+ opened.push(store);
+ return store;
+ };
+ t.after(() => {
+ for (const store of opened)
+ try {
+ store.db.close();
+ } catch {
+ // Closed by the test already.
+ }
+ rmSync(dir, { recursive: true, force: true });
+ });
+ // What the previous version stored: every value, the earlier defaults among them.
+ const earlier = {
+ model: 'model-the-app-picked',
+ plannerModel: 'model-the-app-picked-for-plans',
+ stalenessDays: 30,
+ autoRefreshStale: true,
+ keepVersions: 3,
+ textSharing: 'excerpts',
+ visualFallback: false,
+ pacing: { minDelaySec: 20, jitterSec: 8, maxPerHour: 40, maxPerDay: 250 },
+ budgets: { requestIterations: 14, planIterations: 24, maxPlanItems: 30 },
+ showBrowser: true,
+ includeAdoptionTable: false,
+ };
+ const old = open(before);
+ old.set('preferences', earlier);
+ old.db.close();
+
+ const db = open(all);
+ const s = db.settings();
+ // Both models are automatic: the app cannot tell its own pick from the user's.
+ assert.equal(s.model, '');
+ assert.equal(s.plannerModel, '');
+ // The earlier defaults give way to the new ones.
+ assert.deepEqual(s.budgets, { requestIterations: 40, planIterations: 60, maxPlanItems: 60 });
+ assert.equal(s.visualFallback, true);
+ assert.equal(s.spendLimitUsd, 200);
+ // Everything the user chose is as it was. Pacing is never touched.
+ assert.equal(s.stalenessDays, 30);
+ assert.equal(s.autoRefreshStale, true);
+ assert.equal(s.textSharing, 'excerpts');
+ assert.equal(s.showBrowser, true);
+ assert.equal(s.pacing.minDelaySec, 20);
+
+ // Only once: what the user sets afterwards stays through every later start.
+ db.set('preferences', {
+ ...s,
+ model: 'model-by-hand',
+ visualFallback: false,
+ budgets: { requestIterations: 14, planIterations: 24, maxPlanItems: 30 },
+ });
+ db.db.close();
+ const again = open(all).settings();
+ assert.equal(again.model, 'model-by-hand');
+ assert.equal(again.visualFallback, false);
+ assert.deepEqual(again.budgets, { requestIterations: 14, planIterations: 24, maxPlanItems: 30 });
+});
+test('step limits the user changed by hand survive the move to the new defaults', (t) => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'codepull-chosen-'));
+ const file = path.join(dir, 'workspace.sqlite');
+ const all = path.resolve('src/db/migrations');
+ const before = path.join(dir, 'before');
+ mkdirSync(before);
+ for (const script of readdirSync(all))
+ if (parseInt(script) < 10) cpSync(path.join(all, script), path.join(before, script));
+ const old = new Store(file, before);
+ old.set('preferences', {
+ visualFallback: true,
+ budgets: { requestIterations: 9, planIterations: 24, maxPlanItems: 12 },
+ });
+ old.db.close();
+ const db = new Store(file, all);
+ t.after(() => {
+ db.db.close();
+ rmSync(dir, { recursive: true, force: true });
+ });
+ assert.deepEqual(db.settings().budgets, {
+ requestIterations: 9,
+ planIterations: 60,
+ maxPlanItems: 12,
+ });
+ assert.equal(db.settings().visualFallback, true);
+});
test('rule_R15_pacing_enforced_below_agent: saved settings are clamped to the hard limits', (t) => {
const { db } = workspace(t);
assert.ok(!('acceptedTerms' in db.settings()), 'there is no notice to accept');
assert.equal(db.settings().textSharing, 'outline');
- assert.equal(db.settings().visualFallback, false, 'no screenshot goes to Claude by default');
+ // The owner's decision, 1 December 2026: looking at the page is on unless the user turns it
+ // off. What Claude may see as text stays at outlines.
+ assert.equal(db.settings().visualFallback, true);
+ assert.equal(db.settings().spendLimitUsd, 200, 'a spending limit is set from the start');
+ assert.equal(db.settings().model, '', 'the model is chosen for the user');
assert.deepEqual(db.settings().pacing, {
minDelaySec: 12,
jitterSec: 8,
@@ -94,7 +204,8 @@ test('rule_R15_pacing_enforced_below_agent: saved settings are clamped to the ha
activeWorkers: 50,
},
budgets: { maxPlanItems: 500, requestIterations: 1000 },
- visualFallback: 'yes',
+ visualFallback: 'no',
+ spendLimitUsd: -50,
stalenessDays: 30,
});
const s = db.settings();
@@ -109,8 +220,13 @@ test('rule_R15_pacing_enforced_below_agent: saved settings are clamped to the ha
[6, 120, 600, 500, 4],
);
assert.equal(s.budgets.maxPlanItems, 60);
- assert.equal(s.budgets.requestIterations, 40);
- assert.equal(s.visualFallback, false, 'a stored value of the wrong kind is not a yes');
+ assert.equal(s.budgets.requestIterations, 200);
+ assert.equal(
+ s.visualFallback,
+ true,
+ 'a stored value of the wrong kind is not read: the default stands',
+ );
+ assert.equal(s.spendLimitUsd, 200, 'a limit that is not an amount is not read either');
assert.equal(s.stalenessDays, 30);
// Settings from the version with an access-mode switch are read without it.
db.set('preferences', {
diff --git a/test/upgrade.test.ts b/test/upgrade.test.ts
index 2012b0d..7ac6c7a 100644
--- a/test/upgrade.test.ts
+++ b/test/upgrade.test.ts
@@ -80,7 +80,11 @@ test('a workspace made by 0.1.3 opens with its accounts, plans, queue, library a
assert.ok(!('acceptedTerms' in stored), 'the old notice key is gone from what is stored');
assert.equal(settings.stalenessDays, 90);
assert.equal(settings.autoRefreshStale, true);
- assert.equal(settings.visualFallback, false);
+ // What this version chooses for the user applies to a workspace that never stored it.
+ assert.equal(settings.visualFallback, true);
+ assert.equal(settings.spendLimitUsd, 200);
+ assert.equal(settings.model, '');
+ assert.deepEqual(settings.budgets, { requestIterations: 40, planIterations: 60, maxPlanItems: 60 });
assert.equal(db.get('paused', false), true, 'a paused queue stays paused');
});
diff --git a/test/visual.electron.cjs b/test/visual.electron.cjs
index 9a04a7d..52a2f07 100644
--- a/test/visual.electron.cjs
+++ b/test/visual.electron.cjs
@@ -156,7 +156,9 @@ async function exercise() {
ws.start();
await ws.key('set', KEY);
await ws.settings({ model: MODEL });
- assert.equal((await ws.state()).settings.visualFallback, false, 'the fallback starts off');
+ // On unless the user turns it off (the owner's decision, 1 December 2026).
+ assert.equal((await ws.state()).settings.visualFallback, true, 'the fallback starts on');
+ await ws.settings({ visualFallback: false });
await ws.account('add', '', 'Work subscription');
[A] = (await ws.state()).accounts;
const site = fixture.createSite();
@@ -166,7 +168,7 @@ async function exercise() {
await ws.account('open', A.id);
await ws.account('done', A.id);
- // 1. With the fallback off, a section the reader cannot place stops, and says it could help.
+ // 1. Turned off by the user, a section the reader cannot place stops, and says it could help.
const off = await quick(target('810.4'));
const stopped = await finished(off, 'blocked');
assert.ok(['not_found', 'layout_changed'].includes(stopped.blockedReason), stopped.blockedReason);
@@ -226,8 +228,8 @@ async function exercise() {
assert.ok(
body.tools.every((t) => t.strict === true && t.input_schema.additionalProperties === false),
);
- assert.equal(body.max_tokens, 16000, 'room to think, below the model’s own 64,000');
- assert.deepEqual(body.output_config, { effort: 'low' });
+ assert.equal(body.max_tokens, 64000, 'the model’s whole output: no cap of the app’s own');
+ assert.deepEqual(body.output_config, { effort: 'medium' });
}
// Reasoning goes back exactly as returned while nothing before it changes. A new screenshot
// replaces the one before it, and the reasoning from before that edit is left out.
diff --git a/test/visual.test.ts b/test/visual.test.ts
index 11f13ba..bd9c1a8 100644
--- a/test/visual.test.ts
+++ b/test/visual.test.ts
@@ -11,6 +11,7 @@ import {
type VisualDeps,
type VisualPage,
} from '../src/agent/visual';
+import { fallbackTokensPerCall, spendState } from '../src/agent/budget';
import { BlockedError, Halted, type SourceCapture } from '../src/sites/adapter';
import type { PageMark } from '../src/extract/marks';
@@ -40,6 +41,7 @@ function setup(
modelInfo?: VisualDeps['modelInfo'],
usage = { input_tokens: 10, output_tokens: 2 },
target: Partial = {},
+ extra: Partial = {},
) {
const calls: Body[] = [];
const replies: object[][] = [];
@@ -100,6 +102,7 @@ function setup(
permitted: (href) => !href.includes('pricing'),
progress: () => {},
usage: () => {},
+ ...extra,
});
const lastResult = () =>
calls
@@ -176,24 +179,36 @@ test('Claude chooses each step with strict pointing tools, one call at most, and
// Strict schemas take no numeric or length bounds; app code checks those.
assert.doesNotMatch(JSON.stringify(tool.input_schema), /minimum|maxLength/, tool.name);
}
- // Thinking cannot be turned off on current models, so a step has room for it.
- assert.equal(body.max_tokens, VISUAL_LIMITS.maxTokens);
- assert.equal(body.max_tokens, 16_000);
- assert.equal(body.output_config, undefined, 'no effort for a model that does not report it');
+ // Thinking cannot be turned off on current models, so a step has room for it: no output cap
+ // of the app's own, and 64,000 only because this model's own limit is not known.
+ assert.equal(body.max_tokens, fallbackTokensPerCall);
+ assert.equal(body.max_tokens, 64_000);
+ assert.equal(body.output_config, undefined, 'no effort unless one was fitted to the model');
}
assert.deepEqual(calls[0]!.tools, calls[1]!.tools, 'the tools stay the same for the whole look');
});
test("the model's own limits and controls shape each step", async () => {
- const small = setup([start, end], async () => captured, { maxOutputTokens: 8_192, effort: true });
+ const small = setup(
+ [start, end],
+ async () => captured,
+ { maxOutputTokens: 8_192 },
+ undefined,
+ {},
+ { effort: 'medium' },
+ );
await small.run();
for (const body of small.calls) {
assert.equal(body.max_tokens, 8_192, 'never more than the model can write');
- assert.deepEqual(body.output_config, { effort: 'low' });
+ assert.deepEqual(body.output_config, { effort: 'medium' });
}
const large = setup([start, end], async () => captured, { maxOutputTokens: 128_000 });
await large.run();
- assert.equal(large.calls[0]!.max_tokens, 16_000, 'never more than one step needs');
+ assert.equal(
+ large.calls[0]!.max_tokens,
+ 128_000,
+ 'the model’s whole output, with no cap of the app’s',
+ );
const loose = setup([start, end], async () => captured, { structuredOutputs: false });
await loose.run();
assert.ok(
@@ -250,7 +265,7 @@ test('a step cut off at its output limit is a give-up, and nothing in it is carr
],
async () => captured,
);
- await assert.rejects(run(), /reached its limit of 16,000 output tokens for one step/);
+ await assert.rejects(run(), /reached the most this model can write in one step/);
assert.equal(calls.length, 1);
assert.deepEqual(opened, []);
});
@@ -344,41 +359,64 @@ test('a choice whose arguments do not fit its tool is refused, and Claude is tol
);
});
-test('a look never sends past its input limit, so what it can cost has a ceiling', async () => {
+test('a look has no token limit: it stops at its steps, however much it has sent', async () => {
const scroll = { name: 'scroll', input: { direction: 'down' } };
- // Two requests of 40,000 fit in 100,000; a third would not, so it is never sent.
- const { run, calls } = setup([scroll, scroll, scroll, scroll], async () => captured, undefined, {
- input_tokens: 40_000,
- output_tokens: 2,
+ const steps = Array.from({ length: VISUAL_LIMITS.actions + 5 }, () => scroll);
+ const { run, calls } = setup(steps, async () => captured, undefined, {
+ input_tokens: 400_000,
+ output_tokens: 60_000,
});
await assert.rejects(
run(),
- (error) => error instanceof VisualGiveUp && /token limit/.test(error.message),
+ (error) => error instanceof VisualGiveUp && /within 40 steps/.test(error.message),
);
- assert.equal(calls.length, 2);
- assert.ok(2 * 40_000 <= VISUAL_LIMITS.inputTokens);
+ assert.equal(calls.length, VISUAL_LIMITS.actions);
+ assert.equal(VISUAL_LIMITS.actions, 40);
+ assert.deepEqual(Object.keys(VISUAL_LIMITS).sort(), ['actions', 'marks', 'pageLoads']);
});
-test('a larger screenshot counts toward the next request before it is sent', async () => {
+test('the month’s spending limit stops a look before its next request', async () => {
const scroll = { name: 'scroll', input: { direction: 'down' } };
- const png = (width: number, height: number) => {
- const bytes = Buffer.alloc(24);
- bytes.write('\x89PNG\r\n\x1a\n', 0, 'latin1');
- bytes.write('IHDR', 12, 'ascii');
- bytes.writeUInt32BE(width, 16);
- bytes.writeUInt32BE(height, 20);
- return bytes;
- };
- const usage = { input_tokens: 40_000, output_tokens: 2 };
- const same = setup([scroll, scroll, scroll], async () => captured, undefined, usage);
- same.page.screenshot = async () => png(1000, 800);
- await assert.rejects(same.run(), VisualGiveUp);
- assert.equal(same.calls.length, 2);
- // The window grew: its next screenshot adds (4000 x 4000 - 1000 x 800) / 750 tokens, which leaves
- // no room for a second request of the same size.
- const shots = [png(1000, 800), png(4000, 4000)];
- const grown = setup([scroll, scroll, scroll], async () => captured, undefined, usage);
- grown.page.screenshot = async () => shots.shift() ?? png(4000, 4000);
- await assert.rejects(grown.run(), VisualGiveUp);
- assert.equal(grown.calls.length, 1);
+ let spent = 10;
+ const spend = () => spendState(spent, 200);
+ // Reached before the first request: nothing is sent.
+ spent = 200;
+ const never = setup([start, end], async () => captured, undefined, undefined, {}, { spend });
+ await assert.rejects(
+ never.run(),
+ (error) =>
+ error instanceof VisualGiveUp &&
+ /Claude is stopped: this month's estimated cost/.test(error.message),
+ );
+ assert.equal(never.calls.length, 0);
+ // Reached while it looks: the step in flight finishes, and the next is not sent.
+ spent = 10;
+ const live = setup(
+ [scroll, scroll, start, end],
+ async () => captured,
+ undefined,
+ undefined,
+ {},
+ {
+ spend,
+ usage: (total) => {
+ if (total.iterations === 2) spent = 200;
+ },
+ },
+ );
+ await assert.rejects(live.run(), /reached your limit of \$200/);
+ assert.equal(live.calls.length, 2);
+ // No limit set, or not reached: the look runs its course.
+ spent = 1_000_000;
+ const free = setup(
+ [start, end],
+ async () => captured,
+ undefined,
+ undefined,
+ {},
+ {
+ spend: () => spendState(spent, 0),
+ },
+ );
+ assert.equal(await free.run(), captured);
});