Skip to content

Read Meta Muse Code sessions - #1326

Closed
ozymandiashh wants to merge 4 commits into
getagentseal:mainfrom
ozymandiashh:feat/muse-code-provider
Closed

ozymandiashh wants to merge 4 commits into
getagentseal:mainfrom
ozymandiashh:feat/muse-code-provider

Conversation

@ozymandiashh

Copy link
Copy Markdown
Collaborator

Summary

  • Adds a muse-code provider for Meta's Muse Code CLI (muse, beta since 2026-08-05, on the Muse Spark models). It walks $XDG_DATA_HOME/muse/sessions/YYYY/MM/DD/<session-id>/session.jsonl (default ~/.local/share/muse, with MUSE_DATA_DIR as an exact-directory override the way OPENCODE_DATA_DIR is) plus the subagent/<child-id>/session.jsonl transcripts beside it, and prices each model step from the meta/muse-spark-* rows already in the bundled LiteLLM snapshot — contributor tier included, and no alias needed: the snapshot already carries the bare spellings the logs use.
  • Handles the two ways this format double-counts. Muse 1.1.x writes two records for one model step — a goal_usage_attribution carrying the tokens, a stable usage_id and the owner, and a model_completed carrying the model name — so they are paired within a run_id and counted once. And a delegated run is copied into the parent's log as well as its own, so dedup is on identity (muse-code:<usage_id>), never on position; the same key collapses a forked session replaying the prefix it inherited. Delegated work bills to the root session, as codex does for forks.
  • probeRoots() reports the sessions dir so codeburn doctor distinguishes "Muse Code is not installed" from "MUSE_DATA_DIR points somewhere empty" (doctor: extend probeRoots() beyond 7/42 providers to kill the silent-zero class #899). sessions/.msp-view-v1/ is a fold of the same usage and is skipped. No quota adapter: Muse never persists plan windows to disk — they arrive only at the end of a live, billed model call, so a refresh would cost the user money. docs/providers/muse-code.md says so.

⚠️ Validated against published log excerpts and a free local --provider echo run, NOT against a paid Meta session

Please read this before the diff.

A real Muse Code 1.1.1 (1.1.1-R2514.1) binary (build sha b934305d21) is installed on the machine this was written on, and it wrote real sessions to disk. But it was never logged in: every local session was produced with muse exec --provider echo, which needs no credentials and bills nothing. So every token counter in every local log is zero, and no model id appears anywhere — the echo provider has none and rejects --model outright ("--model requires --provider meta").

That splits the evidence in three, and the split is the single most important thing to review:

Confirmed from the real binary

Read off session.jsonl directly and cross-checked against muse export --session <id> (whose events[].envelope is the on-disk line verbatim), muse trace inspect --session-log, and the wire schema from muse schema generate-json-schema — all offline, all unauthenticated.

Claim Evidence
Path sessions/YYYY/MM/DD/<session-id>/session.jsonl, XDG-based on macOS 3 sessions written across a date boundary and two workspace roots
subagent/<child-id>/session.jsonl for delegated runs 6 child transcripts on disk
sessions/.msp-view-v1/<session-id>/ holds a fold of the same usage HEAD.json, binary journal/index, snapshot-*.json
Two line shapes. Most lines are the record; some are a retained_frame transaction wrapper whose children[].record_json are records escaped as JSON strings the first line of every session is such a wrapper — a parser that misses it starts two records late
recorded_at is microseconds e.g. 1789246716491567
Project is runtime.session.metadata → payload.record.workspace_root (not "the first record") seq 3; also carries provider_id, build.{sha,semver}
goal_usage_attribution in full: record.usage_id, usage_family, quantity.{unit, reported, input_tokens, output_tokens, cached_tokens, reasoning_tokens, main_llm_steps}, owner.{requester_kind, session_id, run_id, owner_id, owner_type} seq 48
model_completed: usage.{input_tokens, output_tokens, cached_tokens, reasoning_tokens}, duration_ms seq 49 — same run, same numbers as seq 48. This is the "recorded twice" quirk
runtime.user_intent.accepted.refill_blocks[], session.opened.observed, session.end, session.workspace_branch.observed all present
Reasoning is inside output Meta's schema: TokenUsage.reasoningTokens = "Output tokens spent on reasoning"
An unreadable model is an unpriced leg, not a default Meta's schema: SessionTokenUsageParams.modelId null is "never back-filled, an unpriced leg"
Child usage is never folded into a parent's totals Meta's schema: it "rides the owning items"
Child run streams are mirrored into the parent log muse trace inspect --help: "hashed workflow-child run streams mirrored into the parent log (#6408)"

Confirmed only from published excerpts of real Meta-provider logs

Claim Source
model_completed.event.model, spelled muse-spark-1.2 / muse-spark-1.3 / -contributor, no meta/ prefix steipete/CodexBar PR #3587, MuseCostUsageScannerTests.swift, the case named for a real Muse CLI runtime log; and superset-sh/superset packages/host-service/src/trpc/router/usage/history/muse.test.ts, the case named for a real Muse Code 1.1.1 record
cache_read_tokens / cache_write_tokens on model_completed.usage CodexBar PR #3587
runtime.session.metadata.record.model_id superset's helper
assistant_tool_calls_committed.tool_calls[].name specstoryai/getspecstory specstory-cli/docs/MUSE-FORMAT.md

Both fixtures are checked in under tests/fixtures/muse-code/ with a _provenance first line naming the file and case they came from. The four other tests in CodexBar's file use a flat {timestamp, model, input_tokens, messages[]} shape that Muse does not write; they were deliberately not copied.

Not confirmed by anyone — review this line hardest

Whether input_tokens includes cached_tokens. Meta's schema refuses to say: TokenUsage.cachedTokens is "inside or beside inputTokens, provider-convention-dependent — the reason promptTokens exists", and the counted-once promptTokens is not in the durable log, only in the MSP projection. Neither real-model excerpt is numerically decisive (one has cached_tokens: 0, the other no total).

This PR subtracts — reads input as inclusive, like codex.ts — following superset, the one source that states the convention outright and implements max(0, input - cached). CodexBar does not subtract. If a real session proves cached sits beside input, exactly one line in src/providers/muse-code.ts changes; it is called out in a block comment there and in the docs.

Also unverified: which record carries the model on a real --provider meta run (all three candidate locations are read, in order); whether 1.1.1 really mirrors subagent usage (documented, but the local children died before producing any); muse resume behaviour (needs a TTY); and totals against Muse's own /usage, which is the ground truth.

Testing

  • I have tested this locally against real data (not just unit tests)
  • npm test passes
  • npm run build succeeds

For new providers only:

  • I installed the tool and generated real sessions by using it — but with --provider echo, so they carry no tokens and no cost. See the warning above.
  • npm run dev -- today shows correct costs and session counts for this provider — discovery and session counts yes, costs no. All 9 sources are found and parsed; every counter is a true zero because the echo provider bills nothing, so today correctly reports no usage rather than a fabricated $0.00 call. A paid session is the only thing that can exercise the cost path.
  • npm run dev -- models --provider muse-code shows correct model names and pricing — cannot pass without a paid session. An echo run has no model id. The pricing path is instead pinned by tests against the published real-model excerpts, which assert muse-spark-1.3 at $1.25/1M input and muse-spark-1.3-contributor at $0.10/1M off the bundled snapshot.
  • Screenshot or terminal output attached below proving it works with real data

Everything above is why this PR should not be merged on my say-so. The new-provider bar exists exactly for this: the discovery, dedup, project attribution and schema handling are validated end to end against real logs, and the cost path is validated only against published numbers. A maintainer with a Muse Code subscription running npm run dev -- today and models next to muse's own /usage is the missing check. I have also not commented on an issue first — there is no CodeBurn issue for Muse (gh search issues --repo getagentseal/codeburn muse finds none), so this PR is also the proposal.

Affiliation: none. No connection to Meta or to Muse Code.

Terminal output

codeburn doctor against the three real sessions on disk:

$ npm run dev -- doctor --provider muse-code
CodeBurn doctor   1 provider

┌─────────────┬────────────┬──────────┬──────────┬───────────────────┐
│  Provider   │  Sessions  │  Parsed  │  Cached  │  Verdict          │
├─────────────┼────────────┼──────────┼──────────┼───────────────────┤
│  Muse Code  │         9  │    8/8+  │       0  │  OK (9 sessions)  │
└─────────────┴────────────┴──────────┴──────────┴───────────────────┘

Details
  Muse Code
    sessions: /Users/me/.local/share/muse/sessions (exists)

9 sources = 3 top-level transcripts + 6 subagent/ children. Projects resolve from workspace_root, which is only reachable through the retained_frame unwrap plus the metadata record.

The #899 case, with the override pointed at nothing — a missing directory is reported, never a silent zero:

$ MUSE_DATA_DIR=/tmp/nope-not-here npm run dev -- doctor --provider muse-code
Details
  Muse Code
    override MUSE_DATA_DIR=/tmp/nope-not-here
    sessions: /tmp/nope-not-here/sessions (missing)

Bottom line: 0 OK, 1 with nothing found, 0 with errors.

today and models both report no usage, which is the correct outcome for echo-provider logs and the case that must never surface as a fabricated $0.00.

Suite

  • tests/providers/muse-code.test.ts: 36 tests, including all three real-log fixtures parsed end to end.
  • Mutation-checked: 16 mutants applied to the provider, 16 killed — including "sum both usage records", "dedupe by position not identity", "cached NOT subtracted from input", "default unknown model to a tier", "no retained_frame unwrap" and "descend into dot dirs".
  • Full suite: 297 files / 4050 tests passing (2 files, 5 tests skipped). npx tsc --noEmit clean. semgrep bracket-assign rule: 0 findings. cd mac && swift build succeeds (no Swift surface touched).
  • Two existing guards needed feeding and are green: MUSE_DATA_DIR added to tests/setup/env-isolation-vars.ts, and a FILE_PROVIDERS entry in tests/provider-env-declarations.test.ts (Nine providers' env overrides do not invalidate their cache (undeclared in PROVIDER_ENV_VARS) #920). tests/providers/probe-roots-899-census.test.ts passes unchanged.

New-provider checklist (docs/providers/NEW_PROVIDER.md)

  • One provider, one product — muse-code is the CLI only; the consumer "Muse" app runs on a Meta-hosted VM and writes nothing locally
  • src/providers/muse-code.ts implementing the Provider contract
  • Registration in src/providers/index.ts (lazy list)
  • PROVIDER_ENV_VARS entry — ['MUSE_DATA_DIR', 'XDG_DATA_HOME']
  • PROVIDER_PARSE_VERSIONS entry — intentionally absent. A new provider has no cached entries to force a re-parse of; the first entry belongs to the first parser change after ship, and the cached-vs-inclusive-input decision above is the likeliest reason for it.
  • probeRoots() implemented
  • Cost rules — Muse meters tokens, never dollars, so it stays off the providerCallToCachedCall reported-cost allowlist and everything goes through calculateCost. quantity.reported: false sets costIsEstimated.
  • Defensive reads on every field
  • Dedup keys namespaced — muse-code:<usage_id>
  • Timestamp seconds/ms/µs guard with an implausibility floor
  • One corrupt file never throws
  • Fixture-based tests covering discovery, parsing, cost semantics and probeRoots
  • Tests set their own overrides (suite scrubs env)
  • Proof of real local testing: generated sessions from the actual tool, not only fixtures — PARTIAL. Real sessions from the real binary, yes; real costs, no. This is the gap, and it is the one the maintainer has to close.
  • No Claude/Anthropic co-author trailers
  • Docs page under docs/providers/muse-code.md

Muse Code (Meta's `muse` CLI, beta since 2026-08-05, running on the Muse
Spark models) writes append-only JSONL transcripts to a date-sharded tree
that looks a lot like Codex's, and the Muse Spark prices are already in
the bundled LiteLLM snapshot. Nothing read them.

Discovery walks `sessions/YYYY/MM/DD/<id>/session.jsonl` under
`$XDG_DATA_HOME/muse` (default `~/.local/share/muse`), with `MUSE_DATA_DIR`
as an exact-directory override, the contract `OPENCODE_DATA_DIR` has, so a
relocated install is found instead of reporting zero. The date filters also
keep the walk out of `sessions/.msp-view-v1/`, which is a fold of the same
usage and would double every call.

Two double counts drove the parser's shape, and each has its own test:

* Muse 1.1.x writes BOTH a `goal_usage_attribution` and a `model_completed`
  record for one model step, carrying the same numbers. Summing them
  doubles every call, so the two are paired within a `run_id`: tokens and
  the stable `usage_id` come from the attribution, the model name and
  duration from the completion. A step with only a completion is billed
  from it instead.
* A delegated run is copied into the parent's log as well as into
  `subagent/<child-id>/session.jsonl`. Dedup is therefore on identity -
  `muse-code:<usage_id>` in the scan-wide key set - never on position,
  which also collapses a forked session replaying its inherited prefix.
  Delegated work bills to the root session, as codex does for forks.

The rest is defensive reading of a format that auto-updates hourly: the
retained-frame transaction wrapper that opens every transcript is
unwrapped into its escaped children, microsecond timestamps are promoted
and range-checked, non-numeric token counts read as zero, an unknown event
kind is counted and skipped rather than fatal, and a corrupt line never
takes the file down. `probeRoots()` reports the sessions dir so `doctor`
can tell "not installed" from "override points somewhere empty" (getagentseal#899).

Pricing: the snapshot already resolves the bare log spellings, contributor
tier included, so no alias was added - a test pins that the two tiers stay
12.5x apart instead. Reasoning joins the inclusive-output set, because
Meta's own MSP wire schema defines `TokenUsage.reasoningTokens` as output
tokens spent on reasoning. A step whose model cannot be read is reported
unpriced rather than guessed into a tier, which is also Meta's rule: a null
`modelId` there is "never back-filled, an unpriced leg".

No quota adapter. Muse does not persist plan windows to disk; they arrive
only at the end of a live, billed model call, so a refresh would cost the
user money.

Validated against a real `Muse Code 1.1.1 (1.1.1-R2514.1)` binary's own
logs, cross-checked with `muse export`, `muse trace inspect` and its
exported wire schema, plus published excerpts of real Meta-provider
sessions for the token-bearing fields the local echo runs cannot produce.
NOT validated against a paid `--provider meta` session; the fixtures carry
their provenance and docs/providers/muse-code.md lists exactly which
fields came from which source.
Adds `docs/providers/muse-code.md` in the house style - storage layout,
the records read, the two double-count traps, cost rules, why there is no
quota adapter - plus the README provider row and index entries.

The page carries one section the others do not: an explicit
confirmed-versus-unverified split. Muse Code was verified here against a
real 1.1.1 binary, but its echo provider bills nothing and refuses
`--model`, so the model-id field and the cache convention rest on
published excerpts of real Meta-provider logs. Whoever sees a wrong number
should know which half of the schema to distrust first, and the page says
so, naming the single line that changes if `input_tokens` turns out to sit
beside `cached_tokens` rather than include it.

No logo: no Muse Code mark is published under terms we can vendor, so the
README lists it as a text link the way LingTai TUI is listed, and the doc
says where to drop one in.
…yout

The model id was the one field the local `--provider echo` runs could not
produce: echo has no model and rejects `--model` outright. It is now
confirmed from the binary itself. Rust stores serde field-name literals
contiguously in declaration order, so the structs are recoverable from
`muse-bin-1.1.1-R2514.1`, and every key already known from the JSONL shows
up there in the right neighbourhood - which is what validates the method
rather than the guess.

What that settles:

* `SessionMetadata` is `provider_id` `model_id` `web_search_mode`
  `tool_surface_version`. So `model_id` really is the session default, in
  snake_case, right after `provider_id`; an echo run omits it only because
  it is null and serde skips it.
* The `model_completed` event is `usage` `duration_ms` `finish_reason`
  `model`. The per-completion field is `model`, not `model_id`.
* `EffectiveModelState` is `provider_id` `profile_id` `model_id`
  `display_label` `source` `last_command_id`, and it rides a contiguous
  family of run events. Three of them apply a model
  (`model_selection_initialized`, `model_reconfigure_completed` via its
  nested `effective`, `run_model_configured` via a flat `model_id`) and
  three deliberately do not (`model_reconfigure_failed`, `_rejected`,
  `standing_model_route_unserved`). The negative ones name the model that
  was NOT applied; treating one as a setter would price every later step
  at a model the session never ran, so they are listed as explicitly inert
  instead of being left to fall through.

So the session default now moves with the session instead of being read
once at pricing time, and precedence is: this step's own `model`, then
another completion in the same run, then the session default in force when
the record was read, then unknown. The metadata record is deliberately not
consulted again at the end - doing so silently undoes a mid-session change
for any step that named no model itself.

Two smaller findings from the same scan:

* A sibling usage struct spells `input_tokens` `cached_input_tokens`
  `non_cached_input_tokens` `output_tokens` `total_tokens` - cached is a
  partition OF input there. That corroborates the subtraction this parser
  already does for `quantity.cached_tokens`, so the docs downgrade that
  caveat from "unverified" to "corroborated, unconfirmed on a paid run".
  It is a sibling struct, not `quantity`, so it is not proof.
* This build bakes in `muse-spark-1.2` and `muse-spark-1.2-internal`, with
  the live catalog served by `model/list`. The internal id resolves to its
  published Standard sibling's row: it is not a contributor id, so the
  contributor rate would understate it 12.5x, and leaving it unknown would
  report real spend as $0. An internal rate, if Meta ever publishes one,
  needs a price override rather than an alias.

Also documents, without reading, the SQLite session registry the binary
keeps at `<root>/runtime/muse/.session-registry*` - an obvious future index
for cheap discovery, `git_branch` attribution and session titles. The JSONL
stays canonical; adding a SQLite path here would be scope creep.

`duration_ms` and `finish_reason` are named in the docs but not parsed:
there is no throughput or stop-reason accounting for this provider, and
capturing fields nothing reads is just cost.

New fixture `tests/fixtures/muse-code/synthesised-meta-run.jsonl` is the
real echo log with exactly two fields added at the positions above, plus
non-zero counters so the pricing path has something to exercise. It is the
only synthesised fixture here, its first line says so in full, and it must
be replaced by a real `--provider meta` session.
CHANGELOG.md only: both sides added entries to the unreleased section; kept both.
@ozymandiashh

Copy link
Copy Markdown
Collaborator Author

Closing for now — it has drifted behind main and the slot is needed under the new five-open-PR cap. The branch stays on the fork; it can be rebased and reopened once the queue clears.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant