Skip to content

Reading cost outside spwn

spwn writes each session’s cost into a file of its own, in spwn’s data folder. Reading it doesn’t need spwn, only a TOML parser, so a script can total a sprint’s branches and a workflow can report what a ticket cost.

The file is not in your repository. spwn used to commit it on the session’s branch; it no longer does, so a branch’s diff is the work and nothing else. The cost of a change still reaches your teammates, in the pull request.

Each session has one PR doc:

<app data dir>/pr/<project id>/<branch-slug>.md

The app data dir is ~/.local/share/gg.spwn.spwn/ on Linux. The slug is the branch name with anything outside A-Z a-z 0-9 . _ - replaced by -, so branch spwn/1a2b3c4d has its doc at pr/<project id>/spwn-1a2b3c4d.md. The Inspector’s PR tab shows the full path, and a workflow gets the folder from spwn.project.prDocs.

The file is TOML front matter between +++ fences, followed by markdown prose:

+++
problem = "checkout-latency"
reviewer = "dana" # anything you like
[cost]
files = 1
model = "claude-opus-5"
sessions = ["6b254ae6-c327-43f6-a071-e19fc5baad4d"]
usd = 5.9289
[cost.tokens]
cacheRead = 6120455
cacheWrite = 188920
cacheWrite1h = 170512
cacheWrite5m = 18408
input = 310
output = 41877
requests = 58
+++
# Cache the tax lookup
The agent's description of the change…

The fences are +++, not ---. Most tools read --- as YAML. The front matter is free-form: spwn owns cost (plus title, pr, pr_url and pr_repo once a pull request exists), and every other key is yours. When spwn writes a key, it rewrites only that key and leaves your comments, key order, and prose unchanged. Every field of cost is described in How cost is counted.

One file per branch, so no two sessions ever write the same one.

It is a file; read it:

Terminal window
cat ~/.local/share/gg.spwn.spwn/pr/<project id>/spwn-1a2b3c4d.md

For one branch on its own, cost.usd and cost.tokens are the figures you want: the whole conversation, including anything inherited from a fork.

To total several branches, add up each one’s own spend, not its tokens. Three rules cover every doc:

  1. If own is present, use it. The session is a fork, and own excludes the conversation it inherited.
  2. If own is absent, it equals tokens. The session inherited nothing.
  3. If ownUnknown = true, skip the session. spwn couldn’t measure what it inherited, and its tokens include spend that’s already counted on its parent.

This script applies those rules to every doc in a project’s folder. It uses only Python’s standard library (3.11 or later, for tomllib):

#!/usr/bin/env python3
"""Total what every spwn branch in a project cost, from the PR docs alone."""
import pathlib, re, sys, tomllib
FIELDS = ("input", "output", "cacheRead", "cacheWrite", "requests")
FRONT = re.compile(r"\A\ufeff?\+\+\+\r?\n(.*?)^\+\+\+\r?$", re.S | re.M)
docs = pathlib.Path(sys.argv[1]) # <app data dir>/pr/<project id>
total = dict.fromkeys(FIELDS, 0)
usd = 0.0
for path in sorted(docs.glob("*.md")):
name = path.stem
match = FRONT.match(path.read_text())
cost = tomllib.loads(match.group(1)).get("cost") if match else None
if not cost:
print(f"{name:32} no cost recorded")
continue
if cost.get("ownUnknown"):
print(f"{name:32} skipped: own share unknown")
continue
own = cost.get("own", cost["tokens"]) # absent own == tokens
own_usd = cost.get("ownUsd") if "own" in cost else cost.get("usd")
for k in FIELDS:
total[k] += own.get(k, 0)
usd += own_usd or 0.0
shown = f"${own_usd:,.2f}" if own_usd is not None else "unpriced"
print(f"{name:32} {shown:>10} {own['requests']:>6} req")
print(f"{'total':32} ${usd:>9,.2f} {total['requests']:>6} req "
f"{total['output']:,} output tokens")
Terminal window
python3 scripts/spwn-cost.py ~/.local/share/gg.spwn.spwn/pr/<project id>

A few notes on the result:

  • Tokens sum exactly. Dollars are an estimate. A fork’s ownUsd is its usd split by request share, and usd itself comes from a rate table. If the table was emptied, there’s no usd, and the script reports unpriced.
  • Only branches that still exist are counted. A doc is removed once its branch and its session are both gone, as described in the next section.
  • It runs where spwn runs. The docs are on the machine spwn is on, so this is not a CI job. What CI and reviewers can see is the cost line in the pull request.

A PR doc lasts as long as something refers to it. When a session is deleted, spwn removes every doc in the project whose branch no longer exists and whose session is gone. A branch that outlives its session keeps its doc.

Once the doc is removed it is gone: nothing commits it, so there is no history of it to read back. What stays is the pull request, whose body carries the cost as of its last Push update.

Older versions of spwn kept the doc at .spwn/pr/<branch-slug>.md in the worktree and committed it. Two things are left over from that:

  • A session started under the old version still has its doc in its worktree. spwn moves it into the data folder the first time it reads it, and the file’s deletion shows up in that session’s next commit.

  • Your base branch may still carry .spwn/pr/ files from sessions that merged. Nothing reads them and nothing removes them for you. Delete them once:

    Terminal window
    git rm -r .spwn/pr && git commit -m "Remove spwn PR docs from the repo"

Inside spwn, a workflow can get a group total without reading the files. session.cost() returns spend across every session working the same problem as the one you call it on:

export default async (spwn) => {
const s = await spwn.sessions.find("TICKET-412");
if (!s) return;
const { problem, sessions, total } = await s.cost();
console.log(`${problem.kind} ${problem.key}: $${total.usd ?? "?"} over ${total.requests} requests`);
for (const row of sessions) {
console.log(row.title, row.branch, row.own ? `${row.own.requests} req` : "not measured");
}
};

spwn groups sessions within the project by the first rule that applies:

problem.kind Groups sessions that… problem.key
declared have the same problem key in their PR doc’s front matter that value
workflowKey were created by the same workflow with the same key (sessions.create({ key }) or agents.run({ key })) the key
lineage descend from the same root session by forking the root session’s id

declared is the only rule that can group sessions that were never forked from one another. Set it from the PR tab’s front-matter editor, from a workflow with s.setPr({ problem: "checkout-latency" }), or by having the agent write it into the doc.

The result has this shape:

  • total is the group’s spend, with the same token fields as cost.tokens, plus usd and unpriced where they apply. spwn computes it by scanning all the group’s transcripts together and deduplicating by request id. It isn’t a sum of anyone’s tokens, so shared fork history is counted once.
  • sessions is one row per member: terminalId, title, branch, and own. own is the part that’s safe to add up, already resolved (an absent own in the doc shows up here as tokens). It’s null for a session with no cost yet, or one marked ownUnknown.

The PR tab shows the same rollup under Spend across this problem. The full types are in spwn.d.ts and the Workflows API reference.

When spwn opens a pull request from a session, or you press Push update, the body gets a spwn section between <!-- spwn:begin --> and <!-- spwn:end -->. It ends with a one-line summary such as Cost to produce: $5.93 · 6.4M tokens. The token count there is the session’s own input, output, cache-read and cache-write tokens added together. See Pull requests.