Commit graph

181 commits

Author SHA1 Message Date
iamtoruk
f9f79b0660 Merge remote-tracking branch 'origin/main' into pr1040-rebase
# Conflicts:
#	CHANGELOG.md
2026-08-19 13:18:09 -07:00
Aditya Vikram Singh
3e93741f6f fix(hermes): require origin identity and fail-closed fences 2026-08-19 20:50:19 +05:30
Aditya Vikram Singh
fae4db0008 fix(hermes): restore z-ai pricing; require owner/repo; reject UNC
Extra High held 91754c5. z-ai/glm-5.2 went unpriced (Cline's real
vendor spelling). Forward-slash UNC became a workspace on POSIX.
PR matching used basename, so evil/codeburn collided. Tilde fences
were still scanned.

Add z-ai to known namespaces. Reject // UNC on POSIX. Attribute
PRs only when origin yields owner/repo. Strip ``` and ~~~ fences.
Bump Hermes parse version to v4.
2026-08-19 20:32:51 +05:30
Aditya Vikram Singh
91754c5f54 fix(hermes): fail closed on unknown namespaces, relative cwd, fenced PRs
Extra High held #1039 again. An unknown provider/model still became a
bare-model price via getCanonicalName's first-segment strip. Relative
cwd values like '.' could inherit the invoking repo. PR scrape treated
fenced dumps and other repos as attribution.

Peel only known vendor/router namespaces. Require an absolute
platform path before a Hermes cwd is a workspace. Ignore fenced URLs
and, when a git root exists, keep only that repo's pull links.
Bump the Hermes parse version so old cache rows reparse.
2026-08-19 20:19:29 +05:30
Aditya Vikram Singh
10fdec6037 fix(hermes): fail closed on unknown GLM, namespaces, and ACP identity
Extra High review held #1039. Stop pricing every future glm-5.x as 5.2,
stop collapsing unknown provider/org/model trees onto a priced leaf, and
stop calling ACP Buzz — source=acp is a transport and the DB has no
client field. Strip trailing punctuation on PR URLs and bump the Hermes
parse version so old cache rows reparse.
2026-08-19 19:42:42 +05:30
Aditya Vikram Singh
66a776acfa fix(hermes): treat routing prefixes and session surfaces as classes
Price any OmniRoute/Cline/cmd/antigravity wrapper by peeling prefixes
and, for GLM 5.x, falling back to the newest priced sibling. Do not
require a new alias per model id.

Classify Hermes sessions by surface and workspace: ACP is the Buzz
app; project comes from git root or a real cwd, never $HOME or a
profile name.
2026-08-19 18:46:11 +05:30
Aditya Vikram Singh
0abbbd1b4a fix(hermes): only attribute PRs mentioned by the user or assistant
Tool dumps (gh pr list, changelog grep) were smearing one session
across dozens of pull URLs. Capture links from user and assistant
text only.
2026-08-19 18:28:07 +05:30
Tim De Pauw
1d36f444d7
Fix Codex model attribution after session metadata
Limit session_meta model extraction to direct payload fields so nested provenance metadata cannot overwrite turn_context. Invalidate cached parses and cover model switches with a regression test.
2026-08-19 14:49:04 +02:00
Aditya Vikram Singh
0658308448 fix(hermes): price glm-5.3, label default as hermes, capture PR links
GLM-5.3 is missing from LiteLLM, so Hermes/Cline sessions priced at $0.
Alias it to the glm-5p2 sibling and keep the display name GLM-5.3.

The root Hermes profile was shown as project "default". Use "hermes"
for that profile only; named profiles and cwd inference are unchanged.

Scan Hermes transcripts for https GitHub pull URLs and attach them so
the Pull requests page can attribute those sessions.
2026-08-19 18:06:51 +05:30
iamtoruk
37796a568e models: distinguish grok-4.5-build from grok-4.5 in reports
Reports bucket rows by model id and label them afterwards, so the two ids
collapsing onto one display name printed what looked like the same row twice
with different numbers. Give the variant its own SHORT_NAMES entry, which the
longest-first match picks over the grok-4.5 prefix. Display only: ids are
untouched, so nothing re-parses and no cost moves.

Fixed in the shared table rather than the grok provider so the menubar and
model-breakdown, which call getShortModelName directly, get it too.

Fixes #1029.
2026-08-18 12:01:12 -07:00
iamtoruk
ada9382833 test(grok): pin the unpriced-model branch instead of inheriting it from the snapshot
Both multi-model tests assert that chooseAuthoritativeModel skips a
modelUsage id it cannot price and falls back to a priced one. They got that
"cannot price" from the bundled LiteLLM snapshot happening not to carry
grok-4.6-build, so `npm run build` - which re-fetches the snapshot - flipped
both assertions the moment an xai/grok-4.6 entry appeared upstream and the
prefix match started pricing the id.

Stub getModelCosts for that one id instead. The reporter's real ids stay in
the fixtures, so the tests still document the #998 case, and calculateCost is
left alone: module-internal calls are not intercepted, so cost assertions
keep pricing off the real tables.

Verified by re-running both files against a refreshed snapshot that does
carry xai/grok-4.6; 26/26 pass where they previously failed.
2026-08-18 10:26:06 -07:00
iamtoruk
05a2afb064 Merge remote-tracking branch 'origin/main' into pr1015-rebase
# Conflicts:
#	src/main.ts
#	src/optimize.ts
#	src/session-cache.ts
#	tests/models-report.test.ts
2026-08-18 10:09:05 -07:00
ozymandiashh
72aad9e012 fix(grok): read the CLI's own completed-turn usage instead of estimating it
Grok CLI writes a turn_completed update carrying a full usage object --
inputTokens, outputTokens, cachedReadTokens, cacheCreationTokens,
reasoningTokens -- into the same updates.jsonl the parser already reads. We
ignored it and reconstructed an estimate from _meta.totalTokens, a running
context-size counter that rides on unrelated events, with a
total < prevTotal * 0.5 reset as the turn boundary.

On the cache-heavy session reported in #998 that reconstruction captured about
1.4% of the real cache-read volume and roughly 6% of the day's tokens, while
over-counting output about fivefold. cacheCreationInputTokens and
reasoningTokens were hardcoded to zero regardless of what the session held.

The parser now reads turn_completed.usage, keyed by the record's snake_case
prompt_id so a re-emitted turn cannot double count, and sums across turns.
Two decompositions matter, both derivable from the reported numbers:
totalTokens equals inputTokens + outputTokens exactly, so cachedReadTokens and
cacheCreationTokens are subsets of input and are subtracted out per record
before pricing, matching the cache-exclusive convention codex and copilot
already use; and reasoningTokens is a subset of output.

That second one needs care, because the repo contract is the opposite of
Grok's: ParsedProviderCall.reasoningTokens is exclusive of outputTokens
everywhere, and every consumer sums the two -- tests/providers/kiro.test.ts
says so outright. So reasoning is clamped to the reported output and output is
emitted without it, and the downstream sum reconstructs Grok's number. Without
the clamp a record with reasoning > output produced a negative output and left
the pipeline pricing reasoning instead.

Multi-model attribution is deliberately out of scope. modelUsage only selects a
priced attribution id; a session that used two models is priced at one rate.
Splitting per model was tried and dropped: chooseAuthoritativeModel's
priced-id fallback exists to avoid a truthful-but-$0 row when modelUsage names
an id this checkout cannot price, and per-model pricing loses it -- the
reporter's own session collapsed from $1.20 to near zero the moment a second
id appeared.

When no valid completed record exists -- older Grok CLI versions -- the old
heuristic still runs, unchanged. The decision is taken from the deduplicated
records rather than latched per line, so a superseded or all-zero record cannot
flip a session off the heuristic and drop it. A session only partly covered by
turn_completed records keeps costIsEstimated: true rather than presenting
itself as fully provider-measured.

costUsdTicks is deliberately not read. Its scale is undocumented, and guessing
it would fabricate spend.

Bumps the grok parse version, and DAILY_CACHE_VERSION with
MIN_SUPPORTED_VERSION together, since the daily cache serves every day before
today and retains ten years. Moving them in lockstep is what keeps the
carry-forward lossless: the filename is version-suffixed, so the old file stays
on disk and is adopted for days no source can still re-derive.

Separately, detectContextBloat divided by outputTokens alone. Reasoning is
stored beside output for every reasoning-bearing provider, so the detector saw
a fraction of the generated tokens and invented high-impact findings -- a
session whose provider-reported ratio is 20:1, below the 25:1 threshold, was
reported as 133:1 with 710K tokens of claimed savings. It now uses the same
output + reasoning sum the reports use, which fixes codex, kiro, hermes, qwen
and cursor-agent too.

Reported in #998.
2026-08-18 05:44:29 +03:00
iamtoruk
09965f93ae fix(dsh): cap zstd decode, coerce usage fields, scope the snap read
Security audit follow-ups on the DeepSeek Harness provider.

- **Decompression bomb.** Every zstd frame was decoded with no output bound, so
  a 16 KB crafted log expanded to ~916 MB of RSS (a 65 KB one declares 2 GB).
  Each frame now decodes under a 64 MB per-call cap, and the caps chain into a
  running per-file budget of MAX_SESSION_FILE_BYTES: a frame is given only the
  bytes the file has left, so node throws ERR_BUFFER_TOO_LARGE without
  allocating past the cap. The throw propagates out of the existing skip path,
  which discards the whole file rather than counting the frames read before the
  bomb, so a crafted tail cannot poison a partial total. The discovery header
  read takes the same per-frame cap. Measured on a 65 KB / 2 GB bomb: 916 MB
  -> 67 MB peak, zero calls emitted, one notice.
  Lines are still materialized eagerly; the byte budget bounds that, and making
  the read lazy would change readEventLines' contract for no further bound.
- **Usage type confusion.** Token fields were read with `?? 0` and never
  type-checked, so a string or array inputTokens flowed into the global totals
  and the persisted cache, where `0 + [1, 2]` becomes "01,2". They now go
  through numberOrZero (copilot.ts semantics: finite, positive, else 0).
  All-zero calls are still skipped.
- **Snap over-scope.** The personal-files read entry is `$HOME/.dsh/sessions`
  rather than all of `$HOME/.dsh`; the provider reads nothing else.
- **Third-party notice.** scanZstdFrames is transcribed from
  @deepseek-ai/dsh-session-persistence-jsonl. The published npm package is
  BSD-3-Clause (Copyright (c) 2026, DeepSeek) while the monorepo source
  declares MIT for the same package; THIRD_PARTY_NOTICES.md reproduces the
  stricter of the two and ships via package.json `files`.
2026-08-17 17:28:41 -07:00
iamtoruk
ffd9213126 test(dsh): skip zstd container tests where node:zlib lacks zstd, cover both Node lines in CI
zstd landed in node:zlib in 22.15; the package floor and CI pin are 22.13, so
the runtime already degrades with a notice there. The tests compressed
fixtures at runtime and failed outright. Fixture writes now fall back to
plain jsonl below 22.15 so parsing semantics still run, container-specific
tests skip, and the Tests workflow runs on both 22.13.0 and latest 22.x.
2026-08-17 14:32:55 -07:00
iamtoruk
4fa16a2293 fix(dsh): correct usage attribution against the real session format
Reviewed src/providers/dsh.ts against deepseek-harness @ 99f6f02f and fixed
what the format says but the parser did not:

- A forked session's log replays its parent's events verbatim, and codeburn
  parses the parent's own log as its own session, so every inherited call was
  billed twice. The header's parentSession + seedLength mark that prefix;
  events with seq < seedLength are now skipped.
- The model now comes from the reporting assistant/message's own
  message.source, which is what actually served the step. request/header only
  describes the request DSH was about to make, and is the fallback.
- user/message also carries agent-injected context (runtime snapshots, skill
  bodies) under source.kind 'plugin'; only a typed prompt becomes the preview,
  and it is bounded to 500 chars like every other provider rather than holding
  a whole injected system prompt per turn.
- A log stamped with a session format version other than 0 is skipped with a
  notice. The format is pinned at 0 upstream with no compatibility implied, so
  reading a bumped format under today's assumptions would report confident
  wrong numbers.
- Timestamps go through the seconds-vs-milliseconds guard and fall back to the
  header createdAt, so a call can no longer carry an empty timestamp and land
  in the undated cache shard.
- The compressed read buffers the whole log to scan its frames, so it now takes
  the same oversize guard readSessionFile applies to the uncompressed variant.
- The zstd-unavailable notice fired once per session log; each distinct notice
  is now emitted once.
- Emit workingDirectory beside projectPath, as codex does.

Tests add the upstream examples/acp-agent snapshot as a fixture, covering the
real record shapes: packed reasoning-chunks/tool-call-chunks storage rows, a
plugin-injected user/message beside the typed one, and both the streamed usage
chunk and the final assistant/message usage for the same step. Plus the same
snapshot re-encoded as multi-frame zstd with a torn tail (identical output), a
forked session, an unsupported format version, and unparsable lines.
2026-08-17 10:59:52 -07:00
iamtoruk
56e291fc7c Merge remote-tracking branch 'origin/main' into pr1001-review 2026-08-17 10:49:29 -07:00
iamtoruk
1acdecdebf test(codex): give the every-boundary differential an explicit timeout
110 resume splits take ~1.3s locally but exceeded vitest's 5s default on the
CI runner once the parallel suite also hosts the parse-worker tests.
2026-08-17 01:48:04 -07:00
iamtoruk
0e11b51516 fix(cache): make the shard layout safe against a second live writer
Two live processes share one cache directory routinely (a one-shot CLI
beside the resident serve child, two menubar polls), and the shard layout
had two ways to lose data there.

- The atomic write used a FIXED temp name, so two writers publishing the
  envelope — every save does — shared one `envelope.json.tmp` and
  interleaved into a torn payload, or one deleted the shards the other's
  envelope named. 39 of 40 rounds ended in a total cache loss. The temp
  name carries a nonce again, as it did before the shard layout.
- A save reused a shard filename from its own load snapshot without
  checking the file was still there. Another process republishing that
  provider unlinks the old shard, so the stale writer published an
  envelope naming a deleted file — read back as a corrupt provider and
  dropped whole, including PR-linked orphans no re-parse can recover. A
  reused shard is now existence-checked, and re-verified once more
  immediately before the envelope is published; a vanished one is
  rewritten from memory.

Also:
- Progress saves take a 30s floor beside the file counter. Only the
  claude scan reports per file; every other provider calls saveProgress
  once at its own boundary, so the counter alone never fired there.
- The unreferenced-shard sweep waits an hour (temps still 5 minutes): an
  unreferenced shard may belong to a concurrent save whose envelope has
  not landed yet.
- The sweep also retires the pre-v8 single-file temps in the parent
  directory, which nothing writes anymore.
- The shard directory is created 0o700.
- The claude and provider paths mark the cache dirty where they DELETE a
  stale entry, not only where they replace it: an unreadable file skips
  the replace, and the deletion would otherwise live only in memory.
- Codex only treats a grown file as an append when the recorded boundary
  still lands just after a newline, so a same-inode rewrite that happens
  to end up larger re-parses instead of resuming mid-line.
2026-08-16 19:23:39 -07:00
iamtoruk
72ed163db0 perf(codex): resume an appended rollout from its last task boundary
Codex rollout files are append-only and the active ones run to hundreds
of MB, but any growth re-read the file from byte 0 because the cache
keyed only on mtime+size. The parser now records a restart point at every
task_started boundary — the byte offset plus the state the single-pass
decode carries across it — and a grown file with the same dev/ino picks
up from there.

The boundary sits at the task_started line itself, so the task it opens
is re-decoded from the tail; the entry stores how many calls were decoded
before that point so the resumed run starts from exactly those and cannot
double-count the open task. An unusable or absent snapshot falls back to
a full re-parse.

CODEX_CACHE_VERSION is deliberately not bumped: the new fields are
additive and absence-safe both ways, so a bump would discard a warm
cache for nothing.
2026-08-16 19:03:12 -07:00
iamtoruk
0bfdfa372a perf(cache): shard the session cache per provider
A warm launch rewrote the entire session cache whenever any provider
appended a few KB: on a 6 GB corpus that is a 155 MB stringify + fsync
every run. The on-disk cache is now a version-suffixed directory holding
one shard per provider plus a small envelope, and a save rewrites only
the providers marked dirty.

- Dirtiness is tracked per provider (markCacheDirty) instead of one
  global flag, so an appended Claude session no longer republishes
  Codex, Copilot and the rest.
- Shards carry a nonce in their filename and the envelope is renamed
  last, so a save is published at a single point: readers never see a
  half-updated set, and a writer that loses the refresh ownership fence
  leaves the canonical shards untouched.
- A shard that fails validation is treated as an absent provider rather
  than rejecting the whole cache, so one malformed turn costs one
  provider's re-parse instead of every provider's history.
- v7 migrates losslessly: the blob is re-laid-out into shards and
  removed only once that save publishes. Nothing re-parses.
- Cold-parse progress saves now trigger every N files parsed rather than
  every 5s, so a slow cold parse no longer rewrites the growing cache on
  a wall clock.
2026-08-16 19:03:12 -07:00
MiloMMIN
0b6141929d feat: add DeepSeek Harness (dsh) provider
Reads DSH sessions from $DSH_HOME/sessions (default ~/.dsh/sessions):
one directory per session holding session.jsonl.zstd (or an
uncompressed session.jsonl when compression=none).

The .zstd log is a concatenation of independent zstd frames (one per
appended event batch), which node:zlib's one-shot API cannot decode
whole; the provider ports the frame-boundary scan from the official
@deepseek-ai/dsh-session-persistence-jsonl package and decompresses
frame by frame. zstd needs Node >= 22.15; older runtimes get a notice
and DSH data is skipped.

Usage follows dsh-token-meter semantics: an assistant/message usage
report is the final value for its (turn, step) and replaces the
earlier assistant/chunk sample instead of double counting. Models come
from the most recent request/header config; reasoning tokens are
billed at the output rate. One parsed call per (turn, step), dedup key
dsh:<sessionId>:<turn>:<step>.
2026-08-16 16:10:08 +08:00
ozymandiashh
a95a2c5bf8 fix(desktop): close cache and lifecycle review gaps 2026-08-12 20:31:17 +03:00
ozymandiashh
d8d343e83a perf(desktop): share cache state and eliminate duplicate cold hydration 2026-08-12 17:16:41 +03:00
iamtoruk
27eac2cca4 Merge main; declare openclaude in the env-declaration guard file map 2026-08-10 02:49:25 -07:00
Resham Joshi
ad3b12bb4d
Merge pull request #908 from ozymandiashh/fix/swarm-robustness
fix(hardening): guard three malformed-input crashes (URL, timestamp, pricing entry)
2026-08-10 02:40:33 -07:00
Matthew Kelch
3536a1d3ac
fix(copilot): classify CLI sessions by source provenance, not producer (#945)
Some checks failed
CI / semgrep (push) Has been cancelled
Tests / test (push) Has been cancelled
Fixes #944.
2026-08-09 04:51:44 +03:00
ozymandiashh
b7235adb16 fix(parser): fold SQLite -wal siblings into source fingerprints
Hermes, Cursor, OpenCode and copilot OTel sources all live in SQLite
databases that their agents keep open in WAL mode for the life of the
process. Committed writes park in <db>-wal until a checkpoint, so the
main file's stat can sit hours or days behind the newest committed data.

fingerprintFile only statted the main file, which broke two ways:

- The date-range mtime pre-filter in parseProviderSources read the stale
  mtime as "nothing in range" and skipped the source entirely. Every
  Hermes session committed after the last checkpoint vanished from
  reports: the today-parse skipped the db (mtime < local midnight) while
  the backfill only keeps days through yesterday. Exactly the "17
  sessions in the DB, 14 reported, the 3 from today missing" report in
  issue #913.

- reconcileFile saw an unchanged fingerprint between checkpoints and kept
  serving stale cached turns for sessions that had since grown.

Fold the -wal sibling into the fingerprint: newest mtime wins and sizes
add, so both WAL growth and a checkpoint (db grows, wal truncates) move
the fingerprint. -shm is deliberately ignored (it mutates on reads).
Bare SQLite paths get the fold only when the extension says database, so
JSONL transcript fingerprints (offset-based append detection) are
untouched.

Refs #913
2026-08-04 14:38:43 +03:00
ozymandiashh
48fd0daa0c fix(providers): guard two malformed-input crashes in the parse path
- vscode-cline-parser: entry.ts was truthy-checked but not validity-checked,
  so a garbage timestamp made new Date(ts).toISOString() throw RangeError and
  abort the whole session parse. Validate the date, fall back to empty.
- models: parseLiteLLMEntry read fields off its argument with no null/type
  guard, so a null value in the remote LiteLLM pricing JSON threw and aborted
  the entire live pricing load. Return null for a null/non-object entry.

Both mutation-checked: the tests raise RangeError / TypeError before the fix.
2026-08-04 06:28:41 +03:00
ozymandiashh
6c4645a8bc fix(kiro): estimate input tokens from the full prompt, not a 500-char slice
parseChatFile estimated input tokens from pendingUserMessage - the last
human turn sliced to 500 chars - while output summed every bot char, so a
multi-turn session or any prompt over 500 chars undercounted input tokens
and therefore costUSD severalfold. Accumulate every human turn's full
length (inputChars), matching the modern-execution path; keep the 500
slice for the display userMessage only. Mutation-checked: a 2400-char
prompt reports 125 tokens before, 600 after.
2026-08-04 05:58:17 +03:00
ozymandiashh
718a2b3a08 feat(openclaude): OpenClaude CLI provider (#213)
OpenClaude is a Claude Code fork routing to any LLM; transcripts are
Claude-Code-schema JSONL under ~/.openclaude/projects/<slug>/<uuid>.jsonl
with replay.json siblings skipped. Only usage-bearing assistant lines
become calls; sidechain lines are counted as real spend; costs are always
computed (the transcript reports none) through the shared tables.

Real local testing: sessions generated with the actual CLI against
DeepSeek (deepseek-chat), parsed end to end.
2026-08-04 04:05:25 +03:00
AgentSeal
c642787113 fix(cline-cli): decline the rollup when per-message calls were all deduped
The rollup fallback was gated on the post-dedup emitted counter, so a session
whose per-message calls were all suppressed by the shared dedup (a duplicated
session directory reusing a session_id) fell through to the metadata.usage
rollup and double-counted its cost. Gate on a hadMetrics flag set before the
dedup check instead.
2026-08-04 01:57:27 +02:00
Rick Culpepper (claude)
448d470049 feat(providers): add cline-cli provider for Cline CLI sessions
The Cline CLI (npm `cline`, 3.x) stores sessions as
<sessions>/<id>/<id>.json + <id>.messages.json. The existing `cline`
provider only discovers tasks/<id>/ui_messages.json, so every CLI session
was silently reported as $0.00 — no warning, not even under --verbose.

Adds `cline-cli` as its own provider rather than a third root on `cline`,
leaving the shared Cline-family parser (Roo Code, KiloCode, IBM Bob)
untouched. It mirrors the CLI's own root resolution
(CLINE_SESSION_DATA_DIR -> CLINE_DATA_DIR -> CLINE_DIR -> ~/.cline),
implements probeRoots() so `doctor` can tell "not installed" from "wrong
override", emits one call per assistant message's `metrics` block, and
falls back to the session rollup when a session carries none. The
fallback reads `usage`, not `aggregateUsage`, which folds in spawned
subagents that are themselves separate session directories.

Two supporting changes, both required for CLI costs to report correctly:

- parser.ts re-priced cline-cli calls from tokens because the provider
  was not on the reported-cost allowlist, inflating a real 12-session
  local sample from $1.11 to $3.92.
- session-cache.ts gains the matching PROVIDER_ENV_VARS entry (so a
  changed override invalidates) and a `reported-cost-v1` parse version
  (so sessions cached before the allowlist fix re-parse once instead of
  being re-priced forever).

Cost is treated as metered only when actually present and non-negative,
so a metered $0 stays reported while a missing or negative cost falls
back to token pricing — applied identically on the per-message and
rollup paths. Timestamps promote a seconds-resolution value rather than
silently landing in 1970, matching the guard kiro.ts uses.

CLINE_DIR / CLINE_DATA_DIR / CLINE_SESSION_DATA_DIR are added to the test
env-isolation list so a developer's real sessions cannot bleed into
fixtures.

The VS Code variant discovery bug reported alongside this in #874 is
deliberately NOT fixed here — it shipped in #882.

Verified against 18 real local sessions: 142 calls, 4,934,762 input /
224,561 output tokens, and a cost matching the CLI's own metered total to
the cent. `codeburn doctor` reports "Cline CLI  OK".

Refs: #874
2026-08-04 02:45:16 +03:00
Resham Joshi
2c69516b02
Merge pull request #882 from ozymandiashh/fix/874-cline-vscode-variants
fix(cline): scan all VS Code variants for task storage
2026-08-03 15:33:23 -07:00
AgentSeal
4ff3497eb8 fix(codex): guard non-string timestamp and model on the parse path
Follow-up to #881. Structural discovery admits third-party rollouts whose
schema is unverified. Two unchecked JSON.parse fields still reached string ops
on the parse path: an unparseable timestamp threw RangeError out of the
fork-cutoff Date math, and a non-string model threw TypeError from calculateCost
(.replace). Either sank that session's usage to zero. Skip the fork cutoff for
an unparseable timestamp, and only adopt a string model (falling back to a real
model otherwise) so the session is counted instead of silently reading zero.
2026-08-04 00:14:28 +02:00
Resham Joshi
733003df35
Merge pull request #881 from ozymandiashh/fix/873-codex-originator-structural
fix(codex): validate rollouts structurally instead of by originator
2026-08-03 15:08:00 -07:00
ozymandiashh
eece4cf005 fix(codex): validate rollouts structurally instead of by originator
Codex session discovery required `payload.originator` to start with
"codex" (case-insensitive). `originator` is a free-form client identity
string, not a format marker: any tool driving `codex app-server` writes
structurally identical rollouts under ~/.codex/sessions with its own
value ("t3code_desktop", "JetBrains.IntelliJ IDEA", ...). Those sessions
were silently dropped from every report, and each past fix only admitted
one more spelling.

Gate on structure instead: a first line that parses as JSON, has
type === "session_meta", and carries a plain-object payload. Foreign and
malformed files are still rejected. Directory ownership decides the
provider — codex.ts is the only provider that reads ~/.codex, and the
walk only visits rollout-*.jsonl under the strict YYYY/MM/DD path or
archived_sessions/ — so no double counting is possible. `originator` is
still parsed onto the meta entry; nothing downstream reads it.

Bump the daily cache to v16. Historical days are served from that cache
(usage-aggregator only recomputes today) and retention is ten years, so
without a bump an upgrading user with a warm cache keeps the pre-fix
rollups forever: discovery reruns, so the session COUNT moves, while
cost and calls stay frozen — a self-contradicting report that reads as
"fixed". Measured on a fixture with two same-day rollouts, one
codex-cli and one t3code_desktop:

  pristine main, fresh cache      cost 4.55  calls 1  sessions 1
  this branch, main's warm cache  cost 4.55  calls 1  sessions 2  (was)
  this branch, main's warm cache  cost 18.2  calls 2  sessions 2  (now)
  this branch, fresh cache        cost 18.2  calls 2  sessions 2  (truth)

CODEX_CACHE_VERSION and PROVIDER_PARSE_VERSIONS.codex deliberately stay
put: both caches are keyed per file path and are written only after a
successful parse, so a file rejected at discovery has no entry to
invalidate. Verified on the fixture above — main's codex-results.json
and session-cache.v7.json hold only the first-party rollout, and reusing
them unchanged still yields the correct total.

Harden `payload.cwd` while admitting unverified clients. It is declared
`string` but comes straight off JSON.parse, and a number/object/array
threw "cwd.replace is not a function" out of sanitizeProject; the throw
escaped discoverSessions into safeDiscoverSessions, which returns [] for
the WHOLE provider, so one malformed file made every Codex report read
zero. Guarded in discovery (falls back to the `unknown` project) and on
the parse side, where a non-string cwd would otherwise ride into
projectPath/workingDirectory and reach the parser's path helpers.

Closes #873, closes #626.
2026-08-04 00:15:24 +03:00
ozymandiashh
43410e88a7 fix(cline): scan all VS Code variants for task storage
Cline discovery only looked at the stable VS Code globalStorage root, so
tasks created in VS Code Insiders or VSCodium were never found. The
singular getVSCodeGlobalStoragePath helper returns paths[0], and because
the provider always passed a concrete overrideDir, the 3-variant fallback
inside discoverClineTasks was never reached - unlike the Roo Code and
KiloCode siblings, which pass overrideDir straight through.

Build the default roots from getVSCodeGlobalStoragePaths (stable,
Insiders, VSCodium) plus the ~/.cline/data root and hand them to
discoverClineTasks in one call. The existing dedupe by task id still
collapses a task id seen in more than one root, so totals cannot inflate.
The configuredDirs override used by tests and createClineProvider(dirs)
is unchanged.
2026-08-04 00:01:57 +03:00
AgentSeal
80f5ed6cf7 Merge branch 'main' into fix/opencode-session-model 2026-08-03 22:56:49 +02:00
AgentSeal
62f6eb27c7 Merge branch 'main' into fix/omp-title-slot-discovery
# Conflicts:
#	src/providers/pi.ts
2026-08-03 21:59:19 +02:00
AgentSeal
2c65764c0b Merge branch 'main' into fix/omp-session-discovery 2026-08-03 21:44:19 +02:00
Aditya Vikram Singh
a4627a1a5a fix(providers): scan bounded leading lines for Pi/OMP session discovery
The shared Pi/OMP discovery gate only checked the first physical line of a
transcript for a `type: "session"` record. Oh My Pi writes a fixed-width
`type: "title"` metadata line before that header (upstream
can1357/oh-my-pi@0ce330a, 2026-06-27), so valid OMP transcripts were rejected
and omitted from `codeburn sessions --provider omp`.

readFirstEntry now scans up to MAX_HEADER_LINES_SCANNED (20) leading lines via
the existing streaming readSessionLines helper, skipping blank lines and
malformed JSON, until it finds a session record. This keeps discovery bounded
for message-only files (and pathological blank/junk-line runs) instead of
reading the whole file, and Pi and OMP continue to share the exact same
discovery path.

Fixes #845
2026-07-29 22:43:01 +05:30
ihearttokyo
a056d22e78
Merge branch 'main' into agent/fix-daily-history-scan 2026-07-27 19:59:08 -04:00
iamtoruk
7fe432094d refactor(codex): buffer a task's calls until its timing is known
Active/tool-wait timing used to be back-patched onto calls that had
already been appended to the result list. Buffer the calls decoded since
the last task_started instead, stamp them in place on task_complete, and
append them at the next task_started or at end of stream, so a task is
only emitted once its timing is final. Single-pass and split decodes then
agree instead of depending on where a decode boundary falls.

Output is unchanged: parsing 827 real rollouts (4.2 GB, 51224 calls) with
and without this change produces byte-identical results. The buffer holds
one task's calls; the deepest observed over that corpus was 924 against a
result list of 8196.

Attribution still spans everything since the last task_started, which
matters when a mid-file session_meta re-arms the fork-replay cutoff and
swallows a task_started while its task_complete lands past the cutoff.
The added test pins that case.
2026-07-27 11:36:21 -07:00
iamtoruk
fad846622f fix(codex): restore discovery fast path, duration precedence, and dashboard width
Review fixes on top of #805.

Discovery: getCachedCodexProject short-circuits again without opening the
file. The PR read the first line of every rollout to collect session_id,
which cost +129ms on an 827-file session directory with a warm cache.
Archived duplicates are now filtered by basename, which needs no file I/O.

Timing: on oversized mcp_tool_call_end lines a `duration_ms` key inside
invocation.arguments outranked the payload-level duration, inflating tool
wait. The depth-aware payload value wins; the naive scan stays as the
fallback for task_complete.

Layout: MIN_WIDE goes back to 90 so 90-129 column terminals keep the
two-column dashboard. The By Model panel drops the Tok/s column (and its
footnote) when the panel has fewer than 61 inner columns or when no model
recorded active timing, so narrow terminals do not truncate and non-Codex
users get no dead column.
2026-07-27 11:36:07 -07:00
Jan Brennenstuhl
36e5ef0a46
fix(omp): discover title-first session transcripts
Co-authored-by: openai/gpt-5.6-terra <noreply@openai.com>
2026-07-27 19:58:50 +02:00
Resham Joshi
264e8e1b50
Merge pull request #800 from getagentseal/fix/611-desktop-msix-sessions
fix(claude): discover Claude Desktop/Cowork sessions in Windows MSIX installs
2026-07-26 06:47:18 -07:00
ihearttokyo
a6bf81f756 feat(codex): add tool-excluded active throughput metrics 2026-07-24 22:53:43 -04:00
EuanTop
dd6147e529 fix(opencode): read session fallback model from real schema 2026-07-24 13:03:22 +08:00
ozymandiashh
d92b9fea43 fix(claude): discover Claude Desktop/Cowork sessions in Windows MSIX installs
The desktop sessions resolver returned a single per-platform path, so
Microsoft Store (MSIX) installs of Claude Desktop were invisible: their
data lives under %LOCALAPPDATA%\Packages\<Claude package>\LocalCache\Roaming\Claude\local-agent-mode-sessions
and a filesystem junction workaround breaks Cowork's own file access
(reported and verified in #611).

getDesktopSessionsDir() becomes getDesktopSessionsDirs(): an ordered,
deduped candidate list (override, then classic APPDATA, then MSIX packages
matching Claude_* or *.Claude_*, existence-checked, lexicographically
sorted; .config on Linux). Results are memoized per env-input tuple so the
parser's per-file classification never rescans Packages. All call sites
scan every candidate; macOS, Linux and classic Windows behavior unchanged.

Fixes #611
2026-07-24 00:30:30 +03:00